title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
From Nested Dictionary to CSV File
38,454,203
<p>I have nested dictionary (with length > 70.000): </p> <pre><code>users_item = { "sessionId1": { "12345645647": 1.0, "9798654": 5.0 }, "sessionId2":{ "3445657657": 1.0 }, "sessionId3": { "87967976": 5.0, "35325626436": 1.0, "126789435...
1
2016-07-19T09:13:40Z
38,454,732
<p>Assuming you want each session as a row, the number of columns for every row will be the total number of unique keys in all session dicts. Based on the data you've given, I'm guessing the number of unique keys are astronomical.</p> <p>That is why you're running into memory issues with the solution <a href="http://s...
0
2016-07-19T09:37:11Z
[ "python", "python-3.x", "csv", "dictionary" ]
From Nested Dictionary to CSV File
38,454,203
<p>I have nested dictionary (with length > 70.000): </p> <pre><code>users_item = { "sessionId1": { "12345645647": 1.0, "9798654": 5.0 }, "sessionId2":{ "3445657657": 1.0 }, "sessionId3": { "87967976": 5.0, "35325626436": 1.0, "126789435...
1
2016-07-19T09:13:40Z
38,454,754
<pre><code>for session, ratings in users_item.items(): for rating, value in ratings.items(): print("{} {}".format(session, value)) </code></pre> <p>Output:</p> <pre><code>sessionId3 5.0 sessionId3 1.0 sessionId3 5.0 sessionId3 1.0 sessionId1 5.0 sessionId1 1.0 sessionId4 1.0 sessionId2 1.0 </code></pre> ...
0
2016-07-19T09:37:53Z
[ "python", "python-3.x", "csv", "dictionary" ]
From Nested Dictionary to CSV File
38,454,203
<p>I have nested dictionary (with length > 70.000): </p> <pre><code>users_item = { "sessionId1": { "12345645647": 1.0, "9798654": 5.0 }, "sessionId2":{ "3445657657": 1.0 }, "sessionId3": { "87967976": 5.0, "35325626436": 1.0, "126789435...
1
2016-07-19T09:13:40Z
38,455,029
<p>If you iteratively write the file, there should be no memory issues:</p> <pre><code>import csv users_item = { "sessionId1": { "12345645647": 1.0, "9798654": 5.0 }, "sessionId2":{ "3445657657": 1.0 }, "sessionId3": { "87967976": 5.0, "35325626436": 1.0, ...
0
2016-07-19T09:49:22Z
[ "python", "python-3.x", "csv", "dictionary" ]
Pycharm Run/Debug uses Python different from one configured as an interpreter
38,454,207
<p>I am using PyCharm 2016.1.4 on Ubuntu 16.04</p> <p>Earlier I created a virtual environment while 'tf' while having an alias of 'python' to my local installation of python 3.5+ (in case it matters).</p> <p>Currently, my project interpreter is configured as </p> <pre><code> "Python 3.5.1+ virtualenv at ~/tf" </code...
0
2016-07-19T09:13:42Z
38,454,672
<p>Go to project structure (File/Project Structure) <code>cmd + ;</code> on Mac.</p> <p>There you can specify which SDK to use. Click <code>New</code> -> <code>Python</code> -> <code>Add Local</code> and select the <code>virtualnv/bin/python</code> file.</p>
0
2016-07-19T09:34:31Z
[ "python", "pycharm" ]
mock file open in python
38,454,272
<p>I'm trying to mock file open, and all of the examples show that I need to </p> <pre><code>@patch('open', create=True) </code></pre> <p>but I keep getting </p> <pre><code>Need a valid target to patch. You supplied: 'open' </code></pre> <p>I know patch needs the <strong>full dotted path of <code>open</code></stro...
1
2016-07-19T09:16:14Z
38,454,455
<p>You need to include a module name; if you are testing in a script, the name of the module is <code>__main__</code>:</p> <pre><code>@patch('__main__.open') </code></pre> <p>otherwise use the name of the module that contains the code you are testing:</p> <pre><code>@patch('module_under_test.open') </code></pre> <p...
3
2016-07-19T09:24:38Z
[ "python", "unit-testing", "mocking", "magicmock" ]
Convert Excel style date with pandas
38,454,403
<p>I have to parse an xml file which gives me datetimes in excel style. For example: 42580.3333333333.</p> <p>Does pandas provide a way to convert that number in a proper datetime?</p> <p>Thanks for your help.</p>
1
2016-07-19T09:22:17Z
38,454,637
<p>OK I think the easiest thing is to construct a TimedeltaIndex from the floats and add this to the scalar datetime for 1900,1,1:</p> <pre><code>In [85]: df = pd.DataFrame({'date':[42580.3333333333, 10023]}) df Out[85]: date 0 42580.333333 1 10023.000000 In [86]: df['real_date'] = pd.TimedeltaIndex(df[...
2
2016-07-19T09:33:05Z
[ "python", "excel", "date", "pandas" ]
How to deattach webview once attached?
38,454,505
<p>I've successfully attached WebView to my Kivy app <a href="https://github.com/kivy/kivy/wiki/Android-native-embedded-browser" rel="nofollow">following Kivy wiki instructions</a>. It works as expected, but I'd like to deattach and return to my normal Kivy ui. How to I do that?</p> <p>I've tried to explore WebView <a...
4
2016-07-19T09:27:22Z
38,607,984
<p>Ok, I'm not sure whether this is the best solution, or clean enough, but the only one I know that works. While it works and seems stable, it needs further testing by someone with better knowledge of Kivy and Android API itself.</p> <pre><code>if platform == 'android': from jnius import autoclass from androi...
2
2016-07-27T08:42:56Z
[ "android", "python", "webview", "kivy" ]
How to Print character using its unicode value in Python?
38,454,521
<p>I have a list which contains english alphabets, Hindi alphabets, Greek Symbols and digits as well. I want to remove all alphabets except that of Hindi. Hindi alphabets range in unicode is u'0900'-u'097F'. For details about Hindi alphabets visit <a href="http://jrgraphix.net/r/Unicode/0900-097F" rel="nofollow">http:/...
-2
2016-07-19T09:27:55Z
38,455,197
<p>To get a character value you can use the <code>ord(char)</code> buildin function.</p> <p>In your case, something like this should works:</p> <pre><code>strings = [u'ग',u'1ए',u'==क',u'@',u'ऊं',u'abc123',u'η',u'θ',u'abcशि'] for string in strings: for char in string: if ord(u'\u0900') &lt;...
4
2016-07-19T09:56:15Z
[ "python", "unicode", "python-2.x", "hindi" ]
extract data from nested xpath
38,454,535
<p>I am newbie using <code>xpath</code>, I wanna extract every single title, body, link , release date from <a href="http://thehackernews.com/search/label/mobile%20hacking" rel="nofollow">this link</a></p> <p>everthing seems okay, but no on body, how to extract every single body on nested xPath, thanks before :)</p> ...
0
2016-07-19T09:28:51Z
38,466,452
<p>I think you where struggling with the selectors, right? I think you should check the documentation for <a href="http://doc.scrapy.org/en/latest/topics/selectors.html" rel="nofollow">selectors</a>, there's a lot of good information there. In this particular example, using the css selectors, I think it would be someth...
1
2016-07-19T18:57:42Z
[ "python", "xpath", "scrapy", "web-crawler" ]
Pythonic accessors / mutators for "internal" lists
38,454,560
<p>I'm aware that attribute getters and setters are considered "unpythonic", and the pythonic way to do things is to simply use an normal attribute and use the property decorator if you later need to trigger some functionality when an attribute is accessed or set.</p> <p>e.g. <a href="http://stackoverflow.com/question...
0
2016-07-19T09:30:05Z
38,454,799
<p>What's unpythonic are <em>useless</em> getters and setters - since Python have a strong support for computed attributes. This doesn't mean you shouldn't properly encapsulate your implementation.</p> <p>In your above exemple, the way your <code>AnimalShelter</code> class handles it's "owned" animals is an implementa...
1
2016-07-19T09:39:40Z
[ "python", "oop", "design-patterns", "getter-setter" ]
How to use django serializer in unit test
38,454,589
<p>class ProcessDocRequestTestCase(BxApiTestCase): username = 'hr'</p> <pre><code>def test_email_sent_on_creation(self): r = r0 = self.r('post', 201, '/api/processes', %post_data%) requestor_superior_id = r0.data['extra']['next_employees'][0] superior_emp = Employee.objects.get(pk=requestor_superior_i...
0
2016-07-19T09:31:11Z
38,460,052
<p>to do this I simply had to "mock" a request using <a href="http://www.django-rest-framework.org/api-guide/testing/" rel="nofollow">APIRequestFactory</a>. </p> <p>So I wrote this method as well:</p> <pre><code># call response def r(self, method, status_code, url, data=None, *args, **kwargs): kwargs['data'] = da...
1
2016-07-19T13:29:51Z
[ "python", "django", "python-2.7", "serialization" ]
cv2.VideoCapture doesn't return frames
38,454,655
<p>I am trying to save a webcam video with wx Buttons. This is my code</p> <pre><code>def OnRecord(self, evt): capture = cv2.VideoCapture(0) if (not capture.isOpened()): print "Error" # video recorder fourcc = cv2.cv.CV_FOURCC('D', 'I', 'V', 'X') # cv2.VideoWriter_fourcc() does not exist ...
2
2016-07-19T09:33:51Z
38,538,670
<p>Try initialize counter before reading the capture for Eg:</p> <pre><code>i = 0 while i &lt; 0: ret, frame = capture.read() if ret: out.write(frame) else: print "Error" </code></pre>
0
2016-07-23T05:55:04Z
[ "python", "opencv", "wxpython", "video-capture", "raspberry-pi2" ]
Wrong folder after installing a wheel with python
38,454,697
<p>I have a python project that I want to distribute. I read multiple tutorials on how to write my setup.py file and how to install the produced wheel: <a href="https://github.com/pypa/sampleproject" rel="nofollow">sample project example</a>, <a href="https://packaging.python.org/distributing/#configuring-your-project"...
0
2016-07-19T09:35:35Z
38,455,143
<p><code>find_packages()</code> determines packages by the <code>__init__.py</code> files. It looks like your <code>lib</code> and <code>tests</code> directories have <code>__init__.py</code> files in them.</p> <p>Neither your <code>lib</code> or <code>tests</code> directories are packages, remove the <code>__init__.p...
0
2016-07-19T09:54:19Z
[ "python", "python-3.x", "pip", "setuptools", "python-wheel" ]
Does Appdynamics provide any APIs for creating project/job and user
38,454,851
<p>I Have tried to find if Appdynamics provides any API but I could not find any. So I want to know if there are any APIs available for creating users and project/job in Appdynamics, so that I can automate the process using Python scripts. </p>
0
2016-07-19T09:41:46Z
38,459,237
<p>There are lots of APIs available out of the box, you can find the docs at <a href="https://docs.appdynamics.com/" rel="nofollow">https://docs.appdynamics.com/</a> not everything has an API. You should find the user management as part of the configuration API here : <a href="https://docs.appdynamics.com/display/PRO42...
0
2016-07-19T12:55:16Z
[ "python", "appdynamics" ]
ImportError: with error 'is not a package'
38,454,852
<p>In python 3 getting into ImportError issues. My project structure is like:</p> <pre><code>cts_sap_polaris/ |-- etc | |-- clean_cts_sap_polaris.yaml ...
0
2016-07-19T09:41:49Z
38,455,706
<p>From what i understand, python only searches the current directory and sys.path. So you can add to the python path at run time. A similar question has been answered <a href="http://stackoverflow.com/questions/4383571/importing-files-from-different-folder-in-python">here</a></p> <p>I would suggest you to <strong>try...
0
2016-07-19T10:18:13Z
[ "python", "python-3.x" ]
VI_ERROR_TMO (-1073807339)
38,454,891
<p>I'm using RS-232 port to communicate with KeithleyInstruments(SCPI Protocol) and have a problem.I can send the write command but when I send a query command it*s show the error below.</p> <pre><code>import visa rm = visa.ResourceManager() inst = rm.list_resources() print inst # print inst --&gt; (u'USB0::0x05E6::0x...
1
2016-07-19T09:43:42Z
38,468,768
<p>A query is a write and a read combined, so you only need the query, not the write.</p> <p>If it still times out after removing the extra write, try setting a really long timeout like:</p> <pre><code>keithleyInst.timeout = 5000 </code></pre> <p>To give it 5 seconds to respond. You can always shorten this once you'...
0
2016-07-19T21:22:17Z
[ "python", "serial-port", "visa" ]
python pygame how to fade in the volume?
38,454,892
<pre><code>song = "choy_san_dou.ogg" pygame.init() pygame.display.set_mode((200,100)) pygame.mixer.init() pygame.mixer.music.load(song) pygame.mixer.music.set_volume(0.1) pygame.mixer.music.play(0) </code></pre> <p>I am unable to find a way to fade in the volume when the song is loaded, means to have the volume of the...
-1
2016-07-19T09:43:44Z
38,515,604
<p>The pygame.mixer module has a Sound class (doc: <a href="http://www.pygame.org/docs/ref/mixer.html" rel="nofollow">http://www.pygame.org/docs/ref/mixer.html</a>) that takes a file name as input and converts the file contents to a Sound object. Sound objects have a method play() where you can specify an amount of tim...
0
2016-07-21T22:50:50Z
[ "python", "raspberry-pi", "pygame" ]
Save IPython console output without IDE
38,454,894
<p>I currently use Spyder to generate some plots that are shown in Spyder's IPython console. This allows me to save the output as an HTML file by right-clicking on the IPython console and selecting 'Save as HTML/XML'.</p> <p>Say I have the following code:</p> <pre><code>import matplotlib.pylab as plt print "Some text...
0
2016-07-19T09:43:51Z
38,456,663
<p>For what I gathered you want to save the output of an interactive iPython console to html. I couldn't find a direct way of right-clicking and saving to HTML (I'm sure if it's possible to do using a UI command it's possible to do without, I haven't looked carefully). </p> <p>A workaround however could be first savi...
1
2016-07-19T11:00:06Z
[ "python", "plot", "ssh", "remote-server", "spyder" ]
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
38,454,914
<p>I use Python Beautiful Soup to move through DOM elements and Selenium to open page in chrome and ActionChains to scroll in page. It worked fine but the website changed something and now I run into two kinds of error on the way it worked before and on a new way as a possible solution.</p> <p>Old solution:</p> <pre>...
0
2016-07-19T09:44:49Z
38,457,911
<p>I think I see the problem. If you show all of your code, it will probably show that last line is within a for loop that is navigating away from the page, then coming back to the same page (or some ajax has refreshed that set of options on the page). The problem is that the page has reloaded, so the target element ...
0
2016-07-19T11:58:03Z
[ "python", "selenium" ]
Why are Django tests printing output?
38,454,946
<p>I thought Django was not supposed to print any output in the tests....I have some print statements that help me with data entry, and I have written <code>TestCase</code>s for them, but when the tests run they print all the output to the terminal which is annoying. </p> <p>Is there a way to stop django from printing...
0
2016-07-19T09:45:59Z
38,455,297
<p>Your <code>wiktionary_lookup</code> function is doing the printing. Your test cases aren't going to alter the functionality of your <code>wiktionary_lookup</code> code -- in fact, if they did, they wouldn't be very good test cases! (You'd be testing your altered code and not the real stuff.) If you don't want it to ...
2
2016-07-19T10:00:54Z
[ "python", "django" ]
python fancy indexing with a boolean masked array
38,454,972
<p>I have a numpy masked array of data:</p> <pre><code>data = masked_array(data = [7 -- 7 1 8 -- 1 1 -- -- 3 -- -- 3 --], mask = [False True False False False True False False True True False True True False True]) </code></pre> <p>I have a flag of a specific type of data, which is a boolean maske...
0
2016-07-19T09:46:44Z
38,455,685
<p>What about something like:</p> <pre><code>import numpy as np from numpy.ma import masked_array data = masked_array(data = [7, 0, 7, 1, 8, 0, 1, 1, 0, 0, 3, 0, 0, 3, 0], mask = [False, True, False, False, False, True, False, False, True, True,...
2
2016-07-19T10:17:25Z
[ "python", "numpy", "indexing", "masked-array" ]
python fancy indexing with a boolean masked array
38,454,972
<p>I have a numpy masked array of data:</p> <pre><code>data = masked_array(data = [7 -- 7 1 8 -- 1 1 -- -- 3 -- -- 3 --], mask = [False True False False False True False False True True False True True False True]) </code></pre> <p>I have a flag of a specific type of data, which is a boolean maske...
0
2016-07-19T09:46:44Z
38,458,630
<p>I figured out how indexing with masked arrays works. </p> <p>In fact, python does not deal with this kind of indexing.</p> <p>When doing something like <code>data[flag]</code> with <code>flag</code> a boolean masked array, python takes the underlying data of <code>flag</code>. In other words, it takes the values o...
0
2016-07-19T12:29:11Z
[ "python", "numpy", "indexing", "masked-array" ]
python fancy indexing with a boolean masked array
38,454,972
<p>I have a numpy masked array of data:</p> <pre><code>data = masked_array(data = [7 -- 7 1 8 -- 1 1 -- -- 3 -- -- 3 --], mask = [False True False False False True False False True True False True True False True]) </code></pre> <p>I have a flag of a specific type of data, which is a boolean maske...
0
2016-07-19T09:46:44Z
38,467,561
<p>If I reconstruct your arrays with:</p> <pre><code>In [28]: d=np.ma.masked_equal([7,0,7,1,8,0,1,1,0,0,3,0,0,3,0],0) In [29]: f=np.ma.MaskedArray([True,False,False,True, False,False,False,False,True,True,True,True,True,True,True],[False, False, False, False, True, True, True, False, True, False, True, True, True, Tr...
1
2016-07-19T20:06:53Z
[ "python", "numpy", "indexing", "masked-array" ]
Tastypie : Usage of the XML aspects requires lxml and defusedxml
38,454,978
<p>I'm getting the following error while running Tastypie from production server whilst it's working fine in development environment :</p> <pre><code>File "/opt/python/run/venv/lib/python2.7/site-packages/tastypie/serializers.py" in to_xml 446. "Usage of the XML aspects requires lxml and defusedxml.") </code></pre> <...
0
2016-07-19T09:47:07Z
38,484,231
<p>If you ever have this problem, the reason is that indeed, the path where is installed the library is not in your Apache Python path.</p> <p>The problem from my side was that I installed the package manually and it went in the <code>dist-package</code> directory instead of the <code>site-package</code> directory whe...
0
2016-07-20T14:35:35Z
[ "python", "amazon-web-services", "lxml", "tastypie" ]
Is there a way to test methods with a lot of raw_input in django?
38,455,009
<p>I have found this URL here: <a href="http://stackoverflow.com/questions/21046717/python-mocking-raw-input-in-unittests">python mocking raw input in unittests</a></p> <p>and it answers my question somewhat, but what about the case when there is a lot of raw_inputs? something like this...</p> <pre><code>class MyMode...
1
2016-07-19T09:48:48Z
38,455,208
<p>Simple answer: wraps each call to <code>raw_input()</code> in distinct object that you can easily mock.</p>
1
2016-07-19T09:56:44Z
[ "python", "django" ]
Is there a way to test methods with a lot of raw_input in django?
38,455,009
<p>I have found this URL here: <a href="http://stackoverflow.com/questions/21046717/python-mocking-raw-input-in-unittests">python mocking raw input in unittests</a></p> <p>and it answers my question somewhat, but what about the case when there is a lot of raw_inputs? something like this...</p> <pre><code>class MyMode...
1
2016-07-19T09:48:48Z
38,455,748
<p>If I understand correctly, you wanted to mock each and every <code>raw_input</code> method but set different return value. <code>unittest.mock</code> comes up with <code>side_effect</code> properties. that can be helpful in this case. <a href="https://docs.python.org/3/library/unittest.mock.html#quick-guide" rel="no...
1
2016-07-19T10:20:00Z
[ "python", "django" ]
turn displays on with python under Windows 7 64bit
38,455,038
<p>I'm trying to turn displays on using python. Found <a href="https://github.com/arjun024/turn-off-screen/blob/master/platform-specific/turnoff_win8.1.py" rel="nofollow">this</a> code very useful but the problem is that it is turning display on for a brief moment and after like 1 second all displays are still 'enterin...
-4
2016-07-19T09:49:41Z
38,456,285
<p>Thanks for the hint, <strong>martineau</strong>! Simple sending message like that will not work:</p> <pre><code>win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SYSCOMMAND, SC_MONITORPOWER, -1) </code></pre> <p>I also tried:</p> <pre><code>ctypes.windll.user32.SetCursorPos(100, 20) </code></pre> <p>and<...
0
2016-07-19T10:44:33Z
[ "python", "windows" ]
Using .ix loses headers
38,455,054
<p>How come when I use:</p> <pre><code>dfa=df1["10_day_mean"].ix["2015":"2015"] </code></pre> <p>The dataframe dfa has no header?</p> <p>dfa:</p> <pre><code>Date 2015-01-10 2.000000 2015-01-20 3.000000 </code></pre> <p>df1:</p> <pre><code> 10day_mean Attenuation Channel1 Channel2 Channel3 Cha...
0
2016-07-19T09:50:28Z
38,455,568
<p>Your confusion here is that when you do this:</p> <pre><code>dfa=df1["10_day_mean"].ix["2015":"2015"] </code></pre> <p>this returns a <code>Series</code> which only has a single column so the output doesn't show the column name above the column, it'll show it at the bottom in the summary info as <code>name</code>....
0
2016-07-19T10:11:58Z
[ "python", "pandas", "dataframe" ]
Exit Fullscreen QMediaPlayer
38,455,130
<p>My question is how do I exit full screen. I have made a program that is set up as such:</p> <pre><code> class Ui_MainWindow(object): def UI: some random ui stuff self.fullscreenbutton.clicked.connect(self.fullscreen) def vid(self): self.Video_Player = QtMultime...
0
2016-07-19T09:53:47Z
38,475,208
<pre><code>class Ui_MainWindow(object): def setupUi(self, MainWindow): self.Video_Widget=Video_Widget_Class() self.horizontalLayout_4.addWidget(self.Video_Widget) class Video_Widget_Class(QVideoWidget): def Video_Widget(self): self.Video_Player = QtMultimediaWidget...
0
2016-07-20T07:40:47Z
[ "python", "pyqt", "pyqt5", "qmediaplayer" ]
combining/merging multiple 2d arrays into single array by using python
38,455,254
<p>I have four 2 dimensional np arrays. Shape of each array is (203 , 135). Now I want join all these arrays into one single array with respect to latitude and longitude.</p> <p>I have used code below to read data</p> <pre><code>import pandas as pd import numpy as np import os import glob from pyhdf import SD import ...
0
2016-07-19T09:59:04Z
38,458,637
<p>This should be a comment, yet the comment space is not enough for these questions. Therefore I am posting here: </p> <p>You say that you have 4 input arrays (a,b,c,d) which are somehow to be intergrated into an output array. As far as is understood, two of these arrays contain positional information (x,y) such as l...
0
2016-07-19T12:29:27Z
[ "python", "arrays", "numpy", "gdal" ]
Pands: Apply function over each pair of columns under constraints
38,455,278
<p>As title says, I'm trying to apply a function over each pair of columns of a dataframe under some conditions. I'm going to try to illustrate this. My df is of the form:</p> <pre><code>Code | 14 | 17 | 19 | ... w1 | 0 | 5 | 3 | ... w2 | 2 | 5 | 4 | ... w3 | 0 | 0 | 5 | ... </c...
0
2016-07-19T10:00:01Z
38,457,101
<p>To apply the cosine metric to each pair from two collections of inputs, you could use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist" rel="nofollow"><code>scipy.spatial.distance.cdist</code></a>. This will be much much faster than using a d...
1
2016-07-19T11:21:38Z
[ "python", "pandas", "cosine-similarity" ]
Simple function that returns a number incremented by 1 on each call, without globals?
38,455,353
<p>I am trying to write a python function that on the first call, returns a 1. On the second call, returns a 2. On the third, a 3. Etc.</p> <p>Currently, I have achieved this using a global variable:</p> <pre><code>index = 0 def foo(): global index index += 1 return index </code></pre> <p>When calling t...
8
2016-07-19T10:03:32Z
38,455,478
<p>You can use function attributes:</p> <pre><code>def f(): f.counter = getattr(f, 'counter', 0) + 1 return f.counter </code></pre> <p>Or closures:</p> <pre><code>def w(): counter = 0 def f(): nonlocal counter counter += 1 return counter return f </code></pre>
6
2016-07-19T10:08:34Z
[ "python", "increment" ]
Simple function that returns a number incremented by 1 on each call, without globals?
38,455,353
<p>I am trying to write a python function that on the first call, returns a 1. On the second call, returns a 2. On the third, a 3. Etc.</p> <p>Currently, I have achieved this using a global variable:</p> <pre><code>index = 0 def foo(): global index index += 1 return index </code></pre> <p>When calling t...
8
2016-07-19T10:03:32Z
38,455,715
<p>Using a closure:</p> <pre><code>def make_inc(): val = [0] def inc(): val[0] += 1 return val[0] return inc inc = make_inc() print inc() print inc() print inc() </code></pre> <p>Using a class (the most obvious solution in an OOPL ):</p> <pre><code>class Inc(object): def __init__(sel...
11
2016-07-19T10:18:33Z
[ "python", "increment" ]
Simple function that returns a number incremented by 1 on each call, without globals?
38,455,353
<p>I am trying to write a python function that on the first call, returns a 1. On the second call, returns a 2. On the third, a 3. Etc.</p> <p>Currently, I have achieved this using a global variable:</p> <pre><code>index = 0 def foo(): global index index += 1 return index </code></pre> <p>When calling t...
8
2016-07-19T10:03:32Z
38,455,753
<p>I will provide an alternative solution to Sergey's answer: exploit <a href="http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">mutable default arguments!</a></p> <pre><code>def f(_=[0]): _[0] += 1 return _[0] </code></pre> <p>This has the disadvantage that...
4
2016-07-19T10:20:11Z
[ "python", "increment" ]
Simple function that returns a number incremented by 1 on each call, without globals?
38,455,353
<p>I am trying to write a python function that on the first call, returns a 1. On the second call, returns a 2. On the third, a 3. Etc.</p> <p>Currently, I have achieved this using a global variable:</p> <pre><code>index = 0 def foo(): global index index += 1 return index </code></pre> <p>When calling t...
8
2016-07-19T10:03:32Z
38,455,782
<p>Can you use an object? </p> <pre><code>class Incrementer: def __init__(self): self.value = 0 def __call__(self): print(self.value) self.value += 1 </code></pre> <p>Then you can call it like a function after instantiating it:</p> <pre><code>&gt;&gt;&gt; a = Incrementer() &gt;&gt;&...
2
2016-07-19T10:21:34Z
[ "python", "increment" ]
Simple function that returns a number incremented by 1 on each call, without globals?
38,455,353
<p>I am trying to write a python function that on the first call, returns a 1. On the second call, returns a 2. On the third, a 3. Etc.</p> <p>Currently, I have achieved this using a global variable:</p> <pre><code>index = 0 def foo(): global index index += 1 return index </code></pre> <p>When calling t...
8
2016-07-19T10:03:32Z
38,455,883
<p>You can use generator also.</p> <pre><code>def yrange(n): i = 0 while i &lt; n: yield i i += 1 </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; y = yrange(3) &gt;&gt;&gt; y &lt;generator object yrange at 0x401f30&gt; &gt;&gt;&gt; y.next() 0 &gt;&gt;&gt; y.next() 1 &gt;&gt;&gt; y.next()...
1
2016-07-19T10:25:47Z
[ "python", "increment" ]
Simple function that returns a number incremented by 1 on each call, without globals?
38,455,353
<p>I am trying to write a python function that on the first call, returns a 1. On the second call, returns a 2. On the third, a 3. Etc.</p> <p>Currently, I have achieved this using a global variable:</p> <pre><code>index = 0 def foo(): global index index += 1 return index </code></pre> <p>When calling t...
8
2016-07-19T10:03:32Z
38,466,745
<p>You can also improve generator, make it more flexible: </p> <pre><code>def counter_gen(): count = 0 while True: res = yield count count += res &gt;&gt;&gt; counter = counter_gen() &gt;&gt;&gt; counter.send(None) #initialize generator &gt;&gt;&gt; 0 &gt;&gt;&gt; counter.send(1) &gt;&gt;&gt;...
0
2016-07-19T19:15:38Z
[ "python", "increment" ]
randomly sort a list with bias
38,455,356
<p>I have a list as follows:<br/></p> <pre><code>i = [ {'id': '1', 'P': 0.5}, {'id': '2', 'P': 0.4}, {'id': '3', 'P': 0.8}, ... {'id': 'x', 'P': P(x)} ] </code></pre> <p>When I do the following:</p> <pre><code>i.sort(key=lambda x: x['P'], reverse=True) </code></pre> <p>Th...
1
2016-07-19T10:03:40Z
38,457,314
<p>According to my understanding, you want to have the list sorted but still want some some randomness. A list cannot be sorted as well as random at the same time. The nearest can be achieved via something like </p> <pre><code>i.sort(key=lambda x: x['P']*random.triangular(0.6, 1.4), reverse=True) </code></pre> <p>Thi...
3
2016-07-19T11:31:32Z
[ "python", "list", "sorting", "random" ]
randomly sort a list with bias
38,455,356
<p>I have a list as follows:<br/></p> <pre><code>i = [ {'id': '1', 'P': 0.5}, {'id': '2', 'P': 0.4}, {'id': '3', 'P': 0.8}, ... {'id': 'x', 'P': P(x)} ] </code></pre> <p>When I do the following:</p> <pre><code>i.sort(key=lambda x: x['P'], reverse=True) </code></pre> <p>Th...
1
2016-07-19T10:03:40Z
38,458,057
<p>As I alluded to in a comment, you could sort with a level of random bias by sampling a bias factor from a standard normal distribution. You can then add this bias (which is symmetrical either side of zero) to your P value.</p> <pre><code>import numpy as np #Give some control over the level of rearrangement - large...
3
2016-07-19T12:04:55Z
[ "python", "list", "sorting", "random" ]
randomly sort a list with bias
38,455,356
<p>I have a list as follows:<br/></p> <pre><code>i = [ {'id': '1', 'P': 0.5}, {'id': '2', 'P': 0.4}, {'id': '3', 'P': 0.8}, ... {'id': 'x', 'P': P(x)} ] </code></pre> <p>When I do the following:</p> <pre><code>i.sort(key=lambda x: x['P'], reverse=True) </code></pre> <p>Th...
1
2016-07-19T10:03:40Z
38,459,325
<p>Here is my take on it: Suppose that item 1 has similarity score <code>0.3</code> and item 2 has similarity score <code>0.4</code>. Then, it seems reasonable that when choosing between these two items, item 1 should be before item 2 with probability <code>0.3 / (0.3 + 0.4)</code>. This way the higher-scored item is <...
2
2016-07-19T12:58:51Z
[ "python", "list", "sorting", "random" ]
How do I append a list of multiple objects to the end of a file path?
38,455,468
<p>I have created a for loop to create a list containing the string 'size_i' so I have size_01, size_02, size_03 etc all the way to size_84. Like:</p> <pre><code>def size(): x = list() for i in range(0,84): x = x.append('size' + str(i)) return x </code></pre> <p>This works fine. Now I want to save...
0
2016-07-19T10:08:08Z
38,456,126
<p>From what I understand of the question, you are writing your function wrong. <code>x.append('size_' + str(i))</code> returns <code>None</code>, so basically you were replacing x with <code>None</code> in <code>x = x.append('size_' + str(i))</code> which was giving an error when you were trying to join. Your current ...
0
2016-07-19T10:37:50Z
[ "python", "list", "python-2.7", "function" ]
How do I append a list of multiple objects to the end of a file path?
38,455,468
<p>I have created a for loop to create a list containing the string 'size_i' so I have size_01, size_02, size_03 etc all the way to size_84. Like:</p> <pre><code>def size(): x = list() for i in range(0,84): x = x.append('size' + str(i)) return x </code></pre> <p>This works fine. Now I want to save...
0
2016-07-19T10:08:08Z
38,456,134
<p>Does this work for you? </p> <pre><code>import os def size(): d_path = '/home/Jake/Documents/sizes' x = [] p = [] for i in range(0,84): z = 'size_' + str(i) x.append(z) p.append(d_path+z) return p </code></pre>
0
2016-07-19T10:38:05Z
[ "python", "list", "python-2.7", "function" ]
How do I append a list of multiple objects to the end of a file path?
38,455,468
<p>I have created a for loop to create a list containing the string 'size_i' so I have size_01, size_02, size_03 etc all the way to size_84. Like:</p> <pre><code>def size(): x = list() for i in range(0,84): x = x.append('size' + str(i)) return x </code></pre> <p>This works fine. Now I want to save...
0
2016-07-19T10:08:08Z
38,456,246
<p>Try this one</p> <pre><code>import os def size(): d_path = '/home/Jake/Documents/sizes' x = list() for i in range(0,84): x.append(os.path.join(d_path,'size_' + str(i))) return x </code></pre>
0
2016-07-19T10:43:04Z
[ "python", "list", "python-2.7", "function" ]
How do I append a list of multiple objects to the end of a file path?
38,455,468
<p>I have created a for loop to create a list containing the string 'size_i' so I have size_01, size_02, size_03 etc all the way to size_84. Like:</p> <pre><code>def size(): x = list() for i in range(0,84): x = x.append('size' + str(i)) return x </code></pre> <p>This works fine. Now I want to save...
0
2016-07-19T10:08:08Z
38,456,294
<p>The function append in class list doesn't return a significant value.</p>
0
2016-07-19T10:44:48Z
[ "python", "list", "python-2.7", "function" ]
How do I append a list of multiple objects to the end of a file path?
38,455,468
<p>I have created a for loop to create a list containing the string 'size_i' so I have size_01, size_02, size_03 etc all the way to size_84. Like:</p> <pre><code>def size(): x = list() for i in range(0,84): x = x.append('size' + str(i)) return x </code></pre> <p>This works fine. Now I want to save...
0
2016-07-19T10:08:08Z
38,456,533
<p>Try this:</p> <pre><code>import os def size(): d_path = '/home/Jake/Documents/sizes' x = [] p=[] for i in range(0,84): x.append('size_{:02}'.format(i)) p.append(os.path.join(d_path,x[i])) return p print size() </code></pre>
0
2016-07-19T10:54:21Z
[ "python", "list", "python-2.7", "function" ]
How do I append a list of multiple objects to the end of a file path?
38,455,468
<p>I have created a for loop to create a list containing the string 'size_i' so I have size_01, size_02, size_03 etc all the way to size_84. Like:</p> <pre><code>def size(): x = list() for i in range(0,84): x = x.append('size' + str(i)) return x </code></pre> <p>This works fine. Now I want to save...
0
2016-07-19T10:08:08Z
38,456,539
<p>Some of these answers are unnecessarily long and complex, but may more be insightful about what's going on than the following snippets:</p> <p><strong>Clear Approach</strong></p> <pre><code>path_root = "/home/Jake/Documents/sizes" sizes = ["size_%d" % i for i in range(84)] paths = [os.path.join(path_root, s) for ...
0
2016-07-19T10:54:42Z
[ "python", "list", "python-2.7", "function" ]
How do I append a list of multiple objects to the end of a file path?
38,455,468
<p>I have created a for loop to create a list containing the string 'size_i' so I have size_01, size_02, size_03 etc all the way to size_84. Like:</p> <pre><code>def size(): x = list() for i in range(0,84): x = x.append('size' + str(i)) return x </code></pre> <p>This works fine. Now I want to save...
0
2016-07-19T10:08:08Z
38,461,998
<p>Thank you all for your clear help, I see where I have been going wrong now!</p>
0
2016-07-19T14:54:58Z
[ "python", "list", "python-2.7", "function" ]
How can I pick specific records in TensorFlow from a .tfrecords file?
38,455,548
<p>My goal is to train a neural net for a fixed number of epochs or steps, I would like each step to use a batch of data of a specific size from a .tfrecords file. </p> <p>Currently I am reading from the file using this loop:</p> <pre><code>i = 0 data = np.empty(shape=[x,y]) for serialized_example in tf.python_io.tf...
0
2016-07-19T10:11:18Z
40,104,973
<p>Impossible. TFRecords is a streaming reader and has no random access.</p> <blockquote> <p>A TFRecords file represents a sequence of (binary) strings. The format is not random access, so it is suitable for streaming large amounts of data but not suitable if fast sharding or other non-sequential access is desired.<...
0
2016-10-18T09:50:21Z
[ "python", "python-2.7", "numpy", "machine-learning", "tensorflow" ]
Bypassing size limitation on a subprocess command
38,455,598
<p>I need your help to solve my problem. I want to launch a powershell command using subprocess. However the command used will be very long, so it will be bigger than the size of the buffer. I have done many tests and right now I'm not able to find a good solution. I would like to split my big buffer (it's a base64 co...
0
2016-07-19T10:13:29Z
38,636,977
<p>The solution that I've found is easy to implement. The goal is to keep the subprocess open and to write the buffer in stdin. Here is an example:</p> <pre><code># keep the pipe open p = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=True) # initialize the powershell value p.stdin.write("$data=\"...
1
2016-07-28T12:53:24Z
[ "python", "size", "subprocess", "buffer", "maxlength" ]
Python Referencing old OpenSSL
38,455,688
<p>This may sound like the copy of <a href="http://stackoverflow.com/questions/24323858/python-referencing-old-ssl-version">this</a> question but not only all the solutions do not work, but the question itself is pretty old and things may have changed in the mean time.</p> <p>The following is my problem:</p> <pre><co...
1
2016-07-19T10:17:32Z
38,970,261
<p>did you figure this out? I'm following the same steps but Python is still importing the old OpenSSL version.</p>
1
2016-08-16T08:42:12Z
[ "python", "osx", "openssl" ]
Python Referencing old OpenSSL
38,455,688
<p>This may sound like the copy of <a href="http://stackoverflow.com/questions/24323858/python-referencing-old-ssl-version">this</a> question but not only all the solutions do not work, but the question itself is pretty old and things may have changed in the mean time.</p> <p>The following is my problem:</p> <pre><co...
1
2016-07-19T10:17:32Z
39,496,285
<p>I'm in the same boat, looking for a similar set of solutions.</p>
0
2016-09-14T17:21:21Z
[ "python", "osx", "openssl" ]
How to implement token based pagination using cassandra python-driver?
38,455,736
<p>Yes, iterate over <code>Query</code> is good thing, but i need paging results and send them with token to frontend. </p> <p>Can i create token for previous page too?</p> <p>How can i <strong>get and use</strong> <code>ResponseFuture._paging_state</code> in Models or Querysets.</p> <p>I search something like <a hr...
0
2016-07-19T10:19:20Z
38,525,339
<p>I'm afraid this isn't possible. At least I can't see a way for this to work by looking at the API and the documentation. There seems to be an open ticket (<a href="https://datastax-oss.atlassian.net/browse/PYTHON-200" rel="nofollow">PYTHON-200</a>) created by <a href="https://stackoverflow.com/users/20688/adam-holmb...
2
2016-07-22T11:29:29Z
[ "python", "orm", "cassandra", "datastax-enterprise", "cassandra-python-driver" ]
How to implement token based pagination using cassandra python-driver?
38,455,736
<p>Yes, iterate over <code>Query</code> is good thing, but i need paging results and send them with token to frontend. </p> <p>Can i create token for previous page too?</p> <p>How can i <strong>get and use</strong> <code>ResponseFuture._paging_state</code> in Models or Querysets.</p> <p>I search something like <a hr...
0
2016-07-19T10:19:20Z
39,450,298
<p>Fixed in <code>python driver v 3.7.0</code> You can find usage example in tests files on <a href="https://github.com/datastax/python-driver/commit/acd5f746d2f7586d94b8d96d2873aace1fdc5bf9" rel="nofollow">Github</a></p> <pre class="lang-py prettyprint-override"><code>page_state = result_set.paging_state result_set =...
0
2016-09-12T12:25:52Z
[ "python", "orm", "cassandra", "datastax-enterprise", "cassandra-python-driver" ]
Create google calendar appointment slots via API
38,455,964
<p>Google calendar has this feature called <a href="https://support.google.com/calendar/answer/190998?hl=en" rel="nofollow">Appointment slots</a></p> <p>But I can't find any API endpoints to create appointment slots. Does the google api support them? The documentation doesn't seem to mention it as well.</p>
0
2016-07-19T10:30:06Z
38,478,452
<p>Reading Google's blog entitled <a href="https://googleblog.blogspot.ca/2012/12/winter-cleaning.html" rel="nofollow">"Winter Cleaning"</a>, Appointment slots has been discontinued last <em>January 4, 2013</em>.</p> <blockquote> <p>"You’ll be unable to create new reservable times on your Calendar through Appoin...
0
2016-07-20T10:14:45Z
[ "python", "google-apps-script", "google-calendar", "google-apps" ]
Select rows from a pandas dataframe where two columns match list of pairs
38,456,273
<p>I'm trying to create a boolean mask (or list of indices) from a dataframe to indicate where multiple columns match some combinations in a list. Here's an example:</p> <pre><code>import pandas as pd df = pd.DataFrame({'A': ['alice', 'bob', 'charlie', 'dave', 'dave'], 'B': ['andy', 'bridget', 'cha...
1
2016-07-19T10:44:02Z
38,456,344
<p>You could perform a <code>outer</code> type merge with <code>indicator=True</code> param and test whether <code>_merge</code> <code>column == 'both'</code>:</p> <pre><code>In [97]: merged = df.merge(pairs, how='outer', indicator=True) merged[merged['_merge'] =='both'].index Out[97]: Int64Index([0, 3], dtype='int64...
1
2016-07-19T10:47:06Z
[ "python", "pandas" ]
Python replace and strip not working to remove carriage return and new line \r\n
38,456,295
<p>First of all, I'm sorry I'm asking this question, because by the looks of things there are hundreds of posts about removing \n and the like from a variable, but nothing seems to work for me.</p> <p>So I'm using an arduino to sample values from a sensor and sending them across serial to my python script and reading ...
1
2016-07-19T10:44:49Z
38,456,584
<p><code>b'100\r\n'</code> is the internal representation of the (byte) string, and you don't need to do anything special to pass it to <code>int</code>:</p> <pre><code>&gt;&gt;&gt; s = b'100\r\n' &gt;&gt;&gt; print(s) b'100\r\n' &gt;&gt;&gt; int(s) 100 &gt;&gt;&gt; </code></pre>
2
2016-07-19T10:56:34Z
[ "python", "replace", "newline" ]
Individual timeouts for concurrent.futures
38,456,357
<p>I see two ways to specify timeouts in <a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow"><code>concurrent.futures</code></a>.</p> <ul> <li><code>as_completed()</code></li> <li><code>wait()</code></li> </ul> <p>Both methods handle N running futures.</p> <p>I would like to specify an...
13
2016-07-19T10:47:48Z
38,576,573
<p>How about implementing your own:</p> <pre><code>wait(dbfutures + httpfutures, timeout=0.5) [fut.cancel() for fut in bdfutures if not fut.done()] wait(httpfutures, timeout=0.7) [fut.cancel() for fut in httpfutures if not fut.done()] </code></pre> <p>(or a while loop with sleep/check or wait with short timeout)</p>
5
2016-07-25T20:10:07Z
[ "python", "concurrency", "parallel-processing", "concurrent.futures" ]
FeatureUnion in scikit klearn and incompatible row dimension
38,456,377
<p>I have started to use scikit learn for text extraction. When I use standard function CountVectorizer and TfidfTransformer in a pipeline and when I try to combine with new features ( a concatention of matrix) I have got a row dimension problem.</p> <p>This is my pipeline:</p> <pre><code>pipeline = Pipeline([('feats...
0
2016-07-19T10:48:27Z
38,498,848
<p>OK, I will try to give more explication. When I say do_something, I say do_nothing with X. In the class AddNed if I rewrite :</p> <pre><code>def transform (self, X, **transform_params): print(X.shape) #Print X shape on first line before do anything print(type(X)) #For information do_nothing_withX #C...
0
2016-07-21T08:24:06Z
[ "python", "scikit-learn", "pipeline", "feature-selection", "grid-search" ]
concurrent.futures not parallelizing write
38,456,458
<p>I have a list <code>dataframe_chunk</code> which contains chunks of a very large pandas dataframe.I would like to write every single chunk into a different csv, and to do so in parallel. However, I see the files being written sequentially and I'm not sure why this is the case. Here's the code:</p> <pre><code>import...
0
2016-07-19T10:51:31Z
38,458,739
<p>One thing that is stated in the <a href="https://docs.python.org/2.7/library/threading.html" rel="nofollow">Python 2.7.x <code>threading</code> docs</a> but not in the 3.x docs is that Python cannot achieve true parallelism using the <code>threading</code> library - only one thread will execute at a time.</p> <p>...
0
2016-07-19T12:34:00Z
[ "python", "multithreading", "python-3.x", "concurrent.futures" ]
Extract string inside nested brackets
38,456,603
<p>I need to extract strings from nested brackets like so:</p> <pre><code>[ this is [ hello [ who ] [what ] from the other side ] slim shady ] </code></pre> <p>Result <strong>(Order doesn't matter)</strong>:</p> <pre><code>This is slim shady Hello from the other side Who What </code></pre> <p>Note, the string coul...
2
2016-07-19T10:57:40Z
38,457,198
<p>This can quite comfortably be solved using regex:</p> <pre><code>import re s= '[ this is [ hello [ who ] [what ] from the other [side] ] slim shady ][oh my [g[a[w[d]]]]]' result= [] pattern= r'\[([^[\]]*)\]' #regex pattern to find non-nested square brackets while '[' in s: #while brackets remain result.extend...
4
2016-07-19T11:25:38Z
[ "python", "algorithm", "brackets" ]
Extract string inside nested brackets
38,456,603
<p>I need to extract strings from nested brackets like so:</p> <pre><code>[ this is [ hello [ who ] [what ] from the other side ] slim shady ] </code></pre> <p>Result <strong>(Order doesn't matter)</strong>:</p> <pre><code>This is slim shady Hello from the other side Who What </code></pre> <p>Note, the string coul...
2
2016-07-19T10:57:40Z
38,458,211
<p>You can represent your matches using a tree-like structure.</p> <pre><code>class BracketMatch: def __init__(self, refstr, parent=None, start=-1, end=-1): self.parent = parent self.start = start self.end = end self.refstr = refstr self.nested_matches = [] def __str__(s...
1
2016-07-19T12:11:53Z
[ "python", "algorithm", "brackets" ]
Extract string inside nested brackets
38,456,603
<p>I need to extract strings from nested brackets like so:</p> <pre><code>[ this is [ hello [ who ] [what ] from the other side ] slim shady ] </code></pre> <p>Result <strong>(Order doesn't matter)</strong>:</p> <pre><code>This is slim shady Hello from the other side Who What </code></pre> <p>Note, the string coul...
2
2016-07-19T10:57:40Z
38,458,711
<pre><code>a = '[ this is [ hello [ who ] [what ] from the other side ] slim shady ]' lvl = -1 words = [] for i in a: if i == '[' : lvl += 1 words.append('') elif i == ']' : lvl -= 1 else: words[lvl] += i for word in words: print ' '.join(word.split()) </code></pre> <p>...
1
2016-07-19T12:33:07Z
[ "python", "algorithm", "brackets" ]
Extract string inside nested brackets
38,456,603
<p>I need to extract strings from nested brackets like so:</p> <pre><code>[ this is [ hello [ who ] [what ] from the other side ] slim shady ] </code></pre> <p>Result <strong>(Order doesn't matter)</strong>:</p> <pre><code>This is slim shady Hello from the other side Who What </code></pre> <p>Note, the string coul...
2
2016-07-19T10:57:40Z
38,464,181
<p>This code scans the text by character and pushes an empty <code>list</code> on to the stack for every opening <code>[</code> and pops the last pushed <code>list</code> from the stack for every closing <code>]</code>. </p> <pre><code>text = '[ this is [ hello [ who ] [what ] from the other side ] slim shady ]' de...
1
2016-07-19T16:44:00Z
[ "python", "algorithm", "brackets" ]
How to connect these 2 statements in python
38,456,684
<pre><code>if ask == "yes" or ask == "Yes": print("lets go, if you dont know a question you can say 'I dont know' to leave the gameshow") else: if ask == "no" or ask == "No": print("then go home") exit(ask) print("What is the capital of Sarajevo?") if ask == "sarajevo" or ask == "Sarajevo": print(...
-6
2016-07-19T11:01:18Z
38,456,799
<p>For the whole thing to make sense, <code>ask</code> has to be provided by the user using <code>input()</code>. So i am going to assume it is. Below is a modified version of your code. Note that you do not have to get the case correctly. You can simply convert whatever answer you were given to lowercase using the <co...
0
2016-07-19T11:07:57Z
[ "python" ]
How to connect these 2 statements in python
38,456,684
<pre><code>if ask == "yes" or ask == "Yes": print("lets go, if you dont know a question you can say 'I dont know' to leave the gameshow") else: if ask == "no" or ask == "No": print("then go home") exit(ask) print("What is the capital of Sarajevo?") if ask == "sarajevo" or ask == "Sarajevo": print(...
-6
2016-07-19T11:01:18Z
38,456,854
<p>I dont understand which 2 statement you want to connect Check this if this works for you : </p> <pre><code>if ask == "yes" or ask == "Yes": statement 1 = "lets go, if you dont know a question you can say 'I dont know' to leave the gameshow" print("lets go, if you dont know a question you can say 'I dont...
0
2016-07-19T11:10:45Z
[ "python" ]
how to file.write() an empty string if dictionary produces a KeyError in python
38,456,712
<p>I have a particular problem with json files. The following code reads json, and writes to a txt file. I have shortened the code for readability, in my real code it is hundereds of fields and write statements.</p> <pre><code>import os import json def _getjson(filename): """ returns a list of dictionaries """ ...
0
2016-07-19T11:02:49Z
38,456,759
<p>Use <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="nofollow"><code>dict.get</code></a>:</p> <pre><code>f.write(d.get('field1', '') + ' ' + d.get('field2', '') + ' ' + d.get('field3', '') + '\n') </code></pre> <p><code>get()</code> returns the value for <em>key</em>, or give...
3
2016-07-19T11:05:54Z
[ "python", "python-3.x", "python-3.4" ]
how to file.write() an empty string if dictionary produces a KeyError in python
38,456,712
<p>I have a particular problem with json files. The following code reads json, and writes to a txt file. I have shortened the code for readability, in my real code it is hundereds of fields and write statements.</p> <pre><code>import os import json def _getjson(filename): """ returns a list of dictionaries """ ...
0
2016-07-19T11:02:49Z
38,456,887
<p>More simpler is <code>str.join</code> with <code>dict.values</code>.</p> <p><code>f.write(' '.join(d.values()))</code> </p> <p>or if values are not strings use genexps like</p> <p><code>f.write(' '.join(str(value) for value in d.values()))</code> </p>
2
2016-07-19T11:12:11Z
[ "python", "python-3.x", "python-3.4" ]
matching a substring in a dateframe column
38,456,792
<p>I want to match the ID column in my dataframe if the name contain a string say 'test_'. Is there a simple way to get the Boolean vector like df.ID == 'something' for df.ID contains 'test_'. </p>
1
2016-07-19T11:07:37Z
38,456,815
<p>IIUC then the following should work:</p> <pre><code>df.loc[df['ID'].str.contains('test_'), 'ID'] </code></pre> <p>this will return all ID's that contain the partial string</p> <p>If you want a boolean array against all rows:</p> <pre><code>df['ID'].str.contains('test_') </code></pre>
1
2016-07-19T11:08:50Z
[ "python", "pandas" ]
How do I update a variable value across modules Python?
38,456,878
<p>I have a main script and I am importing another module with a class in it. When I instantiate the class one of the arguments is <code>y</code> and therefore I have an equivalent <code>self.y = y</code> in the <code>__init__</code> method. Now the problem is that in the main script I have a <code>for</code> loop that...
0
2016-07-19T11:11:49Z
38,460,068
<p>I'm not really sure if it's what you want, but from my understanding you want to update the value of self.y without a method?</p> <p>This would be done by executing</p> <pre><code>object_name.y = new_value </code></pre> <p>where <code>object_name</code> is the name you gave the instance of your Class, seeing as <...
2
2016-07-19T13:30:33Z
[ "python" ]
How do I update a variable value across modules Python?
38,456,878
<p>I have a main script and I am importing another module with a class in it. When I instantiate the class one of the arguments is <code>y</code> and therefore I have an equivalent <code>self.y = y</code> in the <code>__init__</code> method. Now the problem is that in the main script I have a <code>for</code> loop that...
0
2016-07-19T11:11:49Z
38,460,550
<p>From what i've understand, mutator arn't what you are looking for. A mutator is a function within a class that access an attribut and modify it's value.</p> <p>I think in your code, you want to use <code>y</code> as if <code>self.y</code> and <code>y</code> where linked to each others. But when you give <code>y</co...
0
2016-07-19T13:51:34Z
[ "python" ]
What is the asterisk for in signal and slot connections?
38,456,924
<p>In Python Qt, I'm connecting a QListWidget signal to a slot, like this:</p> <pre><code>QtCore.QObject.connect(self.myList, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.ListEventHandler) </code></pre> <p>My question is: what does the trailing asterisk in <code>QListWidgetItem *</code> do?</p>
1
2016-07-19T11:13:54Z
38,457,033
<p>It's C++ syntax for indicating that the function <code>itemClicked</code> is passed a pointer to a <code>QListWidgetItem</code> as its only argument.</p> <p>You can think of this as being "pass by reference", rather than "pass by value".</p>
1
2016-07-19T11:18:47Z
[ "python", "qt", "pyqt", "signals-slots" ]
What is the asterisk for in signal and slot connections?
38,456,924
<p>In Python Qt, I'm connecting a QListWidget signal to a slot, like this:</p> <pre><code>QtCore.QObject.connect(self.myList, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.ListEventHandler) </code></pre> <p>My question is: what does the trailing asterisk in <code>QListWidgetItem *</code> do?</p>
1
2016-07-19T11:13:54Z
38,457,771
<p>A couple of bullet points to explain (I'll try to avoid C++ syntax):</p> <ul> <li>PyQt is a Python wrapper around Qt, which is written in C++.</li> <li>Qt provides introspection for classes inheriting from <code>QObject</code>, frequently using strings to identify things. Python has native introspection, but C++ do...
5
2016-07-19T11:51:33Z
[ "python", "qt", "pyqt", "signals-slots" ]
Python "int is not subscriptable" error
38,456,975
<p>Why isn't this working? It says <code>int is not subscriptable</code> when I run speedtest.</p> <p>This is the error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; speedtest() File "\\internal.sloughgrammar.berks.sch.uk\students$\Home\2014\14KHANDELWA...
-6
2016-07-19T11:16:20Z
38,457,206
<pre><code>val, j = 0[i], i-1 </code></pre> <p>Edit this line and try this instead - </p> <pre><code>val, j = a[i], i-1 </code></pre>
1
2016-07-19T11:25:51Z
[ "python", "insertion" ]
Pandas changing cell values based on another cell
38,457,059
<p>I am currently formatting data from two different data sets. One of the dataset reflects an observation count of people in room on hour basis, the second one is a count of people based on wifi logs generated in 5 minutes interval.</p> <p>After merging these two dataframes into one, I run into the issue where each h...
4
2016-07-19T11:19:54Z
38,458,506
<p>Somewhere to start:</p> <pre><code>b = df[(df['time'] &gt; X) &amp; (df['time'] &lt; Y)] </code></pre> <p>selects all the elements within times X and Y</p> <p>And then </p> <pre><code>df.loc[df['column_name'].isin(b)] </code></pre> <p>Gives you the rows you want (ie - between X and Y) and you can just assign as...
1
2016-07-19T12:24:00Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Pandas changing cell values based on another cell
38,457,059
<p>I am currently formatting data from two different data sets. One of the dataset reflects an observation count of people in room on hour basis, the second one is a count of people based on wifi logs generated in 5 minutes interval.</p> <p>After merging these two dataframes into one, I run into the issue where each h...
4
2016-07-19T11:19:54Z
38,461,318
<p>If I understood it correctly, you want to fill all the missing values in your merged dataframe with the corresponding closest data point available in the given hour. I did something similar in essence in the past using a variate of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="...
1
2016-07-19T14:25:46Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Pandas changing cell values based on another cell
38,457,059
<p>I am currently formatting data from two different data sets. One of the dataset reflects an observation count of people in room on hour basis, the second one is a count of people based on wifi logs generated in 5 minutes interval.</p> <p>After merging these two dataframes into one, I run into the issue where each h...
4
2016-07-19T11:19:54Z
38,599,883
<p>Actually I was able to fix this by:</p> <p>First: using partition on "time" feature in order to generate two additional columns, one for the <strong>day</strong> showed in "time" and one for the <strong>hour</strong> in the "time" column. I used the lambda functions to get these columns:</p> <pre><code>df['date'] ...
0
2016-07-26T21:06:42Z
[ "python", "python-3.x", "pandas", "dataframe" ]
c pointers and ctypes
38,457,079
<p>So, I have C++ class that I wrap in C so I can use it in Python using ctypes. Declaration of C++ class:</p> <pre><code>// Test.h class Test { public: static double Add(double a, double b); }; //Test.cpp #include "stdafx.h" #include "Test.h" double Test::Add(double a, double b) { return a + b; } </code></pr...
1
2016-07-19T11:20:54Z
38,457,569
<p>As <code>AddC</code> is a static function the pointer is not your problem.</p> <p>You need to pass <code>double</code> values to <code>AddC</code>, and get a double type back:</p> <pre><code>t.AddC.restype = c_double t.AddC(a, c_double(2), c_double(3)) </code></pre> <p>The <a href="https://docs.python.org/3/libra...
2
2016-07-19T11:43:14Z
[ "python", "c++", "c", "ctypes" ]
c pointers and ctypes
38,457,079
<p>So, I have C++ class that I wrap in C so I can use it in Python using ctypes. Declaration of C++ class:</p> <pre><code>// Test.h class Test { public: static double Add(double a, double b); }; //Test.cpp #include "stdafx.h" #include "Test.h" double Test::Add(double a, double b) { return a + b; } </code></pr...
1
2016-07-19T11:20:54Z
38,457,582
<p><a href="https://docs.python.org/3/library/ctypes.html#return-types" rel="nofollow">As stated in the documentation</a></p> <blockquote> <p>By default functions are assumed to return the C int type. Other return types can be specified by setting the <code>restype</code> attribute of the function object.</p> </bloc...
1
2016-07-19T11:43:46Z
[ "python", "c++", "c", "ctypes" ]
Python - Print script running time: each 1 or 10 minute
38,457,276
<p>I'm running scripts that take 10-80 minutes. I would like to be able to print the script running time each 1/5/10 minutes ( as i choose).</p> <p>For example i have a script where i'm creating tables and inserting data to a DB and want to measure the time through the script.</p> <p>So lets say i have some printing ...
0
2016-07-19T11:29:21Z
38,457,718
<p>You can use <a href="https://docs.python.org/3.5/library/datetime.html#datetime-objects" rel="nofollow">datetime</a>:</p> <pre><code>from datetime import datetime #at the start of the script: start_time = datetime.now() # ... some stuff ... # when you want to print the time elapsed so far: now_time = datetime.now()...
1
2016-07-19T11:49:30Z
[ "python", "performance", "function", "time", "minute" ]
Python timeout handling
38,457,316
<p>I am trying to handle timeout exception when I connecting to CIM server like that:</p> <pre><code> si = pywbem.WBEMConnection(HOST, ("root", "passwrord"), "ns",no_verification=True) </code></pre> <p>I Googled, that this function have a parameter name: "timeout" but it's only for newer version PyWBEM, which I canno...
1
2016-07-19T11:31:34Z
38,464,125
<p>Hmmm... I imagine you would have to create some type of asynchronous process to do the check.</p> <p>Borrowing from a solution from <a href="http://stackoverflow.com/questions/492519/timeout-on-a-function-call">here</a> by Rich, here is what I would try:</p> <pre><code>import multiprocessing.pool import functools ...
0
2016-07-19T16:40:20Z
[ "python", "python-2.7", "timeout" ]
cutting a trapezium (or whatever) in multiple pieces of same size
38,457,391
<p>I am just using python occasionally at the moment, so I don't get what's wrong with this code:</p> <pre><code>from sympy.solvers import solve from sympy import Symbol x = Symbol('x') xpos = list([]) for i in range(6): xp = solve(6*x+22/32*x**2-544/6*(i+1),x) xpos.append(xp) xpos1 = list([]) for i in ra...
0
2016-07-19T11:35:07Z
38,458,681
<p>I tested on Python3, with the latest version of sympy installed through <code>pip3 install sympy</code><br> And I don't see what is going wrong in your code, as it works on my computer. I would only suggest an alternative approach to creating the list xpos1 : </p> <pre><code>xpos1 = [xp[1] for xp in xpos] </code><...
0
2016-07-19T12:31:28Z
[ "python", "list" ]
cutting a trapezium (or whatever) in multiple pieces of same size
38,457,391
<p>I am just using python occasionally at the moment, so I don't get what's wrong with this code:</p> <pre><code>from sympy.solvers import solve from sympy import Symbol x = Symbol('x') xpos = list([]) for i in range(6): xp = solve(6*x+22/32*x**2-544/6*(i+1),x) xpos.append(xp) xpos1 = list([]) for i in ra...
0
2016-07-19T11:35:07Z
38,458,717
<p>Try printing out the variable before the script terminates:</p> <pre><code>from sympy.solvers import solve from sympy import Symbol x = Symbol('x') xpos = list([]) for i in range(6): xp = solve(6*x+22/32*x**2-544/6*(i+1),x) xpos.append(xp) xpos1 = list([]) for i in range(len(xpos)): xpos1.append(xp...
0
2016-07-19T12:33:18Z
[ "python", "list" ]
Django - ManyToMany relation without the cross table
38,457,409
<p>I have 2 models: City and Service. Each city record can contain many services and each service can be linked to each city.</p> <pre><code>class City(models.Model): name = models.CharField(max_length=255, unique=True) class Service(models.Model): name = models.CharField(max_length=255, unique=True) class C...
0
2016-07-19T11:35:58Z
38,457,602
<p>There is no need for the CityService table at all. A ManyToManyField <em>already</em> implies a join table; you are creating a <em>second</em> one, to no purpose at all. Have the M2M directly between City and Service.</p>
0
2016-07-19T11:44:30Z
[ "python", "django", "django-models" ]
Django - ManyToMany relation without the cross table
38,457,409
<p>I have 2 models: City and Service. Each city record can contain many services and each service can be linked to each city.</p> <pre><code>class City(models.Model): name = models.CharField(max_length=255, unique=True) class Service(models.Model): name = models.CharField(max_length=255, unique=True) class C...
0
2016-07-19T11:35:58Z
38,457,666
<p>Why not just use a structure like:</p> <pre><code>class Service(models.Model): name = models.CharField(max_length=255, unique=True) class City(models.Model): name = models.CharField(max_length=255, unique=True) service = models.ManyToManyField(Service) </code></pre>
0
2016-07-19T11:47:33Z
[ "python", "django", "django-models" ]
Django - ManyToMany relation without the cross table
38,457,409
<p>I have 2 models: City and Service. Each city record can contain many services and each service can be linked to each city.</p> <pre><code>class City(models.Model): name = models.CharField(max_length=255, unique=True) class Service(models.Model): name = models.CharField(max_length=255, unique=True) class C...
0
2016-07-19T11:35:58Z
38,457,950
<p>you misunderstood the <code>ManyToManyField</code> usage. You do not need to create a separate model to use this relation. To create a separate model to work as <code>ManyToManyField</code> relation is mentioned below. But doing so you will not able to use the feature that <code>Django</code> provides for this <code...
0
2016-07-19T11:59:43Z
[ "python", "django", "django-models" ]
pymongo why we can use a dot to get a collection instance?
38,457,449
<pre><code>from pymongo import MongoClient DBC = MongoClient("localhost").test.test </code></pre> <p>Just as the snippet above, we can use just a <code>.</code> instead of <code>get_database("test")</code> and <code>get_collection("test")</code> to get a database instance or a collection instance. Despite the convenie...
2
2016-07-19T11:38:18Z
38,457,561
<p>There is a <a href="https://docs.python.org/3/reference/datamodel.html#object.__getattr__" rel="nofollow"><em><code>__getattr__()</code> magic method</em></a> making dot notation/attribute lookup happen.</p> <p>Let's look into the source code. <code>MongoClient</code> class <a href="https://github.com/mongodb/mongo...
2
2016-07-19T11:43:05Z
[ "python", "pymongo" ]
Trying renaming all files in a folder
38,457,455
<p>I am trying the script below to rename all files in a folder.It is working fine,But when i am trying to run it outside the folder.It shows error.</p> <pre><code>import os path=os.getcwd() path=os.path.join(path,'it') filenames = os.listdir(path) i=0 for filename in filenames: os.rename(filename, "%d.jpg"%i) ...
-3
2016-07-19T11:38:35Z
38,457,533
<p>When you do <code>os.listdir(path)</code> you get the filenames of files in the folder, but not the complete paths to those files. When you call <code>os.rename</code> you need the path to the file rather than just the filename.</p> <p>You can join the filename to its parent folder's path using <a href="https://doc...
4
2016-07-19T11:41:46Z
[ "python", "python-3.x" ]
Trying renaming all files in a folder
38,457,455
<p>I am trying the script below to rename all files in a folder.It is working fine,But when i am trying to run it outside the folder.It shows error.</p> <pre><code>import os path=os.getcwd() path=os.path.join(path,'it') filenames = os.listdir(path) i=0 for filename in filenames: os.rename(filename, "%d.jpg"%i) ...
-3
2016-07-19T11:38:35Z
38,457,537
<p>You need to mention complete or relative path to file.</p> <p>In this case, it should be</p> <pre><code>path + '/' + filename </code></pre> <p>or more generally,</p> <pre><code>newpath = os.path.join(path, filename) </code></pre>
0
2016-07-19T11:42:05Z
[ "python", "python-3.x" ]
Sort list of lists that each contain a dictionary
38,457,618
<p>I have this list:</p> <pre><code>list_users= [[{'points': 9, 'values': 1, 'division': 1, 'user_id': 3}], [{'points': 3, 'values': 0, 'division': 1, 'user_id': 1}], [{'points': 2, 'values': 0, 'division': 1, 'user_id': 4}], [{'points': 9, 'values': 0, 'division': 1, 'user_id': 11}], [{'points': 3, 'values': 0, 'divi...
-1
2016-07-19T11:45:13Z
38,457,719
<p>Sort using a <a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>key</code> function for <code>sorted</code></a> that builds a tuple of <code>points</code> and <code>values</code> for each dict in each list.</p> <pre><code>def kf(x): return (x[0]["points"], x[0]["values"]) s =...
2
2016-07-19T11:49:34Z
[ "python" ]
Sort list of lists that each contain a dictionary
38,457,618
<p>I have this list:</p> <pre><code>list_users= [[{'points': 9, 'values': 1, 'division': 1, 'user_id': 3}], [{'points': 3, 'values': 0, 'division': 1, 'user_id': 1}], [{'points': 2, 'values': 0, 'division': 1, 'user_id': 4}], [{'points': 9, 'values': 0, 'division': 1, 'user_id': 11}], [{'points': 3, 'values': 0, 'divi...
-1
2016-07-19T11:45:13Z
38,457,725
<p>Access the dictionary containing <code>points</code> and <code>values</code> by <em>indexing</em> on the inner list:</p> <pre><code>list_users_sorted = sorted(list_users, key=lambda x: (x[0]['points'], x[0]['values'])) # ^ ^ </code></pre>
3
2016-07-19T11:49:46Z
[ "python" ]
Python: what did I wrong with Threads or Exceptions?
38,457,626
<p>I have the following function:</p> <pre><code>def getSuggestengineResult(suggestengine, seed, tablename): table = getTable(tablename) for keyword_result in results[seed][suggestengine]: i = 0 while True: try: allKeywords.put_item( Item={ ...
1
2016-07-19T11:45:41Z
38,458,264
<p>You have to use a specific counter if you want all your thread to have the same counter :</p> <pre><code>from multiprocessing import Lock, Process, Value class ThreadCounter(object): def __init__(self, initval=0): self.val = Value('i', initval) self.lock = Lock() def increment(self): with se...
0
2016-07-19T12:14:08Z
[ "python", "multithreading" ]
Iterating over resultset with comparison of column name - in python with Mysqldb
38,457,650
<p>i want to use python to populate a database. I have to get values out of a table, calculate a score and fill this score into anoter table. I cant figure out how i can compare the column names of a row from a resultset. Because i dont need all of the columns to calculate, but need a few others as id and type_name for...
-1
2016-07-19T11:46:55Z
38,478,993
<p>Maybe someone is searching for the answer too. With help of the previous comment, i could solve it like that</p> <pre><code>field_names = cur.description for row in rs: for index, col in enumerate(row): name = field_names[index][0] if(name == "..."): ... elif(name == "..."): ...
0
2016-07-20T10:39:57Z
[ "python", "iteration", "mysql-python" ]
Python: os.chdir does not work in Python?
38,457,784
<p>I have the below code snippet and the function <code>chdir</code> doesn't seem to work.. </p> <pre><code>cwd_path = os.getcwd() print("CWD: " + cwd_path) changed = os.chdir(r"C:/CISCO/PYTHON/My_Learning/prank") print(changed) </code></pre> <p>The below is the output:</p> <pre><code>CWD C:\CISCO\PYTHON\My_Learning...
-4
2016-07-19T11:52:02Z
38,457,869
<p>As you can read <a href="http://www.tutorialspoint.com/python/os_chdir.htm" rel="nofollow">here</a> os.chdir returns None in all the cases.</p>
1
2016-07-19T11:56:23Z
[ "python", "operating-system" ]
Python: os.chdir does not work in Python?
38,457,784
<p>I have the below code snippet and the function <code>chdir</code> doesn't seem to work.. </p> <pre><code>cwd_path = os.getcwd() print("CWD: " + cwd_path) changed = os.chdir(r"C:/CISCO/PYTHON/My_Learning/prank") print(changed) </code></pre> <p>The below is the output:</p> <pre><code>CWD C:\CISCO\PYTHON\My_Learning...
-4
2016-07-19T11:52:02Z
38,457,919
<p><code>os.chdir</code> returns <code>None</code>. </p> <p>In that case, you should set <code>changed</code> as a flag that checks if the current directory is the same as the last one:</p> <pre><code>cwd_path = os.getcwd() os.chdir(r"C:/CISCO/PYTHON/My_Learning/prank") changed = (cwd_path != os.getcwd()) print(chang...
1
2016-07-19T11:58:20Z
[ "python", "operating-system" ]
Python: os.chdir does not work in Python?
38,457,784
<p>I have the below code snippet and the function <code>chdir</code> doesn't seem to work.. </p> <pre><code>cwd_path = os.getcwd() print("CWD: " + cwd_path) changed = os.chdir(r"C:/CISCO/PYTHON/My_Learning/prank") print(changed) </code></pre> <p>The below is the output:</p> <pre><code>CWD C:\CISCO\PYTHON\My_Learning...
-4
2016-07-19T11:52:02Z
38,457,934
<p><code>os.chdir</code> doesn't return anything back to you. When you want to see what directory you are in you want <code>os.getcwd</code>. E.g.</p> <pre><code>print(os.getcwd()) os.chdir('/') print(os.getcwd()) </code></pre> <p>Outputs something like;</p> <pre> /my/home / </pre>
0
2016-07-19T11:58:59Z
[ "python", "operating-system" ]
Python: os.chdir does not work in Python?
38,457,784
<p>I have the below code snippet and the function <code>chdir</code> doesn't seem to work.. </p> <pre><code>cwd_path = os.getcwd() print("CWD: " + cwd_path) changed = os.chdir(r"C:/CISCO/PYTHON/My_Learning/prank") print(changed) </code></pre> <p>The below is the output:</p> <pre><code>CWD C:\CISCO\PYTHON\My_Learning...
-4
2016-07-19T11:52:02Z
38,457,965
<p>os.chdir does not have a output, you have to make a os.chdir() then make:</p> <pre><code> changed = os.getcwd() </code></pre> <p>that way you get the new directory</p>
0
2016-07-19T12:00:31Z
[ "python", "operating-system" ]
Selection of text as starting point of an algorithm in Python
38,457,900
<p>I 've some troubles to figure out how to make the act of selecting or clicking a word in a text a call to action for other functions</p> <p>I explain myself with the following pseudo-code of what I would like to do:</p> <pre><code>word_selected= recognition_of_selected_word_function() if(word_selected) func...
-3
2016-07-19T11:57:43Z
38,502,845
<p>Just in case someone would have the same problem, I 've found the solution in another stackoverflow question <a href="http://stackoverflow.com/questions/11927178/mouse-events-on-text-in-python-using-wxpython">Mouse events on text in Python using wxPython</a></p>
0
2016-07-21T11:18:16Z
[ "python", "algorithm" ]
Classifying two lists and arrange accordingly in python
38,457,948
<p>I'm working with 2 lists looks like this: </p> <pre><code>list_a = [x,y,z,.....] list_b = [xa,xb,xc,xd,xe,ya,yb,yc,yd,za,zb,zc,zd,ze,zf] </code></pre> <p>What I'm trying to achieve is, to make more lists while arranging the data like following: </p> <pre><code>list_x = [x,xa,xb,xc,xd,xe] list_y = [y,ya,yb...
-2
2016-07-19T11:59:41Z
38,458,102
<p>You can use this code:</p> <pre><code>list_a = ['x','y','z'] list_b = ['xa','xb','xc','xd','xe','ya','yb','yc','yd','za','zb','zc','zd','ze','zf'] print [(key, [_ for _ in list_b if key == _[0]]) for key in list_a] </code></pre> <p>It gives you a list of tuples with the first entry being the single letter and the ...
2
2016-07-19T12:07:23Z
[ "python" ]
Classifying two lists and arrange accordingly in python
38,457,948
<p>I'm working with 2 lists looks like this: </p> <pre><code>list_a = [x,y,z,.....] list_b = [xa,xb,xc,xd,xe,ya,yb,yc,yd,za,zb,zc,zd,ze,zf] </code></pre> <p>What I'm trying to achieve is, to make more lists while arranging the data like following: </p> <pre><code>list_x = [x,xa,xb,xc,xd,xe] list_y = [y,ya,yb...
-2
2016-07-19T11:59:41Z
38,458,112
<pre><code>list_a = ['x','y','z'] list_b = ['xa','xb','xc','xd','xe','ya','yb','yc','yd','za','zb','zc','zd','ze','zf'] print [[x for x in list_b if x.startswith(y)] for y in list_a] </code></pre> <p>Output :</p> <pre><code>[['xa', 'xb', 'xc', 'xd', 'xe'], ['ya', 'yb', 'yc', 'yd'], ['za', 'zb', 'zc', 'zd', 'ze',...
3
2016-07-19T12:07:52Z
[ "python" ]
Classifying two lists and arrange accordingly in python
38,457,948
<p>I'm working with 2 lists looks like this: </p> <pre><code>list_a = [x,y,z,.....] list_b = [xa,xb,xc,xd,xe,ya,yb,yc,yd,za,zb,zc,zd,ze,zf] </code></pre> <p>What I'm trying to achieve is, to make more lists while arranging the data like following: </p> <pre><code>list_x = [x,xa,xb,xc,xd,xe] list_y = [y,ya,yb...
-2
2016-07-19T11:59:41Z
38,458,159
<p>Not 100% about this formatting, but you could use a list of lists.</p> <pre><code>list_a = ["x","y","z"] list_b = ["xa","xb","xc","xd","xe","ya","yb","yc","yd","za","zb","zc","zd","ze","zf"] final_list = [] for item in list_a: item_list = [item] for value in list_b: if value[0] == item: ...
1
2016-07-19T12:09:53Z
[ "python" ]