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
sequence
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 [Errno 2] No such file or directory: 'media/2016/10/14/image.png'</p> <p>Here's my models.py:</p> <pre><code>class UploadedImage(models.Model): uImage = models.FileField(upload_to='media/%Y/%m/%d') </code></pre> <p>forms.py:</p> <pre><code>class QuoteForm(forms.Form): name = forms.CharField(required=True) from_email = forms.EmailField(required=True) uImage = forms.FileField(required=False, help_text='5mb max.') message = forms.CharField(widget=forms.Textarea) </code></pre> <p>views.py:</p> <pre><code>def quote(request): form = QuoteForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] subject = "Quote" message = "From: " + name + "\n" + "Return Email: " + from_email + "\n" + "Subject: " + subject + "\n" + "Message: " + message newImage = UploadedImage(uImage = request.FILES['uImage']) newImage.save() msg = EmailMessage(subject, message, from_email, ['[email protected]'], reply_to=[from_email]) image_url = newImage.uImage.url msg.attach_file(image_url) try: msg.send() except BadHeaderError: return HttpResponse('Invalid header found') return HttpResponseRedirect('/thankyou') return render(request, "quote.html", {'form': form}) </code></pre>
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></pre> <p>Any hints for a simple (and fast) method for that problem? Thank you very much for your help!</p>
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> selects the first row</li> <li><code>x[0] &gt; 5</code> creates an array of boolean, checking whether an element is > 5 or not. (This is <code>[False, False, False, False, True, True, True]</code>.)</li> <li><p>When we write <code>some_array[boolean_array]</code>, we only keep the elements in <code>some_array</code> which the corresponding value in <code>boolean_array</code> is True. For instance, </p> <pre><code>&gt;&gt;&gt; numpy.array([2, 4, 6, 8])[numpy.array([True, False, False, True])] array([2, 8]) </code></pre></li> <li><p>Since we are going to select columns, the boolean array <code>x[0] &gt; 5</code> should be placed in the second axis. We select the whole first axis with <code>:</code>. Thus the final expression is <code>x[:, x[0] &gt; 5]</code>.</p></li> </ul>
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></pre> <p>Any hints for a simple (and fast) method for that problem? Thank you very much for your help!</p>
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 │ │ __init__.py │ └─templates hello.html </code></pre> <p>the url.py:</p> <pre><code>from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] </code></pre> <p>the setting.py:</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, </code></pre> <p>the hello.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;temtest&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;{{ hello }}&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>the view.py:</p> <pre><code>#coding:utf-8 from django.http import HttpResponse from django.shortcuts import render def hello(request): context = {} context['hello'] = 'yes i am' return render(request,'hello.html',context) def first_page(request): info = 'on yes' return HttpResponse(info) </code></pre> <p>when i run and type 127.0.0.1:8000 i can open it successfully, but when i type 127.0.0.1:8000/hello ,it show me this:<a href="https://i.stack.imgur.com/Id33r.png" rel="nofollow">enter image description here</a></p> <p>it seems like that the templates can`t be recognized. can somebody do me a flavor? thank you!</p>
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 directory.<br> The <code>cron</code> setup was done using the <code>gnome-schedule</code> app, so I assume nothing is wrong there. This is <code>alert.py</code>:</p> <pre><code>from kivy.base import runTouchApp from kivy.uix.label import Label from kivy.core.window import Window Window.size = (200, 100) runTouchApp(Label(text = "Test Alert!")) </code></pre> <p>The problem is that the window is not appearing. And as it seems, the script is not running at all (I've added a <code>os.mkdir</code> call, but no directories appeared). What's the problem? And how can I see the log that the script outputs to <code>stdout</code>? </p>
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-schedule"></a></p>
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></pre> <p>And I am trying to group by a time with a time frame of 10 minutes and sum the amount and create a dataframe similar to: </p> <pre><code>date | amount -----------------|------- 2016-03-04 12:00 |0.0 2016-03-04 12:10 |15.40 2016-03-04 12:20 |20.70 2016-03-04 12:30 |10.0 2016-03-04 12:40 |5.40 </code></pre> <p>I have tried to loop a datetime variable, filter the dataframe,group and sum than append to a list and create a dataframe with the list . </p> <pre><code>bar_list = [] while date_loop &lt; final_date: start_time = date_loop - datetime.timedelta(minutes=10) end_time = date_loop - datetime.timedelta(seconds=1) df_range = (df_sale .filter((df_sale.date &gt;= start_time) &amp; (df_sale.date &lt;= end_time)) .groupby() .sum('amount')) bar_list.append((date_loop,df_range.head()['sum(amount)'])) date_loop += datetime.timedelta(minutes=10) fields = ['date','amount'] df = sqlContext.createDataFrame(bar_list,fields).na.fill(0) </code></pre> <p>In a file with 214626 lines this code can take up to 20 minutes to calculate the sales of 2 months in a time frame of 10 minutes. </p> <p>Is there a more efficient way to do it?, I understand that I can share variable between workers,Can a share a list? Is appending to the list my bottle neck?</p> <p>Thank you. </p>
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 } timeAmtRDD.map(x=&gt; x._1+","+x._2+","+x._3) .map(x=&gt;x.split(",")) .map(x=&gt; (getDTClosestMin(x(1)), x(2).toFloat)) .reduceByKey(_+_) .sortByKey().toDF("date", "amount").show() Output: +----------------+------+ | date|amount| +----------------+------+ |2016-03-04 12:10| 15.4| |2016-03-04 12:20| 20.7| |2016-03-04 12:30| 10.0| |2016-03-04 12:40| 5.4| +----------------+------+ </code></pre> <p>Update what time this took.. ;)</p>
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'), ] ) y = sc.parallelize([('_guid_oX6Lu2xxHtA_T93sK6igyW5RaHH1tAsWcF0RpNx_kUQ=', 'JmJCFu3N'), ('_guid_hG88Yt5EUsqT8a06Cy380ga3XHPwaFylNyuvvqDslCw=', 'KNPQLQth'), ('_guid_YWKnKkcrg_Ej0icb07bhd-mXPjw-FcPi764RRhVrOxE=', 'KlGZj08d'), ] ) </code></pre> <p>My code :</p> <pre><code>df_x = x.toDF(['id', 'countrycode', 'postalcode']) df_y = y.toDF(['id_gigya', 'krux']) df = df_x.join(df_y, df_x.id == df_y.id_gigya, 'fullouter') </code></pre> <p>which gives :</p> <pre><code>[Row(id=u'_guid_XblBPCaB8qx9SK3D4HuAZwO-1cuBPc1GgfgNUC2PYm4=', countrycode=u'TN', postalcode=u'8160', id_gigya=None, krux=None), Row(id=None, countrycode=None, postalcode=None, id_gigya=u'_guid_oX6Lu2xxHtA_T93sK6igyW5RaHH1tAsWcF0RpNx_kUQ=', krux=u'JmJCFu3N'), Row(id=None, countrycode=None, postalcode=None, id_gigya=u'_guid_hG88Yt5EUsqT8a06Cy380ga3XHPwaFylNyuvvqDslCw=', krux=u'KNPQLQth'), Row(id=u'_guid_YWKnKkcrg_Ej0icb07bhd-mXPjw-FcPi764RRhVrOxE=', countrycode=u'FR', postalcode=u'75001', id_gigya=u'_guid_YWKnKkcrg_Ej0icb07bhd-mXPjw-FcPi764RRhVrOxE=', krux=u'KlGZj08d')] </code></pre> <p>It's perfect, but I want a keep a unique id, either 'id_gigya' or 'id', since it's the same id !</p> <p>With :</p> <pre><code>df_x.join(df_y, df_x.id == df_y.id_gigya, 'fullouter').drop(df_y.id_gigya).collect() Or df_x.join(df_y, df_x.id == df_y.id_gigya, 'fullouter').drop(df_x.id).collect() </code></pre> <p>I got this :</p> <pre><code>[Row(id=u'_guid_XblBPCaB8qx9SK3D4HuAZwO-1cuBPc1GgfgNUC2PYm4=', countrycode=u'TN', postalcode=u'8160', krux=None), Row(id=None, countrycode=None, postalcode=None, krux=u'JmJCFu3N'), Row(id=None, countrycode=None, postalcode=None, krux=u'KNPQLQth'), Row(id=u'_guid_YWKnKkcrg_Ej0icb07bhd-mXPjw-FcPi764RRhVrOxE=', countrycode=u'FR', postalcode=u'75001', krux=u'KlGZj08d')] [Row(countrycode=u'TN', postalcode=u'8160', id_gigya=None, krux=None), Row(countrycode=None, postalcode=None, id_gigya=u'_guid_oX6Lu2xxHtA_T93sK6igyW5RaHH1tAsWcF0RpNx_kUQ=', krux=u'JmJCFu3N'), Row(countrycode=None, postalcode=None, id_gigya=u'_guid_hG88Yt5EUsqT8a06Cy380ga3XHPwaFylNyuvvqDslCw=', krux=u'KNPQLQth'), Row(countrycode=u'FR', postalcode=u'75001', id_gigya=u'_guid_YWKnKkcrg_Ej0icb07bhd-mXPjw-FcPi764RRhVrOxE=', krux=u'KlGZj08d')] </code></pre> <p>My objectif is to have, anyway, an id by row.. Ideas ? Thx !</p>
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=x.postalcode, countrycode=x.countrycode))\ .collect() </code></pre> <p>which outputs:</p> <pre><code>[ Row(countrycode=u'TN', id=u'_guid_XblBPCaB8qx9SK3D4HuAZwO-1cuBPc1GgfgNUC2PYm4=', postalcode=u'8160'), Row(countrycode=None, id=u'_guid_hG88Yt5EUsqT8a06Cy380ga3XHPwaFylNyuvvqDslCw=', postalcode=None), Row(countrycode=u'FR', id=u'_guid_YWKnKkcrg_Ej0icb07bhd-mXPjw-FcPi764RRhVrOxE=', postalcode=u'75001'), Row(countrycode=None, id=u'_guid_oX6Lu2xxHtA_T93sK6igyW5RaHH1tAsWcF0RpNx_kUQ=', postalcode=None) ] </code></pre>
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 16 0 7 16 0 8 16 0 </code></pre> <p>Now, I want to generate the rest of the column 'b' by taking the minimum of the previous row and adding two. One solution would be</p> <pre><code>for i in range(1, len(df)): df.ix[i, 'b'] = df.ix[i-1, :].min() + 2 </code></pre> <p>Resulting in the desired output</p> <pre><code> a b 0 1 1 1 1 3 2 5 3 3 2 5 4 7 4 5 8 6 6 16 8 7 16 10 8 16 12 </code></pre> <p>Does pandas have a 'clean' way to do this? Preferably one that would vectorize the computation?</p>
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 for i in range(1, len(a)): b[i] = min(b[i-1], a[i-1]) + 2 return b df['b'] = make_b(df['a'].values) df Out[73]: a b 0 1 1 1 1 3 2 5 3 3 2 5 4 7 4 5 8 6 6 16 8 7 16 10 8 16 12 </code></pre>
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--rating them as more or less identical is important to my situation). </p> <p>However, in order to create the composite image, I need to include a "mask" that is the same size as the two images. </p> <p>I am having trouble finding an example of creating the mask online and using it for the Image.composite function. </p> <p>Here is my code: </p> <pre><code>compA = ImageOps.invert(imgA) imgAB = Image.composite(compA,imgB,??? mask) </code></pre> <p>Right now, I have created a mask of all zeros--however, the composite image does not appear correctly (both A and B are exactly the same images; a mask of all zeros--or all ones for that matter--does not work). </p> <pre><code>mask = Image.fromarray(np.zeros(imgA.size,dtype=int),mode='L') imgAB = Image.composite(compA,imgB,mask) </code></pre> <p>How does this mask work?</p> <p>How do I just add these two binary images on top of eachother? </p>
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 ) arrayDelta = arrayA - arrayB print( (arrayDelta !=0 ).sum() ) # print the number of non-identical pixels (why count them by hand?) # NB: this number may be inflated by a factor of 3 if there are 3 identical channels R, G, B imgDelta = Image.fromarray((numpy.sign(arrayDelta)*127+127).astype('uint8')) # display this image if you want to visualize where the differences are </code></pre> <p>You could do this even more simply, e.g.</p> <pre><code>print((numpy.asarray(imgA) != numpy.asarray(imgB)).sum()) </code></pre> <p>but I thought casting to a signed integer type first and then subtracting would allow you to visualize more information (A white and B black -> white pixel in delta; A black and B white -> black pixel in delta)</p>
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;userID&gt;[0-9]+)/(?P&lt;token&gt;/?$)', changepassword, name='Change Password'), </code></pre> <p>I get the following error in the terminal while trying to go to the page.</p> <blockquote> <p>Not Found: /members/ChangePassword/11/aw7MdMn4DaFoPp6W4P+c4IZWXRAF9g== [14/Oct/2016 16:53:53] "GET /members/ChangePassword/11/aw7MdMn4DaFoPp6W4P+c4IZWXRAF9g== HTTP/1.1" 404 3294</p> </blockquote> <p>Am I missing a regex or do I have the pattern wrong? I've been going through user docs and question on here and found a solution yet. It needs to accept the userID and a special token so we know that we can reset/change the password.</p>
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 so that it captures the characters in your token. Since it looks like <code>base64</code> encoding, which includes <code>[A-Z][a-z][0-9][+/=]</code>, you should be able to edit as follows:</p> <pre><code>(?P&lt;token&gt;[A-Za-z0-9+/=]+$) </code></pre>
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 F 411 80.451 91.974 95.377 1.00 0.00 C ATOM 1378 CB PHE F 411 80.968 93.339 100.842 1.00 0.00 C ATOM 1379 CG PHE F 411 81.813 93.277 102.083 1.00 0.00 C ATOM 1381 HD1 PHE F 411 83.566 92.729 105.124 1.00 0.00 H </code></pre> <p>What I want to do is to group the lines by using the values on the eighth column and then extract the corresponding values of the sixth column and find their maximum and minimum.</p> <p>Like this:</p> <pre><code>Group 1 8th column values from 95 to 100 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 F 411 80.451 91.974 95.377 1.00 0.00 C </code></pre> <p>My desired output is:</p> <pre><code>Min-80.451 Max-82.393 </code></pre> <p>Second group - from 100 to 105</p> <pre><code>Mix - 80.968 Max - 83.566 </code></pre> <p>And so on and so forth</p> <p>This is my code in python:</p> <pre><code>def get_x(file): x=[] for line in file: new_line=line.split() for z in range(80, 140, 2): if ( float(new_line[8]) &gt;z and float(new_line[8])&lt;z+2): x.append(float(new_line[6])) else: pass maxx=max(x) minx=min(x) print maxx, minx </code></pre> <p>The output I get is the minimum and the maximum of all values , like </p> <pre><code>Min- 80.451 ; Max- 83.566 </code></pre> <p>Any help is appreciated :)</p> <p>Thanks in advance</p>
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 1376 H PHE F 411 82.393 91.667 97.546 1.00 0.00 H ATOM 1377 CA PHE F 411 80.451 91.974 95.377 1.00 0.00 C ATOM 1378 CB PHE F 411 80.968 93.339 100.842 1.00 0.00 C ATOM 1379 CG PHE F 411 81.813 93.277 102.083 1.00 0.00 C ATOM 1381 HD1 PHE F 411 83.566 92.729 105.124 1.00 0.00 H """ lines = text.split('\n') data = [line.split() for line in lines] groups = [ (95, 100), (100, 105), ] for i in range(len(groups)): gMin, gMax = groups[i] results = filter(lambda x: gMin &lt;= float(x[8]) &lt; gMax, data) results = map(lambda x: float(x[6]), results) print "Group", i+1, "8th column values from", gMin, "to", gMax print "Min -", min(results) print "Max -", max(results) print "" </code></pre> <p>Here is the output:</p> <pre><code>Group 1 8th column values from 95 to 100 Min - 80.451 Max - 82.393 Group 2 8th column values from 100 to 105 Min - 80.968 Max - 81.813 </code></pre> <p>This code is inefficient because it does not remove results from previous groups. If you need the added efficiency let me know.</p>
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 my code.</p> <pre><code>class My_Compressed_Source(filebasedsource.FileBasedSource): def read_records(self, file_name, range_tracker): import tarfile import re start_offset = range_tracker.start_position() with self.open_file(file_name) as f: tar = tarfile.open(fileobj = f) for member in tar.getmembers(): f = tar.extractfile(member) content = f.read() # do some regular expression process to content </code></pre> <p>And here is my pipeline</p> <pre><code>pcoll = p | 'Read' &gt;&gt; beam.Read(My_Compressed_Source(args.input, splittable = False)) pcoll | beam.ParDo('parse tar member', Parse_Members()) p.run() </code></pre> <p>also, my input path of bucket is "--input gs://mybucket/source/*.tgz" and my job-id is "2016-10-14_09_21_43-4409773810679481086". I am wondering should I set "splittable" to True. Or if there is something wrong. </p>
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 = p | "Read" &gt;&gt; beam.io.Read(My_Compressed_Source(args.input, split = False, compression_type = fileio.CompressionTypes.GZIP)) pcoll | beam.ParDo('parse tar member', Parse_Members()) p.run() </code></pre> <p>I try to execute it locally through "DirectPipelineRunner", and tarfile.open() showed an error. So I modified my read_records function to the below version.</p> <pre><code>class My_Compressed_Source(filebasedsource.FileBasedSource): def read_records(self, file_name, range_tracker): import tarfile import re import StringIO start_offset = range_tracker.start_position() f = self.open_file(file_name) start = range_tracker.start_position text_str = str(f.read(f._read_size)) tar = tarfile.open(fileobj=StringIO.StringIO(text_str), bufsize=f._read_size) for mem in tar.getmembers(): print mem.name </code></pre> <p>I specify the number of bytes for f.read() to get the whole content of my tgz file. And now the files are just tar. <br> And then I use StringIO module to create a temporary file_obj to put in tarfile.open. Finally I used a loop to access each name of the file. I indeed extract some file name but just a few of files are accessed.<br></p> <p>After trying different data source, I think the key is no matter which the source is, the length of f._read_size is always has a maximum 16384 = 16k. I wonder If there is some where to set the maximum of buffer size can let me access whole content, or I should try another way?</p>
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 my code.</p> <pre><code>class My_Compressed_Source(filebasedsource.FileBasedSource): def read_records(self, file_name, range_tracker): import tarfile import re start_offset = range_tracker.start_position() with self.open_file(file_name) as f: tar = tarfile.open(fileobj = f) for member in tar.getmembers(): f = tar.extractfile(member) content = f.read() # do some regular expression process to content </code></pre> <p>And here is my pipeline</p> <pre><code>pcoll = p | 'Read' &gt;&gt; beam.Read(My_Compressed_Source(args.input, splittable = False)) pcoll | beam.ParDo('parse tar member', Parse_Members()) p.run() </code></pre> <p>also, my input path of bucket is "--input gs://mybucket/source/*.tgz" and my job-id is "2016-10-14_09_21_43-4409773810679481086". I am wondering should I set "splittable" to True. Or if there is something wrong. </p>
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.open_file().</p> <p>I filed <a href="https://issues.apache.org/jira/browse/BEAM-778" rel="nofollow">https://issues.apache.org/jira/browse/BEAM-778</a> for this.</p>
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 = [] list3 = [] for a,b,c in zip(x,y,z): list1.append(a) list2.append(b) list3.append(c) </code></pre> <p>I realize in the example you can initialize this lists to the correct length, in fact you can just use <code>x,y,z</code> as they are. My question is regarding a situation in which you don't necessarily know the length of the lists. In my opinion, having to use three lines to initialize this lists is clunky; what do you guys thing? Thanks for any input!</p>
-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 = [] list3 = [] for a,b,c in zip(x,y,z): list1.append(a) list2.append(b) list3.append(c) </code></pre> <p>I realize in the example you can initialize this lists to the correct length, in fact you can just use <code>x,y,z</code> as they are. My question is regarding a situation in which you don't necessarily know the length of the lists. In my opinion, having to use three lines to initialize this lists is clunky; what do you guys thing? Thanks for any input!</p>
-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 successfully.</p> <p>when I try to do the import on the python shell. I am able to successfully as below; <a href="https://i.stack.imgur.com/iWvmm.png" rel="nofollow"><img src="https://i.stack.imgur.com/iWvmm.png" alt="sc1"></a></p> <p>But when I try to run code that uses this import statement I get an import error for missing magic module as below; <a href="https://i.stack.imgur.com/jOCkB.png" rel="nofollow"><img src="https://i.stack.imgur.com/jOCkB.png" alt="sc2"></a></p> <p>If anyone knows what is happening. Please help.</p>
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 repositories, which can be installed with <code>sudo apt-get install python3-magic</code>. Modules installed for Python 2.7 are not necessarily shared with Python 3, so you may need to install both versions if you need it for 2.7 as well.</p> <p>On Ubuntu, you can run Python 3 with <code>python3</code> and access Python 3's pip installation with <code>pip3</code> to ensure that you are using the correct version.</p>
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 attribute for the graph, but that doesn't solve my problem of passing information to the graph about the node-node frequency.</p> <p>So two part question:<br> 1) What are best practices transferring an adjacency matrix into a networkX graph?<br> 2) How do I use that information to scale the size of the nodes and the weight of the edges? </p> <pre><code>## Compute Graph (G) G = nx.Graph(A) ## Add frequency of word as attribute of graph def Freq_Attribute(G, A): frequency = {} # Dictionary Declaration for node in G.nodes(): frequency[str(node)] = A[str(node)][str(node)] return nx.set_node_attributes(G, 'frequency', frequency) Freq_Attribute(g,A) # Adds attribute frequency to graph, for font scale ## Plot Graph with Labels plt.figure(1, figsize=(10,10)) # Set location of nodes as the default pos = nx.spring_layout(G, k=0.50, iterations=30) # Nodes node_size = 10000 nodes1 = nx.draw_networkx_nodes(G,pos, node_color='None', node_size=node_size, alpha=1.0) # nodelist=[0,1,2,3], nodes1.set_edgecolor('#A9C1CD') # Set edge color to black # Edges edges = nx.draw_networkx_edges(G,pos,width=1,alpha=0.05,edge_color='black') edges.set_zorder(3) # Labels nx.draw_networkx_labels(G,pos,labels=nx.get_node_attributes(G,'label'), font_size=16, font_color='#062D40', font_family='arial') # sans-serif, Font=16 # node_labels = nx.get_node_attributes(g, 'name') # Use 'g.graph' to find attribute(s): {'name': 'words'} plt.axis('off') #plt.show() </code></pre> <p>I have tried setting label font_size, but this didn't work.: font_size=nx.get_node_attributes(G,'frequency')) + 8) </p>
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.5), (1, 2, 1.0), (2, 3, 0.8), (0, 2, 0.2), (3, 4, 0.1), (2, 4, 0.6)] ## Compute Graph (G) G = create_graph_from_adj(A) plt.subplot(121) # Set location of nodes as the default spring_pose = nx.spring_layout(G, k=0.50, iterations=30) nx.draw_networkx(G,pos=spring_pose) plt.subplot(122) # Nodes default_node_size = 300 default_label_size = 12 node_size_by_freq = [] label_size_by_freq = [] for n in G.nodes(): sum_freq_in = sum([G.edge[n][t]['freq'] for t in G.neighbors(n)]) node_size_by_freq.append(sum_freq_in*default_node_size) label_size_by_freq.append(int(sum_freq_in*default_label_size)) nx.draw_networkx_nodes(G,pos=spring_pose, node_color='red', node_size=node_size_by_freq, alpha=1.0) nx.draw_networkx_labels(G,pos=spring_pose, font_size=12, #label_size_by_freq is not allowed font_color='#062D40', font_family='arial') # Edges default_width = 5.0 edge_width_by_freq = [] for e in G.edges(): edge_width_by_freq.append(G.edge[e[0]][e[1]]['freq']*default_width) nx.draw_networkx_edges(G,pos=spring_pose, width=edge_width_by_freq, alpha=1.0, edge_color='black') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/IPD3F.png" rel="nofollow"><img src="https://i.stack.imgur.com/IPD3F.png" alt="enter image description here"></a></p> <p>First of all, the adjacency reaction is not given in Matrix format, but IMHO that's too tedious. </p> <p>Secondly, <a href="https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.drawing.nx_pylab.draw_networkx_labels.html#networkx.drawing.nx_pylab.draw_networkx_labels" rel="nofollow"><code>nx.draw_networkx_labels</code></a> does not allow different font size for the labels. Can't help there. </p> <p>Last, the edge width and node size however allows that. So they are scaled based on its frequency and summation of incoming frequency, respectively. </p> <p>Hope it helps. </p>
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 a scale of greens.</p> <p>I can do this easily in Excel with conditional formatting of cells, but I can't find any help online to do this with Python either with matplotlib, seaborn, ggplot. What am I missing?</p> <p>Thank you for your time.</p>
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>):</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.axes_grid1 as axes_grid1 import pandas as pd # make a random DataFrame np.random.seed(1) arr = np.random.choice(['Absent', 'Unknown']+list(range(10)), size=(5,7)) df = pd.DataFrame(arr) # find the largest and smallest finite values finite_values = pd.to_numeric(list(set(np.unique(df.values)) .difference(['Absent', 'Unknown']))) vmin, vmax = finite_values.min(), finite_values.max() # change Absent and Unknown to numeric values df2 = df.replace({'Absent': vmax+1, 'Unknown': vmin-1}) # make sure the values are numeric for col in df2: df2[col] = pd.to_numeric(df2[col]) fig, ax = plt.subplots() cmap_custom = plt.get_cmap('Greens') cmap_custom.set_under('red') cmap_custom.set_over('black') im = plt.imshow(df2, interpolation='nearest', cmap = cmap_custom, vmin=vmin, vmax=vmax) # add a colorbar (http://stackoverflow.com/a/18195921/190597) divider = axes_grid1.make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(im, cax=cax, extend='both') plt.show() </code></pre> <hr> <p>The DataFrame</p> <pre><code>In [117]: df Out[117]: 0 1 2 3 4 5 6 0 3 9 6 7 9 3 Absent 1 Absent Unknown 5 4 7 0 2 2 3 0 2 9 8 0 2 3 5 5 7 Unknown 5 Absent 4 4 7 7 5 4 7 Unknown Absent </code></pre> <p>becomes</p> <p><a href="https://i.stack.imgur.com/9mReF.png" rel="nofollow"><img src="https://i.stack.imgur.com/9mReF.png" alt="enter image description here"></a></p>
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 you would check for existence with something like this, which returns <code>False</code>:</p> <pre><code>obj = None if obj: print(True) else: print(False) </code></pre> <p>Here's my minimum reproducible example:</p> <pre><code>&gt;&gt;&gt; class Dog: def __init__(self, name, age): self.name = name self.age = age def add_years(self, years): self.age += years self.has_aged = True def do_something_if_has_aged(self): if self.has_aged: print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") &gt;&gt;&gt; dog = Dog('Spot', 3) &gt;&gt;&gt; dog.age 3 &gt;&gt;&gt; dog.do_something_if_has_aged() Traceback (most recent call last): File "&lt;pyshell#193&gt;", line 1, in &lt;module&gt; dog.do_something_if_has_aged() File "&lt;pyshell#190&gt;", line 9, in do_something_if_has_aged if not self.has_aged: AttributeError: 'Dog' object has no attribute 'has_aged' &gt;&gt;&gt; dog.add_years(1) &gt;&gt;&gt; dog.age 4 &gt;&gt;&gt; dog.do_something_if_has_aged() The dog hasn't aged, apparently. </code></pre> <p>Clearly the dog <em>has aged</em>, though.</p> <p>I apologize if the title doesn't reflect what I'm trying to convey below; I'm new to OOP.</p>
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;&gt;&gt; hasattr(a, 'age') True </code></pre> <p>In your case, you can modify as follows:</p> <pre><code>def do_something_if_has_aged(self): if hasattr(self, 'has_aged'): pass # do your logic </code></pre>
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 you would check for existence with something like this, which returns <code>False</code>:</p> <pre><code>obj = None if obj: print(True) else: print(False) </code></pre> <p>Here's my minimum reproducible example:</p> <pre><code>&gt;&gt;&gt; class Dog: def __init__(self, name, age): self.name = name self.age = age def add_years(self, years): self.age += years self.has_aged = True def do_something_if_has_aged(self): if self.has_aged: print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") &gt;&gt;&gt; dog = Dog('Spot', 3) &gt;&gt;&gt; dog.age 3 &gt;&gt;&gt; dog.do_something_if_has_aged() Traceback (most recent call last): File "&lt;pyshell#193&gt;", line 1, in &lt;module&gt; dog.do_something_if_has_aged() File "&lt;pyshell#190&gt;", line 9, in do_something_if_has_aged if not self.has_aged: AttributeError: 'Dog' object has no attribute 'has_aged' &gt;&gt;&gt; dog.add_years(1) &gt;&gt;&gt; dog.age 4 &gt;&gt;&gt; dog.do_something_if_has_aged() The dog hasn't aged, apparently. </code></pre> <p>Clearly the dog <em>has aged</em>, though.</p> <p>I apologize if the title doesn't reflect what I'm trying to convey below; I'm new to OOP.</p>
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 be defined (unless explicitly deleted). </code></pre> <p>Now, the rest of your class should work as written. However, if you want to see if an attribute has been defined on an object, you can write this:</p> <pre><code>class Foo(object): def set_bar(self): self.bar = True # Define the attribute bar if it is not yet defined. def is_bar_set(self): return hasattr(self, 'bar') </code></pre>
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 you would check for existence with something like this, which returns <code>False</code>:</p> <pre><code>obj = None if obj: print(True) else: print(False) </code></pre> <p>Here's my minimum reproducible example:</p> <pre><code>&gt;&gt;&gt; class Dog: def __init__(self, name, age): self.name = name self.age = age def add_years(self, years): self.age += years self.has_aged = True def do_something_if_has_aged(self): if self.has_aged: print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") &gt;&gt;&gt; dog = Dog('Spot', 3) &gt;&gt;&gt; dog.age 3 &gt;&gt;&gt; dog.do_something_if_has_aged() Traceback (most recent call last): File "&lt;pyshell#193&gt;", line 1, in &lt;module&gt; dog.do_something_if_has_aged() File "&lt;pyshell#190&gt;", line 9, in do_something_if_has_aged if not self.has_aged: AttributeError: 'Dog' object has no attribute 'has_aged' &gt;&gt;&gt; dog.add_years(1) &gt;&gt;&gt; dog.age 4 &gt;&gt;&gt; dog.do_something_if_has_aged() The dog hasn't aged, apparently. </code></pre> <p>Clearly the dog <em>has aged</em>, though.</p> <p>I apologize if the title doesn't reflect what I'm trying to convey below; I'm new to OOP.</p>
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><code>def do_something_if_has_aged(self): if self.has_aged: # instead of not self.has_aged print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") </code></pre>
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 you would check for existence with something like this, which returns <code>False</code>:</p> <pre><code>obj = None if obj: print(True) else: print(False) </code></pre> <p>Here's my minimum reproducible example:</p> <pre><code>&gt;&gt;&gt; class Dog: def __init__(self, name, age): self.name = name self.age = age def add_years(self, years): self.age += years self.has_aged = True def do_something_if_has_aged(self): if self.has_aged: print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") &gt;&gt;&gt; dog = Dog('Spot', 3) &gt;&gt;&gt; dog.age 3 &gt;&gt;&gt; dog.do_something_if_has_aged() Traceback (most recent call last): File "&lt;pyshell#193&gt;", line 1, in &lt;module&gt; dog.do_something_if_has_aged() File "&lt;pyshell#190&gt;", line 9, in do_something_if_has_aged if not self.has_aged: AttributeError: 'Dog' object has no attribute 'has_aged' &gt;&gt;&gt; dog.add_years(1) &gt;&gt;&gt; dog.age 4 &gt;&gt;&gt; dog.do_something_if_has_aged() The dog hasn't aged, apparently. </code></pre> <p>Clearly the dog <em>has aged</em>, though.</p> <p>I apologize if the title doesn't reflect what I'm trying to convey below; I'm new to OOP.</p>
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 add_years(self, years): self.age += years self.has_aged = True # sets an instance attribute def do_something_if_has_aged(self): if self.has_aged: print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") </code></pre> <p>(note that I had to invert your test, if <code>self.has_aged</code> is <em>true</em> you want to go into the first branch, not the other way around).</p> <p>Or you can set a default value for the attribute in the <code>__init__</code>:</p> <pre><code>class Dog: def __init__(self, name, age): self.name = name self.age = age self.has_aged = False def add_years(self, years): self.age += years self.has_aged = True def do_something_if_has_aged(self): if self.has_aged: print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") </code></pre> <p>You can also test if an attribute is present with the <a href="https://docs.python.org/3/library/functions.html#hasattr" rel="nofollow"><code>hasattr()</code> function</a>:</p> <pre><code>def do_something_if_has_aged(self): if hasattr(self 'has_aged') and self.has_aged: print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") </code></pre> <p>or by using the <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow"><code>getattr()</code> function</a> with a default value:</p> <pre><code>def do_something_if_has_aged(self): if not getattr(self 'has_aged', False): print("The dog has aged and is %d years closer to death" % self.years) else: print("The dog hasn't aged, apparently.") </code></pre> <p>However, testing dynamically for attributes should not be the first option you pick; having a class default is much cleaner.</p>
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/geckodriver </code></pre> <p>When I run the following Python code</p> <pre><code>from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from selenium.webdriver.common.desired_capabilities import DesiredCapabilities firefox_capabilities = DesiredCapabilities.FIREFOX firefox_capabilities['marionette'] = True firefox_capabilities['binary'] = '/Users/Conger/Documents/Firefox.app' driver = webdriver.Firefox(capabilities=firefox_capabilities) </code></pre> <p>I still get the following error</p> <pre><code>Python - testwebscrap.py:8 Traceback (most recent call last): File "/Users/Conger/Documents/Python/Crash_Course/testwebscrap.py", line 11, in &lt;module&gt; driver = webdriver.Firefox(capabilities=firefox_capabilities) File "/Users/Conger/miniconda2/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 135, in __init__ self.service.start() File "/Users/Conger/miniconda2/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 71, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. Exception AttributeError: "'Service' object has no attribute 'process'" in &lt;bound method Service.__del__ of &lt;selenium.webdriver.firefox.service.Service object at 0x1006df6d0&gt;&gt; ignored [Finished in 0.194s] </code></pre>
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 put gekodriver at the <code>/usr/bin/</code> ok,that's my answer and i have tested.</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/load models, but is it also possible to import models into scikit-learn using PMML?</p>
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 rule, because its R and Scikit-Learn implementations are just thin wrappers around the native XGBoost library. Inside a trained R XGBoost object there's a blob <code>raw</code>, which is the model in its native XGBoost representation. Save it to a file, and load in Python using the <code>xgb.Booster.load_model(fname)</code> method. </p> <p>If you know that you need to the deploy XGBoost model in Scikit-Learn, then why do you train it in R?</p>
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 containing:</p> <pre><code> from distutils.core import setup from Cython.Build import cythonize setup(name='Hello world app',ext_modules=cythonize("helloworld.pyx"),) </code></pre> <p>But I get the following error:</p> <pre><code> 'helloworld.pyx' doesn't match any files </code></pre> <p>Could you please tell me what should I do now? Where should I save these two files?</p>
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 = cythonize(["*.pyx"]), ) </code></pre> <p>Looks like cythonize accepts a list of strings, but you're providing a string.</p>
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?</p> <pre><code>class Vector2: def __init__(self, x: float, y: float): self.x = x self.y = y def Translate(self, pos: Vector2): self.x += pos.x self.y += pos.y </code></pre>
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), you should use a <em><a href="https://www.python.org/dev/peps/pep-0484/#forward-references" rel="nofollow">forward reference</a></em> to it by enclosing it in quotes:</p> <pre><code>class Vector2: # __init__ as defined def Translate(self, pos: 'Vector2'): self.x += pos.x self.y += pos.y </code></pre> <p>Python (and any checkers complying to <code>PEP 484</code>) will understand your hint and register it appropriately. Python does recognize this when <code>__annotations__</code> are accessed through <a href="https://docs.python.org/3/library/typing.html#typing.get_type_hints" rel="nofollow"><code>typing.get_type_hints</code></a>:</p> <pre><code>from typing import get_type_hints get_type_hints(Vector2(1,2).Translate) {'pos': __main__.Vector2} </code></pre>
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 'shows-view' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['shows/(\\d+)$'] </code></pre> <p>But if I try to access the page directly (<code>http://localhost/shows/3333</code>) then it works fine</p> <p>But if I do a reverse for other views like this:</p> <pre><code>print reverse("shows-default-view") </code></pre> <p>with the following declaration in the same <code>urls.py</code> file:</p> <pre><code>url(r'^shows/', views.popular, name="shows-default-view"), </code></pre> <p>then it works fine. Does anyone have any idea why?</p>
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-default-view", args=[1]) # to show show with id of 1 </code></pre> <p>In general for URL's like that, the recommendation is to have a named captured group:</p> <pre><code>url(r'^shows/(?P&lt;pk&gt;\d+)$', views.show_details, name="shows-view") </code></pre> <p>And then the call to <code>reverse</code> will be:</p> <pre><code>reverse("shows-default-view", kwargs={'pk': 1}) </code></pre> <p>To use <code>reverse</code> in a template, just put the two arguments together:</p> <pre><code>{% url 'shows-view' 1 %} </code></pre>
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 (outdir+'/temp.txt','w') as f : a = random.randint(0,9) f.write(str(a)) </code></pre> <p>This will create only one text file in the local machine.<br> Is there any way I can use the multiple instances of this program, use multiple nodes and get multiple outputs? </p> <p>I got a template for mpiexec in C program which looks like this, but I could not find any template for python program.</p> <pre><code>#PBS -N my_job #PBS -l walltime=0:10:00 #PBS -l nodes=4:ppn=12 #PBS -j oe cd $PBS_O_WORKDIR mpicc -O2 mpi-hello.c -o mpi-hello cp $PBS_O_WORKDIR/* $PFSDIR cd $PFSDIR mpiexec ./mpi-hello cp $PFSDIR/* $PBS_O_WORKDIR </code></pre> <p><strong>Note:</strong> On a single node using multiple cores I can write a bash script like this: </p> <pre><code>for i in `seq 1 10`; do python myfile.py &amp;&amp; cp temp.txt outputs/out$i.txt &amp; done </code></pre> <p>But I want to utilize different <strong>nodes</strong>.<br> <strong>Required output:</strong> outputs/out1.txt,out2.txt,out3.txt etc</p> <p>Some related links are following:<br> <a href="https://www.osc.edu/sites/osc.edu/files/documentation/Batch%20Training%20-%2020150312%20-%20OSC.pdf" rel="nofollow">https://www.osc.edu/sites/osc.edu/files/documentation/Batch%20Training%20-%2020150312%20-%20OSC.pdf</a><br> <a href="https://www.osc.edu/~kmanalo/multithreadedsubmission" rel="nofollow">https://www.osc.edu/~kmanalo/multithreadedsubmission</a> </p>
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 outdir = 'outputs' comm = MPI.COMM_WORLD rank = comm.Get_rank() if not os.path.exists(outdir): os.makedirs(outdir) with open (outdir+'/temp%s.txt' % rank,'w') as f : a = random.randint(0,9) f.write(str(a)) </code></pre> <p>and the pbs file:</p> <pre><code>#!/bin/bash ################################################################################ #PBS -N myfile.py #PBS -l nodes=7:ppn=4 #PBS -l walltime=30:30:00:00 #PBS -m bea ##PBS -M [email protected] ############################################################################### cores=$(awk 'END {print NR}' $PBS_NODEFILE) mpirun -np $cores python myfile.py </code></pre>
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 (lists how many calls you've made for that particular shop)</p> </blockquote> <p>On a Shopify support page I found a thread asking this same question, and Shopify's response was:</p> <blockquote> <p>If (you are using) the python adapter then you probably need to use the get_headers method. I'm not sure, I don't use this library.</p> </blockquote> <p>When exploring I have tried calls like the following:</p> <pre><code>shopify.ShopifyResource.get_headers().get('HTTP_X_SHOPIFY_API_CALL_LIMIT') &gt;&gt;None </code></pre>
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'</code></p>
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\x17PARMNf\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Name,Value\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\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa3\x95\x80\x82-GPS\x00BIHBcLLeeEefI\x00\x00\x00Status,TimeMS,Week,NSats,HDop,Lat,Lng,RelAlt,Alt,Spd,GCrs,VZ,T\x00\x00\xa3\x95\x80\x83\x1fIMU\x00Iffffff\x00\x00\x00\x00\x00\x00\x00\x00\x00TimeMS,GyrX,GyrY,G </code></pre> <p>I have been reading around to try and find how do I implement a code into python that will allow me to parse this data so that I can plot some of the column against each other (Mostly time).</p> <p>Some things I found that may help in doing this:</p> <p>There is a code that will allow me to convert this data into a CSV file. I know how to use the code and convert it to a CSV file and plot from there, but for a learning experience I want to be able to do this without converting it to a CSV file. Now I tried reading that code but I am clueless since I am very new to python. Here is the link to the code:</p> <pre><code>https://github.com/PX4/Firmware/blob/master/Tools/sdlog2/sdlog2_dump.py </code></pre> <p>Also, Someone posted this saying this might be the log format, but again I couldn't understand or run any code on that page.</p> <pre><code>http://dev.px4.io/advanced-ulog-file-format.html </code></pre>
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 <code>process</code> method, it's doing the following:</p> <ul> <li>Read a chunk of binary data</li> <li>Figure out if it has a valid header</li> <li>Check the message type - if it's a FORMAT message parse that. If it's a description message, parse that. </li> <li>Dump out a CSV row</li> </ul> <p>You could modify this code to essentially replace the <code>__printCSVRow</code> method with something that captures the data into a pandas dataframe (or other handy data structure) so that when the main routine is all done you can grab all the data from the dataframe and plot it.</p>
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: Apple. I need a complete list of all suffixes from the all the company names, keeping only unique suffixes in the list.</p> <p>How do I accomplish this task? </p>
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've never used pandas, so getting <code>company_names</code> might be the hard part of this.</p>
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: Apple. I need a complete list of all suffixes from the all the company names, keeping only unique suffixes in the list.</p> <p>How do I accomplish this task? </p>
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', 'Limited'], dtype=object) </code></pre> <p>or ignoring punctuation:</p> <pre><code>In [38]: import string In [39]: df.Company.str.replace('['+string.punctuation+']+','') Out[39]: 0 Google 1 Apple Inc 2 Microsoft Inc 3 ABC Inc 4 XYZ Gmbh 5 PQR Ltd 6 JKL Limited Name: Company, dtype: object In [40]: df.Company.str.replace('['+string.punctuation+']+','').str.extract(r'\s+([^\s]+$)', expand=False).dropna().unique() Out[40]: array(['Inc', 'Gmbh', 'Ltd', 'Limited'], dtype=object) </code></pre> <p>export result into Excel file:</p> <pre><code>data = df.Company.str.replace('['+string.punctuation+']+','').str.extract(r'\s+([^\s]+$)', expand=False).dropna().unique() res = pd.DataFrame(data, columns=['Comp_suffix']) res.to_excel(r'/path/to/file.xlsx', index=False) </code></pre>
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: Apple. I need a complete list of all suffixes from the all the company names, keeping only unique suffixes in the list.</p> <p>How do I accomplish this task? </p>
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). </p> <p>So you can take the suffixes from the library and use them as a dictionary to search in your data, e.g.:</p> <pre><code>import pandas as pd company_names = pd.Series(["Apple", "ABS LLC", "Animusoft Corp", "A GMBH"]) suffixes = ["llc", "corp", "abc"] # take from cleanco source code found = [any(company_names.map(lambda x: x.lower().endswith(' ' + suffix))) for suffix in suffixes] suffixes_found = [suffix for (suffix, suffix_found) in zip(suffixes, found) if suffix_found] print suffixes_found # outputs ['llc', 'corp'] </code></pre>
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: Apple. I need a complete list of all suffixes from the all the company names, keeping only unique suffixes in the list.</p> <p>How do I accomplish this task? </p>
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 unique requirement. This doesn't cover that you can have a company named like "Be Smart" and "Smart" is not a suffix but part of the name. However this takes care of the unique requirement: </p> <pre><code>company_names = ["Apple", "ABS LLC", "Animusoft Corp", "BBC Corp"] suffixes = [] for name in company_names: if len(name.split()) &gt; 1 and name.split()[-1] not in suffixes: suffixes.append(name.split()[-1]) </code></pre>
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 verify the text contained within is accurately being displayed.</p> <blockquote> <p>This is what it looks like on the user's end: <a href="https://i.stack.imgur.com/YYaB2.png" rel="nofollow">The highlighted element displays as this </a></p> </blockquote> <p>But whenever I search for "GlobalHeaderCommunitySwitcher", it spits back an error that it can't find it.</p> <p>So I try searching for the other elements in the block of code:</p> <pre><code>&lt;a href="javascript:void(0)" class="zen-trigger" aria-haspopup="true" id="globalHeaderCommunitySwitcher" title="Press space bar or Enter key to open" data-uidsfdc="51"&gt;&lt;b class="zen-selectArrow"&gt;&lt;/b&gt;PVT GBI Internal&lt;/a&gt; &lt;b class="zen-selectArrow"&gt;&lt;/b&gt; "PVT GBI Internal" </code></pre> <p>I've come up empty each time by searching by:</p> <blockquote> <p>browser.find_element_by_id("globalHeaderCommunitySwitcher") browser.find_element_by_class_name &amp; used "zen-trigger" and "zen-selectArrow" browser.find_element_by_xpath("//div[@class='zen-trigger'and text()='PVT GBI Internal']")</p> </blockquote> <p>This also results in nothing being returned.. </p> <p><strong>Essentially, how do I locate the element in the screenshot via the above code and then have the script verify that the text within that element ("PVT GBI INTERNAL") is present and correct?</strong></p>
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 select Copy</li> <li>Click either copy Selector or XPath depending on your preference</li> <li>Paste that into your selenium find_element_by_xpath() or find_element_by_css_selector() statement as appropriate.</li> </ol>
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 verify the text contained within is accurately being displayed.</p> <blockquote> <p>This is what it looks like on the user's end: <a href="https://i.stack.imgur.com/YYaB2.png" rel="nofollow">The highlighted element displays as this </a></p> </blockquote> <p>But whenever I search for "GlobalHeaderCommunitySwitcher", it spits back an error that it can't find it.</p> <p>So I try searching for the other elements in the block of code:</p> <pre><code>&lt;a href="javascript:void(0)" class="zen-trigger" aria-haspopup="true" id="globalHeaderCommunitySwitcher" title="Press space bar or Enter key to open" data-uidsfdc="51"&gt;&lt;b class="zen-selectArrow"&gt;&lt;/b&gt;PVT GBI Internal&lt;/a&gt; &lt;b class="zen-selectArrow"&gt;&lt;/b&gt; "PVT GBI Internal" </code></pre> <p>I've come up empty each time by searching by:</p> <blockquote> <p>browser.find_element_by_id("globalHeaderCommunitySwitcher") browser.find_element_by_class_name &amp; used "zen-trigger" and "zen-selectArrow" browser.find_element_by_xpath("//div[@class='zen-trigger'and text()='PVT GBI Internal']")</p> </blockquote> <p>This also results in nothing being returned.. </p> <p><strong>Essentially, how do I locate the element in the screenshot via the above code and then have the script verify that the text within that element ("PVT GBI INTERNAL") is present and correct?</strong></p>
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-trigger']//*[contains(@class="zen-selectArrow")and contains(text(),'PVT GBI Internal')] </code></pre>
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 to read like this:</p> <pre><code>vbat = [Vmax - x + y + z for x in a and y in b and z in c] </code></pre> <p>I know that I can use the map operator to make a new combined list and then use a list comprehension on the new list but it seems a little ugly and hard to read. The code that I know would work is shown below:</p> <pre><code>newlist = map(sub,map(add,b,c),a) vbat = [Vmax + x for x in newlist] </code></pre> <p>Is there a solution to this that is friendlier for the reader? Thanks in advance.</p>
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 some work with with the dequeued query self.write(response) </code></pre> <p>On the client side, I use <code>python-requests</code> to long poll it:</p> <pre><code>fetched = session.get(QueryURL) </code></pre> <p>I can make a query, the server blocks waiting on the queue until cough up a something to process and finally respond.</p> <p>This works pretty slick until... the long poll gets shutdown and restarted while the handler is blocking on the queue. When I stop the query on the client side, the handler stays happily blocked. Worse if I restart the query on the client side, I now have a second handler instance blocking on the queue. So when the queue DOES have data show up, the stale handler processes it and replies to the bitbucket, and the restarted query is now blocked indefinitely.</p> <p>Is there a pattern I can use to avoid this? I had hoped that when the client side closed, the handler would receive some sort of exception indicating that things have gone south. The queue.get() can have a timeout, but what I really want is not a timeout but a sort of "unless I close" exception.</p>
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 previous ids</li> <li>when the client connects it asks to subscribe to the queue</li> <li>when a client is disconnected, it reconnects and asks for all entries with ids greater than the last id it saw</li> <li>when your QueryHandler receives a <code>get</code> with a non-<code>None</code> id, it first serves all entries with ids greater than id, then begins waiting on the queue</li> <li>when your QueryHandler raises an exception from <code>self.write</code>, ignore it: the client is responsible for retrieving the lost entry</li> <li>keep all past entries in a list</li> <li>expire the oldest list entries after some time (hours?)</li> </ul>
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 your cards starting from the highest value: ") print() #values going from 1 (ace) to 13 (king) and suits: 1 (spades), 2 (hearts), 3 (diamonds) and 4 (clubs) value1 = int(input("1. Value: ")) suit1 = int(input("1. Suit: ")) value2 = int(input("2. Value: ")) suit2 = int(input("2. Suit: ")) value3 = int(input("3. Value: ")) suit3 = int(input("3. Suit: ")) value4 = int(input("4. Value: ")) suit4 = int(input("4. Suit: ")) value5 = int(input("5. Value: ")) suit5 = int(input("5. Suit: ")) </code></pre> <p>I am using <code>if</code> statements to evaluate poker hands and determine their <a href="http://www.cardplayer.com/rules-of-poker/hand-rankings" rel="nofollow">ranking</a>. For me it seems the easiest way. An example of an evaluation would be:</p> <pre><code>#Evaluating the hand and comparing the cards c = [value1, value2, value3, value4, value5] #four of a kind if c[0] == c[1] == c[2] == c[3] != c[4] or c[0] == c[1] == c[2] == c[4] != c[3] or c[0] == c[1] == c[3] == c[4] != c[2] or c[0] == c[2] == c[3] == c[4] != c[1] or c[1] == c[2] == c[3] == c[4] != c[0]: print("You have Four Of A Kind!") #three of a kind #two pairs #one pair #highest card </code></pre> <p>This code checks if 1 of 5 combinations is true. It is inefficient and time-consuming. And as I want to code further the options of "three of a kind", "two pairs" and "one pair", the combinations get bigger. Is there a way to shorten the <code>if</code> statement?</p>
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>function checkPairs(){ card = hand[0]; pairs=1; for (i =1; i&lt;5; i++){ if(card == hand[1]){ pairs++; }else{ pairs=1; } return pairs; } </code></pre> <p>or for a flush</p> <pre><code>card = hand[0]; return_value ="flush"; if(card = 10) return_value ="royal_flush"; for (i =1; i&lt;5; i++){ if((hand[1] - card) !=1){ return false; } return return_value; </code></pre>
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 your cards starting from the highest value: ") print() #values going from 1 (ace) to 13 (king) and suits: 1 (spades), 2 (hearts), 3 (diamonds) and 4 (clubs) value1 = int(input("1. Value: ")) suit1 = int(input("1. Suit: ")) value2 = int(input("2. Value: ")) suit2 = int(input("2. Suit: ")) value3 = int(input("3. Value: ")) suit3 = int(input("3. Suit: ")) value4 = int(input("4. Value: ")) suit4 = int(input("4. Suit: ")) value5 = int(input("5. Value: ")) suit5 = int(input("5. Suit: ")) </code></pre> <p>I am using <code>if</code> statements to evaluate poker hands and determine their <a href="http://www.cardplayer.com/rules-of-poker/hand-rankings" rel="nofollow">ranking</a>. For me it seems the easiest way. An example of an evaluation would be:</p> <pre><code>#Evaluating the hand and comparing the cards c = [value1, value2, value3, value4, value5] #four of a kind if c[0] == c[1] == c[2] == c[3] != c[4] or c[0] == c[1] == c[2] == c[4] != c[3] or c[0] == c[1] == c[3] == c[4] != c[2] or c[0] == c[2] == c[3] == c[4] != c[1] or c[1] == c[2] == c[3] == c[4] != c[0]: print("You have Four Of A Kind!") #three of a kind #two pairs #one pair #highest card </code></pre> <p>This code checks if 1 of 5 combinations is true. It is inefficient and time-consuming. And as I want to code further the options of "three of a kind", "two pairs" and "one pair", the combinations get bigger. Is there a way to shorten the <code>if</code> statement?</p>
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 which you could exclude from your pre-built list and use a "fall back" check when nothing else matches.</p> <p>Check out this website <a href="http://people.math.sfu.ca/~alspach/comp18/" rel="nofollow">http://people.math.sfu.ca/~alspach/comp18/</a></p>
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 your cards starting from the highest value: ") print() #values going from 1 (ace) to 13 (king) and suits: 1 (spades), 2 (hearts), 3 (diamonds) and 4 (clubs) value1 = int(input("1. Value: ")) suit1 = int(input("1. Suit: ")) value2 = int(input("2. Value: ")) suit2 = int(input("2. Suit: ")) value3 = int(input("3. Value: ")) suit3 = int(input("3. Suit: ")) value4 = int(input("4. Value: ")) suit4 = int(input("4. Suit: ")) value5 = int(input("5. Value: ")) suit5 = int(input("5. Suit: ")) </code></pre> <p>I am using <code>if</code> statements to evaluate poker hands and determine their <a href="http://www.cardplayer.com/rules-of-poker/hand-rankings" rel="nofollow">ranking</a>. For me it seems the easiest way. An example of an evaluation would be:</p> <pre><code>#Evaluating the hand and comparing the cards c = [value1, value2, value3, value4, value5] #four of a kind if c[0] == c[1] == c[2] == c[3] != c[4] or c[0] == c[1] == c[2] == c[4] != c[3] or c[0] == c[1] == c[3] == c[4] != c[2] or c[0] == c[2] == c[3] == c[4] != c[1] or c[1] == c[2] == c[3] == c[4] != c[0]: print("You have Four Of A Kind!") #three of a kind #two pairs #one pair #highest card </code></pre> <p>This code checks if 1 of 5 combinations is true. It is inefficient and time-consuming. And as I want to code further the options of "three of a kind", "two pairs" and "one pair", the combinations get bigger. Is there a way to shorten the <code>if</code> statement?</p>
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, '10' : 9, '9' : 8, '8' : 7, '7' : 6, '6' : 5, '5' : 4, '4' : 3, '3' : 2, '2' : 1} card_suits = {'spades' : u'♤', 'diamonds' : u'♦', 'clubs': u'♧', 'hearts' : u'♥'} def __init__(self, suit, name): self.name = name self.value = self.card_values[name] if suit in self.card_suits.keys(): self.suit = suit def __lt__(self, other): return self.value &lt; other.value def __gt__(self, other): return self.value &gt; other.value def __eq__(self, other): return (self.value == other.value) and (self.suit == other.suit) def __str__(self): return self.__repr__() def __repr__(self): return u"{" + unicode(self.name, "utf-8") + u" " + self.card_suits[self.suit] + u"}" def get_value(self): return self.value def get_suit(self): return self.suit def get_name(self): return self.name def same_suit(self, other): return self.suit == other.suit class Hand(object): def __init__(self, card_list): assert len(card_list) == 5 self.cards = sorted(card_list) def determine_strength(self): score = self.high_card() if self.royal_flush(): print "royal_flush" score += 1000 return score elif self.straight_flush(): print "straight_flush" score += 900 return score elif self.four_of_a_kind(): print "four_of_a_kind" score += 800 return score elif self.full_house(): print "full_house" score += 700 return score elif self.flush(): print "flush" score += 600 return score elif self.straight(): print "straight" score += 500 return score elif self.three_of_kind(): print "three_of_kind" score += 400 return score elif self.two_pair(): print "two_pair" score += 300 return score elif self.one_pair(): print "one_pair" score += 200 return score print "high card" return score def flush(self): suit = self.cards[0].get_suit() return all([card.get_suit() == suit for card in self.cards]) def straight(self): start = self.cards[0].get_value() for card in self.cards[1:]: if card.get_value() == (start + 1): start = card.get_value() else: return False return True def straight_flush(self): return (self.straight() and self.flush()) def royal_flush(self): return ((self.cards[0].get_name() == '10') and self.straight_flush()) def _pair(self): count = 0 names = [card.get_name() for card in self.cards] for i in range(len(names)): if (names[0:i] + names[i+1:]).count(names[i]) == 1: count += 1 return count def one_pair(self): return self._pair() == 2 def two_pair(self): if self.three_of_kind(): return False return self._pair() == 4 def _of_a_kind(self): count = {} names = [card.get_name() for card in self.cards] for name in names: if name not in count: count[name] = 1 else: count[name] += 1 return max(count.values()) def three_of_kind(self): return self._of_a_kind() == 3 def four_of_a_kind(self): return self._of_a_kind() == 4 def full_house(self): return (self.one_pair() and self.three_of_kind()) def high_card(self): return max([card.get_value() for card in self.cards]) def __str__(self): return self.__repr__() def __repr__(self): return u'&lt;&gt;'.join([repr(card) for card in self.cards]).encode('utf-8') def run_hand(h): H = Hand(h) print H print H.determine_strength() rand_hand = [] while len(rand_hand) &lt; 5: c = Card(random.choice(Card.card_suits.keys()), random.choice(Card.card_values.keys())) if c not in rand_hand: rand_hand.append(c) rf = [Card('hearts', 'ace'), Card('hearts', 'king'), Card('hearts', 'queen'), Card('hearts', 'jack'), Card('hearts', '10')] sf = [Card('spades', '9'), Card('spades', '8'), Card('spades', '7'), Card('spades', '6'), Card('spades', '5')] foak = [Card('spades', 'ace'), Card('hearts', 'ace'), Card('clubs', 'ace'), Card('diamonds', 'ace'), Card('spades', '5')] fh = [Card('spades', 'ace'), Card('hearts', 'ace'), Card('clubs', 'ace'), Card('diamonds', 'king'), Card('spades', 'king')] f = [Card('spades', 'ace'), Card('spades', '10'), Card('spades', '2'), Card('spades', '5'), Card('spades', '7')] s = [Card('spades', '6'), Card('spades', '5'), Card('clubs', '4'), Card('diamonds', '3'), Card('hearts', '2')] toak = [Card('spades', 'ace'), Card('diamonds', 'ace'), Card('clubs', 'ace'), Card('diamonds', 'king'), Card('spades', '10')] tp = [Card('spades', 'ace'), Card('diamonds', 'ace'), Card('clubs', 'king'), Card('diamonds', 'king'), Card('spades', '10')] op = [Card('spades', 'ace'), Card('diamonds', 'ace'), Card('clubs', '9'), Card('diamonds', 'king'), Card('spades', '10')] hc = [Card('spades', 'ace'), Card('diamonds', '10'), Card('clubs', '9'), Card('diamonds', 'king'), Card('spades', '5')] run_hand(rand_hand) print "-----Royal Flush-----" run_hand(rf) print "-----Straight Flush-----" run_hand(sf) print "-----Four of a Kind-----" run_hand(foak) print "-----Full House-----" run_hand(fh) print "-----Flush-----" run_hand(f) print "-----Straight-----" run_hand(s) print "-----Three of a Kind-----" run_hand(toak) print "-----Two Pairs-----" run_hand(tp) print "-----One Pair-----" run_hand(op) print "-----High Card-----" run_hand(hc) </code></pre> <p>NB: this is python2.7, I'll try to convert it to python3 for you <em>if you need</em> </p>
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 a group by.</p> <p>So, using the tips database, I want to see, for each sex/smoker, what the tip percentage is is for female smoker / all female and for female non smoker / all female (and the same thing for men)</p> <p>When I do this,</p> <pre><code>import pandas as pd df=pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/master/ch08/tips.csv", sep=',') df.groupby(['sex', 'smoker'])[['total_bill','tip']].sum() </code></pre> <p>I get the following:</p> <pre><code> total_bill tip sex smoker Female No 977.68 149.77 Yes 593.27 96.74 Male No 1919.75 302.00 Yes 1337.07 183.07 </code></pre> <p>But I am looking for something more like this</p> <pre><code> Tip Pct Female No 0.153189183 Yes 0.163062349 Male No 0.15731215 Yes 0.136918785 </code></pre> <p>Where Tip Pct = sum(tip)/sum(total_bill) for each group</p> <p>What am I doing wrong and how do I fix this? Thank you!</p> <p>I understand that this would give me tip as a percentage of total tips:</p> <pre><code>(df.groupby(['sex', 'smoker'])['tip'].sum().groupby(level = 0).transform(lambda x: x/x.sum())) </code></pre> <p>Is there a way to modify it to look at another column, i.e.</p> <pre><code>(df.groupby(['sex', 'smoker'])['tip'].sum().groupby(level = 0).transform(lambda x: x/x['total_bill'].sum())) </code></pre> <p>Thanks!</p>
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: r.tip/r.total_bill, axis = 1)) #sex smoker #Female No 0.153189 # Yes 0.163062 #Male No 0.157312 # Yes 0.136919 #dtype: float64 </code></pre>
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, ,08019 246311053,USA, ,1/11/2016,7523, ,1.50, ,11101 953217,USA, ,1/29/2016,5968, ,29.70, ,95032 270542768,USA, ,1/17/2016,7832, ,18.30, ,40503 42855400, , ,1/6/2016,0, ,50.00, , 190065824, , ,12/31/2015,0, ,120.00, , 243492296,USA, ,1/25/2016,5331, ,6.89, ,40810 102483965,US , ,12/31/2015,5814, ,25.00, ,19341 </code></pre> <p>I want to look at the last column, and do a histogram, so, I did (df is the pandas df)</p> <pre><code>df = df[df[LAST_COLUMN].apply(lambda x: x.isnumeric())] </code></pre> <p>This way I cleaned up the elements that are not numeric (which I checked and worked).</p> <p>However, when I do a df.hist(), I get histograms only for columns 0,4 and 6, not for column 8 (LAST_COLUMN). It looks like some element is not numeric, but I checked and they all are numeric.</p> <p>Why is that?</p>
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: """Events are channel specific commands without arguments that are deactivated if they are triggered once.""" def __init__(self, trigger, channel, callback): self.trigger = trigger self.callback = callback self.channel = channel </code></pre> <p>The first thing I get when I try to run it is this traceback.</p> <pre><code>Traceback (most recent call last): File "bot.py", line 1, in &lt;module&gt; from twisted.words.protocols import irc ImportError: cannot import name 'irc' </code></pre> <p>However, I've installed both Twisted and IRC through pip, and this is only happening to me (other people can run the code without any problem)</p> <pre><code>~/Desktop/TriviaBot/triviabot(branch:develop*) » pip list kuro@Horus -lxc (0.1) aiohttp (0.21.6) appdirs (1.4.0) Beaker (1.8.0) beautifulsoup4 (4.5.1) Brlapi (0.6.5) bs4 (0.0.1) cffi (1.7.0) chardet (2.3.0) clipboard (0.0.4) Cython (0.24.1) decorator (4.0.10) discord.py (0.11.0) flake8 (2.5.4) flake8-docstrings (0.2.6) Flask (0.10.1) i3-py (0.6.4) inflect (0.2.5) irc (15.0.3) itsdangerous (0.24) jaraco.classes (1.4) jaraco.collections (1.5) jaraco.functools (1.15.1) jaraco.itertools (2.0) jaraco.logging (1.5) jaraco.stream (1.1.1) jaraco.text (1.8) Jinja2 (2.8) kazam (1.4.5) Kivy (1.9.1) Kivy-Garden (0.1.4) libusb1 (1.5.0) livestreamer (1.12.2) louis (3.0.0) Mako (1.0.4) MarkupSafe (0.23) mccabe (0.4.0) more-itertools (2.2) notify2 (0.3) numpy (1.11.2) packaging (16.7) pep257 (0.7.0) pep8 (1.7.0) Pillow (3.4.1) pip (8.1.2) Pmw (2.0.1) praw (3.5.0) py2exe (0.9.2.2) PyAutoGUI (0.9.33) pycparser (2.14) pyflakes (1.0.0) pygame (1.9.2b8) Pygments (2.1.3) pygobject (3.22.0) PyInstaller (3.2) PyMsgBox (1.0.3) PyNaCl (1.0.1) pyparsing (2.1.10) pyperclip (1.5.27) PyScreeze (0.1.8) pyserial (3.1.1) python-distutils-extra (2.39) python-sane (2.8.2) python-steamcontroller (1.0) python-xlib (0.17) PyTweening (1.0.3) pytz (2016.7) pyusb (1.0.0) pyxdg (0.25) requests (2.10.0) setproctitle (1.1.10) setuptools (28.3.0) six (1.10.0) tempora (1.6.1) Twisted (16.4.1) udemy-dl (0.1.8) update-checker (0.11) urllib3 (1.18) websockets (3.1) Werkzeug (0.11.10) wget (3.2) xerox (0.4.1) zope.interface (4.3.2) </code></pre> <p>This is what I'm trying to import. <a href="https://twistedmatrix.com/documents/15.4.0/api/twisted.words.protocols.irc.html" rel="nofollow">https://twistedmatrix.com/documents/15.4.0/api/twisted.words.protocols.irc.html</a></p> <p>It's using the right version of python. I'm not sure what could be happening.</p>
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 = [] flag = 0 while flag == 0: tempResult = getPart(m, d, v) for i in range(0, len(tempResult)): result.append(tempResult[i]) flag = tempResult[0] return result print getAll(5,4,1,'ds',8,'data') </code></pre> <p>I need print the result partial value, if occur a except in some step when I call tempResult in getAll</p>
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(tempResult[i]) flag = tempResult[0] except: #handle what ever errors comes here return tempResult return tempResult </code></pre> <p>Basically when you catch an error or an error is raised it will run what ever is in the except block, since we are putting <code>return tempResult</code> it will return the value. </p> <p>Like the comment says, catching all exceptions is a bad idea since you might hit an error that has nothing to do with your code and it will catch it, for specific execeptions you should do: </p> <pre><code>try: #do something except &lt;Error name like "ValueError"&gt; #handle it </code></pre> <p>You can also see more error details like:</p> <pre><code>try: #do something except ValueError as e: #handle it print(e) #prints the error </code></pre> <p>So find out what errors will cause your program to stop and put it there. </p>
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 = [] flag = 0 while flag == 0: tempResult = getPart(m, d, v) for i in range(0, len(tempResult)): result.append(tempResult[i]) flag = tempResult[0] return result print getAll(5,4,1,'ds',8,'data') </code></pre> <p>I need print the result partial value, if occur a except in some step when I call tempResult in getAll</p>
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 = getPart(m, d, v) except SomeError: # specify error type print('The partial result is', result) raise # re-raise error for i in range(0, len(tempResult)): result.append(tempResult[i]) flag = tempResult[0] return result print getAll(5,4,1,'ds',8,'data') </code></pre> <p>On another note, since you already know calling <code>getPart</code> might raise an error, you may move the <code>try/except</code> block into the function. This depends of course on what exactly you're trying to achieve.</p>
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 = [] flag = 0 while flag == 0: tempResult = getPart(m, d, v) for i in range(0, len(tempResult)): result.append(tempResult[i]) flag = tempResult[0] return result print getAll(5,4,1,'ds',8,'data') </code></pre> <p>I need print the result partial value, if occur a except in some step when I call tempResult in getAll</p>
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>WhateverError</code> is the error that is raised in your case):</p> <pre><code>def getAll(m, d, v, t, s, tn, type): result = [] flag = 0 while flag == 0: try: tempResult = getPart(m, d, v) except WhateverError: return result for i in range(0, len(tempResult)): result.append(tempResult[i]) flag = tempResult[0] return result print getAll(5,4,1,'ds',8,'data') </code></pre>
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 = [] flag = 0 while flag == 0: tempResult = getPart(m, d, v) for i in range(0, len(tempResult)): result.append(tempResult[i]) flag = tempResult[0] return result print getAll(5,4,1,'ds',8,'data') </code></pre> <p>I need print the result partial value, if occur a except in some step when I call tempResult in getAll</p>
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)): result.append(tempResult[i]) flag = tempResult[0] return result except Exception as e: print e return result </code></pre>
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 result to be the following dataframe:</p> <pre><code>df3 = spark.createDataFrame([([31, 32], "Mark", 68), ([41, 42, 43], "John", 59), `(None, "Mary", 49)],[ 'Age', 'Name', 'Weight']) </code></pre>
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), ("Mary", 49)], ['Name', \ 'Weight']) df2 = sql.createDataFrame([(31, "Mark"), (32, "Mark"), (41, "John"), (42, "John\ "), (43, "John")],[ 'Age', 'Name']) grouped = df2.groupBy(['Name']).agg(collect_list("Age").alias('age_list')) joined_df = df1.join(grouped, df1.Name == grouped.Name, 'left_outer') print(joined_df.select(grouped.age_list, df1.Name, df1.Weight).collect()) </code></pre> <p>Result</p> <pre><code>[Row(age_list=None, Name=u'Mary', Weight=49), Row(age_list=[31, 32], Name=u'Mark', Weight=68), Row(age_list=[41, 42, 43], Name=u'John', Weight=59)] </code></pre>
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_length=255) tags = models.ManyToManyField(Tag, related_name='Item_tags') price = models.CharField(max_length=255) status = models.BooleanField(default=False) </code></pre>
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 to exclude the form field "name" from it only if the <code>obj is None</code>.</p> <p>In Django 1.10 that method is in <code>django.contrib.admin.options.ModelAdmin.get_form</code>.</p> <p><strong>EDIT 1</strong> (<strong>this is by far not the best solution</strong>) I can't give you a full solution here, but you can start with something like: </p> <pre><code># admin.py from django.contrib import admin from models import Toys class ToysModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): # all the code you have in the original # django.contrib.admin.options.ModelAdmin.get_form # up to the last try except if obj is not None: defaults['fields'] = ('tags', 'price', 'status', ) try: return modelform_factory(self.model, **defaults) except FieldError as e: raise FieldError( '%s. Check fields/fieldsets/exclude attributes of class %s.' % (e, self.__class__.__name__) ) admin.site.register(Toys, ToysModelAdmin) </code></pre> <p><strong>EDIT 2</strong> (<strong>this is a better example</strong>)</p> <pre><code># admin.py from collections import OrderedDict from django.contrib import admin from models import Toys class ToysModelAdmin(admin.ModelAdmin): # this is not perfect as you'll need to keep track of your # model changes also here, but you won't accidentally add # a field that is not supposed to be editable _add_fields = ('tags', 'price', 'status', ) def get_form(self, request, obj=None, **kwargs): model_form = super(ToysModelAdmin, self).get_form( request, obj, **kwargs ) if obj is None: model_form._meta.fields = self._add_fields model_form.base_fields = OrderedDict(**[ (field, model_form.base_fields[field]) for field in self._add_fields ]) return model_form </code></pre>
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</a>. Is there a convenient way to exclude between two times in <code>pandas</code>?</p> <p>For example, to exclude data between 16:00 and 17:00, I am currently doing the following.</p> <pre><code>In [1]: import pandas as pd import numpy as np In [2]: df = pd.DataFrame(np.random.randn(24 * 60 + 1, 2), columns=list("AB"), index=pd.date_range(start="20161013 00:00:00", freq="1T", periods=24 * 60 +1)) In [3]: idx = df.index.hour == 16 In [4]: df = df[~idx] In [5]: df.between_time("16:00", "17:00") Out[5]: A B 2016-10-13 17:00:00 -0.745892 1.832912 </code></pre> <p><strong>EDIT</strong></p> <p>I have been able to use this:</p> <pre><code>In[41]:df2 = df.ix[np.setdiff1d(df.index, df.between_time("16:00", "17:00").index)] In[42]:df2.between_time("15:59", "17:01") Out[42]: A B 2016-10-13 15:59:00 1.190678 0.783776 2016-10-13 17:01:00 -0.590931 -1.059962 </code></pre> <p>Is there a better way?</p>
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</a>. Is there a convenient way to exclude between two times in <code>pandas</code>?</p> <p>For example, to exclude data between 16:00 and 17:00, I am currently doing the following.</p> <pre><code>In [1]: import pandas as pd import numpy as np In [2]: df = pd.DataFrame(np.random.randn(24 * 60 + 1, 2), columns=list("AB"), index=pd.date_range(start="20161013 00:00:00", freq="1T", periods=24 * 60 +1)) In [3]: idx = df.index.hour == 16 In [4]: df = df[~idx] In [5]: df.between_time("16:00", "17:00") Out[5]: A B 2016-10-13 17:00:00 -0.745892 1.832912 </code></pre> <p><strong>EDIT</strong></p> <p>I have been able to use this:</p> <pre><code>In[41]:df2 = df.ix[np.setdiff1d(df.index, df.between_time("16:00", "17:00").index)] In[42]:df2.between_time("15:59", "17:01") Out[42]: A B 2016-10-13 15:59:00 1.190678 0.783776 2016-10-13 17:01:00 -0.590931 -1.059962 </code></pre> <p>Is there a better way?</p>
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 combine <code>Train_X</code> and <code>Train_y</code> and create a new list which is like <code>Total</code>.</p>
-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 of Pygame on the fly (by updating the computed X and Y values that the program works from), every time the surface is resized, however, the Pygame surface only outputs randomly coloured pixels for pixels within the programs initial surface width and height (in this case 1300 x 700) and the rest of the surface is left black (the defult background colour I set), even though when I print the variables that respond to the screen height and width (and are being used to iterate through all the pixel) to the program log, they update as expected.</p> <p>I don't understand how the surface is not responding to thees updated variables and I don't know how to fix this issue.</p> <p>Any help is much appreciated and any questions about my code are welcome, thanks!</p> <pre><code>import pygame import random pygame.init() #initiates pygame Comp_X = 1300 Comp_Y = 700 Window = pygame.display.set_mode((Comp_X, Comp_Y), pygame.RESIZABLE) #defines the window size (the varible doesnt have to be called window) pygame.display.set_caption("Random Colours") #sets the title of the window clock = pygame.time.Clock() #sets the refresh rate of the program def GameLoop(): global Comp_X #computed pixles for the X axis global Comp_Y #computed pixles for the Y axis Comp_Tot = Comp_X * Comp_Y #total pixles on the screen print("initial computed total pixles = " + str(Comp_Tot)) #setting x and y position x = 0 y = 0 GameExit = False #sets the defult value of this varible to true while not GameExit: #this is effectivly a "while true" loop, unless the varible "crashed" is set to false for event in pygame.event.get(): #this for loop will listen for events print(event.type) print("X = " + str(Comp_X)) print("Y = " + str(Comp_Y)) if event.type == pygame.QUIT: # this if statement checks to see if the X in the top right of the window was pressed GameExit = True # this will break the while loop if the condition is met print("X = " + str(Comp_X)) print("Y = " + str(Comp_Y)) if event.type == 16: #event type 16 is the window resizing event Comp_X = event.dict['size'][0] Comp_Y = event.dict['size'][1] Comp_Tot = Comp_X * Comp_Y print("current computed total pixles = " + str(Comp_Tot)) #Creating the colours if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: for pixle in range (0, Comp_Tot): if x == Comp_X: print("Computed X = " + str(Comp_X)) print("Computed Y = " + str(Comp_Y)) x = 0 y += 1 pygame.draw.rect(Window, (random.randint(0,255), random.randint(0,255), random.randint(0,255)), [x, y, 2, 2])# draws a red square x += 1 #Drawing the frame pygame.display.update() #This updates the frame clock.tick(60) # this defines the FPS GameLoop() pygame.quit() # this will close the window if the "while GameLoop" loop stops running quit() </code></pre> <p><a href="https://i.stack.imgur.com/gJ7lr.jpg" rel="nofollow">Using defult height and width of 1300 x 700</a></p> <p><a href="https://i.stack.imgur.com/8pATR.jpg" rel="nofollow">Resizing surface to 1457 x 992 - not all of the surface is filled!</a></p>
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 of Pygame on the fly (by updating the computed X and Y values that the program works from), every time the surface is resized, however, the Pygame surface only outputs randomly coloured pixels for pixels within the programs initial surface width and height (in this case 1300 x 700) and the rest of the surface is left black (the defult background colour I set), even though when I print the variables that respond to the screen height and width (and are being used to iterate through all the pixel) to the program log, they update as expected.</p> <p>I don't understand how the surface is not responding to thees updated variables and I don't know how to fix this issue.</p> <p>Any help is much appreciated and any questions about my code are welcome, thanks!</p> <pre><code>import pygame import random pygame.init() #initiates pygame Comp_X = 1300 Comp_Y = 700 Window = pygame.display.set_mode((Comp_X, Comp_Y), pygame.RESIZABLE) #defines the window size (the varible doesnt have to be called window) pygame.display.set_caption("Random Colours") #sets the title of the window clock = pygame.time.Clock() #sets the refresh rate of the program def GameLoop(): global Comp_X #computed pixles for the X axis global Comp_Y #computed pixles for the Y axis Comp_Tot = Comp_X * Comp_Y #total pixles on the screen print("initial computed total pixles = " + str(Comp_Tot)) #setting x and y position x = 0 y = 0 GameExit = False #sets the defult value of this varible to true while not GameExit: #this is effectivly a "while true" loop, unless the varible "crashed" is set to false for event in pygame.event.get(): #this for loop will listen for events print(event.type) print("X = " + str(Comp_X)) print("Y = " + str(Comp_Y)) if event.type == pygame.QUIT: # this if statement checks to see if the X in the top right of the window was pressed GameExit = True # this will break the while loop if the condition is met print("X = " + str(Comp_X)) print("Y = " + str(Comp_Y)) if event.type == 16: #event type 16 is the window resizing event Comp_X = event.dict['size'][0] Comp_Y = event.dict['size'][1] Comp_Tot = Comp_X * Comp_Y print("current computed total pixles = " + str(Comp_Tot)) #Creating the colours if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: for pixle in range (0, Comp_Tot): if x == Comp_X: print("Computed X = " + str(Comp_X)) print("Computed Y = " + str(Comp_Y)) x = 0 y += 1 pygame.draw.rect(Window, (random.randint(0,255), random.randint(0,255), random.randint(0,255)), [x, y, 2, 2])# draws a red square x += 1 #Drawing the frame pygame.display.update() #This updates the frame clock.tick(60) # this defines the FPS GameLoop() pygame.quit() # this will close the window if the "while GameLoop" loop stops running quit() </code></pre> <p><a href="https://i.stack.imgur.com/gJ7lr.jpg" rel="nofollow">Using defult height and width of 1300 x 700</a></p> <p><a href="https://i.stack.imgur.com/8pATR.jpg" rel="nofollow">Resizing surface to 1457 x 992 - not all of the surface is filled!</a></p>
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 causes it to not work properly if resized after filling the screen once already and that is that you are never resetting the values of x or y back to 0 after you fill the screen.</p> <p>Fixed section of code:</p> <pre><code> if event.type == pygame.VIDEORESIZE: Comp_X = event.w Comp_Y = event.h Comp_Tot = Comp_X * Comp_Y print("current computed total pixles = " + str(Comp_Tot)) Window = pygame.display.set_mode((Comp_X, Comp_Y), pygame.RESIZABLE) #Creating the colours if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: for pixle in range (0, Comp_Tot): if x == Comp_X: #print("Computed X = " + str(Comp_X)) #print("Computed Y = " + str(Comp_Y)) x = 0 y += 1 pygame.draw.rect(Window, (random.randint(0,255), random.randint(0,255), random.randint(0,255)), [x, y, 2, 2])# draws a red square x += 1 x = 0 y = 0 </code></pre> <p>I also changed <code>event.type == 16</code> to <code>event.type == pygame.VIDEORESIZE</code>as it's more readable.</p>
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'],'value':\ [1,2,3,4,5,6],'value2':[7,8,9,10,11,12]}) </code></pre>
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'],'value':\ [1,2,3,4,5,6],'value2':[7,8,9,10,11,12]}) </code></pre>
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 5 11 5 a 6 12 &gt;&gt;&gt; df.name.map({'a':'G','b':'H','c':'F'}) 0 G 1 H 2 F 3 G 4 H 5 G Name: name, dtype: object &gt;&gt;&gt; df['name'] = df.name.map({'a':'G','b':'H','c':'F'}) &gt;&gt;&gt; df name value value2 0 G 1 7 1 H 2 8 2 F 3 9 3 G 4 10 4 H 5 11 5 G 6 12 &gt;&gt;&gt; </code></pre>
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/VGGHZNcEc2vAc5gHxOMR/" rel="nofollow">here you go</a>. Here is the relevant portion:</p> <pre><code>def draw(good_guesses, bad_guesses, secret_word): # DRAW spaces, letters &amp; strikes clear() print(secret_word) # printing strikes first print("Strikes: {}/7".format(len(bad_guesses))) print("") # printing bad guesses so far for letter in bad_guesses: print(letter, end=" ") # have a space between each element print("\n") # double blank lines # print discovered/undiscovered letters for letter in secret_word: if letter in good_guesses: print(letter, end=" ") else: print('_', end=" ") print('') </code></pre> <p>Back to our example though. For the string <em>"beauty and the beast"</em>, user will see printed out for him the following:</p> <p>"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _"</p> <p>As you can see, the spaces of the string are printed out as underscores, and that's precisely what I'd like to change.</p> <p>It would be much better if this was printed out instead:</p> <p>"_ _ _ _ _ _ / _ _ _ / _ _ _ / _ _ _ _ _"</p> <p>I'm thinking maybe there's a way to target blank spaces and print them out as spaces instead of underscores? Can't figure how to do that though.</p> <p>Thanks.</p>
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 characters, too:</p> <pre><code>if letter in good_guesses + ' -,': # Commas, spaces, and dashes are "given" to the player. </code></pre>
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/VGGHZNcEc2vAc5gHxOMR/" rel="nofollow">here you go</a>. Here is the relevant portion:</p> <pre><code>def draw(good_guesses, bad_guesses, secret_word): # DRAW spaces, letters &amp; strikes clear() print(secret_word) # printing strikes first print("Strikes: {}/7".format(len(bad_guesses))) print("") # printing bad guesses so far for letter in bad_guesses: print(letter, end=" ") # have a space between each element print("\n") # double blank lines # print discovered/undiscovered letters for letter in secret_word: if letter in good_guesses: print(letter, end=" ") else: print('_', end=" ") print('') </code></pre> <p>Back to our example though. For the string <em>"beauty and the beast"</em>, user will see printed out for him the following:</p> <p>"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _"</p> <p>As you can see, the spaces of the string are printed out as underscores, and that's precisely what I'd like to change.</p> <p>It would be much better if this was printed out instead:</p> <p>"_ _ _ _ _ _ / _ _ _ / _ _ _ / _ _ _ _ _"</p> <p>I'm thinking maybe there's a way to target blank spaces and print them out as spaces instead of underscores? Can't figure how to do that though.</p> <p>Thanks.</p>
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('_', end=" ") print('') </code></pre>
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/VGGHZNcEc2vAc5gHxOMR/" rel="nofollow">here you go</a>. Here is the relevant portion:</p> <pre><code>def draw(good_guesses, bad_guesses, secret_word): # DRAW spaces, letters &amp; strikes clear() print(secret_word) # printing strikes first print("Strikes: {}/7".format(len(bad_guesses))) print("") # printing bad guesses so far for letter in bad_guesses: print(letter, end=" ") # have a space between each element print("\n") # double blank lines # print discovered/undiscovered letters for letter in secret_word: if letter in good_guesses: print(letter, end=" ") else: print('_', end=" ") print('') </code></pre> <p>Back to our example though. For the string <em>"beauty and the beast"</em>, user will see printed out for him the following:</p> <p>"_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _"</p> <p>As you can see, the spaces of the string are printed out as underscores, and that's precisely what I'd like to change.</p> <p>It would be much better if this was printed out instead:</p> <p>"_ _ _ _ _ _ / _ _ _ / _ _ _ / _ _ _ _ _"</p> <p>I'm thinking maybe there's a way to target blank spaces and print them out as spaces instead of underscores? Can't figure how to do that though.</p> <p>Thanks.</p>
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): # DRAW spaces, letters &amp; strikes clear() print(secret_word) # printing strikes first print("Strikes: {}/7\n".format(len(bad_guesses))) # printing bad guesses so far print("{}\n".format(' '.join(bad_guesses))) # print discovered/undiscovered letters print("{}\n".format(''.join(letter if letter in good_guesses else '/' if letter == ' ' else '_' for letter in secret_word))) </code></pre> <p><code>' '.join(bad_guesses)</code> has the advantage over the original <code>for</code> loop that it does not print a trailing space.</p> <p><code>''.join(letter if letter in good_guesses else '/' if letter == ' ' else '_' for letter in secret_word)</code> joins all the elements of an iterator with the empty string. The iterator returns the letter if it was guessed correctly, <code>'/'</code> for spaces, and <code>'_'</code> for everything else.</p> <p>In both cases, pre-formatting the string makes it unnecessary to use custom line endings in <code>print</code>.</p> <p>Here is a sample output for your input string where the user guessed all the vowels:</p> <pre><code>&gt;&gt;&gt; draw('aeuy', 'io', 'beauty and the beast') beauty and the beast Strikes: 2/7 i o _eau_y/a__/__e/_ea__ </code></pre>
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':[1,7,3,4,5]}) df['C'] = pd.to_datetime(df['C']) def date_test(x): key_date = pd.Timestamp(np.datetime64('2015-08-13')) end_date = pd.Timestamp(np.datetime64('2016-10-10')) result = False for i in x.index: if key_date &lt; x[i] &lt; end_date: result = True return result def int_test(x): result = False for i in x.index: if 1 &lt; x[i] &lt; 9: result = True return result </code></pre> <p>Now I am grouping by column <code>B</code> and transforming column <code>C</code> and <code>D</code></p> <p>The following code producess column of ones. </p> <pre><code>df.groupby(['B'])['D'].transform(int_test) </code></pre> <p>And the following code produces column of dates</p> <pre><code>df.groupby(['B'])['C'].transform(date_test) </code></pre> <p>I would expect them both to produce collection of ones and zeros and not dates. My goal is to get collection of ones and zeros. Any thoughts?</p> <p><strong>Update</strong>: My main goal is to understand how <code>transform</code> works. </p>
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 into dates, thus you obtain a datetime series. Explicitly cast to <code>int</code> to get the expected type:</p> <pre><code>df.groupby(['B'])['C'].transform(date_test).astype('int64') </code></pre>
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-has-already-lost/article32314064/comments/" rel="nofollow">http://www.theglobeandmail.com/opinion/it-doesnt-matter-who-won-the-debate-america-has-already-lost/article32314064/comments/</a></p> <pre><code>from bs4 import BeautifulSoup import urllib import urllib.request import urllib.parse req =urllib.request.Request('http://www.theglobeandmail.com/opinion/it-doesnt-matter-who-won-the-debate-america-has-already-lost/article32314064/comments/') response = urllib.request.urlopen(req) the_page = response.read() soup = BeautifulSoup(the_page, 'html.parser') f = open('test.html', 'w') f.write(soup.prettify()) f.close() </code></pre> <p>Thanks! </p>
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 result, I will leave it to you to figure out how you can influence the results:</p> <pre><code>from json import loads from urllib.request import urlopen from urllib.parse import urlencode data = {"categoryID":"Production", "streamID":"32314064", "APIKey":"2_oNjjtSC8Qc250slf83cZSd4sbCzOF4cCiqGIBF8__5dWzOJY_MLAoZvds76cHeQD", "callback" :"foo",} r = urlopen("http://comments.us1.gigya.com/comments.getComments", data=urlencode(data).encode("utf-8")) json_dcts = loads(r.read().decode("utf-8"))["comments"] print(json_dcts) </code></pre> <p>That gives you a list of dicts that hold all the comments, upvotes, negvotes etc.. If you wanted to parse the key it is in the url of inside one of th scripts <code>src='https://cdns.gigya.com/js/socialize.js?apiKey=2_oNjjtSC8Qc250slf83cZSd4sbCzOF4cCiqGIBF8__5dWzOJY_MLAoZvds76cHeQD'</code>, the <em>streamID</em> is in your original url.</p>
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 </code></pre> <p>sample2.py</p> <pre><code>Class B(A): Class C(D): def _init_(self): super(B.C,self)._init_() def foo(): if self.isConnected: print "error" def __init__(self): super(C, self).__init__() </code></pre> <p>sample3.py</p> <pre><code>Class A(Object): def __init__(self): self.isConnected = False </code></pre> <p>Whenever D.disconnect() is executed, I want to change A.isConnected value. If i am not allowed to call A.isConnected = False. How can I use delegation to achieve my goal. </p> <p>It would be great if you can provide some hints or suggestions.</p> <p>Thanks </p>
-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_writer.writeheader() f.close() something where I get the information (title, author and year) for each webpage variables={ele:"NA" for ele in fieldnames} variables['Title']=title variables['Author']=author variables['year']=year with open('file.csv', 'a+b') as f: header = next(csv.reader(f)) dict_writer = csv.DictWriter(f, header) dict_writer.writerow(variables) counter+=1 </code></pre> <p>However, there could be more than one author (so author after web scrapping is actually a list) so I would like to have in the headers of the csv file: author1, author2, author3, etc. But I don't know what would be the maximum number of authors. So in the loop I would like to edit the header and start adding author2,author3 etc depending if in that row is necessary to create more authors.</p>
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, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() for row in records: writer.writerow(row) def scrap(): for webpage of webpages: webpage_data = [{'title':'','author1':'foo','author2':'bar'}] #sample data write_to_csv(webpage[0].title+'csv', webpage_data,webpage_data[0].keys()) </code></pre> <p>I`m assuming:</p> <ul> <li>Data will be consistent for the same webpage, but differ the next webpage in loop</li> <li>webpage data is a list of dictionaries, having values mapped to keys</li> <li>the above code is based on Python 3</li> </ul> <p>So in the loop, we`ll just get the data, and pass the relevant fieldnames and the values to another function, so be able to write it to csv.</p>
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_writer.writeheader() f.close() something where I get the information (title, author and year) for each webpage variables={ele:"NA" for ele in fieldnames} variables['Title']=title variables['Author']=author variables['year']=year with open('file.csv', 'a+b') as f: header = next(csv.reader(f)) dict_writer = csv.DictWriter(f, header) dict_writer.writerow(variables) counter+=1 </code></pre> <p>However, there could be more than one author (so author after web scrapping is actually a list) so I would like to have in the headers of the csv file: author1, author2, author3, etc. But I don't know what would be the maximum number of authors. So in the loop I would like to edit the header and start adding author2,author3 etc depending if in that row is necessary to create more authors.</p>
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 assignment line to something like this:</p> <pre><code>variables['Authors']=';'.join(webpage.authors) </code></pre> <p>This is a simple serialization of all of the authors. You can of course come up with something else - use a different separator or serialize to JSON or YAML or something more elaborate like that.</p> <p>Hopefully that gives some ideas.</p>
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 where the Maya file is, and what code to run when we open a headless Maya application (mayapy.exe/standalone)</p> <p>I have rewritten this many times, first using my own queue system, but then i decided to use python's. Next using a pool, using Queue.Queue, using mp.Manager.Queue and pool, etc. I have a hard time finding any examples of a simple multithreaded server that receives information and kicks off a thread, but uses a queue for when it gets too many requests.</p> <p>I just fundamentally do not understand how to place information in a queue, and have an mp.pool churn through the queue, kicking off apply_async processes that use that data and telling the queue when it's complete.</p> <p>Here's the current state of the code:</p> <pre><code>import tempfile import os import subprocess import threading import multiprocessing as mp import socket import sys from PySide import QtGui, QtCore import serverUtils selfDirectory = os.path.dirname(__file__) uiFile = selfDirectory + '/server.ui' if os.path.isfile(uiFile): form_class, base_class = serverUtils.loadUiType(uiFile) else: print('Cannot find UI file: ' + uiFile) def show(): global mayaTaskServerWindow try: mayaTaskServerWindow.close() except: pass mayaTaskServerWindow = mayaTaskServer() mayaTaskServerWindow.show() return mayaTaskServerWindow class MayaTaskServer(base_class, form_class): refreshSignal = QtCore.Signal() def __init__(self): super(MayaTaskServer, self).__init__() self.setupUi(self) self.mainJobServer = None self.mpPool = None self.manager = None self.q = None self.workerDict = {} self.refreshSignal.connect(self.refreshTree) self.startLocalCoresBTN.clicked.connect(self.startLocalCoresFn) self.killLocalCoresBTN.clicked.connect(self.killLocalCoresFn) self.jobTree.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.jobTree.customContextMenuRequested.connect(self.openMenu) self.startJobServer(6006) self.startQueue() # set the default temp folder filepath = os.path.realpath(__file__) self.localTempFolderEDT.setText(filepath.replace(filepath.split('\\')[-1], '')) ## JOB SYSTEM #################################################################### class MayaWorker(object): def __init__(self, host, port, cpuID): self.host = host self.port = port self.location = None self.cpuID = cpuID self.location = self.host self.busy = False self.task = None self.taskHistory = {} def runTask(self, task): print 'starting task - ', self.task['description'] self.busy = True serverUtils.spawnMaya(task) win.refreshSignal.emit() def taskComplete(self, arg): self.busy = False self.task = None self.mayaFile = None win.refreshSignal.emit() def bootUpLocalWorkers(self, numProcs): self.mpPool = mp.Pool(processes=numProcs) for i in range(0, numProcs): mw = self.MayaWorker('localhost', 6006, i) win.mpPool.apply_async(mw, args=(win.q)) win.workerDict['CPU_' + str(i)] = mw ## USER INTERFACE #################################################################### #UI code here you don't care about ## JOB LISTENER / SERVER / QUEUE #################################################################### class JobServer(threading.Thread): def __init__(self, port): threading.Thread.__init__(self) self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind(('localhost', port)) self.server_socket.listen(5) self.port = port self.running = True self.mpPool = None def addToQueue(self, task): #add to queue win.q.put(task, timeout=1000) #update UI wid1 = QtGui.QTreeWidgetItem() wid1.setText(0, str(task)) win.queTree.addTopLevelItem(wid1) def run(self, debug=1): print 'Starting Task Server @' + socket.gethostbyname(socket.gethostname()) + ':' + str(self.port) while self.running: client_socket, address = self.server_socket.accept() ip = str(address[0]) data = client_socket.recv(512) if 'runTask' in data: taskDict = eval(data.split(' &gt;&gt; ')[-1]) print 'SERVER&gt;&gt; Received task:', str(taskDict) self.addToQueue(taskDict) class TaskQueueServer(threading.Thread): def __init__(self): q = self.q_in while True: if self.q_in: worker = win.findLocalWorker() if worker: taskDict = self.q_in[0] worker.task = taskDict worker.startTask() self.q_in.pop[0] def startJobServer(self, port): self.mainJobServer = self.JobServer(port) self.mainJobServer.start() def startQueue(self): self.manager = mp.Manager() self.q = self.manager.Queue() if __name__ == "__main__": app = QtGui.QApplication(sys.argv) win = MayaTaskServer() win.show() sys.exit(app.exec_()) </code></pre>
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'.</p> <p>When a worker finishes a task, mpPool.apply_async has a callback that fires the taskComplete method. This method says 'if self.q, take the [0] item of the list and pop (remove) it. Else mark myself as not busy'.</p> <p>This allows for overflowing incoming requests like a batch of 500 animations to be queued up in the task list, but also the server still is able to receive no tasks for some time and immediately work on any task that comes in.</p> <p>I will put the final code up on github.</p>
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?</p>
-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:</p> <pre><code>itertools.product(*[range(1, n+1) for n in list_nums]) </code></pre>
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> <p>Here is a sample of how one file is named: <code>org2015365_res_version.asc</code></p> <p>What I need is logic to only change the year day (<code>2015365</code>) in this case to <code>2015364</code>. This logic needs to span a few years so <code>2015001</code> would be <code>2014365</code>.</p> <p>I guess I'm not sure this is possible since its not working with the current date so using a module like <code>datetime</code> does not seem applicable.</p> <p>Partial logic I came up with. I know it is rudimentary at best, but wanted to take a stab at it.</p> <pre><code># open all files all_data = glob.glob('/somedir/org*.asc') # empty array to be appended to day = [] year = [] # loop through all files for f in all_data: # get first part of string, renders org2015365 f_split = f.split('_')[0] # get only year day - renders 2015365 year_day = f_split.replace(f_split[:3], '') # get only day - renders 365 days = year_day.replace(year_day[0:4], '') # get only year - renders 2015 day.append(days) years = year_day.replace(year_day[4:], '') year.append(years) # convert to int for easier processing day = [int(i) for i in day] year = [int(i) for i in year] if day == 001 &amp; year == 2016: day = 365 year = 2015 elif day == 001 &amp; year == 2015: day = 365 year = 2014 else: day = day - 1 </code></pre> <p>Apart from the logic above I also came across the function below from <a href="http://stackoverflow.com/questions/225735/batch-renaming-of-files-in-a-directory">this</a> post, I am not sure what would be the best way to combine that with the partial logic above. Thoughts?</p> <pre><code>import glob import os def rename(dir, pattern, titlePattern): for pathAndFilename in glob.iglob(os.path.join(dir, pattern)): title, ext = os.path.splitext(os.path.basename(pathAndFilename)) os.rename(pathAndFilename, os.path.join(dir, titlePattern % title + ext)) rename(r'c:\temp\xx', r'*.doc', r'new(%s)') </code></pre> <p>Help me, stackoverflow. You're my only hope.</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.year #Day in year with shift nday = dt.timetuple().tm_yday </code></pre>
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> <p>Here is a sample of how one file is named: <code>org2015365_res_version.asc</code></p> <p>What I need is logic to only change the year day (<code>2015365</code>) in this case to <code>2015364</code>. This logic needs to span a few years so <code>2015001</code> would be <code>2014365</code>.</p> <p>I guess I'm not sure this is possible since its not working with the current date so using a module like <code>datetime</code> does not seem applicable.</p> <p>Partial logic I came up with. I know it is rudimentary at best, but wanted to take a stab at it.</p> <pre><code># open all files all_data = glob.glob('/somedir/org*.asc') # empty array to be appended to day = [] year = [] # loop through all files for f in all_data: # get first part of string, renders org2015365 f_split = f.split('_')[0] # get only year day - renders 2015365 year_day = f_split.replace(f_split[:3], '') # get only day - renders 365 days = year_day.replace(year_day[0:4], '') # get only year - renders 2015 day.append(days) years = year_day.replace(year_day[4:], '') year.append(years) # convert to int for easier processing day = [int(i) for i in day] year = [int(i) for i in year] if day == 001 &amp; year == 2016: day = 365 year = 2015 elif day == 001 &amp; year == 2015: day = 365 year = 2014 else: day = day - 1 </code></pre> <p>Apart from the logic above I also came across the function below from <a href="http://stackoverflow.com/questions/225735/batch-renaming-of-files-in-a-directory">this</a> post, I am not sure what would be the best way to combine that with the partial logic above. Thoughts?</p> <pre><code>import glob import os def rename(dir, pattern, titlePattern): for pathAndFilename in glob.iglob(os.path.join(dir, pattern)): title, ext = os.path.splitext(os.path.basename(pathAndFilename)) os.rename(pathAndFilename, os.path.join(dir, titlePattern % title + ext)) rename(r'c:\temp\xx', r'*.doc', r'new(%s)') </code></pre> <p>Help me, stackoverflow. You're my only hope.</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</code> module, I put the code below to help future users who may have a similar question!</p> <pre><code># open all files all_data = glob.glob('/some_dir/org*.asc') # loop through for f in all_data: # get first part of string, renders org2015365 f_split = f.split('_')[1] # get only year day - renders 2015365 year_day = f_split.replace(f_split[:10], '') # first argument - string 2015365, second argument - format the string to datetime dt = datetime.datetime.strptime(year_day, '%Y%j') # create a threshold where version changes its naming convention # only rename files greater than threshold threshold = '2014336' th = datetime.datetime.strptime(threshold, '%Y%j') if dt &gt; th: # Time shift - go back one day dt = dt + datetime.timedelta(days=-1) # Year with shift nyear = dt.year # Day in year with shift nday = dt.timetuple().tm_yday # rename files correctly f_output = 'org' + str(nyear) + str(nday).zfill(3) + '_res_version.asc' os.rename(f, '/some_dir/' + f_output) else: pass </code></pre>
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, 'e': 0}) </code></pre> <p><code>Counter</code> has a <code>most_common(n)</code> method that will take the <code>n</code> most common elements. Note that it will <em>exclude</em> ties. Therefore:</p> <pre><code>&gt;&gt;&gt; c.most_common(4) [('b', 3), ('a', 3), ('c', 2), ('f', 1)] </code></pre> <p>To <em>include</em> all values equal to the nth element, you can do something like the following, without converting to a <code>Counter</code>. This is pretty messy, but it should do the trick.</p> <pre><code>from collections import Counter def most_common_inclusive(freq_dict, n): # find the nth most common value nth_most_common = sorted(c.values(), reverse=True)[n-1] return { k: v for k, v in c.items() if v &gt;= nth_most_common } </code></pre> <p>You can use as follows:</p> <pre><code>&gt;&gt;&gt; d = {'b': 3, 'a': 3, 'c': 2, 'f': 1, 'd': 1, 'e': 0} &gt;&gt;&gt; most_common_inclusive(d, 4) {'d': 1, 'b': 3, 'c': 2, 'f': 1, 'a': 3} </code></pre>
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) most_common = sorted(d.keys(), reverse= True) return [(word, val) for val in most_common[:n] for word in d[val]] </code></pre> <p>And the tests:</p> <pre><code> &gt;&gt; get_n_most_common(2, list_of_words) =&gt; [('pun', 2), ('dog', 2), ('moo', 1), ('cat', 1)] &gt;&gt; get_n_most_common(1, list_of_words) =&gt; [('pun', 2), ('dog', 2)] </code></pre>
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></pre> <p>example </p> <pre><code>equation = ["-x+y+z=0", "x-3y-2z=5", "5x+y+4z=3"] </code></pre> <p>expected output</p> <pre><code>[[-1, 1, 1, 0], [1, -1, -2, 5], [5, 1, 4, 3]] </code></pre> <p>but actual output is </p> <pre><code>[[0], [-2, 5], [5,1,4,3]] </code></pre> <p>can you help me to improve the regular expression?</p>
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> becomes <code>5x+1+4z=3</code></p> <pre><code>for x in equation: s = re.sub(pat, "1", x) # substitute by "1" print (re.findall(r"[-]?\d", s)) # find digits (with signs) </code></pre> <p>this gives:</p> <pre><code>['-1', '1', '1', '0'] ['1', '-3', '-2', '5'] ['5', '1', '4', '3'] </code></pre>
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></pre> <p>example </p> <pre><code>equation = ["-x+y+z=0", "x-3y-2z=5", "5x+y+4z=3"] </code></pre> <p>expected output</p> <pre><code>[[-1, 1, 1, 0], [1, -1, -2, 5], [5, 1, 4, 3]] </code></pre> <p>but actual output is </p> <pre><code>[[0], [-2, 5], [5,1,4,3]] </code></pre> <p>can you help me to improve the regular expression?</p>
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 results.groups() samples = ["-x+y+z=0", "x-3y-2z=5", "5x+y+4z=3"] for s in samples: print parse_equation(s) </code></pre> <p>The output is</p> <pre><code>('-', '+', '+', '0') ('', '-3', '-2', '5') ('5', '+', '+4', '3') </code></pre> <p>And then you only need to worry about converting those strings to a number. For the first three, you know they cannot be zero, so they might have a different conversion function, but that's not necessary. The important thing is that if you don't find any digits in the string, then you return +/- 1.</p> <p>Since you want to handle floats and E-notation, you will need to do a tiny bit more to strip whitespace, but I will leave that up to you. For example, if you have the equation "0.5x - 36E-4y + z=0" then the space between - and 36, before the y, will throw off a simple float(s) conversion. But if you take out that space, you can do this:</p> <pre><code>def default_to_one(s): try: coefficient = float(s) return coefficient except: if -1 != s.find('-'): return -1 else: return 1 </code></pre> <p>and get the coefficients with [default_to_one(x) for x in parse_equation(s)], resulting in this output for the three cases you gave, plus an extra case "0.5x -36E-4y + z=0" to demonstrate handling all the types you intended, according to your original regexp.</p> <pre><code>[-1, 1, 1, 0.0] [1, -3.0, -2.0, 5.0] [5.0, 1, 4.0, 3.0] [0.5, -0.0036, 1, 0.0] </code></pre>
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,5)</code> I get <code>False</code>. After some troubleshooting, I found that the reason is because </p> <pre><code>&gt;&gt;&gt; math.log(125,5) 3.0000000000000004 </code></pre> <p>Even though the result should be <code>3</code>. So my question is, should I just use a different algorithm, one I'm not aware of? Or is there a way to ensure this will work correctly no matter how large of a number I use?</p>
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,5)</code> I get <code>False</code>. After some troubleshooting, I found that the reason is because </p> <pre><code>&gt;&gt;&gt; math.log(125,5) 3.0000000000000004 </code></pre> <p>Even though the result should be <code>3</code>. So my question is, should I just use a different algorithm, one I'm not aware of? Or is there a way to ensure this will work correctly no matter how large of a number I use?</p>
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><code>def isRoot(n, root, epsilon=1e-10): test = math.log(n, root)%1 return abs(test - int(round(test))) &lt; epsilon </code></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,5)</code> I get <code>False</code>. After some troubleshooting, I found that the reason is because </p> <pre><code>&gt;&gt;&gt; math.log(125,5) 3.0000000000000004 </code></pre> <p>Even though the result should be <code>3</code>. So my question is, should I just use a different algorithm, one I'm not aware of? Or is there a way to ensure this will work correctly no matter how large of a number I use?</p>
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,5)</code> I get <code>False</code>. After some troubleshooting, I found that the reason is because </p> <pre><code>&gt;&gt;&gt; math.log(125,5) 3.0000000000000004 </code></pre> <p>Even though the result should be <code>3</code>. So my question is, should I just use a different algorithm, one I'm not aware of? Or is there a way to ensure this will work correctly no matter how large of a number I use?</p>
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,5)</code> I get <code>False</code>. After some troubleshooting, I found that the reason is because </p> <pre><code>&gt;&gt;&gt; math.log(125,5) 3.0000000000000004 </code></pre> <p>Even though the result should be <code>3</code>. So my question is, should I just use a different algorithm, one I'm not aware of? Or is there a way to ensure this will work correctly no matter how large of a number I use?</p>
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): super().on_connection_close() # DO SOMETHING HERE THAT BREAKS OUT OF THE YIELD UP THERE?? </code></pre> <p>If the connection closes, I don't really want to remain blocked on the queue, to erroneously pull a value off later. Is there a mechanism I can set up to abort the the blocked <code>get()</code> method?</p>
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><code>from tornado.concurrent import Future, chain_future class MyHandler(tornado.web.RequestHandler): def initialize(self): # of course you can create that in get as well self.close_indicator = Future() @tornado.gen.coroutine def get(self): queue = self.getQueue() # returns a tornado.queues.Queue qget_future = queue.get() chain_future(self.close_indicator, qget_future) _ = yield qget_future self.write("whatever") def on_connection_close(self): super().on_connection_close() # set close indicator by resolving future # result will be copied to chained future (qget_future) self.close_indicator.set_result(None) </code></pre>
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 used in (1) the user's home directory and, if you want, (2) in the root environment where it will override the user's <code>.condarc</code> configuration details.</p> <p>The proxy server information that you have set in your home directory <code>.condarc</code> should be used in any environment you create.</p>
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 to change if one is changed?</p> <p>Part I understand:</p> <pre><code>c[0] = 8888888 a[0] 8888888 </code></pre> <p>Part I don't understand:</p> <pre><code>b[0] = 9999999 a[0] 1 </code></pre>
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 because <code>a is c</code>. (and modifying <code>a</code> changes <code>c</code>)</p> <p>But since <code>list</code> type is mutable, <code>a</code> cannot be <code>b</code> (Python doesn't allow itself to optimize storage in that case). Those are independent objects. Modifying <code>a</code> cannot change <code>b</code>.</p> <p>note about my "can be true or false" remark. Consider this in python 3.4</p> <pre><code>&gt;&gt;&gt; b=1234567890 &gt;&gt;&gt; a=[1234567890] &gt;&gt;&gt; b is a[0] False </code></pre> <p>Python did not bother to make the link between <code>b</code> and <code>a[0]</code>. Also happens with long strings (I assume that would be a performance issue vs low probability to find an exact big number 2 times in a row? whereas <code>1</code> has better chance to be repeated throughout the program)</p> <p>However if you do this you get a different result:</p> <pre><code>&gt;&gt;&gt; b=1234567890 &gt;&gt;&gt; a=[b,1,2] &gt;&gt;&gt; b is a[0] True </code></pre> <p>(I wouldn't say for sure why as it can vary depending whether it is stored as a long int or mere int, value or address, etc... , but Python has definitely more information about the value being duplicated here!)</p> <p>Conclusion is: don't rely on that for immutable objects. Use <code>==</code> at all times.</p>
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 to change if one is changed?</p> <p>Part I understand:</p> <pre><code>c[0] = 8888888 a[0] 8888888 </code></pre> <p>Part I don't understand:</p> <pre><code>b[0] = 9999999 a[0] 1 </code></pre>
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 on the other hand you did this:</p> <pre><code>L = [1,2,3] a = [L] b = [L] a.[0].append(4) </code></pre> <p>you'd see the change reflected in <code>b</code> as well</p>
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 to change if one is changed?</p> <p>Part I understand:</p> <pre><code>c[0] = 8888888 a[0] 8888888 </code></pre> <p>Part I don't understand:</p> <pre><code>b[0] = 9999999 a[0] 1 </code></pre>
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 reference - illustrates the point</p> <pre><code>In [37]: a = range(1, 6) In [38]: b = range(1, 6) In [39]: id(1) Out[39]: 4298160472 In [40]: id(a[0]) Out[40]: 4298160472 In [41]: id(a) Out[41]: 4376534696 In [42]: id(b) Out[42]: 4378531744 In [44]: c = a In [45]: id(c) Out[45]: 4376534696 </code></pre> <p>However, this will not work on floats - which is logical, since quantity of floats, and integers is infinite</p> <pre><code>In [49]: a = .1 In [50]: b = .1 In [51]: id(a) Out[51]: 4298708040 In [52]: id(b) Out[52]: 4303248152 </code></pre> <p>As you may see, new object is created for each new float, though value is the same</p>
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('On Pick!') thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind print(ind) points = tuple(zip(xdata[ind], ydata[ind])) print('onpick points:', points) QtGui.QMessageBox.information(self, "Click!", 'got data' + points) </code></pre> <p>the call is </p> <pre><code>self.canvas.mpl_connect('pick_event', self.on_pick) </code></pre> <p>and the output shoul be this as i already described it:</p> <pre><code>QtGui.QMessageBox.information(self, "Click!", 'got data' + points) </code></pre> <p>So where points is written in the last line i want to fill in the string of the tuple points. Im new to python so dont hate me :D</p>
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></pre>
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('On Pick!') thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind print(ind) points = tuple(zip(xdata[ind], ydata[ind])) print('onpick points:', points) QtGui.QMessageBox.information(self, "Click!", 'got data' + points) </code></pre> <p>the call is </p> <pre><code>self.canvas.mpl_connect('pick_event', self.on_pick) </code></pre> <p>and the output shoul be this as i already described it:</p> <pre><code>QtGui.QMessageBox.information(self, "Click!", 'got data' + points) </code></pre> <p>So where points is written in the last line i want to fill in the string of the tuple points. Im new to python so dont hate me :D</p>
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 there are <code>int</code> or <code>float</code> types than maybe map <code>str</code> or just print them one by one.</p>
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><code>result = [] number = eval(input("Enter a whole number: ")) for index in range(number): if index % 7 == 0 and index % 3 == 0: result.append("ping-pong") elif index % 3 == 0: result.append("ping") elif index % 7 == 0: result.append("pong") else: result.append(index) print(result) == 0 </code></pre> <p>Now also replaces numbers ending in 3 by the word ‘PING’ and numbers ending in 7 by the word ‘PONG’ this I am not sure how to go about doing.</p>
-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 started at 1, I changed the range.</li> <li>To know the last digit, I calculated the number modulo 10, based on the clever comment by @Renuka Deshmukh. Other less clever solutions could have been to check the end of the number casted as a string, with <code>str(index).endswith("7")</code> or <code>str(index)[-1] == "7"</code>, for example.</li> <li>What was your <code>print(result) == 0</code> trying to do? I removed the <code>==0</code>.</li> </ul> <p>Here is the resulting code:</p> <pre><code>result = [] number = int(input("Enter a whole number: ")) for index in range(1,number+1): if index % 7 == 0 and index % 3 == 0: result.append("ping-pong") elif index % 3 == 0 or index % 10 == 3: result.append("ping") elif index % 7 == 0 or index % 10 == 7: result.append("pong") else: result.append(index) print(result) </code></pre>
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 architecture, I can imagine that there is a buffer where all read/write requests gather and the thread schedules them one by one. But in a real life internet application where thousands or millions of request are to be processed, how does redis handle those requests without significant latency? If some write operation takes say few milliseconds time, does it block other read write operation during that period of time? </p> <p>Does redis implement any locking concept like relational db? If no, then how redis handles thousands of read/writes without significant latency?</p> <p>Any internals / examples would be great for my further study.</p>
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 your requests, if you work on a large number of keys or a large data structure. Avoid the KEYS command, prefer it the SCAN family of commands. Be even more careful when writing a Lua script which will be sent to Redis using the EVAL command.</p> <p>Each request having a very short execution time, the clients won't be impacted, in most of the use cases, by the fact Redis commands won't respond to any other command during the execution of a given one.</p> <p>Most of the time, the limiting factor won't be Redis itself, but the network. </p> <p>However, in some use cases, you may hit Redis limits (which are very high). In these cases, you can use <a href="http://redis.io/topics/partitioning" rel="nofollow">multiple Redis instances</a> in master-slave mode (replication, monitored by <a href="http://redis.io/topics/sentinel" rel="nofollow">Redis Sentinel</a>), and make some kind of load balacing between the instances for reading requests. You can also use a tool like <a href="https://github.com/twitter/twemproxy" rel="nofollow">twemproxy</a> in front on several Redis instances.</p>
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 any idea about it. Thank you!</p> <pre><code>import turtle import random import time wn = turtle.Screen() wn.bgcolor("lightgreen") t = turtle.Turtle() t.shape('turtle') t.color('red') t2 = turtle.Turtle() t2.shape('turtle') t2.color('blue') #user input function p = float(input('please insert the perimeter:')) #set the track def drawTrack(p,r): shortside = (p/2.0)/(r+1) longside = r*shortside turtle.setup((shortside*2)+60, longside +40) t.penup() t2.penup() t.setposition(-shortside-10, -longside/2) t2.setposition(10, -longside/2) for i in range (2): #first track t.speed(1) t.pendown() t.forward(shortside) t.left(90) t.forward(longside) t.left(90) #second track t2.speed(1) t2.pendown() t2.forward(shortside) t2.left(90) t2.forward(longside) t2.left(90) drawTrack(p,2) wn.exitonclick() </code></pre>
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 <code>exitonclick()</code>).</p> <p>The approach I used below is to break up turtle motion into tiny steps inside a Python <em>generator</em> which yields after every bit of motion. This allows us to alternate between the turtles. The race takes place before the turtle event loop so <code>exitonclick()</code> is invalid until the race is over.</p> <p>To provide a differential in speed, I've used the turtle drawing speed as part of the motion calculation so if you say <code>turtle1.speed("fast")</code> it will move fast compared to a <code>turtle2.speed("slow")</code>. There are other ways to go about this using random and/or varying speeds.</p> <p>I've changed the prompt for the perimeter to be a dialog box and made various style tweaks:</p> <pre><code>from turtle import Turtle, Screen screen = Screen() screen.bgcolor("lightgreen") turtle1 = Turtle(shape='turtle') turtle1.color('red') turtle1.speed("slow") # = 3 turtle1.penup() turtle2 = Turtle(shape='turtle') turtle2.color('blue') turtle2.speed(4) # "slow" (3) &lt; 4 &lt; "normal" (6) turtle2.penup() # user input function perimeter = screen.numinput("Track Perimeter", "Please enter the perimeter:", default=2000, minval=500, maxval=3000) def full_track_crawl(turtle, shortside, longside): speed = turtle.speed() turtle.pendown() for j in range (2): for i in range(0, int(shortside), speed): turtle.forward(speed) yield(0) turtle.left(90) for i in range(0, int(longside), speed): turtle.forward(speed) yield(0) turtle.left(90) turtle.penup() # set the track def drawTrack(perimeter, ratio): shortside = (perimeter / 2.0) / (ratio + 1) longside = ratio * shortside screen.setup(shortside * 2 + 60, longside + 40) turtle1.setposition(-shortside - 10, -longside / 2) turtle2.setposition(10, -longside / 2) generator1 = full_track_crawl(turtle1, shortside, longside) generator2 = full_track_crawl(turtle2, shortside, longside) while (next(generator1, 1) + next(generator2, 1) &lt; 2): pass drawTrack(perimeter, 2) screen.exitonclick() </code></pre> <p>Happy racing!</p>
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(simplesite) name=models.CharField(max_length=100) due_date=models.DateTimeField() </code></pre> <p>This is the error displayed when i run this command: <code>python .\manage.py makemigrations simplest</code></p> <pre><code>PS C:\django\simplesite&gt; python .\manage.py makemigrations simplest Traceback (most recent call last): File ".\manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python27\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\django\simplesite\simplest\models.py", line 9 due_date=models.DateTimeField() ^ IndentationError: unindent does not match any outer indentation level </code></pre> <p>any please help i am stack on that place .i am a beginner in python django framework</p>
-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(simplesite) name=models.CharField(max_length=100) due_date=models.DateTimeField() </code></pre> <p>This is the error displayed when i run this command: <code>python .\manage.py makemigrations simplest</code></p> <pre><code>PS C:\django\simplesite&gt; python .\manage.py makemigrations simplest Traceback (most recent call last): File ".\manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Python27\lib\site-packages\django\apps\config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\django\simplesite\simplest\models.py", line 9 due_date=models.DateTimeField() ^ IndentationError: unindent does not match any outer indentation level </code></pre> <p>any please help i am stack on that place .i am a beginner in python django framework</p>
-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></pre> <p>Is my problems having the <code>c_cnt += 1</code> inside of two if statements?</p> <p>I have put it outside of the <code>while</code> loop, yet that doesn't increase count either. I have also put the <code>u_cnt = 0</code> and <code>c_cnt = 0</code> on separate lines.</p> <p>It's not doing an infinite loop, as it should not do. It's just not incrementing.</p> <p>Thank you</p> <p>edit:</p> <pre><code>import random u_name = input('What is your name? ') points = int(input('How many points: ')) u_cnt, c_cnt = 0, 0 while True: a = ['rock', 'paper', 'scissors'] comp = random.choice(a) print('Pick from:', str(a).strip('[]')) user = input() u = a.index(user) c = a.index(comp) line_1 = '{} : {}\t{} : {}'.format(u_name, user, 'Computer', comp) line_2 = '{} : {}\t{} : {}\n'.format(u_name, u_cnt, 'Computer', c_cnt) if c_cnt &lt; points or u_cnt &lt; points: if u &gt; c or u == 0 and c == 2: u_cnt += 1 print(line_1, '\t', u_name, 'wins') print(line_2) elif u &lt; c or u == 2 and c == 0: c_cnt += 1 print(line_1, '\t', 'Computer wins') print(line_2) elif u == c: print(line_1, '\t', 'Tie') print(line_2) else: break </code></pre> <p>so when you run this the first time, you get an answer back like</p> <pre><code>What is your name? chad How many points: 3 Pick from: 'rock', 'paper', 'scissors' rock chad : rock Computer : scissors chad wins chad : 0 Computer : 0 Pick from: 'rock', 'paper', 'scissors' </code></pre> <p>how to get the count be 1, 0 on the first iteration through. that might be a better question.</p>
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_cnt &lt; points: if u &lt; c: c_cnt += 1 elif u &gt; c: u_cnt += 1 </code></pre> <p>You are also have no method to exit the loop. You need to add in a <strong>break</strong> to exit the loop. For example:</p> <pre><code>while True: if some_condition: break </code></pre>
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></pre> <p>Is my problems having the <code>c_cnt += 1</code> inside of two if statements?</p> <p>I have put it outside of the <code>while</code> loop, yet that doesn't increase count either. I have also put the <code>u_cnt = 0</code> and <code>c_cnt = 0</code> on separate lines.</p> <p>It's not doing an infinite loop, as it should not do. It's just not incrementing.</p> <p>Thank you</p> <p>edit:</p> <pre><code>import random u_name = input('What is your name? ') points = int(input('How many points: ')) u_cnt, c_cnt = 0, 0 while True: a = ['rock', 'paper', 'scissors'] comp = random.choice(a) print('Pick from:', str(a).strip('[]')) user = input() u = a.index(user) c = a.index(comp) line_1 = '{} : {}\t{} : {}'.format(u_name, user, 'Computer', comp) line_2 = '{} : {}\t{} : {}\n'.format(u_name, u_cnt, 'Computer', c_cnt) if c_cnt &lt; points or u_cnt &lt; points: if u &gt; c or u == 0 and c == 2: u_cnt += 1 print(line_1, '\t', u_name, 'wins') print(line_2) elif u &lt; c or u == 2 and c == 0: c_cnt += 1 print(line_1, '\t', 'Computer wins') print(line_2) elif u == c: print(line_1, '\t', 'Tie') print(line_2) else: break </code></pre> <p>so when you run this the first time, you get an answer back like</p> <pre><code>What is your name? chad How many points: 3 Pick from: 'rock', 'paper', 'scissors' rock chad : rock Computer : scissors chad wins chad : 0 Computer : 0 Pick from: 'rock', 'paper', 'scissors' </code></pre> <p>how to get the count be 1, 0 on the first iteration through. that might be a better question.</p>
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></pre> <p>Is my problems having the <code>c_cnt += 1</code> inside of two if statements?</p> <p>I have put it outside of the <code>while</code> loop, yet that doesn't increase count either. I have also put the <code>u_cnt = 0</code> and <code>c_cnt = 0</code> on separate lines.</p> <p>It's not doing an infinite loop, as it should not do. It's just not incrementing.</p> <p>Thank you</p> <p>edit:</p> <pre><code>import random u_name = input('What is your name? ') points = int(input('How many points: ')) u_cnt, c_cnt = 0, 0 while True: a = ['rock', 'paper', 'scissors'] comp = random.choice(a) print('Pick from:', str(a).strip('[]')) user = input() u = a.index(user) c = a.index(comp) line_1 = '{} : {}\t{} : {}'.format(u_name, user, 'Computer', comp) line_2 = '{} : {}\t{} : {}\n'.format(u_name, u_cnt, 'Computer', c_cnt) if c_cnt &lt; points or u_cnt &lt; points: if u &gt; c or u == 0 and c == 2: u_cnt += 1 print(line_1, '\t', u_name, 'wins') print(line_2) elif u &lt; c or u == 2 and c == 0: c_cnt += 1 print(line_1, '\t', 'Computer wins') print(line_2) elif u == c: print(line_1, '\t', 'Tie') print(line_2) else: break </code></pre> <p>so when you run this the first time, you get an answer back like</p> <pre><code>What is your name? chad How many points: 3 Pick from: 'rock', 'paper', 'scissors' rock chad : rock Computer : scissors chad wins chad : 0 Computer : 0 Pick from: 'rock', 'paper', 'scissors' </code></pre> <p>how to get the count be 1, 0 on the first iteration through. that might be a better question.</p>
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.net/pybiblio/practice/wilson/rockpaperscissors.php</a><br> I didn't put the ctrl-d into it though.</p> <p>I'll make comments on the code that worked how I wanted it to. That is give the count as each try was went through.</p> <pre><code>import random u_name = input('What is your name? ') points = int(input('How many points to play to? ')) u_cnt, c_cnt = 0, 0 a = ['rock', 'paper', 'scissors'] while u_cnt &lt; points or c_cnt &lt; points: comp = random.choice(a) print('Pick from:', str(a).strip('[]')) user = input() u = a.index(user) c = a.index(comp) line_1 = '{} : {}\t{} : {}'.format(u_name, user, 'Computer', comp) if u &gt; c or u == 0 and c == 2: u_cnt += 1 print(line_1, '\t', u_name, 'wins') elif u &lt; c or u == 2 and c == 0: c_cnt += 1 print(line_1, '\t', 'Computer wins') elif u == c: print(line_1, '\t', 'Tie') line_2 = '{} : {}\t{} : {}\n'.format(u_name, u_cnt, 'Computer', c_cnt) print(line_2) if u_cnt == points or c_cnt == points: if u_cnt &gt; c_cnt: print('\n', u_name.upper(), 'WINS!!!') elif u_cnt &lt; c_cnt: print('\n', 'COMPUTER WINS!!!') print(line_2) break exit() </code></pre> <p>To get my count for each attempt I had to put <code>line_2</code> at the end of my first <code>if</code> loop so that it would increment properly. </p> <p>If you look at my original post, you will see that I have <code>line_2</code> outside of the first <code>if</code> statement. This was making it so that it would go through the whole loop and then add the count the next time through, instead of adding it right away.</p> <p>I put the second <code>if</code> statement in so that it would test the loop and then print who the winner was.</p> <p>I also learned that I had alot of extra <code>print(line_2)</code> statements in the original post and if I just put the one in I could reduce my typing. (pythonic way?)</p> <p>I have done this (rock, paper, scissors) on other practice sites and this is the least amount of <code>if, elif</code>'s that I have had to do.</p> <p>As the people who know what they are doing will tell you, practice code, read code, practice code.</p> <p>Thank you everyone for your help and tips/tricks.<br> em</p>
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) stockholmLargeCap = list(reader) start = datetime.datetime(1970, 1, 1) end = datetime.datetime.today(); stockData = {} for symbol in stockholmLargeCap: f = pdr.DataReader(symbol, 'yahoo', start, end) print f </code></pre> <p>The stockholm_largecap.csv contains all stocks in alphabetical order but once I get to certain stocks I get (for example BETS-B.ST): SymbolWarning: Failed to read symbol: 'BETS-B.ST', replacing with NaN. and the script terminates. Is there some way to continue the program, ignoring the error and what could be the cause of some stocks not working?</p> <pre><code>raise RemoteDataError(msg.format(self.__class__.__name__)) pandas_datareader._utils.RemoteDataError: No data fetched using 'YahooDailyReader' </code></pre>
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 Low Close Volume Adj Close Date 2001-01-02 132.0000 132.1562 127.5625 128.8125 8737500 95.2724 2001-01-03 128.3125 136.0000 127.6562 135.0000 19431600 99.8488 2001-01-04 134.9375 135.4687 133.0000 133.5468 9219000 98.7740 2001-01-05 133.4687 133.6250 129.1875 129.1875 12911400 95.5497 2001-01-08 129.8750 130.1875 127.6875 130.1875 6625300 96.2893 did not find: holla </code></pre>
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" rel="nofollow"><img src="https://i.stack.imgur.com/2pt93.png" alt="Image with transparent"></a></p> <p>Someone know how i can do that using PIL, or maybe, unix tools. Thanks for any help</p>
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.com/eD04t.png" alt="enter image description here"></a></p> <p>But I am going to do morphology and I want white on black, so invert it:</p> <pre><code>convert input.png -alpha extract -negate alpha.png </code></pre> <p><a href="https://i.stack.imgur.com/R6ppT.png" rel="nofollow"><img src="https://i.stack.imgur.com/R6ppT.png" alt="enter image description here"></a></p> <p>Now run a <em>"Connected Components"</em> analysis to find the blobs of white:</p> <pre><code>convert input.png -alpha extract -negate -threshold 50% \ -define connected-components:verbose=true \ -define connected-components:area-threshold=100 \ -connected-components 8 -auto-level null: </code></pre> <p><strong>Output</strong></p> <pre><code>Objects (id: bounding-box centroid area mean-color): 0: 600x376+0+0 249.7,205.3 129723 srgb(0,0,0) 2: 203x186+70+20 170.8,112.6 27425 srgb(255,255,255) 1: 218x105+337+13 445.5,65.0 22890 srgb(255,255,255) 4: 218x105+337+251 445.5,303.0 22890 srgb(255,255,255) 3: 218x104+337+132 445.5,183.5 22672 srgb(255,255,255) </code></pre> <p>And there they are. Ignore the first row because it is black and corresponds to the whole image. Now, look at the second row and you can see the block is 203x186 at offset +70+20. The centroid is there too. Let me box that blob in in red:</p> <pre><code>convert input.png -stroke red -fill none -draw "rectangle 70,20 272,205" z.png </code></pre> <p><a href="https://i.stack.imgur.com/BJS2k.png" rel="nofollow"><img src="https://i.stack.imgur.com/BJS2k.png" alt="enter image description here"></a></p>
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>I want the triangular matrix of distances between all coordinates. A simple approach would be to code a double loop over all coordinates </p> <pre><code>In [4]: n_coor = len(coor) In [5]: dist = np.zeros((n_coor, n_coor)) In [6]: for j in xrange(n_coor): for k in xrange(j+1, n_coor): dist[j, k] = np.sqrt(np.sum((coor[j] - coor[k]) ** 2)) </code></pre> <p>with the result being an upper triangular matrix of the distances</p> <pre><code>In [7]: dist Out[7]: array([[ 0. , 3.31662479, 7.28010989, 9.2736185 ], [ 0. , 0. , 10.48808848, 10.81665383], [ 0. , 0. , 0. , 9.43398113], [ 0. , 0. , 0. , 0. ]]) </code></pre> <p>Leveraging NumPy, I can avoid looping using</p> <pre><code>In [8]: dist = np.sqrt(((coor[:, None, :] - coor) ** 2).sum(-1)) </code></pre> <p>but the result is the entire matrix</p> <pre><code>In [9]: dist Out[9]: array([[ 0. , 3.31662479, 7.28010989, 9.2736185 ], [ 3.31662479, 0. , 10.48808848, 10.81665383], [ 7.28010989, 10.48808848, 0. , 9.43398113], [ 9.2736185 , 10.81665383, 9.43398113, 0. ]]) </code></pre> <p>This one line version takes roughly half the time when I use 2048 coordinates (4 s instead of 10 s) but this is doing twice as many calculations as it needs in order to get the symmetric matrix. Is there a way to adjust the one line command to only get the triangular matrix (and the additional 2x speedup, i.e. 2 s)?</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 scipy.spatial.distance import pdist n_coor = len(coor) dist = np.zeros((n_coor, n_coor)) row,col = np.triu_indices(n_coor,1) dist[row,col] = pdist(coor) </code></pre> <p>Alternatively, we can use boolean-indexing to assign values, replacing the last two lines</p> <pre><code>dist[np.arange(n_coor)[:,None] &lt; np.arange(n_coor)] = pdist(coor) </code></pre> <hr> <p><strong>Runtime test</strong></p> <p>Functions:</p> <pre><code>def subscripted_indexing(coor): n_coor = len(coor) dist = np.zeros((n_coor, n_coor)) row,col = np.triu_indices(n_coor,1) dist[row,col] = pdist(coor) return dist def boolean_indexing(coor): n_coor = len(coor) dist = np.zeros((n_coor, n_coor)) r = np.arange(n_coor) dist[r[:,None] &lt; r] = pdist(coor) return dist </code></pre> <p>Timings:</p> <pre><code>In [110]: # Setup input array ...: coor = np.random.randint(0,10, (2048,3)) In [111]: %timeit subscripted_indexing(coor) 10 loops, best of 3: 91.4 ms per loop In [112]: %timeit boolean_indexing(coor) 10 loops, best of 3: 47.8 ms per loop </code></pre>
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" ]