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
Use of hdf5 library in Python with ctypes
39,154,663
<p>I would like to use <code>hdf5</code> library directly from <code>Python</code> with <code>ctypes</code>. I know that <code>h5py</code> and <code>PyTables</code> do the job perfectly. The reason I want to do this: I need to work with <code>hdf5</code> files with a <code>Python</code> interpreter where I can not inst...
0
2016-08-25T21:01:28Z
39,174,875
<p>I have followed the advices given, and I have written a small C program to discover the value of different macros. </p> <pre><code>#include "hdf5.h" #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main (void) { printf("H5F_ACC_TRUNC = %u\n",H5F_ACC_TRUNC); printf("H5P_DEFAULT = %u\n",H5P_DEFAULT...
0
2016-08-26T21:30:06Z
[ "python", "ctypes", "hdf5" ]
Installing basemap
39,154,666
<p>There are some pretty helpful links in <a href="http://gnperdue.github.io/yak-shaving/osx/python/matplotlib/2014/05/01/basemap-toolkit.html" rel="nofollow">installing basemap</a> for python, however I seem to be encountering an issue towards the end of installation when trying to test if the installation has worked ...
2
2016-08-25T21:01:46Z
39,156,099
<p>You should try to set the locale of python before importing basemap </p> <pre><code>import locale locale.setlocale(locale.LC_ALL, 'en_US') </code></pre>
1
2016-08-25T23:13:03Z
[ "python", "installation", "matplotlib-basemap" ]
How do I make a Python Docker image an OpenWhisk action?
39,154,762
<p>I have a Docker image which runs a Python program. I want now to run this container as an OpenWhisk action. How do I do this? </p> <p>I have seen several examples in other programming languages, and an excellent <a href="http://blog.altoros.com/how-to-use-openwhisk-docker-actions-in-ibm-bluemix.html" rel="nofollo...
2
2016-08-25T21:09:08Z
39,154,763
<p>It's a lot simpler now (Sept 2016) than in my previous answer.</p> <p>After having created the <code>dockerSkeleton</code> directory with the command <code>$ wsk sdk install docker</code> all you have to do is to edit the <code>Dockerfile</code> and make sure your Python (2.7 right now) is accepting parameters an...
3
2016-08-25T21:09:08Z
[ "python", "docker", "openwhisk" ]
Postgres syntax error on a DELETE query
39,154,774
<p>I've successfully run this query as a <code>SELECT</code> using DataGrip directly against the specified table, but when I try to run it as a <code>DELETE</code>, it's resulting in a syntax error.</p> <p>Code:</p> <pre><code>conn = psycopg2.connect(connection_str.format(*connection_args)) with conn, conn.cursor() ...
1
2016-08-25T21:09:50Z
39,154,917
<p>from the docs:</p> <pre><code>cur.execute( """INSERT INTO some_table (an_int, a_date, another_date, a_string) VALUES (%(int)s, %(date)s, %(date)s, %(str)s);""", {'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005, 11, 18)}) </code></pre> <p>so, for you:</p> <pre><code>cur = conn.cursor() ...
0
2016-08-25T21:22:14Z
[ "python", "postgresql", "amazon-redshift", "psycopg2" ]
PyQt, Any way to use one changeValue method for multiple sliders?
39,154,886
<p>I need to have 3 sliders (or more). So at the moment, I have three different changeValues methods for each slider. </p> <p>In initUI(self), I have three sliders:</p> <pre><code> sigmaTitle = QtGui.QLabel('Sigma') sigmaSlider = QtGui.QSlider(QtCore.Qt.Horizontal, self) sigmaSlider.setRange(0, 100) si...
0
2016-08-25T21:19:28Z
39,160,103
<p>Yes, you can connect all slider <code>valueChanged</code> signals to the same slot. If you need to know which slider has sent the signal, you can use the <code>QObject.sender()</code> method inside the slot. See <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qobject.html#sender" rel="nofollow">QObject.sender()</a> ...
0
2016-08-26T06:55:20Z
[ "python", "qt", "pyqt", "slider" ]
How can I dynamically read streamed/pushed data from a webpage with java or Python?
39,154,937
<p>I am looking for the best approach that can help me to fetch/receive a Push Stream (e.g. lightstreamer) from a Web-Page. </p> <p>It is not possible to program a crawler for this as the website updates a Table via JavaScript every 5 seconds, it is dynamically loaded. </p> <p>I want this Table of data from this web ...
0
2016-08-25T21:24:07Z
39,155,256
<p>You can use <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a> to retrieve the web page.</p> <p>Then parse the response every 5sec.</p>
0
2016-08-25T21:49:31Z
[ "javascript", "java", "python", "http", "stream" ]
How can I dynamically read streamed/pushed data from a webpage with java or Python?
39,154,937
<p>I am looking for the best approach that can help me to fetch/receive a Push Stream (e.g. lightstreamer) from a Web-Page. </p> <p>It is not possible to program a crawler for this as the website updates a Table via JavaScript every 5 seconds, it is dynamically loaded. </p> <p>I want this Table of data from this web ...
0
2016-08-25T21:24:07Z
39,355,646
<p>It looks like their <a href="http://www.lightstreamer.com/repo/distros/Lightstreamer_Allegro-Presto-Vivace_6_0_3_20160905.zip%23/Lightstreamer/DOCS-SDKs/sdk_client_web_unified/doc/API-reference/index.html" rel="nofollow">JavaScript Client Library</a> is what you want. If you program it in Python or Java you'll just...
0
2016-09-06T18:32:19Z
[ "javascript", "java", "python", "http", "stream" ]
pyodbc/sqlalchemy - read each column in the table using pd.read_sql_query. Pass variable through the query
39,154,972
<p>I want to pass a variable 'single_column' through pd.read_sql_query in loop:</p> <pre><code>for single_column in columns_list: df_trial_queries = pd.read_sql_query("SELECT single_column FROM dw.db.table;",db_cnxn) </code></pre> <p>I tried to use something like this:</p> <pre><code>for single_column in col...
0
2016-08-25T21:27:05Z
39,155,116
<p>You can't "paremeterize" table or column names in SQL (SQL allows to "parameterize" <a href="https://en.wikipedia.org/wiki/Literal_(computer_programming)" rel="nofollow">literals</a> only), but you can easily do it on Python level:</p> <pre><code>In [25]: single_column = 'col1' In [52]: table = 'dw.db.table' In [...
1
2016-08-25T21:38:36Z
[ "python", "sql", "pandas", "sqlalchemy", "pyodbc" ]
How to get elements in a string after and until a specific point in Python?
39,155,022
<p>I'm sure the title sounded a bit cryptic but I couldn't think of a better way to ask the question.</p> <p>I have this code: </p> <pre><code>from bs4 import BeautifulSoup from requests import get import re eune = 'http://www.lolking.net/leaderboards#/eune/1' patt = re.compile("\$\.get\('/leaderboards/(\w+)/") js ...
0
2016-08-25T21:31:45Z
39,155,064
<p>If <code>json</code> is your dictionary, you can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>username_list = [summoner['name'] for summoner in json['data']] </code></pre> <p>Output:</p> <pre><code>['Sadastyczny', ...
2
2016-08-25T21:34:40Z
[ "python" ]
How to get elements in a string after and until a specific point in Python?
39,155,022
<p>I'm sure the title sounded a bit cryptic but I couldn't think of a better way to ask the question.</p> <p>I have this code: </p> <pre><code>from bs4 import BeautifulSoup from requests import get import re eune = 'http://www.lolking.net/leaderboards#/eune/1' patt = re.compile("\$\.get\('/leaderboards/(\w+)/") js ...
0
2016-08-25T21:31:45Z
39,155,092
<p>I don't understand why you're talking about strings. Json is a serialisation format that you decode into Python objects: in this case, a dict. You can get the name with <code>json['data'][0]['name']</code>.</p>
1
2016-08-25T21:36:46Z
[ "python" ]
How to get elements in a string after and until a specific point in Python?
39,155,022
<p>I'm sure the title sounded a bit cryptic but I couldn't think of a better way to ask the question.</p> <p>I have this code: </p> <pre><code>from bs4 import BeautifulSoup from requests import get import re eune = 'http://www.lolking.net/leaderboards#/eune/1' patt = re.compile("\$\.get\('/leaderboards/(\w+)/") js ...
0
2016-08-25T21:31:45Z
39,155,098
<p>You may achieve this by using <code>map</code> and <code>lambda</code> function as:</p> <pre><code># my_json = your json object &gt;&gt;&gt; map(lambda x: x['name'], my_json['data']) ['Sadastyczny', 'Richor', 'Azzapp', 'YanetGarcia1337', 'Rapisher', 'Kizuro', 'Nataa', 'Huunnt\xc3\xa9r', 'Hades147', 'Yolo Que Warr...
0
2016-08-25T21:37:33Z
[ "python" ]
Unable to mock open, even when using the example from the documentation
39,155,048
<p>I've copied and pasted the following code directly from the Python <a href="https://docs.python.org/3/library/unittest.mock.html#mock-open" rel="nofollow">mock docs</a>:</p> <pre><code>from unittest.mock import patch, mock_open with patch('__main__.open', mock_open(read_data='bibble')) as m: with open('foo') a...
2
2016-08-25T21:33:24Z
39,155,212
<p>Well, <code>__main__</code> is the module name given by default when you run a script.</p> <p>Paste the code in a python file and call it.</p>
0
2016-08-25T21:46:05Z
[ "python", "python-3.x", "io", "mocking" ]
Unable to mock open, even when using the example from the documentation
39,155,048
<p>I've copied and pasted the following code directly from the Python <a href="https://docs.python.org/3/library/unittest.mock.html#mock-open" rel="nofollow">mock docs</a>:</p> <pre><code>from unittest.mock import patch, mock_open with patch('__main__.open', mock_open(read_data='bibble')) as m: with open('foo') a...
2
2016-08-25T21:33:24Z
39,155,250
<p>I figured it out.</p> <p><code>open</code> is a builtin, so I needed to patch <code>builtins.open</code>, not <code>__main__.open</code>.</p> <p>Skipped over this info in the docs.</p>
0
2016-08-25T21:48:53Z
[ "python", "python-3.x", "io", "mocking" ]
In python 2.7 using CGI, how to check whether forked process completed
39,155,088
<p>So I have a set of python scripts. In an attempt to make a simple GUI, I have been combining html and CGI. So far so good. However, one of my scripts takes a long time to complete (>2 hours). So obviously, when I run this on my server (localhost on mac) I get a "gateway timeout error". I was reading about forking th...
0
2016-08-25T21:36:28Z
39,155,191
<p>Did you try this one:</p> <pre><code>import os processing = len(os.popen('ps aux | grep yourscript.py').readlines()) &gt; 2 </code></pre> <p>It tells you if your script is still running (returns boolean value).</p>
-1
2016-08-25T21:44:33Z
[ "python", "subprocess", "cgi" ]
Loop a function using the previous output value as input
39,155,113
<p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the foll...
0
2016-08-25T21:38:24Z
39,155,192
<p>I'm guessing <code>res</code> can have a special value indicating no more rows were returned, if so, a while loop can be deployed:</p> <pre><code>res = query() while True: res = query(res) if not res: break </code></pre> <p>you just rebind the result of the query to <code>res</code> and re-use it during ev...
3
2016-08-25T21:44:36Z
[ "python", "function", "loops" ]
Loop a function using the previous output value as input
39,155,113
<p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the foll...
0
2016-08-25T21:38:24Z
39,155,229
<p>Try collecting the results externally, and then call the function again:</p> <pre><code>results = [] MAX_ITERATIONS = 20 offset = None def query(offset=None): page = at.get('Accounts', offset=offset) return page['records'], page['offset'] while len(results) &lt;= MAX_ITERATIONS: result, offset = query(offs...
0
2016-08-25T21:47:25Z
[ "python", "function", "loops" ]
Loop a function using the previous output value as input
39,155,113
<p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the foll...
0
2016-08-25T21:38:24Z
39,155,295
<p>how are you returning the final results? consider:</p> <pre><code>def query(): offset = None a = [] while True: page = at.get('Accounts',offset=offset) a.extend(page['records']) offset = page['offset'] if not offset: break return a </code></pre> <p>which is really j...
0
2016-08-25T21:52:01Z
[ "python", "function", "loops" ]
Loop a function using the previous output value as input
39,155,113
<p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the foll...
0
2016-08-25T21:38:24Z
39,155,303
<pre><code>def query(result): # perform query return result def end_query_condition(result): # if want to continue query: return True # if you want to stop: return False continue_query = True result = None while continue_query: result = query(result) continue_query = end_query_conditio...
0
2016-08-25T21:52:27Z
[ "python", "function", "loops" ]
Loop a function using the previous output value as input
39,155,113
<p>I'm trying to query an API, but it only provides me with 100 records at a time and provides an offshoot record, which I need to use to query the next 100 records. I can write a function to query my results, but am having trouble looping my function to use the output of the previous function as the input of the foll...
0
2016-08-25T21:38:24Z
39,155,323
<p>You may simply make your function recursive without the need of any loop as:</p> <pre><code>def query(my_offset=None): if not offset: return None page = at.get('Accounts',offset=my_offset) a = page['records'] return query(str(page['offset'])) </code></pre>
0
2016-08-25T21:54:23Z
[ "python", "function", "loops" ]
Using python3, what is the fastest way to extract all <div> blocks from a html str?
39,155,127
<p>there are <code>&lt;div&gt;</code> inner blocks inside a <code>&lt;div&gt;</code> block, What is the fastest way to extract all <code>&lt;div&gt;</code> blocks from a html str ? (bs4, lxml or regex ?)</p>
-1
2016-08-25T21:39:15Z
39,155,253
<p><a href="http://lxml.de/" rel="nofollow"><code>lxml</code></a> is generally considered to be the fastest among existing Python parsers, though the parsing speed depends on multiple factors starting with the specific HTML to parse and ending with the computational power you have available. For HTML parsing use the <c...
1
2016-08-25T21:49:02Z
[ "python", "html", "regex", "parsing" ]
Using python3, what is the fastest way to extract all <div> blocks from a html str?
39,155,127
<p>there are <code>&lt;div&gt;</code> inner blocks inside a <code>&lt;div&gt;</code> block, What is the fastest way to extract all <code>&lt;div&gt;</code> blocks from a html str ? (bs4, lxml or regex ?)</p>
-1
2016-08-25T21:39:15Z
39,155,600
<p>When I'm teaching XML/HTML parsing with Python, I use to show this levels of complexity:</p> <ol> <li>RegEx: efficient for (very) simple parsing but can be/become hard to maintain.</li> <li>SAX: efficient and safe to parse XML as a stream. Easy to extract pieces of data but awful when you want to transform the tree...
0
2016-08-25T22:18:15Z
[ "python", "html", "regex", "parsing" ]
NameError: global name 'Path' is not defined
39,155,206
<p>I'm a beginner of learning GUI. My python version is 2.7,and I'm using windows</p> <p>what should I do to be able to change the value of "path" by clicking button?</p> <p>here is the part of my code. :)</p> <pre><code>class Sign_page(tk.Frame): def __init__(self, parent, controller): self.controller ...
0
2016-08-25T21:45:48Z
39,155,276
<p><code>Path</code> is not accessible from <code>asking_path</code> because it's not defined in the scope. One solution is to set an attribute on the instance when you create <code>Path</code> in <code>__init__</code>. In general, you should use lowercased variable names for Python variables ("<code>path</code>"), and...
0
2016-08-25T21:51:07Z
[ "python", "user-interface", "tkinter" ]
Can someone explain debugging / Pycharm's debugger in an easy to understand way?
39,155,391
<p>I have reached the stage in developing my Django project where I need to start debugging my code, as my site is breaking and I don't know why. I'm using Pycharm's IDE to code, and the debugger that comes with it is super intimidating! </p> <p>Maybe because I am a total newbie to programming (been coding only since ...
0
2016-08-25T22:00:34Z
39,162,697
<p>A can leave you some links i found useful when i got to that same point - i cant get you a more comprehensive explanation on the topic than this materials do. Debugging is fundamental as you said and very broad. But this videos and links should get you start with more confidence.</p> <pre><code>https://www.youtube...
1
2016-08-26T09:15:35Z
[ "python", "django", "debugging", "pycharm" ]
Can someone explain debugging / Pycharm's debugger in an easy to understand way?
39,155,391
<p>I have reached the stage in developing my Django project where I need to start debugging my code, as my site is breaking and I don't know why. I'm using Pycharm's IDE to code, and the debugger that comes with it is super intimidating! </p> <p>Maybe because I am a total newbie to programming (been coding only since ...
0
2016-08-25T22:00:34Z
39,164,574
<p>It's really easy. You can debug your script by pressing Alt+F5 or the bug button in Pycharm IDE. After that the Debugger handle the execution of the script. now you can debugging line by line by F10, get into a function or other object by pressing F11. Also there is Watch Window where you can trace your variable val...
1
2016-08-26T10:52:47Z
[ "python", "django", "debugging", "pycharm" ]
Django rest framework assign POST data to specific user
39,155,423
<p>Started Django and DRF a month ago and I'm stuck on this part... I get a JSON from Android device that already contains a primary key of user so the data gets saved to correct user. Recently I have implemented JWT token authentication (from Blimp) and it's working like a charm. Now I want to remove that primary key ...
0
2016-08-25T22:03:03Z
39,164,763
<pre><code>class ObrazacSerializer(serializers.ModelSerializer): izdavatelj = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Obrazac fields = ('local', 'izdavatelj') class ObrazacList(generics.ListCreateAPIView): queryset = Obrazac.objects.all() se...
0
2016-08-26T11:01:38Z
[ "python", "django", "authentication", "django-rest-framework", "jwt" ]
Using a named (fifo) pipe to transport arrays (images) between python and c++
39,155,655
<p>I need to send an array (representing an image) through a named FIFO pipe from a python process to a c++ process, and then back the other way (on a Linux system). </p> <p>The below code works great when using named pipes between two Python processes. It uses numpy's tostring() and fromstring() functions:</p> <p><s...
2
2016-08-25T22:23:05Z
39,155,722
<p>This is overcomplicated. If you need to send binary data, send their length first, then newline (<code>\n</code>), and then the data (raw, no base64). Receive it on the other side by readling a line, parsing the number and then just reading a block of data of given length.</p> <p><strong>Example</strong> - writing ...
1
2016-08-25T22:29:37Z
[ "python", "c++", "linux", "pipe", "ipc" ]
I Need Bigger Font in Python IDLE
39,155,656
<p>Context for why I'm asking:</p> <p>I am currently teaching a course on Python. I am using IDLE to show basic syntax in the shell. My screen is projected onto a large screen. The maximum font size in IDLE's preferences is 22. This is decently sized, but when projected, the students in the back have trouble seeing it...
0
2016-08-25T22:23:10Z
39,156,068
<p>The font size selection had ended with 22 for at least 15 years. It is set by this statement in <code>idlelib.ConfigDialog.py</code> (or <code>configdialog</code> in 3.6). It is about line 1000.</p> <pre><code> self.optMenuFontSize.SetMenu(('7', '8', '9', '10', '11', '12', '13', ...
4
2016-08-25T23:08:57Z
[ "python", "fonts", "python-idle" ]
Python: Append a list with a newline
39,155,665
<p>In the following code I am updating a list with two items by appending to it from within a for loop. I need a newline to be added after appending each string but I can't seem to be able to do it.</p> <p>I thought it would have been:</p> <pre><code>lines = [] for i in range(10): line = ser.readline() if li...
0
2016-08-25T22:24:25Z
39,155,786
<p>You can add all items to the list, then use .join() function to add new line between each item in the list:</p> <pre><code>for i in range(10): line = ser.readline() if line: lines.append(line) lines.append(datetime.now()) final_string = '\n'.join(lines) </code></pre>
3
2016-08-25T22:35:45Z
[ "python" ]
Python: Append a list with a newline
39,155,665
<p>In the following code I am updating a list with two items by appending to it from within a for loop. I need a newline to be added after appending each string but I can't seem to be able to do it.</p> <p>I thought it would have been:</p> <pre><code>lines = [] for i in range(10): line = ser.readline() if li...
0
2016-08-25T22:24:25Z
39,155,797
<p>It looks like the <code>lines</code> list is simple being printed in its entirety. The <code>\n</code> you see is only printing as an indicator that there are in fact new-lines. See this smaller example:</p> <pre><code>In [18]: print ['asdf' + '\n\n'] + [datetime.now()], ['asdf\n\n', datetime.datetime(2016, 8, 25, ...
0
2016-08-25T22:36:43Z
[ "python" ]
Python: Append a list with a newline
39,155,665
<p>In the following code I am updating a list with two items by appending to it from within a for loop. I need a newline to be added after appending each string but I can't seem to be able to do it.</p> <p>I thought it would have been:</p> <pre><code>lines = [] for i in range(10): line = ser.readline() if li...
0
2016-08-25T22:24:25Z
39,188,175
<p>I fixed the issue by appending 'datetime.now' to the list as a string on every frame using the 'strftime' method. I was then able to add newlines with 'lines = '\n'.join(lines)'. See code below for the working code.</p> <pre><code>lines = [] for frame in range(frames): line = ser.readline() if line: ...
0
2016-08-28T05:03:25Z
[ "python" ]
Python 2.7.11 pip not installed
39,155,669
<p>I have Python 2.7.11 installed on my machine which to my understanding should come with pip, however when I check the <code>C:\Python27\Tools\Scripts\</code> directory there is no <code>pip.exe</code> present.</p> <p>I have tried completely removing and reinstalling Python 2.7.11 without success. Running the insta...
0
2016-08-25T22:24:38Z
39,155,891
<p><a href="https://www.python.org/ftp/python/2.7.11/python-2.7.11.amd64.msi" rel="nofollow">python2.7.11</a> should install pip into c:\python27\scripts, you can take a look <a href="http://screencast.com/t/xX6WwxdnNN" rel="nofollow">here</a></p>
0
2016-08-25T22:46:22Z
[ "python", "windows", "python-2.7", "pip" ]
Passing variables with continuous functions?
39,155,697
<p>I am using a function to read an analog value from a joystick and update the label on the tkinter screen. This works well but I also want to use that value outside the function to perform if statements with other returned values. Here is what I have so far:</p> <pre><code>def joystick(): global joystick_adc ...
-1
2016-08-25T22:27:52Z
39,155,755
<p>If you <em>really</em> need such architecture, you could do it like this:</p> <pre><code>def joystick(adc): global joystickVal joystickVal = readadc(adc, SPICLK, SPIMOSI, SPIMISO, SPICS) joy_val.config(text=joystickVal) joy_val.after(1000, joystick, adc) joystick(joystick_adc) # to start # Also th...
-1
2016-08-25T22:32:32Z
[ "python", "python-3.x", "tkinter" ]
Passing variables with continuous functions?
39,155,697
<p>I am using a function to read an analog value from a joystick and update the label on the tkinter screen. This works well but I also want to use that value outside the function to perform if statements with other returned values. Here is what I have so far:</p> <pre><code>def joystick(): global joystick_adc ...
-1
2016-08-25T22:27:52Z
39,166,206
<p>By far, the simplest solution is to simply make <code>joystickValue</code> a global variable.</p> <pre><code>def joystick(): global joystickValue ... joystickValue = joystickRead ... </code></pre> <p>Generally speaking, global variables should be avoided. In an event driven program, however, they a...
1
2016-08-26T12:20:04Z
[ "python", "python-3.x", "tkinter" ]
Error redirecting after login
39,155,772
<p>I am trying to redirect users to a create-profile form after signup.Since I don't know how to use dynamic url for LOGIN_REDIRECT_URL.I tried this little trick of linking it to a static view then finally to a dynamic view using <code>redirect</code>.It gives the error <code>Reverse for 'add_profile' with arguments '(...
0
2016-08-25T22:34:12Z
39,155,848
<p>When you reverse urls (including when you use a url name with the <code>redirect</code> shortcut), you should use the name of the <em>url pattern</em>, not the view. The url pattern has <code>name='create-profile'</code>, so use that. </p> <pre><code>redirect('create-profile', username=username) </code></pre>
0
2016-08-25T22:42:18Z
[ "python", "django", "django-views" ]
thresholds in roc_curve in scikit learn
39,155,900
<p>I am referring to the below link and sample, and post the plot diagram from this page where I am confused. My confusion is, there are only 4 threshold, but it seems the roc curve has many data points (> 4 data points), wondering how roc_curve working underlying to find more data points?</p> <p><a href="http://sciki...
0
2016-08-25T22:47:13Z
39,157,785
<p>That plot is actually from this example: <a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html</a></p>
1
2016-08-26T03:15:50Z
[ "python", "python-2.7", "machine-learning", "scikit-learn", "roc" ]
How to get a python script to invoke "python -i" when called normally?
39,155,928
<p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p> <p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the scrip...
18
2016-08-25T22:51:54Z
39,155,956
<p>I think you're looking for <a href="https://docs.python.org/3/library/code.html#code.interact" rel="nofollow" title="code.interact">this</a>?</p> <pre class="lang-py prettyprint-override"><code>import code foo = 'bar' print foo code.interact(local=locals()) </code></pre>
3
2016-08-25T22:54:42Z
[ "python", "python-interactive" ]
How to get a python script to invoke "python -i" when called normally?
39,155,928
<p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p> <p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the scrip...
18
2016-08-25T22:51:54Z
39,155,981
<p>From within <code>script.py</code>, set the <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONINSPECT"><code>PYTHONINSPECT</code></a> environment variable to any nonempty string. Python will recheck this environment variable at the end of the program and enter interactive mode.</p> <pre><code>impor...
19
2016-08-25T22:57:40Z
[ "python", "python-interactive" ]
How to get a python script to invoke "python -i" when called normally?
39,155,928
<p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p> <p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the scrip...
18
2016-08-25T22:51:54Z
39,155,984
<p>You could use an instance of <a href="https://docs.python.org/3/library/code.html#code.InteractiveInterpreter" rel="nofollow"><code>code.InteractiveConsole</code></a> to get this to work:</p> <pre><code>from code import InteractiveConsole i = 20 d = 30 InteractiveConsole(locals=locals()).interact() </code></pre> <...
6
2016-08-25T22:58:07Z
[ "python", "python-interactive" ]
How to get a python script to invoke "python -i" when called normally?
39,155,928
<p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p> <p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the scrip...
18
2016-08-25T22:51:54Z
39,156,962
<p>In addition to all the above answers, you can run the script as simply <code>./script.py</code> by making the file executable and setting the shebang line, e.g.</p> <pre><code>#!/usr/bin/python -i this = "A really boring program" </code></pre> <hr> <p>If you want to use this with the <code>env</code> command in o...
7
2016-08-26T01:10:06Z
[ "python", "python-interactive" ]
How to get a python script to invoke "python -i" when called normally?
39,155,928
<p>I have a python script that I like to run with <code>python -i script.py</code>, which runs the script and then enters interactive mode so that I can play around with the results.</p> <p>Is it possible to have the script itself invoke this option, such that I can just run <code>python script.py</code> and the scrip...
18
2016-08-25T22:51:54Z
39,157,837
<p>I would simply accompany the script with a shell script that invokes it.</p> <pre class="lang-sh prettyprint-override"><code>exec python -i "$(dirname "$0")/script.py" </code></pre>
1
2016-08-26T03:23:18Z
[ "python", "python-interactive" ]
"QStackedWidget.setCurrentIndex": It does not work or error mark
39,155,952
<p>I'm doing a program with graphical interface using PyQt5 . I want to do is that when the user presses certain button, this change widget and show other options.</p> <p>For this I decided to use QStackedWidget, and all my interface build it from the QT5 designer.</p> <p>However, in my code, wanting to determine tha...
2
2016-08-25T22:54:23Z
39,158,076
<p>Your question isn't completely clear, but don't you just want:</p> <pre><code>def setIndex(self, index): self.setCurrentIndex(index) </code></pre> <p>However, this is a little redundant as you should able to link the button directly to the <code>setCurrentIndex</code> method and use <code>lambda</code> to pass...
0
2016-08-26T03:59:59Z
[ "python", "python-3.x", "pyqt", "pyqt5", "qstackedwidget" ]
Exposing python jupyter on LAN
39,155,953
<p>I've installed jupyter on local network LAN but im unable to access <code>http://&lt;IP&gt;:8888</code> from another macine on LAN. I've opened ports 8888 and port range 49152 to 65535 with iptables (this range is specified at <a href="http://jupyter-notebook.readthedocs.io/en/latest/public_server.html" rel="nofollo...
3
2016-08-25T22:54:27Z
39,156,006
<p>Try <code>jupyter notebook --ip &lt;your_LAN_ip&gt; --port 8888</code> Then visit <code>http://your_LAN_ip:8888</code> from another computer</p>
2
2016-08-25T23:00:27Z
[ "python", "linux", "python-3.x", "ubuntu-14.04", "jupyter" ]
how to do a nested for-each loop with PySpark
39,155,954
<p>Imagine a large dataset (>40GB parquet file) containing value observations of thousands of variables as triples <strong>(variable, timestamp, value)</strong>.</p> <p>Now think of a query in which you are just interested in a subset of 500 variables. And you want to retrieve the observations (values --> time series)...
2
2016-08-25T22:54:29Z
39,166,573
<p>Generally speaking only the first approach looks sensible to me. Exact joining strategy on the number of records and distribution but you can either create a top level data frame:</p> <pre><code>ref = sc.parallelize([(var_, incident) for var_ in variables_of_interest: for incident in incidents ]).toDF(["va...
1
2016-08-26T12:38:48Z
[ "python", "apache-spark", "pyspark" ]
Sending multiple pings with Python
39,155,999
<p>How can I ping <code>192.168.0.1</code> - <code>192.168.0.254</code> all at once? Trying to make the script run faster as it takes several minutes to finish. </p> <pre><code>import os import subprocess ip = raw_input("IP Address? ") print "Scanning IP Address: " + ip subnet = ip.split(".") FNULL = open(os.devnu...
2
2016-08-25T22:59:33Z
39,156,105
<p>Instead of waiting for each process to finish in your loop you can start all the processes at once and save them in a list:</p> <pre><code>processes = [] for x in range(1, 255): ip2 = subnet[0]+"."+ subnet[1] +"."+ subnet[2] +"."+ str(x) process = subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2],...
2
2016-08-25T23:13:32Z
[ "python" ]
Sending multiple pings with Python
39,155,999
<p>How can I ping <code>192.168.0.1</code> - <code>192.168.0.254</code> all at once? Trying to make the script run faster as it takes several minutes to finish. </p> <pre><code>import os import subprocess ip = raw_input("IP Address? ") print "Scanning IP Address: " + ip subnet = ip.split(".") FNULL = open(os.devnu...
2
2016-08-25T22:59:33Z
39,156,126
<p>Look at the method you use to get a response:</p> <pre><code>response=subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip2], stdout=FNULL, stderr=subprocess.STDOUT).wait() </code></pre> <p>most importantly, the <code>.wait()</code> at the end means your program will wait until the process finishes.</p> <p>Yo...
0
2016-08-25T23:16:03Z
[ "python" ]
Sending multiple pings with Python
39,155,999
<p>How can I ping <code>192.168.0.1</code> - <code>192.168.0.254</code> all at once? Trying to make the script run faster as it takes several minutes to finish. </p> <pre><code>import os import subprocess ip = raw_input("IP Address? ") print "Scanning IP Address: " + ip subnet = ip.split(".") FNULL = open(os.devnu...
2
2016-08-25T22:59:33Z
39,156,641
<p>Or you could ping them all with one ping to the subnet broadcast address. So if your subnet is <code>255.255.255.0</code> (also known as <code>/24</code>) then just ping <code>192.168.0.255</code> and <em>normally</em> everyone will ping back. </p>
0
2016-08-26T00:23:02Z
[ "python" ]
UnboundLocalError local variables referenced before assignment / Consideration
39,156,076
<p>I have the following function based view</p> <pre><code>def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query'...
0
2016-08-25T23:10:17Z
39,156,094
<p>It means, either your <code>form.is_valid()</code> is <code>False</code> or, you are not making the <code>GET</code> request. </p> <p>Add <code>cd = results = total_results = None</code> before the first if condition. Because, in your current code, if any of the <code>if</code> condition fails, <code>cd</code>, <co...
1
2016-08-25T23:12:35Z
[ "python", "django", "variables", "scope" ]
Is it possible to insert knobs on nodes in Nuke?
39,156,092
<p>The main interface for adding knobs to nodes in nuke appears to be the <code>node.addKnob()</code> function. The knobs are added in the order that the <code>addKnob</code> method is called. Is there a way to insert knobs before other knobs that have already been created?</p>
0
2016-08-25T23:12:14Z
39,215,596
<p>According to Foundry support, it is <em>not</em> possible to insert knobs into existing nodes or groups. The only option is to delete and recreate the set of knobs.</p>
0
2016-08-29T21:37:07Z
[ "python", "nuke" ]
Can't find string after a tag with BeautifulSoup in Python?
39,156,107
<p>In this HTML I want to get the string of it but no matter what I try it doesn't work (string = none)</p> <pre><code> &lt;a href="/analyze/default/index/49398962/1/34925733" target="_blank"&gt; &lt;img alt="" class="ajax-tooltip shadow radius lazy" data-id="acctInfo:34925733_1" data-original="/upload/pro...
3
2016-08-25T23:13:51Z
39,156,201
<p>Well, if your <code>soup</code> variable is made off that html piece of code then the output you get is <code>None</code> because there is no <code>td</code> element inside it, and of course there is not <code>td</code> element with <code>class=tou</code>.</p> <p>Now, if you want to get that text maybe you could ca...
0
2016-08-25T23:25:51Z
[ "python", "beautifulsoup" ]
Can't find string after a tag with BeautifulSoup in Python?
39,156,107
<p>In this HTML I want to get the string of it but no matter what I try it doesn't work (string = none)</p> <pre><code> &lt;a href="/analyze/default/index/49398962/1/34925733" target="_blank"&gt; &lt;img alt="" class="ajax-tooltip shadow radius lazy" data-id="acctInfo:34925733_1" data-original="/upload/pro...
3
2016-08-25T23:13:51Z
39,156,223
<p>You need to select the <em>a</em> from the parent <em>td</em> and call <em>.text</em>, the text is inside the anchor which is a child of the td:</p> <pre><code>print([td.a.text for td in soup.find_all('td', class_='tou')]) </code></pre> <p>There obviously is a td with the class tou or you would not be getting a li...
3
2016-08-25T23:28:35Z
[ "python", "beautifulsoup" ]
Can't find string after a tag with BeautifulSoup in Python?
39,156,107
<p>In this HTML I want to get the string of it but no matter what I try it doesn't work (string = none)</p> <pre><code> &lt;a href="/analyze/default/index/49398962/1/34925733" target="_blank"&gt; &lt;img alt="" class="ajax-tooltip shadow radius lazy" data-id="acctInfo:34925733_1" data-original="/upload/pro...
3
2016-08-25T23:13:51Z
39,156,228
<pre><code>&gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; soup = BeautifulSoup(open('input.html'), 'lxml') &gt;&gt;&gt; [tag.text.strip() for tag in soup] [u'Jue VioIe Grace'] </code></pre> <p>If we want to restrict the search to text in <em>anchor</em> tags:</p> <pre><code>&gt;&gt;&gt; [tag.text.strip() for...
2
2016-08-25T23:29:16Z
[ "python", "beautifulsoup" ]
Django client test (get, post) response load data from main db instead fixtures loaded in test db
39,156,132
<p>I'm new in Django, and I have this problem: I use self.client to test routes in my app. e.g.</p> <pre><code>class BookSell(TestCase): fixtures = [ 'sellers.yaml', 'books.yaml' ... ] def test_get_book_sell(self): book = Books.objects.get(pk=1) print(book.name)#i...
0
2016-08-25T23:16:39Z
39,339,532
<p>Finally I discovered what I was doing wrong, thanks to this answer: <a href="http://stackoverflow.com/questions/29773665/django-reload-form-data-after-db-values-change">Django: reload form data after db values change</a></p> <p>I had a form like this:</p> <pre><code>class BookSellForm(forms.Form): books = [('...
0
2016-09-06T01:49:19Z
[ "python", "django", "testing", "fixtures" ]
Django how to filter based on ManyToManyField?
39,156,154
<p>Suppose I have the following Django classes:</p> <p>in myclassa.py:</p> <pre><code>class MyClassA(models.Model): name = models.CharField(max_length=254) def my_method(self): # WHAT GOES HERE? </code></pre> <p>in myclassb.py:</p> <pre><code>from myclassa import MyClassA class MyClassB(models.Mode...
2
2016-08-25T23:19:14Z
39,156,215
<p>You may define it as:</p> <pre><code>def my_method(self): return self.MyClassB_MyClassA.all() </code></pre> <p>Alternatively, you may also define it as:</p> <pre><code>def my_method(self): return MyClassB.objects.filter(a=self) </code></pre>
2
2016-08-25T23:27:34Z
[ "python", "django", "django-models", "django-queryset" ]
Installing module in python with anaconda and jupyter notebook
39,156,207
<p>I've been having a problem with installing modules, and I can't find an exact solution to it anywhere. What I'm trying to do is use anaconda to install a module. When I type into the anaconda command prompt:</p> <pre><code>pip install imbox </code></pre> <p>it says it installs. So then i open jupyter notebook by s...
0
2016-08-25T23:26:35Z
39,156,348
<p>Try using the pip that comes with conda, instead of your default pip.</p> <p><code>PATH_TO_CONDA_DIR/bin/pip install imbox</code></p> <p>In your case:</p> <p><code>C:\Users\USERNAME\Anaconda2\bin\pip install imbox</code></p> <p>Alternative, install the package again, in the specified location:</p> <p><code>pip ...
1
2016-08-25T23:42:53Z
[ "python", "module", "anaconda", "jupyter" ]
Python - Fastest way to clear the screen?
39,156,221
<p>What would the fastest way to clear the screen, be?</p> <p>I've tried many solutions, they seem to work, however, I need the fastest way. Could anyone point me in the right direction?</p> <p>The screen, in my case, is a command prompt.</p> <p>I've edited my question for better understandings.</p> <p>Any help wel...
-5
2016-08-25T23:28:16Z
39,156,262
<p>One portable solution could be:</p> <pre><code>def clear_sceen(): os.system('cls' if os.name == 'nt' else 'clear') </code></pre> <p>Another possible way would be using:</p> <pre><code>print(chr(27) + "[2J") </code></pre> <p>Although this one wouldn't be really a portable solution</p>
3
2016-08-25T23:33:08Z
[ "python", "cmd", "screen", "line", "clear" ]
Why am I getting an sqlalchemy.exc.ProgrammingError rather than a sqlalchemy.exc.IntegrityError?
39,156,330
<p>I'm writing some account creation code and trying to catch a particular sqlalchemy exception so that I can feed back an appropriate error message when a user registers an account with an email that is already associated to an existing account.</p> <p>I was expecting to get an IntegrityError when this happened but I...
3
2016-08-25T23:40:46Z
39,156,742
<p>Unfortunately, when it comes to <a href="https://www.python.org/dev/peps/pep-0249" rel="nofollow">DBAPI</a> errors SQLAlchemy merely wraps the exception raised by the underlying dbapi compatible library.</p> <p>That is, SQLAlchemy raises a <code>ProgrammingError</code> in particular only <em>because <code>pg8000</c...
3
2016-08-26T00:38:42Z
[ "python", "sqlalchemy" ]
Do ec2 tag numbers change?
39,156,377
<p>Below is some simple code. What SHOULD pull the key:name tag. However when I add a second tag, it seems to change the order, so 0 isn't always the name??? </p> <pre><code>instances = ec2.instances.filter(Filters=[{'Name':'instance-state-name','Values':['running']}]) for instance in instances: for tag...
-1
2016-08-25T23:46:54Z
39,156,416
<p>Yes. <code>instance.tags</code> is a list and your tag can appear anywhere in the list. If you are trying to get the 'Name', you have to loop through the list. Each element in the list is a dictionary. Check if the key is 'Name' before getting the value.</p> <p>It sounds complex, but very simple to code. You cannot...
1
2016-08-25T23:51:27Z
[ "python", "amazon-web-services", "amazon-ec2", "boto3" ]
Sorting dictionary of lists based on first value in list
39,156,425
<p>I need to return a dictionary of lists in descending order based on the first number in each list, for example:</p> <pre><code>{'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]} should return: {'key2': [7, 7], 'key3': [5, 10], 'key1': [2, 3]} </code></pre> <p>What I had originally was:</p> <pre><code>orderedDict =...
0
2016-08-25T23:53:33Z
39,156,452
<p>You are almost there!</p> <pre><code>collections.OrderedDict(sorted(a.iteritems(), key=lambda (k,v):v[0], reverse=True)) ^^^^ </code></pre> <p>When <code>sorted(..)</code> is called with a <code>key=</code> argument, every element of the first paramete...
1
2016-08-25T23:57:37Z
[ "python", "list", "sorting", "dictionary", "ordereddictionary" ]
Sorting dictionary of lists based on first value in list
39,156,425
<p>I need to return a dictionary of lists in descending order based on the first number in each list, for example:</p> <pre><code>{'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]} should return: {'key2': [7, 7], 'key3': [5, 10], 'key1': [2, 3]} </code></pre> <p>What I had originally was:</p> <pre><code>orderedDict =...
0
2016-08-25T23:53:33Z
39,156,462
<p>Instead of <code>v</code>, you have to just mention <code>v[0]</code> that is the is the index in value on which you want to sort.</p> <pre><code>&gt;&gt;&gt; orderedDict = collections.OrderedDict(sorted(my_dict.iteritems(), key=lambda (k,v):v[0], reverse=True)) &gt;&gt;&gt; orderedDict OrderedDict([('key2', [7, 7]...
0
2016-08-25T23:58:42Z
[ "python", "list", "sorting", "dictionary", "ordereddictionary" ]
Sorting dictionary of lists based on first value in list
39,156,425
<p>I need to return a dictionary of lists in descending order based on the first number in each list, for example:</p> <pre><code>{'key1': [2, 3], 'key2': [7, 7], 'key3': [5, 10]} should return: {'key2': [7, 7], 'key3': [5, 10], 'key1': [2, 3]} </code></pre> <p>What I had originally was:</p> <pre><code>orderedDict =...
0
2016-08-25T23:53:33Z
39,156,603
<p>Did you test what you already had to see whether it still worked? Because it does. When you sort a group of sequences, they are compared "alphabetically" - if the first items of two sequences are equal, their second items are compared, and so on. This means that, in your example, <code>sorted</code> would compare th...
0
2016-08-26T00:16:30Z
[ "python", "list", "sorting", "dictionary", "ordereddictionary" ]
How do you permanently change the JYTHONPATH in Jython 2.5 on Ubuntu 14?
39,156,446
<p>I'm using Ubuntu 14.04 LTS and Jython 2.5.3. I want to add a directory to the path Jython takes to search for Python packages. When I import sys and enter sys.path, here's what I get:</p> <pre><code>&gt;&gt;&gt; sys.path ['', '/usr/lib/site-python', '/usr/share/jython/Lib', '/usr/Lib', '__classpath__', '__pyclasspa...
0
2016-08-25T23:56:33Z
39,156,478
<p>I was able to accomplish this by adding the following line to my user bashrc file (~/.bashrc):</p> <pre><code>export JYTHONPATH=/foo/bar:/usr/lib/site-python:/usr/share/jython/Lib </code></pre>
0
2016-08-26T00:00:11Z
[ "python", "ubuntu", "ubuntu-14.04", "pythonpath", "jython-2.5" ]
numpy delete not deleting element
39,156,458
<p>Under what circumstances would bumpy.delete simply return a copy of the original array, unaltered?</p> <p>If I do a simple example as follows, then things work as advertised:</p> <pre><code>&gt;&gt;&gt; a = numpy.arange(0, 10) &gt;&gt;&gt; numpy.delete(a, [1]) &gt;&gt;&gt; array([0, 2, 3, 4, 5, 6, 7, 8, 9]) </code...
-2
2016-08-25T23:58:27Z
39,156,679
<p>To me, it appears that you are simply trying to delete an index that is out of the array; hence the lack of change ... From your code <code>len(scale)</code> gives only 17 .</p> <p>For the record as the <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.delete.html" rel="nofollow">doc</a> ind...
1
2016-08-26T00:30:29Z
[ "python", "arrays", "numpy" ]
numpy delete not deleting element
39,156,458
<p>Under what circumstances would bumpy.delete simply return a copy of the original array, unaltered?</p> <p>If I do a simple example as follows, then things work as advertised:</p> <pre><code>&gt;&gt;&gt; a = numpy.arange(0, 10) &gt;&gt;&gt; numpy.delete(a, [1]) &gt;&gt;&gt; array([0, 2, 3, 4, 5, 6, 7, 8, 9]) </code...
-2
2016-08-25T23:58:27Z
39,156,967
<p>first, <code>delete</code> does not operate in place:</p> <pre><code>In [849]: a=np.arange(10) In [850]: np.delete(a,[1]) Out[850]: array([0, 2, 3, 4, 5, 6, 7, 8, 9]) # returned array In [851]: a Out[851]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # not change in a </code></pre> <p>If I do an out of bounds delete wi...
0
2016-08-26T01:11:12Z
[ "python", "arrays", "numpy" ]
alpha & beta (for linear regression) calculations output nan?
39,156,506
<p>I am new to Python and have been attempting to calculate the linear regression/Beta/Alpha for two securities, however my code is outputting Nan for both Beta &amp; Alpha, and therefore I am unable to draw the regression line. </p> <p>here is the code in question:</p> <pre><code>#calculate linear regression beta_yP...
0
2016-08-26T00:03:14Z
39,160,836
<p>Trying to look into this, but it's a little confusing to me. In addition, I can not reproduce the data-pulling from yahoo on my current machine, so I can not run your code as it is.</p> <p>Here a few questions and ideas:</p> <ul> <li>You should not name a variable <code>close</code>, since this word is used by Pyt...
0
2016-08-26T07:35:22Z
[ "python", "pandas", "numpy", "linear-regression" ]
alpha & beta (for linear regression) calculations output nan?
39,156,506
<p>I am new to Python and have been attempting to calculate the linear regression/Beta/Alpha for two securities, however my code is outputting Nan for both Beta &amp; Alpha, and therefore I am unable to draw the regression line. </p> <p>here is the code in question:</p> <pre><code>#calculate linear regression beta_yP...
0
2016-08-26T00:03:14Z
39,165,218
<p>I cannot retrieve the data either.</p> <p>My best guess: there are <code>nan</code>s or duplicate points in the retrieved data.</p>
0
2016-08-26T11:25:21Z
[ "python", "pandas", "numpy", "linear-regression" ]
alpha & beta (for linear regression) calculations output nan?
39,156,506
<p>I am new to Python and have been attempting to calculate the linear regression/Beta/Alpha for two securities, however my code is outputting Nan for both Beta &amp; Alpha, and therefore I am unable to draw the regression line. </p> <p>here is the code in question:</p> <pre><code>#calculate linear regression beta_yP...
0
2016-08-26T00:03:14Z
39,166,741
<pre><code>def compute_daily_returns(df): daily_returns = (df / df.shift(1)) - 1 daily_returns.ix[0, :] = 0 return daily_returns </code></pre> <p>adding <code>daily_returns.ix[0, :] = 0</code> fixed the issue, thanks to Nickil Maveli</p>
0
2016-08-26T12:48:10Z
[ "python", "pandas", "numpy", "linear-regression" ]
interactive conditional histogram bucket slicing data visualization
39,156,545
<p>I have a df that looks like: </p> <pre><code>df.head() Out[1]: A B C city0 40 12 73 city1 65 56 10 city2 77 58 71 city3 89 53 49 city4 33 98 90 </code></pre> <p>An example df can be created by the following code:</p> <pre><code>df = pd.DataFrame(np.random.randint(100,size=(1000000,...
12
2016-08-26T00:08:52Z
39,218,998
<p>As a newbie with insufficient rep, I can't comment, so I'm putting this here as an "answer," though it shouldn't be treated as one; these are just some incomplete suggestions in the same vein as the comments. </p> <p>Along with the others, I like <code>seaborn</code> though I'm not sure those plots are interactive ...
3
2016-08-30T04:55:13Z
[ "python", "pandas", "data-visualization", "seaborn", "bokeh" ]
interactive conditional histogram bucket slicing data visualization
39,156,545
<p>I have a df that looks like: </p> <pre><code>df.head() Out[1]: A B C city0 40 12 73 city1 65 56 10 city2 77 58 71 city3 89 53 49 city4 33 98 90 </code></pre> <p>An example df can be created by the following code:</p> <pre><code>df = pd.DataFrame(np.random.randint(100,size=(1000000,...
12
2016-08-26T00:08:52Z
39,363,715
<p>In order to get the interaction effect you're looking for, you must bin all the columns you care about, together.</p> <p>The cleanest way I can think of doing this is to <code>stack</code> into a single <code>series</code> then use <code>pd.cut</code></p> <p>Considering your sample <code>df</code></p> <p><a href=...
7
2016-09-07T07:26:47Z
[ "python", "pandas", "data-visualization", "seaborn", "bokeh" ]
interactive conditional histogram bucket slicing data visualization
39,156,545
<p>I have a df that looks like: </p> <pre><code>df.head() Out[1]: A B C city0 40 12 73 city1 65 56 10 city2 77 58 71 city3 89 53 49 city4 33 98 90 </code></pre> <p>An example df can be created by the following code:</p> <pre><code>df = pd.DataFrame(np.random.randint(100,size=(1000000,...
12
2016-08-26T00:08:52Z
39,432,898
<p>Here is a new solution using <a href="http://bokeh.pydata.org/en/latest/docs/user_guide/charts.html" rel="nofollow"><code>bokeh</code></a> and <a href="http://holoviews.org/#installation" rel="nofollow"><code>HoloViews</code></a>. It should respond a little more to the interactive part.</p> <p>I try to remember tha...
4
2016-09-11T04:37:31Z
[ "python", "pandas", "data-visualization", "seaborn", "bokeh" ]
why use transpose than directly set array?
39,156,724
<p>In a python code I see two lines below (initially, labels was of type (15093, that is, 1-d array)(from py-faster-rcnn)</p> <pre><code>labels = labels.reshape((1, height, width, A)).transpose(0, 3, 1, 2) labels = labels.reshape((1, 1, A * height, width)) </code></pre> <p>Is there any reason the author use transpose...
0
2016-08-26T00:36:20Z
39,156,968
<p>The answer is quite easy : yes there is a reason, given the same <code>labels</code> array, the results of your 3 methods simply aren't the same. </p> <p>Lets check that with an example:</p> <pre><code>import numpy as np height, width, A = [2,3,4] arr=np.random.rand(1*height*width*A) print("Method 1") labels1=np....
1
2016-08-26T01:11:24Z
[ "python", "numpy" ]
While loop not repeating once information in entered
39,156,728
<p>Making a program which has a list of the different star signs, then asks the user to enter what star sign they are and then for the program to check that is contained in the list before moving on. </p> <p>The problem is that it does check that it is in the list, but it does not repeat.</p> <pre><code>play = True ...
1
2016-08-26T00:36:42Z
39,189,676
<p>if you want to repeat an <code>input</code> until you get a valid answer and THEN ask the next question, you need to place the 1st input inside <code>while</code> loop and the 2nd input outside the loop, like this:</p> <pre><code>starsigns = ("leo", "virgo", ...) starsign = None while starsign not in starsigns: ...
0
2016-08-28T09:12:59Z
[ "python" ]
Python: Replace Slashes
39,156,795
<p>I got some unicode with percent signs I want to change to backslashes. I know you need an additional backslash as an escape sequence, but when I did this <code>replace()</code> gave me two backslashes:</p> <pre><code>&gt;&gt;&gt; s ="%20%u200F%u05D1%u05E8%u05DB%u05EA%u200F%20%u200F%u05D4%u05E8%u05D9%u05D7%u200F%20%...
0
2016-08-26T00:46:05Z
39,156,826
<p>That is just python invoking the string <code>__repr__</code> because you're in the REPL and the <code>__repr__</code> escapes the <code>\</code> character giving you the output you see.</p> <p>Using <code>print</code>, which will use the strings <code>__str__</code>, will get you the right output:</p> <pre><code>...
3
2016-08-26T00:49:27Z
[ "python", "string" ]
Python: Replace Slashes
39,156,795
<p>I got some unicode with percent signs I want to change to backslashes. I know you need an additional backslash as an escape sequence, but when I did this <code>replace()</code> gave me two backslashes:</p> <pre><code>&gt;&gt;&gt; s ="%20%u200F%u05D1%u05E8%u05DB%u05EA%u200F%20%u200F%u05D4%u05E8%u05D9%u05D7%u200F%20%...
0
2016-08-26T00:46:05Z
39,156,863
<p>Just like you have to type two backslashes to enter one, Python, when displaying a quoted string, displays two to indicate it is a literal backslash. <code>'\\x41'</code> is four characters, <code>'\x41'</code> is one (equivalent to <code>'A'</code>). It's a debugging feature so you can see unprintable characters,...
0
2016-08-26T00:55:20Z
[ "python", "string" ]
PyGame draw a square inside a square
39,156,809
<p>I'm writing a grid-based game where instances of the Character class can move around using their move(direction) method.</p> <pre><code>class Character(object): #can move around and do cool stuff def __init__(self, name, HP, internal_column, internal_row): self.name = name sel...
0
2016-08-26T00:47:46Z
39,416,708
<p>Ended up doing it like this:</p> <pre><code> if str(Map.Grid[column][row][i].__class__.__name__) == "Character": #Drawing the little red square showing character direction if Map.Grid[column][row][i].direction == "N": Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGI...
0
2016-09-09T17:17:51Z
[ "python", "python-3.x", "oop", "pygame", "game-engine" ]
Sage doesn't find cycle_type() attribute on a permutation element
39,156,851
<p>Im trying to work on some group theory with Sage.</p> <p>In particular I was trying to learn the basic commands related to symmetric groups.</p> <p>My input is</p> <pre><code>G=SymmetricGroup(6) sigma=G('(1,3,5)(4,6)') </code></pre> <p>then I use <code>sigma.cycle_type()</code> and according to the documentatio...
0
2016-08-26T00:53:48Z
39,156,979
<p>Possibly you just need a newer version of Sage? In a late beta of 7.3, I get:</p> <pre><code>sage: sigma.cycle_type() [3, 2, 1] </code></pre> <p>I should point out that the version in SageMathCloud appears to be too old for this currently, if that's your platform...</p>
0
2016-08-26T01:13:46Z
[ "python", "sage" ]
Having no performance problems with threading and Python's Global Interpreter Lock. Scalability?
39,156,864
<p>I have been having no problems with performance with Python's Global Interpreter Lock. I've had to make a few things thread-safe - despite common advice, the GIL does NOT automatically guarantee thread-safety - but I've got a program commonly running upwards of 10 threads, where all of them can be active at any time...
0
2016-08-26T00:55:41Z
39,157,969
<p>The GIL is a complex topic and the exact behavior in your case is hard to explain without your code. So I can not tell you if you will run into troubles in future. I can just advise to bring you project to a recent version of Python 3 if posdible. There have been many improvents made to the GIL in Python 3.</p> <p>...
0
2016-08-26T03:44:20Z
[ "python", "multithreading", "globalinterpreterlock" ]
Integrating twisted into existing pyqt GUI application
39,156,867
<p>I am trying to add twisted to my already existing app. According to <a href="https://pypi.python.org/pypi/qt4reactor/1.6" rel="nofollow">this</a> and other sources, I should import qt4reactor. When I try:</p> <pre><code>app = QApplication(sys.argv) from twisted.application import reactors reactors.installReactor('p...
0
2016-08-26T00:56:05Z
39,157,264
<p>Now qt4reactor is separate from Twisted and located <a href="https://github.com/ghtdak/qtreactor" rel="nofollow">here</a></p> <p>So you need to install it first, then try:</p> <pre><code>from twisted.application import reactors reactors.installReactor('pyqt4') </code></pre> <p>or</p> <pre><code>from qtreactor im...
0
2016-08-26T01:56:20Z
[ "python", "pyqt4", "twisted" ]
My function doesn't return a value, can't figure out why
39,156,882
<p>The function is supposed to open a csv file that has data in this format</p> <p>"polling company,date range,how many polled,margin of error,cruz,kasich,rubio,trump"</p> <p>When I run this function, read_data_file, there is no output, which I don't understand since I am returning the poll_data. I don't believe ther...
3
2016-08-26T00:58:18Z
39,156,909
<p>you changed that last line in the function from <code>print</code> to <code>return</code>. So, when you call your function as such:</p> <p><code>read_data_file('florida-gop.csv')</code></p> <p>it <em>does</em> return that data. It's sitting right there! But then your script ends, doing nothing with that data. ...
2
2016-08-26T01:02:10Z
[ "python", "function", "return" ]
My function doesn't return a value, can't figure out why
39,156,882
<p>The function is supposed to open a csv file that has data in this format</p> <p>"polling company,date range,how many polled,margin of error,cruz,kasich,rubio,trump"</p> <p>When I run this function, read_data_file, there is no output, which I don't understand since I am returning the poll_data. I don't believe ther...
3
2016-08-26T00:58:18Z
39,156,915
<p>You have two options here:</p> <ol> <li>Replacing <code>return poll_data</code> with <code>print poll_data</code>.</li> <li>Instead of <code>read_data_file('florida-gop.csv')</code>, you can do <code>print read_data_file('florida-gop.csv')</code>.</li> </ol> <p>Why do you need to do this? </p> <p><strong><code>Pr...
1
2016-08-26T01:02:59Z
[ "python", "function", "return" ]
My function doesn't return a value, can't figure out why
39,156,882
<p>The function is supposed to open a csv file that has data in this format</p> <p>"polling company,date range,how many polled,margin of error,cruz,kasich,rubio,trump"</p> <p>When I run this function, read_data_file, there is no output, which I don't understand since I am returning the poll_data. I don't believe ther...
3
2016-08-26T00:58:18Z
39,156,924
<p>Continuing from the above(or not so above anymore xD) answer...</p> <p>the full code would now be,</p> <pre><code>def read_data_file(filename): file = open(filename, 'r') poll_data = [] for data in file: data = data.strip('\n') data = data.split(',') poll_data.append(data) r...
0
2016-08-26T01:04:30Z
[ "python", "function", "return" ]
How do you query MongoDB by pairs of keys using pymongo
39,156,920
<p>I have a list of pairs of things, of the form e.g. <code>[['A', 'B'], ['C', 'D']]</code>. I want to query <code>MongoDB</code> for records in a specific collection which have properties matching both of these things.</p> <p>For example, here is what I would want to get back:</p> <pre><code>[{'_id': ObjectId('...')...
0
2016-08-26T01:03:34Z
39,157,867
<p>I got pretty good performance out of the following pattern:</p> <pre><code>client.find({'$or': [{'property_a': value_a, 'property_b': value_b} for value_a, value_b in some_list_of_two_element_tuples]} </code></pre> <p>This creates a very long <a href="https://docs.mongodb.com/manual/reference/operator/query/or/" r...
1
2016-08-26T03:28:09Z
[ "python", "mongodb", "pymongo" ]
My url template not work
39,156,940
<p>I have a problem with my template tag url. The redirect not work when i click on button.</p> <p>Django version => 1.9 Python version => 2.7</p> <p>In my urls.py(main) i have:</p> <pre><code>from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from d...
0
2016-08-26T01:06:19Z
39,157,643
<p>From doc here <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#url-dispatcher" rel="nofollow">URL dispatcher</a></p> <pre><code>&lt;button type="button" class="btn btn-primary"&gt;&lt;a id="back-profile" href="{% url 'memory:update' %}"&gt; Update&lt;/a&gt;&lt;/button&gt; &lt;button type="button" ...
0
2016-08-26T02:55:08Z
[ "python", "django", "templates", "django-templates" ]
Extract specific section from LaTeX file with python
39,157,084
<p>I have a set of LaTeX files. I would like to extract the "abstract" section for each one: </p> <pre class="lang-tex prettyprint-override"><code>\begin{abstract} ..... \end{abstract} </code></pre> <p>I have tried the suggestion here: <a href="http://stackoverflow.com/questions/30752351/how-to-parse-latex-file">Ho...
3
2016-08-26T01:30:22Z
39,157,185
<p><code>.*</code> does not match newlines unless the re.S flag is given:</p> <pre><code>re.findall(r'\\begin{abstract}(.*?)\\end{abstract}', data, re.S) </code></pre> <h3>Example</h3> <p>Consider this test file:</p> <pre class="lang-tex prettyprint-override"><code>\documentclass{report} \usepackage[margin=1in]{geo...
3
2016-08-26T01:45:00Z
[ "python", "regex", "latex" ]
Extract specific section from LaTeX file with python
39,157,084
<p>I have a set of LaTeX files. I would like to extract the "abstract" section for each one: </p> <pre class="lang-tex prettyprint-override"><code>\begin{abstract} ..... \end{abstract} </code></pre> <p>I have tried the suggestion here: <a href="http://stackoverflow.com/questions/30752351/how-to-parse-latex-file">Ho...
3
2016-08-26T01:30:22Z
39,157,209
<p>The <code>.</code> does not match newline character. However, you can pass a flag to ask it to include newlines.</p> <p>Example:</p> <pre><code>import re s = r"""\begin{abstract} this is a test of the linebreak capture. \end{abstract}""" pattern = r'\\begin\{abstract\}(.*?)\\end\{abstract\}' re.findall(pattern...
1
2016-08-26T01:48:49Z
[ "python", "regex", "latex" ]
Pandas Multiindex selecting list of columns from given level
39,157,142
<p>If I make a multi-indexed column dataframe like this:</p> <pre><code>iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']] index = pd.MultiIndex.from_product(iterables, names=['first', 'second']) df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index) first bar b...
1
2016-08-26T01:38:36Z
39,157,232
<p>You can use <code>loc</code> to select columns:</p> <pre><code>df.loc[:, ["bar", "qux"]] # first bar qux # second one two one two # A 1.245525 -1.469999 -0.399174 0.017094 # B -0.242284 0.835131 -0.400847 -0.344612 # C -1.067006 -1...
3
2016-08-26T01:52:16Z
[ "python", "pandas", "dataframe", "multi-index" ]
Pandas Multiindex selecting list of columns from given level
39,157,142
<p>If I make a multi-indexed column dataframe like this:</p> <pre><code>iterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']] index = pd.MultiIndex.from_product(iterables, names=['first', 'second']) df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=index) first bar b...
1
2016-08-26T01:38:36Z
39,157,293
<p>Simple column selection works as well:</p> <pre><code>df[['bar', 'qux']] # first bar qux # second one two one two # A 0.651522 0.480115 -2.924574 0.616674 # B -0.395988 0.001643 0.358048 0.022727 # C -0.317829 1.400970 -0.773148 1.5491...
4
2016-08-26T02:01:35Z
[ "python", "pandas", "dataframe", "multi-index" ]
python how to implement a list into a tree?
39,157,193
<p>I have a list of data indicates what direction is going next like:</p> <pre><code>[[0,1,0,0,1],[0,0,1],[0,0],[0,1,1,1,0]] </code></pre> <p>I want to implement this data into a tree structure like: <a href="http://i.stack.imgur.com/NA80y.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/NA80y.jpg" alt="enter i...
2
2016-08-26T01:46:31Z
39,157,266
<p>Try making a separate class for the node like so</p> <pre><code>class Node: def __init__(self, value): self.value = value self.left = None self.right = None </code></pre> <p>Then in your <code>Tree</code> class initialize <code>self.root</code> and declare your functions with recursion ...
2
2016-08-26T01:56:56Z
[ "python", "data-structures" ]
Python Sockets Select is hanging - Doing other tasks while waiting for socket data?
39,157,229
<p>I am rather a noob here, but trying to setup a script where I can poll a socket, and when no socket data has been sent, a loop continues to run and do other things. I have been playing with several examples I found using select(), but no matter how I organize the code, it seems to stop on or near the server.recv() l...
0
2016-08-26T01:52:05Z
39,166,461
<p>Great news. This was an easy fix, wanted to post in case anyone else needed it. The suggestion from acw1668 above got me going.</p> <p>Simply added a timeout of "0" to the select.select() like this:</p> <pre><code>inputready,outputready,exceptready = select.select(input,[],[],0) </code></pre> <p>This is in the py...
0
2016-08-26T12:32:32Z
[ "python", "multithreading", "sockets", "select" ]
Python - scapy sniff() filter with port range
39,157,299
<p>I want to sniff all packets in a range of ports with the scapy module.</p> <p>This is how it works for one port..</p> <pre><code>from scapy.all import * packets = sniff(filter='udp and port 14000') </code></pre> <p>But rather than only port 14000, i want to sniff the range from 14000 up to 64000.</p> <p>The foll...
1
2016-08-26T02:02:07Z
39,171,891
<p><em>Scapy</em> uses the <a href="http://biot.com/capstats/bpf.html" rel="nofollow"><em>BPF</em> syntax</a> for specifying the filter:</p> <pre><code>packets = sniff(filter='udp and portrange 14000-64000') </code></pre> <p>Note that the range is inclusive and that no spaces are allowed around the <code>'-'</code> s...
2
2016-08-26T17:38:38Z
[ "python", "range", "port", "scapy", "packet-sniffers" ]
tweepy IndexError: list index out of range
39,157,338
<p>This could be a super stupid mistake, but I just cant see what's wrong.</p> <pre><code>class listener(tweepy.streaming.StreamListener): def on_data(self, data): tweet = data.split(',"text":"')[1].split('","source')[0] screen_name = data.split(',"screen_name":"')[1].split('","location":')[0] ...
0
2016-08-26T02:07:45Z
39,160,294
<p>The tweets you get are in a JSON format, you should take advantage of that rather than trying to parse them as plain text. The attributes will be a lot easier to extract, and your code will also be much more readable.</p> <pre><code>class listener(tweepy.streaming.StreamListener): def on_data(self, data): ...
0
2016-08-26T07:06:47Z
[ "python", "split", "tweepy" ]
tweepy IndexError: list index out of range
39,157,338
<p>This could be a super stupid mistake, but I just cant see what's wrong.</p> <pre><code>class listener(tweepy.streaming.StreamListener): def on_data(self, data): tweet = data.split(',"text":"')[1].split('","source')[0] screen_name = data.split(',"screen_name":"')[1].split('","location":')[0] ...
0
2016-08-26T02:07:45Z
39,164,448
<p>The output of Tweepy response is JSON. Because JSON is an standard in intra-communicating between applications you should follow this standard by using json lib in python. So you need to load Tweepy response like this:</p> <pre><code>tweet = json.loads(data) username = tweet[user][screeen_name] language = tweet[use...
0
2016-08-26T10:46:09Z
[ "python", "split", "tweepy" ]
python return empty list from function
39,157,353
<p>I am sorry to ask such a basic question but I am trying to learn python and don't understand why this does not work. When I run this program on a directory it prints and empty list []. I don't understand why. Can someone help? Python 3.</p> <pre><code>import sys, os, def getfiles(currdir): myfiles = [] ...
-1
2016-08-26T02:10:26Z
39,163,420
<p>If i understand you want to get all of the file names in a specific directory. here is my code to do that :</p> <pre><code>Import os AllFiles = [] AllFiles = os.listdir("your Directory") </code></pre> <p>listdir() return all files name in the specific directory.</p>
0
2016-08-26T09:50:36Z
[ "python" ]
python return empty list from function
39,157,353
<p>I am sorry to ask such a basic question but I am trying to learn python and don't understand why this does not work. When I run this program on a directory it prints and empty list []. I don't understand why. Can someone help? Python 3.</p> <pre><code>import sys, os, def getfiles(currdir): myfiles = [] ...
-1
2016-08-26T02:10:26Z
39,163,700
<p>Well, at least one case where your function will return an empty list, is if the topmost directory contains only directories. Here's your code (after removing the redundant loop):</p> <pre><code>for file in os.listdir(currdir): path = os.path.join(currdir,file) if not os.path.isdir(path): myfiles.ap...
0
2016-08-26T10:06:09Z
[ "python" ]
how can I move a list index value forward 'x' amount of times using python?
39,157,398
<p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p> <p>For example if the code was</p> <pre><code>abc </code></pre> <p>Then the solution would be</p> <pre><code>cde </code></pre> <p>So I am trying to figure out how I add 2 ...
2
2016-08-26T02:19:26Z
39,157,428
<p>Try:</p> <pre><code>&gt;&gt;&gt; s = 'abc' &gt;&gt;&gt; ''.join(chr(ord(c)+2) for c in s) 'cde' </code></pre> <p>The above is not limited to standard ASCII: it works up through the unicode character set.</p> <h3>Limiting ourselves to 26 characters</h3> <pre><code>&gt;&gt;&gt; s = 'abcyz' &gt;&gt;&gt; ''.join(chr...
1
2016-08-26T02:23:21Z
[ "python" ]
how can I move a list index value forward 'x' amount of times using python?
39,157,398
<p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p> <p>For example if the code was</p> <pre><code>abc </code></pre> <p>Then the solution would be</p> <pre><code>cde </code></pre> <p>So I am trying to figure out how I add 2 ...
2
2016-08-26T02:19:26Z
39,157,441
<p>One solution would be to use enumerate:</p> <pre><code>for idx, char in enumerate(sentence): # Do what you need to do here, idx is the index of the char, # char is the char itself letter = sentence[idx + 2] # would get you the char 2 places ahead in the list </code></pre> <p>This way you could index i...
0
2016-08-26T02:25:34Z
[ "python" ]
how can I move a list index value forward 'x' amount of times using python?
39,157,398
<p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p> <p>For example if the code was</p> <pre><code>abc </code></pre> <p>Then the solution would be</p> <pre><code>cde </code></pre> <p>So I am trying to figure out how I add 2 ...
2
2016-08-26T02:19:26Z
39,157,443
<p>There are a couple of ways to do this. </p> <p>First one, use a dictionary.</p> <pre><code>a={'a':'c','b':'e'....} sol=[] for i in sentence: sol.append(a[i]) </code></pre>
0
2016-08-26T02:26:02Z
[ "python" ]
how can I move a list index value forward 'x' amount of times using python?
39,157,398
<p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p> <p>For example if the code was</p> <pre><code>abc </code></pre> <p>Then the solution would be</p> <pre><code>cde </code></pre> <p>So I am trying to figure out how I add 2 ...
2
2016-08-26T02:19:26Z
39,157,452
<pre><code>alphabet = "abc" ord_a = ord('a') solution = ''.join(chr((ord(c)-ord_a+2)%26+ord_a) for c in alphabet) </code></pre>
0
2016-08-26T02:27:13Z
[ "python" ]
how can I move a list index value forward 'x' amount of times using python?
39,157,398
<p>I'm trying to unscramble a code using pythonic methods. The way to crack the code is by selecting the letter two places ahead of itself.</p> <p>For example if the code was</p> <pre><code>abc </code></pre> <p>Then the solution would be</p> <pre><code>cde </code></pre> <p>So I am trying to figure out how I add 2 ...
2
2016-08-26T02:19:26Z
39,157,703
<p>Something like this would be useful because it would allow you to change your offset value easily. It'll also handle things other than characters</p> <pre><code>def caesar_cipher(sentence, offset): pt_alphabet = ['a','b'...'z'] ct_alphabet = [] index = len(pt_alphabet) + offset while len(ct_alphabet) &l...
0
2016-08-26T03:03:14Z
[ "python" ]
String compression using repeated chars count
39,157,420
<p>I'm going through Cracking the Code and there is this question where they ask to write a method for string compression so:</p> <pre><code>aabbccccaa </code></pre> <p>Would become: </p> <pre><code>a2b1c4a2 </code></pre> <p>I came up with this:</p> <pre><code>''.join(y+str.count(y) for y in set(str)) </code></pr...
2
2016-08-26T02:22:17Z
39,157,493
<p>You could use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby"><code>groupby</code></a> to do the work for you:</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; s = 'aabbccccaa' &gt;&gt;&gt; ''.join(k + str(sum(1 for x in g)) for k, g in groupby(s)) 'a2b2c4a2' </cod...
7
2016-08-26T02:31:53Z
[ "python" ]
using newaxis in Python
39,157,426
<pre><code>A = np.array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10,11,12]]) B = A[:, np.newaxis] print(B) print(B.shape) </code></pre> <p>the output is</p> <pre><code>[[[ 1 2 3]] [[ 4 5 6]] [[ 7 8 9]] [[10 11 12]]] (4L, 1L, 3L) </code></pre> <p>I have two questions...
0
2016-08-26T02:22:59Z
39,157,505
<p>Refer to numpy reference document (<a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a>), Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dime...
0
2016-08-26T02:34:36Z
[ "python", "arrays", "numpy", "matrix" ]