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
Django isn't finding my files in media/
40,047,874
<p>I am trying to create a webpage where users can fill out a form and email me their name, email address, a message, and an image.</p> <p>My issue is getting the image attached to the email. When the code runs, the image is uploaded to my media root along with my other media files, but it throws an FileNotFoundError ...
0
2016-10-14T16:25:27Z
40,048,870
<p>You're passing a (non-existent) URL to <code>msg.attach_file</code>. You need to pass the location of the file on disk:</p> <pre><code>msg.attach_file(os.path.join(settings.MEDIA_ROOT, newImage.uImage.name)) </code></pre>
1
2016-10-14T17:29:07Z
[ "python", "django", "forms", "email", "attachment" ]
Iterate over numpy array
40,048,006
<p>Given the following array:</p> <pre><code>x = np.array([[0,2,4,5,5.5,6,7],[4,5,6,7,2,3,4]]) </code></pre> <p>Based on that array I need to create another array that skip the rows unit the value in the first column is >5.</p> <p>So the result should like like this:</p> <pre><code>([[5.5,6,7],[2,3,4]]) </code></pr...
2
2016-10-14T16:33:53Z
40,048,058
<p>We could use a <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">boolean array</a> as index for filtering.</p> <pre><code>&gt;&gt;&gt; x[:, x[0] &gt; 5] array([[ 5.5, 6. , 7. ], [ 2. , 3. , 4. ]]) </code></pre> <ul> <li><code>x[0]</code> sele...
3
2016-10-14T16:37:27Z
[ "python", "numpy" ]
Iterate over numpy array
40,048,006
<p>Given the following array:</p> <pre><code>x = np.array([[0,2,4,5,5.5,6,7],[4,5,6,7,2,3,4]]) </code></pre> <p>Based on that array I need to create another array that skip the rows unit the value in the first column is >5.</p> <p>So the result should like like this:</p> <pre><code>([[5.5,6,7],[2,3,4]]) </code></pr...
2
2016-10-14T16:33:53Z
40,048,128
<p>Or the enumerate function:</p> <pre><code> res = [] for i, _ in enumerate(x): res.append([]) for j, val in enumerate(x[i]): if j &gt; 5: res[i].append(val) </code></pre>
0
2016-10-14T16:41:48Z
[ "python", "numpy" ]
my django looks like can`t recognize the templates
40,048,016
<p>i am a noob learning python,when i learning the template of django,i met some mistakes;what i am using is pycharm2016.2.3 ,python3.5.2,django1.10.1</p> <p>here is my dir list:</p> <pre><code>│ db.sqlite3 │ manage.py ├─djangotest │ │ settings.py │ │ urls.py │ │ view.py │ │ wsgi.py ...
1
2016-10-14T16:34:24Z
40,048,233
<p>You're missing a url definition :</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello$/', djangotest.hello), ] </code></pre>
1
2016-10-14T16:47:48Z
[ "python", "django", "templates", "pycharm" ]
How to show a Kivy GUI using cron planner?
40,048,097
<p>I've made a simple Python script that would display a little alert window. I wanted it to do so every 20 minutes, so I looked into the <code>cron</code> planner, as I am using Ubuntu.<br> The command I used to run the script was <code>python3 alert.py</code>, with <code>alert.py</code> being the script in my home di...
1
2016-10-14T16:40:14Z
40,048,469
<p>The solution was to change the command behaviour to <code>X application</code> (rather than <code>Default behaviour</code>). After that change, the console shows up and the GUI is displayed.</p> <p><a href="https://i.stack.imgur.com/Levi1.png" rel="nofollow"><img src="https://i.stack.imgur.com/Levi1.png" alt="gnome...
2
2016-10-14T17:04:14Z
[ "python", "cron", "kivy" ]
a more efficient way to compute a spark dataframe
40,048,239
<p>I have a sales dataframe similar to:</p> <pre><code>id | date | amount -----|-------------------|------- 1 |2016-03-04 12:03:00|10.40 1 |2016-03-04 12:05:10|5.0 1 |2016-03-04 12:15:50|11.30 1 |2016-03-04 12:16:00|9.40 1 |2016-03-04 12:30:00|10.0 1 |2016-03-04 12:40:00|5.40 </code>...
1
2016-10-14T16:47:59Z
40,053,805
<p>This can be little dirty if you want to process as String, you can try this:</p> <pre><code>def getDTClosestMin(s:String):String = { s.substring(0,4)+"-"+s.substring(5,7)+"-"+s.substring(8,10)+" " + s.substring(11,13)+":" + ((((s.substring(14,16)).toInt)*0.1).ceil)*10).round.toString.padTo(2,"0").mkString } ti...
0
2016-10-15T00:35:04Z
[ "python", "apache-spark", "pyspark" ]
From RDDs to jointed DataFrames PySpark
40,048,298
<p>I'm looking for a way to combine two DataFrames by key. I started by creating Dataframes from rdds :</p> <p>Given :</p> <pre><code>x = sc.parallelize([('_guid_YWKnKkcrg_Ej0icb07bhd-mXPjw-FcPi764RRhVrOxE=', 'FR', '75001'), ('_guid_XblBPCaB8qx9SK3D4HuAZwO-1cuBPc1GgfgNUC2PYm4=', 'TN', '8160'), ...
1
2016-10-14T16:51:38Z
40,052,733
<p>Once you have your joined dataset, you can run another <code>select</code> to output specific columns, then convert to rdd, map it to get only non-null IDs:</p> <pre><code>df.select('id','id_gigya','countrycode','postalcode')\ .rdd\ .map(lambda x: Row(id=(x.id if x.id_gigya == None else x.id_gigya), postalcode=...
0
2016-10-14T22:14:06Z
[ "python", "join", "apache-spark", "pyspark", "spark-dataframe" ]
SymPy - Solving for variable in equation
40,048,309
<p>Is it possible to define an equation and solve a variable in that equation?</p> <pre><code>D_PWM, Rsense, A = symbols('D_PWM, Rsense, A') i_out = D_PWM * (A/Rsense) print i_out solve(i_out, Rsense) </code></pre> <p>Result:</p> <pre><code>A*D_PWM/Rsense [] </code></pre>
2
2016-10-14T16:52:05Z
40,048,637
<p><strong>i_out</strong> has not been declared as a symbol.</p> <pre><code>&gt;&gt;&gt; from sympy import * &gt;&gt;&gt; var('D_PWM, Rsense, A i_out') (D_PWM, Rsense, A, i_out) &gt;&gt;&gt; eqn=Eq(i_out,D_PWM * (A/Rsense)) &gt;&gt;&gt; solve(eqn,Rsense) [A*D_PWM/i_out] </code></pre>
4
2016-10-14T17:15:15Z
[ "python", "sympy" ]
Pandas: building a column with self-refrencing past values
40,048,323
<p>I need to generate a column that starts with an initial value, and then is generated by a function that includes past values of that column. For example</p> <pre><code>df = pd.DataFrame({'a': [1,1,5,2,7,8,16,16,16]}) df['b'] = 0 df.ix[0, 'b'] = 1 df a b 0 1 1 1 1 0 2 5 0 3 2 0 4 7 0 5 8 0 6 ...
4
2016-10-14T16:53:16Z
40,048,869
<p><code>pandas</code> doesn't have a great way to handle general recursive calculations. There may be some trick to vectorize it, but if you can take the dependency, this is relatively painless and very fast with <code>numba</code>.</p> <pre><code>@numba.njit def make_b(a): b = np.zeros_like(a) b[0] = 1 ...
3
2016-10-14T17:29:06Z
[ "python", "pandas" ]
Python Pillow: how to overlay one binary image on top of another to produce a composite?
40,048,342
<p>I am doing some image processing, and I need to check if a binary image is identical to another. </p> <p>Processing speed isn't an issue, and the simple thing I thought to do was count the white pixels remaining after adding the inverse of image A to image B (these images are very nearly identical, but not quite--...
0
2016-10-14T16:55:01Z
40,048,456
<p>Clearly you're using <code>numpy</code>, so why not just work with <code>numpy</code> arrays and explicitly do whatever arithmetic you want to do in that domain—such as subtracting one image from the other:</p> <pre><code>arrayA = numpy.asarray( imgA, dtype=int ) arrayB = numpy.asarray( imgB, dtype=int ) arrayDe...
1
2016-10-14T17:03:28Z
[ "python", "image", "pillow" ]
django urlpattern wrong? need to accept 2 different parameters
40,048,470
<p>I'm working on building a django app for a small little game I'm building to integrate it. Instead of re-writing my app to use django's membership system I've added my small little game login system to the django site. My issue is with my ChangePassword url pattern.</p> <pre><code>url(r'^ChangePassword/(?P&lt;userI...
0
2016-10-14T17:04:14Z
40,048,586
<p>Your regex pattern for the token:</p> <pre><code>(?P&lt;token&gt;/?$) </code></pre> <p>Will match an optional forward slash <code>/</code> that <em>ends</em> the url. In other words it will match <code>/members/ChangePassword/11/</code> or <code>/members/ChangePassword/11//</code>.</p> <p>You will need to modify ...
0
2016-10-14T17:12:01Z
[ "python", "django", "python-2.7" ]
Make several lists matching several ranges in python
40,048,546
<p>I have a problem with my code and I have spent a long time on it and I can't fix it:</p> <p>I have a file like this:</p> <pre><code>ATOM 1375 N PHE F 411 81.522 91.212 98.734 1.00 0.00 N ATOM 1376 H PHE F 411 82.393 91.667 97.546 1.00 0.00 H ATOM 1377 CA PHE ...
1
2016-10-14T17:08:57Z
40,049,195
<p>Here is some code I put together that does what you are looking for. I would look at the python documentation for <code>map</code> and <code>filter</code> which are really handy for doing things like this.</p> <pre><code>text = """ATOM 1375 N PHE F 411 81.522 91.212 98.734 1.00 0.00 N ATOM ...
0
2016-10-14T17:49:22Z
[ "python" ]
google cloud dataflow can run locally but can't run on the cloud
40,048,563
<p>I can't run my pipeline locally, using the "DirectPipelineRunner" but when I use "BlockingDataflowPipelineRunner" to run on the cloud it always shows that "Failed to split source". I don't where is the problem of my pipeline.</p> <p>I define my custom sources to read a lot of tgz file in my bucket. The following is...
0
2016-10-14T17:10:19Z
40,098,608
<p>Thanks for all the comments above.<br> I tried several ways to solve my problem. And I have a little progress. I think it is necessary that I should describe my problem again.<br> <br> I add the compression_type argument and set it to <code>fileio.CompressionTypes.GZIP</code>. Just as below.</p> <pre><code>pcoll = ...
0
2016-10-18T02:33:18Z
[ "python", "google-cloud-dataflow" ]
google cloud dataflow can run locally but can't run on the cloud
40,048,563
<p>I can't run my pipeline locally, using the "DirectPipelineRunner" but when I use "BlockingDataflowPipelineRunner" to run on the cloud it always shows that "Failed to split source". I don't where is the problem of my pipeline.</p> <p>I define my custom sources to read a lot of tgz file in my bucket. The following is...
0
2016-10-14T17:10:19Z
40,137,016
<p>Reading a tar file using StringIO as mentioned above cannot be recommended due to having to load all data into memory.</p> <p>Seems like your original implementation didn't work since tarfile.open() using methods seek() and tell() which are not supported by fileio._CompressedFile object returned by filebasedsource....
0
2016-10-19T16:34:16Z
[ "python", "google-cloud-dataflow" ]
What is the cleanest way to initialize dynamic list in Python?
40,048,576
<p>This is a question regarding best coding practices. Suppose I have to populate a list of unknown length; usually I just initialize the list with <code>myList = []</code>, but I feel like this is a poor way of doing this. I often end up with chunks of code that look like this:</p> <pre><code>list1 = [] list2 = [] li...
-1
2016-10-14T17:11:11Z
40,048,651
<p>Use a list of lists:</p> <pre><code>lol = [[], [], []] for items in zip(x, y, z): for i, item in enumerate(items): lol[i].append(item) </code></pre>
1
2016-10-14T17:15:43Z
[ "python" ]
What is the cleanest way to initialize dynamic list in Python?
40,048,576
<p>This is a question regarding best coding practices. Suppose I have to populate a list of unknown length; usually I just initialize the list with <code>myList = []</code>, but I feel like this is a poor way of doing this. I often end up with chunks of code that look like this:</p> <pre><code>list1 = [] list2 = [] li...
-1
2016-10-14T17:11:11Z
40,048,679
<p>No need for anything clever:</p> <pre><code>list1 = list(x) list2 = list(y) list3 = list(z) </code></pre>
2
2016-10-14T17:17:23Z
[ "python" ]
Import Error: No module called magic yet python-magic is installed
40,048,614
<p>I am trying to edit some code that uses python-magic but I get an <em>Import Error: No module called magic</em>. Before I looked around the Internet and found advise on installing python-magic using pip which I did. I installed python-magic using pip install python-magic and also did pip install libarchive-c succes...
1
2016-10-14T17:13:32Z
40,048,704
<p>You have installed <code>magic</code> for Python 2.7, but Diffoscope uses Python 3 and <a href="http://pydigger.com/pypi/diffoscope" rel="nofollow">explicitly recommends</a> the package <a href="http://packages.ubuntu.com/search?keywords=python3-magic" rel="nofollow"><code>python3-magic</code></a> in the repositorie...
2
2016-10-14T17:19:27Z
[ "python", "python-magic" ]
Scaling NetworkX nodes and edges proportional to adjacency matrix
40,048,657
<p>Does NetworkX have a built-in way of scaling the nodes and edges proportional to the adjacency matrix frequency / node-node frequency? I am trying to scale the size of the nodes and text based on the adjacency matrix frequency and the weight of the edge based on the node-node frequency. I have created a frequency at...
0
2016-10-14T17:16:12Z
40,053,852
<p>I tried the following to match your need:</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt ## create nx graph from adjacency matrix def create_graph_from_adj(A): # A=[(n1, n2, freq),....] G = nx.Graph() for a in A: G.add_edge(a[0], a[1], freq=a[2]) return G A = [(0, 1, ...
0
2016-10-15T00:44:33Z
[ "python", "text", "graph", "networkx" ]
Python Plotting: Heatmap from dataframe with fixed colors in case of strings
40,048,702
<p>I'm trying to visualise a large (pandas) dataframe in Python as a heatmap. This dataframe has two types of variables: strings ("Absent" or "Unknown") and floats.</p> <p>I want the heatmap to show cells with "Absent" in black and "Unknown" in red, and the rest of the dataframe as a normal heatmap, with the floats in...
0
2016-10-14T17:19:19Z
40,050,116
<p>You could use <code>cmap_custom.set_under('red')</code> and <code>cmap_custom.set_over('black')</code> to apply custom colors to values below and above <code>vmin</code> and <code>vmax</code> (See <a href="http://stackoverflow.com/a/27175748/190597">1</a>, <a href="http://stackoverflow.com/a/35905483/190597">2</a>):...
1
2016-10-14T18:46:55Z
[ "python", "pandas", "matplotlib", "dataframe", "heatmap" ]
Check if method already is in instance in object?
40,048,729
<p>I'm trying to see whether an instance of an attribute already exists for my object. As you can see below, I want to do something if my <code>Dog</code> object has a certain attribute, via the <code>do_something_if_has_aged</code> method. How can I check whether a certain attribute has already been declared? Usually ...
1
2016-10-14T17:20:29Z
40,048,776
<p>It looks like you are looking for the <a href="https://docs.python.org/2/library/functions.html#hasattr" rel="nofollow"><code>hasattr</code></a> built-in function:</p> <pre><code>&gt;&gt;&gt; class Dog(object): ... pass ... &gt;&gt;&gt; a = Dog() &gt;&gt;&gt; hasattr(a, 'age') False &gt;&gt;&gt; a.age = 7 &gt;&...
4
2016-10-14T17:22:54Z
[ "python", "class", "oop", "attributes", "instance" ]
Check if method already is in instance in object?
40,048,729
<p>I'm trying to see whether an instance of an attribute already exists for my object. As you can see below, I want to do something if my <code>Dog</code> object has a certain attribute, via the <code>do_something_if_has_aged</code> method. How can I check whether a certain attribute has already been declared? Usually ...
1
2016-10-14T17:20:29Z
40,048,874
<p>I would rewrite the <code>__init__</code> method to include <code>self.has_aged = False</code> to avoid having to do inspection:</p> <pre><code>class Dog(object): def __init__(self, name, age): self.name = name self.age = age self.has_aged = False # Starting value so it is guaranteed to ...
1
2016-10-14T17:29:23Z
[ "python", "class", "oop", "attributes", "instance" ]
Check if method already is in instance in object?
40,048,729
<p>I'm trying to see whether an instance of an attribute already exists for my object. As you can see below, I want to do something if my <code>Dog</code> object has a certain attribute, via the <code>do_something_if_has_aged</code> method. How can I check whether a certain attribute has already been declared? Usually ...
1
2016-10-14T17:20:29Z
40,048,907
<p>To check if using <code>hasattr</code> is perfectly fine, but in case you are looking for a quick fix for you code, you can do initialize the variable as false before hand:</p> <pre><code>class Dog: has_aged = False </code></pre> <p>and also the fix your condition as i think it should be reversed:</p> <pre><cod...
1
2016-10-14T17:31:13Z
[ "python", "class", "oop", "attributes", "instance" ]
Check if method already is in instance in object?
40,048,729
<p>I'm trying to see whether an instance of an attribute already exists for my object. As you can see below, I want to do something if my <code>Dog</code> object has a certain attribute, via the <code>do_something_if_has_aged</code> method. How can I check whether a certain attribute has already been declared? Usually ...
1
2016-10-14T17:20:29Z
40,048,979
<p>Rather than test for the attribute, set a default value on the class; if an instance attribute is missing Python looks for a class attribute instead:</p> <pre><code>class Dog: has_aged = False # default for all instances def __init__(self, name, age): self.name = name self.age = age def...
3
2016-10-14T17:36:08Z
[ "python", "class", "oop", "attributes", "instance" ]
geckodriver executable needs to be in path
40,048,940
<p>I have read previous questions asked on this topic and tried to follow the suggestions but I continue to get errors. On terminal, I ran </p> <pre><code>export PATH=$PATH:/Users/Conger/Documents/geckodriver-0.8.0-OSX </code></pre> <p>I also tried</p> <pre><code> export PATH=$PATH:/Users/Conger/Documents/geckodr...
0
2016-10-14T17:33:38Z
40,085,081
<p>First we know that gekodriver is the driver engine of Firefox,and we know that <code>driver.Firefox()</code> is used to open Firefox browser, and it will call the gekodriver engine ,so we need to give the gekodirver a executable permission. so we download the latest gekodriver uncompress the tar packge ,and p...
0
2016-10-17T11:21:53Z
[ "python" ]
Importing PMML models into Python (Scikit-learn)
40,048,987
<p>There seem to be a few options for exporting PMML models out of scikit-learn, such as sklearn2pmml, but a lot less information going in the other direction. My case is an XGboost model previously built in R, and saved to PMML using r2pmml, that I would like to use in Python. Scikit normally uses pickle to save/loa...
0
2016-10-14T17:36:50Z
40,049,831
<p>You can't connect different specialized representations (such as R and Scikit-Learn native data structures) over a generalized representation (such as PMML). You may have better luck trying to translate R data structures to Scikit-Learn data structures directly.</p> <p>XGBoost is really an exception to the above ru...
1
2016-10-14T18:28:10Z
[ "python", "scikit-learn", "pmml" ]
'helloworld.pyx' doesn't match any files
40,048,990
<p>I am a beginner in python and I have just got familiar with cython as well. I am using Anaconda on Windows 64-bit. I am trying to run the "helloworld" example as follows:</p> <p>1- I build a helloworld.pyx file containing:</p> <pre><code> print("Hello World") </code></pre> <p>2- I build a setup.py file contain...
1
2016-10-14T17:36:56Z
40,050,367
<p>From here: <a href="https://github.com/cython/cython/wiki/enhancements-distutils_preprocessing" rel="nofollow">https://github.com/cython/cython/wiki/enhancements-distutils_preprocessing</a></p> <pre><code>from distutils.core import setup from Cython.Build import cythonize setup( name = 'MyProject', ext_modules...
1
2016-10-14T19:04:59Z
[ "python", "cython" ]
Requiring the type of a parameter of an objects method to be the class of this same object
40,049,016
<p>The code I have included below throws the following error:</p> <pre><code>NameError: name 'Vector2' is not defined </code></pre> <p>at this line: </p> <pre><code>def Translate (self, pos: Vector2): </code></pre> <p>Why does Python not recognize my <code>Vector2</code> class in the <code>Translate</code> method?...
1
2016-10-14T17:39:05Z
40,049,081
<p>Because when it encounters <code>Translate</code> (while compiling the class body), <code>Vector2</code> hasn't been defined yet (it is currently compiling, name binding hasn't been performed); Python naturally complains. </p> <p>Since this is such a common scenario (type-hinting a class in the body of that class),...
3
2016-10-14T17:43:02Z
[ "python", "python-3.x", "oop", "type-hinting" ]
View not found for views with number at the end
40,049,048
<p>I'm trying to do a <code>reverse</code> like this:</p> <pre><code>print reverse("shows-view") </code></pre> <p>This is in my <code>urls.py</code>:</p> <pre><code>url(r'^shows/(\d+)$', views.show_details, name="shows-view"), </code></pre> <p>Whenever I try to do that, it just returns:</p> <pre><code>Reverse for ...
1
2016-10-14T17:41:23Z
40,049,203
<p>The URL in question accepts an argument <code>(\d+)</code> which you are not passing your <code>reverse</code> function. Just think: this is a details view, but <em>which</em> show do you want to display?</p> <p>To fix, call <code>reverse</code> with the <code>args</code> parameter:</p> <pre><code>reverse("shows-d...
0
2016-10-14T17:49:45Z
[ "python", "django", "python-2.7", "django-templates", "django-views" ]
Supercomputer: Dead simple example of a program to run in supercomputer
40,049,092
<p>I am learning how to use supercomputers to make the good use of resources. Let's say I have a python script, that will create a text file with given random number.</p> <h1>myfile.py</h1> <pre><code># Imports import random,os outdir = 'outputs' if not os.path.exists(outdir): os.makedirs(outdir) with open (out...
1
2016-10-14T17:43:40Z
40,049,264
<p>Take a look to this link it may solve your problem</p> <p><a href="http://materials.jeremybejarano.com/MPIwithPython/introMPI.html" rel="nofollow">http://materials.jeremybejarano.com/MPIwithPython/introMPI.html</a></p> <p>so your code may be something like:</p> <pre><code>from mpi4py import MPI import random,os ...
1
2016-10-14T17:53:13Z
[ "python", "supercomputers", "mpiexec" ]
Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
40,049,174
<p>I am looking for a way to view the header information of my requests when calling the Shopify API.</p> <p>The API documentation says: </p> <blockquote> <p>You can check how many calls you've already made using the Shopify header that was sent in response to your API call: HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT (li...
0
2016-10-14T17:47:54Z
40,049,210
<p>Was able to access it via:</p> <p><code>resp_header = shopify.ShopifyResource.connection.response.headers.['x-shopify-shop-api-call-limit']</code></p> <p>However, I also saw on another thread that there is also an API Key Global limit that should be accessible somewhere through: <code>'x-shopify-api-call-limit'</c...
0
2016-10-14T17:50:21Z
[ "python", "shopify" ]
How do I tell python what my data structure (that is in binary) looks like so I can plot it?
40,049,249
<p>I have a data set that looks like this.</p> <pre><code>b'\xa3\x95\x80\x80YFMT\x00BBnNZ\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Type,Length,Name,Format,Columns\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa3\x95\x80\x81\x17PAR...
0
2016-10-14T17:52:46Z
40,075,559
<p>A good starting point for parsing binary data is the struct module <a href="https://docs.python.org/3/library/struct.html" rel="nofollow">https://docs.python.org/3/library/struct.html</a> and it's <code>unpack</code> function. That's what the CSV dump routine you linked to is doing as well. If you walk through the <...
2
2016-10-16T21:14:47Z
[ "python" ]
Getting a list of suffixes from the company names
40,049,268
<p>I have a data frame df with a column name - Company. Few examples of the company names are: ABC Inc., XYZ Gmbh, PQR Ltd, JKL Limited etc. I want a list of all the suffixes (Inc.,Gmbh, Ltd., Limited etc). Please notice that suffix length is always different. There might be companies without any suffix, for example: A...
1
2016-10-14T17:53:26Z
40,049,727
<p>So you want the last word of the Company name, assuming the company has a name more than one word long?</p> <pre><code>set(name_list[-1] for name_list in map(str.split, company_names) if len(name_list) &gt; 1) </code></pre> <p>The <code>[-1]</code> gets the last word. <code>str.split</code> splits on spaces. I'v...
0
2016-10-14T18:21:03Z
[ "python", "pandas" ]
Getting a list of suffixes from the company names
40,049,268
<p>I have a data frame df with a column name - Company. Few examples of the company names are: ABC Inc., XYZ Gmbh, PQR Ltd, JKL Limited etc. I want a list of all the suffixes (Inc.,Gmbh, Ltd., Limited etc). Please notice that suffix length is always different. There might be companies without any suffix, for example: A...
1
2016-10-14T17:53:26Z
40,051,993
<p>try this:</p> <pre><code>In [36]: df Out[36]: Company 0 Google 1 Apple Inc 2 Microsoft Inc 3 ABC Inc. 4 XYZ Gmbh 5 PQR Ltd 6 JKL Limited In [37]: df.Company.str.extract(r'\s+([^\s]+$)', expand=False).dropna().unique() Out[37]: array(['Inc', 'Inc.', 'Gmbh', 'Ltd', 'Limit...
0
2016-10-14T21:06:54Z
[ "python", "pandas" ]
Getting a list of suffixes from the company names
40,049,268
<p>I have a data frame df with a column name - Company. Few examples of the company names are: ABC Inc., XYZ Gmbh, PQR Ltd, JKL Limited etc. I want a list of all the suffixes (Inc.,Gmbh, Ltd., Limited etc). Please notice that suffix length is always different. There might be companies without any suffix, for example: A...
1
2016-10-14T17:53:26Z
40,052,513
<p>You can use <a href="https://github.com/psolin/cleanco" rel="nofollow">cleanco</a> Python library for that, it has a <a href="https://github.com/psolin/cleanco/blob/master/termdata.py" rel="nofollow">list</a> of all possible suffixes inside. E.g. it contains all the examples you provided (Inc, Gmbh, Ltd, Limited). <...
0
2016-10-14T21:50:04Z
[ "python", "pandas" ]
Getting a list of suffixes from the company names
40,049,268
<p>I have a data frame df with a column name - Company. Few examples of the company names are: ABC Inc., XYZ Gmbh, PQR Ltd, JKL Limited etc. I want a list of all the suffixes (Inc.,Gmbh, Ltd., Limited etc). Please notice that suffix length is always different. There might be companies without any suffix, for example: A...
1
2016-10-14T17:53:26Z
40,052,528
<p>This only adds the suffixes when the company name has more than one word as you required.</p> <pre><code>company_names = ["Apple", "ABS LLC", "Animusoft Corp"] suffixes = [name.split()[-1] for name in company_names if len(name.split()) &gt; 1] </code></pre> <p>Now having into account that this doesn't cover the un...
0
2016-10-14T21:51:15Z
[ "python", "pandas" ]
Python - Salesforce: How to find an object with no definitive class name and verify the text?
40,049,278
<p>So, currently I'm using Python 3 and the selenium webdriver with Salesforce to automate admin verifications.</p> <p>I've been pretty successful (even though I'm not that proficient with programming). However, I've run into an issue... I can't seem to figure out how to find an element on the page so that I can verif...
1
2016-10-14T17:53:53Z
40,064,312
<ol> <li>Open the page using the google chrome browser</li> <li>Move the mouse over the element that you want to find and right-click it</li> <li>Left click Inspect (at the bottom of the selection list)</li> <li>Your element will be hi-lighted in the Developers tools</li> <li>Right click the hi-lighted element and sele...
0
2016-10-15T21:17:09Z
[ "python", "selenium", "salesforce" ]
Python - Salesforce: How to find an object with no definitive class name and verify the text?
40,049,278
<p>So, currently I'm using Python 3 and the selenium webdriver with Salesforce to automate admin verifications.</p> <p>I've been pretty successful (even though I'm not that proficient with programming). However, I've run into an issue... I can't seem to figure out how to find an element on the page so that I can verif...
1
2016-10-14T17:53:53Z
40,065,996
<p>you can use <code>//tag[text()="value"] or //tag[contains(attribute,‘value’)]</code></p> <p>example : <code>browser.find_element_by_xpath("//a[@class='zen-trigger']//*[‌​text()='PVT GBI Internal']")</code> </p> <pre><code>//a[@class='zen-trigger']//*[contains(text(),'PVT GBI Internal')] //a[@class='zen-tri...
0
2016-10-16T01:43:47Z
[ "python", "selenium", "salesforce" ]
List comprehension using multiple lists
40,049,311
<p>I was unable to determine a Pythonic way for generating a list using list comprehension from multiple lists. I'm trying to generate a list that implements the following function:</p> <p>vbat = Vmax - a + b + c</p> <p>Where Vmax is a constant but a, b and c are lists. I was hoping I could do something that's easy...
1
2016-10-14T17:56:01Z
40,049,376
<p>The <code>zip</code> function can combine multiple lists into a sequence of tuples:</p> <pre><code>[Vmax - a_el + b_el + c_el for (a_el, b_el, c_el) in zip(a, b, c)] </code></pre>
4
2016-10-14T17:59:13Z
[ "python", "list" ]
Any way for tornado handler to detect closure on other end?
40,049,320
<p>I have a tornado coroutine hander that looks in part like:</p> <pre><code>class QueryHandler(tornado.web.RequestHandler): queryQueues = defaultdict(tornado.queues.Queue) @tornado.gen.coroutine def get(self, network): qq = self.queryQueues[network] query = yield qq.get() # do som...
0
2016-10-14T17:56:25Z
40,050,632
<p>You want a "queue with guaranteed delivery" which is a hard problem in distributed systems. After all, even if "self.write" succeeds, you can't be certain the other end really received the message.</p> <p>A basic approach would look like this:</p> <ul> <li>each entry in the queue gets an id greater than all previo...
1
2016-10-14T19:25:02Z
[ "python", "python-requests", "tornado", "coroutine" ]
Compare multiple values in a poker game in python
40,049,335
<p>Here's the question: For a poker game, I want to be able to compare multiple variables efficiently. This is the body of the code, one has to enter five cards starting from the one with the highest value (ace = 1, king = 13):</p> <pre><code>print("*********") print("P O K E R") print("*********") print("Type in you...
0
2016-10-14T17:57:23Z
40,049,489
<p>My approach would be to first order the cards by size (4,7,9,12,13) and then write functions like checkPairs(), checkFlush() and apply them to it.</p> <p>Ordering the cars will help you because you will be able to check for example if you have two cards of the same value.. they will be consecitve</p> <pre><code>fu...
1
2016-10-14T18:05:53Z
[ "python", "combinations" ]
Compare multiple values in a poker game in python
40,049,335
<p>Here's the question: For a poker game, I want to be able to compare multiple variables efficiently. This is the body of the code, one has to enter five cards starting from the one with the highest value (ace = 1, king = 13):</p> <pre><code>print("*********") print("P O K E R") print("*********") print("Type in you...
0
2016-10-14T17:57:23Z
40,049,864
<p>Rather than creating tons of <code>if/elif</code> branches, you might want to consider building the complete list of all poker combinations, and use that to compare drawn hands to this pre-built list. The number of 5-card poker hand combinations is ~2.6 million. This includes 1.3 million high card combinations whic...
1
2016-10-14T18:30:00Z
[ "python", "combinations" ]
Compare multiple values in a poker game in python
40,049,335
<p>Here's the question: For a poker game, I want to be able to compare multiple variables efficiently. This is the body of the code, one has to enter five cards starting from the one with the highest value (ace = 1, king = 13):</p> <pre><code>print("*********") print("P O K E R") print("*********") print("Type in you...
0
2016-10-14T17:57:23Z
40,050,603
<p>Why don't you use OOP? I think it'll make it much easier to change your project as you go along. I've worked something out here - <em>not fully tested</em>, but it should give you an idea:</p> <pre><code>import random class Card(object): card_values = {'ace' : 13, 'king' : 12, 'queen' : 11, 'jack' : 10, ...
1
2016-10-14T19:23:03Z
[ "python", "combinations" ]
Pandas Grouping - Values as Percent of Grouped Totals Based on Another Column
40,049,347
<p>This question is an extension of <a href="http://stackoverflow.com/questions/40033190/pandas-grouping-values-as-percent-of-grouped-totals-not-working">a question I asked yesterday, but I will rephrase</a></p> <p>Using a data frame and pandas, I am trying to figure out what the tip percentage is for each category in...
1
2016-10-14T17:58:01Z
40,049,501
<p>You can use <code>apply</code> to loop through rows of the data frame (with <code>axis = 1</code>), where for each row you can access the <code>tip</code> and <code>total_bill</code> and divide them to get the percentage:</p> <pre><code>(df.groupby(['sex', 'smoker'])[['total_bill','tip']].sum() .apply(lambda r: ...
1
2016-10-14T18:06:17Z
[ "python", "pandas", "dataframe", "aggregate", "aggregation" ]
pandas df seems not showing histogram, though data seems to be numeric
40,049,348
<p>I have the following data:</p> <pre><code>23345355,USA, ,1/8/2016,5411, ,18.31, ,95448 268035111,USA, ,1/8/2016,5921, ,15.22, ,90266 35940332,USA, ,1/26/2016,5651, ,121.94, ,91306 4211391, , ,12/31/2015,0, ,44.40, , 319878537,USA, ,12/29/2015,5814,04,0.86, ,90029 117039647,ESP, ,1/2/2016,3535, ,372.38, ...
0
2016-10-14T17:58:01Z
40,049,745
<p>You last column won't be of type <code>int</code> because <code>08019</code> isn't implicitely considered a int. Call <code>astype(int)</code> against that column for convert it into int.</p>
1
2016-10-14T18:22:16Z
[ "python", "pandas", "histogram", "numeric" ]
cannot import name "irc"
40,049,371
<p>I'm trying to run a piece of code that starts like this.</p> <pre><code>from twisted.words.protocols import irc from twisted.internet import reactor, protocol import logging import logging.config import utilities import time class TriviaBot(irc.IRCClient): """A trivia IRC Bot.""" class Event: "...
0
2016-10-14T17:59:02Z
40,050,980
<p>Are you using Python 3 by any chance? It looks like only the <code>jabber</code> module has been ported to Python 3 from the <code>twisted.words.protocols</code> package. Twisted is fully supported on Python 2 so try running your script using <code>python2</code>.</p>
1
2016-10-14T19:50:21Z
[ "python", "import", "twisted", "irc" ]
Return part of result if occur a except
40,049,375
<p>I am using python. I have a function (getAll) that call other function in a loop (getPart) and in each step the return value is updated. In some case when I call the function that is inside the loop, this fail. I need return the result in this moment.</p> <pre><code>def getAll(m, d, v, t, s, tn, type): result = [...
0
2016-10-14T17:59:13Z
40,049,461
<p>Sounds like you need to use try, except blocks</p> <pre><code>def getAll(m, d, v, t, s, tn, type): result = [] flag = 0 while flag == 0: try: #start of the try block. tempResult = getPart(m, d, v) for i in range(0, len(tempResult)): result.append(tempResu...
3
2016-10-14T18:04:39Z
[ "python", "except" ]
Return part of result if occur a except
40,049,375
<p>I am using python. I have a function (getAll) that call other function in a loop (getPart) and in each step the return value is updated. In some case when I call the function that is inside the loop, this fail. I need return the result in this moment.</p> <pre><code>def getAll(m, d, v, t, s, tn, type): result = [...
0
2016-10-14T17:59:13Z
40,049,494
<p>You can handle the exception by wrapping the code that raises the error with a <code>try/except</code> and <em>printing</em> the result in the <code>except</code> block:</p> <pre><code>def getAll(m, d, v, t, s, tn, type): result = [] flag = 0 while flag == 0: try: tempResult = getPar...
3
2016-10-14T18:06:03Z
[ "python", "except" ]
Return part of result if occur a except
40,049,375
<p>I am using python. I have a function (getAll) that call other function in a loop (getPart) and in each step the return value is updated. In some case when I call the function that is inside the loop, this fail. I need return the result in this moment.</p> <pre><code>def getAll(m, d, v, t, s, tn, type): result = [...
0
2016-10-14T17:59:13Z
40,049,502
<p>This is not necessarily the best solution, since depending on the error, it may be better to prevent it than to handle it in this way. However, you can <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="nofollow">try</a> (no pun originally intended...) the following (where <code>Whatev...
1
2016-10-14T18:06:20Z
[ "python", "except" ]
Return part of result if occur a except
40,049,375
<p>I am using python. I have a function (getAll) that call other function in a loop (getPart) and in each step the return value is updated. In some case when I call the function that is inside the loop, this fail. I need return the result in this moment.</p> <pre><code>def getAll(m, d, v, t, s, tn, type): result = [...
0
2016-10-14T17:59:13Z
40,049,613
<p>Wrap your method in a try, except block. You might want to raise an exception so you can respond to it too. </p> <pre><code>def getAll(m, d, v, t, s, tn, type): result = [] flag = 0 try: while flag == 0: tempResult = getPart(m, d, v) for i in range(0, len(tempResult)): ...
1
2016-10-14T18:13:43Z
[ "python", "except" ]
PySpark: How to group a column as a list when joining two spark dataframes?
40,049,380
<p>I want to join the following spark dataframes on Name:</p> <pre><code>df1 = spark.createDataFrame([("Mark", 68), ("John", 59), ("Mary", 49)], ['Name', 'Weight']) df2 = spark.createDataFrame([(31, "Mark"), (32, "Mark"), (41, "John"), (42, "John"), (43, "John")],[ 'Age', 'Name']) </code></pre> <p>but I want the res...
0
2016-10-14T17:59:25Z
40,066,971
<p>A DataFrame is equivalent to a relational table in Spark SQL. You can groupBy, join, then select.</p> <pre><code>from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.functions import * sc = SparkContext() sql = SQLContext(sc) df1 = sql.createDataFrame([("Mark", 68), ("John", 59), ...
0
2016-10-16T04:52:43Z
[ "python", "apache-spark", "pyspark" ]
Django hide field when creating new object
40,049,437
<p>I want to hide field name when user is creating new object, but it must be visible if user wants to edit this object. I tried exclude method but it makes field invisible when i try to edit this field. for example i want to hide status field.</p> <pre><code>class Toys(BaseModel): name = models.CharField(max_len...
0
2016-10-14T18:03:16Z
40,050,432
<p>In the model admin that you register in your <code>admin.py</code> file you can overload the <code>get_form(self, request, obj=None, **kwargs)</code> method. As you can see it takes the obj argument, it is <code>None</code> only on add (not <code>None</code> on change). From there you could mess around with the form...
1
2016-10-14T19:09:27Z
[ "python", "django" ]
Exclude between time in pandas
40,049,456
<p>I know that you can select data from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow">pandas.DatetimeIndex</a> using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow">pandas.DataFrame.between_time<...
1
2016-10-14T18:04:23Z
40,049,607
<pre><code>df['hour'] = df.index.hour df[(df['hour'] &lt; 16) | (df['hour'] &gt; 17)] </code></pre>
-1
2016-10-14T18:13:21Z
[ "python", "pandas", "numpy" ]
Exclude between time in pandas
40,049,456
<p>I know that you can select data from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow">pandas.DatetimeIndex</a> using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow">pandas.DataFrame.between_time<...
1
2016-10-14T18:04:23Z
40,050,882
<p>You can combine <code>between_time</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a>:</p> <pre><code>df2 = df.drop(df.between_time("16:00", "17:00").index) </code></pre>
2
2016-10-14T19:43:14Z
[ "python", "pandas", "numpy" ]
How do you combine two split data back into original (numpy)
40,049,504
<p>I have a data named <code>Total</code> and I split it into features and labels as below. Later I split them into training and test data. </p> <pre><code>Total_X = Total[:,:-1] Total_y = Total[:,-1] Train_X , Test_X , Train_y, Test_y = train_test_split(Total_X,Total_y,test_size = .3) </code></pre> <p>Now I want to...
-2
2016-10-14T18:06:34Z
40,053,782
<p>Are you sure you wanted to divide them in the first place?</p> <pre><code>test_len = np.floor(len(Total) * 0.3) test_xy, train_xy = Total[:test_len], Total[test_len:] </code></pre> <p>And then if you need them, you can extract <code>test_x = test_xy[:,:-1]</code> etc</p>
0
2016-10-15T00:30:19Z
[ "python", "numpy" ]
Pygame not responding to variable updates
40,049,513
<p>I'm trying to build a program that will change each individual pixel within a Pygame surface to a random colour. </p> <p>For a fixed and constant surface size (eg. 1300 x 700) this works and the whole surface is filled with random colours, however I'm trying to resize the surface with the pygame.RESIZABLE feature o...
1
2016-10-14T18:07:15Z
40,049,654
<p>When the window resize event fires, you need to call <code>pygame.display.set_mode((w, h))</code> again to allocate a new surface of that size. Otherwise you're still writing to the original 1300x700 Surface instance.</p>
0
2016-10-14T18:16:50Z
[ "python", "python-3.x", "pygame" ]
Pygame not responding to variable updates
40,049,513
<p>I'm trying to build a program that will change each individual pixel within a Pygame surface to a random colour. </p> <p>For a fixed and constant surface size (eg. 1300 x 700) this works and the whole surface is filled with random colours, however I'm trying to resize the surface with the pygame.RESIZABLE feature o...
1
2016-10-14T18:07:15Z
40,052,550
<p>There are actually two problems with the code that cause the error. The first is not having the</p> <p><code>Window = pygame.display.set_mode((Comp_X, Comp_Y), pygame.RESIZABLE)</code> </p> <p>line inside of the <code>if event.type == 16:</code> as already mentioned.</p> <p>The other problem is very minor but cau...
1
2016-10-14T21:53:38Z
[ "python", "python-3.x", "pygame" ]
mapping the names of groups in a data-frame in pandas
40,049,523
<p>I have a dataframe </p> <pre><code>df=pd.DataFrame({'name':['a','b','c','a','b','a'],'value':\ [1,2,3,4,5,6],'value2':[7,8,9,10,11,12]}) </code></pre> <p>I want to map the columns name to a new list for example:['G','H','F'], so I would get:</p> <pre><code>df=pd.DataFrame({'name':['G','H','F','G','H','G'],'val...
1
2016-10-14T18:08:10Z
40,049,620
<p>Make a dict:</p> <pre><code>mapping = {'a':'G', 'b':'H', 'c':'F'} </code></pre> <p>Then:</p> <pre><code>df['name'] = [mapping[item] for item in df['name']] </code></pre>
0
2016-10-14T18:14:21Z
[ "python", "pandas" ]
mapping the names of groups in a data-frame in pandas
40,049,523
<p>I have a dataframe </p> <pre><code>df=pd.DataFrame({'name':['a','b','c','a','b','a'],'value':\ [1,2,3,4,5,6],'value2':[7,8,9,10,11,12]}) </code></pre> <p>I want to map the columns name to a new list for example:['G','H','F'], so I would get:</p> <pre><code>df=pd.DataFrame({'name':['G','H','F','G','H','G'],'val...
1
2016-10-14T18:08:10Z
40,049,628
<p>Use the built-in <code>pandas</code> method:</p> <pre><code>&gt;&gt;&gt; df=pd.DataFrame({'name':['a','b','c','a','b','a'],'value':\ ... [1,2,3,4,5,6],'value2':[7,8,9,10,11,12]}) &gt;&gt;&gt; df name value value2 0 a 1 7 1 b 2 8 2 c 3 9 3 a 4 10 4 b ...
2
2016-10-14T18:15:00Z
[ "python", "pandas" ]
Targeting blank spaces in string
40,049,669
<p>I'm creating a hangman-like game. Basically let's say I have a secret word, like, <em>"beauty and the beast"</em> and it's up to the user to guess the letters and ultimately the whole word.</p> <p>So far my code works fine, but if you want to check it out anyway <a href="https://paste.pound-python.org/show/VGGHZNcE...
0
2016-10-14T18:17:33Z
40,049,729
<p>I think what you want to do is change line 40 to the following:</p> <pre><code>if letter in good_guesses or letter == ' ': </code></pre> <p>Alternately, you can tack on characters to <code>good_guesses</code>:</p> <pre><code>if letter in good_guesses + ' ': </code></pre> <p>This allows you to add other character...
1
2016-10-14T18:21:13Z
[ "python", "python-3.x" ]
Targeting blank spaces in string
40,049,669
<p>I'm creating a hangman-like game. Basically let's say I have a secret word, like, <em>"beauty and the beast"</em> and it's up to the user to guess the letters and ultimately the whole word.</p> <p>So far my code works fine, but if you want to check it out anyway <a href="https://paste.pound-python.org/show/VGGHZNcE...
0
2016-10-14T18:17:33Z
40,049,786
<p>In the logic of your code, you need to handle that case with an equality operator: <code>==</code>. So something like this would work:</p> <pre><code>for letter in secret_word: if letter in good_guesses: print(letter, end=" ") elif letter == ' ': print('/', end=" ") else: print('...
3
2016-10-14T18:24:35Z
[ "python", "python-3.x" ]
Targeting blank spaces in string
40,049,669
<p>I'm creating a hangman-like game. Basically let's say I have a secret word, like, <em>"beauty and the beast"</em> and it's up to the user to guess the letters and ultimately the whole word.</p> <p>So far my code works fine, but if you want to check it out anyway <a href="https://paste.pound-python.org/show/VGGHZNcE...
0
2016-10-14T18:17:33Z
40,049,970
<p>You can make a number of improvements to your code, mostly by using <code>str.join</code> and comprehensions.</p> <p>Here is a <code>draw</code> function that does what your original does, but with the requested changes and some other modifications:</p> <pre><code>def draw(good_guesses, bad_guesses, secret_word): ...
1
2016-10-14T18:36:47Z
[ "python", "python-3.x" ]
Pandas - operations on groups using transform
40,049,802
<p>Here is my example:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({'A A': ['one', 'one', 'two', 'two', 'one'] , 'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] , 'C': ['12/15/2011', '11/11/2001', '08/30/2015', '07/3/1999','03/03/2000' ], 'D':...
3
2016-10-14T18:25:53Z
40,050,941
<p>For type consistency with subsequent operations your can do with the results of a <code>transform</code> call, that function tries to cast the resulting Series into the dtype of the selected data it works against. The function source code has this dtype cast explicitly done.</p> <p>Your boolean data can be turned i...
2
2016-10-14T19:47:40Z
[ "python", "pandas", "transform" ]
Python urllib is not extracting reader comments from a website
40,049,808
<p>I am trying to extract reader comments from the following page with the code shown below. But the output html <em>test.html</em> does not contain any comments from the page. How do I get this information with Python? </p> <p><a href="http://www.theglobeandmail.com/opinion/it-doesnt-matter-who-won-the-debate-america...
1
2016-10-14T18:26:26Z
40,053,988
<p>The comments are retrieved using an ajax requests which you can mimic:</p> <p><a href="https://i.stack.imgur.com/fqp4Y.png" rel="nofollow"><img src="https://i.stack.imgur.com/fqp4Y.png" alt="enter image description here"></a></p> <p>You can see there are numerous parameters but what is below is enough to get a res...
0
2016-10-15T01:12:33Z
[ "python", "web-scraping", "urllib" ]
change an object variable from other object(delegation)
40,049,830
<p>I am using python to implement something like following. </p> <p>sample1.py</p> <pre><code>Class D: def __ini__(self): return def disconnect(self): ## I want to change isConnected in A, but I can not do something like A.isConnected = False here. I want to use delegation. return ...
-1
2016-10-14T18:28:06Z
40,050,315
<p>I'm unclear on your objective. Sounds like you want to edit a variable before it is created. </p> <p>If that is not the case, you should be able to change A.isConnected with the following code: </p> <p><code>A.isConnected = True</code></p>
0
2016-10-14T19:01:56Z
[ "python", "oop", "design-patterns" ]
Create new headers when writing a csv using python
40,049,952
<p>I´m web scrapping different webpages and for each webpage I´m writing each row of the csv file</p> <pre><code>import csv fieldnames=["Title", "Author", "year"] counter=1 for webpage of webpages: if counter==1: f = open('file.csv', 'wb') my_writer = csv.DictWriter(f, fieldnames) my_wr...
0
2016-10-14T18:35:40Z
40,050,258
<p>It could be something like:</p> <pre><code>def write_to_csv(file_name, records, fieldnames=None): import csv from datetime import datetime with open('/tmp/' + file_name, 'w') as csvfile: if not fieldnames: fieldnames = records[0].keys() writer = csv.DictWriter(csvfile, fiel...
1
2016-10-14T18:57:37Z
[ "python", "csv" ]
Create new headers when writing a csv using python
40,049,952
<p>I´m web scrapping different webpages and for each webpage I´m writing each row of the csv file</p> <pre><code>import csv fieldnames=["Title", "Author", "year"] counter=1 for webpage of webpages: if counter==1: f = open('file.csv', 'wb') my_writer = csv.DictWriter(f, fieldnames) my_wr...
0
2016-10-14T18:35:40Z
40,050,298
<p>Because "Author" is a variable-length list, you should serialize it in some way to fit inside a single field. For example, use a semicolon as a separator.</p> <p>Assuming you have an <code>authors</code> field with all the authors in them from your <code>webpage</code> object, you would want to change your assignme...
1
2016-10-14T19:00:53Z
[ "python", "csv" ]
Multi-threaded python (mp.Pool) server with task queue
40,050,115
<p>So, I am writing a free python task server for Autodesk Maya that holds a queue of x number of 'workers'. At any time the server can accept a 'task' and toss that task on the queue that the workers churn through.</p> <p>From the queue each worker gets a 'taskDict' which is a dictionary sent to the server that says ...
0
2016-10-14T18:46:47Z
40,063,090
<p>So here's how I did it. A very simple, pragmatic solution.</p> <p>I have a method called 'finaLocalWorker', you can see the worker class can get marked as 'busy'. If a worker isn't busy, an incoming task is sent to it.</p> <p>If all workers are busy, then an incoming task gets added to a simple list called 'self.q...
0
2016-10-15T19:04:52Z
[ "python", "multithreading", "server", "queue", "pool" ]
Generating variants over a list in Python
40,050,118
<p>Let me have a arbitrary list of positive integers:</p> <pre><code>[2, 2, 3, 5] </code></pre> <p>I need to write a code, which will generate me a list of all products of those integers, enumerated like that:</p> <pre><code>1111, ..., 1115, 1121, ..., 1125, ... 1135, 1235, 2235. </code></pre> <p>How do I do that?<...
-2
2016-10-14T18:47:04Z
40,050,187
<pre><code>import itertools itertools.product(range(1,3), range(1,3), range(1,4), range(1,6)) </code></pre> <p>Docs here: <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">https://docs.python.org/3/library/itertools.html#itertools.product</a></p> <p>A more general solution:</...
0
2016-10-14T18:52:43Z
[ "python" ]
Python - rename files incrementally based on julian day
40,050,149
<p><strong>Problem:</strong> I have a bunch of files that were downloaded from an org. Halfway through their data directory the org changed the naming convention (reasons unknown). I am looking to create a script that will take the files in a directory and rename the file the same way, but simply "go back one day". </p...
2
2016-10-14T18:49:27Z
40,089,749
<p>You can use <a href="https://docs.python.org/3.6/library/datetime.html" rel="nofollow">datetime</a> module:</p> <pre><code>#First argument - string like 2015365, second argument - format dt = datetime.datetime.strptime(year_day,'%Y%j') #Time shift dt = dt + datetime.timedelta(days=-1) #Year with shift nyear = dt.ye...
1
2016-10-17T15:00:53Z
[ "python", "glob" ]
Python - rename files incrementally based on julian day
40,050,149
<p><strong>Problem:</strong> I have a bunch of files that were downloaded from an org. Halfway through their data directory the org changed the naming convention (reasons unknown). I am looking to create a script that will take the files in a directory and rename the file the same way, but simply "go back one day". </p...
2
2016-10-14T18:49:27Z
40,095,184
<p>Based on feedback from the community I was able to get the logic needed to fix the files downloaded from the org! The logic was the biggest hurdle. It turns out that the <code>datetime</code> module can be used, I need to read up more on that. </p> <p>I combined the logic with the batch renaming using the <code>os<...
0
2016-10-17T20:33:55Z
[ "python", "glob" ]
Python Get top values in dictionary
40,050,154
<p>I have a dictionary called <code>wordCounts</code> which maps a word to how many times it occurred, how can I get the top <code>n</code> words in the dict while allowing more than <code>n</code> if there is a tie?</p>
1
2016-10-14T18:49:39Z
40,050,426
<p>As the previous answer says, you can cast as a <code>Counter</code> to make this dataset easier to deal with.</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; d = {"d":1,"c":2,"a":3,'b':3,'e':0,'f':1} &gt;&gt;&gt; c = Counter(d) &gt;&gt;&gt; c Counter({'b': 3, 'a': 3, 'c': 2, 'f': 1, 'd': 1,...
1
2016-10-14T19:09:13Z
[ "python", "dictionary" ]
Python Get top values in dictionary
40,050,154
<p>I have a dictionary called <code>wordCounts</code> which maps a word to how many times it occurred, how can I get the top <code>n</code> words in the dict while allowing more than <code>n</code> if there is a tie?</p>
1
2016-10-14T18:49:39Z
40,050,456
<p>One solution could be:</p> <pre><code>from collections import Counter, defaultdict list_of_words = ['dog', 'cat', 'moo', 'dog', 'pun', 'pun'] def get_n_most_common(n, list_of_words): ct = Counter(list_of_words) d = defaultdict(list) for word, quantity in ct.items(): d[quantity].append(word) ...
1
2016-10-14T19:11:12Z
[ "python", "dictionary" ]
Python Get top values in dictionary
40,050,154
<p>I have a dictionary called <code>wordCounts</code> which maps a word to how many times it occurred, how can I get the top <code>n</code> words in the dict while allowing more than <code>n</code> if there is a tie?</p>
1
2016-10-14T18:49:39Z
40,050,526
<p>MooingRawr is on the right track, but now we need to just get the top <code>n</code> results</p> <pre><code>l = [] for i, (word, count) in enumerate(sorted(d.items(), reverse=True, key=lambda x: x[1])): if i &gt;= n and count&lt;l[-1][1]: break l.append((word, count)) </code></pre>
1
2016-10-14T19:16:15Z
[ "python", "dictionary" ]
parse numbers from x,y,z equation
40,050,227
<p>I am parsing numbers from equation. From my code there is little problem. It does not recognize the number 1 from equation because normally in equation, number 1 is skipped. </p> <pre><code>def equationSystem(e): a = [] for s in e: a.append(re.findall("[-]?\d+[\.]?\d*[eE]?[-+]?\d*", s)) print a[0] </code></pr...
0
2016-10-14T18:55:30Z
40,051,273
<p>This should work fine:</p> <pre><code>pat = re.compile(r"(?:(?&lt;=^)|(?&lt;=[+-]))[a-z]") </code></pre> <p>Here the pattern <code>pat</code> will help substitute all the Non-Digit-Preceding characters by <code>1</code>, for eg:<br> <code>-x+y+z=0</code> becomes <code>-1+1+1=0</code> and <code>5x+y+4z=3</code> bec...
1
2016-10-14T20:10:51Z
[ "python" ]
parse numbers from x,y,z equation
40,050,227
<p>I am parsing numbers from equation. From my code there is little problem. It does not recognize the number 1 from equation because normally in equation, number 1 is skipped. </p> <pre><code>def equationSystem(e): a = [] for s in e: a.append(re.findall("[-]?\d+[\.]?\d*[eE]?[-+]?\d*", s)) print a[0] </code></pr...
0
2016-10-14T18:55:30Z
40,051,342
<p>Suppose instead you look for the known constants "xyz=" as separators, and took everything between them as regular expression groups.</p> <pre><code>import re pattern_string = '([^x]*)x([^y]*)y([^z]*)z=(.+)' pattern = re.compile(pattern_string) def parse_equation(s): results = pattern.search(s) return res...
1
2016-10-14T20:16:51Z
[ "python" ]
Is Root Algorithm
40,050,238
<p>I create a function to determine if a number was a root (not sure if this is the right term) of another number.</p> <pre><code>def isRoot(n, root): return not math.log(n, root)%1 </code></pre> <p>For the most part this works, but I've found I've had a floating point problem. For example if I do <code>isRoot(125...
2
2016-10-14T18:56:11Z
40,050,292
<p>If you don't mind the performance hit, you could look at the <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code></a> module in the standard library. It's got arbitrary-precision numbers.</p>
0
2016-10-14T19:00:36Z
[ "python", "python-2.7", "floating-point", "precision" ]
Is Root Algorithm
40,050,238
<p>I create a function to determine if a number was a root (not sure if this is the right term) of another number.</p> <pre><code>def isRoot(n, root): return not math.log(n, root)%1 </code></pre> <p>For the most part this works, but I've found I've had a floating point problem. For example if I do <code>isRoot(125...
2
2016-10-14T18:56:11Z
40,050,627
<p>You're relying on a floating point number being exactly equal to 0 (False) for your function to work. Generally speaking, you should avoid testing for equality when dealing with floating point numbers. Instead, it's better to set an acceptable tolerance level for the difference.</p> <p>Try this instead:</p> <pre><...
1
2016-10-14T19:24:47Z
[ "python", "python-2.7", "floating-point", "precision" ]
Is Root Algorithm
40,050,238
<p>I create a function to determine if a number was a root (not sure if this is the right term) of another number.</p> <pre><code>def isRoot(n, root): return not math.log(n, root)%1 </code></pre> <p>For the most part this works, but I've found I've had a floating point problem. For example if I do <code>isRoot(125...
2
2016-10-14T18:56:11Z
40,050,745
<p>How about this:</p> <pre><code>def isRoot(n, root): power = 1 while root ** power &lt; n: power += 1 return root ** power == n </code></pre> <p>If this is too slow you can also do a sort of binary search to reduce the number of checks.</p>
1
2016-10-14T19:32:48Z
[ "python", "python-2.7", "floating-point", "precision" ]
Is Root Algorithm
40,050,238
<p>I create a function to determine if a number was a root (not sure if this is the right term) of another number.</p> <pre><code>def isRoot(n, root): return not math.log(n, root)%1 </code></pre> <p>For the most part this works, but I've found I've had a floating point problem. For example if I do <code>isRoot(125...
2
2016-10-14T18:56:11Z
40,050,791
<p>The best way to avoid the problem is with a different approach that avoids floating point math entirely.</p> <pre><code>def isRoot(n, root): return n &lt;= 1 or (False if n % root != 0 else isRoot(n // root, root)) </code></pre>
2
2016-10-14T19:35:41Z
[ "python", "python-2.7", "floating-point", "precision" ]
Is Root Algorithm
40,050,238
<p>I create a function to determine if a number was a root (not sure if this is the right term) of another number.</p> <pre><code>def isRoot(n, root): return not math.log(n, root)%1 </code></pre> <p>For the most part this works, but I've found I've had a floating point problem. For example if I do <code>isRoot(125...
2
2016-10-14T18:56:11Z
40,050,833
<p>Just round to an integer and verify:</p> <pre><code>def isRoot(n, root): power = int(round(math.log(n, root))) return root ** power == n </code></pre>
0
2016-10-14T19:39:19Z
[ "python", "python-2.7", "floating-point", "precision" ]
Unblock tornado.queues.Queue.get() coroutine when on_connection_close()?
40,050,251
<p>Given a tornado handler that looks like:</p> <pre><code>class MyHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): queue = self.getQueue() # returns a tornado.queues.Queue _ = yield queue.get() self.write("whatever") def on_connection_close(self): ...
0
2016-10-14T18:57:03Z
40,062,092
<p>Use <a href="http://www.tornadoweb.org/en/stable/concurrent.html#tornado.concurrent.chain_future" rel="nofollow"><code>chain_future</code></a>. Chain <code>queue.get</code>'s future with some other future that is in your control (some kind of indicator/flag), then simply resolve flag future on close: </p> <pre><co...
1
2016-10-15T17:26:59Z
[ "python", "tornado", "coroutine" ]
do I need another .condarc for each environment
40,050,285
<p>I'm using anaconda and I needed to use <code>.condarc</code> to setup proxy settings.</p> <p>Do I need to put another <code>.condarc</code> somewhere for an environment I created? If so, where?</p>
0
2016-10-14T19:00:15Z
40,088,987
<p>You don't need a separate <code>.condarc</code> for different environments. As I can tell you are aware, that file is used to store runtime configuration information for conda. In the <a href="http://conda.pydata.org/docs/config.html#the-conda-configuration-file-condarc" rel="nofollow">docs</a>, we see that it is us...
1
2016-10-17T14:25:16Z
[ "python", "virtualenv", "anaconda", "conda" ]
Variable creation process in Python
40,050,327
<p>Doing everything in Microsoft shell and using 2.7.12</p> <h1>Prelude</h1> <pre><code>a = [1,2,3,4,5] b = [1,2,3,4,5] c = a </code></pre> <h1>Actions</h1> <pre><code>a[0] is b[0] is c[0] True </code></pre> <p>Are not the three lists pointing to the same elements in the memory location? and are therefore liable t...
0
2016-10-14T19:02:26Z
40,050,410
<p>Python can decide to share immutable objects storage (strings, integers, ...)</p> <p>Since they are immutable, it is transparent to the user. It just saves memory.</p> <pre><code>a[0] is b[0] </code></pre> <p>could be True or False. On the other hand</p> <pre><code>a[0] is c[0] </code></pre> <p>is always True b...
3
2016-10-14T19:07:50Z
[ "python", "arrays", "python-2.7" ]
Variable creation process in Python
40,050,327
<p>Doing everything in Microsoft shell and using 2.7.12</p> <h1>Prelude</h1> <pre><code>a = [1,2,3,4,5] b = [1,2,3,4,5] c = a </code></pre> <h1>Actions</h1> <pre><code>a[0] is b[0] is c[0] True </code></pre> <p>Are not the three lists pointing to the same elements in the memory location? and are therefore liable t...
0
2016-10-14T19:02:26Z
40,050,424
<p><code>int</code>s are <em>immutable</em>. This means that when you reassign <code>a[0]</code>, you're not changing whatever <code>1</code> is. Rather, you're changing whatever <code>a[0]</code> holds. You don't change what it means to be <code>1</code> - you change what it means to be <code>a[0]</code>.</p> <p>If o...
0
2016-10-14T19:09:06Z
[ "python", "arrays", "python-2.7" ]
Variable creation process in Python
40,050,327
<p>Doing everything in Microsoft shell and using 2.7.12</p> <h1>Prelude</h1> <pre><code>a = [1,2,3,4,5] b = [1,2,3,4,5] c = a </code></pre> <h1>Actions</h1> <pre><code>a[0] is b[0] is c[0] True </code></pre> <p>Are not the three lists pointing to the same elements in the memory location? and are therefore liable t...
0
2016-10-14T19:02:26Z
40,050,549
<p>Assignment in Python is by reference - it creates a new reference, or alias for an object, not copies the object - and since event <em>int</em> is an object in Python - at least (in my version - up to 256), this rule mostly works works.</p> <p>The following example wit function <em>id</em> - which shows object refe...
0
2016-10-14T19:18:12Z
[ "python", "arrays", "python-2.7" ]
Convert tuple to a string
40,050,371
<p>I know tuple to string questions were asked before but i dont really get it the way they explain it so I try to get an explanation on my example. So i need to convert the tuple points to a string to fill it in in the last line after 'got data'. This is the script:</p> <pre><code>def on_pick(self, event): print...
0
2016-10-14T19:05:12Z
40,050,479
<p>How about </p> <pre><code>myString = "got data %s, %s" % (str(xdata),str(ydata)) QtGui.QMessageBox.information(self, "Click!", myString) </code></pre> <p>or if xdata is a tuple</p> <pre><code>myString = "got data %s, %s" % (str(xdata[0]),str(xdata[1])) a = (1,2) b = "asdf %s %s" % (str(a[0]),str(a[1])) </code></...
0
2016-10-14T19:12:44Z
[ "python", "string", "tuples" ]
Convert tuple to a string
40,050,371
<p>I know tuple to string questions were asked before but i dont really get it the way they explain it so I try to get an explanation on my example. So i need to convert the tuple points to a string to fill it in in the last line after 'got data'. This is the script:</p> <pre><code>def on_pick(self, event): print...
0
2016-10-14T19:05:12Z
40,050,505
<p>if the every element data in the tuple is <code>string</code> type, than you can simply do:</p> <pre><code>" ".join(points) </code></pre> <p>where your code should something look like this:</p> <pre><code>QtGui.QMessageBox.information(self, "Click!", 'got data' + " "join(points)) </code></pre> <p>where as if the...
0
2016-10-14T19:14:52Z
[ "python", "string", "tuples" ]
Replacing numbers ending in 3 and 7 in a string
40,050,408
<p>Write a program that generates and prints a list of n elements (n informed by the user) containing the natural numbers (starting with 1) and replacing multiples of 3 by the word 'ping', multiples of 7 by the word 'pong', and multiples of 3 and 7 by the word 'ping-pong'</p> <p>Here is the code for that</p> <pre><co...
-4
2016-10-14T19:07:42Z
40,050,699
<p>I tried to make your code do what you want while doing as few modifications to it as possible.</p> <ul> <li>Do <strong>NOT</strong> use <code>eval</code>. Ever. Bad, bad, bad <code>eval</code>. To cast an string to an int, use <code>int()</code>.</li> <li>Your code was starting at 0 when it was asked that it starte...
2
2016-10-14T19:29:59Z
[ "python" ]
Redis request handling internal
40,050,422
<p>I have some confusion in redis. I am self learning redis.</p> <p>I have got to know that redis is single threaded and it works on the concept of event loop. So read/write operations are serialized in redis and there is no race condition.</p> <p>My confusion is - when I naively think about single threaded architect...
0
2016-10-14T19:08:48Z
40,050,758
<p>Your understanding of Redis internal is quite correct. There is no locking system. All operations are atomic and blocking.</p> <p>The recommendation when using Redis, is to make multiple short requests, instead of a long one. Take in account the time complexity mentioned in Redis Commands documentation when writing...
1
2016-10-14T19:33:25Z
[ "python", "redis", "nosql", "node-redis" ]
How to move multiple turtles at the same time in python?
40,050,438
<p>Hi I have an assignment which is asked to set two turtles in a race track(same size but separate track). I can able to make them move but the second one move only when the first one moved a half of the track. I'm not sure how to make the turtles move at the same time. Here is my code, please help me if you have a...
0
2016-10-14T19:09:48Z
40,052,807
<p>There are a couple of ways you can go about this.</p> <p>One approach to use the <code>screen.ontimer()</code> event (see the turtle documentation). This approach is nice as you can adjust the turtles to actual clock time and this can run within the turtle event loop so that other events can also take place (like ...
1
2016-10-14T22:21:32Z
[ "python", "turtle-graphics" ]
python django iam stack in this part of code shown below .error displayed un IndentationError: unindent does not match any outer indentation level
40,050,443
<pre><code>from __future__ import unicode_literals from django.db import models # Create your simplesite models here. class simplesite(models.Model): name=models.CharField(max_length=100) due_date=models.DateTimeField() #simplest app model class simplest(models.Model): simple_site=models.foreignkey(sim...
-3
2016-10-14T19:10:05Z
40,050,494
<p>This is a basic python syntax issue. Make sure you have not mixed spaces and tabs in your indentation.</p>
0
2016-10-14T19:14:12Z
[ "python", "django" ]
python django iam stack in this part of code shown below .error displayed un IndentationError: unindent does not match any outer indentation level
40,050,443
<pre><code>from __future__ import unicode_literals from django.db import models # Create your simplesite models here. class simplesite(models.Model): name=models.CharField(max_length=100) due_date=models.DateTimeField() #simplest app model class simplest(models.Model): simple_site=models.foreignkey(sim...
-3
2016-10-14T19:10:05Z
40,050,589
<p>You have to configure your editor to be 4 spaces by tab and not only tab, because four spaces for python is not the same that one tab.</p> <p>You have to make sure that all the code is using four spaces the code</p>
0
2016-10-14T19:21:34Z
[ "python", "django" ]
counter not inceasing in python
40,050,470
<p>I have looked at other while loops and am stuck on why this one is not working.</p> <pre><code>points = int(input('How many points: ')) while True: u_cnt, c_cnt = 0, 0 if u_cnt &lt; points or c_cnt &lt; points: if u &lt; c: c_cnt += 1 elif u &gt; c: u_cnt += 1 </code>...
0
2016-10-14T19:12:02Z
40,050,517
<p>You are resetting the counters to 0 every time you run the loop again so it may increment but it will just get rest to zero. To fix this you can move your variable declarations outside of the loop:</p> <pre><code>points = int(input('How many points: ')) u_cnt, c_cnt = 0, 0 while True: if u_cnt &lt; points or c_cn...
0
2016-10-14T19:15:43Z
[ "python", "while-loop" ]
counter not inceasing in python
40,050,470
<p>I have looked at other while loops and am stuck on why this one is not working.</p> <pre><code>points = int(input('How many points: ')) while True: u_cnt, c_cnt = 0, 0 if u_cnt &lt; points or c_cnt &lt; points: if u &lt; c: c_cnt += 1 elif u &gt; c: u_cnt += 1 </code>...
0
2016-10-14T19:12:02Z
40,050,519
<p>The code have to be right there:</p> <pre><code>points = int(input('How many points: ')) u_cnt, c_cnt = 0, 0 # asign the values before the loop while True: if u_cnt &lt; points or c_cnt &lt; points: if u &lt; c: c_cnt += 1 elif u &gt; c: u_cnt += 1 </code></pre>
1
2016-10-14T19:15:50Z
[ "python", "while-loop" ]
counter not inceasing in python
40,050,470
<p>I have looked at other while loops and am stuck on why this one is not working.</p> <pre><code>points = int(input('How many points: ')) while True: u_cnt, c_cnt = 0, 0 if u_cnt &lt; points or c_cnt &lt; points: if u &lt; c: c_cnt += 1 elif u &gt; c: u_cnt += 1 </code>...
0
2016-10-14T19:12:02Z
40,053,624
<p>Writing all this out in hopes that it helps other beginners like me. If others can explain it better than I do please comment.</p> <p>So this was a python beginner practice problem from-<br> <a href="http://openbookproject.net/pybiblio/practice/wilson/rockpaperscissors.php" rel="nofollow">http://openbookproject.ne...
0
2016-10-15T00:04:18Z
[ "python", "while-loop" ]
SymbolWarning: Failed to read symbol replacing with NaN
40,050,491
<p>I'm trying to use pandas to download historical stock data for all Stockholm Large Cap stocks. It works fine but for some stocks it doesn't. </p> <pre><code>import pandas_datareader.data as pdr import datetime import csv with open('stockholm_largecap.csv', 'rb') as f: reader = csv.reader(f) stockholmLargeC...
0
2016-10-14T19:13:52Z
40,050,771
<p>use <code>try</code> and <code>except</code></p> <pre><code>import pandas_datareader.data as pdr for symbol in ['SPY', 'holla']: try: f = pdr.DataReader(symbol, 'yahoo', "2001-01-01", "2010-01-01") print f.head(5) except: print ('did not find: '+symbol) Open High...
1
2016-10-14T19:34:39Z
[ "python", "pandas", "anaconda" ]
Find positions of transparent areas in images using PIL
40,050,540
<p>I want to fill transparent blocks in images by others images. For example: In this images we have 4 transparent blocks, witch need to fill.</p> <p>Need to find positions of the blocks and determine x,y,x2,y2 coords so i will know how to resize the thumbnail to.</p> <p><a href="https://i.stack.imgur.com/2pt93.png" ...
0
2016-10-14T19:17:17Z
40,051,961
<p>You can do that at the command-line with <strong>ImageMagick</strong>, or in Python, Perl, PHP or C/C++.</p> <p>First, extract the alpha channel:</p> <pre><code>convert input.png -alpha extract alpha.png </code></pre> <p><a href="https://i.stack.imgur.com/eD04t.png" rel="nofollow"><img src="https://i.stack.imgur....
1
2016-10-14T21:04:15Z
[ "python", "imagemagick", "python-imaging-library", "alpha", "pillow" ]
Calculate the triangular matrix of distances between NumPy array of coordinates
40,050,559
<p>I have an NumPy array of coordinates. For example purposes, I will use this</p> <pre><code>In [1]: np.random.seed(123) In [2]: coor = np.random.randint(10, size=12).reshape(-1,3) In [3]: coor Out[3]: array([[2, 2, 6], [1, 3, 9], [6, 1, 0], [1, 9, 0]]) </code></pre> <p>...
1
2016-10-14T19:18:57Z
40,050,651
<p>We can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow">SciPy's <code>pdist</code> method</a> to get those distances. So, we just need to initialize the output array and then set the upper triangular values with those distances</p> <pre><code>from sc...
1
2016-10-14T19:26:37Z
[ "python", "numpy", "matrix" ]
How do I make python to wait for a return value limited time?
40,050,578
<p>I'm calling a method which run time is undefiniable. I want to wait for it some second (for example 2 sec) and after then I want to step my program next.</p>
-2
2016-10-14T19:20:18Z
40,050,710
<p>I think this is a more suitable answer to the question: <a href="http://stackoverflow.com/questions/25027122/break-the-function-after-certain-time">break the function after certain time</a></p> <p>P.S: Could not post it as a comment due to insufficient reputation. </p>
4
2016-10-14T19:30:47Z
[ "python" ]
How do I make python to wait for a return value limited time?
40,050,578
<p>I'm calling a method which run time is undefiniable. I want to wait for it some second (for example 2 sec) and after then I want to step my program next.</p>
-2
2016-10-14T19:20:18Z
40,050,752
<p>I believe you are looking for the sleep function in the time module.</p> <p><a href="https://docs.python.org/2/library/time.html#time.sleep/%22time.sleep%22" rel="nofollow">https://docs.python.org/2/library/time.html#time.sleep</a></p>
0
2016-10-14T19:33:08Z
[ "python" ]