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:
Iterating through all files in a root folder to search for specific files using os.walk()
I've tried to search previous questions but I couldn't figure out a solution to my problem.
I have a root folder that has many different subfolders and files. Each subfolder also has files within them and possibly even another subfolder within that subfolder.
I want to iterate through all files in this root folder to find all files that are excel files. I was using the os.path.splitext(filename)[1] == ".xlsx" to confirm that the file is an excel file. Then I will perform data analysis on these files using pandas.
Here is the full code that I am using to do this:
import os
import pandas as pd
rootFolderPath = r'.'
for root, dirs, files in os.walk(rootFolderPath):
for filename in files:
if os.path.isfile(os.path.splitext(filename)[1]) == ".xlsx":
xlsx = pd.ExcelFile(filename)
I took my code and added a counter to make sure that is finding all excel files, which should be 85, but I am getting a total of 0.
Here is my code with the counter added:
import os
import pandas as pd
rootFolderPath = r'.'
counter = 0
for root, dirs, files in os.walk(rootFolderPath):
for filename in files:
if os.path.isfile(os.path.splitext(filename)[1]) == ".xlsx":
xlsx = pd.ExcelFile(filename)
counter += 1
print(counter)
UPDATE
I found a way to solve this if anyone is curious:
import os
import pandas as pd
rootFolderPath = r'.'
for root, dirs, files in os.walk(rootFolderPath):
for filename in files:
if (filename[-5:-1] == ".xls") and (filename[0] != "~"):
xlsx = pd.ExcelFile(root + "\\" + filename)
So, there were three things that I needed to do:
Some of the excel files had extensions of either 'xlsx' or 'xlsm' so I needed a way to account for this.
The program was duplicating some of the excel files but adding a '~' at the start of the name, so I had to filter these out as well.
The program was not creating a pandas dataframe for the excel files in the root folder itself, so I needed to account for this as well.
A:
Instead of os.walk(), use glob.glob(). It has an option to search recursively through subdirectories.
from glob import glob
import os
for filename in glob.glob(os.path.join(rootFolderPath, "**", "*.xlsx"), recursive=True):
xlsx = pd.excelFile(filename)
counter += 1
|
Iterating through all files in a root folder to search for specific files using os.walk()
|
I've tried to search previous questions but I couldn't figure out a solution to my problem.
I have a root folder that has many different subfolders and files. Each subfolder also has files within them and possibly even another subfolder within that subfolder.
I want to iterate through all files in this root folder to find all files that are excel files. I was using the os.path.splitext(filename)[1] == ".xlsx" to confirm that the file is an excel file. Then I will perform data analysis on these files using pandas.
Here is the full code that I am using to do this:
import os
import pandas as pd
rootFolderPath = r'.'
for root, dirs, files in os.walk(rootFolderPath):
for filename in files:
if os.path.isfile(os.path.splitext(filename)[1]) == ".xlsx":
xlsx = pd.ExcelFile(filename)
I took my code and added a counter to make sure that is finding all excel files, which should be 85, but I am getting a total of 0.
Here is my code with the counter added:
import os
import pandas as pd
rootFolderPath = r'.'
counter = 0
for root, dirs, files in os.walk(rootFolderPath):
for filename in files:
if os.path.isfile(os.path.splitext(filename)[1]) == ".xlsx":
xlsx = pd.ExcelFile(filename)
counter += 1
print(counter)
UPDATE
I found a way to solve this if anyone is curious:
import os
import pandas as pd
rootFolderPath = r'.'
for root, dirs, files in os.walk(rootFolderPath):
for filename in files:
if (filename[-5:-1] == ".xls") and (filename[0] != "~"):
xlsx = pd.ExcelFile(root + "\\" + filename)
So, there were three things that I needed to do:
Some of the excel files had extensions of either 'xlsx' or 'xlsm' so I needed a way to account for this.
The program was duplicating some of the excel files but adding a '~' at the start of the name, so I had to filter these out as well.
The program was not creating a pandas dataframe for the excel files in the root folder itself, so I needed to account for this as well.
|
[
"Instead of os.walk(), use glob.glob(). It has an option to search recursively through subdirectories.\nfrom glob import glob\nimport os\n\nfor filename in glob.glob(os.path.join(rootFolderPath, \"**\", \"*.xlsx\"), recursive=True):\n xlsx = pd.excelFile(filename)\n counter += 1\n\n"
] |
[
1
] |
[] |
[] |
[
"os.path",
"os.walk",
"python"
] |
stackoverflow_0074553881_os.path_os.walk_python.txt
|
Q:
Button to next display in matplotlib
I have a class object with an attribute display(self):
import matplotlib.pyplot as plt
class Obj:
def display(self) -> None:
fig = plt.figure()
sub = fig.add_subplot()
sub.plot(...)
plt.show()
def dostuff(self) -> 'stuff':
...
self.display()
...
self.display()
...
self.display()
return
I use this function to have a better visual reference of how my dostuff(self) attribute is handling its task. It all works as intended, when the self.display() command is registered the scrypt pauses execution and plots stuff. However, to resume the only way is closing the matplotlib window manually and then the program reopens another one with the next changes.
Is there a way to implement a button or a better way to view the next changes without having to close and reopen a new window every single time?
A:
plt.show has parameter block. If you set it to False, then the execution is not blocked. Hope this helps.
|
Button to next display in matplotlib
|
I have a class object with an attribute display(self):
import matplotlib.pyplot as plt
class Obj:
def display(self) -> None:
fig = plt.figure()
sub = fig.add_subplot()
sub.plot(...)
plt.show()
def dostuff(self) -> 'stuff':
...
self.display()
...
self.display()
...
self.display()
return
I use this function to have a better visual reference of how my dostuff(self) attribute is handling its task. It all works as intended, when the self.display() command is registered the scrypt pauses execution and plots stuff. However, to resume the only way is closing the matplotlib window manually and then the program reopens another one with the next changes.
Is there a way to implement a button or a better way to view the next changes without having to close and reopen a new window every single time?
|
[
"plt.show has parameter block. If you set it to False, then the execution is not blocked. Hope this helps.\n"
] |
[
0
] |
[] |
[] |
[
"class",
"debugging",
"interface",
"matplotlib",
"python"
] |
stackoverflow_0074553555_class_debugging_interface_matplotlib_python.txt
|
Q:
Gtk has no attribute 'DIALOG_DESTROY_WITH_PARENT'
I am trying to create a working dialog box in Python 2.7/GTK+ 3 (PyGObject). I found an online tutorial which offered the following code...
md = Gtk.MessageDialog(window,
Gtk.DIALOG_DESTROY_WITH_PARENT,
Gtk.MESSAGE_INFO,
Gtk.BUTTONS_CLOSE,
msg)
response = md.run()
However, running this results in the error...
AttributeError: 'gi.repository.Gtk' object has no attribute
'DIALOG_DESTROY_WITH_PARENT'
I'm fairly sure this has to do with the fact that the above code worked on PyGtk (GTK 2). How do I get this working?
A:
After a little bit of research, I found that, yes, this is due to a change in library structure from PyGTK to PyGObject. (Read the documentation for how to work with dialogs, and see line 27 of the example at that link's bookmark.)
The enumeration Gtk.DIALOG_DESTROY_WITH_PARENT does not appear to exist in PyGObject, as the documentation suggests passing a 0 directly.
Beyond that, Gtk.MESSAGE_INFO has been moved to Gtk.MessageType.INFO, and GTK.BUTTONS_CLOSE has been moved to Gtk.ButtonsType.CLOSE.
This may be bright-blazingly obvious to some, but Gtk isn't exactly famous for their documentation, so this is for anyone who might have been fighting with this for a while as I did.
A:
As shown in this Flags documentation, there is a Gtk.DialogFlags.DESTROY_WITH_PARENT flag available.
|
Gtk has no attribute 'DIALOG_DESTROY_WITH_PARENT'
|
I am trying to create a working dialog box in Python 2.7/GTK+ 3 (PyGObject). I found an online tutorial which offered the following code...
md = Gtk.MessageDialog(window,
Gtk.DIALOG_DESTROY_WITH_PARENT,
Gtk.MESSAGE_INFO,
Gtk.BUTTONS_CLOSE,
msg)
response = md.run()
However, running this results in the error...
AttributeError: 'gi.repository.Gtk' object has no attribute
'DIALOG_DESTROY_WITH_PARENT'
I'm fairly sure this has to do with the fact that the above code worked on PyGtk (GTK 2). How do I get this working?
|
[
"After a little bit of research, I found that, yes, this is due to a change in library structure from PyGTK to PyGObject. (Read the documentation for how to work with dialogs, and see line 27 of the example at that link's bookmark.)\nThe enumeration Gtk.DIALOG_DESTROY_WITH_PARENT does not appear to exist in PyGObject, as the documentation suggests passing a 0 directly.\nBeyond that, Gtk.MESSAGE_INFO has been moved to Gtk.MessageType.INFO, and GTK.BUTTONS_CLOSE has been moved to Gtk.ButtonsType.CLOSE.\nThis may be bright-blazingly obvious to some, but Gtk isn't exactly famous for their documentation, so this is for anyone who might have been fighting with this for a while as I did.\n",
"As shown in this Flags documentation, there is a Gtk.DialogFlags.DESTROY_WITH_PARENT flag available.\n"
] |
[
10,
0
] |
[] |
[] |
[
"pygobject",
"python"
] |
stackoverflow_0027008201_pygobject_python.txt
|
Q:
headless_ie_selenium not working with python
I'm trying to change my code to use an IE headless browser. The automation I'm doing is in a website that only works in internet explorer
My code was working great until I tried to use a headless browser
When I run this code, absolutely nothing happens, no error is thrown
# selenium 4
from selenium import webdriver
from selenium.webdriver.ie.service import Service
from webdriver_manager.microsoft import IEDriverManager
from selenium.webdriver.ie.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import StaleElementReferenceException
from dotenv import load_dotenv
# Inicialização do Selenium
ie_options = Options()
ie_options.ignore_zoom_level = True
## WORKS!
# driver = webdriver.Ie(service=Service(IEDriverManager().install()), options=ie_options)
## NOT WORKING
service = Service(executable_path=constantes.PATH_HEADLESS)
driver = webdriver.Ie(service=service, options=ie_options)
# Acessa a página
driver.get(constantes.URL)
A:
I believe the reason why it seems nothing is happening is because you have no output (not printing anything). I'm not familiar with your process, but I tried it out with mine also using chrome and it worked fine. Context:
chrome_options = Options()
chrome_options.add_argument("--headless")
driver=webdriver.Chrome(service=Service('*executable
path'),options=chrome_options)
driver.get('https://stackoverflow.com/')
print(driver.title)
|
headless_ie_selenium not working with python
|
I'm trying to change my code to use an IE headless browser. The automation I'm doing is in a website that only works in internet explorer
My code was working great until I tried to use a headless browser
When I run this code, absolutely nothing happens, no error is thrown
# selenium 4
from selenium import webdriver
from selenium.webdriver.ie.service import Service
from webdriver_manager.microsoft import IEDriverManager
from selenium.webdriver.ie.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import StaleElementReferenceException
from dotenv import load_dotenv
# Inicialização do Selenium
ie_options = Options()
ie_options.ignore_zoom_level = True
## WORKS!
# driver = webdriver.Ie(service=Service(IEDriverManager().install()), options=ie_options)
## NOT WORKING
service = Service(executable_path=constantes.PATH_HEADLESS)
driver = webdriver.Ie(service=service, options=ie_options)
# Acessa a página
driver.get(constantes.URL)
|
[
"I believe the reason why it seems nothing is happening is because you have no output (not printing anything). I'm not familiar with your process, but I tried it out with mine also using chrome and it worked fine. Context:\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n driver=webdriver.Chrome(service=Service('*executable \n path'),options=chrome_options)\n \n driver.get('https://stackoverflow.com/')\n print(driver.title)\n\n"
] |
[
0
] |
[] |
[] |
[
"headless_ie_selenium",
"headless_selenium_for_win",
"python"
] |
stackoverflow_0074553201_headless_ie_selenium_headless_selenium_for_win_python.txt
|
Q:
Returning value after recursively iterating through XML
I'm working with a very nested XML file and the path is critical for understanding. This answer enables me to print both the path and value: Python xml absolute path
What I can't figure out is how to output the result in a more usable way (trying to construct a dataframe listing Path and Value).
For example, from the linked example:
<A>
<B>foo</B>
<C>
<D>On</D>
</C>
<E>Auto</E>
<F>
<G>
<H>shoo</H>
<I>Off</I>
</G>
</F>
</A>
from lxml import etree
root = etree.XML(your_xml_string)
def print_path_of_elems(elem, elem_path=""):
for child in elem:
if not child.getchildren() and child.text:
# leaf node with text => print
print "%s/%s, %s" % (elem_path, child.tag, child.text)
else:
# node with child elements => recurse
print_path_of_elems(child, "%s/%s" % (elem_path, child.tag))
print_path_of_elems(root, root.tag)
Results in the following printout:
/A/B, foo
/A/C/D, On
/A/E, Auto
/A/F/G/H, shoo
/A/F/G/I, Off
I believe yield is the correct technique but I'm getting no where, current attempt returns nothing:
from lxml import etree
root = etree.XML(your_xml_string)
def yield_path_of_elems(elem, elem_path=""):
for child in elem:
if not child.getchildren() and child.text:
ylddict = {'Path':elem_path, 'Value':child.text}
yield(ylddict)
else:
# node with child elements => recurse
yield_path_of_elems(child, "%s/%s" % (elem_path, child.tag))
for i in yield_path_of_elems(root):
#print for simplicity in example, otherwise turn into DF and concat
print(i)
From experimenting I believe when I use yield or return the recursion doesn't function correctly.
A:
You need to pass the values yielded by the recursive call back to the original caller. So change:
yield_path_of_elems(child, "%s/%s" % (elem_path, child.tag))
to
yield from yield_path_of_elems(child, "%s/%s" % (elem_path, child.tag))
This is analogous to the way you have to use return recursive_call(...) in a normal recursive function.
|
Returning value after recursively iterating through XML
|
I'm working with a very nested XML file and the path is critical for understanding. This answer enables me to print both the path and value: Python xml absolute path
What I can't figure out is how to output the result in a more usable way (trying to construct a dataframe listing Path and Value).
For example, from the linked example:
<A>
<B>foo</B>
<C>
<D>On</D>
</C>
<E>Auto</E>
<F>
<G>
<H>shoo</H>
<I>Off</I>
</G>
</F>
</A>
from lxml import etree
root = etree.XML(your_xml_string)
def print_path_of_elems(elem, elem_path=""):
for child in elem:
if not child.getchildren() and child.text:
# leaf node with text => print
print "%s/%s, %s" % (elem_path, child.tag, child.text)
else:
# node with child elements => recurse
print_path_of_elems(child, "%s/%s" % (elem_path, child.tag))
print_path_of_elems(root, root.tag)
Results in the following printout:
/A/B, foo
/A/C/D, On
/A/E, Auto
/A/F/G/H, shoo
/A/F/G/I, Off
I believe yield is the correct technique but I'm getting no where, current attempt returns nothing:
from lxml import etree
root = etree.XML(your_xml_string)
def yield_path_of_elems(elem, elem_path=""):
for child in elem:
if not child.getchildren() and child.text:
ylddict = {'Path':elem_path, 'Value':child.text}
yield(ylddict)
else:
# node with child elements => recurse
yield_path_of_elems(child, "%s/%s" % (elem_path, child.tag))
for i in yield_path_of_elems(root):
#print for simplicity in example, otherwise turn into DF and concat
print(i)
From experimenting I believe when I use yield or return the recursion doesn't function correctly.
|
[
"You need to pass the values yielded by the recursive call back to the original caller. So change:\nyield_path_of_elems(child, \"%s/%s\" % (elem_path, child.tag))\n\nto\nyield from yield_path_of_elems(child, \"%s/%s\" % (elem_path, child.tag))\n\nThis is analogous to the way you have to use return recursive_call(...) in a normal recursive function.\n"
] |
[
0
] |
[] |
[] |
[
"elementtree",
"python",
"xml"
] |
stackoverflow_0074553850_elementtree_python_xml.txt
|
Q:
Measure integral between 2 curves (linear func & arbitrary curve)
In the img. below my goal is to locate the integral in area 1 / 2 / 3.
In that way that I know how much area below the linear line (area 1 / 3),
and how much area that are above the linear line (area 2)
Im not looking for the exact integral, just an approximately value to measure on. an approx that would work in the same fashion for other version of the curves I have represented.
y1: The blue line is a linear function y= -0.148x + 1301.35
y2:The yellow line is a arbitrary curve
Both curves share the same x axis.
image of curves linear & arbitrary curve
I have tried several methods, found here on stackoverflow, mainly theese 2 methods cought my attention:
https://stackoverflow.com/a/57827807
&
https://stackoverflow.com/a/25447819
They give me the exact same output for the whole area, my issue is to seperate it above / below.
Example of my best try:
(Modified version of https://stackoverflow.com/a/25447819/20441461)
y1 / y2 / x - is the data used for the curves in the img. above
y1 = [1298.54771845, 1298.40019417, 1298.2526699, 1298.10514563,
1297.95762136,1297.81009709, 1297.66257282, 1297.51504854]
y2 = [1298.59, 1297.31, 1296.04, 1297.31, 1296.95, 1299.18, 1297.05, 1297.45]
x = np.arange(len(y1))
z = y1-y2
dx = x[1:] - x[:-1]
cross_test = np.sign(z[:-1] * z[1:])
x_intersect = x[:-1] - dx / (z[1:] - z[:-1]) * z[:-1]
dx_intersect = - dx / (z[1:] - z[:-1]) * z[:-1]
areas_pos = abs(z[:-1] + z[1:]) * 0.5 * dx # signs of both z are same
areas_neg = 0.5 * dx_intersect * abs(z[:-1]) + 0.5 * (dx - dx_intersect) * abs(z[1:])
negatives = np.where(cross_test < 0)
negative_sum = np.sum(x_intersect[negatives])
positives = np.where(cross_test >= 0)
positive_sum = np.sum(x_intersect[positives])`
is give me this result:
Negative integral = 10.15
Positive integral = 9.97
Just from looking at the picture, I can tell that can not be the correct value. ( there is alot more area below the linear line than above.)
I have spend loads of time now on this, and are quite stuck - any advise or suggestion are welcome.
A:
Perhaps you can integrate the absolute difference of both arrays:
>>> np.trapz(np.abs(y2 - y1))
7.1417718350001
A:
Here is a little bit of code that calculates exactly all the areas, and does so in a vectorized way (fast):
def areas(x, y1, y2, details=None):
dy = y1 - y2
b0 = dy[:-1]
b1 = dy[1:]
b = np.c_[b0, b1]
r = np.abs(b0) / (np.abs(b0) + np.abs(b1))
rr = np.c_[r, 1-r]
dx = np.diff(x)
h = rr * dx[:, None]
br = (b * rr[:, ::-1]).sum(1)
a = (b + br[:, None]) * h / 2
result = np.sum(a[a > 0]), np.sum(a[a < 0])
if details is not None:
details.update(locals()) # for debugging
return result
Example:
x = np.array([0,1,2])
y1 = np.array([1,0,3])
y2 = np.array([0,3,4])
>>> areas(x, y1, y2)
(0.125, -3.125)
Your original example:
y1 = np.array([
1298.54771845, 1298.40019417, 1298.2526699, 1298.10514563,
1297.95762136,1297.81009709, 1297.66257282, 1297.51504854])
y2 = np.array([1298.59, 1297.31, 1296.04, 1297.31, 1296.95, 1299.18, 1297.05, 1297.45])
x = np.arange(len(y1))
>>> areas(x, y1, y2)
(5.228440802728334, -0.8687563377282332)
Explanation
To understand how it works, let us consider the quadrilateral of four points: [a, b, c, d], where a and b are at the same x position, and so are c and d. It can be "straight" if none of the edges intersect, or "twisted" otherwise. In both cases, we consider the x-position of the intersection where the twisted version would intersect, and the actual vertical section of the quadrilateral at that position (0 if twisted, or the weighted average of the vertical sides if straight).
Say we call the vertical distances b0 and b1. They are oriented (positive if y1 > y2). The intersection is at x-coordinate x + r * dx, where r = |b0| / (|b0| + |b1|) and is a factor between 0 and 1.
For a twisted quad, the left (triangular) area is b0*r*dx/2 and the right one is b1*(1-r)*dx/2.
For a straight quad, the left area (trapeze) is (b0 + br)/2 * r * dx and the right is (b1 + br) / 2 * (1 - r) * dx, where br is the height at the r horizontal proportion, and br = b0 * (1 - r) + b1 * r.
To generalize, we always use br in the calculation. For twisted quads, it is 0 and we can use the same expression as for straight quads. This is the key to eliminate any tests and produce a pure vectorized function.
The rest is a bit of numpy expressions to calculate all these values efficiently.
Example detail
def plot_details(details, ax=None):
x, y1, y2, dx, r, a = [details[k] for k in 'x y1 y2 dx r a'.split()]
ax = ax if ax else plt.gca()
ax.plot(x, y1, 'b.-')
ax.plot(x, y2, 'r.-')
xmid = x[:-1] + dx * r
[ax.axvline(xi) for xi in xmid]
xy1 = np.c_[x, y1]
xy2 = np.c_[x, y2]
for A,B,C,D,r,(a0,a1) in zip(xy1, xy2, xy1[1:], xy2[1:], r, a):
ACmid = A*(1-r) + C*r
BDmid = B*(1-r) + D*r
q0 = np.c_[A,ACmid,BDmid,B]
q1 = np.c_[ACmid,C,D,BDmid]
ax.fill(*q0, alpha=.2)
ax.fill(*q1, alpha=.2)
ax.text(*q0.mean(1), f'{a0:.3f}', ha='center')
ax.text(*q1.mean(1), f'{a1:.3f}', ha='center')
Taking the earlier example:
x = np.array([0,1,2])
y1 = np.array([1,0,3])
y2 = np.array([0,3,4])
details = {}
>>> areas(x, y1, y2, details)
(0.125, -3.125)
>>> details
{'x': array([0, 1, 2]),
'y1': array([1, 0, 3]),
'y2': array([0, 3, 4]),
'details': {...},
'dy': array([ 1, -3, -1]),
'b0': array([ 1, -3]),
'b1': array([-3, -1]),
'b': array([[ 1, -3],
[-3, -1]]),
'r': array([0.25, 0.75]),
'rr': array([[0.25, 0.75],
[0.75, 0.25]]),
'dx': array([1, 1]),
'h': array([[0.25, 0.75],
[0.75, 0.25]]),
'br': array([ 0. , -1.5]),
'a': array([[ 0.125 , -1.125 ],
[-1.6875, -0.3125]]),
'result': (0.125, -3.125)}
And:
plot_details(details)
|
Measure integral between 2 curves (linear func & arbitrary curve)
|
In the img. below my goal is to locate the integral in area 1 / 2 / 3.
In that way that I know how much area below the linear line (area 1 / 3),
and how much area that are above the linear line (area 2)
Im not looking for the exact integral, just an approximately value to measure on. an approx that would work in the same fashion for other version of the curves I have represented.
y1: The blue line is a linear function y= -0.148x + 1301.35
y2:The yellow line is a arbitrary curve
Both curves share the same x axis.
image of curves linear & arbitrary curve
I have tried several methods, found here on stackoverflow, mainly theese 2 methods cought my attention:
https://stackoverflow.com/a/57827807
&
https://stackoverflow.com/a/25447819
They give me the exact same output for the whole area, my issue is to seperate it above / below.
Example of my best try:
(Modified version of https://stackoverflow.com/a/25447819/20441461)
y1 / y2 / x - is the data used for the curves in the img. above
y1 = [1298.54771845, 1298.40019417, 1298.2526699, 1298.10514563,
1297.95762136,1297.81009709, 1297.66257282, 1297.51504854]
y2 = [1298.59, 1297.31, 1296.04, 1297.31, 1296.95, 1299.18, 1297.05, 1297.45]
x = np.arange(len(y1))
z = y1-y2
dx = x[1:] - x[:-1]
cross_test = np.sign(z[:-1] * z[1:])
x_intersect = x[:-1] - dx / (z[1:] - z[:-1]) * z[:-1]
dx_intersect = - dx / (z[1:] - z[:-1]) * z[:-1]
areas_pos = abs(z[:-1] + z[1:]) * 0.5 * dx # signs of both z are same
areas_neg = 0.5 * dx_intersect * abs(z[:-1]) + 0.5 * (dx - dx_intersect) * abs(z[1:])
negatives = np.where(cross_test < 0)
negative_sum = np.sum(x_intersect[negatives])
positives = np.where(cross_test >= 0)
positive_sum = np.sum(x_intersect[positives])`
is give me this result:
Negative integral = 10.15
Positive integral = 9.97
Just from looking at the picture, I can tell that can not be the correct value. ( there is alot more area below the linear line than above.)
I have spend loads of time now on this, and are quite stuck - any advise or suggestion are welcome.
|
[
"Perhaps you can integrate the absolute difference of both arrays:\n>>> np.trapz(np.abs(y2 - y1))\n7.1417718350001\n\n",
"Here is a little bit of code that calculates exactly all the areas, and does so in a vectorized way (fast):\ndef areas(x, y1, y2, details=None):\n dy = y1 - y2\n b0 = dy[:-1]\n b1 = dy[1:]\n b = np.c_[b0, b1]\n r = np.abs(b0) / (np.abs(b0) + np.abs(b1))\n rr = np.c_[r, 1-r]\n dx = np.diff(x)\n h = rr * dx[:, None]\n br = (b * rr[:, ::-1]).sum(1)\n a = (b + br[:, None]) * h / 2\n result = np.sum(a[a > 0]), np.sum(a[a < 0])\n if details is not None:\n details.update(locals()) # for debugging\n return result\n\nExample:\nx = np.array([0,1,2])\ny1 = np.array([1,0,3])\ny2 = np.array([0,3,4])\n\n>>> areas(x, y1, y2)\n(0.125, -3.125)\n\nYour original example:\ny1 = np.array([\n 1298.54771845, 1298.40019417, 1298.2526699, 1298.10514563, \n 1297.95762136,1297.81009709, 1297.66257282, 1297.51504854])\n\ny2 = np.array([1298.59, 1297.31, 1296.04, 1297.31, 1296.95, 1299.18, 1297.05, 1297.45])\n\nx = np.arange(len(y1))\n\n>>> areas(x, y1, y2)\n(5.228440802728334, -0.8687563377282332)\n\nExplanation\nTo understand how it works, let us consider the quadrilateral of four points: [a, b, c, d], where a and b are at the same x position, and so are c and d. It can be \"straight\" if none of the edges intersect, or \"twisted\" otherwise. In both cases, we consider the x-position of the intersection where the twisted version would intersect, and the actual vertical section of the quadrilateral at that position (0 if twisted, or the weighted average of the vertical sides if straight).\nSay we call the vertical distances b0 and b1. They are oriented (positive if y1 > y2). The intersection is at x-coordinate x + r * dx, where r = |b0| / (|b0| + |b1|) and is a factor between 0 and 1.\nFor a twisted quad, the left (triangular) area is b0*r*dx/2 and the right one is b1*(1-r)*dx/2.\nFor a straight quad, the left area (trapeze) is (b0 + br)/2 * r * dx and the right is (b1 + br) / 2 * (1 - r) * dx, where br is the height at the r horizontal proportion, and br = b0 * (1 - r) + b1 * r.\nTo generalize, we always use br in the calculation. For twisted quads, it is 0 and we can use the same expression as for straight quads. This is the key to eliminate any tests and produce a pure vectorized function.\nThe rest is a bit of numpy expressions to calculate all these values efficiently.\nExample detail\ndef plot_details(details, ax=None):\n x, y1, y2, dx, r, a = [details[k] for k in 'x y1 y2 dx r a'.split()]\n ax = ax if ax else plt.gca()\n ax.plot(x, y1, 'b.-')\n ax.plot(x, y2, 'r.-')\n xmid = x[:-1] + dx * r\n [ax.axvline(xi) for xi in xmid]\n xy1 = np.c_[x, y1]\n xy2 = np.c_[x, y2]\n for A,B,C,D,r,(a0,a1) in zip(xy1, xy2, xy1[1:], xy2[1:], r, a):\n ACmid = A*(1-r) + C*r\n BDmid = B*(1-r) + D*r\n q0 = np.c_[A,ACmid,BDmid,B]\n q1 = np.c_[ACmid,C,D,BDmid]\n ax.fill(*q0, alpha=.2)\n ax.fill(*q1, alpha=.2)\n ax.text(*q0.mean(1), f'{a0:.3f}', ha='center')\n ax.text(*q1.mean(1), f'{a1:.3f}', ha='center')\n\nTaking the earlier example:\nx = np.array([0,1,2])\ny1 = np.array([1,0,3])\ny2 = np.array([0,3,4])\n\ndetails = {}\n>>> areas(x, y1, y2, details)\n(0.125, -3.125)\n\n>>> details\n{'x': array([0, 1, 2]),\n 'y1': array([1, 0, 3]),\n 'y2': array([0, 3, 4]),\n 'details': {...},\n 'dy': array([ 1, -3, -1]),\n 'b0': array([ 1, -3]),\n 'b1': array([-3, -1]),\n 'b': array([[ 1, -3],\n [-3, -1]]),\n 'r': array([0.25, 0.75]),\n 'rr': array([[0.25, 0.75],\n [0.75, 0.25]]),\n 'dx': array([1, 1]),\n 'h': array([[0.25, 0.75],\n [0.75, 0.25]]),\n 'br': array([ 0. , -1.5]),\n 'a': array([[ 0.125 , -1.125 ],\n [-1.6875, -0.3125]]),\n 'result': (0.125, -3.125)}\n\nAnd:\nplot_details(details)\n\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"area",
"curve",
"integral",
"numpy",
"python"
] |
stackoverflow_0074549674_area_curve_integral_numpy_python.txt
|
Q:
I want to create a nested dictionary from a csv file with headers as keys
This is my csv file:
Player Name,2022 Cap Number,Rating,Position
Poona Ford,"10,075,000",74,DT
Tyler Lockett,"10,050,000",90,WR
D.K. Metcalf,"8,838,827",89,WR
Gabe Jackson,"7,237,778",79,G
Uchenna Nwosu,"6,295,000",79,LB
Quandre Diggs,"5,800,000",85,FS
I want my output to be:
{'Poona Ford': {'2022 Cap Number': '"10075000"', 'Rating': '74', 'Position': 'DT'}, 'Tyler Lockett': {'2022 Cap Number': '"10050000"', 'Rating': '90', 'Position': 'WR'}, 'D.K. Metcalf': {'2022 Cap Number': '"8838827"', 'Rating': '89', 'Position': 'WR'}, 'Gabe Jackson': {'2022 Cap Number': '"7237778"', 'Rating': '79', 'Position': 'G'}, 'Uchenna Nwosu': {'2022 Cap Number': '"6295000"', 'Rating': '79', 'Position': 'LB'}, 'Quandre Diggs': {'2022 Cap Number': '"5800000"', 'Rating': '85', 'Position': 'FS'}
I've been able to produce this but the names are the only keys. I need the other header names to be keys within each name. '2002 Cap Number' , 'Rating', and 'Postion' need to be keys within Player Name.
csv_list = [['Player Name', '2022 Cap Number', 'Rating', 'Position'], ['Poona Ford', '"10075000"', '74', 'DT'], ['Tyler Lockett', '"10050000"', '90', 'WR'], ['D.K. Metcalf', '"8838827"', '89', 'WR'], ['Gabe Jackson', '"7237778"', '79', 'G'], ['Uchenna Nwosu', '"6295000"', '79', 'LB'], ['Quandre Diggs', '"5800000"', '85', 'FS']
(_, *header), *data = csv_list
csv_dict = {}
for row in data:
key, *values = row
csv_dict[key] = {key: value for key, value in zip(header, values)}
print(csv_dict)
I tried this but only the names are keys. The rest of the headers and data are all values.
A:
Try this:
csv_list = [['Player Name', '2022 Cap Number', 'Rating', 'Position'], ['Poona Ford', '"10075000"', '74', 'DT'], ['Tyler Lockett', '"10050000"', '90', 'WR'], ['D.K. Metcalf', '"8838827"', '89', 'WR'], ['Gabe Jackson', '"7237778"', '79', 'G'], ['Uchenna Nwosu', '"6295000"', '79', 'LB'], ['Quandre Diggs', '"5800000"', '85', 'FS']]
csv_dict = {}
for i,*j in csv_list[1:]:
csv_dict[i] = dict(zip(csv_list[0][1:], j))
|
I want to create a nested dictionary from a csv file with headers as keys
|
This is my csv file:
Player Name,2022 Cap Number,Rating,Position
Poona Ford,"10,075,000",74,DT
Tyler Lockett,"10,050,000",90,WR
D.K. Metcalf,"8,838,827",89,WR
Gabe Jackson,"7,237,778",79,G
Uchenna Nwosu,"6,295,000",79,LB
Quandre Diggs,"5,800,000",85,FS
I want my output to be:
{'Poona Ford': {'2022 Cap Number': '"10075000"', 'Rating': '74', 'Position': 'DT'}, 'Tyler Lockett': {'2022 Cap Number': '"10050000"', 'Rating': '90', 'Position': 'WR'}, 'D.K. Metcalf': {'2022 Cap Number': '"8838827"', 'Rating': '89', 'Position': 'WR'}, 'Gabe Jackson': {'2022 Cap Number': '"7237778"', 'Rating': '79', 'Position': 'G'}, 'Uchenna Nwosu': {'2022 Cap Number': '"6295000"', 'Rating': '79', 'Position': 'LB'}, 'Quandre Diggs': {'2022 Cap Number': '"5800000"', 'Rating': '85', 'Position': 'FS'}
I've been able to produce this but the names are the only keys. I need the other header names to be keys within each name. '2002 Cap Number' , 'Rating', and 'Postion' need to be keys within Player Name.
csv_list = [['Player Name', '2022 Cap Number', 'Rating', 'Position'], ['Poona Ford', '"10075000"', '74', 'DT'], ['Tyler Lockett', '"10050000"', '90', 'WR'], ['D.K. Metcalf', '"8838827"', '89', 'WR'], ['Gabe Jackson', '"7237778"', '79', 'G'], ['Uchenna Nwosu', '"6295000"', '79', 'LB'], ['Quandre Diggs', '"5800000"', '85', 'FS']
(_, *header), *data = csv_list
csv_dict = {}
for row in data:
key, *values = row
csv_dict[key] = {key: value for key, value in zip(header, values)}
print(csv_dict)
I tried this but only the names are keys. The rest of the headers and data are all values.
|
[
"Try this:\ncsv_list = [['Player Name', '2022 Cap Number', 'Rating', 'Position'], ['Poona Ford', '\"10075000\"', '74', 'DT'], ['Tyler Lockett', '\"10050000\"', '90', 'WR'], ['D.K. Metcalf', '\"8838827\"', '89', 'WR'], ['Gabe Jackson', '\"7237778\"', '79', 'G'], ['Uchenna Nwosu', '\"6295000\"', '79', 'LB'], ['Quandre Diggs', '\"5800000\"', '85', 'FS']]\n\ncsv_dict = {}\nfor i,*j in csv_list[1:]:\n csv_dict[i] = dict(zip(csv_list[0][1:], j))\n\n"
] |
[
1
] |
[] |
[] |
[
"csv",
"dictionary",
"python"
] |
stackoverflow_0074553953_csv_dictionary_python.txt
|
Q:
How do I mock methods of a decorated class in python?
Having trouble with applying mocks to a class with a decorator. If I write the class without a decorator, patches are applied as expected. However, once the class is decorated, the same patch fails to apply.
What's going on here, and what's the best way to approach testing classes that may be decorated?
Here's a minimal reproduction.
# module.py
import functools
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@decorator # comment this out and the test passes
class Something:
def do_external(self):
raise Exception("should be mocked")
def run(self):
self.do_external()
# test_module.py
from unittest import TestCase
from unittest.mock import Mock, patch
from module import Something
class TestModule(TestCase):
@patch('module.Something.do_external', Mock())
def test_module(self):
s = Something()
s.run()
If you prefer, here's an online reproducible example of the issue.
A:
So, as I stated in the comment, your wrapper function replaces Something in the module module namespace. So, putting your code in module.py on my computer, observe:
>>> import module
>>> type(module.Something)
<class 'function'>
Since you used the functools.wraps decorator, the object being wrapped is added to the wrapper function at .__wrapped__:
>>> module.Something.__wrapped__
<class 'module.Something'>
>>> type(module.Something.__wrapped__)
<class 'type'>
So when you patch module.Something, you are patching the function object, not the class object. But instances of your class directly reference the class internally, it doesn't matter what global name refers to it. So, observe some more:
>>> import unittest.mock as mock
>>> with mock.patch('module.Something.do_external', mock.Mock()):
... print(module.Something.do_external)
... print(module.Something.__wrapped__.do_external)
...
<Mock id='140609580169920'>
<function Something.do_external at 0x7fe23822cc10>
This is why we see this particular behavior:
>>> with mock.patch('module.Something.do_external', mock.Mock()):
... module.Something().do_external()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/jarrivillaga/module.py", line 18, in do_external
raise Exception("should be mocked")
Exception: should be mocked
In this particular case, because the __wrapped__ attribute references the original class, we can patch that:
>>> with mock.patch('module.Something.__wrapped__.do_external', mock.Mock()):
... module.Something().do_external()
...
<Mock name='mock()' id='140608505553680'>
But I highly suggest rethinking your decorator design, if this is meant for external/public use. But just fundamentally, module.Something is not a class, it is a function, so you cannot treat it like a class and expect it to work like a class.
Note, the fact that you used wraps makes it possible for the patch to work at all, although, it just hides the problem because putting those other functions as attributes of the wrapper function don't really provide anything useful. wraps is mostly meant to be used when wrapping other functions, where creating a new function that looks like the old function makes sense, in the case of a class, though, you are making a function look like a class, but only superficially. Just removing the @wraps line, observe:
>>> import module
>>> import unittest.mock as mock
>>> with mock.patch('module.Something.do_external', mock.Mock()):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jarrivillaga/miniconda3/lib/python3.9/unittest/mock.py", line 1404, in __enter__
original, local = self.get_original()
File "/Users/jarrivillaga/miniconda3/lib/python3.9/unittest/mock.py", line 1377, in get_original
raise AttributeError(
AttributeError: <function decorator.<locals>.wrapper at 0x7ff820081160> does not have the attribute 'do_external'
So functools.wraps here was just hiding a fundamental error.
|
How do I mock methods of a decorated class in python?
|
Having trouble with applying mocks to a class with a decorator. If I write the class without a decorator, patches are applied as expected. However, once the class is decorated, the same patch fails to apply.
What's going on here, and what's the best way to approach testing classes that may be decorated?
Here's a minimal reproduction.
# module.py
import functools
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@decorator # comment this out and the test passes
class Something:
def do_external(self):
raise Exception("should be mocked")
def run(self):
self.do_external()
# test_module.py
from unittest import TestCase
from unittest.mock import Mock, patch
from module import Something
class TestModule(TestCase):
@patch('module.Something.do_external', Mock())
def test_module(self):
s = Something()
s.run()
If you prefer, here's an online reproducible example of the issue.
|
[
"So, as I stated in the comment, your wrapper function replaces Something in the module module namespace. So, putting your code in module.py on my computer, observe:\n>>> import module\n>>> type(module.Something)\n<class 'function'>\n\nSince you used the functools.wraps decorator, the object being wrapped is added to the wrapper function at .__wrapped__:\n>>> module.Something.__wrapped__\n<class 'module.Something'>\n>>> type(module.Something.__wrapped__)\n<class 'type'>\n\nSo when you patch module.Something, you are patching the function object, not the class object. But instances of your class directly reference the class internally, it doesn't matter what global name refers to it. So, observe some more:\n>>> import unittest.mock as mock\n>>> with mock.patch('module.Something.do_external', mock.Mock()):\n... print(module.Something.do_external)\n... print(module.Something.__wrapped__.do_external)\n...\n<Mock id='140609580169920'>\n<function Something.do_external at 0x7fe23822cc10>\n\nThis is why we see this particular behavior:\n>>> with mock.patch('module.Something.do_external', mock.Mock()):\n... module.Something().do_external()\n...\nTraceback (most recent call last):\n File \"<stdin>\", line 2, in <module>\n File \"/Users/jarrivillaga/module.py\", line 18, in do_external\n raise Exception(\"should be mocked\")\nException: should be mocked\n\nIn this particular case, because the __wrapped__ attribute references the original class, we can patch that:\n>>> with mock.patch('module.Something.__wrapped__.do_external', mock.Mock()):\n... module.Something().do_external()\n...\n<Mock name='mock()' id='140608505553680'>\n\nBut I highly suggest rethinking your decorator design, if this is meant for external/public use. But just fundamentally, module.Something is not a class, it is a function, so you cannot treat it like a class and expect it to work like a class.\nNote, the fact that you used wraps makes it possible for the patch to work at all, although, it just hides the problem because putting those other functions as attributes of the wrapper function don't really provide anything useful. wraps is mostly meant to be used when wrapping other functions, where creating a new function that looks like the old function makes sense, in the case of a class, though, you are making a function look like a class, but only superficially. Just removing the @wraps line, observe:\n>>> import module\n>>> import unittest.mock as mock\n>>> with mock.patch('module.Something.do_external', mock.Mock()):\n... pass\n...\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/Users/jarrivillaga/miniconda3/lib/python3.9/unittest/mock.py\", line 1404, in __enter__\n original, local = self.get_original()\n File \"/Users/jarrivillaga/miniconda3/lib/python3.9/unittest/mock.py\", line 1377, in get_original\n raise AttributeError(\nAttributeError: <function decorator.<locals>.wrapper at 0x7ff820081160> does not have the attribute 'do_external'\n\nSo functools.wraps here was just hiding a fundamental error.\n"
] |
[
1
] |
[] |
[] |
[
"patch",
"python",
"python_unittest"
] |
stackoverflow_0074553493_patch_python_python_unittest.txt
|
Q:
Per line index url in requirements.txt
Suppose I have the following PyPIs:
public PyPi (standard packages)
gitlab pypi (because internal team ABC wanted to use this)
artifactory PyPi (because contractor team DEF wanted to use this)
Now suppose package titled "ABC" exists on all of them, but are not the same thing (for instance, "apples," which are 3 entirely different packages on all pypis.). How do I do something in my requirements and setup.py to map the package name to the pypi to use?
Something like:
package_def==1.2.3 --index-url=artifactory
apples==1.08 --index-url=gitlab # NOT FROM PUBLIC OR FROM ARTIFACTORY
package_abc==1.2.3 --index-url=artifactory
package_efg==1.0.0 # public pypi
I don't even know how I'd configure the setup.py in this instance either.
I really don't want multiple requirements.txt with different index urls at the top. I also don't want --extra-index-url due to the vulnerabilities it could introduce when using a private pypi.
I tried googling around, messing around with the order of requirements.txt, breaking it up into different files, etc. No luck. Seems that the last --index-url is always used to install all packages.
Any ideas?
A:
The question gets back to the idea that a package dependency specification usually is a state of need that is independent of how that need should be satisfied.
So the dependency declaration “foo==1.0.0” (the thing declared as part of the package metadata) means “I need the package named foo with version 1.0.0" and that is in principle implementation independent. You can install that package with pip from PyPI, but you could also use a different tool and/or different source to satisfy that requirement (e.g. conda, installation-from-source, etc.).
This distinction is the reason why there's no good way to do this.
There are a few work arounds:
You can specify the full link to a wheel you want to pip install
You can use an alternative tool like Poetry, which does support this a little more cleanly.
For my particular usecase, I just listed the full link to the wheel I wanted to pip install, since upgrading to poetry is out of scope at the moment.
|
Per line index url in requirements.txt
|
Suppose I have the following PyPIs:
public PyPi (standard packages)
gitlab pypi (because internal team ABC wanted to use this)
artifactory PyPi (because contractor team DEF wanted to use this)
Now suppose package titled "ABC" exists on all of them, but are not the same thing (for instance, "apples," which are 3 entirely different packages on all pypis.). How do I do something in my requirements and setup.py to map the package name to the pypi to use?
Something like:
package_def==1.2.3 --index-url=artifactory
apples==1.08 --index-url=gitlab # NOT FROM PUBLIC OR FROM ARTIFACTORY
package_abc==1.2.3 --index-url=artifactory
package_efg==1.0.0 # public pypi
I don't even know how I'd configure the setup.py in this instance either.
I really don't want multiple requirements.txt with different index urls at the top. I also don't want --extra-index-url due to the vulnerabilities it could introduce when using a private pypi.
I tried googling around, messing around with the order of requirements.txt, breaking it up into different files, etc. No luck. Seems that the last --index-url is always used to install all packages.
Any ideas?
|
[
"The question gets back to the idea that a package dependency specification usually is a state of need that is independent of how that need should be satisfied.\nSo the dependency declaration “foo==1.0.0” (the thing declared as part of the package metadata) means “I need the package named foo with version 1.0.0\" and that is in principle implementation independent. You can install that package with pip from PyPI, but you could also use a different tool and/or different source to satisfy that requirement (e.g. conda, installation-from-source, etc.).\nThis distinction is the reason why there's no good way to do this.\nThere are a few work arounds:\n\nYou can specify the full link to a wheel you want to pip install\nYou can use an alternative tool like Poetry, which does support this a little more cleanly.\n\nFor my particular usecase, I just listed the full link to the wheel I wanted to pip install, since upgrading to poetry is out of scope at the moment.\n"
] |
[
0
] |
[] |
[] |
[
"pip",
"python",
"python_3.x"
] |
stackoverflow_0074538877_pip_python_python_3.x.txt
|
Q:
Xpath returns empty array - lxml
I'm trying to write a program that scrapes https://www.tcgplayer.com/ to get a list of Pokemon TCG prices based on a specified list
from lxml import etree, html
import requests
import string
def clean_text(element):
all_text = element.text_content()
cleaned = ' '.join(all_text.split())
return cleaned
page = requests.get("http://www.tcgplayer.com/product/231462/pokemon-first-partner-pack-pikachu?xid=pi731833d1-f2cc-4043-9551-4ca08506b43a&page=1&Language=English")
tree = html.fromstring(page.content)
price = tree.xpath("/html/body/div[2]/div/div/section[2]/section/div/div[2]/section[3]/div/section[1]/ul/li[1]/span[2]")
print(price)
However, when I am running this code the output ends up just being an empty list "[]"
I have tried using selenium and the browser function that it has, however I would like it to not need to open a browser for 100+ cards to get the price data. I have tested this code on another website url and xpath (https://www.pricecharting.com/game/pokemon-promo/jolteon-v-swsh183, /html/body/div[1]/div[2]/div/div/table/tbody[1]/tr[1]/td[4]/span[1]) - so I wonder if it is just how https://www.tcgplayer.com/ is built.
The expected return value is around $5
A:
Question answered above by @Grismar:
When you test the XPath on a site, you probably do this in the Developer Console in the browser, after the page has loaded. At that point in time, any JavaScript will have already executed and completed and the page may have been updated or even been constructed from scratch by it. When using requests, it just loads the basic page and no scripts get executed - you'll need something that can execute JavaScript to get the same result, like selenium
BeautifulSoup scraping returns no data
|
Xpath returns empty array - lxml
|
I'm trying to write a program that scrapes https://www.tcgplayer.com/ to get a list of Pokemon TCG prices based on a specified list
from lxml import etree, html
import requests
import string
def clean_text(element):
all_text = element.text_content()
cleaned = ' '.join(all_text.split())
return cleaned
page = requests.get("http://www.tcgplayer.com/product/231462/pokemon-first-partner-pack-pikachu?xid=pi731833d1-f2cc-4043-9551-4ca08506b43a&page=1&Language=English")
tree = html.fromstring(page.content)
price = tree.xpath("/html/body/div[2]/div/div/section[2]/section/div/div[2]/section[3]/div/section[1]/ul/li[1]/span[2]")
print(price)
However, when I am running this code the output ends up just being an empty list "[]"
I have tried using selenium and the browser function that it has, however I would like it to not need to open a browser for 100+ cards to get the price data. I have tested this code on another website url and xpath (https://www.pricecharting.com/game/pokemon-promo/jolteon-v-swsh183, /html/body/div[1]/div[2]/div/div/table/tbody[1]/tr[1]/td[4]/span[1]) - so I wonder if it is just how https://www.tcgplayer.com/ is built.
The expected return value is around $5
|
[
"Question answered above by @Grismar:\n\nWhen you test the XPath on a site, you probably do this in the Developer Console in the browser, after the page has loaded. At that point in time, any JavaScript will have already executed and completed and the page may have been updated or even been constructed from scratch by it. When using requests, it just loads the basic page and no scripts get executed - you'll need something that can execute JavaScript to get the same result, like selenium\n\nBeautifulSoup scraping returns no data\n"
] |
[
0
] |
[] |
[] |
[
"lxml",
"python",
"web_scraping",
"xpath"
] |
stackoverflow_0074440794_lxml_python_web_scraping_xpath.txt
|
Q:
Pandas - Create multiple new columns if str.contains return multiple value
I have some data like this:
0 Very user friendly interface and has 2FA support
1 The trading page is great though with allot o...
2 Widget support
3 But it’s really only for serious traders with...
4 The KYC and AML process is painful - it took ...
...
937 Legit platform!
938 Horrible customer service won’t get back to m...
939 App is fast and reliable
940 I wish it had a portfolio chart though
941 The app isn’t as user friendly as it need to b...
Name: reviews, Length: 942, dtype: object
and features:
['support',
'time',
'follow',
'submit',
'ticket',
'team',
'swap',
'account',
'experi',
'contact',
'user',
'platform',
'screen',
'servic',
'custom',
'restrict',
'fast',
'portfolio',
'specialist']
I want to check if one or more of features in reviews add that words in new column.
and my code is this:
data["words"] = data[data["reviews"].str.contains('|'.join(features))]
but this code make new column with name "words" however because sometime code return multi value so I get error
ValueError: Columns must be same length as key
how can fix it?
A:
The issue is that you are not actually extracting any of the words. You need to pull the words you want out of the text and then cat them into a new column.
import pandas as pd
from io import StringIO
import re
TESTDATA = StringIO("""Index,reviews,
0, Very user friendly interface and has 2FA support,
1, The trading page is great though with allot o...,
2, Widget support,
3, But it’s really only for serious traders with...,
4, The KYC and AML process is painful - it took ...,
937, Legit platform!,
938, Horrible customer service won’t get back to m...,
939, App is fast and reliable,
940, I wish it had a portfolio chart though,
941, The app isn’t as user friendly as it need to b...
""")
data = pd.read_csv(TESTDATA, sep=",").drop('Unnamed: 2', axis = 1)
data
#> Index reviews
0 0 Very user friendly interface and has 2F...
1 1 The trading page is great though with a...
2 2 Widge...
3 3 But it’s really only for serious trader...
4 4 The KYC and AML process is painful - it...
5 937 Legit pl...
6 938 Horrible customer service won’t get back ...
7 939 App is fast and r...
8 940 I wish it had a portfolio chart...
9 941 The app isn’t as user friendly as it need ...
data['words'] = list(map(lambda x: ", ".join(x), [re.findall('|'.join(features), x) for x in data.reviews]))
data
#> Index reviews words
0 0 Very user friendly interface and has 2F... user, support
1 1 The trading page is great though with a...
2 2 Widge... support
3 3 But it’s really only for serious trader...
4 4 The KYC and AML process is painful - it...
5 937 Legit pl... platform
6 938 Horrible customer service won’t get back ... custom, servic
7 939 App is fast and r... fast
8 940 I wish it had a portfolio chart... portfolio
9 941 The app isn’t as user friendly as it need ... user
|
Pandas - Create multiple new columns if str.contains return multiple value
|
I have some data like this:
0 Very user friendly interface and has 2FA support
1 The trading page is great though with allot o...
2 Widget support
3 But it’s really only for serious traders with...
4 The KYC and AML process is painful - it took ...
...
937 Legit platform!
938 Horrible customer service won’t get back to m...
939 App is fast and reliable
940 I wish it had a portfolio chart though
941 The app isn’t as user friendly as it need to b...
Name: reviews, Length: 942, dtype: object
and features:
['support',
'time',
'follow',
'submit',
'ticket',
'team',
'swap',
'account',
'experi',
'contact',
'user',
'platform',
'screen',
'servic',
'custom',
'restrict',
'fast',
'portfolio',
'specialist']
I want to check if one or more of features in reviews add that words in new column.
and my code is this:
data["words"] = data[data["reviews"].str.contains('|'.join(features))]
but this code make new column with name "words" however because sometime code return multi value so I get error
ValueError: Columns must be same length as key
how can fix it?
|
[
"The issue is that you are not actually extracting any of the words. You need to pull the words you want out of the text and then cat them into a new column.\nimport pandas as pd\nfrom io import StringIO\nimport re\n\nTESTDATA = StringIO(\"\"\"Index,reviews,\n0, Very user friendly interface and has 2FA support,\n1, The trading page is great though with allot o...,\n2, Widget support,\n3, But it’s really only for serious traders with...,\n4, The KYC and AML process is painful - it took ...,\n937, Legit platform!,\n938, Horrible customer service won’t get back to m...,\n939, App is fast and reliable,\n940, I wish it had a portfolio chart though,\n941, The app isn’t as user friendly as it need to b...\n \"\"\")\n\ndata = pd.read_csv(TESTDATA, sep=\",\").drop('Unnamed: 2', axis = 1)\ndata\n#> Index reviews\n0 0 Very user friendly interface and has 2F...\n1 1 The trading page is great though with a...\n2 2 Widge...\n3 3 But it’s really only for serious trader...\n4 4 The KYC and AML process is painful - it...\n5 937 Legit pl...\n6 938 Horrible customer service won’t get back ...\n7 939 App is fast and r...\n8 940 I wish it had a portfolio chart...\n9 941 The app isn’t as user friendly as it need ...\n\ndata['words'] = list(map(lambda x: \", \".join(x), [re.findall('|'.join(features), x) for x in data.reviews]))\ndata\n#> Index reviews words\n0 0 Very user friendly interface and has 2F... user, support\n1 1 The trading page is great though with a... \n2 2 Widge... support\n3 3 But it’s really only for serious trader... \n4 4 The KYC and AML process is painful - it... \n5 937 Legit pl... platform\n6 938 Horrible customer service won’t get back ... custom, servic\n7 939 App is fast and r... fast\n8 940 I wish it had a portfolio chart... portfolio\n9 941 The app isn’t as user friendly as it need ... user\n\n"
] |
[
0
] |
[] |
[] |
[
"contains",
"pandas",
"python"
] |
stackoverflow_0074553856_contains_pandas_python.txt
|
Q:
Python monkey patching: instance creation in method of library/object
what is the easiest way to solve the following problem in extending/altering the functionality of a third party library?
The library offers a class LibraryClass with a function func_to_be_changed. This function has a local variable internal_variable which is the instance of another class SimpleCalculation of that library. I created a new class BetterCalculation in my own module and now want LibraryClass.func_to_be_changed to use an instance of this new class.
# third party library
from third_party_library.utils import SimpleCalculation
class LibraryClass:
def func_to_be_changed(self, x):
# many complicated things go on
internal_variable = SimpleCalculation(x)
# many more complicated things go on
The easiest solution would be, to just copy the code from the third party library, subclass the LibraryClass and overwrite the function func_to_be_changed:
# my module
from third_party_library import LibraryClass
class BetterLibraryClass(LibraryClass):
def func_to_be_changed(self, x):
"""This is an exact copy of LibraryClass.func_to_be_changed."""
# many complicated things go on
internal_variable = BetterCalculation(x) # Attention: this line has been changed!!!
# many more complicated things go on
However, this involves copying of many lines of code. When a new version of the third party class improves on code that was copied without modification, this modifications need to be incorporated manually by another copying step.
I tried to use unittest.mock.patch as I know that the following two snippets work:
# some script
from unittest.mock import patch
import third_party_library
from my_module import BetterCalculation
with patch('third_party_library.utils.SimpleCalculation', BetterCalculation):
local_ = third_party_library.utils.SimpleCalculation(x) # indeed uses `BetterCalculation`
def foo(x):
return third_party_library.utils.SimpleCalculation(x)
with patch('third_party_library.utils.SimpleCalculation', BetterCalculation):
local_ = foo(x) # indeed uses `BetterCalculation`
However, the following does not work:
# some script
from unittest.mock import patch
from third_party_library.utils import SimpleCalculation
from my_module import BetterCalculation
def foo(x):
return SimpleCalculation(x)
with patch('third_party_library.utils.SimpleCalculation', BetterCalculation):
local_ = foo(x) # does not use `BetterCalculation`
# this works again
with patch('__main__.SimpleCalculation', BetterCalculation):
local_ = foo(x) # indeed uses `BetterCalculation`
Therefore, the following won`t work either:
# my module
from unittest.mock import patch
from third_party_library import LibraryClass
from my_module import BetterCalculation
class BetterLibraryClass(LibraryClass):
def func_to_be_changed(self, x):
with patch(
'third_party_library.utils.SimpleCalculation',
BetterCalculation
):
super().func_to_be_changed(x)
Is there an elegant pythonic way to do this? I guess this boils down to the question: What is the equivaltent of __main__ in the last code snippet that needs to replace third_party_library.utils?
A:
Some context
The first string argument in the patch function can have two different meanings depending on the situation. In the first situation the described object has not been imported and is unavailable to the program which would, therefore, result in a NameError without the mocking. However, in the question, an object needs to be overwritten. Therefore, it is available to the program and not using patch would not result in an error.
Disclaimer
I might have used the complete wrong language in here, as for sure there are precise python terms for all the described notions.
Overwriting an object
As shown in the question, the locally imported SimpleCalculation can be overwritten with __main__.SimpleCalculation. Therefore, it is important to remember that you need to tell patch the path to the local object and not how that same object would be imported in the current script.
Let's assume the following module:
# thirdpartymodule/__init__.py
from .utils import foo
def local_foo():
print("Hello local!")
class Bar:
def __init__(self):
foo()
local_foo()
and
# thirdpartymodule/utils.py
def foo():
print("third party module")
We want to override the functions foo and local_foo. But we don't want to override any functions, we want to override the functions foo and local_foo in the context of the file thirdpartymodule/__init__.py. It is unimportant that the function foo enters the context of the file via an import statement, while local_foo is defined locally. So we want to override the functions in the context of thirdpartymodule.foo and thirdpartymodule.local_foo. The context thirdpartymodule.utils.foo is not important here and won't help us. The following snippet illustrates that:
from unittest.mock import patch
from thirdpartymodule import Bar
bar = Bar()
# third party module
# Hello local!
def myfoo():
print("patched function")
with patch("thirdpartymodule.foo", myfoo):
bar = Bar()
# patched function
# Hello local!
# will not work!
with patch("thirdpartymodule.utils.foo", myfoo):
bar = Bar()
# third party module
# Hello local!
with patch("thirdpartymodule.local_foo", myfoo):
bar = Bar()
# third party module
# patched function
In the hypothetical module of the question we first need to assume that the class LibraryClass is defined in the file third_party_library/library_class.py. Then, we want to override third_party_library.library_class.SimpleCalculation and the correct patch would be:
# my module
from unittest.mock import patch
from third_party_library import LibraryClass
from my_module import BetterCalculation
class BetterLibraryClass(LibraryClass):
def func_to_be_changed(self, x):
with patch(
'third_party_library.library_class.SimpleCalculation',
BetterCalculation
):
super().func_to_be_changed(x)
|
Python monkey patching: instance creation in method of library/object
|
what is the easiest way to solve the following problem in extending/altering the functionality of a third party library?
The library offers a class LibraryClass with a function func_to_be_changed. This function has a local variable internal_variable which is the instance of another class SimpleCalculation of that library. I created a new class BetterCalculation in my own module and now want LibraryClass.func_to_be_changed to use an instance of this new class.
# third party library
from third_party_library.utils import SimpleCalculation
class LibraryClass:
def func_to_be_changed(self, x):
# many complicated things go on
internal_variable = SimpleCalculation(x)
# many more complicated things go on
The easiest solution would be, to just copy the code from the third party library, subclass the LibraryClass and overwrite the function func_to_be_changed:
# my module
from third_party_library import LibraryClass
class BetterLibraryClass(LibraryClass):
def func_to_be_changed(self, x):
"""This is an exact copy of LibraryClass.func_to_be_changed."""
# many complicated things go on
internal_variable = BetterCalculation(x) # Attention: this line has been changed!!!
# many more complicated things go on
However, this involves copying of many lines of code. When a new version of the third party class improves on code that was copied without modification, this modifications need to be incorporated manually by another copying step.
I tried to use unittest.mock.patch as I know that the following two snippets work:
# some script
from unittest.mock import patch
import third_party_library
from my_module import BetterCalculation
with patch('third_party_library.utils.SimpleCalculation', BetterCalculation):
local_ = third_party_library.utils.SimpleCalculation(x) # indeed uses `BetterCalculation`
def foo(x):
return third_party_library.utils.SimpleCalculation(x)
with patch('third_party_library.utils.SimpleCalculation', BetterCalculation):
local_ = foo(x) # indeed uses `BetterCalculation`
However, the following does not work:
# some script
from unittest.mock import patch
from third_party_library.utils import SimpleCalculation
from my_module import BetterCalculation
def foo(x):
return SimpleCalculation(x)
with patch('third_party_library.utils.SimpleCalculation', BetterCalculation):
local_ = foo(x) # does not use `BetterCalculation`
# this works again
with patch('__main__.SimpleCalculation', BetterCalculation):
local_ = foo(x) # indeed uses `BetterCalculation`
Therefore, the following won`t work either:
# my module
from unittest.mock import patch
from third_party_library import LibraryClass
from my_module import BetterCalculation
class BetterLibraryClass(LibraryClass):
def func_to_be_changed(self, x):
with patch(
'third_party_library.utils.SimpleCalculation',
BetterCalculation
):
super().func_to_be_changed(x)
Is there an elegant pythonic way to do this? I guess this boils down to the question: What is the equivaltent of __main__ in the last code snippet that needs to replace third_party_library.utils?
|
[
"Some context\nThe first string argument in the patch function can have two different meanings depending on the situation. In the first situation the described object has not been imported and is unavailable to the program which would, therefore, result in a NameError without the mocking. However, in the question, an object needs to be overwritten. Therefore, it is available to the program and not using patch would not result in an error.\nDisclaimer\nI might have used the complete wrong language in here, as for sure there are precise python terms for all the described notions.\nOverwriting an object\nAs shown in the question, the locally imported SimpleCalculation can be overwritten with __main__.SimpleCalculation. Therefore, it is important to remember that you need to tell patch the path to the local object and not how that same object would be imported in the current script.\nLet's assume the following module:\n# thirdpartymodule/__init__.py\nfrom .utils import foo\n\n\ndef local_foo():\n print(\"Hello local!\")\n\n\nclass Bar:\n def __init__(self):\n foo()\n local_foo()\n\nand\n# thirdpartymodule/utils.py\ndef foo():\n print(\"third party module\")\n\nWe want to override the functions foo and local_foo. But we don't want to override any functions, we want to override the functions foo and local_foo in the context of the file thirdpartymodule/__init__.py. It is unimportant that the function foo enters the context of the file via an import statement, while local_foo is defined locally. So we want to override the functions in the context of thirdpartymodule.foo and thirdpartymodule.local_foo. The context thirdpartymodule.utils.foo is not important here and won't help us. The following snippet illustrates that:\nfrom unittest.mock import patch\nfrom thirdpartymodule import Bar\n\n\nbar = Bar()\n# third party module\n# Hello local!\n\ndef myfoo():\n print(\"patched function\")\n \n \nwith patch(\"thirdpartymodule.foo\", myfoo):\n bar = Bar()\n # patched function\n # Hello local!\n \n# will not work!\nwith patch(\"thirdpartymodule.utils.foo\", myfoo):\n bar = Bar()\n # third party module\n # Hello local!\n \nwith patch(\"thirdpartymodule.local_foo\", myfoo):\n bar = Bar()\n # third party module\n # patched function\n\nIn the hypothetical module of the question we first need to assume that the class LibraryClass is defined in the file third_party_library/library_class.py. Then, we want to override third_party_library.library_class.SimpleCalculation and the correct patch would be:\n# my module\nfrom unittest.mock import patch\nfrom third_party_library import LibraryClass\n\nfrom my_module import BetterCalculation\n\nclass BetterLibraryClass(LibraryClass):\n def func_to_be_changed(self, x):\n with patch(\n 'third_party_library.library_class.SimpleCalculation',\n BetterCalculation\n ):\n super().func_to_be_changed(x)\n\n"
] |
[
1
] |
[] |
[] |
[
"mocking",
"monkeypatching",
"python",
"python_3.x"
] |
stackoverflow_0074536960_mocking_monkeypatching_python_python_3.x.txt
|
Q:
How to programmatically generate the CREATE TABLE SQL statement for a given model in Django?
I need to programmatically generate the CREATE TABLE statement for a given unmanaged model in my Django app (managed = False)
Since i'm working on a legacy database, i don't want to create a migration and use sqlmigrate.
The ./manage.py sql command was useful for this purpose but it has been removed in Django 1.8
Do you know about any alternatives?
A:
As suggested, I post a complete answer for the case, that the question might imply.
Suppose you have an external DB table, that you decided to access as a Django model and therefore have described it as an unmanaged model (Meta: managed = False).
Later you need to be able to create it in your code, e.g for some tests using your local DB. Obviously, Django doesn't make migrations for unmanaged models and therefore won't create it in your test DB.
This can be solved using Django APIs without resorting to raw SQL - SchemaEditor. See a more complete example below, but as a short answer you would use it like this:
from django.db import connections
with connections['db_to_create_a_table_in'].schema_editor() as schema_editor:
schema_editor.create_model(YourUnmanagedModelClass)
A practical example:
# your_app/models/your_model.py
from django.db import models
class IntegrationView(models.Model):
"""A read-only model to access a view in some external DB."""
class Meta:
managed = False
db_table = 'integration_view'
name = models.CharField(
db_column='object_name',
max_length=255,
primaty_key=True,
verbose_name='Object Name',
)
some_value = models.CharField(
db_column='some_object_value',
max_length=255,
blank=True,
null=True,
verbose_name='Some Object Value',
)
# Depending on the situation it might be a good idea to redefine
# some methods as a NOOP as a safety-net.
# Note, that it's not completely safe this way, but might help with some
# silly mistakes in user code
def save(self, *args, **kwargs):
"""Preventing data modification."""
pass
def delete(self, *args, **kwargs):
"""Preventing data deletion."""
pass
Now, suppose you need to be able to create this model via Django, e.g. for some tests.
# your_app/tests/some_test.py
# This will allow to access the `SchemaEditor` for the DB
from django.db import connections
from django.test import TestCase
from your_app.models.your_model import IntegrationView
class SomeLogicTestCase(TestCase):
"""Tests some logic, that uses `IntegrationView`."""
# Since it is assumed, that the `IntegrationView` is read-only for the
# the case being described it's a good idea to put setup logic in class
# setup fixture, that will run only once for the whole test case
@classmethod
def setUpClass(cls):
"""Prepares `IntegrationView` mock data for the test case."""
# This is the actual part, that will create the table in the DB
# for the unmanaged model (Any model in fact, but managed models will
# have their tables created already by the Django testing framework)
# Note: Here we're able to choose which DB, defined in your settings,
# will be used to create the table
with connections['external_db'].schema_editor() as schema_editor:
schema_editor.create_model(IntegrationView)
# That's all you need, after the execution of this statements
# a DB table for `IntegrationView` will be created in the DB
# defined as `external_db`.
# Now suppose we need to add some mock data...
# Again, if we consider the table to be read-only, the data can be
# defined here, otherwise it's better to do it in `setUp()` method.
# Remember `IntegrationView.save()` is overridden as a NOOP, so simple
# calls to `IntegrationView.save()` or `IntegrationView.objects.create()`
# won't do anything, so we need to "Improvise. Adapt. Overcome."
# One way is to use the `save()` method of the base class,
# but provide the instance of our class
integration_view = IntegrationView(
name='Biggus Dickus',
some_value='Something really important.',
)
super(IntegrationView, integration_view).save(using='external_db')
# Another one is to use the `bulk_create()`, which doesn't use
# `save()` internally, and in fact is a better solution
# if we're creating many records
IntegrationView.objects.using('external_db').bulk_create([
IntegrationView(
name='Sillius Soddus',
some_value='Something important',
),
IntegrationView(
name='Naughtius Maximus',
some_value='Whatever',
),
])
# Don't forget to clean after
@classmethod
def tearDownClass(cls):
with connections['external_db'].schema_editor() as schema_editor:
schema_editor.delete_model(IntegrationView)
def test_some_logic_using_data_from_integration_view(self):
self.assertTrue(IntegrationView.objects.using('external_db').filter(
name='Biggus Dickus',
))
To make the example more complete... Since we're using multiple DB (default and external_db) Django will try to run migrations on both of them for the tests and as of now there's no option in DB settings to prevent this. So we have to use a custom DB router for testing.
# your_app/tests/base.py
class PreventMigrationsDBRouter:
"""DB router to prevent migrations for specific DBs during tests."""
_NO_MIGRATION_DBS = {'external_db', }
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""Actually disallows migrations for specific DBs."""
return db not in self._NO_MIGRATION_DBS
And a test settings file example for the described case:
# settings/test.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'db_name',
'USER': 'username',
'HOST': 'localhost',
'PASSWORD': 'password',
'PORT': '1521',
},
# For production here we would have settings to connect to the external DB,
# but for testing purposes we could get by with an SQLite DB
'external_db': {
'ENGINE': 'django.db.backends.sqlite3',
},
}
# Not necessary to use a router in production config, since if the DB
# is unspecified explicitly for some action Django will use the `default` DB
DATABASE_ROUTERS = ['your_app.tests.base.PreventMigrationsDBRouter', ]
Hope this detailed new Django user user-friendly example will help someone and save their time.
A:
unfortunately there seems to be no easy way to do this, but for your luck I have just succeeded in producing a working snippet for you digging in the internals of the django migrations jungle.
Just:
save the code to get_sql_create_table.py (in example)
do $ export DJANGO_SETTINGS_MODULE=yourproject.settings
launch the script with python get_sql_create_table.py yourapp.yourmodel
and it should output what you need.
Hope it helps!
import django
django.setup()
from django.db.migrations.state import ModelState
from django.db.migrations import operations
from django.db.migrations.migration import Migration
from django.db import connections
from django.db.migrations.state import ProjectState
def get_create_sql_for_model(model):
model_state = ModelState.from_model(model)
# Create a fake migration with the CreateModel operation
cm = operations.CreateModel(name=model_state.name, fields=model_state.fields)
migration = Migration("fake_migration", "app")
migration.operations.append(cm)
# Let the migration framework think that the project is in an initial state
state = ProjectState()
# Get the SQL through the schema_editor bound to the connection
connection = connections['default']
with connection.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor:
state = migration.apply(state, schema_editor, collect_sql=True)
# return the CREATE TABLE statement
return "\n".join(schema_editor.collected_sql)
if __name__ == "__main__":
import importlib
import sys
if len(sys.argv) < 2:
print("Usage: {} <app.model>".format(sys.argv[0]))
sys.exit(100)
app, model_name = sys.argv[1].split('.')
models = importlib.import_module("{}.models".format(app))
model = getattr(models, model_name)
rv = get_create_sql_for_model(model)
print(rv)
A:
For Django v4.1.3, the above get_create_sql_for_model soruce code changed like this:
from django.db.migrations.state import ModelState
from django.db.migrations import operations
from django.db.migrations.migration import Migration
from django.db import connections
from django.db.migrations.state import ProjectState
def get_create_sql_for_model(model):
model_state = ModelState.from_model(model)
table_name = model_state.options['db_table']
# Create a fake migration with the CreateModel operation
cm = operations.CreateModel(name=model_state.name, fields=model_state.fields.items())
migration = Migration("fake_migration", "app")
migration.operations.append(cm)
# Let the migration framework think that the project is in an initial state
state = ProjectState()
# Get the SQL through the schema_editor bound to the connection
connection = connections['default']
with connection.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor:
state = migration.apply(state, schema_editor, collect_sql=True)
sqls = schema_editor.collected_sql
items = []
for sql in sqls:
if sql.startswith('--'):
continue
items.append(sql)
return table_name,items
#EOP
I used it to create all tables (like the command syncdb of old Django version):
for app in settings.INSTALLED_APPS:
app_name = app.split('.')[0]
app_models = apps.get_app_config(app_name).get_models()
for model in app_models:
table_name,sqls = get_create_sql_for_model(model)
if settings.DEBUG:
s = "SELECT COUNT(*) AS c FROM sqlite_master WHERE name = '%s'" % table_name
else:
s = "SELECT COUNT(*) AS c FROM information_schema.TABLES WHERE table_name='%s'" % table_name
rs = select_by_raw_sql(s)
if not rs[0]['c']:
for sql in sqls:
exec_by_raw_sql(sql)
print('CREATE TABLE DONE:%s' % table_name)
The full soure code can be found at Django syncdb command came back for v4.1.3 version
|
How to programmatically generate the CREATE TABLE SQL statement for a given model in Django?
|
I need to programmatically generate the CREATE TABLE statement for a given unmanaged model in my Django app (managed = False)
Since i'm working on a legacy database, i don't want to create a migration and use sqlmigrate.
The ./manage.py sql command was useful for this purpose but it has been removed in Django 1.8
Do you know about any alternatives?
|
[
"As suggested, I post a complete answer for the case, that the question might imply.\nSuppose you have an external DB table, that you decided to access as a Django model and therefore have described it as an unmanaged model (Meta: managed = False).\nLater you need to be able to create it in your code, e.g for some tests using your local DB. Obviously, Django doesn't make migrations for unmanaged models and therefore won't create it in your test DB.\nThis can be solved using Django APIs without resorting to raw SQL - SchemaEditor. See a more complete example below, but as a short answer you would use it like this:\n from django.db import connections\n\n with connections['db_to_create_a_table_in'].schema_editor() as schema_editor:\n schema_editor.create_model(YourUnmanagedModelClass)\n\nA practical example:\n# your_app/models/your_model.py\n\nfrom django.db import models\n\nclass IntegrationView(models.Model):\n \"\"\"A read-only model to access a view in some external DB.\"\"\"\n\n class Meta:\n managed = False\n db_table = 'integration_view'\n\n name = models.CharField(\n db_column='object_name',\n max_length=255,\n primaty_key=True,\n verbose_name='Object Name',\n )\n some_value = models.CharField(\n db_column='some_object_value',\n max_length=255,\n blank=True,\n null=True,\n verbose_name='Some Object Value',\n )\n\n # Depending on the situation it might be a good idea to redefine\n # some methods as a NOOP as a safety-net.\n # Note, that it's not completely safe this way, but might help with some\n # silly mistakes in user code\n\n def save(self, *args, **kwargs):\n \"\"\"Preventing data modification.\"\"\"\n pass\n\n def delete(self, *args, **kwargs):\n \"\"\"Preventing data deletion.\"\"\"\n pass\n\nNow, suppose you need to be able to create this model via Django, e.g. for some tests.\n# your_app/tests/some_test.py\n\n# This will allow to access the `SchemaEditor` for the DB\nfrom django.db import connections\nfrom django.test import TestCase\nfrom your_app.models.your_model import IntegrationView\n\nclass SomeLogicTestCase(TestCase):\n \"\"\"Tests some logic, that uses `IntegrationView`.\"\"\"\n\n # Since it is assumed, that the `IntegrationView` is read-only for the\n # the case being described it's a good idea to put setup logic in class \n # setup fixture, that will run only once for the whole test case\n @classmethod\n def setUpClass(cls):\n \"\"\"Prepares `IntegrationView` mock data for the test case.\"\"\"\n\n # This is the actual part, that will create the table in the DB\n # for the unmanaged model (Any model in fact, but managed models will\n # have their tables created already by the Django testing framework)\n # Note: Here we're able to choose which DB, defined in your settings,\n # will be used to create the table\n\n with connections['external_db'].schema_editor() as schema_editor:\n schema_editor.create_model(IntegrationView)\n\n # That's all you need, after the execution of this statements\n # a DB table for `IntegrationView` will be created in the DB\n # defined as `external_db`.\n\n # Now suppose we need to add some mock data...\n # Again, if we consider the table to be read-only, the data can be \n # defined here, otherwise it's better to do it in `setUp()` method.\n\n # Remember `IntegrationView.save()` is overridden as a NOOP, so simple\n # calls to `IntegrationView.save()` or `IntegrationView.objects.create()`\n # won't do anything, so we need to \"Improvise. Adapt. Overcome.\"\n\n # One way is to use the `save()` method of the base class,\n # but provide the instance of our class\n integration_view = IntegrationView(\n name='Biggus Dickus',\n some_value='Something really important.',\n )\n super(IntegrationView, integration_view).save(using='external_db')\n\n # Another one is to use the `bulk_create()`, which doesn't use\n # `save()` internally, and in fact is a better solution\n # if we're creating many records\n\n IntegrationView.objects.using('external_db').bulk_create([\n IntegrationView(\n name='Sillius Soddus',\n some_value='Something important',\n ),\n IntegrationView(\n name='Naughtius Maximus',\n some_value='Whatever',\n ),\n ])\n\n # Don't forget to clean after\n @classmethod\n def tearDownClass(cls):\n with connections['external_db'].schema_editor() as schema_editor:\n schema_editor.delete_model(IntegrationView)\n\n def test_some_logic_using_data_from_integration_view(self):\n self.assertTrue(IntegrationView.objects.using('external_db').filter(\n name='Biggus Dickus',\n ))\n\nTo make the example more complete... Since we're using multiple DB (default and external_db) Django will try to run migrations on both of them for the tests and as of now there's no option in DB settings to prevent this. So we have to use a custom DB router for testing.\n # your_app/tests/base.py\n\nclass PreventMigrationsDBRouter:\n \"\"\"DB router to prevent migrations for specific DBs during tests.\"\"\"\n _NO_MIGRATION_DBS = {'external_db', }\n\n def allow_migrate(self, db, app_label, model_name=None, **hints):\n \"\"\"Actually disallows migrations for specific DBs.\"\"\"\n return db not in self._NO_MIGRATION_DBS\n\nAnd a test settings file example for the described case:\n# settings/test.py\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.oracle',\n 'NAME': 'db_name',\n 'USER': 'username',\n 'HOST': 'localhost',\n 'PASSWORD': 'password',\n 'PORT': '1521',\n },\n # For production here we would have settings to connect to the external DB,\n # but for testing purposes we could get by with an SQLite DB \n 'external_db': {\n 'ENGINE': 'django.db.backends.sqlite3',\n },\n}\n\n# Not necessary to use a router in production config, since if the DB \n# is unspecified explicitly for some action Django will use the `default` DB\nDATABASE_ROUTERS = ['your_app.tests.base.PreventMigrationsDBRouter', ]\n\nHope this detailed new Django user user-friendly example will help someone and save their time.\n",
"unfortunately there seems to be no easy way to do this, but for your luck I have just succeeded in producing a working snippet for you digging in the internals of the django migrations jungle.\nJust:\n\nsave the code to get_sql_create_table.py (in example)\ndo $ export DJANGO_SETTINGS_MODULE=yourproject.settings\nlaunch the script with python get_sql_create_table.py yourapp.yourmodel\n\nand it should output what you need.\nHope it helps!\nimport django\ndjango.setup()\n\nfrom django.db.migrations.state import ModelState\nfrom django.db.migrations import operations\nfrom django.db.migrations.migration import Migration\nfrom django.db import connections\nfrom django.db.migrations.state import ProjectState\n\ndef get_create_sql_for_model(model):\n\n model_state = ModelState.from_model(model)\n\n # Create a fake migration with the CreateModel operation\n cm = operations.CreateModel(name=model_state.name, fields=model_state.fields)\n migration = Migration(\"fake_migration\", \"app\")\n migration.operations.append(cm)\n\n # Let the migration framework think that the project is in an initial state\n state = ProjectState()\n\n # Get the SQL through the schema_editor bound to the connection\n connection = connections['default']\n with connection.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor:\n state = migration.apply(state, schema_editor, collect_sql=True)\n\n # return the CREATE TABLE statement\n return \"\\n\".join(schema_editor.collected_sql)\n\nif __name__ == \"__main__\":\n\n import importlib\n import sys\n\n if len(sys.argv) < 2:\n print(\"Usage: {} <app.model>\".format(sys.argv[0]))\n sys.exit(100)\n\n app, model_name = sys.argv[1].split('.')\n\n models = importlib.import_module(\"{}.models\".format(app))\n model = getattr(models, model_name)\n rv = get_create_sql_for_model(model)\n print(rv)\n\n",
"For Django v4.1.3, the above get_create_sql_for_model soruce code changed like this:\n\n from django.db.migrations.state import ModelState\n from django.db.migrations import operations\n from django.db.migrations.migration import Migration\n from django.db import connections\n from django.db.migrations.state import ProjectState\n \n def get_create_sql_for_model(model):\n model_state = ModelState.from_model(model)\n table_name = model_state.options['db_table']\n \n # Create a fake migration with the CreateModel operation\n cm = operations.CreateModel(name=model_state.name, fields=model_state.fields.items())\n migration = Migration(\"fake_migration\", \"app\")\n migration.operations.append(cm)\n \n # Let the migration framework think that the project is in an initial state\n state = ProjectState()\n \n # Get the SQL through the schema_editor bound to the connection\n connection = connections['default']\n with connection.schema_editor(collect_sql=True, atomic=migration.atomic) as schema_editor:\n state = migration.apply(state, schema_editor, collect_sql=True)\n \n sqls = schema_editor.collected_sql\n items = []\n for sql in sqls:\n if sql.startswith('--'):\n continue\n items.append(sql)\n \n return table_name,items\n \n #EOP\n\nI used it to create all tables (like the command syncdb of old Django version):\n for app in settings.INSTALLED_APPS:\n app_name = app.split('.')[0]\n app_models = apps.get_app_config(app_name).get_models()\n for model in app_models:\n table_name,sqls = get_create_sql_for_model(model)\n\n if settings.DEBUG:\n s = \"SELECT COUNT(*) AS c FROM sqlite_master WHERE name = '%s'\" % table_name\n else:\n s = \"SELECT COUNT(*) AS c FROM information_schema.TABLES WHERE table_name='%s'\" % table_name\n rs = select_by_raw_sql(s)\n if not rs[0]['c']:\n for sql in sqls:\n exec_by_raw_sql(sql)\n print('CREATE TABLE DONE:%s' % table_name)\n\n\nThe full soure code can be found at Django syncdb command came back for v4.1.3 version\n"
] |
[
15,
6,
0
] |
[] |
[] |
[
"django",
"migration",
"python",
"sql"
] |
stackoverflow_0048666334_django_migration_python_sql.txt
|
Q:
PyPy memory leak with custom C++ extension?
I am trying to write a C++ extension with support for CPython and PyPy.
My extension involves creating some custom types that support the call interface.
However, I appear to be getting memory leaks in PyPy when I raise Python exceptions. I am not getting any memory leaks with regular CPython.
I have isolated the leaking code, with a corresponding test in https://github.com/Lalaland/memoryleak_example. Run make to build the code and then test it by either running python test.py or pypy test.py
My extension class is the following:
struct custom_function {
PyObject_HEAD
};
PyObject* custom_call(PyObject *self, PyObject *args, PyObject *kwargs) {
std::cout << "Calling custom function with except, simpler" << std::endl;
PyErr_SetString(PyExc_SystemError, "Fancier exception for custom fancy func");
return nullptr;
};
PyTypeObject custom_function_type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "custom_function",
.tp_basicsize = sizeof(custom_function),
.tp_itemsize = 0,
.tp_call = custom_call,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = PyDoc_STR("Custom function type"),
.tp_new = PyType_GenericNew,
};
My memory leak detection code (using weakref) is:
import helloworld as m
import gc
import weakref
class ExampleClass:
def __init__(self):
pass
def simple_test(f):
it = ExampleClass()
a = weakref.ref(it)
try:
f(it)
except Exception as e:
print("Got exception!", e)
del e
assert a() is not None
del it
gc.collect()
assert a() is None
simple_test(m.custom_fancy_func)
Does anyone know what I am doing wrong?
A:
Hmm, looks like this is a bug in PyPy: https://foss.heptapod.net/pypy/pypy/-/issues/3854
|
PyPy memory leak with custom C++ extension?
|
I am trying to write a C++ extension with support for CPython and PyPy.
My extension involves creating some custom types that support the call interface.
However, I appear to be getting memory leaks in PyPy when I raise Python exceptions. I am not getting any memory leaks with regular CPython.
I have isolated the leaking code, with a corresponding test in https://github.com/Lalaland/memoryleak_example. Run make to build the code and then test it by either running python test.py or pypy test.py
My extension class is the following:
struct custom_function {
PyObject_HEAD
};
PyObject* custom_call(PyObject *self, PyObject *args, PyObject *kwargs) {
std::cout << "Calling custom function with except, simpler" << std::endl;
PyErr_SetString(PyExc_SystemError, "Fancier exception for custom fancy func");
return nullptr;
};
PyTypeObject custom_function_type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "custom_function",
.tp_basicsize = sizeof(custom_function),
.tp_itemsize = 0,
.tp_call = custom_call,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = PyDoc_STR("Custom function type"),
.tp_new = PyType_GenericNew,
};
My memory leak detection code (using weakref) is:
import helloworld as m
import gc
import weakref
class ExampleClass:
def __init__(self):
pass
def simple_test(f):
it = ExampleClass()
a = weakref.ref(it)
try:
f(it)
except Exception as e:
print("Got exception!", e)
del e
assert a() is not None
del it
gc.collect()
assert a() is None
simple_test(m.custom_fancy_func)
Does anyone know what I am doing wrong?
|
[
"Hmm, looks like this is a bug in PyPy: https://foss.heptapod.net/pypy/pypy/-/issues/3854\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"pypy",
"python",
"python_extensions"
] |
stackoverflow_0074553376_c++_pypy_python_python_extensions.txt
|
Q:
How to sort lists that contain letters and numbers?
I have tried lots of different ways to sort the list, but it never sorts it.
list = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american
dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']
I want them to all be in order eg:
ep1
ep2
ep3
ep4
ep5
A:
I suggest to use re module to extract name, episode, season etc. The key_function will sort the list by Name, Season, Episode:
import re
pat = re.compile(r"(.*) S(\d+)-EP(\d+)")
def key_function(value):
name, season, episode = pat.search(value).groups()
return name, int(season), int(episode)
print(sorted(lst, key=key_function))
Prints:
[
"american dad S1-EP1",
"american dad S1-EP2",
"american dad S1-EP3",
"american dad S1-EP4",
"american dad S1-EP5",
"american dad S1-EP6",
"american dad S1-EP7",
"american dad S1-EP8",
"american dad S1-EP9",
"american dad S1-EP10",
"american dad S1-EP11",
"american dad S1-EP12",
"american dad S1-EP13",
"american dad S1-EP14",
"american dad S1-EP15",
"american dad S1-EP16",
"american dad S1-EP17",
"american dad S1-EP18",
"american dad S1-EP19",
"american dad S1-EP20",
"american dad S1-EP21",
"american dad S1-EP22",
"american dad S1-EP23",
]
A:
found an answer by using:
list.sort(key=lambda x: int("".join([i for i in x if i.isdigit()])))
A:
Create a regular expression pattern with two capturing groups - one for the season number, one for the episode number.
Define a custom key for the sorting function, which returns a tuple of integers. The episodes will be sorted in ascending order according to these integers.
Code:
import re
episodes = [
'american dad S1-EP1',
'american dad S1-EP10',
'american dad S1-EP11',
'american dad S1-EP12',
'american dad S1-EP13',
'american dad S1-EP14',
'american dad S1-EP15',
'american dad S1-EP16',
'american dad S1-EP17',
'american dad S1-EP18',
'american dad S1-EP19',
'american dad S1-EP2',
'american dad S1-EP20',
'american dad S1-EP21',
'american dad S1-EP22',
'american dad S1-EP23',
'american dad S1-EP3',
'american dad S1-EP4',
'american dad S1-EP5',
'american dad S1-EP6',
'american dad S1-EP7',
'american dad S1-EP8',
'american dad S1-EP9'
]
pattern = "S(\\d+)-EP(\\d+)"
def key(episode):
regex_match = re.search(pattern, episode)
return tuple(map(int, regex_match.groups()))
print(sorted(episodes, key=key))
Output:
['american dad S1-EP1', 'american dad S1-EP2', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23']
>>>
A:
Try using the sorted function with a key:
list1 = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19',
'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']
def get_last_digits(s):
last_digits = s[s.index("P") + 1:]
return int(last_digits)
list1.sort(key=get_last_digits)
Note: This only works if all episodes are the same season.
A:
The big question here would be whether you need to sort decimals or not. Assuming that you only care about integers (e.g. that 12.6 would come before 12.56), then you can convert the list of strings to a list of lists, where each item in the list is either a string or an integer, then sort that:
import re
RE_NUM = re.compile(r'(\d+)|(\D+)')
def sort_mixed(strings):
# sort list of strings with integers embedded in them
split_strings = []
for string in strings:
split_string = [(int(i or 0), i or s) for i, s in RE_NUM.findall(string)]
split_strings.append(split_string)
return [''.join(s for _, s in v) for v in sorted(split_strings)]
# example usage
sort_mixed(['15.51', '12.9', '15.6.6', '15.6'])
# ['12.9', '15.6', '15.6.6', '15.51']
Note: Unlike other answers in this thread, the above works for any combination of integers and strings, including both no integers, no strings, or any number of integers more than one.
A:
You can customize the sorted key by lambda. (BTW, avoid to name a variable as list in python because it's a reserved word link)
For more details about lambda, you can check link
Example:
l = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']
sorted_l = sorted(l, key=lambda x: int(x.split("-EP")[1]))
print(sorted_l)
Or, python can sort one list based on values from another list (check link). You can create a new list, which only contains ep number.
Example:
l = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']
ep_list = [int(x.split("-EP")[1]) for x in l]
sorted_l = [x for _, x in sorted(zip(ep_list, l))]
print(sorted_l)
output:
['american dad S1-EP1', 'american dad S1-EP2', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23']
|
How to sort lists that contain letters and numbers?
|
I have tried lots of different ways to sort the list, but it never sorts it.
list = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american
dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']
I want them to all be in order eg:
ep1
ep2
ep3
ep4
ep5
|
[
"I suggest to use re module to extract name, episode, season etc. The key_function will sort the list by Name, Season, Episode:\nimport re\n\npat = re.compile(r\"(.*) S(\\d+)-EP(\\d+)\")\n\n\ndef key_function(value):\n name, season, episode = pat.search(value).groups()\n return name, int(season), int(episode)\n\n\nprint(sorted(lst, key=key_function))\n\nPrints:\n[\n \"american dad S1-EP1\",\n \"american dad S1-EP2\",\n \"american dad S1-EP3\",\n \"american dad S1-EP4\",\n \"american dad S1-EP5\",\n \"american dad S1-EP6\",\n \"american dad S1-EP7\",\n \"american dad S1-EP8\",\n \"american dad S1-EP9\",\n \"american dad S1-EP10\",\n \"american dad S1-EP11\",\n \"american dad S1-EP12\",\n \"american dad S1-EP13\",\n \"american dad S1-EP14\",\n \"american dad S1-EP15\",\n \"american dad S1-EP16\",\n \"american dad S1-EP17\",\n \"american dad S1-EP18\",\n \"american dad S1-EP19\",\n \"american dad S1-EP20\",\n \"american dad S1-EP21\",\n \"american dad S1-EP22\",\n \"american dad S1-EP23\",\n]\n\n",
"found an answer by using:\nlist.sort(key=lambda x: int(\"\".join([i for i in x if i.isdigit()])))\n\n",
"\nCreate a regular expression pattern with two capturing groups - one for the season number, one for the episode number.\nDefine a custom key for the sorting function, which returns a tuple of integers. The episodes will be sorted in ascending order according to these integers.\n\nCode:\nimport re\n\nepisodes = [\n 'american dad S1-EP1',\n 'american dad S1-EP10',\n 'american dad S1-EP11',\n 'american dad S1-EP12',\n 'american dad S1-EP13',\n 'american dad S1-EP14',\n 'american dad S1-EP15',\n 'american dad S1-EP16',\n 'american dad S1-EP17',\n 'american dad S1-EP18',\n 'american dad S1-EP19',\n 'american dad S1-EP2',\n 'american dad S1-EP20',\n 'american dad S1-EP21',\n 'american dad S1-EP22',\n 'american dad S1-EP23',\n 'american dad S1-EP3',\n 'american dad S1-EP4',\n 'american dad S1-EP5',\n 'american dad S1-EP6',\n 'american dad S1-EP7',\n 'american dad S1-EP8',\n 'american dad S1-EP9'\n]\n\npattern = \"S(\\\\d+)-EP(\\\\d+)\"\n\ndef key(episode):\n regex_match = re.search(pattern, episode)\n return tuple(map(int, regex_match.groups()))\n\nprint(sorted(episodes, key=key))\n\nOutput:\n['american dad S1-EP1', 'american dad S1-EP2', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23']\n>>> \n\n",
"Try using the sorted function with a key:\nlist1 = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19',\n 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']\n\ndef get_last_digits(s):\n last_digits = s[s.index(\"P\") + 1:]\n return int(last_digits)\n\nlist1.sort(key=get_last_digits)\n\nNote: This only works if all episodes are the same season.\n",
"The big question here would be whether you need to sort decimals or not. Assuming that you only care about integers (e.g. that 12.6 would come before 12.56), then you can convert the list of strings to a list of lists, where each item in the list is either a string or an integer, then sort that:\nimport re\n\nRE_NUM = re.compile(r'(\\d+)|(\\D+)')\n\ndef sort_mixed(strings):\n # sort list of strings with integers embedded in them\n split_strings = []\n for string in strings:\n split_string = [(int(i or 0), i or s) for i, s in RE_NUM.findall(string)]\n split_strings.append(split_string)\n return [''.join(s for _, s in v) for v in sorted(split_strings)]\n\n# example usage\nsort_mixed(['15.51', '12.9', '15.6.6', '15.6'])\n# ['12.9', '15.6', '15.6.6', '15.51']\n\nNote: Unlike other answers in this thread, the above works for any combination of integers and strings, including both no integers, no strings, or any number of integers more than one.\n",
"You can customize the sorted key by lambda. (BTW, avoid to name a variable as list in python because it's a reserved word link)\nFor more details about lambda, you can check link\nExample:\nl = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']\nsorted_l = sorted(l, key=lambda x: int(x.split(\"-EP\")[1]))\nprint(sorted_l)\n\nOr, python can sort one list based on values from another list (check link). You can create a new list, which only contains ep number.\nExample:\nl = ['american dad S1-EP1', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP2', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9']\nep_list = [int(x.split(\"-EP\")[1]) for x in l]\nsorted_l = [x for _, x in sorted(zip(ep_list, l))]\nprint(sorted_l)\n\noutput:\n['american dad S1-EP1', 'american dad S1-EP2', 'american dad S1-EP3', 'american dad S1-EP4', 'american dad S1-EP5', 'american dad S1-EP6', 'american dad S1-EP7', 'american dad S1-EP8', 'american dad S1-EP9', 'american dad S1-EP10', 'american dad S1-EP11', 'american dad S1-EP12', 'american dad S1-EP13', 'american dad S1-EP14', 'american dad S1-EP15', 'american dad S1-EP16', 'american dad S1-EP17', 'american dad S1-EP18', 'american dad S1-EP19', 'american dad S1-EP20', 'american dad S1-EP21', 'american dad S1-EP22', 'american dad S1-EP23']\n\n"
] |
[
2,
1,
1,
1,
0,
0
] |
[] |
[] |
[
"python",
"sorting"
] |
stackoverflow_0074553992_python_sorting.txt
|
Q:
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
Im using a Pytorch Unet model to which i am feeding in a image as input and along with that i am feeding the label as the input image mask and traning the dataset on it.
The Unet model i have picked up from somewhere else, and i am using the cross-entropy loss as a loss function but i get this dimension out of range error,
RuntimeError
Traceback (most recent call last)
<ipython-input-358-fa0ef49a43ae> in <module>()
16 for epoch in range(0, num_epochs):
17 # train for one epoch
---> 18 curr_loss = train(train_loader, model, criterion, epoch, num_epochs)
19
20 # store best loss and save a model checkpoint
<ipython-input-356-1bd6c6c281fb> in train(train_loader, model, criterion, epoch, num_epochs)
16 # measure loss
17 print (outputs.size(),labels.size())
---> 18 loss = criterion(outputs, labels)
19 losses.update(loss.data[0], images.size(0))
20
/usr/local/lib/python3.5/dist-packages/torch/nn/modules/module.py in _ _call__(self, *input, **kwargs)
323 for hook in self._forward_pre_hooks.values():
324 hook(self, input)
--> 325 result = self.forward(*input, **kwargs)
326 for hook in self._forward_hooks.values():
327 hook_result = hook(self, input, result)
<ipython-input-355-db66abcdb074> in forward(self, logits, targets)
9 probs_flat = probs.view(-1)
10 targets_flat = targets.view(-1)
---> 11 return self.crossEntropy_loss(probs_flat, targets_flat)
/usr/local/lib/python3.5/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
323 for hook in self._forward_pre_hooks.values():
324 hook(self, input)
--> 325 result = self.forward(*input, **kwargs)
326 for hook in self._forward_hooks.values():
327 hook_result = hook(self, input, result)
/usr/local/lib/python3.5/dist-packages/torch/nn/modules/loss.py in f orward(self, input, target)
599 _assert_no_grad(target)
600 return F.cross_entropy(input, target, self.weight, self.size_average,
--> 601 self.ignore_index, self.reduce)
602
603
/usr/local/lib/python3.5/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce)
1138 >>> loss.backward()
1139 """
-> 1140 return nll_loss(log_softmax(input, 1), target, weight, size_average, ignore_index, reduce)
1141
1142
/usr/local/lib/python3.5/dist-packages/torch/nn/functional.py in log_softmax(input, dim, _stacklevel)
784 if dim is None:
785 dim = _get_softmax_dim('log_softmax', input.dim(), _stacklevel)
--> 786 return torch._C._nn.log_softmax(input, dim)
787
788
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
Part of my code looks like this
class crossEntropy(nn.Module):
def __init__(self, weight = None, size_average = True):
super(crossEntropy, self).__init__()
self.crossEntropy_loss = nn.CrossEntropyLoss(weight, size_average)
def forward(self, logits, targets):
probs = F.sigmoid(logits)
probs_flat = probs.view(-1)
targets_flat = targets.view(-1)
return self.crossEntropy_loss(probs_flat, targets_flat)
class UNet(nn.Module):
def __init__(self, imsize):
super(UNet, self).__init__()
self.imsize = imsize
self.activation = F.relu
self.pool1 = nn.MaxPool2d(2)
self.pool2 = nn.MaxPool2d(2)
self.pool3 = nn.MaxPool2d(2)
self.pool4 = nn.MaxPool2d(2)
self.conv_block1_64 = UNetConvBlock(4, 64)
self.conv_block64_128 = UNetConvBlock(64, 128)
self.conv_block128_256 = UNetConvBlock(128, 256)
self.conv_block256_512 = UNetConvBlock(256, 512)
self.conv_block512_1024 = UNetConvBlock(512, 1024)
self.up_block1024_512 = UNetUpBlock(1024, 512)
self.up_block512_256 = UNetUpBlock(512, 256)
self.up_block256_128 = UNetUpBlock(256, 128)
self.up_block128_64 = UNetUpBlock(128, 64)
self.last = nn.Conv2d(64, 2, 1)
def forward(self, x):
block1 = self.conv_block1_64(x)
pool1 = self.pool1(block1)
block2 = self.conv_block64_128(pool1)
pool2 = self.pool2(block2)
block3 = self.conv_block128_256(pool2)
pool3 = self.pool3(block3)
block4 = self.conv_block256_512(pool3)
pool4 = self.pool4(block4)
block5 = self.conv_block512_1024(pool4)
up1 = self.up_block1024_512(block5, block4)
up2 = self.up_block512_256(up1, block3)
up3 = self.up_block256_128(up2, block2)
up4 = self.up_block128_64(up3, block1)
return F.log_softmax(self.last(up4))
A:
According to your code:
probs_flat = probs.view(-1)
targets_flat = targets.view(-1)
return self.crossEntropy_loss(probs_flat, targets_flat)
You are giving two 1d tensor to nn.CrossEntropyLoss but according to documentation, it expects:
Input: (N,C) where C = number of classes
Target: (N) where each value is 0 <= targets[i] <= C-1
Output: scalar. If reduce is False, then (N) instead.
I believe that is the cause of the problem you are encountering.
A:
The problem is that you are passing in bad arguments to torch.nn.CrossEntropyLoss in your classification problem.
Specifically, in this line
---> 18 loss = criterion(outputs, labels)
the argument labels is not what CrossEntropyLoss is expecting. labels should be a 1-D array. The length of this array should be the batch size that matches outputs in your code. The value of each element should be the 0-based target class ID.
Here's an example.
Suppose you have batch size B=2, and each data instance is given one of K=3 classes.
Further, suppose that the final layer of your neural network is outputting the following raw logits (the values before softmax) for each of the two instances in your batch. Those logits and the true label for each data instance are shown below.
Logits (before softmax)
Class 0 Class 1 Class 2 True class
------- ------- ------- ----------
Instance 0: 0.5 1.5 0.1 1
Instance 1: 2.2 1.3 1.7 2
Then in order to call CrossEntropyLoss correctly, you need two variables:
input of shape (B, K) containing the logit values
target of shape B containing the index of the true class
Here's how to correctly use CrossEntropyLoss with the values above. I am using torch.__version__ 1.9.0.
import torch
yhat = torch.Tensor([[0.5, 1.5, 0.1], [2.2, 1.3, 1.7]])
print(yhat)
# tensor([[0.5000, 1.5000, 0.1000],
# [2.2000, 1.3000, 1.7000]])
y = torch.Tensor([1, 2]).to(torch.long)
print(y)
# tensor([1, 2])
loss = torch.nn.CrossEntropyLoss()
cel = loss(input=yhat, target=y)
print(cel)
# tensor(0.8393)
I'm guessing that the error you received originally
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
probably occurred because you are trying to compute cross entropy loss for one data instance, where the target is encoded as one-hot. You probably had your data like this:
Logits (before softmax)
Class 0 Class 1 Class 2 True class 0 True class 1 True class 2
------- ------- ------- ------------ ------------ ------------
Instance 0: 0.5 1.5 0.1 0 1 0
Here's the code to represent the data above:
import torch
yhat = torch.Tensor([0.5, 1.5, 0.1])
print(yhat)
# tensor([0.5000, 1.5000, 0.1000])
y = torch.Tensor([0, 1, 0]).to(torch.long)
print(y)
# tensor([0, 1, 0])
loss = torch.nn.CrossEntropyLoss()
cel = loss(input=yhat, target=y)
print(cel)
At this point, I get the following error:
---> 10 cel = loss(input=yhat, target=y)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
That error message is incomprehensible and inactionable, in my opinion.
See also a similar problem but in TensorFlow:
What are logits? What is the difference between softmax and softmax_cross_entropy_with_logits?
A:
I had the same issue and since this thread doesn't provide any clear answer, i will post my solution despite the age of the post.
In the forward() method, you need to return x too.
It needs to look like so:
return F.log_softmax(self.last(up4)), x
A:
crossEntropy_loss function appears to be accepting a 2D array probably for a batch. In case of single input it should be (1,N) instead of only N elements 1D array.. so you should replace
return self.crossEntropy_loss(probs_flat, targets_flat)
with
return self.crossEntropy_loss(torch.unsqueeze(probs_flat,0), torch.unsqueeze(targets_flat,0))
|
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
|
Im using a Pytorch Unet model to which i am feeding in a image as input and along with that i am feeding the label as the input image mask and traning the dataset on it.
The Unet model i have picked up from somewhere else, and i am using the cross-entropy loss as a loss function but i get this dimension out of range error,
RuntimeError
Traceback (most recent call last)
<ipython-input-358-fa0ef49a43ae> in <module>()
16 for epoch in range(0, num_epochs):
17 # train for one epoch
---> 18 curr_loss = train(train_loader, model, criterion, epoch, num_epochs)
19
20 # store best loss and save a model checkpoint
<ipython-input-356-1bd6c6c281fb> in train(train_loader, model, criterion, epoch, num_epochs)
16 # measure loss
17 print (outputs.size(),labels.size())
---> 18 loss = criterion(outputs, labels)
19 losses.update(loss.data[0], images.size(0))
20
/usr/local/lib/python3.5/dist-packages/torch/nn/modules/module.py in _ _call__(self, *input, **kwargs)
323 for hook in self._forward_pre_hooks.values():
324 hook(self, input)
--> 325 result = self.forward(*input, **kwargs)
326 for hook in self._forward_hooks.values():
327 hook_result = hook(self, input, result)
<ipython-input-355-db66abcdb074> in forward(self, logits, targets)
9 probs_flat = probs.view(-1)
10 targets_flat = targets.view(-1)
---> 11 return self.crossEntropy_loss(probs_flat, targets_flat)
/usr/local/lib/python3.5/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
323 for hook in self._forward_pre_hooks.values():
324 hook(self, input)
--> 325 result = self.forward(*input, **kwargs)
326 for hook in self._forward_hooks.values():
327 hook_result = hook(self, input, result)
/usr/local/lib/python3.5/dist-packages/torch/nn/modules/loss.py in f orward(self, input, target)
599 _assert_no_grad(target)
600 return F.cross_entropy(input, target, self.weight, self.size_average,
--> 601 self.ignore_index, self.reduce)
602
603
/usr/local/lib/python3.5/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce)
1138 >>> loss.backward()
1139 """
-> 1140 return nll_loss(log_softmax(input, 1), target, weight, size_average, ignore_index, reduce)
1141
1142
/usr/local/lib/python3.5/dist-packages/torch/nn/functional.py in log_softmax(input, dim, _stacklevel)
784 if dim is None:
785 dim = _get_softmax_dim('log_softmax', input.dim(), _stacklevel)
--> 786 return torch._C._nn.log_softmax(input, dim)
787
788
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
Part of my code looks like this
class crossEntropy(nn.Module):
def __init__(self, weight = None, size_average = True):
super(crossEntropy, self).__init__()
self.crossEntropy_loss = nn.CrossEntropyLoss(weight, size_average)
def forward(self, logits, targets):
probs = F.sigmoid(logits)
probs_flat = probs.view(-1)
targets_flat = targets.view(-1)
return self.crossEntropy_loss(probs_flat, targets_flat)
class UNet(nn.Module):
def __init__(self, imsize):
super(UNet, self).__init__()
self.imsize = imsize
self.activation = F.relu
self.pool1 = nn.MaxPool2d(2)
self.pool2 = nn.MaxPool2d(2)
self.pool3 = nn.MaxPool2d(2)
self.pool4 = nn.MaxPool2d(2)
self.conv_block1_64 = UNetConvBlock(4, 64)
self.conv_block64_128 = UNetConvBlock(64, 128)
self.conv_block128_256 = UNetConvBlock(128, 256)
self.conv_block256_512 = UNetConvBlock(256, 512)
self.conv_block512_1024 = UNetConvBlock(512, 1024)
self.up_block1024_512 = UNetUpBlock(1024, 512)
self.up_block512_256 = UNetUpBlock(512, 256)
self.up_block256_128 = UNetUpBlock(256, 128)
self.up_block128_64 = UNetUpBlock(128, 64)
self.last = nn.Conv2d(64, 2, 1)
def forward(self, x):
block1 = self.conv_block1_64(x)
pool1 = self.pool1(block1)
block2 = self.conv_block64_128(pool1)
pool2 = self.pool2(block2)
block3 = self.conv_block128_256(pool2)
pool3 = self.pool3(block3)
block4 = self.conv_block256_512(pool3)
pool4 = self.pool4(block4)
block5 = self.conv_block512_1024(pool4)
up1 = self.up_block1024_512(block5, block4)
up2 = self.up_block512_256(up1, block3)
up3 = self.up_block256_128(up2, block2)
up4 = self.up_block128_64(up3, block1)
return F.log_softmax(self.last(up4))
|
[
"According to your code:\nprobs_flat = probs.view(-1)\ntargets_flat = targets.view(-1)\nreturn self.crossEntropy_loss(probs_flat, targets_flat)\n\nYou are giving two 1d tensor to nn.CrossEntropyLoss but according to documentation, it expects:\nInput: (N,C) where C = number of classes\nTarget: (N) where each value is 0 <= targets[i] <= C-1\nOutput: scalar. If reduce is False, then (N) instead.\n\nI believe that is the cause of the problem you are encountering.\n",
"The problem is that you are passing in bad arguments to torch.nn.CrossEntropyLoss in your classification problem.\nSpecifically, in this line\n---> 18 loss = criterion(outputs, labels)\n\nthe argument labels is not what CrossEntropyLoss is expecting. labels should be a 1-D array. The length of this array should be the batch size that matches outputs in your code. The value of each element should be the 0-based target class ID.\nHere's an example.\nSuppose you have batch size B=2, and each data instance is given one of K=3 classes.\nFurther, suppose that the final layer of your neural network is outputting the following raw logits (the values before softmax) for each of the two instances in your batch. Those logits and the true label for each data instance are shown below.\n Logits (before softmax)\n Class 0 Class 1 Class 2 True class\n ------- ------- ------- ----------\nInstance 0: 0.5 1.5 0.1 1\nInstance 1: 2.2 1.3 1.7 2\n\nThen in order to call CrossEntropyLoss correctly, you need two variables:\n\ninput of shape (B, K) containing the logit values\ntarget of shape B containing the index of the true class\n\nHere's how to correctly use CrossEntropyLoss with the values above. I am using torch.__version__ 1.9.0.\nimport torch\n\nyhat = torch.Tensor([[0.5, 1.5, 0.1], [2.2, 1.3, 1.7]])\nprint(yhat)\n# tensor([[0.5000, 1.5000, 0.1000],\n# [2.2000, 1.3000, 1.7000]])\n\ny = torch.Tensor([1, 2]).to(torch.long)\nprint(y)\n# tensor([1, 2])\n\nloss = torch.nn.CrossEntropyLoss()\ncel = loss(input=yhat, target=y)\nprint(cel)\n# tensor(0.8393)\n\nI'm guessing that the error you received originally\nRuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)\n\nprobably occurred because you are trying to compute cross entropy loss for one data instance, where the target is encoded as one-hot. You probably had your data like this:\n Logits (before softmax)\n Class 0 Class 1 Class 2 True class 0 True class 1 True class 2\n ------- ------- ------- ------------ ------------ ------------\nInstance 0: 0.5 1.5 0.1 0 1 0\n\nHere's the code to represent the data above:\nimport torch\n\nyhat = torch.Tensor([0.5, 1.5, 0.1])\nprint(yhat)\n# tensor([0.5000, 1.5000, 0.1000])\n\ny = torch.Tensor([0, 1, 0]).to(torch.long)\nprint(y)\n# tensor([0, 1, 0])\n\nloss = torch.nn.CrossEntropyLoss()\ncel = loss(input=yhat, target=y)\nprint(cel)\n\nAt this point, I get the following error:\n---> 10 cel = loss(input=yhat, target=y)\n\nIndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)\n\nThat error message is incomprehensible and inactionable, in my opinion.\nSee also a similar problem but in TensorFlow:\nWhat are logits? What is the difference between softmax and softmax_cross_entropy_with_logits?\n",
"I had the same issue and since this thread doesn't provide any clear answer, i will post my solution despite the age of the post.\nIn the forward() method, you need to return x too.\nIt needs to look like so:\nreturn F.log_softmax(self.last(up4)), x\n\n",
"crossEntropy_loss function appears to be accepting a 2D array probably for a batch. In case of single input it should be (1,N) instead of only N elements 1D array.. so you should replace\nreturn self.crossEntropy_loss(probs_flat, targets_flat)\n\nwith\nreturn self.crossEntropy_loss(torch.unsqueeze(probs_flat,0), torch.unsqueeze(targets_flat,0))\n\n"
] |
[
34,
12,
0,
0
] |
[] |
[] |
[
"machine_learning",
"python",
"pytorch"
] |
stackoverflow_0048377214_machine_learning_python_pytorch.txt
|
Q:
How can I reset password in django by sending code to the user?
How can I implement password reset in django, in a safe and secure way by sending a code to the user's email/phone?
I emphasise that I want to do this by sending a code to the user, not a link or anything else.
Something like what microsoft or google accounts does.
I've searched a lot for this problem but I've never found a proper solution.
A:
I'm not really sure, but I think you can do it with django-phone-verify
The example on the website is about first authenticating, but modules API can be reused/extended.
|
How can I reset password in django by sending code to the user?
|
How can I implement password reset in django, in a safe and secure way by sending a code to the user's email/phone?
I emphasise that I want to do this by sending a code to the user, not a link or anything else.
Something like what microsoft or google accounts does.
I've searched a lot for this problem but I've never found a proper solution.
|
[
"I'm not really sure, but I think you can do it with django-phone-verify\nThe example on the website is about first authenticating, but modules API can be reused/extended.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_rest_framework",
"python"
] |
stackoverflow_0074549054_django_django_rest_framework_python.txt
|
Q:
Getting missing positional parameter errors when using scipy odeint
I am attempting to code a basic gravitational 2 body problem (2 bodies of equal mass), by using scipy odeint to solve the differential equations. Code below
#N Body test case
#%%
#import modules
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
#%%
#define constants
G=6.67e-11
AU=1.496e11
m1= m2=1.989e30
def twobody(x1, y1, vx1, vy1, x2, y2, vx2, vy2):
rx=x1-x2
ry=y1-y2
r=np.sqrt(rx**2+ry**2)
f=[vx1, vy1, vx2, vy2, G*m2*rx/r**3, G*m2*ry/r**3, G*m1*rx/r**3, G*m2*ry/r**3]
return f
t=np.linspace(0, 1.577e8, 2000)
initial=[-0.5*AU, -0.5*AU, 0,0,0,0,-15000, 15000]
twobodysol=odeint(twobody, initial, t, args=(m1, m2))
I keep getting an error:
twobody() missing 4 required positional arguments: 'x2', 'y2', 'vx2', and 'vy2'
Can anyone help with what I've done wrong here?
Many thanks
A:
Firstly odeint is old, SciPy recommends using solve_ivp(). Your function should look something like func(y, t, ...) where y is the initial condition array, and t is an array containing time points to calculate. All the other parameters you have to provide yourself through the args parameter of odeint(). With what you've supplied to odeint your function looks like this when it is called :
twobody(initial, t, m1, m2). Whereas you want it to look like this :
twobody(x1, y1, vx1, vy1, x2, y2, vx2, vy2).
I recommend you look into solve_ivp().
|
Getting missing positional parameter errors when using scipy odeint
|
I am attempting to code a basic gravitational 2 body problem (2 bodies of equal mass), by using scipy odeint to solve the differential equations. Code below
#N Body test case
#%%
#import modules
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
#%%
#define constants
G=6.67e-11
AU=1.496e11
m1= m2=1.989e30
def twobody(x1, y1, vx1, vy1, x2, y2, vx2, vy2):
rx=x1-x2
ry=y1-y2
r=np.sqrt(rx**2+ry**2)
f=[vx1, vy1, vx2, vy2, G*m2*rx/r**3, G*m2*ry/r**3, G*m1*rx/r**3, G*m2*ry/r**3]
return f
t=np.linspace(0, 1.577e8, 2000)
initial=[-0.5*AU, -0.5*AU, 0,0,0,0,-15000, 15000]
twobodysol=odeint(twobody, initial, t, args=(m1, m2))
I keep getting an error:
twobody() missing 4 required positional arguments: 'x2', 'y2', 'vx2', and 'vy2'
Can anyone help with what I've done wrong here?
Many thanks
|
[
"Firstly odeint is old, SciPy recommends using solve_ivp(). Your function should look something like func(y, t, ...) where y is the initial condition array, and t is an array containing time points to calculate. All the other parameters you have to provide yourself through the args parameter of odeint(). With what you've supplied to odeint your function looks like this when it is called :\ntwobody(initial, t, m1, m2). Whereas you want it to look like this :\ntwobody(x1, y1, vx1, vy1, x2, y2, vx2, vy2).\n I recommend you look into solve_ivp().\n"
] |
[
0
] |
[] |
[] |
[
"numpy",
"python",
"scipy"
] |
stackoverflow_0074553893_numpy_python_scipy.txt
|
Q:
Auto expand table range in excel
Tying to find to an Excel VBA equivalent to
sheet.range('A1').expand('table')
#https://docs.xlwings.org/en/stable/datastructures.html
I've tried to create a xlwings func like this :
@xw.func
def expand(rng, caller):
sht = caller.sheet
return sht.range(rng).expand().address
=expand("C7") returns "$C$7:$E$8" (works)
So I've tried for feed this rng as string inside the following macro (that spots changes within a range)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng_s As String
rng_s = expand("C7") #This is where there is the error
Set rng = Target.Worksheet.Range(rng_s)
If Not Intersect(Target, rng) Is Nothing Then my_macro2 (rng)
End Sub
#The Python console returns : TypeError: The Python instance can not be converted to a COM object
Any idea how to make this table expand automatically? Or make this xlwings function work?
A:
You need to call the function directly instead of using xlwings way as they need to correct the code in order to support calling from another function/sub.
Use this in your function instead of calling expand
rng_s = Py.CallUDF("udftest", "expand", Array("C7", Nothing), ThisWorkbook, ThisWorkbook.ActiveSheet.Range("C7"))
Change ThisWorkbook.ActiveSheet for the Sheet where the range you are looking for belongs, that last parameter is passed as the caller in the defined python function, so even you could use only that parameter do get the desired range in your expand function.
|
Auto expand table range in excel
|
Tying to find to an Excel VBA equivalent to
sheet.range('A1').expand('table')
#https://docs.xlwings.org/en/stable/datastructures.html
I've tried to create a xlwings func like this :
@xw.func
def expand(rng, caller):
sht = caller.sheet
return sht.range(rng).expand().address
=expand("C7") returns "$C$7:$E$8" (works)
So I've tried for feed this rng as string inside the following macro (that spots changes within a range)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng_s As String
rng_s = expand("C7") #This is where there is the error
Set rng = Target.Worksheet.Range(rng_s)
If Not Intersect(Target, rng) Is Nothing Then my_macro2 (rng)
End Sub
#The Python console returns : TypeError: The Python instance can not be converted to a COM object
Any idea how to make this table expand automatically? Or make this xlwings function work?
|
[
"You need to call the function directly instead of using xlwings way as they need to correct the code in order to support calling from another function/sub.\nUse this in your function instead of calling expand\n rng_s = Py.CallUDF(\"udftest\", \"expand\", Array(\"C7\", Nothing), ThisWorkbook, ThisWorkbook.ActiveSheet.Range(\"C7\"))\n\nChange ThisWorkbook.ActiveSheet for the Sheet where the range you are looking for belongs, that last parameter is passed as the caller in the defined python function, so even you could use only that parameter do get the desired range in your expand function.\n"
] |
[
0
] |
[] |
[] |
[
"excel",
"python",
"vba",
"xlwings"
] |
stackoverflow_0073940796_excel_python_vba_xlwings.txt
|
Q:
Is there a more efficient way to represent my string containing image pixel data as an image mask?
I'm representing image pixel data as a string.
For example, let's say an image is 2x2 pixels, the string would be 4 characters long since we have 4 pixels.
So if the string is 0100 (where 1 is a white pixel), what I basically want to achieve is to create an image mask from this string.
NOTE: I do not have to use 1's and 0's as representation for my pixels. This is just for use as an example. It could be x and y or any other combination of characters, but the string will only contain two distinct characters. For example, I could have 'bwwb' where b represents a black pixel and w is a white pixel.
The data being a string is also just the way that it is being received as input to python. I am allowed to convert it into a numpy array or other formats.
With the order that the pixel data in my string is stored, bwwb would look like this if represented as a matrix:
w b
b w
Similarly for a 3x3 image with string 'wbbbwbwbw', the image matrix would look like this:
w b w
b w b
w b b
I am currently using this method to generate the image mask:
mask = np.zeros((height,width,3), dtype=np.uint8)
for ph in range(height):
for pw in range(width):
index = ph + pw
pixel_value = pixel_string[index]
if pixel_value == 'w':
mask[ph,pw] = 255
Using nested loops is too slow for my needs however. I was wondering if there are more efficient ways to achieve this, maybe in numpy or cv2?
A:
To answer the your question of the comments
a = "0 1 1 0"
b = np.fromstring(a, dtype=int, sep=" ")
b.reshape(int(len(b)/2), int(len(b)/2))
something like this e.g --> results in:
array([[0, 1], [1, 0]])
|
Is there a more efficient way to represent my string containing image pixel data as an image mask?
|
I'm representing image pixel data as a string.
For example, let's say an image is 2x2 pixels, the string would be 4 characters long since we have 4 pixels.
So if the string is 0100 (where 1 is a white pixel), what I basically want to achieve is to create an image mask from this string.
NOTE: I do not have to use 1's and 0's as representation for my pixels. This is just for use as an example. It could be x and y or any other combination of characters, but the string will only contain two distinct characters. For example, I could have 'bwwb' where b represents a black pixel and w is a white pixel.
The data being a string is also just the way that it is being received as input to python. I am allowed to convert it into a numpy array or other formats.
With the order that the pixel data in my string is stored, bwwb would look like this if represented as a matrix:
w b
b w
Similarly for a 3x3 image with string 'wbbbwbwbw', the image matrix would look like this:
w b w
b w b
w b b
I am currently using this method to generate the image mask:
mask = np.zeros((height,width,3), dtype=np.uint8)
for ph in range(height):
for pw in range(width):
index = ph + pw
pixel_value = pixel_string[index]
if pixel_value == 'w':
mask[ph,pw] = 255
Using nested loops is too slow for my needs however. I was wondering if there are more efficient ways to achieve this, maybe in numpy or cv2?
|
[
"To answer the your question of the comments\na = \"0 1 1 0\"\nb = np.fromstring(a, dtype=int, sep=\" \")\nb.reshape(int(len(b)/2), int(len(b)/2))\n\nsomething like this e.g --> results in:\narray([[0, 1], [1, 0]]) \n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074554083_python.txt
|
Q:
Python Data Structure to pop anywhere and push to the end in O(1)
I was wondering,
is there any python data structure to pop from anywhere (using an object), remove from the front and push to the back in O(1)?
To prove its even possible lets look at the next data structure that can be implemented in C:
(Notice all the pointers are 2 way)
Thus we can:
pop(object) - lookup the object at the hashtable O(1) on average, remove it from the doubly linked list in O(1), and remove it from the hashtable in O(1).
popFront() - look at the front of the list in O(1), remove it from the hashtable in O(1), remove it from the doubly linked list in O(1).
PushBack() - add the item to the back of the doubly linked list O(1), add the item to the hashtable O(1) on average.
|
Python Data Structure to pop anywhere and push to the end in O(1)
|
I was wondering,
is there any python data structure to pop from anywhere (using an object), remove from the front and push to the back in O(1)?
To prove its even possible lets look at the next data structure that can be implemented in C:
(Notice all the pointers are 2 way)
Thus we can:
pop(object) - lookup the object at the hashtable O(1) on average, remove it from the doubly linked list in O(1), and remove it from the hashtable in O(1).
popFront() - look at the front of the list in O(1), remove it from the hashtable in O(1), remove it from the doubly linked list in O(1).
PushBack() - add the item to the back of the doubly linked list O(1), add the item to the hashtable O(1) on average.
|
[] |
[] |
[
"Thanks to the comments.\nJust use a regular dict.\nPython dicts keep the order of insertion so:\npop(object) - del dict[Int]\n\npopFront - dict.pop(next(iter(dict.items())))\n\nPushBack - dict[Int] = Object\n\n"
] |
[
-1
] |
[
"data_structures",
"python"
] |
stackoverflow_0074554058_data_structures_python.txt
|
Q:
Registration form is not submitting
After trying multiple solutions from other stack overflows, I cannot seem to get my registration form to work in Django.
This is the registration form
<h1>Register</h1>
<div>
<form method="POST" action="{% url 'register' %}"></form>
{% csrf_token %}
{{ form.as_p}}
<input type="submit" value="register" />
</div>
Below is the views.py
`
def register_page(request):
form = CustomUserCreateForm()
if request.method == 'POST':
form = CustomUserCreateForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
login(request, user)
return redirect('login')
page = 'register'
context={'page':page, 'form':form}
return render(request, 'login_register.html', context)
`
The forms.py
`
class CustomUserCreateForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'name', 'password1', 'password2']
`
Its not throwing any error, rather just not submitting. I tried changing the input to button feature but it is still not working. Any Ideas?
A:
I think saving the form instance doesn't actually make user an authenticatable User object
Try this
if form.is_valid():
#You are not doing anything to user, so no need to commit=False
#user = form.save(commit=False)
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
#Make sure user is an authenticated user object
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
#Handle no user as appropriate eg,
#else:
# messages.error(request,'Well that didn't work')
|
Registration form is not submitting
|
After trying multiple solutions from other stack overflows, I cannot seem to get my registration form to work in Django.
This is the registration form
<h1>Register</h1>
<div>
<form method="POST" action="{% url 'register' %}"></form>
{% csrf_token %}
{{ form.as_p}}
<input type="submit" value="register" />
</div>
Below is the views.py
`
def register_page(request):
form = CustomUserCreateForm()
if request.method == 'POST':
form = CustomUserCreateForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
login(request, user)
return redirect('login')
page = 'register'
context={'page':page, 'form':form}
return render(request, 'login_register.html', context)
`
The forms.py
`
class CustomUserCreateForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'name', 'password1', 'password2']
`
Its not throwing any error, rather just not submitting. I tried changing the input to button feature but it is still not working. Any Ideas?
|
[
"I think saving the form instance doesn't actually make user an authenticatable User object\nTry this\n if form.is_valid():\n #You are not doing anything to user, so no need to commit=False\n #user = form.save(commit=False)\n form.save()\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password1')\n #Make sure user is an authenticated user object\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n #Handle no user as appropriate eg,\n #else:\n # messages.error(request,'Well that didn't work')\n\n"
] |
[
0
] |
[] |
[] |
[
"css",
"django",
"forms",
"html",
"python"
] |
stackoverflow_0074553017_css_django_forms_html_python.txt
|
Q:
Python and Beautiful Soup nested values
I have the following html:
<label class="cOpt" for="prod_1234_rMon_3"> <span>12 M <span>+300 €</span></span> </label>
How can I get the 12 M and +300 €?
Edit:
So I tried this to get alle the data I need, but find just picks the first value.
vObj_detail = bsObj.find('label', attrs={'class': 'cOpt'}).get_text(strip=True).split("+")
The original source looks like this, so there are more then one.
[<label class="cOpt" for="prod_1234_rMon_0">
<span>6 M</span>
</label>
<label class="cOpt" for="prod_1234_rMon_1">
<span>24 M
<span>+150 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rMon_2">
<span>18 M
<span>
+200 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rMon_3">
<span>12 M
<span>+300 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rRen_0">
<span>1.250 km
</span>
</label>
<label class="cOpt" for="prod_1234_rRen_1">
<span>1.750 km
<span>+100 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rRen_2">
<span>2.000 km
<span>+150 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rRen_3">
<span>2.500 km
<span>+250 €
</span>
</span>
</label>]
Thanks,
Sven
Getting 12 M and 300
A:
You can use .get_text() with separator= and then str.split:
from bs4 import BeautifulSoup
html_doc = """\
<label class="cOpt" for="prod_1234_rMon_3"> <span>12 M <span>+300 €</span></span> </label>"""
soup = BeautifulSoup(html_doc, "html.parser")
a, b = soup.find("span").get_text(strip=True, separator="|").split("|")
print(a)
print(b)
Prints:
12 M
+300 €
Or: use .find and .find_next:
a = soup.find("span").find(text=True)
b = a.find_next(text=True)
print(a)
print(b)
Prints:
12 M
+300 €
|
Python and Beautiful Soup nested values
|
I have the following html:
<label class="cOpt" for="prod_1234_rMon_3"> <span>12 M <span>+300 €</span></span> </label>
How can I get the 12 M and +300 €?
Edit:
So I tried this to get alle the data I need, but find just picks the first value.
vObj_detail = bsObj.find('label', attrs={'class': 'cOpt'}).get_text(strip=True).split("+")
The original source looks like this, so there are more then one.
[<label class="cOpt" for="prod_1234_rMon_0">
<span>6 M</span>
</label>
<label class="cOpt" for="prod_1234_rMon_1">
<span>24 M
<span>+150 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rMon_2">
<span>18 M
<span>
+200 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rMon_3">
<span>12 M
<span>+300 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rRen_0">
<span>1.250 km
</span>
</label>
<label class="cOpt" for="prod_1234_rRen_1">
<span>1.750 km
<span>+100 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rRen_2">
<span>2.000 km
<span>+150 €
</span>
</span>
</label>
<label class="cOpt" for="prod_1234_rRen_3">
<span>2.500 km
<span>+250 €
</span>
</span>
</label>]
Thanks,
Sven
Getting 12 M and 300
|
[
"You can use .get_text() with separator= and then str.split:\nfrom bs4 import BeautifulSoup\n\n\nhtml_doc = \"\"\"\\\n<label class=\"cOpt\" for=\"prod_1234_rMon_3\"> <span>12 M <span>+300 €</span></span> </label>\"\"\"\n\nsoup = BeautifulSoup(html_doc, \"html.parser\")\n\na, b = soup.find(\"span\").get_text(strip=True, separator=\"|\").split(\"|\")\nprint(a)\nprint(b)\n\nPrints:\n12 M\n+300 €\n\n\nOr: use .find and .find_next:\na = soup.find(\"span\").find(text=True)\nb = a.find_next(text=True)\nprint(a)\nprint(b)\n\nPrints:\n12 M \n+300 €\n\n"
] |
[
0
] |
[] |
[] |
[
"beautifulsoup",
"html",
"python",
"web_scraping"
] |
stackoverflow_0074554264_beautifulsoup_html_python_web_scraping.txt
|
Q:
How to Shorten a lot of Repetition
I am trying to make a game of Tic Tac Toe, and I ran into this problem.
I have to store a lot of different variables with very similar characters.
Currently, I have a solution, but it seems ineffective. I am trying to find a quicker and easier way of accomplishing the same task.
Below is a solution I currently have, but it seems like there is a lot of wasted space.
p1 = playerX.count(1)
p2 = playerX.count(2)
p3 = playerX.count(3)
p4 = playerX.count(4)
p5 = playerX.count(5)
p6 = playerX.count(6)
p7 = playerX.count(7)
p8 = playerX.count(8)
p9 = playerX.count(9)
c1 = computerO.count(1)
c2 = computerO.count(2)
c3 = computerO.count(3)
c4 = computerO.count(4)
c5 = computerO.count(5)
c6 = computerO.count(6)
c7 = computerO.count(7)
c8 = computerO.count(8)
c9 = computerO.count(9)
# Player Win options
if (p1 and p2 and p3 ) or (p1 and p4 and p7 ) or (p1 and p5 and p9 ) or (p2 and p5 and p8) or (p3 ==1 and p5 and p7 ) or (p3 and p6 and p9 ) or (p4 and p5 and p6) or (p7 and p8 and p9):
winner = 1
# AI Win options
elif (c1 and c2 and c3 ) or (c1 and c4 and c7 ) or (c1 and c5 and c9 ) or (c2 and c5 and c8) or (c3 ==1 and c5 and c7 ) or (c3 and c6 and c9 ) or (c4 and c5 and c6) or (c7 and c8 and c9):
winner = 2
if winner == 1 or winner == 2:
break
This basically checks all 8 ways of winning the game for the player and AI.
It works, but I am trying to find a way to shorted the assigning of variables.
A way I was thinking of doing this was by using a 'for loop'. But I am unsure how to make one that will accommodate it.
p = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
c = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
for i in p:
p[i] = playerX.count(i)
c[i] = computerO.count[i]
A:
Perhaps something like this:
c = []
p = []
for x in range(1,10):
c.append(PlayerX.count(x))
p.append(computer0.count(x))
|
How to Shorten a lot of Repetition
|
I am trying to make a game of Tic Tac Toe, and I ran into this problem.
I have to store a lot of different variables with very similar characters.
Currently, I have a solution, but it seems ineffective. I am trying to find a quicker and easier way of accomplishing the same task.
Below is a solution I currently have, but it seems like there is a lot of wasted space.
p1 = playerX.count(1)
p2 = playerX.count(2)
p3 = playerX.count(3)
p4 = playerX.count(4)
p5 = playerX.count(5)
p6 = playerX.count(6)
p7 = playerX.count(7)
p8 = playerX.count(8)
p9 = playerX.count(9)
c1 = computerO.count(1)
c2 = computerO.count(2)
c3 = computerO.count(3)
c4 = computerO.count(4)
c5 = computerO.count(5)
c6 = computerO.count(6)
c7 = computerO.count(7)
c8 = computerO.count(8)
c9 = computerO.count(9)
# Player Win options
if (p1 and p2 and p3 ) or (p1 and p4 and p7 ) or (p1 and p5 and p9 ) or (p2 and p5 and p8) or (p3 ==1 and p5 and p7 ) or (p3 and p6 and p9 ) or (p4 and p5 and p6) or (p7 and p8 and p9):
winner = 1
# AI Win options
elif (c1 and c2 and c3 ) or (c1 and c4 and c7 ) or (c1 and c5 and c9 ) or (c2 and c5 and c8) or (c3 ==1 and c5 and c7 ) or (c3 and c6 and c9 ) or (c4 and c5 and c6) or (c7 and c8 and c9):
winner = 2
if winner == 1 or winner == 2:
break
This basically checks all 8 ways of winning the game for the player and AI.
It works, but I am trying to find a way to shorted the assigning of variables.
A way I was thinking of doing this was by using a 'for loop'. But I am unsure how to make one that will accommodate it.
p = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
c = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
for i in p:
p[i] = playerX.count(i)
c[i] = computerO.count[i]
|
[
"Perhaps something like this:\nc = []\np = []\nfor x in range(1,10):\n c.append(PlayerX.count(x))\n p.append(computer0.count(x))\n\n"
] |
[
0
] |
[] |
[] |
[
"count",
"for_loop",
"list",
"python"
] |
stackoverflow_0074554335_count_for_loop_list_python.txt
|
Q:
Linear Regression without Sklearn
I am trying to write a class LinearModel, representing a linear regression model. it gives an error for def predict
class LinearModel:
def __init__(self, X, y):
self.X = X
self.y = y
#X columns of 1s appended on its left,
X = np.vstack((np.ones((X.shape[0], )), X.T)).T
if len(self.X)!=len(y):
raise ("they are not similar")
def fit(self):
# stores this coefficient vector in the object.
Xt = np.transpose(X)
XtX = np.dot(Xt,X)
Xty = np.dot(Xt,y)
beta = np.linalg.solve(XtX,Xty)
self.fit = beta
def coef(self):
# raise an error if called before the model has been fitted
if not self.fit:
raise ValueError("Need to call the fit function first")
#returns βˆ.
return self.fit
def predict(self,X0=None): # Takes an optional argument X0
if not self.fit:
raise ValueError("Need to call the fit function first")
if X0==None:
X0 = X
X0 = np.vstack((np.ones((X0.shape[0], )), X0.T)).T
# where X0 is X0 with column of 1s added on its left.
prediction = self.fit * X0 # method should return X0 * βˆ
return prediction
X = np.array([[-1.34164079, -1.25675744], [-0.4472136, -0.48336824],
[0.4472136, 0.29002095], [1.34164079, 1.45010473]])
y = np.array([1, 3, 4, 6])
model = LinearModel(X, y)
model.fit()
print(model.coef())
print(model.predict())
edits
class LinearModel:
def __init__(self, X, y):
self.X = X
self.y = y
#X columns of 1s appended on its left,
X = np.vstack((np.ones((X.shape[0], )), X.T)).T
if len(self.X)!=len(y):
raise ("they are not similar")
self._is_fitted : bool = False
def fit(self):
Xt = np.transpose(X)
XtX = np.dot(Xt,X)
Xty = np.dot(Xt,y)
beta = np.linalg.solve(XtX,Xty)
beta_array = np.array(beta)
self.fit = beta_array
self._is_fitted = True
def coef(self):
# raise an error if called before the model has been fitted
if not self._is_fitted:
raise ValueError("Need to call the fit function first")
#returns βˆ
return self.fit
def predict(self,X0=None): # Takes an optional argument X0
if not self._is_fitted:
raise ValueError("Need to call the fit function first")
if X0==None:
X0 = X
X0 = np.vstack((np.ones((X0.shape[0], )), X0.T)).T
# where X0 is X0 with column of 1s added on its left.
prediction = np.multiply(X0, self.fit) # method should return X0 * βˆ
return prediction
X = np.array([[-1.34164079, -1.25675744], [-0.4472136, -0.48336824],
[0.4472136, 0.29002095], [1.34164079, 1.45010473]])
y = np.array([1, 3, 4, 6])
model = LinearModel(X, y)
model.fit()
print(model.coef())
print(model.predict())
it gives an error of ValueError: operands could not be broadcast together with shapes (4,3) (2,) meaning that I will have to to broadcasting to multiply 2 matrices. Can anymore suggest me how?
A:
You can't use a method name as an attribute. Is self.fit supposed to be a method to fit? Or the coefficients?
You can't test if that attribute (let's call it beta) is assigned simply by saying if self.beta or something similar. First of all, if it is not, you'll get an error for trying to read an unassigned variable. Secondly, and that is the error you get, if that beta contains something that is neither True nor False, you'll get an error about Truth value. So, assign a value to beta in the __init__ method. For example self.beta=None. And then test if it is None with if beta is None.
All attributes access must be prefixed with self.. You are using X instead of self.X more than once. Which means that those X are the global one. The one to which you haven't added a column of 1.
self.beta * X0 is not doing what you expect to do. * is a member×member multiplication, not a matrix multiplication (and if it were a matrix multiplication it would be an illegal one). @ (or .dot) is the matrix multiplication operator. And to multiply a 3×n matrix by a 3 elements vector, you need to do it the other way. So X0 @ self.beta
[Non fatal] There is a np.hstack function, rather than vstack + double transpose.
|
Linear Regression without Sklearn
|
I am trying to write a class LinearModel, representing a linear regression model. it gives an error for def predict
class LinearModel:
def __init__(self, X, y):
self.X = X
self.y = y
#X columns of 1s appended on its left,
X = np.vstack((np.ones((X.shape[0], )), X.T)).T
if len(self.X)!=len(y):
raise ("they are not similar")
def fit(self):
# stores this coefficient vector in the object.
Xt = np.transpose(X)
XtX = np.dot(Xt,X)
Xty = np.dot(Xt,y)
beta = np.linalg.solve(XtX,Xty)
self.fit = beta
def coef(self):
# raise an error if called before the model has been fitted
if not self.fit:
raise ValueError("Need to call the fit function first")
#returns βˆ.
return self.fit
def predict(self,X0=None): # Takes an optional argument X0
if not self.fit:
raise ValueError("Need to call the fit function first")
if X0==None:
X0 = X
X0 = np.vstack((np.ones((X0.shape[0], )), X0.T)).T
# where X0 is X0 with column of 1s added on its left.
prediction = self.fit * X0 # method should return X0 * βˆ
return prediction
X = np.array([[-1.34164079, -1.25675744], [-0.4472136, -0.48336824],
[0.4472136, 0.29002095], [1.34164079, 1.45010473]])
y = np.array([1, 3, 4, 6])
model = LinearModel(X, y)
model.fit()
print(model.coef())
print(model.predict())
edits
class LinearModel:
def __init__(self, X, y):
self.X = X
self.y = y
#X columns of 1s appended on its left,
X = np.vstack((np.ones((X.shape[0], )), X.T)).T
if len(self.X)!=len(y):
raise ("they are not similar")
self._is_fitted : bool = False
def fit(self):
Xt = np.transpose(X)
XtX = np.dot(Xt,X)
Xty = np.dot(Xt,y)
beta = np.linalg.solve(XtX,Xty)
beta_array = np.array(beta)
self.fit = beta_array
self._is_fitted = True
def coef(self):
# raise an error if called before the model has been fitted
if not self._is_fitted:
raise ValueError("Need to call the fit function first")
#returns βˆ
return self.fit
def predict(self,X0=None): # Takes an optional argument X0
if not self._is_fitted:
raise ValueError("Need to call the fit function first")
if X0==None:
X0 = X
X0 = np.vstack((np.ones((X0.shape[0], )), X0.T)).T
# where X0 is X0 with column of 1s added on its left.
prediction = np.multiply(X0, self.fit) # method should return X0 * βˆ
return prediction
X = np.array([[-1.34164079, -1.25675744], [-0.4472136, -0.48336824],
[0.4472136, 0.29002095], [1.34164079, 1.45010473]])
y = np.array([1, 3, 4, 6])
model = LinearModel(X, y)
model.fit()
print(model.coef())
print(model.predict())
it gives an error of ValueError: operands could not be broadcast together with shapes (4,3) (2,) meaning that I will have to to broadcasting to multiply 2 matrices. Can anymore suggest me how?
|
[
"\nYou can't use a method name as an attribute. Is self.fit supposed to be a method to fit? Or the coefficients?\n\nYou can't test if that attribute (let's call it beta) is assigned simply by saying if self.beta or something similar. First of all, if it is not, you'll get an error for trying to read an unassigned variable. Secondly, and that is the error you get, if that beta contains something that is neither True nor False, you'll get an error about Truth value. So, assign a value to beta in the __init__ method. For example self.beta=None. And then test if it is None with if beta is None.\n\nAll attributes access must be prefixed with self.. You are using X instead of self.X more than once. Which means that those X are the global one. The one to which you haven't added a column of 1.\n\nself.beta * X0 is not doing what you expect to do. * is a member×member multiplication, not a matrix multiplication (and if it were a matrix multiplication it would be an illegal one). @ (or .dot) is the matrix multiplication operator. And to multiply a 3×n matrix by a 3 elements vector, you need to do it the other way. So X0 @ self.beta\n\n[Non fatal] There is a np.hstack function, rather than vstack + double transpose.\n\n\n"
] |
[
2
] |
[] |
[] |
[
"linear_regression",
"numpy",
"python"
] |
stackoverflow_0074554177_linear_regression_numpy_python.txt
|
Q:
How to read a parquet file into a PCollection from s3?
My problem is simple: I want to read a parquet file from s3 into a PCollection in Apache Beam using the Python Sdk.
I know of the apache_beam.io.parquetio module but this one does not seem to be able to read from s3 directly (or does it?).
I know of the apache_beam.io.aws.s3io module but this one seems to return an s3 file object or something that is not a PCollection anyway (or does it?).
So what’s the best way to do this?
A:
if you install beam with the aws requirement
pip install 'apache-beam[aws]'
You can just pass in an s3 filename to read from it
filename = "s3://bucket-name/...
beam.io.ReadFromParquet(filenam)
|
How to read a parquet file into a PCollection from s3?
|
My problem is simple: I want to read a parquet file from s3 into a PCollection in Apache Beam using the Python Sdk.
I know of the apache_beam.io.parquetio module but this one does not seem to be able to read from s3 directly (or does it?).
I know of the apache_beam.io.aws.s3io module but this one seems to return an s3 file object or something that is not a PCollection anyway (or does it?).
So what’s the best way to do this?
|
[
"if you install beam with the aws requirement\npip install 'apache-beam[aws]'\nYou can just pass in an s3 filename to read from it\nfilename = \"s3://bucket-name/...\nbeam.io.ReadFromParquet(filenam)\n\n"
] |
[
0
] |
[] |
[] |
[
"amazon_s3",
"apache_beam",
"parquet",
"python"
] |
stackoverflow_0073283594_amazon_s3_apache_beam_parquet_python.txt
|
Q:
Replace Items in List with Random Items from Dictionary of Lists
I have a list of items that may repeat multiple times. Let us say for example
list = ['a', 'b', 'c', 'd', 'b', 'a', 'c', 'a']
I also have a dictionary of lists that defines multiple values for each key. Suppose:
dict = {'a':[1, 2], 'b':[3, 4], 'c':[5, 6], 'd':[7, 8]}
I want to be able to:
randomly select a value from the dictionary where the key is equal to the value in the original list, and
have this value be randomly selected at each key occurrence in the list.
I attempted to use Pandas to create a DataFrame from my list and leverage pd.Series.map() to randomly map my dictionary like in the following:
df = pd.DataFrame(list, index = [0,1,2,3,4,5,6,7], columns = ['Letters'])
df['Random_Values'] = df['Letters'].map({k:random.choice(v) for k,v in dict.items()})
Output:
Letters Random_Values
0 a 1
1 b 3
2 c 5
3 d 7
4 b 3
5 a 1
6 c 5
7 a 1
This code is successful in randomly selecting a value where the key matches, but it currently randomly selects the same value for every key (i.e., all instances of 'a' will always be 1 or 2, not a mixture).
How can I alter this code to randomly select the values each time the key is matched? Any advice appreciate, Pandas not essential -- if you have a better way with just lists I want to hear it!
A:
You can simply use the built-in random.choice and a list comprehension:
>>> import random
>>>
>>> my_list = ['a', 'b', 'c', 'd', 'b', 'a', 'c', 'a']
>>> my_dict = {'a':[1,2], 'b':[3,4], 'c':[5,6], 'd':[7,8]}
>>>
>>> [(key, random.choice(my_dict[key])) for key in my_list]
[('a', 2), ('b', 3), ('c', 6), ('d', 8), ('b', 4), ('a', 1), ('c', 6), ('a', 1)]
As a side note, don't use builtins such as list and dict as your variable names as they will shadow the builtins.
|
Replace Items in List with Random Items from Dictionary of Lists
|
I have a list of items that may repeat multiple times. Let us say for example
list = ['a', 'b', 'c', 'd', 'b', 'a', 'c', 'a']
I also have a dictionary of lists that defines multiple values for each key. Suppose:
dict = {'a':[1, 2], 'b':[3, 4], 'c':[5, 6], 'd':[7, 8]}
I want to be able to:
randomly select a value from the dictionary where the key is equal to the value in the original list, and
have this value be randomly selected at each key occurrence in the list.
I attempted to use Pandas to create a DataFrame from my list and leverage pd.Series.map() to randomly map my dictionary like in the following:
df = pd.DataFrame(list, index = [0,1,2,3,4,5,6,7], columns = ['Letters'])
df['Random_Values'] = df['Letters'].map({k:random.choice(v) for k,v in dict.items()})
Output:
Letters Random_Values
0 a 1
1 b 3
2 c 5
3 d 7
4 b 3
5 a 1
6 c 5
7 a 1
This code is successful in randomly selecting a value where the key matches, but it currently randomly selects the same value for every key (i.e., all instances of 'a' will always be 1 or 2, not a mixture).
How can I alter this code to randomly select the values each time the key is matched? Any advice appreciate, Pandas not essential -- if you have a better way with just lists I want to hear it!
|
[
"You can simply use the built-in random.choice and a list comprehension:\n>>> import random\n>>>\n>>> my_list = ['a', 'b', 'c', 'd', 'b', 'a', 'c', 'a']\n>>> my_dict = {'a':[1,2], 'b':[3,4], 'c':[5,6], 'd':[7,8]}\n>>>\n>>> [(key, random.choice(my_dict[key])) for key in my_list]\n[('a', 2), ('b', 3), ('c', 6), ('d', 8), ('b', 4), ('a', 1), ('c', 6), ('a', 1)]\n\nAs a side note, don't use builtins such as list and dict as your variable names as they will shadow the builtins.\n"
] |
[
0
] |
[] |
[] |
[
"list",
"python",
"random"
] |
stackoverflow_0074554351_list_python_random.txt
|
Q:
Alien Invasion AttributeError: 'Scoreboard' object has no attribute 'level_img'
I can't find the problem in my code, it says that there is an attribute error but i can't find the problem. I need help Here is a github repository link https://github.com/Hunty405/Alien-Invasion
the book I'm using "python crash course" has what it should be and i've tried to fix the code by using the code in it but i can't get it to work. i believe there is a problem with prep_high_score not being called but i am not sure how to fix it.
Sorry for not posting the error
Traceback (most recent call last):
File "c:\Users\hlehm\Onedrive Transfer\Python\Projects\Alien_Invasion\alien_invasion.py", line 272, in <module>
ai.run_game()
File "c:\Users\hlehm\Onedrive Transfer\Python\Projects\Alien_Invasion\alien_invasion.py", line 50, in run_game
self._update_screen()
File "c:\Users\hlehm\Onedrive Transfer\Python\Projects\Alien_Invasion\alien_invasion.py", line 258, in _update_screen
self.sb.show_score()
File "c:\Users\hlehm\Onedrive Transfer\Python\Projects\Alien_Invasion\scoreboard.py", line 75, in show_score
self.screen.blit(self.level_image, self.level_rect)
AttributeError: 'Scoreboard' object has no attribute 'level_image'
--
import pygame.font
class Scoreboard:
"""A class to report scoring information"""
def __init__(self, ai_game):
"""Initialize scorekeeping attributes"""
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.stats
#Font settings for scoring information
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
#Prepare the initial score images
self.prep_score()
self.prep_high_score()
def prep_score(self):
"""Turn the score into a render image"""
rounded_score = round(self.stats.score, -1)
score_str = "{:,}".format(rounded_score)
self.score_image = self.font.render(score_str, True, self.text_color, self.settings.bg_color)
#Display the score at the top right of the screen
self.score_rect = self.score_image.get_rect()
self.score_rect.right = self.screen_rect.right - 20
self.score_rect.top = 20
def prep_high_score(self):
"""Turn the high score into a rendered image"""
high_score = round(self.stats.high_score, -1)
high_score_str = "{:,}".format(high_score)
self.high_score_image = self.font.render(
high_score_str, True, self.text_color, self.settings.bg_color)
#Center the high score at the top of the screen
self.high_score_rect = self.high_score_image.get_rect()
self.high_score_rect.centerx = self.screen_rect.centerx
self.high_score_rect.top = self.screen_rect.top
def check_high_score(self):
"""Check to see if there's a new high score"""
if self.stats.score > self.stats.high_score:
self.stats.high_score = self.stats.score
self.prep_high_score()
self.prep_level()
def prep_level(self):
"""Turn the level into a rendered image"""
level_str = str(self.stats.level)
self.level_image = self.font.render(
level_str, True, self.text_color, self.settings.bg_color)
#Posistion the level below the score
self.level_rect = self.level_image.get_rect()
self.level_rect.right = self.score_rect.right
self.level_rect.top = self.score_rect.bottom + 10
def show_score(self):
"""Draw scores and level to the screen"""
self.screen.blit(self.score_image, self.score_rect)
self.screen.blit(self.high_score_image, self.high_score_rect)
self.screen.blit(self.level_image, self.level_rect)
A:
The error AttributeError: 'Scoreboard' object has no attribute 'level_image' is saying that your Scoreboard class has no attribute 'level_image'.
So, you'll need to add the attribute it to your __init__ function for the that class. You also need to call the function self.prep_level() as it appears that is the function that will set the value for level_image. I commented on the two lines I added.
def __init__(self, ai_game):
"""Initialize scorekeeping attributes"""
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.stats
### added: level_image here ###
self.level_image = None
#Font settings for scoring information
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
#Prepare the initial score images
self.prep_score()
self.prep_high_score()
### added: call this as well since this function sets the value for level_img ###
self.prep_level()
This should get it to run.
|
Alien Invasion AttributeError: 'Scoreboard' object has no attribute 'level_img'
|
I can't find the problem in my code, it says that there is an attribute error but i can't find the problem. I need help Here is a github repository link https://github.com/Hunty405/Alien-Invasion
the book I'm using "python crash course" has what it should be and i've tried to fix the code by using the code in it but i can't get it to work. i believe there is a problem with prep_high_score not being called but i am not sure how to fix it.
Sorry for not posting the error
Traceback (most recent call last):
File "c:\Users\hlehm\Onedrive Transfer\Python\Projects\Alien_Invasion\alien_invasion.py", line 272, in <module>
ai.run_game()
File "c:\Users\hlehm\Onedrive Transfer\Python\Projects\Alien_Invasion\alien_invasion.py", line 50, in run_game
self._update_screen()
File "c:\Users\hlehm\Onedrive Transfer\Python\Projects\Alien_Invasion\alien_invasion.py", line 258, in _update_screen
self.sb.show_score()
File "c:\Users\hlehm\Onedrive Transfer\Python\Projects\Alien_Invasion\scoreboard.py", line 75, in show_score
self.screen.blit(self.level_image, self.level_rect)
AttributeError: 'Scoreboard' object has no attribute 'level_image'
--
import pygame.font
class Scoreboard:
"""A class to report scoring information"""
def __init__(self, ai_game):
"""Initialize scorekeeping attributes"""
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.stats
#Font settings for scoring information
self.text_color = (30, 30, 30)
self.font = pygame.font.SysFont(None, 48)
#Prepare the initial score images
self.prep_score()
self.prep_high_score()
def prep_score(self):
"""Turn the score into a render image"""
rounded_score = round(self.stats.score, -1)
score_str = "{:,}".format(rounded_score)
self.score_image = self.font.render(score_str, True, self.text_color, self.settings.bg_color)
#Display the score at the top right of the screen
self.score_rect = self.score_image.get_rect()
self.score_rect.right = self.screen_rect.right - 20
self.score_rect.top = 20
def prep_high_score(self):
"""Turn the high score into a rendered image"""
high_score = round(self.stats.high_score, -1)
high_score_str = "{:,}".format(high_score)
self.high_score_image = self.font.render(
high_score_str, True, self.text_color, self.settings.bg_color)
#Center the high score at the top of the screen
self.high_score_rect = self.high_score_image.get_rect()
self.high_score_rect.centerx = self.screen_rect.centerx
self.high_score_rect.top = self.screen_rect.top
def check_high_score(self):
"""Check to see if there's a new high score"""
if self.stats.score > self.stats.high_score:
self.stats.high_score = self.stats.score
self.prep_high_score()
self.prep_level()
def prep_level(self):
"""Turn the level into a rendered image"""
level_str = str(self.stats.level)
self.level_image = self.font.render(
level_str, True, self.text_color, self.settings.bg_color)
#Posistion the level below the score
self.level_rect = self.level_image.get_rect()
self.level_rect.right = self.score_rect.right
self.level_rect.top = self.score_rect.bottom + 10
def show_score(self):
"""Draw scores and level to the screen"""
self.screen.blit(self.score_image, self.score_rect)
self.screen.blit(self.high_score_image, self.high_score_rect)
self.screen.blit(self.level_image, self.level_rect)
|
[
"The error AttributeError: 'Scoreboard' object has no attribute 'level_image' is saying that your Scoreboard class has no attribute 'level_image'.\nSo, you'll need to add the attribute it to your __init__ function for the that class. You also need to call the function self.prep_level() as it appears that is the function that will set the value for level_image. I commented on the two lines I added.\n def __init__(self, ai_game):\n \"\"\"Initialize scorekeeping attributes\"\"\"\n self.screen = ai_game.screen\n self.screen_rect = self.screen.get_rect()\n self.settings = ai_game.settings\n self.stats = ai_game.stats\n\n ### added: level_image here ###\n self.level_image = None\n\n #Font settings for scoring information\n self.text_color = (30, 30, 30)\n self.font = pygame.font.SysFont(None, 48)\n\n #Prepare the initial score images\n self.prep_score()\n self.prep_high_score()\n\n ### added: call this as well since this function sets the value for level_img ###\n self.prep_level()\n\nThis should get it to run.\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074551618_python.txt
|
Q:
Flask-WTForms: populating a FileField field
I have a form using WTF-Forms on Flask such as:
class ImageForm(FlaskForm):
"""Form used for image uploading"""
image = FileField(
validators=[
FileRequired(),
FileAllowed(["png", "jpg", "jpeg"], "This file is not a valid image !",),
],
render_kw={"class": "form-control-file border"},
)
patient_ID = StringField(
"patient_ID",
validators=[DataRequired()],
render_kw={"placeholder": "Patient ID", "class": "form-control"},
)
submit = SubmitField("Upload", render_kw={"class": "btn btn-primary mb-2"})
It works great when filled in.
However I want people to be able to modify the informations later on. So what I do is that if the form page is opened with a GET args such as id=1, I prefill the form with the informations stored such as:
if request.args:
image_request = Image.query.get(request.args.get("id"))
# Check that image exists in DB and prepare the FileStoage object.
if image_request is not None:
file = None
with open(image_request.image_path, "rb") as fp:
file = FileStorage(fp)
form = ImageForm(
image=file,
patient_ID=image_request.patient_id)
It works for patient_ID it is correctly filled. However the "image" field stay UnboundFile.
print(type(file))
print(file)
print(type(ImageForm.image))
print(ImageForm.image)
Gives:
<class 'werkzeug.datastructures.FileStorage'>
<FileStorage: '/home/xxx/xxx/data/hkjhk/hkjhk_dog.jpg' (None)>
<class 'wtforms.fields.core.UnboundField'>
<UnboundField(FileField, (), {'validators': [<flask_wtf.file.FileRequired object at 0x7f170969fb20>, <flask_wtf.file.FileAllowed object at 0x7f170969ffd0>], 'render_kw': {'class': 'form-control-file border'}})>
Has anyone experience on how to prefill a FileStorage field ?
Can you help me with it ?
Thanks a lot !
A:
I know that this is very late, but I'm writing this answer cause I was stuck on the same issue. for security reasons, the browser doesn't accept a prefilled FileField. You need to show the image with html and the keep the FileField for updating the image.
To know if the FileField contains a new file storage you can check for its type. If it is a string then no new file is inserted:
if imageForm.image.data and not sinstance(form.imageFile.data, str):
# here you have a new image file
else:
# here the FileField contains a string or is empty meaning that the
# user has no intention of changing or adding a file.
I hope this is clear and will help someone.
|
Flask-WTForms: populating a FileField field
|
I have a form using WTF-Forms on Flask such as:
class ImageForm(FlaskForm):
"""Form used for image uploading"""
image = FileField(
validators=[
FileRequired(),
FileAllowed(["png", "jpg", "jpeg"], "This file is not a valid image !",),
],
render_kw={"class": "form-control-file border"},
)
patient_ID = StringField(
"patient_ID",
validators=[DataRequired()],
render_kw={"placeholder": "Patient ID", "class": "form-control"},
)
submit = SubmitField("Upload", render_kw={"class": "btn btn-primary mb-2"})
It works great when filled in.
However I want people to be able to modify the informations later on. So what I do is that if the form page is opened with a GET args such as id=1, I prefill the form with the informations stored such as:
if request.args:
image_request = Image.query.get(request.args.get("id"))
# Check that image exists in DB and prepare the FileStoage object.
if image_request is not None:
file = None
with open(image_request.image_path, "rb") as fp:
file = FileStorage(fp)
form = ImageForm(
image=file,
patient_ID=image_request.patient_id)
It works for patient_ID it is correctly filled. However the "image" field stay UnboundFile.
print(type(file))
print(file)
print(type(ImageForm.image))
print(ImageForm.image)
Gives:
<class 'werkzeug.datastructures.FileStorage'>
<FileStorage: '/home/xxx/xxx/data/hkjhk/hkjhk_dog.jpg' (None)>
<class 'wtforms.fields.core.UnboundField'>
<UnboundField(FileField, (), {'validators': [<flask_wtf.file.FileRequired object at 0x7f170969fb20>, <flask_wtf.file.FileAllowed object at 0x7f170969ffd0>], 'render_kw': {'class': 'form-control-file border'}})>
Has anyone experience on how to prefill a FileStorage field ?
Can you help me with it ?
Thanks a lot !
|
[
"I know that this is very late, but I'm writing this answer cause I was stuck on the same issue. for security reasons, the browser doesn't accept a prefilled FileField. You need to show the image with html and the keep the FileField for updating the image.\nTo know if the FileField contains a new file storage you can check for its type. If it is a string then no new file is inserted:\nif imageForm.image.data and not sinstance(form.imageFile.data, str):\n # here you have a new image file\nelse:\n # here the FileField contains a string or is empty meaning that the\n # user has no intention of changing or adding a file.\n\nI hope this is clear and will help someone.\n"
] |
[
0
] |
[] |
[] |
[
"flask",
"flask_wtforms",
"python",
"werkzeug"
] |
stackoverflow_0069312929_flask_flask_wtforms_python_werkzeug.txt
|
Q:
How to merge two dataframes as like "vlookup" with index in pandas
df1
index
A
B
C
No1
-
-
-
No2
-
-
-
No3
-
-
-
df2
index
X
Y
Z
No1
-
-
z1
No2
-
-
z2
No3
-
-
z3
In this case, I would like to make df3 as below
df3
index
A
B
C
Z
No1
-
-
-
z1
No2
-
-
-
z2
No3
-
-
-
z3
I tried that
df3 = pd.merge(df1,df2["Z"], left_on=True)
However, I could not it at all.
A:
what I understood is you want to join the two data frames by their index. if so, then you can use this
df1.join(df2)
or simply by
df3 = pandas.merge(df1, df2['z'], left_index=True, right_index=True)
|
How to merge two dataframes as like "vlookup" with index in pandas
|
df1
index
A
B
C
No1
-
-
-
No2
-
-
-
No3
-
-
-
df2
index
X
Y
Z
No1
-
-
z1
No2
-
-
z2
No3
-
-
z3
In this case, I would like to make df3 as below
df3
index
A
B
C
Z
No1
-
-
-
z1
No2
-
-
-
z2
No3
-
-
-
z3
I tried that
df3 = pd.merge(df1,df2["Z"], left_on=True)
However, I could not it at all.
|
[
"what I understood is you want to join the two data frames by their index. if so, then you can use this\ndf1.join(df2)\n\nor simply by\ndf3 = pandas.merge(df1, df2['z'], left_index=True, right_index=True)\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074554423_pandas_python.txt
|
Q:
How do I output a string of characters based on some rules and an initial string of characters?
Basically, I want to know how to replace every A, + and - in a string of A's,+'s and -'s based on rules inputted.
So if I have a chain of the characters mentioned above, and I input that every A will become A+A, every - will become -+-, every + will become A-+. How do I "choose" every single one of the characters in the initial chain, and change them to the replacements so that it outputs the "new" chain?
Being a beginner to Python, I tried basic commands like
input:"Initial chain: "
input:"What does A become? "
input:"What does + become? "
input:"What does - become? "
but I do not know what to go from there.
A:
You could just make a blank output string variable and then loop through the characters of the initial chain
If the character at any given position is 'A', then concatenate the output string with 'A+A'.
Else if it is '-' concatenate '-+-'.
Else if it is '+' concatenate 'A-+'.
Else just add the original character to the output string.
chain = input('Initial chain: ')
r1 = input('What does A become? ')
r2 = input('What does + become? ')
r3 = input('What does - become? ')
i = 2 # amount of iterations you would like
while i > 0:
result = ''
for c in chain:
if c == 'A':
result += r1
elif c == '+':
result += r2
elif c == '-':
result += r3
else:
result += c
i -= 1
chain = result
print(chain)
|
How do I output a string of characters based on some rules and an initial string of characters?
|
Basically, I want to know how to replace every A, + and - in a string of A's,+'s and -'s based on rules inputted.
So if I have a chain of the characters mentioned above, and I input that every A will become A+A, every - will become -+-, every + will become A-+. How do I "choose" every single one of the characters in the initial chain, and change them to the replacements so that it outputs the "new" chain?
Being a beginner to Python, I tried basic commands like
input:"Initial chain: "
input:"What does A become? "
input:"What does + become? "
input:"What does - become? "
but I do not know what to go from there.
|
[
"You could just make a blank output string variable and then loop through the characters of the initial chain\nIf the character at any given position is 'A', then concatenate the output string with 'A+A'.\nElse if it is '-' concatenate '-+-'.\nElse if it is '+' concatenate 'A-+'.\nElse just add the original character to the output string.\nchain = input('Initial chain: ')\nr1 = input('What does A become? ')\nr2 = input('What does + become? ')\nr3 = input('What does - become? ')\n\ni = 2 # amount of iterations you would like\nwhile i > 0:\n result = ''\n for c in chain:\n if c == 'A':\n result += r1\n elif c == '+':\n result += r2\n elif c == '-':\n result += r3\n else:\n result += c\n i -= 1\n chain = result\n\nprint(chain)\n\n"
] |
[
0
] |
[
"Something like this?\noriginal = input(\"Initial Chain: \")\nin1 = input(\"What does A become? \")\nin2 = input(\"What does + become? \")\nin3 = input(\"What does - become? \")\n\nprint(original.replace(\"A\",in1).replace(\"+\",in2).replace(\"-\",in3))\n\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0074554371_python.txt
|
Q:
Sagemaker Local Mode: RuntimeError: Giving up, endpoint: didn't launch correctly
While running sagemaker in local mode.
I am experimenting with an inference endpoint in local mode using docker container. But as soon as my model.tar.gz file exceeds a certain size i.e. around 200 mb, the deployment fails and returns the error:
RuntimeError: Giving up, endpoint: didn't launch correctly
When I deploy it on a sagemaker instance, it works fine.
Do you know if there is something I could do, perhaps some docker setting I could change to make sure that the local deployment also works with the larger model.tar.gz?
A:
Instead of using SageMaker SDK Local Mode, you can also run vanilla docker commands yourself to imitate the hosted environment:
Such as:
Start "local endpoint"
image=$1
docker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve
Invoke "local endpoint"
payload=$1
content=${2:-text/csv}
curl --data-binary @${payload} -H "Content-Type: ${content}" -v http://localhost:8080/invocations
https://github.com/aws/amazon-sagemaker-examples/tree/main/advanced_functionality/scikit_bring_your_own/container/local_test
|
Sagemaker Local Mode: RuntimeError: Giving up, endpoint: didn't launch correctly
|
While running sagemaker in local mode.
I am experimenting with an inference endpoint in local mode using docker container. But as soon as my model.tar.gz file exceeds a certain size i.e. around 200 mb, the deployment fails and returns the error:
RuntimeError: Giving up, endpoint: didn't launch correctly
When I deploy it on a sagemaker instance, it works fine.
Do you know if there is something I could do, perhaps some docker setting I could change to make sure that the local deployment also works with the larger model.tar.gz?
|
[
"Instead of using SageMaker SDK Local Mode, you can also run vanilla docker commands yourself to imitate the hosted environment:\nSuch as:\n\nStart \"local endpoint\"\n\nimage=$1\n\ndocker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve\n\n\nInvoke \"local endpoint\"\n\npayload=$1\ncontent=${2:-text/csv}\n\ncurl --data-binary @${payload} -H \"Content-Type: ${content}\" -v http://localhost:8080/invocations\n\nhttps://github.com/aws/amazon-sagemaker-examples/tree/main/advanced_functionality/scikit_bring_your_own/container/local_test\n"
] |
[
0
] |
[] |
[] |
[
"amazon_sagemaker",
"amazon_sagemaker_studio",
"docker",
"docker_compose",
"python"
] |
stackoverflow_0074453608_amazon_sagemaker_amazon_sagemaker_studio_docker_docker_compose_python.txt
|
Q:
How to disable the header with filename and date when converting .ipynb to pdf with nbconvert?
I am using nbconvert for converting my .ipynb into an .pdf file. When doing so the resulting .pdf file contains a header with the filename and the current date below. How can I disable that?
I was looking in the docs but cannot find how to do it.
CLI command
jupyter nbconvert --to pdf filename.ipynb
Actual
Wanted
A:
I found some helpful pointer in the docs. Just follow these steps:
Run jupyter --paths in your command-line.
Copy the path who looks like /Users/username/.venv/venvName/share/jupyter (I run nbconvert from a venv. Could be different for you).
Go to the path and duplicate the folder latex
Name the folder hide_header or whatever you want
Open base.tex.j2 and delete the line ((* block maketitle *))\maketitle((* endblock maketitle *))
Save
run jupyter nbconvert --to pdf filename.ipynb --template=hide_header
|
How to disable the header with filename and date when converting .ipynb to pdf with nbconvert?
|
I am using nbconvert for converting my .ipynb into an .pdf file. When doing so the resulting .pdf file contains a header with the filename and the current date below. How can I disable that?
I was looking in the docs but cannot find how to do it.
CLI command
jupyter nbconvert --to pdf filename.ipynb
Actual
Wanted
|
[
"I found some helpful pointer in the docs. Just follow these steps:\n\nRun jupyter --paths in your command-line.\nCopy the path who looks like /Users/username/.venv/venvName/share/jupyter (I run nbconvert from a venv. Could be different for you).\nGo to the path and duplicate the folder latex\nName the folder hide_header or whatever you want\nOpen base.tex.j2 and delete the line ((* block maketitle *))\\maketitle((* endblock maketitle *))\nSave\nrun jupyter nbconvert --to pdf filename.ipynb --template=hide_header\n\n"
] |
[
0
] |
[] |
[] |
[
"jupyter_notebook",
"nbconvert",
"python"
] |
stackoverflow_0074554325_jupyter_notebook_nbconvert_python.txt
|
Q:
Python slice and delete function
I do not understand the slice function. I want to delete all columns from a certain number.
data = np.delete(data, slice(1344,-1), axis = 1)
print(data.shape)
print(data[0,1340:1345])
data = np.delete(data,1344, axis =1 )
print(data.shape)
print(data[0,1340:1345])
If I do so, data.shape somehow does not delete the last element and therefore I get a '0' there which I have to delete in an additional step.
(200000, 1345)
[435 432 426 438 0]
(200000, 1344)
[435 432 426 438]
If I decrease the index by 1,
data = np.delete(data, slice(1343,-1), axis = 1)
print(data.shape)
print(data[0,1340:1345])
I still get a '0' at the end, but the number before is deleted.
(200000, 1344)
[435 432 426 0]
How can I get in a single line an array with size of (200000, 1344) with no 0 at the end, but the real number?
A:
For a simple 1d array:
In [170]: x=np.arange(10)
In [171]: x[slice(5,-1)]
Out[171]: array([5, 6, 7, 8])
The slice by itself is:
In [172]: slice(5,-1)
Out[172]: slice(5, -1, None)
which is the equivalent of:
In [173]: x[5:-1]
Out[173]: array([5, 6, 7, 8])
To get values starting from the end:
In [174]: x[slice(None,5,-1)]
Out[174]: array([9, 8, 7, 6])
In [176]: x[:5:-1]
Out[176]: array([9, 8, 7, 6])
Or deleting:
In [177]: np.delete(x,slice(None,5,-1))
Out[177]: array([0, 1, 2, 3, 4, 5])
|
Python slice and delete function
|
I do not understand the slice function. I want to delete all columns from a certain number.
data = np.delete(data, slice(1344,-1), axis = 1)
print(data.shape)
print(data[0,1340:1345])
data = np.delete(data,1344, axis =1 )
print(data.shape)
print(data[0,1340:1345])
If I do so, data.shape somehow does not delete the last element and therefore I get a '0' there which I have to delete in an additional step.
(200000, 1345)
[435 432 426 438 0]
(200000, 1344)
[435 432 426 438]
If I decrease the index by 1,
data = np.delete(data, slice(1343,-1), axis = 1)
print(data.shape)
print(data[0,1340:1345])
I still get a '0' at the end, but the number before is deleted.
(200000, 1344)
[435 432 426 0]
How can I get in a single line an array with size of (200000, 1344) with no 0 at the end, but the real number?
|
[
"For a simple 1d array:\nIn [170]: x=np.arange(10) \nIn [171]: x[slice(5,-1)]\nOut[171]: array([5, 6, 7, 8])\n\nThe slice by itself is:\nIn [172]: slice(5,-1)\nOut[172]: slice(5, -1, None)\n\nwhich is the equivalent of:\nIn [173]: x[5:-1]\nOut[173]: array([5, 6, 7, 8])\n\nTo get values starting from the end:\nIn [174]: x[slice(None,5,-1)]\nOut[174]: array([9, 8, 7, 6])\nIn [176]: x[:5:-1]\nOut[176]: array([9, 8, 7, 6])\n\nOr deleting:\nIn [177]: np.delete(x,slice(None,5,-1))\nOut[177]: array([0, 1, 2, 3, 4, 5])\n\n"
] |
[
0
] |
[] |
[] |
[
"numpy",
"numpy_ndarray",
"python"
] |
stackoverflow_0074553523_numpy_numpy_ndarray_python.txt
|
Q:
Pandas Split Columns in Columns different sizes
--Edited--['SOLVED']
I am using tabula to convert pdf invoices to pandas dataframe, but the last column isn't in the good way.
I want to split the last row named 'PVF c/ IVA PVA s/Tx Desc% Tx Inf. IVA% P.Unit. Total Liq.'
I want to split, in each space, and have new columns ['PVFc/IVA', 'PVAs/Tx', 'Desc%' 'TxInf.', 'IVA%', 'P.Unit.', 'Total Liq.'], and the rows should be split for each space. Row2 '7,41', '6,30', '65,0', '0,03', '6', '2,24', '22,40'.
I have searched and found how to split, but... some rows will be split in 7 columns and other only in 6 columns and I get an error.
For more information, every row which 'PVP c/Iva' is NaN or 'Esc.' is 'NETT' don't have 'PVFc/IVA' value, so the (len) of the column is 6. it's possible for my analyses insert 0,00 as prefix in that rows to all have a 7 columns len().
Any solution is welcome, I am starting with Python and pandas... thanks for your time
I apply parts of the code from @Ahmed Sayed, and i have made progess,
to concatenate Nan Colums with other, first i replace Nan with a space
dataframe['placeHolderColumn'] = dataframe['placeHolderColumn'].fillna(value='')
after some trying e errors, i found that sometimes there are more than one space, so I have replaced all spaces for one space, and then replace '*'
dataframe["newColumn"]= dataframe['newColumn'].str.replace(' ','*')
the i have created a new column to confirme the split element
dataframe["count2"]= dataframe['newColumn'].str.count('\*', re.I)
I get this result
So, as last job i apply the split métode,
dataframe[['c1','c2','c3','c4','c5','c6']] = dataframe['newColumn'].str.split('*', expand=True)
but i get this error
--FOUND--
i have to pass another column name, i am just passing 6 new colums and i have 7 values
dataframe[['c1','c2','c3','c4','c5','c6', 'c7']] = dataframe['newColumn'].str.split('*', expand=True)
A:
So the problem here is the cells do not have an equal number of values in that column, we can address this by counting the number of values and wherever we see a missing value, we can add a dummy 00 at the beginning so it is easier for us to split later.
first, let's create a column with the number of spaces. This gives the number of values in that row.
import re
df["count"]= df['PVF c/ IVA PVA s/Tx Desc% Tx Inf. IVA% P.Unit. Total Liq.'].str.count(' ', re.I)
then, if the count is less than what we are expecting, let's append a zero at the beginning of each cell string
# here we compare the number of spaces to 5, 5 is for the short cells that need a dummy 00 at the beginning
df.loc[df["count"] <= 5, 'placeHolderColumn'] = '00 ' #notice there is a space after the zeros
# now let's create a new column and merge the placeHolderColumn column to the old values column
df['newColumn'] = df['placeHolderColumn'] + df['PVF c/ IVA PVA s/Tx Desc% Tx Inf. IVA% P.Unit. Total Liq.'].astype(str)
lastly, we can split the column by
df[['c1','c2','c3','c4','c5','c6']] = df['newColumn'].str.split(' ', expand=True)
|
Pandas Split Columns in Columns different sizes
|
--Edited--['SOLVED']
I am using tabula to convert pdf invoices to pandas dataframe, but the last column isn't in the good way.
I want to split the last row named 'PVF c/ IVA PVA s/Tx Desc% Tx Inf. IVA% P.Unit. Total Liq.'
I want to split, in each space, and have new columns ['PVFc/IVA', 'PVAs/Tx', 'Desc%' 'TxInf.', 'IVA%', 'P.Unit.', 'Total Liq.'], and the rows should be split for each space. Row2 '7,41', '6,30', '65,0', '0,03', '6', '2,24', '22,40'.
I have searched and found how to split, but... some rows will be split in 7 columns and other only in 6 columns and I get an error.
For more information, every row which 'PVP c/Iva' is NaN or 'Esc.' is 'NETT' don't have 'PVFc/IVA' value, so the (len) of the column is 6. it's possible for my analyses insert 0,00 as prefix in that rows to all have a 7 columns len().
Any solution is welcome, I am starting with Python and pandas... thanks for your time
I apply parts of the code from @Ahmed Sayed, and i have made progess,
to concatenate Nan Colums with other, first i replace Nan with a space
dataframe['placeHolderColumn'] = dataframe['placeHolderColumn'].fillna(value='')
after some trying e errors, i found that sometimes there are more than one space, so I have replaced all spaces for one space, and then replace '*'
dataframe["newColumn"]= dataframe['newColumn'].str.replace(' ','*')
the i have created a new column to confirme the split element
dataframe["count2"]= dataframe['newColumn'].str.count('\*', re.I)
I get this result
So, as last job i apply the split métode,
dataframe[['c1','c2','c3','c4','c5','c6']] = dataframe['newColumn'].str.split('*', expand=True)
but i get this error
--FOUND--
i have to pass another column name, i am just passing 6 new colums and i have 7 values
dataframe[['c1','c2','c3','c4','c5','c6', 'c7']] = dataframe['newColumn'].str.split('*', expand=True)
|
[
"So the problem here is the cells do not have an equal number of values in that column, we can address this by counting the number of values and wherever we see a missing value, we can add a dummy 00 at the beginning so it is easier for us to split later.\nfirst, let's create a column with the number of spaces. This gives the number of values in that row.\nimport re\ndf[\"count\"]= df['PVF c/ IVA PVA s/Tx Desc% Tx Inf. IVA% P.Unit. Total Liq.'].str.count(' ', re.I)\n\nthen, if the count is less than what we are expecting, let's append a zero at the beginning of each cell string\n# here we compare the number of spaces to 5, 5 is for the short cells that need a dummy 00 at the beginning\ndf.loc[df[\"count\"] <= 5, 'placeHolderColumn'] = '00 ' #notice there is a space after the zeros\n# now let's create a new column and merge the placeHolderColumn column to the old values column\ndf['newColumn'] = df['placeHolderColumn'] + df['PVF c/ IVA PVA s/Tx Desc% Tx Inf. IVA% P.Unit. Total Liq.'].astype(str) \n\nlastly, we can split the column by\ndf[['c1','c2','c3','c4','c5','c6']] = df['newColumn'].str.split(' ', expand=True)\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python",
"tabula"
] |
stackoverflow_0074554396_dataframe_pandas_python_tabula.txt
|
Q:
change the color of a tkinter widget with command
I'm trying to make gui with tkinter (I also use customtkinter to have a good design) and I'm trying to make categories, I created for this a margin (with a frame) in which I have place buttons for the different categories, I would like the button of the current category to be colored blue, and the other buttons to be gray, so I wrote the code for this but the expected effect does not happen, the problem is that the last button of the dictionary turns blue (and the rest) and that even if I don't press this one but another one, can you help me please? here is my code
class App(customtkinter.CTk):
def __init__(self):
super().__init__()
self.WIDTH = 780
self.HEIGHT = 520
self.nom_window='Opticopilot 1.0'
self.geometry(str(self.WIDTH)+'x'+str(self.HEIGHT))
self.title(self.nom_window)
self.configure(bg='#333333')
#self.columnconfigure(0, weight=1)
#self.rowconfigure(0, weight=1)
self.frame_gauche=customtkinter.CTkFrame(master=self,width=(self.winfo_screenwidth()//13),height=self.winfo_screenheight(),corner_radius=0)
self.frame_gauche.grid(row=1, column=0,sticky='w',rowspan=15, columnspan=2)
self.frame_gauche.grid_propagate(0)
#self.frame_gauche.winfo_screenwidth()
self.dictionnaire_bouttons_marge_gauche={}
self.dictionnaire_bouttons_marge_gauche["P.E.C"]= customtkinter.CTkButton(master=self.frame_gauche,width=(self.frame_gauche.winfo_screenwidth()//13),height=(self.frame_gauche.winfo_screenheight()//25),border_width=0,corner_radius=0,text="P.E.C", fg_color='grey')
self.dictionnaire_bouttons_marge_gauche["P.E.C"].grid(row=0, column=0)
self.dictionnaire_bouttons_marge_gauche["Notifications"]= customtkinter.CTkButton(master=self.frame_gauche,width=(self.frame_gauche.winfo_screenwidth()//13),height=(self.frame_gauche.winfo_screenheight()//25),border_width=0,corner_radius=0,text="Notifications", fg_color='grey')
self.dictionnaire_bouttons_marge_gauche["Notifications"].grid(row=2, column=0)
self.dictionnaire_bouttons_marge_gauche["Facturation"]= customtkinter.CTkButton(master=self.frame_gauche,width=(self.frame_gauche.winfo_screenwidth()//13),height=(self.frame_gauche.winfo_screenheight()//25),border_width=0,corner_radius=0,text="Facturation", fg_color='grey')
self.dictionnaire_bouttons_marge_gauche["Facturation"].grid(row=1, column=0)
def effet_boutton_selectionne(dictionnaire,key):
for clee in dictionnaire:
if clee!=key:
dictionnaire[clee].configure(fg_color='grey')
else:
dictionnaire[clee].configure(fg_color='blue')
"""self.dictionnaire_bouttons_marge_gauche["P.E.C"].configure(command=lambda:effet_boutton_selectionne(self.dictionnaire_bouttons_marge_gauche,self.dictionnaire_bouttons_marge_gauche["P.E.C"]))
self.dictionnaire_bouttons_marge_gauche["Facturation"].configure(command=lambda:effet_boutton_selectionne(self.dictionnaire_bouttons_marge_gauche,self.dictionnaire_bouttons_marge_gauche["Facturation"]))
self.dictionnaire_bouttons_marge_gauche["Notifications"].configure(command=lambda:effet_boutton_selectionne(self.dictionnaire_bouttons_marge_gauche,self.dictionnaire_bouttons_marge_gauche["Notifications"]))"""
for boutton in self.dictionnaire_bouttons_marge_gauche:
self.dictionnaire_bouttons_marge_gauche[boutton].configure(command=lambda:effet_boutton_selectionne(self.dictionnaire_bouttons_marge_gauche,boutton))
I tried the code above but without success, I tried different methods of configuring the code, without success either
A:
Try looking at the tkinter documentation for coloring GUI elements.
In short, to color a GUI button, use the following code:
l1 = tkinter.Label(text="Test", fg="black", bg="white")
|
change the color of a tkinter widget with command
|
I'm trying to make gui with tkinter (I also use customtkinter to have a good design) and I'm trying to make categories, I created for this a margin (with a frame) in which I have place buttons for the different categories, I would like the button of the current category to be colored blue, and the other buttons to be gray, so I wrote the code for this but the expected effect does not happen, the problem is that the last button of the dictionary turns blue (and the rest) and that even if I don't press this one but another one, can you help me please? here is my code
class App(customtkinter.CTk):
def __init__(self):
super().__init__()
self.WIDTH = 780
self.HEIGHT = 520
self.nom_window='Opticopilot 1.0'
self.geometry(str(self.WIDTH)+'x'+str(self.HEIGHT))
self.title(self.nom_window)
self.configure(bg='#333333')
#self.columnconfigure(0, weight=1)
#self.rowconfigure(0, weight=1)
self.frame_gauche=customtkinter.CTkFrame(master=self,width=(self.winfo_screenwidth()//13),height=self.winfo_screenheight(),corner_radius=0)
self.frame_gauche.grid(row=1, column=0,sticky='w',rowspan=15, columnspan=2)
self.frame_gauche.grid_propagate(0)
#self.frame_gauche.winfo_screenwidth()
self.dictionnaire_bouttons_marge_gauche={}
self.dictionnaire_bouttons_marge_gauche["P.E.C"]= customtkinter.CTkButton(master=self.frame_gauche,width=(self.frame_gauche.winfo_screenwidth()//13),height=(self.frame_gauche.winfo_screenheight()//25),border_width=0,corner_radius=0,text="P.E.C", fg_color='grey')
self.dictionnaire_bouttons_marge_gauche["P.E.C"].grid(row=0, column=0)
self.dictionnaire_bouttons_marge_gauche["Notifications"]= customtkinter.CTkButton(master=self.frame_gauche,width=(self.frame_gauche.winfo_screenwidth()//13),height=(self.frame_gauche.winfo_screenheight()//25),border_width=0,corner_radius=0,text="Notifications", fg_color='grey')
self.dictionnaire_bouttons_marge_gauche["Notifications"].grid(row=2, column=0)
self.dictionnaire_bouttons_marge_gauche["Facturation"]= customtkinter.CTkButton(master=self.frame_gauche,width=(self.frame_gauche.winfo_screenwidth()//13),height=(self.frame_gauche.winfo_screenheight()//25),border_width=0,corner_radius=0,text="Facturation", fg_color='grey')
self.dictionnaire_bouttons_marge_gauche["Facturation"].grid(row=1, column=0)
def effet_boutton_selectionne(dictionnaire,key):
for clee in dictionnaire:
if clee!=key:
dictionnaire[clee].configure(fg_color='grey')
else:
dictionnaire[clee].configure(fg_color='blue')
"""self.dictionnaire_bouttons_marge_gauche["P.E.C"].configure(command=lambda:effet_boutton_selectionne(self.dictionnaire_bouttons_marge_gauche,self.dictionnaire_bouttons_marge_gauche["P.E.C"]))
self.dictionnaire_bouttons_marge_gauche["Facturation"].configure(command=lambda:effet_boutton_selectionne(self.dictionnaire_bouttons_marge_gauche,self.dictionnaire_bouttons_marge_gauche["Facturation"]))
self.dictionnaire_bouttons_marge_gauche["Notifications"].configure(command=lambda:effet_boutton_selectionne(self.dictionnaire_bouttons_marge_gauche,self.dictionnaire_bouttons_marge_gauche["Notifications"]))"""
for boutton in self.dictionnaire_bouttons_marge_gauche:
self.dictionnaire_bouttons_marge_gauche[boutton].configure(command=lambda:effet_boutton_selectionne(self.dictionnaire_bouttons_marge_gauche,boutton))
I tried the code above but without success, I tried different methods of configuring the code, without success either
|
[
"Try looking at the tkinter documentation for coloring GUI elements.\nIn short, to color a GUI button, use the following code:\nl1 = tkinter.Label(text=\"Test\", fg=\"black\", bg=\"white\")\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"tkinter"
] |
stackoverflow_0074554018_python_tkinter.txt
|
Q:
What's the most efficient way to resample from an array many times and take the mode of each sample?
So bootstrapping, but for modes.
The end goal is to create a probability distribution out of these modes. I need to create a test statistic that compares these distributions (and then perform a permutation test), so the initial bootstrapping needs to be as quick as possible so that creating the null distribution doesn't take too much time.
Can I use numpy's random.choice for this?
A:
Adapting from Using bootstrapping random.choice
import scipy.stats as ss
array = ...
num_samples = 1000
sample_size = 100
Replications = np.array([np.random.choice(array, sample_size, replace = True) for _ in range(num_samples)])
mode_result = ss.mode(Replications, axis=1)
mode = mode_result.mode
|
What's the most efficient way to resample from an array many times and take the mode of each sample?
|
So bootstrapping, but for modes.
The end goal is to create a probability distribution out of these modes. I need to create a test statistic that compares these distributions (and then perform a permutation test), so the initial bootstrapping needs to be as quick as possible so that creating the null distribution doesn't take too much time.
Can I use numpy's random.choice for this?
|
[
"Adapting from Using bootstrapping random.choice\nimport scipy.stats as ss\n\narray = ...\nnum_samples = 1000\n\nsample_size = 100\n\nReplications = np.array([np.random.choice(array, sample_size, replace = True) for _ in range(num_samples)])\nmode_result = ss.mode(Replications, axis=1)\n\nmode = mode_result.mode\n\n"
] |
[
1
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0074554393_numpy_python.txt
|
Q:
Python AttributeError: 'Page' object has no attribute 'insertImage'
I'am trying to add a png sign to the PDF by using a python code and the code that i am running is I am using PyMuPDF and have used fitz library.
import fitz
input_file = "example.pdf"
output_file = "example-with-sign.pdf"
barcode_file = "sign.png"
# define the position (upper-right corner)
image_rectangle = fitz.Rect(450,20,550,120)
# retrieve the first page of the PDF
file_handle = fitz.open(input_file)
first_page = file_handle[0]
# add the image
first_page.insertImage(image_rectangle, fileName=barcode_file)
file_handle.save(output_file)
A:
Thank you for 'insert_image' correction. It currently works as follows:
import fitz
input_file = "example.pdf"
output_file = "example-with-sign.pdf"
# define the position (upper-right corner)
image_rectangle = fitz.Rect(450,20,550,120)
# retrieve the first page of the PDF
file_handle = fitz.open(input_file)
first_page = file_handle[0]
img = open("sign.png", "rb").read() # an image file
img_xref = 0
first_page.insert_image(image_rectangle,stream=img,xref=img_xref)
file_handle.save(output_file)
A:
I got stuck with a very similar error to your question. The insert_image solution you posted is correct, but I think the reason is that from a certain version of PyMuPDF, camelCase (which was good to use before) was totally deprecated, and was replaced by under_score_case. I think it's necessary to mark the PyMuPDF version here, just in case somebody was confused by these two coding styles when they met similar errors in the future.
Currently, I'm under PyMuPDF==1.21.0, in which I'm pretty sure camelCase was totally deprecated. So if you met a similar error, just try to convert your method someMethod() into some_method().
See: doc is here
|
Python AttributeError: 'Page' object has no attribute 'insertImage'
|
I'am trying to add a png sign to the PDF by using a python code and the code that i am running is I am using PyMuPDF and have used fitz library.
import fitz
input_file = "example.pdf"
output_file = "example-with-sign.pdf"
barcode_file = "sign.png"
# define the position (upper-right corner)
image_rectangle = fitz.Rect(450,20,550,120)
# retrieve the first page of the PDF
file_handle = fitz.open(input_file)
first_page = file_handle[0]
# add the image
first_page.insertImage(image_rectangle, fileName=barcode_file)
file_handle.save(output_file)
|
[
"Thank you for 'insert_image' correction. It currently works as follows:\nimport fitz\n\ninput_file = \"example.pdf\"\noutput_file = \"example-with-sign.pdf\"\n\n\n# define the position (upper-right corner)\nimage_rectangle = fitz.Rect(450,20,550,120)\n\n# retrieve the first page of the PDF\nfile_handle = fitz.open(input_file)\nfirst_page = file_handle[0]\n\nimg = open(\"sign.png\", \"rb\").read() # an image file\nimg_xref = 0\n\nfirst_page.insert_image(image_rectangle,stream=img,xref=img_xref)\n\nfile_handle.save(output_file)\n\n",
"I got stuck with a very similar error to your question. The insert_image solution you posted is correct, but I think the reason is that from a certain version of PyMuPDF, camelCase (which was good to use before) was totally deprecated, and was replaced by under_score_case. I think it's necessary to mark the PyMuPDF version here, just in case somebody was confused by these two coding styles when they met similar errors in the future.\nCurrently, I'm under PyMuPDF==1.21.0, in which I'm pretty sure camelCase was totally deprecated. So if you met a similar error, just try to convert your method someMethod() into some_method().\nSee: doc is here\n"
] |
[
1,
1
] |
[] |
[] |
[
"compiler_errors",
"pdf",
"pymupdf",
"python"
] |
stackoverflow_0073633334_compiler_errors_pdf_pymupdf_python.txt
|
Q:
ValueError: Unknown loss function: categorical crossentropy. Please ensure this object is passed to the `custom_objects` argument
I am trying to build a chatbot for a University project, by following a youtube tutorial and basically having zero experience. Everything worked fine until now, and I get a ValueError.
This is what I receive when I run the code:
C:\Users\Kimbe\.conda\envs\tf.2\python.exe C:\Users\Kimbe\PycharmProjects\chatbot\training.py
C:\Users\Kimbe\PycharmProjects\chatbot\training.py:53: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
training = np.array(training)
2022-11-23 21:38:00.366897: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found
2022-11-23 21:38:00.367881: W tensorflow/stream_executor/cuda/cuda_driver.cc:263] failed call to cuInit: UNKNOWN ERROR (303)
2022-11-23 21:38:00.371587: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: Kims-Surface
2022-11-23 21:38:00.371782: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: Kims-Surface
2022-11-23 21:38:00.372191: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\optimizers\optimizer_v2\gradient_descent.py:111: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.
super().__init__(name, **kwargs)
Epoch 1/200
Traceback (most recent call last):
File "C:\Users\Kimbe\PycharmProjects\chatbot\training.py", line 69, in <module>
model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\Kimbe\AppData\Local\Temp\__autograph_generated_filecynafcyn.py", line 15, in tf__train_function
retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 1160, in train_function *
return step_function(self, iterator)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 1146, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 1135, in run_step **
outputs = model.train_step(data)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 994, in train_step
loss = self.compute_loss(x, y, y_pred, sample_weight)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 1052, in compute_loss
return self.compiled_loss(
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\compile_utils.py", line 240, in __call__
self.build(y_pred)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\compile_utils.py", line 182, in build
self._losses = tf.nest.map_structure(
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\compile_utils.py", line 353, in _get_loss_object
loss = losses_mod.get(loss)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\losses.py", line 2649, in get
return deserialize(identifier)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\losses.py", line 2603, in deserialize
return deserialize_keras_object(
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\utils\generic_utils.py", line 769, in deserialize_keras_object
raise ValueError(
ValueError: Unknown loss function: categorical crossentropy. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.
Process finished with exit code 1
This is my code:
import random
import json
import pickle
import numpy as np
import nltk
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras.optimizers import SGD
lemmatizer = WordNetLemmatizer()
intents = json.loads(open('intents.json').read())
words = []
classes = []
documents = []
ignore_letters = ['?', '!', '.', ',']
for intent in intents['intents']:
for pattern in intent['patterns']:
word_list = nltk.word_tokenize(pattern)
words.extend(word_list)
documents.append((word_list, intent['tag']))
if intent['tag'] not in classes:
classes.append(intent['tag'])
words = [lemmatizer.lemmatize(word) for word in words if word not in ignore_letters]
words = sorted(set(words))
classes = sorted(set(classes))
pickle.dump(words, open('words.pkl', 'wb'))
pickle.dump(words, open('classes.pkl', 'wb'))
training = []
output_empty = [0] * len(classes)
for document in documents:
bag = []
word_patterns = document[0]
word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]
for word in words:
bag.append(1) if word in word_patterns else bag.append(0)
output_row = list(output_empty)
output_row[classes.index(document[1])] = 1
training.append([bag, output_row])
random.shuffle(training)
training = np.array(training)
train_x = list(training[:, 0])
train_y = list(training[:, 1])
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical crossentropy', optimizer=sgd, metrics=['accuracy'])
model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save('Chatbot_model.model')
print("Done")
I googled a bit and tried out different fixes but none of them seemed to work.
Since it says something about rebuilding tensorflow I assume I need to redownload it and do the code again?
Before, the tensorflow and the code seemed to be running fine but after adding random.shuffle this error came.
Would be nice if anybody could help me out. Thank you! :)
|
ValueError: Unknown loss function: categorical crossentropy. Please ensure this object is passed to the `custom_objects` argument
|
I am trying to build a chatbot for a University project, by following a youtube tutorial and basically having zero experience. Everything worked fine until now, and I get a ValueError.
This is what I receive when I run the code:
C:\Users\Kimbe\.conda\envs\tf.2\python.exe C:\Users\Kimbe\PycharmProjects\chatbot\training.py
C:\Users\Kimbe\PycharmProjects\chatbot\training.py:53: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
training = np.array(training)
2022-11-23 21:38:00.366897: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found
2022-11-23 21:38:00.367881: W tensorflow/stream_executor/cuda/cuda_driver.cc:263] failed call to cuInit: UNKNOWN ERROR (303)
2022-11-23 21:38:00.371587: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: Kims-Surface
2022-11-23 21:38:00.371782: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: Kims-Surface
2022-11-23 21:38:00.372191: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\optimizers\optimizer_v2\gradient_descent.py:111: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.
super().__init__(name, **kwargs)
Epoch 1/200
Traceback (most recent call last):
File "C:\Users\Kimbe\PycharmProjects\chatbot\training.py", line 69, in <module>
model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:\Users\Kimbe\AppData\Local\Temp\__autograph_generated_filecynafcyn.py", line 15, in tf__train_function
retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 1160, in train_function *
return step_function(self, iterator)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 1146, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 1135, in run_step **
outputs = model.train_step(data)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 994, in train_step
loss = self.compute_loss(x, y, y_pred, sample_weight)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\training.py", line 1052, in compute_loss
return self.compiled_loss(
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\compile_utils.py", line 240, in __call__
self.build(y_pred)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\compile_utils.py", line 182, in build
self._losses = tf.nest.map_structure(
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\engine\compile_utils.py", line 353, in _get_loss_object
loss = losses_mod.get(loss)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\losses.py", line 2649, in get
return deserialize(identifier)
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\losses.py", line 2603, in deserialize
return deserialize_keras_object(
File "C:\Users\Kimbe\.conda\envs\tf.2\lib\site-packages\keras\utils\generic_utils.py", line 769, in deserialize_keras_object
raise ValueError(
ValueError: Unknown loss function: categorical crossentropy. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.
Process finished with exit code 1
This is my code:
import random
import json
import pickle
import numpy as np
import nltk
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras.optimizers import SGD
lemmatizer = WordNetLemmatizer()
intents = json.loads(open('intents.json').read())
words = []
classes = []
documents = []
ignore_letters = ['?', '!', '.', ',']
for intent in intents['intents']:
for pattern in intent['patterns']:
word_list = nltk.word_tokenize(pattern)
words.extend(word_list)
documents.append((word_list, intent['tag']))
if intent['tag'] not in classes:
classes.append(intent['tag'])
words = [lemmatizer.lemmatize(word) for word in words if word not in ignore_letters]
words = sorted(set(words))
classes = sorted(set(classes))
pickle.dump(words, open('words.pkl', 'wb'))
pickle.dump(words, open('classes.pkl', 'wb'))
training = []
output_empty = [0] * len(classes)
for document in documents:
bag = []
word_patterns = document[0]
word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]
for word in words:
bag.append(1) if word in word_patterns else bag.append(0)
output_row = list(output_empty)
output_row[classes.index(document[1])] = 1
training.append([bag, output_row])
random.shuffle(training)
training = np.array(training)
train_x = list(training[:, 0])
train_y = list(training[:, 1])
model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical crossentropy', optimizer=sgd, metrics=['accuracy'])
model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save('Chatbot_model.model')
print("Done")
I googled a bit and tried out different fixes but none of them seemed to work.
Since it says something about rebuilding tensorflow I assume I need to redownload it and do the code again?
Before, the tensorflow and the code seemed to be running fine but after adding random.shuffle this error came.
Would be nice if anybody could help me out. Thank you! :)
|
[] |
[] |
[
"you may need to consider the input format as float or int.\n\nSample: Calculation is beneficial when the sequence is in format, passthrough possible but no meaning when it cannot have a load of functions.\n\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\n\nimport tensorflow as tf\n\nimport json\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Variables\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nvocab = [ \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\", \"_\", \n\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\",\n\",\", \"ù\", \"é\", \"ç\", \"ô\", \"À\", \"à\" ]\n\nlemmatizer = WordNetLemmatizer()\nintents = json.loads(open(\"F:\\\\temp\\\\Python\\\\chatbots\\\\intents.json\").read())\n\nwords = []\nclasses = []\ndocuments = []\nignore_letters = ['?', '!', '.', ',']\n\nlist_classes = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]\nlist_words = [ ]\nlist_label = [ ]\n\nfor intent in intents['intents']:\n for pattern in intent['patterns']:\n word_list = nltk.word_tokenize(pattern)\n words.extend(word_list)\n documents.append((word_list, intent['tag']))\n if intent['tag'] not in classes:\n classes.append(intent['tag'])\n \nwords = [lemmatizer.lemmatize(word) for word in words if word not in ignore_letters]\nwords = sorted(set(words))\n\nclasses = sorted(set(classes))\nprint( \"======================================================================================\" )\nlayer = tf.keras.layers.StringLookup(vocabulary=vocab)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Class / Functions\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\ndef auto_paddings( data, max_sequences=40 ):\n data = tf.constant( data, shape=(data.shape[0], 1) )\n paddings = tf.constant([[1, 40 - data.shape[0] - 1], [0, 0]])\n padd_data = tf.pad( data, paddings, \"CONSTANT\" )\n padd_data = tf.constant( padd_data, shape=(40, 1) ).numpy()\n return padd_data\n\nprint( \"======================================================================================\" )\n\nfor words_string in words:\n padd_data = auto_paddings( layer( tf.strings.bytes_split(words_string) ), 40 )\n list_words.append( padd_data )\n list_label.append( list_classes[0] ) # requires mapping or supervise learning\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: DataSet\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\ndataset = tf.data.Dataset.from_tensor_slices((tf.constant(list_words, shape=(168, 1, 40, 1),dtype=tf.float32), tf.constant(list_label, shape=(168, 1, 1), dtype=tf.int64)))\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Model Initialize\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.InputLayer(input_shape=( 40, 1 )),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32, return_sequences=True, return_state=False)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(192, activation='relu'),\n tf.keras.layers.Dense(11),\n])\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Optimizer\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\noptimizer = tf.keras.optimizers.Nadam(\n learning_rate=0.00001, beta_1=0.9, beta_2=0.999, epsilon=1e-07,\n name='Nadam'\n)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Loss Fn\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nlossfn = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=False,\n reduction=tf.keras.losses.Reduction.AUTO,\n name='sparse_categorical_crossentropy'\n)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Model Summary\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nmodel.compile(optimizer=optimizer, loss=lossfn, metrics=['accuracy'])\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Training\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nhistory = model.fit( dataset, batch_size=100, epochs=50 )\n\n\nOutput: Function revokes with sample inputs, feedback value make sense loss optimizer fn and matrixes value seem to reflect the real truth.\n\nEpoch 1/50\n2022-11-24 08:13:14.910457: I tensorflow/stream_executor/cuda/cuda_dnn.cc:384] Loaded cuDNN version 8100\n168/168 [==============================] - 11s 26ms/step - loss: 0.9852 - accuracy: 0.5893\nEpoch 2/50\n168/168 [==============================] - 5s 27ms/step - loss: 0.2256 - accuracy: 1.0000\nEpoch 3/50\n104/168 [=================>............] - ETA: 1s - loss: 0.0082 - accuracy: 1.0000\n\n"
] |
[
-1
] |
[
"chatbot",
"keras",
"python",
"tensorflow",
"valueerror"
] |
stackoverflow_0074552911_chatbot_keras_python_tensorflow_valueerror.txt
|
Q:
Reading Multiple S3 Folders / Paths Into PySpark
I am conducting a big data analysis using PySpark. I am able to import all CSV files, stored in a particular folder of a particular bucket, using the following command:
df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('file:///home/path/datafolder/data2014/*.csv')
(where * acts like a wildcard)
The issues I have are the following:
What if I want to do my analysis on 2014 and 2015 data i.e. file 1 is .load('file:///home/path/SFweather/data2014/*.csv'), file 2 is .load('file:///home/path/SFweather/data2015/*.csv') and file 3 is .load('file:///home/path/NYCweather/data2014/*.csv') and file 4 is .load('file:///home/path/NYCweather/data2015/*.csv'). How do I import multiple paths at the same time to get one dataframe? Do I need to store them all individually as dataframes and then join them together within PySpark? (You may assume they all CSVs have the same schema)
Suppose it is November 2014 now. What if I want to run the analysis again, but on the "most recent data" run e.g. dec14 when it is December 2014? For example, I want to load in file 2: .load('file:///home/path/datafolder/data2014/dec14/*.csv') in December 14 and use this file: .load('file:///home/path/datafolder/data2014/nov14/*.csv') for the original analysis. Is there a way to schedule the Jupyter notebook (or similar) to update the load path and import the latest run (in this case 'nov14' would be replaced by 'dec14' and then 'jan15' etc).
I had a look through the previous questions but was unable to find an answer given this is AWS / PySpark integration specific.
Thank you in advance for the help!
[Background: I have been given access to many S3 buckets from various teams containing various big data sets. Copying it over to my S3 bucket, then building a Jupyter notebook seems like a lot more work than just pulling in the data directly from their bucket and building a model / table / etc ontop of it and saving the processed output into a database. Hence I am posting the questions above. If my thinking is completely wrong, please stop me! :)]
A:
You can read in multiple paths with wildcards as long as the files are all in the same format.
In your example:
.load('file:///home/path/SFweather/data2014/*.csv')
.load('file:///home/path/SFweather/data2015/*.csv')
.load('file:///home/path/NYCweather/data2014/*.csv')
.load('file:///home/path/NYCweather/data2015/*.csv')
You could replace the 4 load statements above with the following path to read all csv's in at once to one dataframe:
.load('file:///home/path/*/*/*.csv')
If you want to be more specific in order to avoid reading in certain files/folders, you can do the following:
.load('file:///home/path/[SF|NYC]weather/data201[4|5]/*.csv')
A:
You can load multiple paths at once using lists of pattern strings. The pyspark.sql.DataFrameReader.load method accepts a list of path strings, which is especially helpful if you can't express all of the paths you want to load using a single Hadoop glob pattern:
?
Matches any single character.
*
Matches zero or more characters.
[abc]
Matches a single character from character set {a,b,c}.
[a-b]
Matches a single character from the character range {a...b}.
Note that character a must be lexicographically less than or
equal to character b.
[^a]
Matches a single character that is not from character set or
range {a}. Note that the ^ character must occur immediately
to the right of the opening bracket.
\c
Removes (escapes) any special meaning of character c.
{ab,cd}
Matches a string from the string set {ab, cd}
{ab,c{de,fh}}
Matches a string from the string set {ab, cde, cfh}
For example, if you want to load the following paths:
[
's3a://bucket/prefix/key=1/year=2010/*.csv',
's3a://bucket/prefix/key=1/year=2011/*.csv',
's3a://bucket/prefix/key=2/year=2020/*.csv',
's3a://bucket/prefix/key=2/year=2021/*.csv',
]
You could reduce these to two path patterns,
s3a://bucket/prefix/key=1/year=201[0-1]/*.csv and
s3a://bucket/prefix/key=2/year=202[0-1]/*.csv,
and call load() twice. You could go further and reduce these to a single pattern string using {ab,cd} alternation, but I think the most readable way to express paths like these using glob patterns with a single call to load() is to pass a list of path patterns:
spark.read.format('csv').load(
[
's3a://bucket/prefix/key=1/year=201[0-1]/*.csv',
's3a://bucket/prefix/key=2/year=202[0-1]/*.csv',
]
)
For the paths you listed in your issue № 1, you can express all four with a single pattern string:
'file:///home/path/{NY,SF}weather/data201[45]/*.csv'
For your issue № 2, you can write logic to construct the paths you want to load.
|
Reading Multiple S3 Folders / Paths Into PySpark
|
I am conducting a big data analysis using PySpark. I am able to import all CSV files, stored in a particular folder of a particular bucket, using the following command:
df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('file:///home/path/datafolder/data2014/*.csv')
(where * acts like a wildcard)
The issues I have are the following:
What if I want to do my analysis on 2014 and 2015 data i.e. file 1 is .load('file:///home/path/SFweather/data2014/*.csv'), file 2 is .load('file:///home/path/SFweather/data2015/*.csv') and file 3 is .load('file:///home/path/NYCweather/data2014/*.csv') and file 4 is .load('file:///home/path/NYCweather/data2015/*.csv'). How do I import multiple paths at the same time to get one dataframe? Do I need to store them all individually as dataframes and then join them together within PySpark? (You may assume they all CSVs have the same schema)
Suppose it is November 2014 now. What if I want to run the analysis again, but on the "most recent data" run e.g. dec14 when it is December 2014? For example, I want to load in file 2: .load('file:///home/path/datafolder/data2014/dec14/*.csv') in December 14 and use this file: .load('file:///home/path/datafolder/data2014/nov14/*.csv') for the original analysis. Is there a way to schedule the Jupyter notebook (or similar) to update the load path and import the latest run (in this case 'nov14' would be replaced by 'dec14' and then 'jan15' etc).
I had a look through the previous questions but was unable to find an answer given this is AWS / PySpark integration specific.
Thank you in advance for the help!
[Background: I have been given access to many S3 buckets from various teams containing various big data sets. Copying it over to my S3 bucket, then building a Jupyter notebook seems like a lot more work than just pulling in the data directly from their bucket and building a model / table / etc ontop of it and saving the processed output into a database. Hence I am posting the questions above. If my thinking is completely wrong, please stop me! :)]
|
[
"You can read in multiple paths with wildcards as long as the files are all in the same format.\nIn your example:\n.load('file:///home/path/SFweather/data2014/*.csv')\n.load('file:///home/path/SFweather/data2015/*.csv')\n.load('file:///home/path/NYCweather/data2014/*.csv')\n.load('file:///home/path/NYCweather/data2015/*.csv')\n\nYou could replace the 4 load statements above with the following path to read all csv's in at once to one dataframe:\n.load('file:///home/path/*/*/*.csv')\n\nIf you want to be more specific in order to avoid reading in certain files/folders, you can do the following:\n.load('file:///home/path/[SF|NYC]weather/data201[4|5]/*.csv')\n\n",
"You can load multiple paths at once using lists of pattern strings. The pyspark.sql.DataFrameReader.load method accepts a list of path strings, which is especially helpful if you can't express all of the paths you want to load using a single Hadoop glob pattern:\n?\n Matches any single character.\n\n*\n Matches zero or more characters.\n\n[abc]\n Matches a single character from character set {a,b,c}.\n\n[a-b]\n Matches a single character from the character range {a...b}.\n Note that character a must be lexicographically less than or\n equal to character b.\n\n[^a]\n Matches a single character that is not from character set or\n range {a}. Note that the ^ character must occur immediately\n to the right of the opening bracket.\n\n\\c\n Removes (escapes) any special meaning of character c.\n\n{ab,cd}\n Matches a string from the string set {ab, cd}\n\n{ab,c{de,fh}}\n Matches a string from the string set {ab, cde, cfh}\n\nFor example, if you want to load the following paths:\n[\n 's3a://bucket/prefix/key=1/year=2010/*.csv',\n 's3a://bucket/prefix/key=1/year=2011/*.csv',\n 's3a://bucket/prefix/key=2/year=2020/*.csv',\n 's3a://bucket/prefix/key=2/year=2021/*.csv',\n]\n\nYou could reduce these to two path patterns,\n\ns3a://bucket/prefix/key=1/year=201[0-1]/*.csv and\ns3a://bucket/prefix/key=2/year=202[0-1]/*.csv,\n\nand call load() twice. You could go further and reduce these to a single pattern string using {ab,cd} alternation, but I think the most readable way to express paths like these using glob patterns with a single call to load() is to pass a list of path patterns:\nspark.read.format('csv').load(\n [\n 's3a://bucket/prefix/key=1/year=201[0-1]/*.csv',\n 's3a://bucket/prefix/key=2/year=202[0-1]/*.csv',\n ]\n)\n\nFor the paths you listed in your issue № 1, you can express all four with a single pattern string:\n'file:///home/path/{NY,SF}weather/data201[45]/*.csv'\n\nFor your issue № 2, you can write logic to construct the paths you want to load.\n"
] |
[
7,
0
] |
[] |
[] |
[
"amazon_s3",
"jupyter_notebook",
"pyspark",
"python"
] |
stackoverflow_0046240271_amazon_s3_jupyter_notebook_pyspark_python.txt
|
Q:
Get Youtube's most replayed data through web scraping
I want to get data out of youtube's "heat-map" feature, which is present in videos with certain features. This is an example. I want to retrieve this data somehow yet Youtube API's don't provide it and, this api doesn't always work. I'm aware they probably use the same approach, but I want to be able to have a reliable source of information. As of this approach (web-scrapping), I have tried using selenium, with the XPath of the element (you can find in the html of the video if you search for the class ytp-heat-map-path, like this):
driver = webdriver.Firefox()
driver.get("https://www.youtube.com/watch?v=09wcDevb1q4")
while len(driver.find_elements(By.XPATH,"/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div/ytd-player/div/div/div[31]/div[1]/div[1]/div[2]/svg/defs/clipPath/path")) == 0:
pass
a = driver.find_element(By.XPATH,"/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div/ytd-player/div/div/div[31]/div[1]/div[1]/div[2]/svg/defs/clipPath/path")
I have also tried with beautifulSoup, finding the class:
mydivs = soup.find_all("path", {"class": "ytp-heat-map-path"})
None of them can find the data. I'm happy to find a solution to this with web scrapping or any other method. Thanks.
A:
That desired data is under an attribute value of d with path tag. So you can try the next example.
from selenium import webdriver
import time
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.service import Service
#You change this portion into Firefox instead
webdriver_service = Service("./chromedriver")
driver = webdriver.Chrome(service=webdriver_service)
driver.get('https://www.youtube.com/watch?v=09wcDevb1q4')
driver.maximize_window()
time.sleep(8)
soup = BeautifulSoup(driver.page_source,"html.parser")
mydivs = soup.find("path", {"class": "ytp-heat-map-path"}).get('d')
print(mydivs)
Output:
M 0.0,100.0 C 1.0,87.5 2.0,42.2 5.0,37.6 C 8.0,33.1 11.0,69.1 15.0,77.3 C 19.0,85.6 21.0,79.1 25.0,78.8 C 29.0,78.5
31.0,74.3 35.0,75.7 C 39.0,77.1 41.0,82.9 45.0,85.8 C 49.0,88.6 51.0,89.2 55.0,90.0 C 59.0,90.8 61.0,90.0 65.0,90.0
C 69.0,90.0 71.0,90.0 75.0,90.0 C 79.0,90.0 81.0,90.0 85.0,90.0 C 89.0,90.0 91.0,90.0 95.0,90.0 C 99.0,90.0 101.0,90.0 105.0,90.0 C 109.0,90.0 111.0,90.0 115.0,90.0 C 119.0,90.0 121.0,90.0 125.0,90.0 C 129.0,90.0 131.0,90.0 135.0,90.0 C 139.0,90.0 141.0,90.0 145.0,90.0 C 149.0,90.0 151.0,90.0 155.0,90.0 C 159.0,90.0 161.0,90.0 165.0,90.0 C 169.0,90.0 171.0,90.7 175.0,90.0 C 179.0,89.3 181.0,88.3 185.0,86.6 C 189.0,84.9 191.0,82.1 195.0,81.7 C 199.0,81.3 201.0,84.4 205.0,84.6 C 209.0,84.8 211.0,83.9 215.0,82.6 C 219.0,81.4 221.0,79.8 225.0,78.3 C 229.0,76.7 231.0,73.5 235.0,74.9 C 239.0,76.3 241.0,82.4 245.0,85.1 C 249.0,87.9 251.0,87.9 255.0,88.8 C 259.0,89.8 261.0,89.5 265.0,89.7 C 269.0,89.9 271.0,90.1 275.0,90.0 C 279.0,89.9 281.0,89.3 285.0,89.1 C 289.0,89.0 291.0,89.1 295.0,89.3 C 299.0,89.5 301.0,89.9 305.0,90.0 C 309.0,90.1 311.0,90.9 315.0,89.8 C 319.0,88.6 321.0,84.5 325.0,84.3 C 329.0,84.1 331.0,87.5 335.0,88.6 C 339.0,89.8 341.0,91.0 345.0,90.0 C 349.0,89.0 351.0,85.9 355.0,83.8 C 359.0,81.7 361.0,78.8 365.0,79.5 C 369.0,80.2 371.0,85.2 375.0,87.3 C 379.0,89.4 381.0,89.5 385.0,90.0 C 389.0,90.5 391.0,90.0 395.0,90.0 C 399.0,90.0 401.0,90.2 405.0,89.9 C 409.0,89.5 411.0,88.5 415.0,88.4 C 419.0,88.3 421.0,89.1 425.0,89.5 C 429.0,89.8 431.0,89.9 435.0,90.0 C 439.0,90.1 441.0,90.0 445.0,90.0 C 449.0,90.0 451.0,91.3 455.0,90.0 C 459.0,88.7 461.0,87.1 465.0,83.4 C
469.0,79.7 471.0,73.7 475.0,71.6 C 479.0,69.6 481.0,71.7 485.0,73.0 C 489.0,74.4 491.0,76.7 495.0,78.3 C 499.0,79.9
501.0,80.9 505.0,80.9 C 509.0,80.9 511.0,77.9 515.0,78.3 C 519.0,78.8 521.0,81.3 525.0,83.2 C 529.0,85.2 531.0,86.7
535.0,88.1 C 539.0,89.5 541.0,89.6 545.0,90.0 C 549.0,90.4 551.0,90.5 555.0,90.0 C 559.0,89.5 561.0,87.5 565.0,87.4
C 569.0,87.2 571.0,88.7 575.0,89.2 C 579.0,89.8 581.0,89.8 585.0,90.0 C 589.0,90.2 591.0,90.1 595.0,90.0 C 599.0,89.9 601.0,89.5 605.0,89.5 C 609.0,89.5 611.0,89.9 615.0,90.0 C 619.0,90.1 621.0,90.0 625.0,90.0 C 629.0,90.0 631.0,90.0 635.0,90.0 C 639.0,90.0 641.0,90.6 645.0,90.0 C 649.0,89.4 651.0,87.7 655.0,87.2 C 659.0,86.7 661.0,86.8 665.0,87.3 C 669.0,87.9 671.0,89.5 675.0,90.0 C 679.0,90.5 681.0,90.4 685.0,90.0 C 689.0,89.6 691.0,89.1 695.0,88.1 C 699.0,87.1 701.0,86.5 705.0,85.0 C 709.0,83.5 711.0,81.4 715.0,80.5 C 719.0,79.6 721.0,80.6 725.0,80.5 C 729.0,80.4 731.0,80.5 735.0,80.0 C 739.0,79.5 741.0,78.3 745.0,78.2 C 749.0,78.1 751.0,78.8 755.0,79.5 C 759.0,80.2 761.0,79.7 765.0,81.8 C 769.0,83.9 771.0,88.4 775.0,90.0 C 779.0,91.6 781.0,90.0 785.0,90.0 C 789.0,90.0 791.0,90.0 795.0,90.0 C 799.0,90.0 801.0,90.0 805.0,90.0 C 809.0,90.0 811.0,90.0 815.0,90.0 C 819.0,90.0 821.0,90.3 825.0,90.0 C 829.0,89.7 831.0,90.8 835.0,88.7 C 839.0,86.6 841.0,82.7 845.0,79.5 C 849.0,76.4 851.0,74.5 855.0,73.0 C 859.0,71.5 861.0,72.3 865.0,72.0 C 869.0,71.6 871.0,70.4 875.0,71.1 C 879.0,71.8 881.0,77.0 885.0,75.6 C 889.0,74.2 891.0,74.0 895.0,64.3 C 899.0,54.6 901.0,39.9 905.0,27.1 C 909.0,14.2 911.0,-0.4 915.0,0.0 C 919.0,0.4 921.0,15.3 925.0,29.2 C 929.0,43.1 931.0,60.0 935.0,69.6 C 939.0,79.3 941.0,75.1 945.0,77.5 C 949.0,79.8 951.0,79.9 955.0,81.3 C 959.0,82.6 961.0,82.4 965.0,84.1 C 969.0,85.8 971.0,88.8 975.0,90.0 C 979.0,91.2 981.0,90.4 985.0,90.0 C 989.0,89.6 992.0,88.2 995.0,87.8 C 998.0,87.3 999.0,85.3 1000.0,87.8 C 1001.0,90.2 1000.0,97.6 1000.0,100.0
A:
I want to be able to have a reliable source of information
Note that by web-scraping you can't have a better stability than my open-source API you are referring to. I guess the stability issue you are referring to is that when web-scraping is abused, YouTube servers suspend temporarily your ability to retrieve the most replayed data.
As far as I know nobody using their own instance of my API for their own private usage have faced this issue. So I guess you only used the official instance of my API which, by its numerous users, abuses from YouTube UI servers, and so it is regularly suspended.
So the solutions are:
To try with your own private instance of my API.
Otherwise just directly parse the ytInitialData JavaScript variable in the HTML, as I did in my API, that way you don't need a JavaScript interpreter such as Selenium.
A:
The way to get it through the ytInitialData JavaScript variable in the HTML:
soup = BS(requests.get(url).text, "html.parser")
data = re.search(r"var ytInitialData = ({.*?});", soup.prettify()).group(1)
data = json.loads(data)
data['playerOverlays']['playerOverlayRenderer']['decoratedPlayerBarRenderer']['decoratedPlayerBarRenderer']['playerBar']['multiMarkersPlayerBarRenderer']['markersMap']
|
Get Youtube's most replayed data through web scraping
|
I want to get data out of youtube's "heat-map" feature, which is present in videos with certain features. This is an example. I want to retrieve this data somehow yet Youtube API's don't provide it and, this api doesn't always work. I'm aware they probably use the same approach, but I want to be able to have a reliable source of information. As of this approach (web-scrapping), I have tried using selenium, with the XPath of the element (you can find in the html of the video if you search for the class ytp-heat-map-path, like this):
driver = webdriver.Firefox()
driver.get("https://www.youtube.com/watch?v=09wcDevb1q4")
while len(driver.find_elements(By.XPATH,"/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div/ytd-player/div/div/div[31]/div[1]/div[1]/div[2]/svg/defs/clipPath/path")) == 0:
pass
a = driver.find_element(By.XPATH,"/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div/ytd-player/div/div/div[31]/div[1]/div[1]/div[2]/svg/defs/clipPath/path")
I have also tried with beautifulSoup, finding the class:
mydivs = soup.find_all("path", {"class": "ytp-heat-map-path"})
None of them can find the data. I'm happy to find a solution to this with web scrapping or any other method. Thanks.
|
[
"That desired data is under an attribute value of d with path tag. So you can try the next example.\nfrom selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium.webdriver.chrome.service import Service\n\n#You change this portion into Firefox instead\nwebdriver_service = Service(\"./chromedriver\") \ndriver = webdriver.Chrome(service=webdriver_service)\n\n\ndriver.get('https://www.youtube.com/watch?v=09wcDevb1q4')\ndriver.maximize_window()\ntime.sleep(8)\n\n\nsoup = BeautifulSoup(driver.page_source,\"html.parser\")\n\nmydivs = soup.find(\"path\", {\"class\": \"ytp-heat-map-path\"}).get('d')\nprint(mydivs)\n\nOutput:\nM 0.0,100.0 C 1.0,87.5 2.0,42.2 5.0,37.6 C 8.0,33.1 11.0,69.1 15.0,77.3 C 19.0,85.6 21.0,79.1 25.0,78.8 C 29.0,78.5 \n31.0,74.3 35.0,75.7 C 39.0,77.1 41.0,82.9 45.0,85.8 C 49.0,88.6 51.0,89.2 55.0,90.0 C 59.0,90.8 61.0,90.0 65.0,90.0 \nC 69.0,90.0 71.0,90.0 75.0,90.0 C 79.0,90.0 81.0,90.0 85.0,90.0 C 89.0,90.0 91.0,90.0 95.0,90.0 C 99.0,90.0 101.0,90.0 105.0,90.0 C 109.0,90.0 111.0,90.0 115.0,90.0 C 119.0,90.0 121.0,90.0 125.0,90.0 C 129.0,90.0 131.0,90.0 135.0,90.0 C 139.0,90.0 141.0,90.0 145.0,90.0 C 149.0,90.0 151.0,90.0 155.0,90.0 C 159.0,90.0 161.0,90.0 165.0,90.0 C 169.0,90.0 171.0,90.7 175.0,90.0 C 179.0,89.3 181.0,88.3 185.0,86.6 C 189.0,84.9 191.0,82.1 195.0,81.7 C 199.0,81.3 201.0,84.4 205.0,84.6 C 209.0,84.8 211.0,83.9 215.0,82.6 C 219.0,81.4 221.0,79.8 225.0,78.3 C 229.0,76.7 231.0,73.5 235.0,74.9 C 239.0,76.3 241.0,82.4 245.0,85.1 C 249.0,87.9 251.0,87.9 255.0,88.8 C 259.0,89.8 261.0,89.5 265.0,89.7 C 269.0,89.9 271.0,90.1 275.0,90.0 C 279.0,89.9 281.0,89.3 285.0,89.1 C 289.0,89.0 291.0,89.1 295.0,89.3 C 299.0,89.5 301.0,89.9 305.0,90.0 C 309.0,90.1 311.0,90.9 315.0,89.8 C 319.0,88.6 321.0,84.5 325.0,84.3 C 329.0,84.1 331.0,87.5 335.0,88.6 C 339.0,89.8 341.0,91.0 345.0,90.0 C 349.0,89.0 351.0,85.9 355.0,83.8 C 359.0,81.7 361.0,78.8 365.0,79.5 C 369.0,80.2 371.0,85.2 375.0,87.3 C 379.0,89.4 381.0,89.5 385.0,90.0 C 389.0,90.5 391.0,90.0 395.0,90.0 C 399.0,90.0 401.0,90.2 405.0,89.9 C 409.0,89.5 411.0,88.5 415.0,88.4 C 419.0,88.3 421.0,89.1 425.0,89.5 C 429.0,89.8 431.0,89.9 435.0,90.0 C 439.0,90.1 441.0,90.0 445.0,90.0 C 449.0,90.0 451.0,91.3 455.0,90.0 C 459.0,88.7 461.0,87.1 465.0,83.4 C \n469.0,79.7 471.0,73.7 475.0,71.6 C 479.0,69.6 481.0,71.7 485.0,73.0 C 489.0,74.4 491.0,76.7 495.0,78.3 C 499.0,79.9 \n501.0,80.9 505.0,80.9 C 509.0,80.9 511.0,77.9 515.0,78.3 C 519.0,78.8 521.0,81.3 525.0,83.2 C 529.0,85.2 531.0,86.7 \n535.0,88.1 C 539.0,89.5 541.0,89.6 545.0,90.0 C 549.0,90.4 551.0,90.5 555.0,90.0 C 559.0,89.5 561.0,87.5 565.0,87.4 \nC 569.0,87.2 571.0,88.7 575.0,89.2 C 579.0,89.8 581.0,89.8 585.0,90.0 C 589.0,90.2 591.0,90.1 595.0,90.0 C 599.0,89.9 601.0,89.5 605.0,89.5 C 609.0,89.5 611.0,89.9 615.0,90.0 C 619.0,90.1 621.0,90.0 625.0,90.0 C 629.0,90.0 631.0,90.0 635.0,90.0 C 639.0,90.0 641.0,90.6 645.0,90.0 C 649.0,89.4 651.0,87.7 655.0,87.2 C 659.0,86.7 661.0,86.8 665.0,87.3 C 669.0,87.9 671.0,89.5 675.0,90.0 C 679.0,90.5 681.0,90.4 685.0,90.0 C 689.0,89.6 691.0,89.1 695.0,88.1 C 699.0,87.1 701.0,86.5 705.0,85.0 C 709.0,83.5 711.0,81.4 715.0,80.5 C 719.0,79.6 721.0,80.6 725.0,80.5 C 729.0,80.4 731.0,80.5 735.0,80.0 C 739.0,79.5 741.0,78.3 745.0,78.2 C 749.0,78.1 751.0,78.8 755.0,79.5 C 759.0,80.2 761.0,79.7 765.0,81.8 C 769.0,83.9 771.0,88.4 775.0,90.0 C 779.0,91.6 781.0,90.0 785.0,90.0 C 789.0,90.0 791.0,90.0 795.0,90.0 C 799.0,90.0 801.0,90.0 805.0,90.0 C 809.0,90.0 811.0,90.0 815.0,90.0 C 819.0,90.0 821.0,90.3 825.0,90.0 C 829.0,89.7 831.0,90.8 835.0,88.7 C 839.0,86.6 841.0,82.7 845.0,79.5 C 849.0,76.4 851.0,74.5 855.0,73.0 C 859.0,71.5 861.0,72.3 865.0,72.0 C 869.0,71.6 871.0,70.4 875.0,71.1 C 879.0,71.8 881.0,77.0 885.0,75.6 C 889.0,74.2 891.0,74.0 895.0,64.3 C 899.0,54.6 901.0,39.9 905.0,27.1 C 909.0,14.2 911.0,-0.4 915.0,0.0 C 919.0,0.4 921.0,15.3 925.0,29.2 C 929.0,43.1 931.0,60.0 935.0,69.6 C 939.0,79.3 941.0,75.1 945.0,77.5 C 949.0,79.8 951.0,79.9 955.0,81.3 C 959.0,82.6 961.0,82.4 965.0,84.1 C 969.0,85.8 971.0,88.8 975.0,90.0 C 979.0,91.2 981.0,90.4 985.0,90.0 C 989.0,89.6 992.0,88.2 995.0,87.8 C 998.0,87.3 999.0,85.3 1000.0,87.8 C 1001.0,90.2 1000.0,97.6 1000.0,100.0\n\n",
"\nI want to be able to have a reliable source of information\n\nNote that by web-scraping you can't have a better stability than my open-source API you are referring to. I guess the stability issue you are referring to is that when web-scraping is abused, YouTube servers suspend temporarily your ability to retrieve the most replayed data.\nAs far as I know nobody using their own instance of my API for their own private usage have faced this issue. So I guess you only used the official instance of my API which, by its numerous users, abuses from YouTube UI servers, and so it is regularly suspended.\nSo the solutions are:\n\nTo try with your own private instance of my API.\nOtherwise just directly parse the ytInitialData JavaScript variable in the HTML, as I did in my API, that way you don't need a JavaScript interpreter such as Selenium.\n\n",
"The way to get it through the ytInitialData JavaScript variable in the HTML:\nsoup = BS(requests.get(url).text, \"html.parser\")\ndata = re.search(r\"var ytInitialData = ({.*?});\", soup.prettify()).group(1)\ndata = json.loads(data)\ndata['playerOverlays']['playerOverlayRenderer']['decoratedPlayerBarRenderer']['decoratedPlayerBarRenderer']['playerBar']['multiMarkersPlayerBarRenderer']['markersMap']\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"python",
"web_scraping",
"youtube",
"youtube_api"
] |
stackoverflow_0074464780_python_web_scraping_youtube_youtube_api.txt
|
Q:
Pandas; Trying to split a string in a column with | , and then list all strings, removing all duplicates
I'm working on a data frame for a made up TV show. In this dataframe, are columns: "Season","EpisodeTitle","About","Ratings","Votes","Viewership","Duration","Date","GuestStars",Director","Writers", With rows listed as ascending numerical values.
In this data frame, my problem relates to two columns; 'Writers' and 'Viewership'. In the Writers column, some of the columns have multiple writers, separated with " | ". In the Viewership column, each column has a float value between 1 and 23, with a max of 2 decimal places.
Here's a condensed example of the data frame I'm working with. I am trying to filter the "Writers" column, and then determine the total average viewership for each individual writer:
df = pd.DataFrame({'Writers' : ['John Doe','Jennifer Hopkins | John Doe','Ginny Alvera','Binny Glasglow | Jennifer Hopkins','Jennifer Hopkins','Sam Write','Lawrence Fieldings | Ginny Alvera | John Doe','John Doe'], 'Viewership' : '3.4','5.26','22.82','13.5','4.45','7.44','9'})
The solution I came up with to split the column strings:
df["Writers"]= df["Writers"].str.split('|', expand=False)
This does split the string, but in some cases will leave whitespace before and after commas. I need the whitespace removed, and then I need to list all writers, but only list each writer once.
Second, for each individual writer, I would like to have columns stating their total average viewership, or a list of each writer, stating what their total average viewership was for all episodes they worked on:
["John Doe : 15" , "Jennifer Hopkins : 7.54" , "Lawrence Fieldings : 3.7"]
This is my first post here, I really appreciate any help!
A:
# I believe in newer versions of pandas you can split cells to multiple rows like this
# here is a reference https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.25.0.html#series-explode-to-split-list-like-values-to-rows
df2 =df.assign(Writers=df.Writers.str.split('|')).explode('Writers').reset_index(drop=True)
#to remove whitespaces just use this
#this will remove white spaces at the beginning and end of every cell in that column
df2['Writers'] = df2['Writers'].str.strip()
#if you want to remove duplicates, then do a groupby
# this will combine (sum) duplicate, you can use any other mathematical aggregation
# function as well (you can replace sum() by mean())
df2.groupby(['writers']).sum()
|
Pandas; Trying to split a string in a column with | , and then list all strings, removing all duplicates
|
I'm working on a data frame for a made up TV show. In this dataframe, are columns: "Season","EpisodeTitle","About","Ratings","Votes","Viewership","Duration","Date","GuestStars",Director","Writers", With rows listed as ascending numerical values.
In this data frame, my problem relates to two columns; 'Writers' and 'Viewership'. In the Writers column, some of the columns have multiple writers, separated with " | ". In the Viewership column, each column has a float value between 1 and 23, with a max of 2 decimal places.
Here's a condensed example of the data frame I'm working with. I am trying to filter the "Writers" column, and then determine the total average viewership for each individual writer:
df = pd.DataFrame({'Writers' : ['John Doe','Jennifer Hopkins | John Doe','Ginny Alvera','Binny Glasglow | Jennifer Hopkins','Jennifer Hopkins','Sam Write','Lawrence Fieldings | Ginny Alvera | John Doe','John Doe'], 'Viewership' : '3.4','5.26','22.82','13.5','4.45','7.44','9'})
The solution I came up with to split the column strings:
df["Writers"]= df["Writers"].str.split('|', expand=False)
This does split the string, but in some cases will leave whitespace before and after commas. I need the whitespace removed, and then I need to list all writers, but only list each writer once.
Second, for each individual writer, I would like to have columns stating their total average viewership, or a list of each writer, stating what their total average viewership was for all episodes they worked on:
["John Doe : 15" , "Jennifer Hopkins : 7.54" , "Lawrence Fieldings : 3.7"]
This is my first post here, I really appreciate any help!
|
[
"# I believe in newer versions of pandas you can split cells to multiple rows like this\n# here is a reference https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.25.0.html#series-explode-to-split-list-like-values-to-rows\n\ndf2 =df.assign(Writers=df.Writers.str.split('|')).explode('Writers').reset_index(drop=True)\n\n#to remove whitespaces just use this\n#this will remove white spaces at the beginning and end of every cell in that column\ndf2['Writers'] = df2['Writers'].str.strip()\n\n#if you want to remove duplicates, then do a groupby\n# this will combine (sum) duplicate, you can use any other mathematical aggregation\n# function as well (you can replace sum() by mean())\ndf2.groupby(['writers']).sum()\n\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"iteration",
"multiple_columns",
"pandas",
"python"
] |
stackoverflow_0074554643_dataframe_iteration_multiple_columns_pandas_python.txt
|
Q:
Python traitlets package warring and permission denied in vscode interactive windows
OS: Arch linux(termux proot)
Python version: 3.10.8
My error message as follow
Visual Studio Code (1.73.1, undefined, desktop)
Jupyter Extension Version: 2022.9.1303220346.
Python Extension Version: 2022.18.2.
Workspace folder /home/jack/Documents/Medical-segmentation
info 15:00:11.430: ZMQ install verified.
User belongs to experiment group 'jupyterTestcf'
User belongs to experiment group 'jupyterEnhancedDataViewer'
info 15:00:12.217: LSP Notebooks experiment is disabled -- not in treatment group
info 15:00:13.731: Got empty env vars with python /bin/python in 1275ms
info 15:00:13.731: Got env vars ourselves faster /bin/python with env var count 59 in 1276ms
info 15:00:13.768: Process Execution: > /bin/python -m pip list
> /bin/python -m pip list
info 15:00:22.102: Starting interactive window for resource '/home/jack/Documents/Medical-segmentation/snakes/example2.py'
info 15:00:22.512: Preferred Remote kernel for Interactive-1.interactive is undefined
info 15:00:25.004: Process Execution: > /bin/python ~/.vscode/extensions/ms-toolsai.jupyter-2022.9.1303220346/pythonFiles/normalizeSelection.py
> /bin/python ~/.vscode/extensions/ms-toolsai.jupyter-2022.9.1303220346/pythonFiles/normalizeSelection.py
info 15:00:25.022: Starting Jupyter Session startUsingPythonInterpreter, .jvsc74a57bd0e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a./bin/python./bin/python.-m#ipykernel_launcher (Python Path: , EnvType: Global, EnvName: '', Version: 3.10.8) for 'Interactive-1.interactive' (disableUI=false)
info 15:00:25.024: Computing working directory for resource '/home/jack/Documents/Medical-segmentation/snakes/example2.py'
info 15:00:25.054: Got env vars ourselves faster /bin/python with env var count 59 in 2ms
info 15:00:25.108: Process Execution: > /bin/python -c "import ipykernel; print(ipykernel.__version__); print("5dc3a68c-e34e-4080-9c3e-2a532b2ccb4d"); print(ipykernel.__file__)"
> /bin/python -c "import ipykernel; print(ipykernel.__version__); print("5dc3a68c-e34e-4080-9c3e-2a532b2ccb4d"); print(ipykernel.__file__)"
info 15:00:25.266: Got env vars ourselves faster /bin/python with env var count 59 in 14ms
info 15:00:25.266: Got env vars ourselves faster /bin/python with env var count 59 in 6ms
info 15:00:25.308: Process Execution: > /bin/python -m ipykernel_launcher --ip=127.0.0.1 --stdin=9003 --control=9001 --hb=9000 --Session.signature_scheme="hmac-sha256" --Session.key=b"a946baa0-e0d4-41d4-b72d-1eed7330e6f9" --shell=9002 --transport="tcp" --iopub=9004 --f=/home/jack/.local/share/jupyter/runtime/kernel-v2-32230pKMrdOglR18w.json
> /bin/python -m ipykernel_launcher --ip=127.0.0.1 --stdin=9003 --control=9001 --hb=9000 --Session.signature_scheme="hmac-sha256" --Session.key=b"a946baa0-e0d4-41d4-b72d-1eed7330e6f9" --shell=9002 --transport="tcp" --iopub=9004 --f=/home/jack/.local/share/jupyter/runtime/kernel-v2-32230pKMrdOglR18w.json
info 15:00:25.308: Process Execution: cwd: ~/Documents/Medical-segmentation/snakes
cwd: ~/Documents/Medical-segmentation/snakes
info 15:00:25.823: Registering dummy command feature
info 15:00:27.946: ipykernel version & path 6.18.0, /usr/lib/python3.10/site-packages/ipykernel/__init__.py for /bin/python
info 15:00:29.175: Got empty env vars with python /bin/python in 4123ms
info 15:00:29.176: Got empty env vars with python /bin/python in 3924ms
info 15:00:29.176: Got empty env vars with python /bin/python in 3916ms
warn 15:00:33.920: StdErr from Kernel Process /usr/lib/python3.10/site-packages/traitlets/traitlets.py:2412: FutureWarning: Supporting extra quotes around strings is deprecated in traitlets 5.0. You can use 'hmac-sha256' instead of '"hmac-sha256"' if you require traitlets >=5.
warn(
warn 15:00:33.921: StdErr from Kernel Process /usr/lib/python3.10/site-packages/traitlets/traitlets.py:2366: FutureWarning: Supporting extra quotes around Bytes is deprecated in traitlets 5.0. Use 'a946baa0-e0d4-41d4-b72d-1eed7330e6f9' instead of 'b"a946baa0-e0d4-41d4-b72d-1eed7330e6f9"'.
warn(
warn 15:00:33.964: StdErr from Kernel Process Permission denied (src/ip_resolver.cpp:542)
error 15:00:33.979: Disposing kernel process due to an error o [Error]: The kernel died. Error: /usr/lib/python3.10/site-packages/traitlets/traitlets.py:2412: FutureWarning: Supporting extra quotes around strings is deprecated in traitlets 5.0. You can use 'hmac-sha256' instead of '"hmac-sha256"' if you require traitlets >=5.
warn(
/usr/lib/python3.10/site-packages/traitlets/traitlets.py:2366: FutureWarning: Supporting extra quotes around Bytes is deprecated in traitlets 5.0. Use 'a946baa0-e0d4-41d4-b72d-1eed7330e6f9' instead of 'b"a946baa0-e0d4-41d4-b72d-1eed7330e6f9"'.
warn(
Permission denied (src/ip_resolver.cpp:542)... View Jupyter [log](command:jupyter.viewOutput) for further details.
at ChildProcess.<anonymous> (/home/jack/.vscode/extensions/ms-toolsai.jupyter-2022.9.1303220346/out/extension.node.js:2:2195101)
at ChildProcess.emit (node:events:538:35)
at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12) {
category: 'kerneldied',
kernelConnectionMetadata: {
kind: 'startUsingPythonInterpreter',
kernelSpec: {
specFile: '/home/jack/.vscode/extensions/ms-toolsai.jupyter-2022.9.1303220346/temp/jupyter/kernels/python3108jvsc74a57bd0e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a/kernel.json',
interpreterPath: '/bin/python',
isRegisteredByVSC: 'registeredByNewVersionOfExt',
name: 'python3108jvsc74a57bd0e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a',
argv: [Array],
language: 'python',
executable: 'python',
display_name: 'Python 3.10.8 64-bit',
metadata: [Object],
env: {}
},
I encounter this error message but I does not have any issue in another termux proot system. I remove all python and packages and reinstall. It didn't work for me.
11/24 updated:
It's weird because I look to another system by using pip list. It's the same version with I currently use system.
Package Version
---------------------- -----------
aiohttp 3.8.3
aiohttp-socks 0.7.1
aiorpcX 0.22.1
aiosignal 1.2.0
anyio 3.6.2
appdirs 1.4.4
argon2-cffi 21.3.0
argon2-cffi-bindings 21.2.0
asttokens 2.1.0
async-generator 1.10
async-timeout 4.0.2
attrs 22.1.0
autocommand 2.2.2
Babel 2.11.0
backcall 0.2.0
beautifulsoup4 4.11.1
bitstring 3.1.9
black 22.10.0
bleach 5.0.1
build 0.9.0
certifi 2022.9.24
cffi 1.15.1
chardet 5.0.0
charset-normalizer 3.0.0
click 8.1.3
codespell 0.0.0
comm 0.1.0
commonmark 0.9.1
contourpy 1.0.6
cryptography 38.0.1
cycler 0.11.0
Cython 0.29.32
debugpy 1.6.3
decorator 5.1.1
defusedxml 0.7.1
deprecation 2.1.0
dnspython 2.2.1
docopt 0.6.2
docutils 0.19
ecdsa 0.18.0
Electrum 4.3.1
entrypoints 0.4
executing 1.2.0
fastjsonschema 2.16.2
flake8 5.0.4
flake8-black 0.3.3
flake8-isort 5.0.0
fonttools 4.38.0
frozenlist 1.3.1
future 0.18.2
greenlet 1.1.3.post0
idna 3.4
imageio 2.22.4
imutils 0.5.4
inflect 6.0.2
installer 0.5.1
ipykernel 6.18.0
ipython 8.6.0
ipython-genutils 0.2.0
isort 5.10.1
jaraco.context 4.1.2
jaraco.functools 3.5.2
jaraco.text 3.11.0
jedi 0.18.1
Jinja2 3.1.2
json5 0.9.10
jsonrpclib-pelix 0.4.3.2
jsonschema 4.17.1
jupyter_client 7.4.7
jupyter_core 5.0.0
jupyter_packaging 0.12.3
jupyter-server 1.23.3
jupyterlab 3.5.0
jupyterlab-pygments 0.2.2
jupyterlab_server 2.16.3
kiwisolver 1.4.4
lxml 4.9.1
mackup 0.8.36
markdown-it-py 2.1.0
MarkupSafe 2.1.1
matplotlib 3.6.2
matplotlib-inline 0.1.6
mccabe 0.7.0
mdurl 0.1.2
mistune 2.0.4
more-itertools 9.0.0
msgpack 1.0.4
multidict 6.0.2
mypy-extensions 0.4.3
mysql-connector-python 8.0.31
nbclassic 0.4.8
nbclient 0.7.0
nbconvert 7.2.5
nbformat 5.7.0
nest-asyncio 1.5.6
networkx 2.8.8
nibabel 4.0.2
notebook 6.5.2
notebook_shim 0.2.2
numpy 1.23.4
ordered-set 4.1.0
packaging 21.3
pandas 1.5.1
pandocfilters 1.5.0
parso 0.8.3
pathspec 0.10.1
pbkdf2 1.3
pep517 0.13.0
pexpect 4.8.0
pickleshare 0.7.5
pikaur 1.13
Pillow 9.3.0
pip 22.3
platformdirs 2.5.2
pluggy 1.0.0
ply 3.11
portalocker 2.6.0
progressbar2 4.2.0
prometheus-client 0.15.0
prompt-toolkit 3.0.33
protobuf 4.21.7
psutil 5.9.4
ptyprocess 0.7.0
pure-eval 0.2.2
pyaes 1.6.1
pyalpm 0.10.6
pycodestyle 2.9.1
pycparser 2.21
pycryptodomex 3.12.0
pydantic 1.10.2
pyflakes 2.5.0
Pygments 2.13.0
pynvim 0.4.3
pyparsing 3.0.9
PyQt5 5.15.7
PyQt5-sip 12.11.0
pyrsistent 0.19.2
PySocks 1.7.1
python-dateutil 2.8.2
python-dotenv 0.21.0
python-lsp-jsonrpc 1.0.0
python-lsp-server 1.5.0
python-socks 2.0.3
python-utils 3.4.5
pytz 2022.5
pytz-deprecation-shim 0.1.0.post0
PyWavelets 1.4.1
pyzmq 24.0.1
qrcode 7.3.1
regex 2022.10.31
requests 2.28.1
requests-unixsocket 0.3.0
ruamel.yaml 0.17.21
ruamel.yaml.clib 0.2.7
scikit-image 0.19.3
scipy 1.9.3
Send2Trash 1.8.0
setuptools 63.2.0
Shapely 1.8.2
six 1.16.0
sniffio 1.3.0
soupsieve 2.3.2.post1
SQLAlchemy 1.4.43
stack-data 0.6.1
TBB 0.2
terminado 0.17.0
testpath 0.6.0
tifffile 2022.10.10
tinycss2 1.2.1
toml 0.10.2
tomli 2.0.1
tomlkit 0.11.6
tornado 6.2
traitlets 5.5.0
trove-classifiers 2022.10.19
typing_extensions 4.4.0
tzdata 2022.6
tzlocal 4.2
uc-micro-py 1.0.1
ujson 5.5.0
urllib3 1.26.12
validate-pyproject 0.10.1
wcwidth 0.2.5
webencodings 0.5.1
websocket-client 1.4.1
wheel 0.37.1
yarl 1.8.1
A:
Open your vscode and reinstall the Python and Jupyter Notebook extensions.
Reinstall ipykernel package in the terminal.
At the same time, this issue also proposes other solutions.
Added:
I encountered the same problem with traitlets==4.3.3. I updated it by using pip install traitlets and it's version is 5.5.0 to solve this problem.
|
Python traitlets package warring and permission denied in vscode interactive windows
|
OS: Arch linux(termux proot)
Python version: 3.10.8
My error message as follow
Visual Studio Code (1.73.1, undefined, desktop)
Jupyter Extension Version: 2022.9.1303220346.
Python Extension Version: 2022.18.2.
Workspace folder /home/jack/Documents/Medical-segmentation
info 15:00:11.430: ZMQ install verified.
User belongs to experiment group 'jupyterTestcf'
User belongs to experiment group 'jupyterEnhancedDataViewer'
info 15:00:12.217: LSP Notebooks experiment is disabled -- not in treatment group
info 15:00:13.731: Got empty env vars with python /bin/python in 1275ms
info 15:00:13.731: Got env vars ourselves faster /bin/python with env var count 59 in 1276ms
info 15:00:13.768: Process Execution: > /bin/python -m pip list
> /bin/python -m pip list
info 15:00:22.102: Starting interactive window for resource '/home/jack/Documents/Medical-segmentation/snakes/example2.py'
info 15:00:22.512: Preferred Remote kernel for Interactive-1.interactive is undefined
info 15:00:25.004: Process Execution: > /bin/python ~/.vscode/extensions/ms-toolsai.jupyter-2022.9.1303220346/pythonFiles/normalizeSelection.py
> /bin/python ~/.vscode/extensions/ms-toolsai.jupyter-2022.9.1303220346/pythonFiles/normalizeSelection.py
info 15:00:25.022: Starting Jupyter Session startUsingPythonInterpreter, .jvsc74a57bd0e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a./bin/python./bin/python.-m#ipykernel_launcher (Python Path: , EnvType: Global, EnvName: '', Version: 3.10.8) for 'Interactive-1.interactive' (disableUI=false)
info 15:00:25.024: Computing working directory for resource '/home/jack/Documents/Medical-segmentation/snakes/example2.py'
info 15:00:25.054: Got env vars ourselves faster /bin/python with env var count 59 in 2ms
info 15:00:25.108: Process Execution: > /bin/python -c "import ipykernel; print(ipykernel.__version__); print("5dc3a68c-e34e-4080-9c3e-2a532b2ccb4d"); print(ipykernel.__file__)"
> /bin/python -c "import ipykernel; print(ipykernel.__version__); print("5dc3a68c-e34e-4080-9c3e-2a532b2ccb4d"); print(ipykernel.__file__)"
info 15:00:25.266: Got env vars ourselves faster /bin/python with env var count 59 in 14ms
info 15:00:25.266: Got env vars ourselves faster /bin/python with env var count 59 in 6ms
info 15:00:25.308: Process Execution: > /bin/python -m ipykernel_launcher --ip=127.0.0.1 --stdin=9003 --control=9001 --hb=9000 --Session.signature_scheme="hmac-sha256" --Session.key=b"a946baa0-e0d4-41d4-b72d-1eed7330e6f9" --shell=9002 --transport="tcp" --iopub=9004 --f=/home/jack/.local/share/jupyter/runtime/kernel-v2-32230pKMrdOglR18w.json
> /bin/python -m ipykernel_launcher --ip=127.0.0.1 --stdin=9003 --control=9001 --hb=9000 --Session.signature_scheme="hmac-sha256" --Session.key=b"a946baa0-e0d4-41d4-b72d-1eed7330e6f9" --shell=9002 --transport="tcp" --iopub=9004 --f=/home/jack/.local/share/jupyter/runtime/kernel-v2-32230pKMrdOglR18w.json
info 15:00:25.308: Process Execution: cwd: ~/Documents/Medical-segmentation/snakes
cwd: ~/Documents/Medical-segmentation/snakes
info 15:00:25.823: Registering dummy command feature
info 15:00:27.946: ipykernel version & path 6.18.0, /usr/lib/python3.10/site-packages/ipykernel/__init__.py for /bin/python
info 15:00:29.175: Got empty env vars with python /bin/python in 4123ms
info 15:00:29.176: Got empty env vars with python /bin/python in 3924ms
info 15:00:29.176: Got empty env vars with python /bin/python in 3916ms
warn 15:00:33.920: StdErr from Kernel Process /usr/lib/python3.10/site-packages/traitlets/traitlets.py:2412: FutureWarning: Supporting extra quotes around strings is deprecated in traitlets 5.0. You can use 'hmac-sha256' instead of '"hmac-sha256"' if you require traitlets >=5.
warn(
warn 15:00:33.921: StdErr from Kernel Process /usr/lib/python3.10/site-packages/traitlets/traitlets.py:2366: FutureWarning: Supporting extra quotes around Bytes is deprecated in traitlets 5.0. Use 'a946baa0-e0d4-41d4-b72d-1eed7330e6f9' instead of 'b"a946baa0-e0d4-41d4-b72d-1eed7330e6f9"'.
warn(
warn 15:00:33.964: StdErr from Kernel Process Permission denied (src/ip_resolver.cpp:542)
error 15:00:33.979: Disposing kernel process due to an error o [Error]: The kernel died. Error: /usr/lib/python3.10/site-packages/traitlets/traitlets.py:2412: FutureWarning: Supporting extra quotes around strings is deprecated in traitlets 5.0. You can use 'hmac-sha256' instead of '"hmac-sha256"' if you require traitlets >=5.
warn(
/usr/lib/python3.10/site-packages/traitlets/traitlets.py:2366: FutureWarning: Supporting extra quotes around Bytes is deprecated in traitlets 5.0. Use 'a946baa0-e0d4-41d4-b72d-1eed7330e6f9' instead of 'b"a946baa0-e0d4-41d4-b72d-1eed7330e6f9"'.
warn(
Permission denied (src/ip_resolver.cpp:542)... View Jupyter [log](command:jupyter.viewOutput) for further details.
at ChildProcess.<anonymous> (/home/jack/.vscode/extensions/ms-toolsai.jupyter-2022.9.1303220346/out/extension.node.js:2:2195101)
at ChildProcess.emit (node:events:538:35)
at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12) {
category: 'kerneldied',
kernelConnectionMetadata: {
kind: 'startUsingPythonInterpreter',
kernelSpec: {
specFile: '/home/jack/.vscode/extensions/ms-toolsai.jupyter-2022.9.1303220346/temp/jupyter/kernels/python3108jvsc74a57bd0e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a/kernel.json',
interpreterPath: '/bin/python',
isRegisteredByVSC: 'registeredByNewVersionOfExt',
name: 'python3108jvsc74a57bd0e7370f93d1d0cde622a1f8e1c04877d8463912d04d973331ad4851f04de6915a',
argv: [Array],
language: 'python',
executable: 'python',
display_name: 'Python 3.10.8 64-bit',
metadata: [Object],
env: {}
},
I encounter this error message but I does not have any issue in another termux proot system. I remove all python and packages and reinstall. It didn't work for me.
11/24 updated:
It's weird because I look to another system by using pip list. It's the same version with I currently use system.
Package Version
---------------------- -----------
aiohttp 3.8.3
aiohttp-socks 0.7.1
aiorpcX 0.22.1
aiosignal 1.2.0
anyio 3.6.2
appdirs 1.4.4
argon2-cffi 21.3.0
argon2-cffi-bindings 21.2.0
asttokens 2.1.0
async-generator 1.10
async-timeout 4.0.2
attrs 22.1.0
autocommand 2.2.2
Babel 2.11.0
backcall 0.2.0
beautifulsoup4 4.11.1
bitstring 3.1.9
black 22.10.0
bleach 5.0.1
build 0.9.0
certifi 2022.9.24
cffi 1.15.1
chardet 5.0.0
charset-normalizer 3.0.0
click 8.1.3
codespell 0.0.0
comm 0.1.0
commonmark 0.9.1
contourpy 1.0.6
cryptography 38.0.1
cycler 0.11.0
Cython 0.29.32
debugpy 1.6.3
decorator 5.1.1
defusedxml 0.7.1
deprecation 2.1.0
dnspython 2.2.1
docopt 0.6.2
docutils 0.19
ecdsa 0.18.0
Electrum 4.3.1
entrypoints 0.4
executing 1.2.0
fastjsonschema 2.16.2
flake8 5.0.4
flake8-black 0.3.3
flake8-isort 5.0.0
fonttools 4.38.0
frozenlist 1.3.1
future 0.18.2
greenlet 1.1.3.post0
idna 3.4
imageio 2.22.4
imutils 0.5.4
inflect 6.0.2
installer 0.5.1
ipykernel 6.18.0
ipython 8.6.0
ipython-genutils 0.2.0
isort 5.10.1
jaraco.context 4.1.2
jaraco.functools 3.5.2
jaraco.text 3.11.0
jedi 0.18.1
Jinja2 3.1.2
json5 0.9.10
jsonrpclib-pelix 0.4.3.2
jsonschema 4.17.1
jupyter_client 7.4.7
jupyter_core 5.0.0
jupyter_packaging 0.12.3
jupyter-server 1.23.3
jupyterlab 3.5.0
jupyterlab-pygments 0.2.2
jupyterlab_server 2.16.3
kiwisolver 1.4.4
lxml 4.9.1
mackup 0.8.36
markdown-it-py 2.1.0
MarkupSafe 2.1.1
matplotlib 3.6.2
matplotlib-inline 0.1.6
mccabe 0.7.0
mdurl 0.1.2
mistune 2.0.4
more-itertools 9.0.0
msgpack 1.0.4
multidict 6.0.2
mypy-extensions 0.4.3
mysql-connector-python 8.0.31
nbclassic 0.4.8
nbclient 0.7.0
nbconvert 7.2.5
nbformat 5.7.0
nest-asyncio 1.5.6
networkx 2.8.8
nibabel 4.0.2
notebook 6.5.2
notebook_shim 0.2.2
numpy 1.23.4
ordered-set 4.1.0
packaging 21.3
pandas 1.5.1
pandocfilters 1.5.0
parso 0.8.3
pathspec 0.10.1
pbkdf2 1.3
pep517 0.13.0
pexpect 4.8.0
pickleshare 0.7.5
pikaur 1.13
Pillow 9.3.0
pip 22.3
platformdirs 2.5.2
pluggy 1.0.0
ply 3.11
portalocker 2.6.0
progressbar2 4.2.0
prometheus-client 0.15.0
prompt-toolkit 3.0.33
protobuf 4.21.7
psutil 5.9.4
ptyprocess 0.7.0
pure-eval 0.2.2
pyaes 1.6.1
pyalpm 0.10.6
pycodestyle 2.9.1
pycparser 2.21
pycryptodomex 3.12.0
pydantic 1.10.2
pyflakes 2.5.0
Pygments 2.13.0
pynvim 0.4.3
pyparsing 3.0.9
PyQt5 5.15.7
PyQt5-sip 12.11.0
pyrsistent 0.19.2
PySocks 1.7.1
python-dateutil 2.8.2
python-dotenv 0.21.0
python-lsp-jsonrpc 1.0.0
python-lsp-server 1.5.0
python-socks 2.0.3
python-utils 3.4.5
pytz 2022.5
pytz-deprecation-shim 0.1.0.post0
PyWavelets 1.4.1
pyzmq 24.0.1
qrcode 7.3.1
regex 2022.10.31
requests 2.28.1
requests-unixsocket 0.3.0
ruamel.yaml 0.17.21
ruamel.yaml.clib 0.2.7
scikit-image 0.19.3
scipy 1.9.3
Send2Trash 1.8.0
setuptools 63.2.0
Shapely 1.8.2
six 1.16.0
sniffio 1.3.0
soupsieve 2.3.2.post1
SQLAlchemy 1.4.43
stack-data 0.6.1
TBB 0.2
terminado 0.17.0
testpath 0.6.0
tifffile 2022.10.10
tinycss2 1.2.1
toml 0.10.2
tomli 2.0.1
tomlkit 0.11.6
tornado 6.2
traitlets 5.5.0
trove-classifiers 2022.10.19
typing_extensions 4.4.0
tzdata 2022.6
tzlocal 4.2
uc-micro-py 1.0.1
ujson 5.5.0
urllib3 1.26.12
validate-pyproject 0.10.1
wcwidth 0.2.5
webencodings 0.5.1
websocket-client 1.4.1
wheel 0.37.1
yarl 1.8.1
|
[
"\nOpen your vscode and reinstall the Python and Jupyter Notebook extensions.\nReinstall ipykernel package in the terminal.\n\nAt the same time, this issue also proposes other solutions.\nAdded:\nI encountered the same problem with traitlets==4.3.3. I updated it by using pip install traitlets and it's version is 5.5.0 to solve this problem.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"termux",
"visual_studio_code"
] |
stackoverflow_0074549086_python_termux_visual_studio_code.txt
|
Q:
Save a text file replacing the regular expression from variable in python
I am using this code to save in a text file a ping command:
from subprocess import *
def run_cmd(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
output = p.communicate()[0]
return output
test = run_cmd('ping www.google.com')
print(test)
with open('sample.txt', 'w', encoding='utf-8') as f:
f.write('dict = ' + repr(test) + '\n')
This code save the text using regular expression like /r/n
But when I open the text file or print the variable - the text save in this way:
\r\nDisparando www.google.com [2800:3f0:4001:81b::2004] com 32 bytes de dados:\r\nResposta de 2800:3f0:4001:81b::2004: tempo=20ms \r\nResposta de 2800:3f0:4001:81b::2004: tempo=15ms \r\nResposta de 2800:3f0:4001:81b::2004: tempo=15ms \r\nResposta de 2800:3f0:4001:81b::2004: tempo=16ms \r\n\r\nEstat\xa1sticas do Ping para 2800:3f0:4001:81b::2004:\r\n Pacotes: Enviados = 4, Recebidos = 4, Perdidos = 0 (0% de\r\n perda),\r\nAproximar um n\xa3mero redondo de vezes em milissegundos:\r\n M\xa1nimo = 15ms, M\xa0ximo = 20ms, M\x82dia = 16ms\r\n
Please how can I save in a txt file using this expression replacing in a line break?
Thank you
Please how can I save in a txt file using this expression replacing in a line break?
A:
I found this solution
import io
import subprocess
def commandP(command):
output = subprocess.getoutput(command)
return output
def recordV(file, output):
with io.open(f'{file}.txt', 'w') as f:
f.write(output)
output = commandP('ping www.google.com')
recordV('test', output)
|
Save a text file replacing the regular expression from variable in python
|
I am using this code to save in a text file a ping command:
from subprocess import *
def run_cmd(cmd):
p = Popen(cmd, shell=True, stdout=PIPE)
output = p.communicate()[0]
return output
test = run_cmd('ping www.google.com')
print(test)
with open('sample.txt', 'w', encoding='utf-8') as f:
f.write('dict = ' + repr(test) + '\n')
This code save the text using regular expression like /r/n
But when I open the text file or print the variable - the text save in this way:
\r\nDisparando www.google.com [2800:3f0:4001:81b::2004] com 32 bytes de dados:\r\nResposta de 2800:3f0:4001:81b::2004: tempo=20ms \r\nResposta de 2800:3f0:4001:81b::2004: tempo=15ms \r\nResposta de 2800:3f0:4001:81b::2004: tempo=15ms \r\nResposta de 2800:3f0:4001:81b::2004: tempo=16ms \r\n\r\nEstat\xa1sticas do Ping para 2800:3f0:4001:81b::2004:\r\n Pacotes: Enviados = 4, Recebidos = 4, Perdidos = 0 (0% de\r\n perda),\r\nAproximar um n\xa3mero redondo de vezes em milissegundos:\r\n M\xa1nimo = 15ms, M\xa0ximo = 20ms, M\x82dia = 16ms\r\n
Please how can I save in a txt file using this expression replacing in a line break?
Thank you
Please how can I save in a txt file using this expression replacing in a line break?
|
[
"I found this solution\nimport io\nimport subprocess\n\ndef commandP(command):\n output = subprocess.getoutput(command)\n return output\n\ndef recordV(file, output):\n with io.open(f'{file}.txt', 'w') as f:\n f.write(output)\n\n\noutput = commandP('ping www.google.com')\nrecordV('test', output)\n\n"
] |
[
1
] |
[] |
[] |
[
"cmd",
"expression",
"ping",
"python"
] |
stackoverflow_0074532148_cmd_expression_ping_python.txt
|
Q:
Installed package was successful outside virtual env but errors inside virtual env
I have a package "fretboardgtr" successfully installed outside virtual env using pip. The modules work without any errors.
I started a django project inside a virtual env and tried to install the same package inside the virtual env but it errors with the following error:
Collecting fretboardgtr Using cached
fretboardgtr-0.0.4-py3-none-any.whl (32 kB) Processing
/Users/sajwaltamrakar/Library/Caches/pip/wheels/83/85/db/f83adc7591329e230cb5bda2a339e66a8dbd0f69ade492db56/svglib-1.4.1-py3-none-any.whl
Collecting Pillow>=7.1.2 Using cached Pillow-9.2.0.tar.gz (50.0 MB)
Collecting webencodings>=0.5.1 Using cached
webencodings-0.5.1-py2.py3-none-any.whl (11 kB) Collecting
svgwrite>=1.4 Using cached svgwrite-1.4.3-py3-none-any.whl (67 kB)
Collecting cssselect2>=0.3.0 Using cached
cssselect2-0.7.0-py3-none-any.whl (15 kB) Collecting lxml>=4.5.1
Using cached lxml-4.9.1.tar.gz (3.4 MB) Collecting tinycss2>=1.0.2
Using cached tinycss2-1.1.1-py3-none-any.whl (21 kB) Collecting
reportlab>=3.5.42 Using cached reportlab-3.6.11.tar.gz (4.5 MB)
ERROR: Command errored out with exit status 1:
command: /Users/MYNAME/Documents/Python/content_creator/CC_env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/h2/xy8....
Complete output (10 lines):
##### setup-python-3.9.1-macosx-11-x86_64: ================================================
##### setup-python-3.9.1-macosx-11-x86_64: Attempting build of _rl_accel
##### setup-python-3.9.1-macosx-11-x86_64: extensions from 'src/rl_addons/rl_accel'
##### setup-python-3.9.1-macosx-11-x86_64: ================================================
##### setup-python-3.9.1-macosx-11-x86_64: ===================================================
##### setup-python-3.9.1-macosx-11-x86_64: Attempting build of _renderPM
##### setup-python-3.9.1-macosx-11-x86_64: extensions from 'src/rl_addons/renderPM'
##### setup-python-3.9.1-macosx-11-x86_64: ===================================================
##### setup-python-3.9.1-macosx-11-x86_64: will use package libart 2.3.21
!!!!! cannot find ft2build.h
---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
A:
sudo apt-get install libfreetype6-dev
Probably your are missing this dependency
|
Installed package was successful outside virtual env but errors inside virtual env
|
I have a package "fretboardgtr" successfully installed outside virtual env using pip. The modules work without any errors.
I started a django project inside a virtual env and tried to install the same package inside the virtual env but it errors with the following error:
Collecting fretboardgtr Using cached
fretboardgtr-0.0.4-py3-none-any.whl (32 kB) Processing
/Users/sajwaltamrakar/Library/Caches/pip/wheels/83/85/db/f83adc7591329e230cb5bda2a339e66a8dbd0f69ade492db56/svglib-1.4.1-py3-none-any.whl
Collecting Pillow>=7.1.2 Using cached Pillow-9.2.0.tar.gz (50.0 MB)
Collecting webencodings>=0.5.1 Using cached
webencodings-0.5.1-py2.py3-none-any.whl (11 kB) Collecting
svgwrite>=1.4 Using cached svgwrite-1.4.3-py3-none-any.whl (67 kB)
Collecting cssselect2>=0.3.0 Using cached
cssselect2-0.7.0-py3-none-any.whl (15 kB) Collecting lxml>=4.5.1
Using cached lxml-4.9.1.tar.gz (3.4 MB) Collecting tinycss2>=1.0.2
Using cached tinycss2-1.1.1-py3-none-any.whl (21 kB) Collecting
reportlab>=3.5.42 Using cached reportlab-3.6.11.tar.gz (4.5 MB)
ERROR: Command errored out with exit status 1:
command: /Users/MYNAME/Documents/Python/content_creator/CC_env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/h2/xy8....
Complete output (10 lines):
##### setup-python-3.9.1-macosx-11-x86_64: ================================================
##### setup-python-3.9.1-macosx-11-x86_64: Attempting build of _rl_accel
##### setup-python-3.9.1-macosx-11-x86_64: extensions from 'src/rl_addons/rl_accel'
##### setup-python-3.9.1-macosx-11-x86_64: ================================================
##### setup-python-3.9.1-macosx-11-x86_64: ===================================================
##### setup-python-3.9.1-macosx-11-x86_64: Attempting build of _renderPM
##### setup-python-3.9.1-macosx-11-x86_64: extensions from 'src/rl_addons/renderPM'
##### setup-python-3.9.1-macosx-11-x86_64: ===================================================
##### setup-python-3.9.1-macosx-11-x86_64: will use package libart 2.3.21
!!!!! cannot find ft2build.h
---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
|
[
" sudo apt-get install libfreetype6-dev\n\nProbably your are missing this dependency\n"
] |
[
0
] |
[] |
[] |
[
"django",
"pip",
"pypi",
"python",
"virtualenv"
] |
stackoverflow_0074010991_django_pip_pypi_python_virtualenv.txt
|
Q:
Printing website scrape loop directly into Google Sheets
I'm scraping a bunch of website data and am able to print to terminal, but having real trouble pushing it directly to a sheet.
I can confirm Gspread connection is working - my code loops through the names, but doesn't touch the sheet.
I thought the last line of code (append) would place the results.
Ultimately, I just want to full result of my code in columns on the sheet, but having trouble.
If there's a better approach would love any guidance:
https://docs.google.com/spreadsheets/d/1TD4YmhfAsnSL_Fwo1lckEbnUVBQB6VyKC05ieJ7PKCw/edit#gid=0
import requests
from bs4 import BeautifulSoup
import gspread
gc = gspread.service_account(filename='creds.json')
sh = gc.open_by_key('1TD4YmhfAsnSL_Fwo1lckEbnUVBQB6VyKC05ieJ7PKCw')
worksheet = sh.sheet1
# AddValue = ["Test", 25, "Test2"]
# worksheet.insert_row(AddValue, 3)
def get_links(url):
data = []
req_url = requests.get(url)
soup = BeautifulSoup(req_url.content, "html.parser")
for td in soup.find_all('td', {'data-th': 'Player'}):
a_tag = td.a
name = a_tag.text
player_url = a_tag['href']
print(f"Getting {name}")
req_player_url = requests.get(
f"https://basketball.realgm.com{player_url}")
soup_player = BeautifulSoup(req_player_url.content, "html.parser")
div_profile_box = soup_player.find("div", class_="profile-box")
row = {"Name": name, "URL": player_url}
for p in div_profile_box.find_all("p"):
try:
key, value = p.get_text(strip=True).split(':', 1)
row[key.strip()] = value.strip()
except: # not all entries have values
pass
data.append(row)
return data
urls = [
'https://basketball.realgm.com/dleague/players/2022',
]
for url in urls:
print(f"Getting: {url}")
data = get_links(url)
for entry in data:
worksheet.append_row(entry)
A:
Modification points:
When I saw your script, I thought that data of data = get_links(url) is an array including JSON object. In the current stage, append_row cannot directly use the JSON object. I thought that this is the reason for your current issue.
In your script, append_row is used in the loop. In this case, the process cost will become high.
When these points are reflected in your script, how about the following modification?
From:
for url in urls:
print(f"Getting: {url}")
data = get_links(url)
for entry in data:
worksheet.append_row(entry)
To:
res = []
for url in urls:
print(f"Getting: {url}")
data = get_links(url)
res = [*res, *data]
if res != []:
header = list(res[0].keys())
values = [header, *[[e[k] if e.get(k) else "" for k in header] for e in res]]
worksheet.append_rows(values, value_input_option="USER_ENTERED")
In this modification, all values are retrieved in the for a loop. And, the retrieved values are put into the Spreadsheet by one API call with append_rows.
Note:
In this modification, the header row is used with header = list(res[0].keys()). If you want to use your expected ordered headers, please manually put it to header = list(res[0].keys()).
Reference:
append_rows
|
Printing website scrape loop directly into Google Sheets
|
I'm scraping a bunch of website data and am able to print to terminal, but having real trouble pushing it directly to a sheet.
I can confirm Gspread connection is working - my code loops through the names, but doesn't touch the sheet.
I thought the last line of code (append) would place the results.
Ultimately, I just want to full result of my code in columns on the sheet, but having trouble.
If there's a better approach would love any guidance:
https://docs.google.com/spreadsheets/d/1TD4YmhfAsnSL_Fwo1lckEbnUVBQB6VyKC05ieJ7PKCw/edit#gid=0
import requests
from bs4 import BeautifulSoup
import gspread
gc = gspread.service_account(filename='creds.json')
sh = gc.open_by_key('1TD4YmhfAsnSL_Fwo1lckEbnUVBQB6VyKC05ieJ7PKCw')
worksheet = sh.sheet1
# AddValue = ["Test", 25, "Test2"]
# worksheet.insert_row(AddValue, 3)
def get_links(url):
data = []
req_url = requests.get(url)
soup = BeautifulSoup(req_url.content, "html.parser")
for td in soup.find_all('td', {'data-th': 'Player'}):
a_tag = td.a
name = a_tag.text
player_url = a_tag['href']
print(f"Getting {name}")
req_player_url = requests.get(
f"https://basketball.realgm.com{player_url}")
soup_player = BeautifulSoup(req_player_url.content, "html.parser")
div_profile_box = soup_player.find("div", class_="profile-box")
row = {"Name": name, "URL": player_url}
for p in div_profile_box.find_all("p"):
try:
key, value = p.get_text(strip=True).split(':', 1)
row[key.strip()] = value.strip()
except: # not all entries have values
pass
data.append(row)
return data
urls = [
'https://basketball.realgm.com/dleague/players/2022',
]
for url in urls:
print(f"Getting: {url}")
data = get_links(url)
for entry in data:
worksheet.append_row(entry)
|
[
"Modification points:\n\nWhen I saw your script, I thought that data of data = get_links(url) is an array including JSON object. In the current stage, append_row cannot directly use the JSON object. I thought that this is the reason for your current issue.\nIn your script, append_row is used in the loop. In this case, the process cost will become high.\n\nWhen these points are reflected in your script, how about the following modification?\nFrom:\nfor url in urls:\n print(f\"Getting: {url}\")\n data = get_links(url)\n\n for entry in data:\n worksheet.append_row(entry)\n\nTo:\nres = []\nfor url in urls:\n print(f\"Getting: {url}\")\n data = get_links(url)\n res = [*res, *data]\n\nif res != []:\n header = list(res[0].keys())\n values = [header, *[[e[k] if e.get(k) else \"\" for k in header] for e in res]]\n worksheet.append_rows(values, value_input_option=\"USER_ENTERED\")\n\n\nIn this modification, all values are retrieved in the for a loop. And, the retrieved values are put into the Spreadsheet by one API call with append_rows.\n\nNote:\n\nIn this modification, the header row is used with header = list(res[0].keys()). If you want to use your expected ordered headers, please manually put it to header = list(res[0].keys()).\n\nReference:\n\nappend_rows\n\n"
] |
[
2
] |
[] |
[] |
[
"beautifulsoup",
"google_sheets",
"google_sheets_api",
"gspread",
"python"
] |
stackoverflow_0074552515_beautifulsoup_google_sheets_google_sheets_api_gspread_python.txt
|
Q:
python with sympy
I am trying to make matrix with unknown numbers, and instead of showing it as matrix its saying Matrix and than putting all in 1 line.
Matrix([[cos(t2(t)), 0, sin(t2(t)), 0], [sin(t2(t)), 0, -cos(t2(t)), 0], [0, 1, 0, d2(t)], [0, 0, 0, 1]])
In the pic you can see its showing the matrix in 1 line. this is my good for the matrix and the printing
import sympy as sm
import numpy as np
from sympy.physics.vector import init_vprinting
init_vprinting(use_latex='mathjax', prettyprint=False)
from sympy.physics.mechanics import dynamicsymbols
from sympy import symbols
theta1, theta2, theta4, theta5, theta6, d2, d3, d6 = dynamicsymbols('t1 t2 t4 t5 t6 d2 d3 d6')
theta = dynamicsymbols('theta')
A12=sm.Array([[sm.cos(theta2),0,sm.sin(theta2),0], [sm.sin(theta2),0,-sm.cos(theta2),0],[0,1,0,d2],[0,0,0,1]])
print(A12)
I tried using array but it did not work, still was in 1 line. using 6 matrix and need to double the, together in the end so for now trying to make 1 look right
A:
The "one line matrix" is a compact method of representing the matrix. It is the form given by the "str" function (which apparently is the default method of printing in your context). By using init_printing() at the outset you will get better looking output (probably); I rarely use it.
sample IDE session showing different printing
Note, too, that you are using an Array instead of a Matrix. You can pass your Array as the argument to Matrix and have it do the right thing.
|
python with sympy
|
I am trying to make matrix with unknown numbers, and instead of showing it as matrix its saying Matrix and than putting all in 1 line.
Matrix([[cos(t2(t)), 0, sin(t2(t)), 0], [sin(t2(t)), 0, -cos(t2(t)), 0], [0, 1, 0, d2(t)], [0, 0, 0, 1]])
In the pic you can see its showing the matrix in 1 line. this is my good for the matrix and the printing
import sympy as sm
import numpy as np
from sympy.physics.vector import init_vprinting
init_vprinting(use_latex='mathjax', prettyprint=False)
from sympy.physics.mechanics import dynamicsymbols
from sympy import symbols
theta1, theta2, theta4, theta5, theta6, d2, d3, d6 = dynamicsymbols('t1 t2 t4 t5 t6 d2 d3 d6')
theta = dynamicsymbols('theta')
A12=sm.Array([[sm.cos(theta2),0,sm.sin(theta2),0], [sm.sin(theta2),0,-sm.cos(theta2),0],[0,1,0,d2],[0,0,0,1]])
print(A12)
I tried using array but it did not work, still was in 1 line. using 6 matrix and need to double the, together in the end so for now trying to make 1 look right
|
[
"The \"one line matrix\" is a compact method of representing the matrix. It is the form given by the \"str\" function (which apparently is the default method of printing in your context). By using init_printing() at the outset you will get better looking output (probably); I rarely use it.\nsample IDE session showing different printing\nNote, too, that you are using an Array instead of a Matrix. You can pass your Array as the argument to Matrix and have it do the right thing.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"sympy"
] |
stackoverflow_0074552877_python_sympy.txt
|
Q:
Ignore path does not exist in pyspark
I want ignore the paths that generate the Error:
'Path does not exist'
when I read parquet files with pyspark. For example I have a list of paths:
list_paths = ['path1','path2','path3']
and read the files like:
dataframe = spark.read.parquet(*list_paths)
but the path path2 does not exist. In general, I do not know which path does not exits, so I want ignore path2 automatically. How can I do it and obtain only one dataframe?
A:
You can use Hadoop FS API to check if the files exist before you pass them to spark.read:
conf = sc._jsc.hadoopConfiguration()
Path = sc._gateway.jvm.org.apache.hadoop.fs.Path
filtered_paths = [p for p in list_paths if Path(p).getFileSystem(conf).exists(Path(p))]
dataframe = spark.read.parquet(*filtered_paths)
Where sc is the SparkContext.
A:
Maybe you can do
existing_paths = [path for path in list_paths if os.path.exists(path)]
dataframe = spark.read.parquet(*existing_paths)
A:
Adding to @blackbishop's answer, you can further use Hadoop pattern strings to check for files/objects before loading them.
It's also worth noting that spark.read.load() accepts lists of path strings.
from functools import partial
from typing import Iterator
from pyspark.sql import SparkSession
def iterhadoopfiles(spark: SparkSession, path_pattern: str) -> Iterator[str]:
"""Return iterator of object/file paths that match path_pattern."""
sc = spark.sparkContext
FileUtil = sc._gateway.jvm.org.apache.hadoop.fs.FileUtil
Path = sc._gateway.jvm.org.apache.hadoop.fs.Path
hadoop_config = sc._jsc.hadoopConfiguration()
p = Path(path_pattern)
return (
str(x)
for x in FileUtil.stat2Paths(
p.getFileSystem(hadoop_config).globStatus(p)
)
)
def pathnotempty(spark: SparkSession, path_pattern: str) -> bool:
"""Return true if path matches at least one object/file."""
try:
next(iterhadoopfiles(spark, path_pattern))
except StopIteration:
return False
return True
paths_to_load = list(filter(partial(pathnotempty, spark), ["file:///*.parquet"]))
spark.read.format('parquet').load(paths_to_load)
|
Ignore path does not exist in pyspark
|
I want ignore the paths that generate the Error:
'Path does not exist'
when I read parquet files with pyspark. For example I have a list of paths:
list_paths = ['path1','path2','path3']
and read the files like:
dataframe = spark.read.parquet(*list_paths)
but the path path2 does not exist. In general, I do not know which path does not exits, so I want ignore path2 automatically. How can I do it and obtain only one dataframe?
|
[
"You can use Hadoop FS API to check if the files exist before you pass them to spark.read:\nconf = sc._jsc.hadoopConfiguration()\nPath = sc._gateway.jvm.org.apache.hadoop.fs.Path\n\n\nfiltered_paths = [p for p in list_paths if Path(p).getFileSystem(conf).exists(Path(p))]\n\ndataframe = spark.read.parquet(*filtered_paths)\n\nWhere sc is the SparkContext.\n",
"Maybe you can do\nexisting_paths = [path for path in list_paths if os.path.exists(path)]\ndataframe = spark.read.parquet(*existing_paths)\n\n",
"Adding to @blackbishop's answer, you can further use Hadoop pattern strings to check for files/objects before loading them.\nIt's also worth noting that spark.read.load() accepts lists of path strings.\nfrom functools import partial\nfrom typing import Iterator\nfrom pyspark.sql import SparkSession\n\n\ndef iterhadoopfiles(spark: SparkSession, path_pattern: str) -> Iterator[str]:\n \"\"\"Return iterator of object/file paths that match path_pattern.\"\"\"\n sc = spark.sparkContext\n FileUtil = sc._gateway.jvm.org.apache.hadoop.fs.FileUtil\n Path = sc._gateway.jvm.org.apache.hadoop.fs.Path\n hadoop_config = sc._jsc.hadoopConfiguration()\n p = Path(path_pattern)\n return (\n str(x)\n for x in FileUtil.stat2Paths(\n p.getFileSystem(hadoop_config).globStatus(p)\n )\n )\n\n\ndef pathnotempty(spark: SparkSession, path_pattern: str) -> bool:\n \"\"\"Return true if path matches at least one object/file.\"\"\"\n try:\n next(iterhadoopfiles(spark, path_pattern))\n except StopIteration:\n return False\n return True\n\n\npaths_to_load = list(filter(partial(pathnotempty, spark), [\"file:///*.parquet\"]))\nspark.read.format('parquet').load(paths_to_load)\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"apache_spark",
"apache_spark_sql",
"parquet",
"pyspark",
"python"
] |
stackoverflow_0070367863_apache_spark_apache_spark_sql_parquet_pyspark_python.txt
|
Q:
Compact way of writing (a + b == c or a + c == b or b + c == a)
Is there a more compact or pythonic way to write the boolean expression
a + b == c or a + c == b or b + c == a
I came up with
a + b + c in (2*a, 2*b, 2*c)
but that is a little strange.
A:
If we look at the Zen of Python, emphasis mine:
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
The most Pythonic solution is the one that is clearest, simplest, and easiest to explain:
a + b == c or a + c == b or b + c == a
Even better, you don't even need to know Python to understand this code! It's that easy. This is, without reservation, the best solution. Anything else is intellectual masturbation.
Furthermore, this is likely the best performing solution as well, as it is the only one out of all the proposals that short circuits. If a + b == c, only a single addition and comparison is done.
A:
Solving the three equalities for a:
a in (b+c, b-c, c-b)
A:
Python has an any function that does an or on all the elements of a sequence. Here I've converted your statement into a 3-element tuple.
any((a + b == c, a + c == b, b + c == a))
Note that or is short circuiting, so if calculating the individual conditions is expensive it might be better to keep your original construct.
A:
If you know you're only dealing with positive numbers, this will work, and is pretty clean:
a, b, c = sorted((a, b, c))
if a + b == c:
do_stuff()
As I said, this only works for positive numbers; but if you know they're going to be positive, this is a very readable solution IMO, even directly in the code as opposed to in a function.
You could do this, which might do a bit of repeated computation; but you didn't specify performance as your goal:
from itertools import permutations
if any(x + y == z for x, y, z in permutations((a, b, c), 3)):
do_stuff()
Or without permutations() and the possibility of repeated computations:
if any(x + y == z for x, y, z in [(a, b, c), (a, c, b), (b, c, a)]:
do_stuff()
I would probably put this, or any other solution, into a function. Then you can just cleanly call the function in your code.
Personally, unless I needed more flexibility from the code, I would just use the first method in your question. It's simple and efficient. I still might put it into a function:
def two_add_to_third(a, b, c):
return a + b == c or a + c == b or b + c == a
if two_add_to_third(a, b, c):
do_stuff()
That's pretty Pythonic, and it's quite possibly the most efficient way to do it (the extra function call aside); although you shouldn't worry too much about performance anyway, unless it's actually causing an issue.
A:
If you will only be using three variables then your initial method:
a + b == c or a + c == b or b + c == a
Is already very pythonic.
If you plan on using more variables then your method of reasoning with:
a + b + c in (2*a, 2*b, 2*c)
Is very smart but lets think about why. Why does this work?
Well through some simple arithmetic we see that:
a + b = c
c = c
a + b + c == c + c == 2*c
a + b + c == 2*c
And this will have to hold true for either a,b, or c, meaning that yes it will equal 2*a, 2*b, or 2*c. This will be true for any number of variables.
So a good way to write this quickly would be to simply have a list of your variables and check their sum against a list of the doubled values.
values = [a,b,c,d,e,...]
any(sum(values) in [2*x for x in values])
This way, to add more variables into the equation all you have to do is edit your values list by 'n' new variables, not write 'n' equations
A:
The following code can be used to iteratively compare each element with the sum of the others, which is computed from sum of the whole list, excluding that element.
l = [a,b,c]
any(sum(l)-e == e for e in l)
A:
Don't try and simplify it. Instead, name what you're doing with a function:
def any_two_sum_to_third(a, b, c):
return a + b == c or a + c == b or b + c == a
if any_two_sum_to_third(foo, bar, baz):
...
Replace the condition with something "clever" might make it shorter, but it won't make it more readable. Leaving it how it is isn't very readable either however, because it's tricky to know why you're checking those three conditions at a glance. This makes it absolutely crystal clear what you're checking for.
Regarding performance, this approach does add the overhead of a function call, but never sacrifice readability for performance unless you've found a bottleneck you absolutely must fix. And always measure, as some clever implementations are capable of optimizing away and inlining some function calls in some circumstances.
A:
Python 3:
(a+b+c)/2 in (a,b,c)
(a+b+c+d)/2 in (a,b,c,d)
...
It scales to any number of variables:
arr = [a,b,c,d,...]
sum(arr)/2 in arr
However, in general I agree that unless you have more than three variables, the original version is more readable.
A:
(a+b-c)*(a+c-b)*(b+c-a) == 0
If the sum of any two terms is equal to the third term, then one of the factors will be zero, making the entire product zero.
A:
How about just:
a == b + c or abs(a) == abs(b - c)
Note that this won't work if variables are unsigned.
From the viewpoint of code optimization (at least on x86 platform) this seems to be the most efficient solution.
Modern compilers will inline both abs() function calls and avoid sign testing and subsequent conditional branch by using a clever sequence of CDQ, XOR, and SUB instructions. The above high-level code will thus be represented with only low-latency, high-throughput ALU instructions and just two conditionals.
A:
The solution provided by Alex Varga "a in (b+c, b-c, c-b)" is compact and mathematically beautiful, but I wouldn't actually write code that way because the next developer coming along would not immediately understand the purpose of the code.
Mark Ransom's solution of
any((a + b == c, a + c == b, b + c == a))
is more clear but not much more succinct than
a + b == c or a + c == b or b + c == a
When writing code that someone else will have to look at, or that I will have to look at a long time later when I have forgotten what I was thinking when I wrote it, being too short or clever tends to do more harm than good. Code should be readable. So succinct is good, but not so succinct that the next programmer can't understand it.
A:
Request is for more compact OR more pythonic - I tried my hand at more compact.
given
import functools, itertools
f = functools.partial(itertools.permutations, r = 3)
def g(x,y,z):
return x + y == z
This is 2 characters less than the original
any(g(*args) for args in f((a,b,c)))
test with:
assert any(g(*args) for args in f((a,b,c))) == (a + b == c or a + c == b or b + c == a)
additionally, given:
h = functools.partial(itertools.starmap, g)
This is equivalent
any(h(f((a,b,c))))
A:
As an old habit of my programming, I think placing complex expression at right in a clause can make it more readable like this:
a == b+c or b == a+c or c == a+b
Plus ():
((a == b+c) or (b == a+c) or (c == a+b))
And also I think using multi-lines can also make more senses like this:
((a == b+c) or
(b == a+c) or
(c == a+b))
A:
I want to present what I see as the most pythonic answer:
def one_number_is_the_sum_of_the_others(a, b, c):
return any((a == b + c, b == a + c, c == a + b))
The general case, non-optimized:
def one_number_is_the_sum_of_the_others(numbers):
for idx in range(len(numbers)):
remaining_numbers = numbers[:]
sum_candidate = remaining_numbers.pop(idx)
if sum_candidate == sum(remaining_numbers):
return True
return False
In terms of the Zen of Python I think the emphasized statements are more followed than from other answer:
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
A:
In a generic way,
m = a+b-c;
if (m == 0 || m == 2*a || m == 2*b) do_stuff ();
if, manipulating an input variable is OK for you,
c = a+b-c;
if (c==0 || c == 2*a || c == 2*b) do_stuff ();
if you want to exploit using bit hacks, you can use "!", ">> 1" and "<< 1"
I avoided division though it enables use to avoid two multiplications to avoid round off errors. However, check for overflows
A:
def any_sum_of_others (*nums):
num_elements = len(nums)
for i in range(num_elements):
discriminating_map = map(lambda j: -1 if j == i else 1, range(num_elements))
if sum(n * u for n, u in zip(nums, discriminating_map)) == 0:
return True
return False
print(any_sum_of_others(0, 0, 0)) # True
print(any_sum_of_others(1, 2, 3)) # True
print(any_sum_of_others(7, 12, 5)) # True
print(any_sum_of_others(4, 2, 2)) # True
print(any_sum_of_others(1, -1, 0)) # True
print(any_sum_of_others(9, 8, -4)) # False
print(any_sum_of_others(4, 3, 2)) # False
print(any_sum_of_others(1, 1, 1, 1, 4)) # True
print(any_sum_of_others(0)) # True
print(any_sum_of_others(1)) # False
A:
There is little to gain with such a small expression but using a function just to not having to repeat the summation and comparison could be an option. It makes it a bit more maintainable when wanting to change the operation to something like a + b == c * 2.
def equals_sum(a, b, c):
return a + b == c
if (equals_sum(a, b, c)
or equals_sum(a, c, b)
or equals_sum(b, c, a)):
...
|
Compact way of writing (a + b == c or a + c == b or b + c == a)
|
Is there a more compact or pythonic way to write the boolean expression
a + b == c or a + c == b or b + c == a
I came up with
a + b + c in (2*a, 2*b, 2*c)
but that is a little strange.
|
[
"If we look at the Zen of Python, emphasis mine:\n\nThe Zen of Python, by Tim Peters\nBeautiful is better than ugly.\n Explicit is better than implicit.\nSimple is better than complex.\n Complex is better than complicated.\n Flat is better than nested.\n Sparse is better than dense.\nReadability counts.\n Special cases aren't special enough to break the rules.\n Although practicality beats purity.\n Errors should never pass silently.\n Unless explicitly silenced.\n In the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\n Although that way may not be obvious at first unless you're Dutch.\n Now is better than never.\n Although never is often better than right now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\n Namespaces are one honking great idea -- let's do more of those!\n\nThe most Pythonic solution is the one that is clearest, simplest, and easiest to explain:\na + b == c or a + c == b or b + c == a\n\nEven better, you don't even need to know Python to understand this code! It's that easy. This is, without reservation, the best solution. Anything else is intellectual masturbation.\nFurthermore, this is likely the best performing solution as well, as it is the only one out of all the proposals that short circuits. If a + b == c, only a single addition and comparison is done. \n",
"Solving the three equalities for a:\na in (b+c, b-c, c-b)\n\n",
"Python has an any function that does an or on all the elements of a sequence. Here I've converted your statement into a 3-element tuple.\nany((a + b == c, a + c == b, b + c == a))\n\nNote that or is short circuiting, so if calculating the individual conditions is expensive it might be better to keep your original construct.\n",
"If you know you're only dealing with positive numbers, this will work, and is pretty clean:\na, b, c = sorted((a, b, c))\nif a + b == c:\n do_stuff()\n\nAs I said, this only works for positive numbers; but if you know they're going to be positive, this is a very readable solution IMO, even directly in the code as opposed to in a function.\nYou could do this, which might do a bit of repeated computation; but you didn't specify performance as your goal:\nfrom itertools import permutations\n\nif any(x + y == z for x, y, z in permutations((a, b, c), 3)):\n do_stuff()\n\nOr without permutations() and the possibility of repeated computations:\nif any(x + y == z for x, y, z in [(a, b, c), (a, c, b), (b, c, a)]:\n do_stuff()\n\nI would probably put this, or any other solution, into a function. Then you can just cleanly call the function in your code.\nPersonally, unless I needed more flexibility from the code, I would just use the first method in your question. It's simple and efficient. I still might put it into a function:\ndef two_add_to_third(a, b, c):\n return a + b == c or a + c == b or b + c == a\n\nif two_add_to_third(a, b, c):\n do_stuff()\n\nThat's pretty Pythonic, and it's quite possibly the most efficient way to do it (the extra function call aside); although you shouldn't worry too much about performance anyway, unless it's actually causing an issue.\n",
"If you will only be using three variables then your initial method:\na + b == c or a + c == b or b + c == a\n\nIs already very pythonic.\nIf you plan on using more variables then your method of reasoning with:\na + b + c in (2*a, 2*b, 2*c)\n\nIs very smart but lets think about why. Why does this work? \n Well through some simple arithmetic we see that:\na + b = c\nc = c\na + b + c == c + c == 2*c\na + b + c == 2*c\n\nAnd this will have to hold true for either a,b, or c, meaning that yes it will equal 2*a, 2*b, or 2*c. This will be true for any number of variables.\nSo a good way to write this quickly would be to simply have a list of your variables and check their sum against a list of the doubled values.\nvalues = [a,b,c,d,e,...]\nany(sum(values) in [2*x for x in values])\n\nThis way, to add more variables into the equation all you have to do is edit your values list by 'n' new variables, not write 'n' equations\n",
"The following code can be used to iteratively compare each element with the sum of the others, which is computed from sum of the whole list, excluding that element.\n l = [a,b,c]\n any(sum(l)-e == e for e in l)\n\n",
"Don't try and simplify it. Instead, name what you're doing with a function:\ndef any_two_sum_to_third(a, b, c):\n return a + b == c or a + c == b or b + c == a\n\nif any_two_sum_to_third(foo, bar, baz):\n ...\n\nReplace the condition with something \"clever\" might make it shorter, but it won't make it more readable. Leaving it how it is isn't very readable either however, because it's tricky to know why you're checking those three conditions at a glance. This makes it absolutely crystal clear what you're checking for.\nRegarding performance, this approach does add the overhead of a function call, but never sacrifice readability for performance unless you've found a bottleneck you absolutely must fix. And always measure, as some clever implementations are capable of optimizing away and inlining some function calls in some circumstances.\n",
"Python 3:\n(a+b+c)/2 in (a,b,c)\n(a+b+c+d)/2 in (a,b,c,d)\n...\n\nIt scales to any number of variables:\narr = [a,b,c,d,...]\nsum(arr)/2 in arr\n\nHowever, in general I agree that unless you have more than three variables, the original version is more readable.\n",
"(a+b-c)*(a+c-b)*(b+c-a) == 0\n\nIf the sum of any two terms is equal to the third term, then one of the factors will be zero, making the entire product zero.\n",
"How about just:\na == b + c or abs(a) == abs(b - c)\n\nNote that this won't work if variables are unsigned.\nFrom the viewpoint of code optimization (at least on x86 platform) this seems to be the most efficient solution.\nModern compilers will inline both abs() function calls and avoid sign testing and subsequent conditional branch by using a clever sequence of CDQ, XOR, and SUB instructions. The above high-level code will thus be represented with only low-latency, high-throughput ALU instructions and just two conditionals.\n",
"The solution provided by Alex Varga \"a in (b+c, b-c, c-b)\" is compact and mathematically beautiful, but I wouldn't actually write code that way because the next developer coming along would not immediately understand the purpose of the code.\nMark Ransom's solution of \nany((a + b == c, a + c == b, b + c == a))\n\nis more clear but not much more succinct than \na + b == c or a + c == b or b + c == a\n\nWhen writing code that someone else will have to look at, or that I will have to look at a long time later when I have forgotten what I was thinking when I wrote it, being too short or clever tends to do more harm than good. Code should be readable. So succinct is good, but not so succinct that the next programmer can't understand it.\n",
"Request is for more compact OR more pythonic - I tried my hand at more compact.\ngiven\nimport functools, itertools\nf = functools.partial(itertools.permutations, r = 3)\ndef g(x,y,z):\n return x + y == z\n\nThis is 2 characters less than the original\nany(g(*args) for args in f((a,b,c)))\n\n\ntest with:\nassert any(g(*args) for args in f((a,b,c))) == (a + b == c or a + c == b or b + c == a)\n\n\nadditionally, given:\nh = functools.partial(itertools.starmap, g)\n\nThis is equivalent\nany(h(f((a,b,c))))\n\n",
"As an old habit of my programming, I think placing complex expression at right in a clause can make it more readable like this:\na == b+c or b == a+c or c == a+b\n\nPlus ():\n((a == b+c) or (b == a+c) or (c == a+b))\n\nAnd also I think using multi-lines can also make more senses like this:\n((a == b+c) or \n (b == a+c) or \n (c == a+b))\n\n",
"I want to present what I see as the most pythonic answer:\ndef one_number_is_the_sum_of_the_others(a, b, c):\n return any((a == b + c, b == a + c, c == a + b))\n\nThe general case, non-optimized: \ndef one_number_is_the_sum_of_the_others(numbers):\n for idx in range(len(numbers)):\n remaining_numbers = numbers[:]\n sum_candidate = remaining_numbers.pop(idx)\n if sum_candidate == sum(remaining_numbers):\n return True\n return False \n\nIn terms of the Zen of Python I think the emphasized statements are more followed than from other answer:\n\nThe Zen of Python, by Tim Peters\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\n Complex is better than complicated.\n Flat is better than nested.\n Sparse is better than dense.\nReadability counts.\n Special cases aren't special enough to break the rules.\n Although practicality beats purity.\n Errors should never pass silently.\n Unless explicitly silenced.\n In the face of ambiguity, refuse the temptation to guess.\n There should be one-- and preferably only one --obvious way to do it.\n Although that way may not be obvious at first unless you're Dutch.\n Now is better than never.\n Although never is often better than right now.\n If the implementation is hard to explain, it's a bad idea.\n If the implementation is easy to explain, it may be a good idea.\n Namespaces are one honking great idea -- let's do more of those!\n\n",
"In a generic way,\nm = a+b-c;\nif (m == 0 || m == 2*a || m == 2*b) do_stuff ();\n\nif, manipulating an input variable is OK for you,\nc = a+b-c;\nif (c==0 || c == 2*a || c == 2*b) do_stuff ();\n\nif you want to exploit using bit hacks, you can use \"!\", \">> 1\" and \"<< 1\"\nI avoided division though it enables use to avoid two multiplications to avoid round off errors. However, check for overflows\n",
"def any_sum_of_others (*nums):\n num_elements = len(nums)\n for i in range(num_elements):\n discriminating_map = map(lambda j: -1 if j == i else 1, range(num_elements))\n if sum(n * u for n, u in zip(nums, discriminating_map)) == 0:\n return True\n return False\n\nprint(any_sum_of_others(0, 0, 0)) # True\nprint(any_sum_of_others(1, 2, 3)) # True\nprint(any_sum_of_others(7, 12, 5)) # True\nprint(any_sum_of_others(4, 2, 2)) # True\nprint(any_sum_of_others(1, -1, 0)) # True\nprint(any_sum_of_others(9, 8, -4)) # False\nprint(any_sum_of_others(4, 3, 2)) # False\nprint(any_sum_of_others(1, 1, 1, 1, 4)) # True\nprint(any_sum_of_others(0)) # True\nprint(any_sum_of_others(1)) # False\n\n",
"There is little to gain with such a small expression but using a function just to not having to repeat the summation and comparison could be an option. It makes it a bit more maintainable when wanting to change the operation to something like a + b == c * 2.\ndef equals_sum(a, b, c):\n return a + b == c\n\nif (equals_sum(a, b, c)\nor equals_sum(a, c, b)\nor equals_sum(b, c, a)):\n ...\n\n"
] |
[
206,
101,
54,
40,
16,
12,
10,
9,
6,
6,
4,
2,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"boolean",
"python"
] |
stackoverflow_0032085675_boolean_python.txt
|
Q:
python convert dataframe to json with \n
We converted dataframe to json using to_json(), but \n disappears in the string. How can I convert while keeping \n?
Before conversion, dataframe has \n, which disappears when converted
now:
companyId:"ckurudq3r00efkakh4hgu33pn"
tagName:
contact:"0336443303"
phone:"01066449675"
virtualNumber:"050413736583"
partner:false
certificate:false
memo:null
businesshours:"Mon~Fri: 09:00AM ~ 06:00PM Sat: 09:00AM ~ 06:00PM Sun: 09:00AM ~ 06:00PM"
what i want:
companyId:"ckurudq3r00efkakh4hgu33pn"
tagName:
contact:"0336443303"
phone:"01066449675"
virtualNumber:"050413736583"
partner:false
certificate:false
memo:null
businesshours:"Mon~Fri: 09:00AM ~ 06:00PM\nSat: 09:00AM ~ 06:00PM\nSun: 09:00AM ~ 06:00PM"
A:
I was running through something similar to this and I do not remember that I could figure it out so I came up with a workaround.
#replace '\n' with '\\n'
df.replace('\n', '\\n', inplace= True)
# export normally
df.to_json('path')
whenever you want to open it back, just read the file and again replace any '\\n' with '\n'
|
python convert dataframe to json with \n
|
We converted dataframe to json using to_json(), but \n disappears in the string. How can I convert while keeping \n?
Before conversion, dataframe has \n, which disappears when converted
now:
companyId:"ckurudq3r00efkakh4hgu33pn"
tagName:
contact:"0336443303"
phone:"01066449675"
virtualNumber:"050413736583"
partner:false
certificate:false
memo:null
businesshours:"Mon~Fri: 09:00AM ~ 06:00PM Sat: 09:00AM ~ 06:00PM Sun: 09:00AM ~ 06:00PM"
what i want:
companyId:"ckurudq3r00efkakh4hgu33pn"
tagName:
contact:"0336443303"
phone:"01066449675"
virtualNumber:"050413736583"
partner:false
certificate:false
memo:null
businesshours:"Mon~Fri: 09:00AM ~ 06:00PM\nSat: 09:00AM ~ 06:00PM\nSun: 09:00AM ~ 06:00PM"
|
[
"I was running through something similar to this and I do not remember that I could figure it out so I came up with a workaround.\n#replace '\\n' with '\\\\n'\ndf.replace('\\n', '\\\\n', inplace= True)\n# export normally\ndf.to_json('path')\n\nwhenever you want to open it back, just read the file and again replace any '\\\\n' with '\\n'\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"json",
"python"
] |
stackoverflow_0074554714_dataframe_json_python.txt
|
Q:
How to apply a function element-wise with inputs from multiple numpy masked arrays to create a new masked array?
I have a function that takes in 4 single value inputs to return a singular float output, for example:
from scipy.stats import multivariate_normal
grid_step = 0.25 #in units of sigma
grid_x, grid_y = np.mgrid[-2:2+grid_step:grid_step, -2:2+grid_step:grid_step]
pos = np.dstack((grid_x, grid_y))
rv = multivariate_normal([0.0, 0.0], [[1.0, 0], [0, 1.0]])
grid_pdf = rv.pdf(pos)*grid_step**2
norm_pdf = np.sum(rv.pdf(pos))*grid_step**2
def cal_prob(x, x_err, y, y_err):
x_grid = grid_x*x_err + x
y_grid = grid_y*y_err + y
PSB_grid = ((x_grid>3) & (y_grid<10) & (y_grid < 10**(0.23*x_grid-0.46)))
PSB_prob = np.sum(PSB_grid*grid_pdf)/norm_pdf
return PSB_prob
What this function is doing is estimating the probability that some x-y measurement is within some defined limit in x-y space, given x and y's uncertainties. It assumes the uncertainties are Gaussian and uncorrelated. Then, using the pre-made grid_pdf, it checks which grid points (scaled by x_err/y_err and shifted by x/y) are within the defined limit, and multiply the True/False grid by the grid_pdf, normalized by norm_pdf. The probability is given by the sum of the normalized array.
I want this function to be applied element-wise with those 4 inputs stored in 4 separate numpy masked arrays of the same shape, with possibly different masks, then use the function outputs to create a new array of the same shape. Is there a way that doesn't use a for loop?
Thanks!
My current solution is this:
mask1 = np.array([[False, True, False],[True, True, True],[True, False, False]])
mask2 = np.array([[True, True, True],[True, True, False],[False, False, True]])
# the only overlaps should be [0,1], [1,0] and [1,1]
x = np.ma.array(np.random.randn(*mask1.shape), mask=~mask1)
x_err = np.ma.array(np.abs(np.random.randn(*mask1.shape))*0.1, mask=~mask1)
y = np.ma.array(np.random.randn(*mask2.shape), mask=~mask2)
y_err = np.ma.array(np.abs(np.random.randn(*mask2.shape))*0.1, mask=~mask2)
# a combined mask to iterate through
all_mask = x+x_err+y+y_err
prob = np.zeros(mask1.shape)
prob = np.ma.masked_where(np.ma.getmask(all_mask), prob)
for i,xi in np.ma.ndenumerate(all_mask):
prob[i] = cal_prob(xi, x_err[i], y[i], y_err[i])
A:
A test of np.vectorize with a masked array input:
In [180]: def foo(x):
...: print(x)
...: return 2*x
...:
In [181]: np.vectorize(foo)(np.ma.masked_array([1,2,3],[True,False,True]))
1
1
2
3
Out[181]:
masked_array(data=[--, 4, --],
mask=[ True, False, True],
fill_value=999999)
In [182]: _.data
Out[182]: array([2, 4, 6])
|
How to apply a function element-wise with inputs from multiple numpy masked arrays to create a new masked array?
|
I have a function that takes in 4 single value inputs to return a singular float output, for example:
from scipy.stats import multivariate_normal
grid_step = 0.25 #in units of sigma
grid_x, grid_y = np.mgrid[-2:2+grid_step:grid_step, -2:2+grid_step:grid_step]
pos = np.dstack((grid_x, grid_y))
rv = multivariate_normal([0.0, 0.0], [[1.0, 0], [0, 1.0]])
grid_pdf = rv.pdf(pos)*grid_step**2
norm_pdf = np.sum(rv.pdf(pos))*grid_step**2
def cal_prob(x, x_err, y, y_err):
x_grid = grid_x*x_err + x
y_grid = grid_y*y_err + y
PSB_grid = ((x_grid>3) & (y_grid<10) & (y_grid < 10**(0.23*x_grid-0.46)))
PSB_prob = np.sum(PSB_grid*grid_pdf)/norm_pdf
return PSB_prob
What this function is doing is estimating the probability that some x-y measurement is within some defined limit in x-y space, given x and y's uncertainties. It assumes the uncertainties are Gaussian and uncorrelated. Then, using the pre-made grid_pdf, it checks which grid points (scaled by x_err/y_err and shifted by x/y) are within the defined limit, and multiply the True/False grid by the grid_pdf, normalized by norm_pdf. The probability is given by the sum of the normalized array.
I want this function to be applied element-wise with those 4 inputs stored in 4 separate numpy masked arrays of the same shape, with possibly different masks, then use the function outputs to create a new array of the same shape. Is there a way that doesn't use a for loop?
Thanks!
My current solution is this:
mask1 = np.array([[False, True, False],[True, True, True],[True, False, False]])
mask2 = np.array([[True, True, True],[True, True, False],[False, False, True]])
# the only overlaps should be [0,1], [1,0] and [1,1]
x = np.ma.array(np.random.randn(*mask1.shape), mask=~mask1)
x_err = np.ma.array(np.abs(np.random.randn(*mask1.shape))*0.1, mask=~mask1)
y = np.ma.array(np.random.randn(*mask2.shape), mask=~mask2)
y_err = np.ma.array(np.abs(np.random.randn(*mask2.shape))*0.1, mask=~mask2)
# a combined mask to iterate through
all_mask = x+x_err+y+y_err
prob = np.zeros(mask1.shape)
prob = np.ma.masked_where(np.ma.getmask(all_mask), prob)
for i,xi in np.ma.ndenumerate(all_mask):
prob[i] = cal_prob(xi, x_err[i], y[i], y_err[i])
|
[
"A test of np.vectorize with a masked array input:\nIn [180]: def foo(x):\n ...: print(x)\n ...: return 2*x\n ...: \n\nIn [181]: np.vectorize(foo)(np.ma.masked_array([1,2,3],[True,False,True]))\n1\n1\n2\n3\nOut[181]: \nmasked_array(data=[--, 4, --],\n mask=[ True, False, True],\n fill_value=999999)\n\nIn [182]: _.data\nOut[182]: array([2, 4, 6])\n\n"
] |
[
0
] |
[] |
[] |
[
"masked_array",
"numpy",
"python",
"vectorization"
] |
stackoverflow_0074554618_masked_array_numpy_python_vectorization.txt
|
Q:
Pandas Dataframe to Code
If I have an existing pandas dataframe, is there a way to generate the python code, which when executed in another python script, will reproduce that dataframe.
e.g.
In[1]: df
Out[1]:
income user
0 40000 Bob
1 50000 Jane
2 42000 Alice
In[2]: someFunToWriteDfCode(df)
Out[2]:
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],
...: 'income': [40000, 50000, 42000]})
A:
You could try to use the to_dict() method on DataFrame:
print "df = pd.DataFrame( %s )" % (str(df.to_dict()))
If your data contains NaN's, you'll have to replace them with float('nan'):
print "df = pd.DataFrame( %s )" % (str(df.to_dict()).replace(" nan"," float('nan')"))
A:
I always used this code which help me much
def gen_code(df):
return 'pickle.loads({})'.format(pickle.dumps(df))
import pickle
code_string = gen_code(df)
code_string
So now you can copy the output of the code_string and paste it as follow to that string variable A
A= 'Paste your code_string here'
import pickle
df=eval(A)
This had helped me copy and past data frames in such platform
A:
Here's another approach that does not use dicts
import numpy as np
def dataframe_to_code(df):
data = np.array2string(df.to_numpy(), separator=', ')
data = data.replace(" nan", " float('nan')")
cols = df.columns.tolist()
return f"""df = pd.DataFrame({data}, columns={cols})"""
The data.replace(" nan", " float('nan')") is optional and was inspired by madokis excellent answer.
Note that np.array2string only works for numpy versions 1.11 and higher.
I recommend using https://github.com/psf/black to format the output
A:
more general solution
Supported pd.DataFrame attributes:
dtype of each column
strings with substring 'nan'
index
code
import numpy as np
import pandas as pd
import re
def _values_to_code(vals):
"""
Code representation of values
Parameters
----------
vals : List
Returns
-------
str :
vals as code string
"""
values = str(vals)
values = re.sub(r" nan(?<![,\]])", " np.nan", values)
return values
def _dtype_to_code(dtype):
"""
Code representation of dtypes
Parameters
----------
dtypes : datatype
dtype to convert. Example: np.float64
Returns
-------
str :
dtype as code string
"""
dtype = str(dtype)
dtype = re.sub(r"float64", " np.float64", dtype)
dtype = re.sub(r"int64", " np.int64", dtype)
return dtype
def df_to_code(df):
code = "pd.DataFrame({"
# columns with values
for col in df.columns:
values = _values_to_code(df[col].tolist())
dtype = _dtype_to_code(df.dtypes[col])
code += f'\n\t\'{col}\': np.array({values}, dtype={dtype}),'
code += '\n}'
# index
values = _values_to_code(df.index)
dtype = _dtype_to_code(df.index.dtype)
code += f', index=pd.{values}'
code += ')'
return code
if __name__ == "__main__":
df = pd.DataFrame({
'simple_float': np.array([1, 2, 3], dtype=float),
'simple_int': np.array([4, 5, 6], dtype=int),
'nan_variations': np.array(['np.nan', 'nan', np.nan], dtype=object),
'fancy_content': np.array([4, 'x', [1, 2]], dtype=object),
}, index = [0, '1', 2])
# small unittest
exec('df2 = ' + df_to_code(df))
assert df.equals(df2)
print(df_to_code(df))
output
pd.DataFrame({
'simple_float': np.array([1.0, 2.0, 3.0], dtype= np.float64),
'simple_int': np.array([4, 5, 6], dtype= np.int64),
'nan_variations': np.array(['np.nan', 'nan', np.nan], dtype=object),
'fancy_content': np.array([4, 'x', [1, 2]], dtype=object),
}, index=pd.Index([0, '1', 2], dtype='object'))
You can directly paste the output into a python console and enjoy ;)
python console demonstration
>>> import numpy as np
>>> import pandas as pd
>>> pd.DataFrame({
... 'simple_float': np.array([1.0, 2.0, 3.0], dtype= np.float64),
... 'simple_int': np.array([4, 5, 6], dtype= np.int64),
... 'nan_variations': np.array(['np.nan', 'nan', np.nan], dtype=object),
... 'fancy_content': np.array([4, 'x', [1, 2]], dtype=object),
... }, index=pd.Index([0, '1', 2], dtype='object'))
simple_float simple_int nan_variations fancy_content
0 1.0 4 np.nan 4
1 2.0 5 nan x
2 3.0 6 NaN [1, 2]
A:
Expanding on other answers a little by adding NaT as a type.
def frame_to_code(frame):
convert = str(frame.to_dict()).replace(" nan"," float('nan')").replace(" NaT"," pd.NaT")
return f"df = pd.DataFrame({convert})"
|
Pandas Dataframe to Code
|
If I have an existing pandas dataframe, is there a way to generate the python code, which when executed in another python script, will reproduce that dataframe.
e.g.
In[1]: df
Out[1]:
income user
0 40000 Bob
1 50000 Jane
2 42000 Alice
In[2]: someFunToWriteDfCode(df)
Out[2]:
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],
...: 'income': [40000, 50000, 42000]})
|
[
"You could try to use the to_dict() method on DataFrame:\nprint \"df = pd.DataFrame( %s )\" % (str(df.to_dict()))\n\nIf your data contains NaN's, you'll have to replace them with float('nan'):\nprint \"df = pd.DataFrame( %s )\" % (str(df.to_dict()).replace(\" nan\",\" float('nan')\"))\n\n",
"I always used this code which help me much\ndef gen_code(df):\n return 'pickle.loads({})'.format(pickle.dumps(df))\n\nimport pickle\ncode_string = gen_code(df)\ncode_string\n\nSo now you can copy the output of the code_string and paste it as follow to that string variable A\nA= 'Paste your code_string here'\nimport pickle\ndf=eval(A)\n\nThis had helped me copy and past data frames in such platform \n",
"Here's another approach that does not use dicts\nimport numpy as np\n\ndef dataframe_to_code(df):\n data = np.array2string(df.to_numpy(), separator=', ')\n data = data.replace(\" nan\", \" float('nan')\")\n cols = df.columns.tolist()\n return f\"\"\"df = pd.DataFrame({data}, columns={cols})\"\"\"\n\nThe data.replace(\" nan\", \" float('nan')\") is optional and was inspired by madokis excellent answer.\nNote that np.array2string only works for numpy versions 1.11 and higher.\nI recommend using https://github.com/psf/black to format the output\n",
"more general solution\nSupported pd.DataFrame attributes:\n\ndtype of each column\nstrings with substring 'nan'\nindex\n\ncode\nimport numpy as np\nimport pandas as pd\nimport re\n\ndef _values_to_code(vals):\n \"\"\"\n Code representation of values\n\n Parameters\n ----------\n vals : List\n\n Returns\n -------\n str :\n vals as code string\n \"\"\"\n values = str(vals)\n values = re.sub(r\" nan(?<![,\\]])\", \" np.nan\", values)\n return values\n\ndef _dtype_to_code(dtype):\n \"\"\"\n Code representation of dtypes\n\n Parameters\n ----------\n dtypes : datatype\n dtype to convert. Example: np.float64\n\n Returns\n -------\n str :\n dtype as code string\n \"\"\"\n dtype = str(dtype)\n dtype = re.sub(r\"float64\", \" np.float64\", dtype)\n dtype = re.sub(r\"int64\", \" np.int64\", dtype)\n return dtype\n\n\ndef df_to_code(df):\n code = \"pd.DataFrame({\"\n\n # columns with values\n for col in df.columns:\n values = _values_to_code(df[col].tolist())\n dtype = _dtype_to_code(df.dtypes[col])\n code += f'\\n\\t\\'{col}\\': np.array({values}, dtype={dtype}),'\n code += '\\n}'\n\n # index\n values = _values_to_code(df.index)\n dtype = _dtype_to_code(df.index.dtype)\n code += f', index=pd.{values}'\n\n code += ')'\n return code\n\n\nif __name__ == \"__main__\":\n df = pd.DataFrame({\n 'simple_float': np.array([1, 2, 3], dtype=float),\n 'simple_int': np.array([4, 5, 6], dtype=int),\n 'nan_variations': np.array(['np.nan', 'nan', np.nan], dtype=object),\n 'fancy_content': np.array([4, 'x', [1, 2]], dtype=object),\n }, index = [0, '1', 2])\n\n # small unittest\n exec('df2 = ' + df_to_code(df))\n assert df.equals(df2)\n\n print(df_to_code(df))\n\noutput\npd.DataFrame({\n 'simple_float': np.array([1.0, 2.0, 3.0], dtype= np.float64),\n 'simple_int': np.array([4, 5, 6], dtype= np.int64),\n 'nan_variations': np.array(['np.nan', 'nan', np.nan], dtype=object),\n 'fancy_content': np.array([4, 'x', [1, 2]], dtype=object),\n}, index=pd.Index([0, '1', 2], dtype='object'))\n\nYou can directly paste the output into a python console and enjoy ;)\npython console demonstration\n>>> import numpy as np\n>>> import pandas as pd\n>>> pd.DataFrame({\n... 'simple_float': np.array([1.0, 2.0, 3.0], dtype= np.float64),\n... 'simple_int': np.array([4, 5, 6], dtype= np.int64),\n... 'nan_variations': np.array(['np.nan', 'nan', np.nan], dtype=object),\n... 'fancy_content': np.array([4, 'x', [1, 2]], dtype=object),\n... }, index=pd.Index([0, '1', 2], dtype='object'))\n simple_float simple_int nan_variations fancy_content\n0 1.0 4 np.nan 4\n1 2.0 5 nan x\n2 3.0 6 NaN [1, 2]\n\n",
"Expanding on other answers a little by adding NaT as a type.\ndef frame_to_code(frame):\n convert = str(frame.to_dict()).replace(\" nan\",\" float('nan')\").replace(\" NaT\",\" pd.NaT\")\n return f\"df = pd.DataFrame({convert})\"\n\n"
] |
[
30,
1,
1,
0,
0
] |
[
"You can first save the dataframe you have, and then load in another python script when necessary. You can do it with two packages: pickle and shelve.\nTo do it with pickle:\nimport pandas as pd\nimport pickle\ndf = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], \n 'income': [40000, 50000, 42000]})\nwith open('dataframe', 'wb') as pfile:\n pickle.dump(df, pfile) # save df in a file named \"dataframe\"\n\nTo read the dataframe in another file:\nimport pickle\nwith open('dataframe', 'rb') as pfile:\n df2 = pickle.load(pfile) # read the dataframe stored in file \"dataframe\"\n print(df2)\n\nOutput:\n income user\n0 40000 Bob\n1 50000 Jane\n2 42000 Alice\n\nTo do it with shelve:\nimport pandas as pd\nimport shelve\ndf = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], \n 'income': [40000, 50000, 42000]})\nwith shelve.open('dataframe2') as shelf:\n shelf['df'] = df # store the dataframe in file \"dataframe\"\n\nTo read the dataframe in another file:\nimport shelve\nwith shelve.open('dataframe2') as shelf:\n print(shelf['df']) # read the dataframe \n\nOutput:\n income user\n0 40000 Bob\n1 50000 Jane\n2 42000 Alice\n\n"
] |
[
-1
] |
[
"pandas",
"python"
] |
stackoverflow_0041769882_pandas_python.txt
|
Q:
Why is my Python program returning empty instead of printing out my file?
My Code
File From Teacher
I've tried anything I can think of for "Task 1" which is written in the green comment. Also, when I downloaded "sample.txt" it downloaded as "sample-1.txt" as its name but I'm not sure if it needs the second ".txt" in the code. Thank you.
Code:
"""Task 1: Write a program to read each line from the file sample.txt, and print your original contents of the file.
Task2: Add the following line to the sample.txt file :
"Aaron Woods 1122 123 324 45 88 1561 9 18"
and print your new updated file.
Task 3: Define a function that returns a list that contains information as follows:
[['Cobb' , 'Ty' , 3747.5],[],..,['Smoltz' , 'John' , 293.5],['Woods' , ' Aaron' , 624.00]]
where , 3747.5 is an average calculated by:
Ty Cobb => avg = (13099+11434+3053+724+295+117+1249+9)/8
Same way calculate average for all other players and build the list in the function and return that to main.
Also, note that the last name and first name positions have changed.
Task4: Sort the new list returned by the function, such that the player having least average is printed first and the highest average is printed last."""
#Task 1
file = open("sample-1.txt.txt", "w")
print(file)
file.close()
A:
file is a file object, not the text contained in the file. If you just want to print the contents of the file use print(file.read())
If you want to iterate over every line in the file then this is a very common way of doing so:
with open("sample-1.txt.txt", "r+") as file:
for line in file:
# do stuff here
Using the with is so you don't need to remember to close the file afterwards.
|
Why is my Python program returning empty instead of printing out my file?
|
My Code
File From Teacher
I've tried anything I can think of for "Task 1" which is written in the green comment. Also, when I downloaded "sample.txt" it downloaded as "sample-1.txt" as its name but I'm not sure if it needs the second ".txt" in the code. Thank you.
Code:
"""Task 1: Write a program to read each line from the file sample.txt, and print your original contents of the file.
Task2: Add the following line to the sample.txt file :
"Aaron Woods 1122 123 324 45 88 1561 9 18"
and print your new updated file.
Task 3: Define a function that returns a list that contains information as follows:
[['Cobb' , 'Ty' , 3747.5],[],..,['Smoltz' , 'John' , 293.5],['Woods' , ' Aaron' , 624.00]]
where , 3747.5 is an average calculated by:
Ty Cobb => avg = (13099+11434+3053+724+295+117+1249+9)/8
Same way calculate average for all other players and build the list in the function and return that to main.
Also, note that the last name and first name positions have changed.
Task4: Sort the new list returned by the function, such that the player having least average is printed first and the highest average is printed last."""
#Task 1
file = open("sample-1.txt.txt", "w")
print(file)
file.close()
|
[
"file is a file object, not the text contained in the file. If you just want to print the contents of the file use print(file.read())\nIf you want to iterate over every line in the file then this is a very common way of doing so:\nwith open(\"sample-1.txt.txt\", \"r+\") as file:\n for line in file:\n # do stuff here\n\nUsing the with is so you don't need to remember to close the file afterwards.\n"
] |
[
0
] |
[] |
[] |
[
"file",
"python"
] |
stackoverflow_0074554723_file_python.txt
|
Q:
Multiple serial connections in separate dedicated threads with Tkinter using serial ReaderThread
I want to create and maintain multiple non-blocking serial connections with some peripherals over UART. Truthfully, this is an expansion of this question about tkinter and multithreading
Domarm suggests the following as a solution to the original question of creating a new thread to handle receiving serial data without blocking the main script. (In the code below I left out the Raw data reader class for simplicity here).
import tkinter as tk
from serial import Serial
from serial.threaded import ReaderThread, Protocol, LineReader
class SerialReaderProtocolLine(LineReader):
tk_listener = None
TERMINATOR = b'\n\r'
def connection_made(self, transport):
"""Called when reader thread is started"""
if self.tk_listener is None:
raise Exception("tk_listener must be set before connecting to the socket!")
super().connection_made(transport)
print("Connected, ready to receive data...")
def handle_line(self, line):
"""New line waiting to be processed"""
# Execute our callback in tk
self.tk_listener.after(0, self.tk_listener.on_data, line)
class MainFrame(tk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.listbox = tk.Listbox(self)
self.listbox.pack()
self.pack()
def on_data(self, data):
print("Called from tk Thread:", data)
self.listbox.insert(tk.END, data)
if __name__ == '__main__':
app = tk.Tk()
main_frame = MainFrame()
# Set listener to our reader
SerialReaderProtocolLine.tk_listener = main_frame
# Initiate serial port
serial_port = Serial("/dev/ttyUSB0")
# Initiate ReaderThread
reader = ReaderThread(serial_port, SerialReaderProtocolLine)
# Start reader
reader.start()
app.mainloop()
This solution works well for a single connection, but what if I want to expand this so I can manage multiple connections at once?
Since this code structure is using the SerialReaderProtocolLine class variable tk_listener, I am unsure of how to go about making this modular so that I can create multiple ReaderThreads with each their own listeners.
Here is an example of me trying to move the class variable tk_listener into a constructor to allow for the creation of a new instance of SerialReaderProtocolLine, which I then try to pass into a new ReaderThread. From that, I get a type error, "TypeError: 'SerialReaderProtocolLine' object is not callable". This error is thrown when I try to pass an instance of SerialReaderProtocolLine to ReaderThread.
import tkinter as tk
from serial import Serial
from serial.threaded import ReaderThread, LineReader
class SerialReaderProtocolLine(LineReader):
def __init__(self, listener, *args, **kwargs):
super().__init__(*args, **kwargs)
self.tk_listener = listener
self.TERMINATOR = b'\n\r'
def connection_made(self, transport):
"""Called when reader thread is started"""
if self.tk_listener is None:
raise Exception("tk_listener must be set before connecting to the socket!")
super().connection_made(transport)
print("Connected, ready to receive data...")
def handle_line(self, line):
"""New line waiting to be processed"""
# Execute our callback in tk
self.tk_listener.after(0, self.tk_listener.on_data, line)
class MainFrame(tk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.listbox = tk.Listbox(self)
self.listbox.pack()
self.pack()
def on_data(self, data):
print("Called from tk Thread:", data)
self.listbox.insert(tk.END, data)
if __name__ == '__main__':
app = tk.Tk()
main_frame1 = MainFrame()
main_frame2 = MainFrame()
# Set listener to our reader
reader_listener1 = SerialReaderProtocolLine(main_frame1)
reader_listener2 = SerialReaderProtocolLine(main_frame2)
# Initiate serial port
serial_port1 = Serial("/dev/ttyUSB0")
serial_port2 = Serial("/dev/ttyUSB1")
# Initiate ReaderThread
reader1 = ReaderThread(serial_port1, reader_listener1)
reader2 = ReaderThread(serial_port2, reader_listener2)
# Start reader
reader1.start()
reader2.start()
app.mainloop()
So because it looks like ReaderThread is trying to create a new instance of SerialProtocolLine, I now try a different approach where I pass the SerialProtocolLine class twice to two different ReaderThread constructors. I reassign the tk_listener class variable inbetween ReaderThread instantiation calls...and this bluescreens my computer upon the first receipt of data!
if __name__ == '__main__':
app = tk.Tk()
main_frame0 = MainFrame()
main_frame1 = MainFrame()
# Set listener to our reader
SerialReaderProtocolLine.tk_listener = main_frame0
serial_port0 = Serial("/dev/ttyUSB0")
reader0 = ReaderThread(serial_port0, SerialReaderProtocolLine)
# Initiate serial port
SerialReaderProtocolLine.tk_listener = main_frame1
serial_port1 = Serial("/dev/ttyUSB1")
reader1 = ReaderThread(serial_port1, SerialReaderProtocolLine)
# Start reader
reader0.start()
reader1.start()
app.mainloop()
Any suggestions on how to go about making this modular?
A:
You can pass the instance of MainFrame to SerialReaderProtocolLine class and use functools.partial to pass this extra argument in ReaderThread(...).
Below is the updated code (note that my platform is Windows, so the com ports used are "COM1" and "COM3", change them to the com ports in your platform):
from functools import partial
import tkinter as tk
from serial import Serial
from serial.threaded import ReaderThread, LineReader
class SerialReaderProtocolLine(LineReader):
def __init__(self, tk_listener):
super().__init__()
self.tk_listener = tk_listener
def connection_made(self, transport):
super().connection_made(transport)
self.handle_line(f"Connected {self.tk_listener}, ready to receive data ...")
def handle_line(self, line):
self.tk_listener.after(1, self.tk_listener.on_data, line)
class MainFrame(tk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.listbox = tk.Listbox(self, width=60)
self.listbox.pack()
#self.pack() # it is not recommended to pack itself, let the parent do it
def on_data(self, data):
print("Called from tk Thread:", data)
self.listbox.insert(tk.END, data)
if __name__ == "__main__":
app = tk.Tk()
main_frame1 = MainFrame(app, name="listener1")
main_frame2 = MainFrame(app, name="listener2")
main_frame1.pack(side="left")
main_frame2.pack(side="left")
serial_port1 = Serial("COM1") # change to your required port name
serial_port2 = Serial("COM3") # change to your required port name
reader1 = ReaderThread(serial_port1, partial(SerialReaderProtocolLine, main_frame1))
reader2 = ReaderThread(serial_port2, partial(SerialReaderProtocolLine, main_frame2))
reader1.start()
reader2.start()
app.mainloop()
The result:
|
Multiple serial connections in separate dedicated threads with Tkinter using serial ReaderThread
|
I want to create and maintain multiple non-blocking serial connections with some peripherals over UART. Truthfully, this is an expansion of this question about tkinter and multithreading
Domarm suggests the following as a solution to the original question of creating a new thread to handle receiving serial data without blocking the main script. (In the code below I left out the Raw data reader class for simplicity here).
import tkinter as tk
from serial import Serial
from serial.threaded import ReaderThread, Protocol, LineReader
class SerialReaderProtocolLine(LineReader):
tk_listener = None
TERMINATOR = b'\n\r'
def connection_made(self, transport):
"""Called when reader thread is started"""
if self.tk_listener is None:
raise Exception("tk_listener must be set before connecting to the socket!")
super().connection_made(transport)
print("Connected, ready to receive data...")
def handle_line(self, line):
"""New line waiting to be processed"""
# Execute our callback in tk
self.tk_listener.after(0, self.tk_listener.on_data, line)
class MainFrame(tk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.listbox = tk.Listbox(self)
self.listbox.pack()
self.pack()
def on_data(self, data):
print("Called from tk Thread:", data)
self.listbox.insert(tk.END, data)
if __name__ == '__main__':
app = tk.Tk()
main_frame = MainFrame()
# Set listener to our reader
SerialReaderProtocolLine.tk_listener = main_frame
# Initiate serial port
serial_port = Serial("/dev/ttyUSB0")
# Initiate ReaderThread
reader = ReaderThread(serial_port, SerialReaderProtocolLine)
# Start reader
reader.start()
app.mainloop()
This solution works well for a single connection, but what if I want to expand this so I can manage multiple connections at once?
Since this code structure is using the SerialReaderProtocolLine class variable tk_listener, I am unsure of how to go about making this modular so that I can create multiple ReaderThreads with each their own listeners.
Here is an example of me trying to move the class variable tk_listener into a constructor to allow for the creation of a new instance of SerialReaderProtocolLine, which I then try to pass into a new ReaderThread. From that, I get a type error, "TypeError: 'SerialReaderProtocolLine' object is not callable". This error is thrown when I try to pass an instance of SerialReaderProtocolLine to ReaderThread.
import tkinter as tk
from serial import Serial
from serial.threaded import ReaderThread, LineReader
class SerialReaderProtocolLine(LineReader):
def __init__(self, listener, *args, **kwargs):
super().__init__(*args, **kwargs)
self.tk_listener = listener
self.TERMINATOR = b'\n\r'
def connection_made(self, transport):
"""Called when reader thread is started"""
if self.tk_listener is None:
raise Exception("tk_listener must be set before connecting to the socket!")
super().connection_made(transport)
print("Connected, ready to receive data...")
def handle_line(self, line):
"""New line waiting to be processed"""
# Execute our callback in tk
self.tk_listener.after(0, self.tk_listener.on_data, line)
class MainFrame(tk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.listbox = tk.Listbox(self)
self.listbox.pack()
self.pack()
def on_data(self, data):
print("Called from tk Thread:", data)
self.listbox.insert(tk.END, data)
if __name__ == '__main__':
app = tk.Tk()
main_frame1 = MainFrame()
main_frame2 = MainFrame()
# Set listener to our reader
reader_listener1 = SerialReaderProtocolLine(main_frame1)
reader_listener2 = SerialReaderProtocolLine(main_frame2)
# Initiate serial port
serial_port1 = Serial("/dev/ttyUSB0")
serial_port2 = Serial("/dev/ttyUSB1")
# Initiate ReaderThread
reader1 = ReaderThread(serial_port1, reader_listener1)
reader2 = ReaderThread(serial_port2, reader_listener2)
# Start reader
reader1.start()
reader2.start()
app.mainloop()
So because it looks like ReaderThread is trying to create a new instance of SerialProtocolLine, I now try a different approach where I pass the SerialProtocolLine class twice to two different ReaderThread constructors. I reassign the tk_listener class variable inbetween ReaderThread instantiation calls...and this bluescreens my computer upon the first receipt of data!
if __name__ == '__main__':
app = tk.Tk()
main_frame0 = MainFrame()
main_frame1 = MainFrame()
# Set listener to our reader
SerialReaderProtocolLine.tk_listener = main_frame0
serial_port0 = Serial("/dev/ttyUSB0")
reader0 = ReaderThread(serial_port0, SerialReaderProtocolLine)
# Initiate serial port
SerialReaderProtocolLine.tk_listener = main_frame1
serial_port1 = Serial("/dev/ttyUSB1")
reader1 = ReaderThread(serial_port1, SerialReaderProtocolLine)
# Start reader
reader0.start()
reader1.start()
app.mainloop()
Any suggestions on how to go about making this modular?
|
[
"You can pass the instance of MainFrame to SerialReaderProtocolLine class and use functools.partial to pass this extra argument in ReaderThread(...).\nBelow is the updated code (note that my platform is Windows, so the com ports used are \"COM1\" and \"COM3\", change them to the com ports in your platform):\nfrom functools import partial\nimport tkinter as tk\nfrom serial import Serial\nfrom serial.threaded import ReaderThread, LineReader\n\nclass SerialReaderProtocolLine(LineReader):\n def __init__(self, tk_listener):\n super().__init__()\n self.tk_listener = tk_listener\n\n def connection_made(self, transport):\n super().connection_made(transport)\n self.handle_line(f\"Connected {self.tk_listener}, ready to receive data ...\")\n\n def handle_line(self, line):\n self.tk_listener.after(1, self.tk_listener.on_data, line)\n\nclass MainFrame(tk.Frame):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.listbox = tk.Listbox(self, width=60)\n self.listbox.pack()\n #self.pack() # it is not recommended to pack itself, let the parent do it\n\n def on_data(self, data):\n print(\"Called from tk Thread:\", data)\n self.listbox.insert(tk.END, data)\n\nif __name__ == \"__main__\":\n app = tk.Tk()\n\n main_frame1 = MainFrame(app, name=\"listener1\")\n main_frame2 = MainFrame(app, name=\"listener2\")\n\n main_frame1.pack(side=\"left\")\n main_frame2.pack(side=\"left\")\n\n serial_port1 = Serial(\"COM1\") # change to your required port name\n serial_port2 = Serial(\"COM3\") # change to your required port name\n\n reader1 = ReaderThread(serial_port1, partial(SerialReaderProtocolLine, main_frame1))\n reader2 = ReaderThread(serial_port2, partial(SerialReaderProtocolLine, main_frame2))\n\n reader1.start()\n reader2.start()\n\n app.mainloop()\n\nThe result:\n\n"
] |
[
0
] |
[] |
[] |
[
"class",
"multithreading",
"pyserial",
"python",
"tkinter"
] |
stackoverflow_0074552205_class_multithreading_pyserial_python_tkinter.txt
|
Q:
How to compare two different true or false columns and get a confusion matrix? Python
So I have 2 different true or false results that tested the same column. So test 1 has the wrong results and test 2 has the correct results. Is there python code that can compare these two results and obtain a confusion matrix result (true positives, false positives, false negatives, and true negatives)?
For example:
Test1
a True
b True
c False
d False
e True
f True
g True
Test2
a True
b True
c True
d True
e True
f True
g False
A:
You can do this with numpy
I will ignore the fact that the tests have letters, and just use an array instead
#assume:
#reponses = [...list of booleans...]
#ground_truth = [...list of booleans...]
import numpy as np
responses = np.array(responses)
ground_truth = np.array(ground_truth)
true_positives = np.logical_and(responses,ground_truth)
true_negatives = np.logical_and(np.logical_not(responses),np.logical_not(ground_truth))
false_positives = np.logical_and(responses,np.logical_not(ground_truth))
false_negatives = np.logical_and(np.logical_not(responses),ground_truth)
num_true_positives = np.count_nonzero(true_positives)
num_true_negatives = np.count_nonzero(true_negatives)
num_false_positive = np.count_nonzero(false_positives)
num_false_negatives = np.count_nonzero(false_negatives)
confusion_matrix = np.array([
[num_true_positives,num_false_positives],
[num_true_negatives,num_false_negatives]
])
I'm not sure if that's the correct convention for the confusion matrix, but you can rearrange it in your own code
P.S.:
You can also use sklearn:
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html
A:
Is there python code that can compare these two results and obtain a confusion matrix result (true positives, false positives, false negatives, and true negatives)?
Assuming Test1 and Test2 are Pandas Series objects,
True positives: Test1 & Test2
False positives: Test1 & (Test2 == False)
False negatives: (Test1==False) & Test2
True negatives: (Test1==False) & (Test2==False)
To get the number of True values in a Series, use Series.count(), For example, the number of true positives would be (Test1 & Test2).count().
Assuming you want the confusion matrix as a numpy array, you just fill in the cells appropriately:
confusion = np.zeros((2,2))
confusion[0,0] = (Test1 & Test2).count()
and so on...
|
How to compare two different true or false columns and get a confusion matrix? Python
|
So I have 2 different true or false results that tested the same column. So test 1 has the wrong results and test 2 has the correct results. Is there python code that can compare these two results and obtain a confusion matrix result (true positives, false positives, false negatives, and true negatives)?
For example:
Test1
a True
b True
c False
d False
e True
f True
g True
Test2
a True
b True
c True
d True
e True
f True
g False
|
[
"You can do this with numpy\nI will ignore the fact that the tests have letters, and just use an array instead\n#assume: \n#reponses = [...list of booleans...]\n#ground_truth = [...list of booleans...]\n\nimport numpy as np\nresponses = np.array(responses)\nground_truth = np.array(ground_truth)\n\ntrue_positives = np.logical_and(responses,ground_truth)\ntrue_negatives = np.logical_and(np.logical_not(responses),np.logical_not(ground_truth))\nfalse_positives = np.logical_and(responses,np.logical_not(ground_truth))\nfalse_negatives = np.logical_and(np.logical_not(responses),ground_truth)\n\nnum_true_positives = np.count_nonzero(true_positives)\nnum_true_negatives = np.count_nonzero(true_negatives)\nnum_false_positive = np.count_nonzero(false_positives)\nnum_false_negatives = np.count_nonzero(false_negatives)\n\nconfusion_matrix = np.array([\n [num_true_positives,num_false_positives],\n [num_true_negatives,num_false_negatives]\n])\n\nI'm not sure if that's the correct convention for the confusion matrix, but you can rearrange it in your own code\nP.S.:\nYou can also use sklearn:\nhttps://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html\n",
"\nIs there python code that can compare these two results and obtain a confusion matrix result (true positives, false positives, false negatives, and true negatives)?\n\nAssuming Test1 and Test2 are Pandas Series objects,\nTrue positives: Test1 & Test2\nFalse positives: Test1 & (Test2 == False)\nFalse negatives: (Test1==False) & Test2\nTrue negatives: (Test1==False) & (Test2==False)\nTo get the number of True values in a Series, use Series.count(), For example, the number of true positives would be (Test1 & Test2).count().\nAssuming you want the confusion matrix as a numpy array, you just fill in the cells appropriately:\nconfusion = np.zeros((2,2))\nconfusion[0,0] = (Test1 & Test2).count()\n\nand so on...\n"
] |
[
1,
1
] |
[] |
[] |
[
"boolean",
"confusion_matrix",
"python"
] |
stackoverflow_0074554750_boolean_confusion_matrix_python.txt
|
Q:
Read txt file from specific of line to a certain line base on string
I am trying to write some function of data, however, my data is like this:
noms sommets
0000 Abbesses
0001 Alexandre Dumas
0002 Paris
0004 Nice
...
coord sommets
0000 308 536
0001 472 386
0002 193 404
What I want to is to access from nom sommets to 0004 Nice without knowing the number of line but base on the string value of txt
A:
Read text file to list split based on key word sommets
with open('text.txt') as file:
lines = [line.rstrip() for line in file]
test_loop = []
for item in lines:
if 'sommets' in item:
test_loop.append([item])
else:
test_loop[-1].append(item)
print(test_loop)
which gives list of lists #.
[['noms sommets', '0000 Abbesses', '0001 Alexandre Dumas', '0002 Paris', '0004 Nice', '...'], ['coord sommets', '0000 308 536', '0001 472 386', '0002 193 404']]
If you want to access first set then.
for sublist in test_loop[0]:
print(sublist)
Gives #
noms sommets
0000 Abbesses
0001 Alexandre Dumas
0002 Paris
0004 Nice
...
A:
we can read the whole txt file as single string then use regex to match the keyword.
re.DOTALL modifier will make '.' match any character including newline
with open('text.txt') as f:
txt = f.read()
match = re.search('noms sommets.*?0004 Nice', a, re.DOTALL).group()
# match = 'noms sommets\n0000 Abbesses\n0001 Alexandre Dumas\n0002 Paris\n0004 Nice'
then, you can use match as variable or split it into list
>>> print(match)
noms sommets
0000 Abbesses
0001 Alexandre Dumas
0002 Paris
0004 Nice
>>>
|
Read txt file from specific of line to a certain line base on string
|
I am trying to write some function of data, however, my data is like this:
noms sommets
0000 Abbesses
0001 Alexandre Dumas
0002 Paris
0004 Nice
...
coord sommets
0000 308 536
0001 472 386
0002 193 404
What I want to is to access from nom sommets to 0004 Nice without knowing the number of line but base on the string value of txt
|
[
"Read text file to list split based on key word sommets\nwith open('text.txt') as file:\n lines = [line.rstrip() for line in file]\n\ntest_loop = []\nfor item in lines:\n if 'sommets' in item: \n test_loop.append([item])\n else: \n test_loop[-1].append(item)\nprint(test_loop)\n\nwhich gives list of lists #.\n[['noms sommets', '0000 Abbesses', '0001 Alexandre Dumas', '0002 Paris', '0004 Nice', '...'], ['coord sommets', '0000 308 536', '0001 472 386', '0002 193 404']]\n\nIf you want to access first set then.\nfor sublist in test_loop[0]:\n print(sublist)\n\nGives #\nnoms sommets\n0000 Abbesses\n0001 Alexandre Dumas\n0002 Paris\n0004 Nice\n...\n\n",
"we can read the whole txt file as single string then use regex to match the keyword.\nre.DOTALL modifier will make '.' match any character including newline\nwith open('text.txt') as f:\n txt = f.read()\n\nmatch = re.search('noms sommets.*?0004 Nice', a, re.DOTALL).group()\n# match = 'noms sommets\\n0000 Abbesses\\n0001 Alexandre Dumas\\n0002 Paris\\n0004 Nice'\n\nthen, you can use match as variable or split it into list\n>>> print(match)\nnoms sommets\n0000 Abbesses\n0001 Alexandre Dumas\n0002 Paris\n0004 Nice\n>>>\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0074541919_python_string.txt
|
Q:
How to replace original values in list according to the indexed values of the original values
I have these indexed values like these:
{0:0, 22:1 , 334: 2 , 6666:3}
And have a 2D list:
[[0,22],[22,334,6666],[22,334],[0,6666]]
I am expecting something like this:
[[0,1],[1,2,3],[1,2],[0,3]]
A:
Sure! Try something like:
indexes = {0: 0, 22: 1, 334: 2, 6666: 3}
src = [[0,22],[22,334,6666],[22,334],[0,6666]]
result = [[indexes.get(key) for key in sublst] for sublst in src]
Unwrapping the list comprehension you've got something like:
result = []
for sublst in src:
result_sublst = []
for key in sublst:
if key in indexes:
value = indexes[key]
result_sublst.append(value)
else:
# if your list contains a value that isn't in the
# indexes table
result_sublst.append(None)
result.append(result_sublst)
|
How to replace original values in list according to the indexed values of the original values
|
I have these indexed values like these:
{0:0, 22:1 , 334: 2 , 6666:3}
And have a 2D list:
[[0,22],[22,334,6666],[22,334],[0,6666]]
I am expecting something like this:
[[0,1],[1,2,3],[1,2],[0,3]]
|
[
"Sure! Try something like:\nindexes = {0: 0, 22: 1, 334: 2, 6666: 3}\n\nsrc = [[0,22],[22,334,6666],[22,334],[0,6666]]\nresult = [[indexes.get(key) for key in sublst] for sublst in src]\n\nUnwrapping the list comprehension you've got something like:\nresult = []\nfor sublst in src:\n result_sublst = []\n for key in sublst:\n if key in indexes:\n value = indexes[key]\n result_sublst.append(value)\n else:\n # if your list contains a value that isn't in the\n # indexes table\n result_sublst.append(None)\n result.append(result_sublst)\n\n"
] |
[
1
] |
[] |
[] |
[
"dictionary",
"numpy",
"python"
] |
stackoverflow_0074554834_dictionary_numpy_python.txt
|
Q:
get text files name(number) from a directory, and use the file name(number) to look for data in a separate text file
I am new to python. I have a few text files in a directory, and a seperate textfile maintained the original links for each of the text files. Ie, I have 1.txt,2.txt and 3.txt saved in the directory, and I have weblink text file(line 1(wiki.com/a) is the link for 1.txt, line 2(wiki.com/b is the link for 2.txt...). I am able to get the text file names, but I can't use the result to find the links from the weblink text file.
#first part
path = 'C:\\Users\\PycharmProjects\\pythonProject1\\Document'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print(files) #result from here is ['1', '2', '3']
#second part
file = open("C:\\Users\\PycharmProjects\\pythonProject1\\link.txt")
specified_lines = files #files are taking the result from first part
for pos, l_num in enumerate(file):
if pos in specified_lines:
print(l_num)
if i use specified_lines = [0,1,2] then the function works, how do i incorporate the output from my first part into my second part? As of right now, specified_lines = files in the second part return nothing.
A:
Hope this helps.
Try printing pos, I see its 0 based so you may want to offset pos
Try converting the pos from integer to string before searching
import os
path = '.'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print(files) #result from here is ['1', '2', '3']
#second part
file = open("weblink")
specified_lines = files #files are taking the result from first part
for pos, l_num in enumerate(file):
print(pos)
if str(pos+1) in specified_lines:
print(l_num)
Output from my try:
['orig', 'weblink', 'notes', '3', '2', '1']
0
wiki.com/a
1
wiki.com/b
2
wiki.com/c
|
get text files name(number) from a directory, and use the file name(number) to look for data in a separate text file
|
I am new to python. I have a few text files in a directory, and a seperate textfile maintained the original links for each of the text files. Ie, I have 1.txt,2.txt and 3.txt saved in the directory, and I have weblink text file(line 1(wiki.com/a) is the link for 1.txt, line 2(wiki.com/b is the link for 2.txt...). I am able to get the text file names, but I can't use the result to find the links from the weblink text file.
#first part
path = 'C:\\Users\\PycharmProjects\\pythonProject1\\Document'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print(files) #result from here is ['1', '2', '3']
#second part
file = open("C:\\Users\\PycharmProjects\\pythonProject1\\link.txt")
specified_lines = files #files are taking the result from first part
for pos, l_num in enumerate(file):
if pos in specified_lines:
print(l_num)
if i use specified_lines = [0,1,2] then the function works, how do i incorporate the output from my first part into my second part? As of right now, specified_lines = files in the second part return nothing.
|
[
"Hope this helps.\n\nTry printing pos, I see its 0 based so you may want to offset pos\nTry converting the pos from integer to string before searching\n\nimport os\n\npath = '.'\nfiles = [os.path.splitext(filename)[0] for filename in os.listdir(path)]\nprint(files) #result from here is ['1', '2', '3']\n\n#second part\nfile = open(\"weblink\")\nspecified_lines = files #files are taking the result from first part\n\nfor pos, l_num in enumerate(file):\n print(pos)\n if str(pos+1) in specified_lines:\n print(l_num)\n\nOutput from my try:\n['orig', 'weblink', 'notes', '3', '2', '1']\n0\nwiki.com/a\n\n1\nwiki.com/b\n\n2\nwiki.com/c\n\n"
] |
[
1
] |
[] |
[] |
[
"directory",
"list",
"python",
"text_files"
] |
stackoverflow_0074554395_directory_list_python_text_files.txt
|
Q:
Python kivy [CRITICAL] [Clock ] Warning, too much iteration done before the next frame
I'm making a calendar app in for mobile in kivy and wantto make a scrollview for a stack layout but keep getting this error and I don't know why
python code
`
from kivymd.app import MDApp
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.stacklayout import StackLayout
from calendar import monthrange
import calendar
year = 2022
month_int = 11
num_days = monthrange(year, month_int)[1]
weekheader = str(calendar.weekheader(3))
days = weekheader.split(" ")
days_length = len(days)
month = calendar.monthcalendar(year, month_int)
print(month)
start_day = month[0].count(0)
print(start_day)
class GridLayoutExample(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
for l in range(2):
label4 = Label()
self.add_widget(label4)
button2 = Button(text=str(month_int))
self.add_widget(button2)
button3 = Button(text=str(year))
self.add_widget(button3)
for k in range(3):
label3 = Label()
self.add_widget(label3)
for j in range(days_length):
label1 = Label(text=days[j], color=(0, 0, 0, 1))
self.add_widget(label1)
for g in range(start_day):
label2 = Label()
self.add_widget(label2)
for i in range(num_days):
button = Button(text=str(i + 1))
button.my_id = str(i + 1) + "-" + str(month_int) + "-" + str(year)
self.ids[str(i + 1) + "-" + str(month_int) + "-" + str(year)] = button
self.add_widget(button)
class LayoutExample(StackLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
for l in range(10):
label4 = Label(text="zeer plezant \n \n \n ha \n haha", size = self.size, color=(0, 0, 0, 1), size_hint=(None, None))
self.add_widget(label4)
button = Button(text="verwijder")
self.add_widget(button)
button = Button(text="wijzig")
self.add_widget(button)
class agenda1(MDApp):
pass
agenda1().run()
`
kv file
#:kivy 1.0
PageLayoutExample:
<PageLayoutExample@PageLayout>:
GridLayoutExample:
ScrollViewExample:
<ScrollViewExample@ScrollView>:
LayoutExample:
<GridLayoutExample>:
#left-right top-bottom
cols: 7
orientation: "lr-tb"
size: root.minimum_width, root.minimum_height
padding: ("20dp", "20dp", "20dp", "20dp")
<LayoutExample>:
cols: 1
orientation: "lr-tb"
padding: ("20dp", "20dp", "20dp", "20dp")
size_hint: 1, None
height: self.minimum_height
Did I do something wrong in my code?
I want the scrollview to scroll as far as it has to to get all the data on the screen but not go any farther than that. because I iterate over an x amount task I don't really see a way to get less iterations in
A:
Because you are using height: self.minimum_height in your LayoutExample, you must provide definite sizes for its children.
The Buttons that you add to LayoutExample have the default size_hint of (1,1), so that causes an infinite loop in the LayoutExample layout calculations. It is trying to calculate its minimum_height, so each Button height gets set to the LayoutExample height, the LayoutExample then calculates and applies a new minimum height that will hold the Buttons. The Buttons then change their size to the new size of the LayoutExample, which triggers a new calculation by LayoutExample of its minimum_height....
The fix is just to specify a size for each Button, something like:
for l in range(10):
label4 = Label(text="zeer plezant \n \n \n ha \n haha", size=self.size, color=(0, 0, 0, 1),
size_hint=(None, None))
self.add_widget(label4)
button = Button(text="verwijder", size_hint=(None, None), size=(100, 20))
self.add_widget(button)
button = Button(text="wijzig", size_hint=(None, None), size=(100, 20))
self.add_widget(button)
|
Python kivy [CRITICAL] [Clock ] Warning, too much iteration done before the next frame
|
I'm making a calendar app in for mobile in kivy and wantto make a scrollview for a stack layout but keep getting this error and I don't know why
python code
`
from kivymd.app import MDApp
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.stacklayout import StackLayout
from calendar import monthrange
import calendar
year = 2022
month_int = 11
num_days = monthrange(year, month_int)[1]
weekheader = str(calendar.weekheader(3))
days = weekheader.split(" ")
days_length = len(days)
month = calendar.monthcalendar(year, month_int)
print(month)
start_day = month[0].count(0)
print(start_day)
class GridLayoutExample(GridLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
for l in range(2):
label4 = Label()
self.add_widget(label4)
button2 = Button(text=str(month_int))
self.add_widget(button2)
button3 = Button(text=str(year))
self.add_widget(button3)
for k in range(3):
label3 = Label()
self.add_widget(label3)
for j in range(days_length):
label1 = Label(text=days[j], color=(0, 0, 0, 1))
self.add_widget(label1)
for g in range(start_day):
label2 = Label()
self.add_widget(label2)
for i in range(num_days):
button = Button(text=str(i + 1))
button.my_id = str(i + 1) + "-" + str(month_int) + "-" + str(year)
self.ids[str(i + 1) + "-" + str(month_int) + "-" + str(year)] = button
self.add_widget(button)
class LayoutExample(StackLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
for l in range(10):
label4 = Label(text="zeer plezant \n \n \n ha \n haha", size = self.size, color=(0, 0, 0, 1), size_hint=(None, None))
self.add_widget(label4)
button = Button(text="verwijder")
self.add_widget(button)
button = Button(text="wijzig")
self.add_widget(button)
class agenda1(MDApp):
pass
agenda1().run()
`
kv file
#:kivy 1.0
PageLayoutExample:
<PageLayoutExample@PageLayout>:
GridLayoutExample:
ScrollViewExample:
<ScrollViewExample@ScrollView>:
LayoutExample:
<GridLayoutExample>:
#left-right top-bottom
cols: 7
orientation: "lr-tb"
size: root.minimum_width, root.minimum_height
padding: ("20dp", "20dp", "20dp", "20dp")
<LayoutExample>:
cols: 1
orientation: "lr-tb"
padding: ("20dp", "20dp", "20dp", "20dp")
size_hint: 1, None
height: self.minimum_height
Did I do something wrong in my code?
I want the scrollview to scroll as far as it has to to get all the data on the screen but not go any farther than that. because I iterate over an x amount task I don't really see a way to get less iterations in
|
[
"Because you are using height: self.minimum_height in your LayoutExample, you must provide definite sizes for its children.\nThe Buttons that you add to LayoutExample have the default size_hint of (1,1), so that causes an infinite loop in the LayoutExample layout calculations. It is trying to calculate its minimum_height, so each Button height gets set to the LayoutExample height, the LayoutExample then calculates and applies a new minimum height that will hold the Buttons. The Buttons then change their size to the new size of the LayoutExample, which triggers a new calculation by LayoutExample of its minimum_height....\nThe fix is just to specify a size for each Button, something like:\n for l in range(10):\n label4 = Label(text=\"zeer plezant \\n \\n \\n ha \\n haha\", size=self.size, color=(0, 0, 0, 1),\n size_hint=(None, None))\n self.add_widget(label4)\n button = Button(text=\"verwijder\", size_hint=(None, None), size=(100, 20))\n self.add_widget(button)\n button = Button(text=\"wijzig\", size_hint=(None, None), size=(100, 20))\n self.add_widget(button)\n\n"
] |
[
1
] |
[] |
[] |
[
"kivy",
"kivy_language",
"kivymd",
"python",
"python_3.x"
] |
stackoverflow_0074553574_kivy_kivy_language_kivymd_python_python_3.x.txt
|
Q:
Retain strings in a column using a dictionary's value
I want to retain the string with the largest value based on a dictionary's key and value. Any suggestion to how to do it effectively?
fruit_dict = {
"Apple": 10,
"Watermelon": 20,
"Cherry": 30
}
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"name": [
"Apple, Watermelon",
"Cherry, Watermelon",
"Apple",
"Cherry, Apple",
"Cherry",
],
}
)
ID name
0 1 Apple, Watermelon
1 2 Cherry, Watermelon
2 3 Apple
3 4 Cherry, Apple
4 5 Cherry
Expected output:
ID name
0 1 Watermelon
1 2 Cherry
2 3 Apple
3 4 Cherry
4 5 Cherry
A:
One way it to use apply with max and fruit_dict.get as key:
new_df = (df.assign(name=df['name'].str.split(', ')
.apply(lambda l: max(l, key=fruit_dict.get)))
)
or, if you expect some names to be missing from the dictionary:
new_df = (df.assign(name=df['name'].str.split(', ')
.apply(lambda l: max(l, key=lambda x: fruit_dict.get(x, float('-inf'))))
)
output:
ID name
0 1 Watermelon
1 2 Cherry
2 3 Apple
3 4 Cherry
4 5 Cherry
A:
Use:
df = (df.assign(name= df['name'].str.split(', '))
.explode('name')
.assign(new = lambda x: x['name'].map(fruit_dict))
.sort_values(['ID', 'new'], ascending=[True, False])
.drop_duplicates('ID')
)
print (df)
ID name new
0 1 Watermelon 20
1 2 Cherry 30
2 3 Apple 10
3 4 Cherry 30
4 5 Cherry 30
Or:
df['new'] = df['name'].apply(lambda x: max(x.split(', '), key=fruit_dict.get))
print (df)
ID name new
0 1 Apple, Watermelon Watermelon
1 2 Cherry, Watermelon Cherry
2 3 Apple Apple
3 4 Cherry, Apple Cherry
4 5 Cherry Cherry
EDIT: If no match is returned first value:
fruit_dict = {
"Apple": 10,
"Watermelon": 20,
"Cherry": 30
}
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"name": [
"Apple, Watermelon",
"Cherry, Watermelon",
"Apple",
"Cherry, Apple",
"ooo, Cherry2, aaaa", <- changed data
],
}
)
print (df)
df1 = (df.assign(name= df['name'].str.split(', '))
.explode('name')
.assign(new = lambda x: x['name'].map(fruit_dict))
.sort_values(['ID', 'new'], ascending=[True, False])
.drop_duplicates('ID')
)
print (df1)
ID name new
0 1 Watermelon 20.0
1 2 Cherry 30.0
2 3 Apple 10.0
3 4 Cherry 30.0
4 5 ooo NaN
If need NaNs if no match:
df1['name'] = df1['name'].mask(df1.pop('new').isna())
print (df1)
ID name
0 1 Watermelon
1 2 Cherry
2 3 Apple
3 4 Cherry
4 5 NaN
df['new1'] = df['name'].apply(lambda x: max(x.split(', '), key=lambda x: fruit_dict.get(x, float('-inf'))))
df['new2'] = df['name'].apply(lambda x: max(x.split(', '), key=lambda x: fruit_dict.get(x, 0)))
df['new3'] = df['name'].apply(lambda x: max(x.split(', '), key=lambda x: fruit_dict.get(x, 1000)))
print (df)
ID name new1 new2 new3
0 1 Apple, Watermelon Watermelon Watermelon Watermelon
1 2 Cherry, Watermelon Cherry Cherry Cherry
2 3 Apple Apple Apple Apple
3 4 Cherry, Apple Cherry Cherry Cherry
4 5 ooo, Cherry2, aaaa ooo ooo ooo
A:
fruit_dict = {
"Apple": 10,
"Watermelon": 20,
"Cherry": 30
}
df.assign(name=df.name.str.split(',')).name.map(lambda x:pd.Series(fruit_dict)[x].nlargest().index.values[0])
0 Watermelon
1 Cherry
2 Apple
3 Cherry
4 Cherry
Name: name, dtype: object
|
Retain strings in a column using a dictionary's value
|
I want to retain the string with the largest value based on a dictionary's key and value. Any suggestion to how to do it effectively?
fruit_dict = {
"Apple": 10,
"Watermelon": 20,
"Cherry": 30
}
df = pd.DataFrame(
{
"ID": [1, 2, 3, 4, 5],
"name": [
"Apple, Watermelon",
"Cherry, Watermelon",
"Apple",
"Cherry, Apple",
"Cherry",
],
}
)
ID name
0 1 Apple, Watermelon
1 2 Cherry, Watermelon
2 3 Apple
3 4 Cherry, Apple
4 5 Cherry
Expected output:
ID name
0 1 Watermelon
1 2 Cherry
2 3 Apple
3 4 Cherry
4 5 Cherry
|
[
"One way it to use apply with max and fruit_dict.get as key:\nnew_df = (df.assign(name=df['name'].str.split(', ')\n .apply(lambda l: max(l, key=fruit_dict.get)))\n )\n\nor, if you expect some names to be missing from the dictionary:\nnew_df = (df.assign(name=df['name'].str.split(', ')\n .apply(lambda l: max(l, key=lambda x: fruit_dict.get(x, float('-inf'))))\n )\n\noutput:\n ID name\n0 1 Watermelon\n1 2 Cherry\n2 3 Apple\n3 4 Cherry\n4 5 Cherry\n\n",
"Use:\ndf = (df.assign(name= df['name'].str.split(', '))\n .explode('name')\n .assign(new = lambda x: x['name'].map(fruit_dict))\n .sort_values(['ID', 'new'], ascending=[True, False])\n .drop_duplicates('ID')\n )\nprint (df)\n ID name new\n0 1 Watermelon 20\n1 2 Cherry 30\n2 3 Apple 10\n3 4 Cherry 30\n4 5 Cherry 30\n\nOr:\ndf['new'] = df['name'].apply(lambda x: max(x.split(', '), key=fruit_dict.get))\nprint (df)\n ID name new\n0 1 Apple, Watermelon Watermelon\n1 2 Cherry, Watermelon Cherry\n2 3 Apple Apple\n3 4 Cherry, Apple Cherry\n4 5 Cherry Cherry\n\nEDIT: If no match is returned first value:\nfruit_dict = {\n \"Apple\": 10,\n \"Watermelon\": 20,\n \"Cherry\": 30\n}\n\ndf = pd.DataFrame(\n {\n \"ID\": [1, 2, 3, 4, 5],\n \"name\": [\n \"Apple, Watermelon\",\n \"Cherry, Watermelon\",\n \"Apple\",\n \"Cherry, Apple\",\n \"ooo, Cherry2, aaaa\", <- changed data\n ],\n }\n)\nprint (df)\n\n\ndf1 = (df.assign(name= df['name'].str.split(', '))\n .explode('name')\n .assign(new = lambda x: x['name'].map(fruit_dict))\n .sort_values(['ID', 'new'], ascending=[True, False])\n .drop_duplicates('ID')\n )\nprint (df1)\n ID name new\n0 1 Watermelon 20.0\n1 2 Cherry 30.0\n2 3 Apple 10.0\n3 4 Cherry 30.0\n4 5 ooo NaN\n\nIf need NaNs if no match:\ndf1['name'] = df1['name'].mask(df1.pop('new').isna())\nprint (df1)\n ID name\n0 1 Watermelon\n1 2 Cherry\n2 3 Apple\n3 4 Cherry\n4 5 NaN\n\n\ndf['new1'] = df['name'].apply(lambda x: max(x.split(', '), key=lambda x: fruit_dict.get(x, float('-inf'))))\n\ndf['new2'] = df['name'].apply(lambda x: max(x.split(', '), key=lambda x: fruit_dict.get(x, 0)))\n\ndf['new3'] = df['name'].apply(lambda x: max(x.split(', '), key=lambda x: fruit_dict.get(x, 1000)))\n\nprint (df)\n ID name new1 new2 new3\n0 1 Apple, Watermelon Watermelon Watermelon Watermelon\n1 2 Cherry, Watermelon Cherry Cherry Cherry\n2 3 Apple Apple Apple Apple\n3 4 Cherry, Apple Cherry Cherry Cherry\n4 5 ooo, Cherry2, aaaa ooo ooo ooo\n\n",
"fruit_dict = {\n \"Apple\": 10,\n \"Watermelon\": 20,\n \"Cherry\": 30\n}\n\ndf.assign(name=df.name.str.split(',')).name.map(lambda x:pd.Series(fruit_dict)[x].nlargest().index.values[0])\n\n0 Watermelon\n1 Cherry\n2 Apple\n3 Cherry\n4 Cherry\nName: name, dtype: object\n\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0070200649_pandas_python.txt
|
Q:
Writing to row using openpyxl?
I am trying to write a list to a row in Python using openpyxl, but to no avail.
The list contains say for example ten values. I need to open an existing worksheet, and write those ten values to their own cell, along one row.
I need to use openpyxl due to its functionality of overwriting existing worksheets compared to xlsxwriter where you can only create new worksheets.
A:
Have a look here, scroll down to the heading Writing Values to Cells.
TLDR:
>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> sheet = wb['Sheet']
>>> sheet['A1'] = 'Hello world!'
>>> sheet['A1'].value
'Hello world!
or if you prefer
sheet.cell(row=2, column=3).value = 'hello world'
Update: changed to wb['Sheet'] syntax as per @charlieclark comment, thx
Update: To write mylist into row 2
for col, val in enumerate(mylist, start=1):
sheet.cell(row=2, column=col).value = val
A:
I made a function for you. I have it in a "openpyxlutils" file on my computer.
It allows you to put either the starting row letter or number (but the letter can't be like AA or BB).
def write_row(write_sheet, row_num: int, starting_column: str or int, write_values: list):
if isinstance(starting_column, str):
starting_column = ord(starting_column.lower()) - 96
for i, value in enumerate(write_values):
write_sheet.cell(row_num, starting_column + i, value)
A:
import openpyxl as xl
wb = xl.Workbook()
ws = wb.active
mylist = ['dog', 'cat', 'fish', 'bird']
ws.append(mylist)
wb.save('myFile.xlsx')
wb.close()
|
Writing to row using openpyxl?
|
I am trying to write a list to a row in Python using openpyxl, but to no avail.
The list contains say for example ten values. I need to open an existing worksheet, and write those ten values to their own cell, along one row.
I need to use openpyxl due to its functionality of overwriting existing worksheets compared to xlsxwriter where you can only create new worksheets.
|
[
"Have a look here, scroll down to the heading Writing Values to Cells.\nTLDR:\n>>> import openpyxl\n>>> wb = openpyxl.Workbook()\n>>> sheet = wb['Sheet']\n>>> sheet['A1'] = 'Hello world!'\n>>> sheet['A1'].value\n'Hello world!\n\nor if you prefer\nsheet.cell(row=2, column=3).value = 'hello world'\n\nUpdate: changed to wb['Sheet'] syntax as per @charlieclark comment, thx\nUpdate: To write mylist into row 2\nfor col, val in enumerate(mylist, start=1):\n sheet.cell(row=2, column=col).value = val\n\n",
"I made a function for you. I have it in a \"openpyxlutils\" file on my computer.\nIt allows you to put either the starting row letter or number (but the letter can't be like AA or BB).\ndef write_row(write_sheet, row_num: int, starting_column: str or int, write_values: list):\n if isinstance(starting_column, str):\n starting_column = ord(starting_column.lower()) - 96\n for i, value in enumerate(write_values):\n write_sheet.cell(row_num, starting_column + i, value)\n\n",
"import openpyxl as xl\nwb = xl.Workbook()\nws = wb.active\nmylist = ['dog', 'cat', 'fish', 'bird']\nws.append(mylist)\nwb.save('myFile.xlsx')\nwb.close()\n\n\n"
] |
[
8,
2,
0
] |
[] |
[] |
[
"excel",
"openpyxl",
"python"
] |
stackoverflow_0033920108_excel_openpyxl_python.txt
|
Q:
Converting dates with condition
I'm trying to convert a column of dates. There are dates in 'ms' unit and Timestamp, I want to convert these dates in 'ms' unit in Timestamp too. So, I created this function:
def convert(df):
if df[df['Timestamp'].str.contains(':') == False]:
df.Timestamp = pd.to_datetime(df.Timestamp, unit='ms')
return df
df = convert(df)
But is getting this error: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I also tried to use np.where but didn't work...
A:
Your == False statement is applying to the whole dataframe/series, not just the row you want. What you could do instead is just apply your function to those rows using .loc, which will return the rows set by a condition, and the column/s you request:
def convert(df):
condition = ~df.Timestamp.str.contains(":") #where this field DOESN'T contain ":"
df.loc[condition, 'Timestamp'] = \
pd.to_datetime(df.loc[condition, 'Timestamp'], unit='ms')
return df
df = convert(df)
|
Converting dates with condition
|
I'm trying to convert a column of dates. There are dates in 'ms' unit and Timestamp, I want to convert these dates in 'ms' unit in Timestamp too. So, I created this function:
def convert(df):
if df[df['Timestamp'].str.contains(':') == False]:
df.Timestamp = pd.to_datetime(df.Timestamp, unit='ms')
return df
df = convert(df)
But is getting this error: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I also tried to use np.where but didn't work...
|
[
"Your == False statement is applying to the whole dataframe/series, not just the row you want. What you could do instead is just apply your function to those rows using .loc, which will return the rows set by a condition, and the column/s you request:\ndef convert(df):\n condition = ~df.Timestamp.str.contains(\":\") #where this field DOESN'T contain \":\"\n df.loc[condition, 'Timestamp'] = \\\n pd.to_datetime(df.loc[condition, 'Timestamp'], unit='ms')\nreturn df\n\ndf = convert(df)\n\n"
] |
[
2
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074554938_pandas_python.txt
|
Q:
How to produce a stacked bar plot for the value counts of all columns
My dataframe has more than 10 columns and each column has values like yes/no/na/not specified.
And I want to calculate the count of occurrences in each column and create stacked bar graph.
Below is the image that I need:
A:
Yes, this is possible. But you'll need to re-format your data a little first.
Here's the dataset I'm using in this example. It has the labels in the columns, and 1000 random Yes, No or Maybe responses as values.
asthma boneitis diabetes pneumonia
0 No No Yes Maybe
1 No No No Yes
2 No No No No
3 Yes No No Maybe
4 Yes No No Maybe
.. ... ... ... ...
995 No No Yes No
996 Maybe Yes Yes Yes
997 No No No Yes
998 No No No No
999 No No Maybe No
In order to format the data correctly for the plot, do this:
df2 = df.stack().groupby(level=[1]).value_counts().unstack()
# Preferred order of stacked bar elements
stack_order = ['Yes', 'Maybe', 'No']
df2 = df2[stack_order]
At this point, the data looks like this:
Yes Maybe No
asthma 83 83 834
boneitis 174 173 653
diabetes 244 260 496
pneumonia 339 363 298
Now you're ready to plot the data. Here's the code to do that:
df2.plot.bar(rot=0, stacked=True)
I'm using rot=0 to avoid rotating the text labels (they would normally be at a 45 degree angle,) and stacked=True to produce a stacked bar chart.
The plot looks like this:
Appendix
Code for generating test data set:
import pandas as pd
import numpy as np
categories = [
'asthma',
'boneitis',
'diabetes',
'pneumonia',
]
distribution = {
cat: (i + 1) / 12
for i, cat in enumerate(categories)
}
df = pd.DataFrame({
cat: np.random.choice(['Yes', 'Maybe', 'No'], size=1000, p=[prob, prob, 1 - 2 * prob])
for cat, prob in distribution.items()
})
|
How to produce a stacked bar plot for the value counts of all columns
|
My dataframe has more than 10 columns and each column has values like yes/no/na/not specified.
And I want to calculate the count of occurrences in each column and create stacked bar graph.
Below is the image that I need:
|
[
"Yes, this is possible. But you'll need to re-format your data a little first.\nHere's the dataset I'm using in this example. It has the labels in the columns, and 1000 random Yes, No or Maybe responses as values.\n asthma boneitis diabetes pneumonia\n0 No No Yes Maybe\n1 No No No Yes\n2 No No No No\n3 Yes No No Maybe\n4 Yes No No Maybe\n.. ... ... ... ...\n995 No No Yes No\n996 Maybe Yes Yes Yes\n997 No No No Yes\n998 No No No No\n999 No No Maybe No\n\nIn order to format the data correctly for the plot, do this:\ndf2 = df.stack().groupby(level=[1]).value_counts().unstack()\n# Preferred order of stacked bar elements\nstack_order = ['Yes', 'Maybe', 'No']\ndf2 = df2[stack_order]\n\nAt this point, the data looks like this:\n Yes Maybe No\nasthma 83 83 834\nboneitis 174 173 653\ndiabetes 244 260 496\npneumonia 339 363 298\n\nNow you're ready to plot the data. Here's the code to do that:\ndf2.plot.bar(rot=0, stacked=True)\n\nI'm using rot=0 to avoid rotating the text labels (they would normally be at a 45 degree angle,) and stacked=True to produce a stacked bar chart.\nThe plot looks like this:\n\nAppendix\nCode for generating test data set:\nimport pandas as pd\nimport numpy as np\n\ncategories = [\n 'asthma',\n 'boneitis',\n 'diabetes',\n 'pneumonia',\n]\n\ndistribution = {\n cat: (i + 1) / 12\n for i, cat in enumerate(categories)\n}\n\ndf = pd.DataFrame({\n cat: np.random.choice(['Yes', 'Maybe', 'No'], size=1000, p=[prob, prob, 1 - 2 * prob])\n for cat, prob in distribution.items()\n})\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python",
"stacked_bar_chart"
] |
stackoverflow_0074554788_pandas_python_stacked_bar_chart.txt
|
Q:
How do you increment list string elements in a for loop in python?
How can I increment these list string elements in a for loop?
mylist = ['and1', 'hello', 'world']
#some for loop
for i in np.linspace(start,stop,num_samples)
print('This is %s' % mylist[0])
This gives output:
This is and1
This is and1
This is and1
My desired output is:
This is and1
This is hello
This is world
Is there an easy way to do this in python?
A:
mylist[0] always refers to the initial index in the list, while you probably meant mylist[i]
However, you can directly iterate over lists
for value in mylist:
print(f"This is {value}")
|
How do you increment list string elements in a for loop in python?
|
How can I increment these list string elements in a for loop?
mylist = ['and1', 'hello', 'world']
#some for loop
for i in np.linspace(start,stop,num_samples)
print('This is %s' % mylist[0])
This gives output:
This is and1
This is and1
This is and1
My desired output is:
This is and1
This is hello
This is world
Is there an easy way to do this in python?
|
[
"mylist[0] always refers to the initial index in the list, while you probably meant mylist[i]\nHowever, you can directly iterate over lists\nfor value in mylist:\n print(f\"This is {value}\")\n\n"
] |
[
2
] |
[] |
[] |
[
"for_loop",
"increment",
"list",
"python",
"string"
] |
stackoverflow_0074554983_for_loop_increment_list_python_string.txt
|
Q:
Safest way to generate a unique hash?
I need to produce unique identifiers that can be used in filenames and can be reproduced given the same input values. I need to produce millions of these identifiers as the source input has millions of combinations.
For simplicity's sake, I will use a small set in the example, but the actual sets can be rather large (hundreds, maybe thousands, of items); larger than could be manually encoded into a filename.
I noticed that the 5th method of generating UUID's allows you to provide a string input.
> input_set = {'apple', 'banana', 'orange'}
> uuid.uuid5(uuid.NAMESPACE_URL, pickle.dumps(input_set)).hex
'f39926529ad45997984643816c1bc403'
The documentation says it uses SHA1 under the hood. Is the risk of a collision too high? Is there a better way of reliably hashing unique identifiers?
A:
The odds that you'd get an SHA1 collision from strings is astoundingly low. Currently there are less than 63 known collisions for SHA1.
First ever SHA1 collision found
First ever' SHA-1 hash collision calculated. All it took were five clever brains... and 6,610 years of processor time
SHA1 is no longer considered secure in the cryptography world, but certainly exceeds your expectations here.
Cryptographic hashing functions are designed to be one way functions.This means the functions inverse is "hard" to calculate. (i.e. knowing the output in no way helps you determine the input) As Blender pointed out in the comments this has nothing to do with the chance of collisions.
Take a look at the Birthday Paradox for some basic information on how the probability of a collision is calculated.
This question addresses the likely hood of a SHA1 collision. This article states
A cryptographic hash function has provable security against collision attacks if finding collisions is provably polynomial-time reducible from problem P which is supposed to be unsolvable in polynomial time. The function is then called provably secure, or just provable.
Here is a list of "secure" hash algorithms.
UPDATE
You stated in the comments your input is much larger than the 160 bit limit for SHA1. I recommend you use SHA3 in this case as there is no limit on the size of your input. Check out the Python documentation for more information.
Here is a basic example:
import sha3
k = sha3.keccak_512()
k.update(b"data")
k.hexdigest()
'1065aceeded3a5e4412e2187e919bffeadf815f5bd73d37fe00d384fe29f55f08462fdabe1007b993ce5b8119630e7db93101d9425d6e352e22ffe3dcb56b825'
A:
Instead of using pysha3 (see DoesData's answer), you could also use the built-in hashlib:
import hashlib
h = hashlib.sha3_512() # Python 3.6+
h.update(b"Hello World")
h.hexdigest()
Output:
'3d58a719c6866b0214f96b0a67b37e51a91e233ce0be126a08f35fdf4c043c6126f40139bfbc338d44eb2a03de9f7bb8eff0ac260b3629811e389a5fbee8a894'
A:
If the smaller base64.urlsafe_b64encode output would be preferable:
> import base64, hashlib
> base64.urlsafe_b64encode(hashlib.sha3_512('asdf'.encode()).digest())
b'jYjPWyD1Os164UebWzbcICF1OwSZAsdyR7snsTGzAL08qL7vKHVtzie4mQhnxFd6JTXn47dRQTmcoalMyEsOuQ=='
The above output is of length 88 whereas the corresponding hex would be of length 128.
|
Safest way to generate a unique hash?
|
I need to produce unique identifiers that can be used in filenames and can be reproduced given the same input values. I need to produce millions of these identifiers as the source input has millions of combinations.
For simplicity's sake, I will use a small set in the example, but the actual sets can be rather large (hundreds, maybe thousands, of items); larger than could be manually encoded into a filename.
I noticed that the 5th method of generating UUID's allows you to provide a string input.
> input_set = {'apple', 'banana', 'orange'}
> uuid.uuid5(uuid.NAMESPACE_URL, pickle.dumps(input_set)).hex
'f39926529ad45997984643816c1bc403'
The documentation says it uses SHA1 under the hood. Is the risk of a collision too high? Is there a better way of reliably hashing unique identifiers?
|
[
"The odds that you'd get an SHA1 collision from strings is astoundingly low. Currently there are less than 63 known collisions for SHA1.\nFirst ever SHA1 collision found\n\nFirst ever' SHA-1 hash collision calculated. All it took were five clever brains... and 6,610 years of processor time\n\nSHA1 is no longer considered secure in the cryptography world, but certainly exceeds your expectations here.\nCryptographic hashing functions are designed to be one way functions.This means the functions inverse is \"hard\" to calculate. (i.e. knowing the output in no way helps you determine the input) As Blender pointed out in the comments this has nothing to do with the chance of collisions.\nTake a look at the Birthday Paradox for some basic information on how the probability of a collision is calculated.\nThis question addresses the likely hood of a SHA1 collision. This article states\n\nA cryptographic hash function has provable security against collision attacks if finding collisions is provably polynomial-time reducible from problem P which is supposed to be unsolvable in polynomial time. The function is then called provably secure, or just provable.\n\nHere is a list of \"secure\" hash algorithms.\nUPDATE\nYou stated in the comments your input is much larger than the 160 bit limit for SHA1. I recommend you use SHA3 in this case as there is no limit on the size of your input. Check out the Python documentation for more information.\nHere is a basic example:\nimport sha3\nk = sha3.keccak_512()\nk.update(b\"data\")\nk.hexdigest()\n'1065aceeded3a5e4412e2187e919bffeadf815f5bd73d37fe00d384fe29f55f08462fdabe1007b993ce5b8119630e7db93101d9425d6e352e22ffe3dcb56b825'\n\n",
"Instead of using pysha3 (see DoesData's answer), you could also use the built-in hashlib:\nimport hashlib\n\nh = hashlib.sha3_512() # Python 3.6+\nh.update(b\"Hello World\")\nh.hexdigest()\n\nOutput:\n'3d58a719c6866b0214f96b0a67b37e51a91e233ce0be126a08f35fdf4c043c6126f40139bfbc338d44eb2a03de9f7bb8eff0ac260b3629811e389a5fbee8a894'\n\n",
"If the smaller base64.urlsafe_b64encode output would be preferable:\n> import base64, hashlib\n\n> base64.urlsafe_b64encode(hashlib.sha3_512('asdf'.encode()).digest())\nb'jYjPWyD1Os164UebWzbcICF1OwSZAsdyR7snsTGzAL08qL7vKHVtzie4mQhnxFd6JTXn47dRQTmcoalMyEsOuQ=='\n\nThe above output is of length 88 whereas the corresponding hex would be of length 128.\n"
] |
[
6,
5,
0
] |
[] |
[] |
[
"python",
"uuid"
] |
stackoverflow_0047601592_python_uuid.txt
|
Q:
Function equivalent to (python) seaborn's "set_context()" in (R) ggplot2?
A quite neat function of python's library seaborn is to be able to all the sizes of the plots, labels and the majority of graph elements with a single command: set_context(context), for different contexts the sizes of figures are resized accordingly, so if context is talk everything is larger, but for paper they are scaled down so there is space to include more information in a single graph.
Is there a function equivalent to set_context() in ggplot2?
currently, I am using many theme instructions, such as:
...
theme(text = element_text(size=14)) +
...
and hardcoding all the sizes in the code
A:
I'm not too familiar with seaborn, but based on your description I think there are two features in {ggplot2} that might suit your needs.
If you want all your plots to use the same theme, you can run theme_set() at the top of your script/document to use the same theme for all your plots. Here you can declare a specific "complete theme" and then use base_size to set a default font size. So I often use theme_set(theme_bw(base_size = 16)) at the top of many of my scripts to avoid retyping that for each plot.
If you want to apply different complex themes to different plots, you can just save each theme to a variable and call it as needed.
library(ggplot2)
# create custom themes and assign to variable
theme_talk <- theme(text = element_text(size = 14))
theme_paper <- theme(text = element_text(size = 8))
p <- ggplot(mtcars, aes(disp, mpg)) + geom_point()
# call custom themes as needed
p + ggtitle("Talk theme has big text") + theme_talk
p + ggtitle("Paper theme has small text") + theme_paper
Created on 2022-11-23 with reprex v2.0.2
|
Function equivalent to (python) seaborn's "set_context()" in (R) ggplot2?
|
A quite neat function of python's library seaborn is to be able to all the sizes of the plots, labels and the majority of graph elements with a single command: set_context(context), for different contexts the sizes of figures are resized accordingly, so if context is talk everything is larger, but for paper they are scaled down so there is space to include more information in a single graph.
Is there a function equivalent to set_context() in ggplot2?
currently, I am using many theme instructions, such as:
...
theme(text = element_text(size=14)) +
...
and hardcoding all the sizes in the code
|
[
"I'm not too familiar with seaborn, but based on your description I think there are two features in {ggplot2} that might suit your needs.\nIf you want all your plots to use the same theme, you can run theme_set() at the top of your script/document to use the same theme for all your plots. Here you can declare a specific \"complete theme\" and then use base_size to set a default font size. So I often use theme_set(theme_bw(base_size = 16)) at the top of many of my scripts to avoid retyping that for each plot.\nIf you want to apply different complex themes to different plots, you can just save each theme to a variable and call it as needed.\nlibrary(ggplot2)\n\n# create custom themes and assign to variable\ntheme_talk <- theme(text = element_text(size = 14))\ntheme_paper <- theme(text = element_text(size = 8))\n\np <- ggplot(mtcars, aes(disp, mpg)) + geom_point()\n\n# call custom themes as needed\np + ggtitle(\"Talk theme has big text\") + theme_talk\n\n\np + ggtitle(\"Paper theme has small text\") + theme_paper\n\n\nCreated on 2022-11-23 with reprex v2.0.2\n"
] |
[
2
] |
[] |
[] |
[
"ggplot2",
"python",
"r",
"tidyverse"
] |
stackoverflow_0074554829_ggplot2_python_r_tidyverse.txt
|
Q:
What is the best way to get a client ip in python?
I am building an application that requires the client ip for geolocation purposes. I am using python, flask, and nginx to serve. From what I have read, common ip address capturing happens in the actual server. Any python script I use inevitably just returns my servers ip. What is the best way to get a client's ip address and pass it to the python scripts for further work to be done?
|
What is the best way to get a client ip in python?
|
I am building an application that requires the client ip for geolocation purposes. I am using python, flask, and nginx to serve. From what I have read, common ip address capturing happens in the actual server. Any python script I use inevitably just returns my servers ip. What is the best way to get a client's ip address and pass it to the python scripts for further work to be done?
|
[] |
[] |
[
"Although you're required to share part of your code to get help, I'm gonna answer your question: You can use Flask request.\nfrom flask import request\n\n...\n\nclient_ip = request.environ['REMOTE_ADDR']\nclient_port = request.environ['REMOTE_PORT']\n\n"
] |
[
-1
] |
[
"flask",
"nginx",
"python"
] |
stackoverflow_0074555025_flask_nginx_python.txt
|
Q:
Changing specific values in a python dictionary
I have the following dictionary in python:
dict={('M1 ', 'V1'): 5,
('M1 ', 'V2'): 5,
('M1 ', 'V3'): 5,
('M1 ', 'V4'): 5,
('M2', 'V1'): 5,
('M2', 'V2'): 5,
('M2', 'V3'): 5,
('M2', 'V4'): 5,
('M3', 'V1'): 5,
('M3', 'V2'): 5,
('M3', 'V3'): 5,
('M3', 'V4'): 5}
For contextualization, "dict" is a matrix distance (('Source', 'Destination'): Value) for an optimization problem, and in conducting a sensitivity analysis, I want to make the distances from M1 so high that the model won't choose it. Therefore, I want to get the python code to change the value of each line where M1 is a source.
A:
What you are doing here is you want to filter dictionary keys based on a value. the keys here are of tuple type. so basically you need to iterate the keys and check if they have the needed value.
#let's get a list of your keys first
l = [] #a placeholder for the dict keys that has 'M1' in source
for k in dict.keys(): # iterate the keys
if k[0].strip() == 'M1': # 'M1' in the source node, strip to remove whitespaces if found
l.append(k) # a list of the keys that has 'M1' as a source
A:
There's no way to directly access the items where part of the key tuple is M1. You will need to loop through.
d={
('M1', 'V1'): 5,
('M1', 'V2'): 5,
('M1', 'V3'): 5,
('M1', 'V4'): 5,
('M2', 'V1'): 5,
('M2', 'V2'): 5,
('M2', 'V3'): 5,
('M2', 'V4'): 5,
('M3', 'V1'): 5,
('M3', 'V2'): 5,
('M3', 'V3'): 5,
('M3', 'V4'): 5
}
for source, dest in d:
if source == 'M1':
d[(source, dest)] *= 10000
This will change d in-place to:
{('M1', 'V1'): 50000,
('M1', 'V2'): 50000,
('M1', 'V3'): 50000,
('M1', 'V4'): 50000,
('M2', 'V1'): 5,
('M2', 'V2'): 5,
('M2', 'V3'): 5,
('M2', 'V4'): 5,
('M3', 'V1'): 5,
('M3', 'V2'): 5,
('M3', 'V3'): 5,
('M3', 'V4'): 5}
Also, I'm assuming the key "M1 " with a space is a typo. I've changed that to "M1", above. Adjust as required.
A:
f = lambda src, dist : (dist * 100) if (src == 'M1 ') else dist
new_dict = {(src, dst): f(src, v) for (src, dst), v in dict.items()}
I don't love using python comprehensions for complex code (personally I think .map() function calls are more readable, but this works. It has the benefit of being pure functional - no values are actually mutated, so you can preserve the original for use elsewhere if you so wish.
A:
First off, dict is a reserved keyword, so don't use that as the name of your dictionary.
distances = {(...): ...,}
for source, destination in distances:
if source == "M1 ":
distances[(source, destination)] = 100000 # or something
|
Changing specific values in a python dictionary
|
I have the following dictionary in python:
dict={('M1 ', 'V1'): 5,
('M1 ', 'V2'): 5,
('M1 ', 'V3'): 5,
('M1 ', 'V4'): 5,
('M2', 'V1'): 5,
('M2', 'V2'): 5,
('M2', 'V3'): 5,
('M2', 'V4'): 5,
('M3', 'V1'): 5,
('M3', 'V2'): 5,
('M3', 'V3'): 5,
('M3', 'V4'): 5}
For contextualization, "dict" is a matrix distance (('Source', 'Destination'): Value) for an optimization problem, and in conducting a sensitivity analysis, I want to make the distances from M1 so high that the model won't choose it. Therefore, I want to get the python code to change the value of each line where M1 is a source.
|
[
"What you are doing here is you want to filter dictionary keys based on a value. the keys here are of tuple type. so basically you need to iterate the keys and check if they have the needed value.\n#let's get a list of your keys first\nl = [] #a placeholder for the dict keys that has 'M1' in source\nfor k in dict.keys(): # iterate the keys\n if k[0].strip() == 'M1': # 'M1' in the source node, strip to remove whitespaces if found\n l.append(k) # a list of the keys that has 'M1' as a source\n\n",
"There's no way to directly access the items where part of the key tuple is M1. You will need to loop through.\nd={\n ('M1', 'V1'): 5,\n ('M1', 'V2'): 5,\n ('M1', 'V3'): 5,\n ('M1', 'V4'): 5,\n ('M2', 'V1'): 5,\n ('M2', 'V2'): 5,\n ('M2', 'V3'): 5,\n ('M2', 'V4'): 5,\n ('M3', 'V1'): 5,\n ('M3', 'V2'): 5,\n ('M3', 'V3'): 5,\n ('M3', 'V4'): 5\n}\n\nfor source, dest in d:\n if source == 'M1':\n d[(source, dest)] *= 10000\n \n\nThis will change d in-place to:\n{('M1', 'V1'): 50000,\n ('M1', 'V2'): 50000,\n ('M1', 'V3'): 50000,\n ('M1', 'V4'): 50000,\n ('M2', 'V1'): 5,\n ('M2', 'V2'): 5,\n ('M2', 'V3'): 5,\n ('M2', 'V4'): 5,\n ('M3', 'V1'): 5,\n ('M3', 'V2'): 5,\n ('M3', 'V3'): 5,\n ('M3', 'V4'): 5}\n\nAlso, I'm assuming the key \"M1 \" with a space is a typo. I've changed that to \"M1\", above. Adjust as required.\n",
"\n f = lambda src, dist : (dist * 100) if (src == 'M1 ') else dist\n new_dict = {(src, dst): f(src, v) for (src, dst), v in dict.items()}\n\nI don't love using python comprehensions for complex code (personally I think .map() function calls are more readable, but this works. It has the benefit of being pure functional - no values are actually mutated, so you can preserve the original for use elsewhere if you so wish.\n",
"First off, dict is a reserved keyword, so don't use that as the name of your dictionary.\ndistances = {(...): ...,}\n\nfor source, destination in distances:\n if source == \"M1 \":\n distances[(source, destination)] = 100000 # or something\n\n\n"
] |
[
1,
1,
1,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0074555003_dictionary_python.txt
|
Q:
Are you able to pass uri_file Inputs into an Azure ML Sweep Job?
I've recently started working with the Azure ML python SDKv2.
I'm looking to fine-tune models with my sample of data and was hoping to incorporate different pre-trained models as starting points in my fine-tuning sweep job.
I have a normal fine-tuning pipeline working fine and have been using this guidance to attempt to convert my pipeline to have a sweep step which include choosing separate embedding dictionary starting points (embs are a registered datasets containing a dictionary of word embeddings). https://learn.microsoft.com/en-us/azure/machine-learning/how-to-use-sweep-in-pipeline
I've attempted to use Choice to provide Input options as you do in a normal pipeline as well as trying to pass just the path strings. However, when I run I get the issue below.
Choice([Input(type = "uri_file", path = "azureml:embsa:1"),
Input(type = "uri_file", path = "azureml:embsb:1"),
Input(type = "uri_file", path = "azureml:embsc:1"),
Input(type = "uri_file", path = "azureml:embsd:1")])
Invalid component job since input x for component job Y expecting data with types UriFile has been assigned literal value.
I'm assuming this is because the Choice object is doing something different than just iterating through the list provided, but not really sure I know where to look next.
My question is essentially, is it possible to pass registered datasets as a Choice into a sweep step? if so, how might this be achieved?
A:
Currently it's not supported, we define search_space for hyperparameter sweep in inputs of train_model and call train_model.sweep() to create a sweep node based on train_model with specific run settings.
|
Are you able to pass uri_file Inputs into an Azure ML Sweep Job?
|
I've recently started working with the Azure ML python SDKv2.
I'm looking to fine-tune models with my sample of data and was hoping to incorporate different pre-trained models as starting points in my fine-tuning sweep job.
I have a normal fine-tuning pipeline working fine and have been using this guidance to attempt to convert my pipeline to have a sweep step which include choosing separate embedding dictionary starting points (embs are a registered datasets containing a dictionary of word embeddings). https://learn.microsoft.com/en-us/azure/machine-learning/how-to-use-sweep-in-pipeline
I've attempted to use Choice to provide Input options as you do in a normal pipeline as well as trying to pass just the path strings. However, when I run I get the issue below.
Choice([Input(type = "uri_file", path = "azureml:embsa:1"),
Input(type = "uri_file", path = "azureml:embsb:1"),
Input(type = "uri_file", path = "azureml:embsc:1"),
Input(type = "uri_file", path = "azureml:embsd:1")])
Invalid component job since input x for component job Y expecting data with types UriFile has been assigned literal value.
I'm assuming this is because the Choice object is doing something different than just iterating through the list provided, but not really sure I know where to look next.
My question is essentially, is it possible to pass registered datasets as a Choice into a sweep step? if so, how might this be achieved?
|
[
"Currently it's not supported, we define search_space for hyperparameter sweep in inputs of train_model and call train_model.sweep() to create a sweep node based on train_model with specific run settings.\n\n"
] |
[
2
] |
[] |
[] |
[
"azure_machine_learning_service",
"python"
] |
stackoverflow_0074546629_azure_machine_learning_service_python.txt
|
Q:
__main__ has no attribute preload problem from p5 library in python
every time I run this code I get the error: AttributeError: module 'main' has no attribute 'preload'
I run this code
from p5 import setup, draw, size, background, run
import numpy as np
width = 500
height = 500
def setup():
size(width, height)
def draw():
background(51)
run()
and get the error message
Traceback (most recent call last):
File "c:/Users/Admin/main.py", line 15, in <module>
run()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\p5\sketch\userspace.py", line 160, in run
preload_method = __main__.preload
AttributeError: module '__main__' has no attribute 'preload'
A:
convention is to include if __name__ == '__main__': when running a python file by itself. the docs follow this convention in their examples. this script ran without the error but I'm not familiar with p5 and what it's supposed to show
│ File: test.py
───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
1 │ from p5 import *
2 │ import numpy as np
3 │
4 │
5 │ width = 500
6 │ height = 500
7 │
8 │ def setup():
9 │ size(width, height)
10 │
11 │
12 │ def draw():
13 │ background(51)
14 │
15 │ if __name__ == '__main__':
16 │ run()
|
__main__ has no attribute preload problem from p5 library in python
|
every time I run this code I get the error: AttributeError: module 'main' has no attribute 'preload'
I run this code
from p5 import setup, draw, size, background, run
import numpy as np
width = 500
height = 500
def setup():
size(width, height)
def draw():
background(51)
run()
and get the error message
Traceback (most recent call last):
File "c:/Users/Admin/main.py", line 15, in <module>
run()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\p5\sketch\userspace.py", line 160, in run
preload_method = __main__.preload
AttributeError: module '__main__' has no attribute 'preload'
|
[
"convention is to include if __name__ == '__main__': when running a python file by itself. the docs follow this convention in their examples. this script ran without the error but I'm not familiar with p5 and what it's supposed to show\n │ File: test.py\n───────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n 1 │ from p5 import *\n 2 │ import numpy as np\n 3 │\n 4 │\n 5 │ width = 500\n 6 │ height = 500\n 7 │\n 8 │ def setup():\n 9 │ size(width, height)\n 10 │\n 11 │\n 12 │ def draw():\n 13 │ background(51)\n 14 │\n 15 │ if __name__ == '__main__':\n 16 │ run()\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074554972_python.txt
|
Q:
Automatic Adjust of Y axis values using slider on matplotlib
I was working on making a graph that displays the full line by keping x axis constant and left axis adjusting. I am calculating the cost to produce egg tray with multiple variables.
Using jupyter notebook with ipywidgets as widgets i was able to get the answer.
jypyter auto adjusting y axis
import ipywidgets as widgets
from IPython.display import display
import matplotlib.pyplot as plt
import numpy as np
%matplotlib nbagg
x = np.linspace(50000, 80000, 30000)
fig, ax = plt.subplots(1, figsize=(10,4))
plt.suptitle('Cost To Produce')
def production_cost(carton_percent,assorted_percent,white_percent,dry_eggtray_weight,electric_cost,ebiogas_sold,skilled_labor,manual_labor):
ax.clear()
total_paper_weight = x*dry_eggtray_weight/1000
carton_price = total_paper_weight*carton_percent*1.9/100
assorted_price = total_paper_weight*assorted_percent*4.25/100
white_price = total_paper_weight*white_percent*10/100
burner_consumption = (x+8679)/17.3
electric_consumption = (x+11074)/19.1
skilledlabor_cost = skilled_labor*6*346/7+skilled_labor*6*3.5*54/7
manuallabor_cost = manual_labor*6*290/7+manual_labor*6*3.5*36/7
rawmats_price = carton_price + assorted_price + white_price
burner_price = burner_consumption*2.2*ebiogas_sold
electric_price = electric_consumption*electric_cost
labor_price = skilledlabor_cost + manuallabor_cost
cellophane_price = x*13/(140*2)
maintenance_price = 2000
admin_price = 4000
overall_price = rawmats_price + burner_price + electric_price + labor_price + cellophane_price + maintenance_price + admin_price
y = overall_price/x
ax.plot(x,y)
ax.set_xlabel('Egg Tray Production')
ax.set_ylabel('Cost per Tray')
plt.show()
carton_percent = widgets.FloatSlider(min=0, max=100, value=37.5, description='% Carton:')
assorted_percent = widgets.FloatSlider(min=0, max=100, value=37.5, description='% Assorted:')
white_percent = widgets.FloatSlider(min=0, max=100, value=25, description='% White:')
dry_eggtray_weight = widgets.IntSlider(min=0, max=90, value=80, description='Dry Try (g):')
electric_cost = widgets.FloatSlider(min=6, max=20, value=11.37, description='Elec Cost:')
ebiogas_sold = widgets.FloatSlider(min=6, max=20, value=6.7, description='EBio SellP:')
skilled_labor = widgets.IntSlider(min=0, max=12, value=6, description='Skilled C:')
manual_labor = widgets.IntSlider(min=0, max=16, value=12, description='Manual C:')
widgets.interactive(production_cost, carton_percent=carton_percent, assorted_percent=assorted_percent, white_percent=white_percent, dry_eggtray_weight=dry_eggtray_weight, electric_cost=electric_cost, ebiogas_sold=ebiogas_sold, skilled_labor=skilled_labor, manual_labor=manual_labor)
But using python idle, i wasnt able to copy the result
I tried narrowing variables so it wouldnt be hard to trace. So i tried this code with widgets from matplotlib directly. but only the drawing or graph is moving and both x and y axis is steady. I have tried autoscale but it does not work. Like ax.autoscale
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
# The parametrized function to be plotted
def f(x,electric_cost,ebiogas_sold):
burner_consumption = (x+8679)/17.3
electric_consumption = (x+11074)/19.1
burner_price = burner_consumption*2.2*ebiogas_sold
electric_price = electric_consumption*electric_cost
overall_price = burner_price + electric_price
return overall_price/x
x = np.linspace(50000, 80000, 30001)
# Define initial parameters
init_electric_cost = 11.37
init_ebiogas_sold = 6.7
# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
line, = ax.plot(x, f(x, init_electric_cost, init_ebiogas_sold), lw=2)
ax.autoscale(enable=True, axis="y", tight=True)
ax.set_xlabel('Egg Tray Produced [pcs]')
# adjust the main plot to make room for the sliders
fig.subplots_adjust(left=0.25, bottom=0.25)
# Make a vertically oriented slider to control the cost of electricity
electric_cost = fig.add_axes([0.25, 0.1, 0.65, 0.03])
electric_cost_slider = Slider(
ax=electric_cost,
label="Electric Cost [pesos]",
valmin=0,
valmax=20,
valinit=init_electric_cost,
)
# Make a vertically oriented slider to control the cost of biogas converted to power and then sold
biogas_cost = fig.add_axes([0.1, 0.25, 0.0225, 0.63])
biogas_cost_slider = Slider(
ax=biogas_cost,
label="Biogas Power Sold [pesos]",
valmin=0,
valmax=20,
valinit=init_ebiogas_sold,
orientation="vertical"
)
# The function to be called anytime a slider's value changes
def update(val):
line.set_ydata(f(x, electric_cost_slider.val, biogas_cost_slider.val))
#fig.canvas.draw_idle()
# register the update function with each slider
electric_cost_slider.on_changed(update)
biogas_cost_slider.on_changed(update)
# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = fig.add_axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')
def reset(event):
biogas_cost_slider.reset()
electric_cost_slider.reset()
button.on_clicked(reset)
plt.show()
A:
I finally got the answer.
I just have to change the limits of my Y
My changes are highlighted as BOLD
I dont know how to properly construct yet. so ill just paste the screenshot of changes
enter image description here
enter image description here
|
Automatic Adjust of Y axis values using slider on matplotlib
|
I was working on making a graph that displays the full line by keping x axis constant and left axis adjusting. I am calculating the cost to produce egg tray with multiple variables.
Using jupyter notebook with ipywidgets as widgets i was able to get the answer.
jypyter auto adjusting y axis
import ipywidgets as widgets
from IPython.display import display
import matplotlib.pyplot as plt
import numpy as np
%matplotlib nbagg
x = np.linspace(50000, 80000, 30000)
fig, ax = plt.subplots(1, figsize=(10,4))
plt.suptitle('Cost To Produce')
def production_cost(carton_percent,assorted_percent,white_percent,dry_eggtray_weight,electric_cost,ebiogas_sold,skilled_labor,manual_labor):
ax.clear()
total_paper_weight = x*dry_eggtray_weight/1000
carton_price = total_paper_weight*carton_percent*1.9/100
assorted_price = total_paper_weight*assorted_percent*4.25/100
white_price = total_paper_weight*white_percent*10/100
burner_consumption = (x+8679)/17.3
electric_consumption = (x+11074)/19.1
skilledlabor_cost = skilled_labor*6*346/7+skilled_labor*6*3.5*54/7
manuallabor_cost = manual_labor*6*290/7+manual_labor*6*3.5*36/7
rawmats_price = carton_price + assorted_price + white_price
burner_price = burner_consumption*2.2*ebiogas_sold
electric_price = electric_consumption*electric_cost
labor_price = skilledlabor_cost + manuallabor_cost
cellophane_price = x*13/(140*2)
maintenance_price = 2000
admin_price = 4000
overall_price = rawmats_price + burner_price + electric_price + labor_price + cellophane_price + maintenance_price + admin_price
y = overall_price/x
ax.plot(x,y)
ax.set_xlabel('Egg Tray Production')
ax.set_ylabel('Cost per Tray')
plt.show()
carton_percent = widgets.FloatSlider(min=0, max=100, value=37.5, description='% Carton:')
assorted_percent = widgets.FloatSlider(min=0, max=100, value=37.5, description='% Assorted:')
white_percent = widgets.FloatSlider(min=0, max=100, value=25, description='% White:')
dry_eggtray_weight = widgets.IntSlider(min=0, max=90, value=80, description='Dry Try (g):')
electric_cost = widgets.FloatSlider(min=6, max=20, value=11.37, description='Elec Cost:')
ebiogas_sold = widgets.FloatSlider(min=6, max=20, value=6.7, description='EBio SellP:')
skilled_labor = widgets.IntSlider(min=0, max=12, value=6, description='Skilled C:')
manual_labor = widgets.IntSlider(min=0, max=16, value=12, description='Manual C:')
widgets.interactive(production_cost, carton_percent=carton_percent, assorted_percent=assorted_percent, white_percent=white_percent, dry_eggtray_weight=dry_eggtray_weight, electric_cost=electric_cost, ebiogas_sold=ebiogas_sold, skilled_labor=skilled_labor, manual_labor=manual_labor)
But using python idle, i wasnt able to copy the result
I tried narrowing variables so it wouldnt be hard to trace. So i tried this code with widgets from matplotlib directly. but only the drawing or graph is moving and both x and y axis is steady. I have tried autoscale but it does not work. Like ax.autoscale
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
# The parametrized function to be plotted
def f(x,electric_cost,ebiogas_sold):
burner_consumption = (x+8679)/17.3
electric_consumption = (x+11074)/19.1
burner_price = burner_consumption*2.2*ebiogas_sold
electric_price = electric_consumption*electric_cost
overall_price = burner_price + electric_price
return overall_price/x
x = np.linspace(50000, 80000, 30001)
# Define initial parameters
init_electric_cost = 11.37
init_ebiogas_sold = 6.7
# Create the figure and the line that we will manipulate
fig, ax = plt.subplots()
line, = ax.plot(x, f(x, init_electric_cost, init_ebiogas_sold), lw=2)
ax.autoscale(enable=True, axis="y", tight=True)
ax.set_xlabel('Egg Tray Produced [pcs]')
# adjust the main plot to make room for the sliders
fig.subplots_adjust(left=0.25, bottom=0.25)
# Make a vertically oriented slider to control the cost of electricity
electric_cost = fig.add_axes([0.25, 0.1, 0.65, 0.03])
electric_cost_slider = Slider(
ax=electric_cost,
label="Electric Cost [pesos]",
valmin=0,
valmax=20,
valinit=init_electric_cost,
)
# Make a vertically oriented slider to control the cost of biogas converted to power and then sold
biogas_cost = fig.add_axes([0.1, 0.25, 0.0225, 0.63])
biogas_cost_slider = Slider(
ax=biogas_cost,
label="Biogas Power Sold [pesos]",
valmin=0,
valmax=20,
valinit=init_ebiogas_sold,
orientation="vertical"
)
# The function to be called anytime a slider's value changes
def update(val):
line.set_ydata(f(x, electric_cost_slider.val, biogas_cost_slider.val))
#fig.canvas.draw_idle()
# register the update function with each slider
electric_cost_slider.on_changed(update)
biogas_cost_slider.on_changed(update)
# Create a `matplotlib.widgets.Button` to reset the sliders to initial values.
resetax = fig.add_axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', hovercolor='0.975')
def reset(event):
biogas_cost_slider.reset()
electric_cost_slider.reset()
button.on_clicked(reset)
plt.show()
|
[
"I finally got the answer.\nI just have to change the limits of my Y\nMy changes are highlighted as BOLD\nI dont know how to properly construct yet. so ill just paste the screenshot of changes\nenter image description here\nenter image description here\n"
] |
[
0
] |
[] |
[] |
[
"jupyter",
"matplotlib",
"python",
"slider"
] |
stackoverflow_0074554532_jupyter_matplotlib_python_slider.txt
|
Q:
When changing font size and what font im using, pygame gives me an error
I'm trying to run this snippet of code in my Python Pygame project
my_font = font.SysFont('freesansbold', 50)
my_font.set_bold(True)
size = pygame.font.Font.size(my_font, 50)
counter = font.render(str(round((time+1000)/1000)), True, (50,50,50))
However when I try to run this code it returns this error
File "c:\Users\s12073\Desktop\digi tech stuff\testing.py", line 93, in <module>
size = pygame.font.Font.size(font.SysFont('Courier', 50).bold(True), str(round((time+1000)/1000)))
AttributeError: 'pygame.font.Font' object has no attribute 'SysFont'
Updated code:
coun = str(round((time+1000)/1000))
my_font = pygame.font.SysFont('freesansbold', 50)
my_font.set_bold(True)
size = pygame.font.Font.size(my_font, 50)
width, height = my_font.size(coun)
counter = font.render(coun, True, (50,50,50))
A:
Your code is a bit wrong in places.
First the font object (pygame.font.Font) needs to be created:
pygame.init()
pygame.font.init()
my_font = pygame.font.SysFont('freesansbold', 50)
my_font.set_bold(True)
The function pygame.font.SysFont() returns a configured Font object. Once it's made, generally you always use that for further operations.
Thus, the the size() function needs your Font object, and a string:
width, height = my_font.size( "Some example Text" )
And to render to a Surface, use it again:
counter = my_font.render(str(round((time+1000)/1000)), True, (50,50,50))
The code in the question is changing between using font and my_font. You normally want the Font object, that is my_font.
Putting all that together:
import pygame
pygame.init()
pygame.font.init()
time = 1 # to make the example work
my_font = pygame.font.SysFont('freesansbold', 50)
my_font.set_bold(True)
font_text = str(round((time+1000)/1000))
size = my_font.size( font_text )
counter = my_font.render( font_text, True, (50,50,50))
Full Text of worked example:
import pygame
WINDOW_WIDTH = 600
WINDOW_HEIGHT= 600
pygame.init()
pygame.font.init()
window = pygame.display.set_mode(( WINDOW_WIDTH, WINDOW_HEIGHT))
# Create the Font object
my_font = pygame.font.SysFont('freesansbold', 50)
my_font.set_bold(True)
time = 1
running = True
clock = pygame.time.Clock() # for framerate timing
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False # stops animation
time += 3 # just so it changes
# Convert the numer to a string
counter_text = str( time ) # str(round((time+1000)/1000)
# Convert the string to a bitmap (Surface)
counter_surface = my_font.render( counter_text, True, (50,50,50))
# paint the screen
window.fill( ( 0,0,0 ) ) # black background
window.blit( counter_surface, ( 100, 100 ) ) # draw the counter
pygame.display.update()
clock.tick( 60 )
pygame.quit()
|
When changing font size and what font im using, pygame gives me an error
|
I'm trying to run this snippet of code in my Python Pygame project
my_font = font.SysFont('freesansbold', 50)
my_font.set_bold(True)
size = pygame.font.Font.size(my_font, 50)
counter = font.render(str(round((time+1000)/1000)), True, (50,50,50))
However when I try to run this code it returns this error
File "c:\Users\s12073\Desktop\digi tech stuff\testing.py", line 93, in <module>
size = pygame.font.Font.size(font.SysFont('Courier', 50).bold(True), str(round((time+1000)/1000)))
AttributeError: 'pygame.font.Font' object has no attribute 'SysFont'
Updated code:
coun = str(round((time+1000)/1000))
my_font = pygame.font.SysFont('freesansbold', 50)
my_font.set_bold(True)
size = pygame.font.Font.size(my_font, 50)
width, height = my_font.size(coun)
counter = font.render(coun, True, (50,50,50))
|
[
"Your code is a bit wrong in places.\nFirst the font object (pygame.font.Font) needs to be created:\npygame.init()\npygame.font.init()\n\nmy_font = pygame.font.SysFont('freesansbold', 50)\nmy_font.set_bold(True)\n\nThe function pygame.font.SysFont() returns a configured Font object. Once it's made, generally you always use that for further operations.\nThus, the the size() function needs your Font object, and a string:\nwidth, height = my_font.size( \"Some example Text\" )\n\nAnd to render to a Surface, use it again:\ncounter = my_font.render(str(round((time+1000)/1000)), True, (50,50,50))\n\nThe code in the question is changing between using font and my_font. You normally want the Font object, that is my_font.\nPutting all that together:\nimport pygame\n\npygame.init()\npygame.font.init()\n\ntime = 1 # to make the example work\n\nmy_font = pygame.font.SysFont('freesansbold', 50)\nmy_font.set_bold(True)\n\nfont_text = str(round((time+1000)/1000))\nsize = my_font.size( font_text )\ncounter = my_font.render( font_text, True, (50,50,50))\n\nFull Text of worked example:\nimport pygame\n\nWINDOW_WIDTH = 600\nWINDOW_HEIGHT= 600\n\npygame.init()\npygame.font.init()\nwindow = pygame.display.set_mode(( WINDOW_WIDTH, WINDOW_HEIGHT))\n\n# Create the Font object\nmy_font = pygame.font.SysFont('freesansbold', 50)\nmy_font.set_bold(True)\n\ntime = 1\n\nrunning = True\nclock = pygame.time.Clock() # for framerate timing\nwhile running:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False # stops animation\n\n time += 3 # just so it changes\n\n # Convert the numer to a string\n counter_text = str( time ) # str(round((time+1000)/1000)\n\n # Convert the string to a bitmap (Surface)\n counter_surface = my_font.render( counter_text, True, (50,50,50))\n\n # paint the screen\n window.fill( ( 0,0,0 ) ) # black background\n window.blit( counter_surface, ( 100, 100 ) ) # draw the counter\n\n pygame.display.update()\n clock.tick( 60 )\n\npygame.quit()\n\n"
] |
[
0
] |
[] |
[] |
[
"attributeerror",
"fonts",
"pygame",
"python"
] |
stackoverflow_0074554944_attributeerror_fonts_pygame_python.txt
|
Q:
Most efficient way to convert list of values to probability distribution?
I have several lists that can only contain the following values: 0, 0.5, 1, 1.5
I want to efficiently convert each of these lists into probability mass functions. So if a list is as follows: [0.5, 0.5, 1, 1.5], the PMF will look like this: [0, 0.5, 0.25, 0.25].
I need to do this many times (and with very large lists), so avoiding looping will be optimal, if at all possible. What's the most efficient way to make this happen?
Edit: Here's my current system. This feels like a really inefficient/unelegant way to do it:
def get_distribution(samplemodes1):
n, bin_edges = np.histogram(samplemodes1, bins = 9)
totalcount = np.sum(n)
bin_probability = n / totalcount
bins_per_point = np.fmin(np.digitize(samplemodes1, bin_edges), len(bin_edges)-1)
probability_perpoint = [bin_probability[bins_per_point[i]-1] for i in range(len(samplemodes1))]
counts = Counter(samplemodes1)
total = sum(counts.values())
probability_mass = {k:v/total for k,v in counts.items()}
#print(probability_mass)
key_values = {}
if(0 in probability_mass):
key_values[0] = probability_mass.get(0)
else:
key_values[0] = 0
if(0.5 in probability_mass):
key_values[0.5] = probability_mass.get(0.5)
else:
key_values[0.5] = 0
if(1 in probability_mass):
key_values[1] = probability_mass.get(1)
else:
key_values[1] = 0
if(1.5 in probability_mass):
key_values[1.5] = probability_mass.get(1.5)
else:
key_values[1.5] = 0
distribution = list(key_values.values())
return distribution
A:
Here are some solution for you to benchmark:
Using collections.Counter
from collections import Counter
bins = [0, 0.5, 1, 1.5]
a = [0.5, 0.5, 1.0, 0.5, 1.0, 1.5, 0.5]
denom = len(a)
counts = Counter(a)
pmf = [counts[bin]/denom for bin in Bins]
NumPy based solution
import numpy as np
bins = [0, 0.5, 1, 1.5]
a = np.array([0.5, 0.5, 1.0, 0.5, 1.0, 1.5, 0.5])
denom = len(a)
pmf = [(a == bin).sum()/denom for bin in bins]
but you can probably do better by using np.bincount() instead.
Further reading on this idea: https://thispointer.com/count-occurrences-of-a-value-in-numpy-array-in-python/
|
Most efficient way to convert list of values to probability distribution?
|
I have several lists that can only contain the following values: 0, 0.5, 1, 1.5
I want to efficiently convert each of these lists into probability mass functions. So if a list is as follows: [0.5, 0.5, 1, 1.5], the PMF will look like this: [0, 0.5, 0.25, 0.25].
I need to do this many times (and with very large lists), so avoiding looping will be optimal, if at all possible. What's the most efficient way to make this happen?
Edit: Here's my current system. This feels like a really inefficient/unelegant way to do it:
def get_distribution(samplemodes1):
n, bin_edges = np.histogram(samplemodes1, bins = 9)
totalcount = np.sum(n)
bin_probability = n / totalcount
bins_per_point = np.fmin(np.digitize(samplemodes1, bin_edges), len(bin_edges)-1)
probability_perpoint = [bin_probability[bins_per_point[i]-1] for i in range(len(samplemodes1))]
counts = Counter(samplemodes1)
total = sum(counts.values())
probability_mass = {k:v/total for k,v in counts.items()}
#print(probability_mass)
key_values = {}
if(0 in probability_mass):
key_values[0] = probability_mass.get(0)
else:
key_values[0] = 0
if(0.5 in probability_mass):
key_values[0.5] = probability_mass.get(0.5)
else:
key_values[0.5] = 0
if(1 in probability_mass):
key_values[1] = probability_mass.get(1)
else:
key_values[1] = 0
if(1.5 in probability_mass):
key_values[1.5] = probability_mass.get(1.5)
else:
key_values[1.5] = 0
distribution = list(key_values.values())
return distribution
|
[
"Here are some solution for you to benchmark:\nUsing collections.Counter\nfrom collections import Counter\n\nbins = [0, 0.5, 1, 1.5]\na = [0.5, 0.5, 1.0, 0.5, 1.0, 1.5, 0.5]\ndenom = len(a)\ncounts = Counter(a)\npmf = [counts[bin]/denom for bin in Bins]\n\nNumPy based solution\nimport numpy as np\n\nbins = [0, 0.5, 1, 1.5]\na = np.array([0.5, 0.5, 1.0, 0.5, 1.0, 1.5, 0.5])\ndenom = len(a)\npmf = [(a == bin).sum()/denom for bin in bins]\n\nbut you can probably do better by using np.bincount() instead.\nFurther reading on this idea: https://thispointer.com/count-occurrences-of-a-value-in-numpy-array-in-python/\n"
] |
[
0
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0074555084_numpy_python.txt
|
Q:
Token expires in a certain two hours
Good afternoon, I am making an API in which it will connect to the dropbox API, the problem stems from the fact that the token does not last long, which is unclear in the documentation, does anyone of you know how to obtain the token through the endpoint or That it does not expire, I would appreciate it.
I looked in the documentation and I don't understand it well and some video tutorials don't mention it.
A:
Dropbox is in the process of switching to only issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here.
Apps can still get long-term access by requesting "offline" access though, in which case the app receives a "refresh token" that can be used to retrieve new short-lived access tokens as needed, without further manual user intervention. You can find more information in the OAuth Guide and authorization documentation.
You can find examples of using the OAuth app authorization flow in the Dropbox Python SDK here
|
Token expires in a certain two hours
|
Good afternoon, I am making an API in which it will connect to the dropbox API, the problem stems from the fact that the token does not last long, which is unclear in the documentation, does anyone of you know how to obtain the token through the endpoint or That it does not expire, I would appreciate it.
I looked in the documentation and I don't understand it well and some video tutorials don't mention it.
|
[
"Dropbox is in the process of switching to only issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here.\nApps can still get long-term access by requesting \"offline\" access though, in which case the app receives a \"refresh token\" that can be used to retrieve new short-lived access tokens as needed, without further manual user intervention. You can find more information in the OAuth Guide and authorization documentation.\nYou can find examples of using the OAuth app authorization flow in the Dropbox Python SDK here\n"
] |
[
0
] |
[] |
[] |
[
"api",
"dropbox",
"python"
] |
stackoverflow_0074539973_api_dropbox_python.txt
|
Q:
Python - Column concatenation based on length of data inside the column
Need help on column concatenation based on length size .
Column3= df["column1"] + "_" + df["column2"]
data = {'column1':['af28912368', 'Nan', '234671', 'asr61239'],
'column2':[701, Nan, 761, 312]}
df = pd.DataFrame(data)
df :
column1
column2
af28912368
701
NaN
Nan
234671
761
asr61239
312
If length of the data in column1 is greater than 8 , then need to Insert last 8 symbols of column1
If length of the data in column1 <8 & >0 , Insert value of df['column1'] + (8-Len(df['column1'])) of Blank Spaces
If NaN on Column1 , Column3 can remain as NaN
expected result as shown on column3
column1
column2
column3
aa289123sf
701
289123sf_701
NaN
723
Nan
234671
761
234671 _761
asr61239
312
asr61239_312
I tried this :
df["column3"] = df["column1"].str[-8:] + '_' + df["column2"].astype(str)
But not working with different length size of df["column1"] . Please help on this one.
A:
you're first row column1 value keeps changing so I'm assuming this is a typo and not part of the exercise
this script worked for me:
───────┬─────────────────────────────────────────────────────────────────────
│ File: test-so.py
───────┼─────────────────────────────────────────────────────────────────────
1 │ import pandas as pd
2 │ from pprint import pprint
3 │
4 │ data = {'column1':['af28912368', None, '234671', 'asr61239'], 'column2':[701, None, 761, 312]}
5 │ df = pd.DataFrame(data)
6 │
7 │ def funk(col1,col2):
8 │ try:
9 │ tmp = len(col1)
10 │ if tmp > 8:
11 │ return col1[:8] +'_'+ str(int(col2))
12 │ elif tmp <= 8 and tmp > 0:
13 │ return (int(tmp % 8))*' ' + col1 +'_'+ str(int(col2))
14 │ else:
15 │ return None
16 │ except TypeError as e:
17 │ return None
18 │
19 │ def main():
20 │ df['column3'] = df.apply(lambda row: funk(row['column1'],row['column2']),axis=1)
21 │ pprint(df)
22 │
23 │ if __name__ == '__main__':
24 │ main()
from command line:
python test-so.py
yields:
|
Python - Column concatenation based on length of data inside the column
|
Need help on column concatenation based on length size .
Column3= df["column1"] + "_" + df["column2"]
data = {'column1':['af28912368', 'Nan', '234671', 'asr61239'],
'column2':[701, Nan, 761, 312]}
df = pd.DataFrame(data)
df :
column1
column2
af28912368
701
NaN
Nan
234671
761
asr61239
312
If length of the data in column1 is greater than 8 , then need to Insert last 8 symbols of column1
If length of the data in column1 <8 & >0 , Insert value of df['column1'] + (8-Len(df['column1'])) of Blank Spaces
If NaN on Column1 , Column3 can remain as NaN
expected result as shown on column3
column1
column2
column3
aa289123sf
701
289123sf_701
NaN
723
Nan
234671
761
234671 _761
asr61239
312
asr61239_312
I tried this :
df["column3"] = df["column1"].str[-8:] + '_' + df["column2"].astype(str)
But not working with different length size of df["column1"] . Please help on this one.
|
[
"you're first row column1 value keeps changing so I'm assuming this is a typo and not part of the exercise\nthis script worked for me:\n───────┬─────────────────────────────────────────────────────────────────────\n │ File: test-so.py\n───────┼─────────────────────────────────────────────────────────────────────\n 1 │ import pandas as pd\n 2 │ from pprint import pprint\n 3 │\n 4 │ data = {'column1':['af28912368', None, '234671', 'asr61239'], 'column2':[701, None, 761, 312]}\n 5 │ df = pd.DataFrame(data)\n 6 │\n 7 │ def funk(col1,col2):\n 8 │ try:\n 9 │ tmp = len(col1)\n 10 │ if tmp > 8:\n 11 │ return col1[:8] +'_'+ str(int(col2))\n 12 │ elif tmp <= 8 and tmp > 0:\n 13 │ return (int(tmp % 8))*' ' + col1 +'_'+ str(int(col2))\n 14 │ else:\n 15 │ return None\n 16 │ except TypeError as e:\n 17 │ return None\n 18 │\n 19 │ def main():\n 20 │ df['column3'] = df.apply(lambda row: funk(row['column1'],row['column2']),axis=1)\n 21 │ pprint(df)\n 22 │\n 23 │ if __name__ == '__main__':\n 24 │ main()\n\nfrom command line:\npython test-so.py\n\nyields:\n\n"
] |
[
1
] |
[] |
[] |
[
"concatenation",
"multiple_columns",
"python",
"string_length"
] |
stackoverflow_0074555121_concatenation_multiple_columns_python_string_length.txt
|
Q:
Transforming Badly Formatted Data into something useful
Just for fun, someone just dropped a json file needing to be transformed into a Time Series on to my lap. Unfortunately for me, it looks like this:
"messages": [
{
"format": "string",
"topic": "camera1",
"timestamp": 1669253760775,
"payload": "{\"AnalyticalOutput\":[\"1\",\"6\",\"6\",\"9\",\"2\",\"5\",\"3\",\"7\",\"6\",\"0\",\".\",\"6\",\"7\",\"6\",\"4\",\"8\",\"8\",\"9\"],\"Timestamp\":\"1669253759.7708852\"}",
"qos": 0
},
What I need to do is to transform thousands of lines of that into something manageable for python to use.
For that frame right there, what I need, exactly, to extract from it is the information from the Payload, specifically the numbers 1669253760.64889 and 1669253759.7708852, as columns of something like a csv, or anything that pandas could read.
Where do I even start with something like this?
A:
Here's one example of drilling down into the payload
import json
d = { "messages": [
{
"format": "string",
"topic": "camera1",
"timestamp": 1669253760775,
"payload": "{\"AnalyticalOutput\":[\"1\",\"6\",\"6\",\"9\",\"2\",\"5\",\"3\",\"7\",\"6\",\"0\",\".\",\"6\",\"7\",\"6\",\"4\",\"8\",\"8\",\"9\"],\"Timestamp\":\"1669253759.7708852\"}",
"qos": 0
},
]}
payload = json.loads(d['messages'][0]['payload'])
for k,v in payload.items():
if isinstance(v, list):
v = float(''.join(v))
print(k,v)
|
Transforming Badly Formatted Data into something useful
|
Just for fun, someone just dropped a json file needing to be transformed into a Time Series on to my lap. Unfortunately for me, it looks like this:
"messages": [
{
"format": "string",
"topic": "camera1",
"timestamp": 1669253760775,
"payload": "{\"AnalyticalOutput\":[\"1\",\"6\",\"6\",\"9\",\"2\",\"5\",\"3\",\"7\",\"6\",\"0\",\".\",\"6\",\"7\",\"6\",\"4\",\"8\",\"8\",\"9\"],\"Timestamp\":\"1669253759.7708852\"}",
"qos": 0
},
What I need to do is to transform thousands of lines of that into something manageable for python to use.
For that frame right there, what I need, exactly, to extract from it is the information from the Payload, specifically the numbers 1669253760.64889 and 1669253759.7708852, as columns of something like a csv, or anything that pandas could read.
Where do I even start with something like this?
|
[
"Here's one example of drilling down into the payload\nimport json\nd = { \"messages\": [\n{\n \"format\": \"string\",\n \"topic\": \"camera1\",\n \"timestamp\": 1669253760775,\n \"payload\": \"{\\\"AnalyticalOutput\\\":[\\\"1\\\",\\\"6\\\",\\\"6\\\",\\\"9\\\",\\\"2\\\",\\\"5\\\",\\\"3\\\",\\\"7\\\",\\\"6\\\",\\\"0\\\",\\\".\\\",\\\"6\\\",\\\"7\\\",\\\"6\\\",\\\"4\\\",\\\"8\\\",\\\"8\\\",\\\"9\\\"],\\\"Timestamp\\\":\\\"1669253759.7708852\\\"}\",\n \"qos\": 0\n},\n]}\npayload = json.loads(d['messages'][0]['payload'])\n\nfor k,v in payload.items():\n if isinstance(v, list):\n v = float(''.join(v))\n print(k,v)\n\n"
] |
[
1
] |
[] |
[] |
[
"json",
"python"
] |
stackoverflow_0074555127_json_python.txt
|
Q:
Complex numbers in python
Are complex numbers a supported data-type in Python? If so, how do you use them?
A:
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
A:
The following example for complex numbers should be self explanatory including the error message at the end
>>> x=complex(1,2)
>>> print x
(1+2j)
>>> y=complex(3,4)
>>> print y
(3+4j)
>>> z=x+y
>>> print x
(1+2j)
>>> print z
(4+6j)
>>> z=x*y
>>> print z
(-5+10j)
>>> z=x/y
>>> print z
(0.44+0.08j)
>>> print x.conjugate()
(1-2j)
>>> print x.imag
2.0
>>> print x.real
1.0
>>> print x>y
Traceback (most recent call last):
File "<pyshell#149>", line 1, in <module>
print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y
False
>>>
A:
Yes, complex type is supported in Python.
For numbers, Python 3 supports 3 types int, float and complex types as shown below:
print(type(100), isinstance(100, int))
print(type(100.23), isinstance(100.23, float))
print(type(100 + 2j), isinstance(100 + 2j, complex))
Output:
<class 'int'> True
<class 'float'> True
<class 'complex'> True
For numbers, Python 2 supperts 4 types int, long, float and complex types as shown below:
print(type(100), isinstance(100, int))
print(type(10000000000000000000), isinstance(10000000000000000000, long))
print(type(100.23), isinstance(100.23, float))
print(type(100 + 2j), isinstance(100 + 2j, complex))
Output:
(<type 'int'>, True)
(<type 'long'>, True)
(<type 'float'>, True)
(<type 'complex'>, True)
|
Complex numbers in python
|
Are complex numbers a supported data-type in Python? If so, how do you use them?
|
[
"In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:\n>>> 1j\n1j\n>>> 1J\n1j\n>>> 1j * 1j\n(-1+0j)\n\nThe ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)\nThe type of a complex number is complex, and you can use the type as a constructor if you prefer:\n>>> complex(2,3)\n(2+3j)\n\nA complex number has some built-in accessors:\n>>> z = 2+3j\n>>> z.real\n2.0\n>>> z.imag\n3.0\n>>> z.conjugate()\n(2-3j)\n\nSeveral built-in functions support complex numbers:\n>>> abs(3 + 4j)\n5.0\n>>> pow(3 + 4j, 2)\n(-7+24j)\n\nThe standard module cmath has more functions that handle complex numbers:\n>>> import cmath\n>>> cmath.sin(2 + 3j)\n(9.15449914691143-4.168906959966565j)\n\n",
"The following example for complex numbers should be self explanatory including the error message at the end\n>>> x=complex(1,2)\n>>> print x\n(1+2j)\n>>> y=complex(3,4)\n>>> print y\n(3+4j)\n>>> z=x+y\n>>> print x\n(1+2j)\n>>> print z\n(4+6j)\n>>> z=x*y\n>>> print z\n(-5+10j)\n>>> z=x/y\n>>> print z\n(0.44+0.08j)\n>>> print x.conjugate()\n(1-2j)\n>>> print x.imag\n2.0\n>>> print x.real\n1.0\n>>> print x>y\n\nTraceback (most recent call last):\n File \"<pyshell#149>\", line 1, in <module>\n print x>y\nTypeError: no ordering relation is defined for complex numbers\n>>> print x==y\nFalse\n>>> \n\n",
"Yes, complex type is supported in Python.\nFor numbers, Python 3 supports 3 types int, float and complex types as shown below:\nprint(type(100), isinstance(100, int))\nprint(type(100.23), isinstance(100.23, float))\nprint(type(100 + 2j), isinstance(100 + 2j, complex))\n\nOutput:\n<class 'int'> True\n<class 'float'> True\n<class 'complex'> True\n\nFor numbers, Python 2 supperts 4 types int, long, float and complex types as shown below:\nprint(type(100), isinstance(100, int))\nprint(type(10000000000000000000), isinstance(10000000000000000000, long))\nprint(type(100.23), isinstance(100.23, float))\nprint(type(100 + 2j), isinstance(100 + 2j, complex))\n\nOutput:\n(<type 'int'>, True)\n(<type 'long'>, True)\n(<type 'float'>, True)\n(<type 'complex'>, True)\n\n"
] |
[
246,
17,
0
] |
[] |
[] |
[
"complex_numbers",
"python",
"types"
] |
stackoverflow_0008370637_complex_numbers_python_types.txt
|
Q:
Is it possible to programmatically define identifiers using string data in Python?
Suppose I have a class called Circuit, and a dictionary containing data about each circuit component:
components = {
'V1': [ ... ],
'L1': [ ... ],
'R1': [ ... ],
'R2': [ ... ],
...
}
I want to define child objects Circuit.V1, Circuit.L1, and so on.
The crux of the problem is that I have strings ("V1", "L1", ...) that need to be converted into identifiers. The necessary identifiers would be different depending on what data is passed to the constructor of Circuit, so I can't just hard-code them.
Is this possible, and if so, how do I do this?
I haven't been able to find any information on this (searching just brings up basic info on valid identifier names and such). I have found this page but the question was never directly answered.
Right now I can access my circuit component object like Circuit.components['V1'], but that seems a little clunky and I would prefer Circuit.V1.
Edit: The term for the thing I was trying to do is dynamic attribute assignment. Adding this so that others like me who didn't know what keywords to search for can more easily find information.
A:
Although not recommended, you can use the __setattr__ dunder method:
class C:
...
c = C()
c.__setattr__("V1", 1)
print("c.V1 = ", c.V1) # c.V1 = 1
In principle this works, but if you want to define attributes in runtime (you do not know the name of the attributes beforehand) why would you like to treat them as attributes? I think your dictionary approach is better suited for your use case.
A:
If we want view like Circuit.V1, you will make the class and create a object of class.. Like:
class Component:
V1 = 0
...
Circuit = Component()
Circuit.V1 = 2
But who do this for "beauty"?
|
Is it possible to programmatically define identifiers using string data in Python?
|
Suppose I have a class called Circuit, and a dictionary containing data about each circuit component:
components = {
'V1': [ ... ],
'L1': [ ... ],
'R1': [ ... ],
'R2': [ ... ],
...
}
I want to define child objects Circuit.V1, Circuit.L1, and so on.
The crux of the problem is that I have strings ("V1", "L1", ...) that need to be converted into identifiers. The necessary identifiers would be different depending on what data is passed to the constructor of Circuit, so I can't just hard-code them.
Is this possible, and if so, how do I do this?
I haven't been able to find any information on this (searching just brings up basic info on valid identifier names and such). I have found this page but the question was never directly answered.
Right now I can access my circuit component object like Circuit.components['V1'], but that seems a little clunky and I would prefer Circuit.V1.
Edit: The term for the thing I was trying to do is dynamic attribute assignment. Adding this so that others like me who didn't know what keywords to search for can more easily find information.
|
[
"Although not recommended, you can use the __setattr__ dunder method:\nclass C:\n ...\n\nc = C()\n\nc.__setattr__(\"V1\", 1)\n\nprint(\"c.V1 = \", c.V1) # c.V1 = 1\n\n\nIn principle this works, but if you want to define attributes in runtime (you do not know the name of the attributes beforehand) why would you like to treat them as attributes? I think your dictionary approach is better suited for your use case.\n",
"If we want view like Circuit.V1, you will make the class and create a object of class.. Like:\nclass Component:\n V1 = 0\n ... \n\nCircuit = Component() \nCircuit.V1 = 2\n\nBut who do this for \"beauty\"?\n"
] |
[
3,
0
] |
[] |
[] |
[
"identifier",
"python",
"syntax"
] |
stackoverflow_0074555171_identifier_python_syntax.txt
|
Q:
is user input a letter in the CPU's choice?
I'm trying to check if user input is one of the letters in the chosen word by the CPU. Let me know if this is not possible the way I'm trying to do it, thanks.
import random
test_list = [ 'yes', 'no']
# guessing list
print("Original list is : " + str(test_list))
cpu_choice =[]
cpu_choice=("Random element is :", random.sample(test_list, 1))
print(cpu_choice)
# i know it gives the answer i'm just using this to test and get the program to work
userinput = input('guess a letter ')
for letter in userinput:
if letter in userinput == letter in cpu_choice:
print('correct')
elif print:
print('wrong')
A:
I modified it to loop through the cpu_choice instead of the userinput (userinput is just one letter).
The printing of the result is moved out of the loop so the program won't print 'wrong' for every letter in the word that doesn't match.
userinput = input('guess a letter: ')[0]
match = False
for letter in cpu_choice[1][0]:
if letter == userinput:
match = True
break
if match:
print('correct')
else:
print('wrong')
A:
letter in userinput is evaluating whether or not the letter is in the user's input, which we know it is because you're looping over the letters in userinput to get letter. You should remove this part of the if statement, leaving only if letter in cpu_choice:.
However, the rest of your program looks like it should work, although the user will only have once chance to guess letters because you only get input once.
|
is user input a letter in the CPU's choice?
|
I'm trying to check if user input is one of the letters in the chosen word by the CPU. Let me know if this is not possible the way I'm trying to do it, thanks.
import random
test_list = [ 'yes', 'no']
# guessing list
print("Original list is : " + str(test_list))
cpu_choice =[]
cpu_choice=("Random element is :", random.sample(test_list, 1))
print(cpu_choice)
# i know it gives the answer i'm just using this to test and get the program to work
userinput = input('guess a letter ')
for letter in userinput:
if letter in userinput == letter in cpu_choice:
print('correct')
elif print:
print('wrong')
|
[
"I modified it to loop through the cpu_choice instead of the userinput (userinput is just one letter).\nThe printing of the result is moved out of the loop so the program won't print 'wrong' for every letter in the word that doesn't match.\nuserinput = input('guess a letter: ')[0]\nmatch = False\nfor letter in cpu_choice[1][0]:\n if letter == userinput:\n match = True\n break\nif match:\n print('correct')\nelse:\n print('wrong')\n\n",
"letter in userinput is evaluating whether or not the letter is in the user's input, which we know it is because you're looping over the letters in userinput to get letter. You should remove this part of the if statement, leaving only if letter in cpu_choice:.\nHowever, the rest of your program looks like it should work, although the user will only have once chance to guess letters because you only get input once.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074555158_python.txt
|
Q:
Parameterized Tests with Function Output
I'm working on some fairly complicated test scenarios with PyTest, and I was hoping to encapsulate the test setup for various scenarios in some functions and then make those scenarios available to a test using parameterization.
Here is a simplified example:
def scenario01():
# complicated setup
...
return {
"name": "scenario01",
"cond1": cond1,
"cond2": cond2
}
def scenario02():
# complicated setup
...
return {
"name": "scenario02",
"cond1": cond1,
"cond2": cond2
}
# is it ok to call these functions in the decorator
@pytest.mark.parametrize("test_data", [scenario01(), scenario02()])
def test_my_func(test_data):
name = test_data["name"]
cond1 = test_data["cond1"]
cond2 = test_data["cond2"]
assert cond1 && cond2 #this isn't important
Is there any downside to doing something like this?
I like this because, as a reader, its obvious where the fixtures are coming from and their not magically defined in some conftest.py file, but I'm not sure if there is some side effects that may be happening that I'm not aware of.
A:
If the functions aren't computationally expensive, there's no harm in it. If it were computationally expensive, I might move the function invocation inside the test method, like so:
@pytest.mark.parametrize("test_data", [scenario01, scenario02])
def test_my_func(scenario):
test_data = scenario()
The issue with computationally expensive things at module level is that they'll occur during test collection, regardless of whether those tests actually end up running.
However, if the scenarios aren't expensive, I might gain a few points in readability by pulling the scenario contents into actual parametrized fixtures, and moving the name into the ParamSet's id, so it will show up in the pytest output
@pytest.mark.parametrize(("cond1", "cond2"), [
pytest.param(data['cond1'], data['cond2'], id=data['name'])
for data in [
scenario01(),
scenario02(),
]
])
def test_my_func(cond1, cond2):
assert cond1 and cond2 # this isn't important
|
Parameterized Tests with Function Output
|
I'm working on some fairly complicated test scenarios with PyTest, and I was hoping to encapsulate the test setup for various scenarios in some functions and then make those scenarios available to a test using parameterization.
Here is a simplified example:
def scenario01():
# complicated setup
...
return {
"name": "scenario01",
"cond1": cond1,
"cond2": cond2
}
def scenario02():
# complicated setup
...
return {
"name": "scenario02",
"cond1": cond1,
"cond2": cond2
}
# is it ok to call these functions in the decorator
@pytest.mark.parametrize("test_data", [scenario01(), scenario02()])
def test_my_func(test_data):
name = test_data["name"]
cond1 = test_data["cond1"]
cond2 = test_data["cond2"]
assert cond1 && cond2 #this isn't important
Is there any downside to doing something like this?
I like this because, as a reader, its obvious where the fixtures are coming from and their not magically defined in some conftest.py file, but I'm not sure if there is some side effects that may be happening that I'm not aware of.
|
[
"If the functions aren't computationally expensive, there's no harm in it. If it were computationally expensive, I might move the function invocation inside the test method, like so:\n@pytest.mark.parametrize(\"test_data\", [scenario01, scenario02])\ndef test_my_func(scenario):\n test_data = scenario()\n\nThe issue with computationally expensive things at module level is that they'll occur during test collection, regardless of whether those tests actually end up running.\nHowever, if the scenarios aren't expensive, I might gain a few points in readability by pulling the scenario contents into actual parametrized fixtures, and moving the name into the ParamSet's id, so it will show up in the pytest output\n@pytest.mark.parametrize((\"cond1\", \"cond2\"), [\n pytest.param(data['cond1'], data['cond2'], id=data['name'])\n for data in [\n scenario01(),\n scenario02(),\n ]\n])\ndef test_my_func(cond1, cond2):\n assert cond1 and cond2 # this isn't important\n\n"
] |
[
1
] |
[] |
[] |
[
"pytest",
"python",
"testing"
] |
stackoverflow_0074554736_pytest_python_testing.txt
|
Q:
Cropping an image after Rotation, Scaling and Translation (with Python Transformation Matrix) such that there is no black background
I have pairs of images of the same 2D object with very minor diferences. The two images of a pair have two reference points (a star [x_s,y_s] and an arrow-head [x_a,y_a]) as shown below:
I have written a Python script to align one image with reference to the second image of the pair with the reference points/coordinates. Please go through the code below for a clear understanding:
import numpy as np
import cv2
import pandas as pd
# Function to align image2 with respect to image1:
def alignFromReferenceImage(image1, imgname1, image2, imgname2):
# Using Panda dataframe to read the coordinate values ((x_s,y_s) and (x_a,y_a)) from a csv file
#
# The .csv file looks like this:-
#
# id;x_s;y_s;x_a;y_a
# img11;113;433;45;56
# img12;54;245;55;77
# img21;33;76;16;88
# img22;62;88;111;312
# ... ;..;..;...;
df = pd.read_csv("./image_metadata.csv", delimiter= ';')
# Eliminate .jpg from the image name and fetch the row
filter_data=df[df.isin([imgname1.split('.')[0]]).any(1)]
x1_s=filter_data['x_s'].values[0]
y1_s=filter_data['y_s'].values[0]
x1_a=filter_data['x_a'].values[0]
y1_a=filter_data['y_a'].values[0]
filter_data2=df[df.isin([imgname2.split('.')[0]]).any(1)]
x2_s=filter_data2['x_s'].values[0]
y2_s=filter_data2['y_s'].values[0]
x2_a=filter_data2['x_a'].values[0]
y2_a=filter_data2['y_a'].values[0]
tx=x2_s-x1_s
ty=y2_s-y1_s
rows,cols = image1.shape
M = np.float32([[1,0,-tx],[0,1,-ty]])
image_after_translation = cv2.warpAffine(image2,M,(cols,rows))
d1 = math.sqrt((x1_a - x1_s)**2 + (y1_a - y1_s)**2)
d2 = math.sqrt((x2_a - x2_s)**2 + (y2_a - y2_s)**2)
dx1 = x1_a - x1_s
dy1 = -(y1_a - y1_s)
alpha1 = math.degrees(math.atan2(dy1, dx1))
alpha1=(360+alpha1) if (alpha1<0) else alpha1
dx2 = x2_a - x2_s
dy2 = -(y2_a - y2_s)
alpha2 = math.degrees(math.atan2(dy2, dx2))
alpha2=(360+alpha2) if (alpha2<0) else alpha2
ang=alpha1-alpha2
scale = d1 / d2
centre = (filter_data['x_s'].values[0], filter_data['y_s'].values[0])
M = cv2.getRotationMatrix2D((centre),ang,scale)
aligned_image = cv2.warpAffine(image_after_translation, M, (cols,rows))
return aligned_image
After alignment, the image looks as shown below:
Important: Now, after aligning the first image with respect to the second image, I want to crop the aligned image in such a way that the image will no longer have the black background after cropping. The picture below will clearly explain what I want to do:
I have researched on it and found some useful links:
http://roffle-largest-rectangle.blogspot.com/2011/09/find-largest-rectangle-in-rotated-image.html
Rotate image and crop out black borders
Calculate largest inscribed rectangle in a rotated rectangle
But these posts only discuss about rotation and I have no clue how the maths work for translation and scaling. Any help in this problem would be highly appreciated.
A:
If you want "any help" and are willing to use Imagemagick 7, then there is a simple solution using its aggressive trim.
Input:
magick -fuzz 20% img.png +repage -bordercolor black -border 2 -background black -define trim:percent-background=0% -trim +repage img_trim.png
A:
Here is a Python/OpenCV solution. It first thresholds the image so that the background is black and the rest is white. It tests each edge of the threshold image and computes the mean and looks for the edge with the lowest mean. It stops on that edge if the mean==255. If not, then it trims off that edge and repeats. Once all edges have a mean of 255, it stops completely and uses the increments on each side to compute the crop of the original input.
Input:
Note: I had to adjust the crop of your posted image to ensure the background on all sides was pure black. It would have helped if you have provided separate images. If the sides were still slightly gray, then I would have increased the upper threshold limit.
import cv2
import numpy as np
# read image
img = cv2.imread('star_arrow.png')
h, w = img.shape[:2]
# threshold so border is black and rest is white. Note this is has pure black for the background, so threshold at black and invert. Adjust lower and upper if the background is not pure black.
lower = (0,0,0)
upper = (0,0,0)
mask = cv2.inRange(img, lower, upper)
mask = 255 - mask
# define top and left starting coordinates and starting width and height
top = 0
left = 0
bottom = h
right = w
# compute the mean of each side of the image and its stop test
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_bottom, mean_right)
top_test = "stop" if (mean_top == 255) else "go"
left_test = "stop" if (mean_left == 255) else "go"
bottom_test = "stop" if (mean_bottom == 255) else "go"
right_test = "stop" if (mean_right == 255) else "go"
# iterate to compute new side coordinates if mean of given side is not 255 (all white) and it is the current darkest side
while top_test == "go" or left_test == "go" or right_test == "go" or bottom_test == "go":
# top processing
if top_test == "go":
if mean_top != 255:
if mean_top == mean_minimum:
top += 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("top",mean_top)
continue
else:
top_test = "stop"
# left processing
if left_test == "go":
if mean_left != 255:
if mean_left == mean_minimum:
left += 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("left",mean_left)
continue
else:
left_test = "stop"
# bottom processing
if bottom_test == "go":
if mean_bottom != 255:
if mean_bottom == mean_minimum:
bottom -= 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("bottom",mean_bottom)
continue
else:
bottom_test = "stop"
# right processing
if right_test == "go":
if mean_right != 255:
if mean_right == mean_minimum:
right -= 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("right",mean_right)
continue
else:
right_test = "stop"
# crop input
result = img[top:bottom, left:right]
# print crop values
print("top: ",top)
print("bottom: ",bottom)
print("left: ",left)
print("right: ",right)
print("height:",result.shape[0])
print("width:",result.shape[1])
# save cropped image
#cv2.imwrite('border_image1_cropped.png',result)
cv2.imwrite('img_cropped.png',result)
cv2.imwrite('img_mask.png',mask)
# show the images
cv2.imshow("mask", mask)
cv2.imshow("cropped", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Threshold Image:
Cropped Input:
ADDITION
Here is a version that shows an animation of the processing when run.
import cv2
import numpy as np
# read image
img = cv2.imread('star_arrow.png')
h, w = img.shape[:2]
# threshold so border is black and rest is white (invert as needed)
lower = (0,0,0)
upper = (0,0,0)
mask = cv2.inRange(img, lower, upper)
mask = 255 - mask
# define top and left starting coordinates and starting width and height
top = 0
left = 0
bottom = h
right = w
# compute the mean of each side of the image and its stop test
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_bottom, mean_right)
top_test = "stop" if (mean_top == 255) else "go"
left_test = "stop" if (mean_left == 255) else "go"
bottom_test = "stop" if (mean_bottom == 255) else "go"
right_test = "stop" if (mean_right == 255) else "go"
result = img[top:bottom, left:right]
cv2.imshow("result", result)
cv2.waitKey(100)
# iterate to compute new side coordinates if mean of given side is not 255 (all white) and it is the current darkest side
while top_test == "go" or left_test == "go" or right_test == "go" or bottom_test == "go":
# top processing
if top_test == "go":
if mean_top != 255:
if mean_top == mean_minimum:
top += 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("top",mean_top)
result = img[top:bottom, left:right]
cv2.imshow("result", result)
cv2.waitKey(100)
continue
else:
top_test = "stop"
# left processing
if left_test == "go":
if mean_left != 255:
if mean_left == mean_minimum:
left += 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("left",mean_left)
result = img[top:bottom, left:right]
cv2.imshow("result", result)
cv2.waitKey(100)
continue
else:
left_test = "stop"
# bottom processing
if bottom_test == "go":
if mean_bottom != 255:
if mean_bottom == mean_minimum:
bottom -= 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("bottom",mean_bottom)
result = img[top:bottom, left:right]
cv2.imshow("result", result)
cv2.waitKey(100)
continue
else:
bottom_test = "stop"
# right processing
if right_test == "go":
if mean_right != 255:
if mean_right == mean_minimum:
right -= 1
mean_top = np.mean( mask[top:top+1, left:right] )
mean_left = np.mean( mask[top:bottom, left:left+1] )
mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )
mean_right = np.mean( mask[top:bottom, right-1:right] )
mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)
#print("right",mean_right)
result = img[top:bottom, left:right]
cv2.imshow("result", result)
cv2.waitKey(100)
continue
else:
right_test = "stop"
# crop input
result = img[top:bottom, left:right]
# print crop values
print("top: ",top)
print("bottom: ",bottom)
print("left: ",left)
print("right: ",right)
print("height:",result.shape[0])
print("width:",result.shape[1])
# save cropped image
cv2.imwrite('img_cropped.png',result)
cv2.imwrite('img_mask.png',mask)
# show the images
cv2.waitKey(0)
cv2.destroyAllWindows()
|
Cropping an image after Rotation, Scaling and Translation (with Python Transformation Matrix) such that there is no black background
|
I have pairs of images of the same 2D object with very minor diferences. The two images of a pair have two reference points (a star [x_s,y_s] and an arrow-head [x_a,y_a]) as shown below:
I have written a Python script to align one image with reference to the second image of the pair with the reference points/coordinates. Please go through the code below for a clear understanding:
import numpy as np
import cv2
import pandas as pd
# Function to align image2 with respect to image1:
def alignFromReferenceImage(image1, imgname1, image2, imgname2):
# Using Panda dataframe to read the coordinate values ((x_s,y_s) and (x_a,y_a)) from a csv file
#
# The .csv file looks like this:-
#
# id;x_s;y_s;x_a;y_a
# img11;113;433;45;56
# img12;54;245;55;77
# img21;33;76;16;88
# img22;62;88;111;312
# ... ;..;..;...;
df = pd.read_csv("./image_metadata.csv", delimiter= ';')
# Eliminate .jpg from the image name and fetch the row
filter_data=df[df.isin([imgname1.split('.')[0]]).any(1)]
x1_s=filter_data['x_s'].values[0]
y1_s=filter_data['y_s'].values[0]
x1_a=filter_data['x_a'].values[0]
y1_a=filter_data['y_a'].values[0]
filter_data2=df[df.isin([imgname2.split('.')[0]]).any(1)]
x2_s=filter_data2['x_s'].values[0]
y2_s=filter_data2['y_s'].values[0]
x2_a=filter_data2['x_a'].values[0]
y2_a=filter_data2['y_a'].values[0]
tx=x2_s-x1_s
ty=y2_s-y1_s
rows,cols = image1.shape
M = np.float32([[1,0,-tx],[0,1,-ty]])
image_after_translation = cv2.warpAffine(image2,M,(cols,rows))
d1 = math.sqrt((x1_a - x1_s)**2 + (y1_a - y1_s)**2)
d2 = math.sqrt((x2_a - x2_s)**2 + (y2_a - y2_s)**2)
dx1 = x1_a - x1_s
dy1 = -(y1_a - y1_s)
alpha1 = math.degrees(math.atan2(dy1, dx1))
alpha1=(360+alpha1) if (alpha1<0) else alpha1
dx2 = x2_a - x2_s
dy2 = -(y2_a - y2_s)
alpha2 = math.degrees(math.atan2(dy2, dx2))
alpha2=(360+alpha2) if (alpha2<0) else alpha2
ang=alpha1-alpha2
scale = d1 / d2
centre = (filter_data['x_s'].values[0], filter_data['y_s'].values[0])
M = cv2.getRotationMatrix2D((centre),ang,scale)
aligned_image = cv2.warpAffine(image_after_translation, M, (cols,rows))
return aligned_image
After alignment, the image looks as shown below:
Important: Now, after aligning the first image with respect to the second image, I want to crop the aligned image in such a way that the image will no longer have the black background after cropping. The picture below will clearly explain what I want to do:
I have researched on it and found some useful links:
http://roffle-largest-rectangle.blogspot.com/2011/09/find-largest-rectangle-in-rotated-image.html
Rotate image and crop out black borders
Calculate largest inscribed rectangle in a rotated rectangle
But these posts only discuss about rotation and I have no clue how the maths work for translation and scaling. Any help in this problem would be highly appreciated.
|
[
"If you want \"any help\" and are willing to use Imagemagick 7, then there is a simple solution using its aggressive trim.\nInput:\n\nmagick -fuzz 20% img.png +repage -bordercolor black -border 2 -background black -define trim:percent-background=0% -trim +repage img_trim.png\n\n\n",
"Here is a Python/OpenCV solution. It first thresholds the image so that the background is black and the rest is white. It tests each edge of the threshold image and computes the mean and looks for the edge with the lowest mean. It stops on that edge if the mean==255. If not, then it trims off that edge and repeats. Once all edges have a mean of 255, it stops completely and uses the increments on each side to compute the crop of the original input.\nInput:\n\nNote: I had to adjust the crop of your posted image to ensure the background on all sides was pure black. It would have helped if you have provided separate images. If the sides were still slightly gray, then I would have increased the upper threshold limit.\nimport cv2\nimport numpy as np\n\n# read image\nimg = cv2.imread('star_arrow.png')\nh, w = img.shape[:2]\n\n# threshold so border is black and rest is white. Note this is has pure black for the background, so threshold at black and invert. Adjust lower and upper if the background is not pure black.\nlower = (0,0,0)\nupper = (0,0,0)\nmask = cv2.inRange(img, lower, upper)\nmask = 255 - mask\n\n# define top and left starting coordinates and starting width and height\ntop = 0\nleft = 0\nbottom = h\nright = w\n\n# compute the mean of each side of the image and its stop test\nmean_top = np.mean( mask[top:top+1, left:right] )\nmean_left = np.mean( mask[top:bottom, left:left+1] )\nmean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\nmean_right = np.mean( mask[top:bottom, right-1:right] )\n\nmean_minimum = min(mean_top, mean_left, mean_bottom, mean_right)\n\ntop_test = \"stop\" if (mean_top == 255) else \"go\"\nleft_test = \"stop\" if (mean_left == 255) else \"go\"\nbottom_test = \"stop\" if (mean_bottom == 255) else \"go\"\nright_test = \"stop\" if (mean_right == 255) else \"go\"\n\n# iterate to compute new side coordinates if mean of given side is not 255 (all white) and it is the current darkest side\nwhile top_test == \"go\" or left_test == \"go\" or right_test == \"go\" or bottom_test == \"go\":\n\n # top processing\n if top_test == \"go\":\n if mean_top != 255:\n if mean_top == mean_minimum:\n top += 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"top\",mean_top)\n continue\n else:\n top_test = \"stop\" \n\n # left processing\n if left_test == \"go\":\n if mean_left != 255:\n if mean_left == mean_minimum:\n left += 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"left\",mean_left)\n continue\n else:\n left_test = \"stop\" \n\n # bottom processing\n if bottom_test == \"go\":\n if mean_bottom != 255:\n if mean_bottom == mean_minimum:\n bottom -= 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"bottom\",mean_bottom)\n continue\n else:\n bottom_test = \"stop\" \n\n # right processing\n if right_test == \"go\":\n if mean_right != 255:\n if mean_right == mean_minimum:\n right -= 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"right\",mean_right)\n continue\n else:\n right_test = \"stop\" \n\n\n# crop input\nresult = img[top:bottom, left:right]\n\n# print crop values \nprint(\"top: \",top)\nprint(\"bottom: \",bottom)\nprint(\"left: \",left)\nprint(\"right: \",right)\nprint(\"height:\",result.shape[0])\nprint(\"width:\",result.shape[1])\n\n# save cropped image\n#cv2.imwrite('border_image1_cropped.png',result)\ncv2.imwrite('img_cropped.png',result)\ncv2.imwrite('img_mask.png',mask)\n\n# show the images\ncv2.imshow(\"mask\", mask)\ncv2.imshow(\"cropped\", result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nThreshold Image:\n\nCropped Input:\n\nADDITION\nHere is a version that shows an animation of the processing when run.\nimport cv2\nimport numpy as np\n\n# read image\nimg = cv2.imread('star_arrow.png')\nh, w = img.shape[:2]\n\n# threshold so border is black and rest is white (invert as needed)\nlower = (0,0,0)\nupper = (0,0,0)\nmask = cv2.inRange(img, lower, upper)\nmask = 255 - mask\n\n# define top and left starting coordinates and starting width and height\ntop = 0\nleft = 0\nbottom = h\nright = w\n\n# compute the mean of each side of the image and its stop test\nmean_top = np.mean( mask[top:top+1, left:right] )\nmean_left = np.mean( mask[top:bottom, left:left+1] )\nmean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\nmean_right = np.mean( mask[top:bottom, right-1:right] )\n\nmean_minimum = min(mean_top, mean_left, mean_bottom, mean_right)\n\ntop_test = \"stop\" if (mean_top == 255) else \"go\"\nleft_test = \"stop\" if (mean_left == 255) else \"go\"\nbottom_test = \"stop\" if (mean_bottom == 255) else \"go\"\nright_test = \"stop\" if (mean_right == 255) else \"go\"\n\nresult = img[top:bottom, left:right]\ncv2.imshow(\"result\", result)\ncv2.waitKey(100)\n\n# iterate to compute new side coordinates if mean of given side is not 255 (all white) and it is the current darkest side\nwhile top_test == \"go\" or left_test == \"go\" or right_test == \"go\" or bottom_test == \"go\":\n\n # top processing\n if top_test == \"go\":\n if mean_top != 255:\n if mean_top == mean_minimum:\n top += 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"top\",mean_top)\n result = img[top:bottom, left:right]\n cv2.imshow(\"result\", result)\n cv2.waitKey(100)\n continue\n else:\n top_test = \"stop\" \n\n # left processing\n if left_test == \"go\":\n if mean_left != 255:\n if mean_left == mean_minimum:\n left += 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"left\",mean_left)\n result = img[top:bottom, left:right]\n cv2.imshow(\"result\", result)\n cv2.waitKey(100)\n continue\n else:\n left_test = \"stop\" \n\n # bottom processing\n if bottom_test == \"go\":\n if mean_bottom != 255:\n if mean_bottom == mean_minimum:\n bottom -= 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"bottom\",mean_bottom)\n result = img[top:bottom, left:right]\n cv2.imshow(\"result\", result)\n cv2.waitKey(100)\n continue\n else:\n bottom_test = \"stop\" \n\n # right processing\n if right_test == \"go\":\n if mean_right != 255:\n if mean_right == mean_minimum:\n right -= 1\n mean_top = np.mean( mask[top:top+1, left:right] )\n mean_left = np.mean( mask[top:bottom, left:left+1] )\n mean_bottom = np.mean( mask[bottom-1:bottom, left:right] )\n mean_right = np.mean( mask[top:bottom, right-1:right] )\n mean_minimum = min(mean_top, mean_left, mean_right, mean_bottom)\n #print(\"right\",mean_right)\n result = img[top:bottom, left:right]\n cv2.imshow(\"result\", result)\n cv2.waitKey(100)\n continue\n else:\n right_test = \"stop\" \n\n\n# crop input\nresult = img[top:bottom, left:right]\n\n# print crop values \nprint(\"top: \",top)\nprint(\"bottom: \",bottom)\nprint(\"left: \",left)\nprint(\"right: \",right)\nprint(\"height:\",result.shape[0])\nprint(\"width:\",result.shape[1])\n\n# save cropped image\ncv2.imwrite('img_cropped.png',result)\ncv2.imwrite('img_mask.png',mask)\n\n# show the images\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"geometry",
"image_processing",
"math",
"opencv",
"python"
] |
stackoverflow_0074546776_geometry_image_processing_math_opencv_python.txt
|
Q:
Insert variable in save file name in python
I have a lot of files that need to be saved inside one folder, but the files that need to be saved have the same name except for one part. So, instead of editing one by one, I want to insert variables into similar parts of the names.
Eg:
D = r"c:\users\folder"
f1 = D + r"\apple_table.bin"
f2 = D + r"\apple_chair.bin"
So, I want to replace apple with variable. Like this but my example got an error
A = apple
F1 = D + r"\ A + table.bin"
F2 = D + r"\ A + chair.bin"
In my project, A keeps changing. So, I need to edit them one by one and it is so painful and slows down me.
A:
Use a list and a for-loop. For instance:
PATH_TO_FOLDER = r"\PATH\TO\FOLDER"
SUFFIX = "table.bin"
list_of_names = ["apple"]
for item in list_of_names:
with open("{0}{1}{2}".format(PATH_TO_FOLDER, item, SUFFIX), "w+") as f:
f.write("<what you need to write>")
|
Insert variable in save file name in python
|
I have a lot of files that need to be saved inside one folder, but the files that need to be saved have the same name except for one part. So, instead of editing one by one, I want to insert variables into similar parts of the names.
Eg:
D = r"c:\users\folder"
f1 = D + r"\apple_table.bin"
f2 = D + r"\apple_chair.bin"
So, I want to replace apple with variable. Like this but my example got an error
A = apple
F1 = D + r"\ A + table.bin"
F2 = D + r"\ A + chair.bin"
In my project, A keeps changing. So, I need to edit them one by one and it is so painful and slows down me.
|
[
"Use a list and a for-loop. For instance:\nPATH_TO_FOLDER = r\"\\PATH\\TO\\FOLDER\"\nSUFFIX = \"table.bin\"\nlist_of_names = [\"apple\"]\nfor item in list_of_names:\n with open(\"{0}{1}{2}\".format(PATH_TO_FOLDER, item, SUFFIX), \"w+\") as f:\n f.write(\"<what you need to write>\")\n\n"
] |
[
1
] |
[] |
[] |
[
"file",
"python",
"variables"
] |
stackoverflow_0074555287_file_python_variables.txt
|
Q:
Accessing array outside of the for loop in python
I am trying to access the array soc+ out the for loop.
Outside of the for loop, it gives me only last value.
How to access whole soc array out of the for loop?
If I used append method it gives follow error
" 'numpy.ndarray' object has no attribute 'append' "
Thank you.
Here is part of my code
for k in range(1,len(t)):
soc+=i[k]*(t[k]-t[k-1])/3600*1/(cell_capacity)
soc = soc.append(k)
I tried using append method but it give the error " 'numpy.ndarray' object has no attribute 'append' "
A:
You can add break statement in the for loop and access the soc out side the for loop.
You can keep the entire for loop in 1 function and pass the range value say (k,len(t)) once come out after break.
A:
If I replace soc +=i[k] * (t[k] - t[k - 1]) / 3600 / (cell_capacity) with soc = i[k] * (t[k] - t[k - 1]) / 3600 / (cell_capacity).
And then do np.cumsum.soc outside the loop then it solves the problem for me.
It is "a" solution for me to proceed further.
|
Accessing array outside of the for loop in python
|
I am trying to access the array soc+ out the for loop.
Outside of the for loop, it gives me only last value.
How to access whole soc array out of the for loop?
If I used append method it gives follow error
" 'numpy.ndarray' object has no attribute 'append' "
Thank you.
Here is part of my code
for k in range(1,len(t)):
soc+=i[k]*(t[k]-t[k-1])/3600*1/(cell_capacity)
soc = soc.append(k)
I tried using append method but it give the error " 'numpy.ndarray' object has no attribute 'append' "
|
[
"You can add break statement in the for loop and access the soc out side the for loop.\nYou can keep the entire for loop in 1 function and pass the range value say (k,len(t)) once come out after break.\n",
"If I replace soc +=i[k] * (t[k] - t[k - 1]) / 3600 / (cell_capacity) with soc = i[k] * (t[k] - t[k - 1]) / 3600 / (cell_capacity).\nAnd then do np.cumsum.soc outside the loop then it solves the problem for me.\nIt is \"a\" solution for me to proceed further.\n"
] |
[
0,
0
] |
[] |
[] |
[
"arrays",
"for_loop",
"python"
] |
stackoverflow_0074505654_arrays_for_loop_python.txt
|
Q:
Infinite loop mistake
I'm having issues with this loop. I try to break the loop once the user write "S" or "n" but it doesn't do it.
user_input = ""
issue_num = 0
ISSUES = ["El motor o las cuchillas no arrancan", "La comida esta picada de manera desigual",
"La comida esta picada muy fina o aguada", "Los alimentos se acumulan en la tapa",
"La base del motor no se adhiere a la mesa", 'Tiene un mensaje de "ERR"',
"Tiene una luz roja parapadeante"]
anoun_of_issues = len(ISSUES)
while user_input != "salir":
print(ISSUES[issue_num])
user_input = input('Pulsse "S" si es su inconveniente, pulse "n" si no lo es y escriba "salir" para salir... ')
if user_input != "s" or user_input != "n":
while user_input != "s" or user_input != "n":
user_input = input('Pulsse "S" si es su inconveniente, pulse "n" si no lo es y escriba "salir" para salir... ')
if user_input == "s":
if issue_num == 0:
pass
A:
The condition you are using in your inner loop is user_input != "s" or user_input != "n". This condition is always true because you are using or. The only way it could fail to be true is if user_input was somehow equal to "s" and "n" at the same time. Since that's not possible with a normal string, you keep looping forever.
To make the loop end when either "s" or "n" is entered, use user_input != "s" and user_input != "n".
|
Infinite loop mistake
|
I'm having issues with this loop. I try to break the loop once the user write "S" or "n" but it doesn't do it.
user_input = ""
issue_num = 0
ISSUES = ["El motor o las cuchillas no arrancan", "La comida esta picada de manera desigual",
"La comida esta picada muy fina o aguada", "Los alimentos se acumulan en la tapa",
"La base del motor no se adhiere a la mesa", 'Tiene un mensaje de "ERR"',
"Tiene una luz roja parapadeante"]
anoun_of_issues = len(ISSUES)
while user_input != "salir":
print(ISSUES[issue_num])
user_input = input('Pulsse "S" si es su inconveniente, pulse "n" si no lo es y escriba "salir" para salir... ')
if user_input != "s" or user_input != "n":
while user_input != "s" or user_input != "n":
user_input = input('Pulsse "S" si es su inconveniente, pulse "n" si no lo es y escriba "salir" para salir... ')
if user_input == "s":
if issue_num == 0:
pass
|
[
"The condition you are using in your inner loop is user_input != \"s\" or user_input != \"n\". This condition is always true because you are using or. The only way it could fail to be true is if user_input was somehow equal to \"s\" and \"n\" at the same time. Since that's not possible with a normal string, you keep looping forever.\nTo make the loop end when either \"s\" or \"n\" is entered, use user_input != \"s\" and user_input != \"n\".\n"
] |
[
0
] |
[] |
[] |
[
"loops",
"python"
] |
stackoverflow_0074555339_loops_python.txt
|
Q:
How to pass URL as a path parameter to a FastAPI route?
I have created a simple API using FastAPI, and I am trying to pass a URL to a FastAPI route as an arbitrary path parameter.
from fastapi import FastAPI
app = FastAPI()
@app.post("/{path}")
def pred_image(path:str):
print("path",path)
return {'path':path}
When I test it, it doesn't work and throws an error. I am testing it this way:
http://127.0.0.1:8000/https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg
A:
Option 1
You can simply use the path convertor to capture arbitrary paths. As per Starlette documentation, path returns the rest of the path, including any additional / characters.
from fastapi import Request
@app.get('/{_:path}')
def pred_image(request: Request):
return {"path": request.url.path[1:]}
or
@app.get("/{full_path:path}")
def pred_image(full_path: str):
return {"path": full_path}
Test using the below:
http://127.0.0.1:8000/https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg
Output:
{"path":"https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg"}
Option 2
As @luk2302 mentioned in the comments section, your client (i.e., either end user, javascript, etc) needs to encode the URL. The encoded URL, however, as provided by @luk2302 does not seem to work, leading to a "detail": "Not Found" error. As it turns out, you would need to encode it twice to work. That is:
http://127.0.0.1:8000/https%253A%252F%252Fraw.githubusercontent.com%252Fultralytics%252Fyolov5%252Fmaster%252Fdata%252Fimages%252Fzidane.jpg
On server side, you can decode the URL (twice) as follows:
from urllib.parse import unquote
@app.get("/{path}")
def pred_image(path: str):
return {'path':unquote(unquote(path))}
Option 3
Since your endpoint seems to accept POST requests, you might consider having the client sending the image URL in the body of the request, instead of passing it as a path parameter. Please have a look at the answers here, here and here, as well as FastAPI's documentation, on how to do that.
Note:
If you are testing this through typing the aforementioned URLs into the address bar of a browser, then keep using @app.get() routes, as when you type a URL in the address bar of your browser, it performs a GET request. If , however, you need this to work with POST requests, you will have to change the endpoint's decorator to @app.post() (as shown in your question); otherwise, you would come accross {"detail":"Method Not Allowed"} error.
A:
example:http://127.0.0.1:8000/porxy/https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg
this passed url doesn't have any ? query params, just need
@app.get('/proxy/{url:path}')
async def proxy(url:str):
# url:https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg
return url
{var:path} could match:and /, but will stop at ?, so if you want to get the full url, you need from fastapi import Request.
the req.val contain the full url, include the host.
example:http://127.0.0.1:8000/porxy/http://www.xx.com/abc?query=abc
PS:HttpUrl used to check the passed url is or not legal
from pydantic import HttpUrl
from fastapi import FastAPI, Request
app = FastAPI()
# example request url http://127.0.0.1:8000/proxy/http://www.xx.com/abc?query=abc
@app.get('/proxy/{url:path}', )
async def proxy(url: HttpUrl, req: Request):
# url: http://www.xx.com/abc
# req.url: http://127.0.0.1:8000/porxy/http://www.xx.com/abc?query=abc
# wanted_url: http://www.xx.com/abc?query=abc
wanted_url = str(req.url).partition('/proxy/')[-1]
return {'url': url, 'req_url': str(req.url), 'wanted_url': wanted_url}
if __name__ == '__main__':
import uvicorn
uvicorn.run('main:app', port=8000)
Path convertor https://fastapi.tiangolo.com/tutorial/path-params/#path-convertor
Using an option directly from Starlette you can declare a path parameter containing a path using a URL like:
/files/{file_path:path}
In this case, the name of the parameter is file_path, and the last part, :path, tells it that the parameter should match any path.
So, you can use it with:
from fastapi import FastAPI app = FastAPI()
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
return {"file_path": file_path}
starlette Request: https://www.starlette.io/requests/
|
How to pass URL as a path parameter to a FastAPI route?
|
I have created a simple API using FastAPI, and I am trying to pass a URL to a FastAPI route as an arbitrary path parameter.
from fastapi import FastAPI
app = FastAPI()
@app.post("/{path}")
def pred_image(path:str):
print("path",path)
return {'path':path}
When I test it, it doesn't work and throws an error. I am testing it this way:
http://127.0.0.1:8000/https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg
|
[
"Option 1\nYou can simply use the path convertor to capture arbitrary paths. As per Starlette documentation, path returns the rest of the path, including any additional / characters.\nfrom fastapi import Request\n\n@app.get('/{_:path}')\ndef pred_image(request: Request):\n return {\"path\": request.url.path[1:]}\n\nor\n@app.get(\"/{full_path:path}\")\ndef pred_image(full_path: str):\n return {\"path\": full_path}\n\nTest using the below:\nhttp://127.0.0.1:8000/https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg\n\nOutput:\n{\"path\":\"https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg\"}\n\nOption 2\nAs @luk2302 mentioned in the comments section, your client (i.e., either end user, javascript, etc) needs to encode the URL. The encoded URL, however, as provided by @luk2302 does not seem to work, leading to a \"detail\": \"Not Found\" error. As it turns out, you would need to encode it twice to work. That is:\nhttp://127.0.0.1:8000/https%253A%252F%252Fraw.githubusercontent.com%252Fultralytics%252Fyolov5%252Fmaster%252Fdata%252Fimages%252Fzidane.jpg\n\nOn server side, you can decode the URL (twice) as follows:\nfrom urllib.parse import unquote \n\n@app.get(\"/{path}\")\ndef pred_image(path: str):\n return {'path':unquote(unquote(path))} \n\nOption 3\nSince your endpoint seems to accept POST requests, you might consider having the client sending the image URL in the body of the request, instead of passing it as a path parameter. Please have a look at the answers here, here and here, as well as FastAPI's documentation, on how to do that.\n\nNote:\nIf you are testing this through typing the aforementioned URLs into the address bar of a browser, then keep using @app.get() routes, as when you type a URL in the address bar of your browser, it performs a GET request. If , however, you need this to work with POST requests, you will have to change the endpoint's decorator to @app.post() (as shown in your question); otherwise, you would come accross {\"detail\":\"Method Not Allowed\"} error.\n",
"example:http://127.0.0.1:8000/porxy/https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg\nthis passed url doesn't have any ? query params, just need\n@app.get('/proxy/{url:path}')\nasync def proxy(url:str):\n # url:https://raw.githubusercontent.com/ultralytics/yolov5/master/data/images/zidane.jpg \n return url \n\n{var:path} could match:and /, but will stop at ?, so if you want to get the full url, you need from fastapi import Request.\nthe req.val contain the full url, include the host.\nexample:http://127.0.0.1:8000/porxy/http://www.xx.com/abc?query=abc\nPS:HttpUrl used to check the passed url is or not legal\nfrom pydantic import HttpUrl \nfrom fastapi import FastAPI, Request \n \napp = FastAPI() \n \n \n# example request url http://127.0.0.1:8000/proxy/http://www.xx.com/abc?query=abc \n@app.get('/proxy/{url:path}', ) \nasync def proxy(url: HttpUrl, req: Request): \n # url: http://www.xx.com/abc \n # req.url: http://127.0.0.1:8000/porxy/http://www.xx.com/abc?query=abc \n # wanted_url: http://www.xx.com/abc?query=abc \n wanted_url = str(req.url).partition('/proxy/')[-1] \n return {'url': url, 'req_url': str(req.url), 'wanted_url': wanted_url} \n \n \nif __name__ == '__main__': \n import uvicorn \n uvicorn.run('main:app', port=8000)\n\n\nPath convertor https://fastapi.tiangolo.com/tutorial/path-params/#path-convertor\nUsing an option directly from Starlette you can declare a path parameter containing a path using a URL like:\n/files/{file_path:path}\nIn this case, the name of the parameter is file_path, and the last part, :path, tells it that the parameter should match any path.\nSo, you can use it with:\nfrom fastapi import FastAPI app = FastAPI() \n@app.get(\"/files/{file_path:path}\") \nasync def read_file(file_path: str): \n return {\"file_path\": file_path}\n\nstarlette Request: https://www.starlette.io/requests/\n"
] |
[
4,
0
] |
[] |
[] |
[
"fastapi",
"python",
"starlette"
] |
stackoverflow_0072801333_fastapi_python_starlette.txt
|
Q:
Generating Python interpreter-intolerant wheels from a `pyproject.toml`
Consider the following pyproject.toml:
[build-system]
requires = ["setuptools>=40.8.0", "wheel"]
[project]
name = "foo"
version = "0.0.0"
requires-python = "~=3.9"
If I run pip wheel . in the directory containing this file, then I generate a wheel named foo-0.0.0-py3-none-any.whl. However, this wheel filename indicates that any python3 interpreter is fine, yet my requires-python metadata in my pyproject.toml indicates that only python3.9 is acceptable.
How can I get the requires-python metadata to be reflected in the wheel? I would expect the wheel filename to be foo-0.0.0-cp39-cp39-any.whl in this case. . .
A:
That is not quite what the platform tag in the wheel filename is used for - cp39 would indicate that you're only compatible with CPython 3.9 or higher, and this wheel should not be selected by PyPy or some other implementations. You would usually only use a compatibility tag like that if you had some compiled C extensions inside the wheel that are CPython-specific.
The Requires-Python metadata is still located inside your built wheel, which you'll see if you try to install it on an incompatible Python version:
$ python3.8 -m pip install ./foo-0.0.0-py3-none-any.whl
Processing ./foo-0.0.0-py3-none-any.whl
ERROR: Package 'foo' requires a different Python: 3.8.13 not in '~=3.9'
The location of the metadata is here:
$ unzip foo-0.0.0-py3-none-any.whl
Archive: foo-0.0.0-py3-none-any.whl
inflating: foo-0.0.0.dist-info/METADATA
inflating: foo-0.0.0.dist-info/WHEEL
inflating: foo-0.0.0.dist-info/top_level.txt
inflating: foo-0.0.0.dist-info/RECORD
$ grep Requires foo-0.0.0.dist-info/METADATA
Requires-Python: ~=3.9
As for how this works with PyPI - the index may return this metadata in the json API (example) and in the simple API (example)†. That allows pip to avoid downloading and unpacking incompatible wheels.
† It's in a data-requires-python attribute of the href - you might have to "view-source" in your browser to see it.
|
Generating Python interpreter-intolerant wheels from a `pyproject.toml`
|
Consider the following pyproject.toml:
[build-system]
requires = ["setuptools>=40.8.0", "wheel"]
[project]
name = "foo"
version = "0.0.0"
requires-python = "~=3.9"
If I run pip wheel . in the directory containing this file, then I generate a wheel named foo-0.0.0-py3-none-any.whl. However, this wheel filename indicates that any python3 interpreter is fine, yet my requires-python metadata in my pyproject.toml indicates that only python3.9 is acceptable.
How can I get the requires-python metadata to be reflected in the wheel? I would expect the wheel filename to be foo-0.0.0-cp39-cp39-any.whl in this case. . .
|
[
"That is not quite what the platform tag in the wheel filename is used for - cp39 would indicate that you're only compatible with CPython 3.9 or higher, and this wheel should not be selected by PyPy or some other implementations. You would usually only use a compatibility tag like that if you had some compiled C extensions inside the wheel that are CPython-specific.\nThe Requires-Python metadata is still located inside your built wheel, which you'll see if you try to install it on an incompatible Python version:\n$ python3.8 -m pip install ./foo-0.0.0-py3-none-any.whl\nProcessing ./foo-0.0.0-py3-none-any.whl\nERROR: Package 'foo' requires a different Python: 3.8.13 not in '~=3.9'\n\nThe location of the metadata is here:\n$ unzip foo-0.0.0-py3-none-any.whl\nArchive: foo-0.0.0-py3-none-any.whl\n inflating: foo-0.0.0.dist-info/METADATA \n inflating: foo-0.0.0.dist-info/WHEEL \n inflating: foo-0.0.0.dist-info/top_level.txt \n inflating: foo-0.0.0.dist-info/RECORD \n$ grep Requires foo-0.0.0.dist-info/METADATA\nRequires-Python: ~=3.9\n\nAs for how this works with PyPI - the index may return this metadata in the json API (example) and in the simple API (example)†. That allows pip to avoid downloading and unpacking incompatible wheels.\n† It's in a data-requires-python attribute of the href - you might have to \"view-source\" in your browser to see it.\n"
] |
[
2
] |
[] |
[] |
[
"pyproject.toml",
"python"
] |
stackoverflow_0074555302_pyproject.toml_python.txt
|
Q:
Pandas; Need to combine duplicate columns, and find the mean of another column
I have this data frame with about 200 rows, and I need to combine the duplicate writers columns, and then find the mean value of their viewership. How can I accomplish this? Below is a sample of the data frame.
Viewership Writers
0 11.20 Ricky Gervais
1 11.20 Stephen Merchant
2 11.20 Greg Daniels
3 8.70 Greg Daniels
4 10.30 Mindy Kaling
.. ... ...
192 3.25 Halsted Sullivan
193 3.25 Warren Lieberstein
194 3.51 Niki Schwartz-Wright
195 4.56 Brent Forrester
196 5.69 Greg Daniels
[197 rows x 2 columns]
My solution was:
mean = df2.groupby(['Writers']).mean()
print(mean)
However, it still lists all the writers with duplicates, and does not combine their viewership into a mean value. The result I get is:
Viewership
Writers
Brent Forrester 7.560000
Gabe Miller 4.165000
Gene Stupnitsky 8.618333
Gene Stupnitsky 10.200000
Greg Daniels 9.200000
Halsted Sullivan 7.503333
Justin Spitzer 7.670000
Lee Eisenberg 7.867143
Lee Eisenberg 10.120000
Michael Schur 9.040000
Mindy Kaling 9.420000
Paul Lieberstein 7.395000
Stephen Merchant 9.070000
Stephen Merchant 11.200000
Warren Lieberstein 5.280000
Aaron Shure 7.173333
Allison Silverman 4.746667
Amelie Gillette 5.655000
Anthony Q. Farrell 8.315000
B. J. Novak 7.718182
Brent Forrester 7.348889
Brent Forrester 7.670000
Caroline Williams 8.840000
Steve Carell 7.945000
Steve Hely 6.073333
Tim McAuliffe 3.440000
Warren Lieberstein 7.503333
I did my best to preserve the indentations I get in my results. As you can see, some writers have a whitespace at the beginning of their name. I'm sure this may be causing my issue?
A:
Try:
df2['Writers'] = df2['Writers'].str.strip()
mean = df2.groupby(['Writers']).mean()
print(mean)
This should remove any whitespace issues before grouping
|
Pandas; Need to combine duplicate columns, and find the mean of another column
|
I have this data frame with about 200 rows, and I need to combine the duplicate writers columns, and then find the mean value of their viewership. How can I accomplish this? Below is a sample of the data frame.
Viewership Writers
0 11.20 Ricky Gervais
1 11.20 Stephen Merchant
2 11.20 Greg Daniels
3 8.70 Greg Daniels
4 10.30 Mindy Kaling
.. ... ...
192 3.25 Halsted Sullivan
193 3.25 Warren Lieberstein
194 3.51 Niki Schwartz-Wright
195 4.56 Brent Forrester
196 5.69 Greg Daniels
[197 rows x 2 columns]
My solution was:
mean = df2.groupby(['Writers']).mean()
print(mean)
However, it still lists all the writers with duplicates, and does not combine their viewership into a mean value. The result I get is:
Viewership
Writers
Brent Forrester 7.560000
Gabe Miller 4.165000
Gene Stupnitsky 8.618333
Gene Stupnitsky 10.200000
Greg Daniels 9.200000
Halsted Sullivan 7.503333
Justin Spitzer 7.670000
Lee Eisenberg 7.867143
Lee Eisenberg 10.120000
Michael Schur 9.040000
Mindy Kaling 9.420000
Paul Lieberstein 7.395000
Stephen Merchant 9.070000
Stephen Merchant 11.200000
Warren Lieberstein 5.280000
Aaron Shure 7.173333
Allison Silverman 4.746667
Amelie Gillette 5.655000
Anthony Q. Farrell 8.315000
B. J. Novak 7.718182
Brent Forrester 7.348889
Brent Forrester 7.670000
Caroline Williams 8.840000
Steve Carell 7.945000
Steve Hely 6.073333
Tim McAuliffe 3.440000
Warren Lieberstein 7.503333
I did my best to preserve the indentations I get in my results. As you can see, some writers have a whitespace at the beginning of their name. I'm sure this may be causing my issue?
|
[
"Try:\ndf2['Writers'] = df2['Writers'].str.strip()\nmean = df2.groupby(['Writers']).mean()\nprint(mean)\n\nThis should remove any whitespace issues before grouping\n"
] |
[
1
] |
[] |
[] |
[
"duplicates",
"mean",
"multiple_columns",
"pandas",
"python"
] |
stackoverflow_0074555228_duplicates_mean_multiple_columns_pandas_python.txt
|
Q:
Using Lambda in GroupBy .agg to find Mean
I'm not understanding how to pull the Mean of filtered data within a groupby DataFrame. It works perfectly for sum(), but mean() simply gives me the Percentage of occurrences from the total count.
df = test.groupby(['Code']).agg(
Count=('% Change', 'count'),
H2C_Up_Mean=('% C2H',lambda x: (x > 0).mean()),
H2C_Pct_Up=('% C2H',lambda x: (x > 0).sum())
"H2C_Pct_Up" properly sums when I manually tally in Excel.
"H2C_Up_Mean" gives me "H2C_Pct_Up" DIVIDED by "Count"
How can I pull the 'Mean' of when "x > 0" from within a groupby dataframe?
Example Dataframe:
code % change % C2H
abc 0.50 0.75
abc 1.00 0.25
abc -0.25 -0.50
Expected output...
Count : 3 (CORRECT)
H2C_Pct_Up : 2 (CORRECT)
H2C_Up_Mean : 0.50 (ERROR; This produces 0.667)
A:
df = test.groupby(['Code']).agg(
Count=('% Change', 'count'),
H2C_Up_Mean=('% C2H',lambda x: x[x > 0].mean()),
H2C_Pct_Up=('% C2H',lambda x: (x > 0).sum()))
gives df as:
Count H2C_Up_Mean H2C_Pct_Up
Code
abc 3 0.5 2
|
Using Lambda in GroupBy .agg to find Mean
|
I'm not understanding how to pull the Mean of filtered data within a groupby DataFrame. It works perfectly for sum(), but mean() simply gives me the Percentage of occurrences from the total count.
df = test.groupby(['Code']).agg(
Count=('% Change', 'count'),
H2C_Up_Mean=('% C2H',lambda x: (x > 0).mean()),
H2C_Pct_Up=('% C2H',lambda x: (x > 0).sum())
"H2C_Pct_Up" properly sums when I manually tally in Excel.
"H2C_Up_Mean" gives me "H2C_Pct_Up" DIVIDED by "Count"
How can I pull the 'Mean' of when "x > 0" from within a groupby dataframe?
Example Dataframe:
code % change % C2H
abc 0.50 0.75
abc 1.00 0.25
abc -0.25 -0.50
Expected output...
Count : 3 (CORRECT)
H2C_Pct_Up : 2 (CORRECT)
H2C_Up_Mean : 0.50 (ERROR; This produces 0.667)
|
[
"df = test.groupby(['Code']).agg(\n Count=('% Change', 'count'),\n H2C_Up_Mean=('% C2H',lambda x: x[x > 0].mean()),\n H2C_Pct_Up=('% C2H',lambda x: (x > 0).sum()))\n\ngives df as:\n Count H2C_Up_Mean H2C_Pct_Up\nCode \nabc 3 0.5 2\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074554100_pandas_python.txt
|
Q:
Python merging multiple JSON into one JSON without result merged in list
I was trying to merge multiple JSON files into one JSON files
if file1.json has dict like
{"cars": 1, "houses": 2, "schools": 3, "stores": 4}
and file2.json has dict like
{"Pens": 1, "Pencils": 2, "Paper": 3}
The result I am looking for is file3.json
{"cars": 1, "houses": 2, "schools": 3, "stores": 4, "Pens": 1, "Pencils": 2, "Paper": 3}
However I got [{"cars": 1, "houses": 2, "schools": 3, "stores": 4, "Pens": 1, "Pencils": 2, "Paper": 3}] with the bracket at the start and the end
here is my code
glob_data=[]
for file in p_test:
with open(file) as infile:
glob_data.append(json.load(infile))
# print(glob_data)
with open(path, "w") as data:
json.dump(glob_data, data)
with open(path,encoding='utf-8') as file:
data = json.load(file)
how can I fix my code so I can combine them not in list data type?
thanks for any help!
A:
Just make a dictionary and update it:
data={}
for file in p_test:
with open(file) as infile:
data.update(json.load(infile))
with open(path, "w") as outfile:
json.dump(data, outfile)
with open(path,encoding='utf-8') as file:
data = json.load(file)
|
Python merging multiple JSON into one JSON without result merged in list
|
I was trying to merge multiple JSON files into one JSON files
if file1.json has dict like
{"cars": 1, "houses": 2, "schools": 3, "stores": 4}
and file2.json has dict like
{"Pens": 1, "Pencils": 2, "Paper": 3}
The result I am looking for is file3.json
{"cars": 1, "houses": 2, "schools": 3, "stores": 4, "Pens": 1, "Pencils": 2, "Paper": 3}
However I got [{"cars": 1, "houses": 2, "schools": 3, "stores": 4, "Pens": 1, "Pencils": 2, "Paper": 3}] with the bracket at the start and the end
here is my code
glob_data=[]
for file in p_test:
with open(file) as infile:
glob_data.append(json.load(infile))
# print(glob_data)
with open(path, "w") as data:
json.dump(glob_data, data)
with open(path,encoding='utf-8') as file:
data = json.load(file)
how can I fix my code so I can combine them not in list data type?
thanks for any help!
|
[
"Just make a dictionary and update it:\ndata={}\nfor file in p_test:\n with open(file) as infile:\n data.update(json.load(infile))\nwith open(path, \"w\") as outfile:\n json.dump(data, outfile)\n\nwith open(path,encoding='utf-8') as file:\n data = json.load(file)\n\n"
] |
[
0
] |
[] |
[] |
[
"dictionary",
"json",
"list",
"python"
] |
stackoverflow_0074555508_dictionary_json_list_python.txt
|
Q:
Conda build fails with `Aborting implicit building of eggs.` message
I am trying to build a new conda package based on an old one. The repo and code is available for Theme Material Darcula. Theme-material-darcula Jupyter labextension builds and install perfectly fine on my system. But the conda build . command fails for me on Aborting implicit building of eggs. Use pip install. to install from source.
The traceback is here:
cmdclass = create_cmdclass(
/home/adhadse/anaconda3/conda-bld/theme-material-darcula_1657766513713/work/setup.py:50: DeprecatedWarning: install_npm is deprecated as of 0.8 and will be removed in 1.0. Use `npm_builder` and `wrap_installers`
install_npm(HERE, build_cmd="build:prod", npm=["jlpm"]),
running install
/home/adhadse/anaconda3/conda-bld/theme-material-darcula_1657766513713/_build_env/lib/python3.9/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
/home/adhadse/anaconda3/conda-bld/theme-material-darcula_1657766513713/_build_env/lib/python3.9/site-packages/setuptools/command/easy_install.py:144: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
running bdist_egg
Aborting implicit building of eggs. Use `pip install .` to install from source.
Traceback (most recent call last):
File "/home/adhadse/anaconda3/bin/conda-build", line 11, in <module>
sys.exit(main())
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/cli/main_build.py", line 488, in main
execute(sys.argv[1:])
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/cli/main_build.py", line 477, in execute
outputs = api.build(args.recipe, post=args.post, test_run_post=args.test_run_post,
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/api.py", line 186, in build
return build_tree(
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/build.py", line 3088, in build_tree
packages_from_this = build(metadata, stats,
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/build.py", line 2211, in build
utils.check_call_env(cmd, env=env, rewrite_stdout_env=rewrite_env,
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/utils.py", line 411, in check_call_env
return _func_defaulting_env_to_os_environ('call', *popenargs, **kwargs)
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/utils.py", line 391, in _func_defaulting_env_to_os_environ
raise subprocess.CalledProcessError(proc.returncode, _args)
subprocess.CalledProcessError: Command '['/bin/bash', '-o', 'errexit', '/home/adhadse/anaconda3/conda-bld/theme-material-darcula_1657766513713/work/conda_build.sh']' returned non-zero exit status 1.
My Conda recipe (meta.yaml) is as follows:
package:
name: "theme-material-darcula"
version: "3.2.0"
source:
path: .
git_rev: v3.2.0
git_url: https://github.com/adhadse/theme-material-darcula
build:
script: python setup.py install -f
requirements:
host:
- python
build:
- python
- setuptools
- wheel
- jupyter-packaging
run:
- python
- jupyterlab>=3.0.0
about:
home: https://github.com/adhadse/theme-material-darcula
license: BSD
license_family: BSD
license_file: LICENSE
summary: "Darcula theme for JupyterLab with Material Design. Modelled after the classic Intellij theme."
extra:
recipe-maintainers:
- adhadse
What am I doing wrong?
A:
I'll answer my own question.
I'm building the package the wrong way. The package is supposed to be built using python setuptools via:
python3 setup.py sdist
which will create tarball file dist directory.
This file is supposed to be published to PyPI. A bash script will make the job a whole lot easier (do make sure to create an account on TestPyPI and PyPI):
# Adapted from https://github.com/jupyter-lsp/jupyterlab-lsp/blob/master/scripts/publish_pypi.sh
rm dist/*
python3 setup.py sdist
twine upload dist/* -r testpypi
echo "Published to testpypi"
while true; do
read -p "Do you wish to publish to pypi?" yn
case $yn in
[Yy]* ) twine upload dist/*; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
The script will first create tarball file and then first publish it to TestPyPI, if all looks fine, continue with publishing on PyPI.
Publishing to Conda
The same python package can be published to Conda via anaconda-client:
conda activate <enironment-name>
conda install anaconda-client
anaconda login
Then upload it:
anaconda upload dist/*
|
Conda build fails with `Aborting implicit building of eggs.` message
|
I am trying to build a new conda package based on an old one. The repo and code is available for Theme Material Darcula. Theme-material-darcula Jupyter labextension builds and install perfectly fine on my system. But the conda build . command fails for me on Aborting implicit building of eggs. Use pip install. to install from source.
The traceback is here:
cmdclass = create_cmdclass(
/home/adhadse/anaconda3/conda-bld/theme-material-darcula_1657766513713/work/setup.py:50: DeprecatedWarning: install_npm is deprecated as of 0.8 and will be removed in 1.0. Use `npm_builder` and `wrap_installers`
install_npm(HERE, build_cmd="build:prod", npm=["jlpm"]),
running install
/home/adhadse/anaconda3/conda-bld/theme-material-darcula_1657766513713/_build_env/lib/python3.9/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
/home/adhadse/anaconda3/conda-bld/theme-material-darcula_1657766513713/_build_env/lib/python3.9/site-packages/setuptools/command/easy_install.py:144: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
running bdist_egg
Aborting implicit building of eggs. Use `pip install .` to install from source.
Traceback (most recent call last):
File "/home/adhadse/anaconda3/bin/conda-build", line 11, in <module>
sys.exit(main())
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/cli/main_build.py", line 488, in main
execute(sys.argv[1:])
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/cli/main_build.py", line 477, in execute
outputs = api.build(args.recipe, post=args.post, test_run_post=args.test_run_post,
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/api.py", line 186, in build
return build_tree(
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/build.py", line 3088, in build_tree
packages_from_this = build(metadata, stats,
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/build.py", line 2211, in build
utils.check_call_env(cmd, env=env, rewrite_stdout_env=rewrite_env,
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/utils.py", line 411, in check_call_env
return _func_defaulting_env_to_os_environ('call', *popenargs, **kwargs)
File "/home/adhadse/anaconda3/lib/python3.9/site-packages/conda_build/utils.py", line 391, in _func_defaulting_env_to_os_environ
raise subprocess.CalledProcessError(proc.returncode, _args)
subprocess.CalledProcessError: Command '['/bin/bash', '-o', 'errexit', '/home/adhadse/anaconda3/conda-bld/theme-material-darcula_1657766513713/work/conda_build.sh']' returned non-zero exit status 1.
My Conda recipe (meta.yaml) is as follows:
package:
name: "theme-material-darcula"
version: "3.2.0"
source:
path: .
git_rev: v3.2.0
git_url: https://github.com/adhadse/theme-material-darcula
build:
script: python setup.py install -f
requirements:
host:
- python
build:
- python
- setuptools
- wheel
- jupyter-packaging
run:
- python
- jupyterlab>=3.0.0
about:
home: https://github.com/adhadse/theme-material-darcula
license: BSD
license_family: BSD
license_file: LICENSE
summary: "Darcula theme for JupyterLab with Material Design. Modelled after the classic Intellij theme."
extra:
recipe-maintainers:
- adhadse
What am I doing wrong?
|
[
"I'll answer my own question.\nI'm building the package the wrong way. The package is supposed to be built using python setuptools via:\npython3 setup.py sdist\n\nwhich will create tarball file dist directory.\nThis file is supposed to be published to PyPI. A bash script will make the job a whole lot easier (do make sure to create an account on TestPyPI and PyPI):\n# Adapted from https://github.com/jupyter-lsp/jupyterlab-lsp/blob/master/scripts/publish_pypi.sh\n\nrm dist/*\npython3 setup.py sdist\ntwine upload dist/* -r testpypi\necho \"Published to testpypi\"\nwhile true; do\n read -p \"Do you wish to publish to pypi?\" yn\n case $yn in\n [Yy]* ) twine upload dist/*; break;;\n [Nn]* ) exit;;\n * ) echo \"Please answer yes or no.\";;\n esac\ndone\n\nThe script will first create tarball file and then first publish it to TestPyPI, if all looks fine, continue with publishing on PyPI.\nPublishing to Conda\nThe same python package can be published to Conda via anaconda-client:\nconda activate <enironment-name>\nconda install anaconda-client\nanaconda login\n\nThen upload it:\nanaconda upload dist/*\n\n"
] |
[
0
] |
[] |
[] |
[
"anaconda",
"conda",
"conda_build",
"python",
"recipe"
] |
stackoverflow_0072974643_anaconda_conda_conda_build_python_recipe.txt
|
Q:
Stripping non printable characters from a string in python
I use to run
$s =~ s/[^[:print:]]//g;
on Perl to get rid of non printable characters.
In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not.
What would you do?
EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output.
curses.ascii.isprint will return false for any unicode character.
A:
Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Database for descriptions of the categories.
import unicodedata, re, itertools, sys
all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
For Python2
import unicodedata, re, sys
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
For some use-cases, additional categories (e.g. all from the control group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:
Cc (control): 65
Cf (format): 161
Cs (surrogate): 2048
Co (private-use): 137468
Cn (unassigned): 836601
Edit Adding suggestions from the comments.
A:
As far as I know, the most pythonic/efficient method would be:
import string
filtered_string = filter(lambda x: x in string.printable, myStr)
A:
You could try setting up a filter using the unicodedata.category() function:
import unicodedata
printable = {'Lu', 'Ll'}
def filter_non_printable(str):
return ''.join(c for c in str if unicodedata.category(c) in printable)
See Table 4-9 on page 175 in the Unicode database character properties for the available categories
A:
The following will work with Unicode input and is rather fast...
import sys
# build a table mapping all non-printable characters to None
NOPRINT_TRANS_TABLE = {
i: None for i in range(0, sys.maxunicode + 1) if not chr(i).isprintable()
}
def make_printable(s):
"""Replace non-printable characters in a string."""
# the translate method on str removes characters
# that map to None from the string
return s.translate(NOPRINT_TRANS_TABLE)
assert make_printable('Café') == 'Café'
assert make_printable('\x00\x11Hello') == 'Hello'
assert make_printable('') == ''
My own testing suggests this approach is faster than functions that iterate over the string and return a result using str.join.
A:
In Python 3,
def filter_nonprintable(text):
import itertools
# Use characters of control category
nonprintable = itertools.chain(range(0x00,0x20),range(0x7f,0xa0))
# Use translate to remove all non-printable characters
return text.translate({character:None for character in nonprintable})
See this StackOverflow post on removing punctuation for how .translate() compares to regex & .replace()
The ranges can be generated via nonprintable = (ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c)=='Cc') using the Unicode character database categories as shown by @Ants Aasma.
A:
This function uses list comprehensions and str.join, so it runs in linear time instead of O(n^2):
from curses.ascii import isprint
def printable(input):
return ''.join(char for char in input if isprint(char))
A:
Yet another option in python 3:
re.sub(f'[^{re.escape(string.printable)}]', '', my_string)
A:
Based on @Ber's answer, I suggest removing only control characters as defined in the Unicode character database categories:
import unicodedata
def filter_non_printable(s):
return ''.join(c for c in s if not unicodedata.category(c).startswith('C'))
A:
The best I've come up with now is (thanks to the python-izers above)
def filter_non_printable(str):
return ''.join([c for c in str if ord(c) > 31 or ord(c) == 9])
This is the only way I've found out that works with Unicode characters/strings
Any better options?
A:
In Python there's no POSIX regex classes
There are when using the regex library: https://pypi.org/project/regex/
It is well maintained and supports Unicode regex, Posix regex and many more. The usage (method signatures) is very similar to Python's re.
From the documentation:
[[:alpha:]]; [[:^alpha:]]
POSIX character classes are supported. These
are normally treated as an alternative form of \p{...}.
(I'm not affiliated, just a user.)
A:
An elegant pythonic solution to stripping 'non printable' characters from a string in python is to use the isprintable() string method together with a generator expression or list comprehension depending on the use case ie. size of the string:
''.join(c for c in my_string if c.isprintable())
str.isprintable()
Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)
A:
The one below performs faster than the others above. Take a look
''.join([x if x in string.printable else '' for x in Str])
A:
Adapted from answers by Ants Aasma and shawnrad:
nonprintable = set(map(chr, list(range(0,32)) + list(range(127,160))))
ord_dict = {ord(character):None for character in nonprintable}
def filter_nonprintable(text):
return text.translate(ord_dict)
#use
str = "this is my string"
str = filter_nonprintable(str)
print(str)
tested on Python 3.7.7
A:
To remove 'whitespace',
import re
t = """
\n\t<p> </p>\n\t<p> </p>\n\t<p> </p>\n\t<p> </p>\n\t<p>
"""
pat = re.compile(r'[\t\n]')
print(pat.sub("", t))
A:
Error description
Run the copied and pasted python code report:
Python invalid non-printable character U+00A0
The cause of the error
The space in the copied code is not the same as the format in Python;
Solution
Delete the space and re-enter the space. For example, the red part in the above picture is an abnormal space. Delete and re-enter the space to run;
Source : Python invalid non-printable character U+00A0
A:
I used this:
import sys
import unicodedata
# the test string has embedded characters, \u2069 \u2068
test_string = """"ABC. 6", "}"""
nonprintable = list((ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if
unicodedata.category(c) in ['Cc','Cf']))
translate_dict = {character: None for character in nonprintable}
print("Before translate, using repr()", repr(test_string))
print("After translate, using repr()", repr(test_string.translate(translate_dict)))
|
Stripping non printable characters from a string in python
|
I use to run
$s =~ s/[^[:print:]]//g;
on Perl to get rid of non printable characters.
In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not.
What would you do?
EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output.
curses.ascii.isprint will return false for any unicode character.
|
[
"Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Database for descriptions of the categories.\nimport unicodedata, re, itertools, sys\n\nall_chars = (chr(i) for i in range(sys.maxunicode))\ncategories = {'Cc'}\ncontrol_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)\n# or equivalently and much more efficiently\ncontrol_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))\n\ncontrol_char_re = re.compile('[%s]' % re.escape(control_chars))\n\ndef remove_control_chars(s):\n return control_char_re.sub('', s)\n\nFor Python2\nimport unicodedata, re, sys\n\nall_chars = (unichr(i) for i in xrange(sys.maxunicode))\ncategories = {'Cc'}\ncontrol_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)\n# or equivalently and much more efficiently\ncontrol_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))\n\ncontrol_char_re = re.compile('[%s]' % re.escape(control_chars))\n\ndef remove_control_chars(s):\n return control_char_re.sub('', s)\n\nFor some use-cases, additional categories (e.g. all from the control group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:\n\nCc (control): 65\nCf (format): 161\nCs (surrogate): 2048\nCo (private-use): 137468\nCn (unassigned): 836601\n\nEdit Adding suggestions from the comments.\n",
"As far as I know, the most pythonic/efficient method would be:\nimport string\n\nfiltered_string = filter(lambda x: x in string.printable, myStr)\n\n",
"You could try setting up a filter using the unicodedata.category() function:\nimport unicodedata\nprintable = {'Lu', 'Ll'}\ndef filter_non_printable(str):\n return ''.join(c for c in str if unicodedata.category(c) in printable)\n\nSee Table 4-9 on page 175 in the Unicode database character properties for the available categories\n",
"The following will work with Unicode input and is rather fast...\nimport sys\n\n# build a table mapping all non-printable characters to None\nNOPRINT_TRANS_TABLE = {\n i: None for i in range(0, sys.maxunicode + 1) if not chr(i).isprintable()\n}\n\ndef make_printable(s):\n \"\"\"Replace non-printable characters in a string.\"\"\"\n\n # the translate method on str removes characters\n # that map to None from the string\n return s.translate(NOPRINT_TRANS_TABLE)\n\n\nassert make_printable('Café') == 'Café'\nassert make_printable('\\x00\\x11Hello') == 'Hello'\nassert make_printable('') == ''\n\nMy own testing suggests this approach is faster than functions that iterate over the string and return a result using str.join.\n",
"In Python 3,\ndef filter_nonprintable(text):\n import itertools\n # Use characters of control category\n nonprintable = itertools.chain(range(0x00,0x20),range(0x7f,0xa0))\n # Use translate to remove all non-printable characters\n return text.translate({character:None for character in nonprintable})\n\nSee this StackOverflow post on removing punctuation for how .translate() compares to regex & .replace()\nThe ranges can be generated via nonprintable = (ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if unicodedata.category(c)=='Cc') using the Unicode character database categories as shown by @Ants Aasma.\n",
"This function uses list comprehensions and str.join, so it runs in linear time instead of O(n^2):\nfrom curses.ascii import isprint\n\ndef printable(input):\n return ''.join(char for char in input if isprint(char))\n\n",
"Yet another option in python 3:\nre.sub(f'[^{re.escape(string.printable)}]', '', my_string)\n\n",
"Based on @Ber's answer, I suggest removing only control characters as defined in the Unicode character database categories:\nimport unicodedata\ndef filter_non_printable(s):\n return ''.join(c for c in s if not unicodedata.category(c).startswith('C'))\n\n",
"The best I've come up with now is (thanks to the python-izers above) \ndef filter_non_printable(str):\n return ''.join([c for c in str if ord(c) > 31 or ord(c) == 9])\n\nThis is the only way I've found out that works with Unicode characters/strings\nAny better options?\n",
"\nIn Python there's no POSIX regex classes\n\nThere are when using the regex library: https://pypi.org/project/regex/\nIt is well maintained and supports Unicode regex, Posix regex and many more. The usage (method signatures) is very similar to Python's re.\nFrom the documentation:\n\n[[:alpha:]]; [[:^alpha:]]\nPOSIX character classes are supported. These\n are normally treated as an alternative form of \\p{...}.\n\n(I'm not affiliated, just a user.)\n",
"An elegant pythonic solution to stripping 'non printable' characters from a string in python is to use the isprintable() string method together with a generator expression or list comprehension depending on the use case ie. size of the string:\n ''.join(c for c in my_string if c.isprintable())\n\nstr.isprintable()\nReturn True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)\n",
"The one below performs faster than the others above. Take a look\n''.join([x if x in string.printable else '' for x in Str])\n\n",
"Adapted from answers by Ants Aasma and shawnrad:\nnonprintable = set(map(chr, list(range(0,32)) + list(range(127,160))))\nord_dict = {ord(character):None for character in nonprintable}\ndef filter_nonprintable(text):\n return text.translate(ord_dict)\n\n#use\nstr = \"this is my string\"\nstr = filter_nonprintable(str)\nprint(str)\n\ntested on Python 3.7.7\n",
"To remove 'whitespace',\nimport re\nt = \"\"\"\n\\n\\t<p> </p>\\n\\t<p> </p>\\n\\t<p> </p>\\n\\t<p> </p>\\n\\t<p>\n\"\"\"\npat = re.compile(r'[\\t\\n]')\nprint(pat.sub(\"\", t))\n\n",
"\nError description\nRun the copied and pasted python code report:\n\nPython invalid non-printable character U+00A0\n\nThe cause of the error\nThe space in the copied code is not the same as the format in Python;\n\nSolution\nDelete the space and re-enter the space. For example, the red part in the above picture is an abnormal space. Delete and re-enter the space to run;\n\n\nSource : Python invalid non-printable character U+00A0\n\n",
"I used this:\nimport sys\nimport unicodedata\n\n# the test string has embedded characters, \\u2069 \\u2068\ntest_string = \"\"\"\"ABC. 6\", \"}\"\"\"\nnonprintable = list((ord(c) for c in (chr(i) for i in range(sys.maxunicode)) if\n unicodedata.category(c) in ['Cc','Cf']))\n\ntranslate_dict = {character: None for character in nonprintable}\nprint(\"Before translate, using repr()\", repr(test_string))\nprint(\"After translate, using repr()\", repr(test_string.translate(translate_dict)))\n\n"
] |
[
94,
83,
20,
15,
13,
8,
7,
6,
3,
3,
3,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"non_printable",
"python",
"string"
] |
stackoverflow_0000092438_non_printable_python_string.txt
|
Q:
Render a Django view with data classified in a one to many relationship
I have a one to many relationshiop:
class SessionGPS(models.Model):
start_timestamp = models.IntegerField()
end_timestamp= models.IntegerField()
class GPSData(models.Model):
longitude = models.DecimalField(max_digits=15, decimal_places=13)
lat = models.DecimalField(max_digits=15, decimal_places=13)
session_new = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name="sesion_gps")
Each SessionGPS entry has multiple GPSData entries. A session is composed of a set of GPS coordinates. This set is in the model GPSData.
I need to query SessionGPS based in start and end timestamps:
def date_search(request):
data = request.body.decode("utf-8")
start=int(datetime.datetime.strptime(request.POST['start'], '%Y-%m-%d').timestamp())
end=int(datetime.datetime.strptime(request.POST['end'], '%Y-%m-%d').timestamp())
res = GPSData.objects.filter(session_new_id__start_timestamp__gte=start,session_new_id__end_timestamp__lte=end)
res = serializers.serialize("json", res)
return HttpResponse(res, content_type='application/json')
In this way I get all GPSData between the timestamps but are not classified by session, they are merged.
I need to get the query like this:
session 1 ->> all GPSData of that session 1
session 2 ->> all GPSData of that session 2
So in the template I can render like this:
For GPSData in session 1 do something
For GPSData in session 2 do something
etc.
I tried to return multiple queries to the view but it didn't worked.
Thanks for any help.
A:
I don't think there is a query option to what you want. So, the only way I could think of is to post process the data:
models.py:
class SessionGPS(models.Model):
start_timestamp = models.DateTimeField(auto_now_add=True)
end_timestamp = models.DateTimeField(null=True)
class GPSData(models.Model):
longitude = models.DecimalField(max_digits=15, decimal_places=13)
latitude = models.DecimalField(max_digits=15, decimal_places=13)
session = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name="sesion_gps")
views.py:
def gps_timestamps(request):
if request.method == 'POST':
start = request.POST.get('start_date').split('-')
end = request.POST.get('end_date').split('-')
start_date = datetime.datetime(int(start[0]), int(start[1]), int(start[2]))
end_date = datetime.datetime(int(end[0]), int(end[1]), int(end[2]))
data_rows = GPSData.objects.filter(session__start_timestamp__gte=start_date,session__end_timestamp__lte=end_date)
# Initialize dictionary
# with unique sessions keys inside the queryset
data = {}
for row in data_rows:
if row.session.id not in data:
data[row.session.id] = {
'start_time': row.session.start_timestamp.strftime("%Y-%m-%d"),
'end_time': row.session.end_timestamp.strftime("%Y-%m-%d"),
}
else:
pass
# Populate
for key, value in data.items():
gps_data_list = []
for row in data_rows:
if row.session.id == key:
gps_data_list.append( {'latitude': str(row.latitude), 'longitude': str(row.longitude)} )
data[key].update(data=gps_data_list)
# If you really want JSON
json_object = json.dumps(data, indent = 4)
print(json_object)
context = {
'data': data
}
return render(request, 'gps_timestamp.html', context)
gps_timestamp.html (I used bootstrap 5), two inputs with format yyyy-mm-dd:
<div class="container">
<form action="{% url 'app:urlname' %}" method="post">
{% csrf_token %}
<div class="form-group mb-3">
<label class="form-label" for="start_date">Start Date</label>
<input id="start_date" name="start_date" type="text" class="form-control" placeholder="year-month-day" aria-label="start_date">
</div>
<div class="form-group mb-3">
<label class="form-label" for="end_date">End Date</label>
<input id="end_date" name="end_date" type="text" class="form-control" placeholder="year-month-day" aria-label="end_date">
</div>
<input type="submit" value="OK">
</form>
</div>
<div class="container d-flex justify-content-center" style="flex-direction: column;">
{% for key, obj in data.items %}
<p>Session ID: {{key}}</p>
<p>Start Time: {{obj.start_time}}</p>
<p>End Time: {{obj.end_time}}</p>
<p>GPS Data:</p>
{% for row in obj.data %}
{{row}}
<br>
{% endfor %}
<p>----------------------------------</p>
{% endfor %}
</div>
JSON output of my test:
{
"2": {
"start_time": "2022-11-25",
"end_time": "2022-11-26",
"data": [
{
"latitude": "70.7762500000000",
"longitude": "12.4800500000000"
},
{
"latitude": "42.7545200000000",
"longitude": "71.1392900000000"
},
{
"latitude": "56.1794700000000",
"longitude": "90.8119600000000"
}
]
},
"3": {
"start_time": "2022-11-27",
"end_time": "2022-11-28",
"data": [
{
"latitude": "10.1099500000000",
"longitude": "-19.2024500000000"
},
{
"latitude": "80.1405100000000",
"longitude": "16.2555700000000"
},
{
"latitude": "-16.1924200000000",
"longitude": "-51.7266300000000"
},
{
"latitude": "19.4745700000000",
"longitude": "10.7191800000000"
}
]
}
}
By the way, I have to mention that I had some problems with your GPSData model, when either latitude or logitude had 3 digits. Like, 123.3123123.
It only accepts <100, but I didn't get into this.
Just changed SessionGPS to better access data.
|
Render a Django view with data classified in a one to many relationship
|
I have a one to many relationshiop:
class SessionGPS(models.Model):
start_timestamp = models.IntegerField()
end_timestamp= models.IntegerField()
class GPSData(models.Model):
longitude = models.DecimalField(max_digits=15, decimal_places=13)
lat = models.DecimalField(max_digits=15, decimal_places=13)
session_new = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name="sesion_gps")
Each SessionGPS entry has multiple GPSData entries. A session is composed of a set of GPS coordinates. This set is in the model GPSData.
I need to query SessionGPS based in start and end timestamps:
def date_search(request):
data = request.body.decode("utf-8")
start=int(datetime.datetime.strptime(request.POST['start'], '%Y-%m-%d').timestamp())
end=int(datetime.datetime.strptime(request.POST['end'], '%Y-%m-%d').timestamp())
res = GPSData.objects.filter(session_new_id__start_timestamp__gte=start,session_new_id__end_timestamp__lte=end)
res = serializers.serialize("json", res)
return HttpResponse(res, content_type='application/json')
In this way I get all GPSData between the timestamps but are not classified by session, they are merged.
I need to get the query like this:
session 1 ->> all GPSData of that session 1
session 2 ->> all GPSData of that session 2
So in the template I can render like this:
For GPSData in session 1 do something
For GPSData in session 2 do something
etc.
I tried to return multiple queries to the view but it didn't worked.
Thanks for any help.
|
[
"I don't think there is a query option to what you want. So, the only way I could think of is to post process the data:\nmodels.py:\nclass SessionGPS(models.Model):\n start_timestamp = models.DateTimeField(auto_now_add=True)\n end_timestamp = models.DateTimeField(null=True)\n \nclass GPSData(models.Model):\n longitude = models.DecimalField(max_digits=15, decimal_places=13)\n latitude = models.DecimalField(max_digits=15, decimal_places=13)\n session = models.ForeignKey(SessionGPS, on_delete=models.CASCADE, related_name=\"sesion_gps\")\n\nviews.py:\ndef gps_timestamps(request):\n if request.method == 'POST':\n start = request.POST.get('start_date').split('-')\n end = request.POST.get('end_date').split('-')\n\n start_date = datetime.datetime(int(start[0]), int(start[1]), int(start[2]))\n end_date = datetime.datetime(int(end[0]), int(end[1]), int(end[2]))\n data_rows = GPSData.objects.filter(session__start_timestamp__gte=start_date,session__end_timestamp__lte=end_date)\n \n # Initialize dictionary\n # with unique sessions keys inside the queryset\n data = {}\n for row in data_rows:\n if row.session.id not in data:\n data[row.session.id] = {\n 'start_time': row.session.start_timestamp.strftime(\"%Y-%m-%d\"),\n 'end_time': row.session.end_timestamp.strftime(\"%Y-%m-%d\"),\n }\n else:\n pass\n \n # Populate\n for key, value in data.items():\n gps_data_list = []\n for row in data_rows:\n if row.session.id == key:\n gps_data_list.append( {'latitude': str(row.latitude), 'longitude': str(row.longitude)} )\n data[key].update(data=gps_data_list)\n\n # If you really want JSON\n json_object = json.dumps(data, indent = 4) \n print(json_object)\n\n context = {\n 'data': data\n }\n return render(request, 'gps_timestamp.html', context)\n\ngps_timestamp.html (I used bootstrap 5), two inputs with format yyyy-mm-dd:\n<div class=\"container\">\n <form action=\"{% url 'app:urlname' %}\" method=\"post\">\n {% csrf_token %}\n <div class=\"form-group mb-3\">\n <label class=\"form-label\" for=\"start_date\">Start Date</label>\n <input id=\"start_date\" name=\"start_date\" type=\"text\" class=\"form-control\" placeholder=\"year-month-day\" aria-label=\"start_date\">\n </div>\n <div class=\"form-group mb-3\">\n <label class=\"form-label\" for=\"end_date\">End Date</label>\n <input id=\"end_date\" name=\"end_date\" type=\"text\" class=\"form-control\" placeholder=\"year-month-day\" aria-label=\"end_date\">\n </div>\n <input type=\"submit\" value=\"OK\">\n </form>\n</div>\n\n<div class=\"container d-flex justify-content-center\" style=\"flex-direction: column;\">\n {% for key, obj in data.items %}\n <p>Session ID: {{key}}</p>\n <p>Start Time: {{obj.start_time}}</p>\n <p>End Time: {{obj.end_time}}</p>\n <p>GPS Data:</p>\n {% for row in obj.data %}\n {{row}}\n <br>\n {% endfor %} \n <p>----------------------------------</p>\n {% endfor %}\n</div>\n\nJSON output of my test:\n{\n \"2\": {\n \"start_time\": \"2022-11-25\",\n \"end_time\": \"2022-11-26\",\n \"data\": [\n {\n \"latitude\": \"70.7762500000000\",\n \"longitude\": \"12.4800500000000\"\n },\n {\n \"latitude\": \"42.7545200000000\",\n \"longitude\": \"71.1392900000000\"\n },\n {\n \"latitude\": \"56.1794700000000\",\n \"longitude\": \"90.8119600000000\"\n }\n ]\n },\n \"3\": {\n \"start_time\": \"2022-11-27\",\n \"end_time\": \"2022-11-28\",\n \"data\": [\n {\n \"latitude\": \"10.1099500000000\",\n \"longitude\": \"-19.2024500000000\"\n },\n {\n \"latitude\": \"80.1405100000000\",\n \"longitude\": \"16.2555700000000\"\n },\n {\n \"latitude\": \"-16.1924200000000\",\n \"longitude\": \"-51.7266300000000\"\n },\n {\n \"latitude\": \"19.4745700000000\",\n \"longitude\": \"10.7191800000000\"\n }\n ]\n }\n}\n\nBy the way, I have to mention that I had some problems with your GPSData model, when either latitude or logitude had 3 digits. Like, 123.3123123.\nIt only accepts <100, but I didn't get into this.\nJust changed SessionGPS to better access data.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0074554244_django_python.txt
|
Q:
Taking multiple integers on the same line as input from the user in python
I know how to take a single input from user in python 2.5:
raw_input("enter 1st number")
This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box.
How can I take two or more inputs together in the same dialogue box that opens such that:
Enter 1st number:................
enter second number:.............
A:
This might prove useful:
a,b=map(int,raw_input().split())
You can then use 'a' and 'b' separately.
A:
How about something like this?
user_input = raw_input("Enter three numbers separated by commas: ")
input_list = user_input.split(',')
numbers = [float(x.strip()) for x in input_list]
(You would probably want some error handling too)
A:
Or if you are collecting many numbers, use a loop
num = []
for i in xrange(1, 10):
num.append(raw_input('Enter the %s number: '))
print num
A:
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop's level.
For instance,
data=""
while 1:
data=raw_input("Command: ")
if data in ("test", "experiment", "try"):
data2=""
while data2=="":
data2=raw_input("Which test? ")
if data2=="chemical":
print("You chose a chemical test.")
else:
print("We don't have any " + data2 + " tests.")
elif data=="quit":
break
else:
pass
A:
a, b, c = input().split() # for space-separated inputs
a, b, c = input().split(",") # for comma-separated inputs
A:
You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed
user_input = input("Enter Numbers\n").split(',')
#strip is used to remove the white space. Not mandatory
all_numbers = [int(x.strip()) for x in user_input]
for i in all_numbers:
print(i)
A:
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
A:
The best way to practice by using a single liner,
Syntax:
list(map(inputType, input("Enter").split(",")))
Taking multiple integer inputs:
list(map(int, input('Enter: ').split(',')))
Taking multiple Float inputs:
list(map(float, input('Enter: ').split(',')))
Taking multiple String inputs:
list(map(str, input('Enter: ').split(',')))
A:
List_of_input=list(map(int,input (). split ()))
print(List_of_input)
It's for Python3.
A:
Python and all other imperative programming languages execute one command after another. Therefore, you can just write:
first = raw_input('Enter 1st number: ')
second = raw_input('Enter second number: ')
Then, you can operate on the variables first and second. For example, you can convert the strings stored in them to integers and multiply them:
product = int(first) * int(second)
print('The product of the two is ' + str(product))
A:
In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way.
I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','.
items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')]
print items
A:
You can try this.
import sys
for line in sys.stdin:
j= int(line[0])
e= float(line[1])
t= str(line[2])
For details, please review,
https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects
A:
Split function will split the input data according to whitespace.
data = input().split()
name=data[0]
id=data[1]
marks = list(map(datatype, data[2:]))
name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.
A:
A common arrangement is to read one string at a time until the user inputs an empty string.
strings = []
# endless loop, exit condition within
while True:
inputstr = input('Enter another string, or nothing to quit: ')
if inputstr:
strings.append(inputstr)
else:
break
This is Python 3 code; for Python 2, you would use raw_input instead of input.
Another common arrangement is to read strings from a file, one per line. This is more convenient for the user because they can go back and fix typos in the file and rerun the script, which they can't for a tool which requires interactive input (unless you spend a lot more time on basically building an editor into the script!)
with open(filename) as lines:
strings = [line.rstrip('\n') for line in lines]
A:
n = int(input())
for i in range(n):
i = int(input())
If you dont want to use lists, check out this code
A:
There are 2 methods which can be used:
This method is using list comprehension as shown below:
x, y = [int(x) for x in input("Enter two numbers: ").split()] # This program takes inputs, converts them into integer and splits them and you need to provide 2 inputs using space as space is default separator for split.
x, y = [int(x) for x in input("Enter two numbers: ").split(",")] # This one is used when you want to input number using comma.
Another method is used if you want to get inputs as a list as shown below:
x, y = list(map(int, input("Enter the numbers: ").split())) # The inputs are converted/mapped into integers using map function and type-casted into a list
|
Taking multiple integers on the same line as input from the user in python
|
I know how to take a single input from user in python 2.5:
raw_input("enter 1st number")
This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box.
How can I take two or more inputs together in the same dialogue box that opens such that:
Enter 1st number:................
enter second number:.............
|
[
"This might prove useful:\na,b=map(int,raw_input().split())\n\nYou can then use 'a' and 'b' separately.\n",
"How about something like this?\nuser_input = raw_input(\"Enter three numbers separated by commas: \")\n\ninput_list = user_input.split(',')\nnumbers = [float(x.strip()) for x in input_list]\n\n(You would probably want some error handling too)\n",
"Or if you are collecting many numbers, use a loop\nnum = []\nfor i in xrange(1, 10):\n num.append(raw_input('Enter the %s number: '))\n\nprint num\n\n",
"My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it's not what you wanted, but I already wrote this answer before I realized that. So, I'm going to post it in case other people (or even you) find it useful.\nYou just need nested loops with an input statement at each loop's level.\nFor instance,\ndata=\"\"\nwhile 1:\n data=raw_input(\"Command: \")\n if data in (\"test\", \"experiment\", \"try\"):\n data2=\"\"\n while data2==\"\":\n data2=raw_input(\"Which test? \")\n if data2==\"chemical\":\n print(\"You chose a chemical test.\")\n else:\n print(\"We don't have any \" + data2 + \" tests.\")\n elif data==\"quit\":\n break\n else:\n pass\n\n",
"\na, b, c = input().split() # for space-separated inputs\na, b, c = input().split(\",\") # for comma-separated inputs\n\n",
"You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed\nuser_input = input(\"Enter Numbers\\n\").split(',')\n#strip is used to remove the white space. Not mandatory\nall_numbers = [int(x.strip()) for x in user_input]\nfor i in all_numbers:\n print(i)\n\n",
"You could use the below to take multiple inputs separated by a keyword\na,b,c=raw_input(\"Please enter the age of 3 people in one line using commas\\n\").split(',')\n\n",
"The best way to practice by using a single liner,\nSyntax:\n\nlist(map(inputType, input(\"Enter\").split(\",\")))\n\nTaking multiple integer inputs:\n list(map(int, input('Enter: ').split(',')))\n\n\nTaking multiple Float inputs:\nlist(map(float, input('Enter: ').split(',')))\n\n\nTaking multiple String inputs:\nlist(map(str, input('Enter: ').split(',')))\n\n\n",
"List_of_input=list(map(int,input (). split ()))\nprint(List_of_input)\n\nIt's for Python3.\n",
"Python and all other imperative programming languages execute one command after another. Therefore, you can just write:\nfirst = raw_input('Enter 1st number: ')\nsecond = raw_input('Enter second number: ')\n\nThen, you can operate on the variables first and second. For example, you can convert the strings stored in them to integers and multiply them:\nproduct = int(first) * int(second)\nprint('The product of the two is ' + str(product))\n\n",
"In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way.\nI am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ','. \nitems= [x for x in raw_input(\"Enter your numbers comma separated: \").split(',')]\n\nprint items\n\n",
"You can try this.\nimport sys\n\nfor line in sys.stdin:\n j= int(line[0])\n e= float(line[1])\n t= str(line[2])\n\nFor details, please review,\nhttps://en.wikibooks.org/wiki/Python_Programming/Input_and_Output#Standard_File_Objects\n",
"Split function will split the input data according to whitespace.\ndata = input().split()\nname=data[0]\nid=data[1]\nmarks = list(map(datatype, data[2:]))\n\nname will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.\n",
"A common arrangement is to read one string at a time until the user inputs an empty string.\nstrings = []\n# endless loop, exit condition within\nwhile True:\n inputstr = input('Enter another string, or nothing to quit: ')\n if inputstr:\n strings.append(inputstr)\n else:\n break\n\nThis is Python 3 code; for Python 2, you would use raw_input instead of input.\nAnother common arrangement is to read strings from a file, one per line. This is more convenient for the user because they can go back and fix typos in the file and rerun the script, which they can't for a tool which requires interactive input (unless you spend a lot more time on basically building an editor into the script!)\nwith open(filename) as lines:\n strings = [line.rstrip('\\n') for line in lines]\n\n",
"n = int(input())\nfor i in range(n):\n i = int(input())\n\nIf you dont want to use lists, check out this code\n",
"There are 2 methods which can be used:\n\nThis method is using list comprehension as shown below:\n x, y = [int(x) for x in input(\"Enter two numbers: \").split()] # This program takes inputs, converts them into integer and splits them and you need to provide 2 inputs using space as space is default separator for split.\n\n x, y = [int(x) for x in input(\"Enter two numbers: \").split(\",\")] # This one is used when you want to input number using comma.\n\n\nAnother method is used if you want to get inputs as a list as shown below:\n x, y = list(map(int, input(\"Enter the numbers: \").split())) # The inputs are converted/mapped into integers using map function and type-casted into a list\n\n\n\n"
] |
[
17,
16,
4,
2,
2,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
] |
[
"Try this:\nprint (\"Enter the Five Numbers with Comma\")\n\nk=[x for x in input(\"Enter Number:\").split(',')]\n\nfor l in k:\n print (l)\n\n",
"How about making the input a list. Then you may use standard list operations.\na=list(input(\"Enter the numbers\"))\n\n",
"# the more input you want to add variable accordingly\nx,y,z=input(\"enter the numbers: \").split( ) \n#for printing \nprint(\"value of x: \",x)\nprint(\"value of y: \",y)\nprint(\"value of z: \",z)\n\n#for multiple inputs \n#using list, map\n#split seperates values by ( )single space in this case\n\nx=list(map(int,input(\"enter the numbers: \").split( )))\n\n#we will get list of our desired elements \n\nprint(\"print list: \",x)\n\nhope you got your answer :)\n"
] |
[
-1,
-1,
-1
] |
[
"python",
"python_2.x"
] |
stackoverflow_0007378091_python_python_2.x.txt
|
Q:
What is the logic used to break down multiple lambda variables in python?
I am trying to reason through why the result of the following would be 8 but I'm a little stuck.
f = lambda x,y: lambda z: (x)(y)(z)
print((f)(lambda x: lambda y: x, lambda z: z*2)(3)(4))
I know that the next step would be to substitute f into the line as shown below, but this is where I get lost.
ans = (lambda x,y: lambda z: (x)(y)(z))(lambda x: lambda y: x, lambda z: z*2)(3)(4)
From my understanding, f requires three arguments in total, one in this (x,y) format and another one like (z).
(lambda x: lambda y: x, lambda z: z*2)(3)(4)
I think 3 should be the argument for lambda x and nothing should be inputted for lambda y. I think 4 would then be the argument for lambda z.
This leads me to think (3,8) is what is returned for (lambda x: lambda y: x, lambda z: z*2), but then I don't have an input for lambda z in the original f.
I could use explanation of how this is processed to give a final answer of 8. Apologies for any formatting errors.
A:
Let's give a name to some of those lambdas:
const = lambda x: (lambda y: x)
double = lambda z: (z*2)
And eta-reduct the lambda z:... inside f (that is lambda z: ( x(y) )(z) -> x(y)):
f = lambda x, y: x(y)
We can now rewrite that expression as ( ( f(const, double) )(3) )(4).
Reducing, we get:
f(const, double) -> const(double) -> lambda y: double
(lambda y: double)(3) -> double
double(4) -> 8
|
What is the logic used to break down multiple lambda variables in python?
|
I am trying to reason through why the result of the following would be 8 but I'm a little stuck.
f = lambda x,y: lambda z: (x)(y)(z)
print((f)(lambda x: lambda y: x, lambda z: z*2)(3)(4))
I know that the next step would be to substitute f into the line as shown below, but this is where I get lost.
ans = (lambda x,y: lambda z: (x)(y)(z))(lambda x: lambda y: x, lambda z: z*2)(3)(4)
From my understanding, f requires three arguments in total, one in this (x,y) format and another one like (z).
(lambda x: lambda y: x, lambda z: z*2)(3)(4)
I think 3 should be the argument for lambda x and nothing should be inputted for lambda y. I think 4 would then be the argument for lambda z.
This leads me to think (3,8) is what is returned for (lambda x: lambda y: x, lambda z: z*2), but then I don't have an input for lambda z in the original f.
I could use explanation of how this is processed to give a final answer of 8. Apologies for any formatting errors.
|
[
"Let's give a name to some of those lambdas:\nconst = lambda x: (lambda y: x)\ndouble = lambda z: (z*2)\n\nAnd eta-reduct the lambda z:... inside f (that is lambda z: ( x(y) )(z) -> x(y)):\nf = lambda x, y: x(y)\n\nWe can now rewrite that expression as ( ( f(const, double) )(3) )(4).\nReducing, we get:\nf(const, double) -> const(double) -> lambda y: double\n(lambda y: double)(3) -> double\ndouble(4) -> 8\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074555178_python.txt
|
Q:
How to use groupby transform across multiple columns
I have a big dataframe, and I'm grouping by one to n columns, and want to apply a function on these groups across two columns (e.g. foo and bar).
Here's an example dataframe:
foo_function = lambda x: np.sum(x.a+x.b)
df = pd.DataFrame({'a':[1,2,3,4,5,6],
'b':[1,2,3,4,5,6],
'c':['q', 'q', 'q', 'q', 'w', 'w'],
'd':['z','z','z','o','o','o']})
# works with apply, but I want transform:
df.groupby(['c', 'd'])[['a','b']].apply(foo_function)
# transform doesn't work!
df.groupby(['c', 'd'])[['a','b']].transform(foo_function)
TypeError: cannot concatenate a non-NDFrame object
But transform apparently isn't able to combine multiple columns together because it looks at each column separately (unlike apply). What is the next best alternative in terms of speed / elegance? e.g. I could use apply and then create df['new_col'] by using pd.match, but that would necessitate matching over sometimes multiple groupby columns (col1 and col2) which seems really hacky / would take a fair amount of code.
--> Is there a function that is like groupby().transform that can use functions that work over multiple columns? If this doesn't exist, what's the best hack?
A:
Circa Pandas version 0.18, it appears the original answer (below) no longer works.
Instead, if you need to do a groupby computation across multiple columns, do the multi-column computation first, and then the groupby:
df = pd.DataFrame({'a':[1,2,3,4,5,6],
'b':[1,2,3,4,5,6],
'c':['q', 'q', 'q', 'q', 'w', 'w'],
'd':['z','z','z','o','o','o']})
df['e'] = df['a'] + df['b']
df['e'] = (df.groupby(['c', 'd'])['e'].transform('sum'))
print(df)
yields
a b c d e
0 1 1 q z 12
1 2 2 q z 12
2 3 3 q z 12
3 4 4 q o 8
4 5 5 w o 22
5 6 6 w o 22
Original answer:
The error message:
TypeError: cannot concatenate a non-NDFrame object
suggests that in order to concatenate, the foo_function should return an NDFrame (such as a Series or DataFrame). If you return a Series, then:
In [99]: df.groupby(['c', 'd']).transform(lambda x: pd.Series(np.sum(x['a']+x['b'])))
Out[99]:
a b
0 12 12
1 12 12
2 12 12
3 8 8
4 22 22
5 22 22
A:
The way I read the question, you want to be able to do something arbitrary with both the individual values from both columns. You just need to make sure to return a dataframe of the same size as you get passed in. I think the best way is to just make a new column, like this:
df = pd.DataFrame({'a':[1,2,3,4,5,6],
'b':[1,2,3,4,5,6],
'c':['q', 'q', 'q', 'q', 'w', 'w'],
'd':['z','z','z','o','o','o']})
df['e']=0
def f(x):
y=(x['a']+x['b'])/sum(x['b'])
return pd.DataFrame({'e':y,'a':x['a'],'b':x['b']})
df.groupby(['c','d']).transform(f)
:
a b e
0 1 1 0.333333
1 2 2 0.666667
2 3 3 1.000000
3 4 4 2.000000
4 5 5 0.909091
5 6 6 1.090909
If you have a very complicated dataframe, you can pick your columns (e.g. df.groupby(['c'])['a','b','e'].transform(f))
This sure looks very inelegant to me, but it's still much faster than apply on large datasets.
Another alternative is to use set_index to capture all the columns you need and then pass just one column to transform.
A:
The following workaround allows you to transform with similar transform syntax, using .groupby and .apply instead.
So you don't have break multi-column computation apart, hence fragmenting the processing steps.
df = pd.DataFrame({'a':[1,2,3,4,5,6],
'b':[1,2,3,4,5,6],
'c':['q', 'q', 'q', 'q', 'w', 'w'],
'd':['z','z','z','o','o','o']})
group = ['c', 'd']
df['result'] = df.groupby(group)\
.apply(
# your typical transform function here
lambda df: (df.a + df.b)/df.b.sum()
).reset_index(group, drop=True)
df
a b c d result
0 1 1 q z 0.333333
1 2 2 q z 0.666667
2 3 3 q z 1.000000
3 4 4 q o 2.000000
4 5 5 w o 0.909091
5 6 6 w o 1.090909
|
How to use groupby transform across multiple columns
|
I have a big dataframe, and I'm grouping by one to n columns, and want to apply a function on these groups across two columns (e.g. foo and bar).
Here's an example dataframe:
foo_function = lambda x: np.sum(x.a+x.b)
df = pd.DataFrame({'a':[1,2,3,4,5,6],
'b':[1,2,3,4,5,6],
'c':['q', 'q', 'q', 'q', 'w', 'w'],
'd':['z','z','z','o','o','o']})
# works with apply, but I want transform:
df.groupby(['c', 'd'])[['a','b']].apply(foo_function)
# transform doesn't work!
df.groupby(['c', 'd'])[['a','b']].transform(foo_function)
TypeError: cannot concatenate a non-NDFrame object
But transform apparently isn't able to combine multiple columns together because it looks at each column separately (unlike apply). What is the next best alternative in terms of speed / elegance? e.g. I could use apply and then create df['new_col'] by using pd.match, but that would necessitate matching over sometimes multiple groupby columns (col1 and col2) which seems really hacky / would take a fair amount of code.
--> Is there a function that is like groupby().transform that can use functions that work over multiple columns? If this doesn't exist, what's the best hack?
|
[
"Circa Pandas version 0.18, it appears the original answer (below) no longer works.\nInstead, if you need to do a groupby computation across multiple columns, do the multi-column computation first, and then the groupby:\ndf = pd.DataFrame({'a':[1,2,3,4,5,6],\n 'b':[1,2,3,4,5,6],\n 'c':['q', 'q', 'q', 'q', 'w', 'w'], \n 'd':['z','z','z','o','o','o']})\ndf['e'] = df['a'] + df['b']\ndf['e'] = (df.groupby(['c', 'd'])['e'].transform('sum'))\nprint(df)\n\nyields\n a b c d e\n0 1 1 q z 12\n1 2 2 q z 12\n2 3 3 q z 12\n3 4 4 q o 8\n4 5 5 w o 22\n5 6 6 w o 22\n\n\nOriginal answer:\nThe error message:\nTypeError: cannot concatenate a non-NDFrame object\n\nsuggests that in order to concatenate, the foo_function should return an NDFrame (such as a Series or DataFrame). If you return a Series, then:\nIn [99]: df.groupby(['c', 'd']).transform(lambda x: pd.Series(np.sum(x['a']+x['b'])))\nOut[99]: \n a b\n0 12 12\n1 12 12\n2 12 12\n3 8 8\n4 22 22\n5 22 22\n\n",
"The way I read the question, you want to be able to do something arbitrary with both the individual values from both columns. You just need to make sure to return a dataframe of the same size as you get passed in. I think the best way is to just make a new column, like this:\ndf = pd.DataFrame({'a':[1,2,3,4,5,6],\n 'b':[1,2,3,4,5,6],\n 'c':['q', 'q', 'q', 'q', 'w', 'w'], \n 'd':['z','z','z','o','o','o']})\ndf['e']=0\n\ndef f(x):\n y=(x['a']+x['b'])/sum(x['b'])\n return pd.DataFrame({'e':y,'a':x['a'],'b':x['b']})\n\ndf.groupby(['c','d']).transform(f)\n\n:\n a b e\n0 1 1 0.333333\n1 2 2 0.666667\n2 3 3 1.000000\n3 4 4 2.000000\n4 5 5 0.909091\n5 6 6 1.090909\n\nIf you have a very complicated dataframe, you can pick your columns (e.g. df.groupby(['c'])['a','b','e'].transform(f))\nThis sure looks very inelegant to me, but it's still much faster than apply on large datasets.\nAnother alternative is to use set_index to capture all the columns you need and then pass just one column to transform.\n",
"The following workaround allows you to transform with similar transform syntax, using .groupby and .apply instead.\nSo you don't have break multi-column computation apart, hence fragmenting the processing steps.\ndf = pd.DataFrame({'a':[1,2,3,4,5,6],\n 'b':[1,2,3,4,5,6],\n 'c':['q', 'q', 'q', 'q', 'w', 'w'], \n 'd':['z','z','z','o','o','o']})\n\ngroup = ['c', 'd']\ndf['result'] = df.groupby(group)\\\n .apply(\n # your typical transform function here\n lambda df: (df.a + df.b)/df.b.sum()\n ).reset_index(group, drop=True)\n\ndf\n\n a b c d result\n0 1 1 q z 0.333333\n1 2 2 q z 0.666667\n2 3 3 q z 1.000000\n3 4 4 q o 2.000000\n4 5 5 w o 0.909091\n5 6 6 w o 1.090909\n\n"
] |
[
22,
2,
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0034099684_pandas_python.txt
|
Q:
How do I return an output for lambda expression to be the actual date in string format
my_date = input('Please enter your start date with format year/month/day: ')
print(f'You entered {my_date}')
split_my_date = my_date.split("/")
a = int(split_my_date[0]) # Year
b = int(split_my_date[1]) # Month
c = int(split_my_date[2]) # Day
s_my_date = str(lambda r_s_my_date : date(a,b,c) + timedelta(days=100))
#e_my_date = str(lambda r_e_my_date : date(a,b,c) - timedelta(days=100))
print(s_my_date)
type(s_my_date)
Hi, I'm a noob actually. What I'm trying to accomplish is to print s_my_date and output my_date + 100 days. For example if I input "2022/3/1" as my_date, its output will be s_my_date = 2022/3/1 plus 100 days but I need this output to be a string. Unfortunately whenever I print(s_my_date) it just returns
<function <lambda> at 0x7f66f2a12790>
I also tried to read some comments but can't really wrap my head around it yet so taking my chances to post my actual work. Thank you!
A:
I think what you are trying to do is to pass the year, month and date as parameters to your lambda function and return the date + 100 days.
In that case, it should be like this,
s_my_date = lambda a, b, c : str(date(a,b,c) + timedelta(days=100))
a, b and c are your parameters, which will be used in the function.
What comes after the colon is what is going to be returned by your function. So, you need to convert your parameters to a date: date(a,b,c), add the 100 days: date(a,b,c) + timedelta(days=100) and then convert it to a string: str(date(a,b,c) + timedelta(days=100)).
This does not make sense either because it's like we are trying to convert the function itself into a string,
str(lambda a, b, c : date(a,b,c) + timedelta(days=100))
I am not entirely sure what r_s_my_date is, but maybe you were trying to name your function?
Lambda functions are anonymous functions and they will not be named.
Now, this function is stored in the variable s_my_date. So, now you have to call it,
print(s_my_date(a, b, c))
Here, you are passing in your variables which are also called a, b and c.
You can learn more about anonymous (lambda) functions here,
https://www.w3schools.com/python/python_lambda.asp
|
How do I return an output for lambda expression to be the actual date in string format
|
my_date = input('Please enter your start date with format year/month/day: ')
print(f'You entered {my_date}')
split_my_date = my_date.split("/")
a = int(split_my_date[0]) # Year
b = int(split_my_date[1]) # Month
c = int(split_my_date[2]) # Day
s_my_date = str(lambda r_s_my_date : date(a,b,c) + timedelta(days=100))
#e_my_date = str(lambda r_e_my_date : date(a,b,c) - timedelta(days=100))
print(s_my_date)
type(s_my_date)
Hi, I'm a noob actually. What I'm trying to accomplish is to print s_my_date and output my_date + 100 days. For example if I input "2022/3/1" as my_date, its output will be s_my_date = 2022/3/1 plus 100 days but I need this output to be a string. Unfortunately whenever I print(s_my_date) it just returns
<function <lambda> at 0x7f66f2a12790>
I also tried to read some comments but can't really wrap my head around it yet so taking my chances to post my actual work. Thank you!
|
[
"I think what you are trying to do is to pass the year, month and date as parameters to your lambda function and return the date + 100 days.\nIn that case, it should be like this,\ns_my_date = lambda a, b, c : str(date(a,b,c) + timedelta(days=100))\n\na, b and c are your parameters, which will be used in the function.\nWhat comes after the colon is what is going to be returned by your function. So, you need to convert your parameters to a date: date(a,b,c), add the 100 days: date(a,b,c) + timedelta(days=100) and then convert it to a string: str(date(a,b,c) + timedelta(days=100)).\nThis does not make sense either because it's like we are trying to convert the function itself into a string,\nstr(lambda a, b, c : date(a,b,c) + timedelta(days=100))\nI am not entirely sure what r_s_my_date is, but maybe you were trying to name your function?\nLambda functions are anonymous functions and they will not be named.\nNow, this function is stored in the variable s_my_date. So, now you have to call it,\nprint(s_my_date(a, b, c))\n\nHere, you are passing in your variables which are also called a, b and c.\nYou can learn more about anonymous (lambda) functions here,\nhttps://www.w3schools.com/python/python_lambda.asp\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074555656_python.txt
|
Q:
Python - Sum and count specific values with pandas pivot_table
I have a pandas dataframe like
ACCOUNT AMOUNT STATUS
1 -2 1
2 2 0
2 -1 0
1 2 1
1 2 1
This is would like to get converted into an dataframe like
ACCOUNT STATUS COUNT>0 COUNT<0 AMOUNT>0 AMOUNT<0
1 1 2 1 4 2
2 0 1 1 2 1
So basically split if AMOUNT is > or < than 0 and then count and sum the result. I currently have the following, but can't get the split AMOUNT right.
Data = pd.pivot_table(trans, values =['Status', 'AMOUNT'], index = ['ACCOUNT'], aggfunc = {'Status':np.mean, 'AMOUNT': [np.sum, 'count'] } )
A:
Using np.sign
This function returns an array of -1/0/1 depending on the signs of the values. Essentially giving me a convenient way of identifying things less, equal, or greater than zero. I use this in the group by statement and use agg to count the number of values, and sum to produce the total. After grouping by 3 vectors, I'll end up with a 3-layer multi index. I unstack in order to take the last layer and pivot it to be included with the columns. This last layer is the sign layer.
df.groupby(
['ACCOUNT', 'STATUS', np.sign(df.AMOUNT)]
).AMOUNT.agg(['count', 'sum']).unstack()
count sum
AMOUNT -1 1 -1 1
ACCOUNT STATUS
1 1 1 2 -2 4
2 0 1 1 -1 2
Extra effort to mimic OP's expected output:
Here, I do the same things. But I add several steps that rename columns, combine layers, and take absolute values.
df.groupby(
['ACCOUNT', 'STATUS', np.sign(df.AMOUNT).map({-1: '<0', 0: '=0', 1: '>0'})]
).AMOUNT.agg(['count', 'sum']).rename(
columns=dict(count='COUNT', sum='AMOUNT')
).unstack().abs().pipe(
lambda d: d.set_axis(d.columns.map('{0[0]}{0[1]}'.format), 1, inplace=False)
)
COUNT<0 COUNT>0 AMOUNT<0 AMOUNT>0
ACCOUNT STATUS
1 1 1 2 2 4
2 0 1 1 1 2
A:
This is try to fix your pivot_table
pd.pivot_table(df.assign(new=df.AMOUNT.gt(0)), values =['AMOUNT'], index = ['ACCOUNT','STATUS'],columns='new',aggfunc = { 'AMOUNT': [np.sum, 'count'] } ).abs()
Out[431]:
AMOUNT
count sum
new False True False True
ACCOUNT STATUS
1 1 1 2 2 4
2 0 1 1 1 2
A:
You can do this better with groupby and unstack. I have also created a few extra columns to make things clearer.
data = pd.DataFrame(
[[1, -2, 1],
[2, 2, 0],
[2, -1, 0],
[1, 2, 1],
[1, 2, 1]
],
columns = ['ACCOUNT', 'AMOUNT', 'STATUS']
)
data['AMOUNT_POSITIVE'] = data['AMOUNT'] > 0
data['AMOUNT_ABSOLUTE'] = data['AMOUNT'].abs()
result = (data
.groupby(["ACCOUNT", "STATUS", "AMOUNT_POSITIVE"])['AMOUNT_ABSOLUTE']
.agg(['count', 'sum'])
.unstack("AMOUNT_POSITIVE")
)
print(result)
And you get your table:
count sum
AMOUNT_POSITIVE False True False True
ACCOUNT STATUS
1 1 1 2 2 4
2 0 1 1 1 2
|
Python - Sum and count specific values with pandas pivot_table
|
I have a pandas dataframe like
ACCOUNT AMOUNT STATUS
1 -2 1
2 2 0
2 -1 0
1 2 1
1 2 1
This is would like to get converted into an dataframe like
ACCOUNT STATUS COUNT>0 COUNT<0 AMOUNT>0 AMOUNT<0
1 1 2 1 4 2
2 0 1 1 2 1
So basically split if AMOUNT is > or < than 0 and then count and sum the result. I currently have the following, but can't get the split AMOUNT right.
Data = pd.pivot_table(trans, values =['Status', 'AMOUNT'], index = ['ACCOUNT'], aggfunc = {'Status':np.mean, 'AMOUNT': [np.sum, 'count'] } )
|
[
"Using np.sign\nThis function returns an array of -1/0/1 depending on the signs of the values. Essentially giving me a convenient way of identifying things less, equal, or greater than zero. I use this in the group by statement and use agg to count the number of values, and sum to produce the total. After grouping by 3 vectors, I'll end up with a 3-layer multi index. I unstack in order to take the last layer and pivot it to be included with the columns. This last layer is the sign layer.\ndf.groupby(\n ['ACCOUNT', 'STATUS', np.sign(df.AMOUNT)]\n).AMOUNT.agg(['count', 'sum']).unstack()\n\n count sum \nAMOUNT -1 1 -1 1\nACCOUNT STATUS \n1 1 1 2 -2 4\n2 0 1 1 -1 2\n\n\nExtra effort to mimic OP's expected output:\nHere, I do the same things. But I add several steps that rename columns, combine layers, and take absolute values.\ndf.groupby(\n ['ACCOUNT', 'STATUS', np.sign(df.AMOUNT).map({-1: '<0', 0: '=0', 1: '>0'})]\n).AMOUNT.agg(['count', 'sum']).rename(\n columns=dict(count='COUNT', sum='AMOUNT')\n).unstack().abs().pipe(\n lambda d: d.set_axis(d.columns.map('{0[0]}{0[1]}'.format), 1, inplace=False)\n)\n\n COUNT<0 COUNT>0 AMOUNT<0 AMOUNT>0\nACCOUNT STATUS \n1 1 1 2 2 4\n2 0 1 1 1 2\n\n",
"This is try to fix your pivot_table \npd.pivot_table(df.assign(new=df.AMOUNT.gt(0)), values =['AMOUNT'], index = ['ACCOUNT','STATUS'],columns='new',aggfunc = { 'AMOUNT': [np.sum, 'count'] } ).abs()\nOut[431]: \n AMOUNT \n count sum \nnew False True False True \nACCOUNT STATUS \n1 1 1 2 2 4\n2 0 1 1 1 2\n\n",
"You can do this better with groupby and unstack. I have also created a few extra columns to make things clearer.\ndata = pd.DataFrame(\n [[1, -2, 1],\n [2, 2, 0],\n [2, -1, 0],\n [1, 2, 1],\n [1, 2, 1] \n ],\n columns = ['ACCOUNT', 'AMOUNT', 'STATUS']\n)\n\ndata['AMOUNT_POSITIVE'] = data['AMOUNT'] > 0\ndata['AMOUNT_ABSOLUTE'] = data['AMOUNT'].abs()\n\nresult = (data\n .groupby([\"ACCOUNT\", \"STATUS\", \"AMOUNT_POSITIVE\"])['AMOUNT_ABSOLUTE']\n .agg(['count', 'sum'])\n .unstack(\"AMOUNT_POSITIVE\")\n )\n\nprint(result)\n\nAnd you get your table:\n count sum \nAMOUNT_POSITIVE False True False True \nACCOUNT STATUS \n1 1 1 2 2 4\n2 0 1 1 1 2\n\n"
] |
[
3,
1,
0
] |
[
"The next example aggregates by taking the mean across multiple columns.\n\ntable = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],\n aggfunc={'D': np.mean,\n 'E': np.mean})\ntable\n D E\nA C\nbar large 5.500000 7.500000\n small 5.500000 8.500000\nfoo large 2.000000 4.500000\n small 2.333333 4.333333\n\n\"\"\"P.S this is from official documentation\"\"\"\n"
] |
[
-1
] |
[
"pandas",
"python"
] |
stackoverflow_0049154895_pandas_python.txt
|
Q:
python csv reader delete special character in uuid
Got a large csv file like
fab47e7c-05df-4315-b23f-de2cfc8b180f,Lindie,Lilybelle,Lindie.Lilybelle@yopmail.coma
959d21f-e131-473c-ae44-cfea24dbaf3f,Vere,Ax,Vere.Ax@yopmail.com
dd20bea2-f3a8-4283-82e2-501efb846fa8,Lacie,Byrne,Lacie.Byrne@yopmail.com
and some of uuids imported with typo like
#@3b751941-dca2-4224-b453-d81c53cc4c6e%$,Ivett,Urias,Ivett.Urias@yopmail.com
im trying to replace that symbols in uuid but not really understand how to do it right.
my code is like
def read_csv(path, string):
with open(path, 'r') as data:
reader = csv.DictReader(data)
for row in reader:
string.match(row['id'])
where the string is a regex for uuid
string = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', re.I)
A:
Your regex is wrong, it's looking for regexes that don't have any characters after them, because of the "$" symbol at the end. Use this:
[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}
You can test it here: https://regex101.com/r/TJXCaR/1
|
python csv reader delete special character in uuid
|
Got a large csv file like
fab47e7c-05df-4315-b23f-de2cfc8b180f,Lindie,Lilybelle,Lindie.Lilybelle@yopmail.coma
959d21f-e131-473c-ae44-cfea24dbaf3f,Vere,Ax,Vere.Ax@yopmail.com
dd20bea2-f3a8-4283-82e2-501efb846fa8,Lacie,Byrne,Lacie.Byrne@yopmail.com
and some of uuids imported with typo like
#@3b751941-dca2-4224-b453-d81c53cc4c6e%$,Ivett,Urias,Ivett.Urias@yopmail.com
im trying to replace that symbols in uuid but not really understand how to do it right.
my code is like
def read_csv(path, string):
with open(path, 'r') as data:
reader = csv.DictReader(data)
for row in reader:
string.match(row['id'])
where the string is a regex for uuid
string = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', re.I)
|
[
"Your regex is wrong, it's looking for regexes that don't have any characters after them, because of the \"$\" symbol at the end. Use this:\n[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\nYou can test it here: https://regex101.com/r/TJXCaR/1\n"
] |
[
0
] |
[] |
[] |
[
"csv",
"python",
"uuid"
] |
stackoverflow_0074555560_csv_python_uuid.txt
|
Q:
Change Specific Word in Pandas
I have a dataframe
city = pd.DataFrame({'id': [1,2,3,4],
'city': ['NRTH CAROLINA','NEW WST AMSTERDAM','EAST TOKYO','LONDON STH']})
How can I change NRTH to NORTH, WST to WEST, and STH to SOUTH, so the output will be like this
id city
1 NORTH CAROLINA
2 NEW WEST AMSTERDAM
3 EAST TOKYO
4 LONDON STH
A:
Let's define a replace dictionary first then use Series.replace(regex=True) to replace by the word boundary of the dictionary key.
import re
d = {
'NRTH': 'NORTH',
'WST': 'WEST',
'STH': 'SOUTH'
}
df['city'] = df['city'].replace({rf"\b{re.escape(k)}\b":v for k, v in d.items()}, regex=True)
print(df)
id city
0 1 NORTH CAROLINA
1 2 NEW WEST AMSTERDAM
2 3 EAST TOKYO
3 4 LONDON SOUTH
A:
Hello, Arthur!
I have defined mapping_dict where you can define any other words that you want to change.
For changing them I made a separate function for mapping city names.
import pandas as pd
city = pd.DataFrame({'id': [1,2,3,4],
'city': ['NRTH CAROLINA','NEW WST AMSTERDAM','EAST TOKYO','LONDON STH']})
mapping_dict = {'NRTH':'NORTH','WST':'WEST','STH':'SOUTH'}
def mapping_words(city_name):
updated_name = ""
for word in city_name.split():
if word in mapping:
updated_name += mapping[word]+" "
else:
updated_name += word+" "
return updated_name.strip()
city['city'] = city['city'].apply(lambda x: mapping_words(x))
Another optimized way
mapping_dict = {'NRTH':'NORTH','WST':'WEST','STH':'SOUTH'}
city['city'] = city['city'].replace(mapping_dict,regex=True)
I hope this may help you.
Thanks!
|
Change Specific Word in Pandas
|
I have a dataframe
city = pd.DataFrame({'id': [1,2,3,4],
'city': ['NRTH CAROLINA','NEW WST AMSTERDAM','EAST TOKYO','LONDON STH']})
How can I change NRTH to NORTH, WST to WEST, and STH to SOUTH, so the output will be like this
id city
1 NORTH CAROLINA
2 NEW WEST AMSTERDAM
3 EAST TOKYO
4 LONDON STH
|
[
"Let's define a replace dictionary first then use Series.replace(regex=True) to replace by the word boundary of the dictionary key.\nimport re\n\nd = {\n 'NRTH': 'NORTH',\n 'WST': 'WEST',\n 'STH': 'SOUTH'\n}\n\n\ndf['city'] = df['city'].replace({rf\"\\b{re.escape(k)}\\b\":v for k, v in d.items()}, regex=True)\n\nprint(df)\n\n id city\n0 1 NORTH CAROLINA\n1 2 NEW WEST AMSTERDAM\n2 3 EAST TOKYO\n3 4 LONDON SOUTH\n\n",
"\nHello, Arthur!\nI have defined mapping_dict where you can define any other words that you want to change.\nFor changing them I made a separate function for mapping city names.\nimport pandas as pd\ncity = pd.DataFrame({'id': [1,2,3,4],\n 'city': ['NRTH CAROLINA','NEW WST AMSTERDAM','EAST TOKYO','LONDON STH']})\nmapping_dict = {'NRTH':'NORTH','WST':'WEST','STH':'SOUTH'}\ndef mapping_words(city_name):\n updated_name = \"\"\n for word in city_name.split():\n if word in mapping:\n updated_name += mapping[word]+\" \"\n else:\n updated_name += word+\" \"\n return updated_name.strip()\n\ncity['city'] = city['city'].apply(lambda x: mapping_words(x))\n\nAnother optimized way\nmapping_dict = {'NRTH':'NORTH','WST':'WEST','STH':'SOUTH'}\ncity['city'] = city['city'].replace(mapping_dict,regex=True)\n\nI hope this may help you.\nThanks!\n"
] |
[
3,
3
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074555652_dataframe_pandas_python.txt
|
Q:
I cannot get my await to work in the new py update
I am having some trouble with my discord bot that we use in a server for a group of friends to listen to youtube music. I will include the error screenshot and sources below. Thanks for looking.
Error from console(replit)
main.py:
import discord
from discord.ext import commands
import music
from webserver import keep_alive
import os
cogs = [music]
client = commands.Bot(command_prefix='!', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup(client)
keep_alive()
TOKEN = os.environ.get("DISCORD_BOT_SECRET");
client.run(TOKEN)
music.py:
import discord
from discord.ext import commands
import random
import asyncio
import itertools
import sys
import traceback
from async_timeout import timeout
from functools import partial
import youtube_dl
from youtube_dl import YoutubeDL
# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''
ytdlopts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # ipv6 addresses cause issues sometimes
}
ffmpegopts = {
'before_options': '-nostdin',
'options': '-vn'
}
ytdl = YoutubeDL(ytdlopts)
class VoiceConnectionError(commands.CommandError):
"""Custom Exception class for connection errors."""
class InvalidVoiceChannel(VoiceConnectionError):
"""Exception for cases of invalid Voice Channels."""
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, requester):
super().__init__(source)
self.requester = requester
self.title = data.get('title')
self.web_url = data.get('webpage_url')
self.duration = data.get('duration')
# YTDL info dicts (data) have other useful information you might want
# https://github.com/rg3/youtube-dl/blob/master/README.md
def __getitem__(self, item: str):
"""Allows us to access attributes similar to a dict.
This is only useful when you are NOT downloading.
"""
return self.__getattribute__(item)
@classmethod
async def create_source(cls, ctx, search: str, *, loop, download=False):
loop = loop or asyncio.get_event_loop()
to_run = partial(ytdl.extract_info, url=search, download=download)
data = await loop.run_in_executor(None, to_run)
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
embed = discord.Embed(title="", description=f"Queued [{data['title']}]({data['webpage_url']}) [{ctx.author.mention}]", color=discord.Color.green())
await ctx.send(embed=embed)
if download:
source = ytdl.prepare_filename(data)
else:
return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}
return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)
@classmethod
async def regather_stream(cls, data, *, loop):
"""Used for preparing a stream, instead of downloading.
Since Youtube Streaming links expire."""
loop = loop or asyncio.get_event_loop()
requester = data['requester']
to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False)
data = await loop.run_in_executor(None, to_run)
return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester)
class MusicPlayer:
"""A class which is assigned to each guild using the bot for Music.
This class implements a queue and loop, which allows for different guilds to listen to different playlists
simultaneously.
When the bot disconnects from the Voice it's instance will be destroyed.
"""
__slots__ = ('bot', '_guild', '_channel', '_cog', 'queue', 'next', 'current', 'np', 'volume')
def __init__(self, ctx):
self.bot = ctx.bot
self._guild = ctx.guild
self._channel = ctx.channel
self._cog = ctx.cog
self.queue = asyncio.Queue()
self.next = asyncio.Event()
self.np = None # Now playing message
self.volume = .5
self.current = None
ctx.bot.loop.create_task(self.player_loop())
async def player_loop(self):
"""Our main player loop."""
await self.bot.wait_until_ready()
while not self.bot.is_closed():
self.next.clear()
try:
# Wait for the next song. If we timeout cancel the player and disconnect...
async with timeout(300): # 5 minutes...
source = await self.queue.get()
except asyncio.TimeoutError:
return self.destroy(self._guild)
if not isinstance(source, YTDLSource):
# Source was probably a stream (not downloaded)
# So we should regather to prevent stream expiration
try:
source = await YTDLSource.regather_stream(source, loop=self.bot.loop)
except Exception as e:
await self._channel.send(f'There was an error processing your song.\n'
f'```css\n[{e}]\n```')
continue
source.volume = self.volume
self.current = source
self._guild.voice_client.play(source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set))
embed = discord.Embed(title="Now playing", description=f"[{source.title}]({source.web_url}) [{source.requester.mention}]", color=discord.Color.green())
self.np = await self._channel.send(embed=embed)
await self.next.wait()
# Make sure the FFmpeg process is cleaned up.
source.cleanup()
self.current = None
def destroy(self, guild):
"""Disconnect and cleanup the player."""
return self.bot.loop.create_task(self._cog.cleanup(guild))
class Music(commands.Cog):
"""Music related commands."""
__slots__ = ('bot', 'players')
def __init__(self, bot):
self.bot = bot
self.players = {}
async def cleanup(self, guild):
try:
await guild.voice_client.disconnect()
except AttributeError:
pass
try:
del self.players[guild.id]
except KeyError:
pass
async def __local_check(self, ctx):
"""A local check which applies to all commands in this cog."""
if not ctx.guild:
raise commands.NoPrivateMessage
return True
async def __error(self, ctx, error):
"""A local error handler for all errors arising from commands in this cog."""
if isinstance(error, commands.NoPrivateMessage):
try:
return await ctx.send('This command can not be used in Private Messages.')
except discord.HTTPException:
pass
elif isinstance(error, InvalidVoiceChannel):
await ctx.send('Error connecting to Voice Channel. '
'Please make sure you are in a valid channel or provide me with one')
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
def get_player(self, ctx):
"""Retrieve the guild player, or generate one."""
try:
player = self.players[ctx.guild.id]
except KeyError:
player = MusicPlayer(ctx)
self.players[ctx.guild.id] = player
return player
@commands.command(name='join', aliases=['connect', 'j'], description="connects to voice")
async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
"""Connect to voice.
Parameters
------------
channel: discord.VoiceChannel [Optional]
The channel to connect to. If a channel is not specified, an attempt to join the voice channel you are in
will be made.
This command also handles moving the bot to different channels.
"""
if not channel:
try:
channel = ctx.author.voice.channel
except AttributeError:
embed = discord.Embed(title="", description="No channel to join. Please call `,join` from a voice channel.", color=discord.Color.green())
await ctx.send(embed=embed)
raise InvalidVoiceChannel('No channel to join. Please either specify a valid channel or join one.')
vc = ctx.voice_client
if vc:
if vc.channel.id == channel.id:
return
try:
await vc.move_to(channel)
except asyncio.TimeoutError:
raise VoiceConnectionError(f'Moving to channel: <{channel}> timed out.')
else:
try:
await channel.connect()
except asyncio.TimeoutError:
raise VoiceConnectionError(f'Connecting to channel: <{channel}> timed out.')
if (random.randint(0, 1) == 0):
await ctx.message.add_reaction('')
await ctx.send(f'**Joined `{channel}`**')
@commands.command(name='play', aliases=['sing','p','P','Play'], description="streams music")
async def play_(self, ctx, *, search: str):
"""Request a song and add it to the queue.
This command attempts to join a valid voice channel if the bot is not already in one.
Uses YTDL to automatically search and retrieve a song.
Parameters
------------
search: str [Required]
The song to search and retrieve using YTDL. This could be a simple search, an ID or URL.
"""
await ctx.trigger_typing()
vc = ctx.voice_client
if not vc:
await ctx.invoke(self.connect_)
player = self.get_player(ctx)
# If download is False, source will be a dict which will be used later to regather the stream.
# If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)
await player.queue.put(source)
@commands.command(name='pause', aliases=['Pause'], description="pauses music")
async def pause_(self, ctx):
"""Pause the currently playing song."""
vc = ctx.voice_client
if not vc or not vc.is_playing():
embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())
return await ctx.send(embed=embed)
elif vc.is_paused():
return
vc.pause()
await ctx.send("Paused ⏸️")
@commands.command(name='resume', aliases=['Resume'], description="resumes music")
async def resume_(self, ctx):
"""Resume the currently paused song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
elif not vc.is_paused():
return
vc.resume()
await ctx.send("Resuming ⏯️")
@commands.command(name='skip', aliases=['Skip','s','S'], description="skips to next song in queue")
async def skip_(self, ctx):
"""Skip the song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
if vc.is_paused():
pass
elif not vc.is_playing():
return
vc.stop()
@commands.command(name='remove', aliases=['rm', 'rem'], description="removes specified song from queue")
async def remove_(self, ctx, pos : int=None):
"""Removes specified song from queue"""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
if pos == None:
player.queue._queue.pop()
else:
try:
s = player.queue._queue[pos-1]
del player.queue._queue[pos-1]
embed = discord.Embed(title="", description=f"Removed [{s['title']}]({s['webpage_url']}) [{s['requester'].mention}]", color=discord.Color.green())
await ctx.send(embed=embed)
except:
embed = discord.Embed(title="", description=f'Could not find a track for "{pos}"', color=discord.Color.green())
await ctx.send(embed=embed)
@commands.command(name='clear', aliases=['clr', 'cl', 'cr'], description="clears entire queue")
async def clear_(self, ctx):
"""Deletes entire queue of upcoming songs."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
player.queue._queue.clear()
await ctx.send(' **Cleared**')
@commands.command(name='queue', aliases=['q', 'playlist', 'que'], description="shows the queue")
async def queue_info(self, ctx):
"""Retrieve a basic queue of upcoming songs."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
if player.queue.empty():
embed = discord.Embed(title="", description="queue is empty", color=discord.Color.green())
return await ctx.send(embed=embed)
seconds = vc.source.duration % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour > 0:
duration = "%dh %02dm %02ds" % (hour, minutes, seconds)
else:
duration = "%02dm %02ds" % (minutes, seconds)
# Grabs the songs in the queue...
upcoming = list(itertools.islice(player.queue._queue, 0, int(len(player.queue._queue))))
fmt = '\n'.join(f"`{(upcoming.index(_)) + 1}.` [{_['title']}]({_['webpage_url']}) | ` {duration} Requested by: {_['requester']}`\n" for _ in upcoming)
fmt = f"\n__Now Playing__:\n[{vc.source.title}]({vc.source.web_url}) | ` {duration} Requested by: {vc.source.requester}`\n\n__Up Next:__\n" + fmt + f"\n**{len(upcoming)} songs in queue**"
embed = discord.Embed(title=f'Queue for {ctx.guild.name}', description=fmt, color=discord.Color.green())
embed.set_footer(text=f"{ctx.author.display_name}", icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
@commands.command(name='np', aliases=['song', 'current', 'currentsong', 'playing'], description="shows the current playing song")
async def now_playing_(self, ctx):
"""Display information about the currently playing song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
if not player.current:
embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())
return await ctx.send(embed=embed)
seconds = vc.source.duration % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour > 0:
duration = "%dh %02dm %02ds" % (hour, minutes, seconds)
else:
duration = "%02dm %02ds" % (minutes, seconds)
embed = discord.Embed(title="", description=f"[{vc.source.title}]({vc.source.web_url}) [{vc.source.requester.mention}] | `{duration}`", color=discord.Color.green())
embed.set_author(icon_url=self.bot.user.avatar_url, name=f"Now Playing ")
await ctx.send(embed=embed)
@commands.command(name='volume', aliases=['vol', 'v'], description="changes Kermit's volume")
async def change_volume(self, ctx, *, vol: float=None):
"""Change the player volume.
Parameters
------------
volume: float or int [Required]
The volume to set the player to in percentage. This must be between 1 and 100.
"""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I am not currently connected to voice", color=discord.Color.green())
return await ctx.send(embed=embed)
if not vol:
embed = discord.Embed(title="", description=f" **{(vc.source.volume)*100}%**", color=discord.Color.green())
return await ctx.send(embed=embed)
if not 0 < vol < 101:
embed = discord.Embed(title="", description="Please enter a value between 1 and 100", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
if vc.source:
vc.source.volume = vol / 100
player.volume = vol / 100
embed = discord.Embed(title="", description=f'**`{ctx.author}`** set the volume to **{vol}%**', color=discord.Color.green())
await ctx.send(embed=embed)
@commands.command(name='leave', aliases=["stop", "dc", "disconnect", "bye"], description="stops music and disconnects from voice")
async def leave_(self, ctx):
"""Stop the currently playing song and destroy the player.
!Warning!
This will destroy the player assigned to your guild, also deleting any queued songs and settings.
"""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
if (random.randint(0, 1) == 0):
await ctx.message.add_reaction('')
await ctx.send('**Successfully disconnected**')
await self.cleanup(ctx.guild)
def setup(bot):
await bot.add_cog(Music(bot))
We tried awaiting the last line in the music.py file per the code doc on discord dev, but it appears something else is going on?
A:
You can not use await statement outside async def ....
You need to do like so:
async def setup(bot):
await bot.add_cog(Music(bot))
Then at the entry point of your program you should call something like asyncio.run(setup())
Please refer to official documentation, it has some handy examples: https://docs.python.org/3/library/asyncio-task.html
|
I cannot get my await to work in the new py update
|
I am having some trouble with my discord bot that we use in a server for a group of friends to listen to youtube music. I will include the error screenshot and sources below. Thanks for looking.
Error from console(replit)
main.py:
import discord
from discord.ext import commands
import music
from webserver import keep_alive
import os
cogs = [music]
client = commands.Bot(command_prefix='!', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup(client)
keep_alive()
TOKEN = os.environ.get("DISCORD_BOT_SECRET");
client.run(TOKEN)
music.py:
import discord
from discord.ext import commands
import random
import asyncio
import itertools
import sys
import traceback
from async_timeout import timeout
from functools import partial
import youtube_dl
from youtube_dl import YoutubeDL
# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''
ytdlopts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # ipv6 addresses cause issues sometimes
}
ffmpegopts = {
'before_options': '-nostdin',
'options': '-vn'
}
ytdl = YoutubeDL(ytdlopts)
class VoiceConnectionError(commands.CommandError):
"""Custom Exception class for connection errors."""
class InvalidVoiceChannel(VoiceConnectionError):
"""Exception for cases of invalid Voice Channels."""
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, requester):
super().__init__(source)
self.requester = requester
self.title = data.get('title')
self.web_url = data.get('webpage_url')
self.duration = data.get('duration')
# YTDL info dicts (data) have other useful information you might want
# https://github.com/rg3/youtube-dl/blob/master/README.md
def __getitem__(self, item: str):
"""Allows us to access attributes similar to a dict.
This is only useful when you are NOT downloading.
"""
return self.__getattribute__(item)
@classmethod
async def create_source(cls, ctx, search: str, *, loop, download=False):
loop = loop or asyncio.get_event_loop()
to_run = partial(ytdl.extract_info, url=search, download=download)
data = await loop.run_in_executor(None, to_run)
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
embed = discord.Embed(title="", description=f"Queued [{data['title']}]({data['webpage_url']}) [{ctx.author.mention}]", color=discord.Color.green())
await ctx.send(embed=embed)
if download:
source = ytdl.prepare_filename(data)
else:
return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}
return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)
@classmethod
async def regather_stream(cls, data, *, loop):
"""Used for preparing a stream, instead of downloading.
Since Youtube Streaming links expire."""
loop = loop or asyncio.get_event_loop()
requester = data['requester']
to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False)
data = await loop.run_in_executor(None, to_run)
return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester)
class MusicPlayer:
"""A class which is assigned to each guild using the bot for Music.
This class implements a queue and loop, which allows for different guilds to listen to different playlists
simultaneously.
When the bot disconnects from the Voice it's instance will be destroyed.
"""
__slots__ = ('bot', '_guild', '_channel', '_cog', 'queue', 'next', 'current', 'np', 'volume')
def __init__(self, ctx):
self.bot = ctx.bot
self._guild = ctx.guild
self._channel = ctx.channel
self._cog = ctx.cog
self.queue = asyncio.Queue()
self.next = asyncio.Event()
self.np = None # Now playing message
self.volume = .5
self.current = None
ctx.bot.loop.create_task(self.player_loop())
async def player_loop(self):
"""Our main player loop."""
await self.bot.wait_until_ready()
while not self.bot.is_closed():
self.next.clear()
try:
# Wait for the next song. If we timeout cancel the player and disconnect...
async with timeout(300): # 5 minutes...
source = await self.queue.get()
except asyncio.TimeoutError:
return self.destroy(self._guild)
if not isinstance(source, YTDLSource):
# Source was probably a stream (not downloaded)
# So we should regather to prevent stream expiration
try:
source = await YTDLSource.regather_stream(source, loop=self.bot.loop)
except Exception as e:
await self._channel.send(f'There was an error processing your song.\n'
f'```css\n[{e}]\n```')
continue
source.volume = self.volume
self.current = source
self._guild.voice_client.play(source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set))
embed = discord.Embed(title="Now playing", description=f"[{source.title}]({source.web_url}) [{source.requester.mention}]", color=discord.Color.green())
self.np = await self._channel.send(embed=embed)
await self.next.wait()
# Make sure the FFmpeg process is cleaned up.
source.cleanup()
self.current = None
def destroy(self, guild):
"""Disconnect and cleanup the player."""
return self.bot.loop.create_task(self._cog.cleanup(guild))
class Music(commands.Cog):
"""Music related commands."""
__slots__ = ('bot', 'players')
def __init__(self, bot):
self.bot = bot
self.players = {}
async def cleanup(self, guild):
try:
await guild.voice_client.disconnect()
except AttributeError:
pass
try:
del self.players[guild.id]
except KeyError:
pass
async def __local_check(self, ctx):
"""A local check which applies to all commands in this cog."""
if not ctx.guild:
raise commands.NoPrivateMessage
return True
async def __error(self, ctx, error):
"""A local error handler for all errors arising from commands in this cog."""
if isinstance(error, commands.NoPrivateMessage):
try:
return await ctx.send('This command can not be used in Private Messages.')
except discord.HTTPException:
pass
elif isinstance(error, InvalidVoiceChannel):
await ctx.send('Error connecting to Voice Channel. '
'Please make sure you are in a valid channel or provide me with one')
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
def get_player(self, ctx):
"""Retrieve the guild player, or generate one."""
try:
player = self.players[ctx.guild.id]
except KeyError:
player = MusicPlayer(ctx)
self.players[ctx.guild.id] = player
return player
@commands.command(name='join', aliases=['connect', 'j'], description="connects to voice")
async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
"""Connect to voice.
Parameters
------------
channel: discord.VoiceChannel [Optional]
The channel to connect to. If a channel is not specified, an attempt to join the voice channel you are in
will be made.
This command also handles moving the bot to different channels.
"""
if not channel:
try:
channel = ctx.author.voice.channel
except AttributeError:
embed = discord.Embed(title="", description="No channel to join. Please call `,join` from a voice channel.", color=discord.Color.green())
await ctx.send(embed=embed)
raise InvalidVoiceChannel('No channel to join. Please either specify a valid channel or join one.')
vc = ctx.voice_client
if vc:
if vc.channel.id == channel.id:
return
try:
await vc.move_to(channel)
except asyncio.TimeoutError:
raise VoiceConnectionError(f'Moving to channel: <{channel}> timed out.')
else:
try:
await channel.connect()
except asyncio.TimeoutError:
raise VoiceConnectionError(f'Connecting to channel: <{channel}> timed out.')
if (random.randint(0, 1) == 0):
await ctx.message.add_reaction('')
await ctx.send(f'**Joined `{channel}`**')
@commands.command(name='play', aliases=['sing','p','P','Play'], description="streams music")
async def play_(self, ctx, *, search: str):
"""Request a song and add it to the queue.
This command attempts to join a valid voice channel if the bot is not already in one.
Uses YTDL to automatically search and retrieve a song.
Parameters
------------
search: str [Required]
The song to search and retrieve using YTDL. This could be a simple search, an ID or URL.
"""
await ctx.trigger_typing()
vc = ctx.voice_client
if not vc:
await ctx.invoke(self.connect_)
player = self.get_player(ctx)
# If download is False, source will be a dict which will be used later to regather the stream.
# If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)
await player.queue.put(source)
@commands.command(name='pause', aliases=['Pause'], description="pauses music")
async def pause_(self, ctx):
"""Pause the currently playing song."""
vc = ctx.voice_client
if not vc or not vc.is_playing():
embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())
return await ctx.send(embed=embed)
elif vc.is_paused():
return
vc.pause()
await ctx.send("Paused ⏸️")
@commands.command(name='resume', aliases=['Resume'], description="resumes music")
async def resume_(self, ctx):
"""Resume the currently paused song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
elif not vc.is_paused():
return
vc.resume()
await ctx.send("Resuming ⏯️")
@commands.command(name='skip', aliases=['Skip','s','S'], description="skips to next song in queue")
async def skip_(self, ctx):
"""Skip the song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
if vc.is_paused():
pass
elif not vc.is_playing():
return
vc.stop()
@commands.command(name='remove', aliases=['rm', 'rem'], description="removes specified song from queue")
async def remove_(self, ctx, pos : int=None):
"""Removes specified song from queue"""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
if pos == None:
player.queue._queue.pop()
else:
try:
s = player.queue._queue[pos-1]
del player.queue._queue[pos-1]
embed = discord.Embed(title="", description=f"Removed [{s['title']}]({s['webpage_url']}) [{s['requester'].mention}]", color=discord.Color.green())
await ctx.send(embed=embed)
except:
embed = discord.Embed(title="", description=f'Could not find a track for "{pos}"', color=discord.Color.green())
await ctx.send(embed=embed)
@commands.command(name='clear', aliases=['clr', 'cl', 'cr'], description="clears entire queue")
async def clear_(self, ctx):
"""Deletes entire queue of upcoming songs."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
player.queue._queue.clear()
await ctx.send(' **Cleared**')
@commands.command(name='queue', aliases=['q', 'playlist', 'que'], description="shows the queue")
async def queue_info(self, ctx):
"""Retrieve a basic queue of upcoming songs."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
if player.queue.empty():
embed = discord.Embed(title="", description="queue is empty", color=discord.Color.green())
return await ctx.send(embed=embed)
seconds = vc.source.duration % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour > 0:
duration = "%dh %02dm %02ds" % (hour, minutes, seconds)
else:
duration = "%02dm %02ds" % (minutes, seconds)
# Grabs the songs in the queue...
upcoming = list(itertools.islice(player.queue._queue, 0, int(len(player.queue._queue))))
fmt = '\n'.join(f"`{(upcoming.index(_)) + 1}.` [{_['title']}]({_['webpage_url']}) | ` {duration} Requested by: {_['requester']}`\n" for _ in upcoming)
fmt = f"\n__Now Playing__:\n[{vc.source.title}]({vc.source.web_url}) | ` {duration} Requested by: {vc.source.requester}`\n\n__Up Next:__\n" + fmt + f"\n**{len(upcoming)} songs in queue**"
embed = discord.Embed(title=f'Queue for {ctx.guild.name}', description=fmt, color=discord.Color.green())
embed.set_footer(text=f"{ctx.author.display_name}", icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
@commands.command(name='np', aliases=['song', 'current', 'currentsong', 'playing'], description="shows the current playing song")
async def now_playing_(self, ctx):
"""Display information about the currently playing song."""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
if not player.current:
embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())
return await ctx.send(embed=embed)
seconds = vc.source.duration % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour > 0:
duration = "%dh %02dm %02ds" % (hour, minutes, seconds)
else:
duration = "%02dm %02ds" % (minutes, seconds)
embed = discord.Embed(title="", description=f"[{vc.source.title}]({vc.source.web_url}) [{vc.source.requester.mention}] | `{duration}`", color=discord.Color.green())
embed.set_author(icon_url=self.bot.user.avatar_url, name=f"Now Playing ")
await ctx.send(embed=embed)
@commands.command(name='volume', aliases=['vol', 'v'], description="changes Kermit's volume")
async def change_volume(self, ctx, *, vol: float=None):
"""Change the player volume.
Parameters
------------
volume: float or int [Required]
The volume to set the player to in percentage. This must be between 1 and 100.
"""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I am not currently connected to voice", color=discord.Color.green())
return await ctx.send(embed=embed)
if not vol:
embed = discord.Embed(title="", description=f" **{(vc.source.volume)*100}%**", color=discord.Color.green())
return await ctx.send(embed=embed)
if not 0 < vol < 101:
embed = discord.Embed(title="", description="Please enter a value between 1 and 100", color=discord.Color.green())
return await ctx.send(embed=embed)
player = self.get_player(ctx)
if vc.source:
vc.source.volume = vol / 100
player.volume = vol / 100
embed = discord.Embed(title="", description=f'**`{ctx.author}`** set the volume to **{vol}%**', color=discord.Color.green())
await ctx.send(embed=embed)
@commands.command(name='leave', aliases=["stop", "dc", "disconnect", "bye"], description="stops music and disconnects from voice")
async def leave_(self, ctx):
"""Stop the currently playing song and destroy the player.
!Warning!
This will destroy the player assigned to your guild, also deleting any queued songs and settings.
"""
vc = ctx.voice_client
if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
if (random.randint(0, 1) == 0):
await ctx.message.add_reaction('')
await ctx.send('**Successfully disconnected**')
await self.cleanup(ctx.guild)
def setup(bot):
await bot.add_cog(Music(bot))
We tried awaiting the last line in the music.py file per the code doc on discord dev, but it appears something else is going on?
|
[
"You can not use await statement outside async def ....\nYou need to do like so:\nasync def setup(bot):\n await bot.add_cog(Music(bot))\n\nThen at the entry point of your program you should call something like asyncio.run(setup())\nPlease refer to official documentation, it has some handy examples: https://docs.python.org/3/library/asyncio-task.html\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.py",
"python",
"replit"
] |
stackoverflow_0074555631_discord_discord.py_python_replit.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.