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 date time get the current time but with seconds and hour and minute
38,036,699
<p>I am able to get the current time as this:</p> <pre><code>import datetime str(datetime.date.today().strftime("%Y-%m-%d")) </code></pre> <p>that prints</p> <blockquote> <p>2016-06-26</p> </blockquote> <p>but i need to add the minutes and seconds and hour</p> <p>i search on internet and people are suggesting us...
0
2016-06-26T08:38:59Z
38,036,735
<p>Use</p> <pre><code>&gt;&gt;&gt; datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") '2016-06-26 14:15:44' </code></pre> <p>You can even use <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.today" rel="nofollow"><code>.today()</code></a> instead of <a href="https://docs.python.org/2/libr...
2
2016-06-26T08:43:02Z
[ "python", "python-2.7", "datetime" ]
python date time get the current time but with seconds and hour and minute
38,036,699
<p>I am able to get the current time as this:</p> <pre><code>import datetime str(datetime.date.today().strftime("%Y-%m-%d")) </code></pre> <p>that prints</p> <blockquote> <p>2016-06-26</p> </blockquote> <p>but i need to add the minutes and seconds and hour</p> <p>i search on internet and people are suggesting us...
0
2016-06-26T08:38:59Z
38,036,736
<p><code>datetime.date</code> only takes care of the date, you need to use <code>datetime.datetime</code>.</p>
1
2016-06-26T08:43:11Z
[ "python", "python-2.7", "datetime" ]
python date time get the current time but with seconds and hour and minute
38,036,699
<p>I am able to get the current time as this:</p> <pre><code>import datetime str(datetime.date.today().strftime("%Y-%m-%d")) </code></pre> <p>that prints</p> <blockquote> <p>2016-06-26</p> </blockquote> <p>but i need to add the minutes and seconds and hour</p> <p>i search on internet and people are suggesting us...
0
2016-06-26T08:38:59Z
38,036,749
<p>You are using the datetime.date object which doesn't contain any time.</p> <p>You need to use 'datetime.datetime.now()'</p>
1
2016-06-26T08:45:06Z
[ "python", "python-2.7", "datetime" ]
python date time get the current time but with seconds and hour and minute
38,036,699
<p>I am able to get the current time as this:</p> <pre><code>import datetime str(datetime.date.today().strftime("%Y-%m-%d")) </code></pre> <p>that prints</p> <blockquote> <p>2016-06-26</p> </blockquote> <p>but i need to add the minutes and seconds and hour</p> <p>i search on internet and people are suggesting us...
0
2016-06-26T08:38:59Z
38,036,799
<p>Try this: will return a String with Hour,Minutes and Seconds</p> <pre><code>datetime.datetime.now()..strftime("%Y-%m-%d %H:%M:%S") </code></pre>
0
2016-06-26T08:53:50Z
[ "python", "python-2.7", "datetime" ]
How can I tell what value my function is returning in Python?
38,036,781
<p>I'm trying to debug this program I wrote. How can I tell if, for a given <em>word</em>, <em>hand</em>, and <em>word_list</em>, it returns True or False? I tried initializing a variable <strong>failure</strong> and then modifying it and printing it's value. It isn't printing, so I don't know if it is behaving like it...
0
2016-06-26T08:50:07Z
38,036,814
<p>The reason why it is not printing out is because you are returning the function before it <code>print</code>s. This means that the program stops before it reaches the <code>print</code> statement. For example:</p> <pre><code>def foo(x): return x print x foo("asdf") </code></pre> <p>Will return nothing whi...
4
2016-06-26T08:56:05Z
[ "python", "dictionary", "boolean", "value" ]
How can I tell what value my function is returning in Python?
38,036,781
<p>I'm trying to debug this program I wrote. How can I tell if, for a given <em>word</em>, <em>hand</em>, and <em>word_list</em>, it returns True or False? I tried initializing a variable <strong>failure</strong> and then modifying it and printing it's value. It isn't printing, so I don't know if it is behaving like it...
0
2016-06-26T08:50:07Z
38,036,844
<p>You can print the result directly <code>print is_valid_word(word,hand2,load_words())</code></p>
1
2016-06-26T09:00:28Z
[ "python", "dictionary", "boolean", "value" ]
How can I tell what value my function is returning in Python?
38,036,781
<p>I'm trying to debug this program I wrote. How can I tell if, for a given <em>word</em>, <em>hand</em>, and <em>word_list</em>, it returns True or False? I tried initializing a variable <strong>failure</strong> and then modifying it and printing it's value. It isn't printing, so I don't know if it is behaving like it...
0
2016-06-26T08:50:07Z
38,036,904
<p>You have some indentation issues, and doing something <strong>after</strong> a return statement is futile.</p> <p>You don't need to use <code>keys</code> or <code>iterkeys</code> the <code>in</code> operator will check for you, and will work with lists, set, dicts (keys), tuples, strings, ...</p> <p>The <code>in</...
0
2016-06-26T09:08:46Z
[ "python", "dictionary", "boolean", "value" ]
How to pythonically make a total count of all counts in a list of objects?
38,036,985
<p>I've got a list of objects which have a <code>.count()</code> method. I now want a total count of all objects. The following works:</p> <pre><code>count = 0 for the_obj in obj_list: count += the_obj.count() print count </code></pre> <p>but I've got the feeling that there are more Pythonic ways of doing this. A...
1
2016-06-26T09:20:37Z
38,036,996
<p>You can use the built-in <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum()</code></a> with a generator to sum the individual counts. </p> <pre><code>count = sum(obj.count() for obj in obj_list) </code></pre> <p>Alternatively (<em>although not necessary</em>), a functional ap...
5
2016-06-26T09:22:21Z
[ "python", "python-2.7", "count" ]
PygraphViz Import Error With PyCharm
38,037,013
<p>I believe I have installed pygraphviz on my Debian build. I can import it if I run Python from the command line:</p> <pre><code>jon@debian:~/anaconda3/bin$ ipython Python 3.5.1 |Continuum Analytics, Inc.| (default, Dec 7 2015, 11:17:45) Type "copyright", "credits" or "license" for more information. IPython 4.1.2...
10
2016-06-26T09:25:20Z
38,206,220
<p><a href="https://www.jetbrains.com/help/pycharm/2016.1/quick-start-guide.html#init" rel="nofollow">This guide</a> should help you configuring everything including custom paths to your libraries. </p> <p>The interpreter is ok, it is already pointing to Anaconda's distribution. But under "Default Project" settings th...
3
2016-07-05T14:36:47Z
[ "python", "pycharm", "anaconda", "graphviz", "pygraphviz" ]
How to wait for a particular time interval for an event in pygame?
38,037,077
<p>Here is a basic pygame code-</p> <pre><code>import pygame screen = pygame.display.set_mode((800,600)) try: while True: e = pygame.event.wait() if e.type == pygame.QUIT: raise StopIteration if e.type == pygame.MOUSEBUTTONDOWN: if e.type == pygame.MOUSEBUTTONUP: ...
0
2016-06-26T09:34:14Z
38,037,117
<p>You could use <code>sleep()</code>. </p> <p>For example: </p> <pre><code>import time time.sleep(5) </code></pre> <p><a href="http://www.tutorialspoint.com/python/time_sleep.htm" rel="nofollow">Link</a></p>
0
2016-06-26T09:39:29Z
[ "python", "pygame" ]
How to wait for a particular time interval for an event in pygame?
38,037,077
<p>Here is a basic pygame code-</p> <pre><code>import pygame screen = pygame.display.set_mode((800,600)) try: while True: e = pygame.event.wait() if e.type == pygame.QUIT: raise StopIteration if e.type == pygame.MOUSEBUTTONDOWN: if e.type == pygame.MOUSEBUTTONUP: ...
0
2016-06-26T09:34:14Z
38,037,303
<p>You can try to use <code>time.time()</code> method of <code>time</code> module. It returns the current time in referenced to epoch as mentioned <a href="https://docs.python.org/2/library/time.html" rel="nofollow">here</a>.</p> <blockquote> <p><code>time.time()</code></p> <p>Return the time in seconds since t...
0
2016-06-26T10:01:36Z
[ "python", "pygame" ]
Parse json from array values
38,037,142
<p>I currently pass the "buttons" to somefunction as two separate parameters, like so:</p> <pre><code>button1 = {"title": "foo", "url": "bar" /.../ } button2 = {"title": "foo", "url": "bar" /.../ } somefunction(id, text, button1, button2) def somefunction(recipient_id, message_text, button1, button2): data = json...
0
2016-06-26T09:41:37Z
38,037,298
<p>You can send a JSON containing a list of 'buttons':</p> <pre><code>{ "buttons" : [ {"title": "foo", "url": "bar" /.../ }, {"title": "foo", "url": "bar" /.../ } ] } </code></pre> <p>and then parse it in <code>somefunction</code></p>
0
2016-06-26T10:01:07Z
[ "python" ]
Parse json from array values
38,037,142
<p>I currently pass the "buttons" to somefunction as two separate parameters, like so:</p> <pre><code>button1 = {"title": "foo", "url": "bar" /.../ } button2 = {"title": "foo", "url": "bar" /.../ } somefunction(id, text, button1, button2) def somefunction(recipient_id, message_text, button1, button2): data = json...
0
2016-06-26T09:41:37Z
38,037,391
<p>You could use keyword-only arguments (only works if you are using python 3) along with keyword-argument unpacking to achieve this:</p> <pre><code>import json def somefunction(recipient_id, message_text, *, button1, button2): return json.dumps({ "recipient": { "id": recipient_id }, ...
0
2016-06-26T10:09:44Z
[ "python" ]
Zero padding zfill function bug?
38,037,288
<p>I have noticed that <code>str.zfill(x)</code> can return a string which is smaller than `x characters. For example: </p> <pre><code>&gt;&gt;&gt; "%.2x".zfill(8) % 255 '0000ff' &gt;&gt;&gt; "%.2x".zfill(8) % 256 '0000100' </code></pre> <p>How is this strange behavior explained?</p>
-1
2016-06-26T09:59:57Z
38,037,307
<p>The behaviour is correct. <code>zfill(x)</code> itself always return a string that is at least as long as the original string and with at least <code>x</code> characters. <strong>It's <code>%</code> that is shortening it</strong> by replacing <code>%.2f</code> with a shorter string:</p> <pre><code>&gt;&gt;&gt; "%.2...
3
2016-06-26T10:01:56Z
[ "python" ]
How to process locally withdrawn data from Django REST Framework in Select2?
38,037,493
<p>I'm trying to process results I get from Django REST Framework in select2 plugin according examples they have on their site, but only I get is:</p> <p><a href="http://i.stack.imgur.com/uix3A.png" rel="nofollow"><img src="http://i.stack.imgur.com/uix3A.png" alt="enter image description here"></a></p> <p>I.e. unclic...
0
2016-06-26T10:22:48Z
38,475,938
<p>You should provide object with <code>id</code> and <code>text</code> property in order for Select2 to work properly. </p> <p>So your code should be updated to something like that: </p> <pre><code> $(".js-data-example-ajax").select2({ ajax: { ... data: function (term) { return { ...
0
2016-07-20T08:17:44Z
[ "javascript", "python", "django", "rest", "select2" ]
Python list comprehension and variable creation
38,037,541
<p>I am trying to make a variable 'listy' that stores all possible combinations of the numbers 6 , 9 and 20 in a given range.</p> <p>I started with all numbers that are bigger than 5 and are divisible by 3 , then to this list I added a new list containing each element of the first list +20 and repeated the process one...
0
2016-06-26T10:29:13Z
38,037,671
<p>You can try:</p> <pre><code>&gt;&gt;&gt; [i for j in map(lambda x: (x, x+20, x+40), [x for x in range(6,100) if x % 3 == 0]) for i in j] [6, 26, 46, 9, 29, 49, 12, 32, 52, 15, 35, 55, 18, 38, 58, 21, 41, 61, 24, 44, 64, 27, 47, 67, 30, 50, 70, 33, 53, 73, 36, 56, 76, 39, 59, 79, 42, 62, 82, 45, 65, 85, 48, 68, 88,...
0
2016-06-26T10:43:54Z
[ "python", "python-3.x", "list-comprehension" ]
Python list comprehension and variable creation
38,037,541
<p>I am trying to make a variable 'listy' that stores all possible combinations of the numbers 6 , 9 and 20 in a given range.</p> <p>I started with all numbers that are bigger than 5 and are divisible by 3 , then to this list I added a new list containing each element of the first list +20 and repeated the process one...
0
2016-06-26T10:29:13Z
38,037,703
<p>You can note that any number larger than 43 is possible to represent with combination of 3, 5 and 20 (it's not too hard to prove). And only numbers not more than 43 which needs 20 are 26, 29, 32, 35, 38, 41. So basically you can either hardcode all suitable values:</p> <pre><code>listy = [x in [6, 9, 12, 15, 18, 21...
0
2016-06-26T10:47:44Z
[ "python", "python-3.x", "list-comprehension" ]
Facebook Ads of the last 7 days
38,037,572
<p>I want to show the Facebook ads that have been active on the last 7 days. The following code shows me a certain campaign but I need all the campaigns.</p> <pre><code>today = datetime.date.today() start_time = str(today - datetime.timedelta(days=7)) end_time = str(today) campaign = Campaign(campaign_id) params = { ...
1
2016-06-26T10:31:50Z
38,201,090
<p>On account level there is a method called get_campaigns. What you have to do is get the campaigns and fetch the insights for each of them. </p> <pre><code>campaigns = account.get_campaigns() insights = {camp['id']:camp.get_insights(params=params)[0] for camp in campaigns} </code></pre> <p>Then you may want to sort...
0
2016-07-05T10:28:48Z
[ "python", "facebook", "ads", "facebook-marketing-api" ]
pop from empty list error in car app
38,037,657
<p>I'm mostly new to this so apologies in advance if the answer is blindingly obvious to this. For a school assignment (and out of interest also) I'm building a sort of basic car app that uses lists to store cars (objects) as they are made then a separate list to record cars that are rented.</p> <p>The rent process wo...
0
2016-06-26T10:42:36Z
38,037,796
<p>The problem is that you are passing an empty list through the <code>rental_system</code> method to the <code>rented</code> method. </p> <p>You have defined <code>rentedcars = []</code> in <code>rental_system</code> method and without modifying it you are trying to pop from it in the <code>rented</code> method.</p> ...
1
2016-06-26T10:58:12Z
[ "python", "python-2.7" ]
Python yahoo-finance package ImportError: cannot import name Share
38,037,688
<p>I am using Python2.7 and I try to use python yahoo-finance package on mac to get some data</p> <pre><code>from yahoo_finance import Share yahoo = Share('YHOO') print yahoo.get_open() </code></pre> <p>but it shows error message: "ImportError: cannot import name Share"</p> <p>I use sudo pip install to install yahoo...
0
2016-06-26T10:46:16Z
38,909,813
<p><a href="http://i.stack.imgur.com/BC9Hc.png" rel="nofollow"><img src="http://i.stack.imgur.com/BC9Hc.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/lUWul.png" rel="nofollow"><img src="http://i.stack.imgur.com/lUWul.png" alt="enter image description here"></a> If you chekc pypi...
0
2016-08-12T04:15:27Z
[ "python" ]
Find same sequence in two strings
38,037,734
<p>I have two sets of hex data:</p> <pre><code>01 9b 09 45 00 00 b1 21 b1 2e 56 58 16 b9 bb 57 a1 cb 14 5f 66 33 fc 8e 22 6b 78 d9 d0 0f 06 e8 14 ee e5 66 57 75 f4 fe ca 23 5d 17 40 c7 f8 a7 f8 6b c9 e5 64 0c d7 1b 6e cf 76 31 50 03 6f 5b 14 78 90 bf d1 55 47 60 41 a8 f6 40 d6 59 ff 38 76 80 f9 83 db f8 a6 e5 d1 77 14...
0
2016-06-26T10:50:53Z
38,037,912
<pre><code>a = "01 9b 09 45 00 00 b1 21 b1 2e 56 58 16 b9 bb 57 a1 cb 14 5f 66 33 fc 8e 22 6b 78 d9 d0 0f 06 e8 14 ee e5 66 57 75 f4 fe ca 23 5d 17 40 c7 f8 a7 f8 6b c9 e5 64 0c d7 1b 6e cf 76 31 50 03 6f 5b 14 78 90 bf d1 55 47 60 41 a8 f6 40 d6 59 ff 38 76 80 f9 83 db f8 a6 e5 d1 77 14 59 c7 d7 51 5c b9 0e 1a ed c2 d...
1
2016-06-26T11:10:56Z
[ "python", "sequence" ]
Find same sequence in two strings
38,037,734
<p>I have two sets of hex data:</p> <pre><code>01 9b 09 45 00 00 b1 21 b1 2e 56 58 16 b9 bb 57 a1 cb 14 5f 66 33 fc 8e 22 6b 78 d9 d0 0f 06 e8 14 ee e5 66 57 75 f4 fe ca 23 5d 17 40 c7 f8 a7 f8 6b c9 e5 64 0c d7 1b 6e cf 76 31 50 03 6f 5b 14 78 90 bf d1 55 47 60 41 a8 f6 40 d6 59 ff 38 76 80 f9 83 db f8 a6 e5 d1 77 14...
0
2016-06-26T10:50:53Z
38,038,106
<pre><code>import itertools def same_string(str1, str2): set1 = set(str1[begin:end] for (begin, end) in itertools.combinations(range(len(str1)+1), 2)) set2 = set(str2[begin:end] for (begin, end) in itertools.combinations(range(len(str2)+1), 2)) common = set1.intersection(set2) m...
0
2016-06-26T11:34:54Z
[ "python", "sequence" ]
Find same sequence in two strings
38,037,734
<p>I have two sets of hex data:</p> <pre><code>01 9b 09 45 00 00 b1 21 b1 2e 56 58 16 b9 bb 57 a1 cb 14 5f 66 33 fc 8e 22 6b 78 d9 d0 0f 06 e8 14 ee e5 66 57 75 f4 fe ca 23 5d 17 40 c7 f8 a7 f8 6b c9 e5 64 0c d7 1b 6e cf 76 31 50 03 6f 5b 14 78 90 bf d1 55 47 60 41 a8 f6 40 d6 59 ff 38 76 80 f9 83 db f8 a6 e5 d1 77 14...
0
2016-06-26T10:50:53Z
38,126,835
<p>Python standard library module <code>difflib</code> has a class <code>SequenceMatcher</code> which can be used to extract common substrings.<br> The first argument to the class is a function which takes one argument and returns boolean value. It is used to ignore chracters in the string. Second argument is the first...
0
2016-06-30T14:59:02Z
[ "python", "sequence" ]
How can I convert a simple image from the disk to OpenCV mat file?
38,037,741
<p>I need to send the image with RabbitMQ and the only way I found is:</p> <pre><code>f = open("asd.jpg","rb") img = f.read() f.close() </code></pre> <p>Than I can send the <code>img</code>.</p> <p>I would like to process the sent image where I received it so how can I convert it to an OpenCV mat file?</p> <p>Here ...
0
2016-06-26T10:51:55Z
38,051,567
<p>So after a few tries I managed to <strong>solve</strong> my problem.</p> <p>This is how I did it:</p> <pre><code>#Read the image as binary f = open("picture.jpg","rb") rawImg= f.read() f.close() #Convert the raw image to a numpy array for further processing npImage = np.fromstring(rawImg, dtype='uint8') #Convert ...
0
2016-06-27T10:26:40Z
[ "python", "opencv", "rabbitmq" ]
Problems with removing constant features using standard deviation python pandas
38,037,798
<p>I've got a dataset with approximately 2 million rows and 50 columns</p> <p>I know some of these columns have constant data values - e.g. all rows in that column have the same value</p> <p>Therefore I thought I would be able to find all constant columns using:</p> <pre><code>for col in data.columns: print data...
0
2016-06-26T10:58:18Z
38,037,942
<p>For example taken from <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow">link</a>:</p> <pre><code>&gt;&gt;&gt; 0.1 + 0.2 0.30000000000000004 </code></pre> <p>Why is that? 1/10 and 2/10 are not exactly representable as a binary fraction. Almost all machines today (July 2010) use IEEE-75...
0
2016-06-26T11:15:13Z
[ "python", "pandas", "data-cleaning" ]
Problems with removing constant features using standard deviation python pandas
38,037,798
<p>I've got a dataset with approximately 2 million rows and 50 columns</p> <p>I know some of these columns have constant data values - e.g. all rows in that column have the same value</p> <p>Therefore I thought I would be able to find all constant columns using:</p> <pre><code>for col in data.columns: print data...
0
2016-06-26T10:58:18Z
38,037,966
<p>That seems like a <a href="http://floating-point-gui.de/" rel="nofollow">floating point issue</a>. </p> <p>You can use numpy's <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html" rel="nofollow"><code>isclose</code></a> to check whether the standard deviation is close to zero. Howeve...
1
2016-06-26T11:18:27Z
[ "python", "pandas", "data-cleaning" ]
Debug and Release Build Strategy for Python Projects
38,037,801
<p>I have a piece of software (2100 SLOC) that I consider to run in two different versions: one version provides verbose debug information to the console and the other version is an optimized release version.</p> <p>My goal is to have a single <code>git</code> branch to maintain. Is there a way to mark the debug parts...
1
2016-06-26T10:58:57Z
38,037,943
<p>I found an answer <a href="http://stackoverflow.com/a/561338/1103558">here</a>:</p> <blockquote> <pre><code>if __debug__: doSomething() </code></pre> </blockquote> <p>To set <code>__debug__</code> to <code>false</code> requires you to run Python with either flag <code>-O</code> or <code>-OO</code></p>
0
2016-06-26T11:15:40Z
[ "python", "python-2.7", "build", "interpreter", "compiler-optimization" ]
Debug and Release Build Strategy for Python Projects
38,037,801
<p>I have a piece of software (2100 SLOC) that I consider to run in two different versions: one version provides verbose debug information to the console and the other version is an optimized release version.</p> <p>My goal is to have a single <code>git</code> branch to maintain. Is there a way to mark the debug parts...
1
2016-06-26T10:58:57Z
38,038,051
<p>I think you are overcomplicating this. You should ideally not have different code paths for development and production environments, just different configuration, otherwise it becomes harder to be sure whether your tests actually reflect how the code will behave when deployed. Things like profiling and debugging the...
1
2016-06-26T11:28:42Z
[ "python", "python-2.7", "build", "interpreter", "compiler-optimization" ]
Running a scrapy app in Heroku throws error
38,037,873
<p>Trying to run a Scrapy app in Heroku using</p> <pre><code>heroku run scrapy crawl spider </code></pre> <p>returns</p> <pre><code>File "/app/.heroku/python/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 76, in wrapper ffi.def_extern(name=name, **kwargs)(func) AttributeError: 'Co...
0
2016-06-26T11:06:33Z
38,065,326
<p>This error means the wrong version of cffi is installed. Try upgrading it to the latest version (or at least 1.4+) and this problem should go away.</p>
0
2016-06-28T00:40:25Z
[ "python", "heroku", "scrapy" ]
Mapping fields on Python
38,037,881
<p>I'm trying to re-map a certain field in Python, but not sure how to go about it. The topic is regarding gravitational lensing. So what i've done upto now is obtain a deflection field, which tells you how light is bent around masses.<a href="http://i.stack.imgur.com/aQeLH.png" rel="nofollow">Deflection Field Map</a> ...
1
2016-06-26T11:07:34Z
38,039,603
<p>Figured it out, just simply had to subtract directly from the np.meshgrid and then replot I with respect to the new coordinate system. Guess I just got confused because of all the components involved. Thanks for your help!</p>
1
2016-06-26T14:40:00Z
[ "python", "numpy" ]
How do you run a python program in visual studio
38,037,951
<p>Whenever I hit the <strong>f5 key</strong> to run a program a new file called <code>launch.json</code> opens and I don't know what to do from there. Does anyone know hat to do and no this is no the same as how do I install python for visual studio. This is what <code>launch.json</code> looks like.</p> <pre><code>{ ...
0
2016-06-26T11:16:23Z
39,692,868
<p>I guess you meant VS Code. If that's the case, this is an auto generated file where you can configure what will happen when you press <code>F5</code>. If you save that file as is and then switch back to your <code>main.py</code> or whatever python file you want to debug and press again <code>F5</code> you will start...
0
2016-09-25T23:40:14Z
[ "python", "json" ]
Executing program again, once finished (Python)
38,037,957
<p>So I'm writing this little piece of code as a small project: It uses the turtle graphics module to draw various shapes. It picks which shape to draw by way of the random module. Here's the code.</p> <pre><code>import time import sys import random import os from turtle import * while True: value = 0 def f()...
1
2016-06-26T11:17:21Z
38,038,054
<p>The first time you launch your program, you set your <code>random</code> variable with <code>random.choice()</code> it work because the variable <code>random</code> isn't created before you call <code>random.choice()</code>. However, the seconde time, your variable <code>random</code> is a string and when you try to...
0
2016-06-26T11:28:46Z
[ "python", "random", "attributes", "restart" ]
Executing program again, once finished (Python)
38,037,957
<p>So I'm writing this little piece of code as a small project: It uses the turtle graphics module to draw various shapes. It picks which shape to draw by way of the random module. Here's the code.</p> <pre><code>import time import sys import random import os from turtle import * while True: value = 0 def f()...
1
2016-06-26T11:17:21Z
38,038,055
<p>You're relying on <code>random</code> to be the <code>random</code> module, which has a function <code>choice</code>. The first time you call it, you assign its result, one of the characters in <code>'123456'</code>, to the name <code>random</code>, thus making the name <code>random</code> no longer point to the <co...
1
2016-06-26T11:28:48Z
[ "python", "random", "attributes", "restart" ]
No python interpreter found. Abort - Opscenter
38,038,038
<p>Just want to ask on what possibilities to check on our opscenter rpm. we are getting this error when starting the opscenter</p> <pre><code>[opscenter@mybox]$ sudo /etc/init.d/opscenterd start Starting Cassandra cluster manager opscenterd Starting opscenterdNo python interpreter found. Abort. [opscenter@mybox start-...
0
2016-06-26T11:27:13Z
38,060,469
<blockquote> <p>not sure how to make the opscenter point it on this location</p> </blockquote> <p>Since this is your specific question, I'll echo my comment here as an answer.</p> <p>You can set <code>PYTHON</code> to your python interpreter prior to running the opscenter init script. This will bypass the check for...
1
2016-06-27T18:08:39Z
[ "python", "path", "opscenter" ]
Pandas Groupby TimeGrouper and apply
38,038,090
<p>As per <a href="http://stackoverflow.com/questions/38032495/reset-pandas-series-rolling-on-a-daily-basis/38032579#38032579">this</a> question. This groupby works when applied to my <code>df</code> for a <code>pd.rolling_mean</code> column as follows: </p> <pre><code>data['maFast']=data['Last'].groupby(pd.TimeGroup...
1
2016-06-26T11:32:54Z
38,038,189
<p>I think you need function <code>lambda</code>:</p> <pre><code>data['maSlow_std']=data['Last'].groupby(pd.TimeGrouper('d')) .apply(lambda x: pd.rolling_mean(x, window=60) + 2* pd.rolling_std(x, 20, min_periods=20)) </code></pre> <p>If <cod...
1
2016-06-26T11:44:18Z
[ "python", "pandas", "dataframe", "group-by" ]
Python return several value to add in the middle of a list
38,038,123
<p>Is it possible to make a function that returns several elements like this:</p> <pre><code>def foo(): return 'b', 'c', 'd' print ['a', foo(), 'e'] # ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>I tried this but it doesn't work</p>
2
2016-06-26T11:36:25Z
38,038,151
<p>You can insert a sequence into a list with a slice assignment:</p> <pre><code>bar = ['a', 'e'] bar[1:1] = foo() print bar </code></pre> <p>Note that the slice is essentially empty; <code>bar[1:1]</code> is an empty list between <code>'a'</code> and <code>'e'</code> here.</p> <p>To do this on one line in Python 2 ...
9
2016-06-26T11:39:23Z
[ "python" ]
Python return several value to add in the middle of a list
38,038,123
<p>Is it possible to make a function that returns several elements like this:</p> <pre><code>def foo(): return 'b', 'c', 'd' print ['a', foo(), 'e'] # ['a', 'b', 'c', 'd', 'e'] </code></pre> <p>I tried this but it doesn't work</p>
2
2016-06-26T11:36:25Z
38,038,280
<p>You can also use this simple piece of code:</p> <pre><code>import itertools def foo(): return 'b', 'c', 'd' l = ['a', foo(), 'e'] x=list(itertools.chain(*l)) print x </code></pre> <blockquote> <p>Output: ['a', 'b', 'c', 'd', 'e']</p> </blockquote>
-2
2016-06-26T11:55:17Z
[ "python" ]
python :Read from a USB HID device
38,038,129
<p>I have a USB RFID device that appears on /dev/hidraw for my serial devices they appear on /dev/ttyUSB* i used pyserial and it works like charm but for this one i couldn't read from it using <code>cat /dev/hidraw0</code> need root privileges plus i need to read one line and not keep on listening </p> <p>I used evde...
0
2016-06-26T11:37:19Z
38,038,467
<p>By <a href="https://python-evdev.readthedocs.io/en/latest/apidoc.html#evdev.util.list_devices" rel="nofollow">default</a> evdev.list_devices() look only to /dev/input</p> <p>And you need permissions to work with your device. You can add your user to group which own your device (see $ ls -l /dev/hidraw0 )</p> <p>Th...
1
2016-06-26T12:19:53Z
[ "python", "linux", "usb", "device", "hid" ]
python manage.py runserver error django.core.exceptions.ImproperlyConfigured: T
38,038,133
<p>I started learning a Django tutorial , and when I want to run </p> <pre><code>python manage.py runserver </code></pre> <p>there is a lots of error Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/sarfraz/.local/lib/python2.7/site-packages/dj...
-1
2016-06-26T11:37:47Z
38,038,178
<p>Add a comma to the end of the value closed between parenthesis otherwise it is not a <code>tuple</code>:</p> <p><code>TEMPLATE_DIRS = ( "/home/sarfraz/django/crepes_bretonnes/templates/", )</code></p> <p>it should solve the issue. Hope that it helps.</p>
1
2016-06-26T11:43:17Z
[ "python", "django", "django-manage.py" ]
django fail to create project
38,038,256
<p>I want to use the DjangoCMS 3.3 version to create a new project. I use the following guide <a href="http://docs.django-cms.org/en/release-3.3.x/introduction/install.html" rel="nofollow">http://docs.django-cms.org/en/release-3.3.x/introduction/install.html</a></p> <p>but when running the the command </p> <pre><code...
0
2016-06-26T11:52:44Z
38,038,309
<p>It may be the problem that <code>djangocms</code> cannot recognize the path with spaces. Change your project path without any space. </p>
1
2016-06-26T11:57:52Z
[ "python", "django", "content-management-system" ]
How can I over-write a string in a file using python?
38,038,378
<p>So I have a text file (called 'Numbers') which looks like this: </p> <pre><code>1 - 2 - 3 - 8 - 5 - 6 1 - 2 - 3 - 4 - 5 - 6 1 - 2 - 3 - 4 - 5 - 6 1 - 2 - 3 - 4 - 5 - 6 </code></pre> <p>I want to replace the number 8 in the first line with a number 4. How do I do this?<br> So far I've got the following: </p...
1
2016-06-26T12:07:57Z
38,038,757
<p>Text files are problematic to rewrite because they often have variable length records, however yours is fixed length, so:</p> <pre><code>fh = open('gash.txt','r+') # read the first line line = fh.readline() row = line.split(' - ') fourthValue = row[3] newFourthValue = '4' newLine = line.replace(fourthValue, newF...
0
2016-06-26T13:03:50Z
[ "python", "file", "replace", "file-handling", "file-manipulation" ]
How can I over-write a string in a file using python?
38,038,378
<p>So I have a text file (called 'Numbers') which looks like this: </p> <pre><code>1 - 2 - 3 - 8 - 5 - 6 1 - 2 - 3 - 4 - 5 - 6 1 - 2 - 3 - 4 - 5 - 6 1 - 2 - 3 - 4 - 5 - 6 </code></pre> <p>I want to replace the number 8 in the first line with a number 4. How do I do this?<br> So far I've got the following: </p...
1
2016-06-26T12:07:57Z
38,038,761
<p>After reading the first line you need to "rewind" the file so you can overwrite the first line. </p> <pre><code>with open(fname, 'r+') as f: row = f.readline() row = row.replace('8', '4') f.seek(0) f.write(row) </code></pre> <p>Be careful when doing this though, because if the new data isn't <stron...
0
2016-06-26T13:04:26Z
[ "python", "file", "replace", "file-handling", "file-manipulation" ]
Preventing pandas data frame header row from repeating in for statement
38,038,383
<p>I am iterating through pipeline to print out the 20 most informative features for a class called <code>safety</code>. </p> <pre><code>classnum_saf = 3 inds = np.argsort(clf_3.named_steps['clf'].coef_[classnum_saf, :])[-20:] for i in inds: f = feature_names[i] c = clf_3.named_steps['clf'].coef_[classnum_saf, ...
1
2016-06-26T12:09:10Z
38,038,556
<p>I try simulate some data and you can append <code>list</code> to <code>L</code> in each step in loop and last create <code>df</code> from <code>L</code>:</p> <pre><code>L = [] classnum_saf = 3 inds = np.argsort(clf_3.named_steps['clf'].coef_[classnum_saf, :])[-20:] for i in inds: f = feature_names[i] c = clf...
1
2016-06-26T12:33:15Z
[ "python", "for-loop", "pandas", "dataframe", "naivebayes" ]
How to make a digital clock within a status bar in pygame (without tkinter)?
38,038,386
<p>Currently I am doing an assignment for school to create a game in Pygame. I am stuck on the process of creating a clock which determines the; days, hour, and minute. </p> <p>So far I have created some code but my Pygame crashes when ever I run it. I know this is probably a bit nooby but I would really appreciate so...
0
2016-06-26T12:09:52Z
38,039,657
<p>Your problem is: </p> <pre><code>while Time==0: # &lt;--- here time.sleep(1) # ... </code></pre> <p>You initialize <code>Time</code> with <code>0</code> but you never change it's value. That causes an endless loop.</p>
0
2016-06-26T14:46:16Z
[ "python", "python-2.7", "pygame", "clock", "pygame-clock" ]
File size increases after converting from .mat files to .txt files
38,038,393
<p>I have a lot of .mat files which contain the information about the radial part of some different wavefunctions and some other information about an atom. Now I successfully extracted the wavefunction part and using numpy.savetxt() to save it into .txt file. But the size of the file increases so much: After I ran </p>...
1
2016-06-26T12:10:46Z
38,038,657
<p><code>.mat</code> is a binary format whereas <code>numpy.savetxt()</code> writes a plain text file. The binary representation of a double precision number (IEEE 754 double precision) takes 8 bytes. By default, numpy saves this as plain text in the format <code>0.000000000000000000e+00</code> resulting in 24 bytes.</...
3
2016-06-26T12:50:58Z
[ "python", "numpy", "filesize", "file-type", "mat" ]
pandas read excel as formatted
38,038,428
<p>how do i get the values of a spreadsheet as they are formatted? im working on spreadsheets with a currency format</p> <p>this for example:</p> <pre><code>ITEM NAME UNIT PRICE item1 USD 99 item2 SGD 45 </code></pre> <p>but the terms 'USD' and 'SGD' were added using the formatting capabilities of excel, and...
0
2016-06-26T12:15:56Z
38,039,928
<p>There's not any great way to do this. <code>pandas</code> has no knowledge of the number formats, and <code>xlrd</code> doesn't seem to be able to read formats from a .xlsx file - see <a href="http://stackoverflow.com/questions/13892307/python-xlutils-formatting-info-true-not-yet-implemented">here</a></p> <p>You c...
1
2016-06-26T15:13:52Z
[ "python", "excel", "pandas" ]
pandas read excel as formatted
38,038,428
<p>how do i get the values of a spreadsheet as they are formatted? im working on spreadsheets with a currency format</p> <p>this for example:</p> <pre><code>ITEM NAME UNIT PRICE item1 USD 99 item2 SGD 45 </code></pre> <p>but the terms 'USD' and 'SGD' were added using the formatting capabilities of excel, and...
0
2016-06-26T12:15:56Z
38,046,420
<p>to anyone having the same problem, i did it by separating each sheet into CSVs, using this <a href="http://superuser.com/questions/561923/how-can-one-split-an-excel-xlsx-file-that-contains-multiple-sheets-into-sep">answer</a></p> <p>It preserves the currency details as displayed in the spreadsheet, and while a litt...
1
2016-06-27T05:22:52Z
[ "python", "excel", "pandas" ]
Bokeh interactively changing the columns being plotted
38,038,432
<p>I have a large dataset that I want to explore. However I don't want to create multiple plots. I just want a single plot where I can interactively change the columns used for the x and y axis and the plot will update itself. </p> <p>I'm trying to do this with Python/Bokeh using Bokeh to serve my script to a browser....
1
2016-06-26T12:16:05Z
38,100,431
<p>The following script seems to work just fine. It does not use the Bokeh Server but the CustomJS client side style instead.</p> <pre><code>import numpy as np from bokeh.models import ColumnDataSource from bokeh.plotting import Figure from bokeh.models.widgets import Select,TextInput from bokeh.models.layouts impor...
1
2016-06-29T13:03:59Z
[ "python", "plot", "interactive", "bokeh" ]
Other than HTMLTestRunner
38,038,581
<p>I want to generate a report of selenium script which is written in python. I have not used unittest, so is there any other way of generating report other than HTMLTestRunner?</p>
0
2016-06-26T12:38:27Z
38,041,180
<p>You could try <a href="http://pythonhosted.org/behave/" rel="nofollow">behave</a>. Behave has custom formatters. Also see <a href="https://testingbot.com/support/getting-started/behave.html" rel="nofollow">here</a>.</p>
0
2016-06-26T17:25:12Z
[ "python", "selenium" ]
How to replace multiple consecutive duplicate characters
38,038,595
<p>I have a string like this below.</p> <pre><code>aabbccddee </code></pre> <p>I want to replace the duplicate into one character in one line of RegEx to get the following result.</p> <pre><code>abcde </code></pre> <p>I can easily do this by doing</p> <pre><code>input_string = re.sub(ur"a+", u"a", input_string) in...
0
2016-06-26T12:41:13Z
38,038,611
<p>I have found the answer.</p> <pre><code>input_string = re.sub(ur"([a-z])\1+", r"\1", input_string) </code></pre>
1
2016-06-26T12:43:42Z
[ "python", "regex" ]
How to replace multiple consecutive duplicate characters
38,038,595
<p>I have a string like this below.</p> <pre><code>aabbccddee </code></pre> <p>I want to replace the duplicate into one character in one line of RegEx to get the following result.</p> <pre><code>abcde </code></pre> <p>I can easily do this by doing</p> <pre><code>input_string = re.sub(ur"a+", u"a", input_string) in...
0
2016-06-26T12:41:13Z
38,038,673
<p>Using <code>groupby</code> from <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow">itertools</a> <em>(almost copy/pasted from the doc)</em>:</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; ''.join([k for k, g in groupby('aabbccddee')]) abcde </code></p...
1
2016-06-26T12:53:35Z
[ "python", "regex" ]
How to replace multiple consecutive duplicate characters
38,038,595
<p>I have a string like this below.</p> <pre><code>aabbccddee </code></pre> <p>I want to replace the duplicate into one character in one line of RegEx to get the following result.</p> <pre><code>abcde </code></pre> <p>I can easily do this by doing</p> <pre><code>input_string = re.sub(ur"a+", u"a", input_string) in...
0
2016-06-26T12:41:13Z
38,038,685
<p>You could also do this:</p> <pre><code>string = "aabbccddee" print("".join(sorted(set(string), key = string.index))) </code></pre> <p>Output:</p> <pre><code>abcde </code></pre> <p>You could even use <code>OrderedDict</code> here:</p> <pre><code>from collections import OrderedDict string = "aabbccddee" print(""....
0
2016-06-26T12:55:09Z
[ "python", "regex" ]
Python set variable from list to new value without pointing to new location
38,038,700
<p><strong>Short version:</strong></p> <p>If <code>x = [[True], [False]]</code>, and <code>n = x[0]</code>, is it possible/how do I set <code>x[0]</code> to an integer using only <code>n</code>?</p> <p><strong>Long version:</strong></p> <p>I'm trying to write a voxel type script which is using a lot of recursive lis...
0
2016-06-26T12:56:56Z
38,039,031
<p>The best you can do is stop one short when processing the path, so rather than finding <code>cur</code>, you instead find <code>prev</code>. You can then use the last index of <code>path</code> to modify <code>cur</code> within <code>prev</code>. For example:</p> <pre><code>l = [0, [[[2], 0], 0], 0] path = [1, 0,...
0
2016-06-26T13:37:03Z
[ "python" ]
Computationally picking a random point on a n-sphere
38,038,776
<p>I need to randomly pick an n-dimensional vector with length 1. My best idea is to pick a random point in the sphere an normalize it:</p> <pre><code>import random def point(n): sq = 0 v = [] while len(v) &lt; n: x = 1 - 2*random.random() v.append(x) sq = sq + x*x if sq &g...
5
2016-06-26T13:05:12Z
38,038,926
<p>According to <a href="http://mathworld.wolfram.com/HyperspherePointPicking.html" rel="nofollow">Muller, M. E. "A Note on a Method for Generating Points Uniformly on N-Dimensional Spheres"</a> you would need to create a vector of n gaussian random variables and divide by its length: </p> <pre><code>import random imp...
5
2016-06-26T13:26:47Z
[ "python", "random" ]
airflow get result after executing an operator
38,039,045
<p>I have configured airflow and created some Dags and subDags that call several operators.</p> <p>My trouble is that when an operators runs and finishes the job, I'd like to receive the results back in some python structure. For instance:</p> <p><strong>File1.py</strong></p> <pre><code> ... ... sub_dag_one...
0
2016-06-26T13:38:31Z
38,309,783
<p>You can use Hooks for your need. Basically the HiveOperator does the same, he calls Hive Hooks which have multiple methods to work with results.</p> <p>Use a PythonOperator to call a function which then starts a hive hook.</p> <p>Following example might help you.</p> <p>Code Snippet:</p> <pre><code>callHook = Py...
1
2016-07-11T14:41:27Z
[ "python", "hive", "airflow" ]
Interface Error of mysql
38,039,073
<p>I installed mysql <em>connector/python</em> and am using MAMP. When I try to connect to a database,this is what comes up in the terminal :</p> <pre><code>Traceback (most recent call last): File "database.py", line 7, in &lt;module&gt; raise_on_warnings= True) File "/Library/Python/2.7/site-packages/mysql/connec...
0
2016-06-26T13:41:38Z
38,039,109
<p>Remove the port and colon sign from your host:</p> <pre><code> con = mysql.connector.connect(user='root', password ='root', host='localhost', database='testdb', raise_on_warnings= True) </code...
1
2016-06-26T13:46:30Z
[ "python", "mysql", "python-2.7", "mysql-connector" ]
How to know the called program path in C/C++ in Linux?
38,039,278
<p>I am having a compiled C program say <strong><em>test</em></strong> in /usr/bin and a python program say <strong><em>pgm.py</em></strong> is in /opt/python/ . In <strong><em>pgm.py</em></strong> , I am calling the C program like os.system("test arg1 arg2") . Is it possible for the C program to know that it is being ...
0
2016-06-26T14:04:11Z
38,040,155
<p><a href="https://docs.python.org/2/library/os.html" rel="nofollow">Misc operating system interfaces</a> will have the information you want. One way would be to get the python program to write the information to a temp file, and then pass the file as a c-line arg into the C program.</p>
0
2016-06-26T15:37:17Z
[ "python", "c++", "c" ]
How to know the called program path in C/C++ in Linux?
38,039,278
<p>I am having a compiled C program say <strong><em>test</em></strong> in /usr/bin and a python program say <strong><em>pgm.py</em></strong> is in /opt/python/ . In <strong><em>pgm.py</em></strong> , I am calling the C program like os.system("test arg1 arg2") . Is it possible for the C program to know that it is being ...
0
2016-06-26T14:04:11Z
38,040,746
<p>Assuming you're using something akin to Linux, you could use a platform-specific solution. For simplicity, I'm using a Python script <code>test.py</code> in place of a binary.</p> <p><strong>pgm.py</strong></p> <pre><code>#!/usr/bin/env python import os os.system('python test.py') </code></pre> <p><strong>test.p...
0
2016-06-26T16:39:02Z
[ "python", "c++", "c" ]
XPath: Find element that contains text X and not Y
38,039,367
<p>I'm attempting to find a web element using XPath in <code>Selenium</code> for Python. The web element should contain the text <em>"Chocolate"</em> but not include <em>"Dark"</em>.</p> <p>I've tried this syntax but not gotten it to work (be mindful of parantheses):</p> <pre><code>choco = driver.find_element_by_xpat...
4
2016-06-26T14:14:03Z
38,039,975
<p>Please try following <code>XPath</code> and let me know if any errors occurs:</p> <pre><code>//*[contains(text(), "Chocolate")][not(contains(text(), "Dark"))] </code></pre>
3
2016-06-26T15:20:32Z
[ "python", "selenium", "xpath" ]
XPath: Find element that contains text X and not Y
38,039,367
<p>I'm attempting to find a web element using XPath in <code>Selenium</code> for Python. The web element should contain the text <em>"Chocolate"</em> but not include <em>"Dark"</em>.</p> <p>I've tried this syntax but not gotten it to work (be mindful of parantheses):</p> <pre><code>choco = driver.find_element_by_xpat...
4
2016-06-26T14:14:03Z
38,048,606
<p>Here is the syntax with using just one set of square brackets.</p> <p>For elements containing the word 'Chocolate' but not 'Dark', use:</p> <pre><code>//*[contains(text(), 'Chocolate') and not(contains(text(), 'Dark'))] </code></pre> <p>For just the text of the elements, use:</p> <pre><code>//text()[contains(., ...
1
2016-06-27T07:56:30Z
[ "python", "selenium", "xpath" ]
Extracting a packet content using a Python script
38,039,421
<p>I'm trying to make a code that will send an HTTP get request to a site and will save the content in an HTML file using scapy.</p> <p>So if that my code:</p> <pre><code>r = Ether() / IP(dst=cache_ip) / TCP() / "GET /index.html HTTP/1.0 \n\n" b = str(r) http.write(b) print "html page is ready, check your html files ...
-1
2016-06-26T14:20:28Z
38,044,828
<p>In your given code, it isn't clear what <code>http</code> is, and as a result, there is no way of knowing exactly what <code>http.write()</code> and <code>http.close()</code> would do.</p> <p>But in any case, if your aim is to retrieve HTML from the web using <em>ONLY</em> scapy, you must start with the TCP 3-way h...
0
2016-06-27T01:40:06Z
[ "python", "ubuntu", "httprequest", "http-get", "scapy" ]
Extract YAML headers using regular expressions
38,039,426
<p>I have a file with YAML headers, that is a file with starts with <code>---</code>, have <code>---</code>. Something like:</p> <pre><code>--- title: Quantes monedes de cèntim caben a un cercle? author: Dan Meyer date: 2013-08-26 abstract: Quantes monedes de cèntim caben a un cercle? tags: 3-acts continguts: àrea,...
0
2016-06-26T14:20:51Z
38,039,502
<p><code>.</code> does not match newlines, unless you set the <a href="https://docs.python.org/3/library/re.html#re.S" rel="nofollow"><code>DOTALL</code> flag</a>:</p> <pre><code>p = re.compile('---\n(.*?)\n---\n(.*)', flags=re.DOTALL) </code></pre> <p>Note that I dropped the <code>?</code> from the second <code>*</c...
2
2016-06-26T14:28:48Z
[ "python", "regex", "python-3.x" ]
Extract YAML headers using regular expressions
38,039,426
<p>I have a file with YAML headers, that is a file with starts with <code>---</code>, have <code>---</code>. Something like:</p> <pre><code>--- title: Quantes monedes de cèntim caben a un cercle? author: Dan Meyer date: 2013-08-26 abstract: Quantes monedes de cèntim caben a un cercle? tags: 3-acts continguts: àrea,...
0
2016-06-26T14:20:51Z
38,039,512
<p>For such a simple delimiter, you don't really need regular expressions. Given test file...</p> <pre><code>--- This is the first part --- This is the second part </code></pre> <p>...something as simple as...</p> <pre><code>&gt;&gt;&gt; s = open('testfile').read() &gt;&gt;&gt; _, part1, part2 = s.split('---\n') &gt...
2
2016-06-26T14:30:47Z
[ "python", "regex", "python-3.x" ]
python how to sort differents lists with a single unique value and append it to a result list
38,039,461
<p>I have several lists with unique values</p> <pre><code>&gt;&gt;&gt;print(ad) 5 &gt;&gt;&gt;print(ae) 2 &gt;&gt;&gt;print(af) 3 &gt;&gt;&gt;print(ag) 4 &gt;&gt;&gt;print(ah) 1 &gt;&gt;&gt;print(ai) 6 &gt;&gt;&gt;print(aj) 7 </code></pre> <p>I'm trying to sort them and append them to a empty list <code>results</code...
0
2016-06-26T14:24:16Z
38,039,585
<pre><code>ad=[5] ae=[2] af=[3] ag=[4] ah=[1] ai=[6] aj=[7] res.extend(ad) res.extend(ae) res.extend(af) res.extend(ag) res.extend(ah) res.extend(ai) res.extend(aj) res.sort() </code></pre>
0
2016-06-26T14:38:02Z
[ "python" ]
python how to sort differents lists with a single unique value and append it to a result list
38,039,461
<p>I have several lists with unique values</p> <pre><code>&gt;&gt;&gt;print(ad) 5 &gt;&gt;&gt;print(ae) 2 &gt;&gt;&gt;print(af) 3 &gt;&gt;&gt;print(ag) 4 &gt;&gt;&gt;print(ah) 1 &gt;&gt;&gt;print(ai) 6 &gt;&gt;&gt;print(aj) 7 </code></pre> <p>I'm trying to sort them and append them to a empty list <code>results</code...
0
2016-06-26T14:24:16Z
38,040,069
<p>If you want to learn about merge sort, here is how <code>merge</code> sort can be written in python which is implemented using recursive functions and what it does is split the list into two sublists, sort each one separately and than combine them together while maintaining the order:</p> <pre><code>def combine(lef...
3
2016-06-26T15:28:57Z
[ "python" ]
django - validate char field as email
38,039,558
<p>Lets say i have model:</p> <pre><code>class Subscription(models.Model): address = models.CharField(max_length=255) </code></pre> <p>then i create form:</p> <pre><code>class SubscriptionForm(ModelForm): class Meta: model = Subscription fields = ['address'] def clean_address(self): ...
-3
2016-06-26T14:36:01Z
38,039,617
<p>Add a validator to the <code>validator</code> field of your <code>CharField</code>:</p> <pre><code>from django.core.validators import EmailValidator emailvalidator = EmailValidator(message="invalid email") class Subscription(models.Model): address = models.CharField(max_length=255, validators=[emailvalidator...
0
2016-06-26T14:41:27Z
[ "python", "django" ]
django - validate char field as email
38,039,558
<p>Lets say i have model:</p> <pre><code>class Subscription(models.Model): address = models.CharField(max_length=255) </code></pre> <p>then i create form:</p> <pre><code>class SubscriptionForm(ModelForm): class Meta: model = Subscription fields = ['address'] def clean_address(self): ...
-3
2016-06-26T14:36:01Z
38,040,200
<p>You're better off just setting the validator in the model. Adding a validator doesn't affect the database in anyway so it isn't really changing the database model.</p> <p>but if you really want to just call the validator then do that.</p> <pre><code>from django.core.validators import EmailValidator def clean_addre...
1
2016-06-26T15:40:42Z
[ "python", "django" ]
Plotting graph of text file with strings and integers at the same lines
38,039,579
<p>I am trying to plot a graph using a txt data file of followig arrangement way:</p> <pre><code>{"alpha": 77.6, "beta": 135, "gamma": 342, "delta": 86.3} {"alpha": 77.3, "beta": 140, "gamma": 332, "delta": 82.3} </code></pre> <p>......</p> <p>(300++ lines below with similar arrangements)</p> <p>A normal table sho...
1
2016-06-26T14:37:23Z
38,039,993
<p>why not use the json package - clearly each line of your data is a JSON-formatted line</p> <pre><code>import json with open('data','r') as f: for line in f.readlines(): print(json.loads(line).values()) </code></pre> <p>If you'd rather have an array of dicts, rewrite the last line as pr...
0
2016-06-26T15:21:39Z
[ "python", "json", "python-3.x", "matplotlib" ]
Plotting graph of text file with strings and integers at the same lines
38,039,579
<p>I am trying to plot a graph using a txt data file of followig arrangement way:</p> <pre><code>{"alpha": 77.6, "beta": 135, "gamma": 342, "delta": 86.3} {"alpha": 77.3, "beta": 140, "gamma": 332, "delta": 82.3} </code></pre> <p>......</p> <p>(300++ lines below with similar arrangements)</p> <p>A normal table sho...
1
2016-06-26T14:37:23Z
38,040,126
<p>The following snippet should work for your purpose.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from json import loads data = {} def get_points(x, y): a = 'xyz/examples.txt' with open(a, 'r') as f: for line in f: new_dict = loads(line.strip()) for k in ...
0
2016-06-26T15:34:29Z
[ "python", "json", "python-3.x", "matplotlib" ]
Python Autobahn - Where do you write the logic to broad a signal?
38,039,677
<p>I'm currently working with the Autobahn Python library. I'm attempting to set up a websocket server that broadcasts a signal to connected clients. However, I'm struggling to understand where I should place the logic for actually broadcasting the signal.</p> <p>When defining the WebSocketProtocol, it appears that it...
1
2016-06-26T14:48:38Z
38,119,912
<p>Not a Python expert (plus I've never used Autobahn|Python without using the WAMP functionality), but <a href="https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/broadcast/server.py" rel="nofollow">https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/b...
0
2016-06-30T10:03:47Z
[ "python", "autobahn" ]
Using an R Markdown style document (.Rmd) as input for Pweave
38,039,697
<p>I'm trying to run a basic R Markdown document (that calls python in code chunks) through <code>Pweave</code>. In the <a href="http://mpastell.com/pweave/usage.html#markdown" rel="nofollow"><code>Pweave</code> documentation</a> it states that you can declare code chunks using the style <code>```{python}</code>. Howev...
4
2016-06-26T14:50:04Z
38,205,496
<p>Instead of <code>pweave -f pandoc &lt;source&gt;</code> try using <code>pweave -i markdown &lt;source&gt;</code>.</p> <p>If you do not provide the input format, it is <a href="https://github.com/mpastell/Pweave/blob/master/pweave/pweb.py#L109-L116" rel="nofollow">deduced from file extension</a>. As you can see in l...
1
2016-07-05T14:03:18Z
[ "python", "markdown", "rmarkdown", "pweave" ]
Splitting a large Pandas Dataframe with minimal memory footprint
38,039,723
<p>I have a large DataFrame, which I would like to split into a test set and a train set for model building. However, I do not want to duplicate the DataFrame because I am reaching a memory limit.</p> <p>Is there an operation, similar to pop but for a large segment, that will simultaneously remove a portion of the Dat...
7
2016-06-26T14:53:28Z
38,086,123
<p>If you have the space to add one more column, you could add one with a random value that you could then filter on for your testing. Here I used uniform between 0 and 1, but you could use anything if you wanted a different proportion.</p> <pre><code>df = pd.DataFrame({'one':[1,2,3,4,5,4,3,2,1], 'two':[6,7,8,9,10,9,...
3
2016-06-28T20:53:43Z
[ "python", "pandas", "dataframe" ]
Splitting a large Pandas Dataframe with minimal memory footprint
38,039,723
<p>I have a large DataFrame, which I would like to split into a test set and a train set for model building. However, I do not want to duplicate the DataFrame because I am reaching a memory limit.</p> <p>Is there an operation, similar to pop but for a large segment, that will simultaneously remove a portion of the Dat...
7
2016-06-26T14:53:28Z
38,103,843
<p>I would do something similar as @jeff-l, i.e. keep your data frame on file. When you read it in as a csv, use the <code>chunksize</code> keyword. The following script illustrates this:</p> <pre><code>import pandas import numpy test = 5 m, n = 2*test, 3 df = pandas.DataFrame( data=numpy.random.random((m, n)) )...
1
2016-06-29T15:21:56Z
[ "python", "pandas", "dataframe" ]
Splitting a large Pandas Dataframe with minimal memory footprint
38,039,723
<p>I have a large DataFrame, which I would like to split into a test set and a train set for model building. However, I do not want to duplicate the DataFrame because I am reaching a memory limit.</p> <p>Is there an operation, similar to pop but for a large segment, that will simultaneously remove a portion of the Dat...
7
2016-06-26T14:53:28Z
38,108,052
<p>As other answers are more focused on the file reading, I guess you also can do something, if for any reason your DataFrame isn't read from a file.</p> <p>Maybe you can take a look at the code of the <a href="https://github.com/pydata/pandas/blob/6d8c04ce64d975c2fd8c902c0e5df343805bd112/pandas/core/generic.py#L1847"...
1
2016-06-29T19:01:31Z
[ "python", "pandas", "dataframe" ]
Unable to access python array from php
38,039,777
<p>I have two code snippets:- </p> <p>1) get_pos_tags.py</p> <pre><code>import sys import json from nltk.tokenize import word_tokenize from nltk.tag import pos_tag def getPOSTags(sentence=sys.argv[1]): sentence_s=str(sentence) word_token=word_tokenize(sentence_s) print word_token word_POS_tags=pos_t...
0
2016-06-26T14:58:58Z
38,039,888
<p>I don't know much PHP, but you may want to look into piping the output from your python script into your php script using sys.stdout</p>
0
2016-06-26T15:10:32Z
[ "php", "python", "xampp" ]
difference in program behavior when run from python script and from windows
38,039,933
<p>Some background:<br> A program runs a manufacturing machine. This program runs on windows XP. The program controls the machine and writes a simple manufacturing log.<br> I wrote a python script that asks the user to enter current manufacturing project name. the script writes project name to log file. This way, I ...
1
2016-06-26T15:14:21Z
38,040,208
<p>If you want the program BadePanel to write to the Steelusage.bsu-file, you should close the file from the python script before you call the BadePanel.exe. If you don't do this, the file will still be opened by your script and the exe you call won't be able to write data to the file.</p>
0
2016-06-26T15:41:23Z
[ "python", "windows", "logging", "exe" ]
How to use the previous command output to use as a part of another command: python
38,039,934
<p>I have been trying to use the output of a system command to use it as a part of the command in the next portion. However, I cannot seem to join it up properly and hence not being able to run the second command properly. The OS used is KALI LINUX and python 2.7</p> <pre><code>#IMPORTS import commands, os, subprocess...
1
2016-06-26T15:14:24Z
38,040,086
<p>Assuming you haven't called <code>os.chdir()</code> anywhere prior to the <code>cp -R</code>, then you can use a relative path. Changing the code to...</p> <pre><code>if 'TOOLS' in checkdir: cmd = 'cp -R RAW ~/Desktop/TOOLS' os.system(cmd) </code></pre> <p>...should do the trick.</p> <p>Note that the line...
0
2016-06-26T15:30:16Z
[ "python", "linux", "command-line", "command", "concatenation" ]
PyQt4 Signal and QObject.Emit()
38,040,071
<p>I am learning GUI programing using python and pyqt4 and this is the app i am working on to learn Signal and Slots. This is a simple app which has a spinbox and a dialogue box that connected together using pyqt signals. but i added a class zerospinbox ,it supposed to print massage to console every time that the spinb...
0
2016-06-26T15:29:05Z
38,041,204
<p>You created <em>three</em> spinboxes, but only added the first of them to the dialog layout. The only one that is shown is a <code>QSpinBox</code>, not a <code>ZeroSpinBox</code>. The other two just get deleted without being shown.</p> <p>You used old-style signal/slot syntax and made a spelling error, so the conne...
0
2016-06-26T17:28:08Z
[ "python", "qt", "signals", "pyqt4", "emit" ]
Why do identical strings return false with ==?
38,040,121
<p>This is the simplified version of my problem.</p> <pre><code>QA = open('Qestions and answers.txt') Q = [] A = [] for line in QA: (first,second) = line.split(';') Q.append(first) A.append(second) QA.close() print(A[0], A[1]) print(A[0] == '1981') print(A[1] == 'Feb') print(str(A[0]) == '1981') # I even tr...
1
2016-06-26T15:34:04Z
38,040,161
<p>You've got extra whitespace in there. My guess is this:</p> <pre><code>print(repr(A[0])) </code></pre> <p>Output:</p> <pre><code>'1981\n' </code></pre> <p>This is because when you read lines from a file, you will get the line breaks at the end of each line as well. If you don't want that, strip them out.</p> ...
4
2016-06-26T15:37:31Z
[ "python", "string" ]
Why do identical strings return false with ==?
38,040,121
<p>This is the simplified version of my problem.</p> <pre><code>QA = open('Qestions and answers.txt') Q = [] A = [] for line in QA: (first,second) = line.split(';') Q.append(first) A.append(second) QA.close() print(A[0], A[1]) print(A[0] == '1981') print(A[1] == 'Feb') print(str(A[0]) == '1981') # I even tr...
1
2016-06-26T15:34:04Z
38,043,342
<p>strip() works for this problem</p> <pre><code>print(A[0].strip() == '1981') print(A[1].strip() == 'Feb') True True </code></pre>
0
2016-06-26T21:26:07Z
[ "python", "string" ]
Getting relative frequencies for a categorical variable (filtered on a count)?
38,040,206
<p>I've got a DataFrame of student test results, where the two columns that interest me are <code>country</code> and <code>result</code>, as in:</p> <pre><code>country result FR Pass FR Fail US Pass US Pass DK Fail DK Fail SE Pass ... ... </code></pre> ...
0
2016-06-26T15:41:02Z
38,040,400
<p>You can use groupby.agg. First I created a random dataset:</p> <pre><code>import numpy as np np.random.seed(0) countries = ["FR", "US", "DK", "SE", "NL"] df = pd.DataFrame({"country": np.random.choice(countries, 1000), "result": np.random.choice(["Pass", "Fail"], 1000)}) </code></pre> <p>It has 1000 rows with coun...
2
2016-06-26T16:03:08Z
[ "python", "pandas", "dataframe" ]
Apache web server 32bit on 64bit computer
38,040,240
<p>simple question - if I run apache 32bit version, on 64bit OS, with a lot of memory (32GB RAM). Does this mean all the memory will go to waste since 32bit apache can't use more then 3GB ram?</p>
0
2016-06-26T15:45:23Z
38,040,277
<p>I would assume so. You should definitely go for a 64-bit version of Apache to make use of all the memory available.</p>
0
2016-06-26T15:48:52Z
[ "python", "django", "apache", "32bit-64bit", "32-bit" ]
Scraping Instagram followers page using selenium and python
38,040,300
<p>I have a question related to scraping the instagram followers page. I have a code but it displays only 9 followers. Kindly help me.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import...
-3
2016-06-26T15:51:54Z
38,323,441
<p>You can easily scroll down using javascript by increasing the scrollTop. You run this scroll until the amount of users in the list no longer changes.</p> <p>The difference in the amount of users can be checked using the following function</p> <pre><code>count = 0 def check_difference_in_count(driver): global ...
0
2016-07-12T08:18:19Z
[ "python", "selenium" ]
Python: how to delete object from class?
38,040,308
<p>I'm new to python and having a little trouble with object classes. I have created code were ball objects bounce off the side of the wall. I would like to delete a ball after it has been clicked on. I have tried several different methods of doing this but they have all resulted in errors. Below is my code for the bal...
2
2016-06-26T15:53:02Z
38,042,841
<p>Use the bind-method of the class canvas and delete the clicked oval. Your for loop should have an exception handling because a deleted object can't have coordiantes or speed. The del() function is typically used to delete objects.</p> <pre><code>from Tkinter import * import random import time canvasWidth = 480 can...
0
2016-06-26T20:23:06Z
[ "python", "class", "tkinter" ]
Lasagne/Theano mnist example issue
38,040,389
<p>I'm trying to slightly change the code from github <a href="https://github.com/Lasagne/Lasagne/blob/master/examples/mnist.py" rel="nofollow">here</a> to a toy example of reading a simpler two dimensional data. My toy data set has the following structure</p> <pre><code>x-coordinate, y-coordinate, class </code></pre>...
0
2016-06-26T16:02:01Z
38,046,062
<p>You're declaring <code>input_var</code> as a 4d tensor, but the error message suggests that you're passing a data matrix of size <code>(5,2)</code> as input. Based on the shape of your input layer, this should be <code>(5, 1, 1, 2)</code> (assuming the 5 corresponds to the number of training examples in a minibatch ...
1
2016-06-27T04:42:54Z
[ "python", "neural-network", "theano", "lasagne" ]
Deleting files from pre installed python folder of mac
38,040,394
<p>Is it safe to delete files/folders from the site-packages folder?<br/><br/> /Library/Python/2.7/site-packages/mysql<br/><br/> The read me file in this folder says : <br/></p> <blockquote> <p>This directory exists so that 3rd party packages can be installed here. Read the source for site.py for more details.</p...
0
2016-06-26T16:02:45Z
38,040,505
<p>Use:</p> <pre><code>pip uninstall [options] &lt;package&gt; ... </code></pre>
0
2016-06-26T16:13:37Z
[ "python", "mysql", "osx", "mysql-connector" ]
Usage of python-readability
38,040,554
<p>(<a href="https://github.com/buriy/python-readability" rel="nofollow">https://github.com/buriy/python-readability</a>)</p> <p>I am struggling using this library and I can't find any documentation for it. (Is there any?)</p> <p>There are some kind of useable pieces calling help(Document) but there is still somethin...
0
2016-06-26T16:18:43Z
38,040,612
<p>There's an error in the library code. If you look at <a href="https://github.com/buriy/python-readability/blob/master/readability/readability.py#L67" rel="nofollow"><code>compile_pattern</code></a>:</p> <pre><code>def compile_pattern(elements): if not elements: return None elif isinstance(elements, ...
1
2016-06-26T16:25:06Z
[ "python", "readability" ]
Python multiprocessing creates sub-process using wrong function
38,040,699
<p>I'm trying to write code that create sub-process using another module(demo_2.py),<br> and exit program if i get wanted value on sub-processes.</p> <p>But result looks like this.</p> <p><a href="http://i.stack.imgur.com/QdjQL.png" rel="nofollow"><img src="http://i.stack.imgur.com/QdjQL.png" alt="Unexpected action o...
0
2016-06-26T16:33:43Z
38,040,735
<pre><code>if process_status_A == 'exit' and process_status_B == 'exit': </code></pre> <p>should be</p> <pre><code>if process_status_A_output == 'exit' and process_status_B_output == 'exit': </code></pre> <hr> <p>Conclusion: The naming of variables is important. Avoid long variable names which are <em>almost</em> ...
2
2016-06-26T16:37:40Z
[ "python", "python-2.7", "multiprocessing" ]
Appending Pandas dataframes in for loop results in ValueError
38,040,825
<p>I want to generate a dataframe that is made up of separate dataframes generated in a for loop. Each individual dataframe consists of a name column, a range of integers and a column identify a category to which the integer belongs (e.g. quintile 1 to 5). If I generate each dataframe individually and then append one t...
1
2016-06-26T16:48:08Z
38,040,875
<p>You can first append all <code>DataFrames</code> to list <code>dfs</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p> <pre><code>dfs = [] # Create a dataframe for each group for i in names: tempDF = pd.DataFrame(columns ...
1
2016-06-26T16:53:33Z
[ "python", "python-3.x", "pandas", "dataframe" ]
How to get only numbers as a response in python?
38,040,898
<p>I'm very new to python, in fact, to programming in general. I'm trying to do a program that compares three numbers and determines which one is smaller. I got the code done, but now i need to make it only accept numbers, and still running when it finds a literal value. For example, code will be ok if you put any numb...
0
2016-06-26T16:55:25Z
38,040,950
<pre><code>def getNumber(i): try: num = int(raw_input("type in number %s : " %i)) return num except Exception as e: print('This is not a valid number') return getNumber(i) numbers = [] for i in range(1,4): numbers.append(getNumber(i)) print(numbers) </code></pre>
0
2016-06-26T17:01:01Z
[ "python", "exception" ]
How to get only numbers as a response in python?
38,040,898
<p>I'm very new to python, in fact, to programming in general. I'm trying to do a program that compares three numbers and determines which one is smaller. I got the code done, but now i need to make it only accept numbers, and still running when it finds a literal value. For example, code will be ok if you put any numb...
0
2016-06-26T16:55:25Z
38,040,969
<p>You can simply add the input getting code in try except block and handle the <code>ValueError</code> exception with some meaningful code.</p> <pre><code>try: num1=int((raw_input("Type below the first number \n"))); num2=int((raw_input("Type below the second number\n"))); num3=int((raw_input("Type below ...
-2
2016-06-26T17:02:51Z
[ "python", "exception" ]
How to get only numbers as a response in python?
38,040,898
<p>I'm very new to python, in fact, to programming in general. I'm trying to do a program that compares three numbers and determines which one is smaller. I got the code done, but now i need to make it only accept numbers, and still running when it finds a literal value. For example, code will be ok if you put any numb...
0
2016-06-26T16:55:25Z
38,040,978
<p>A simple while loop. You may put this in a function.</p> <pre><code>while True: try: num1=int((raw_input("Type below the first number \n"))) break except ValueError: # catch the *specific* exception print("Enter numbers only") </code></pre> <p>Read more on exceptions: <a href=...
2
2016-06-26T17:03:11Z
[ "python", "exception" ]
How to get only numbers as a response in python?
38,040,898
<p>I'm very new to python, in fact, to programming in general. I'm trying to do a program that compares three numbers and determines which one is smaller. I got the code done, but now i need to make it only accept numbers, and still running when it finds a literal value. For example, code will be ok if you put any numb...
0
2016-06-26T16:55:25Z
38,041,124
<p>The most important point is probably to separate concerns, ie. keeping user input separate from validation. You've gotten a couple of good solutions using exceptions. Here is a solution that manually validates the input:</p> <pre><code>def is_int(strval): """A string represents an int if all characters are dig...
0
2016-06-26T17:19:07Z
[ "python", "exception" ]
unable to resolve "requests". IntelliSense may be missing for this module
38,040,916
<p>I have this code: <code>import requests</code> <br> I get this error under requests:</p> <blockquote> <p>unable to resolve "requests". IntelliSense may be missing for this module.</p> </blockquote> <p>What is causing this error and how can it be fixed? Thanks in advance!</p>
0
2016-06-26T16:58:02Z
38,040,960
<p>You have to install the requests package first.</p> <p>Simply run <code>pip install requests</code> in your terminal. Here's the <a href="http://docs.python-requests.org/en/master/user/install/" rel="nofollow">requests documentation</a>.</p>
0
2016-06-26T17:02:00Z
[ "python", "python-3.x" ]
What's considered nesting in python?
38,040,920
<p>I have always considered nesting as embedding one object in another object of the same type.</p> <p>But I was recently told that nesting also means embedding objects of different type so the following has three levels of nesting.</p> <pre><code>def my_function(): # first level of nesting ??? while expr: ...
-3
2016-06-26T16:58:21Z
38,040,966
<p>There are at least 2 definitions of nesting:</p> <ul> <li><p>Putting one object inside of another could be considered nesting (think Russian Nesting Dolls), but it's more generally referred to as <strong>composition</strong>. I'm guessing this is what you were referring to as putting one object inside of another; a...
2
2016-06-26T17:02:46Z
[ "python" ]
Keep first and drop the next duplicate rows
38,040,929
<p>I want to keep the first row from the set of duplicates. I am also trying to append the current input file. My doubt is if both deleting the duplication and appending the same file, will it be possible? If so then the code below referring the Pandas doc isnt working. </p> <p>Input:</p> <pre><code>,id_merged,time_1...
1
2016-06-26T16:59:24Z
38,041,015
<p>You need add parameter <code>inplace=True</code>:</p> <pre><code>import pandas as pd import io temp=u""",id_merged,time_1,time_2,gps_1or3,gps_2or4 0,00022d9064bc,1073260801,1073260803,819251,440006 1,00022d9064bc,1073260801,1073260803,819251,440006 2,00022d9064bc,1073260801,1073260803,819251,440006 3,00022d9064bc,...
1
2016-06-26T17:06:19Z
[ "python", "python-2.7", "csv", "pandas", "duplicates" ]
Need help using split function
38,040,931
<p>This function adds up the numbers between zero in a string. For example ('25025') becomes 25+25. However, if I have a 0 at start and/or end of the string of the string argument being sent to test_string, it creates a space in the at the start/end of the list and won't compute. What can I add to this function to m...
-1
2016-06-26T16:59:42Z
38,040,983
<p>Replace this:</p> <pre><code>numbers=[int(x) for x in test] </code></pre> <p>With this:</p> <pre><code>numbers=[int(x) for x in test if x] </code></pre> <p>This code is self-explanatory: convert <code>x</code> to integer and append it to the list <code>if</code> <code>bool(x)</code> is <code>True</code>, thus <e...
1
2016-06-26T17:03:30Z
[ "python", "python-3.x" ]
Need help using split function
38,040,931
<p>This function adds up the numbers between zero in a string. For example ('25025') becomes 25+25. However, if I have a 0 at start and/or end of the string of the string argument being sent to test_string, it creates a space in the at the start/end of the list and won't compute. What can I add to this function to m...
-1
2016-06-26T16:59:42Z
38,041,007
<p>If you're ok with keeping your current approach, then this should do:</p> <pre><code>test = test_string.strip('0').split("0") numbers = [int(x) for x in test] </code></pre> <p>Otherwise, you could use a comprehension in a generator expression altogether:</p> <pre><code>sum(int(x) for x in test_string.strip('0').s...
2
2016-06-26T17:05:31Z
[ "python", "python-3.x" ]
Need help using split function
38,040,931
<p>This function adds up the numbers between zero in a string. For example ('25025') becomes 25+25. However, if I have a 0 at start and/or end of the string of the string argument being sent to test_string, it creates a space in the at the start/end of the list and won't compute. What can I add to this function to m...
-1
2016-06-26T16:59:42Z
38,041,046
<p>You can use string one of methods <em>strip()/rstrip()/lstrip()</em>.</p> <pre><code>&gt;&gt;&gt; s = '0138076023' &gt;&gt;&gt; s.lstrip('0') '138076023' &gt;&gt;&gt; s.strip('0') '138076023' &gt;&gt;&gt; s = ' asasd ' &gt;&gt;&gt; s.strip() 'asasd' &gt;&gt;&gt; </code></pre> <p>Docs about these methods can...
1
2016-06-26T17:08:57Z
[ "python", "python-3.x" ]
Need help using split function
38,040,931
<p>This function adds up the numbers between zero in a string. For example ('25025') becomes 25+25. However, if I have a 0 at start and/or end of the string of the string argument being sent to test_string, it creates a space in the at the start/end of the list and won't compute. What can I add to this function to m...
-1
2016-06-26T16:59:42Z
38,041,067
<p>Try this</p> <pre><code>def test_one(test_string): test = test_string.split("0") print(test) if test[0] != '': numbers=[int(x) for x in test] else: test = test[1:] numbers=[int(x) for x in test] print(sum(numbers)) test_one('2022022022') test_one('02022022022') </code></...
0
2016-06-26T17:12:21Z
[ "python", "python-3.x" ]