Unnamed: 0
int64 0
1.91M
| id
int64 337
73.8M
| title
stringlengths 10
150
| question
stringlengths 21
64.2k
| answer
stringlengths 19
59.4k
| tags
stringlengths 5
112
| score
int64 -10
17.3k
|
---|---|---|---|---|---|---|
1,903,200 | 72,727,692 |
Run action after Gtk window is shown
|
<p>I have a multi-window Gtk application, which is an installer.
During the installation process, which takes some time, I want to show a Window with a label to notify the user that the installation is in progress.
So I tried to bind the respective method to the <em>show</em> event.</p>
<p>However, that causes the appearance of the window to be delayed until the the method finishes, after which the next window is immediately shown.
The result is, that the previous window shows, then the screen goes blank for the duration of the actual installation and then the final window is shown.</p>
<p>I boiled the issue down to the fact, that the <em>show</em> event is obviously triggered, before the window is actually shown.</p>
<p>Here's a minimal snipped to clarify my issue.
The window shows after the call to <code>sleep()</code>, not before.</p>
<pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python3
from time import sleep
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk
class GUI(Gtk.ApplicationWindow):
def __init__(self):
"""Initializes the GUI."""
super().__init__(title='Gtk Window')
self.set_position(Gtk.WindowPosition.CENTER)
self.grid = Gtk.Grid()
self.add(self.grid)
self.label = Gtk.Label()
self.label.set_text('Doing stuff')
self.grid.attach(self.label, 0, 0, 1, 1)
self.connect('show', self.on_show)
def on_show(self, *args):
print('Doing stuff.')
sleep(3)
print('Done stuff.')
def main() -> None:
"""Starts the GUI."""
win = GUI()
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()
if __name__ == '__main__':
main()
</code></pre>
<p>How can I achieve, that the window shows <em>before</em> the method <code>on_show()</code> is called?</p>
<p>The desired program flow is</p>
<ol>
<li>Show window</li>
<li>run installation</li>
<li>hide window (and show next one)</li>
</ol>
<p>without any user interaction.</p>
|
<p>I fixed it by using multiprocessing :</p>
<pre><code>from ast import Gt
from time import sleep
from multiprocessing import Process
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gtk
class GUI(Gtk.ApplicationWindow):
def __init__(self):
"""Initializes the GUI."""
super().__init__(title='Gtk Window')
self.set_position(Gtk.WindowPosition.CENTER)
self.grid = Gtk.Grid()
self.add(self.grid)
self.label = Gtk.Label()
self.label.set_text('Doing stuff')
self.grid.attach(self.label, 0, 0, 1, 1)
def on_show():
print('Doing stuff.')
sleep(3)
print('Done stuff.')
def main() -> None:
"""Starts the GUI."""
win = GUI()
win.connect('destroy', Gtk.main_quit)
win.show_all()
p1 = Process(target = on_show)
p1.start()
Gtk.main()
if __name__ == '__main__':
main()
</code></pre>
<p>Basically, what was happening is that Gtk.main() renders your app while show_all() just packs the widgets, so putting a sleep func before it delays the render.</p>
|
python|python-3.x|gtk|gtk3|pygobject
| 1 |
1,903,201 | 68,034,235 |
pandas products analysis getting pairs according to purchases
|
<p>Here's an example of my dataframe:</p>
<pre><code>df.head(10)
, customer_id order_id, product, purchased_at
0, 2, 2000, B, 2021-05-01 21:51:13
1, 1, 1996, A, 2021-04-06 13:02:37
2, 1, 2540, B, 2021-05-06 16:02:37
3, 4, 4514, C, 2021-04-05 10:55:18
4, 4, 4560, D, 2021-04-10 11:56:18
5, 5, 6899, Y, 2021-04-07 09:53:45
6, 2, 7891, A, 2021-04-07 09:59:21
7, 2, 8120, B, 2021-06-04 09:19:41
8, 3, 9423, Z, 2021-03-28 15:34:29
9, 3, 9423, X, 2021-03-28 15:34:29
... ... ....
</code></pre>
<p>I want to get which product led to another for each customer and than calculate the interval between pairs, for example:
customer 1 bought product A in his first order then product B in his second one. So product A led to product B (A->B) that's a pair. And then calculate the average intervals.</p>
<p>I need your help to find the best approach in order to achieve what I already explained and the best way to display the output in order to calculate the average interval between those pairs and a library to visualise it.Thank you in advance.</p>
|
<pre><code>result= pd.DataFrame()
df.purchase_at = pd.to_datetime(df.purchase_at)
df = df.sort_values(by='purchase_at')
unique_customers = df.customer_id.unique()
result = pd.DataFrame()
for customer in unique_customers:
temp = df[df.customer_id == customer].copy()
if len(temp) > 1:
temp['previous_sale'] = temp['product'].shift()
temp['previous_order_id'] = temp['order_id'].shift()
temp['previous_sale_date'] = temp['purchase_at'].shift()
temp['time_diff'] = temp.purchase_at.diff()
result = result.append(temp[1:])
</code></pre>
|
python|pandas|numpy|data-science
| 0 |
1,903,202 | 68,430,065 |
Generate random tuple combination based on their score in Python
|
<p>I am trying to create a python program, I have 4 list of tuples, I would like to create different 'words', each letter having it's own probability to appear, I would also like the words to be unique.</p>
<p>I first tried creating by assigning probability to each letter, which worked using <code>numpy.random.choice()</code> function.</p>
<p>Now I would like to take the problem from the other side. I put a weight (or score) to each letter (second part of each tuple) so each word I create have a score, here: from 4 to 16. (see below the 4 list of tuple, it's an exemple of what I am working with, the 4 lists are different)</p>
<pre class="lang-py prettyprint-override"><code>liste1 = [('A',1), ('E',1), ('I',1), ('O',1), ('U',1), ('M',2), ('N',2), ('B',2), ('Y',2), ('R',3), ('E',3), ('T',3), ('G',4), ('J',4)]
liste2 = [('A',1), ('E',1), ('I',1), ('O',1), ('U',1), ('L',2), ('N',2), ('Z',2), ('Y',2), ('R',3), ('E',3), ('P',3), ('F',4), ('X',4)]
liste3 = [('A',1), ('E',1), ('I',1), ('O',1), ('U',1), ('Q',2), ('N',2), ('B',2), ('Y',2), ('R',3), ('E',3), ('T',3), ('H',4), ('J',4)]
liste4 = [('A',1), ('E',1), ('I',1), ('O',1), ('U',1), ('M',2), ('N',2), ('B',2), ('Y',2), ('R',3), ('E',3), ('T',3), ('S',4), ('J',4)]
</code></pre>
<p>And what I would like to do is telling my program I want x number of word with a score of 16, and then the program will create randomly x unique words with this score, then also do it for a score of 15, 14 etc...</p>
<p>I have no idea how to do that and I know it is a pretty specific demand, So I would be glad if anyone can bring me an answer.</p>
<p>Thank you for your time!</p>
|
<p>Try:</p>
<pre class="lang-py prettyprint-override"><code>import random
liste1 = [
("A", 1),
("E", 1),
("I", 1),
("O", 1),
("U", 1),
("M", 2),
("N", 2),
("B", 2),
("Y", 2),
("R", 3),
("E", 3),
("T", 3),
("G", 4),
("J", 4),
]
def get_words(lst, n, target):
def get_combinations(candidates):
res = []
def fn(arr, start):
s = sum(arr)
if s == target:
res.append(arr[:])
return
if s > target:
return
for i in range(start, len(candidates)):
arr.append(candidates[i])
fn(arr, i)
arr.pop()
fn([], 0)
return res
tmp = {}
for ch, v in lst:
tmp.setdefault(v, []).append(ch)
all_comb = get_combinations(list(tmp))
res = []
for _ in range(n):
while True:
s = ""
comb = random.choice(all_comb)
random.shuffle(comb)
for v in comb:
s += random.choice(tmp[v])
if s not in res:
res.append(s)
break
return res
print(get_words(liste1, 10, 16))
</code></pre>
<p>This prints 10 random words from <code>liste1</code> that has characters whose value sums to 16 (for example):</p>
<pre class="lang-py prettyprint-override"><code>[
"UNINONMBAM",
"TMYRNYY",
"UOUUAEOUUUIAEOAA",
"JIJMJA",
"MNNJJN",
"OIMAIIGOJ",
"TTNBYMY",
"EIAAIUUAMIEOI",
"IEUAOJENUU",
"BBGJENI",
]
</code></pre>
|
python|list|numpy|random|tuples
| 2 |
1,903,203 | 59,364,441 |
How do I print a Python variable as an attribute value for XML file
|
<p>Python Version 3.6.8</p>
<pre><code>import xml.etree.cElementTree as ET
</code></pre>
<p>Following is the code to generate XML file, XML file generation code is working fine. I need to write some values from variables. Variables are <strong>i</strong>, <strong>height</strong> and <strong>width</strong>. </p>
<pre><code>frame = ET.SubElement(root, "frame", number="{i}")
objectlist = ET.SubElement(frame, "objectlist")
object = ET.SubElement(objectlist, "object", id="1")
ET.SubElement(object, "box", h="{height}", w="{width}")
</code></pre>
<p>How can I pass the variables in the given code? (First Line of Code and fourth line of code)</p>
|
<p>First, please specify all the valuable information like <em>version of Python</em> and what is the library you are using (<code>ET</code>).</p>
<p>If this code is in Python 3.6 or later the most intuitive way would be to use <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow noreferrer">f-strings</a>, which would be in your case:</p>
<pre><code>frame = ET.SubElement(root, "frame", number=f"{i}"
</code></pre>
<p>(Note how the only change is <code>f</code> before the value of <code>number</code>)</p>
<p>You can do the same with any other string value.</p>
<p>Another way to achieve this would be to cast the value of <code>i</code> to string using <code>str(i)</code>, which will work the same but will lack the efficiency of f-strings.</p>
|
python|xml
| 2 |
1,903,204 | 59,348,409 |
How to Display Sprites in Pygame?
|
<p>This is just a quick question regarding sprites in PyGame, I have my image loaded as in the code below, and I'm just wondering how to display the sprite in PyGame like drawing a rectangle or circle. I don't want to have it behave in anyway. I think I use a <code>blit</code> command, but I'm not sure and I'm not finding much online.</p>
<p>Here's my image code for loading it.</p>
<pre class="lang-py prettyprint-override"><code>Star = pygame.image.load('WhiteStar.png').convert_alpha()
</code></pre>
<p>You could just provide an outline for loading a sprite. I simply want to display it.</p>
|
<p>Use <a href="https://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit" rel="nofollow noreferrer"><code>blit</code></a> to draw an image. Actually <code>blit</code> draws one <a href="https://www.pygame.org/docs/ref/surface.html#pygame.Surface.blit" rel="nofollow noreferrer"><code>Surface</code></a> onto another. Hence you need to <code>blit</code> the image onto the <em>Surface</em> associated to the display.<br />
You need to specify the position where the image is <code>blit</code> on the target. The position can be specified by a pair of coordinates that define the top left position. Or it can be specified by a rectangle, only taking into account the top left point of the rectangle:</p>
<pre class="lang-py prettyprint-override"><code>screen = pygame.dispaly.set_mode((width, height))
star = pygame.image.load('WhiteStar.png').convert_alpha()
# [...]
while run:
# [...]
screen.blit(star, (x, y))
# [...]
</code></pre>
<hr />
<p>Use a <a href="https://www.pygame.org/docs/ref/rect.html" rel="nofollow noreferrer"><code>pygame.Rect</code></a> when you want to place the center of a surface at a specific point. <a href="https://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect" rel="nofollow noreferrer"><code>pygame.Surface.get_rect.get_rect()</code></a> returns a rectangle with the size of the <em>Surface</em> object, that always starts at (0, 0) since a <em>Surface</em> object has no position. The position of the rectangle can be specified by a keyword argument. For example, the center of the rectangle can be specified with the keyword argument <code>center</code>. These keyword argument are applied to the attributes of the <a href="https://www.pygame.org/docs/ref/rect.html" rel="nofollow noreferrer"><code>pygame.Rect</code></a> before it is returned (see <a href="https://www.pygame.org/docs/ref/rect.html" rel="nofollow noreferrer"><code>pygame.Rect</code></a> for a full list of the keyword arguments):</p>
<pre class="lang-py prettyprint-override"><code>screen.blit(star, star.get_rect(center = (x, y)))
</code></pre>
|
python|pygame|sprite|pygame-surface
| 0 |
1,903,205 | 72,895,682 |
How to let the server socket react to a second client request?
|
<p>I have a simple echo server that echos back whatever it receives. This works well for a single client request.</p>
<pre><code># echo-server.py
import socket
HOST = "127.0.0.1"
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
try:
data = conn.recv(1024)
except KeyboardInterrupt:
print ("KeyboardInterrupt exception captured")
exit(0)
conn.sendall(data)
# echo-client.py
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print(f"Received {data!r}")
</code></pre>
<p>However, if I finish one client request, and do a second client request, the server no more echoes back. How can I solve this issue?</p>
<pre><code>(base) root@40029e6c3f36:/mnt/pwd# python echo-client.py
Received b'Hello, world'
(base) root@40029e6c3f36:/mnt/pwd# python echo-client.py
</code></pre>
|
<p>On the server side, you need to accept connections in an infinite loop. This should work.</p>
<p><strong>server.py</strong></p>
<pre><code>HOST = "127.0.0.1"
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
print(f"Connected by {addr}")
try:
data = conn.recv(1024)
except KeyboardInterrupt:
print ("KeyboardInterrupt exception captured")
exit(0)
conn.sendall(data)
</code></pre>
|
python|sockets
| 2 |
1,903,206 | 63,017,575 |
Python3. Setuptools. Adding a local package to an assembly
|
<p>There is a locally built package (eg <strong>main-0.1.tar.gz</strong>). There is another package (for example <strong>base-0.1</strong>) that requires <strong>main-0.1</strong> as a dependency.</p>
<p>It is necessary that during the subsequent installation of the <strong>base-0.1</strong> package, the <strong>main-0.1</strong> package is also installed.</p>
<p>Those. You can specify only packages with <strong>PyPI</strong> in <strong>install_requires</strong>, but local adding packages to the assembly is not clear how.</p>
<p>You can add the package <strong>main-0.1.tag.gz</strong> to the <strong>base-0.1</strong> archive using <strong>MANIFEST.in</strong> (<code>include main-0.1.tag.gz</code>). But further <strong>dependency_links</strong>, for example, does not work correctly.</p>
<p>How do I add a local package to the build of another package and then install it along with another package, as if it were pulled from <strong>PyPI</strong>?</p>
|
<p>You might want to look at:</p>
<ul>
<li><a href="https://www.python.org/dev/peps/pep-0440/#file-urls" rel="nofollow noreferrer"><em>PEP 440</em> ("<em>File URLs</em>")</a></li>
<li><a href="https://www.python.org/dev/peps/pep-0508/#examples" rel="nofollow noreferrer"><em>PEP 508</em></a></li>
</ul>
<pre><code>import setuptools
setuptools.setup(
# [...]
install_requires = [
'main @ file:///path/to/main-0.1.tar.gz'
# [...]
],
)
</code></pre>
<hr />
<p>Alternatively (probably better actually), use some combination of <a href="https://pip.pypa.io/en/stable/reference/pip_install/#options" rel="nofollow noreferrer"><code>pip install</code> options</a>:</p>
<pre><code>pip install --no-index --find-links '/path/to/distributions' main base
</code></pre>
<p>Reference:</p>
<ul>
<li><a href="https://pip.pypa.io/en/stable/user_guide/#installing-from-local-packages" rel="nofollow noreferrer">https://pip.pypa.io/en/stable/user_guide/#installing-from-local-packages</a></li>
</ul>
|
python|python-3.x|installation|setuptools
| 1 |
1,903,207 | 62,927,819 |
How to use chromedriver in selenium in all platforms like mac,linux and windows?
|
<p>Actually I'm doing a project on creating a <strong>library package</strong> to add in PIP repository where I have to create single program which has to be executable on all platforms. Here is my program:</p>
<pre><code>def DataSet():
**PATH = "C:\Program Files (x86)\chromedriver.exe"**
DataSet.driver = webdriver.Chrome(PATH)
DataSet.driver.get(url)
r = input('\n'+"Enter the dataset name: ")
login_form = DataSet.driver.find_element_by_xpath("//h1[contains(text(),'{}')]".format(r))
check = login_form.click()
urr = DataSet.driver.current_url
</code></pre>
<p>Here the <strong>PATH</strong> which I'm defining is not same in all windows, mac and Linux. Is there any solution for this, please reply soon. Thanks in advance.</p>
|
<p>You could take different approaches to solve this, Here are a few solutions:</p>
<blockquote>
<p>Using Docker to distribute your application (Most Preferred).</p>
</blockquote>
<p>Once you containerize your application/program it runs the same regardless of the platform on which it runs. The chromedriver should also be packaged along with the docker container.</p>
<p>Here is a sample reference of <code>Dockerfile</code> to use chromedriver and selenium: <a href="https://gitlab.com/snippets/1921886" rel="nofollow noreferrer">Sample Dockerfile for Python-Selenium-Chromedriver</a></p>
<p>The second approach would be to check for the Operating System and then look out for chromedriver in platform-specific locations. Incase if chromedriver is not present ask the application user to install in a specific location (add PATH as well) and then use the application.</p>
|
python|selenium|selenium-chromedriver
| 0 |
1,903,208 | 62,399,310 |
pip installing in usr/lib/python3.6/site-packages instead of virtualenv on ubuntu server
|
<p>I'm having a problem when installing packages on my virtualenv.It all started when I upgraded my pip to the latest version. I tried to revert my pip version to where I find it stable. When I try to install, for example, django-tables2, it says:</p>
<pre><code>Requirement already satisfied: django-tables2 in /usr/lib/python3.6/site-packages (2.3.1)
Requirement already satisfied: Django>=1.11 in /usr/local/lib/python3.6/dist-packages (from django-tables2) (2.2.4)
Requirement already satisfied: pytz in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-tables2) (2019.2)
Requirement already satisfied: sqlparse in /usr/local/lib/python3.6/dist-packages (from Django>=1.11->django-tables2) (0.3.0)
WARNING: You are using pip version 19.3.1; however, version 20.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code></pre>
<p>But when I check my folder in my virtualenv, it doesn't show there. I tried some commands like <code>which pip</code> and <code>which pip3</code> and it says this:</p>
<pre><code>(unidaenv) root@UnidaWebApplication:/home/unidaweb/unidaproject# which pip
/home/unidaweb/unidaproject/unidaenv/bin/pip
(unidaenv) root@UnidaWebApplication:/home/unidaweb/unidaproject# which pip3
/home/unidaweb/unidaproject/unidaenv/bin/pip3
(unidaenv) root@UnidaWebApplication:/home/unidaweb/unidaproject#
</code></pre>
<p>I also tried <code>pip list</code> but I can't find the package that I installed to my virtualenv.</p>
<p>I'm getting a <code>bad gateway error</code> when I try to add it on my <code>settings.py</code>, I don't really know how to fix this but when I'm in the version of pip that I know was stable running my project, I don't get this error and I can install any package that I needed to my project. Any help would be much appreciated. I'm stuck on this for about a week, hoping that someone could help me with this issue.</p>
|
<p>virtualenvs can break occasionally especially if the somebody updated the python executable the virtualenv was based or some packages / shared libraries of it.</p>
<p>I'd suggest to try out with a new virtualenv. (delete the broken one and replace it)</p>
<p>Further.</p>
<p>for debugging I suggest to type following two commands:
<code>type -a python</code> and <code>type -a pip</code></p>
<p>In case your search path has some hidden surprises it could be safer to call
<code>python -m pip</code> instead of <code>python</code> though in a properly setup virtualenv it shouldn't make a difference.</p>
|
python|django|pip
| 0 |
1,903,209 | 35,756,339 |
--version support in a Python program built with Pants
|
<p>How can I get <a href="https://pantsbuild.github.io/" rel="nofollow">Pants</a> to store the output of <code>git describe</code> somewhere in my <code>.pex</code> file so that I can access it from the Python code I'm writing?</p>
<p>Basically I want to be able to clone <a href="https://github.com/walles/px" rel="nofollow">my project</a> and do this:</p>
<ol>
<li><code>./pants binary px</code></li>
<li>Distribute the resulting <code>dist/px.pex</code> to somebody</li>
<li>That somebody should be able to do <code>px.pex --version</code> and get a printout of whatever <code>git describe</code> said when I built the <code>.pex</code> in step one.</li>
</ol>
<p>Help!</p>
|
<p>Turns out <code>pex</code> already does <code>git describe</code> on build. The result it stores in a <code>PEX-INFO</code> file in the root of the <code>.pex</code> file. So to read it, I did this:</p>
<pre><code>def get_version():
"""Extract version string from PEX-INFO file"""
my_pex_name = os.path.dirname(__file__)
zip = zipfile.ZipFile(my_pex_name)
with zip.open("PEX-INFO") as pex_info:
return json.load(pex_info)['build_properties']['tag']
</code></pre>
<p>This is good enough IMO, but there are also drawbacks. If somebody has an improved answer I'm prepared to switch to that one as the accepted one.</p>
<p>Outages with this one:</p>
<ul>
<li>Relies on relative paths to locate <code>PEX-INFO</code>, would be better if there was some kind of API call for this.</li>
<li>No way to customize how the version number is computed; I'd like to do <code>git describe --dirty</code> for example.</li>
</ul>
|
python|pants
| 0 |
1,903,210 | 35,457,984 |
Why does pygame stop working when I remove a print statement?
|
<p>I have some pygame code here I made:</p>
<pre><code>#############################################################################
# IMPORTS
#############################################################################
import pygame, sys
from pygame.locals import *
#############################################################################
# PRE-INITIALIZATION
#############################################################################
pygame.init()
#############################################################################
# CONSTANTS
#############################################################################
SW = 300
SH = 300
#############################################################################
WHITE = (255,255,255)
LIGHTEST_GRAY = (230,230)
LIGHT_GRAY = (205,205,205)
SORTLIGHT_GRAY = (180,180,180)
GRAY = (155,155,155)
SORTDARK_GRAY = (130,130,130)
DARK_GRAY = (105,105,105)
DARKEST_GRAY = (80,80,80)
BLACK_GRAY = (55,55,55)
LIGHT_BLACK = (30,30,30)
SORTLIGHT_BLACK = (5,5,5)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
#############################################################################
SYS_FONT = pygame.font.SysFont(None, 30)
#############################################################################
# GLOBAL VARIABLES
#############################################################################
state = ""
#############################################################################
# CLASSES
##############################################################################
#############################################################################
# FUNCTIONS
#############################################################################
def addTuples(a,b):
for i in range(len(a)):
a[i] += b[i]
def set_state(newstate="",init_function=None):
global state
state=newstate
if init_function!=None:init_function()
return state
def get_state():
return state
#############################################################################
def initSplashScreen():
screen.fill(BLACK)
def initGameScreen():
pass
#############################################################################
def quitEvent():
pygame.quit()
sys.exit()
def updateEvent():
checkEvents()
if get_state() == "splash":
drawSplashScreen()
elif get_state() == "game":
drawGameScreen()
#############################################################################
def checkEvents():
for event in pygame.event.get():
if event.type == QUIT:
quitEvent()
def checkSplashScreenEvents():
print("naff")
for event in pygame.event.get():
if event.type == KEYUP:
print("saff")
set_state("game",initGameScreen)
def checkGameScreenEvents():
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == K_ESCAPE:
set_state("pause")
def checkPauseScreenEvents():
for event in pygame.event.get():
if event.type == KEYDOWN:
set_state("game")
#############################################################################
def drawText(text,color,loc):
text_obj = SYS_FONT.render(text, True, color)
screen.blit(text_obj,loc)
#############################################################################
def drawSplashScreen():
checkSplashScreenEvents()
drawText("Grid Game",RED,(95,50))
drawText("Press SPACE to begin!",YELLOW,(35,100))
def drawGameScreen():
checkGameScreenEvents()
screen.fill(BLACK)
drawText("Game",BLUE,(95,50))
def drawPauseScreen():
checkPauseScreenEvents()
drawText("Paused",GREEN,(115,50))
drawText("Press ANY KEY to continue!",YELLOW,(15,100))
#############################################################################
# INITIALIZATION
#############################################################################
screen = pygame.display.set_mode((SW,SH))
pygame.display.set_caption("Grid")
set_state("splash",initSplashScreen)
#############################################################################
# PROGRAM STARTS HERE
#############################################################################
while True:
updateEvent()
pygame.display.update()
</code></pre>
<p>When I run the program I can press 'space' key and it says 'game' in blue on the screen with a black background.</p>
<p>However, when I remove the print statement in checkSplashScreenEvents function: <code>print("naff")</code> the program no longer works correctly. When I press 'space' about twenty times it works after 10 seconds or so...</p>
<p>The print statements were only used for testing to make sure the function was called earlier on when I was creating this program.</p>
<p>I thought the python Idle IDE might have been glitching out so I got out of Idle and when back in. This did not fix the problem.</p>
<p>Does anyone know what is going on here, why this is happening?
And how to fix it?</p>
<p>Thank you, in advance.</p>
|
<p>You are not making <em>ANY</em> pause between frames or event checking- the CPU and I/O are overloaded at maximum. The print statement would provide a brief relief to the system.</p>
<p>Try just adding a <code>pygame.time.delay(30)</code> or so immediately after calling <code>display.update()</code>.</p>
<p>Now, with a little more calm, the real problem is that you are making calls to <code>pygame.event.get</code> in more than one location in your code, and doing that in your loop. That call is destructive in a way that it does consume any pending events. The print would introduce a small pause between calls to <code>.get</code> so that a <code>KEYUP</code> event eventually has a chance to sneak-in between the calls to <code>event.get</code> in your <code>checkEvents</code> method and the one in <code>checkSplashScreenEvents</code> method. </p>
<p>You'd better reorganize your code so that you call <code>event.get</code> in ONE single place- otherwise your code will be unmaintainable (it is already hard to follow, and there is almost nothing in there) - for example, try to set an event callback for each of the game states - the callback gets a list of the ongoing events - from a single <code>getEvents</code> method.</p>
<p>For the code as it is to run, just replace your checkEvents for one with a non-destructive way to check for a quit event - for example:</p>
<pre><code>def checkEvents():
if pygame.event.peek(QUIT):
quitEvent()
</code></pre>
|
python|python-3.x|pygame
| 1 |
1,903,211 | 58,925,655 |
When using a Tensorflow Dataset from_tensor_slices(), is it possible to NOT load a new batch every train step?
|
<p>I would like to train for a few steps on the same batch since I want to give the CPU time to load the next batch. I am using reinitializable iterators and <code>tf.data.Dataset.from_tensor_slices((tf.range(n_train)))</code> and then using .map() to get my dataset by index. I want to run at least as many train steps on the batch as takes to load the next batch.</p>
|
<p>So you want to repeat each datapoint <code>n</code> times right? The following should achieve that.</p>
<pre><code>n_train = 10
n_repeat = 5
ds = tf.data.Dataset.from_tensor_slices((tf.range(n_train))).interleave(lambda x: tf.data.Dataset.from_tensors(x).repeat(n_repeat), block_length=n_repeat)
diter = ds.make_one_shot_iterator()
elem = diter.get_next()
with tf.Session() as sess:
for _ in range(n_train*n_repeat):
print(sess.run(elem))
</code></pre>
|
python|tensorflow|tensorflow-datasets
| 0 |
1,903,212 | 58,985,428 |
Python Pandas - Cleaning data column depending on multiple criteria
|
<p>I have the following code to create a column with cleaned up zip codes for the USA and Canada</p>
<pre><code>df = pd.read_csv(file1)
usa = df['Region'] == 'USA'
canada = df['Region'] == 'Canada'
df.loc[usa, 'ZipCleaned'] = df.loc[usa, 'Zip'].str.slice(stop=5)
df.loc[canada, 'ZipCleaned'] = df.loc[canada, 'Zip'].str.replace(' |-','')
</code></pre>
<p>The problem is that some of the rows that have "USA" as the country contain Canadian postal codes in the dataset. So the USA logic from above is being applied to Canadian postal codes. </p>
<p>I tried the edited code below along with teh above and experimented with one provinces ("BC") to prevent the USA logic from being applied in this case but it didn't work </p>
<pre><code>usa = df['Region'] == 'USA' and df['Ship To State'] != 'BC'
</code></pre>
|
<p>The following code solves this question </p>
<pre><code>df.loc[~df['Ship To Customer Zip'].str.contains('[A-Za-z]'), 'ZipCleaned'] = df['Ship To Customer Zip'].str.slice(stop=5)
df.loc[df['Ship To Customer Zip'].str.contains('[A-Za-z]'), 'ZipCleaned'] = df['Ship To Customer Zip'].str.replace(' |-','')
</code></pre>
|
python|pandas|conditional-statements|data-cleaning
| 0 |
1,903,213 | 73,304,901 |
RecursionError: maximum recursion depth exceeded in comparison with djongo.exceptions.SQLDecodeError:
|
<p>I am trying to make an app with django using djongo and mongodb. The connectivity for tables with no foreign key is working fine but where there is a Foreign Key involved, it is throwing this error. I will be greatful if anyone could help. I am getting this error.</p>
<pre><code>Traceback (most recent call last):
</code></pre>
<p>File "C:\Users\theri\Desktop\Python_Amygo\amygo_python\venv\lib\site-packages\djongo\sql2mongo\query.py", line 808, in <strong>iter</strong><br />
yield from iter(self._query)</p>
<p>File "C:\Users\theri\Desktop\Python_Amygo\amygo_python\venv\lib\site-packages\sqlparse\tokens.py", line 19, in <strong>contains</strong>
return item is not None and (self is item or item[:len(self)] == self)
RecursionError: maximum recursion depth exceeded in comparison</p>
<p>The above exception was the direct cause of the following exception:</p>
<p>Traceback (most recent call last):
File "C:\Users\theri\Desktop\Python_Amygo\amygo_python\venv\lib\site-packages\djongo\cursor.py", line 76, in fetchone
return self.result.next()
File "C:\Users\theri\Desktop\Python_Amygo\amygo_python\venv\lib\site-packages\djongo\sql2mongo\query.py", line 797, in <strong>next</strong><br />
result = next(self._result_generator)
File "C:\Users\theri\Desktop\Python_Amygo\amygo_python\venv\lib\site-packages\djongo\sql2mongo\query.py", line 830, in <strong>iter</strong><br />
raise exe from e
djongo.exceptions.SQLDecodeError:</p>
<pre><code> Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "accounts_account" WHERE "accounts_account"."id" = %(1)s LIMIT 1
</code></pre>
<p>Params: (1, 1)
Version: 1.3.6
Sub SQL: None
FAILED SQL: None
Params: None
Version: None</p>
<p>The above exception was the direct cause of the following exception:</p>
<p>Traceback (most recent call last):
File "C:\Users\theri\Desktop\Python_Amygo\amygo_python\venv\lib\site-packages\django\db\utils.py", line 98, in inner
return func(*args, **kwargs)
File "C:\Users\theri\Desktop\Python_Amygo\amygo_python\venv\lib\site-packages\djongo\cursor.py", line 81, in fetchone
raise db_exe from e
djongo.database.DatabaseError</p>
<p>I am using the following versions:<br />
django-4.1 , djongo-1.3.6 , pymongo-4.2.0 , sqlparse-0.2.4</p>
|
<p>I had this same issue Downgrading django from 4.1 to 3.2 worked for me.</p>
<p><code>pip install django==3.2</code></p>
|
python|django|mongodb|djongo
| 0 |
1,903,214 | 31,327,442 |
Sending email through gmail with Python
|
<p>So I have tried at least 5-10 examples online to send an email, but I keep getting the same error.</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/alxu/Project/LogFilter.py", line 88, in ?
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
File "C:\Python24\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python24\lib\smtplib.py", line 292, in connect
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
socket.gaierror: (11004, 'getaddrinfo failed')
</code></pre>
<p>The last example I used code was like this...</p>
<pre><code>import smtplib
to = 'mkyong2002@yahoo.com'
gmail_user = 'mkyong2002@gmail.com'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.close()
</code></pre>
<p>I am using Python 2.4.3.</p>
<p>EDIT: McAfee is has host intrusion prevention so all the times I attempted to do this it blocked it.</p>
|
<p>Your last example code should work. One thing you need to do is to make sure you allow access to less secure apps by going to the following link.</p>
<p><a href="https://www.google.com/settings/security/lesssecureapps" rel="nofollow">google settings for secure apps</a></p>
<p>The reason for this is google flags such automated email scripts as less secure. You should also be aware of the risks. Make sure you change this setting back if you are not gonna need it.</p>
|
python|email|python-2.x
| 1 |
1,903,215 | 59,734,613 |
How to save images with scrapy
|
<p>I extracted links to images from <a href="https://www.topgear.com/car-reviews/ferrari/laferrari" rel="nofollow noreferrer">https://www.topgear.com/car-reviews/ferrari/laferrari</a> using scrapy in bash, is there any simple way to save them without a pipeline?</p>
<pre><code>scrapy shell https://www.topgear.com/car-reviews/ferrari/laferrari
response.xpath('//div[@class="carousel__content-inner"]//img/@srcset').extract()
</code></pre>
<pre><code>['https://www.topgear.com/sites/default/files/styles/fit_980x551/public/cars-car/carousel/2015/02/buyers_guide_-_laf_-_front.jpg?itok=KiD7ErMe 980w',
'https://www.topgear.com/sites/default/files/styles/fit_980x551/public/cars-car/carousel/2015/02/buyers_guide_-_laf_-_rear.jpg?itok=JMYaaJ5L 980w',
'https://www.topgear.com/sites/default/files/styles/fit_980x551/public/cars-car/carousel/2015/02/buyers_guide_-_laf_-_interior.jpg?itok=4Z0zIdH_ 980w',
'https://www.topgear.com/sites/default/files/styles/fit_980x551/public/cars-car/carousel/2015/02/buyers_guide_-_laf_-_side.jpg?itok=OKl2MOJ2 980w']
</code></pre>
<p>Thanks for any help.</p>
|
<p>You can use scrapy Selector <a href="https://docs.scrapy.org/en/latest/topics/selectors.html" rel="nofollow noreferrer">https://docs.scrapy.org/en/latest/topics/selectors.html</a>
and requests library:</p>
<pre><code>from scrapy.selector import Selector
import requests
from tqdm import tqdm
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
response = requests.get('https://www.topgear.com/car-reviews/ferrari/laferrari', headers=headers)
links = Selector(text=response.text).xpath('//div[@class="carousel__content-inner"]//img/@srcset').getall()
for i, image_url in tqdm(enumerate(links)):
try:
response = requests.get(image_url, headers=headers)
except:
pass
else:
if response.status_code == 200:
with open('{:02}.jpg'.format(i), 'wb') as f:
f.write(response.content)
</code></pre>
|
python-3.x|bash|scrapy
| 2 |
1,903,216 | 49,128,182 |
How to get userprofile in django 2.0
|
<p>I read a few post already, but I couldn't find what I was looking for.</p>
<p>I'm trying to figure out how to get the UserProfile of a user. I created a one to one field relationship when I create the User Profile. I thought I could just query the UserProfile as is, but I can't get it to work.</p>
<pre><code>def profile_edit(request):
user = UserProfile.objects.get(user=request.user)
return render(request, 'medium/profile_edit.html', {'user_profile_form': form,
'current_user': user})
</code></pre>
<p>Any thoughts? Here's my models.py and views </p>
<h1>models.py</h1>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,)
bio = models.TextField(blank=True)
avatar = models.ImageField(upload_to='avatars', blank=True)
</code></pre>
<h1>views.py</h1>
<pre><code>def register_user(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
user_profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and user_profile_form.is_valid():
new_user = user_form.save()
new_user.set_password(new_user.password)
new_user.save()
new_user_profile = user_profile_form.save(commit=False)
new_user_profile.user = new_user
if 'avatar' in request.FILES:
new_user_profile.avatar = request.FILES['avatar']
new_user_profile.save()
registered = True
else:
print(user_form.errors, user_profile_form.errors)
else:
user_form = UserForm()
user_profile_form = UserProfileForm()
return render(request, 'medium/registration.html', {
'user_form': user_form,
'user_profile_form': user_profile_form,
'registered': registered
})
</code></pre>
|
<p>Of course after 2 hours of googling, I finally figured it out. </p>
<p>I put a related_name on my Model and then added this in the view</p>
<pre><code>def profile_edit(request):
user_form = UserForm(instance=request.user)
user_profile_form = UserProfileForm(instance=request.user.profile)
return render(request, 'medium/profile_edit.html', {
'user_profile_form': user_profile_form,
'user_form': user_form,
})
</code></pre>
|
python|django|user-profile
| 0 |
1,903,217 | 70,781,908 |
Poetry add dependency to package in non-standard apt-get repository
|
<p>Is it possible to use poetry to include a dependency to a package that's installed via <code>apt-get</code> from a non-standard repository? Specifically I'm trying to add <a href="https://www.jive.eu/jivewiki/doku.php?id=parseltongue:parseltongue" rel="nofollow noreferrer">ParselTongue</a> as a dependency, but this requires adding a repository to apt-get to install:</p>
<pre><code>sudo add-apt-repository ppa:kettenis-w/parseltongue
sudo apt-get update
sudo apt-get install python3-parseltongue
</code></pre>
<p>Is this possible with poetry?</p>
|
<p>Poetry can handle only python package repositories like PyPi. So it is not possible to handle dependencies in a linux distribution repo.</p>
|
python-3.x|ubuntu|python-poetry
| 0 |
1,903,218 | 70,995,596 |
how to create Snapshot & Release Folder for Artifactory using CI pipeline?
|
<p>I want to create snapshot & release folder in Jfrog Artifactory using CI Pipeline while doing deployment in Gitlab. Can anybody help me on this ?</p>
|
<p>JFrog Artifactory uses repositories for storing and managing artifacts. One repository usually contains many artifacts. In general, repositories are usually created once, not during a CI run.</p>
<p><a href="https://www.jfrog.com/confluence/display/JFROG/Maven+Repository" rel="nofollow noreferrer">Maven repositories</a> can be configured to host releases, snapshots or both. The common practice is to create a <a href="https://www.jfrog.com/confluence/display/JFROG/Local+Repositories" rel="nofollow noreferrer">local repository</a> for snapshots (e.g. <code>libs-snapshot-local</code>) and a local repository for releases (e.g. <code>libs-release-local</code>). In addition, you can add <a href="https://www.jfrog.com/confluence/display/JFROG/Remote+Repositories" rel="nofollow noreferrer">remote repositories</a> (e.g. for proxying Maven Central). On top of that you can add <a href="https://www.jfrog.com/confluence/display/JFROG/Virtual+Repositories" rel="nofollow noreferrer">virtual repositories</a> - to aggregate several repositories.</p>
<p>Please refer to the following links to get more information:</p>
<ul>
<li>Screencast: <a href="https://jfrog.com/screencast/setting-maven-repository-jfrog-artifactory-less-one-minute/" rel="nofollow noreferrer">Setting Up A Maven Repository With JFrog Artifactory In Less Than One Minute</a></li>
<li>Official Documentation: <a href="https://www.jfrog.com/confluence/display/JFROG/Maven+Repository" rel="nofollow noreferrer">Maven Repository</a></li>
<li>QuickStart Guide: <a href="https://www.jfrog.com/confluence/display/JFROG/QuickStart+Guide%3A+Maven+and+Gradle" rel="nofollow noreferrer">Maven and Gradle</a></li>
</ul>
|
sbt|gitlab-ci|artifactory|python-wheel|jfrog
| 2 |
1,903,219 | 59,971,592 |
Can't pre-define dtype when reading data
|
<p>I am reading a pipe delimited file without headings into Pandas and I am using Pandas version 0.24.2. And this is public data so no worries around confidentiality.</p>
<p>The data looks like:</p>
<pre><code>999778247820|R|JPMORGAN CHASE BANK, NATIONAL ASSOCIATION|7.375|113000|360|02/2001|04/2001|95|95|1|52|665|Y|P|SF|1|P|IL|601|30|FRM||1|N
999783196683|R|OTHER|7.25|59000|360|01/2001|04/2001|97|97|2|43|682|Y|P|PU|1|P|HI|967|30|FRM|676|1|N
999783470376|C|BANK OF AMERICA, N.A.|7.875|110000|360|12/2000|02/2001|74|74|2|26|700|N|P|SF|1|P|NY|125||FRM|698||N
999786911479|C|BANK OF AMERICA, N.A.|7.5|57000|360|12/2000|02/2001|90|90|1|28|699|N|P|SF|1|P|TX|781|25|FRM||1|N
999786913710|R|JPMORGAN CHASE BANK, NA|7.125|114000|360|01/2001|04/2001|73|73|2|16|745|N|C|SF|1|P|WA|992||FRM|||N
999788833695|B|OTHER|9|50000|360|10/2000|12/2000|90|90|2|40|674|N|P|SF|2|I|WI|535|25|FRM|737|1|N
</code></pre>
<p>This is the code I am using:</p>
<pre class="lang-py prettyprint-override"><code>orig_files_fnma = glob.glob("/...1/Acquisition*.txt")
col_names = ["loan_id", "origination_channel","seller_name","original_interest_rate","original_upb","original_loan_term","origination_date","first_payment_date","original_ltv","original_cltv","number_of_borrowers","original_dti",
"borrower_fico_at_origination","first_time_home_buyer_indicator", "loan_purpose","property_type","number_of_units","occupancy_type","property_state","zip_code_short","primary_mortgage_insurance_percent",
"product_type","coborrower_fico_at_origination","mortgage_insurance_type","relocation_mortgage_indicator"]
col_type = {"loan_id": "object","origination_channel": "object","seller_name": "object","original_interest_rate": "float","original_upb": "float","original_loan_term": "int","origination_date": "object",
"first_payment_date": "object","original_ltv": "object","original_cltv": "object","number_of_borrowers": "int","original_dti": "float","borrower_fico_at_origination": "int",
"first_time_home_buyer_indicator": "object", "loan_purpose": "object","property_type": "object","number_of_units": "int","occupancy_type": "object","property_state": "object",
"zip_code_short": "object","primary_mortgage_insurance_percent": "float",
"product_type": "object","coborrower_fico_at_origination": "int","mortgage_insurance_type": "object","relocation_mortgage_indicator": "object"}
dfs = []
temp_df = []
for orig_files_fnma in orig_files_fnma:
temp_df = pd.read_csv(orig_files_fnma, sep = '|', header = None, names = col_names, dtype = col_type, index_col = None, parse_dates=True, verbose = True, engine='python')
dfs.append(temp_df)
</code></pre>
<p>Always getting the following errors:</p>
<pre class="lang-py prettyprint-override"><code>Filled 1 NA values in column original_ltv
Filled 52 NA values in column original_cltv
ValueError: Unable to convert column number_of_borrowers to type int
</code></pre>
<p>I do find out if I don't pre-define the dtype and .astype to change the data type after loading. But ask if possible that I can pre-define the data type first like the code above.</p>
<p>Also, I want to define the length of object for 20 length. What is the right code to do so?</p>
<p>Thanks a lot!</p>
|
<p>I got a different error:</p>
<pre><code>ValueError: Unable to convert column coborrower_fico_at_origination to type int
</code></pre>
<p>import you import the data into Excel, you will see that there are 3 rows in this columns that are blank. The <code>int</code> type cannot handle blanks. You should change it to float, upon which blanks become <code>nan</code>:</p>
<pre><code>col_type = {..., "coborrower_fico_at_origination": "float", ...}
</code></pre>
<p>The command succeeded after that.</p>
|
python|pandas
| 0 |
1,903,220 | 60,096,436 |
Query all rows from DynamoDB using python
|
<p>As far as I went, there is very little information on how to retrieve all rows of a DynamoDB.</p>
<p>I used <code>table.scan()</code> But when using this method you have a limit, so you will not get all the items.</p>
<p>I tried <code>table.query()</code> But it says: <code>Either the KeyConditions or KeyConditionExpression parameter must be specified in the request.</code></p>
<p>Thanks a lot</p>
|
<p>The only way is to use table.scan() but you will need to add consistent read.</p>
<p>Scan uses eventually consistent reads when accessing the data in a table; therefore, the result set might not include the changes to data in the table immediately before the operation began. If you need a consistent copy of the data, as of the time that the Scan begins, you can set the ConsistentRead parameter to true . Here is a link to the documentation.
<a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.scan" rel="nofollow noreferrer">https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.scan</a></p>
<p>If LastEvaluatedKey is empty, then the "last page" of results has been processed and there is no more data to be retrieved.</p>
<p>If LastEvaluatedKey is not empty, it does not necessarily mean that there is more data in the result set. The only way to know when you have reached the end of the result set is when LastEvaluatedKey is empty.</p>
|
python|amazon-dynamodb
| 1 |
1,903,221 | 30,400,297 |
Django Not Recognizing Multiple Databases
|
<p>I'm trying to use multiple databases with my Django project but it is only recognizing the default one. In my settings.py file I have the following set:</p>
<pre><code>DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "primary",
"USER": "admin",
"PASSWORD": "password",
"HOST": "",
"PORT": "",
},
"deals": {
"ENGINE": 'django_mongodb_engine',
"NAME": "database",
"HOST": "HOSTNAME",
"PORT": "27017",
"USER": "",
"PASSWORD": "",
"SUPPORTS_TRANSACTIONS": False,
},
}
</code></pre>
<p>But when I try to run </p>
<pre><code>python manage.py syncdb --database=deals
</code></pre>
<p>or</p>
<pre><code>python manage.py inspectdb --database=deals
</code></pre>
<p>I am getting the following error:</p>
<pre><code>django.db.utils.ConnectionDoesNotExist: The connection deals doesn't exist
</code></pre>
<p>When I try to debug in /lib/python2.7/site-packages/django/db/utils.py I am seeing that only the default database is being recognized. I get the same error when I try to create a second local database.</p>
<p><strong>EDIT</strong>
I've updated my settings.py file according to the comments but still have the same issue.</p>
|
<p>Maybe the indentation? I checked it with my code, it looks ok. Or it does not support multiple Databases with MongoDB.</p>
|
python|django
| 0 |
1,903,222 | 30,469,445 |
Why am I getting TypeError: 'module' object is not callable in python?
|
<p>I'm creating a string that I an then use in a method that queries a mongodb collection. Eventually the dates will be from user input. Here's the relevant code and string:</p>
<pre><code>import pymongo
from pymongo import MongoClient
from datetime import datetime
import time
import datetime
start_yr = 2015
start_mnth = 2
start_day = 1
end_yr = 2015
end_mnth = 2
end_day = 28
# this is the line called in the error
created_at_string = { "created_at": {"$gte" : datetime(start_yr, start_mnth, start_day),"$lt" : datetime(end_yr, end_mnth, end_day)}}
</code></pre>
<p>The idea will be to use <code>created_at_string</code> as an argument in more complex query methods.</p>
<p>I'm getting:</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 218, in <module>
program.runProgram()
File "main.py", line 61, in runProgram
report.RcreateReport()
File "/filepath/report.py", line 95, in RcreateReport
created_at_string = { "created_at": {"$gte" : datetime(start_yr, start_mnth, start_day),"$lt" : datetime(end_yr, end_mnth, end_day)}}
TypeError: 'module' object is not callable
</code></pre>
<p>Why?</p>
|
<p>I've found your issue:</p>
<pre><code>from datetime import datetime
import time
import datetime
</code></pre>
<p>Let's look at this in order:</p>
<p>In your <code>globals</code>, you have something called <code>datetime</code>, a function. Then, you import <code>time</code>, a module object. Then, you import <code>datetime</code>, hence overwriting your <code>datetime</code> function. Here's an example:</p>
<pre><code>>>> from datetime import datetime
>>> datetime(2015, 05, 26)
datetime.datetime(2015, 5, 26, 0, 0)
>>> import datetime
>>> datetime(2015, 05, 26)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
datetime(2015, 05, 26)
TypeError: 'module' object is not callable
>>>
</code></pre>
<p>No matter what, even if you change the order, you will overwrite something, be it the function or module objects. So, just rename something:</p>
<pre><code>import datetime
import time
from datetime import datetime as dt
</code></pre>
|
python|mongodb|python-2.7|pymongo
| 5 |
1,903,223 | 67,159,066 |
Python intersection on list of dictionaries
|
<p>I have list of dict say :</p>
<pre><code> data:-[
{
"cat_nbr": 4,
"cat_name": "STORE",
"l_id": "15.8",
"size": 19,
"f_type": "EPIC",
"p_type": "single"
},
{
"cat_nbr": 4,
"cat_name": "STORE",
"l_id": "63.9",
"size": 192,
"f_type": "EPIC",
"p_type": "single"
},
{
"cat_nbr": 5,
"cat_name": "UN_STORE",
"l_id": "54.0",
"size": 191,
"f_type": "EPIC",
"p_type": "single"
}
</code></pre>
<p>Here i want to create a list based on cat_nbr and cat_name and append to existing list. I want to do intersection based on cat_nbr and cat_name, if same add to that list or elase create a new object My output should look like this:-</p>
<pre><code>"catalogs" :[
{
"cat_nbr" :4,
"cat_name" "STORE",
"flist" : [
{
"l_id": "15.8",
"size": 19,
"f_type": "EPIC",
"p_type": "single"
},
{
"l_id": "63.9",
"size": 192,
"f_type": "EPIC",
"p_type": "single"
}
] //flist closed for cat_nbr 4 and cat_name STORE
}, //cat_nbr 4 and cat_name STORE close
{
"cat_nbr" :5,
"cat_name" "UNSTORE",
"flist" : [
{
"l_id": "54.0",
"size": 191,
"f_type": "EPIC",
"p_type": "single"
}
] //flist closed for cat_nbr 5 and cat_name UNSTORE
] //catalogs closed
</code></pre>
<p>This is my code looks like:-</p>
<pre><code> def get_catalog_data(data):
catalog_result = []
for item in data:
catalog_dict = {}
catalog_dict['flist'] = get_flist(item)
catalog_result.append(catalog_dict)
//Logic to add in the same cat_nbr and cat_name
return catalog_result
</code></pre>
|
<p>Following @C Hetch answer on using a tuple as dict key, but using defaultdict as an alternative to pandas,</p>
<pre><code>from collections import defaultdict
catalogs = defaultdict(list)
for item in data:
catalogs[(item['cat_nbr'],item['cat_name'])].append({key:value for key,value in item.items() if key not in ['cat_nbr','cat_name']})
</code></pre>
<p>It doesn't completely answer your question but can lead you the way.</p>
|
python|python-3.x
| 0 |
1,903,224 | 42,669,263 |
If else statement , global name not defined
|
<pre><code>def vel(y,umax,r,Rmax):
vel_p=umax*(1-(r/Rmax)**2)
if r<50:
r=50-y
else:
r=y-50
return 'the value of velocity in cell is %r,%r,%r,%r'%(umax,r,Rmax,vel_p)
def main ():
y=(input('enter y'))
a=(input('enter the umax'))
#b=(input('enter the r'))
b=(r)
c=(input('enter the Rmax'))
print(vel(a,c,b,y))
main()
</code></pre>
<p>i do not understand where i should put r it gives me an error global variable r not defined</p>
|
<p>As already mentioned in the comments, try to use "good" (=readable) variable names since this helps to reduce confusion.</p>
<p>The conversion from string to float should be made robust against non-numerical input with <code>try</code>...<code>except</code>, so I put that in a separate function.</p>
<p>Usually you don't want a function to return a string with all your calculated values inserted, but the "raw" values. The printing of those values should normally be done somewhere else.</p>
<p>In the comments you mention you "need to get the value of r from y, if i do not put that in comments it is taking my value of r and will not calculate from the if r statement", but your function <code>vel()</code> uses r to calculate vel_p in the very first line. The variable r is an argument to the function, so it has to come from somewhere. Either you let the user input it like all the other values, or you have to define it somewhere else. If you do that globally, have a look at Vipin Chaudharys answer.</p>
<p>My suggestion, if you want the user to input r:</p>
<pre><code>def vel(y, u_max, r, r_max):
# You use the value of r here already!
vel_p=u_max*(1-(r/r_max)**2)
# Here you change r, if r is less than 50.
# You are using r again, before assigning a new value!
if r<50:
r=50-y
else:
r=y-50
# I use the preferred .format() function with explicit field names
# \ is used to do a line-break for readability
return 'The value of velocity in cell is umax: {value_u_max}, \
r: {value_r}, Rmax: {value_r_max}, vel_p: {value_vel_p}.'.format(
value_u_max=u_max, value_r=r,value_r_max=r_max, value_vel_p=vel_p)
# Helper function to sanitize user input
def numberinput(text='? '):
while True:
try:
number=float(input(text))
# return breaks the loop
return number
except ValueError:
print('Input error. Please enter a number!')
def main():
y=numberinput('Enter y: ')
u_max=numberinput('Enter the umax: ')
r=numberinput('Enter the r: ')
r_max=numberinput('Enter the Rmax: ')
print(vel(y, u_max, r, r_max))
main()
</code></pre>
<p>Notice, that the input value of r is used to do the calculation. Then it is changed depending on y, and the new value gets printed.</p>
|
python|if-statement|global-variables
| 0 |
1,903,225 | 66,693,195 |
How to debug a recursively called function?
|
<p>I am trying to write a function which searches for a key in an arbitrarily deep nested <code>dict</code> and returns its value(s) together with the path(s) of ancestor keys -</p>
<pre><code># find_key.py
def find_key(key, targ, path=[]):
""" Search an aribitarily deep nested dict `targ` for key `key`.
Return its value(s) together with the path(s) of ancestor keys.
"""
if key == targ:
yield v, path
if isinstance(targ, dict):
for k, v in targ.items():
if k == key:
yield v, path
else:
find_key(key, v, path.append(k))
path.pop()
# test code
targ_1 = {'a': 1, 'b': {'b': 2, 'c': 3}, 'd': {'e': {'f': 4}}}
tests = {'test_a': {'key' : 'a', 'targ': targ_1, 'expect': [(1, [])]},
'test_b': {'key' : 'b', 'targ': targ_1, 'expect': [({'b': 2, 'c': 3}, []), (2, ['b'])]},
'test_c': {'key' : 'c', 'targ': targ_1, 'expect': [(3, ['b'])]},
'test_d': {'key' : 'd', 'targ': targ_1, 'expect': [({'e': {'f': 4}}, [])]},
'test_e': {'key' : 'e', 'targ': targ_1, 'expect': [({'f': 4}, ['d'])]},
'test_f': {'key' : 'f', 'targ': targ_1, 'expect': [(4, ['d', 'e'])]}}
for k, v in tests.items():
if list(find_key(v['key'], v['targ'])) == v['expect']:
print(k, 'OK')
else:
print(k, 'actual:', list(find_key(v['key'], v['targ'])))
print(k, 'expected:', v['expect'])
</code></pre>
<p>Executing the code shows that many test cases failed -</p>
<pre><code>(3.8) $ python find_key.py
test_a OK
test_b actual: [({'b': 2, 'c': 3}, [])]
test_b expected: [({'b': 2, 'c': 3}, []), (2, ['b'])]
test_c actual: []
test_c expected: [(3, ['b'])]
test_d OK
test_e actual: []
test_e expected: [({'f': 4}, ['d'])]
test_f actual: []
test_f expected: [(4, ['d', 'e'])]
</code></pre>
<p>I suspect the problem lies in the recursive call <code>find_key</code> so I inserted a <code>breakpoint()</code> above the call and re-executed the file -</p>
<pre><code>(3.8) $ python find_key.py
> find_key.py(15)find_key()
-> find_key(key, v, path.append(k))
(Pdb) s
--Call--
> find_key.py(1)find_key()
-> def find_key(key, targ, path=None):
(Pdb) s
GeneratorExit
> find_key.py(1)find_key()
-> def find_key(key, targ, path=None):
(Pdb) s
--Return--
> find_key.py(1)find_key()->None
-> def find_key(key, targ, path=None):
(Pdb) s
> find_key.py(16)find_key()
-> path.pop()
(Pdb)
</code></pre>
<p>As you can see, Pdb does not step into the recursively called <code>find_key</code> but instead issues messages <code>GeneratorExit</code> and <code>--Return--</code>. How can I debug this issue?</p>
|
<p><strong>human brain debugging</strong></p>
<pre class="lang-py prettyprint-override"><code># find_key.py
def find_key(key, targ, path=[]):
""" Search an aribitarily deep nested dict `targ` for key `key`.
Return its value(s) together with the path(s) of ancestor keys.
"""
if key == targ:
yield v, path
if isinstance(targ, dict):
for k, v in targ.items():
if k == key:
yield v, path
else:
find_key(key, v, path.append(k))
path.pop()
</code></pre>
<pre class="lang-py prettyprint-override"><code>targ_1 = {'a': 1, 'b': {'b': 2, 'c': 3}, 'd': {'e': {'f': 4}}}
list(find_key("b", targ_1))
</code></pre>
<p>Let's simply evaluate the program using our human brain evaluator -</p>
<pre class="lang-py prettyprint-override"><code>key = "b"
targ = {'a': 1, 'b': {'b': 2, 'c': 3}, 'd': {'e': {'f': 4}}}
path = []
# if key == targ:
# yield v, path
if isinstance(targ, dict):
for k, v in targ.items():
# ("a", 1)
# ("b", {'b': 2, 'c': 3})
# ("d", {'e': {'f': 4}})
k = "a"
v = 1
# if k == key:
# yield v, path
else:
find_key(key, v, path.append(k)) # path = ["a"]
path.pop() # path = []
</code></pre>
<p>In the first iteration of the <code>for</code> loop, <code>k</code> is not equal to <code>key</code> so we run the <code>else</code> branch of the program. <code>find_key</code> returns a generator, but we don't do anything with it. Ie, no <code>return</code> or <code>yield from</code> is used. So whatever it does, we can just ignore it entirely as it won't show up in the output of our function. To understand what I mean by that, consider the following example -</p>
<pre class="lang-py prettyprint-override"><code>def foo():
1+10 # missing yield or return
foo()
</code></pre>
<pre class="lang-py prettyprint-override"><code>None
</code></pre>
<p>In the program above, <code>foo</code> will evaluate <code>1+10</code> but nothing happens with it, so it is ignored. This is the same as calling a function like <code>find_key</code> without using its return value - python will evaluate it but the result is immediate discarded. Let's move onto the second iteration now -</p>
<pre class="lang-py prettyprint-override"><code>key = "b"
targ = {'a': 1, 'b': {'b': 2, 'c': 3}, 'd': {'e': {'f': 4}}}
path = []
# if key == targ:
# yield v, path
if isinstance(targ, dict):
for k, v in targ.items():
# ("a", 1)
# ("b", {'b': 2, 'c': 3})
# ("d", {'e': {'f': 4}})
k = "b"
v = {'b': 2, 'c': 3}
if k == key:
yield v, path # ({'b': 2, 'c': 3}, [])
# else:
# find_key(key, v, path.append(k)) # path = ["a"]
# path.pop() # path = []
</code></pre>
<p>Above, we see the second iteration of the <code>for</code> loop. Here <code>k == key</code>, so now we <code>yield</code>. Note because you use the <code>else</code> keyword, we won't recur <code>find_key</code>. That means there is no attempt to find additional <code>key = "b"</code> values in <code>v</code>.</p>
<pre class="lang-py prettyprint-override"><code>key = "b"
targ = {'a': 1, 'b': {'b': 2, 'c': 3}, 'd': {'e': {'f': 4}}}
path = []
# if key == targ:
# yield v, path
if isinstance(targ, dict):
for k, v in targ.items():
# ("a", 1)
# ("b", {'b': 2, 'c': 3})
# ("d", {'e': {'f': 4}})
k = "d"
v = {'e': {'f': 4}}
# if k == key:
# yield v, path
else:
find_key(key, v, path.append(k)) # path = ["d"]
path.pop() # path = []
</code></pre>
<p>In the third iteration of the <code>for</code> loop, it is just the same as the first. <code>k</code> is not equal to <code>key</code> and so <code>find_key</code> is called and the result is ignored.</p>
<p>The output is simple to determine. The second iteration where <code>k == "b"</code> is the only output from our function. Since you wrap the <code>find_key</code> call in <code>list(...)</code> this is the only result we will see in the list -</p>
<pre class="lang-py prettyprint-override"><code>[({'b': 2, 'c': 3}, [])]
</code></pre>
<p><strong>fixing the problem</strong></p>
<p>Here are the things I noticed -</p>
<ol>
<li>You are missing <code>yield from</code> before the recursive call to <code>find_key</code>.</li>
<li>The conditional logic can be simplified</li>
<li>Using <code>else</code> prevents recursion on values, <code>v</code>, where <code>k == key</code></li>
<li>Avoiding mutation <code>.append</code> and <code>.pop</code> makes reasoning about the algorithm easier</li>
</ol>
<pre class="lang-py prettyprint-override"><code>def find_key(key, targ, path = []):
""" Search an aribitarily deep nested dict `targ` for key `key`.
Return its value(s) together with the path(s) of ancestor keys.
"""
if isinstance(targ, dict):
for (k,v) in targ.items():
if k == key:
yield (v, path)
yield from find_key(key, v, [*path, k]) # <- no else, yield from
</code></pre>
<pre class="lang-py prettyprint-override"><code>test_a OK
test_b OK
test_c OK
test_d OK
test_e OK
test_f OK
</code></pre>
<p><strong>path param</strong></p>
<p>You have the option to remove the <code>path</code> parameter from <code>find_key</code> signature as well -</p>
<pre class="lang-py prettyprint-override"><code># find_key.py
def find_key(key, targ): # <- no path arg
""" Search an aribitarily deep nested dict `targ` for key `key`.
Return its value(s) together with the path(s) of ancestor keys.
"""
if isinstance(targ, dict):
for (k,v) in targ.items():
if k == key:
yield (v, []) # <- empty path
for (v, path) in find_key(key, v): # <- get path from recursive result
yield (v, [k, *path]) # <- prepend path
</code></pre>
<p><strong>direct ancestor</strong></p>
<p>Finally I think it's odd that the direct ancestor doesn't appear in the result. Ie,</p>
<pre class="lang-py prettyprint-override"><code>list(find_key("a", {"a":1}))
</code></pre>
<pre class="lang-py prettyprint-override"><code>[(1, [])]
</code></pre>
<p>According to the result above, the path to <code>1</code> is empty, <code>[]</code>. I would expect the result to be <code>[(1, ["a"])]</code>. Ie, <em>the path to <code>1</code> is <code>targ["a"]</code></em>. This is an easy change -</p>
<pre class="lang-py prettyprint-override"><code># find_key.py
def find_key(key, targ):
""" Search an aribitarily deep nested dict `targ` for key `key`.
Return its value(s) together with the path(s) of ancestor keys.
"""
if isinstance(targ, dict):
for (k,v) in targ.items():
if k == key:
yield (v, [k]) # <- base path
for (v, path) in find_key(key, v):
yield (v, [k, *path])
</code></pre>
<pre class="lang-py prettyprint-override"><code>list(find_key("b", targ_1))
</code></pre>
<p><em>The path to <code>{'b': 2, 'c': 3}</code> is <code>targ["b"]</code></em><br />
<em>The path to <code>2</code> is <code>targ["b"]["b"]</code></em></p>
<pre class="lang-py prettyprint-override"><code>[({'b': 2, 'c': 3}, ['b']), (2, ['b', 'b'])]
</code></pre>
|
python|python-3.x|debugging|recursion
| 1 |
1,903,226 | 72,373,873 |
How to use Optuna to determine optimum of a parameter set without an objective function
|
<p>I want to use <a href="https://optuna.org" rel="nofollow noreferrer">Optuna</a> to determine an optimum of a following data set:</p>
<p><a href="https://i.stack.imgur.com/V10Lw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V10Lw.png" alt="img" /></a></p>
<p>All these parameters are used to find the optimal value in column optimum. The clou now is that these optimum values are not known until a device uses the parameters to run at these settings and bring up this specific optimum value at these parameters.
My problem is that I don't know how to realize this with Optuna. I had a look the tutorials but couldn't figure out which matches my task?</p>
<p>On <a href="https://optuna.readthedocs.io/en/stable/tutorial/20_recipes/009_ask_and_tell.html#apply-optuna-to-an-existing-optimization-problem-with-minimum-modifications" rel="nofollow noreferrer">https://optuna.readthedocs.io/en/stable/tutorial/20_recipes/009_ask_and_tell.html#apply-optuna-to-an-existing-optimization-problem-with-minimum-modifications</a> I've seen <code>You can apply Optuna’s hyperparameter optimization to your original code without an objective function.</code></p>
<p>But I can't figure out how to adapt it to my task.</p>
|
<p>It seems like your data can be approached by multiple regression. You can use for example the <a href="https://xgboost.readthedocs.io/en/stable/" rel="nofollow noreferrer">xboost</a> library to find the parameter coefficients to approximate your optimum values. Now the xgboost output can be optimized by optimizing its parameters too. You can then use optuna to optimize the parameters of xgboost.</p>
|
python|optuna
| 1 |
1,903,227 | 65,583,162 |
Translating Python API call to NodeJS Axios api call - how do I format it correctly?
|
<p>I'm getting a 400 error and <code>isAxiosError: true</code>. I think the problem is the auth line is not formatted correctly, or I'm not quite understanding how params work in axios and what's needed by the api? What am I doing wrong in my translating of python to Axios/JS?
Here's the <a href="http://api.voilanorbert.com/2018-01-08/#search-endpoint-post" rel="nofollow noreferrer">Voila Norbert API documentation</a>.</p>
<p>Here's my Axios api call.</p>
<pre><code>axios.post('https://api.voilanorbert.com/2018-01-08/search/name', {
params: {
auth: {any_string: API_KEY},
data: {
domain: 'amazon.com',
name: 'Jeff Bezos'
}
}
})
</code></pre>
<p>Here's the python version:</p>
<pre><code>API_TOKEN = 'abcde'
req = requests.post(
'https://api.voilanorbert.com/2018-01-08/search/name',
auth=('any_string', API_TOKEN),
data = {
'name': 'Cyril Nicodeme',
'domain': 'reflectiv.net'
}
)
</code></pre>
|
<p>According to their documentation, <a href="https://github.com/axios/axios" rel="nofollow noreferrer">https://github.com/axios/axios</a>, you need to give <code>auth</code> as a separate field, not inside <code>params</code>:</p>
<pre><code>axios.post('https://api.voilanorbert.com/2018-01-08/search/name', {
auth: {
username: 'any_string',
password: API_KEY
},
data: {
domain: 'amazon.com',
name: 'Jeff Bezos'
}
})
</code></pre>
<p>Updated: removed the nesting of <code>data</code> in <code>params</code>. They should be sent as POST body, not URL params.</p>
|
javascript|python|node.js|axios
| 1 |
1,903,228 | 3,593,475 |
How do I yield a pre-unpacked list?
|
<p>I have a list that is created within an <code>itertools.groupby</code> operation:</p>
<pre><code>def yield_unpacked_list():
for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):
subset_of_grp = list(item[2] for item in list(grp))
yield key, subset_of_grp
</code></pre>
<p>If, for example, <code>subset_of_grp</code> turns out to be <code>[1, 2, 3, 4]</code> and <code>[5, 6, 7, 8]</code>:</p>
<pre><code>for m in yield_unpacked_list():
print m
</code></pre>
<p>would print out:</p>
<pre><code>('first_key', [1, 2, 3, 4])
('second_key', [5, 6, 7, 8])
</code></pre>
<p>Now, going back to my function definition. Obviously the following is a syntax error (the <code>*</code> operator):</p>
<pre><code>def yield_unpacked_list():
for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]):
subset_of_grp = list(item[2] for item in list(grp))
yield key, *subset_of_grp
</code></pre>
<p>I want the following result for the <strong>same</strong> <code>print</code> loop to be without the <code>[list]</code> brackets:</p>
<pre><code>('first_key', 1, 2, 3, 4)
('second_key', 5, 6, 7, 8)
</code></pre>
<p>Note that <code>print</code> is only for illustrative purposes here. I have other functions that would benefit from the simplified <code>tuple</code> structure.</p>
|
<p><code>yield (key,) + tuple(subset_of_grp)</code></p>
|
python|group-by|yield|itertools|iterable-unpacking
| 5 |
1,903,229 | 50,627,630 |
pandas data format to preserve DateTimeIndex
|
<p>I do a lot of work with data that has DateTime indexes and multi-indexes. Saving and reading as a .csv is tedious because every time I have to reset_index and name it "date" then when I read again, I have to convert the date back to a datetime and set the index. What format will help me avoid this? I'd prefer something open source - for instance I think SAS and Stata will do this, but they are proprietary. </p>
|
<p>feather was made for this:
<a href="https://github.com/wesm/feather" rel="nofollow noreferrer">https://github.com/wesm/feather</a></p>
<blockquote>
<p>Feather provides binary columnar serialization for data frames. It is
designed to make reading and writing data frames efficient, and to
make sharing data across data analysis languages easy. This initial
version comes with bindings for python (written by Wes McKinney) and R
(written by Hadley Wickham).</p>
<p>Feather uses the Apache Arrow columnar memory specification to
represent binary data on disk. This makes read and write operations
very fast. This is particularly important for encoding null/NA values
and variable-length types like UTF8 strings.</p>
<p>Feather is a part of the broader Apache Arrow project. Feather defines
its own simplified schemas and metadata for on-disk representation.</p>
<p>Feather currently supports the following column types:</p>
<p>A wide range of numeric types (int8, int16, int32, int64, uint8,
uint16, uint32, uint64, float, double). Logical/boolean values. Dates,
times, and timestamps. Factors/categorical variables that have fixed
set of possible values. UTF-8 encoded strings. Arbitrary binary data.</p>
</blockquote>
|
python|pandas|datetime|file-format
| 3 |
1,903,230 | 61,291,795 |
Detecting borders of a page on a table and then "refocus"
|
<p>I have the following picture and I would like to detect the border of the page and then to refocus to see "only" the page. How can I start to code this with opencv3 and Python 3 ?</p>
<p><a href="https://i.stack.imgur.com/6IESI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6IESI.jpg" alt="enter image description here"></a></p>
|
<p>You can simply use thresholding methods to seperate the paper from background. To demonstrate:</p>
<p>Read image and convert to gray.</p>
<pre><code>image = cv2.imread("page.jpg")
gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
</code></pre>
<p>check histogram to choose threshold values. More <a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_histograms/py_histogram_begins/py_histogram_begins.html" rel="nofollow noreferrer">here</a></p>
<pre><code>color = ('b','g','r')
fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(1,2,1)
ax.imshow(image)
ax1 = fig.add_subplot(1,2,2)
for i,col in enumerate(color):
histogram = cv2.calcHist([image],[i],None,[256],[0,256])
ax1.plot(histogram,color = col)
ax1.set_xlim([0,256])
</code></pre>
<p>Use blur to get rid of the notebook's details.</p>
<pre><code>blurred_gray_image = cv2.blur(gray_image,(21,21))
</code></pre>
<p>Do <a href="https://en.wikipedia.org/wiki/Thresholding_(image_processing)" rel="nofollow noreferrer">thresholding</a>. Using values which we got from the histogram.</p>
<pre><code>_,thresholded_blurry_image = cv2.threshold(blurred_gray_image,165,255,cv2.THRESH_BINARY)
</code></pre>
<p>Detect <a href="https://docs.opencv.org/3.4/d4/d73/tutorial_py_contours_begin.html" rel="nofollow noreferrer">contours</a> (which are undivided, closed shapes).</p>
<pre><code>contours, hierarchy = cv2.findContours(thresholded_blurry_image,
cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
</code></pre>
<p>Draw the biggest contour's outline to the copy of the original image if there are any contours.<a href="https://stackoverflow.com/questions/44588279/find-and-draw-the-largest-contour-in-opencv-on-a-specific-color-python">Source</a> post for finding the biggest contour.</p>
<pre><code>output = image.copy()
if len(contours) != 0:
c = max(contours, key = cv2.contourArea)
# coordinates of the contour
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(output,(x,y),(x+w,y+h),(0,255,0),2)
</code></pre>
<p>Show the result</p>
<pre><code>output = cv2.cvtColor(output,cv2.COLOR_BGR2RGB)
plt.imshow(output)
</code></pre>
<p><a href="https://i.stack.imgur.com/J35DH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J35DH.png" alt="Output"></a></p>
<p>You can use cv2.imwrite() function to save the image.
Hope this answer satisfies your question. But be aware that this method won't always work because we evaluate the histogram ourselves and pick the thresholding values by hand. If you want to take a more general approach try <code>adaptive thresholding</code> or evaluate histogram values with help of an algorithm. Best of luck.</p>
|
python-3.x|opencv3.0
| 2 |
1,903,231 | 61,473,713 |
Optimizing a function within a given range in scipy
|
<p>I have been trying to get the minimum for a function of a single variable. The function is: </p>
<pre><code>sym.sqrt((x+6)**2 + 25) + sym.sqrt((x-6)**2 - 121)
</code></pre>
<p>The function's derivative (which is (x - 6)/sym.sqrt((x - 6)**2 - 121) + (x + 6)/sym.sqrt((x + 6)**2 + 25)) blows up for x equal to -5 ad becomes complex for x greater than that (for example, -4) but less than 18 (which we can ignore for simplicity here), due to the first term. Therefore, I wrote the code to only evaluate the function for x between -6 and -10 (by inspection, I could see that the minimum was around -8.6, so I chose -10): </p>
<pre><code>def h(x):
for x in np.arange(-10,-5):
sym.sqrt((x+6)**2 + 25) + sym.sqrt((x-6)**2 - 121)
result = optimize.minimize_scalar(h,bounds=(-10,-5))
x_min = result.x
print(x_min)
</code></pre>
<p>Unfortunately, I got this error: </p>
<p>TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''</p>
<p>Can someone help me with this issue? </p>
<p>Regards, </p>
<p>Prasannaa </p>
|
<p>I don't think numpy and sympy play well together unless you <code>lambdify</code> your sympy equation. And I'm not sure with <code>NaN</code> values either, which appear to be in your equation.</p>
<p>You could try it numerically. When plotting your functions I found no minimum in the range, but there was a maximum in the derivative:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import argrelmax
x = np.linspace(-10, -6, 256) # generate x range of interest
y = np.sqrt((x+6)**2 + 25) + np.sqrt((x-6)**2 - 121)
dydx = (x - 6)/np.sqrt((x - 6)**2 - 121) + (x + 6)/np.sqrt((x + 6)**2 + 25)
maximum, = argrelmax(dydx) # returns index of maximum
x[maximum]
>>> -8.50980392
# plot it
plt.plot(x, y)
ax = plt.gca().twinx() # make twin axes so can see both y and dydx
ax.plot(x, dydx, 'tab:orange')
ax.plot(x[maximum], dydx[maximum], 'r.')
</code></pre>
<p><a href="https://i.stack.imgur.com/HJOeD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HJOeD.png" alt="plot of code above with maximum identified"></a></p>
|
python|function|optimization|scipy|minima
| 0 |
1,903,232 | 57,984,830 |
Trying to specify command line arguments and can't figure it out - not entirely sure what 'dest' and 'store' do in optparse
|
<p>So I'm trying to get my program to do take the command line arguments and use it in my script. I read <code>argparse</code> and the <code>optparse</code> documentation and I'm still lost.
What I'm trying to do is have my code execute this on the command line:</p>
<pre><code>./program <-p port> <-s> [required1] [required2]
</code></pre>
<p>The -p is optional, and I want to make the port a variable in my script, like so:</p>
<pre><code>server_address = ('some server name', **port**)
</code></pre>
<p>I thought that that's what <code>store</code> and <code>dest</code> would do... as in <code>store</code> would take the <code>port</code> argument and <code>dest</code> would be the variable name and I could call it like <code>program.port</code>. It doesn't work this way, however, and I can't find or decipher explanations for what exactly store and dest do.</p>
<p>I'm new to Python, so this might not be a well-formed question. </p>
|
<p>so, following the documentation:</p>
<ol>
<li>You create a parser </li>
</ol>
<pre class="lang-py prettyprint-override"><code>import argparse
parser = argparse.ArgumentParser(description='Some helpful text about what your function does')
</code></pre>
<ol start="2">
<li>You add arguments, optional ones have '-'s before hand, see below</li>
</ol>
<pre class="lang-py prettyprint-override"><code>parser.add_argument('-p', '--port', type=int, default=0, help='port')
parser.add_argument('-s', help='I don\'t know what this is')
parser.add_argument('required_1') # Note the lack of dashes
parser.add_argument('required_2')
</code></pre>
<ol start="3">
<li>You need to parse the arguments with a function call</li>
</ol>
<pre class="lang-py prettyprint-override"><code>args = parser.parse_args()
</code></pre>
<ol start="4">
<li>This creates a <a href="https://docs.python.org/3/library/argparse.html#the-namespace-object" rel="nofollow noreferrer">namespace object</a> which you can then access your variables from, see below</li>
</ol>
<pre class="lang-py prettyprint-override"><code>port = args.port
or
port = vars(args)['port']
req1 = args.required_1
req2 = args.required_2
etc...
</code></pre>
<p>For more information on namespace objects, checkout this <a href="https://stackoverflow.com/questions/20828277/what-is-a-namespace-object">question</a></p>
<p>Hopefully that helps.</p>
|
python|bash|parsing|command-line
| 1 |
1,903,233 | 56,114,974 |
problem when uploading file to google drive with its API with Python
|
<p>I am trying to upload a file to Google Drive using its Python API since I need to make a script to upload automatic backup copies from my server to Google Drive if user interaction. I have the following code which I have extracted from the Google Drive documentation.</p>
<p>Code of my Script:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient.http import MediaFileUpload
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
def main():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
file_metadata = {
'name' : 'report.csv',
'mimeType' : 'application/vnd.google-apps.spreadsheet'
}
media = MediaFileUpload('files/report.csv',
mimetype='text/csv',
resumable=True)
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print ("File ID: %s" % file.get("id"))
main()</code></pre>
</div>
</div>
</p>
<p>The errors that it shows me are these:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Traceback (most recent call last):
File "gdriveprueba.py", line 55, in <module>
resumable=True)
File "/home/servicioweb/.local/lib/python2.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/servicioweb/.local/lib/python2.7/site-packages/googleapiclient/http.py", line 554, in __init__
fd = open(self._filename, 'rb')
IOError: [Errno 2] No such file or directory: 'files/report.csv'</code></pre>
</div>
</div>
</p>
<p>the files directory create it manually in Google Drive but it keeps telling me that it can not find it, what could be happening that I can not see? I have 2 days in this and I have not been able to upload the files from the script.</p>
|
<p>You are confusing the parameters on line <code>50</code> and line <code>53</code>. The parameter <code>name</code> which goes in the <code>file_metadata</code> structure is referring to the <strong>name of the file on the google drive</strong>. The first parameter to the <code>MediaFileUpload</code> constructor refers to the <strong>path on the local drive</strong>. For your code to work this file needs to exist. Also you are referring to an undefined variable <code>drive_service</code> on line <code>56</code>. You can either redefine the variable <code>service</code>, which is defined in the main function, as a <a href="https://www.python-course.eu/python3_global_vs_local_variables.php" rel="nofollow noreferrer">global variable</a>, or move the code which requests the api upload (starting on line <code>49</code>) into the function <code>main</code>. Also <code>main</code> needs to be called first before your upload code to actually create the service object. </p>
<p>If you just want to upload this to the root of your drive, you can just create the file <code>files/report.csv</code>, relative to this file, and you will have the file <code>report.csv</code> created on the root of your drive.</p>
<p>To create the file <code>files/report.csv</code>, you need to find the <code>fileId</code> of the directory <code>files</code> on your google drive, and send that as a parameter to the <code>create</code> api call.</p>
<p>To find the <code>fileId</code> run this code:</p>
<pre><code>dirp = "files" # Name of directory to find.
parent_id = "" # The id we are looking for.
query = ("name='%s'" % (dirp))
resp = service.files().list(
q=query,
fields="files(id, name)",
pageToken=None).execute()
files = resp.get('files', [])
if len(files) > 0:
parent_id = files[0].get('id')
</code></pre>
<p>Now use the variable <code>parent_id</code> in the api request to create the file.</p>
<pre><code>media = MediaFileUpload('report.csv',
mimetype='text/csv',
resumable=True)
meta_data= { 'name': 'report.csv',
'mimeType' : 'application/vnd.google-apps.spreadsheet',
'parents': [parent_id] }
f = service.files().create(
body=meta_data,
media_body=media,
fields='id').execute()
if not f is None: print("[*] uploaded %s" % (f.get('id')))
</code></pre>
<p><a href="https://developers.google.com/drive/api/v3/reference/files/create" rel="nofollow noreferrer">Here</a> is more info on the parameters for the <code>create</code> function.</p>
<p>The working code would look like this:</p>
<pre><code>from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient.http import MediaFileUpload
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
service = None
def main():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
global service
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
main()
# Retrieve the parent ID of the files/ directory
dirp = "files" # Name of directory to find.
parent_id = "" # The id we are looking for.
query = ("name='%s'" % (dirp))
resp = service.files().list(
q=query,
fields="files(id, name)",
pageToken=None).execute()
files = resp.get('files', [])
# Create a file object for file 'report.csv' on your local drive.
media = MediaFileUpload('report.csv',
mimetype='text/csv',
resumable=True)
# Upload the file.
if len(files) > 0:
parent_id = files[0].get('id')
meta_data= { 'name': 'report.csv',
'parents': [parent_id],
'mimeType' : 'application/vnd.google-apps.spreadsheet' }
f = service.files().create(
body=meta_data,
media_body=media,
fields='id').execute()
if not f is None: print("[*] uploaded %s" % (f.get('id')))
else: print("The folder files/ does not exist on your drive.")
</code></pre>
|
python|google-drive-api
| 0 |
1,903,234 | 69,392,147 |
Can't execute shell script in snakemake
|
<p>I recently started using <code>snakemake</code> and would like to run a <code>shell</code> script in my snakefile. However, I'm having trouble accessing <code>input</code>, <code>output</code> and <code>params</code>. I would appreciate any advice!</p>
<p>Here the relevant code snippets:</p>
<ol>
<li>from my snakefile</li>
</ol>
<pre class="lang-py prettyprint-override"><code>rule ..:
input:
munged = 'results/munged.sumstats.gz'
output:
ldsc = 'results/ldsc.txt'
params:
mkdir = 'results/ldsc_results/',
ldsc_sumstats = '/resources/ldsc_sumstats/',
shell:
'scripts/run_gc.sh'
</code></pre>
<ol start="2">
<li>and the script:</li>
</ol>
<pre class="lang-sh prettyprint-override"><code>chmod 770 {input.munged}
mkdir -p {params.mkdir}
ldsc=$(ls {params.ldsc_sumstats})
for i in $ldsc; do
...
</code></pre>
<p>I get the following error message:</p>
<pre><code>...
chmod: cannot access '{input.munged}': No such file or directory
ls: cannot access '{params.ldsc_sumstats}': No such file or directory
...
</code></pre>
|
<p>The syntax of using <code>{}</code> statements applies only to shell scripts defined within <code>Snakefile</code>, while in the example you provide, the script is defined externally.</p>
<p>If you want to use the script as an external script you will need to pass the relevant arguments (and parse them inside the shell script). Otherwise, it should be possible to copy-paste the script content inside the <code>shell</code> directive and let snakemake substitute the <code>{}</code> variables.</p>
|
python|shell|snakemake
| 2 |
1,903,235 | 55,519,006 |
Find keyword and iterate through file to find the next keyword
|
<p>I am searching a file for a specific keyword. From there I want to search the previous lines for an additional keyword.
Ex: Search text for "source". Then search the previous 15 lines of text for the keyword "destination".
The problem is, the second keyword appears within about a 15-20 line range from the first keyword, so I can't just put lines[i-15] because it won't return the same result for each instance of finding the keyword "source".</p>
<p>I've tried setting a variable that will increment if the second keyword is not found in the line above so that it will keep iterating and searching but it through an error.</p>
<p>First attempt...</p>
<pre><code> keyword_2 ="destination
j =
if re.match(keyword_1, line):
lineafter = lines[i + j]
lineafter_split= lineafter.split(' ')
if value2 and cell_value in line:
if 'access-list' not in line:
if 'nat' not in line:
lineafter_2 = lines[i + 1]
if 'description' not in lineafter_2:
print(lineafter_2)
Second attempt ...
```keyword_1 ="source"
keyword_2 ="destination
j=1
for i, line in enumerate(lines):
if keyword_1 in line:
prev_line=lines[i - j]
for i in range(1,15):
if w in prev_line:
print(prev_line)
else:j= j+1
</code></pre>
|
<p>Okay , so what I understood is that you want to iterate through the text , and then look for the second Keyword prior to that.</p>
<p>However as I am unclear if you want to prevent the search from going too far , or if you want to look for the second keyword until there are no previous lines, I will give you a function that does both.</p>
<pre><code>def looking_for_keywords(lines, keyword_1, keyword_2, range = None):
for i,line in enumerate(lines):
if keyword_1 in line:
j=0
max = range if range else i
not_found = True
while j<max and not_found:
j+=1
not_found = not(keyword_2 in lines[i-j])
if not_found:
print('Not Found')
else:
print(f'Found first at {i} and second at {i-j}')
</code></pre>
<p>Note that your answer does not give the same result ,and will behave weirdly if <code>i <3</code> </p>
|
python-3.x|loops|iteration
| 1 |
1,903,236 | 57,590,423 |
Inserting 'Attribute' type (from python 2.7 ldap3 package) with unicode characters into MySQL db
|
<p>I'm writing script which takes data form Active Directory and puts it into MySQL database. </p>
<pre><code>tls = Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2)
server = Server(serverName, use_ssl=True, tls=tls)
c = Connection(server, authentication=SASL, sasl_mechanism=KERBEROS)
c.bind()
c.search(dc, filter, attributes=['Name'])
</code></pre>
<p>I'm encountering some problems with unicode characters. For example, i have attribute that contains 'Ł' letter.</p>
<pre><code>var = c.entries[0]['Name']
</code></pre>
<p>When i've been testing this code in interactive python mode, i realised few things:</p>
<pre><code>type(var)
var
str(var)
type(var.value)
var.value
str(var.value)
</code></pre>
<p>Those lines print the following results:</p>
<pre><code><class 'ldap3.abstract.attribute.Attribute'>
name: Ł
'\xc5\x81'
<type 'unicode'>
u'\0141'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0141' in position 0: ordinal not in range(128)
</code></pre>
<p>How to insert the 'Ł' char into the database instead of \u0141? I was trying encode/decode methods that i found in google solutions but nothing seems to work.</p>
|
<p>use decode() method before inserting it in database. it will store unicode instead of bytes.</p>
|
python|mysql|unicode|ldap|mariadb
| 0 |
1,903,237 | 42,344,403 |
In python3, how do I choose to encode in order to be able to read the page correctly
|
<p>I am trying to use the following command to get the page's source code</p>
<blockquote>
<p>requests.get("website").text</p>
</blockquote>
<p>But I get an error:</p>
<blockquote>
<p>UnicodeEncodeError: 'gbk' codec can't encode character '\xe6' in position 356: illegal multibyte sequence</p>
</blockquote>
<p>Then I tried to change the page code to utf-8</p>
<blockquote>
<p>requests.get("website").text.encode('utf-8')</p>
</blockquote>
<p>But in addition to English will become the following form</p>
<blockquote>
<p>\xe6°\xb8\xe4\xb9\x85\xe6\x8f\x90\xe4\xbe\x9b\xe5\x85\x8dè\xb4\xb9VPN\xe5\xb8\x90\xe5\x8f·\xe5\x92\x8c\xe5\x85\x8dè\xb4\xb</p>
</blockquote>
<p>How can I do?
Thank you for your help</p>
|
<p>You can query the encoding of the <code>requests.Response</code> object by accessing its <code>Response.content</code> attribute. </p>
<p>Whenever you call <code>requests.Response.text</code>, the response object uses <code>requests.Response.encoding</code> to decode the bytes.</p>
<p>This may, however, not always be the correct encoding, hence you sometimes have to set it manually by looking it up in the <code>content</code> attribute, since websites usually specify the encoding there, if it's not <code>utf-8</code> or similar (this is from experience, I'm not sure if this is actual standard behavior).</p>
<p><a href="http://docs.python-requests.org/en/master/user/quickstart/#response-content" rel="nofollow noreferrer">See more on <code>requests.Response</code> contents here</a> </p>
|
html|python-3.x|encode|html-encode
| 0 |
1,903,238 | 59,082,202 |
how to export data from python pandas with user defined message
|
<p>From the pandas data frame, I got the list of customer info and want to export it to an excel printing all the customer info like: </p>
<p>"This customer James"</p>
<p>"This customer Mark"</p>
<p>''''''''</p>
<p>''''''''</p>
<p>but am getting only 1 customer to excel instead of 10.</p>
<p>Below is the code i tried:</p>
<pre><code>info =
df['TABLE'].drop_duplicates().values.tolist()
for i in (Info):
excel_print= "This customer" ' ' +i
print(excel_print) ## I will get all 10 customers
for j in excel_print:
worksheet.write(1,1,excel_print)
</code></pre>
|
<p>If you want it in separated cells then you have to change first (or second) argument in <code>write()</code></p>
<p>I use <code>enumerate()</code> to have different values </p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('filename.xlsx')
worksheet1 = workbook.add_worksheet()
info = ['Adam','James', 'Mark']
for x, name in enumerate(info):
worksheet1.write(x, 0, "This customer " + name)
workbook.close()
</code></pre>
<p>If you want all in one cell then you have to create string with all text and then put it</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('filename.xlsx')
worksheet1 = workbook.add_worksheet()
info = ['Adam','James', 'Mark']
lines = []
for name in info:
lines.append("This customer " + name)
text = '\n'.join(lines)
worksheet1.write(0, 0, text)
workbook.close()
</code></pre>
|
python|pandas
| 2 |
1,903,239 | 54,118,823 |
Why can't I reference self.text_1 in the constructor from my kv file?
|
<p>I'm working on a simple Kivy Popup and I'm confused as to why I can't reference my class variable, 'self.text_1', from within the constructor of the Popup class, but I can do so with the variable 'self.title'.</p>
<p>First, I'll start with the ubiquitous, "I'm new to Python and Kivy, so perhaps I'm just missing something obvious, but I'm at a loss."</p>
<p>I've tried to find answers, but nothing so far has seemed to cover this topic, at least in a way that I can understand and draw the connection. Below is my problem and some simplified code for demonstration.</p>
<p>From within the kv file > Label widget > text, I can refer to 'text_1' from the CustomPopup class in my py file by using 'root.text_1' when the variable is placed outside of the constructor (either before or after), but I cannot do so when placed within. The 'self.title' variable is setup the exact same way as 'self.text_1', but I CAN get that value without issue.</p>
<p>If I un-comment this line, using 'root.text_1' in the kv file returns the correct value.</p>
<pre><code>class CustomPopup( Popup ):
# I can reference this text from the kv file using "root.text_1"
# text_1 = 'blah blah blah'
</code></pre>
<p>If instead I try to use 'self.text_1' from within the constructor, I get an Attribute error. However, I have no issues using the variable 'self.title' just below 'self.text_1'.</p>
<p>AttributeError: 'CustomPopup' object has no attribute 'text_1'</p>
<pre><code>def __init__( self, foo = 'bar' ):
super().__init__()
self.foo = foo
# I can't reference this text from the kv file using "root.text_1". Why?
self.text_1 = 'blah blah {foo}'.format( foo = self.foo )
# I can reference this text from the kv file using "root.title"
self.title = 'Title {foo}!'.format( foo = self.foo )
</code></pre>
<p>What is the difference here as to why I can get the value from one constructor variable, but not another with ostensibly similar syntax?</p>
<p>I'm using Python 3.7.1 (conda version : 4.5.12) and Kivy 1.10.1.</p>
<p>Python:</p>
<pre><code>import kivy
from kivy import Config
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.popup import Popup
kivy.require( '1.10.1' )
Config.set( 'graphics', 'fullscreen', 0 )
Config.set( 'graphics', 'height', 600 )
Config.set( 'graphics', 'width', 800 )
Config.set( 'graphics', 'resizable', 0 )
Config.set( 'kivy', 'exit_on_escape', 0 )
class CustomPopup( Popup ):
# I can reference this text from the kv file using "root.text_1"
# text_1 = 'blah blah blah'
def __init__( self, foo = 'bar' ):
super().__init__()
self.foo = foo
# I can't reference this text from the kv file using "root.title". Why?
self.text_1 = 'blah blah {foo}'.format( foo = self.foo )
# I can reference this text from the kv file using "root.title"
self.title = 'Title {foo}!'.format( foo = self.foo )
class CustomPopupTestApp( App ):
def build( self ):
return CustomPopup()
#Instantiate top-level/root widget and run it
if __name__ == "__main__":
CustomPopupTestApp().run()
</code></pre>
<p>kv:</p>
<pre><code><CustomPopup>:
id: popup
title: root.title
title_size: 30
title_align: 'center'
size_hint: 0.8, 0.8
auto_dismiss: False
pos_hint: { 'x' : 0.1 , 'y' : 0.1 }
GridLayout:
cols: 1
rows: 2
spacing: 15
padding: 15
Label:
id: content
text: root.text_1
font_size: 25
padding: 15, 25
size_hint_y: None
text_size: self.width, None
height: self.texture_size[ 1 ]
halign: 'center'
GridLayout:
cols: 2
rows: 1
AnchorLayout:
anchor_x : 'center'
anchor_y : 'bottom'
padding: 20
Button:
id: yes
text: 'Yes'
font_size: 30
size_hint: 0.8, 0.4
AnchorLayout:
anchor_x : 'center'
anchor_y : 'bottom'
padding: 20
Button:
id: no
text: 'No'
font_size: 30
size_hint: 0.8, 0.4
</code></pre>
<p>I would like to setup the text for my pop-up and use the str.format() method to insert a variable text element so that my message is tailored to the circumstances at hand, rather than generic or hard-coded with multiple options.</p>
<p>In this case, I pass an argument of 'foo' to the constructor, set the variable 'self.foo' equal to 'foo', then refer to 'self.foo' within my 'self.title' string and 'self.text_1' string.</p>
<p>If I place 'text_1' outside of the constructor, while I can retrieve the text value, since 'foo' hasn't been defined within that scope, I can't reference it to format my string.</p>
<p>I am interested in other solutions and any opportunity to learn, but ultimately, if there's a way to make this work without a workaround, that would be ideal.</p>
<p>Thanks in advance for any help. I've already learned a ton from everyone on this site.</p>
<p>P.S. - If I've done something "stupid" or offended your sensibilities, please provide a suggestion or correction rather than just berate me. Sometimes people get negative and it's (usually) not necessary.</p>
|
<p>Through research and testing, I've found my answers.</p>
<p>It turns out, firstly, that I wasn't calling 'self.title' like I thought I was. Therefore, I wasn't seeing different behavior for 'self.title' vs 'self.text_1'; I was seeing the same behavior. So, how then was I able to get my title to show, but not my content?</p>
<p>The Popup widget has inherent attributes of 'title' and 'content'. When I defined 'self.title' in CustomPopup(), I just provided that attribute's value. Even after removing the corresponding kv code 'title: root.title', the same value defined for 'self.title' was still displayed. This was the crucial moment the clued me in that I was distracted by the red herring of 'self.title' vs 'self.text_1'.</p>
<p>Once I ruled out the issue that I'm seeing different behavior for two otherwise identical lines of code, I looked deeper into how I was defining my CustomPopup class. That's when I came across this post that demonstrated how to handle this properly: <a href="https://stackoverflow.com/questions/49487672/kivy-how-to-get-class-variables-in-popup">Kivy: How to get class Variables in Popup</a>.</p>
<p>Long story... slightly less long... I updated my super method to inherit my 'text_1' StringProperty so that I could reference it from the CustomPopup object!</p>
<p>Here's the updated working solution:</p>
<p>Python:</p>
<pre><code>import kivy
from kivy import Config
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.properties import StringProperty
kivy.require( '1.10.1' )
Config.set( 'graphics', 'fullscreen', 0 )
Config.set( 'graphics', 'height', 600 )
Config.set( 'graphics', 'width', 800 )
Config.set( 'graphics', 'resizable', 0 )
Config.set( 'kivy', 'exit_on_escape', 0 )
class CustomPopup( Popup ):
text_1 = StringProperty( '' )
def __init__( self, foo = 'bar' ):
super( CustomPopup, self ).__init__()
self.foo = foo
self.text_1 = 'blah blah {foo}'.format( foo = self.foo )
self.title = 'Title {foo}!'.format( foo = self.foo )
class CustomPopupTestApp( App ):
def build( self ):
blarg = CustomPopup()
return blarg
#Instantiate top-level/root widget and run it
if __name__ == "__main__":
CustomPopupTestApp().run()
</code></pre>
<p>kv:</p>
<pre><code><CustomPopup>:
id: popup
# title: root.title
title_size: 30
title_align: 'center'
size_hint: 0.8, 0.8
auto_dismiss: False
pos_hint: { 'x' : 0.1 , 'y' : 0.1 }
GridLayout:
cols: 1
rows: 2
spacing: 15
padding: 15
Label:
id: content
text: root.text_1
font_size: 25
padding: 15, 25
size_hint_y: None
text_size: self.width, None
height: self.texture_size[ 1 ]
halign: 'center'
GridLayout:
cols: 2
rows: 1
AnchorLayout:
anchor_x : 'center'
anchor_y : 'bottom'
padding: 20
Button:
id: yes
text: 'Yes'
font_size: 30
size_hint: 0.8, 0.4
AnchorLayout:
anchor_x : 'center'
anchor_y : 'bottom'
padding: 20
Button:
id: no
text: 'No'
font_size: 30
size_hint: 0.8, 0.4
</code></pre>
<p>Notice that the kv file no longer refers to 'root.title', yet the title is still displayed properly.</p>
<p>The final product pictured in the link below is a Kivy popup with the structure/formatting defined in the kv file with the functionality and variable text defined in Python. It looks much cleaner to me than doing it all on the Python side.</p>
<p><a href="https://i.stack.imgur.com/bUQth.png" rel="nofollow noreferrer">CustomPopupTest Working Solution</a></p>
<p>I hope this helps someone else like so many other posts have helped me.</p>
|
python|python-3.x|kivy|kivy-language
| 1 |
1,903,240 | 58,204,573 |
UnboundLocalError: local variable 'di' referenced before assignment
|
<p>I know there's many questions about this problem, but after having been looking for a solution on the internet for a while nothing have work.
Here's my code:</p>
<pre><code>def posicio_relativ(x1,y1,z1,x2,y2,z2):
if x1<x2:
di='dreta'
if x1>x2:
di='esquerra'
if y1<y2:
ss='sobre'
if y1>y2:
ss='sota'
if z1<z2:
dd='davant'
if z1>z2:
dd='darrera'
return di, ss, dd
</code></pre>
<p>I'm a begginer in using python, so I would aprecciate any help or explaination.</p>
<p>Thank you in advanced!</p>
<p>P.D: sorry for my English, I'm from Spain!</p>
|
<p>You'll need to declare the values <code>di</code>, <code>ss</code>, and <code>dd</code> and initialise them as blank strings before your <code>if</code> statements. For example, if <code>x1 == x2</code> then <code>di</code> will never get initialised.</p>
<pre><code>def posicio_relativ(x1,y1,z1,x2,y2,z2):
di = ''
ss = ''
dd = ''
if x1<x2:
di='dreta'
if x1>x2:
di='esquerra'
if y1<y2:
ss='sobre'
if y1>y2:
ss='sota'
if z1<z2:
dd='davant'
if z1>z2:
dd='darrera'
return di, ss, dd
</code></pre>
|
python|variables|global
| 2 |
1,903,241 | 65,378,005 |
Is it possible to change the content in canvas.create_text by clicking on it just like in Entry?
|
<p>Following is my code,</p>
<pre><code>from tkinter import *
window = Tk()
canvas = Canvas(window,width=300, height=300, bd=0)
canvas.pack()
background = PhotoImage(file="Images/background.png") # can be any background image
canvas.create_image(300,300,image=background)
canvas_textbox = canvas.create_text(20, 70, text='TOUCH ME TO EDIT THIS TEXT', anchor=NW, fill="lime")
window.mainloop()
</code></pre>
<p>Is there any possibilities to change the <code>canvas.create_text</code> so that it can function just like <code>Entry</code> (gives the text cursor when user clicks on it for edit text) but looks like <code>canvas.create_text</code> only.</p>
|
<p><code>canvas_textbox = canvas.create_text()</code> will return an object id(numeric)</p>
<p>Firstly, Bind the canvas to the mouse. Then pass the mouse position to <code>closest=canvas.find_closest(x, y)</code>, which will return the item(s) id under the x,y position.</p>
<p>Now check whether the object id text is in the <code>closest</code>. If it is in the closest use <code>create_window</code> to place the <code>Entry</code> widget at the mouse position or the position f your choice.</p>
<p>Here is the code:</p>
<pre><code>from tkinter import *
from PIL import Image, ImageTk
def update(event):
canvas.delete('entry')
canvas.itemconfig(tagOrId='text', text=text_box.get())
def clicked(event):
closest = canvas.find_closest(event.x, event.y)# returns the closest item to x, y in the form of tuple
if 2 in closest:
canvas.itemconfig(tagOrId='text', text='')
canvas.create_window(event.x, event.y, window=text_box, tag='entry')
else:
print('No')
window = Tk()
canvas = Canvas(window,width=300, height=300, bd=0)
canvas.pack()
background = ImageTk.PhotoImage(Image.open(r"\path.jpg")) # can be any background image
canvas.create_image(300,300,image=background)
canvas_textbox = canvas.create_text(20, 70, text='TOUCH ME TO EDIT THIS TEXT', anchor=NW, fill="lime", tag='text')
text_box = Entry(window)
text_box.bind('<Return>', update)
print(canvas.find_all()) # returns all the items in canvas as tuple
canvas.bind('<Button>', clicked)
window.mainloop()
</code></pre>
<p>Or you may also try this:</p>
<pre><code>from tkinter import *
from PIL import Image, ImageTk
def update(event):
canvas.delete('entry')
canvas.itemconfig(tagOrId='text', text=text_box.get())
def clicked(event):
closest = canvas.find_closest(event.x, event.y)# returns the closest item to x, y in the form of tuple
x, y = canvas.coords(closest)
if canvas_textbox in closest:
canvas.itemconfig(tagOrId='text', text='')
canvas.create_window(x+100, y, window=text_box, tag='entry')
else:
print('No')
window = Tk()
canvas = Canvas(window,width=300, height=300, bd=0)
canvas.pack()
background = ImageTk.PhotoImage(Image.open(r"\image")) # can be any background image
canvas.create_image(300,300,image=background)
canvas_textbox = canvas.create_text(20, 70, text='TOUCH ME TO EDIT THIS TEXT', anchor=NW, fill="lime", tag='text')
text_box = Entry(window, borderwidth=0, highlightthickness=0)
text_box.insert(0, 'TOUCH ME TO EDIT THIS TEXT')
print(canvas.coords(2))
text_box.bind('<Return>', update)
print(canvas.find_all()) # returns all the items in canvas as tuple
canvas.bind('<Double-1>', clicked)
window.mainloop()
</code></pre>
<p>(double click on the text)</p>
|
python|python-3.x|tkinter|tkinter-canvas|tkinter-entry
| 2 |
1,903,242 | 45,388,499 |
remove element from xpath tree not working
|
<p>I have a problem removing elements from my xpath list.<br>
I am a rookie in Python and HTML scraping, so bear with me :)<br>
I've read that <code>nodes.getparent().remove(nodes)</code> should remove an element, but I can't even compile it.<br>
So it seems like I am not getting the element type that I need to be able to remove.<br>
I am able to call <code>nodes.getparent()</code> without problems, but not remove on that.</p>
<blockquote>
<p>Error: <br><br>
"TypeError: Argument 'element' has incorrect type (expected lxml.etree._Element, got lxml.etree._ElementUnicodeResult)"</p>
</blockquote>
<p>Best regards<br>
Jesper</p>
<pre class="lang-python prettyprint-override"><code>from lxml import html
import requests
headers = {'User-Agent': 'Fiddler', 'Host': 'bilmodel.dk'}
page = requests.get('https://bilmodel.dk/Sitemap/Biler', headers=headers)
tree = html.fromstring(page.content)
#This will create a list of car brands
CarBrands = tree.xpath('//*[@id="content"]/ul[1]//text()')
for nodes in CarBrands:
if nodes.find('\r\n\t\t\t\t') == 0:
print('Found it')
nodes.getparent().remove(nodes)
# Press Enter to exit window
#CarBrand = input('Write car brand:')
print(CarBrands)
</code></pre>
|
<blockquote>
<p><strong>Question</strong>: I am not getting the element type that I need to be able to remove</p>
</blockquote>
<p>The Element you want to Remove is a "<strong>special text node</strong>", instead of removing, clear it by assigning a Blank <code>''</code>. </p>
<p>For instance:</p>
<pre><code># Get all <li> inside <ul>[1]
CarBrands = tree.xpath('//*[@id="content"]/ul[1]/li')
# Iterate all <li> Nodes
for node in CarBrands:
# Findall <ul><li>...</li> ...
li_nodes = node.findall('./ul/li')
# Iterate all <li>
for li in li_nodes:
# Find the <a> inside <li>
a = li.find('./a')
# Clear "special text nodes"
a.tail = ''
print('a:{}'.format(etree.tostring(a)))
</code></pre>
<blockquote>
<p><strong>Output</strong>: </p>
<pre><code>a:b'<a href="/Biler/AC/Ace/">Ace</a>'
a:b'<a href="/Biler/AC/Cobra/">Cobra</a>'
</code></pre>
</blockquote>
<p><strong><em>Tested with Python: 3.4.2</em></strong></p>
|
python|xpath|lxml
| 0 |
1,903,243 | 28,679,750 |
Selecting Glyphs in Python Bokeh plots
|
<p>I have a Python Bokeh plot containing multiple lines, Is there a way I can interactively switch some of these lines on and off?</p>
<pre><code>p1.line(Time,Temp0,size=12,color=getcolor())
p1.line(Time,Temp1,size=12,color=getcolor())
p1.line(Time,Temp2,size=12,color=getcolor())
p1.line(Time,Temp3,size=12,color=getcolor())
....
show(p1)
</code></pre>
|
<p>I just came across <a href="https://stackoverflow.com/questions/42403834/how-do-i-select-data-points-based-with-a-rangeslider-in-bokeh">this problem myself in a similar scenario</a>. In my case, I also wanted to do other operations on it.</p>
<p>There are 2 possible approaches:</p>
<p>1.) Client-server approach</p>
<p>2.) Client only approach</p>
<hr>
<p><strong>1.) Client Server Approach ak Bokeh Server</strong></p>
<p>One way how you can achieve this interactivity is by using the bokeh server which you can read more about <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/server.html#userguide-server" rel="nofollow noreferrer">here</a>. I will describe this way in more detail since at this point, I am a bit more familiar with it.</p>
<p>Going by your example above, if I were to use the bokeh serve, I would first setup a ColumnDataSource like so:</p>
<pre><code>source = ColumnDataSource(data = dict(
time = Time,
temp0 = [],
temp1 = [],
temp2 = [],
temp3 = [],
)
</code></pre>
<p>Next I would <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html#userguide-interaction-widgets" rel="nofollow noreferrer">setup a widget</a> that allows you to toggle what temperatures to show:</p>
<pre><code>multi_select = MultiSelect(title="Option:", value=["Temp1"],
options=["Temp1", "Temp2", "Temp3"])
# Add an event listener on the python side.
multi_select.on_change('value', lambda attr, old, new: update())
</code></pre>
<p>Then I would define the update function like below. The purpose of the update function is to update the ColumnDataSource (which was previously empty) with values you want to populate in the graph now.</p>
<pre><code>def update():
"""This function will syncronize the server data object with
your browser data object. """
# Here I retrieve the value of selected elements from multi-select
selection_options = multi_select.options
selections = multi_select.value
for option in selection_options:
if option not in selections:
source.data[option] = []
else:
# I am assuming your temperatures are in a dataframe.
source.data[option] = df[option]
</code></pre>
<p>The last thing to do is to redefine how you plot your glyphs. Instead of drawing from lists, or dataframes, we will draw our data from a ColumnDataSource like so:</p>
<pre><code>p1.line("time","temp0", source=source, size=12,color=getcolor())
p1.line("time","temp1", source=source, size=12,color=getcolor())
p1.line("time","temp2", source=source, size=12,color=getcolor())
p1.line(Time,Temp3, source=source, size=12,color=getcolor())
</code></pre>
<p>So basically by controlling the content of the ColumnDataSource which is synchronized with the browser object, I can toggle whether data points are shown or not. You may or may not need to define multiple ColumnDataSources. Try it out this way first.</p>
<p><strong>2.) Client only approach ak Callbacks</strong></p>
<p>The approach above uses a client-server architecture. Another possible approach would be to do this all on the front-end. <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/callbacks.html#userguide-interaction-callbacks" rel="nofollow noreferrer">This link</a> shows how some simple interactions can be done completely on the browser side via various forms of callbacks.</p>
<p>Anyway, I hope this is helpful. Cheers!</p>
|
python|bokeh
| 3 |
1,903,244 | 28,585,367 |
Python Pandas: How I can determine the distribution of my dataset?
|
<p>This is my dataset with two columns of NS and count.</p>
<pre><code> NS count
0 ns18.dnsdhs.com. 1494
1 ns0.relaix.net. 1835
2 ns2.techlineindia.com. 383
3 ns2.microwebsys.com. 1263
4 ns2.holy-grail-body-transformation-program.com. 1
5 ns2.chavano.com. 1
6 ns1.x10host.ml. 17
7 ns1.amwebaz.info. 48
8 ns2.guacirachocolates.com.br. 1
9 ns1.clicktodollars.com. 2
</code></pre>
<p>Now I would like to see how many NSs have the same count by plotting it. My own guess is that I can use histogram to see that but I am not sure how. Can anyone help?</p>
|
<p>From your comment, I'm guessing your data table is actually much longer, and you want to see the distribution of name server <code>counts</code> (whatever count is here).</p>
<p>I think you should just be able to do this:</p>
<pre><code>df.hist(column="count")
</code></pre>
<p>And you'll get what you want. IF that is what you want.</p>
<p>pandas has decent documentation for all of it's functions though, and histograms are described <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.hist.html" rel="noreferrer">here</a>.</p>
<p>If you actually want to see "how many have the same count", rather than a representation of the disribution, then you'll either need to set the <code>bins</code> kwarg to be <code>df["count"].max()-df["count"].min()</code> - or do as you said and count the number of times you get each <code>count</code> and then create a bar chart.</p>
<p>Maybe something like:</p>
<pre><code>from collections import Counter
counts = Counter()
for count in df["count"]:
counts[count] += 1
print counts
</code></pre>
<p>An alternative, and cleaner approach, which i completely missed and wwii pointed out below, is just to use the standard constructor of <code>Counter</code>:</p>
<pre><code>count_counter = Counter(df['count'])
</code></pre>
|
python|pandas|plot|histogram
| 7 |
1,903,245 | 68,806,420 |
Pandas uptime to datetime with resets to uptime
|
<p>I have a main dataframe and several small dataframes (DF_0, DF_1, ...), each one have an uptime column.</p>
<p>DF_main:</p>
<pre><code> (some columns) uptime
0 . 90094
1 . 90154
2 . 90214
3 . 90274
4 . 90334
. . .
. . .
. . .
1178 . 160774
1179 . 160834
1180 . 160894
. . .
. . .
. . .
1200 . 34
1201 . 94
1202 . 154
1203 . 214
</code></pre>
<p>DF_0:</p>
<pre><code> (some columns) uptime
2 . 90094
25 . 90154
45 . 90214
23213 . 160834
23235 . 160894
23258 . 160954
25321 . 154
25359 . 214
</code></pre>
<p>Think these dataframes like a system log.</p>
<ol>
<li><strong>uptime</strong> column shows how many time passed since the system started.</li>
<li><strong>DF_main</strong>'s rows represent main events that occur every 60 seconds</li>
<li><strong>DF_0, DF_1, ...</strong> represents events that occurs alongside main events. But they don't occur everytime.</li>
</ol>
<p>The uptime of DF_main can start with any number and the value in the next row always adds +60 except sometimes the system can reset and next uptime value becomes "(any uptime value) mod 60" (as you can see in the 1200th row in DF_main). And when it resets, it resets for every dataframe.</p>
<p>I need to subtract the first uptime from all the values in the uptime column. But because of the resets in the uptime values, the subtracted values becomes negative.</p>
<p><strong>Basically I want to:</strong></p>
<ol>
<li>Change the first uptime of DF_main to 0 and increment next value by +60.</li>
<li>Negate all resets, changing the uptime values like no resets happened for every dataframe.</li>
</ol>
<p>This is quite easy to do if there was no system/uptime resets. But resets confused me.</p>
<p>I know the corresponding timestamp of the first event so if I can achieve this I'll know which event took place in which date and time by summing timestamp with uptime.</p>
<p>What I'm trying to get is like this:</p>
<p>DF_main:</p>
<pre><code> (some columns) uptime
0 . 0
1 . 60
2 . 120
3 . 180
4 . 240
. . .
. . .
. . .
1178 . 70680
1179 . 70740
1180 . 70800
. . .
. . .
. . .
1200 . 72000
1201 . 72060
1202 . 72120
</code></pre>
<p>DF_0:</p>
<pre><code>(some columns) uptime
. 0
. 60
. 120
. 70740
. 70800
. 70860
. 72060
. 72120
</code></pre>
<p>I've tried some variations of the code below to at least manage to achieve it with DF_0 but couldn't.</p>
<pre><code>first_uptime = int(float(DF_main.iloc[0]['uptime']))
DF_0['uptime'] = DF_0['uptime'].apply(lambda x: x - first_uptime).where(lambda x: x>0, 0)
</code></pre>
<p><strong>UPDATE:</strong> I did it using a for loop as much I didn't want to do it with iterating through the dataframe. If you can think of a solution wtihout a for loop, please let me know.</p>
<pre><code>for index, row in DT_0.iterrows():
if (row.uptime - first_uptime < 0):
first_uptime = row.uptime
DF_0.at[index, 'uptime'] = row.uptime - first_uptime
first_uptime = int(float(DF_main.iloc[0]['uptime']))
for index, row in DF_main.iterrows():
if (row.uptime - first_uptime < 0):
first_uptime = row.uptime
DF_main.at[index, 'uptime'] = row.uptime - first_uptime
</code></pre>
|
<p>Assuming a decrease in uptime is a sure indication of a reset, here is a general method to calculate cumulative uptime (ignoring resets and even when the logged values are irregular).</p>
<pre><code>import pandas as pd
def add_calc_uptime(df, t0=0):
# Determine when a reset occurred:
resets = df['uptime'].diff() < 0
# Make a new variable to denote each run between resets
df['run_id'] = resets.cumsum()
# Group results by run
uptime_by_run_id = df[['run_id', 'uptime']].groupby('run_id')
cum_uptimes_by_run = {}
for i, x in uptime_by_run_id:
# Calculate the uptime values for each run
cum_uptimes = x['uptime'].diff().cumsum()
# Replace NaN value in first row
cum_uptimes.iloc[0] = 0
# Add final time from previous run to current run
cum_uptimes = cum_uptimes + t0
cum_uptimes_by_run[i] = cum_uptimes
t0 = cum_uptimes.iloc[-1]
# Add results to dataframe
df['Uptime Calc'] = pd.concat(cum_uptimes_by_run.values())
return df
data = [90094, 90154, 90214, 90274, 90334, 34, 94, 154]
DF_main = pd.DataFrame(data, columns=['uptime'])
print(add_calc_uptime(DF_main))
data = [90094, 90154, 90214, 160834, 160894, 160954, 154, 214]
index = [2, 25, 45, 23213, 23235, 23258, 25321, 25359]
DF_0 = pd.DataFrame(data, index=index, columns=['uptime'])
print(add_calc_uptime(DF_0))
</code></pre>
<p>Output:</p>
<pre><code> uptime run_id Uptime Calc
0 90094 0 0.0
1 90154 0 60.0
2 90214 0 120.0
3 90274 0 180.0
4 90334 0 240.0
5 34 1 240.0
6 94 1 300.0
7 154 1 360.0
uptime run_id Uptime Calc
2 90094 0 0.0
25 90154 0 60.0
45 90214 0 120.0
23213 160834 0 70740.0
23235 160894 0 70800.0
23258 160954 0 70860.0
25321 154 1 70860.0
25359 214 1 70920.0
</code></pre>
<p>Note: This also assumes that the duration of resets is zero or if not, that a process did not continue to run after the last report before the reset started.</p>
|
python|pandas
| 0 |
1,903,246 | 68,643,407 |
Why Can't I use the varible name delclass?
|
<p>I'm making a calender using pyqt5, and it gives me this error when
I Wrote these lines of code: <code>from pyqt5 import QtCore, QtGui, QtWidgets, uic</code>, and <code>delclass = uic.loaduiType</code>.</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\hungy\Desktop\Mason Works\Python\Projects\Calender.py", line 7, in <module>
delclass = uic.loadUiType('Del_btn.ui')
File "C:\Users\hungy\AppData\Local\Programs\Python\Python39\lib\site-packages\PyQt5\uic\__init__.py", line 204, in loadUiType
exec(code_string.getvalue(), ui_globals)
File "<string>", line 5
def setupUi(self, del):
^
SyntaxError: invalid syntax
</code></pre>
<p>What's wrong with my code?
I tried Changing the name to <code>Delclass</code>, but that didn't work.
This is my code:</p>
<pre><code>import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
# defines the formclasses
calclass = uic.loadUiType("Calender.ui")[0]
addclass = uic.loadUiType('Add_btn.ui')
delclass = uic.loadUiType('Del_btn.ui')
editclass = uic.loadUiType('Edit_btn.ui')
# classes
class Add(QtWidgets.QMainWindow, addclass):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
# self.Namevalue = Name_Text.value
class Calender(QtWidgets.QMainWindow, calclass):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.Add.triggered.connect(self.add_clicked)
self.Delete.triggered.connect(self.del_clicked)
self.Close_Exit.triggered.connect(self.x_clicked)
def x_clicked(self):
self.close()
def del_clicked(self):
pass
def add_clicked(self):
pass
app = QtWidgets.QApplication(sys.argv)
Window = Calender()
Window.show()
app.exec_()
</code></pre>
<p><strong>.ui</strong></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>del</class>
<widget class="QDialog" name="del">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>355</width>
<height>106</height>
</rect>
</property>
<property name="windowTitle">
<string>Del</string>
</property>
<property name="sizeGripEnabled">
<bool>false</bool>
</property>
<widget class="QDialogButtonBox" name="OKCANCEL">
<property name="geometry">
<rect>
<x>-80</x>
<y>60</y>
<width>341</width>
<height>32</height>
</rect>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
<widget class="QPushButton" name="Why">
<property name="geometry">
<rect>
<x>10</x>
<y>10</y>
<width>93</width>
<height>28</height>
</rect>
</property>
<property name="text">
<string>Why:</string>
</property>
</widget>
<widget class="QPlainTextEdit" name="plainTextEdit">
<property name="geometry">
<rect>
<x>120</x>
<y>10</y>
<width>191</width>
<height>31</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections>
<connection>
<sender>OKCANCEL</sender>
<signal>accepted()</signal>
<receiver>del</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>OKCANCEL</sender>
<signal>rejected()</signal>
<receiver>del</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>
</code></pre>
|
<p>From the look of your code, you probably renamed the top level widget in Qt Designer as <code>del</code>.</p>
<p>While this doesn't represent a real problem from the Qt perspective, it can become such when using <code>uic</code> functions, which build a raw python file (or an "abstract" form of it) when using <code>loadUiType</code>.</p>
<p><code>uic</code> (and <code>pyuic</code>, which uses the same functions) creates functions and objects based on the object names of the UI. Among these, there are:</p>
<ul>
<li><code>def setupUi(self, <object name of the form>)</code>;</li>
<li><code>def retranslateUi(self, <object name of the form>)</code>;</li>
</ul>
<p>The result is that if you name <code>del</code> your top level object, the functions will be:</p>
<ul>
<li><code>def setupUi(self, del)</code>;</li>
<li><code>def retranslateUi(self, del)</code>;</li>
</ul>
<p>This will obviously cause an exception, since <code>del</code> cannot be used like that in python.</p>
<p>Be aware that the same is valid for all other python protected words:</p>
<ul>
<li><code>exec</code> (while this is not an issue anymore in recent python versions, it's still better to avoid it, similarly to <code>print</code>)</li>
<li><code>raise</code>, <code>assert</code></li>
<li><code>def</code>, <code>class</code></li>
<li><code>if</code>, <code>elif</code>, <code>else</code>, <code>not</code></li>
<li><code>for</code>, <code>while</code></li>
<li><code>continue</code>, <code>break</code></li>
<li><code>try</code>, <code>except</code>, <code>finally</code></li>
<li>etc...</li>
</ul>
<p>The solution (which is valid in <strong>any case</strong>) is to <em>carefully</em> choose object names: look for <em>descriptive</em> names, not short names, as they don't have any practical benefit.<br />
Instead of <code>del</code>, prefer <code>delButton</code> (or <code>del_button</code>, if you want to keep the standard Python style), or <code>deleteButton</code>.</p>
<p>Remember: the name reference (or object name in Qt) of an object should <strong>always</strong> allow you to tell <em>at a glance</em> what that object is and what it does.<br />
What does "del" do? Delete? Delete what? Is it a function or a variable? Is it a widget? If it's a widget, what kind of widget is it?</p>
<p>Reopen the UI file in Designer and change the name of the top level object accordingly, and also ensure that <strong>no</strong> other widget uses those protected names, because they would throw an exception in any case (for instance, you cannot have an object named <code>self.raise</code>).</p>
|
python|pyqt5
| 3 |
1,903,247 | 41,342,945 |
Python Subprocess CREATE_NEW_CONSOLE Windows Not Closing on kill()
|
<p>On a Windows server I start subprocs from the main script with a new console window and add it into a list of procs so I can close them:</p>
<pre><code>p = Popen(["python", 'secondscript.py', arg1, arg2, arg3], creationflags=CREATE_NEW_CONSOLE)
Proc.append(p)
</code></pre>
<p>Later on if I kill the procs with:</p>
<pre><code>for p in Proc:
p.kill()
</code></pre>
<p>They do seem to stop running but I do get left with console windows remaining open. In itself not a huge deal but that can add up over time and start causing issues.</p>
<p>Life is a lot easier using the new console flag but is there a neater way of making sure the console windows close properly? I could rely on a taskkill from the OS lib maybe but that doesn't seem like a good way of doing it.</p>
<p>I had a look around it looks like some people had problems on Linux servers and had to send a sigkill but I thought this was what the kill() was supposed to do anyway.</p>
<p>I might have to just use kill() to stop it working then a taskkil to tidy up but I'd appreciate any advice if there is a neater way of doing that.</p>
|
<p>I had the same issue (on windows) and I found somewhere in SO (unfortunately it was some time ago) the following command:</p>
<pre><code>proc_class = subprocess.Popen(r"C:blabla\server.bat", creationflags=CREATE_NEW_CONSOLE)
... do some stuff ...
Popen("TASKKILL /F /PID {} /T".format(proc_class.pid))
</code></pre>
<p>and it works pretty well</p>
|
python|windows|subprocess|kill
| 1 |
1,903,248 | 6,645,357 |
Doing math to a list in python
|
<p>How do I, say, take <code>[111, 222, 333]</code> and multiply it by 3 to get <code>[333, 666, 999]</code>?</p>
|
<pre><code>[3*x for x in [111, 222, 333]]
</code></pre>
|
python|list
| 36 |
1,903,249 | 56,961,893 |
Detect if any value is above zero and change it
|
<p>I have the following array:</p>
<pre><code>[(True,False,True), (False,False,False), (False,False,True)]
</code></pre>
<p>If any element contains a True then they should all be true. So the above should become:</p>
<pre><code>[(True,True,True), (False,False,False), (True,True,True)]
</code></pre>
<p>My below code attempts to do that but it simply converts all elements to True:</p>
<pre><code>a = np.array([(True,False,True), (False,False,False), (False,True,False)], dtype='bool')
aint = a.astype('int')
print(aint)
aint[aint.sum() > 0] = (1,1,1)
print(aint.astype('bool'))
</code></pre>
<p>The output is:</p>
<pre><code>[[1 0 1]
[0 0 0]
[0 1 0]]
[[ True True True]
[ True True True]
[ True True True]]
</code></pre>
|
<p>You could try <code>np.any</code>, which <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.any.html" rel="nofollow noreferrer">tests whether any array element along a given axis evaluates to True</a>.</p>
<p>Here's a quick line of code that uses a list comprehension to get your intended result.</p>
<pre><code>lst = [(True,False,True), (False,False,False), (False,False,True)]
result = [(np.any(x),) * len(x) for x in lst]
# result is [(True, True, True), (False, False, False), (True, True, True)]
</code></pre>
|
python|numpy
| 2 |
1,903,250 | 57,102,559 |
getting error NameError: name 'main_screen' is not defined for a tkinter login system
|
<p>i keep getting the error </p>
<pre><code>Traceback (most recent call last):
File "G:/computing project/test2.py", line 21, in <module>
main_screen.mainloop() # start the GUI
NameError: name 'main_screen' is not defined
</code></pre>
<p>while trying to create a simple tkinter login system i have tried changing the main_screen.mainloop to TK.mainloop</p>
<pre><code>from tkinter import*
def main_account_screen():
main_screen = Tk() # create a GUI window
main_screen.geometry("1920x1080") # set the configuration of GUI window
main_screen.title("Account Login") # set the title of GUI window
# create a Form label
Label(text="Choose Login Or Register", bg="blue", width="300", height="2", font=("Calibri", 13)).pack()
Label(text="").pack()
# create Login Button
Button(text="Login", height="2", width="30").pack()
Label(text="").pack()
# create a register button
Button(text="Register", height="2", width="30").pack()
main_screen.mainloop() # start the GUI
main_account_screen() # call the main_account_screen() function
</code></pre>
|
<p>You can try this snippet of code if you want no errors</p>
<pre><code>from tkinter import *
main_screen = Tk() # create a GUI window
def main_account_screen():
global main_screen
main_screen.geometry("1920x1080") # set the configuration of GUI window
main_screen.title("Account Login") # set the title of GUI window
# create a Form label
Label(text="Choose Login Or Register", bg="blue", width="300", height="2", font=("Calibri", 13)).pack()
Label(text="").pack()
# create Login Button
Button(text="Login", height="2", width="30").pack()
Label(text="").pack()
# create a register button
Button(text="Register", height="2", width="30").pack()
main_screen.mainloop() # start the GUI
main_account_screen() # call the main_account_screen() function
</code></pre>
<p>This will perfectly work as you have used the <code>global</code> keyword</p>
|
python|authentication|tkinter|nameerror
| 3 |
1,903,251 | 25,791,596 |
Django 1.7 - makemigrations not detecting changes - managed models
|
<p>I have just installed django 1.7 in my virtual env.</p>
<p>Then I manually created the following files:</p>
<pre><code>service_bus/
service_bus/__init__.py
service_bus/django_settings.py
service_bus/models
service_bus/models/__init__.py
service_bus/models/dsp.py
service_bus/models/audience_type.py
service_bus/models/category.py
service_bus/models/audience.py
service_bus/models/dsp_config.py
service_bus/models/apsettings.py
</code></pre>
<p>So I have a settings file <code>service_bus/django_settings.py</code> and the <code>service_bus</code> app.</p>
<p>Then I did, on bash:</p>
<pre><code>export DJANGO_SETTINGS_MODULE='service_bus.django_settings'
</code></pre>
<p>Then I just try to run makemigrations, but it says no changes are detected. </p>
<pre><code>$ django-admin makemigrations
Loading properties from /etc/s1mbi0se/dmp.ini
System check identified some issues:
WARNINGS:
?: (1_6.W001) Some project unittests may not execute as expected.
HINT: Django 1.6 introduced a new default test runner. It looks like this project was generated using Django 1.5 or earlier. You should ensure your tests are all running & behaving as expected. See https://docs.djangoproject.com/en/dev/releases/1.6/#new-test-runner for more information.
No changes detected
$ django-admin makemigrations service_bus
Loading properties from /etc/s1mbi0se/dmp.ini
System check identified some issues:
WARNINGS:
?: (1_6.W001) Some project unittests may not execute as expected.
HINT: Django 1.6 introduced a new default test runner. It looks like this project was generated using Django 1.5 or earlier. You should ensure your tests are all running & behaving as expected. See https://docs.djangoproject.com/en/dev/releases/1.6/#new-test-runner for more information.
No changes detected in app 'service_bus'
</code></pre>
<p>In all my models I have something like</p>
<pre><code>class APSettings(models.Model):
...
class Meta:
db_table = u'APSettings'
app_label = 'service_bus'
</code></pre>
<p>What could I be missing?</p>
|
<p>Make sure you update your models.py file to actually import the models. For example in models.py you'd have <code>from service_bus.models.audience import *</code>. The manage script goes over that file, imports all the models in audience.py and detects changes in there. If you did not add your new models to models.py then the manage script won't know about the new models in you models files.</p>
|
python|django|django-models|django-migrations
| 1 |
1,903,252 | 44,546,209 |
urllib2 : AttributeError 'strip',
|
<p>I am getting "AttributeError('strip',)" while calling following function to make post request to my endpoint with JSON data</p>
<pre><code>def makePostRequest(apiUrl, body):
try:
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
len(jsondataasbytes)
req = urllib2.Request(apiUrl, jsondata, {'Content-Type': 'application/json',
'Content-Length': jsondataasbytes})
try:
response = urllib2.Request(req, jsondataasbytes)
response_data = response.read()
print (response_data)
except Exception as err:
print ("Error: %s", err)
except Exception as error:
print ("error in makePostRequest: ", error)
</code></pre>
|
<p>I was doing it the wrong way. It is working fine now after making some changes as follows:</p>
<pre><code>def makePostRequest(apiUrl, body):
try:
req = urllib2.Request(apiUrl)
req.add_header('Content-Type', 'application/json')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
try:
response = urllib2.urlopen(req, jsondataasbytes)
response_data = response.read()
print (response_data)
except Exception as err:
print ("Error: %s", err)
except Exception as error:
print ("error in makePostRequest: ", error)
</code></pre>
|
python-2.7|urllib2
| 0 |
1,903,253 | 20,583,069 |
Using Openlayers proxy.cgi with Fedora?
|
<p>I am trying to move my application into Fedora server from my Windows server. My problem is that I use proxy.cgi to get information from geoserver.
How should I edit proxy.cgi after I move it into Fedora?</p>
<p>I have tried</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>and it still only return plain text.</p>
<p>This is my proxy.cgi code:</p>
<pre><code>#!/usr/bin/python -u
"""This is a blind proxy that we use to get around browser
restrictions that prevent the Javascript from loading pages not on the
same server as the Javascript. This has several problems: it's less
efficient, it might break some sites, and it's a security risk because
people can use this proxy to browse the web and possibly do bad stuff
with it. It only loads pages via http and https, but it can load any
content type. It supports GET and POST requests."""
import urllib2
import cgi
import sys, os
# Designed to prevent Open Proxy type stuff.
allowedHosts = ['www.google.co.id','www.openlayers.org', 'openlayers.org',
'labs.metacarta.com', 'world.freemap.in',
'prototype.openmnnd.org', 'geo.openplans.org',
'sigma.openplans.org', 'demo.opengeo.org',
'www.openstreetmap.org', 'sample.azavea.com',
'v2.suite.opengeo.org', 'v-swe.uni-muenster.de:8080',
'vmap0.tiles.osgeo.org', 'www.openrouteservice.org', '172.20.32.11:8080', '172.20.32.11','localhost',
'localhost:8080',
'http://192.168.64.2:8080', 'http://192.168.64.2']
method = os.environ["REQUEST_METHOD"]
if method == "POST":
qs = os.environ["QUERY_STRING"]
d = cgi.parse_qs(qs)
if d.has_key("url"):
url = d["url"][0]
else:
url = "http://www.openlayers.org"
else:
fs = cgi.FieldStorage()
url = fs.getvalue('url', "http://www.openlayers.org")
try:
host = url.split("/")[2]
if allowedHosts and not host in allowedHosts:
print "Status: 502 Bad Gateway"
print "Content-Type: text/plain"
print
print "This proxy does not allow you to access that location (%s)." % (host,)
print
print os.environ
elif url.startswith("http://") or url.startswith("https://"):
if method == "POST":
length = int(os.environ["CONTENT_LENGTH"])
headers = {"Content-Type": os.environ["CONTENT_TYPE"]}
body = sys.stdin.read(length)
r = urllib2.Request(url, body, headers)
y = urllib2.urlopen(r)
else:
y = urllib2.urlopen(url)
# print content type header
i = y.info()
if i.has_key("Content-Type"):
print "Content-Type: %s" % (i["Content-Type"])
else:
print "Content-Type: text/plain"
print
print y.read()
y.close()
else:
print "Content-Type: text/plain"
print
print "Illegal request."
except Exception, E:
print "Status: 500 Unexpected Error"
print "Content-Type: text/plain"
print
print "Some unexpected error occurred. Error text was:", E
</code></pre>
|
<p>Your webserver needs to be setup to execute <code>.cgi</code> scripts.</p>
<p>See: <a href="http://httpd.apache.org/docs/current/howto/cgi.html" rel="nofollow">http://httpd.apache.org/docs/current/howto/cgi.html</a></p>
<p>Example (<em>Apache</em>:);</p>
<pre><code>ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/
</code></pre>
<p>I should also point out that CGI is not really the recommend approach in Python. Please consider one of the following:</p>
<ul>
<li>WSGI (<a href="http://wsgi.readthedocs.org/en/latest/" rel="nofollow">http://wsgi.readthedocs.org/en/latest/</a>)</li>
<li>A Web Framework (<em>there are many to choose from</em>)</li>
</ul>
<p>As noted by the OP's comments below (<em>no sudo/root access to the server</em>)
your only other option is to build a simple web app with a suitable web framework
and wrap the CGI using something like <a href="https://pypi.python.org/pypi/wsgi2cgi" rel="nofollow">wsgi2cgi</a></p>
<p>Here is an example using <a href="http://circuitsweb.com" rel="nofollow">circuits.web</a></p>
<p>hello.cgi:</p>
<pre><code>#!/usr/bin/env python
print "Contnt-Type: text/html"
print
print "Hello World!"
</code></pre>
<p>cgiwrapper.py (<em>server</em>):</p>
<pre><code>#!/usr/bin/env python
from wsgi2cgi import CGI
from circuits.web import Server
from circuits.web.wsgi import Gateway
def app(environ, start_response):
wrapper = CGI("hello.cgi")
return wrapper.application(environ, start_response)
server = Server(("0.0.0.0", 5000))
Gateway({"/": app}).register(server)
server.run()
</code></pre>
<p>example output:</p>
<pre><code>$ curl -q -o - http://localhost:5000/
Hello World!
</code></pre>
<p>This would not require root/sudo access to the server; <em>but you are restricted to running on non-priveleged ports</em> (>1024).</p>
|
python|proxy|cgi|fedora|geoserver
| 1 |
1,903,254 | 35,838,111 |
Matplotlib, controlling mark_inset() properties (kwargs)
|
<p>I am trying to make a plot with matplotlib with an inset zoom. I found the following example which will produce a plot with an inset:</p>
<pre><code>import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import numpy as np
def get_demo_image():
from matplotlib.cbook import get_sample_data
import numpy as np
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
z = np.load(f)
# z is a numpy array of 15x15
return z, (-3, 4, -4, 3)
fig, ax = plt.subplots(figsize=[5, 4])
# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30 + ny, 30:30 + nx] = Z
# extent = [-3, 4, -4, 3]
ax.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.imshow(Z2, extent=extent, interpolation="nearest",
origin="lower")
# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
plt.xticks(visible=False)
plt.yticks(visible=False)
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
plt.draw()
plt.show()
</code></pre>
<p>However, I am having trouble finding the correct arguments to pass the <code>mark_inset()</code> function in order to make the linewidth of the boxing line thicker, or the color line red. </p>
<p>I could not find what the arguments <code>fc</code> and <code>ec</code> stand for either, by searching for the documentation.</p>
|
<p>Adding the following after the <code>zoomed_inset_axes</code> should do what you need:</p>
<pre><code>axins = zoomed_inset_axes(ax, 6, loc=1)
for axis in ['top','bottom','left','right']:
axins.spines[axis].set_linewidth(3)
axins.spines[axis].set_color('r')
</code></pre>
<p>To change the inset lines change as follows for red:</p>
<pre><code>mark_inset(ax, axins, loc1=2, loc2=4, fc="none", lw=2, ec='r')
</code></pre>
<p>Giving you the following kind of output:</p>
<p><a href="https://i.stack.imgur.com/nYuux.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nYuux.png" alt="Matplot lib screenshot"></a></p>
<p>The Matplot lib defines <code>fc</code> and <code>ec</code> as follows for <a href="http://matplotlib.org/mpl_toolkits/axes_grid/api/inset_locator_api.html?highlight=mark_inset#mpl_toolkits.axes_grid1.inset_locator.mark_inset" rel="noreferrer">mark_inset</a>:</p>
<ul>
<li><code>facecolor</code> or <code>fc</code> - mpl color spec, or None for default, or ‘none’
for no color. </li>
<li><code>edgecolor</code> or <code>ec</code> - mpl color spec, or None for
default, or ‘none’ for no color.</li>
</ul>
|
python|matplotlib
| 7 |
1,903,255 | 29,780,803 |
Vanilla Django casts a ResourceWarning: "unclosed file" on logging
|
<p>I have an issue with my Django 1.8/Python 3.4 setup.
When running </p>
<pre><code>python -Wall ./manage.py runserver
</code></pre>
<p>I get the following warning:</p>
<pre><code>/lib/python3.4/logging/config.py:763:
ResourceWarning: unclosed file <_io.TextIOWrapper name='/Users/furins/logs/test-project.log' mode='a' encoding='UTF-8'>
for h in logger.handlers[:]:
</code></pre>
<p>these are the settings in <code>settings.py</code> related to logging:
</p>
<pre><code>LOGGING_LEVEL = 'DEBUG'
LOG_DATE_FORMAT = '%d %b %Y %H:%M:%S'
LOG_FORMATTER = logging.Formatter(
'%(asctime)s | %(levelname)-7s | %(name)s | %(message)s',
datefmt=LOG_DATE_FORMAT)
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'standard': {
'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt': LOG_DATE_FORMAT
},
},
'handlers': {
'logfile': {
'level': LOGGING_LEVEL,
'class': 'logging.handlers.RotatingFileHandler',
'filename': PROJECT_DIR / 'logs/test-project.log',
'maxBytes': 1024 * 1024 * 5, # 5 MB
'backupCount': 5,
'formatter': 'standard',
},
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'null': {
'level': 'DEBUG',
'class': 'django.utils.log.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django': {
'handlers': ['console', 'logfile'],
'propagate': True,
'level': 'DEBUG',
},
'django.db.backends': {
'handlers': ['console', 'logfile'],
'level': 'INFO',
'propagate': False,
},
'django.request': {
'handlers': ['console', 'mail_admins', 'logfile'],
'level': 'DEBUG',
'propagate': True,
},
'eurogielle': {
'handlers': ['console', 'logfile', 'mail_admins'],
'level': LOGGING_LEVEL,
'propagate': True
},
'eurogielle2': {
'handlers': ['console', 'logfile', 'mail_admins'],
'level': LOGGING_LEVEL,
'propagate': True
},
'eurogielle_management': {
'handlers': ['console', 'logfile', 'mail_admins'],
'level': LOGGING_LEVEL,
'propagate': True
},
'eurogielle_prodotti': {
'handlers': ['console', 'logfile', 'mail_admins'],
'level': LOGGING_LEVEL,
'propagate': True
},
}
}
</code></pre>
<p>I've tried to search on Google and SO for a similar issue without luck. I know how to silence this warning, of course, but I would like to know if this warning is referring to something that may leak resources in production and if there is a way to "close the file". </p>
<p>Did Any Stackoverflow Django ninja had the same issue?</p>
|
<p>After further search I've found <a href="http://bugs.python.org/issue23010" rel="nofollow noreferrer">a potentially related issue</a> and <a href="http://codeinthehole.com/writing/a-deferred-logging-file-handler-for-django/" rel="nofollow noreferrer">a blog post</a> that drove my to the right direction. </p>
<p>It was really simple, indeed. I'd just had to add a <code>'delay': True</code> to the configuration:</p>
<pre><code> 'logfile': {
'level': LOGGING_LEVEL,
'class': 'logging.handlers.RotatingFileHandler',
'filename': PROJECT_DIR / 'logs/test-project.log',
'maxBytes': 1024 * 1024 * 5, # 5 MB
'backupCount': 5,
'formatter': 'standard',
'delay': True # <- this line solved the problem!
},
</code></pre>
<p>and the warning was gone!
For further reference the property is explained <a href="https://docs.python.org/3/library/logging.handlers.html#rotatingfilehandler" rel="nofollow noreferrer">in python docs</a>:</p>
<blockquote>
<p>If delay is true, then file opening is deferred until the first call to emit().</p>
</blockquote>
|
python|django|python-3.x|logging
| 9 |
1,903,256 | 46,285,046 |
Disable link step of distutils Extension
|
<p>Is it possible to disable the creation of shared objects with <code>distutils.core.Extension</code>? I want to stop the compiler before linking (i.e. <code>g++ -c ...</code>). </p>
<p>I am swigging a native file, which creates an object file and a python file. I have other code to compile that I'll later link with this object file, so I don't want this to proceed after the <code>.o</code> compilation.</p>
<pre><code>$ python setup.py build
running build
....
building 'foo' extension
swigging src/foobar.i to src/foobar.cpp
swig -python -c++ -o src/foobar.cpp src/foobar.i
</code></pre>
<p>I want to stop here, but it continues.</p>
<pre><code>creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/src
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Isrc -I/usr/include/python2.7 -c src/foobar.cpp -o build/temp.linux-x86_64-2.7/src/foobar.o
g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/src/foobar.o -o build/lib.linux-x86_64-2.7/foobar.so
</code></pre>
<p>Do I need to use the CCompiler class directly? Or is there a way to wrangle the <code>Extension</code> class?</p>
<pre><code>23 ext_modules=[
24 # Swig
25 Extension(
26 name='foobar',
27 sources=['src/foobar.i'],
28 include_dirs=['src'],
29 swig_opts=['-c++'],
30 ),
31 ]
</code></pre>
|
<p>You could do something like this:</p>
<pre><code>from distutils.command import build_ext
def cmd_ex(command_subclass):
orig_ext = command_subclass.build_extension
def build_ext(self, ext):
sources = self.swig_sources(list(ext.sources), ext)
command_subclass.build_extension = build_ext
return command_subclass
@cmd_ex
class build_ext_ex(build_ext):
pass
setup(
name = ...,
cmdclass = {'build_ext': build_ext_ex},
ext_modules = ...
)
</code></pre>
<p>to override the default behavior of distutils command.</p>
<p><a href="https://blog.niteo.co/setuptools-run-custom-code-in-setup-py/" rel="nofollow noreferrer">Setuptools – run custom code in setup.py</a></p>
|
python|swig|distutils
| 0 |
1,903,257 | 49,662,291 |
How can I force Pandas dataframe column query to return only str and not interpret what it is seeing?
|
<p>I have an excel spreadsheet that has four column names: "Column One, Column Two, Jun-17, and Column Three"</p>
<p>When I display my column names after reading in the data I get something very different from the "Jun-17" text I was hoping to receive. What should I be doing differently?</p>
<pre><code>import pandas as pd
df = pd.read_excel('Sample.xlsx', sheet_name='Sheet1')
print("Column headings:")
print(df.columns.tolist())
Column headings:
['Column One', 'Column Two', datetime.datetime(2018, 6, 17, 0, 0), 'Column Three']
</code></pre>
|
<p>One of your column names is a <code>datetime</code> object. You can rename it to a string using <code>datetime.strftime</code>. Example below.</p>
<pre><code>import datetime
import pandas as pd, numpy as np
df = pd.DataFrame(columns=['Column One', 'Column Two',
datetime.datetime(2018, 6, 17, 0, 0), 'Column Three'])
df.columns.values[2] = df.columns[2].strftime('%b-%d')
# alternatively:
# df = df.rename(columns={df.columns[2]: df.columns[2].strftime('%b-%d')})
df.columns
# Index(['Column One', 'Column Two', 'Jun-17', 'Column Three'], dtype='object')
</code></pre>
<p>If you see this problem repeatedly, wrap your dataframe in a function:</p>
<pre><code>def normalise_columns(df):
df.columns = [i.strftime('%b-%d') if isinstance(i, datetime.datetime) \
else i for i in df.columns]
return df
normalise_columns(df).columns
</code></pre>
|
python|python-3.x|pandas|datetime|dataframe
| 1 |
1,903,258 | 49,617,685 |
Using strptime to get UTC offset with separation between hours and minutes
|
<p>I have a string like this <code>2018-04-03 02:59:59+00:00</code> and I need to use <code>strptime</code> to convert it to datetime.</p>
<p>However, looking at the <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="noreferrer">docs</a>, the <code>%z</code> (UTC offset) directive is <code>+HHMM</code>, but I need <code>+HH:MM</code>. How can I achieve that? </p>
|
<p>It is not currently possible using <code>datetime.strptime</code>, because of the colon character in the offset. So, forget <code>strptime</code> and choose one of the options below:</p>
<ul>
<li>Pre-process the string to remove the colon from the offset</li>
<li>Use a <a href="https://dateutil.readthedocs.io/en/stable/" rel="nofollow noreferrer"><code>dateutil.parser</code></a> instead of <code>strptime</code></li>
<li>Upgrade to Python 3.7</li>
</ul>
<p>Regarding the last option: there's a new feature provided in 3.7, added specifically to address <a href="https://bugs.python.org/issue15873" rel="nofollow noreferrer">the issue you're seeing</a>. It's a new datetime method, which can correctly parse your string:</p>
<pre><code># Python 3.7.0b1
>>> from datetime import datetime
>>> datetime.fromisoformat('2018-04-03 02:59:59+00:00')
datetime.datetime(2018, 4, 3, 2, 59, 59, tzinfo=datetime.timezone.utc)
</code></pre>
<p>Additionally, Python 3.7 supports colons in the offset for <code>%z</code> if you wanted to stick with <code>strptime</code>.</p>
|
python|datetime
| 7 |
1,903,259 | 49,518,239 |
Change Numpy savetxt from using datatype int16 to int8
|
<p>I use <code>savetxt</code> in numpy to store text files containing binary values as the following:</p>
<pre><code>np.savetxt(filepath, Arr, fmt='%d')
</code></pre>
<p>I realized that <code>fmt='%d'</code> uses <code>int16</code> datatype (which is 2 bytes for each value) even if <code>Arr</code> is created as <code>np.int8</code>. For instance:</p>
<pre><code>def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes // p, 2)
return "%s %s" % (s, size_name[I])
n = 1000
dim = 64
Arr = np.random.choice(np.array([0, 1], dtype=np.int8), size=(n, dim))
Arr = np.unique(Arr, axis=0)
print(convert_size(Arr.nbytes))
filepath = open('test.txt', 'w')
np.savetxt(filepath, Arr.astype(np.int8), fmt='%d')
filepath.close()
</code></pre>
<p>yields to <code>test.txt</code> of size 128 KB while I am expecting 64 KB. Since my values to be written are binary, and very very large, I want to save the size of the file by using <code>int8</code> instead, how can I force <code>np.savetxt</code> to use <code>int8</code>? </p>
<p>Thank you</p>
|
<p>You're seriously misunderstanding the format <code>numpy.savetxt</code> uses. It's not int16 or int8 or anything like that. It's <strong>text</strong>. That's why it says <code>txt</code>.</p>
<p>You're spending two bytes per number because</p>
<pre><code>1 0 0 1 0 1 1 0 ...
1 1 1 1 0 0 0 0 ...
</code></pre>
<p>takes two bytes per number, one for the digit and one for the separating whitespace. It would take more bytes if your numbers had more decimal digits.</p>
<p>If you want to save your array in binary format, consider <code>numpy.save</code>.</p>
|
python|python-3.x|python-2.7
| 2 |
1,903,260 | 49,500,259 |
How to find Most frequently used words used on data using Python?
|
<p>I am doing a sentiment analysis project in Python (using Natural Language Processing). I already collected the data from twitter and saved it as a CSV file. The file contains tweets, which are mostly about cryptocurrency. I cleaned the data and applied sentiment analysis using classification algorithms.</p>
<p>Since the data is clean, I want to find the most frequently used words. Here's the code that I used to import the libraries and the csv file:</p>
<pre><code># importing Libraries
from pandas import DataFrame, read_csv
import chardet
import matplotlib.pyplot as plt; plt.rcdefaults()
from matplotlib import rc
%matplotlib inline
import pandas as pd
plt.style.use('ggplot')
import numpy as np
import re
import warnings
#Visualisation
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
from IPython.display import display
from mpl_toolkits.basemap import Basemap
from wordcloud import WordCloud, STOPWORDS
#nltk
from nltk.stem import WordNetLemmatizer
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk.sentiment.util import *
from nltk import tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.stem.snowball import SnowballStemmer
matplotlib.style.use('ggplot')
pd.options.mode.chained_assignment = None
warnings.filterwarnings("ignore")
## Reading CSV File and naming the object called crime
ltweet=pd.read_csv("C:\\Users\\name\\Documents\\python assignment\\bitcoin1.csv",index_col = None, skipinitialspace = True)
print(btweet)
</code></pre>
<p>There is no need for me to post the other codes because they are very long.
For data cleaning, I got rid of hyperlinks, RT(Retweeted), URL, Punctuation's, put text in lowercase, etc.</p>
<p>Here's the output for the list of positive tweets for example</p>
<pre><code>In [35]: btweet[btweet.sentiment_type == 'POSITIVE'].Tweets.reset_index(drop = True)[0:5]
Out[35]:
0 anizameddine more than just bitcoin blockchain...
1 bitcoinmagazine icymi wyoming house unanimousl...
2 bitracetoken bitrace published the smart contr...
3 unusual and quite promising ico banca banca_of...
4 airdrop coinstocks link it is a exchange so ge...
Name: Tweets, dtype: object
</code></pre>
<p>Is there a way to find the most frequently used words in the data? Can anyone help me write the code for it?</p>
|
<p>Demo:</p>
<pre><code>from nltk import sent_tokenize, word_tokenize, regexp_tokenize, FreqDist
from nltk.corpus import stopwords
from sklearn.datasets import fetch_20newsgroups
from wordcloud import WordCloud, STOPWORDS
def tokenize(text, pat='(?u)\\b\\w\\w+\\b', stop_words='english', min_len=2):
if stop_words:
stop = set(stopwords.words(stop_words))
return [w
for w in regexp_tokenize(text.casefold(), pat)
if w not in stop and len(w) >= min_len]
def get_data():
categories = ['alt.atheism', 'soc.religion.christian',
'comp.graphics', 'sci.med']
twenty_train = \
fetch_20newsgroups(subset='train',
categories=categories, shuffle=True)
twenty_test = \
fetch_20newsgroups(subset='test',
categories=categories, shuffle=True)
X_train = pd.DataFrame(twenty_train.data, columns=['text'])
X_test = pd.DataFrame(twenty_test.data, columns=['text'])
return X_train, X_test, twenty_train.target, twenty_test.target
X_train, X_test, y_train, y_test = get_data()
words = tokenize(X_train.text.str.cat(sep=' '), min_len=4)
fdist = FreqDist(words)
wc = WordCloud(width=800, height=400, max_words=100).generate_from_frequencies(fdist)
plt.figure(figsize=(12,10))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.savefig('d:/temp/result.png')
</code></pre>
<p>Result:</p>
<p><a href="https://i.stack.imgur.com/z09zx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z09zx.png" alt="enter image description here"></a></p>
|
python|pandas|twitter|nlp|sentiment-analysis
| 1 |
1,903,261 | 70,351,750 |
django_heroku.settings(locals()) KeyError: 'MIDDLEWARE' and 'MIDDLEWARE_CLASSES'
|
<p><strong>settings.py</strong></p>
<pre><code>MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ALLOWED_HOSTS = ['my-app.herokuapp.com', '127.0.0.1:8000', 'localhost']
django_heroku.settings(locals())
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/assets')
]
</code></pre>
<p><strong>error (2 exceptions)</strong></p>
<pre><code>remote: Traceback (most recent call last):
remote: File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 97, in settings
remote: config['MIDDLEWARE_CLASSES'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE_CLASSES']))
remote: KeyError: 'MIDDLEWARE_CLASSES'
remote: django_heroku.settings(locals())
remote: File "/app/.heroku/python/lib/python3.9/site-packages/django_heroku/core.py", line 99, in settings
remote: config['MIDDLEWARE'] = tuple(['whitenoise.middleware.WhiteNoiseMiddleware'] + list(config['MIDDLEWARE']))
remote: KeyError: 'MIDDLEWARE'
</code></pre>
<p>I am trying to deploy my web app but I am getting this error everytime, cannot find a solution anywhere... nothing wrong with the Procfile, requirements.txt and runtime.txt, any help is appreciated!</p>
|
<p>Nevermind I fixed it, in my file django_heroku.settings(locals()) was <strong>above</strong> the middleware list so that was causing the errors... now I have a problem where app.settings is not found, guess another question is inevitable.</p>
|
python|django|heroku
| 1 |
1,903,262 | 53,697,043 |
Trouble loading template HTML on click using Flask and Jinja2
|
<p>I believe I have a fundamental misunderstanding as to how Jinja templates are rendered. I am trying to pass data to my flask backend via a GET request, run a query given that data as a parameter, and then render a jinja child template with the given queried information.</p>
<p>Here is my simple javascript function, the click registers, and it runs the query just fine. I don't even believe I need anything in the success tag.</p>
<pre><code>$( "td" ).click(function() {
var comname = $(this).text();
$.ajax({
type: 'GET',
url: "/getSightings",
data: {name: comname},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var result =data.result;
}
});
});
</code></pre>
<p>Here I format the result as a JSON dict and attempt to render sighting.html. My "base" html is called home.html, which I render immediately upon @app.route('/')</p>
<pre><code>@app.route('/getSightings')
def getSightings():
js = request.args.get('name')
with conn:
print("this is the data" + js)
sql = ('SELECT PERSON, LOCATION, SIGHTED, GENUS, SPECIES '
'FROM SIGHTINGS AS S, FLOWERS AS F '
'WHERE S.NAME = F.COMNAME '
'AND NAME = ?'
'ORDER BY S.SIGHTED DESC '
'LIMIT 10; ')
cur = conn.cursor()
cur.execute(sql, (js, ))
r = [dict((cur.description[i][0], value) \
for i, value in enumerate(row)) for row in cur.fetchall()]
return render_template('sighting.html', result=r)
</code></pre>
<p>This is my home.html where I attempt to link to the child template</p>
<pre><code><div id="sighting" class="background p-2">
{% block sighting %}{% endblock %}
</div>
</code></pre>
<p>And this is my sighting.html</p>
<pre><code>{% extends "home.html" %}
{% block sighting %}
<script type="text/javascript">
console.log("loaded");
</script>
{% if result%}
<h2 class="flower-name">PLAINTEXT</h2>
<div class="table-wrapper-scroll-y wrap">
<table class="table table-hover" id="sightingsTable">
<tbody>
{% for item in result %}
<tr>
<td>{{item["PERSON"]}}</td>
<td>{{item["LOCATION"]}}</td>
<td>{{item["SIGHTED"]}}</td>
<td>{{item["GENUS"]}}</td>
<td>{{item["SPECIES"]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p>Didn't work</p>
{% endif %}
{% endblock %}
</code></pre>
<p>No errors are given, but the template is never rendered and the console.log never functions. So I am confused as to how I can conditionally have html rendered using flask. If I replace the above home.html with {% include sighting.html %}, the html is rendered, but it does not have the data from the query (obviously) so it just has the default {elseif} value I gave it. </p>
<p>EDIT:
I understand how to change html with jquery. But based on flask documentation I was under the impression that you can render dynamic html using jinja2 and flask templates. If the the workaround is "just use the ajax form and jquery to implement the changes" then thats fine, I will re-evaluate. But is there no way to, on a condition, call a route and render a template based on that route. </p>
|
<p>Your misunderstanding is not with Jinja, but with Ajax. Your function correctly renders the Jinja template and returns it to the Ajax success function, which... does nothing with it. You need to do something in that success function to insert the response into the existing page.</p>
|
python|jquery|ajax|flask|jinja2
| 0 |
1,903,263 | 46,148,302 |
What is the best way to access values in a dataframe column?
|
<p>For example I have</p>
<pre><code>df=pd.DataFrame({'a':[1,2,3]})
df[df['a']==3].a = 4
</code></pre>
<p>This does not assign 4 to where 3 is </p>
<pre><code>df[df['a']==3] = 4
</code></pre>
<p>But this works.</p>
<p>It confused me on how the assignment works. Appreciate if anyone can give me some references or explanation.</p>
|
<p>Use <code>.loc</code> with boolean index and column label selection:</p>
<pre><code>df.loc[df.a == 3,'a'] = 4
print(df)
</code></pre>
<p>Output:</p>
<pre><code> a
0 1
1 2
2 4
</code></pre>
<p>In your method what is happening is that you are slicing your dataframe and pandas is creating a copy and that assignment is happening on the copy of the dataframe and not the original dataframe itself.</p>
|
python|pandas|dataframe|indexing
| 3 |
1,903,264 | 45,917,524 |
Why NumPy is casting objects to floats?
|
<p>I'm trying to store intervals (with its specific arithmetic) in NumPy arrays. If I use my own Interval class, it works, but my class is very poor and my Python knowledge limited.</p>
<p>I know <a href="http://pyinterval.readthedocs.io/en/latest/" rel="nofollow noreferrer" title="pyInterval">pyInterval</a> and it's very complete. It covers my problems. The only thing which is not working is storing pyInterval objects in NumPy arrays. </p>
<pre><code>class Interval(object):
def __init__(self, lower, upper = None):
if upper is None:
self.upper = self.lower = lower
elif lower <= upper:
self.lower = lower
self.upper = upper
else:
raise ValueError(f"Lower is bigger than upper! {lower},{upper}")
def __repr__(self):
return "Interval " + str((self.lower,self.upper))
def __mul__(self,another):
values = (self.lower * another.lower,
self.upper * another.upper,
self.lower * another.upper,
self.upper * another.lower)
return Interval(min(values), max(values))
import numpy as np
from interval import interval
i = np.array([Interval(2,3), Interval(-3,6)], dtype=object) # My class
ix = np.array([interval([2,3]), interval([-3,6])], dtype=object) # pyInterval
</code></pre>
<p>These are the results</p>
<pre><code>In [30]: i
Out[30]: array([Interval (2, 3), Interval (-3, 6)], dtype=object)
In [31]: ix
Out[31]:
array([[[2.0, 3.0]],
[[-3.0, 6.0]]], dtype=object)
</code></pre>
<p>The intervals from pyInterval has been casted as list of list of floats. It doesn't be a problem if them preserves interval arithmetics...</p>
<pre><code>In [33]: i[0] * i[1]
Out[33]: Interval (-9, 18)
In [34]: ix[0] * ix[1]
Out[34]: array([[-6.0, 18.0]], dtype=object)
</code></pre>
<p><code>Out[33]</code> is the wished output. The output using pyInterval is incorrect. Obviously using raw pyInterval it works like a charm</p>
<pre><code>In [35]: interval([2,3]) * interval([-3,6])
Out[35]: interval([-9.0, 18.0])
</code></pre>
<p><a href="https://github.com/taschini/pyinterval/blob/master/interval/__init__.py" rel="nofollow noreferrer" title="pyInterval source">Here</a> is the pyInterval source code. I don't understand why using this object NumPy doesn't work as I expect.</p>
|
<p>To be fair, it is really hard for the <code>numpy.ndarray</code> constructor to infer what kind of data should go into it. It receives objects which resemble lists of tuples and makes do with it.</p>
<p>You can, however, help your constructor a bit by not having it guess the shape of your data:</p>
<pre><code>a = interval([2,3])
b = interval([-3,6])
ll = [a,b]
ix = np.empty((len(ll),), dtype=object)
ix[:] = [*ll]
ix[0]*ix[1] #interval([-9.0, 18.0])
</code></pre>
|
python|class|numpy|intervals
| 2 |
1,903,265 | 45,964,621 |
Python 2.7 sklearn.svm warning message
|
<p>I am running a Support Vector Regression in Python using:</p>
<pre><code>model=SVR(C=1.0, epsilon=0.01,kernel='linear',verbose=True)
</code></pre>
<p>I received the following warning: </p>
<pre><code>[LibSVM].........................................
Warning: using -h 0 may be faster
</code></pre>
<p>What does it mean? How can I use this information?</p>
|
<p>According to <a href="https://stats.stackexchange.com/questions/70242/libsvm-warning-using-h-0-may-be-faster">this post</a>:</p>
<blockquote>
<p>This means, that optimization algorithm detected that with high probability (not in the strict, mathematical sense) you can speed up your training by turning the -h 0 flag in your options. Basically, -h is the shrinking heuristics, implemented in the libsvm package which for some data significantly reduces number of required computations, while in others - makes it slower.</p>
</blockquote>
<p>This flag is implemented in sklearn with 'shrinking' parameter which you can set to <code>False</code> (shrinking=False)</p>
|
python-2.7|scikit-learn|regression|svm
| 1 |
1,903,266 | 54,958,592 |
get text in td's in a table with specific id and tr with specific attribute
|
<p>Given an html like this:</p>
<pre><code> page_html = '''
<html>
<head>
<title>Title</title>
</head>
<body>
<div id="div1">
<h1>h1 text</h1>
<div id="div div1">text div div1
</div>
<p>text in p</p>
<table id="tab1" border="1">
<tr id="tab1 tr1" class="class1">
<td><a href="/info/tab1/tr1/td1">tab1 tr1 td 1</a></td>
<td><a href="/info/tab1/tr1/td2">tab1 tr1 td 2</a></td>
<td><a href="/info/tab1/tr1/td3">tab1 tr1 td 3</a></td>
</tr>
<tr id="tab1 tr2" class="class1">
<td><a href="/info/tab1/tr2/td1">tab1 tr2 td 1</a></td>
<td><a href="/info/tab1/tr2/td2">tab1 tr2 td 2</a></td>
</tr>
<tr id="tab1 tr3" class="class2">
<td><a href="/info/tab1/tr3/td1">tab1 tr3 td 1</a></td>
<td><a href="/info/tab1/tr3/td2">tab1 tr3 td 2</a></td>
</tr>
</table>
<table id="tab2" border="1">
<tr id="tab2 tr1" class="class2">
<td><a href="/info/tab2/tr1/td1">tab2 tr1 td 1</a></td>
<td><a href="/info/tab2/tr1/td2">tab2 tr1 td 2</a></td>
<td><a href="/info/tab2/tr1/td3">tab2 tr1 td 3</a></td>
</tr>
<tr id="tab2 tr2" class="class2">
<td><a href="/info/tab2/tr2/td1">tab2 tr2 td 1</a></td>
<td><a href="/info/tab2/tr2/td2">tab2 tr2 td 2</a></td>
</tr>
<tr id="tab2 tr3" class="class3">
<td><a href="/info/tab2/tr3/td1">tab2 tr3 td 1</a></td>
<td><a href="/info/tab2/tr3/td2">tab2 tr3 td 2</a></td>
</tr>
</table>
</div>
</body>
</html>
'''
</code></pre>
<p>I would like to get the text from td's in table with <code>id=tab2</code> where tr's have attribute <code>class=class2</code>, corresponding to:</p>
<pre><code> <tr id="tab2 tr1" class="class2">
<td><a href="/info/tab2/tr1/td1">tab2 tr1 td 1</a></td>
<td><a href="/info/tab2/tr1/td2">tab2 tr1 td 2</a></td>
<td><a href="/info/tab2/tr1/td3">tab2 tr1 td 3</a></td>
</tr>
<tr id="tab2 tr2" class="class2">
<td><a href="/info/tab2/tr2/td1">tab2 tr2 td 1</a></td>
<td><a href="/info/tab2/tr2/td2">tab2 tr2 td 2</a></td>
</tr>
</code></pre>
<p>My partial solution is:</p>
<pre><code>from bs4 import BeautifulSoup
bsobj = BeautifulSoup(page_html)
res = bsobj.find('table', id='tab2').findAll('tr', {'class':'class2'})
</code></pre>
<p>but I am not able to extract the text.</p>
<p>Trying with list comprehension:</p>
<pre><code>[td.text for td in res]
</code></pre>
<p>gets the general (right) result but as a list of the two tr's and with anomalous <code>\n</code>, that is:</p>
<blockquote>
<p>['\ntab2 tr1 td 1\ntab2 tr1 td 2\ntab2 tr1 td 3\n', '\ntab2 tr2 td
1\ntab2 tr2 td 2\n']</p>
</blockquote>
<p>Is there a cleaner way to get the text for each td satisfying my conditions on table and tr?</p>
|
<p>ResultSet objects can be treated like a list and used in a list comprehension directly. You can use a nested list comprehension to first get the all the <code>tr</code> and then all the <code>td</code> from each of the <code>tr</code> without storing intermediate results.</p>
<pre><code>from bs4 import BeautifulSoup
bsobj = BeautifulSoup(page_html,'html.parser')
res = [td.text for tr in bsobj.find('table', id='tab2').findAll('tr', {'class':'class2'}) for td in tr.findAll('td')]
print(res)
</code></pre>
<p>Output</p>
<pre><code>['tab2 tr1 td 1', 'tab2 tr1 td 2', 'tab2 tr1 td 3', 'tab2 tr2 td 1', 'tab2 tr2 td 2']
</code></pre>
|
html|python-3.x|beautifulsoup
| 0 |
1,903,267 | 54,815,631 |
Dendrogram y-axis labeling confusion
|
<p>I have a large <code>(106x106)</code> correlation matrix in pandas with the following structure:</p>
<pre><code>+---+-------------------+------------------+------------------+------------------+------------------+-----------------+------------------+------------------+------------------+-------------------+
| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+---+-------------------+------------------+------------------+------------------+------------------+-----------------+------------------+------------------+------------------+-------------------+
| 0 | 1.0 | 0.465539925807 | 0.736955649673 | 0.733077703346 | -0.177380436347 | -0.268022641963 | 0.0642473239514 | -0.0136866435594 | -0.025596700815 | -0.00385065532308 |
| 1 | 0.465539925807 | 1.0 | -0.173472213691 | -0.16898620433 | -0.0460674481563 | 0.0994673318696 | 0.137137216943 | 0.061999118034 | 0.0944808695878 | 0.0229095105328 |
| 2 | 0.736955649673 | -0.173472213691 | 1.0 | 0.996627003263 | -0.172683935315 | -0.33319698831 | -0.0562591684255 | -0.0306820050477 | -0.0657065745626 | -0.0457836647012 |
| 3 | 0.733077703346 | -0.16898620433 | 0.996627003263 | 1.0 | -0.153606414649 | -0.321562257834 | -0.0465540370732 | -0.0224318843281 | -0.0586629098513 | -0.0417237678539 |
| 4 | -0.177380436347 | -0.0460674481563 | -0.172683935315 | -0.153606414649 | 1.0 | 0.0148395123941 | 0.191615549534 | 0.289211355855 | 0.28799868259 | 0.291523969899 |
| 5 | -0.268022641963 | 0.0994673318696 | -0.33319698831 | -0.321562257834 | 0.0148395123941 | 1.0 | 0.205432455075 | 0.445668299971 | 0.454982398693 | 0.427323555674 |
| 6 | 0.0642473239514 | 0.137137216943 | -0.0562591684255 | -0.0465540370732 | 0.191615549534 | 0.205432455075 | 1.0 | 0.674329392219 | 0.727261969241 | 0.67891326835 |
| 7 | -0.0136866435594 | 0.061999118034 | -0.0306820050477 | -0.0224318843281 | 0.289211355855 | 0.445668299971 | 0.674329392219 | 1.0 | 0.980543049288 | 0.939548790275 |
| 8 | -0.025596700815 | 0.0944808695878 | -0.0657065745626 | -0.0586629098513 | 0.28799868259 | 0.454982398693 | 0.727261969241 | 0.980543049288 | 1.0 | 0.930281915882 |
| 9 | -0.00385065532308 | 0.0229095105328 | -0.0457836647012 | -0.0417237678539 | 0.291523969899 | 0.427323555674 | 0.67891326835 | 0.939548790275 | 0.930281915882 | 1.0 |
+---+-------------------+------------------+------------------+------------------+------------------+-----------------+------------------+------------------+------------------+-------------------+
</code></pre>
<p>Truncated here for simplicity.</p>
<p>If I calculate the linkage, and later plot the dendrogram using the following code:</p>
<pre><code>from scipy.cluster.hierarchy import dendrogram, linkage
Z = linkage(result_df.corr(),'average')
plt.figure()
fig, axes = plt.subplots(1, 1, figsize=(20, 20))
axes.tick_params(axis='both', which='major', labelsize=15)
dendrogram(Z=Z, labels=result_df_null_cols.columns,
leaf_rotation=90., ax=axes,
color_threshold=2.)
</code></pre>
<p>It yields a dendrogram like:
<a href="https://i.stack.imgur.com/UudJF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UudJF.png" alt="enter image description here"></a></p>
<p>My question is surrounding the y-axis. On all examples I have seen, the Y axis is bound between 0,2 - which I have read to interpret as <code>(1-corr)</code>. In my result, the boundary is much higher. 0 being items that are highly correlated <code>(1-1 = 0)</code>, and 2 being the cutoff on lowly correlated stuff <code>(1 - -1 = 2)</code>.</p>
<p>I found the <a href="https://stackoverflow.com/questions/34175462/dendrogram-using-pandas-and-scipy">following answer</a> but <a href="https://stats.stackexchange.com/questions/82326/how-to-interpret-the-dendrogram-of-a-hierarchical-cluster-analysis">it does not agree with this answer</a> and the <a href="http://www.econ.upf.edu/~michael/stanford/maeb7.pdf" rel="noreferrer">referenced lecture notes here</a>.</p>
<p>Anyway - hoping someone can clarify which source is the correct one, and help spread some knowledge on the topic.</p>
|
<p>The metric, which has been used for the <code>linkage()</code> is the euclidean distance, see <a href="https://github.com/scipy/scipy/blob/v1.2.1/scipy/cluster/hierarchy.py#L1118" rel="noreferrer">here</a> and not the actual values. Therefore, it can go beyond 2 and it purely depends on the type of distance metric we use.</p>
<p>This supports the points, mentioned in <a href="https://stats.stackexchange.com/questions/82326/how-to-interpret-the-dendrogram-of-a-hierarchical-cluster-analysis">this</a> answer.</p>
<blockquote>
<p>1) The y-axis is a measure of closeness of either individual data
points or clusters.</p>
</blockquote>
<p>Then, these distances are used to compute the tree, using the following calculation between every pair of clusters.</p>
<p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html#scipy.cluster.hierarchy.linkage" rel="noreferrer"><strong>From Documentation:</strong></a></p>
<p><a href="https://i.stack.imgur.com/Ll6H4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ll6H4.png" alt="enter image description here"></a></p>
<p>In your mentioned sample, </p>
<p>Even though the individual values does not go beyond <code>(-1, +1)</code>, we will get the following dendrogram. </p>
<p><a href="https://i.stack.imgur.com/iLNeY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iLNeY.png" alt="enter image description here"></a></p>
<pre><code>from scipy.spatial import distance
distance.pdist(df, 'euclidean')
</code></pre>
<p>The reason is that the distance array of size 45 (<strong><code>10 C 2</code></strong> - every pair of columns; ordering is explained <a href="https://github.com/scipy/scipy/blob/v1.2.1/scipy/spatial/distance.py#L1764" rel="noreferrer">here</a>) would have following values:</p>
<pre><code>array([1.546726 , 0.79914141, 0.79426728, 2.24085106, 2.50838998,
2.22772899, 2.52578923, 2.55978527, 2.51553289, 2.11329023,
2.10501739, 1.66536963, 1.6303103 , 1.71821177, 2.04386712,
2.03917033, 2.03614219, 0.0280283 , 2.33440388, 2.68373496,
2.43771817, 2.68351612, 2.73148741, 2.66843754, 2.31758222,
2.67031469, 2.4206485 , 2.66539997, 2.7134241 , 2.65058045,
1.44756593, 1.39699605, 1.55063416, 1.56324546, 1.52001219,
1.32204039, 1.30206957, 1.29596715, 1.2895916 , 0.65145881,
0.62242858, 0.6283212 , 0.08642582, 0.11145739, 0.14420816])
</code></pre>
<p>If we build a random value matrix with uniform dist. <code>(-1, 1)</code> of size <code>(160, 160)</code>, the dendrogram would be something similar to this!</p>
<p><a href="https://i.stack.imgur.com/5XM8c.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5XM8c.png" alt="enter image description here"></a></p>
<p>Hence, the solution for your problem is,</p>
<p>You need to convert the correlation values into some form of distance measure. </p>
<ol>
<li><p>we could use the same <a href="https://github.com/scipy/scipy/blob/v1.2.1/scipy/spatial/distance.py#L2078" rel="noreferrer">squareform()</a> suggested in the <a href="https://stackoverflow.com/questions/34175462/dendrogram-using-pandas-and-scipy">other answer</a>. This is a duct tape approach to achieve two aspects of a distance measure. It has to be zero [between same two points] and non-negatives for any two points. This can be achieved by subtracting each corr value from one. </p></li>
<li><p>Directly we can use the <code>distance.pdist</code> function with correlation as metric. The implementation is available <a href="https://github.com/scipy/scipy/blob/v1.2.1/scipy/spatial/distance.py#L182" rel="noreferrer">here</a>. Remember to transform the dataframe, because we need correlation between each column and not row. </p></li>
</ol>
<p>Example to understand the solution:</p>
<pre><code>size = (10000,1)
col1 = np.random.randint(0,100,size) # base column
col2 = col1 * 0.9 + np.random.normal(0,2,size) # huge corr with small noise
col3 = col1 * 0.1 + np.random.normal(0,100,size) # uncorrelated column
col4 = col1 * (-0.5) + np.random.normal(0,1,size) # negatively corr
data = np.hstack((col1,col2,col3,col4))
df = pd.DataFrame(data , columns=list('ABCD'))
df.corr()
A B C D
A 1.000000 0.997042 0.029078 -0.997614
B 0.997042 1.000000 0.029233 -0.994677
C 0.029078 0.029233 1.000000 -0.028421
D -0.997614 -0.994677 -0.028421 1.000000
#pdist_values = distance.squareform(1 - df.corr().values )
pdist_values = distance.pdist(df.T, 'correlation')
z = linkage(pdist_values, method='average')
dendrogram(z, labels=df.columns)
</code></pre>
<p><a href="https://i.stack.imgur.com/ecgbG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ecgbG.png" alt="enter image description here"></a></p>
|
python|scikit-learn|hierarchical-clustering|dendrogram
| 5 |
1,903,268 | 54,967,054 |
How to remove spaces from the url in Django
|
<p>How can I remove spaces or any non-alpha-numeric characters from the URLs in Django? </p>
<p>My urls.py looks like this. </p>
<pre><code>urlpatterns = [
url(r'^(P?<query>^\d+:[a-z]+)/show$', views.results, name='results')
]
</code></pre>
<p>I want to remove if there is space in the queries like ("/12:some query/show") and fire the query as ex("/12:somequery/show")</p>
|
<p>I guess one simpler solution could be parsing <code>query</code> in your views before fetching the object and replacing space there. </p>
<p>for example in your views.py:</p>
<pre><code># If class based
def get_object(self):
query = self.kwargs.get('query', '')
query = query.replace(' ', '')
....
# If using function based
query = request.GET.get('query', '')
query = query.replace(' ', '')
....
</code></pre>
|
python|django|url
| 0 |
1,903,269 | 55,065,496 |
Calculation on list of numpy array
|
<p>I'm trying to do some calculation (mean, sum, etc.) on a list containing numpy arrays.
For example:</p>
<blockquote>
<p>list = [array([2, 3, 4]),array([4, 4, 4]),array([6, 5, 4])]</p>
</blockquote>
<p>How can retrieve the mean (for example) ?
In a list like <code>[4,4,4]</code> or a numpy array like <code>array([4,4,4])</code> ?</p>
<p>Thanks in advance for your help!</p>
<hr>
<p>EDIT : Sorry, I didn't explain properly what I was aiming to do : I would like to get the mean of i-th index of the arrays. For example, for index 0 :</p>
<blockquote>
<p>(2+4+6)/3 = 4</p>
</blockquote>
<p>I don't want this : </p>
<blockquote>
<p>(2+3+4)/3 = 3</p>
</blockquote>
<p>Therefore the end result will be </p>
<blockquote>
<p>[4,4,4] / and not [3,4,5]</p>
</blockquote>
|
<p>Given a 1d array <code>a</code>, <code>np.mean(a)</code> should do the trick.</p>
<p>If you have a 2d array and want the means for each one separately, specify <code>np.mean(a, axis=1)</code>.</p>
<p>There are equivalent functions for <code>np.sum</code>, etc.</p>
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html</a>
<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html</a></p>
|
python|list|numpy
| 0 |
1,903,270 | 33,331,732 |
Python initialize multiple variables to the same initial value
|
<p>I have gone through these questions,</p>
<blockquote>
<ol>
<li><a href="https://stackoverflow.com/questions/16348815/python-assigning-multiple-variables-to-same-value-list-behavior">Python assigning multiple variables to same value? list behavior</a>
<br><em>concerned with tuples, I want just variables may be a string, integer or dictionary</em></li>
<li><a href="https://stackoverflow.com/questions/5495332/more-elegant-way-of-declaring-multiple-variables-at-the-same-time">More elegant way of declaring multiple variables at the same time</a>
<br> <em>The question has something I want to ask, but the accepted answer is much complex</em></li>
</ol>
</blockquote>
<p>so what I'm trying to achieve,</p>
<p>I declare variables as follows, and I want to reduce these declarations to as less line of code as possible.</p>
<pre><code>details = None
product_base = None
product_identity = None
category_string = None
store_id = None
image_hash = None
image_link_mask = None
results = None
abort = False
data = {}
</code></pre>
<p>What is the simplest, easy to maintain ?</p>
|
<p>I agree with the other answers but would like to explain the important point here.</p>
<p><strong>None</strong> object is singleton object. How many times you assign None object to a variable, same object is used. So </p>
<pre><code>x = None
y = None
</code></pre>
<p>is equal to </p>
<pre><code>x = y = None
</code></pre>
<p>but you should not do the same thing with any other object in python. For example,</p>
<pre><code>x = {} # each time a dict object is created
y = {}
</code></pre>
<p>is not equal to</p>
<pre><code>x = y = {} # same dict object assigned to x ,y. We should not do this.
</code></pre>
|
python|variables|variable-assignment
| 65 |
1,903,271 | 73,527,933 |
Traffic Sign Segmentation using K-means Clustering OpenCV
|
<p>I used K-Means Clustering to perform segmentation on this traffic sign as shown below.
<a href="https://i.stack.imgur.com/dU47J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dU47J.png" alt="enter image description here" /></a></p>
<p>These are my code</p>
<p>Read image and blur</p>
<pre><code>img = cv.imread('000_0001.png')
img_rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)
kernel_size = 5
img_rgb = cv.blur(img_rgb, (kernel_size, kernel_size))
# reshape
img_reshape = img_rgb.reshape((-1, 3))
img_reshape = np.float32(img_reshape)
</code></pre>
<p>Perform k-means clustering</p>
<pre><code>criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 4
attempts = 10
ret, label, center = cv.kmeans(img_reshape, K, None, criteria, attempts, cv.KMEANS_PP_CENTERS)
# reshape into original dimensions
center = np.uint8(center)
res = center[label.flatten()]
result = res.reshape(img_rgb.shape)
plt.figure(figsize = (15, 15))
plt.subplot(1, 2, 1)
plt.imshow(img_rgb)
plt.subplot(1, 2, 2)
plt.imshow(result)
plt.show()
</code></pre>
<p>create masks</p>
<pre><code>from numpy import linalg as LN
red = (255, 0, 0)
Idx_min_red = np.argmin(LN.norm(center-red, axis = 1))
white = (255, 255, 255)
Idx_min_white = np.argmin(LN.norm(center-white, axis = 1))
black = (0, 0, 0)
Idx_min_black = np.argmin(LN.norm(center-black, axis = 1))
mask_red = result == center[Idx_min_red]
mask_white = result == center[Idx_min_white]
mask_black = result == center[Idx_min_black]
pre_mask = cv.bitwise_or(np.float32(mask_red), np.float32(mask_white))
mask = cv.bitwise_or(np.float32(pre_mask), np.float32(mask_black))
</code></pre>
<p>Segment the image</p>
<pre><code>seg_img = img*(mask.astype("uint8"))
</code></pre>
<p>Morphological Transformation</p>
<pre><code>kernel = np.ones((5, 5), dtype = np.uint8)
img_dilate = cv.morphologyEx(seg_img, cv.MORPH_OPEN, kernel)
res = np.hstack((img, img_dilate))
cv.imshow("res", res)
cv.waitKey(0)
cv.destroyAllWindows()
</code></pre>
<p><strong>Question here</strong>
These codes can only segment red traffic signs, is it possible to tweak a little bit on different colours so that it can segment red, blue and yellow traffic signs? (like the one below for example)</p>
<p><a href="https://i.stack.imgur.com/37Gu6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/37Gu6.png" alt="enter image description here" /></a></p>
<p>Update, this is what I have tried:
I used a pipeline to do OR operation on all the masks
<code>mask = mask_red | mask_white | mask_black | mask_blue</code></p>
<p>but then the new mask will fail to segment the image
<a href="https://i.stack.imgur.com/LZOGP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LZOGP.png" alt="enter image description here" /></a></p>
|
<p><a href="https://i.stack.imgur.com/4Whdw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Whdw.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/lbuzm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lbuzm.png" alt="enter image description here" /></a></p>
<p>Rather than K means, I'd suggest a connected components based approach to find this. These signs and symbols have relatively uniform color areas that take a fairly significant part of the image, that would result in large connected components. You can later write downstream logic to select the relevant connected components to define your sign and create a segmented image from them.</p>
<pre><code>import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
colors = (np.array(plt.cm.tab10.colors) * 255).astype('int')
im1 = cv2.imread('37Gu6.png')
im2 = cv2.imread('dU47J.png')
for i in [im1, im2]:
gray = cv2.cvtColor(i, cv2.COLOR_BGR2GRAY)
# Calculate image value histogram to get an adaptive threshold value based
hist = np.histogram(gray.ravel(), bins=25)
modeIdx = np.where(hist[0] == hist[0].max())[0][0]
modeVal = hist[1][modeIdx]
tVal = modeVal * 1.15 # Our threshold is 115% of the most common hist value
_, thresh = cv2.threshold(gray, tVal, 255, cv2.THRESH_BINARY)
# Find connected componenents
output = cv2.connectedComponentsWithStats(thresh, 8, cv2.CV_32S)
(numLabels, labels, stats, centroids) = output
# The 5th column in the CC stats is the area
# Find the indices of CCs with above average area
CCArea = stats[:,4]
aboveAvgLbls = np.where(CCArea > CCArea.mean())[0]
# Generate labeled output image
outputImg = np.zeros(i.shape, dtype="uint8")
for l, c in zip(aboveAvgLbls, colors):
w = np.where(labels == l)
outputImg[ w[0], w[1] ] = c
f, ax = plt.subplots(1,4,figsize=(20,5))
for a, img, t in zip(ax, [i, gray, thresh, outputImg], ['RGB', 'Gray', f'Thresh [t={tVal}]', 'Labels']):
a.imshow(img[:,:,::-1] if img.shape[-1] == 3 else img, 'gray')
a.set_title(t)
plt.show()
</code></pre>
|
python|opencv|computer-vision|image-segmentation
| 2 |
1,903,272 | 13,076,194 |
ASCII art in Python
|
<p>I'm pretty new to python, picked it up as an hobby interest, and through some searching found myself a bunch of exercises from "<em>The Practice of computing</em>", one of them asks about writing an ASCII figure, like the one denoted below.</p>
<p><img src="https://i.stack.imgur.com/aVNGc.png" alt="ascii cross"></p>
<p>It all seems like an easy enough exercise, but i can't seem wrap my head around the use of a number to draw this, the exercise states that the above drawing was drawn through use of the number "1". </p>
<p>It also states that no number under 0 or above 100 can or should be used to create an ASCII drawing.</p>
<p>Here's another example: </p>
<p>The input here was the number "2".</p>
<p><img src="https://i.stack.imgur.com/pXbzy.png" alt="bigger ascii cross"></p>
<p>I've found a way to make the first image appear, but not through any use of the given numbers in any way, just a simple "else" inside a while loop so i could filter out the numbers that are below or equal to 0 and higher or equal to 100.</p>
<p>I've hit a dead stop.</p>
<p>My code as stated above that does not use the variable number to create the first drawing : </p>
<pre><code>while True:
s = input("Give me a number to make a drawing with that is between 0 and 100: ")
if not s.isdigit():
print ("Error, only numbers will make this program run.")
continue #Try Again but with a number this time
if int(s) >= 100:
print ("The number is bigger than or equal to 100 and won't work. \nDo try again.")
continue #try again
if int(s) <= 0:
print ("The number is smaller than or equal to 0 and won't work. \nDo try again.")
continue #try again
else:
print ("%5s" %("*" *3),"\n"'%5s' %("* *"),"\n" '%7s' %("*** ***"),"\n" '%7s' %("* *"),"\n" '%7s' %("*** ***"),"\n" '%5s' %("* *"),"\n" '%5s' %("*" *3))
print ('Want to make another drawing ?')
continue #make another drawing
</code></pre>
<p><strong>The excercise states the following :</strong> </p>
<p>An ASCII Figure of the size $n$ is made up of one or several lines. On each line only spaces and the stars (*) are allowed, after each star on a line no spaces are allowed as such you should end with a "\n" or newline. And then followed by the above stated examples.</p>
<p><strong>My new code example which is dependent on the variable input:</strong>
<em>Also, in this code example it is set to trigger when the input is 1, I'm still having problems with "enlarging" the entire drawing when I increase the input number.</em></p>
<pre><code> while True:
A = input("Give me a number to make a drawing with that is between 0 and 100: ")
b = "***"
c = "*"
d = " "
if not A.isdigit():
print ("Error, only numbers will make this program run.")
continue #Try Again but with a number this time
if int(A) >= 100:
print ("The number is bigger than or equal to 100 and won't work. \nDo try again.")
continue #try again
if int(A) <= 0:
print ("The number is smaller than or equal to 0 and won't work. \nDo try again.")
continue #try again
else :
range(1,99)
if int(A) == (1) :
print ((d *((int(A))*2)) + b,)
print ((d *((int(A))*2))+ c + d + c,)
print ((d *((int(A))*0))+ b + d + b,)
print ((d *((int(A))*0))+ c + d*5 + c,)
print ((d *((int(A))*0))+ b + d + b,)
print ((d *((int(A))*2))+ c + d + c,)
print ((d *((int(A))*2)) + b,)
continue #try again
</code></pre>
<p>But i've still got a problam with "growing" the number of spaces inside the ASCII figure alongside the increase of 1 to 2.</p>
<p>As i've got a problem with line 3 as well, because it needs to be denoted along the sides of the console, it should have a spacing of 0 from the side, but it must increase to a spacing of 2 with the number 2.</p>
|
<p>Think about the difference between 1 and 2. Try to draw by hand what 3 and 4 should look like to make the sequence work. Think about it like one of those problems where you are given the start of a sequence and you have to work our the rest.</p>
<p>Like:</p>
<p>0 1 1 2 3 5 8 13</p>
<p>If you don't recognize that right off, it is the Fibonacci sequence. Once you figure out the pattern you can write an arbitrarily long sequence of the values.</p>
<p>And think about this simple ascii sequence:</p>
<p>1)</p>
<pre><code>#
</code></pre>
<p>2)</p>
<pre><code>##
#
</code></pre>
<p>3)</p>
<pre><code>###
##
#
</code></pre>
<p>What does 4) look like?</p>
<p>Or another ascii sequence:</p>
<p>1)</p>
<pre><code>#
</code></pre>
<p>2)</p>
<pre><code> #
# #
#
</code></pre>
<p>3)</p>
<pre><code> #
# #
# #
# #
#
</code></pre>
<p>What is (4)?</p>
<p>If it still doesn't make sense, try designing a few recursive shapes of your own which are a little similar to the one you are trying to figure out (maybe something along the lines of my second example). Don't worry about how to code it for now, just worry about what the output should be. Then look at the patterns and come out with an algorithm.</p>
|
python|ascii
| 14 |
1,903,273 | 21,755,574 |
IPython notebook - unable to export to pdf
|
<p>I'm trying to export my IPython notebook to pdf, but somehow I can't figure out how to do that. I searched through stackoverflow and already read about nbconvert, but where do I type that command? In the notebook? In the cmd prompt?
If someone can tell me, step by step, what to do? I'm using Python 3.3 and IPython 1.1.0.
Thank you in advance :)</p>
|
<ol>
<li><p>For HTML output, you should now use Jupyter in place of IPython and select <em>File</em> -> <em>Download as</em> -> <em>HTML (.html)</em> or run the following command: </p>
<pre><code>jupyter nbconvert --to html notebook.ipynb
</code></pre>
<p>This will convert the Jupyter document file notebook.ipynb into the html output format.</p>
<p>Google Colaboratory is Google's free Jupyter notebook environment that requires no setup and runs entirely in the cloud. If you are using Google Colab the commands are the same, but Google Colab only lets you download .ipynb or .py formats. </p></li>
<li><p>Convert the html file notebook.html into a pdf file called notebook.pdf. In Windows, Mac or Linux, install <a href="https://wkhtmltopdf.org/downloads.html" rel="nofollow noreferrer">wkhtmltopdf</a>. wkhtmltopdf is a command line utility to convert html to pdf using WebKit. You can download wkhtmltopdf from the linked webpage, or in many Linux distros it can be found in their repositories. </p>
<pre><code>wkhtmltopdf notebook.html notebook.pdf
</code></pre></li>
</ol>
<hr>
<p>Original (now almost obsolete) revision:</p>
<ol>
<li><p>Convert the IPython notebook file to html.</p>
<pre><code>ipython nbconvert --to html notebook.ipynb
</code></pre>
<p>This will convert the IPython document file notebook.ipynb into the html output format.</p></li>
<li><p>Convert the html file notebook.html into a pdf file called notebook.pdf. In Windows, Mac or Linux, install <a href="https://wkhtmltopdf.org/downloads.html" rel="nofollow noreferrer">wkhtmltopdf</a>. wkhtmltopdf is a command line utility to convert html to pdf using WebKit. You can download wkhtmltopdf from the linked webpage, or in many Linux distros it can be found in their repositories. </p>
<pre><code>wkhtmltopdf notebook.html notebook.pdf
</code></pre></li>
</ol>
|
python|pdf|ipython|ipython-notebook
| 4 |
1,903,274 | 24,601,405 |
Why do statsmodels's correlation and autocorrelation functions give different results in Python?
|
<p>I need to obtain the correlation between two different series A and B as well as the autocorrelations of A and B. Using the correlation functions provided by statsmodels I got different results, it's not the same to calculate the autocorrelation of A and to calculate the correlation between A and A, Why are the results different?.</p>
<p>Here is an example of the behavior I'm talking about:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
from statsmodels.tsa.stattools import ccf
from statsmodels.tsa.stattools import acf
#this is the data series that I want to analyze
A = np.array([np.absolute(x) for x in np.arange(-1,1.1,0.1)])
#This is the autocorrelation using statsmodels's autocorrelation function
plt.plot(acf(A, fft=True))
</code></pre>
<p><img src="https://i.stack.imgur.com/hgLd5.png" alt="enter image description here"></p>
<pre><code>#This the autocorrelation using statsmodels's correlation function
plt.plot(ccf(A, A))
</code></pre>
<p><img src="https://i.stack.imgur.com/o3Uug.png" alt="enter image description here"></p>
|
<p>The two functions have different default arguments for the boolean <code>unbiased</code> argument. To get the same result as <code>acf(A, fft=True)</code>, use <code>ccf(A, A, unbiased=False)</code>.</p>
|
python|numpy|statsmodels
| 4 |
1,903,275 | 24,504,956 |
Writing to a File in Python: Out of Memory Exception
|
<p>I am trying to write a list to a file using pickle but I can not write except a limited size of it like the first 3000 items or so. Eech time I try to write the list fully I get this error:</p>
<pre><code>java.lang.OutOfMemoryError: Java heap space
</code></pre>
<p>This is the code I am using to do the job:</p>
<pre><code>output = open('myfile.pkl', 'w')
pickle.dump(wells[:3000], output)
output.close()
</code></pre>
|
<p>Following are few options available to change Heap Size.</p>
<pre><code> -Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
</code></pre>
|
java|python|file|memory|pickle
| 0 |
1,903,276 | 40,876,120 |
Why does Python 3.4.3 using lxml not output print statement correctly?
|
<p>While I'm trying to run through an lxml tutorial, I couldn't help but wonder why when I use the print command, the output to the screen keeps wanting to put everything on one line even with pretty_print=True.</p>
<p>So say I just installed Python 3.4.3 64-bit and installed lxml-3.4.0.win32-py3.4.exe after Python was installed.</p>
<p>Then, in IDLE or at the python.exe cmd prompt, I do the following:</p>
<pre><code>from lxml import etree
root = etree.XML('<root><a><b/></a></root>')
print(etree.tostring(root, pretty_print=True))
</code></pre>
<p>What I (and the tutorial) expected was the following output to the screen:</p>
<pre><code><root>
<a>
<b/>
</a>
</root>
</code></pre>
<p>But what I actually see in both IDLE and the python cmd prompt in the Windows 7 is this:</p>
<pre><code>b'<root>\n <a>\n <b/>\n </a>\n</root>\n'
</code></pre>
<p>So why does the interpreter do this? Is there a way to toggle between single-line mode and the more normal standard output? And perhaps more importantly, if I want to write this XML to a file, will Python with the lxml insist on putting the \n and everything else on a line instead of pretty-printing this the way it's supposed to?</p>
<p>Thanks,
Johnny</p>
|
<p>What you see is the representation of the bytes string. You can write bytes directly to a file:</p>
<pre><code>with open("file.xml", "wb") as output:
output.write(etree.tostring(root, pretty_print=True))
</code></pre>
<p><code>print</code> expects an unicode string, so you have to encode to unicode:</p>
<pre><code>print(etree.tostring(root, pretty_print=True, encoding='unicode'))
</code></pre>
|
python|lxml|pretty-print
| 3 |
1,903,277 | 40,898,165 |
Why am I getting an Assertion Error on this Python code?
|
<p>I have a function written here:</p>
<pre><code>def addItem(aBookcase, name, mediaType):
"""
Returns False if aBookcase is full, otherwise returns True and
adds item of given name and mediaType to aBookcase.
"""
pass
emptySpacesBefore = aBookcase.getEmptySpaces()
if aBookcase.getEmptySpaces() == 0:
added = False
return added
else:
position = findSpace(aBookcase)
aBookcase.setName(*position, name=name)
aBookcase.setType(*position, mediaType=mediaType)
added = True
emptySpacesAfter = aBookcase.getEmptySpaces()
assert added is True, "No free positions"
assert emptySpacesAfter < emptySpacesBefore, "Same amount of empty spaces"
assert aBookcase.getName(*position) is name, "Error with name"
assert aBookcase.getType(*position) is mediaType, "Error with media type"
</code></pre>
<p>Yet when I go to test the function with this line of code:</p>
<pre><code>assert addItem(small, "Algorhythms, date structures and compatibility", BOOK)
</code></pre>
<p>I get an 'AssertionError' as shown here:</p>
<p><a href="https://i.stack.imgur.com/G15LR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G15LR.png" alt="Screenshot of 'AssertionError'"></a></p>
<p>So if I'm right, it means I'm not handling it but I'm not sure how or why? Is it something wrong with my code? Something missing? etc. </p>
|
<p>when it works properly, your <code>addItem</code> function returns nothing, so it returns <code>None</code>, which is seen as a failure by the last <code>assert</code> statement that you inserted. You should return <code>added</code> for both cases (<code>True</code> or <code>False</code>)</p>
<p>BTW since you reached that line, it means that all previous assertions are OK so good news: your code is OK.</p>
|
python|function|python-3.x|assert
| 1 |
1,903,278 | 38,150,308 |
How can I initialize a python threaded socketserver with another class?
|
<p>I am writing a python irc bot, and I would like to add a tcp server so the bot can echo messages sent to it in irc channels. I am using the python socketserver module so that it supports both linux and freebsd (I use both). I have a short testing script here:</p>
<pre><code>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import socketserver
from threading import Thread
class announce():
""" Return message uppercase """
def uppercase(message):
print (message.upper())
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
""" Echo data back in uppercase """
def handle(self):
self.announce = announce
data = str(self.request.recv(1024), 'utf-8')
if data is not None:
self.announce.uppercase(data)
self.request.send(bytes("message recieved", 'utf-8'))
self.request.close()
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
daemon_threads = True
allow_reuse_address = True
def __init__(self, server_address, RequestHandlerClass):
socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)
if __name__ == "__main__":
HOST = "localhost"
PORT = 2000
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
server.shutdown()
server.server_close()
</code></pre>
<p>What I want to be able todo is have the irc bot start the tcp server, and have the tcp server send any data it receives to the bot.</p>
<p>The full (non-working) bot code is here: <a href="https://github.com/meskarune/autobot/blob/master/src/autobot.py" rel="nofollow">https://github.com/meskarune/autobot/blob/master/src/autobot.py</a></p>
<p>Below is a truncated version with the relevant pieces:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
class AutoBot(irc.bot.SingleServerIRCBot):
"""Create the single server irc bot"""
def __init__(self):
self.config = configparser.ConfigParser()
self.config.read("autobot.conf")
self.nick = self.config.get("irc", "nick")
self.nickpass = self.config.get("irc", "nickpass")
self.name = self.config.get("irc", "name")
self.network = self.config.get("irc", "network")
self.port = int(self.config.get("irc", "port"))
self._ssl = self.config.getboolean("irc", "ssl")
self.channel_list = [channel.strip() for channel in self.config.get("irc", "channels").split(",")]
self.prefix = self.config.get("bot", "prefix")
if self._ssl:
factory = irc.connection.Factory(wrapper=ssl.wrap_socket)
else:
factory = irc.connectionFactory()
try:
irc.bot.SingleServerIRCBot.__init__(self, [(self.network, self.port)],
self.nick, self.name,
reconnection_interval=120,
connect_factory = factory)
except irc.client.ServerConnectionError:
sys.stderr.write(sys.exc_info()[1])
#Listen for data to announce to channels
self.listenhost = self.config.get("tcp", "host")
self.listenport = int(self.config.get("tcp", "port"))
TCPinput(self.connection, self, self.listenhost, self.listenport)
def announce(self, connection, text):
"""Send notice to joined channels"""
for channel in self.channel_list:
self.connection.notice(channel, text)
self.log_message(channel, "-!-", "(notice) {0}: {1}"
.format(self.connection.get_nickname(), text))
class TCPinput():
"""Listen for data on a port and send it to Autobot.announce"""
def __init__(self, connection, AutoBot, listenhost, listenport):
self.connection = connection
self.AutoBot = AutoBot
self.listenhost = listenhost
self.listenport = listenport
server = ThreadedTCPServer((self.listenhost, self.listenport), ThreadedTCPRequestHandler)
try:
server.serve_forever()
except:
server.shutdown()
server.server_close()
def send(self, message):
self.AutoBot.announce(self.connection, message.strip())
class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
""" Echo data back in uppercase """
def handle(self):
self.TCPinput = TCPinput
data = str(self.request.recv(1024), 'utf-8')
if data is not None:
self.TCPinput.send(data.strip())
self.request.close()
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
daemon_threads = True
allow_reuse_address = True
def __init__(self, server_address, RequestHandlerClass):
socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass)
def main():
bot = AutoBot()
bot.start()
if __name__ == "__main__":
main()
</code></pre>
<p>With the current code the bot hangs upon running and when I do ctrl-c it connects and then crashes. I'd really love to know how I can get this working. Thanks.</p>
|
<p>Inside <code>TCPinput</code>, you are calling <code>serve_forever</code> within the main thread of control, causing it to block. Instead, you need to run the server within a separate thread. You can achieve this by deriving <code>TCPinput</code> from <code>threading.Thread</code>, setting <code>serve_forever</code> as the thread target when initializing the object. Then, while initializing the bot, you can <code>Thread.start()</code> that thread.</p>
|
python|python-3.x
| 1 |
1,903,279 | 30,873,361 |
change an image in pygame after a length of time
|
<p>Hi I am new to this site.
Here is the question.</p>
<p>Currently the program displays an image which is supposed to be the start up screen for three seconds.
I then want it to stop displaying the first image and display another one instead continuously.
I am using pygame version 1.9.1 and python version 2.7.9.
The code is below.
Thanks in advance too.</p>
<pre><code> import pygame, sys
from pygame.locals import *
pygame.init()
gameDisplay=pygame.display.set_mode((600,600))
pygame.display.set_caption("Platypus")
white=255,255,255
black=0,0,0
red=255,0,0
important_platypus=pygame.image.load("C:/Users/Sarah_2/Pictures/no_one_knows_why_Duck_Billed_Platypi_are_important.jpg")
important_platypus=pygame.transform.scale(important_platypus,(600,600))
gameExit=False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameDisplay.blit(important_platypus, (0, 0) )
pygame.display.update()
pygame.quit()
quit()
</code></pre>
|
<p><code>time.sleep</code> is the function you want. Below is a full example:</p>
<pre><code> import pygame, sys
from pygame.locals import *
pygame.init()
gameDisplay=pygame.display.set_mo de((600,600))
pygame.display.set_caption ("Platypus")
time.sleep(3)
gameDisplay=pygame.display.set_mo de((600,600))
pygame.display.set_caption ("second image")
</code></pre>
|
python|image|background|pygame
| 0 |
1,903,280 | 30,791,228 |
Serving a django static text file
|
<p>I have a text file in the static folder in my project root. </p>
<p>I'd like to serve it so I've created:</p>
<pre><code>@csrf_exempt
def display_text(request):
content =
return HttpResponse(content, content_type='text/plain; charset=utf8')
</code></pre>
<p>How do I set the path to the textfile, or how do I read it in to 'content', so that I can display it.</p>
|
<p>Have a look at <a href="https://stackoverflow.com/questions/1156246/having-django-serve-downloadable-files">this question</a> that lets Apache handle the file delivery with <code>mod_xsendfile</code>.</p>
<p>If you insist on having Django itself delivering the file, you could do the following:</p>
<pre><code>from django.http import StreamingHttpResponse
@csrf_exempt
def display_text(request):
content = open('/your/file', 'r').read()
response = StreamingHttpResponse(content)
response['Content-Type'] = 'text/plain; charset=utf8'
return response
</code></pre>
|
python|django
| 5 |
1,903,281 | 29,106,899 |
Can you clarify this referencing issue in Python?
|
<p>I'm used to pointers and references, but I need some clarification on this point:</p>
<p>I have this method in my Node class:</p>
<pre><code>def createNewNode(graph):
#Create New Node Dictionary
newNode = {}
# Fill in Details for that Node
newNode['NAME'] = 'Max'
newNode['AGE'] = 22
newNode['ID'] = 'DC1234SH987'
#Add the Node to the Graph
graph.addNode(newNode)
</code></pre>
<p>The scope of the <code>newNode</code> created is within the function <code>createNewNode()</code>. Now this Node is added to a list of nodes in the Graph class.</p>
<p>The Graph class has this function:</p>
<pre><code>def addNode(self, node):
self.nodeList.append(node)
</code></pre>
<p>Now the Graph class function <code>addNode()</code> just appends the node to the list of nodes in the graph class. After the call to <code>graph.addNode()</code> in the node class, when does the scope of the <code>newNode</code> variable stop existing?</p>
<p>Won’t the data that was appended to the list in the Graph class be invalid now?
Does <code>append()</code> makes a new copy of the object passed? Can you explain this to me?</p>
<p>(In this example, the graph just contains a list of nodes and the node is actually a dictionary with details.)</p>
|
<p>The name <code>newNode</code> goes out of scope, but the object it refers to is not destroyed. You added another reference to that object by appending it to <code>nodeList</code>. <code>append</code> doesn't make a copy, but it does create a separate reference to the same object. A <em>name</em> goes out of scope when the function it is in ends, but an <em>object</em> is only garbage collected when <em>all</em> references to it are gone.</p>
|
python|python-2.7|reference|concept
| 5 |
1,903,282 | 29,144,921 |
Numpy local maximas in one dimension of 2D array
|
<p>I'd like to find the local maximas of a 2D array but only in one dimension. Ie:</p>
<pre><code>1 2 3 2 1 1 4 5 6 2
2 2 3 3 3 2 2 2 2 2
1 2 3 2 2 2 2 3 3 3
</code></pre>
<p>would return:</p>
<pre><code>0 0 1 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0 1 0
</code></pre>
<p>Obviously this is trivial to solve by iterating through the array, but this is slow and usually avoidable. Is there a fast way of achieving this?</p>
<p>Edit:
I've devised a faster solution:</p>
<p>import numpy as np</p>
<pre><code>testArray = np.array([[1,2,3,2,1,1,4,5,6,2],[2,2,3,3,3,2,2,2,2,2],[1,2,3,2,2,2,2,3,3,3] ])
leftShift = np.roll(testArray,1, axis=1)
rightShift = np.roll(testArray,-1, axis=1)
Max = ((testArray>leftShift) & (testArray>rightShift) )*1
print(Max)
</code></pre>
<p>Which returns:</p>
<pre><code>[[0 0 1 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0]]
</code></pre>
<p>This is the right result except for repeated readings. Ie.. what differentiates "13331" (maxima) from "13333789" (stationary point)</p>
|
<p>You can solve this by applying finite difference gradient to each row and check sign change.
However it is not clear what to do at the boundaries.</p>
|
python|arrays|numpy
| 1 |
1,903,283 | 52,206,801 |
MySQL-python installation failed from python-alpine
|
<p>I'm going to build a docker image by the following Dockerfile:</p>
<pre><code>FROM python:2.7-alpine
RUN set -ex \
&& apk --no-cache add --virtual build-dependencies \
&& pip install --no-cache-dir mysql-python
</code></pre>
<p>It downloads the package via:</p>
<pre><code>Downloading https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip (108kB)
</code></pre>
<p>and executes</p>
<pre><code>python setup.py install
</code></pre>
<p>but it failes and returns the following error:</p>
<pre><code>_mysql.c: In function '_mysql_ConnectionObject_ping':
_mysql.c:2005:41: error: 'MYSQL {aka struct st_mysql}' has no member named 'reconnect'
if ( reconnect != -1 ) self->connection.reconnect = reconnect;
^
error: command 'gcc' failed with exit status 1
</code></pre>
<p>but when I try with:</p>
<pre><code>FROM python:2.7
</code></pre>
<p>it prefectly works.
any idea?</p>
|
<p>Solution is to use <strong>mysqlclient</strong> package instead of MySQL-python, it's a fork that solves multiple issues current MySQL-python has.</p>
<p><a href="https://github.com/PyMySQL/mysqlclient-python" rel="nofollow noreferrer">https://github.com/PyMySQL/mysqlclient-python</a></p>
|
python|mysql|docker
| 4 |
1,903,284 | 52,166,769 |
Astropy Coordinates: Second Nearest Neighbour
|
<p>I am using <code>Astropy.coordinates</code> to match two astronomical catalogues with RA,DEC coordinates. </p>
<p>I can find the list of nearest neighbours by following the <code>astropy</code> documentation<a href="http://docs.astropy.org/en/stable/coordinates/matchsep.html" rel="nofollow noreferrer">(link to astropy.coordinates documentation)</a> and doing:</p>
<pre><code>from astropy.coordinates import SkyCoord
from astropy import units as u
cat1 = SkyCoord(ra=ra1*u.degree, dec=dec1*u.degree)
cat2 = SkyCoord(ra=ra2*u.degree, dec=dec2*u.degree)
idx, d2d, d3d = cat1.match_to_catalog_sky(cat2)
</code></pre>
<p>Where <code>ra1</code>, <code>ra2</code>, <code>dec1</code>, <code>dec2</code> are vectors containing the coordinates in the catalogues 1 and 2. </p>
<p>The result <code>idx</code> gives, for each object in the catalogue 1, the id of nearest match in the catalogue 2. <code>d2d</code> gives the 2d separation between the matches, and <code>d3d</code> gives the 3d separation between the matches. </p>
<p>Therefore, to select matches between a desired matching radius, for example, using a 1" radii, I can do:</p>
<pre><code>matched=idx[np.argwhere(d2d<1.*u.arcsec)[0]]
</code></pre>
<p>Now, in order to chose what is the appropriate radii for this last step, I would like to examine what is the distance <code>d2d</code> between each source in <code>cat1</code>and their second-nearest-neighbour. </p>
<p>Does anyone knows how can I do this matching process while also recording the second neighbours? </p>
|
<p>Note that <code>match_to_catalog_sky</code> takes a keyword <code>nthneighbor</code> which defaults to 1 (i.e., nearest) but can be set to other values. Changing this should do it.</p>
<p>It seems like you may also want to pay attention to <code>search_around_sky</code> method using which you can find all matches up to a separation limit.</p>
|
python|coordinate-systems|astronomy|astropy
| 1 |
1,903,285 | 59,631,779 |
Python Project Structure - multiple files and modules
|
<p>I was used to PHP where a global variable will be available on the whole project, and including/requiring a PHP file is pretty much just like 'injecting' it's code lines on that spot: the whole thing would be 'seen' as a single file, and all vars would be instinctively acessed.</p>
<p>Python works in a different way and I'd like to know good practices in order to make a large project more manageable by splitting it into files...</p>
<p>So lets say I have a file called configs.py that's something like:</p>
<pre><code>FRAME_DURATION = int(1000 / 25)
SCREEN_SIZE = 500
LIGHT_GREY = (190,190,190)
RED = (255,0,0)
GREEN = (0,255,0)
YELLOW = (255,255,0)
#etc...
</code></pre>
<p>Then, on the Main.py file I could do something like:</p>
<pre><code>import pygame
from configs import *
pygame.init()
SCREEN = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE),1)
SCREEN.fill(LIGHT_GREY)
run = True
while run:
pygame.time.delay(FRAME_DURATION )
#HERE I'M SUPPOSED TO CHECK THE KEYBOARD AND MOUSE EVENTS
pygame.display.update()
pygame.quit()
</code></pre>
<p>And this work just fine since we're handling only variables. But if i want to make the event listener into another separate file I run into some 'troubles'. Let's say I want a file with all my functions. I'll name it actions.py and it contains the following function:</p>
<pre><code>def checkEvents():
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.key == pygame.K_r:
pass
</code></pre>
<p>If I want to be able to call the checkEvents() function inside the main.py file I get a NameError sinceit doesn't recognizes pygame module inside the actions.py file.</p>
<p>I can't seem to make it work: if i import it on both files (which i know is sup-optimal), the game launches but keys and exit key don't do nothing. I guess the checkEvents() function is listening to another instance of pygame?</p>
<p>Anyway, I'd like to know if there's a way to make modules 'globally available'... Importing it once on main file and using it on the whole project, including inside other imported custom modules?</p>
<p>The final result should look something like this:</p>
<pre><code>import pygame
from configs import *
import actions
pygame.init()
SCREEN = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE),1)
SCREEN.fill(LIGHT_GREY)
run = True
while run:
pygame.time.delay(FRAME_DURATION )
actions.checkEvents()
pygame.display.update()
pygame.quit()
</code></pre>
|
<p>You have to only <code>import pygame</code> in <code>actions.py</code></p>
<p>Other problem is <code>run</code> which you have to return from <code>checkEvents()</code></p>
<pre><code>import pygame
def checkEvents():
run = True # local variable with default value before all tests
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # set local variable
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False # set local variable
if event.key == pygame.K_r:
pass
return run # return local value to main code
</code></pre>
<p>And then you get <code>run</code> in <code>main.py</code></p>
<pre><code>import pygame
from configs import *
import actions
pygame.init()
SCREEN = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE),1)
SCREEN.fill(LIGHT_GREY)
run = True
while run:
pygame.time.delay(FRAME_DURATION )
run = actions.checkEvents() # get result from function and assign to `run`
pygame.display.update()
pygame.quit()
</code></pre>
|
python|scope|architecture|python-import|python-module
| 1 |
1,903,286 | 19,236,698 |
Convert year, day of year and fractional hour to a real date in python
|
<p>I would like to convert arrays of year, day of year and fractional hours to a real date.
Thats my code up to now:<pre></p>
<code>year = [2012,2012,2012]
day = [2,3,4] #day of year
hour = [12,12,12]
import datetime
import pytz
dt=list()
for i in range(len(year)):
dt.append(datetime.datetime(year[i], day[i], hour[i],tzinfo=pytz.UTC))
dt=np.array(dt)
print dt `
</code></pre>
|
<p>The constructor for <a href="http://docs.python.org/2/library/datetime.html#datetime.datetime" rel="nofollow"><code>datetime</code></a> objects takes a year, month, and day, and optional hour, minute, etc. So, you're passing the day as the month, the hour as the day, and nothing as the hour.</p>
<p>On top of that, <code>day</code> has to be a day of the month, not a day of the year, and <code>hour</code> has to be an integer (with separate minutes, seconds, and microseconds if appropriate).</p>
<p>One easy way around this is to create a <code>datetime</code> with the start of the year, and add the days and hours on with <code>timedelta</code>.</p>
<p>While we're at it, you can make the code a bit cleaner by iterating directly over the arrays instead of over <code>range(len(…))</code>.</p>
<pre><code>for y, d, h in zip(year, day, hour):
d0 = datetime.datetime(y, 1, 1, tzdata=pytz.UTC)
dt.append(d0 + datetime.timedelta(days=d, hours=h))
</code></pre>
<hr>
<p>As a side note, I'd name the list variables <code>years</code>, <code>days</code>, <code>hours</code>, and <code>dts</code>, so I could name the individual iteration values <code>year</code>, <code>day</code>, <code>hour</code>, and <code>dt</code>. And, while we're at it, I'd write this as a helper function and a list comprehension rather than a <code>for</code> loop and a complicated body. And put the imports at the time. Like this:</p>
<pre><code>import datetime
import pytz
years = [2012,2012,2012]
days = [2,3,4] #day of year
hours = [12,12,12]
def make_date(year, day, hour, tzdata=pytz.UTC):
dt = datetime.datetime(year, 1, 1, tzdata=tzdata)
return dt + datetime.timedelta(days=day, hours=hour)
dts = [make_date(year, day, hour) for year, day, hour in zip(years, days, hours)]
</code></pre>
<hr>
<p>The above works for your original question, where <code>years</code> and <code>days</code> are lists of integers and <code>hours</code> is a list of floats (as in your description) or integers (as in your sample code). It will also work if <code>days</code> is a list of floats, but not <code>years</code>.</p>
<p>However, from a comment, it sounds like these are actually numpy arrays of <code>int64</code> values. Although you call them floats, <code>int64</code> is not a floating-point type, it's an integer type. And you can convert an <code>int64</code> to a plain Python <code>int</code> with no loss of range or precision.</p>
<p>So, because the <code>datetime</code> and <code>timedelta</code> constructors won't accept <code>int64</code> values, just convert each one into an <code>int</code>:</p>
<pre><code>def make_date(year, day, hour, tzdata=pytz.UTC):
dt = datetime.datetime(int(year), 1, 1, tzdata=tzdata)
return dt + datetime.timedelta(days=int(day), hours=int(hour))
</code></pre>
<p>If your hours were actually of a floating-point type as you originally claimed, like <code>float64</code>, you'd want to use <code>float(hour)</code> instead of <code>int(hour)</code>.</p>
<hr>
<p>One last thing: From your description, I guessed that your days were 0-based (and your hours, but that's not likely to be wrong). If your days are actually 1-based, you're obviously going to need to do <code>days=int(day)-1</code>.</p>
|
python
| 1 |
1,903,287 | 67,365,218 |
CUDA version of package not importing?
|
<p>Firstly, I installed torch 1.1.0, and then I installed its' dependencies. So, I can import torch_scatter 1.2.0 however I get this error when importing torch_scatter.scatter_cuda:</p>
<pre><code> import torch_scatter.scatter_cuda
ModuleNotFoundError: No module named 'torch_scatter.scatter_cuda'
</code></pre>
<p>I have Cuda v10 installed and I have a GPU. All of the requirements for this code were installed together through pip in one go on my virtual environment.</p>
|
<p>As pointed out by phd - it looks like the setup.py file of pytorch_scatter checks for and uses an available cuda installation automatically.</p>
<p>Also in the version you are using as seen <a href="https://github.com/rusty1s/pytorch_scatter/blob/1.2.0/setup.py" rel="nofollow noreferrer">here</a>:</p>
<pre><code>...
if CUDA_HOME is not None:
ext_modules += [
CUDAExtension('torch_scatter.scatter_cuda',
['cuda/scatter.cpp', 'cuda/scatter_kernel.cu'])
]
...
</code></pre>
<p>Might be a question of whether <code>CUDA_HOME</code> is available.</p>
<p>Installing from source might give you more information as suggested <a href="https://github.com/rusty1s/pytorch_scatter/issues/23" rel="nofollow noreferrer">here</a>.</p>
|
python|terminal|pip|pytorch|torch
| 1 |
1,903,288 | 67,574,403 |
Why I am getting this "NameError: name 'trainingData' is not defined"
|
<p>I a trying to import training.txt data as follows.</p>
<pre><code>def readTrainingData(training):
trainingData=[]
with open(training.txt) as f:
for line in f:
a1, a2 = line.strip().split()
trainingData.append((a1, a2))
return trainingData
</code></pre>
<p>After that I am trying to use the traingdata to mesure some score as follows:</p>
<pre><code>for pair in trainingData:
linkScores[pair[0]+''+pair[1]]= computeProximityScore(pair[0],pair[1],'Jaccard',neighbors)
</code></pre>
<p>But it's giving an error</p>
<pre><code>
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-17-2532640f4771> in <module>
----> 1 trainingData
NameError: name 'trainingData' is not defined
</code></pre>
<p>Would anybody help me,please?</p>
<p>Thanks</p>
|
<p>I didn't understand what you have tried to when you passed the variable <code>training</code> to the function.
But when you open a file you need to do it like that:</p>
<pre><code>```with open("file_name.txt") as f:```
</code></pre>
<p>Also, you can't access the variable <code>trainingData</code> outside of the function.</p>
<p>I updated your code(I hope its what you intended to):</p>
<p><strong>Main( Or any other place you run the function):</strong></p>
<pre><code>trainingData = readTrainingData("training.txt")
# The rest of your code.
</code></pre>
<p><strong>Your Function:</strong></p>
<pre><code>def readTrainingData(training):
trainingData = []
with open(training) as f:
for line in f:
a1, a2 = line.strip().split()
trainingData.append((a1, a2))
return trainingData
</code></pre>
|
python-3.x|nameerror
| 1 |
1,903,289 | 67,493,095 |
Is a .pth file a security risk, and how can we sanitise it?
|
<p>It's well-established that pickled files are [unsafe][1] to simply load directly. However, the advice on that SE post concludes that basically one should not use a pickled file if they are not sure of its provenance.</p>
<p>What about PyTorch machine-learning models that are stored as <code>.pth</code> files on, say, public repos on Github, which we want to use for inference? For example, if I have a <code>model.pth</code> which I plan to load with <code>torch.load(model.pth)</code>, is it necessary to check it's safe to do so? Assuming I have no choice but to use the model, how should one go about checking it?</p>
<p>Given these models are ultimately just weights, could we do something like make a minimal Docker container with PyTorch, load the model inside there, and then resave the weights? Is this necessary, and what sort of checking should we do (i.e. assuming it is safe to load within the container, what sort of code treatment should be applied to sanitise the model for shipping?).</p>
<p>EDIT: response to asking for clarification: say I have a <code>model.pth</code> - (1) do I need to be careful with it, like I would with a .pkl, given a .pth is meant to contain only model weights? Or can I just go ahead and throw it into <code>torch.load(model.pth)</code>? (2) If I can't, what can I do before <code>torch.load()</code> to provide some peace-of-mind?</p>
<p>EDIT 2: An answer should show some focus on ML pretrained models in particular. An example: see the model <a href="https://download.pytorch.org/models/resnet34-333f7ec4.pth" rel="nofollow noreferrer">https://download.pytorch.org/models/resnet34-333f7ec4.pth</a> (warning: 80 MB download from TorchHub - feel free to use another Resnet .pth model, but any cleaning does need to be reasonably fast). Currently I would download this and then load it in PyTorch using <code>load_state_dict</code> (explained in detail [here][2] for example). If I didn't know this was a safe model, how could I try to sanitise it first before loading it in <code>load_state_dict</code>?</p>
<pre><code>
[1]: https://stackoverflow.com/questions/25353753/python-can-i-safely-unpickle-untrusted-data
[2]: https://www.programmersought.com/article/95324315915/
</code></pre>
|
<p>As pointed out by <code>@MobeusZoom</code>, this is answer is about Pickle and not PyTorch format. Anyway as <a href="https://pytorch.org/docs/stable/generated/torch.load.html" rel="nofollow noreferrer">PyTorch load mechanism relies on Pickle behind the scene</a> observations drawn in this answer still apply.</p>
<h3>TL;DR;</h3>
<blockquote>
<p>Don't try to sanitize pickle. Trust or reject.</p>
</blockquote>
<p>Quoted from Marco Slaviero in his presentation <a href="https://www.youtube.com/watch?v=HsZWFMKsM08" rel="nofollow noreferrer">Sour Pickle at the Black Hat USA 2011</a>.</p>
<p>Real solution is:</p>
<ul>
<li>Don't setup exchange with unequally trusted parties;</li>
<li>Setup a secure transport layer for exchange;</li>
<li>Sign exchanged files;</li>
</ul>
<p>Also be aware that there are new kind of AI based attacks, this even if the pickle is shellcode free, you still may have other issues to address when loading pre-trained networks from untrusted sources.</p>
<h3>Important notes</h3>
<p>From the presentation linked above we can draw several important notes:</p>
<ul>
<li>Pickle use a Virtual Machine to reconstruct live data (PVM happens alongside the python process), this virtual machine is not Turing complete but has: an instruction set (opcodes), a stack for the execution and a memo to host object data. This is enough for attacker to create exploits.</li>
<li>Pickle mechanism is backward compatible, it means latest Python can unpickle the very first version of its protocol.</li>
<li>Pickle can (re)construct any object as long as PVM does not crash, there is no consistency check in this mechanism to enforce object integrity.</li>
<li>In broad outline, Pickle allows attacker to execute shellcode in any language (including python) and those code can even persist after the victim program exits.</li>
<li>Attacker will generally forge their own pickles because it offers more flexibility than naively using pickle mechanism. Off course they can use pickle as an helper to write opcode sequences. Attacker can craft the malicious pickle payload in two significant ways:
<ul>
<li>to prepend the shellcode to be executed first and leave the PVM stack clean. Then you probably get a normal object after unpickling;</li>
<li>to insert the shellcode into the payload, so it gets executed while unpickling and may interact with the memo. Then unpickled object may have extra capabilities.</li>
</ul>
</li>
<li>Attackers are aware of "safe unpickler" and know how to circumvent them.</li>
</ul>
<h3>MCVE</h3>
<p>Find below a very naive MCVE to evaluate your suggestion to encapsulate cleaning of suspect pickled files in Docker container. We will use it to assess main associated risks. Be aware, real exploit will be more advanced and complexer.</p>
<p>Consider the two classes below, <code>Normal</code> is what you expect to unpickle:</p>
<pre><code># normal.py
class Normal:
def __init__(self, config):
self.__dict__.update(config)
def __str__(self):
return "<Normal %s>" % self.__dict__
</code></pre>
<p>And <code>Exploit</code> is the attacker vessel for its shellcode:</p>
<pre><code># exploit.py
class Exploit(object):
def __reduce__(self):
return (eval, ("print('P@wn%d!')",))
</code></pre>
<p>Then, the attacker can use pickle as an helper to produce intermediate payloads in order to forge the final exploit payload:</p>
<pre><code>import pickle
from normal import Normal
from exploit import Exploit
host = Normal({"hello": "world"})
evil = Exploit()
host_payload = pickle.dumps(host, protocol=0) # b'c__builtin__\neval\np0\n(S"print(\'P@wn%d!\')"\np1\ntp2\nRp3\n.'
evil_payload = pickle.dumps(evil, protocol=0) # b'(i__main__\nNormal\np0\n(dp1\nS"hello"\np2\nS"world"\np3\nsb.'
</code></pre>
<p>At this point the attacker can craft a specific payload to both inject its shellcode and returns the data.</p>
<pre><code>with open("inject.pickle", "wb") as handler:
handler.write(b'c__builtin__\neval\np0\n(S"print(\'P@wn%d!\')"\np1\ntp2\nRp3\n(i__main__\nNormal\np0\n(dp1\nS"hello"\np2\nS"world"\np3\nsb.')
</code></pre>
<p>Now, when victim will deserialize the malicious pickle file, the exploit is executed and a valid object is returned as expected:</p>
<pre><code>from normal import Normal
with open("inject.pickle", "rb") as handler:
data = pickle.load(handler)
print(data)
</code></pre>
<p>Execution returns:</p>
<pre><code>P@wn%d!
<Normal {'hello': 'world'}>
</code></pre>
<p>Off course, shellcode is not intended to be so obvious, you may not notice it has been executed.</p>
<h3>Containerized cleaner</h3>
<p>Now, lets try to clean this pickle as you suggested. We will encapsulate the following cleaning code:</p>
<pre><code># cleaner.py
import pickle
from normal import Normal
with open("inject.pickle", "rb") as handler:
data = pickle.load(handler)
print(data)
cleaned = Normal(data.__dict__)
with open("cleaned.pickle", "wb") as handler:
pickle.dump(cleaned, handler)
with open("cleaned.pickle", "rb") as handler:
recovered = pickle.load(handler)
print(recovered)
</code></pre>
<p>Into a Docker image to try to contain its execution. As a baseline, we could do something like this:</p>
<pre><code>FROM python:3.9
ADD ./exploit ./
RUN chown 1001:1001 inject.pickle
USER 1001:1001
CMD ["python3", "./cleaner.py"]
</code></pre>
<p>Then we build the image and execute it:</p>
<pre><code>docker build -t jlandercy/doclean:1.0 .
docker run -v /home/jlandercy/exploit:/exploit jlandercy/doclean:1.0
</code></pre>
<p>Also ensure the mounted folder containing the exploit has restrictive <em>ad hoc</em> permissions.</p>
<pre><code>P@wn%d!
<Normal {'hello': 'world'}> # <-- Shellcode has been executed
<Normal {'hello': 'world'}> # <-- Shellcode has been removed
</code></pre>
<p>Now the <code>cleaned.pickle</code> is shellcode free. Off course you need to carefully check this assumption before releasing the cleaned pickle.</p>
<h3>Observations</h3>
<p>As you can see, Docker image does not prevent the exploit to be executed when unpickling but it may help to contain the exploit in some extent.</p>
<p>Points of attention are (not exhaustive):</p>
<ul>
<li>Having a recent pickle file with the original protocol is a hint but not an evidence of something suspicious.</li>
<li>Be aware even if containerized, <strong>you still are running attacker code on your host</strong>;</li>
<li>Additionally, <strong>attacker may have designed its exploit to break a Docker container</strong>, use unprivileged user to reduce the risk;</li>
<li>Don't bind any network to this container as attacker can start a terminal and expose it over a network interface (and potentially to the web);</li>
<li>Depending on how the attacker has designed its exploit data may not be available at all. For the instance, if <code>__reduce__</code> method actually returns the exploit instead of a recipe to recreate the desired instance. After all the main purpose of this is to make you unpickling it nothing more;</li>
<li>If you intend to dump raw data after loading the suspicious pickle archive you need a strict procedure to detach data from the exploit;</li>
<li>The cleaning step can be a limitation. It relies on your ability to recreate the intended object from the malicious payload. It will depends on what is really reconstructed from the pickle file and how the desired object constructor needs to be parametrized;</li>
<li>Finally, if you are confident in your cleaning procedure, you can mount a volume to access the result after the container exits.</li>
</ul>
|
python|machine-learning|pytorch|pickle
| 2 |
1,903,290 | 63,470,164 |
Can I change the default __add__ method in Python?
|
<p>Is it possible to change the default <code>__add__</code> method to do something else than just add?</p>
<p>For example, if the goal is with this line:
<code>5+5</code> get <code>The answer is 10</code> or anything else like <code>0</code> by changing <code>__add__</code> to be <code>x-y</code> instead of <code>x+y</code>?</p>
<p>I know I can change <code>__add__</code> in my own classes:</p>
<pre><code>class Vec():
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return f'{self.x, self.y}'
def __add__(self, other):
self.x += other.x
self.y += other.y
return Vec(self.x,self.y)
v1 = Vec(1,2)
v2 = Vec(5,3)
v1+v2
# (6, 5)
</code></pre>
<p>Can I somehow target the default <code>__add__</code> method to change its behaviour? I intuitively think that <code>__add__</code> is defined in each default data type to return specific results, but then again, the <code>__add__</code> method is what we address when changing it for a specific class, so, is it possible to change the main <code>__add__</code> logic?</p>
<p>Something along these lines?</p>
<pre><code>class __add__():
...
</code></pre>
|
<p>Yes, you can overload whatever in user defined classes.</p>
<pre class="lang-py prettyprint-override"><code>class Vec():
def __init__(self,x,y):
self.x = x
self.y = y
def __repr__(self):
return f'{self.x, self.y}'
def __add__(self, other):
self.x += other.x
self.y += other.y
return Vec(self.x,self.y)
v1 = Vec(1,2)
v2 = Vec(5,3)
print(v1+v2)
# using lambda function
Vec.__add__ = lambda self,other: Vec(self.x-other.x,self.y-other.y)
print(v1+v2)
# using "normal" function
def add(self,other):
self.x -= other.x
self.y -= other.y
return Vec(self.x,self.y)
Vec.__add__ = add
print(v1+v2)
</code></pre>
<p>Will not work for built-in types, e.g. resulting in <code>TypeError: can't set attributes of built-in/extension type 'set'</code></p>
<p>Also please note that your implementation of <code>__add__</code> modifies the original instance, which I don't like.. (just my note)</p>
|
python|magic-methods
| 2 |
1,903,291 | 19,434,492 |
How to I convert a Python script to a executable?
|
<p>So far I have tried <code>bbfreeze</code>, <code>cx_freeze</code>, <code>py2exe</code> and <code>pyInstaller</code> with no success.</p>
<p>All I want to do is to make the Python script into an executable so that others can see my work without needing to install Python.</p>
<p>And if I have to install any of these that I have listed above, what do I do with the files?</p>
|
<p>While some of those scripts are available on Linux, I don't think you can actually build an exe for Windows using it on Linux. So instead, you should create the executable on a machine with the OS you are targeting. Then you can create an installer with Inno Setup (or similar) to make it very easy for the end user to install. Here are a couple of articles I wrote on the process:</p>
<ul>
<li><a href="http://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/" rel="nofollow">http://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/</a></li>
<li><a href="http://www.blog.pythonlibrary.org/2008/08/27/packaging-wxpymail-for-distribution/" rel="nofollow">http://www.blog.pythonlibrary.org/2008/08/27/packaging-wxpymail-for-distribution/</a></li>
</ul>
|
python|executable|py2exe
| 0 |
1,903,292 | 13,319,442 |
How to add uneven sub-lists in Python?
|
<p>So lets say I have a list with sub-lists (alignment for visual demonstration):</p>
<pre><code>[[1,2,3,4],
[1,2,3],
[0,3,4]]
</code></pre>
<p>And I want to add them together to get:</p>
<pre><code>[2,7,10,4]
</code></pre>
<p>Originally, for the thing I am working on, I knew an upper bound of these lists, I was thinking about iterating through every sub-list and adding a 0 padding and making each list as long as the upper bound:</p>
<pre><code>result+=[0]*(len(upper_bound)-len(list))
</code></pre>
<p>Then use:</p>
<pre><code>result = [sum(x) for x in zip(list1,list2)
</code></pre>
<p>to get the sum. But the upper bound gets really large (like 10000+) and the number of lists is a lot as well (like 1000+ lists).</p>
<p>My question is: Is there a more efficient method to add N potentially unevenly sized sublists to give a resultant list, or am I asking too much? (I also <em>cannot</em> use any fancy numerical libraries like numpy)</p>
|
<p><a href="http://docs.python.org/2.7/library/itertools.html#itertools.izip_longest" rel="noreferrer"><code>itertools.izip_longest</code></a> can do what you need:</p>
<pre><code>import itertools
lists = [[1,2,3,4],
[1,2,3],
[0,3,4]]
print [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]
# prints [2, 7, 10, 4]
</code></pre>
|
python|python-2.x
| 7 |
1,903,293 | 43,737,713 |
Error in alpha beta prunning algorithm in python
|
<p>In the following pruning, the alpha returned is correct while the beta remains the same, what am i doing wrong?
It's a tree that has the following values at the bottom nodes </p>
<pre><code>tree = [[[5, 1, 2], [8, -8, -9]], [[9, 4, 5], [-3, 4, 3]]]
root = 0
pruned = 0
def children(branch, depth, alpha, beta):
global tree
global root
global pruned
i = 0
for child in branch:
if type(child) is list:
(nalpha, nbeta) = children(child, depth + 1, alpha, beta)
if depth % 2 == 1:
beta = nalpha if nalpha < beta else beta
else:
alpha = nbeta if nbeta > alpha else alpha
branch[i] = alpha if depth % 2 == 0 else beta
i += 1
else:
if depth % 2 == 0 and alpha < child:
alpha = child
if depth % 2 == 1 and beta > child:
beta = child
if alpha >= beta:
pruned += 1
break
if depth == root:
tree = alpha if root == 0 else beta
return (alpha, beta)
def alphabeta(in_tree=tree, start=root, lower=-15, upper=15):
global tree
global pruned
global root
(alpha, beta) = children(tree, start, lower, upper)
if __name__ == "__main__":
print ("(alpha, beta): ", alpha, beta)
print ("Result: ", tree)
print ("Times pruned: ", pruned)
return (alpha, beta, tree, pruned)
if __name__ == "__main__":
alphabeta()
</code></pre>
<p>Is the codes even right, or should i approach it differently?
<strong>EDIT</strong> The problem most likely stems from the modulo(%) in the beta section</p>
<p><strong>EDIT2</strong> UPDATED CODE</p>
<pre><code>tree = [[[1, 8], [5], [6, 4, 7], [9], [3, 2], [6, 10, 2]]]
side = 1
alpha = -1000
beta = 1000
depth = 3
p = []
betacuts=[]
alphacuts=[]
counta=-1
countb=-1
def getLengthLoL(position):
if len(position)==0:
if isinstance(tree,int):
return tree
return len(tree)
if len(position)==1:
if isinstance(tree[p[0]],int):
return tree[p[0]]
return len(tree[p[0]])
if len(position)==2:
if isinstance(tree[p[0]][p[1]],int):
return tree[p[0]][p[1]]
return len(tree[p[0]][p[1]])
if len(position)==3:
if isinstance(tree[p[0]][p[1]][p[2]],int):
return tree[p[0]][p[1]][p[2]]
return len(tree[p[0]][p[1]][p[2]])
if len(position)==4:
if isinstance(tree[p[0]][p[1]][p[2][p[3]]],int):
return tree[p[0]][p[1]][p[2][p[3]]]
return len(tree[p[0]][p[1]][p[2][p[3]]])
def makeMove(move):
global side
if side:
side = 0
else:
side = 1
p.append(move)
def backMove(move):
global side
if side:
side = 0
else:
side = 1
p.pop()
def evaluation(score):
if side==0:
return -1*score
else:
return score
def minmax( alpha, beta, depth ):
global counta
global countb
if depth==0:
return evaluation(getLengthLoL(p))
moves = getLengthLoL(p)
for move in range(int(moves)):
makeMove(move)
val = -1*minmax(-beta,-alpha,depth-1)
backMove(move)
if val >= beta:
betacuts.append(val)
countb += 1
beta=val;
return beta;
if val > alpha:
alphacuts.append(val)
counta += 1
alpha = val;
return alpha
myScore = minmax(alpha,beta,depth)
print (betacuts,alphacuts)
print (myScore)
</code></pre>
<p>This code is printing wrong alphas and betas from the start</p>
|
<p>so this is a more traditional approach. I have not double checked it but I know this is the correct approach. the variable p is encoding the "position". The code will only be accurate if the depth of all the tree's branches are the same. In this case that is why the depth variable is set to 3. A little more work is needed to make it run on any tree.</p>
<pre><code>tree = [[[0,1,2],[-1,2,5],[-2,2,0]],[[-2,-1,-3],[-4,-3,-1],[1,2,8]],[[4,6,1],[1,7,-1],[-2,-4,1]]]
side = 1
alpha = -1000
beta = 1000
depth = 3
p = []
def getLengthLoL(l, address):
item = l
for index in address:
item = item[index]
return len(item) if isinstance(item, list) else item
def makeMove(move):
global side
if side:
side = 0
else:
side = 1
p.append(move)
def backMove(move):
global side
if side:
side = 0
else:
side = 1
p.pop()
def evaluation(score):
if side==0:
return -1*score
else:
return score
def minmax( alpha, beta, depth ):
if depth==0:
return evaluation(getLengthLoL(tree,p))
moves = getLengthLoL(tree,p)
for move in range(int(moves)):
makeMove(move)
val = -1*minmax(-beta,-alpha,depth-1)
backMove(move)
if val >= beta:
return beta;
if val > alpha:
alpha = val;
return alpha
myScore = minmax(alpha,beta,depth)
print myScore
</code></pre>
|
python|algorithm|artificial-intelligence|pruning
| 0 |
1,903,294 | 9,167,282 |
How can i perform inner join with two derived table in django style?
|
<p>This is one derived table:</p>
<pre><code>mysql> select blog_post.id,blog_post.title from blog_post where user_id=2;
+----+--------------------------------------------------------------+
| id | title |
+----+--------------------------------------------------------------+
| 4 | This week at LWN: LCA: Addressing the failure of open source |
| 16 | title week |
+----+--------------------------------------------------------------+
2 rows in set (0.00 sec)
</code></pre>
<p>This is another derived table:</p>
<pre><code>mysql> select object_pk,count(*) as cnt from django_comments group by object_pk;
+-----------+-----+
| object_pk | cnt |
+-----------+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 6 |
| 4 | 13 |
+-----------+-----+
4 rows in set (0.00 sec)
</code></pre>
<p>First i need to make those two derived table in djanto style, then inner join with those tables.</p>
<p>This is the expected final result:</p>
<pre><code>mysql> select blog_post.user_id,blog_post.id,blog_post.title,foo.cnt from blog_post inner join(select object_pk,count(*) as cnt from django_comments group by object_pk) as foo on blog_post.id=foo.object_pk where blog_post.user_id=2;
+---------+----+--------------------------------------------------------------+-----+
| user_id | id | title | cnt |
+---------+----+--------------------------------------------------------------+-----+
| 2 | 4 | This week at LWN: LCA: Addressing the failure of open source | 13 |
+---------+----+--------------------------------------------------------------+-----+
1 row in set (0.00 sec)
</code></pre>
<p>Can anyone tell me how can i do this using django orm?</p>
<p>I managed to get the second derived table in this way:</p>
<pre><code>second = Comment.objects.values('object_pk').annotate(cnt=Count('id'))
</code></pre>
<p>mysql tables:</p>
<pre><code>mysql> describe blog_post;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | MUL | NULL | |
| title | varchar(100) | NO | | NULL | |
| content | longtext | NO | | NULL | |
| created | date | NO | | NULL | |
| modified | date | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)
mysql> describe django_comments;
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| content_type_id | int(11) | NO | MUL | NULL | |
| object_pk | longtext | NO | | NULL | |
| site_id | int(11) | NO | MUL | NULL | |
| user_id | int(11) | YES | MUL | NULL | |
| user_name | varchar(50) | NO | | NULL | |
| user_email | varchar(75) | NO | | NULL | |
| user_url | varchar(200) | NO | | NULL | |
| comment | longtext | NO | | NULL | |
| submit_date | datetime | NO | | NULL | |
| ip_address | char(15) | YES | | NULL | |
| is_public | tinyint(1) | NO | | NULL | |
| is_removed | tinyint(1) | NO | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
13 rows in set (0.00 sec)
</code></pre>
|
<p>Try use "extra" method of queryset:
<a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra</a></p>
<p>Getting blog posts and its comment count:</p>
<pre><code>ctype = ContentType.objects.get_for_model(BlogPost)
blog_items = BlogPost.objects.filter(user=user_id).extra(select={
'comment_count': """
SELECT COUNT(*) AS comment_count
FROM django_comments
WHERE
content_type_id=%s AND
object_pk=blog_post.id
"""
}, select_params=[ctype.pk])
</code></pre>
|
python|django|join|model|inner-join
| 0 |
1,903,295 | 39,075,271 |
How to make it so a list is chosen and then an image will be drawn in that location?
|
<p>I have these 4 lists:</p>
<pre><code>attempt_01 = [['Piece A', 'In box']]
attempt_02 = [['Piece B', 'In box']]
attempt_03 = [['Piece C', 'In box']]
attempt_04 = [['Piece D', 'In box']]
</code></pre>
<p>and I need to create a function being </p>
<pre><code>def attempt(attempt_number):
</code></pre>
<p>so that images that I have created go to these points and start drawing. </p>
<p>So let's say <code>attempt_01</code> has been chosen then only the first piece of my image will be drawn.
Due to the large amount of code that has been written I cannot post my image that has been drawn using turtle.</p>
<p>I have tried this code below so that when the first attempt is put in the function, only A will be drawn, but I do not know how to get only A to draw.</p>
<pre><code>def draw_attempt(attempt_number):
if 'Piece A' and 'In box':
x = 0, 350
elif 'Piece B' and 'In box':
y = 0, 350
elif 'Piece C' and 'In box':
z = 0, 350
elif 'Piece D' and 'In box':
p = 0, 350
goto(x)
#STARTS DRAWING FOR IMAGE A(PIECE A CODE IS HERE)
goto(y)
#STARTS DRAWING FOR IMAGE A(PIECE B CODE IS HERE)
goto(z)
#STARTS DRAWING FOR IMAGE A(PIECE C CODE IS HERE)
goto(p)
#STARTS DRAWING FOR IMAGE A(PIECE D CODE IS HERE)
</code></pre>
|
<p>It seems that you need something like this:</p>
<pre><code>def draw_attempt(attempt_number):
if 'In box':
x = 0, 350
elif 'Top_Right':
x = 350, 350
elif 'Bottom_Left':
x = -350, -350
goto(x)
if 'Piece A':
#STARTS DRAWING FOR IMAGE A(PIECE A CODE IS HERE)
elif 'Piece B':
#STARTS DRAWING FOR IMAGE B(PIECE B CODE IS HERE)
elif 'Piece C':
#STARTS DRAWING FOR IMAGE C(PIECE C CODE IS HERE)
</code></pre>
|
python|python-2.7
| 0 |
1,903,296 | 39,288,105 |
How to call Executor.map in custom dask graph?
|
<p>I've got a computation, consisting of 3 "map" steps, and the last step depends on results of the first two. I am performing this task using <code>dask.distributed</code> running on several PCs.</p>
<p>Dependency graph looks like following.</p>
<pre><code>map(func1, list1) -> res_list1-\
| -> create_list_3(res_list1, res_list2)-> list3 -> map(func3, list3)
map(func2, list2) -> res_list2-/
</code></pre>
<p>If we imagine that these computations are independent, then it is straightforward to call <code>map</code> function 3 times.</p>
<pre><code>from distributed import Executor, progress
def process(jobid):
e = Executor('{address}:{port}'.format(address=config('SERVER_ADDR'),
port=config('SERVER_PORT')))
futures = []
futures.append(e.map(func1, list1))
futures.append(e.map(func2, list2))
futures.append(e.map(func3, list3))
return futures
if __name__ == '__main__':
jobid = 'blah-blah-blah'
r = process(jobid)
progress(r)
</code></pre>
<p>However, <code>list3</code> is constructed from results of <code>func1</code> and <code>func2</code>, and its creation is not easily <code>map</code>pable (<code>list1</code>, <code>list2</code>, <code>res_list1</code> and <code>res_list2</code> are stored in the Postgresql database and creation of <code>list3</code> is a <code>JOIN</code> query, taking some time).</p>
<p>I've tried to add call to <code>submit</code> to the list of futures, however, that did not work as expected:</p>
<pre><code>def process(jobid):
e = Executor('{address}:{port}'.format(address=config('SERVER_ADDR'),
port=config('SERVER_PORT')))
futures = []
futures.append(e.map(func1, list1))
futures.append(e.map(func2, list2))
futures.append(e.submit(create_list_3))
futures.append(e.map(func3, list3))
return futures
</code></pre>
<p>In this case one <code>dask-worker</code> has received the task to execute <code>create_list_3</code>, but others have simultaneously received tasks to call <code>func3</code>, that have erred, because <code>list3</code> did not exist.</p>
<p>Obvious thing - I'm missing synchronization. Workers must stop and wait till creation of <code>list3</code> is finished. </p>
<p>Documentation to <code>dask</code> describes custom task graphs, that can provide a synchronization.</p>
<p>However, examples in the documentation do not include <code>map</code> functions, only simple calculations, like calls <code>add</code> and <code>inc</code>.</p>
<p>Is it possible to use <code>map</code> and custom dask graph in my case, or should I implement sync with some other means, that are not included in <code>dask</code>?</p>
|
<p>If you want to link dependencies between tasks then you should pass the outputs from previous tasks into the inputs of another.</p>
<pre><code>futures1 = e.map(func1, list1)
futures2 = e.map(func2, list2)
futures3 = e.map(func3, futures1, futures2)
</code></pre>
<p>For any invocation of <code>func3</code> Dask will handle waiting until the inputs are ready and will send the appropriate results to that function from wherever they get computed.</p>
<p>However it looks like you want to handle data transfer and synchronization through some other custom means. If this is so then perhaps it would be useful to pass along some token to the call to <code>func3</code>. </p>
<pre><code>futures1 = e.map(func1, list1)
futures2 = e.map(func2, list2)
def do_nothing(*args):
return None
token1 = e.submit(do_nothing, futures1)
token2 = e.submit(do_nothing, futures2)
list3 = e.submit(create_list_3)
def func3(arg, tokens=None):
...
futures3 = e.map(func3, list3, tokens=[token1, token2])
</code></pre>
<p>This is a bit of a hack, but would force all <code>func3</code> functions to wait until they were able to get the token results from the previous map calls.</p>
<p>However I recommend trying to do something like the first option. This will allow dask to be much smarter about when it runs and can release resources. Barriers like <code>token1/2</code> result in sub-optimal scheduling.</p>
|
python-2.7|anaconda|distributed|distributed-computing|dask
| 1 |
1,903,297 | 47,544,617 |
How can I know where the request.user from in Django View?
|
<p>How can I know where the request.user from ?</p>
<p>I have a TestRequestUserAPIView:</p>
<pre><code>class TestRequestUserAPIView(View):
def dispatch(self, request, *args, **kwargs):
result = super(TestRequestUserAPIView, self).dispatch(request, *args, **kwargs)
return result
def get(self, request):
user = request.user # this line I get the user (who access the API)
return HttpResponse("ok")
</code></pre>
<p>When it execute this line <code>user = request.user</code>.
I can get the request <code>user</code>(who request this API).</p>
<p>I want to know how the user generate in request, why I request this API in browser like Chrome, I the request will have the user property?</p>
<p>Does it through the cookie ? or some token (In my test project, I logined. But I did not put the token to the request when access the API, still get the user in backend reqest.user)? </p>
<hr>
<p><strong>EDIT -1</strong></p>
<p>I have django <code>build-in</code> auth, and <code>rest-auth</code> in my project:</p>
<p>The bellow auth are in my INSTALLED_APPS:</p>
<pre><code>'django.contrib.auth',
'rest_auth',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth.registration',
</code></pre>
<p>I also want to know the frontend pass what to backend for identity the user, does it use cookie? or token? I use rest-auth to generate a token when login. </p>
|
<p>I'm assuming you're using <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/" rel="nofollow noreferrer">Django's built-in authentication system</a> - i.e. you have the <code>django.contrib.auth</code> included in your settings installed apps.</p>
<p>Middlewares get a chance to intercept the <code>request</code> before any of your views receive it.
This <code>request.user</code> attribute is set by Django's auth middleware, <a href="https://github.com/django/django/blob/746caf3ef821dbf7588797cb2600fa81b9df9d1d/django/contrib/auth/middleware.py#L79-L83" rel="nofollow noreferrer">here</a>: </p>
<pre><code>class RemoteUserMiddleware(MiddlewareMixin):
"""
Middleware for utilizing Web-server-provided authentication.
If request.user is not authenticated, then this middleware attempts to
authenticate the username passed in the ``REMOTE_USER`` request header.
If authentication is successful, the user is automatically logged in to
persist the user in the session.
The header used is configurable and defaults to ``REMOTE_USER``. Subclass
this class and change the ``header`` attribute if you need to use a
different header.
"""
...
def process_request(self, request):
...
# We are seeing this user for the first time in this session, attempt
# to authenticate the user.
user = auth.authenticate(request, remote_user=username)
if user:
# User is valid. Set request.user and persist user in the session
# by logging the user in.
request.user = user
auth.login(request, user)
</code></pre>
|
python|django
| 1 |
1,903,298 | 47,575,564 |
How do I print certain parts of an array inside an array in python 3
|
<p>How do I print certain parts of an array inside an array. For example: How do I print [0] of the [1] position of the following array: </p>
<pre><code>testarray = [[1, 2, 3], ["icecream", "person", "bird"], [4, 5, 6]]
</code></pre>
<p>the result should be "icecream".</p>
|
<p>To index a single array you need to state which one you want to <code>print</code></p>
<pre><code>A = ["test", "Jam", "boo"]
print(A[0])
test
</code></pre>
<p>if each array has multiple values you simply do the same as before inside each one</p>
<pre><code>A = [["Toast", "sausage", "eggs"], ["breakfast", "lunch", "dinner"]
print(A[0][0])
Toast
</code></pre>
|
python
| 0 |
1,903,299 | 47,836,456 |
Python requests with login credentials
|
<p>I am trying to login to a URL & download the content then parse, the URL needs username & password to login.</p>
<p>using below gives below errors:</p>
<pre><code>import requests
url = 'https://test/acx/databaseUsage.jssp?object=all'
values = {'username': 'test_user',
'password': 'test_pswd'}
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.post(url, data=values, headers=headers)
print r.content
</code></pre>
<p>Error log output from above code:</p>
<p>tried with below values as well , without any success</p>
<p>values = {'Login': 'test',
'Password': 'test',
'Log in': 'submit'}</p>
<pre><code><html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/> <!-- must be first; see SD5930 -->
<title>Test URL login</title>
<!--meta name="apple-mobile-web-app-capable" content="yes" /-->
<link type="text/css" rel="StyleSheet" href="/nl/logon.css"></link>
</head>
<body onLoad="setFocus();">
<div id="htmlContent">
<div id="container">
<div id="content">
<div class="login_frame">
<div class="header_login">
<img src="/nl/img/logo.png" alt="Test URL" />
</div>
<div id="form-main">
<!--[if lte IE 7]>
<div class="warning"><b>Warning</b>: your browser isn't supported by Test URL. <br/>To be able to use Test URL to its full potential, you need to update your browser.</div>
<![endif]-->
<form method="POST" autocorrect="off" autocapitalize="off" name="loginForm" action="/nl/jsp/logon.jsp">
<input type="hidden" name="action" value="submit" />
<input type="hidden" name="target" value="/acx/databaseUsage.jssp?object=all">
<p class="input first">
<label for="login">Login</label>
<span>
<input id="login" name="login" tabindex="1" type="text" value="" />
</span>
</p>
<p class="input">
<label for="password">Password</label>
<span>
<input id="password" name="password" tabindex="2" type="password" autocomplete="off" />
</span>
<br />
</p>
<p class="memorize submit last">
<input id="rememberMe" name="rememberMe" class="checkbox" tabindex="3" type="checkbox" />
<label class="checkbox" for="rememberMe">Keep me logged in</label>
<button id="validate" type="submit">Log in</button>
</p>
</form>
</div>
</div>
</div>
</div>
<div id="footer" class="dashboardFooter">
<div id="footerContent" class="nlui-pageWidth">
<p>
&copy; Test URL 2017
</p>
</div>
</div>
</div>
<script type="text/javascript">
function setFocus() {
document.loginForm.login.focus();
}
</script>
</body>
</html>
</code></pre>
<p>Image of login page</p>
<p><a href="https://i.stack.imgur.com/DMCE8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DMCE8.png" alt="enter image description here"></a></p>
|
<p>In order to login successfully you'll have to submit the correct data to the correct URL. You can get those values from the HTML form, or by inspecting the network traffic in your browser. Also, you may want to gather any authenticated cookies.</p>
<ul>
<li><p>Make sure to use the correct URL. You can get that URL from the form's <code>action</code> attribute (if the form has no action it is submitted to the URL that hosts it). If you examine the form you'll see that it is submitted to: "/nl/jsp/logon.jsp". </p></li>
<li><p>Make sure to include all required data. If the form contains hidden inputs they should be included in the POST data. It is important to submit all the form fields because they may contain essential data.</p></li>
<li><p>You can use a <a href="http://docs.python-requests.org/en/master/user/advanced/#session-objects" rel="nofollow noreferrer"><code>Session()</code></a> object to store your cookies. This will collect and use cookies (and other parameters) across requests, and so you can access the site as an authenticated user. </p></li>
<li><p>If you want to set or change headers you can use either the <code>headers</code> parameter or the <code>Session.headers</code> attribute - which wil use those headers for all requests. Usually changing the default User-Agent is enough, but some sites may expect more headers (a valid Referer for example).</p></li>
</ul>
<hr>
<pre><code>import requests
url = 'https://example.com/nl/jsp/logon.jsp'
post_data = {
'login': 'username',
'password': 'password',
'target':'/acx/databaseUsage.jssp?object=all',
'action':'submit'
}
with requests.Session() as s:
s.headers['User-Agent'] = 'My user-agent'
r = s.post(url, data=post_data)
print(r.text)
</code></pre>
<p>If you still can't login you may have to use <code>Selenium</code>. Sometimes JavaScript is involved in the login process and <code>requests</code> doesn't run JavaScript code. It may be possible to reverse-engineer this process but it would be much easier/better to use <code>Selenium</code>.</p>
|
python|python-requests
| 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.