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
10,600
50,926,012
Wildcard match in python
<p>I have a string in python</p> <pre><code>x = "orange". </code></pre> <p>The program accepts an input string.If the input string matches the wildcard pattern of x, then I perform some operation. The pattern is </p> <pre><code>pattern = "#.orange.*" </code></pre> <p># (hash) - can substitute for zero or more wor...
<p>Not sure if I'm understanding the Regex idea correctly, but if I'm correct, you want to match the following:<br> (Zero or more words).orange.(Exactly one word)</p> <p>Now I do not know if the words in the hash are seperated by spaces, periods or are just words after each other, but here are the following cases:</p>...
python|regex
1
10,601
3,859,097
How to add http headers in WSGI middleware?
<p>How can http headers be added within a WSGI middleware?</p>
<p>I've found a nice example from the <a href="http://pylonsbook.com/en/1.1/the-web-server-gateway-interface-wsgi.html#changing-the-status-and-headers" rel="noreferrer">pylons book</a>.</p> <pre><code>class Middleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_r...
python|wsgi
21
10,602
3,925,614
How do you read a file into a list in Python?
<p>I want to prompt a user for a number of random numbers to be generated and saved to a file. He gave us that part. The part we have to do is to open that file, convert the numbers into a list, then find the mean, standard deviation, etc. without using the easy built-in Python tools.</p> <p>I've tried using <code>ope...
<pre><code>with open('C:/path/numbers.txt') as f: lines = f.read().splitlines() </code></pre> <p>this will give you a list of values (strings) you had in your file, with newlines stripped.</p> <p>also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward sl...
python|file
319
10,603
50,662,176
Best practices for indexing with pandas
<p>I want to select rows based on a mask, <code>idx</code>. I can think of two different possibilities, either using <code>iloc</code> or just using brackets. I have shown the two possibilities (on a dataframe <code>df</code>) below. Are they both equally viable?</p> <pre><code>idx = (df["timestamp"] &gt;= 5) &amp; (d...
<p>No, they are not the same. One uses direct syntax while the other relies on chained indexing.</p> <p>The crucial points are:</p> <ul> <li><a href="https://pandas.pydata.org/pandas-docs/version/0.21/generated/pandas.DataFrame.iloc.html" rel="nofollow noreferrer"><code>pd.DataFrame.iloc</code></a> is used primarily ...
python|pandas|dataframe|indexing|series
8
10,604
26,790,050
pandas conditional aggregation
<p>I want to group the below dataframe based on 'id', then have the aggregate sums of 'flow' for all values of 'id' except 0; those should stay independent. What is the best solution?</p> <p>Original:</p> <pre><code>id flow 0 1 0 1 1 1 1 1 2 1 2 1 </code></pre> <p>Aggregated:</p> <pre><code>id flow 0 ...
<p>One way would be to use <code>transform</code> to assign the new flow values back and then drop duplicates:</p> <pre><code>In [48]: df.loc[df['id'] != 0, 'flow'] = df.groupby('id')['flow'].transform('sum') df.drop(df[df['id']!=0].drop_duplicates().index) Out[48]: id flow 0 0 1 1 0 1 3 1 2 5 ...
python|pandas|aggregation
2
10,605
26,456,215
Python 3 rock, paper, scissors issue
<p>I am working on a rock, paper, scissors game for a programming homework assignment and I have run into a little snag. The program is suppose run by the user selecting 1 of 4 options, 1) rock, 2) paper, 3) scissors and 4) quit. Once the player selects an option the computers selection is displayed and the winner is a...
<p>For issue 1, it's because you set the computer and player choices before your loop, and never update them. Change the beginning of your loop to:</p> <pre><code>while play_again == 'y' or play_again == 'Y': computer_choice = process_computer_choice() player_choice = process_player_choice() </code></pre> <p>...
python
2
10,606
56,826,665
Travis-CI failing to build due to PySide2 and Matplotlib
<p>I have a github repository where I develop an <a href="https://github.com/SanPen/GridCal" rel="nofollow noreferrer">electrical calculation software</a>.</p> <p>Recently I completely migrated from PyQt5 to PySide2.</p> <p>Today I added Travis-CI for continuous integration as a hook to the Githb repository. This mea...
<p>You must enable the XVFB service as indicated in the <a href="https://benlimmer.com/2019/01/14/travis-ci-xvfb/" rel="nofollow noreferrer">docs</a> to be able to test libraries that need a graphical environment:</p> <pre><code>dist: xenial # required for Python &gt;= 3.7 services: - xvfb language: python python:...
python|matplotlib|python-3.6|travis-ci|pyside2
3
10,607
45,198,644
Python's __debug__ special variable not working for an imported module
<p>How do I make the special variable <code>__debug__</code> in python work for modules which have been installed with <code>python setup.py install</code> and then imported?</p> <p>Currently, I am working on a package which has the following statement in a function:</p> <pre><code> ... if __debug__: ...
<p>Thanks for the help in the comment section. It finally worked out - running:</p> <pre><code>python setup.py --help install </code></pre> <p>showed a list of options. Then, it became apparent I was installing with optimization incorrectly. I needed to run:</p> <pre><code>python setup.py install -O2 </code></pre> ...
python|python-2.7
3
10,608
61,301,411
opencv_core.inRange() not allowing opencv_core.Scalar as input type
<pre><code>frame=cv2.imread('lena.jpg') hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) l_b=np.array([110,50,50]) u_b=np.array([130,255,255]) mask=cv2.inRange(hsv,l_b,u_b) cv2.imshow('frame',mask) </code></pre> <blockquote> <p><strong>Error-</strong> OpenCV(4.2.0) C:\projects\opencv-python\opencv\mod...
<p>Instead of converting the frame into grayscale, you have to convert it to HSV.</p> <pre><code>#Change this line hsv=cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) </code></pre>
python|opencv
1
10,609
61,519,591
Ibis create impala table with pandas dataframe and get [Error 61] Connection refused
<p>After doing impyla sql statement, I convert the results into pandas dataframe format. But now I want to auto create a temporary table on impala using Apache Ibis to create table and load a dataframe into it. The following codes are divided into 3 phase:</p> <ol> <li>phase 1 creates a null table with user-defined sc...
<p>Solved. Our environment is CDH6.3.2 and I check the Namenode web ui port <em>dfs.namenode.http-address</em> on CM is 9870 instead of 50070. Change hdfs client connection conf. on the code above and it will work well</p>
python|python-3.x|impala|impyla|ibis
1
10,610
61,401,885
How to copy one key pair value from one dictionary to another in python
<p>Lets say I have a dictionary:</p> <pre><code>mydict = {"color":"green", "type":"veg", "fruit":"apple", "level": 5 } new_dict = {} </code></pre> <p>I would like to append the key "color" and "fruit" and their values receptively into the <code>new_dict</code>. what is the easi...
<p>You can try this:</p> <pre><code>new_dict = {x:mydict[x] for x in mydict if x in ('color','fruit')} </code></pre>
python|dictionary
4
10,611
60,518,454
Using defined strings for regex searching with python
<p>I am looking to enhance the script I have below. I am wondering if it is possible to use defined strings such as <code>'G', 'SG', 'PF', 'PG', 'SF', 'F', 'UTIL', 'C'</code> to search for the Names between them and then use those strings supplied as the name of the column. The issue I have with the current set up is i...
<p>We can simply update your regex expression to check if the capitalised word is not directly next to the previous.</p> <pre><code>r"(?&lt;![A-Z] )\b([A-Z]+) " </code></pre> <p>Note we have added a negative lookbehind. To not match if the previous word is not <code>[A-Z]</code></p> <p>You can find a more in-depth e...
python|regex
0
10,612
57,764,525
How to catch specific exceptions on sqlalchemy?
<p>I want to catch specific exceptions like <code>UniqueViolation</code> on sqlalchemy.</p> <p>But sqlalchemy throw exceptions only through <code>IntegrityError</code>.</p> <p>So I catched specific exceptions with below code.</p> <pre><code>except sqlalchemy.exc.IntegrityError as e: from psycopg2 import errors ...
<p>You can reraise the original exception from the <code>except</code> block and catch whatever specific type you are interested in:</p> <pre><code>import sqlalchemy import psycopg2 from psycopg2 import errors try: raise sqlalchemy.exc.IntegrityError("INSERT INTO table (col1) VALUES (?)", (1,), errors.IntegrityCo...
python|sqlalchemy
2
10,613
71,757,164
Catalog rows according to type conditions
<p>I have a given dataFrame with four columns -</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>X1</th> <th>X2</th> <th>X3</th> <th>X4</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1.2</td> <td>1.2</td> <td>2</td> </tr> <tr> <td>1</td> <td>1.3</td> <td>1.2</td> <td>1.2</td> </tr> <tr> <td...
<pre><code>df['new_column'] = df.apply(lambda x: 1 if isinstance(x['X1'],int) and isinstance(x['X4'],int) else 'bug', axis=1) </code></pre>
python|pandas|dataframe
1
10,614
55,186,122
asyncio/aiohttp not returning response
<p>I am trying to scrape some data from <a href="https://www.officialcharts.com/" rel="nofollow noreferrer">https://www.officialcharts.com/</a> by parallelising web requests using asyncio/aiohttp. I implemented the code given at the link <a href="https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aioh...
<p>Try to use the latest version.</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- from aiohttp import ClientSession, client_exceptions from asyncio import Semaphore, ensure_future, gather, run from json import dumps, loads limit = 10 http_ok = [200] async def scra...
python|web-scraping|python-requests|aiohttp
1
10,615
55,298,747
Why am I stuck in an endless loop?
<p>I am currently writing a python script and I am running into an endless loop. A similar code is working but this isn't:</p> <pre><code>while True: print ("test") sleep(2) try: doc = html.fromstring(page.content) XPATH_PRICE = '//div[@id="product_detail_price"]//content()' print(...
<p><strong>Change this part</strong>:</p> <pre><code>except Exception as e: print e </code></pre> <p><strong>to this</strong>:</p> <pre><code>except Exception as e: print(e) break </code></pre> <p>And if you are <code>break</code>ing while <em>catching the exception</em>, there seems to be no point in h...
python|loops
4
10,616
54,112,336
Docker and Plotly
<p>I created a python script using plotly dash to draw graphs, then using plotly-orca to export a static image of the created graph. I want to dockerise this script but my problem is I build and run the image i get a "The orca executable is required in order to export figures as static images" error. My question now is...
<p>It's a bit complicated due to the nature of plotly-orca, but it can be done, according to <a href="https://github.com/mathieuboudreau/orca-plotly-dockerfile/blob/master/Dockerfile" rel="nofollow noreferrer">this Dockerfile</a> based on <a href="https://github.com/plotly/orca/issues/150#issuecomment-483191715" rel="n...
python-3.x|plotly|plotly-dash
2
10,617
53,808,559
Combined linear congruential generator
<p>I am trying to generate 10 pseudorandom number by using "combined linear congruential generator". Necessary steps for "combined linear congruential generator" are as follows:</p> <p><a href="https://i.stack.imgur.com/y0im4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y0im4.png" alt="enter imag...
<p>There is a number of problems with the script:</p> <ol> <li>You are assigning values to r[i], but the list is empty at that point; you should initialise it to be able to write values to it like that; (for example) <code>r = [0.0] * n</code></li> <li>You are returning r in parentheses, perhaps because you expect a t...
python|python-3.x
1
10,618
58,312,045
How do I add an image from a list in python using docx?
<p>I wrote a code that takes a screenshot that I want to paste into a word document using docx. So far I have to save the image as a png file. The relevant part of my code is:</p> <pre><code>from docx import Document import pyautogui import docx doc = Document() images = [] img = pyautogui.screenshot(region = (some ...
<p>Yes, according to <a href="https://python-docx.readthedocs.io/en/latest/api/document.html?highlight=add_picture#docx.document.Document.add_picture" rel="nofollow noreferrer">add_picture — Document objects — python-docx 0.8.10 documentation</a>, <code>add_picture</code> can import data from a stream as well.</p> <p>...
python|image|ms-word|jupyter-notebook|docx
2
10,619
58,229,964
How to move around Pandas Dataframe column?
<p><a href="https://i.stack.imgur.com/QN6RD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QN6RD.png" alt="enter image description here"></a></p> <p>I've attached a screenshot. I need some method to move the 'DATE' column to be aligned with the actual columns of the dataframes, which are SMA &amp; ...
<p>First column is called <code>index</code> in pandas and for convert to column use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="nofollow noreferrer"><code>DataFrame.reset_index</code></a>:</p> <pre><code>df = df.reset_index() </code></pre> <hr> <p>But n...
python|python-3.x|pandas|dataframe
3
10,620
22,727,800
How do I sort objects inside of objects in JSON? (using Python 2.7)
<p>I have the following code, which is a function to export a transaction history from a digital currency wallet to a json file.</p> <p>The problems I am facing are two:</p> <ol> <li><p>I would like to allow the json file to be written in utf-8, as the property 'label' can be utf-8 characters, and if I do not account...
<p>You need to ensure that both json does not escape characters, and you write your json output as unicode:</p> <pre><code>import codecs import json with codecs.open('tmp.json', 'w', encoding='utf-8') as f: f.write(json.dumps({u'hello' : u'привет!'}, ensure_ascii=False) + '\n') $ cat tmp.json {"hello": "привет!...
python|json|encoding|utf-8
2
10,621
22,539,488
Distinguishing Between Words and Numbers in a String - Assertion Error
<pre><code>def checkio(words): word = words.isalpha() num = words.isdigit() if word: pass if num: pass return True or False print checkio(u"Hello World hello") == True, "Hello" print checkio(u"He is 123 man") == False, "123 man" print checkio(u"1 2 3 4") == False, "Digits" print ch...
<p>To just address the one function you have so far:</p> <pre><code>def checkio(words): word = words.isalpha() # word = either True or False num = words.isdigit() # num = either True or False if word: # these four pass # lines don't if num: # actually pass # do anything return Tru...
python
2
10,622
45,667,561
Java program display the continuous output from Python
<p>I would like to read the output from execute python script in time,but when I was doing this,java always waited the python until it finish(after 5 sec) all process.</p> <p>I reproduced my question as following:</p> <p>read.java</p> <pre><code>public static void main(String[] args) throws IOException{ Runtime...
<p>I would prefer <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html" rel="nofollow noreferrer"><code>ProcessBuilder</code></a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html#inheritIO--" rel="nofollow noreferrer"><code>inheritIO</code></a>, something ...
java|python
3
10,623
45,511,995
Pandas Modify DataFrames in Loop Part 2
<p>Given the following data frames:</p> <pre><code>import pandas as pd k=pd.DataFrame({'A':[1,1],'B':[3,4]}) e=pd.DataFrame({'A':[1,1],'B':[6,7]}) k A B 0 1 3 1 1 4 e A B 0 1 6 1 1 7 </code></pre> <p>I'd like to apply a group-by sum in a loop, but doing so does not seem to modify the data...
<p>This worked:</p> <p>First, define the function</p> <pre><code>def moddf(d): return d.groupby(d.columns[0]).apply(sum) </code></pre> <p>Next, reassign modified data frames like this:</p> <pre><code>k,e=[moddf(x) for x in dfsout] </code></pre> <p>or</p> <pre><code>dfsout2=[moddf(x) for x in dfsout] </code></...
python|loops|pandas|dataframe
0
10,624
28,782,883
Can you append a list to a dictionary?
<p>So I need to create a list which will save the users inputs (a name and their 3 scores) and that will then append this information to one of 3 files. I tried doing this by appending the data to a list and then the list to a dictionary but this doesn't seem to work. I am really new to python so would really appreciat...
<p>You need to have lists in dictionary to be able to append to them. You can do something like: </p> <pre><code>scores = {"class1": [], "class2": [], "class3": []} def main(): name= input ('What is your name?') for i in range(0,3) score = input("Enter your score: ") clss =input('which class?...
python|list|dictionary
7
10,625
41,366,099
Getting blocked when scraping Amazon (even with headers, proxies, delay)
<p>I have a Python code to scrape Amazon product listing. I have set the proxies and headers. I also have <code>sleep()</code> before each crawl. However, I still cannot get the data. The msg I get back is: </p> <blockquote> <p>To discuss automated access to Amazon data please contact api-services-support@amazon.com...
<p>Instead of: </p> <pre><code>r = requests.get(url, headers, proxies=proxies) </code></pre> <p>Do: </p> <pre><code>r = requests.get(url, headers=headers, proxies=proxies) </code></pre> <p>This resolved the issue for me for now. Hopefully, the resolution will keep working.</p>
python|python-2.7|web-scraping
4
10,626
41,601,820
showing TypeError: 'builtin_function_or_method' object is not iterable in Odoo
<p>I am getting this error when I am trying to change the license_id in odoo</p> <pre><code> @api.multi @api.onchange('license_id') def del_potential(self): _logger.info('Status Approved or not' + str(self.license_id.approval_state)) _logger.info('Potential FGL' + str(self.partner_potential_...
<p>It should be like this,</p> <pre><code>@api.multi @api.onchange('license_id') def del_potential(self): for rec in self: _logger.info('Status Approved or not' + str(rec.license_id.approval_state)) _logger.info('Potential FGL' + str(rec.partner_potential_fgl_address)) if rec.license_id.app...
python|openerp
1
10,627
6,477,586
SSL in Python: Why it doesn't send certificate to server?
<p>I'm writing some software that is supposed to acquire information from SSL-secured web page. Below there's piece of code I use to connect to server.</p> <pre><code>s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) ssl_sock = ssl.wrap_socket ( s, ca_certs = '/home/stilz/Desktop/Certyfikaty/GLOWNE_CA.cer...
<p>First of all, you need to determine if you need to authenticate yourself on the server (certificate is sent to the server only in this case) or you need to validate server's authenticity (in which case the certificate is not sent to the server).</p> <p>Now about issues in your code:</p> <p>Case 1: you don't need t...
python|ssl|ssl-certificate|x509|handshake
1
10,628
6,652,124
Naive and easiest way to decompose independent loop into parallel threads/processes
<ol> <li>I have a loop of intensive calculations, I want them to be accelerated using the multicore processor as they are independent: all performed in parallel. What the easiest way to do that in python?</li> <li>Let’s imagine that those calculations have to be summed at the end. How to easily add them to a list or a ...
<p>From my experience, multi-threading is probably not going to be a viable option for speeding things up (due to the <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock" rel="noreferrer">Global Interpreter Lock</a>).</p> <p>A good alternative is the <a href="http://docs.python.org/library/multiprocessing.ht...
python|parallel-processing
12
10,629
57,128,984
How to force range loop to be executed at least once
<p>In python, we can use the following loop:</p> <pre><code>for k in range(n, m): pass </code></pre> <p>where <code>n</code>and <code>m</code>are two integers. If <code>n == m</code> the loop is ignored (doesn't get executed). How to force the program to execute the loop at least once?</p>
<p>This is one way:</p> <pre><code>for k in range(n, max(n+1,m)): </code></pre>
python-3.x
2
10,630
56,963,065
Creating Directed graph of function (callee,caller) pairs: can python `inspect` access modules outside current project drectory?
<p>Please leave a comment if this explanation is long-winded or if I'm not being clear; the ultimate goal of my project is to create a directed acyclic graph using <a href="https://networkx.github.io/documentation/stable/auto_examples/index.html" rel="nofollow noreferrer"><code>networkx</code></a> such that an arrow is...
<blockquote> <p>[...], or if there are already developer tools create directed acyclic graphs from python code, I'd love to know of them.</p> </blockquote> <p>There are a couple of options to determine the dependency graph, for example <a href="https://pypi.org/project/snakefood/" rel="nofollow noreferrer"><code>sna...
python|python-3.x|networkx|developer-tools|inspect
1
10,631
56,911,478
How to make an object move by itself in order to avoid collisions with other objects
<p>I'm making this game about dodging objects that come from different directions. What I'm trying to achieve is to get this object (a 'player' class controlled by the computer) to be able to dodge just like a player controlled by user would do.</p> <p>I've tried to use basic collisions handling provided by pygame (of...
<p>Regardless of player and bullet rect positions in colliding moment, <code>bullet.rect.right</code> always be more than <code>player.rect.left</code> and <code>bullet.rect.left</code> always be less than <code>player.rect.right</code>. You visually see it if draw on paper. Here better check moving side pushing rects ...
python-3.x|pygame|python-3.6
2
10,632
25,638,866
Getting an error when trying to import matplotlib
<p>I am using <code>ipython</code> when I am trying to <code>import matplotlib</code>.</p> <p>I am getting following error</p> <pre><code>ImportError Traceback (most recent call last) /home/akajappan/&lt;ipython-input-4-82be63b7783c&gt; in &lt;module&gt;() ----&gt; 1 import matplotlib /...
<p>If you are satisfied with workaround - install anaconda distribution. This is a python distribution with all (or most) scientific packages installed. It saved me, it may help you as well.</p> <p><a href="http://continuum.io/downloads" rel="nofollow">http://continuum.io/downloads</a></p>
python|matplotlib|scipy|ipython
0
10,633
44,562,190
Setting a negative fixed parameter in the symfit python package
<p>I need to fit two out of the three values in a parameter, say I have <code>a,b,</code> and <code>c</code> and I know <code>a</code> but I just want to fit <code>b</code> and <code>c</code>. The issue becomes if I try to fix a to a negative value I the following error <code>ValueError: SLSQP Error: lb &gt; ub in boun...
<p>This seems to be an issue with <code>symfit</code>, thanks for reporting it.</p> <p>As a quick solution to your problem; it seems that SLSQP is causing the NaN's. Therefore, switching from the <code>Fit</code> object to the <code>NumericalLeastSquares</code> object will solve your problem. (But it will still not al...
python|scipy|curve-fitting|symfit
2
10,634
24,381,090
Performance issue with reading integers from a binary file at specific locations
<p>I have a file with integers stored as binary and I'm trying to extract values at specific locations. It's one big serialized integer array for which I need values at specific indexes. I've created the following code but its terribly slow compared to the F# version I created before.</p> <pre><code>import os, struct ...
<p>Heavily depending on your index file size you might want to read it completely into a numpy array. If the file is not large, complete sequential read may be faster than a large number of seeks.</p> <p>One problem with the seek operations is that python operates on buffered input. If the program was written in some ...
python|numpy|binaryfiles
4
10,635
20,486,032
howto program protocol buffer in python to send messages via socket
<p>I'm trying to use protocol buffer in python to send a message from one to another computer. I learned from a few online examples, and tried to make a minimum example out of them. However, in my code, the server does not print out the correct values of the variables the client sends. Any help is very much apprecia...
<p>First advice: simplify. Lets first see if we can get this thing working <em>without</em> protocol buffers:</p> <h1>client.py</h1> <pre><code>import socket import sys import struct address = ('localhost', 6005) client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client_socket.connect(address) messa...
python|sockets|protocol-buffers
4
10,636
20,624,749
Add conditions in code depending on python version
<p>I am currently writing some code on python 3.3. Unfortunately some of the plugins I rely on are not yet compatible with Python3 and I need to switch back to Python2.7.</p> <p>In order to avoid refactoring all the code, I would like to do something like</p> <pre><code>if(os.python.version&lt;3.0): from _future_ imp...
<p>You're on the wrong track here, on several counts. First, don't check for versions, check for features. The link @dave you in his comment does a good job of explaining that.</p> <p>Second, if you did check for versions, and even if there weren't multiple spelling errors, this wouldn't work at all:</p> <pre><code...
python
3
10,637
20,729,104
Python asyncio, futures and yield from
<p>Consider the following program (running on CPython 3.4.0b1):</p> <pre><code>import math import asyncio from asyncio import coroutine @coroutine def fast_sqrt(x): future = asyncio.Future() if x &gt;= 0: future.set_result(math.sqrt(x)) else: future.set_exception(Exception("negative number")) ...
<p>Regarding #1: Python does no such thing. Note that the <code>fast_sqrt</code> function you've written (i.e. before any decorators) is not a generator function, coroutine function, task, or whatever you want to call it. It's an ordinary function running synchronously and returning what you write after the <code>retur...
python|future|yield|coroutine|python-asyncio
6
10,638
36,044,653
BeautifulSoup Error in file saving .txt
<pre><code>from bs4 import BeautifulSoup import requests import os url = "http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html" r = requests.get(url) soup = BeautifulSoup(r.content.decode('utf-8', 'ignore')) data = soup.find_all("article", {"class": "article"}) with open("dat...
<p>If you want to write the data as UTF-8 to the file try <code>codecs.open</code> like:</p> <pre><code>from bs4 import BeautifulSoup import requests import os import codecs url = "http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html" r = requests.get(url) soup = BeautifulSou...
python|save|beautifulsoup
1
10,639
15,193,713
Django 1.4 Pagination with a query
<p>I'm trying to get pagination working following the example in <a href="https://docs.djangoproject.com/en/dev/topics/pagination/" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/pagination/</a>. I'm using query and can't seem to pass the query data to successive pages. The first page returns my query limi...
<pre><code>from django.core.paginator import Paginator, InvalidPage, EmptyPage def search(request): found_entries = inventory.objects.filter() if request.GET.get('q'): query_string = request.GET.get('q') found_entries = found_entries.filter( id__icontains=query_string ...
django|pagination|python-2.6|django-1.4|django-q
1
10,640
20,990,239
converting a string to list in python in easy way
<p>I have a pdb file and I want to parse pdb. I am using Biopython for the same. I want list of coordinates of N-CA-C-CB in list for every residue. How Can i achieve that?</p> <pre><code>pdb = "1dly.pdb" name = pdb[:3] from Bio import PDB from ast import literal_eval p = PDB.PDBParser() s = p.get_structure(name, pdb...
<p>This should work (untested since I do not have a pdb file to test). I'm using <a href="https://wiki.python.org/moin/Generators" rel="nofollow">Generators</a> here:</p> <pre><code># first create a generator that parses your structure, one residue at time def createDesiredList(structure, desired_atoms): residues...
python|biopython
1
10,641
55,073,917
How to add " to a string in python
<p>I am trying to start a torrent downloader in windows, which is executed from the command prompt. It takes in a command such as <code>torrent "magnet_link"</code>. The problem I'm having is when I start the command from python using <code>os.system("start /wait cmd /c torrent " + '"' + link + '"')</code> for some rea...
<p>Use can use built-in <code>str.center</code>:</p> <pre><code>link = 'http://stackoverflow.com' print("start /wait cmd /c torrent %s" % link.center(len(link)+2, '"')) # start /wait cmd /c torrent "http://stackoverflow.com" </code></pre>
python|windows
2
10,642
55,017,986
Table is not creating on SQL server while uploading data using python
<p>I'm new to connecting sql server using python.I need to read some data from sql server do the processing &amp; upload the processed data on sql server.All of these task will be done using python. So I have written the code to pull the data from sql server,did the processing &amp; finally while I'm trying to upload t...
<p><code>CREATE TABLE if not exists output1</code> is not valid <code>SQL Server</code> syntax. You can use <code>IF OBJECT_ID('output1','U') IS NULL</code> to check if table is present. </p> <p>Change your query like following.</p> <pre><code>c.execute('''IF OBJECT_ID(''output1'',''U'') IS NULL CREATE TABLE output1 ...
python|sql-server
3
10,643
73,773,440
Seaborn PairGrid - how to add frames? (top and right spines)
<p>I'm trying to change the style of sns PairGrid graph. Namely, I want to add a frame around each of the grid graphs. What one graph looks like right now:</p> <p><img src="https://i.stack.imgur.com/rNwcI.png" alt="the graph now" /></p> <p>How I want it to look:</p> <p><img src="https://i.stack.imgur.com/97FZH.png" alt...
<p>Use the <code>despine=False</code> option of <a href="https://seaborn.pydata.org/generated/seaborn.PairGrid.html" rel="nofollow noreferrer"><code>PairGrid</code></a>:</p> <pre><code>import seaborn as sns penguins = sns.load_dataset(&quot;penguins&quot;) g = sns.PairGrid(penguins, despine=False) g.map(sns.scatterplo...
python|matplotlib|plot|seaborn
1
10,644
24,685,601
Python: Cancel object creation during initialization
<p>I'm creating a list of objects, and if any have some undesirable data while they're being initialized, I'd like to immediately cancel their initialization, and move on to the next object. Is there a best practice for something like this in Python?</p> <pre><code>data = [good, bad] theList = [myObject(some_data) for...
<p>Like the other answer said, validate the data before creating objects. Somewhat like this:</p> <pre><code>def validate(data): if data_is_good: return True else: return False data = [good, bad] theList = [myObject(some_data) for some_data in data if validate(some_data)] </code></pre>
python
4
10,645
41,178,761
Tensorflow: DropoutWrapper leads to different output?
<p>I build a LSTM like:</p> <pre><code>lstm_cell = tf.nn.rnn_cell.LSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True, activation=tf.nn.tanh) lstm_cell = tf.nn.rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=0.5) lstm_cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * 3, state_is_tuple=True) </code></pre> <p>Th...
<p>Try using the <code>seed</code> keyword argument to <code>DropoutWrapper(...)</code>:</p> <pre><code>lstm_cell = tf.nn.rnn_cell.DropoutWrapper(lstm_cell, output_keep_prob=0.5, seed=42) </code></pre> <p>See the docs <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/rnn_cell/rnn_cell_wrappers__rnnce...
python|tensorflow|lstm
1
10,646
38,334,665
Kaitai Struct: calculated instances with a condition
<p>I'm trying to get Kaitai Struct to reverse engineer a binary structure. <code>seq</code> fields work as intended, but <code>instances</code> don't seem to work as I want them to.</p> <p>My binary format includes a header with a list of constants that I parse as <code>header</code> field with <code>consts</code> arr...
<p>Yeah, I guess it should be considered a bug. At the very least, compiler should either allow to use <code>if</code> in value instances and process it properly, or disallow <code>if</code> and issue an error message.</p> <p>Thinking of it, I see no reason why <code>if</code> is allowed for regular <code>instances</c...
python|data-structures|reverse-engineering|kaitai-struct
2
10,647
38,468,215
Can this code be turned to use generators instead of lists?
<p>I have a structure like this (pseudo code):</p> <pre><code>class Player { steamid: str hero: Hero } class Hero { class_id: str level: int xp: int skills: list[Skill] } class Skill { class_id: str level: int } </code></pre> <p>Now I'm trying to store it into a database, and I gave my...
<p>There's no way to avoid storing <code>O(len(players))</code> worth of data if you want to save the sets of your player, hero and skill data in separate operations on the database (rather than doing one operation for each player with their associated hero and skill data, or saving it all somehow in parallel).</p> <p...
python|python-3.x|generator
2
10,648
31,030,096
Concatenating url pages as a single Data Frame
<p>I'm trying to download historic weather data for a given Location. I have altered an example given at <a href="http://flowingdata.com/2007/07/09/grabbing-weather-underground-data-with-beautifulsoup/" rel="nofollow">flowingdata</a> but I've stuck in the last step - how to concate multiple <code>Data Frames</code></p>...
<p>You should declare a list outside your loop and append to this then outside the loop you want to concatenate all the dfs into a single df:</p> <pre><code>import pandas as pd frames = pd.DataFrame(columns=['TimeEET', 'TemperatureC', 'Dew PointC', 'Humidity','Sea Level PressurehPa', 'VisibilityKm', 'Wind Dir...
python|pandas
3
10,649
52,189,671
Understanding constraint in scipy's optimize
<p>I am trying to understand <code>constraints</code> in the <code>scipy</code> optimize function. I want to minimize the function under the assumption, that input values would always be positive. So I have my constraint function defined as follows:</p> <pre><code>def apply_constraint(inputs): return inputs[0] - i...
<p>Your constraint function is incorrect</p> <p><code>inputs[0] - inputs[0]</code> will always be 0, it should be </p> <pre><code>def apply_constraint(inputs): return inputs[0] </code></pre> <p>Constraints work in one of two ways either <code>type = 'eq'</code> or <code>type = 'ineq'</code></p> <p>The constrain...
python|scipy
0
10,650
51,570,681
Django - get the query by date using postgresql "to_date"
<p>I need to get raw objects using Django .objects.raw functions like :</p> <pre><code>SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000-02-07','YYYY-MM-DD') AND to_date('2027-02-15', 'YYYY-MM-DD') </code></pre> <p>in pgAdmin select return good result, but when i put it to django there is an error:</p>...
<p>You're passing a string literal with single parenthesis (<code>'</code>) while having them inside the string itself. You must escape them or use <code>"</code>:</p> <pre><code>queryset = Document.objects.raw("SELECT * FROM TEST_APP_DOCUMENT WHERE DATE BETWEEN to_date('0000 - 02 - 07','YYYY - MM - DD') AND to_date('...
python|django|postgresql|to-date
1
10,651
51,620,248
Python Censys Export API
<p>I'm having problems figuring out how to get the Censys Python API to export search queries into a CSV file. Apparently, it has an EXPORT API and I've tried importing it into my code, but it still gives me an undefined function call.</p> <pre><code>#!/user/bin/python3 #import sys #import requests #import os import...
<p>Really here <code>censys.export.CensysExport</code> class isn't required. You can read at the end about how to use <code>censys.export.CensysExport</code>.</p> <pre><code>import csv from censys.ipv4 import CensysIPv4 UID = "&lt;your-uid&gt;" SECRET = "&lt;your-secret&gt;" ipv4 = CensysIPv4(api_id=UID, api_secret...
python
2
10,652
69,160,914
Why does "load_model" cause RAM memory problems while predicting?
<p>I trained neural network (transformer architecture) and saved it by using:</p> <pre><code>model.save(directory + args.name, save_format=&quot;tf&quot;) </code></pre> <p>After that, I want to load the model again with another script to test it by letting it make iterative predictions:</p> <pre><code>from keras.models...
<p>There is a fundamental difference between <code>load_model</code> and <code>load_weights</code>. When you save an model using <code>save_model</code> you save the following things:</p> <p>A Keras model consists of multiple components:</p> <ul> <li>The architecture, or configuration, which specifies what layers the m...
python|tensorflow|tensorflow2.0
0
10,653
56,348,572
I keep getting UnicodeErrors opening a CSV file although adding utf-8 encoding
<p>I know the questions sounds generic but here is my problem. I have a csv file that will always cause UnicodeErrors and errors like csv.empty although I am opening the file with utf-8 like this</p> <pre class="lang-py prettyprint-override"><code> with open(csv_filename, 'r', encoding='utf-8') as csvfile: </code><...
<p>Pandas will load the contents of the csv file into a dataframe</p> <p>The csv module has methods like reader and DictReader that will return generators that let you move through the file.</p> <p>With Pandas:</p> <pre><code>import pandas as pd df=pd.read_csv('file.csv') df.to_csv('new_file.csv',index=False) </cod...
python|pandas|csv
0
10,654
63,507,023
How to make a Keras Dense Layer deal with 3D tensor as input for this Softmax Fully Connected Layer?
<p>I am working on a custom problem, and i have to change the fully connected layer (Dense with softmax), My model code is something like this (with Keras Framework):</p> <pre><code>....... batch_size = 8 inputs = tf.random.uniform(shape=[batch_size,1024,256],dtype=tf.dtypes.float32) preds = Dense(num_classes,activatio...
<p>There are three different ways in which this can be done (that I can think of). If you want to have a single dense layer, that maps a vector of 256 elements to a vector of <code>num_classes</code> elements, and apply it all across your batch of data (that is, use the same <code>256 x num_classes</code> matrix of wei...
tensorflow|keras|deep-learning|neural-network|tensor
1
10,655
63,564,191
ctypes c_uint32 getting passed incorrectly from python to Cpp
<p>I am using python with ctypes to call a C so file.</p> <p>The C structure is:</p> <pre><code>typedef struct { uint32_t var1; uint32_t var2; uint32_t var3; uint8_t var4; uint8_t var5 } struct1; If I call C code where I set the variables of var1 to 0x050A, var2 to 0x102 and var3 to 0x203 build it and print out the v...
<p><code>long</code> on your system is 64-bits as exhibited by <code>printf(&quot;%lx&quot;)</code> printing a 64-bit integer. As I see you found in the comments, your C code <code>uint32_t</code> was defined as <code>unsigned long</code> which would be incorrect on that system.</p> <p>Your system should have a <code>...
python|c++|ctypes|uint32
1
10,656
22,026,064
Python: while loop that quits program if not completed within specified limit
<p>Python Question: i need to run a program that asks for a password but if the wrong answer is input three times the user is thrown out of the program i can run it in a while loop but cant get it to quit if the wrong password is entered. </p> <p>Thanks for your help</p>
<p>Adding an approximation of how I'd do it, in the absence of an example containing the problem. <code>else</code> on a for loop will only execute if you did not break out of the loop. Since you know the max number of times to run the loop is 3 you can just use a <code>for</code> loop instead of a <code>while</code>...
python|loops|while-loop|quit
4
10,657
22,053,852
How to install Matplotlib for anaconda 1.9.1 and Python 3.3.4?
<p>I am configuring Anaconda 1.9.1 together with Python 3.3.4 and I am unable to setup Matplotlib for anaconda environment when I try to add package using Pycharm. I also tried to install from Matplotlib.exe file which I downloaded from its website. I can not change the installation directory in that case. I would like...
<p>If you're using anaconda, your default environment is Python 2.7. You need to create a new environment and install matplotlib in there.</p> <p>In a command prompt, do the following (saying yes to the questions):</p> <pre><code>conda create --name mpl33 python=3.3 matplotlib ipython-notebook activate mpl33 ipython ...
python|python-3.x|matplotlib
5
10,658
43,619,148
How to Upload a file using Openload.co API
<p>I'm trying to <a href="https://openload.co/api#upload" rel="nofollow noreferrer">upload a file</a> called '240p.mp4' with the Openload REST API.</p> <p>Since Upload endpoint requires an SHA-1 Hash of the file, I got it by doing:</p> <pre><code>sha1 = hashlib.sha1() BLOCKSIZE = 65536 with open('240p.mp4', 'rb') as...
<p>try this code.....for uploading file using openload api.</p> <p>first get folder id using this url</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-html lang-html prettyprint-override"><code>https://api.openload...
python|rest|api|multipartform-data
0
10,659
54,545,054
Cleaner way to whiten each image in a batch using keras
<p>I would like to whiten each image in a batch. The code I have to do so is this:</p> <pre><code>def whiten(self, x): shape = x.shape x = K.batch_flatten(x) mn = K.mean(x, 0) std = K.std(x, 0) + K.epsilon() r = (x - mn) / std r = K.reshape(x, (-1,shape[1],shape[2],shape[3])) return r # </...
<p>Let's see what the <code>-1</code> does. From the Tensorflow documentation (Because the documentation from Keras is scarce compared to the one from Tensorflow):</p> <blockquote> <p>If one component of shape is the special value -1, the size of that dimension is computed so that the total size remains constant.</p...
tensorflow|keras
1
10,660
54,352,485
How to use decorators on overridable class methods
<p>I have a custom class with multiple methods that all return a code. I would like standard logic that checks the returned code against a list of acceptable codes <em>for that method</em> and raises an error if it was not expected.</p> <p>I thought a good way to achieve this was with a decorator:</p> <pre><code>fro...
<h2>TL;DR</h2> <p>Use the <code>__wrapped__</code> attribute to ignore the parent's decorator:</p> <pre><code>class MyNewClass(MyClass): @expected_codes(["300", "301"]) def return_300_code(self): return super().return_300_code.__wrapped__(self) # No exception raised </code></pre> <h2>Explanation</h2>...
python|django|python-decorators
1
10,661
34,153,900
subprocess.Popen is not running shell command
<p>I am trying to use <code>subprocess.Popen</code> to run <strong>'cat test.txt | grep txt'</strong>, but it's not working. In my code I have executed the <code>subprocess.Popen</code> command twice.</p> <blockquote> <p>1: First time I used it to run a tshark command which redirectes the command output to a text (test...
<p><strong>TL;DR</strong> <em>Both</em> of your <code>subprocess.Popen()</code> calls are broken; use one of the wrapper methods in <code>subprocess</code> instead, and/or use Python's built-in facilities instead of external tools.</p> <p>Is there a particular reason you use a <a href="http://www.iki.fi/era/unix/award...
python|python-2.7|subprocess|popen
3
10,662
34,120,980
Downloading a file in python using sockets TCP
<p>I am writing a TCP concurrent (process based-concurrency) server which accepts a download command. The client should download a file from the server, as of right now I have the filename hard-coded to download in order to test my download algorithm.</p> <p>I looked up a sample <a href="https://stackoverflow.com/ques...
<p>Sending a file byte by byte might be very slow. Best use <code>shutil.copyfileobj</code>, that handles the transfer for you:</p> <pre><code>def send_file(socket, filename): with open('download.txt','rb') as inp: print "Opened File: " , file.name out = socket.makefile('wb') shutil.copyfil...
python|sockets|tcp|concurrency|concurrent-programming
1
10,663
7,297,217
Calculating a game's high score table
<p>I need to create a function/method ( in python) which calculates a high score "leaderboard". Each player will have played any number of rounds of the game, recieving a score for each round. I want to know what's the best way to sort the top ranking players (accounting for score AND number of rounds played). The poss...
<p>What you are asking is essentially how we define "good" players and it's not an easy problem. As you mentioned, a simple average score or picking-the-highest-score will not be an ideal answer depending on your game design.</p> <p>I'd like to recommend that you read about <a href="http://en.wikipedia.org/wiki/Elo_ra...
python|google-app-engine|math
2
10,664
38,726,333
Converting Python to Scala in Spark ML?
<p>The question is about <a href="https://stackoverflow.com/questions/37278999/logistic-regression-with-spark-ml-data-frames">Logistic regression with spark ml (data frames)</a></p> <p>When I want to change the code Python to Scala</p> <p>Python:</p> <pre><code>[stage.coefficients for stage in model.stages if is...
<blockquote> <p>Why the type is different when the isInstanceOf returns true?</p> </blockquote> <p>Well, Scala is a statically typed language and <code>stages</code> is an <code>Array[Transformer]</code> so each element you access is a <code>Transformer</code>. <code>Transformers</code> in general have no <code>coef...
python|scala|apache-spark|apache-spark-ml
2
10,665
40,330,630
Where does this “pyvenv.cfg” file exist?
<p>I give a quotation of <code>site</code> module documentation below and i am not aware where “pyvenv.cfg” file actually exists.Does it just exist in a directory one level higher than <code>sys/executable</code>'s ?</p> <blockquote> <p>If a file named <strong>“pyvenv.cfg”</strong> exists one directory <strong><em>a...
<p>It doesn't exist unless it is created.</p> <blockquote> <p><strong><em>If</em></strong> ...</p> </blockquote> <p>And if it is created, it should be in the same directory as the executable or one directory above as per <a href="https://www.python.org/dev/peps/pep-0405/" rel="nofollow">PEP 405</a>.</p>
python|python-3.x
1
10,666
40,774,546
K means in scikit learn Kernel died - due to long computations
<p>I am trying to use k means clustering using scikit learn.Hence using the elbow method to find the optimal value of k.</p> <pre><code>def elbow(df, n): kMeansVar = [KMeans(n_clusters=k).fit(df.values) for k in range(10, n)] centroids = [X.cluster_centers_ for X in kMeansVar] k_euclid = [cdist(df.values, cen...
<p>Rather than recomputing all the distamces, why don't you use the <code>inertia_</code> provided by the k-means object?</p> <p>Then you won't need your problematic line (which uses inefficient dats structures).</p>
python|machine-learning|scikit-learn|data-mining|k-means
0
10,667
9,771,171
openerp schedule server action
<p>In OpenERP 6.0.1, I've created a server action to send a confirmation email after an invoice is confirmed, and linked it to appropriately to the invoice workflow. now normally when an invoice is confirmed, an email is automatically sent.<br> is there a way to set a date for when the email should be sent instead of b...
<p>There is a one object <code>ir.cron</code> which will run on specific time period. There you can specify the time when you want to sent the mail. </p> <p>This object will call the function which you given in <code>Method</code> attribute. In this function you have to search for those invoices which are in <code>cre...
python|openerp
9
10,668
26,038,875
Append each line from a text file to a list
<p>My problem is that I want to append each line of a file to a list. Here's what it looks like on the text file:</p> <pre><code>-1,2,1 0,4,4,1 </code></pre> <p>I want to append the contents of each line into a list of it's own:</p> <pre><code>list1 = [-1, 2, 1] list2 = [0, 4, 4, 1] </code></pre>
<pre><code>list_dict = {} # create dict to store all the lists with open(infile) as f: # use with to open your file as it closes them automatically for ind,line in enumerate(f,1): # use enumerate to keep track of each line index list_dict["list{}".format(ind)] = map(int,line.rstrip().split(","))# strip new ...
python|file-io
0
10,669
32,202,831
Align control to bottom of panel in wxPython
<p>I'm trying to align some controls in my wxPython app to bottom of a panel. Here's sample of my code:</p> <pre><code>def __DoLayout(self): vsizer = wx.BoxSizer(wx.VERTICAL) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer2 = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(self.prog, 0, wx.ALL|wx.EXPAND, 5) hsiz...
<p>With reluctance, but as @renae-lider who answered the question has not posted an answer. </p> <p>Change the 0 to 1 in this line : </p> <pre><code>vsizer.Add(hsizer2, 1, wx.EXPAND) </code></pre> <p>This is the <code>proportion</code> parameter. </p> <p>The proportion parameter defines the ratio of how wi...
python-2.7|wxpython
2
10,670
28,289,009
How to get Channel Name for Video, youtubeAPI, Python
<p>Firstly the previous "answer" to a similar question used the deprecated Youtube Api V2. Also none of the answers showed how you can do it with Python.</p> <p>My code is:</p> <pre><code>def youtube_search(item): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) # ...
<p>While all this was going on I was trying to solve it myself and have merged a few other answers around the place to come up with a solution that works. It might not be the best one so please if you have a better one let me know. But it may be useful here for others who stumble across trying to do the same:</p> <p>E...
python|youtube-api
1
10,671
27,918,776
install dependency in Bitnami Odoo Stack
<p>Hi I am having problem with a python Module installation. I want to install a python module pycups in bitnami odoo stack v8. but when i try to install it, It is installed in ubuntu's own python directory. How to direct the bitnami's python to look for default python's library? Also if there is another way to install...
<p>You can find how to install plugins on Odoo at wiki page:</p> <p><a href="https://wiki.bitnami.com/Applications/Bitnami_Odoo#How_to_install_a_plugin_on_Odoo" rel="nofollow">https://wiki.bitnami.com/Applications/Bitnami_Odoo#How_to_install_a_plugin_on_Odoo</a></p> <p>In addition, you can take a look at this other p...
python|odoo|bitnami|cups
1
10,672
32,833,371
Why do I get a ValueError with Json using a windows txt file encoded with utf-8?
<p>Here's the method:</p> <pre><code>def load(self, path): json_data = open(path, "r") self.data = load(json_data) return self.data </code></pre> <p>Here's the file (Which was saved with utf-8 encoding):</p> <pre><code>{ "False": "Falso", "None": "Nulo", "True": "Verdadeiro", "as": "como", "a...
<p>BOM must be the culprit. Open the file with <code>codecs.open(path,"r","utf-8-sig")</code> or autodetect the encoding to open with e.g. as per <a href="https://stackoverflow.com/questions/13590749/reading-unicode-file-data-with-bom-chars-in-python">Reading Unicode file data with BOM chars in Python</a>.</p>
python|json|python-3.x|encoding|utf-8
2
10,673
32,656,126
building '_mysql' extension error: Unable to find vcvarsall.bat
<p>I am trying to install via pip mysql for python 3.5. I have found that I have the missing file, vcvarsall.bat in "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" But I do not know how to modify istall script to point to vcvarsall.bat</p> <p>Here is the output from install. I have tried soluti...
<p>Try pymysql. <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">https://github.com/PyMySQL/PyMySQL</a> </p> <p>It's pure Python, so you won't need to worry about building anything to make it work. I've used both and they both work very well for me.</p>
python|mysql|windows|x86-64
1
10,674
13,932,814
'Command' object has no attribute 'stdout'
<pre><code>from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def handle(self, *args, **options): ...... self.handle_noargs() def handle_noargs(self, **options): packages_count = Package.objects.all().count() Package.objects.all().delet...
<p>i think you can not call handle_noargs directly, the BaseCommand class command has an execute() method which calls handle() and before initializes stdout and stderr</p> <p>so every time you run a command, the execute() method is called which expects the handle method to be implemented</p>
python|django|command|stdout
2
10,675
34,629,458
pygame.error: unable to create gl context
<p>I am trying to follow some OpenGL tutorials and I'm having this error : <code>pygame.error: unable to create gl context</code>. The error occurs in the function :</p> <pre><code>pygame.display.set_mode([800,600],OPENGL|DOUBLEBUF) </code></pre> <p>I am using PyopenGL3.1 with Pygame and PyQt4. I was wondering if it ...
<p>Well I faced this problem when starting openGL on a virtual machine (windows xp).</p> <p>This problem occurs if your GPU is unable to create the GL context. If you have a second GPU (NVIDIA, RADEON), make it the default GPU for python. That solved the problem for me.</p> <p>Have a nice day</p>
python|opengl
0
10,676
34,513,357
sqlalchemy SyntaxError: non-keyword arg after keyword arg
<pre><code>uid = Column(String(32), primary_key= True, ForeignKey("ques_bank.uid"), auto_increment = False) </code></pre> <p>gives me a <code>SyntaxError</code>:</p> <pre><code>SyntaxError: non-keyword arg after keyword arg </code></pre> <p>I'm new at this, so need help. What am I doing wrong?</p>
<p>Try </p> <p><code>uid = Column(String(32), ForeignKey("ques_bank.uid"), primary_key= True, auto_increment = False)</code> </p> <p>You should read up on keyword arguments in Python python keyword arguments order.</p> <p>Let us say that you have a function:</p> <p><code>def fn(a,b=1,x=2,d=6,e=5): return 2</code></...
python|sqlalchemy
0
10,677
26,984,153
how can i re-use previous results of a pagerank calculation in python-igraph
<p>I have an ever-changing graph. Over time, a few number of vertices are added and a few new edges appear (nodes are not deleted). If i have a previous pagerank calculation result, how can i re-use it in order to improve speed?</p> <p>The python igraph module seems nifty and all, but i can't find anything relevant. T...
<p>First of all, PageRank is <em>not</em> a random algorithm. The PageRank equation boils down to calculating the dominant eigenvector of a sparse matrix (well, not exactly a sparse matrix but the sum of a sparse matrix plus some other matrix for which we can calculate vector products as fast as if it were sparse), so ...
python|graph-theory|igraph|pagerank
1
10,678
22,964,740
How do i solve Attribute Error?
<p>We need a way for our <code>Tribute</code> object to reduce their hunger. Create a method <code>eat(food)</code>, which takes in a <code>Food</code> object. It will reduce the hunger of the player by the <code>food.get food value()</code>. If object that's passed to the <code>eat</code> method is of the type <code>M...
<p><code>Food</code> is a subclass of <code>Thing</code> but <code>Food</code>'s <code>__init__</code> doesn't call <code>Thing</code>'s <code>__init__</code>. That is the source of the problem. <code>Food</code>'s <code>__init__</code> needs the following line at its start:</p> <pre><code>super().__init__(name) </cod...
python
2
10,679
8,045,602
How can I copy an in-memory SQLite database to another in-memory SQLite database in Python?
<p>I'm writing a test suite for Django that runs tests in a tree-like fashion. For example, Testcase A might have 2 outcomes, and Testcase B might have 1, and Testcase C might have 3. The tree looks like this</p> <pre><code> X / A-B-C-X \ \ B X \ X \ / C-X \ X </code></pre> ...
<p>Alright, after a fun adventure I figured this one out.</p> <pre><code>from django.db import connections import sqlite3 # Create a Django database connection for our test database connections.databases['test'] = {'NAME': ":memory:", 'ENGINE': "django.db.backends.sqlite3"} # We assume that the database under the so...
python|django|sqlite
4
10,680
47,289,909
Install confluent-kafka avro with pip
<p>I'm trying to install the avro package for confluent-kafka with python3 on macOs Sierra. </p> <p>Installing the confluent-kafka package works fine, no issues. The problem is when I try to install the avro package: </p> <pre><code>pip install confluent-kafka[avro] </code></pre> <p>I just get an error message from ...
<p>Assuming you are not using bash (in my case it was zsh), the <code>[]</code> might mess with your shell. The following should solve this:</p> <pre><code>pip install "confluent-kafka[avro]" </code></pre> <p>For me this worked with the default install from <a href="https://pypi.org/project/confluent-kafka/" rel="nor...
python|apache-kafka|avro|confluent-platform
10
10,681
70,746,779
Python requests get doesn't return anything
<p>I want to request this url and get its information:</p> <p><a href="https://search.codal.ir/api/search/v2/q?=&amp;Audited=true&amp;AuditorRef=-1&amp;Category=1&amp;Childs=false&amp;CompanyState=0&amp;CompanyType=-1&amp;Consolidatable=true&amp;IsNotAudited=false&amp;Isic=232007&amp;Length=12&amp;LetterCode=%D9%86-10&...
<p>Found the issue:</p> <p>You need to have a <code>User-Agent</code> header:</p> <pre><code>import requests if __name__ == '__main__': req = requests.Session() link12month = &quot;https://search.codal.ir/api/search/v2/q?&amp;Audited=true&amp;AuditorRef=-1&amp;Category=1&amp;Childs=false&amp;CompanyState=0&amp...
python|python-requests|scrapy|web-crawler
2
10,682
11,614,021
MEX equivalent for Python ( C wrapper functions)
<p>Coming from MATLAB, I am looking for some way to create functions in Python which are derived from wrapping C functions. I came across Cython, ctypes, SWIG. My intent is not to improve speed by any factor (it would certainly help though). </p> <p>Could someone recommend a decent solution for such a purpose. Edit: W...
<p>I've found that <a href="http://www.scipy.org/Weave" rel="nofollow">weave</a> works pretty well for shorter functions and has a very simple interface. </p> <p>To give you an idea of just how easy the interface is, here's an example (taken from the <a href="http://www.scipy.org/PerformancePython/" rel="nofollow">Per...
python|swig|ctypes|cython|mex
1
10,683
33,758,847
I am making a program in python that sorts a text file
<p>I would like to sort content from a a text file. I have already sorted them by alphabetical order (name). The problem i am getting is that when I try to sort the scores in ascending or decending order, the program does not recognise the 10 as a 10 but as a 1. I have attached my code and text file.</p> <p>Python 3.4 ...
<p>you need to convert string which read from txt file to integer</p> <pre><code>grades = [int(grade) for grade in grades] </code></pre> <p>if you compare string, the result would be as follow</p> <pre><code>numString = ["1","5000","3","6","30","4","2","200"] print(sorted(numString)) ['1', '2', '200', '3', '30', '4...
python|file
1
10,684
46,855,689
ETL process with Python and SQL Server taking a really long time to load
<p>I'm looking for a technique that will increase the performance of a csv file SQL Server database load process. I've attempted various approaches but nothing I do seems to be able to break the 5.5 hour barrier. That's just testing loading a year of data which is about 2 million records. I have 20 years of data to loa...
<blockquote> <p>Bulk load works REALLY fast but then I have to add the data for the extra columns and we're back to row level operations which I think is the bottleneck here.</p> </blockquote> <p>Sorry but I do not understand why you have row level operations. Try:</p> <p>1) bulk load to stage table </p> <p>2) <a ...
python|sql-server|pandas|csv|tsql
2
10,685
46,938,530
Produce balanced mini batch with Dataset API
<p>I've a question about the new dataset API (tensorflow 1.4rc1). I've a unbalanced dataset wrt to labels <code>0</code> and <code>1</code>. My goal is to create balanced mini batches during the preprocessing.</p> <p>Assume I've two filtered datasets:</p> <pre><code>ds_pos = dataset.filter(lambda l, x, y, z: tf.resha...
<p>You are on the right track. The following example uses <code>Dataset.flat_map()</code> to turn each pair of a positive example and a negative example into two consecutive examples in the result:</p> <pre><code>dataset = tf.data.Dataset.zip((ds_pos, ds_neg)) # Each input element will be converted into a two-element...
tensorflow|tensorflow-datasets
7
10,686
37,879,104
How does numpy polyfit work?
<p>I've created the "Precipitation Analysis" example Jupyter Notebook in the Bluemix Spark service.</p> <p>Notebook Link: <a href="https://console.ng.bluemix.net/data/notebooks/3ffc43e2-d639-4895-91a7-8f1599369a86/view?access_token=effff68dbeb5f9fc0d2df20cb51bffa266748f2d177b730d5d096cb54b35e5f0" rel="nofollow">https:...
<p>The question has been answered on Developerworks:- <a href="https://developer.ibm.com/answers/questions/282350/how-does-numpy-polyfit-work.html" rel="nofollow">https://developer.ibm.com/answers/questions/282350/how-does-numpy-polyfit-work.html</a></p> <p>I will try to explain each of this:-</p> <p>index = chile[ch...
numpy|apache-spark|ibm-cloud|linear-regression
0
10,687
37,822,217
How to add a new line with print when another variable is in place (Python 3.x)
<p>I am new to learning Python 3.0 and I am trying to solve an issue I have with making a list and printing at the end of it a new line to separate printing between two strings. </p> <p>I.E.</p> <pre><code>list_1 = ['Autumn', 'Mary', 'Ditto', 'Gamma'] print(list_1) print(list_1[2]) Output: ['Autumn', 'Mary', 'Ditto'...
<p>Yes, set <code>end="\n\n"</code> to add an extra newline or as many as you want:</p> <pre><code>print(list_1, end="\n\n") print(list_1[2]) </code></pre> <p>Or a single print using <em>sep</em>:</p> <pre><code>print(list_1, list_1[2], sep="\n\n") </code></pre>
python|python-3.x
0
10,688
29,822,596
unexpected line breaks in python after writing to csv
<p>i have a code that updates CSVs from a server. it gets data using:</p> <pre><code>a = urllib.urlopen(url) data = a.read().strip() </code></pre> <p>then i append the data to the csv by</p> <pre><code>f = open(filename+".csv", "ab") f.write(ndata) f.close() </code></pre> <p>the problem is that randomly, a line in ...
<p>What actions are performed on your "ndata" variable ?</p> <p>You should use the csv module to manage CSV files : <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a></p> <p>Edit after comment :</p> <p>If you do not want to use the "csv" module I linked...
python|csv
0
10,689
27,609,145
virtualenvwrapper.sh: fork: Resource temporarily unavailable - Python/Django
<p><strong>What do I have to do to successfully launch virtualenvwrapper.sh?</strong> <strong>What do I need to put into my .bashrc?</strong></p> <p>The <em>error message</em>:</p> <pre><code>/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh: fork: Resource temporarily unavailable #When I l...
<p>I think this:</p> <pre><code>export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh </code></pre> <p>Should be something like (for me it is python3, but I see you are using python2):</p> <pre><code>export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.frame...
python|django|virtualenv|virtualenvwrapper
1
10,690
65,731,662
Does Python support declaring a matrix column-wise?
<p>In <em>Python numpy</em> when declaring matrices I use <em>np.array([[row 1], [row 2], . . . [row n]])</em> form. This is declaring a matrix row-wise. Is their any facility in <em>Python</em> to declare a matrix column-wise? I would expect something like - <em>np.array([[col 1], [col 2], . . . [col n]], parameter = ...
<p>At the time of array-creation itself, you could use <code>numpy.transpose()</code> instead of <code>numpy.array()</code>, because <code>numpy.tranpose()</code> takes any &quot;array-like&quot; object as input:</p> <pre><code>my_array = np.transpose ([[1,2,3],[4,5,6]]) print (my_array) </code></pre> <p><strong>Output...
python|arrays|numpy|matrix
2
10,691
36,928,577
How can I get a list of package locations from a PIP requirements file?
<p>Is there a way to generate a list from PIP, to the actual resources in the file? For instance, if I had a requirements file with</p> <pre><code>Flask Flask-Login </code></pre> <p>I would like to get output something like:</p> <pre><code>Name: Flask Version: 0.10.1 Summary: A microframework based on Werkzeug, Jin...
<p>You can look up packages in the PyPI using the <a href="https://wiki.python.org/moin/PyPIXmlRpc" rel="nofollow">XMLRPC API</a>:</p> <pre><code>try: import xmlrpclib # Python 2 except ImportError: import xmlrpc.client as xmlrpclib # Python 3 pypi = xmlrpclib.ServerProxy('http://pypi.python.org/pypi') pac...
python|pip
1
10,692
48,572,552
Binary search: weird middle point calculation
<p>Regarding calculation of the list mid-point: why is there</p> <pre><code>i = (first +last) //2 </code></pre> <p>and <code>last</code> is initialized to <code>len(a_list) - 1</code>? From my quick tests, this algorithm <em>without</em> <code>-1</code> works correctly.</p> <pre><code>def binary_search(a_list, item...
<p>The last legal index <em>is</em> <code>len(a_list) - 1</code>. The algorithm <em>will</em> work correctly, as <code>first</code> will always be no more than this, so that the truncated mean will never go out of bounds. However, without the -1, the midpoint computation will be one larger than optimum about half the...
python|algorithm|search
3
10,693
69,494,548
check if either of two substrings exist in a string
<p>I am using the following code to replace all <code>-</code> and remove all <code>,</code> from my dataframe columns</p> <pre><code>df[['sale_price','mrp', 'discount', 'ratings', 'stars']]=df[['sale_price','mrp', 'discount', 'ratings', 'stars']].applymap(lambda r: np.nan if '-' in str(r) else str(r).replace(',', ''))...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer"><code>DataFrame.replace</code></a> with <code>regex=True</code> by substrings defined in dictionary:</p> <pre><code>df = pd.DataFrame([['10,4','-','nan',5,'kkk-oo']], colu...
python|pandas|string
1
10,694
69,416,717
'str' object has no attribute 'from_directory_url' in python
<p>I am trying to make the call</p> <pre class="lang-py prettyprint-override"><code>from azure.storage.fileshare import ShareDirectoryClient shrdDirClient = ShareDirectoryClient.from_directory_url (detailedFileURI,snapshot=None, credential=None) </code></pre> <p>but resulted in the error above. I tried</p> <pre class...
<p>For some reason ‘ ShareDirectoryClient’ is of type {string}. You either import it as a string, i.e. ‘ azure.storage.fileshare’ simply has this defined as a string, or, you assign it to a string later in your code (not visible in the part that has been shared). Please try this: X = ‘some_string’ X() … and you will ge...
python|azure
0
10,695
48,178,484
Django - Creating a Custom Template Tag to show Model Name
<p>I have a model: </p> <pre><code>class Survey(models.Model): name = models.CharField(max_length = 200) def __str__(self): return self.name </code></pre> <p>And in my template I want to show the name of the current Survey model:</p> <pre><code>&lt;h1&gt; {{survey.name |name}} &lt;/h1&gt; </code></pre> <p>I'm ...
<p>When you are calling the template tag with <code>&lt;h1&gt; {{survey.name |name}} &lt;/h1&gt;</code> you are passing it the string associated with the model. As the field is a <code>CharField</code> it will return a string and therefore the name of the that class is <code>str</code>.</p> <p>I believe what you are w...
python|django|python-3.x|django-templates|django-custom-tags
0
10,696
51,132,865
python 3.6 turn part of string into variable
<p>I have this code here. equation = "4x+7" And I would like to make the 4 and 7 into integers and define x as an integer so I can work out y for the equation. Any easy solutions?</p>
<pre><code>number1 = 4 number2 = 7 x = 1 </code></pre> <p>Then use it:</p> <pre><code>number1 * x + number2 </code></pre>
python-3.x
0
10,697
51,216,567
Mac Python IDLE Autocomplete/Pop-up not working
<p>total beginner in Python here. I installed Python 3.6.5 on my Mac and I am using the default IDLE. When I did VBA or Java (long time ago), there used to be pop-up help/completion suggestions after you typed "." (for example).</p> <p>How do I make it happen in IDLE?</p> <p>EDIT// There is another thread asking esse...
<p>I don't know if this apply to 3.6.5 but here is a solution to 3.7.</p> <ul> <li>MacOS 10.14.4</li> <li>Python 3.7.3</li> <li>Installed from <a href="https://www.python.org/downloads/release/python-373/" rel="nofollow noreferrer">python.org</a></li> <li>Tk version: 8.6.8</li> </ul> <p>Test if this is your problem:<...
macos|autocomplete|popup|python-idle
4
10,698
73,622,392
How to execute multiple queries SQL Python?
<p>I'm trying to execute multiple queries. But it's executing the last one only knowing that I did <code>buffered=True</code> in the cursor. I need to get the result for the 4 queries.</p> <pre><code>updated_query = cursor.execute( 'select count(*) from event where update_count &gt; 0 and date &gt; now() - interval...
<p>Since all four aggregate queries share same source table, consider combining all calculations in a single <code>SELECT</code> query. For long format, use the <a href="https://stackoverflow.com/a/73621161/1422451">proposed solution</a> to your previous question.</p> <pre class="lang-py prettyprint-override"><code>upd...
python|sql|python-3.x
1
10,699
73,692,528
Python script won't handle non-ASCII characters
<p>I'm trying to do some machine learning learning on a sequencing dataset that involves special characters and Greek alphabet. and it keeps throwing errors. Every single time I run the script it throws an error from different position.</p> <pre><code>file = open(filename,encoding=&quot;utf-8&quot;) for record in SeqIO...
<p>line 1725 Bio/Seq.py</p> <pre><code>.... self._data = self._data = bytes(data, encoding=&quot;ASCII&quot;) .... </code></pre> <p>giving:</p> <pre><code>data ='\u0394' data = bytes(data, encoding=&quot;ASCII&quot;) print(data.decode()) </code></pre> <p>output:</p> <pre><code>UnicodeEncodeError: ...
python|bioinformatics|biopython|fasta
1