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
list
Conditional Iteration over a dataframe
38,984,043
<p>I have a dataframe <code>df</code> which looks like:</p> <pre><code> id location grain 0 BBG.XETR.AD.S XETR 16.545 1 BBG.XLON.VB.S XLON 6.2154 2 BBG.XLON.HF.S XLON NaN 3 BBG.XLON.RE.S XLON NaN 4 BBG.XLON.LL.S XLON NaN 5 BBG.XLON.AN.S ...
1
2016-08-16T20:37:52Z
38,984,252
<p>This:</p> <pre><code>df[pd.notnull(df['grain'])] </code></pre> <p>Or this:</p> <pre><code>df['grain].dropna() </code></pre>
0
2016-08-16T20:51:16Z
[ "python", "pandas" ]
Conditional Iteration over a dataframe
38,984,043
<p>I have a dataframe <code>df</code> which looks like:</p> <pre><code> id location grain 0 BBG.XETR.AD.S XETR 16.545 1 BBG.XLON.VB.S XLON 6.2154 2 BBG.XLON.HF.S XLON NaN 3 BBG.XLON.RE.S XLON NaN 4 BBG.XLON.LL.S XLON NaN 5 BBG.XLON.AN.S ...
1
2016-08-16T20:37:52Z
38,984,333
<p>Let's compare different methods (for 800K rows DF):</p> <pre><code>In [21]: df = pd.concat([df] * 10**5, ignore_index=True) In [22]: df.shape Out[22]: (800000, 3) In [23]: %timeit df.grain[~pd.isnull(df.grain)] The slowest run took 5.33 times longer than the fastest. This could mean that an intermediate result is...
0
2016-08-16T20:55:49Z
[ "python", "pandas" ]
MultiValueDictKeyError at /registroEstudianteMayor/ "'Acudiente'"
38,984,044
<p>I have this error </p> <blockquote> <p>MultiValueDictKeyError at /registroEstudianteMayor/"'Acudiente'" ",</p> </blockquote> <p>I searched a lot for an answer to this error but I couldn't find any.</p> <p>I have this controller:</p> <pre><code>def post(self, request, *args, **kwargs): generos = parametros[...
0
2016-08-16T20:37:59Z
38,984,317
<p>You don't have a field called Acudiente in your view; you have one called Nomacud instead.</p> <p>Really though you should be using Django forms for all this.</p>
0
2016-08-16T20:54:44Z
[ "python", "django", "multivalue" ]
add training data to existing LinearSVC
38,984,069
<p>I am scraping approximately 200,000 websites, looking for certain types of media posted on the websites of small businesses. I have a pickled linearSVC, which I've trained to predict the probability that a link found on a web page contains media of the type that I'm looking for, and it performs rather well (overall ...
1
2016-08-16T20:39:15Z
38,984,364
<p>You cannot add data to SVM and achieve the same result as if you would add it to the original training set. You can either retrain with extended training set starting with the previous solution (should be faster) or train on new data only and completely diverge from the previous solution.</p> <p>There are only few ...
2
2016-08-16T20:58:20Z
[ "python", "machine-learning", "scikit-learn" ]
Using Python Exscript need to create regular expression for set_prompt() for cisco switch
38,984,101
<p>Having a hard time figuring out how to write a regular expression in python/exscript so that the prompt matches the output when i run "copy run tftp"...</p> <p>For example the prompt changes to...</p> <p>"Address or name of remote host []?"</p> <p>then to...</p> <p>"Destination filename [lab-3560.confg]?"</p> <...
0
2016-08-16T20:41:09Z
39,045,058
<p>There are so many ways to do this, here is an example:</p> <p>So all you need to do is parse the returned prompt/text, here is a small example from this <a href="http://www.electricmonk.nl/log/2014/07/26/scripting-a-cisco-switch-with-python-and-expect/" rel="nofollow">link</a>:</p> <pre><code>import pexpect switc...
0
2016-08-19T17:50:44Z
[ "python", "cisco", "exscript" ]
pexpect multithread program hangs when spawning a shell
38,984,177
<p>I have a multi-threaded program. When the program is running, some of the threads hang sometimes during the call to pexpect.spawn(). </p> <p>This program creates a Session object in each thread, and a Session object spawns a pexpect session when it is created. In the program, each Session object is binding to one s...
1
2016-08-16T20:46:01Z
38,984,282
<p>Rather than using threads to spawn shells and pexpect to run ssh, just use <a href="http://www.paramiko.org/" rel="nofollow">Paramiko</a>. It's a very good, mature library which implements ssh without having to shell out. And you can run multiple sessions in a single thread which will probably be more efficient in...
0
2016-08-16T20:52:44Z
[ "python", "multithreading", "fork", "pexpect" ]
pexpect multithread program hangs when spawning a shell
38,984,177
<p>I have a multi-threaded program. When the program is running, some of the threads hang sometimes during the call to pexpect.spawn(). </p> <p>This program creates a Session object in each thread, and a Session object spawns a pexpect session when it is created. In the program, each Session object is binding to one s...
1
2016-08-16T20:46:01Z
39,090,310
<p>The issue can be worked around by switching to multiprocessing. Mixing multithreading and fork is problematic.</p>
0
2016-08-22T23:43:27Z
[ "python", "multithreading", "fork", "pexpect" ]
Unpickle class instances by interating over a list
38,984,207
<p>I am trying to unpickle various class instances which are saved in separate .pkl files by iterating over a list containing all the class instances (each class instance appends itself to the appropriate list when instantiated).</p> <p>This <strong>works</strong>:</p> <pre><code># LOAD IN INGREDIENT INSTANCES for ea...
-2
2016-08-16T20:48:29Z
38,984,345
<p>The <code>NameError</code> you are getting is Python telling you that you are trying to use a variable that hasn't been defined yet.</p> <p>You aren't defining <code>SausageAubergineRagu</code> before you use it in this line:</p> <pre><code>globals()[SausageAubergineRagu] = pickle.load(f) </code></pre> <p>In your...
0
2016-08-16T20:56:41Z
[ "python", "class", "filenames", "pickle" ]
How to use gather in python 3.5.2
38,984,257
<p>I tried to learn how asnychron programming in python works and wrote a small tornado app which executues two asnyc loops with sleep commands. If I wait for both coroutines with two await commands, it behaves as expected (first loop, than the second loop is executed.) If I combine both coroutines with gather, nothing...
1
2016-08-16T20:51:26Z
39,048,127
<p><code>gather</code> uses the asyncio event loop. If you wish to mix asyncio with tornado, you need to install tornado's asyncio event loop:</p> <p>Add this to your imports:</p> <pre><code>from tornado.platform.asyncio import AsyncIOMainLoop </code></pre> <p>Remove this:</p> <pre><code>import tornado.platform.asy...
0
2016-08-19T21:48:15Z
[ "python", "async-await" ]
Write xml from list of path/values
38,984,272
<p>This is a follow-up to the previous question: <a href="http://stackoverflow.com/questions/38983126/write-xml-with-a-path-and-value">Write xml with a path and value</a>. I want to now add in two additional things: 1) Attributes and 2) Multiple items with a parent node. Here is the list of paths I have:</p> <pre><cod...
0
2016-08-16T20:52:25Z
38,984,918
<p>To build a XML tree from xpaths and values, I use RegEx and <code>lxml</code>:</p> <pre><code>import re from lxml import etree </code></pre> <p>The entries are:</p> <pre><code>entries = [ {'Path': 'Item/Info/Name', 'Value': 'Body HD'}, {'Path': 'Item/Info/Synopsis', 'Value': 'A great movie'}, {'Path'...
1
2016-08-16T21:40:43Z
[ "python", "xml", "xpath", "lxml" ]
Avoid altering user arguments by deepcopy in the __init__ method?
38,984,311
<p>I want to avoid that user arguments get changed after creating a new instance of an object and working with the object. Is it good practice here to immediately copy the critical arguments in the <strong>init</strong>() method or is there a better solution?</p> <p>Here is a specific example:</p> <pre><code>import c...
0
2016-08-16T20:54:38Z
38,985,108
<p>The author of Fluent Python - Luciano Ramalho - has examples in his book of coping in the <code>__init__.py</code> and I'd be incline to aggree with him.</p> <p>He doesn't use deep copy however, he just takes advantage that you can initialise a list with another. Saves you an <code>import</code>.</p> <pre><code>cl...
1
2016-08-16T21:55:42Z
[ "python" ]
Selenium Clicks but Doesn't Select
38,984,340
<p>I'm working on making an automated web scraper run on Khan Academy to make offline backups of questions using selenium and a python scraper (to come later). I'm currently working on getting it to answer questions (right or wrong doesn't matter) to proceed through exercises. Unfortunately, selenium's .click() functio...
1
2016-08-16T20:56:16Z
39,023,055
<p>After a trial and error process, I found that the actual click selection can be accomplished by pointing to the element with class "description"</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() # gets us to the SAT Math Exercise page driver...
0
2016-08-18T16:16:41Z
[ "python", "selenium" ]
Python fluent filter, map, etc
38,984,369
<p>I love python. However, one thing that bugs me a bit is that I don't know how to format functional activities in a fluid manner like a can in javascript.</p> <p>example (randomly created on the spot): Can you help me convert this to python in a fluent looking manner?</p> <pre><code>var even_set = [1,2,3,4,5] .filt...
1
2016-08-16T20:58:35Z
38,984,512
<p>The biggest dealbreaker to the code you wrote is that Python doesn't support multiline anonymous functions. The return value of <code>filter</code> or <code>map</code> is a list, so you can continue to chain them if you so desire. However, you'll either have to define the functions ahead of time, or use a lambda.</p...
1
2016-08-16T21:07:08Z
[ "python", "functional-programming", "fluent" ]
Python fluent filter, map, etc
38,984,369
<p>I love python. However, one thing that bugs me a bit is that I don't know how to format functional activities in a fluid manner like a can in javascript.</p> <p>example (randomly created on the spot): Can you help me convert this to python in a fluent looking manner?</p> <pre><code>var even_set = [1,2,3,4,5] .filt...
1
2016-08-16T20:58:35Z
38,984,604
<p>Arguments against doing this notwithstanding, here is a translation into Python of your JS code.</p> <pre class="lang-py prettyprint-override"><code>from __future__ import print_function from functools import reduce def print_and_return(x): print(x) return x def isodd(x): return x % 2 == 0 def add_to...
2
2016-08-16T21:15:04Z
[ "python", "functional-programming", "fluent" ]
Python fluent filter, map, etc
38,984,369
<p>I love python. However, one thing that bugs me a bit is that I don't know how to format functional activities in a fluid manner like a can in javascript.</p> <p>example (randomly created on the spot): Can you help me convert this to python in a fluent looking manner?</p> <pre><code>var even_set = [1,2,3,4,5] .filt...
1
2016-08-16T20:58:35Z
38,984,608
<p>Comprehensions are the fluent python way of handling filter/map operations.</p> <p>Your code would be something like:</p> <pre><code>def evenize(input_list): return [x for x in input_list if x % 2 == 0] </code></pre> <p>Comprehensions don't work well with side effects like console logging, so do that in a sep...
0
2016-08-16T21:15:22Z
[ "python", "functional-programming", "fluent" ]
Python fluent filter, map, etc
38,984,369
<p>I love python. However, one thing that bugs me a bit is that I don't know how to format functional activities in a fluid manner like a can in javascript.</p> <p>example (randomly created on the spot): Can you help me convert this to python in a fluent looking manner?</p> <pre><code>var even_set = [1,2,3,4,5] .filt...
1
2016-08-16T20:58:35Z
38,985,641
<p>Generators, iterators, and <code>itertools</code> give added powers to chaining and filtering actions. But rather than remember (or look up) rarely used things, I gravitate toward helper functions and comprehensions. </p> <p>For example in this case, take care of the logging with a helper function:</p> <pre><cod...
1
2016-08-16T22:49:46Z
[ "python", "functional-programming", "fluent" ]
Filter list of tuples for tuples that contain certain items python
38,984,419
<p>I have a list of tuples like so:</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p>I want to be ab...
0
2016-08-16T21:01:52Z
38,984,624
<p>Did you mean this</p> <pre><code>[i for i in a if all([j in i for j in filter_for])] </code></pre> <p>instead of your line?</p> <pre><code>[i for i in a if all(j in filter_for for j in a)] </code></pre>
0
2016-08-16T21:16:53Z
[ "python", "list", "tuples" ]
Filter list of tuples for tuples that contain certain items python
38,984,419
<p>I have a list of tuples like so:</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p>I want to be ab...
0
2016-08-16T21:01:52Z
38,984,702
<p>This code seems to work, it tests every list by dividing them in several lists of the same length as <code>filter_for</code></p> <p><strong>Edit</strong>: I tried to add some excluded patterns after your edit</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'...
-1
2016-08-16T21:22:24Z
[ "python", "list", "tuples" ]
Filter list of tuples for tuples that contain certain items python
38,984,419
<p>I have a list of tuples like so:</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p>I want to be ab...
0
2016-08-16T21:01:52Z
38,984,739
<p>If I understand your requirements correctly, this should return the expected results. Here we convert the lists to strings, and use <a href="https://docs.python.org/3/reference/expressions.html#membership-test-details" rel="nofollow"><code>in</code></a> to check for membership.</p> <pre><code>&gt;&gt;&gt; a = [('1'...
2
2016-08-16T21:26:09Z
[ "python", "list", "tuples" ]
Filter list of tuples for tuples that contain certain items python
38,984,419
<p>I have a list of tuples like so:</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p>I want to be ab...
0
2016-08-16T21:01:52Z
38,984,803
<p>I'm not sure If I get the point what you're trying. But I would do it as following:</p> <pre><code>&gt;&gt;&gt;[i for i in a if "".join(filter_for) in "".join(i)] [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w')] </code></pre>
2
2016-08-16T21:30:32Z
[ "python", "list", "tuples" ]
How to verify that at least one of several fields in a model are not blank
38,984,465
<p>I have a model:</p> <pre><code>class Artwork(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) image_file = models.ImageField(upload_to='portfolios/image/%Y/%m', null=True, blank=True) video_file = models.FileField(upload_to='portfolios/vide...
1
2016-08-16T21:04:27Z
38,984,646
<p>You need to overwrite the form's <code>clean</code> method and assign an error message to a field. Here's an example where all three fields get an error message if they are all blank, adapted from the <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-...
2
2016-08-16T21:18:21Z
[ "python", "django", "forms" ]
How to specify postgres table columns as variables in python?
38,984,495
<p>So I have a table that is being updated with new columns every time a new instance of a class is being instantiated. Here's my code doing that.</p> <pre><code>query = "alter table test add column %s integer" rows = (str(Driver.count), str(Driver.count+1)) for c in rows: cur.execute(query, (AsIs(c),)) conn.commi...
2
2016-08-16T21:06:19Z
38,984,537
<pre><code>cur.execute('INSERT INTO test ("%d", "%d") VALUES (%d, %d)' % (Driver.count, Driver.count+1, currentRow, currentCol)) </code></pre> <p>Or using newer syntax:</p> <pre><code>cur.execute('INSERT INTO test ("{}", "{}") VALUES ({}, {})'.format( Driver.count, Driver.count+1, currentRow, currentCol)) </c...
2
2016-08-16T21:08:58Z
[ "python", "postgresql", "class" ]
Create property with no implemented setter
38,984,508
<pre><code>class Human: def __init__(self) -&gt; None: self.name = None # type: str def introduce(self): print("I'm " + self.name) class Alice(Human): def __init__(self) -&gt; None: super().__init__() self.name = "Alice" class Bob(Human): def __init__(self, rude: bo...
0
2016-08-16T21:06:59Z
38,984,574
<p>If you're certain that your subclasses will assign <code>name</code>, then you can leave out the assignment in the parent constructor. Right now, <code>Human</code> is attempting to set to <code>name</code>, when there is no setter. If you removed it from the <code>Human</code> constructor, then <code>Human</code> c...
1
2016-08-16T21:11:53Z
[ "python", "python-3.x" ]
Create property with no implemented setter
38,984,508
<pre><code>class Human: def __init__(self) -&gt; None: self.name = None # type: str def introduce(self): print("I'm " + self.name) class Alice(Human): def __init__(self) -&gt; None: super().__init__() self.name = "Alice" class Bob(Human): def __init__(self, rude: bo...
0
2016-08-16T21:06:59Z
38,984,808
<p>For class <code>Bob</code>I would have used something like this in this case:</p> <pre><code>@name.setter def name(self, name: str): self._name = name </code></pre> <p>Afterwards you can do whatever you want in the more complex getter with the internal value. Or did I get the question wrong?</p> <p>Executing ...
1
2016-08-16T21:30:51Z
[ "python", "python-3.x" ]
Create property with no implemented setter
38,984,508
<pre><code>class Human: def __init__(self) -&gt; None: self.name = None # type: str def introduce(self): print("I'm " + self.name) class Alice(Human): def __init__(self) -&gt; None: super().__init__() self.name = "Alice" class Bob(Human): def __init__(self, rude: bo...
0
2016-08-16T21:06:59Z
38,984,848
<p>why not make a dummy setter</p> <pre><code>@name.setter def name(self, value): pass </code></pre> <p>When <code>self.name = None</code> is executed it will call this setter and actually do nothing</p>
2
2016-08-16T21:35:12Z
[ "python", "python-3.x" ]
Tkinter unintentional recursion with menu bar command...cause?
38,984,544
<p>I'm trying to make a Python GUI using <code>tkinter</code>, and I need a menu item that opens another copy of the main window. I tried to do the following code, and when I ran the program, it froze for a bit, then opened a large number of windows. The last error message printed is below.</p> <p>I have two questio...
2
2016-08-16T21:09:27Z
38,984,706
<p>The problem is in this line:</p> <pre><code> file.add_command(label = 'New', command = doathing()) </code></pre> <p>Here, you <em>execute</em> the <code>doathing</code> callback and then try to bind its result (which is <code>None</code>) to the command. In this specific case, this also leads to an infinite rec...
2
2016-08-16T21:22:38Z
[ "python", "recursion", "tkinter" ]
How to run createsuperuser from PyDev Django shell
38,984,559
<p>I can't figure out how to do <code>python manage.py createsuperuser</code> in my PyDev Django shell.</p> <p>I was hoping something below would work, but nothing did. I've never really used these shells before, and hope there's a way to create this superuser with a shell.</p> <pre><code>import manage python manage....
0
2016-08-16T21:10:43Z
38,984,728
<pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") from django.core.management import execute_from_command_line execute_from_command_line(["manage.py","createsuperuser"]) </code></pre>
1
2016-08-16T21:24:58Z
[ "python", "django" ]
How to run createsuperuser from PyDev Django shell
38,984,559
<p>I can't figure out how to do <code>python manage.py createsuperuser</code> in my PyDev Django shell.</p> <p>I was hoping something below would work, but nothing did. I've never really used these shells before, and hope there's a way to create this superuser with a shell.</p> <pre><code>import manage python manage....
0
2016-08-16T21:10:43Z
38,984,761
<p>Based on the error information "loading MySQLdb module: No module named 'MySQLdb'", you need to install <a href="https://pypi.python.org/pypi/MySQL-python/1.2.5" rel="nofollow">MySQL-python</a></p>
1
2016-08-16T21:27:38Z
[ "python", "django" ]
Concatenating Strings: str + str or "{:s}{:s}".format()?
38,984,644
<p>Is there any difference between </p> <pre><code>str_ = "foo" + "bar" </code></pre> <p>and </p> <pre><code>str_ = "{:s}{:s}".format("foo","bar") </code></pre> <p>or is it simply preference?</p>
-1
2016-08-16T21:18:20Z
38,984,805
<p><em>Semantically?</em> No, both end up joining <code>"foo"</code> and <code>"bar"</code> and assigning them to <code>str</code>.</p> <p><em>Computationally?</em> Surely, Python will create the literal for <code>"foobar"</code> during compilation, the <code>str = "foo" + "bar"</code> assignment will be faster.</p> ...
2
2016-08-16T21:30:39Z
[ "python", "string", "python-3.x" ]
Concatenating Strings: str + str or "{:s}{:s}".format()?
38,984,644
<p>Is there any difference between </p> <pre><code>str_ = "foo" + "bar" </code></pre> <p>and </p> <pre><code>str_ = "{:s}{:s}".format("foo","bar") </code></pre> <p>or is it simply preference?</p>
-1
2016-08-16T21:18:20Z
38,984,943
<p>To complete @Jim explanation, here's a little benchmark showing a comparison between both methods:</p> <pre><code># measure execution time import timeit def f1(num_iterations): for i in range(num_iterations): value = "foo" + "bar" def f2(num_iterations): for i in range(num_iterations): val...
1
2016-08-16T21:42:57Z
[ "python", "string", "python-3.x" ]
Concatenating Strings: str + str or "{:s}{:s}".format()?
38,984,644
<p>Is there any difference between </p> <pre><code>str_ = "foo" + "bar" </code></pre> <p>and </p> <pre><code>str_ = "{:s}{:s}".format("foo","bar") </code></pre> <p>or is it simply preference?</p>
-1
2016-08-16T21:18:20Z
38,985,024
<p>Regards Jim answer, using <code>+</code> operator with many strings, can be slow. </p> <p>Avoid doing something like this:</p> <pre><code>s = ' ' for p in parts: s += p </code></pre> <p>each <code>+=</code> operation create a new string. To avoid that, use <code>join()</code>.</p> <pre><code>' '.join(parts) ...
0
2016-08-16T21:49:52Z
[ "python", "string", "python-3.x" ]
Concatenating Strings: str + str or "{:s}{:s}".format()?
38,984,644
<p>Is there any difference between </p> <pre><code>str_ = "foo" + "bar" </code></pre> <p>and </p> <pre><code>str_ = "{:s}{:s}".format("foo","bar") </code></pre> <p>or is it simply preference?</p>
-1
2016-08-16T21:18:20Z
38,985,144
<p>If you want to see the actual difference:</p> <pre><code>import dis def concat(): return 'foo' + 'bar' def format(): return '{}{}'.format('foo', 'bar') dis.dis(concat) print('*'*80) dis.dis(format) </code></pre>
2
2016-08-16T21:58:57Z
[ "python", "string", "python-3.x" ]
Lookahead to get values within quotes
38,984,648
<p>Without doing a python <code>split</code>, what would be the regex to get the following:</p> <pre><code>s = '[@Country="US"][@Language="ES"]' ["US", "ES"] </code></pre> <p>The current one I am using doesn't stop before the second quotation and bracket, <code>"]</code>:</p> <pre><code>re.findall(r'=\"(.+)?\"\]', ...
0
2016-08-16T21:18:30Z
38,984,668
<p>You just need a negated character class:</p> <pre><code>="([^"]+)" </code></pre> <p>See the <a href="https://regex101.com/r/rA3jC4/2" rel="nofollow">regex demo</a></p> <p><strong>Details</strong>:</p> <ul> <li><code>="</code> - a literal <code>="</code> text</li> <li><code>([^"]+)</code> - Group 1 (this will be...
2
2016-08-16T21:19:58Z
[ "python", "regex" ]
Lookahead to get values within quotes
38,984,648
<p>Without doing a python <code>split</code>, what would be the regex to get the following:</p> <pre><code>s = '[@Country="US"][@Language="ES"]' ["US", "ES"] </code></pre> <p>The current one I am using doesn't stop before the second quotation and bracket, <code>"]</code>:</p> <pre><code>re.findall(r'=\"(.+)?\"\]', ...
0
2016-08-16T21:18:30Z
38,984,671
<p>Regular expressions are greedy: means that the regex matches the biggest string possible matching your regex since you accept any character before the closing bracket. If you accept any character BUT the closing bracket it works as you wanted.</p> <pre><code>re.findall(r'=\"([^\]]+)?\"\]', s) </code></pre> <p>or a...
1
2016-08-16T21:20:04Z
[ "python", "regex" ]
Lookahead to get values within quotes
38,984,648
<p>Without doing a python <code>split</code>, what would be the regex to get the following:</p> <pre><code>s = '[@Country="US"][@Language="ES"]' ["US", "ES"] </code></pre> <p>The current one I am using doesn't stop before the second quotation and bracket, <code>"]</code>:</p> <pre><code>re.findall(r'=\"(.+)?\"\]', ...
0
2016-08-16T21:18:30Z
38,984,696
<p>Your regex was almost right, try this one:</p> <pre><code>re.findall(r'=\"(.+?)\"\]', s) </code></pre> <p>? Should be inside the parenthesis</p>
1
2016-08-16T21:22:12Z
[ "python", "regex" ]
Lookahead to get values within quotes
38,984,648
<p>Without doing a python <code>split</code>, what would be the regex to get the following:</p> <pre><code>s = '[@Country="US"][@Language="ES"]' ["US", "ES"] </code></pre> <p>The current one I am using doesn't stop before the second quotation and bracket, <code>"]</code>:</p> <pre><code>re.findall(r'=\"(.+)?\"\]', ...
0
2016-08-16T21:18:30Z
38,984,810
<p>I would go with Wiktor's solution too. If you have a consistent pattern where the groups will always be enclosed in " " then something like this should do well.</p> <pre><code>import re output = [] s = '[@Country="US"][@Language="ES"]' regex = r'"([^"]+)"' value = re.findall(regex, s) output.append(value) prin...
0
2016-08-16T21:31:04Z
[ "python", "regex" ]
Car class program not displaying updated speed
38,984,679
<p>I do not understand what is wrong. Here is my code:</p> <pre><code>class CarClass(object): def __init__(self,year_model,make): self.__year_model=year_model self.__make=make self.__speed=0 def accelerate(self): self.__speed+=5 def brake(self): self.__speed-=5 ...
0
2016-08-16T21:20:30Z
38,984,770
<p>when you type <code>car1.get_speed()</code> in a python interpreter, you get the returned value all right, but when you are running a program, you need to print it explicitly like this for instance:</p> <pre><code>print('The current speeed is:'+str(car1.get_sp‌​eed())) </code></pre> <p>(otherwise all methods r...
1
2016-08-16T21:28:13Z
[ "python", "class" ]
Car class program not displaying updated speed
38,984,679
<p>I do not understand what is wrong. Here is my code:</p> <pre><code>class CarClass(object): def __init__(self,year_model,make): self.__year_model=year_model self.__make=make self.__speed=0 def accelerate(self): self.__speed+=5 def brake(self): self.__speed-=5 ...
0
2016-08-16T21:20:30Z
38,984,823
<p>Here's a working example of your code:</p> <pre><code>class CarClass(object): def __init__(self, year_model, make): self.__year_model = year_model self.__make = make self.__speed = 0 def accelerate(self): self.__speed += 5 def brake(self): self.__speed -= 5 ...
1
2016-08-16T21:32:15Z
[ "python", "class" ]
Not writing to log file when using pywinauto
38,984,783
<p>I am trying to automate some Windows action using <a href="https://pywinauto.github.io/" rel="nofollow">pywinauto</a>, but when I <code>import pywinauto</code>, logging to the log file stops working.</p> <p>Before importing - the code is writing the log the file, as in the following example:</p> <pre><code>import ...
1
2016-08-16T21:29:16Z
38,984,784
<p>Turns out that <code>pywinauto</code> has its own usage of <code>logging</code> module.</p> <p>In <a href="https://github.com/pywinauto/pywinauto/blob/master/pywinauto/actionlogger.py#L88" rel="nofollow"><code>pywinauto/actionlogger.py</code></a>, the codes sets the logging level to <code>WARNING</code>, which disa...
2
2016-08-16T21:29:16Z
[ "python", "logging", "pywinauto", "pywin" ]
NetMQ Extended Request-Reply using c# and python
38,984,895
<p>I am able to have c# (client) and python (server) talk to each other by using a simple request-reply. However, I want my web application built on c# asp.net to be stable and need more clients and servers, so I tried connecting c# and python using the Extended REQ-REP connection.</p> <p>But when I run the code below...
0
2016-08-16T21:39:06Z
38,993,188
<p>You are not sending the all message frames with the correct flags.</p> <p>You can try and user Proxy of netmq that does exactly that. If you still want to write it by hand take a look how the proxy do it with the correct frames flags here:</p> <p><a href="https://github.com/zeromq/netmq/blob/master/src/NetMQ/Proxy...
0
2016-08-17T09:46:28Z
[ "c#", "python", "asp.net", "message-queue", "netmq" ]
skipping consecutive alerts
38,984,936
<p>I'm trying to formulate a logic for the following table</p> <pre><code>Hour|Alert_Flag --------------- 6 |0 7 |1 8 |1 9 |1 10 |0 11 |1 where Alert_Flag=1 means raise an alert and Alert_Flag=0 means no alert raised </code></pre> <p>What i want to accomplish here is to raise an alert at 7 since the Al...
0
2016-08-16T21:42:22Z
38,985,048
<p>Here's some clues to solve it yourself:</p> <pre><code>alerts = [(6, 0), (7, 1), (8, 1), (9, 1), (10, 0), (11, 1)] clock_state = 1 for item in alerts: hour, alert_flag = item if alert_flag != clock_state: print "Clock not ringing at {0}".format(hour) else: print "Clock ringing at {0}"....
2
2016-08-16T21:51:09Z
[ "python", "skip" ]
skipping consecutive alerts
38,984,936
<p>I'm trying to formulate a logic for the following table</p> <pre><code>Hour|Alert_Flag --------------- 6 |0 7 |1 8 |1 9 |1 10 |0 11 |1 where Alert_Flag=1 means raise an alert and Alert_Flag=0 means no alert raised </code></pre> <p>What i want to accomplish here is to raise an alert at 7 since the Al...
0
2016-08-16T21:42:22Z
38,985,052
<p>Assuming your alert flags are in a list:</p> <pre><code>for i in range(len(alert_flags)-1): if alert_flags[i] == 0 and alert_flags[i+1] == 1: # code to raise an alert </code></pre>
2
2016-08-16T21:51:46Z
[ "python", "skip" ]
skipping consecutive alerts
38,984,936
<p>I'm trying to formulate a logic for the following table</p> <pre><code>Hour|Alert_Flag --------------- 6 |0 7 |1 8 |1 9 |1 10 |0 11 |1 where Alert_Flag=1 means raise an alert and Alert_Flag=0 means no alert raised </code></pre> <p>What i want to accomplish here is to raise an alert at 7 since the Al...
0
2016-08-16T21:42:22Z
38,985,178
<pre><code>from collections import OrderedDict hour_alerts = OrderedDict([ ("6", 0), ("7", 1), ("8", 1), ("9", 1), ("10", 0), ("11", 1) ]) raiseAlert = 0 for each in hour_alerts.keys(): if hour_alerts[each]== 0: raiseAlert = 1 elif (hour_alerts[each] and raiseAlert): p...
0
2016-08-16T22:01:12Z
[ "python", "skip" ]
skipping consecutive alerts
38,984,936
<p>I'm trying to formulate a logic for the following table</p> <pre><code>Hour|Alert_Flag --------------- 6 |0 7 |1 8 |1 9 |1 10 |0 11 |1 where Alert_Flag=1 means raise an alert and Alert_Flag=0 means no alert raised </code></pre> <p>What i want to accomplish here is to raise an alert at 7 since the Al...
0
2016-08-16T21:42:22Z
38,985,471
<p>All you need to do is store a state of the previous alert, below is a quick example to show that, alerts only when the alert flag is set and previous seen alert flag was not set.</p> <pre><code>for i,n in enumerate(alerts): if n == 1 and (i==0 or alerts[i-1] == 0): print "Alert on",i </code></pre>
1
2016-08-16T22:28:05Z
[ "python", "skip" ]
Parsing a string and converting a date using Python
38,984,996
<p>I am trying to parse this "For The Year Ending December 31, 2015" and convert it to 2015-12-31 using the datetime lib. How would I go about partitioning and then converting the date? My program is looking through an excel file with multiple sheets and combining them into one; however, there is need now to add a date...
-1
2016-08-16T21:47:08Z
38,985,098
<pre><code>from datetime import datetime date_string = 'For The Year Ending December 31, 2015' date_string_format = 'For The Year Ending %B %d, %Y' date_print_class = datetime.strptime(date_string, date_string_format) wanted_date = datetime.strftime(date_print_class, '%Y-%m-%d') print(wanted_date) </code></pre>
2
2016-08-16T21:55:07Z
[ "python", "parsing", "datetime" ]
Parsing a string and converting a date using Python
38,984,996
<p>I am trying to parse this "For The Year Ending December 31, 2015" and convert it to 2015-12-31 using the datetime lib. How would I go about partitioning and then converting the date? My program is looking through an excel file with multiple sheets and combining them into one; however, there is need now to add a date...
-1
2016-08-16T21:47:08Z
38,985,120
<p>Simply include the hard-coded portion and then use the proper identifiers:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; s = "For The Year Ending December 31, 2015" &gt;&gt;&gt; d = datetime.datetime.strptime(s, 'For The Year Ending %B %d, %Y') &gt;&gt;&gt; result = datetime.datetime.strftime(d, '%Y-%m-%...
3
2016-08-16T21:56:59Z
[ "python", "parsing", "datetime" ]
How to append a tuple to a numpy array without it being preformed element-wise?
38,985,011
<p>If I try </p> <p><code>x = np.append(x, (2,3))</code></p> <p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p> <p><code>x = np.array([], dtype = tuple)</code> </p> <p...
1
2016-08-16T21:48:05Z
38,985,058
<p>If I understand what you mean, you can use <code>vstack</code>:</p> <pre><code>&gt;&gt;&gt; a = np.array([(1,2),(3,4)]) &gt;&gt;&gt; a = np.vstack((a, (4,5))) &gt;&gt;&gt; a array([[1, 2], [3, 4], [4, 5]]) </code></pre>
0
2016-08-16T21:52:05Z
[ "python", "arrays", "numpy" ]
How to append a tuple to a numpy array without it being preformed element-wise?
38,985,011
<p>If I try </p> <p><code>x = np.append(x, (2,3))</code></p> <p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p> <p><code>x = np.array([], dtype = tuple)</code> </p> <p...
1
2016-08-16T21:48:05Z
38,985,136
<p>You need to supply the shape to numpy dtype, like so:</p> <pre><code>x = np.dtype((np.int32, (1,2))) x = np.append(x,(2,3)) </code></pre> <p>Outputs</p> <pre><code>array([dtype(('&lt;i4', (2, 3))), 1, 2], dtype=object) </code></pre> <p>[Reference][1]<a href="http://docs.scipy.org/doc/numpy/reference/arrays.dtyp...
1
2016-08-16T21:58:19Z
[ "python", "arrays", "numpy" ]
How to append a tuple to a numpy array without it being preformed element-wise?
38,985,011
<p>If I try </p> <p><code>x = np.append(x, (2,3))</code></p> <p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p> <p><code>x = np.array([], dtype = tuple)</code> </p> <p...
1
2016-08-16T21:48:05Z
38,985,245
<p>I agree with @user2357112 comment:</p> <blockquote> <p>appending to NumPy arrays is catastrophically slower than appending to ordinary lists. It's an operation that they are not at all designed for</p> </blockquote> <p>Here's a little benchmark:</p> <pre><code># measure execution time import timeit import numpy...
2
2016-08-16T22:07:10Z
[ "python", "arrays", "numpy" ]
How to append a tuple to a numpy array without it being preformed element-wise?
38,985,011
<p>If I try </p> <p><code>x = np.append(x, (2,3))</code></p> <p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p> <p><code>x = np.array([], dtype = tuple)</code> </p> <p...
1
2016-08-16T21:48:05Z
38,986,554
<p><code>np.append</code> is easy to use with a case like:</p> <pre><code>In [94]: np.append([1,2,3],4) Out[94]: array([1, 2, 3, 4]) </code></pre> <p>but its first example is harder to understand. It shows the same sort of flat concatenate that bothers you:</p> <pre><code>&gt;&gt;&gt; np.append([1, 2, 3], [[4, 5, 6...
0
2016-08-17T00:49:55Z
[ "python", "arrays", "numpy" ]
mpi4py only works under mpiexec
38,985,018
<p>I have set up <code>mpi4py</code> on a new server, and it isn't quite working. When I import <code>mpi4py.MPI</code>, it crashes. However, if I do the same thing under <code>mpiexec</code>, it works. On my other server and on my workstation, both techniques work fine. What am I missing on the new server?</p> <p>Her...
0
2016-08-16T21:48:57Z
39,024,769
<p>It turned out that <code>mpi4py</code> is not compatible with version 1.10.2 of OpenMPI. It works fine with version 1.6.5.</p> <pre><code>$ module load openmpi/gnu/1.6.5 $ python -c 'from mpi4py import MPI; print("OK")' OK </code></pre>
0
2016-08-18T18:03:25Z
[ "python", "mpi", "mpi4py" ]
Using class from another file in python package and conflicts in __init__()
38,985,042
<p>I'm writing a python package (python 3.6) and have the following directory structure:</p> <pre><code>package/ | __init__.py | fileA.py | fileB.py | tests/ | | __init__.py | | test_classA.py | | test_classB.py </code></pre> <h2>Setup</h2> <p>My files have the following contents:</p> <pre><code># package...
1
2016-08-16T21:50:52Z
38,985,422
<p>The problem is with <code>package/fileA.py</code>. It's both a part of <code>package</code> and calling the <code>__init__.py</code> file of <code>package</code> as it's imported - creating a circular dependency.</p> <p>Can you change <code>fileA.py</code> to look like this?</p> <pre><code># package/fileA.py from ...
2
2016-08-16T22:23:25Z
[ "python", "python-3.x", "import", "package" ]
Using class from another file in python package and conflicts in __init__()
38,985,042
<p>I'm writing a python package (python 3.6) and have the following directory structure:</p> <pre><code>package/ | __init__.py | fileA.py | fileB.py | tests/ | | __init__.py | | test_classA.py | | test_classB.py </code></pre> <h2>Setup</h2> <p>My files have the following contents:</p> <pre><code># package...
1
2016-08-16T21:50:52Z
38,985,526
<p>First of all, renaming your package to literary "package" really confuses this whole situation, but here's my take on it :D.<br> I don't think you are dealing with circular dependency, python just states that it cannot import <code>classB</code> from <code>package</code> and that is because there is no file named <c...
2
2016-08-16T22:34:25Z
[ "python", "python-3.x", "import", "package" ]
Pandas Groupby and Sum Only One Column
38,985,053
<p>So I have a dataframe, df1, that looks like the following:</p> <pre><code> A B C 1 foo 12 California 2 foo 22 California 3 bar 8 Rhode Island 4 bar 32 Rhode Island 5 baz 15 Ohio 6 baz 26 Ohio </code></pre> <p>I want to group by column A a...
1
2016-08-16T21:51:54Z
38,985,129
<p>The only way to do this would be to include C in your groupby (the groupby function can accept a list).</p> <p>Give this a try:</p> <pre><code>df.groupby(['A','C'])['B'].sum() </code></pre> <p>One other thing to note, if you need to work with df after the aggregation you can also use the as_index=False option to ...
1
2016-08-16T21:58:06Z
[ "python", "pandas" ]
Pandas Groupby and Sum Only One Column
38,985,053
<p>So I have a dataframe, df1, that looks like the following:</p> <pre><code> A B C 1 foo 12 California 2 foo 22 California 3 bar 8 Rhode Island 4 bar 32 Rhode Island 5 baz 15 Ohio 6 baz 26 Ohio </code></pre> <p>I want to group by column A a...
1
2016-08-16T21:51:54Z
38,985,197
<p>If you don't care what's in your column C and just want the <code>nth</code> value, you could just do this:</p> <pre><code>df.groupby('A').agg({'B' : 'sum', 'C' : lambda x: x.iloc[n]}) </code></pre>
0
2016-08-16T22:02:53Z
[ "python", "pandas" ]
Issue with base64 to binary conversion
38,985,112
<p>I have a base64 string and would like to write it to a file as a JPEG, using Python 3.</p> <pre><code>file = request.json['file'] prefix = 'data:' + file['filetype'] + ';base64,' full_base64 = prefix + file['base64'] # full_base64 = data:image/jpeg;base64,/9j/4AAQSkZJ.... # base 64 verified with http://codebeauti...
0
2016-08-16T21:56:19Z
38,985,584
<p>If you want to create a valid JPEG file that can be read by image viewers then you should not be prepending the data URI to the file. You still need to decode the base64 encoded image data though.</p> <pre><code>with open('uploads/' + str(uuid.uuid4()) + '.jpeg', 'wb') as f: f.write(b64decode(file['base64'])) <...
0
2016-08-16T22:40:59Z
[ "python", "image", "python-3.x", "base64" ]
tkinter Label updating but not correctly
38,985,226
<p>Using Python 3.5. I have a <code>tkinter</code> form. The user clicks a button to import many files into a <code>Listbox</code>. Another button loops thru the files and reads and extracts data from them.</p> <p>I have a <code>Label</code> on the form that indicates the status of the loop. The status, for the most p...
0
2016-08-16T22:05:28Z
38,998,662
<p>The only explanation I can think of is that you're stacking labels on top of each other in the same row and column, so when you add a long string that ends in "nce..." and later update the screen by adding a shorter label in the same grid cell, the trailing text of the longer label underneath is showing through.</p>...
0
2016-08-17T13:52:59Z
[ "python", "tkinter", "label" ]
tkinter Label updating but not correctly
38,985,226
<p>Using Python 3.5. I have a <code>tkinter</code> form. The user clicks a button to import many files into a <code>Listbox</code>. Another button loops thru the files and reads and extracts data from them.</p> <p>I have a <code>Label</code> on the form that indicates the status of the loop. The status, for the most p...
0
2016-08-16T22:05:28Z
39,007,684
<p>I think I can explain. Root.mainloop repeatedly calls root.update. Root.update executes tasks on the 'main' event queue. In brief, it only executes idletasks when the event queue is empty <em>after</em> checking for file events (on non-Windows), window-gui events, and timer events. Idletasks, which are not well ...
0
2016-08-17T23:22:03Z
[ "python", "tkinter", "label" ]
How to load table from SQLLite db file from PySpark?
38,985,350
<p>I am trying to load table from a SQLLite .db file stored at local disk. Is there any clean way to do this in PySpark?</p> <p>Currently, I am using a solution that works but not as elegant. First I read the table using pandas though sqlite3. One concern is that during the process schema information is not passed (ma...
2
2016-08-16T22:16:54Z
39,002,270
<p>So first thing, you would need is to startup pyspark with JDBC driver jar in path Download the sqllite jdbc driver and provide the jar path in below . <a href="https://bitbucket.org/xerial/sqlite-jdbc/downloads/sqlite-jdbc-3.8.6.jar" rel="nofollow">https://bitbucket.org/xerial/sqlite-jdbc/downloads/sqlite-jdbc-3.8.6...
0
2016-08-17T16:51:20Z
[ "python", "sqlite", "apache-spark", "pyspark", "data-science" ]
How to convert MySQL query result to JSON object?
38,985,363
<p>Goal is to migrate some crucial data from MySQL db to a NoSQL document based db. To make the process simpler, I assume it's best to first convert mysql query result to JSON object. Is this possible?</p>
0
2016-08-16T22:18:01Z
38,985,784
<p>Suppose your SQL query's result set <code>row</code>s contain 4 values each, you just need to give these fields names and create a dict to insert into your NoSQL databse.</p> <pre><code>fieldnames = ['field1', 'field2', 'field3', 'field4'] dict_row = dict(zip(fieldnames, row)) </code></pre>
0
2016-08-16T23:06:48Z
[ "python", "mysql", "json" ]
Why does gensim Doc2Vec give me different vectors for the same sentence?
38,985,470
<p>I am training on two identical sentences (documents) using from <code>gensim.models.doc2vec import Doc2Vec</code> and when checking out the vectors for each sentence they are completely different. Does the Neural Network have a different random initialisation per sentence?</p> <pre><code># imports from gensim.model...
1
2016-08-16T22:27:47Z
39,370,190
<p><strong>Yes</strong>, each sentence vector is initialized differently.</p> <p>In particular in the <a href="https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/models/doc2vec.py#L366" rel="nofollow"><code>reset_weights</code></a> method. The code initializing the sentence vectors randomly is this:</p> ...
1
2016-09-07T12:38:05Z
[ "python", "neural-network", "gensim" ]
How to count the minimum number of possible connected components given only negative information
38,985,598
<p><strong>Preface and setup:</strong> </p> <p>Consider the following iterative clustering procedure. A user is given a set of nodes. In each iteration of the clustering process, a user marks two nodes as either matching or not matching by placing either a positive or negative edge between the two nodes. A positive ed...
0
2016-08-16T22:43:21Z
38,985,860
<blockquote> <p>I'm wondering if there is a more elegant solution</p> </blockquote> <p>Collapse positively-connected components. If there is a negative self-loop, then it's unsatisfiable. Otherwise, find a minimal coloration of the resulting graph (which only has negative edges), and you got a solution.</p> <p>The ...
1
2016-08-16T23:13:52Z
[ "python", "algorithm", "graph", "networkx" ]
How to count the minimum number of possible connected components given only negative information
38,985,598
<p><strong>Preface and setup:</strong> </p> <p>Consider the following iterative clustering procedure. A user is given a set of nodes. In each iteration of the clustering process, a user marks two nodes as either matching or not matching by placing either a positive or negative edge between the two nodes. A positive ed...
0
2016-08-16T22:43:21Z
38,985,996
<p>Computing the minimum number of clusters in your problem is NP complete.</p> <p>One can reduce the <a href="https://en.wikipedia.org/wiki/Clique_cover" rel="nofollow">clique cover problem</a> to it: given a graph, let the nodes be vertices of the graph, and let there be a negative edge between two nodes if and only...
1
2016-08-16T23:30:07Z
[ "python", "algorithm", "graph", "networkx" ]
CM to INCH Converting Program Python
38,985,615
<p>Hello i am trying to make a converting program but i can't get it to work, I am going to convert multiply different things but i start with CM to INCH. I get error TypeError: unsupported operand type(s) for /: 'str' and 'float'. Here is some of the code:</p> <pre><code> print('Press the number of the one you want...
1
2016-08-16T22:45:41Z
38,985,699
<p>%s is the notation for formatting a string, %f should be used for floats. In newer versions of python however you should use {0}</p> <pre><code>print('There are {0}'.format(number / inch)) </code></pre> <p>Read <a href="https://www.python.org/dev/peps/pep-3101/" rel="nofollow" title="pep">PEP 3101</a> for more inf...
1
2016-08-16T22:55:53Z
[ "python" ]
CM to INCH Converting Program Python
38,985,615
<p>Hello i am trying to make a converting program but i can't get it to work, I am going to convert multiply different things but i start with CM to INCH. I get error TypeError: unsupported operand type(s) for /: 'str' and 'float'. Here is some of the code:</p> <pre><code> print('Press the number of the one you want...
1
2016-08-16T22:45:41Z
38,985,719
<p>The problem is that <code>number</code> is a string and you can't perform mathematical operations on it. What you'll need to do is convert it to an integer or a float using <code>int(number)</code> or <code>float(number)</code>. So you could do: <code>print("There are ℅f".format(float(number)/inch))</code></p>
0
2016-08-16T22:58:37Z
[ "python" ]
How to ignore timezone when using bson.json_util.loads in python?
38,985,657
<p>I'm dumping and loading bson to text files and my datetimes are having time zone info added to them. I do not want the time zone info added.</p> <pre><code>import bson, datetime d1 = datetime.datetime.now() d2 = bson.json_util.loads(bson.json_util.dumps(d1)) </code></pre> <p>Results in d1:</p> <pre><code>datetime...
0
2016-08-16T22:51:11Z
38,986,104
<p>Interesting. The <code>bson</code> source directly overwrites <code>object_hook</code> so you can't pass in a custom one.</p> <p>From the <a href="https://github.com/mongodb/mongo-python-driver/blob/master/bson/json_util.py" rel="nofollow">source here</a>: </p> <pre><code>def loads(s, *args, **kwargs): """Help...
0
2016-08-16T23:43:15Z
[ "python", "datetime", "timezone", "pymongo", "bson" ]
XPath expression not working in scrapy spider but it is scrapy shell
38,985,665
<p>I'm working on a small project to get my head around scrapy and I've come across a problem with my xpath.</p> <p>The xpath works in the scrapy shell and the equivalent in javascript but when I put it in the spider.py file it doesn't work. Do I need to change some of the xpath in the spider.py file?</p> <p>I run th...
0
2016-08-16T22:52:41Z
38,985,675
<p>You forgot to <em>return the item</em> from the <code>parse()</code> callback:</p> <pre><code>def parse(self, response): item = PhoneScraperItem() item['price'] = response.xpath('//div[@class="listing-content"]//meta[@itemprop="price"]/@content').extract() return item </code></pre>
0
2016-08-16T22:53:28Z
[ "python", "xpath", "web-scraping", "scrapy" ]
django override admin works locally not on production
38,985,674
<p>I have the following directory structure in my django 10 project:</p> <pre><code>/my-project/ # project dir +app1 +templates +admin base.html 404.html 500.html </code></pre> <p>My templates attribute looks like this in settings:</p> <pre><code>TEMPLATES = [ { ...
0
2016-08-16T22:53:15Z
38,988,239
<p>You must use absolute path in your settings to avoid issues. For example:</p> <pre><code>import os PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..', '..') # depending where your settings.py live ... 'DIRS': [ os.path.join(PROJECT_ROOT, 'templates'), ], </code></pre>
1
2016-08-17T04:42:12Z
[ "python", "django", "django-templates", "django-admin", "django-settings" ]
Rewriting datetime in mysql
38,985,691
<p>I'm having some trouble modifying a sql table that contains a date.</p> <p>This is the code I'm running:</p> <pre><code>import pymysql cnx=pymysql.connect(dbstuff) cursor=cnx.cursor() cursor.execute("SELECT * FROM devices ORDER BY ip_addr,Port ASC") results=cursor.fetchall() lst = [(i,)+line[1:] for i, line in enu...
0
2016-08-16T22:55:06Z
38,985,779
<p>Calling the <strong>str</strong> function of the datetime.datetime object will convert it to the string format required by SQL. It is currently trying to insert a python object. Simply wrap your object like this:</p> <pre><code>dt = str(my_datetime_object) </code></pre>
0
2016-08-16T23:05:49Z
[ "python", "mysql" ]
Error while deploying django app to heroku
38,985,695
<p>I am trying to deploy a django app to heroku through github. </p> <p>I am getting the following error ImportError: No module named settings.staging</p> <p>But I have the "staging.py" file under "settings" folder.</p> <p>My github code is on :<a href="https://github.com/PramathaMadhavankutty/we_are_social" ...
0
2016-08-16T22:55:33Z
38,985,742
<p>Just create an empty <code>__init__.py</code> file in your settings folder (you are missing it now). It will indicate that folder is a package and thus files from it can be imoprted</p>
2
2016-08-16T23:01:08Z
[ "python", "django", "heroku" ]
Imitating the "magic wand" photoshop tool in OpenCV
38,985,755
<p>I'm trying to isolate the sky region from a series of grayscale images in OpenCV. All of the images are fairly similar: the top of the image is always a sky region, and is always a bright, gray-white colour. I've attempted contour-based approaches, and written my own algorithm to extract the line of the horizon and ...
-2
2016-08-16T23:03:06Z
38,985,872
<p>I think what you're looking for is the <a href="http://docs.opencv.org/3.1.0/d8/d83/tutorial_py_grabcut.html#gsc.tab=0" rel="nofollow">grabcut algorithm</a></p>
2
2016-08-16T23:15:17Z
[ "python", "c++", "opencv", "image-processing", "photoshop" ]
How to register class instance count in two separate files?
38,985,796
<p>So I have a python class <code>Driver</code> which has a method <code>drive</code> which essentially runs a loop forever. I have it set up so that with every new instance of the class, a counter goes up. So if I make two separate instances of the class in 2 different files and run them one after the other, will the ...
0
2016-08-16T23:08:01Z
38,985,920
<p>If you are running the files on after another with the interpreter, then the counter will reset once you run the second file, since everything from the first file being run will have exited memory. If you need data to persist between running two different files, your best bet is to write it to an external file in th...
0
2016-08-16T23:21:35Z
[ "python", "class", "instance" ]
SQL iterate over distinct values of a column and build a data frame for each value
38,985,893
<p>I have a table that looks like the following:</p> <pre><code>|A|B|C|D| |---|---|---|---| |1|b1|c1|d1| |1|b2|c2|d2| |2|b3|c3|d3| |2|b4|c4|d4| </code></pre> <p>I would like to iterate over distinct values of A and build a pandas data frame out of the remaining columns and then use that table to do calculations. I t...
0
2016-08-16T23:17:23Z
38,986,164
<p>Is there a particular reason you don't want to do this whole operation in pandas itself? You could simply do it like so:</p> <pre><code>parent_df = pd.read_sql(c, "SELECT * from table") for name, group in parent_df.groupby('A'): print(name, group.head()) </code></pre> <p>Or</p> <pre><code>parent_df.set_index(...
1
2016-08-16T23:52:50Z
[ "python", "sql", "sqlite", "python-3.x", "pandas" ]
SQL iterate over distinct values of a column and build a data frame for each value
38,985,893
<p>I have a table that looks like the following:</p> <pre><code>|A|B|C|D| |---|---|---|---| |1|b1|c1|d1| |1|b2|c2|d2| |2|b3|c3|d3| |2|b4|c4|d4| </code></pre> <p>I would like to iterate over distinct values of A and build a pandas data frame out of the remaining columns and then use that table to do calculations. I t...
0
2016-08-16T23:17:23Z
38,986,224
<p>Put all the data you're interested in into a DataFrame (if it's not a huge dataset) then filter the dataset. </p> <pre><code>df = pd.DataFrame(c.execute("SELECT * FROM table").fetchall()) distict_a = df['A'].unique() for a in distinct_a: df_for_this_a = df.query[df.A == a] </code></pre>
1
2016-08-17T00:01:07Z
[ "python", "sql", "sqlite", "python-3.x", "pandas" ]
SQL iterate over distinct values of a column and build a data frame for each value
38,985,893
<p>I have a table that looks like the following:</p> <pre><code>|A|B|C|D| |---|---|---|---| |1|b1|c1|d1| |1|b2|c2|d2| |2|b3|c3|d3| |2|b4|c4|d4| </code></pre> <p>I would like to iterate over distinct values of A and build a pandas data frame out of the remaining columns and then use that table to do calculations. I t...
0
2016-08-16T23:17:23Z
38,987,371
<p>Consider using pandas's <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="nofollow">read_sql</a> (with parameterization in passing the cursor value) and iteratively save each dataframe to a dictionary where the reference key is the corresponding distinct value (dict route avoi...
1
2016-08-17T02:55:02Z
[ "python", "sql", "sqlite", "python-3.x", "pandas" ]
SQL iterate over distinct values of a column and build a data frame for each value
38,985,893
<p>I have a table that looks like the following:</p> <pre><code>|A|B|C|D| |---|---|---|---| |1|b1|c1|d1| |1|b2|c2|d2| |2|b3|c3|d3| |2|b4|c4|d4| </code></pre> <p>I would like to iterate over distinct values of A and build a pandas data frame out of the remaining columns and then use that table to do calculations. I t...
0
2016-08-16T23:17:23Z
39,028,112
<p>The end solution was to use <code>pandas.read_sql</code> with <code>chunksize</code></p> <p>I found <a href="http://stackoverflow.com/questions/18107953/how-to-create-a-large-pandas-dataframe-from-an-sql-query-without-running-out-of">this post</a> useful as well.</p> <pre><code>import sqlite3 import pandas as pd c...
0
2016-08-18T21:55:50Z
[ "python", "sql", "sqlite", "python-3.x", "pandas" ]
calculate different statistics for multi-dimensional numpy array
38,985,980
<p>There exists an <code>nd.array</code> referred to as <code>label1</code>, when printing it out, it has</p> <pre><code>[[0 0 0 ..., 0 0 0] [0 0 0 ..., 0 88 0] [0 0 0 ..., 0 0 0] ..., [0 0 1 ..., 0 0 0] [0 0 0 ..., 0 2 0] [0 0 0 ..., 0 0 0]] </code></pre> <p>Its shape is <code>(729,816)</code>. Are there any w...
1
2016-08-16T23:28:11Z
38,986,060
<ol> <li>To get the sorted unique values in your array, do <code>numpy.unique(label1)</code>.</li> <li>When called on a two-dimensional array, <code>numpy.where</code> returns two arrays which are the row and column coordinates of all matching entries. So, if <code>numpy.where</code> returns <code>(array([0]), array([1...
0
2016-08-16T23:37:39Z
[ "python", "numpy" ]
Creating a matrix of a certain size from a dictionary
38,986,074
<p>I am wanting to solve a systems of equations through linalg.solve(A, b) Solve a linear matrix equation, or system of linear scalar equations from scipy.org. Specifically, I have two dictionaries, dict1 and dict1, and I need to convert them to matrices in order to use the above script. </p> <pre><code> food = ['frui...
0
2016-08-16T23:39:13Z
38,986,463
<p>You can create a numpy array from the dictionary using list comprehensions:</p> <pre><code>import numpy as np A = np.array([[(consumptions[x]["daily"]*consumptions[y]["daily"], consumptions[x]["rarely"]*consumptions[y]["rarely"]) for y in food] for x in food]) ...
2
2016-08-17T00:36:30Z
[ "python", "python-2.7", "numpy", "dictionary", "matrix" ]
pip Error: bad interpreter: No such file or directory
38,986,075
<p>Here's a sample from my console:</p> <pre><code>Ryans-MacBook-Pro:~ Ryan$ pip -bash: /Library/Frameworks/Python.framework/Versions/3.5/bin/pip: /Library/Frameworks/Python.framework/Versions/3.5/bin/python: bad interpreter: No such file or directory </code></pre> <p>What does this error mean and how do I fix it? It...
0
2016-08-16T23:39:27Z
38,999,458
<p>You could try to execute pip via a python version you know works on your system.</p> <p>Something like:</p> <pre><code>/path/to/python /path/to/pip </code></pre> <p>You could use:</p> <pre><code>which python which pip </code></pre> <p>to find out the relevant paths.</p>
0
2016-08-17T14:28:43Z
[ "python", "bash", "install", "pip" ]
Why are the code colours different for every line in my Jupyter (Ubuntu)?
38,986,117
<p>I was using Jupyter in Windows and just switched to Ubuntu. I found the colour of the code is very weird in the firefox browser. E.g. it highlights the variables in every other line.</p> <p>I tried to solve this problem by <a href="http://github.com/dunovank/jupyter-themes/blob/master/README.md" rel="nofollow">inst...
1
2016-08-16T23:45:35Z
39,112,179
<p>I sometimes get this if I'm copying/pasting from a source that has a different indentation size than that of the jupyter notebook. In your screenshot it looks like a small indent size so this seems like the likely culprit. Try highlighting the full block of indented code and hitting <code>ctrl+[</code> then <code>ct...
0
2016-08-23T23:24:51Z
[ "python", "ubuntu", "ipython", "jupyter" ]
Rearrange text file based on matches in columns
38,986,202
<p>I am working with a data set:</p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre> <p>Usin...
0
2016-08-16T23:58:02Z
38,986,284
<p>As I understand it, you are matching on the first field and the file is sorted. In that case, try:</p> <pre><code>$ awk 'NR&gt;1{printf "%s%s",($1==last?" ":"\n"),$0}; NR==1{printf "%s",$0} {last=$1} END{print""}' file ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 G...
2
2016-08-17T00:08:45Z
[ "python", "unix", "awk" ]
Rearrange text file based on matches in columns
38,986,202
<p>I am working with a data set:</p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre> <p>Usin...
0
2016-08-16T23:58:02Z
38,986,768
<p>another <code>awk</code></p> <pre><code>$ awk '{a[$1]=a[$1]?a[$1] FS $0:$0} END{for(k in a) print a[k] | "sort" }' file | column -t ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P ...
1
2016-08-17T01:21:20Z
[ "python", "unix", "awk" ]
Rearrange text file based on matches in columns
38,986,202
<p>I am working with a data set:</p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre> <p>Usin...
0
2016-08-16T23:58:02Z
38,993,617
<p>This could be approached in Python as follows:</p> <pre><code>from itertools import groupby data = """ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0....
1
2016-08-17T10:06:31Z
[ "python", "unix", "awk" ]
How to extract time from string in python using pattern matching?
38,986,205
<p>An example of the python string is <code>'8:30 AM- 10:00 PM Subject: Math'</code>. In general, the string contains a start time, end time, and the subject I want to separate this string into 3 components: the start time, end time, and subject. For example <code>8:30 AM</code>, <code>10:00 PM</code>, and <code>Subjec...
0
2016-08-16T23:58:26Z
38,986,230
<p>You can use <a href="https://docs.python.org/3/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a> using a <em>positive lookbehind</em> to <code>AM</code> or <code>PM</code> having an optional <code>-</code> and a space character as a delimiter:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &g...
2
2016-08-17T00:01:55Z
[ "python", "regex" ]
Python 2.7 easy_install - the process cannot access the file because it is being used by another process error
38,986,217
<p>Using Python I am trying to install a library called <a href="https://code.google.com/archive/p/yappi/" rel="nofollow">yappi</a> through easy_install. However I am getting this error below on Windows 7 Command Shell:</p> <p><a href="http://i.stack.imgur.com/4oCpl.png" rel="nofollow"><img src="http://i.stack.imgur.c...
0
2016-08-17T00:00:03Z
39,050,639
<p>Try downloading the appropriate wheel from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#yappi" rel="nofollow">here</a>.</p> <p>Then use <code>pip install [package]</code>.</p>
1
2016-08-20T04:59:49Z
[ "python", "python-2.7", "easy-install", "yappi" ]
Django form DateTimeField initial value is blank
38,986,225
<p>I have a create form in which I'm submitting the field ['created_at'] as a hidden datetimefield. I'm importing from django.utils import timezone and have this working on another model. Does anyone have any insight into why the value is blank? Thanks for any help!</p> <p>form:</p> <pre><code>class CreateForm(ModelF...
0
2016-08-17T00:01:09Z
39,009,987
<p>Rather than continue banging my head on the wall with this, I opted to set the created_at time in the model rather than worry about it elsewhere. </p> <p>Set the attribute to have <code>(default=timezone.now)</code> and that cured my woes.</p>
0
2016-08-18T04:24:24Z
[ "python", "django-forms", "timezone", "hidden-field" ]
Spacy Pipeline?
38,986,235
<p>So lately I've been playing around with a WikiDump. I preprocessed it and trained it on Word2Vec + Gensim</p> <p>Does anyone know if there is only one script within Spacy that would generate tokenization, sentence recognition, part of speech tagging, lemmatization, dependency parsing, and named entity recognition a...
0
2016-08-17T00:02:35Z
39,058,506
<p>Spacy gives you all of that with just using <code>en_nlp = spacy.load('en'); doc=en_nlp(sentence)</code>. The <a href="https://spacy.io/docs/#getting-started" rel="nofollow">documentation</a> gives you details about how to access each of the elements.</p> <p>An example is given below:</p> <pre><code>In [1]: import...
3
2016-08-20T20:38:37Z
[ "python", "nlp", "spacy" ]
Running time for converting list to set in Python
38,986,244
<p>In Python, what are the running time and space complexities if a list is converted to a set?</p> <pre><code>Example: data = [1,2,3,4,5,5,5,5,6] # this turns list to set and overwrites the list data = set(data) print data # output will be (1,2,3,4,5,6) </code></pre>
0
2016-08-17T00:03:36Z
38,986,278
<p>You have to iterate through the entire list, which is O(n) time, and then insert each into a set, which is O(1) time. So the overall time complexity is O(n), where n is the length of the list.</p> <p>No other space other than the set being created or the list being used is needed.</p>
1
2016-08-17T00:08:03Z
[ "python", "list", "set", "runtime", "space" ]
Running time for converting list to set in Python
38,986,244
<p>In Python, what are the running time and space complexities if a list is converted to a set?</p> <pre><code>Example: data = [1,2,3,4,5,5,5,5,6] # this turns list to set and overwrites the list data = set(data) print data # output will be (1,2,3,4,5,6) </code></pre>
0
2016-08-17T00:03:36Z
38,986,289
<p>Converting a list to a set requires that every item in the list be visited once, O(n). Inserting an element into a set is O(1), so the overall time complexity would be O(n).</p> <p>Space required for the new set is less than or equal to the length of the list, so that is also O(n).</p> <p>Here's a good <a href="ht...
1
2016-08-17T00:09:32Z
[ "python", "list", "set", "runtime", "space" ]
How to access Pymongo nested document with variable
38,986,261
<p>I understand that in order to find a nested document that I am to use the dot notation, but I need what follows the dot be in variable form. I am doing the following:</p> <pre><code>collection.update_one( {'_id': md5_hash}, {'$addToSet' : { 'src_id': src...
1
2016-08-17T00:05:58Z
38,986,305
<p>You can just have a nested dictionary:</p> <pre><code>collection.update_one({'_id': md5_hash}, {'$addToSet': {'offset': {src_id: offset}}}) </code></pre> <p>Or, you can dynamically make the field via string formatting or concatenation:</p> <pre><code>collection.update_one({'_id': md5_hash},...
1
2016-08-17T00:11:19Z
[ "python", "mongodb", "nested", "pymongo" ]
Python NameError: name is not defined (related to having default input argument types)
38,986,341
<p>I have a problem with the fact that I am calling <code>len(myByteArray)</code> in the input arguments to a function I am declaring. I'd like that to be a default argument, but Python doesn't seem to like it. <code>myByteArray</code> is of type <code>bytearray</code>. See <a href="https://docs.python.org/3.1/library/...
1
2016-08-17T00:17:26Z
38,986,421
<p>At the time of passing the parameters, the parameters are not initialised</p> <pre><code>&gt;&gt;&gt; def a(b=1,c=b): ... print(c,b) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'b' is not defined </code></pre> <p>so you need to send len of myByteA...
1
2016-08-17T00:29:56Z
[ "python", "python-3.x", "arguments", "nameerror" ]
Python NameError: name is not defined (related to having default input argument types)
38,986,341
<p>I have a problem with the fact that I am calling <code>len(myByteArray)</code> in the input arguments to a function I am declaring. I'd like that to be a default argument, but Python doesn't seem to like it. <code>myByteArray</code> is of type <code>bytearray</code>. See <a href="https://docs.python.org/3.1/library/...
1
2016-08-17T00:17:26Z
38,986,430
<p>Python default arguments are evaluated when the function is defined. Rather, you want something like this:</p> <pre><code>def circularFind(myByteArray, searchVal, start=0, end=None): """ Return the first-encountered index in bytearray where searchVal is found, searching to the right, in incrementing-in...
1
2016-08-17T00:31:38Z
[ "python", "python-3.x", "arguments", "nameerror" ]
How would you use the ord function to get ord("a") as 0?
38,986,342
<p>For example, in python, when I type in <code>ord("a")</code> it returns <code>97</code> because it refers to the ascii list. I want <code>ord("a")</code> to return zero from a string that I created such as </p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" </code></pre> <p>so <code>ord("b")</co...
-1
2016-08-17T00:17:28Z
38,986,374
<p>Something like this should do the trick:</p> <pre><code>def my_ord(c): alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" return alphabet.index(c) </code></pre>
0
2016-08-17T00:22:35Z
[ "python" ]
How would you use the ord function to get ord("a") as 0?
38,986,342
<p>For example, in python, when I type in <code>ord("a")</code> it returns <code>97</code> because it refers to the ascii list. I want <code>ord("a")</code> to return zero from a string that I created such as </p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" </code></pre> <p>so <code>ord("b")</co...
-1
2016-08-17T00:17:28Z
38,986,375
<p>You can create a <code>dict</code> to map from characters to indices and then do lookups into that. This will avoid repeatedly searching the string as other answers are suggesting (which is <code>O(n)</code>) and instead give <code>O(1)</code> lookup time with respect to the alphabet:</p> <pre><code>my_ord_dict = {...
0
2016-08-17T00:22:36Z
[ "python" ]
How would you use the ord function to get ord("a") as 0?
38,986,342
<p>For example, in python, when I type in <code>ord("a")</code> it returns <code>97</code> because it refers to the ascii list. I want <code>ord("a")</code> to return zero from a string that I created such as </p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" </code></pre> <p>so <code>ord("b")</co...
-1
2016-08-17T00:17:28Z
38,986,376
<p>You don't.</p> <p>You're going about this the wrong way: you're making the mistake</p> <blockquote> <p>This existing thing doesn't meet my needs. I want to make it meet my needs!</p> </blockquote> <p>instead, the way to go about the problem is</p> <blockquote> <p>This existing thing doesn't meet my needs. I ...
2
2016-08-17T00:22:41Z
[ "python" ]
How would you use the ord function to get ord("a") as 0?
38,986,342
<p>For example, in python, when I type in <code>ord("a")</code> it returns <code>97</code> because it refers to the ascii list. I want <code>ord("a")</code> to return zero from a string that I created such as </p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" </code></pre> <p>so <code>ord("b")</co...
-1
2016-08-17T00:17:28Z
38,986,388
<p>If i've understood correctly, this is what you want:</p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" def crypt(c, key=97): return ord(c)-key def decrypt(c, key=97): return chr(c+key) dst = [crypt(c) for c in alphabet] src = [decrypt(c) for c in dst] print dst print ''.join(src) </co...
0
2016-08-17T00:25:14Z
[ "python" ]
Creating a hyperlink in Python
38,986,343
<p>I'm trying to create a hyper link in python that includes string and variables but i keep getting a syntax error, I think its probably because of quotations but I cant seen to figure it out. Thanks for the help.</p> <pre><code>'&lt;a href="http://maps.google.com/maps?z=12&amp;t=m&amp;q=loc:'str(p['latitude']+'+'+st...
-2
2016-08-17T00:17:58Z
38,986,385
<p>Assuming both Latitude and Longitude are Integers:</p> <pre><code>'&lt;a href="http://maps.google.com/maps?z=12&amp;t=m&amp;q=loc:'+str(p['latitude'])+'+'+str(p['longitude'])+'"&gt;Click Here&lt;/a&gt;' </code></pre> <p>Try This.</p> <p>Your mistake is that you are not concatenating the strings properly.</p>
0
2016-08-17T00:24:28Z
[ "python", "python-2.7" ]
Kind of pyramid numbers pattern exercise
38,986,344
<p>Can you help to simplify this code and make it more efficient? Mine seems like it's not the best version; what can I improve?</p> <pre><code> 1 232 34543 4567654 567898765 678901109876 </code></pre> <p>This is the code I made:</p> <pre><code>c = -1 for y in range(1, 7): print() print((6-y) ...
0
2016-08-17T00:18:26Z
38,986,563
<p>First of all, I'm guessing that you didn't really want to print that <strong>y</strong> value of 10; that you really wanted the base-10 reduction to 0. Note that you have an extra character in the pyramid base.</p> <p>Do <em>not</em> change the value of a loop parameter while you're inside the loop. Specifically,...
0
2016-08-17T00:50:47Z
[ "python", "design-patterns", "numbers" ]
Kind of pyramid numbers pattern exercise
38,986,344
<p>Can you help to simplify this code and make it more efficient? Mine seems like it's not the best version; what can I improve?</p> <pre><code> 1 232 34543 4567654 567898765 678901109876 </code></pre> <p>This is the code I made:</p> <pre><code>c = -1 for y in range(1, 7): print() print((6-y) ...
0
2016-08-17T00:18:26Z
38,986,584
<p>Here's my implementation.</p> <p><strong>Python 2</strong>:</p> <pre><code>def print_triangle(n): for row_num in xrange(1, n + 1): numbers = [str(num % 10) for num in xrange(row_num, 2 * row_num)] num_string = ''.join(numbers + list(reversed(numbers))[1:]) print '{}{}'.format(' ' * (n -...
0
2016-08-17T00:53:55Z
[ "python", "design-patterns", "numbers" ]
Building a server and client with xmlrpc in python
38,986,369
<p>I'm trying to build a client and a server using xmlrpc in python, I HAVE to use a class named FunctionWrapper which has a method and the client use it, the method's name is sendMessage_wrapper(self, message), and the server is declared in another class, I'm trying to register the method in the server but when i call...
0
2016-08-17T00:21:48Z
38,986,383
<p>Here are the constants in case you need it </p> <pre><code>#! /usr/bin/env python # -*- coding: utf-8 -*- #Nombres para etiquetas login local y remoto MY_PORT_NUMBER_TITLE = "Cual es mi puerto?" OTHER_PORT_NUMBER_TITLE = "Cual es el puerto de contacto?" OTHER_IP_NUMBER_TITLE = "Cual es la direccion ip de contacto?...
0
2016-08-17T00:23:38Z
[ "python", "xmlrpclib" ]