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
Python dictionary comparison
39,736,128
<p>Problem:<br> I am trying to implement distance vector routing protocol and I need to track distances of Nodes/Routers (A, B, C) and distances from their neighbors (1,2,3) and update the best path (source router to destination router) if one of the router learns about another best path from its neighbors by processin...
-4
2016-09-28T00:10:49Z
39,736,177
<p>This is not possible with dictionaries, but with sets it is. For example, </p> <pre><code>s = {'K':'L', 'L':'K', 'Q':'P'} p = {'K':'L', 'Q':'P'} # for python 3 k = s.values() &amp; p.values() # k is now {'L', 'P'} # for python 2 k = s.viewvalues() &amp; p.viewvalues() # is now {'L', 'P'} </code></pre> <p>Look at ...
0
2016-09-28T00:16:54Z
[ "python" ]
Load JSON object including escaped json string
39,736,140
<p>I'm trying to load a JSON object from a string (via Python). This object has a single key mapped to an array. The array includes a single value which is another serialized JSON object. I have tried a few online JSON parsers / validators, but can't seem to identify what the issue with loading this object is.</p> <p>...
0
2016-09-28T00:11:53Z
39,736,166
<p>If you try out your string in the REPL, you'll see pretty quickly why it doesn't work:</p> <pre><code>&gt;&gt;&gt; '{"parent":["{\"key\":\"value\"}"]}' '{"parent":["{"key":"value"}"]}' </code></pre> <p>Notice the <code>\</code> have gone away because python is treating them as escape sequences ...</p> <p>One easy...
0
2016-09-28T00:15:18Z
[ "python", "json" ]
Pandas Dataframe performance vs list performance
39,736,195
<p>I'm comparing two dataframes to determine if rows in df1 begin any row in df2. df1 is on the order of a thousand entries, df2 is in the millions.</p> <p>This does the job but is rather slow. </p> <pre><code>df1['name'].map(lambda x: any(df2['name'].str.startswith(x))) </code></pre> <p>When run on a subset of df1 ...
1
2016-09-28T00:19:51Z
39,744,808
<p><code>any()</code> will early return when it get a <code>True</code> value, thus the <code>startswith()</code> calls is less then the <code>Dataframe</code> version. </p> <p>Here is a method that use <code>searchsorted()</code>:</p> <pre><code>import random, string import pandas as pd import numpy as np def rando...
0
2016-09-28T10:25:27Z
[ "python", "pandas" ]
How to get alert from a diff output using python
39,736,205
<p>I am writing a python script to monitor changes in webpage. I have the diff command implemented in python and I have the diff output files in a folder. </p> <p>I have 260 diff output files. Logically i cannot check all 260 to know which file has changes. </p> <p>Is there a python solution to read all the diff file...
1
2016-09-28T00:21:27Z
39,736,381
<p>To check if two files have the same content you can use the <a href="https://docs.python.org/2/library/filecmp.html" rel="nofollow">filecmp</a> module:</p> <pre><code>&gt;&gt;&gt; import filecmp &gt;&gt;&gt; filecmp.cmp('a_file.txt', 'another_file.txt') True </code></pre> <p>So in your case where you have a lot of...
4
2016-09-28T00:48:49Z
[ "python", "diff" ]
How to set time zone in InfluxDB using python client
39,736,238
<p>I am using Python client for InfluxDb to write into Database as shown below. </p> <pre><code> import pytz tz = pytz.timezone('US/Pacific') client.write_points([{"measurement": system_id[1], "tags": tagdic, "time":ts, "fields": fielddic}]) </code></pre> <p>When i run any query in D.B i am getting time info...
0
2016-09-28T00:25:17Z
39,787,332
<p>You can't do that at the moment. There are a lot of github issues regarding that topic but they are not implemented yet. Here are some of them: <a href="https://github.com/influxdata/influxdb/issues/6541" rel="nofollow">Link1</a>, <a href="https://github.com/influxdata/influxdb/issues/2074" rel="nofollow">Link2</a> ...
1
2016-09-30T08:47:34Z
[ "python", "influxdb" ]
Regex add quotes in Python so I can return Python Dictionary
39,736,249
<p>Using Python and Regex, I would like to add quotes to each word. Currently, I am only able to add quotes to a first index. When I loop through my end results, I get a string. Instead, I would like Python Dictionary. To solve this problem, I think adding quotes will help me get dictionary instead of a string. Can som...
1
2016-09-28T00:27:06Z
39,736,570
<p>This looks like an <a href="http://xyproblem.info/" rel="nofollow">XY Problem</a>. Your end goal is to parse that textual data into Python dictionaries. Adding quotes is the way you've come up with to do that (presumably you're then planning to use <code>eval()</code> to parse it), but it's the long way around.</p> ...
1
2016-09-28T01:17:09Z
[ "python", "regex", "for-loop", "dictionary" ]
Regex add quotes in Python so I can return Python Dictionary
39,736,249
<p>Using Python and Regex, I would like to add quotes to each word. Currently, I am only able to add quotes to a first index. When I loop through my end results, I get a string. Instead, I would like Python Dictionary. To solve this problem, I think adding quotes will help me get dictionary instead of a string. Can som...
1
2016-09-28T00:27:06Z
39,736,588
<p>Here's a way to parse it using regular expressions. If you are matching each part so exactly as in your original, there's probably a more generic way.</p> <pre><code>import re raw = "[historic_list {id: 'A(long) 11A' startdate: 42521 numvaluelist: 0.1065599566767107 datelist: 42521}historic_list {id: 'A(short) 11B'...
1
2016-09-28T01:20:19Z
[ "python", "regex", "for-loop", "dictionary" ]
Cleaning up broken XML in Python
39,736,276
<p>A server I don't control sends broken XML with characters such as '>', '&amp;', '&lt;' etc. in attributes and text.</p> <p>A small sample:</p> <pre><code>&lt;StockFormula Description="" Name="F_ΔTURN" RankType="Higher" Scope="Universe" Weight="10.86%"&gt; &lt;Formula&gt;AstTurnTTM&gt;AstTurnPTM&lt;/Formula...
1
2016-09-28T00:32:32Z
39,736,494
<p>First, realize no XML parser can help you with "broken XML." XML parsers only operate over XML, which by definition must be <strong><a href="http://stackoverflow.com/a/25830482/290085">well-formed</a></strong>.</p> <p>Second, it is not possible to repair "broken XML" in the general case. There are no rules govern...
3
2016-09-28T01:06:18Z
[ "python", "xml", "lxml" ]
Have to display coins used in makeChange function?
39,736,280
<p>I am creating a makeChange function using a useIt or loseIt recursive call. I was able to determine the least amount of coins that's needed to create the amount; however, I am unsure as to how to display the actual coins used.</p> <pre><code>def change(amount,coins): '''takes the amount and makes it out of the ...
0
2016-09-28T00:33:15Z
39,736,596
<p>You want something like:</p> <pre><code>def change(amount, coins): ''' &gt;&gt;&gt; change(10, [1, 5, 25]) [5, 5] ''' if not coins or amount &lt;= 0: return [] else: return min((change(amount - coin, coins) + [coin] for coin in coins if amount &gt;= coin),...
0
2016-09-28T01:21:50Z
[ "python", "recursion", "dynamic-programming" ]
Have to display coins used in makeChange function?
39,736,280
<p>I am creating a makeChange function using a useIt or loseIt recursive call. I was able to determine the least amount of coins that's needed to create the amount; however, I am unsure as to how to display the actual coins used.</p> <pre><code>def change(amount,coins): '''takes the amount and makes it out of the ...
0
2016-09-28T00:33:15Z
39,737,314
<p>First of all the semantics of your names for the use-it-or-lose-it strategy are backwards. "Use it" means the element in question is being factored into your total result. "Lose it" means you're simply recursing on the rest of the list without considering the current element. So I'd start by switching those names ar...
0
2016-09-28T02:57:15Z
[ "python", "recursion", "dynamic-programming" ]
Issue with registered ec2 creation variable
39,736,288
<p>I have a playbook that creates an ec2 instance and from that creation I want to register the output as a var. From there I would use the registered var to create and attach an ebs volume. However I'm running into the following error. </p> <pre><code> - name: Create EC2 instance for zone A ec2: key_name: "{{ ...
0
2016-09-28T00:34:31Z
39,738,088
<p>Not sure how with_sequence would affect here, but I see atleast one basic problem here.</p> <p>When you register the output of ec2 task in a variable named "ec2", you can refer to instance_ids with the following -</p> <pre><code>ec2.results[0].instance_ids </code></pre> <p>Ansible task is complaining because ther...
1
2016-09-28T04:31:45Z
[ "python", "ansible", "ansible-playbook" ]
cannot accessing a simple database in django
39,736,293
<p>I went through the django doc polls example. Now I have a database <code>name.info.db</code> available. I put it in same directory as manage.py, also where db.sqlite3 is. I changed <code>settings.py</code> to</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path....
1
2016-09-28T00:35:10Z
39,738,384
<p>Read about <a href="https://docs.djangoproject.com/en/1.10/ref/models/options/#managed" rel="nofollow">managed option</a>. If You set it to <code>False</code>, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database vi...
0
2016-09-28T04:59:25Z
[ "python", "django", "database" ]
`manage.py runserver` and Ctrl+C (Django)
39,736,330
<p>When I quit Django <code>manage.py runserver</code> with Ctrl+C, do threads running HTTP request finish properly or are they interrupted in the middle?</p>
2
2016-09-28T00:40:47Z
39,741,069
<p><strong>TL;DR</strong> running HTTP requests are stopped when Ctrl+C is hit on the django dev server</p> <p>I thought your question is really interesting and investigated:</p> <p>I made a view that takes 10 seconds to execute and after that sends a response. To test for your behaviour I stopped the development-ser...
2
2016-09-28T07:42:37Z
[ "python", "django", "signals" ]
hash table , nonempty slot already contains the key ,the odd data value is replaced with the new data value
39,736,464
<p>I am learning hash table in python and one question occurs here.</p> <p>when hash function begins , I should generate a empty "map" hash the list.But why "nonempty slot already contains the key ,the odd data value is replaced with the new data value", isn't it should find the next empty slot and store there,why rep...
1
2016-09-28T01:00:14Z
39,749,215
<p>First, we need to differentiate between the <code>hash value</code>, <code>key</code> and <code>value</code>.</p> <p><code>Hash value</code> is the ID of the slot in the hash table and it is generated by the hash function.</p> <p><code>Key</code> is the data that you want to map from.</p> <p><code>value</code> is...
1
2016-09-28T13:38:35Z
[ "python", "data-structures", "hash", "hashmap", "hashtable" ]
Is it possible to overload the ~ operator on strings?
39,736,575
<pre><code>&gt;&gt;&gt; a = 55 &gt;&gt;&gt; b = "hello" &gt;&gt;&gt; ~a # this will work &gt;&gt;&gt; ~b # this will fail </code></pre> <p>No real surprise for the failure above, but suppose I wanted to overload ~ operator to work on strings. I'm fairly new to Python, so I did some digging on this and found a few ta...
3
2016-09-28T01:17:56Z
39,736,587
<p>No, this is not possible in Python. You can not add new methods to built-in types in a way that will work reliably.</p> <p>One thing you could do is subclass string, and define the magic method <code>__invert__</code>. But it would not work on string literals, only on instances of your subclass. </p>
1
2016-09-28T01:20:08Z
[ "python", "string", "overloading", "operator-keyword" ]
List appended in function doesn't work
39,736,716
<p>This is my class:</p> <pre><code>from Student import Student class Class: stulist=[] def __init__ (self, classname, numstudents): self.classname=classname self.numstudents=numstudents def addStudent(self, stuNum, stuName, stuGrades): Class.stulist.append(Student(stuName, stuGrade...
2
2016-09-28T01:40:38Z
39,736,758
<p>In your <code>Class</code> class, <code>self.stulist</code> instead of <code>Class.stulist</code>. </p> <p>You are modifying the class itself, not the instance variable.</p> <pre><code>class Class: stulist=[] def __init__ (self, classname, numstudents): self.classname=classname self.numstud...
0
2016-09-28T01:46:21Z
[ "python" ]
Python2.7(on Windows) Need to capture serial port output into log files during Python/Robot script run
39,736,740
<p>We are testing networking devices to which test interaction is done using serial ports. Python 2.7 with Windows is used to achieve this using the PySerial module of Python. The scripts are run using Robot framework.</p> <p>We observe that the Robot logs do not contain the serial device interaction dialogues. </p> ...
0
2016-09-28T01:43:45Z
39,766,125
<p>I may be incorrect but perhaps you want to capture data sent/received between computer and device through serial port. If this is true then serial port sniffer will be required. Linux and mac os x does not support sniffing however you may use sniffing for windows.</p>
0
2016-09-29T09:11:50Z
[ "python", "python-2.7", "testing", "automated-tests", "robotframework" ]
Installing pygame on ubuntu
39,736,745
<p>I am trying to install pygame on an Ubuntu 16.04 system. My default python is 2.7.12. I opened terminal and tried:</p> <pre><code>sudo apt-get install python-pygame </code></pre> <p>I got this message:</p> <pre><code>Reading package lists... Done Building dependency tree Reading state information... Done...
0
2016-09-28T01:44:17Z
39,781,796
<p>Figured it out. Found a terminal command to reinstall python:</p> <pre><code>sudo apt-get purge python &amp;&amp; sudo apt-get install python2.7 </code></pre>
0
2016-09-30T00:06:13Z
[ "python", "linux", "ubuntu", "numpy", "pygame" ]
In python, how to restore the function of os.chdir() if os.chdir = 'path' has been implemented
39,736,773
<p>In path setup, I wrongly wrote the code: os.chdir = '\some path', which turns the function os.chdir() into a string. Is there any quick way to restore the function without restarting the software? Thanks!</p>
2
2016-09-28T01:48:32Z
39,736,831
<p>Kicking <code>os</code> out of the modules cache can make it freshly importable again:</p> <pre><code>&gt;&gt;&gt; import sys, os &gt;&gt;&gt; os.chdir = "d'oh!" &gt;&gt;&gt; os.chdir() TypeError: 'str' object is not callable &gt;&gt;&gt; del sys.modules['os'] &gt;&gt;&gt; import os &gt;&gt;&gt; os.chdir &lt;functi...
2
2016-09-28T01:53:55Z
[ "python" ]
In python, how to restore the function of os.chdir() if os.chdir = 'path' has been implemented
39,736,773
<p>In path setup, I wrongly wrote the code: os.chdir = '\some path', which turns the function os.chdir() into a string. Is there any quick way to restore the function without restarting the software? Thanks!</p>
2
2016-09-28T01:48:32Z
39,736,839
<pre><code>&gt;&gt;&gt; import os </code></pre> <p>Assign to the <code>chdir</code> method a string value:</p> <pre><code>&gt;&gt;&gt; os.chdir = '\some path' &gt;&gt;&gt; os.chdir '\some path' </code></pre> <p>Use <code>reload</code> to, well, reload the module. <code>reload</code> will reload a <em>previously impo...
1
2016-09-28T01:55:44Z
[ "python" ]
Yum is not working anymore in scientific linux after python update
39,736,788
<p>Im using a scientific linux on a remote machine. I tried to install python 2.7 on it. After that the yum and some other python packages are not working (it says "no module named yum"). I searched it online and it seems I should not have touched the system python as it breaks some of the system tools. Is there a way ...
0
2016-09-28T01:49:30Z
39,917,999
<p>Once you get your system back to normal, add Python 2.7 as a Software Collection - it installs "along side" the original Python 2.6 rather than replace it so both are available without collision. Get 2.7 and others from softwarecollections.org.</p>
0
2016-10-07T13:03:51Z
[ "python", "linux", "redhat", "yum" ]
Can generatorizing a list improve Python performance?
39,736,863
<pre><code>def numbers(mi, ma): return [n for n in range(mi, ma + 1)] def gen(xs): return (x for x in xs) example = gen(numbers(10, 20)) </code></pre> <p>In this example, can <code>gen</code> improve iteration performance of <code>numbers</code>? Why (not)?</p> <pre><code>def numbersGen(mi, ma): return ...
0
2016-09-28T01:58:58Z
39,736,913
<p>In this particular case, <code>range</code> is already about as lazy as you can hope for. There's no reason to further wrap its output in layers of indirection. Of course, the usual caveats of Python generators vs. Haskell laziness apply; namely, iterating through multiple times, or continuing from a specific point ...
0
2016-09-28T02:05:12Z
[ "python", "performance", "python-3.x", "generator" ]
Use Python to calculate P**n while n approach +oo and P is a matrix
39,736,887
<p>The code is </p> <pre><code>import sympy as sm import numpy as np k=sm.Symbol('k') p=np.matrix([[1./2,1./4,1./4],[1./2,0,1./2],[1./4,0,3./4]]) sm.limit(p**k,k,sm.oo) </code></pre> <p>It indicates 'TypeError: exponent must be an integer'. But if I change the matrix to a constant like this <code>sm.limit(2**k,k...
2
2016-09-28T02:01:57Z
39,752,785
<p>Use SymPy matrices:</p> <pre><code>In [5]: p = sm.Matrix(p) </code></pre> <p>Then the exponent by a symbol will work:</p> <pre><code>In [6]: p**k Out[6]: ⎡ k k k k ...
1
2016-09-28T16:18:45Z
[ "python", "sympy" ]
chcp 65001 codepage results in program termination without any error
39,736,901
<p><strong>Problem</strong><br> The problem arises when I want to <strong>input</strong> Unicode character in Python interpreter (for simplicity I have used a-umlaut in the example, but I have first encountered this for Farsi characters). Whenever I use python with <code>chcp 65001</code> code page and then try to inpu...
3
2016-09-28T02:03:52Z
39,745,938
<p>To use Unicode in the Windows console for Python 2.7 and 3.x (prior to 3.6), install and enable <a href="https://pypi.python.org/pypi/win_unicode_console">win_unicode_console</a>. This uses the wide-character functions <a href="https://msdn.microsoft.com/en-us/library/ms684958"><code>ReadConsoleW</code></a> and <a h...
5
2016-09-28T11:17:58Z
[ "python", "windows", "unicode", "cmd", "codepages" ]
Python: range doesn't increase
39,736,960
<p>I have to write a program that shows a column of kilograms and a column of pounds, starting at 1 kilogram and ending 99, increasing every step with 2.</p> <p>I have the following code, and the range() works for the pounds part, but not for the kilograms part. It stays always 1 for the kilograms.</p> <pre><code>for...
-2
2016-09-28T02:10:54Z
39,736,991
<p>Because you use <code>break</code> with in a loop.</p> <p>In python you don't end a loop with anything but a decreased indentation. Remove your <code>break</code> statements and try again.</p> <p>The <code>break</code> statements ends the current loop unconditionally. For example,</p> <pre><code>s = 0 for i in ra...
1
2016-09-28T02:16:04Z
[ "python", "for-loop" ]
Python: range doesn't increase
39,736,960
<p>I have to write a program that shows a column of kilograms and a column of pounds, starting at 1 kilogram and ending 99, increasing every step with 2.</p> <p>I have the following code, and the range() works for the pounds part, but not for the kilograms part. It stays always 1 for the kilograms.</p> <pre><code>for...
-2
2016-09-28T02:10:54Z
39,737,028
<p>Try this</p> <pre><code>import numpy as np KG_TO_LBS = 2.20462 KG = np.arange(0,100,2.20462) print("Kilograms", "Pounds") for kg in KG: print(kg, kg/KG_TO_LBS) </code></pre> <p>you may have to change the printout to the format you like.</p>
0
2016-09-28T02:21:43Z
[ "python", "for-loop" ]
Python: range doesn't increase
39,736,960
<p>I have to write a program that shows a column of kilograms and a column of pounds, starting at 1 kilogram and ending 99, increasing every step with 2.</p> <p>I have the following code, and the range() works for the pounds part, but not for the kilograms part. It stays always 1 for the kilograms.</p> <pre><code>for...
-2
2016-09-28T02:10:54Z
39,737,101
<p>First off, remove the breaks, as those will prematurely end the loops iterations. Secondly, why are you using nested <code>for</code>loops?</p> <p>For what you described, nested loops are not even required. You simply need to use <strong>one</strong> <code>for</code>loop. Use <code>range()</code> <strong>once</stro...
1
2016-09-28T02:31:00Z
[ "python", "for-loop" ]
Need help posting first python program on github
39,736,999
<p>I have finally created my own program that works. I am trying to upload the code to github for my first portfolio submission. I added github desktop to my macbook to try to make it easy to upload the code, but I can't figure it out. All of my code ending in .py is unable to be added to github. Can anyone offer advic...
0
2016-09-28T02:17:33Z
39,737,254
<p>Can you share your <code>.gitignore</code> file?</p> <p>Or just try to push it with the command line interface (to learn the basics of the <code>git</code> commands, see <a href="https://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository" rel="nofollow">gitcsm site</a>, or follow github <a href="https://hel...
0
2016-09-28T02:48:37Z
[ "python", "github" ]
Replace all occurrences of 'pattern' in part of a string using Python regex
39,737,138
<p>I would like to replace all '&lt;' symbols that are in between apple and orange with '-'. </p> <pre><code>&gt;&gt;&gt; print re.sub(r'(apple.*)&lt;(.*orange)', r'\1-\2', r'apple &lt; &lt; orange') </code></pre> <blockquote> <p>apple &lt; - orange</p> </blockquote> <pre><code>&gt;&gt;&gt; print re.sub(r'(apple....
0
2016-09-28T02:35:30Z
39,737,253
<p>One invocation to <code>re.sub</code> only processes non-overlapping matches.</p> <p>One way around that is brute force:</p> <pre><code>&gt;&gt;&gt; s = 'apple &lt; &lt; orange' &gt;&gt;&gt; old = None &gt;&gt;&gt; while s != old: ... old = s ... s = re.sub(r'(apple.*)&lt;(.*orange)', r'\1-\2', s) ... &gt;&...
0
2016-09-28T02:48:37Z
[ "python", "regex" ]
Getting error using Tkinter in python on mac OS X
39,737,169
<p>I tried to run a nltk code for drawing parse trees. I got the error that tkinter module is not installed.</p> <p>These are the error messages I got:</p> <pre><code>1. UserWarning: nltk.draw package not loaded (please install Tkinter library). warnings.warn("nltk.draw package not loaded") 2. import _tkinter # I...
1
2016-09-28T02:38:40Z
39,755,391
<p>You should install ActivePython rather than ActiveTcl, and use it as your preferred Python. </p> <p>The problem is your Python install isn't picking up your Tcl install, and the simplest way to solve that is to install a Python version that is configured for Tk, which ActivePython is: <a href="http://www.activestat...
0
2016-09-28T18:45:49Z
[ "python", "osx", "python-2.7", "tkinter", "activetcl" ]
Python push files to Github remote repo without local working directory
39,737,192
<p>I am working on a Python based web application for collaborative xml/document editing, and one requirement from the client is that users should be able to push the files they created (and saved on the server) directly to a Github remote repo, without the need of ever creating a local clone on the server (i.e., no lo...
0
2016-09-28T02:41:53Z
39,770,084
<p>So you can create files via the API and if the user has their own GitHub account, you can upload it as them.</p> <p>Let's use github3.py as an example of how to do this:</p> <pre><code>import github3 gh = github3.login(username='foo', password='bar') repository = gh.repository('organization-name', 'repository-nam...
1
2016-09-29T12:16:00Z
[ "python", "git", "github", "github-api" ]
Replace Duplicate String Characters
39,737,196
<p>I need to convert a string <code>word</code> where each character that appears only once should be appear as <code>'('</code> in the new string. Any duplicate characters in the original string should be replaced with <code>')'</code>. </p> <p>My code below...</p> <pre><code>def duplicate_encode(word): new_word = '...
1
2016-09-28T02:42:21Z
39,737,272
<p>Seems like your result is based on the number of occurrences of a character in the word, you can use <code>Counter</code> to keep track of that:</p> <pre><code>def duplicate_encode(word): from collections import Counter word = word.lower() # to disregard case counter = Counter(word) ne...
0
2016-09-28T02:51:41Z
[ "python", "string", "replace", "duplicates", "iteration" ]
Replace Duplicate String Characters
39,737,196
<p>I need to convert a string <code>word</code> where each character that appears only once should be appear as <code>'('</code> in the new string. Any duplicate characters in the original string should be replaced with <code>')'</code>. </p> <p>My code below...</p> <pre><code>def duplicate_encode(word): new_word = '...
1
2016-09-28T02:42:21Z
39,737,775
<p>Your Code is Good just need some alteration it will be great.</p> <pre><code>def duplicate_encode(word): """ To replace the duplicate letter with ")" in a string. if given letter is unique it replaced with "(" """ word_dict = {} # initialize a dictionary new_word = "" for i in set(wor...
1
2016-09-28T03:55:41Z
[ "python", "string", "replace", "duplicates", "iteration" ]
Replace Duplicate String Characters
39,737,196
<p>I need to convert a string <code>word</code> where each character that appears only once should be appear as <code>'('</code> in the new string. Any duplicate characters in the original string should be replaced with <code>')'</code>. </p> <p>My code below...</p> <pre><code>def duplicate_encode(word): new_word = '...
1
2016-09-28T02:42:21Z
39,742,140
<p>Just because (it's late and) it's possible:</p> <pre><code>def duplicate_encode(word): return (lambda w: ''.join(('(', ')')[c in w[:i] + w[i+1:]] for i, c in enumerate(w)))(word.lower()) print(duplicate_encode("rEcede")) </code></pre> <p>OUTPUT</p> <pre><code>&gt; python3 test.py ()()() &gt; </code></pre>
1
2016-09-28T08:37:30Z
[ "python", "string", "replace", "duplicates", "iteration" ]
Django get months from models.DateTimeField
39,737,216
<p>Is it possible to filter a models.DateTimeField but only get the month in the filter object?</p> <p>The field is:</p> <pre><code>time_stamp = models.DateTimeField( default=timezone.now) </code></pre> <p>When I filter it, this is what I get:</p> <blockquote> <p>[datetime.datetime(2016, 9, 22, 15, 2,...
0
2016-09-28T02:44:09Z
39,737,340
<p>You can use propety:</p> <pre><code>Class your_model(models.Model): time_stamp = models.DateTimeField( default=timezone.now) @property def _get_year(self): return self.time_stamp.strftime("%Y-%m") year = property(_get_year) #EDIT </code></pre>
0
2016-09-28T03:01:08Z
[ "python", "django", "datetime" ]
Django get months from models.DateTimeField
39,737,216
<p>Is it possible to filter a models.DateTimeField but only get the month in the filter object?</p> <p>The field is:</p> <pre><code>time_stamp = models.DateTimeField( default=timezone.now) </code></pre> <p>When I filter it, this is what I get:</p> <blockquote> <p>[datetime.datetime(2016, 9, 22, 15, 2,...
0
2016-09-28T02:44:09Z
39,738,091
<p>If you are using django 1.10.x there is <a href="https://docs.djangoproject.com/en/1.10/ref/models/database-functions/#extract" rel="nofollow"><code>Extract</code></a> db function</p> <pre><code>from django.db.models.functions import Extract months = MyModel.objects.annotate(month_stamp=Extract('time_stamp', 'mont...
1
2016-09-28T04:32:07Z
[ "python", "django", "datetime" ]
How to use a pandas DataFrame as data parameter in Seaborn lmplot
39,737,226
<p>Looking at the <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.lmplot.html" rel="nofollow"><code>lmplot</code> documentation</a>, it shows</p> <blockquote> <p>Parameters: </p> <pre><code> x, y : strings, optional Input variables; these should be column names in data...
0
2016-09-28T02:45:31Z
39,737,302
<p>Thanks to <a href="http://stackoverflow.com/users/3437504/bob-haffner">Bob Haffner</a>, looking closer at the documentation, the DataFrame wasn't the issue at all, rather, the X and Y parameters I was passing. </p> <p>I was passing in Series, when I should have been passing in strings, as such:</p> <pre><code>sns....
1
2016-09-28T02:55:33Z
[ "python", "pandas", "dataframe", "seaborn" ]
Python: How do I refer to an attribute of a class by an attribute of another class or a variable?
39,737,273
<p>I am trying to create a magic system in my text-based RPG that refers to an attribute of a monster class using the attribute from the magic class. The monster class looks like </p> <pre><code>class monster(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) </code></pre> <p>with the li...
0
2016-09-28T02:51:44Z
39,737,353
<p>You could try something like the following:</p> <pre><code>def use_magic(target, spell): if spell.spell_type == "buff": stat = spell.stat setattr(target, stat, getattr(target,stat) + spell.value) </code></pre>
1
2016-09-28T03:02:26Z
[ "python", "attributes" ]
Return string that is not a substring of other strings - is it possible in time less than O(n^2)?
39,737,300
<p>You are given an array of strings. you have to return only those strings that are not sub strings of other strings in the array. Input - <code>['abc','abcd','ab','def','efgd']</code>. Output should be - <code>'abcd'</code> and <code>'efgd'</code> I have come up with a solution in python that has time complexity O(n^...
4
2016-09-28T02:55:12Z
39,737,452
<p>Pop the first element. Go through each remaining element and see if the shorter string is a substring of the longer string. Repeat. That should be O(n log n)</p> <p>EDIT: Rough draft of implementation</p> <pre><code>def not_substrings(l): mask = [True]*len(l) for i in range(len(l)): if not mask[...
-1
2016-09-28T03:16:03Z
[ "python", "string", "python-2.7", "substring" ]
Return string that is not a substring of other strings - is it possible in time less than O(n^2)?
39,737,300
<p>You are given an array of strings. you have to return only those strings that are not sub strings of other strings in the array. Input - <code>['abc','abcd','ab','def','efgd']</code>. Output should be - <code>'abcd'</code> and <code>'efgd'</code> I have come up with a solution in python that has time complexity O(n^...
4
2016-09-28T02:55:12Z
39,802,679
<p>Use a <code>set</code> object to keep all the substrings. This is faster but use a lot of memory, if every string is short, you can try this.</p> <pre><code>import string import random from itertools import combinations def get_substrings(w): return (w[s:e] for s, e in combinations(range(len(w)+1), 2)) def ge...
-1
2016-10-01T03:18:19Z
[ "python", "string", "python-2.7", "substring" ]
Return string that is not a substring of other strings - is it possible in time less than O(n^2)?
39,737,300
<p>You are given an array of strings. you have to return only those strings that are not sub strings of other strings in the array. Input - <code>['abc','abcd','ab','def','efgd']</code>. Output should be - <code>'abcd'</code> and <code>'efgd'</code> I have come up with a solution in python that has time complexity O(n^...
4
2016-09-28T02:55:12Z
39,802,797
<p>Using <a href="https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm" rel="nofollow">Aho-Corasick</a> should allow you to get asymptotic run time of <code>O(n)</code>, at the expense of adding additional memory usage, and higher fixed multiplier on costs (ignored by big-O notation, but still meaningful). The ...
0
2016-10-01T03:40:52Z
[ "python", "string", "python-2.7", "substring" ]
Return string that is not a substring of other strings - is it possible in time less than O(n^2)?
39,737,300
<p>You are given an array of strings. you have to return only those strings that are not sub strings of other strings in the array. Input - <code>['abc','abcd','ab','def','efgd']</code>. Output should be - <code>'abcd'</code> and <code>'efgd'</code> I have come up with a solution in python that has time complexity O(n^...
4
2016-09-28T02:55:12Z
39,803,163
<p>Is memory an issue? You could turn to the tried and true...TRIE! </p> <p>Build a suffix tree!</p> <p>Given your input <code>['abc','abcd','ab','def','efgd']</code></p> <p>We would have a tree of </p> <pre><code> _ / | \ a e d / | \ b* f e ...
2
2016-10-01T04:52:00Z
[ "python", "string", "python-2.7", "substring" ]
Import multiple CSV fields into one MySQL field
39,737,398
<p>I have a table like this</p> <pre><code>mytable(`id` int, 'number1' varchar(11), 'number2' varchar(1200)) </code></pre> <p>Also I have cvs-like file</p> <pre><code>111111111,222222222,333333333,44444444,,, 222222222,333333333, 111111111,555555555,666666666, </code></pre> <p>They are separated by ","(or something...
1
2016-09-28T03:08:54Z
39,737,506
<p>Here is an option which creates a <em>new</em> column combining columns 2 through 100:</p> <pre><code>LOAD DATA INFILE 'input.csv' INTO TABLE myTable COLUMNS TERMINATED BY ',' IGNORE 1 LINES (id, number1, number2, ..., number99) SET newCol = CONCAT(NULLIF(number1, ''), NULLIF(number2, ''), ..., NULLIF(number99, '...
1
2016-09-28T03:22:45Z
[ "python", "mysql", "csv" ]
Import multiple CSV fields into one MySQL field
39,737,398
<p>I have a table like this</p> <pre><code>mytable(`id` int, 'number1' varchar(11), 'number2' varchar(1200)) </code></pre> <p>Also I have cvs-like file</p> <pre><code>111111111,222222222,333333333,44444444,,, 222222222,333333333, 111111111,555555555,666666666, </code></pre> <p>They are separated by ","(or something...
1
2016-09-28T03:08:54Z
39,737,509
<p>you can use the function <code>file()</code> to open the cvs file ;</p> <p>use the function <code>explode(',', $each_line)</code> to seperate each line with <code>,</code>,</p> <p>I did not understand your demand clearly,I think simple code could like this:</p> <pre><code>$file_items = file('file.cvs'); foreach($...
0
2016-09-28T03:23:12Z
[ "python", "mysql", "csv" ]
Parsing date and time using regex from a chuck of string
39,737,498
<p>EDIT: DONE ALREADY! THANKS</p> <p>Code as below:</p> <p>import ast,re</p> <pre><code>a = "('=====================================', '30/06/2016 17:15 T001 -------------------------------')" t=ast.literal_eval(a) z=re.compile(r"(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)") m = z.match(t[1]) if m: print("date: {}, ti...
1
2016-09-28T03:21:58Z
39,737,564
<p>You can iterate list items, and match those items.</p> <pre><code>t = ast.literal_eval(a) # assuming `t` is an iterable z = re.compile(r"(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)") for item in t: # &lt;----- m = z.match(item) if m: print("date: {}, time {}".format(m.group(1), m.group(2))) # break...
1
2016-09-28T03:30:48Z
[ "python", "regex" ]
Basic addition in Tensorflow?
39,737,507
<p>I want to make a program where I enter in a set of x1 x2 and outputs a y. All of the tensor flow tutorials I can find start with image recognition. Can someone help me by providing me either code or a tutorial on how to do this in python? thanks in advance. edit- the x1 x2 coordinates I was planning to use would be ...
0
2016-09-28T03:23:02Z
39,747,526
<p>Here is a snippet to get you started:</p> <pre><code>import numpy as np import tensorflow as tf #a placeholder is like a variable that you can #set later a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) #build the sum operation c = a+b #get the tensorflow session sess = tf.Session() #initialize all v...
0
2016-09-28T12:28:08Z
[ "python", "machine-learning", "bigdata", "tensorflow", "add" ]
Python plot won't run: 'x and y must have same first dimension'
39,737,536
<p>I'm absolutely certain I'm doing something simple wrong with my function definition, but I'm completely drained right now and can't figure it out. If someone can help, I'd love them forever.</p> <pre><code>import matplotlib.pyplot as plt import scipy as sp lamb = sp.array([1100, 1650, 2200, 2750, 3300, 3850, 4400,...
1
2016-09-28T03:28:00Z
39,737,908
<p>You can clearly see there is an issue. You have to give two arrays for the plt.plot(x,y). In your case, you gave an array and rlam which is a function name. So obviously, there is an error. </p> <p>Try to learn more about the python function usage. I added a small code snippet which shows the plot usage and python ...
1
2016-09-28T04:10:30Z
[ "python", "matplotlib" ]
Create new database from chunk reader in pandas
39,737,545
<p>I'm working with a massive excel file (14GB) that I need to clean so only the information I need is left. I made the file into Chunks so my computer would stop crashing, but now need to create a new database that shows only the data for the city I am looking for. </p> <p>I have made it to print(chunk)</p> <pre><co...
0
2016-09-28T03:28:59Z
39,757,560
<p>try this:</p> <pre><code>chunk in reader: chunk.ix[chunk.SitusCity == 'Miami'].to_excel('output.xlsx', mode='a') </code></pre>
0
2016-09-28T20:59:40Z
[ "python", "excel", "pandas", "jupyter", "jupyter-notebook" ]
SQLalchemy find id and use it to lookup other information
39,737,600
<p>I'm making a simple lookup application for Japanese characters (Kanji), where the user can search the database using any of the information available.</p> <h2>My database structure</h2> <p><strong>Kanji</strong>:</p> <ul> <li>id</li> <li>character (A kanji like 頑)</li> <li>heisig6 (a number indicating the order...
0
2016-09-28T03:35:29Z
39,757,177
<p>We would really have to be able to see your database schema to give real critique, but assuming no foreign keys, what you said is basically the best you can do.</p> <p>SQLAlchemy really begins to shine when you have complicated relations going on however. For example, if you properly had foreign keys set, you could...
1
2016-09-28T20:35:12Z
[ "python", "sqlalchemy" ]
Python having issues computing large numbers in complex equations
39,737,687
<p>I'm programming some code that allows a user to input seconds, and receive how many days, hours, minutes, and seconds it churns out to. However, if I enter any number larger than 311039999, the amount of hours goes to 24+, instead of 0.</p> <p>Right now I have something programmed in that tells the user that the nu...
0
2016-09-28T03:45:54Z
39,738,042
<p>If you don't mind using a 3rd party module, <code>dateutil</code> provides an easy way to do this:</p> <pre><code>from dateutil.relativedelta import relativedelta user_sec = int(input("How many seconds are there? ")) d = relativedelta(seconds=user_sec) print(d) </code></pre> <p>This will output the following if y...
2
2016-09-28T04:26:26Z
[ "python", "complex-numbers", "canopy" ]
Get Attributes python
39,737,712
<pre><code>class A(object): a = 1 b = 0 c = None d = None a_obj=A() a_list = ['a', 'b', 'c', 'd'] attrs_present = filter(lambda x: getattr(a_obj, x), a_list) </code></pre> <p>I want both a and b attributes, here 0 is a valid value. I don't want to use comparison==0</p> <p>is there a way to get...
3
2016-09-28T03:49:02Z
39,737,741
<p>If you want to exclude <code>c</code>, <code>d</code> (<code>None</code>s), use <code>is None</code> or <code>is not None</code>:</p> <pre><code>attrs_present = filter(lambda x: getattr(a_obj, x, None) is not None, a_list) # NOTE: Added the third argument `None` # to prevent `AttributeError` in case of missin...
2
2016-09-28T03:51:50Z
[ "python", "python-2.7" ]
Print random number of lines after read a file
39,737,728
<p>I am writing a thread-enabled python program which can read a file and send, but is there any ways to let the program read and send N numbers of line at a time?</p> <pre><code>from random import randint import sys import threading import time def function(): fo = open("1.txt", "r") print "Name of the file:...
-1
2016-09-28T03:50:43Z
39,737,818
<p>If you follow your code logic, in the <code>for</code> loop iterating over the lines in the file, you reset the file pointer to the first line right after having printed it. That's why you get the same first line printed. To achieve a random number of printed lines you could do that in any number of ways, for exampl...
0
2016-09-28T04:00:43Z
[ "python", "python-2.7", "python-3.x" ]
Print random number of lines after read a file
39,737,728
<p>I am writing a thread-enabled python program which can read a file and send, but is there any ways to let the program read and send N numbers of line at a time?</p> <pre><code>from random import randint import sys import threading import time def function(): fo = open("1.txt", "r") print "Name of the file:...
-1
2016-09-28T03:50:43Z
39,737,860
<p>something like this?</p> <pre><code>from random import randint import sys import threading import time def function(): fo = open("1.txt", "r") print "Name of the file: ", fo.name lines = fo.readlines() while lines: toSend = "" for i in range(0,random.randint(x,y)): #plug your range ...
0
2016-09-28T04:05:44Z
[ "python", "python-2.7", "python-3.x" ]
String Output in Python
39,737,767
<pre><code> html_body += "&lt;tr&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;".\format(p[0],p[1],p[2],p[3]) ^ </code></pre> <blockquote> <p>SyntaxError: unexpected character a...
2
2016-09-28T03:54:31Z
39,737,787
<pre><code>html_body += "&lt;tr&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;".\form ^ </code></pre> <p>Right there is your problem. The backslash is the line-continuation character that the error mention...
1
2016-09-28T03:56:58Z
[ "python" ]
String Output in Python
39,737,767
<pre><code> html_body += "&lt;tr&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;".\format(p[0],p[1],p[2],p[3]) ^ </code></pre> <blockquote> <p>SyntaxError: unexpected character a...
2
2016-09-28T03:54:31Z
39,737,788
<pre><code>html_body += "&lt;tr&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;&lt;td&gt;{}&lt;/td&gt;".\format(p[0],p[1],p[2],p[3]) this backslash is not needed ----------------------------------^ </code></pre>
0
2016-09-28T03:57:00Z
[ "python" ]
Google OAuth2client - invalid_grant: Token has been revoked
39,737,796
<p>I'm writing a basic app that prints out projects in Google's Cloud Resources Manager using this method: <a href="https://cloud.google.com/resource-manager/reference/rest/v1/projects/list" rel="nofollow">https://cloud.google.com/resource-manager/reference/rest/v1/projects/list</a></p> <p>Yesterday it worked but I re...
0
2016-09-28T03:57:48Z
39,761,655
<p>Suddenly yesterday we faced a similar issue in Google OAuth2 connection from gerrit code review. So just wanted to share this as it might be related to you. Refer this <a href="https://github.com/davido/gerrit-oauth-provider/issues/64" rel="nofollow">github issue</a> &amp; its <a href="https://github.com/davido/gerr...
0
2016-09-29T04:51:44Z
[ "python", "pycharm", "google-api-client", "google-oauth2", "oauth2client" ]
Google OAuth2client - invalid_grant: Token has been revoked
39,737,796
<p>I'm writing a basic app that prints out projects in Google's Cloud Resources Manager using this method: <a href="https://cloud.google.com/resource-manager/reference/rest/v1/projects/list" rel="nofollow">https://cloud.google.com/resource-manager/reference/rest/v1/projects/list</a></p> <p>Yesterday it worked but I re...
0
2016-09-28T03:57:48Z
39,761,906
<p>Since this code uses application default credentials, the gcloud command is how I get a new token:</p> <pre><code>gcloud beta auth application-default login </code></pre> <p>Although it would be nice if there was a way to do this in code in the event the token is revoked again.</p>
0
2016-09-29T05:14:20Z
[ "python", "pycharm", "google-api-client", "google-oauth2", "oauth2client" ]
Writing to a file after parsing
39,737,812
<p>I have written a small python code where it will read a sample csv file and copy its first column to a temp csv file. Now when I try to compare that temporary file with another text file and try to write result to another file called result file, The file is created but with empty content.</p> <p>But when i tested ...
0
2016-09-28T04:00:05Z
39,738,120
<p>You should close the output file (<code>temp1.csv</code>) before you can read data from it.</p> <pre><code>import csv f = open("sample.csv", "r") reader = csv.reader(f) data = open("temp1.csv", "w") w = csv.writer(data) for row in reader: my_row = [] my_row.append(row[0]) w.writerow(my_row) data.close(...
0
2016-09-28T04:34:22Z
[ "python", "file-writing" ]
Writing to a file after parsing
39,737,812
<p>I have written a small python code where it will read a sample csv file and copy its first column to a temp csv file. Now when I try to compare that temporary file with another text file and try to write result to another file called result file, The file is created but with empty content.</p> <p>But when i tested ...
0
2016-09-28T04:00:05Z
39,738,615
<p><strong>Points regarding code</strong>:</p> <ul> <li><code>data</code> file handle is not closed. <code>data.close()</code> after writing to <code>temp1.csv</code>.</li> <li>In your code, <code>same = set(file1).intersection(file2)</code>, you are directly passing file handle <code>file2</code> to intersection. It ...
0
2016-09-28T05:20:31Z
[ "python", "file-writing" ]
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)
39,737,820
<p><strong>This is not a duplicate of <a href="http://stackoverflow.com/questions/35403605/ssl-certificate-verify-failed-ssl-c600">this question</a></strong></p> <p>I checked <a href="http://stackoverflow.com/questions/38522939/requests-exceptions-sslerror-ssl-certificate-verify-failed-certificate-verif">this</a> but ...
0
2016-09-28T04:00:50Z
39,738,401
<p>You need to download the GoDaddy root certificates, available at <a href="https://certs.godaddy.com/repository" rel="nofollow">this site</a> and then pass it in as a parameter to <code>verify</code>, like this:</p> <pre><code>&gt;&gt;&gt; r = requests.get('https://aucoe.info', verify='/path/to/gd_bundle-g2-g1.crt')...
0
2016-09-28T05:01:01Z
[ "python", "python-3.x", "ssl", "ssl-certificate", "python-requests" ]
"None" string appear after print a line in python
39,737,836
<p>I a new in python programming. Today I practice with sorting a list. I've got a strange output with this code:</p> <pre><code># problem 13 def lensort(list): list.sort(key=lambda x: len(x)) print list print "Sort by length: ", lensort(['python', 'perl', 'java', 'c', 'haskell','ruby']) </code></pre> <p>The...
0
2016-09-28T04:02:11Z
39,737,844
<p>Because you are printing the list at the end of <code>lensort</code> function instead of returning it. A function in Python implicitly returns <code>None</code> if it doesn't <code>return</code> anything explicitly.</p> <pre><code>def lensort(list): list.sort(key=lambda x: len(x)) return list </code></pre>...
0
2016-09-28T04:03:24Z
[ "python", "sorting" ]
"None" string appear after print a line in python
39,737,836
<p>I a new in python programming. Today I practice with sorting a list. I've got a strange output with this code:</p> <pre><code># problem 13 def lensort(list): list.sort(key=lambda x: len(x)) print list print "Sort by length: ", lensort(['python', 'perl', 'java', 'c', 'haskell','ruby']) </code></pre> <p>The...
0
2016-09-28T04:02:11Z
39,737,861
<p>You're almost double printing the list so to speak. You don't want to print in the function since you're already calling <code>print</code> right after it. Instead you'll want to <code>return</code> the list and then have the <code>print</code> function print the returned list when you call <code>lensort</code>. </p...
0
2016-09-28T04:05:51Z
[ "python", "sorting" ]
"None" string appear after print a line in python
39,737,836
<p>I a new in python programming. Today I practice with sorting a list. I've got a strange output with this code:</p> <pre><code># problem 13 def lensort(list): list.sort(key=lambda x: len(x)) print list print "Sort by length: ", lensort(['python', 'perl', 'java', 'c', 'haskell','ruby']) </code></pre> <p>The...
0
2016-09-28T04:02:11Z
39,737,896
<p>The <code>.sort</code> method sorts a list in place. You do not return its return. Also, no <code>lambda</code> needed:</p> <pre><code>&gt;&gt;&gt; li=['python', 'perl', 'java', 'c', 'haskell','ruby'] &gt;&gt;&gt; li.sort(key=len) &gt;&gt;&gt; li ['c', 'perl', 'java', 'ruby', 'python', 'haskell'] </code></pre> <p>...
0
2016-09-28T04:09:38Z
[ "python", "sorting" ]
Resampling (Upsample) Pandas multiindex dataframe
39,737,890
<p>Here is a sample dataframe for reference:</p> <pre><code>import pandas as pd import datetime import numpy as np np.random.seed(1234) arrays = [np.sort([datetime.date(2016, 8, 31), datetime.date(2016, 7, 31), datetime.date(2016, 6, 30)]*3), ['A', 'B', 'C', 'D', 'E']*5] df = pd.DataFrame(np.random.randn(15,...
0
2016-09-28T04:08:56Z
39,737,891
<p>Edit: I have found a solution:</p> <pre><code>df.unstack().resample('W-FRI', how='last', fill_method='ffill') </code></pre> <p>but I wonder if there's a more efficient way to do this.</p>
0
2016-09-28T04:08:56Z
[ "python", "pandas", "dataframe", "multi-index", "resampling" ]
Efficient way to check if the last element in a row (in a list of lists) is found in another list?
39,737,941
<p>I currently have a list of lists (let's name it "big") that is about 9 columns and 5000 rows and growing. I have another list (let's name this one "small") that has approximately 3000 elements. My goal is to return each row in big where big[8] can be found in small. The results will be stored in a list of lists.</p>...
2
2016-09-28T04:14:50Z
39,737,983
<p>You can easily eliminate the linear search of <code>small</code> on each iteration by using a set:</p> <pre><code>smallset = set(small) results = [row for row in big if row[8] in smallset] </code></pre>
3
2016-09-28T04:19:39Z
[ "python", "performance", "list" ]
Efficient way to check if the last element in a row (in a list of lists) is found in another list?
39,737,941
<p>I currently have a list of lists (let's name it "big") that is about 9 columns and 5000 rows and growing. I have another list (let's name this one "small") that has approximately 3000 elements. My goal is to return each row in big where big[8] can be found in small. The results will be stored in a list of lists.</p>...
2
2016-09-28T04:14:50Z
39,738,062
<p>A quick and easy way to do is to create a dictionary with 8 column item as the key. Below is a code snippet. </p> <pre><code>big_dict = {} for list in big: big_dict[list[-1]] = list output_list = [] for element in small: output_list.append(big_dict[element]) </code></pre>
1
2016-09-28T04:28:10Z
[ "python", "performance", "list" ]
Efficient way to check if the last element in a row (in a list of lists) is found in another list?
39,737,941
<p>I currently have a list of lists (let's name it "big") that is about 9 columns and 5000 rows and growing. I have another list (let's name this one "small") that has approximately 3000 elements. My goal is to return each row in big where big[8] can be found in small. The results will be stored in a list of lists.</p>...
2
2016-09-28T04:14:50Z
39,738,133
<p>Binary search your small list which will reduce the time complexity to O(log n).</p> <pre><code>smallset = sort(small) def binarySearch(x): #implement binary search pass results = [row for row in big if binarySearch(row[8])] </code></pre>
-1
2016-09-28T04:36:00Z
[ "python", "performance", "list" ]
meaning of `button_map` in the form_field definition in flask-bootstrap
39,737,970
<p>I am reading the documentation of <a href="https://pythonhosted.org/Flask-Bootstrap/forms.html" rel="nofollow">flask-boostrap doc</a>. In the <code>form_field</code> definition, what is the purpose of the <code>button_map</code>? </p> <pre><code>form_field(field, form_type="basic", horizontal_columns=('lg', 2, 10),...
0
2016-09-28T04:18:20Z
39,738,183
<p>According to your link (see <a href="https://pythonhosted.org/Flask-Bootstrap/forms.html#quick_form" rel="nofollow"><code>quick_form</code></a>):</p> <blockquote> <p><strong>button_map</strong> – A dictionary, mapping button field names to names such as <code>primary</code>, <code>danger</code> or <code>success...
0
2016-09-28T04:40:44Z
[ "python", "flask", "flask-wtforms", "flask-bootstrap" ]
Python: Sleep methods
39,738,065
<p>I know this is already technically "asked" on this forums but this question is based around a different concept that I couldn't find.</p> <p>While using time.sleep(whatever) it obviously sleeps, I get that but while using Pygame it will lock up the program. Is there any real method of using a sleep or a pause in th...
0
2016-09-28T04:28:36Z
39,739,381
<p>I think you may want to try using the method that is shown <a href="http://stackoverflow.com/questions/18839039/how-to-wait-some-time-in-pygame">here</a>.</p> <p>an example of what I mean is this:</p> <pre><code>class Unit(): def __init__(self): self.last = pygame.time.get_ticks() self.cooldown...
0
2016-09-28T06:18:32Z
[ "python", "wait", "sleep" ]
flask-bootstrap with two forms in one page
39,738,069
<p>I plan to put two forms in one page in my flask app, one to edit general user information and the other to reset password. The template looks like this</p> <pre><code>{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block page_content %} &lt;d...
0
2016-09-28T04:29:21Z
39,739,863
<p>Define this two SubmitField with different names, like this:</p> <pre><code>class Form1(Form): name = StringField('name') submit1 = SubmitField('submit') class Form2(Form): name = StringField('name') submit2 = SubmitField('submit') </code></pre> <p>Then in <code>view.py</code>:</p> <pre><code>......
2
2016-09-28T06:43:55Z
[ "python", "flask", "flask-wtforms", "flask-bootstrap" ]
python .loc with some condition(string, regex etc)
39,738,137
<p>I am willing to get subset of the dataframe. And the condition is that, the value of certain column starts with the string 'HOUS'. How should I do?. </p> <pre><code>df.loc[df.id.startswith('HOUS')] </code></pre>
0
2016-09-28T04:36:10Z
39,738,188
<p>I should have searched more.</p> <p>Here is the solution.</p> <pre><code>df[df.id.str.startswith('HOUS')] </code></pre>
0
2016-09-28T04:41:10Z
[ "python", "pandas", "dataframe", "substring" ]
No such file or directory?
39,738,179
<p>For some reason despite having the file in the main and in the same directory, I keep getting the no such file error. Any help is appreciated. </p> <pre><code> import time def firstQues(): print('"TT(Announcing): HONING IN FROM SU CASA CUIDAD, (Their hometown)"') time.sleep(3) ...
0
2016-09-28T04:40:24Z
39,738,323
<p>You cannot open a file in read mode that doesn't exist. Make sure you create a file in a current working directory. Your program executed successfully.</p> <p><a href="http://i.stack.imgur.com/1gqs3.png" rel="nofollow"><img src="http://i.stack.imgur.com/1gqs3.png" alt="enter image description here"></a></p>
0
2016-09-28T04:53:51Z
[ "python", "python-3.x" ]
No such file or directory?
39,738,179
<p>For some reason despite having the file in the main and in the same directory, I keep getting the no such file error. Any help is appreciated. </p> <pre><code> import time def firstQues(): print('"TT(Announcing): HONING IN FROM SU CASA CUIDAD, (Their hometown)"') time.sleep(3) ...
0
2016-09-28T04:40:24Z
39,738,490
<pre><code> with open("Questions1.txt", "r") as f: file_data = f.read().splitlines() for line in file_data: #do what ever you want </code></pre> <p><a href="http://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list-with-python">How to read a file line by line into a list w...
0
2016-09-28T05:08:02Z
[ "python", "python-3.x" ]
No such file or directory?
39,738,179
<p>For some reason despite having the file in the main and in the same directory, I keep getting the no such file error. Any help is appreciated. </p> <pre><code> import time def firstQues(): print('"TT(Announcing): HONING IN FROM SU CASA CUIDAD, (Their hometown)"') time.sleep(3) ...
0
2016-09-28T04:40:24Z
39,740,043
<p>The simplest solution comes down to a paradigm choice, <em>ask for permission</em> or <em>ask for forgiveness</em>.</p> <p>Ask for permission: check if the file exists before using</p> <pre><code>import os.path if os.path.isfile("Questions1.txt"): #read file here </code></pre> <p>Ask for forgiveness: try-excep...
0
2016-09-28T06:54:15Z
[ "python", "python-3.x" ]
How to call csv data into tuples in python with numpy genfromtxt?
39,738,231
<p>I've been having trouble calling csv files in form of tuples with python.</p> <p>I'm using: </p> <pre><code> csv_data = np.genfromtxt('csv-data.csv', dtype=int, delimiter=',', names=True) </code></pre> <p>While the data looks like: (sorry I don't know how to display csv format)</p> <p>Trial1 Trial2 Trial3</p...
0
2016-09-28T04:45:37Z
39,738,381
<p>I think you can use the <code>tolist</code> method.</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html</a></p> <p>It will convert the ndarray to a list.</p> <pre><code>import numpy as np csv_...
1
2016-09-28T04:58:58Z
[ "python", "csv", "numpy", "genfromtxt" ]
YouCompleteMe post install error : cannot import name _compare_digest
39,738,301
<p>I am trying to install YouCompleteMe plugin on a source compiled Vim instance. I have a server without sudo privileges, hence I had to compile new Vim (7.4+) in order to make most plugins work. Also, I have installed miniconda and thus refer to the python in miniconda for all installations.</p> <p>While following a...
0
2016-09-28T04:52:25Z
40,113,395
<p>When I had trouble with dependencies I had to run </p> <p><code>git submodule update --init --recursive</code></p> <p>in the YouCompleteMe directory to get the dependencies installed.</p> <p>Also make sure you have taken all of the other steps here:</p> <p><a href="https://valloric.github.io/YouCompleteMe/#full-...
0
2016-10-18T16:22:48Z
[ "python", "ubuntu", "vim", "conda", "miniconda" ]
Siri-like app: calculating similarities between a query and a predefined set of control phrases
39,738,327
<p>I am trying to make a Apple Siri-like application in python in which you give it vocal commands or questions through a microphone, it determines the text version of the inputted audio, and then determines the appropriate action to take based on the meaning of the command/question. I am going to be using the Speech R...
0
2016-09-28T04:54:24Z
39,742,604
<p>This is a hard problem. It is also the subject of <a href="http://alt.qcri.org/semeval2017/task11" rel="nofollow">Task 11</a> of this year's set of Semantic evaluation challenges (<a href="http://alt.qcri.org/semeval2017/" rel="nofollow">Semeval 2017</a>). So take a look at the <a href="http://alt.qcri.org/semeval20...
3
2016-09-28T08:58:50Z
[ "python", "nlp", "nltk", "wordnet", "gensim" ]
Quicksort: Infinite Loop
39,738,341
<p>The following implementation of <code>QuickSort</code> runs into infinite loop</p> <pre class="lang-py prettyprint-override"><code>def partition(arr, lo, hi): pivot = lo for i in range(lo+1, hi+1): if arr[i] &lt;= arr[lo]: pivot += 1 arr[i], arr[pivot] = arr[pivot], arr[i] ...
0
2016-09-28T04:55:20Z
39,738,410
<p>At one point, your loop never works in partition def. See below</p> <pre><code>[5, 3, 2, -9, 1, 6, 0, -1, 9, 6, 2, 5] lo 0 hi 11 pivot 8 [5, 3, 2, -9, 1, 0, -1, 2, 5, 6, 6, 9] lo 0 hi 7 pivot 7 [2, 3, 2, -9, 1, 0, -1, 5, 5, 6, 6, 9] lo 0 hi 6 pivot 5 [-1, 2, -9, 1, 0, 2, 3, 5, 5, 6, 6, 9] lo 0 hi 4 pivot 1 [-9, -1,...
1
2016-09-28T05:01:28Z
[ "python", "sorting", "infinite-loop", "quicksort" ]
Quicksort: Infinite Loop
39,738,341
<p>The following implementation of <code>QuickSort</code> runs into infinite loop</p> <pre class="lang-py prettyprint-override"><code>def partition(arr, lo, hi): pivot = lo for i in range(lo+1, hi+1): if arr[i] &lt;= arr[lo]: pivot += 1 arr[i], arr[pivot] = arr[pivot], arr[i] ...
0
2016-09-28T04:55:20Z
39,740,077
<p>The problem is with your initialization code for <code>hi</code>:</p> <pre><code>if not hi: hi = len(arr) - 1 </code></pre> <p>The condition <code>not hi</code> is <code>True</code> if <code>hi</code> is zero.</p> <p>This causes <code>quicksort(arr, 0, 0)</code> and <code>quicksort(arr, 1, 0)</code> (one of which...
1
2016-09-28T06:56:15Z
[ "python", "sorting", "infinite-loop", "quicksort" ]
How to make flask jinja use variables from python list as a jinja expression variables
39,738,423
<p>So I have a list:</p> <pre><code>ABC = ['{{ row[0] }}','{{ row[1] }}','{{ row[2] }}'] </code></pre> <p>In HTML template, I want to use each items in list ABC as Jinja expression, how can i do it, here is my HTML table template</p> <pre><code>{% for row in reports %} &lt;tr&gt; {% for item in ABC %} ...
2
2016-09-28T05:02:47Z
39,745,979
<p>The problem is how you are creating the list. Right now you're giving it strings that identify the items you want to output. Instead, give it what you want to output. </p> <pre><code>ABC = [row[0], row[1], row[2]] </code></pre> <p>Edit: Since you are trying to print all of the columns in the template you can just ...
0
2016-09-28T11:20:36Z
[ "python", "python-3.x", "flask", "jinja2" ]
What's this after aggregation in django?
39,738,438
<p>I see the following code from a django project. I understand it's aggregation, but what's ['kw__sum'] after the aggregation?</p> <pre><code>Project.objects.filter(project = project).aggregate(Sum('kw'))['kw__sum'] </code></pre> <p>Thanks</p>
1
2016-09-28T05:03:56Z
39,738,474
<p>Here if you look in <a href="https://docs.djangoproject.com/en/1.10/topics/db/aggregation/#cheat-sheet" rel="nofollow">examples</a> you will see that <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#aggregate" rel="nofollow"><code>aggregate</code></a> returns dictionary so last part is just dict...
2
2016-09-28T05:06:23Z
[ "python", "django", "aggregation" ]
Parse decodeURIComponent JSON string with Python
39,738,443
<p>I have a "deep" JSON string that I need to pass as GET vars in a URL. It looks like the following:</p> <pre><code>{ "meta": { "prune": true, "returnFields": ["gf", "gh", "gh", "rt"], "orient": "split" }, "indicators": [{ "type": "beta", "computeOn": "gf", "parameters": { "timeper...
1
2016-09-28T05:04:11Z
39,738,683
<p>Well, since we hashed it out in the comments, I'll post the answer here for posterity.</p> <p>Use a combination of <code>JSON.stringify</code> on the JavaScript side to serialize your data structure and <code>json.loads</code> on the Python side to deserialize it. Pass the serialized structure as a query string par...
0
2016-09-28T05:25:50Z
[ "javascript", "jquery", "python", "json" ]
Return value from multiprocessing.Queue() in multiprocessing Python
39,738,504
<p>I run a simple multiprocess program (the code below). I just make 2 processors, then initial a queue to store the result.</p> <p>I wonder why with the same name <code>q</code>, but each time it prints out a different value. I know the queue store 2 return values, from <code>pro1</code> and <code>pro2</code>. But I ...
3
2016-09-28T05:09:40Z
39,738,563
<p>I'm not 100% sure what you're confused about exactly, but here's what I think will help, but please correct me if I'm off track. Your queue has the outputs of both processes on it. You're just getting the one that finished first.</p> <p>For example in your case it looks like process 1 finishes first, and then proce...
1
2016-09-28T05:15:58Z
[ "python", "multiprocessing" ]
Python requests, how to add content-type to multipart/form-data request
39,738,525
<p>I Use python requests to upload a file with PUT method.</p> <p>The remote API Accept any request only if the body contains an attribute Content-Type:i mage/png not as Request Header </p> <p>When i use python requests , the request rejected because missing attribute</p> <p><a href="http://i.stack.imgur.com/8KQ0F....
2
2016-09-28T05:12:23Z
39,742,334
<p>As per the [docs][1, you need to add two more arguments to the tuple, filename and the content type:</p> <pre><code># filed name filename file object content=type files = {'location[logo]': ("name.png", open(fileinput),'image/png')} </code></pre> <p>You can see a sample an example below:</...
0
2016-09-28T08:46:31Z
[ "python", "file", "http", "upload", "python-requests" ]
Categorize each feature from a dataset by percentiles via python
39,738,611
<p>I'm trying to figure a way to categorize each column in my dataset based on it's percentiles. For example, consider the column:</p> <pre><code> ticket 24160 113781 113781 113781 113781 19952 13502 112050 11769 </code></pre> <p>The 20th percentile of the column above is 1350. Basically I want to convert th...
0
2016-09-28T05:20:06Z
39,750,582
<pre><code>np.floor(df[df.columns[:-1]].rank() / len(df) / .2).astype(int) + 1 </code></pre> <p>The above code returns what you want, with the same column names as original data.</p> <ol> <li><code>df[df.columns[:-1]]</code> subsets all but the last column as you requested</li> <li><code>.rank()</code> gives the inte...
0
2016-09-28T14:35:41Z
[ "python" ]
AttributeError: '_io.TextIOWrapper' object has no attribute 'lower' for txt file
39,738,661
<p>Here is my code (A pig <strong>Latin translator</strong> from a text file): </p> <pre><code>f = open('Assignment_4.txt', 'r+') for line in f: print(line) def pigLatin(): var = 'ay' wordL = f.lower() firstLetter = wordL[0] pigLatin = wordL + firstLetter + var pigLatin = pigLatin[1:] p...
-1
2016-09-28T05:23:58Z
39,738,851
<p><strong>Points:</strong></p> <ul> <li><code>lower()</code> works with string. You are trying to use with file handle <code>f</code>. That's why you are getting this error. </li> <li>Also, after reading file line by line, you should call <code>pigLatin()</code> for each line as <code>pigLatin(line)</code>. So, now ,...
0
2016-09-28T05:41:02Z
[ "python" ]
AttributeError: '_io.TextIOWrapper' object has no attribute 'lower' for txt file
39,738,661
<p>Here is my code (A pig <strong>Latin translator</strong> from a text file): </p> <pre><code>f = open('Assignment_4.txt', 'r+') for line in f: print(line) def pigLatin(): var = 'ay' wordL = f.lower() firstLetter = wordL[0] pigLatin = wordL + firstLetter + var pigLatin = pigLatin[1:] p...
-1
2016-09-28T05:23:58Z
39,738,885
<p>The error is quite right - file objects don't have a <code>lower()</code> method - before you can use your function you need to <code>read</code> a line of text from your file and <code>split</code> it into separate words. (Note that it is never a good idea to use the same name for a variable and a method as it can ...
0
2016-09-28T05:43:14Z
[ "python" ]
How do you get a probability of all classes to predict without building a classifier for each single class?
39,738,703
<p>Given a classification problem, sometimes we do not just predict a class, but need to return the probability that it is a class.</p> <p>i.e. P(y=0|x), P(y=1|x), P(y=2|x), ..., P(y=C|x)</p> <p>Without building a new classifier to predict y=0, y=1, y=2... y=C respectively. Since training C classifiers (let's say C=1...
0
2016-09-28T05:27:11Z
39,742,380
<p>If you want probabilities, look for sklearn-classifiers that have method: predict_proba()</p> <p>Sklearn documentation about multiclass:[<a href="http://scikit-learn.org/stable/modules/multiclass.html]" rel="nofollow">http://scikit-learn.org/stable/modules/multiclass.html]</a></p> <p>All scikit-learn classifiers a...
2
2016-09-28T08:48:18Z
[ "python", "machine-learning", "scikit-learn" ]
How do you get a probability of all classes to predict without building a classifier for each single class?
39,738,703
<p>Given a classification problem, sometimes we do not just predict a class, but need to return the probability that it is a class.</p> <p>i.e. P(y=0|x), P(y=1|x), P(y=2|x), ..., P(y=C|x)</p> <p>Without building a new classifier to predict y=0, y=1, y=2... y=C respectively. Since training C classifiers (let's say C=1...
0
2016-09-28T05:27:11Z
39,743,987
<p>Random forests do indeed give P(Y/x) for multiple classes. In most cases P(Y/x) can be taken as:</p> <p>P(Y/x)= the number of trees which vote for the class/Total Number of trees.</p> <p>However you can play around with this, for example in one case if the highest class has 260 votes, 2nd class 230 votes and other...
0
2016-09-28T09:53:41Z
[ "python", "machine-learning", "scikit-learn" ]
How to measure similarity between two python code blocks?
39,738,872
<p>Many would want to measure code similarity to catch plagiarisms, however my intention is to cluster a set of python code blocks (say answers to the same programming question) into different categories and distinguish different approaches taken by students. </p> <p>If you have any idea how this could be achieved, I ...
1
2016-09-28T05:42:31Z
39,738,985
<p>One approach would be to count then number of functions, objects, keywords <em>possibly grouped into categories such as branching, creating, manipulating, etc.,</em> and number variables of each type. Without relying on the methods and variables being called the same name(s).</p> <p>For a given problem the similar...
1
2016-09-28T05:51:30Z
[ "python", "compilation", "comparison", "abstract-syntax-tree" ]
How to measure similarity between two python code blocks?
39,738,872
<p>Many would want to measure code similarity to catch plagiarisms, however my intention is to cluster a set of python code blocks (say answers to the same programming question) into different categories and distinguish different approaches taken by students. </p> <p>If you have any idea how this could be achieved, I ...
1
2016-09-28T05:42:31Z
39,741,309
<p>You can choose any scheme you like that essentially hashes the contents of the code blocks, and place code blocks with identical hashes into the same category.</p> <p>Of course, what will turn out to be similar will then depend highly on how you defined the hashing function. For instance, a truly stupid hashing f...
1
2016-09-28T07:54:56Z
[ "python", "compilation", "comparison", "abstract-syntax-tree" ]
Python file matching and appending
39,738,915
<p>This is one file <code>result.csv</code>:</p> <pre><code>M11251TH1230 M11543TH4292 M11435TDS144 </code></pre> <p>This is another file <code>sample.csv</code>:</p> <pre><code>M11435TDS144,STB#1,Router#1 M11543TH4292,STB#2,Router#1 M11509TD9937,STB#3,Router#1 M11543TH4258,STB#4,Router#1 </code></pre> <p>Can I ...
0
2016-09-28T05:45:22Z
39,739,335
<p>The following snippet of code will work for you </p> <pre><code>import csv with open('result.csv', 'rb') as f: reader = csv.reader(f) result_list = [] for row in reader: result_list.extend(row) with open('sample.csv', 'rb') as f: reader = csv.reader(f) sample_list = [] for row in re...
0
2016-09-28T06:14:58Z
[ "python", "append" ]
Python file matching and appending
39,738,915
<p>This is one file <code>result.csv</code>:</p> <pre><code>M11251TH1230 M11543TH4292 M11435TDS144 </code></pre> <p>This is another file <code>sample.csv</code>:</p> <pre><code>M11435TDS144,STB#1,Router#1 M11543TH4292,STB#2,Router#1 M11509TD9937,STB#3,Router#1 M11543TH4258,STB#4,Router#1 </code></pre> <p>Can I ...
0
2016-09-28T05:45:22Z
39,739,728
<pre><code>import pandas as pd d1 = pd.read_csv("1.csv",names=["Type"]) d2 = pd.read_csv("2.csv",names=["Type","Col2","Col3"]) d2["Index"] = 0 for x in d1["Type"] : d2["Index"][d2["Type"] == x] = 1 d2.to_csv("3.csv",header=False) </code></pre> <p>Considering "1.csv" and "2.csv" are your csv input files and "3.c...
0
2016-09-28T06:36:57Z
[ "python", "append" ]
Python file matching and appending
39,738,915
<p>This is one file <code>result.csv</code>:</p> <pre><code>M11251TH1230 M11543TH4292 M11435TDS144 </code></pre> <p>This is another file <code>sample.csv</code>:</p> <pre><code>M11435TDS144,STB#1,Router#1 M11543TH4292,STB#2,Router#1 M11509TD9937,STB#3,Router#1 M11543TH4258,STB#4,Router#1 </code></pre> <p>Can I ...
0
2016-09-28T05:45:22Z
39,741,529
<p>The solution using <code>csv.reader</code> and <code>csv.writer</code> (<code>csv</code> module):</p> <pre><code>import csv newLines = [] # change the file path to the actual one with open('./data/result.csv', newline='\n') as csvfile: data = csv.reader(csvfile) items = [''.join(line) for line in data] wi...
0
2016-09-28T08:06:33Z
[ "python", "append" ]
Python file matching and appending
39,738,915
<p>This is one file <code>result.csv</code>:</p> <pre><code>M11251TH1230 M11543TH4292 M11435TDS144 </code></pre> <p>This is another file <code>sample.csv</code>:</p> <pre><code>M11435TDS144,STB#1,Router#1 M11543TH4292,STB#2,Router#1 M11509TD9937,STB#3,Router#1 M11543TH4258,STB#4,Router#1 </code></pre> <p>Can I ...
0
2016-09-28T05:45:22Z
39,745,025
<p>With only one column, I wonder why you made it as a <code>result.csv</code>. If it is not going to have any more columns, a simple file read operation would suffice. Along with converting the data from <code>result.csv</code> to dictionary will help in quick run as well.</p> <pre><code>result_file = "result.csv" sa...
0
2016-09-28T10:36:03Z
[ "python", "append" ]
Followup : missing required Charfield in django Modelform is saved as empty string and do not raise an error
39,739,029
<p>If I try to save incomplete model instance in Django 1.10, I would expect Django to raise an error. It does not seem to be the case.</p> <p>models.py:</p> <pre><code>from django.db import models class Essai(models.Model): ch1 = models.CharField(max_length=100, blank=False) ch2 = models.CharField(max_lengt...
3
2016-09-28T05:54:37Z
39,739,820
<p>As the two fields <code>ch1</code> and <code>ch2</code> are always required in your case, all you need to do is modify your model such that </p> <pre><code>from django.db import models class Essai(models.Model): ch1 = models.CharField(max_length=100) ch2 = models.CharField(max_length=100) </code></pre> <p...
0
2016-09-28T06:41:36Z
[ "python", "mysql", "django", "validation", "django-models" ]
Followup : missing required Charfield in django Modelform is saved as empty string and do not raise an error
39,739,029
<p>If I try to save incomplete model instance in Django 1.10, I would expect Django to raise an error. It does not seem to be the case.</p> <p>models.py:</p> <pre><code>from django.db import models class Essai(models.Model): ch1 = models.CharField(max_length=100, blank=False) ch2 = models.CharField(max_lengt...
3
2016-09-28T05:54:37Z
39,739,906
<p>There is a slightly notable difference in model and it's forms. Model.save() performs no validation. So if it fails then probably it raises a database level IntegrityError. For reducing risks of failure at database layer one need to call Model.full_clean() which is also done by ModelForm as documented here in <a hre...
0
2016-09-28T06:46:13Z
[ "python", "mysql", "django", "validation", "django-models" ]
Fetching data till the end instead of using multiple next(v)[1]
39,739,093
<p>Hi i have a python code that grab data from sample_data.csv before parsing them into out.csv.</p> <p>Do see the image for better visualisation of sample_data.csv <a href="http://i.imgur.com/wwi4RC7.jpg" rel="nofollow">http://i.imgur.com/wwi4RC7.jpg</a></p> <p>My question is how do i start from the the last next(v)...
2
2016-09-28T05:59:26Z
39,739,684
<p>If I understand the question correctly, you could use a list comprehension to finish reading values in v , like that :</p> <pre><code>transaction = [ x[1] for x in v ] </code></pre> <p>That code will be like grabing all remaining <code>next(v)[1]</code> until the end of v.</p> <p><strong>Side note</strong> : cal...
1
2016-09-28T06:34:42Z
[ "python", "csv" ]
Conditional addition of different values to an array using python
39,739,215
<p>I want to add 10 if <code>x &lt; 50</code>, 20 if <code>50 &lt;= x &lt; 100</code>, 30 if <code>100 &lt;= x &lt; 150</code>, and 40 for <code>150 &lt;= x &lt; 200</code>. How can I solve this problem? In my array <code>arr</code> I have more than 300 data element. Thanks in advance for your kind co-operation. </p>...
-2
2016-09-28T06:07:54Z
39,741,356
<p>It seems a little bit like a homework exercise? I'd explicitly split out the modifications you need to make so it's easy to see what it's doing. Please note: I did not input ALL your rules, just some, so you can see how you could extend it.</p> <pre><code>x=[10,20,30,40,50,60,70,80,90,100,120,130,140,150,160,170,18...
1
2016-09-28T07:56:56Z
[ "python", "arrays", "conditional", "add" ]
virtualenv hanging forever pythonanywhere
39,739,224
<p>I am trying to follow this <a href="https://tutorial.djangogirls.org/en/deploy/" rel="nofollow">tutorial</a> to get a django application up on pythonanywhere, but when trying to create a virtual environment using </p> <pre><code> virtualenv --python=python3.5 myvenv </code></pre> <p>The console hangs</p> <p>I ha...
0
2016-09-28T06:08:21Z
39,739,408
<p>General practice is to reference the python binary directly, run virtualenv as a module, and specify the directory in which to place the virtualenv. For your example above:</p> <pre><code>/path/to/python/bin/python3.5 -m virtualenv myvenv </code></pre> <p>This will create the virtual environment in myvenv, running...
0
2016-09-28T06:20:14Z
[ "python", "virtualenv", "pythonanywhere" ]