title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Group naming with group and nested regex (unit conversion from text file)
38,407,266
<p><strong>Basic Question:</strong></p> <p>How can you name a python regex group with another group value and nest this within a larger regex group? </p> <p><strong>Origin of Question:</strong></p> <p>Given a string such as <code>'Your favorite song is 1 hour 23 seconds long. My phone only records for 1 h 30 mins a...
2
2016-07-16T02:57:25Z
38,407,972
<p>First of all, you can't just write a multiline regex with comments and expect it to match anything if you don't use the <code>re.VERBOSE</code> flag:</p> <pre><code>regex = re.compile(pattern, re.VERBOSE) </code></pre> <hr> <p>Like you said, the best solution is probably to use a dict</p> <pre><code>for val in t...
1
2016-07-16T05:09:59Z
[ "python", "regex", "parsing", "units-of-measurement" ]
LINK: fatal error LNK1181: cannot open input file 'mingw32.lib' when install scikits.bvp_solver module for python
38,407,276
<p>I tried to install <code>scikits.bvp_solver</code> on my laptop (windows 10) follow instruction here: "<code>pythonhosted.org/scikits.bvp_solver</code>"</p> <p>I used <code>gcc-4.8.2-32</code> but when I perform the command: "<code>python setup.py config --compiler=mingw32 build --compiler=mingw32 install</code>", ...
0
2016-07-16T02:59:34Z
38,407,331
<p>Remove <code>*\VC\Bin\link.exe</code> from your $PATH because you used msvc linker not mingw32.</p>
0
2016-07-16T03:10:01Z
[ "python", "gcc", "mingw", "solver", "scikits" ]
Django to change form field error message
38,407,365
<p>I have a problem with form errors. I want to change the field name that the form error displays.</p> <h1>models.py</h1> <pre><code>class Sales(models.Model): customer = models.ForeignKey("Customer") ctype = models.ForeignKey("Customer_type", verbose_name="Customer Type") </code></pre> <h1>forms.py</h1> <...
2
2016-07-16T03:17:56Z
38,407,480
<p>You can specify labels for fields in your <code>Meta</code> like this:</p> <pre><code>from django.utils.translation import ugettext_lazy as _ class Sales_form(forms.ModelForm): class Meta: model = Sales fields = ('customer','ctype') labels = { 'ctype': _('Customer Type'), ...
1
2016-07-16T03:41:19Z
[ "python", "django" ]
Python MemoryError with Queue and threading
38,407,376
<p>I'm currently writing a script that reads reddit comments from a large file (5 gigs compressed, ~30 gigs of data being read). My script reads the comments, checks for some text, parses them, and sends them off to a Queue function (running in a seperate thread). No matter what I do, I always get a MemoryError on a sp...
0
2016-07-16T03:20:05Z
38,408,887
<p>Looks like its not in your code but may be in the data. Have you tried to skip that iteration? </p> <pre><code>x = 0 for comment in tqdm(objects): x += 1 if x != 8162735 comment = str(comment.encode('ascii', 'ignore')) if "&amp;gt;" in comment: c_parse_thread = threading.Thread(...
0
2016-07-16T07:27:54Z
[ "python", "multithreading", "queue" ]
Updata data based on the status django model
38,407,428
<p>I am currently creating a model and one of the field is the percentage. I wanted to update the percentage field depending on the status. </p> <p>this is my models.py</p> <pre><code>class Contact(models.Model): STATUS = ( ('NY','Not Yet'), ('RN','Running'), ('CO','Completed'), ) ...
0
2016-07-16T03:28:36Z
38,407,484
<p>Override Model's save method and put your logic in there. </p> <pre><code>class Contact(models.Model): STATUS = ( ('NY','Not Yet'), ('RN','Running'), ('CO','Completed'), ) status = models.CharField(max_length=2, choices=STATUS, default='NY') percentage = models.FloatField(...
1
2016-07-16T03:41:53Z
[ "python", "django" ]
Updata data based on the status django model
38,407,428
<p>I am currently creating a model and one of the field is the percentage. I wanted to update the percentage field depending on the status. </p> <p>this is my models.py</p> <pre><code>class Contact(models.Model): STATUS = ( ('NY','Not Yet'), ('RN','Running'), ('CO','Completed'), ) ...
0
2016-07-16T03:28:36Z
38,407,498
<p>If you're just using the <code>percentage</code> field for display purposes, you don't need to make it a real field. I would do it like this:</p> <pre><code>class Contact(models.Model): STATUS = ( ('NY','Not Yet'), ('RN','Running'), ('CO','Completed'), ) status = models.CharFiel...
2
2016-07-16T03:44:18Z
[ "python", "django" ]
Python equivalent of MySQL "Left Join" two lists of tuples
38,407,446
<p>This seems fundamental (though I do come from a MySQL background).</p> <pre><code>a = [(1,f,e),(7,r,None),(2,s,f),(32,None,q)] b = [(32,dd), (1,pp)] </code></pre> <p>If I do this in MySQL (LEFT JOIN):</p> <pre><code>SELECT a.*, b.* FROM a LEFT JOIN b ON a[0] = b[0] </code></pre> <p>I get:</p> <pre><code>[(1,f,e...
1
2016-07-16T03:33:48Z
38,407,495
<p>You can solve it by making a dictionary out of the second input list and then looking up into it:</p> <pre><code>&gt;&gt;&gt; a = [(1,'f','e'),(7,'r',None),(2,'s','f'),(32,None,'q')] &gt;&gt;&gt; b = [(32,'dd'), (1,'pp')] &gt;&gt;&gt; &gt;&gt;&gt; b_dict = {item[0]: item for item in b} &gt;&gt;&gt; [item + b_dict.g...
2
2016-07-16T03:43:43Z
[ "python", "left-join" ]
Python equivalent of MySQL "Left Join" two lists of tuples
38,407,446
<p>This seems fundamental (though I do come from a MySQL background).</p> <pre><code>a = [(1,f,e),(7,r,None),(2,s,f),(32,None,q)] b = [(32,dd), (1,pp)] </code></pre> <p>If I do this in MySQL (LEFT JOIN):</p> <pre><code>SELECT a.*, b.* FROM a LEFT JOIN b ON a[0] = b[0] </code></pre> <p>I get:</p> <pre><code>[(1,f,e...
1
2016-07-16T03:33:48Z
38,407,525
<p>You could choose <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> as a solution. pandas is a python module related with data process, it has MySQL interface and could mock database operation(like filter, join, groupby) in its DataFrame, please check <a href="http://pandas.pydata.org/pandas-docs/stable/m...
1
2016-07-16T03:48:28Z
[ "python", "left-join" ]
Pandas conditional ranking
38,407,524
<p>I have a pandas DataFrame that looks like this:</p> <p><a href="http://i.stack.imgur.com/noYw8.png" rel="nofollow"><img src="http://i.stack.imgur.com/noYw8.png" alt="dataframe"></a></p> <p>I would like to use the <code>pd.DataFrame.rank(axis=1, ascending=False)</code> feature to rank the dataframe subject to the c...
1
2016-07-16T03:48:27Z
38,408,031
<p>Try this:</p> <pre><code>df[df &gt; 0].rank(axis=1, ascending=False) </code></pre>
1
2016-07-16T05:19:26Z
[ "python", "pandas", "rank" ]
Not loading entire txt file into dictionary
38,407,630
<p>Im a python noob to get that out of the way and I am writing these functions using the OOP method just a FYI. My save_roster function works correctly, it saves all of the dictionary player roster to my text file 'roster'. I confirmed this by looking in the text file making sure it is all there. Now when I go to loa...
0
2016-07-16T04:09:38Z
38,407,675
<p>Your <code>return (player_roster)</code> statement is inside of the <code>for</code> loop, which means it only reads the first line before returning. You need to put the statement outside the loop like so:</p> <pre><code>def load_roster(player_roster): print("Loading data...") import csv file = open("ro...
0
2016-07-16T04:19:49Z
[ "python", "file", "dictionary", "text-files" ]
How to iterate through multiple results pages when web scraping with Beautiful Soup
38,407,661
<p>I have a script that i have written where i use Beautiful Soup to scrape a website for search results. I have managed to isolate the data that i want via its class name.</p> <p>However, the search results are not on a single page. Instead, they are spread over multiple pages so i want get them all. I want to make m...
-1
2016-07-16T04:16:18Z
38,409,864
<p>Try this:</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup #all_letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o","p","q","r","s","t","u","v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] all_letters= ['x'] pages = [] def ...
0
2016-07-16T09:50:36Z
[ "python", "scripting", "web-scraping", "beautifulsoup" ]
convert specific rows of pandas dataframe into multiindex
38,407,704
<p>here is my DataFrame:</p> <pre><code> 0 1 2 0 0 0.0 20.0 NaN 1 1.0 21.0 NaN 2 2.0 22.0 NaN ID NaN NaN 11111.0 Year NaN NaN 2011.0 1 0 3.0 23.0 NaN 1 4.0 24.0 NaN 2 5.0 25.0 NaN 3 6.0 26.0 NaN ...
2
2016-07-16T04:27:51Z
38,410,099
<p>This should work:</p> <pre><code>df1 = df.loc[pd.IndexSlice[:, ['ID', 'Year']], '2'] dfs = df1.unstack() dfi = df1.index dfn = df.drop(dfi).drop('2', axis=1).unstack() dfn.set_index([dfs.ID, dfs.Year]).stack() </code></pre> <p><a href="http://i.stack.imgur.com/0pFH5.png" rel="nofollow"><img src="http://i.stack.im...
1
2016-07-16T10:17:55Z
[ "python", "pandas", "dataframe", "multi-index" ]
pyGtk3 Do dialogues have to have a parent? If so, how do you call them from a script?
38,407,707
<p>I can have a script that calls a window, but when I try to raise a dialogue with parent = None, I get:</p> <pre><code>Gtk-Message: GtkDialog mapped without a transient parent. This is discouraged. </code></pre> <p>What parent can I map this this to? It seems I can map it to a dummy parent, but will this cause thin...
1
2016-07-16T04:28:05Z
38,408,127
<p>I will made the above comment an answer. You may have a w = Gtk.Window() somewhere in your code (it may be inside function body) and pass that w to on_question:</p> <pre><code>def on_question(parent=None): dialog = Gtk.MessageDialog(parent, 0, Gtk.MessageType.QUESTION, Gtk.ButtonsType.YES_NO, "This is a...
1
2016-07-16T05:36:31Z
[ "python", "pygtk", "gtk3" ]
I want to append to a new list , only the tuples in which the third element is the same with the third element of the first tuple
38,407,745
<p>After a sort to a list of tuples, for example:</p> <pre><code>jen = (34,54,15) , (34,65,15), (34, 78,89) ... </code></pre> <p>I am trying to append to a new list only the tuples which contain the third element of the first tuple for instance the new list must contain only:</p> <pre><code>(34,54,15) (34,65,15) <...
1
2016-07-16T04:34:45Z
38,407,773
<p>You can do that with <code>filter</code> method easily.</p> <p>In one liner <code>filter</code> call:</p> <pre><code>array1 = [(34,54,15) , (34,65,15), (34, 78,89)] array2 = filter(lambda element: element[2] == array[0][2], array) print array2 [(34, 54, 15), (34, 65, 15)] </code></pre> <p>You can check the docume...
1
2016-07-16T04:37:55Z
[ "python", "iteration", "tuples" ]
I want to append to a new list , only the tuples in which the third element is the same with the third element of the first tuple
38,407,745
<p>After a sort to a list of tuples, for example:</p> <pre><code>jen = (34,54,15) , (34,65,15), (34, 78,89) ... </code></pre> <p>I am trying to append to a new list only the tuples which contain the third element of the first tuple for instance the new list must contain only:</p> <pre><code>(34,54,15) (34,65,15) <...
1
2016-07-16T04:34:45Z
38,407,780
<p>If I understood the requirements correctly, this should do what you want:</p> <pre><code>jen = (34,54,15), (34,65,15), (34, 78,89) salvation_army = [j for j in jen if j[2] == jen[0][2]] print(salvation_army) # Output: # [(34, 54, 15), (34, 65, 15)] </code></pre> <p>It's similar to @Harsh's answer but uses list ...
1
2016-07-16T04:39:10Z
[ "python", "iteration", "tuples" ]
Extract value of attribute 'style'
38,407,907
<p>Simple question really, but somehow, I can't figure it out. I have the following, let's call it "s":</p> <pre><code>&lt;tr&gt; &lt;td class="some_class"&gt; &lt;span class="outer_class"&gt; &lt;span class="inner_class" style="width:86.0px"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/td&gt; &lt;td&gt;Var...
0
2016-07-16T04:58:55Z
38,408,020
<p>Got it. </p> <pre><code>width_long=s.find_all('tr')[0].find_all('span')[1].get('style') </code></pre> <p>Needed to ask to find the answer, of course.</p>
0
2016-07-16T05:17:25Z
[ "python", "beautifulsoup" ]
Extract value of attribute 'style'
38,407,907
<p>Simple question really, but somehow, I can't figure it out. I have the following, let's call it "s":</p> <pre><code>&lt;tr&gt; &lt;td class="some_class"&gt; &lt;span class="outer_class"&gt; &lt;span class="inner_class" style="width:86.0px"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/td&gt; &lt;td&gt;Var...
0
2016-07-16T04:58:55Z
38,408,027
<p>maybe: var sd = document.querySelectorAll('.inner_class'), widthValue = sd[0].attributes['style'].value.replace('width:', '');</p>
0
2016-07-16T05:18:44Z
[ "python", "beautifulsoup" ]
Extract value of attribute 'style'
38,407,907
<p>Simple question really, but somehow, I can't figure it out. I have the following, let's call it "s":</p> <pre><code>&lt;tr&gt; &lt;td class="some_class"&gt; &lt;span class="outer_class"&gt; &lt;span class="inner_class" style="width:86.0px"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/td&gt; &lt;td&gt;Var...
0
2016-07-16T04:58:55Z
38,408,028
<p>This can return a list of style of all spans:</p> <pre><code>allSpanStyle = map(lambda x: x.get('style'), s.find_all("span")) notNoneStyle = [x for x in allSpanStyle if x is not None] </code></pre> <p>Unfortunately, it seems that the style is an unicode string. You have to use Regular Expression or handcrafted pro...
0
2016-07-16T05:18:48Z
[ "python", "beautifulsoup" ]
Extract value of attribute 'style'
38,407,907
<p>Simple question really, but somehow, I can't figure it out. I have the following, let's call it "s":</p> <pre><code>&lt;tr&gt; &lt;td class="some_class"&gt; &lt;span class="outer_class"&gt; &lt;span class="inner_class" style="width:86.0px"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/td&gt; &lt;td&gt;Var...
0
2016-07-16T04:58:55Z
38,408,044
<p>You can <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow">pass a filter function to the <code>soup.find</code> function</a>:</p> <pre><code>s.find(lambda tag:tag.has_attr('style')).get('style') </code></pre>
0
2016-07-16T05:21:27Z
[ "python", "beautifulsoup" ]
import a python file that create a window when main window button clicks
38,407,921
<p>I am creating 2 window in my program and i am using two class, since the code is complex, i separate it in 2 different python file. After i imported the second window file, how can i make sure it open without having this error which show in this picture <a href="http://i.stack.imgur.com/5WOFe.jpg" rel="nofollow"><im...
0
2016-07-16T05:01:28Z
38,408,766
<p>You're creating extra <code>Tk</code> windows. Here is an example of using <code>Toplevel</code> widgets and another file.</p> <p><strong>mainWindow.py</strong></p> <pre><code>import tkinter as tk import secondWindow as sW class MainWindow(tk.Tk): def __init__(self): super().__init__() self.ti...
3
2016-07-16T07:12:09Z
[ "python", "import", "tkinter", "interface", "window" ]
while loop not working-can't find similar code like mine that is not breaking with input
38,407,964
<p>I am creating this game in python and I am trying to get the program to stop running if the user puts in a bet more than they have or if they run out of money. I have used while loops in the past but I can not remember how I did it and other while loop questions; I have tried their solutions but no prevail. If I can...
0
2016-07-16T05:08:55Z
38,408,058
<p>Fixed a few things up. Notably, I did what commenters already suggested: I moved the initial <code>money_left=</code> input outside of the loop and I used <code>break</code> statements to exit the loop.</p> <pre><code>import time import random print("Welcome to gambling 50/50 shot game!!! " "You will put in ...
1
2016-07-16T05:23:52Z
[ "python" ]
while loop not working-can't find similar code like mine that is not breaking with input
38,407,964
<p>I am creating this game in python and I am trying to get the program to stop running if the user puts in a bet more than they have or if they run out of money. I have used while loops in the past but I can not remember how I did it and other while loop questions; I have tried their solutions but no prevail. If I can...
0
2016-07-16T05:08:55Z
38,408,097
<p>You are never changing the value of your variable continued.</p> <p>When the user attempts to bet more money than they have you execute:</p> <pre><code>if bet&gt;money: ... continued=='z' </code></pre> <p>This will just evaluate to false, <strong>not</strong> change the state of continued to "z". It seems lik...
0
2016-07-16T05:31:35Z
[ "python" ]
Tkinter : Issue with binding function
38,408,032
<p>I have a project that uses python's turtle module on a canvas, and I'm trying to bind a <code>&lt;Return&gt;</code> key to a function that executes the custom commands that I made. This is an example:</p> <pre><code>from tkinter import * import turtle root = Tk() mainframe=Frame(root) mainframe.pack(fill=BOTH) sc...
0
2016-07-16T05:19:26Z
38,408,049
<p>You need to inject an argument to <code>executeCommand()</code>. So change its definition to:</p> <pre><code>def executeCommand(event): def moveForward(pixels): tt.forward(pixels) </code></pre>
2
2016-07-16T05:22:55Z
[ "python", "tkinter", "command", "bind" ]
django tenant random domain_url and schema_name
38,408,071
<p>I came accross a problem with django tenant. I created a random schema_name and domain_url on my create function like such:</p> <pre><code>new_key = random_id() request.data['schema_name'] = new_key request.data['domain_url'] = new_key def random_id(size=16, chars=string.ascii_uppercase): return ''.join(rando...
1
2016-07-16T05:26:02Z
38,626,983
<p>By default, postgres will turn every uppercase schema name into lowercase </p> <pre><code>CREATE SCHEMA Km9GDUY1L9vKexXd; \dn List of schemas Name | Owner ------------------+-------- first | mo km9gduy1l9vkexxd | mo myschema | mo public | mo </code></pre> <p>...
0
2016-07-28T04:13:11Z
[ "python", "django", "multi-tenant" ]
Replicated the official Python 3 tutorial on Modules and intra-package imports and still receiving ImportError and SystemError exceptions
38,408,123
<p>I followed <a href="https://docs.python.org/3/tutorial/modules.html#packages" rel="nofollow">Python 3 Modules tutorial</a> and I cannot get absolute or relative intra-package imports to work.</p> <p>Specifically I replicated the project structure from the tutorial. The <code>sound</code> folder is located in my hom...
0
2016-07-16T05:36:04Z
38,408,364
<p>I was just looking at the tutorial. I <strong>don't</strong> read that <code>from sound.effects import echo</code> is supposed to work as is from <code>filters/vocoders.py</code>. What is says there in the tutorial is:</p> <blockquote> <p>Users of the package can import individual modules from the package, fo...
0
2016-07-16T06:15:55Z
[ "python", "python-3.x", "packages", "python-import", "python-module" ]
How to convert kivy to a video file
38,408,139
<p>I wrote a kivy app to render some animation on linux server. Is there a good way to convert the animation to a video file directly?</p> <p>Currently I tried Xvfb + ffmpeg approach. However it has some issues I want to avoid such as:</p> <ul> <li>ffmpeg will also record the empty x-windows desktop before the anima...
2
2016-07-16T05:38:50Z
38,409,642
<p>You can use <a href="https://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.export_to_png" rel="nofollow"><code>kivy.uix.widget.Widget.export_to_png</code></a> in order to save Widget into a image file after every frame and then build a movie using tools like <code>ffmpeg</code> or <code>cv2</code> li...
3
2016-07-16T09:22:59Z
[ "python", "video", "ffmpeg", "kivy", "xvfb" ]
How to calculate Eb(k) of networks with Python?
38,408,224
<p>In the paper titled <strong>Scaling of degree correlations and its influence on diffusion in scale-free networks</strong>, the authors define the quantity of $E_b(k)$ to measure the extent of degree correlations. </p> <p><a href="http://i.stack.imgur.com/K6aFg.gif"><img src="http://i.stack.imgur.com/K6aFg.gif" alt...
25
2016-07-16T05:52:19Z
38,408,979
<p>Considering to use the log-binning of the data, the following the function can be adopted. </p> <pre><code>import numpy as np def log_binning(x, y, bin_count=35): max_x = np.log10(max(x)) max_y = np.log10(max(y)) max_base = max([max_x,max_y]) xx = [i for i in x if i&gt;0] min_x = np.log10(np.m...
0
2016-07-16T07:40:50Z
[ "python", "algorithm", "social-networking", "networkx", "correlation" ]
How to calculate Eb(k) of networks with Python?
38,408,224
<p>In the paper titled <strong>Scaling of degree correlations and its influence on diffusion in scale-free networks</strong>, the authors define the quantity of $E_b(k)$ to measure the extent of degree correlations. </p> <p><a href="http://i.stack.imgur.com/K6aFg.gif"><img src="http://i.stack.imgur.com/K6aFg.gif" alt...
25
2016-07-16T05:52:19Z
38,443,215
<p>It looks like you are actually computing the conditional probability using discrete distributions, so you are getting lots of zeros, which creates problems.</p> <p>In the paper (top of second column, second page) it looks like they are using a power law fit to the data to replace the noisy discrete values with a ni...
0
2016-07-18T18:02:44Z
[ "python", "algorithm", "social-networking", "networkx", "correlation" ]
How to calculate Eb(k) of networks with Python?
38,408,224
<p>In the paper titled <strong>Scaling of degree correlations and its influence on diffusion in scale-free networks</strong>, the authors define the quantity of $E_b(k)$ to measure the extent of degree correlations. </p> <p><a href="http://i.stack.imgur.com/K6aFg.gif"><img src="http://i.stack.imgur.com/K6aFg.gif" alt...
25
2016-07-16T05:52:19Z
38,546,501
<p>According to the paper, the purpose of Eb(k) is to get the correlation exponent epsilon: "[We] introduce a scale-invariant quantity Ebk to simplify the estimation of epsilon" (second page, bottom of first column).</p> <p>I haven't found a way to make Eb(k) &lt; 1, but I have found a correction that <strong>computes...
3
2016-07-23T21:17:33Z
[ "python", "algorithm", "social-networking", "networkx", "correlation" ]
way to convert image straight from url to base64 without saving as a file python
38,408,253
<p>I'm looking to convert a web-based image to base64. I know how to do it currently by saving the image as a .jpg file and then using the base64 library to convert the .jpg file to a base64 string. </p> <p>I'm wondering whether I could skip out the step of saving the image first? </p> <p>Thanks!</p>
0
2016-07-16T05:56:35Z
38,408,285
<p>Using the <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> library:</p> <pre><code>import base64 import requests def get_as_base64(url): return base64.b64encode(requests.get(url).content)) </code></pre>
3
2016-07-16T06:02:51Z
[ "python", "base64", "jpeg" ]
Equality between frozensets
38,408,369
<p>Example:</p> <pre><code>&gt;&gt;&gt; tuple((1, 2)) == tuple((2, 1)) False &gt;&gt;&gt; frozenset((1, 2)) == frozenset((2, 1)) True </code></pre> <p>Frozen sets are immutable. I would expect that equality between immutable objects should by determined by order, but here obviously that is not the case.</p> <p>How c...
0
2016-07-16T06:17:41Z
38,413,858
<p>The short answer is you can't, since as pointed out in the comments, sets and frozensets are unordered data structures. Here are some excerpts from the <a href="https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset" rel="nofollow">docs</a><sup>*</sup> to support this statement:</p> <blockquote> ...
1
2016-07-16T17:38:04Z
[ "python", "set", "immutability" ]
How to create regex with multiple variables in python?
38,408,407
<p>I want to create a regex in python which includes string variables to find the presence of those strings in the input sentence.</p> <p>For example:</p> <p>Input sentences:</p> <p><code>In 2009, I was in Kerala. I love that place.</code></p> <p>String 1 = <strong>I</strong>, String 2 = <strong>was</strong></p> ...
0
2016-07-16T06:22:22Z
38,408,473
<p>Based on my suggestion in the comment above, just adding <code>\b</code>s around the strings. I've left the rest of your regular expression as-is:</p> <pre><code>r'([ A-Za-z0-9]*)\b{string1}\b([^\.!?]*)\b{string2}\b([^\.!?]*[\.!?])'.format( string1=string1, string2=string2) </code></pre>
3
2016-07-16T06:32:09Z
[ "python", "regex" ]
python glob matching patterns
38,408,442
<p>I am looking at the glob man page and I cannot make the matching patterns work in python. I have this so far...</p> <pre><code>glob.glob('file.*') + glob.glob('file[0-9].*') </code></pre> <p>and this works and return me a list as long as the file numbers o not exceed 9. If I make a file100.txt it does not work, an...
0
2016-07-16T06:27:58Z
38,408,502
<p>Ordinary globbing doesn't handle that type of thing. You can't specify repetitions of specific patterns of characters. You won't be able to do it with a single call. Your best bet is to just use <code>file*.txt</code>, and then post-process the resulting list to eliminate ones not matching your pattern, for insta...
2
2016-07-16T06:36:43Z
[ "python", "c", "glob" ]
python glob matching patterns
38,408,442
<p>I am looking at the glob man page and I cannot make the matching patterns work in python. I have this so far...</p> <pre><code>glob.glob('file.*') + glob.glob('file[0-9].*') </code></pre> <p>and this works and return me a list as long as the file numbers o not exceed 9. If I make a file100.txt it does not work, an...
0
2016-07-16T06:27:58Z
38,408,512
<p>I'm pretty sure <code>glob</code> isn't expressive enough to do what you want, so I suggest fetching more than you need and then filtering. E.g. (untested)</p> <pre><code>import re file_names = [name for name in glob.glob('file*.*') if re.match(r'^file\d*\.', name] </code></pre>
3
2016-07-16T06:38:15Z
[ "python", "c", "glob" ]
ImportError: cannot import name 'ajax'
38,408,638
<p>using python 3.4, django 1.9.7 ,django_ajax 0.2.0 ; and test in python 2.7 too ; Here is my code :</p> <pre><code>from django_ajax.decorators import ajax from models import Product from cart.cart import Cart @ajax def ajax_add_to_cart(request): if 'product_id' in request.GET and request.GET['product_id']: ...
3
2016-07-16T06:54:47Z
38,409,976
<p>You've apparently installed the wrong package due to name similarity with another package. That usually happens.</p> <p>You've installed <a href="https://pypi.python.org/pypi/django_ajax/0.2.0" rel="nofollow"><code>django_ajax 0.2.0</code></a> while you intend to use <a href="https://github.com/yceruto/django-ajax"...
2
2016-07-16T10:02:49Z
[ "python", "django" ]
Python code is weirdly jumping to the except block
38,408,856
<p>So I am going nuts here trying to figure out what is happening, I have added a TON of print statements to see what is going on with the code and I cannot make any sense of why it is jumping around like it is...</p> <p>I know the code looks hacky, and it is, but I cannot see why it is jumping into the except block.....
-1
2016-07-16T07:24:06Z
38,582,978
<p>What I should have been doing was exactly what @smarx said. I should have been printing the exception by doing this </p> <pre><code>except Exception as e: print str(e) </code></pre> <p>That will print the exception that is being raised and help me to debug where it went wrong. Outside of that I should have bee...
1
2016-07-26T06:55:59Z
[ "python" ]
int('123') in python - is it a function call or constructor call of 'int' class?
38,408,876
<p>I am learning Python, and I am a little confused about the data types of Python. I am reading this line again and again.:</p> <blockquote> <p>'Everything is an object in Python'</p> </blockquote> <p>This includes integer, floats, string, sets, lists, etc. and when we write like this: <code>[1, 2, 3]</code>, so ...
1
2016-07-16T07:26:23Z
38,408,915
<p>As you can read in the python <a href="https://docs.python.org/2/library/functions.html#int" rel="nofollow">documentation</a>.</p> <blockquote> <p>class int(x, base=10) Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, it can be a plain in...
2
2016-07-16T07:32:22Z
[ "python", "types", "python-3.4" ]
int('123') in python - is it a function call or constructor call of 'int' class?
38,408,876
<p>I am learning Python, and I am a little confused about the data types of Python. I am reading this line again and again.:</p> <blockquote> <p>'Everything is an object in Python'</p> </blockquote> <p>This includes integer, floats, string, sets, lists, etc. and when we write like this: <code>[1, 2, 3]</code>, so ...
1
2016-07-16T07:26:23Z
38,408,970
<p>Yes <code>int</code> is a class (and it's also called a type; see <a href="http://stackoverflow.com/questions/4162578/python-terminology-class-vs-type">Python : terminology 'class' VS 'type'</a>), and doing <code>int('123')</code> returns an instance of an <code>int</code> object. </p> <p>However, (in standard Pyth...
3
2016-07-16T07:39:20Z
[ "python", "types", "python-3.4" ]
Difference between shell=True or False in python subprocess
38,408,908
<p>I just started working with python subprocess module.</p> <p>The code <code>subprocess.call("ls", shell = False) and subprocess.call("ls", shell = True)</code> both return the same results. I just want to know what is the main difference between the two shell options.</p>
0
2016-07-16T07:32:00Z
38,411,544
<p><a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">Straight out of the Docs:</a></p> <blockquote> <p>If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system she...
0
2016-07-16T13:09:00Z
[ "python", "python-2.7", "subprocess" ]
Understanding List Comprehensions in Python
38,408,991
<p>When reading the <a href="https://docs.python.org/2.7/tutorial/datastructures.html#list-comprehensions" rel="nofollow">official tutorial</a>, I encountered this example:</p> <pre><code>&gt;&gt;&gt; vec = [[1,2,3], [4,5,6], [7,8,9]] &gt;&gt;&gt; [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] </cod...
0
2016-07-16T07:42:50Z
38,409,039
<p>No worries :). </p> <p>When you execute the list comprehension the value of <code>num</code> is <code>9</code> so the next time you iterate through the <code>vec</code>. You will get a list of <code>9</code>.</p> <p>See this.</p> <pre><code>In [1]: vec = [[1,2,3], [4,5,6], [7,8,9]] In [2]: [num for elem in vec fo...
2
2016-07-16T07:48:51Z
[ "python", "python-2.7", "list-comprehension" ]
Understanding List Comprehensions in Python
38,408,991
<p>When reading the <a href="https://docs.python.org/2.7/tutorial/datastructures.html#list-comprehensions" rel="nofollow">official tutorial</a>, I encountered this example:</p> <pre><code>&gt;&gt;&gt; vec = [[1,2,3], [4,5,6], [7,8,9]] &gt;&gt;&gt; [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] </cod...
0
2016-07-16T07:42:50Z
38,409,067
<pre><code>list1 = [num for elem in vec for num in elem] #is equivalent to: list1 = [] for elem in vec: for num in elem: list1.append(num) </code></pre>
0
2016-07-16T07:54:10Z
[ "python", "python-2.7", "list-comprehension" ]
Understanding List Comprehensions in Python
38,408,991
<p>When reading the <a href="https://docs.python.org/2.7/tutorial/datastructures.html#list-comprehensions" rel="nofollow">official tutorial</a>, I encountered this example:</p> <pre><code>&gt;&gt;&gt; vec = [[1,2,3], [4,5,6], [7,8,9]] &gt;&gt;&gt; [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] </cod...
0
2016-07-16T07:42:50Z
38,409,123
<p>The loops in list comprehension are read from left to right. If your list comprehension would be written as ordinary loop it would look something like this:</p> <pre><code>&gt;&gt;&gt; vec = [[1,2,3], [4,5,6], [7,8,9]] &gt;&gt;&gt; l = [] &gt;&gt;&gt; for elem in vec: ... for num in elem: ... l.append(n...
4
2016-07-16T08:00:57Z
[ "python", "python-2.7", "list-comprehension" ]
Understanding List Comprehensions in Python
38,408,991
<p>When reading the <a href="https://docs.python.org/2.7/tutorial/datastructures.html#list-comprehensions" rel="nofollow">official tutorial</a>, I encountered this example:</p> <pre><code>&gt;&gt;&gt; vec = [[1,2,3], [4,5,6], [7,8,9]] &gt;&gt;&gt; [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] </cod...
0
2016-07-16T07:42:50Z
38,409,612
<p>Let me try to make the answer more clears. And the order obviously will be from left to right and most right value will be stored in the variable i.e num and elem.</p> <p>Initial Data: </p> <pre><code>vec = [[1,2,3], [4,5,6], [7,8,9]] num # Undefined elem # Undefined </code></pre> <p>Step-1: After execution of l...
0
2016-07-16T09:19:09Z
[ "python", "python-2.7", "list-comprehension" ]
Python : Fill Numpy 2D Array with data from triplets
38,409,054
<p>I have a lot of data in database under (x, y, value) triplet form.<br> I would like to be able to create dynamically a 2d numpy array from this data by setting <code>value</code> at the coords <code>(x,y)</code> of the array.</p> <p>For instance if I have :</p> <pre><code>(0,0,8) (0,1,5) (0,2,3) (1,0,4) (1,1,0) (1...
1
2016-07-16T07:52:26Z
38,409,380
<p>is that what you want?</p> <pre><code>In [37]: a = np.array([(0,0,8) ....: ,(0,1,5) ....: ,(0,2,3) ....: ,(1,0,4) ....: ,(1,1,0) ....: ,(1,2,0) ....: ,(2,0,1) ....: ,(2,1,2) ....: ,(2,2,5)...
2
2016-07-16T08:44:45Z
[ "python", "arrays", "python-3.x", "numpy" ]
Python : Fill Numpy 2D Array with data from triplets
38,409,054
<p>I have a lot of data in database under (x, y, value) triplet form.<br> I would like to be able to create dynamically a 2d numpy array from this data by setting <code>value</code> at the coords <code>(x,y)</code> of the array.</p> <p>For instance if I have :</p> <pre><code>(0,0,8) (0,1,5) (0,2,3) (1,0,4) (1,1,0) (1...
1
2016-07-16T07:52:26Z
38,409,427
<p>Extending the answer from @MaxU, in case the <em>coordinates</em> are not ordered in a grid fashion (or in case some coordinates are missing), you can create your array as follows:</p> <pre><code>import numpy as np a = np.array([(0,0,8),(0,1,5),(0,2,3), (1,0,4),(1,1,0),(1,2,0), (2,0,1),...
2
2016-07-16T08:53:17Z
[ "python", "arrays", "python-3.x", "numpy" ]
connecting to oracle timesten via cx_oracle in sqlalchemy
38,409,112
<p>I can connect to oracle via cx_Oracle in sqlalchemy by this connection string:</p> <pre><code>connection_string = 'oracle+cx_oracle://user:pass@127.0.0.1/orcl' </code></pre> <p>and also i can connect TimesTen by cx_Oracle using this:</p> <pre><code>con = cx_Oracle.connect('user/pass@127.0.0.1/tt2:timestendirect')...
0
2016-07-16T08:00:17Z
38,441,678
<p>You should be able to create an entry in the TNSNAMES.ora configuration file and then use that directly. If you are using the instant client, you can set the environment variable TNS_ADMIN to point to a directory of your choosing that contains the tnsnames.ora configuration file.</p> <p><a href="https://docs.oracle...
0
2016-07-18T16:23:36Z
[ "python", "oracle", "sqlalchemy", "cx-oracle", "timesten" ]
Minimal enclosing parallelogram in Python
38,409,156
<p>I have a set of points defining a convex polygon, and would like to find the enclosing parallelogram with the minimum area using Python and/or NumPy.</p> <p>Here are some possible useful resources, but I'm not able to make enough sense of them myself: <a href="http://uk.mathworks.com/matlabcentral/fileexchange/3476...
2
2016-07-16T08:06:17Z
38,411,487
<p>If instead you want the minimum <em>perimeter</em> enclosing parallelogram, my paper below provides a linear-time algorithm. <hr /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <a href="http://i.stack.imgur.com/zy00j.png" rel="nofollow"><img src="http://i.stack.imgur.com/zy00j.png" alt="Fig10"></a> <hr /> All of the minimum ...
0
2016-07-16T13:01:48Z
[ "python", "matlab", "geometry", "bounding-box", "bounding" ]
Minimal enclosing parallelogram in Python
38,409,156
<p>I have a set of points defining a convex polygon, and would like to find the enclosing parallelogram with the minimum area using Python and/or NumPy.</p> <p>Here are some possible useful resources, but I'm not able to make enough sense of them myself: <a href="http://uk.mathworks.com/matlabcentral/fileexchange/3476...
2
2016-07-16T08:06:17Z
38,450,986
<p>Here is the pure Python O(n) implementation I used:</p> <pre><code>import math """ Minimal Enclosing Parallelogram area, v1, v2, v3, v4 = mep(convex_polygon) convex_polygon - array of points. Each point is a array [x, y] (1d array of 2 elements) points should be presented in clockwise order. the algorithm used ...
0
2016-07-19T06:27:45Z
[ "python", "matlab", "geometry", "bounding-box", "bounding" ]
Screenshot of flash element in Python
38,409,162
<p>How can I take a scrennshot of flash website in Python 3.5.1. I trying something like this but I can't see video image. </p> <pre><code>from selenium import webdriver def webshot(url, filename): browser = webdriver.PhantomJS() browser.get(url) browser.save_screenshot(filename) browser.quit() websh...
1
2016-07-16T08:07:20Z
38,415,505
<p><strong>Short version</strong> : With Youtube system, if you didn't press that "play" button (initiate playback) there is no video served. Loading the page via browser is a form of initiating playback too. However using a <code>webshot</code> doesn't fulfill Youtube server's requirements so it wont work.</p> <p><st...
1
2016-07-16T20:50:45Z
[ "python", "flash", "screenshot" ]
Bit Vector tactic leads to exit code 139 in Z3Py
38,409,443
<p>This is a simple bit vector problem:</p> <pre><code>import z3 s = z3.Tactic('bv').solver() m = z3.Function('m', z3.BitVecSort(32), z3.BitVecSort(32)) a, b = z3.BitVecs('a b', 32) axioms = [ a == m(12432), z3.Not(a == b) ] s.add(axioms) print(s.check()) </code></pre> <p>Python crashes with error code 139...
1
2016-07-16T08:56:20Z
38,443,682
<p>It seems to be a bug in 4.4.0. With 4.4.0 and Ubuntu 16.04 LTS and Python 2.7 you can reproduce the issue. However in newer versions of Z3, it has been fixed. I tried 4.4.2 and it returns <code>sat</code>.</p> <p><a href="https://github.com/Z3Prover/z3/issues/685" rel="nofollow">https://github.com/Z3Prover/z3/issue...
0
2016-07-18T18:29:37Z
[ "python", "z3", "smt", "z3py", "bitvector" ]
Logging to python file doesn't overwrite file when using the mode='w' argument to FileHandler
38,409,450
<p>I have some code to set up a log in Python 2.7 (using the logging module): </p> <pre><code>import os import logging logger=logging.getLogger('CopasiTools') logger.setLevel(logging.DEBUG) log_filename=os.path.join(os.path.dirname(copasi_file),os.path.split(copasi_file)[1][:-4]+'_log.log') handler=logging.FileHandler...
0
2016-07-16T08:57:25Z
38,409,507
<p>I am not familiar with this to much, and I did not really see anything that stuck out in google. Have you tried just using:</p> <pre><code> handler=logging.FileHandler(log_filename, 'w') </code></pre>
0
2016-07-16T09:06:07Z
[ "python", "logging" ]
Logging to python file doesn't overwrite file when using the mode='w' argument to FileHandler
38,409,450
<p>I have some code to set up a log in Python 2.7 (using the logging module): </p> <pre><code>import os import logging logger=logging.getLogger('CopasiTools') logger.setLevel(logging.DEBUG) log_filename=os.path.join(os.path.dirname(copasi_file),os.path.split(copasi_file)[1][:-4]+'_log.log') handler=logging.FileHandler...
0
2016-07-16T08:57:25Z
38,409,645
<p>The problem is that the file doesn't actually get overwritten until a new python shell is started. </p>
0
2016-07-16T09:23:24Z
[ "python", "logging" ]
Django 1.9.7 with bootstrap-admin doesn't work
38,409,475
<p>I just knew bootstrap-admin today and I wanted to try it with my django project, but no matter how I changed my settings, the page doesn't show in a decent way, what have I done wrong? <p>(Django 1.9.7/Python 3.5.2/bootstrap-admin-0.3.6) <p>settings.py</p> <pre><code>import os # Build paths inside the project like...
0
2016-07-16T09:01:38Z
38,409,648
<p>Django Admin was completely restyled in Django 1.9. Last update of [<code>django-admin-boostrap</code>] was more than a year ago (which is prior to Django 1.9 release date).</p> <p>And <a href="https://github.com/django-admin-bootstrap/django-admin-bootstrap/issues/88" rel="nofollow">an issue is opened</a> about th...
0
2016-07-16T09:23:52Z
[ "python", "django", "django-admin" ]
Pandas read html only returning 1 table when 5 tables r found
38,409,569
<p>I am trying to use selenium to scrape tables off the weblink below. However, pandas seems to only be returning the first table, and not all tables. </p> <pre><code>weblink = 'http://sgx.com/wps/portal/sgxweb/home/company_disclosure/stockfacts?page=2&amp;code=A68U&amp;lang=en-us' path_to_chromedriver = r'C:\chromedr...
0
2016-07-16T09:13:44Z
38,411,712
<p>Did you look at the content of the <code>TABLE</code> that was returned? It actually contains all 5 "tables". What looks like separate <code>TABLE</code> tags on the page is actually just one and 5 <code>TBODY</code>s formatted to look like separate <code>TABLE</code>s. You should familiarize yourself with the brows...
1
2016-07-16T13:30:12Z
[ "python", "selenium", "pandas" ]
How to tell the hours elapsed in a csv file?
38,409,586
<p><strong>I want a column that tells me the time elapsed since he first row (5/1/2002 at 6:00AM), to the last (11/20/2006 at 2:00PM). How can I create an extra column that tells me the hours passed since the beginning of 5/1/2002? Here is my dataframe:</strong></p> <pre><code> Date Time (HHMM) Site ...
1
2016-07-16T09:16:21Z
38,410,558
<p>Simple:</p> <ul> <li>read the file,</li> <li>parse the date and time,</li> <li>calculate the delta with the first date/time,</li> <li>write the result.</li> </ul> <p>Here is an implementation using file-like objects for the demo:</p> <pre><code>import datetime import io data = """\ Date Time (HHMM) ...
1
2016-07-16T11:07:30Z
[ "python", "csv", "datetime", "pandas" ]
Replacing one number with another in PYTHON
38,409,592
<p>I have declared a board array which is 10*10.I am reading the elements of the board which are 0, 1, and 2. After reading my board looks somewhat like this (shorter version 4*4)</p> <pre><code> 0 1 0 2 2 1 0 1 0 2 1 0 1 2 1 0 </code></pre> <p>Code: </p> <pre><code>board = [] for i in x...
2
2016-07-16T09:16:47Z
38,410,117
<pre><code>for i in xrange(10): for j in xrange(10): if board[i][j] == 0: board[i][j] = 1 </code></pre> <p>This should works. If not, please show me how you create your <code>board</code> table.</p>
0
2016-07-16T10:20:29Z
[ "python", "arrays", "string", "character" ]
Replacing one number with another in PYTHON
38,409,592
<p>I have declared a board array which is 10*10.I am reading the elements of the board which are 0, 1, and 2. After reading my board looks somewhat like this (shorter version 4*4)</p> <pre><code> 0 1 0 2 2 1 0 1 0 2 1 0 1 2 1 0 </code></pre> <p>Code: </p> <pre><code>board = [] for i in x...
2
2016-07-16T09:16:47Z
38,410,246
<p>As I understood, you have a list and just want to replace all 0's with 1's right? If it's like that, you can try to convert that list to string and use the <code>replace</code> method. Like: <code>board = str(board)</code> and then <code>board = board.replace('0','1')</code>. And then convert back to list with <code...
0
2016-07-16T10:34:31Z
[ "python", "arrays", "string", "character" ]
Accessing query set object in django template with PK
38,409,730
<p>I have a related model with ForeignKey and can't figure out how to access it in template with pk. My models.py is given below for details.</p> <pre><code>class Product(models.Model): title = models.CharField(max_length=500) description = models.TextField(blank=True, null=True) price = models.DecimalFiel...
0
2016-07-16T09:34:32Z
38,410,720
<p>Your Product model has multiple Suppliers (ManyToManyField), thus you will need a for loop to show all of them in the template.</p> <pre><code>{% for supplier in object.suppliers.all %} {{ supplier.name }} {% endfor %} </code></pre>
0
2016-07-16T11:28:09Z
[ "python", "django", "django-templates" ]
Python logging with dict from file for a package
38,409,802
<p>I have a configuration file which I recover like this:</p> <pre><code>path = os.path.dirname(os.path.realpath(__file__)) + '/repository/logging.json' with open(path, 'r') as file: logging_config = json.load(file) dictConfig(logging_config) </code></pre> <p>It works but my concern is about packaging the projec...
0
2016-07-16T09:44:09Z
38,410,280
<p>Depending of the kind of application you have, you can have several configurations levels.</p> <p>The common one is two levels :</p> <ol> <li><p>Application-wide configuration located:</p> <ul> <li>near your application's installation folder (mostly for Windows applications),</li> <li>in a specific folder (in <c...
0
2016-07-16T10:38:29Z
[ "python", "logging", "packaging" ]
Python logging with dict from file for a package
38,409,802
<p>I have a configuration file which I recover like this:</p> <pre><code>path = os.path.dirname(os.path.realpath(__file__)) + '/repository/logging.json' with open(path, 'r') as file: logging_config = json.load(file) dictConfig(logging_config) </code></pre> <p>It works but my concern is about packaging the projec...
0
2016-07-16T09:44:09Z
38,411,902
<h1>My App - Two-level configuration example</h1> <p>Example of project with two levels of configuration files:</p> <ul> <li>LEVEL 1: read the configuration from the sources/application's folder (virtualenv)</li> <li>LEVEL 2: read the configuration from the user HOME</li> </ul> <h2>Python project structure</h2> <p>...
0
2016-07-16T13:52:16Z
[ "python", "logging", "packaging" ]
Search and delete duplicate time-series data in pandas dataframe
38,409,805
<p>I have a data source which I can call to get end of day time-series data for financial instruments.</p> <p>As an example, say that I have the following financial instruments' data already coded and retrieved from the data source:</p> <pre><code>price_a </code></pre> <blockquote> <p>[24.74636733, 29.65460993, 28...
2
2016-07-16T09:44:42Z
38,410,267
<pre><code>price_a = [24.74636733, 29.65460993, 28.09686357, 16.24366395, 27.26716605, 17.1444073, 18.76608861, 17.68487362, 19.5026825, 25.62365151, 12.92619601, 25.66759065, 24.40646289, 15.61753458, 13.82584258, 27.2508518, 12.22547517, 24.2317834, 13.33257932, 28.18551972, ...
2
2016-07-16T10:37:01Z
[ "python", "pandas", "dataframe" ]
print unique numbers from a sorted list python
38,409,847
<p>I'm trying to print all elements in a sorted list that only occur <em>once</em>.</p> <p>My code below works but I'm sure there is a better way:</p> <pre><code>def print_unique(alist): i = 0 for i in range(len(alist)): if i &lt; (len(alist)-1): if alist[i] == alist[i+1]: ...
0
2016-07-16T09:48:51Z
38,409,878
<p>you can do by this:</p> <pre><code>print (set(YOUR_LIST)) </code></pre> <p>or if you need a list use this:</p> <pre><code>print (list(set(YOUR_LIST))) </code></pre>
-3
2016-07-16T09:51:43Z
[ "python" ]
print unique numbers from a sorted list python
38,409,847
<p>I'm trying to print all elements in a sorted list that only occur <em>once</em>.</p> <p>My code below works but I'm sure there is a better way:</p> <pre><code>def print_unique(alist): i = 0 for i in range(len(alist)): if i &lt; (len(alist)-1): if alist[i] == alist[i+1]: ...
0
2016-07-16T09:48:51Z
38,409,885
<p>Sets are lists containing unique items. If you construct a set from the array, it will contain only the unique items:</p> <pre><code>def print_unique(alist): print set( alist ) </code></pre> <p>The input list does not need to be sorted.</p>
-4
2016-07-16T09:52:44Z
[ "python" ]
print unique numbers from a sorted list python
38,409,847
<p>I'm trying to print all elements in a sorted list that only occur <em>once</em>.</p> <p>My code below works but I'm sure there is a better way:</p> <pre><code>def print_unique(alist): i = 0 for i in range(len(alist)): if i &lt; (len(alist)-1): if alist[i] == alist[i+1]: ...
0
2016-07-16T09:48:51Z
38,409,927
<p>This question seems to have duplicates.</p> <p>If you do not wish to preserve the order of your list, you can do</p> <pre><code>print list(set(sample_list)) </code></pre> <p>You can also try,</p> <pre><code>unique_list = [] for i in sample_list: if i not in unique_list: unique_list.append(i) </code><...
-1
2016-07-16T09:57:32Z
[ "python" ]
print unique numbers from a sorted list python
38,409,847
<p>I'm trying to print all elements in a sorted list that only occur <em>once</em>.</p> <p>My code below works but I'm sure there is a better way:</p> <pre><code>def print_unique(alist): i = 0 for i in range(len(alist)): if i &lt; (len(alist)-1): if alist[i] == alist[i+1]: ...
0
2016-07-16T09:48:51Z
38,410,155
<p>You could use the <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code> function</a> to group your inputs and filter on groups that are one element long:</p> <pre><code>from itertools import groupby def print_unique(alist): for elem, group ...
3
2016-07-16T10:23:46Z
[ "python" ]
Function that operates on Spark column as argument
38,409,869
<p><strong>Edit: Finally figured it out myself. I kept using <code>select()</code> on <code>column</code> within the function, that's why it didn't work. I added my solution as comments withint the original question just in case it might be of use for somebody else.</strong> </p> <p>I'm working on an online course wh...
-3
2016-07-16T09:51:09Z
38,718,778
<p>You can do this in a single line.</p> <pre><code>return re.sub(r'[^a-z0-9\s]','',text.lower().strip()).strip() </code></pre>
0
2016-08-02T11:08:51Z
[ "python", "apache-spark", "pyspark" ]
Pandas trade signal columns
38,409,962
<p>I am trying to add columns showing a value of 1 where a trade signal is seen. I have put together the following test data to show what I am trying to do.</p> <p>Create test dataframe:</p> <pre><code>import pandas as pd import datetime index = pd.date_range('2013-1-1',periods=100,freq='30Min') data = pd.DataFrame(...
0
2016-07-16T10:01:30Z
38,423,446
<p>Hope this helps. I changed a bit in the data generation code.</p> <pre><code>import pandas as pd import random periods = 48*7 index = pd.date_range('2013-1-1',periods=periods,freq='30Min') data = pd.DataFrame({'value':[random.randint(0,100)+i/10 for i in range(periods)], 'enter_long':[False]*periods, 'enter_short'...
1
2016-07-17T16:31:39Z
[ "python", "pandas" ]
How to get the mean of a subset of rows after using groupby?
38,410,490
<p>I want to get the average of a particular subset of rows in one particular column in my dataframe. </p> <p>I can use </p> <pre><code>df['C'].iloc[2:9].mean() </code></pre> <p>to get the mean of just the particular rows I want from my original Dataframe but my problem is that I want to perform this operation after...
0
2016-07-16T11:00:08Z
38,411,024
<p>Try this variant:</p> <pre><code>for key, grp in df.groupby(["A", "B"]): print grp['C'].iloc[2:9].mean() </code></pre>
2
2016-07-16T12:04:56Z
[ "python", "pandas" ]
How to get the mean of a subset of rows after using groupby?
38,410,490
<p>I want to get the average of a particular subset of rows in one particular column in my dataframe. </p> <p>I can use </p> <pre><code>df['C'].iloc[2:9].mean() </code></pre> <p>to get the mean of just the particular rows I want from my original Dataframe but my problem is that I want to perform this operation after...
0
2016-07-16T11:00:08Z
38,411,890
<p>You can use <code>agg</code> function after the groupby and then subset within each group and take the <code>mean</code>:</p> <pre><code>df = pd.DataFrame({'A': ['a']*22, 'B': ['b1']*11 + ['b2']*11, 'C': list(range(11))*2}) # A dummy data frame to demonstrate df.groupby(['A', 'B'])['C'].agg(lambda g: g.iloc[2:9].m...
2
2016-07-16T13:50:45Z
[ "python", "pandas" ]
Regex match single characters between strings
38,410,513
<p>I have a string with some markup which I'm trying to parse, generally formatted like this.</p> <pre><code>'[*]\r\n[list][*][*][/list][*]text[list][*][/list]' </code></pre> <p>I want to match the asterisks within the [list] tags so I can re.sub them as [**] but I'm having trouble forming an expression to grab them....
1
2016-07-16T11:02:22Z
38,410,874
<p>You may use a <code>re.sub</code> and use a lambda in the replacement part. You pass the match to the lambda and use a mere <code>.replace('*','**')</code> on the match value.</p> <p>Here is the sample code:</p> <pre><code>import re s = '[*]\r\n[list][*][*][/list][*]text[list][*][/list]' match = re.compile('\[list...
0
2016-07-16T11:44:20Z
[ "python", "regex" ]
Python get web page contents that have javascripts - maybe Selenium
38,410,620
<p>I need to analyse web page contents. Page has javascrips. Can you advice on better way than using Selenium?</p> <p>If not: page when loaded in browser has elements:</p> <pre><code>&lt;div class="js-container"&gt; &lt;table class="zebra" style="width: 100%;"&gt; &lt;tbody&gt;&lt;tr&gt; &lt;t...
0
2016-07-16T11:15:32Z
38,410,761
<p>Maybe you need BeautifulSoup - feeding to it Selenium driver.page_source. It is a python tool and it can build a tree based on the web page. <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup document</a></p>
2
2016-07-16T11:33:10Z
[ "javascript", "python", "html", "selenium" ]
Python get web page contents that have javascripts - maybe Selenium
38,410,620
<p>I need to analyse web page contents. Page has javascrips. Can you advice on better way than using Selenium?</p> <p>If not: page when loaded in browser has elements:</p> <pre><code>&lt;div class="js-container"&gt; &lt;table class="zebra" style="width: 100%;"&gt; &lt;tbody&gt;&lt;tr&gt; &lt;t...
0
2016-07-16T11:15:32Z
38,411,665
<p>Selenium can do this just fine.</p> <pre><code>tableDescendants = myDriver.find_elements_by_css_selector("table.zebra *") for tableDescendant in tableDescendants outer = tableDescendant.get_attribute("outerHTML") inner = tableDescendant.get_attribute("innerHTML") print outer[:outer.find(inner)] </code><...
2
2016-07-16T13:23:52Z
[ "javascript", "python", "html", "selenium" ]
Given a byte buffer, dtype, shape and strides, how to create Numpy ndarray
38,410,631
<p>I have a buffer, dtype, shape and strides. I want to create a Numpy ndarray which reuses the memory of the buffer.</p> <p>There is <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.frombuffer.html" rel="nofollow"><code>numpy.frombuffer</code></a> which creates a 1D array from a buffer and reuses th...
3
2016-07-16T11:16:36Z
38,413,027
<p>I'd stick with <code>frombuffer</code> because it's intended directly for this purpose, and makes it clear what you're doing. Here's an example:</p> <pre><code>In [58]: s0 = 'aaaa' # a single int32 In [59]: s1 = 'aaabaaacaaadaaae' # 4 int32s, each increasing by 1 In [60]: a0 = np.frombuffer(s0, dtype='&gt;i4'...
2
2016-07-16T16:11:28Z
[ "python", "arrays", "numpy", "multidimensional-array", "buffer" ]
Given a byte buffer, dtype, shape and strides, how to create Numpy ndarray
38,410,631
<p>I have a buffer, dtype, shape and strides. I want to create a Numpy ndarray which reuses the memory of the buffer.</p> <p>There is <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.frombuffer.html" rel="nofollow"><code>numpy.frombuffer</code></a> which creates a 1D array from a buffer and reuses th...
3
2016-07-16T11:16:36Z
38,414,598
<p>You could use either method - neither of them will generate a copy:</p> <pre><code>s = 'aaabaaacaaadaaae' a1 = np.frombuffer(s, np.int32, 4).reshape(2, 2) a2 = np.ndarray((2, 2), np.int32, buffer=s) print(a1.flags.owndata, a1.base) # (False, 'aaabaaacaaadaaae') print(a2.flags.owndata, a2.base) # (False, 'aaabaaac...
1
2016-07-16T19:02:29Z
[ "python", "arrays", "numpy", "multidimensional-array", "buffer" ]
Python3 urllib3 crawler - can't limit max connections to aa single domain
38,410,661
<p>I am using python3 urllib3 in order to build a crawler to download multiple urls.</p> <p>On my main activity i create 20 threads of that using <strong>the same (one) instance</strong> of my <code>Downloader</code> class which uses one instance of <code>PoolManager</code>:</p> <pre><code>def __init__(self): sel...
0
2016-07-16T11:20:55Z
38,411,961
<p><code>PoolManager(num_pools=20)</code> will limit the pool to 20 cached instances of ConnectionPools, each representing one domain usually. So you're effectively limiting to 20 cached domain pools, the per-domain connections are one level deeper.</p> <p>We can specify the limit per ConnectionPool with <code>maxsize...
1
2016-07-16T14:00:34Z
[ "python", "urllib", "urllib3" ]
Take Screenshot on Windows and save it?
38,410,695
<p>i want to take a screenshot , using python , (Windows Only) and SAVE IT ! i am using pyscreenshot library and PIL</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from PIL import ImageGrab import pyscreenshot as ImageGrab img = ImageGrab.grab() plt.imshow(img, cmap='gray', interpolation='bicubic...
0
2016-07-16T11:24:39Z
38,410,797
<p>try this code:</p> <pre><code>import pyscreenshot as ImageGrab # fullscreen im=ImageGrab.grab() im.show() # part of the screen im=ImageGrab.grab(bbox=(10,10,500,500)) im.show() # to file ImageGrab.grab_to_file('im.png') </code></pre>
0
2016-07-16T11:37:06Z
[ "python", "save", "screenshot" ]
Removing trailing zero after decimal point in python
38,410,800
<pre><code>import math math.floor(85.21) </code></pre> <p>returns <code>85.0</code></p> <p>I want to save the number as a file name and I don't want to see the zero! I would like the output to be <code>85</code></p>
0
2016-07-16T11:37:16Z
38,410,815
<p>Then you should consider <em>casting</em> to <code>int</code> which does the same thing but without the trailing <code>.0</code> instead of <code>math.floor</code>:</p> <pre><code>&gt;&gt;&gt; int(85.21) 85 </code></pre> <blockquote> <p>I want to save the number as a file name</p> </blockquote> <p>Since OP will...
3
2016-07-16T11:38:39Z
[ "python", "floating-point", "floor" ]
Removing trailing zero after decimal point in python
38,410,800
<pre><code>import math math.floor(85.21) </code></pre> <p>returns <code>85.0</code></p> <p>I want to save the number as a file name and I don't want to see the zero! I would like the output to be <code>85</code></p>
0
2016-07-16T11:37:16Z
38,410,831
<pre><code>import math result=int(math.floor(85.21)) print(result) </code></pre>
3
2016-07-16T11:40:04Z
[ "python", "floating-point", "floor" ]
Copying few bits of one variable into another
38,410,843
<p>I have a variable say A that stores 1101 0010 . But I want to just copy the first 5 bits into another variable say B. Also I want to concatenate some bits from another variable to variable B. Basically if A = 1101 0010 then B = 11010 (just taking first 5 bits from A) and C = 1101 0111 (adding 111 to the already e...
-3
2016-07-16T11:41:15Z
38,410,921
<p>In case the A var is a string, you'll have to slice it then concatenate it. </p> <p>Here is an example : </p> <pre><code>&gt;&gt;&gt; a = '11010 0010' &gt;&gt;&gt; b = a[0:5] &gt;&gt;&gt; b '11010' &gt;&gt;&gt; c = b + '111' &gt;&gt;&gt; c = int(c,2) &gt;&gt;&gt; c 215 &gt;&gt;&gt; bin(c) '0b11010111' </code></pre...
0
2016-07-16T11:51:03Z
[ "python", "variables", "bit-manipulation", "concatenation" ]
Copying few bits of one variable into another
38,410,843
<p>I have a variable say A that stores 1101 0010 . But I want to just copy the first 5 bits into another variable say B. Also I want to concatenate some bits from another variable to variable B. Basically if A = 1101 0010 then B = 11010 (just taking first 5 bits from A) and C = 1101 0111 (adding 111 to the already e...
-3
2016-07-16T11:41:15Z
38,410,978
<p>You can do it as:</p> <pre><code>&gt;&gt;&gt; a=int('11010010', 2) &gt;&gt;&gt; temp=int('11111000', 2) &gt;&gt;&gt; b=(a&amp;temp) &gt;&gt;&gt; c=int('11010111', 2) &gt;&gt;&gt; temp1=c&amp;int('00000111', 2) &gt;&gt;&gt; b=b|temp1 &gt;&gt;&gt; b 215 &gt;&gt;&gt; bin(b) '0b11010111' </code></pre>
0
2016-07-16T11:59:46Z
[ "python", "variables", "bit-manipulation", "concatenation" ]
Can't import module with importlib.import_module
38,410,960
<p>I want to use <code>importlib.import_module</code> to import modules dynamically. My code like this:</p> <pre><code>import os import importlib os.chdir('D:\\Python27\\Lib\\bsddb') m = importlib.import_module('db') print dir(m) </code></pre> <p>I can to this successfully in the Python console. But if I run these c...
0
2016-07-16T11:56:49Z
38,412,132
<p>EDIT: I had tested the earlier code in console and it worked. However, I have modified the code again. I kept the <code>bsddb</code> module directly in <code>D drive</code> and changed the code again to:</p> <pre><code>import os os.chdir("D:\\") import importlib m = importlib.import_module("bsddb.db") print len(dir...
0
2016-07-16T14:23:41Z
[ "python", "import", "module", "python-importlib" ]
superfast regexmatch in large text file
38,410,982
<p>I want this code to work fast.</p> <pre><code>import re with open('largetextfile.txt') as f: for line in f: pattern = re.compile("^1234567") if pattern.match(line): print (line) </code></pre> <p>takes 19 seconds.</p> <p>I modified it:</p> <pre><code>import re with open('largetextf...
2
2016-07-16T12:00:13Z
38,411,067
<p>Check if this matches your requirement:</p> <pre><code>with open('largetextfile.txt') as f: for line in f: if line.startswith('1234567'): print line </code></pre>
3
2016-07-16T12:10:28Z
[ "python" ]
superfast regexmatch in large text file
38,410,982
<p>I want this code to work fast.</p> <pre><code>import re with open('largetextfile.txt') as f: for line in f: pattern = re.compile("^1234567") if pattern.match(line): print (line) </code></pre> <p>takes 19 seconds.</p> <p>I modified it:</p> <pre><code>import re with open('largetextf...
2
2016-07-16T12:00:13Z
38,411,597
<p>Since you're matching a string you don't need regular expressions, so you can use this</p> <pre><code>with open('bigfile.txt') as f: for line in f: if line[:7]=="1234567": print (line) </code></pre> <p>I noticed that using string slicing is slightly faster than <code>startswith</code>...
1
2016-07-16T13:15:06Z
[ "python" ]
superfast regexmatch in large text file
38,410,982
<p>I want this code to work fast.</p> <pre><code>import re with open('largetextfile.txt') as f: for line in f: pattern = re.compile("^1234567") if pattern.match(line): print (line) </code></pre> <p>takes 19 seconds.</p> <p>I modified it:</p> <pre><code>import re with open('largetextf...
2
2016-07-16T12:00:13Z
38,412,331
<p>In order to perform tests, I copied in a file <strong>AAA.txt</strong> the following text of 6,31 MB and around 128.000 lines:<br> <a href="http://norvig.com/big.txt" rel="nofollow">http://norvig.com/big.txt</a><br> Then with the help of random module, I changed it to a file <strong>BBB.txt</strong> by randomly inse...
1
2016-07-16T14:49:36Z
[ "python" ]
Pygame/SDL Low Framerate at HD
38,410,990
<p>I know similar stuff like this has been asked before but I couldn't find an answer beyond "don't redraw the whole screen at once" which really isn't an option for a scrolling 2D shooter, where even if I didn't update the whole screen when not necessary, a player wouldn't notice framerates unless you moved anyway, wh...
0
2016-07-16T12:01:31Z
38,426,567
<p>Only scale your assets ONCE at startup. Your logic can stay at default resolution but do the math for the offset when blitting instead. That way you don't scale every frame.</p> <p>On a side note about pygame and performance: pygame, aka sdl1 uses software rendering. Which means your GPU is not used to do the heavy...
0
2016-07-17T22:34:03Z
[ "python", "performance", "pygame", "sdl", "frame-rate" ]
Is it possible to insert import statements with jedi-vim?
38,411,010
<p>I've just started looking at the Vim jedi plugin, and it seems pretty impressive. One feature of some of the Java IDEs I've used is the ability to automatically add required imports. Can Jedi do that? For example, if I enter a line such as</p> <pre><code>arg1 = sys.argv[1] </code></pre> <p>and then invoke some Jed...
1
2016-07-16T12:03:17Z
38,419,392
<p>Currently Jedi doesn't do refactoringing. This includes import additions. There's an issue for the whole subject: <a href="https://github.com/davidhalter/jedi/issues/667" rel="nofollow">https://github.com/davidhalter/jedi/issues/667</a>.</p> <p>It's not that easy to implement this command with good performance. How...
0
2016-07-17T08:39:41Z
[ "python", "vim", "jedi-vim" ]
Is it possible to insert import statements with jedi-vim?
38,411,010
<p>I've just started looking at the Vim jedi plugin, and it seems pretty impressive. One feature of some of the Java IDEs I've used is the ability to automatically add required imports. Can Jedi do that? For example, if I enter a line such as</p> <pre><code>arg1 = sys.argv[1] </code></pre> <p>and then invoke some Jed...
1
2016-07-16T12:03:17Z
38,432,871
<p>FIY, I've defined a generic import feature that can be used on demand in <a href="https://github.com/LucHermitte/lh-dev" rel="nofollow">lh-dev</a>. I use it from my C&amp;C++ suite, and from my <a href="https://github.com/LucHermitte/mu-template/" rel="nofollow">snippet engine (mu-template)</a>.</p> <p>So far I don...
0
2016-07-18T09:16:24Z
[ "python", "vim", "jedi-vim" ]
Windows: Using Tensorflow with Python 3 instead of Python 2 (Docker)
38,411,049
<p>Dearest Community,</p> <p>I've been searching for hours, but after several trials and errors, I give up and ask you, honourable community.</p> <p>My problem is very similar to the one stated here: <a href="http://stackoverflow.com/questions/35771285/using-tensorflow-through-jupyter-python-3">Using TensorFlow throu...
0
2016-07-16T12:08:28Z
38,471,766
<p>Looks like someone created a Tensorflow + Jupyter + Python 3 Docker image (<code>erroneousboat/tensorflow-python3-jupyter</code>) that should fit your needs.</p> <p>You should be able to run the image and sync the Jupyter notebook files to your Windows filesystem with the following, replacing <code>[PATH_TO_NOTEBOO...
0
2016-07-20T03:21:27Z
[ "python", "windows", "docker", "kernel", "tensorflow" ]
Use two different LSTM cell in Tensorflow
38,411,113
<p>I am building a neural machine translator, and I have to use two <strong>different</strong> LSTM cells (one for the encoder, and one for the decode).</p> <p>The two cells have differents shapes:</p> <ul> <li>the encoder (first one) is fed with the token of the input sentence and produces a state vector</li> <li>th...
1
2016-07-16T12:15:55Z
38,424,892
<p>Use variable scopes</p> <pre><code>with tf.variable_scope('enc'): cell_enc = LSTMCell(hidden_size) with tf.variable_scope('dec'): cell_dec = LSTMCell(hidden_size) </code></pre>
0
2016-07-17T19:02:05Z
[ "python", "neural-network", "tensorflow", "lstm", "machine-translation" ]
Use two different LSTM cell in Tensorflow
38,411,113
<p>I am building a neural machine translator, and I have to use two <strong>different</strong> LSTM cells (one for the encoder, and one for the decode).</p> <p>The two cells have differents shapes:</p> <ul> <li>the encoder (first one) is fed with the token of the input sentence and produces a state vector</li> <li>th...
1
2016-07-16T12:15:55Z
38,425,872
<p>I am trying to do machine translation. Here is my encoder and decoder. You just need to use different variable scopes for each rnn. Rather than using the MultiRNNCell cell for the encoder I unroll each layer manually which lets me alternate directions between layers. See how each layer gets its own scope.</p> <...
0
2016-07-17T20:58:33Z
[ "python", "neural-network", "tensorflow", "lstm", "machine-translation" ]
Python 'static core class'
38,411,166
<p>Currently I'm making a game server, I actually want to make a base project for all my server products in Python. I used to use C# but I wanted to do something different so I started on Python. Although I don't know how to do something.</p> <p>In C# I used to make one static 'core' class holding all data, containing...
1
2016-07-16T12:23:57Z
38,411,600
<p>Typical Python code doesn't use static members very much.<sup>1</sup> So I would advise making most of your variables instance variables. For instance, in <code>DynamicEmu.py</code>, don't have a module-level <code>Engine</code> instance. Instead, have a class which is initialized with an <code>Engine</code> instanc...
2
2016-07-16T13:15:33Z
[ "python" ]
Matplotlib get clean plot (remove all decorations)
38,411,226
<p>As a reference, same question but for <code>imshow()</code>: <a href="http://stackoverflow.com/questions/9295026/matplotlib-plots-removing-axis-legends-and-white-spaces">Matplotlib plots: removing axis, legends and white spaces</a></p> <p>It is not obvious in embedded image on selected answer that there are fat whi...
2
2016-07-16T12:32:10Z
38,411,334
<p>I just learned that @unutbu's answer does work with <code>plot()</code> too, if we remove <code>aspect='normal'</code> from <code>plot()</code> directive:</p> <pre><code>data = np.arange(1,10).reshape((3, 3)) fig = plt.figure() fig.set_size_inches(1, 1) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add...
0
2016-07-16T12:43:19Z
[ "python", "matplotlib" ]
Matplotlib get clean plot (remove all decorations)
38,411,226
<p>As a reference, same question but for <code>imshow()</code>: <a href="http://stackoverflow.com/questions/9295026/matplotlib-plots-removing-axis-legends-and-white-spaces">Matplotlib plots: removing axis, legends and white spaces</a></p> <p>It is not obvious in embedded image on selected answer that there are fat whi...
2
2016-07-16T12:32:10Z
38,411,521
<p><code>ax.set_axis_off()</code>, or equivalently, <code>ax.axis('off')</code> toggles the axis lines and labels off. To remove more whitespace, you could use </p> <pre><code>fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0) </code></pre> <p>Or <a href="http://stackoverflow.com/a/4328608/190597">to ...
2
2016-07-16T13:06:26Z
[ "python", "matplotlib" ]
Kik Python documentation for new Invite functionality
38,411,355
<p>We have developed a Kik bot using Python and now want to include the new Invite functionality, but do not see an update in the Python API docs. Is there documentation? If so, where can we find it?</p>
0
2016-07-16T12:45:10Z
38,490,281
<p>Sorry for the delay. Thanks for bringing this up, the docs hadn't been updated/released yet. They are out now here <a href="https://kik.readthedocs.io/en/latest/api.html#kik.messages.FriendPickerMessage" rel="nofollow">https://kik.readthedocs.io/en/latest/api.html#kik.messages.FriendPickerMessage</a> if you have any...
0
2016-07-20T20:29:29Z
[ "python", "documentation", "kik" ]
How do I print from a Python 2.7 script invoked from Bash within PyCharm?
38,411,532
<p>For example if I have a python script <code>test.py</code> containing</p> <pre><code>import time print 'foo' time.sleep(5) print 'bar' time.sleep(5) </code></pre> <p>and a shell script <code>run_test.sh</code> containing</p> <pre><code>#!/usr/bin/env bash python test.py </code></pre> <p>then running the latte...
2
2016-07-16T13:07:34Z
38,411,633
<p>Looks like you need to explicitly flush the buffer:</p> <pre><code>import sys print 'foo' sys.stdout.flush() time.sleep(5) print 'bar' sys.stdout.flush() time.sleep(5) </code></pre> <p>See <a href="http://stackoverflow.com/questions/107705/disable-output-buffering">Disable output buffering</a> for Python 2 solut...
4
2016-07-16T13:19:20Z
[ "python", "bash", "python-2.7", "output", "pycharm" ]
How do I print from a Python 2.7 script invoked from Bash within PyCharm?
38,411,532
<p>For example if I have a python script <code>test.py</code> containing</p> <pre><code>import time print 'foo' time.sleep(5) print 'bar' time.sleep(5) </code></pre> <p>and a shell script <code>run_test.sh</code> containing</p> <pre><code>#!/usr/bin/env bash python test.py </code></pre> <p>then running the latte...
2
2016-07-16T13:07:34Z
38,411,691
<p>Just to add to <a href="https://stackoverflow.com/users/100297/martijn-pieters">@MartijnPieters' answer</a> with regard to PyCharm:</p> <p>In PyCharm, set the run configuration for the shell script under <strong>Run</strong>-><strong>Edit Configurations</strong>, like so:</p> <p><a href="http://i.stack.imgur.com/h...
1
2016-07-16T13:27:59Z
[ "python", "bash", "python-2.7", "output", "pycharm" ]
Pygame, game stops if mouse moves
38,411,554
<p><strong>INFO:</strong> I am currently working on a game and want to get the idea of a start menu down pat before moving on, as this will help with further parts of my game I want to design. Basically I want it so when I press <code>START GAME</code> the game will start, when I press <code>HELP</code>it'll show a hel...
0
2016-07-16T13:09:55Z
38,421,324
<p>I've found your problem now. The problem is in the game loop.</p> <pre><code>while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if menu_on == True: **do stuff 1** if game_start == True: **do stuff 2** </code></pre> <p>In **do...
0
2016-07-17T12:42:49Z
[ "python", "python-2.7", "menu", "pygame", "startup" ]
Making sure a response is given from csv
38,411,605
<p>I am having a problem with a project I'm currently working on. My project is to take a user's query about a problem that they are having with their phone and the program searches for keywords in a csv file. If it finds a keyword in the csv, it prints a linked answer.</p> <p>This is the code:</p> <pre><code>import ...
-2
2016-07-16T13:16:41Z
38,413,023
<p>You get no response because there is no code to display anything when a word is matched nor when there weren't any. In other words—at the very least—you need to add one or more calls to <code>print()</code> based on whether <code>Solved</code> is True <em>or not</em> after the <code>for</code> loops end. i.e. Us...
0
2016-07-16T16:11:09Z
[ "python", "python-3.x", "csv", "response" ]
algining text to center in label in tkinter
38,411,608
<p><a href="http://i.stack.imgur.com/4M1FT.png" rel="nofollow">Image</a></p> <p>I want to align the text of label l to centre so that it doesnot look weird. How can i do that?Thnks in advance.</p> <p>Code:</p> <pre><code>from Tkinter import * import tkMessageBox def func(event): if len(entry1.get())==0 and len(...
0
2016-07-16T13:16:56Z
38,412,234
<p>Text is by default centered inside the Label area. To expand the label across the two columns, you can use the <code>colspan</code> attribute of grid.</p> <p>Since you have your labels in col 19 and your entries column 20, you can try</p> <pre><code>l.grid(row=0,column=19,columnspan=2) </code></pre>
0
2016-07-16T14:36:47Z
[ "python", "python-2.7", "user-interface", "tkinter" ]
When is sys.path modified?
38,411,636
<p>I'm having some difficulty understanding this paragraph in the <a href="https://docs.python.org/2/tutorial/modules.html#the-module-search-path" rel="nofollow">official tutorial</a>:</p> <blockquote> <p>After initialization, Python programs can modify <code>sys.path</code>. The directory containing the script be...
1
2016-07-16T13:20:09Z
38,411,659
<p><code>sys</code> is a <em>built-in</em> module, it is part of the interpreter, and cannot be masked because it is already loaded when the interpreter starts.</p> <p>That's because <code>sys.modules</code> is the core registry for modules being loaded, and <code>sys.modules['sys']</code> points to itself. Any <code>...
2
2016-07-16T13:23:25Z
[ "python", "python-2.7", "sys" ]