title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Vectorizing calculations in pandas
40,123,132
<p>I'm trying to calculate group averages inside of the cross-validation scheme, but this iterating method is extremely slow as my dataframe contains more than 1mln rows. Is it possible to vectorize this calculation? Thanks.</p> <pre><code>import pandas as pd import numpy as np data = np.column_stack([np.arange(1,101)...
3
2016-10-19T05:45:43Z
40,125,786
<p>Replace the <code>for i, row in df.loc[df.fold == 1, :].iterrows():</code>-loop with this:</p> <pre><code>df0 = pd.merge(df[df.fold == 1],aux2,on='group').set_index('id') df = df.set_index('id') df.loc[(df.fold == 1),'group_average'] = df0.loc[:,'group_average_y'] df = df.reset_index() </code></pre> <p>This gives ...
3
2016-10-19T08:17:38Z
[ "python", "pandas", "vectorization", "cross-validation" ]
two foreign keys in one model sqlalchemy duplicate
40,123,291
<p>There are other answers on stacked overflow and I followed them. Its been 3 days with this problem and i have searched all answers before and i feel that even if its repeat question i should be afraid to ask if I cant get it to work after much researching.</p> <p>the desired result is foreign keys in one model usi...
1
2016-10-19T05:55:31Z
40,126,250
<p>Checkout <a href="http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#self-referential-many-to-many-relationship" rel="nofollow">this example</a> on the documentation. Probably you are using a sqlalchemy version &lt;= 0.8 and that's why your code your code won't work.</p>
0
2016-10-19T08:39:47Z
[ "python", "sqlalchemy" ]
Sublime text 3 plugin development for custom autocomplete like emmet?
40,123,520
<p>I would like to create my custom plugin like emmet for auto completion and tag expansion for html tags like <code>h2&gt;span</code> .myclass should result in <code>&lt;div class="myclass"&gt;&lt;/div&gt;</code>.</p> <p>I started with but didn't find any documentation for tracking the user type event and how to def...
0
2016-10-19T06:12:30Z
40,123,648
<p>Typically, one doesn't program a plugin to track what the user types in Sublime Text, but instead binds a command to a keybinding. Then, when the user presses that certain key, under certain conditions, defined in the context of the keybinding, the command executes and looks at the text near the selection caret.</p>...
1
2016-10-19T06:20:47Z
[ "python", "sublimetext3" ]
Numba jitclass and inheritance
40,123,521
<p>I have an hierarchy of classes and I would like to speed up my code by using Numba jitclass. I have tested @jitclass for some examples without class inheritance and it works properly and speed up the code. However, if I have class inheritance the error occurred during the compilation. Below is the sample code demons...
1
2016-10-19T06:12:33Z
40,129,735
<p>Currently (as of 0.28.1), Numba does not support subclassing/inheriting from a <code>jitclass</code>. It's not stated in the documentation but the error message is pretty explicit. I'm guessing this capability will be added sometime in the future, but right now it's a limitation.</p>
1
2016-10-19T11:08:26Z
[ "python", "inheritance", "numba" ]
Ubuntu: No module named tensorflow in IPython but works in Python (Anaconda environment)
40,123,621
<p>When I try to import tensorflow in IPython in my Anaconda environment, I get a <code>No module named tensorflow</code> error. However, when I import it after running the <code>python</code> command in the terminal, there are no errors.</p> <p>I've googled for solutions and so far I have tried the following:</p> <u...
0
2016-10-19T06:18:51Z
40,126,550
<p>Refer: <a href="http://stackoverflow.com/questions/33646541/tensorflow-and-anaconda-on-ubuntu?rq=1">Tensorflow and Anaconda on Ubuntu?</a></p> <p>I found a link where the tensorflow.whl files were converted to conda packages, so I went ahead and installed it using the command:</p> <pre><code>conda install -c https...
0
2016-10-19T08:54:21Z
[ "python", "ubuntu", "ipython", "tensorflow", "anaconda" ]
get attribute from xml-node with specific value
40,123,627
<p>I have an XSD-file where I need to get a namespace as defined in the root-tag:</p> <pre><code>&lt;schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:abw="http://www.liegenschaftsbestandsmodell.de/ns/abw/1.0.1.0" xmlns:adv="http://www.adv-online.de/namespaces/adv/gid/6.0" xmlns:bfm="http://www.liegenschaftsbestan...
1
2016-10-19T06:19:06Z
40,124,264
<p>string must be Unicode else error will appear</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#62&gt;", line 1, in &lt;module&gt; it = etree.iterparse(StringIO(xml)) TypeError: initial_value must be unicode or None, not str </code></pre> <p>code:</p> <pre><code>&gt;&gt;&gt; from io import...
1
2016-10-19T06:57:25Z
[ "python", "xml" ]
get attribute from xml-node with specific value
40,123,627
<p>I have an XSD-file where I need to get a namespace as defined in the root-tag:</p> <pre><code>&lt;schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:abw="http://www.liegenschaftsbestandsmodell.de/ns/abw/1.0.1.0" xmlns:adv="http://www.adv-online.de/namespaces/adv/gid/6.0" xmlns:bfm="http://www.liegenschaftsbestan...
1
2016-10-19T06:19:06Z
40,125,451
<p>Using minidom instead of ETree did it:</p> <pre><code>import xml.dom.minidom as DOM tree = DOM.parse(myFile) root = tree.documentElement targetNamespace = root.getAttribute("targetNamespace") d = dict(root.attributes.items()) for key in d: if d[key] == targetNamespace: return key </code></pre> <p>This will re...
0
2016-10-19T07:59:56Z
[ "python", "xml" ]
Pandas Compare rows in Dataframe
40,123,689
<p>I have following data frame (represented by dictionary below):</p> <pre><code>{'Name': {0: '204', 1: '110838', 2: '110999', 3: '110998', 4: '111155', 5: '111710', 6: '111157', 7: '111156', 8: '111144', 9: '118972', 10: '111289', 11: '111288', 12: '111145', 13: '121131', 14: '118990', 1...
1
2016-10-19T06:23:23Z
40,123,766
<p>You can use double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> with condition with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull</code></a>:</p> <pre><code>ma...
1
2016-10-19T06:27:51Z
[ "python", "pandas", null, "missing-data" ]
Pandas Compare rows in Dataframe
40,123,689
<p>I have following data frame (represented by dictionary below):</p> <pre><code>{'Name': {0: '204', 1: '110838', 2: '110999', 3: '110998', 4: '111155', 5: '111710', 6: '111157', 7: '111156', 8: '111144', 9: '118972', 10: '111289', 11: '111288', 12: '111145', 13: '121131', 14: '118990', 1...
1
2016-10-19T06:23:23Z
40,123,957
<pre><code>dic_new = {0: 1.0, 1: 2.0, 2: 3.0, 3: 4.0, 4: 5.0, 5: 6.0, 6: 7.0, 7: 8.0, 8: 9.0, 9: 10.0, 10: 11.0, 11: 12.0, 12: 'Nan', 13: 13.0, 14: 14.0, 15: 15.0, 16: 16.0, 17: 17.0, 18: 18.0, 19: 19.0, 20: 20.0, 21: 21.0, 22: 22.0, 23: 23.0, 24: 24.0, 25: 25.0, 26: 26.0, 27: 27.0, 28: 28.0, 29: ...
0
2016-10-19T06:39:04Z
[ "python", "pandas", null, "missing-data" ]
mongodb regex embeded search
40,123,779
<p>My data looks like this:</p> <pre><code>blade = { 'model': 'FW254', 'items':{ 'a': {'time':5, 'count':7}, 'b': {'time':4, 'count':8}, 'c': {'time':2, 'count':9} } } </code></pre> <p>I want to do something like this:</p> <pre><code>collection.find({"items./.*/....
0
2016-10-19T06:28:37Z
40,124,750
<p>Where did you read about using a regex in a spot like that?</p> <p>You should recosider the structure of you data and turns <code>items</code> into an array allowing you to use <a href="https://docs.mongodb.com/v3.2/reference/operator/query/elemMatch/#op._S_elemMatch" rel="nofollow"><code>$elemMatch</code></a></p> ...
0
2016-10-19T07:21:48Z
[ "python", "regex", "mongodb", "nested" ]
Getting HTTP POST Error : {"reason":null,"error":"Request JSON object for insert cannot be null."}
40,123,820
<p>I am getting HTTP POST error when I am trying to connect to a Service Now Instance for Change Request Automation using Python. Here is the script I am using with Python 3.4.4</p> <pre><code># SNOW CR AUTOMATION SCRIPT import requests import json # put the ip address or dns of your SNOW API in this url url = 'http...
0
2016-10-19T06:31:08Z
40,128,799
<p>First of all in Service-Now you should always use SSL, so no http! Second error I see in your script is how you pass your payload, you need to transform your dictionary into a JSON Object/String. And you don't need to authenticate twice, you have the basic http authentication handled by requests.post so no need for ...
0
2016-10-19T10:30:16Z
[ "python", "rest", "post", "servicenow" ]
Getting HTTP POST Error : {"reason":null,"error":"Request JSON object for insert cannot be null."}
40,123,820
<p>I am getting HTTP POST error when I am trying to connect to a Service Now Instance for Change Request Automation using Python. Here is the script I am using with Python 3.4.4</p> <pre><code># SNOW CR AUTOMATION SCRIPT import requests import json # put the ip address or dns of your SNOW API in this url url = 'http...
0
2016-10-19T06:31:08Z
40,143,200
<p>This is a working example I tested on my instance. I am using REST Table API to insert a change request. It's not true that it can not be http. It's whatever protocol your instance allows to connect, say from browser. </p> <pre><code>#Need to install requests package for python #easy_install requests import request...
1
2016-10-19T23:37:20Z
[ "python", "rest", "post", "servicenow" ]
Python integer to hex string
40,123,901
<p>Consider an integer 2. I want to convert it into hex string '0x02'. By using python's build-in function hex, I can get '0x2' which is not suitable for my code. Can any one show me how to get what I want in a convenient way. Thank you. </p>
-4
2016-10-19T06:36:22Z
40,123,984
<pre><code>integer = 2 hex_string = '0x{:02x}'.format(integer) </code></pre> <p>See <a href="https://www.python.org/dev/peps/pep-3101/" rel="nofollow">pep 3101</a>, especially <em>Standard Format Specifiers</em> for more info.</p>
4
2016-10-19T06:40:21Z
[ "python", "hex" ]
Python integer to hex string
40,123,901
<p>Consider an integer 2. I want to convert it into hex string '0x02'. By using python's build-in function hex, I can get '0x2' which is not suitable for my code. Can any one show me how to get what I want in a convenient way. Thank you. </p>
-4
2016-10-19T06:36:22Z
40,124,000
<p>Simply add a leading zero if needed:</p> <pre><code>'0x' + hex(i)[2:].rjust(2, '0') </code></pre>
0
2016-10-19T06:41:10Z
[ "python", "hex" ]
Python integer to hex string
40,123,901
<p>Consider an integer 2. I want to convert it into hex string '0x02'. By using python's build-in function hex, I can get '0x2' which is not suitable for my code. Can any one show me how to get what I want in a convenient way. Thank you. </p>
-4
2016-10-19T06:36:22Z
40,124,604
<pre><code>&gt;&gt;&gt; integer = 2 &gt;&gt;&gt; hex_string = format(integer, '#04x') # add 2 to field width for 0x &gt;&gt;&gt; hex_string '0x02' </code></pre> <p>See <a href="https://docs.python.org/3.4/library/string.html#format-specification-mini-language" rel="nofollow">Format Specification Mini-Language</a></p>...
0
2016-10-19T07:14:49Z
[ "python", "hex" ]
Error in inserting python variable in mysql table
40,123,910
<p>I am working on a raspberry pi project, in which I'm fetching data from plc and storing it into mysql database.</p> <p>Here is my code:</p> <pre><code>import minimalmodbus import serial import mysql.connector instrument = minimalmodbus.Instrument('/dev/ttyAMA0',3,mode='rtu') instrument.serial.baudrate=115200 ins...
2
2016-10-19T06:37:00Z
40,124,043
<p>Pretty common error in python.</p> <p><code>(reg_value)</code> is not a tuple <code>(reg_value,)</code> is a tuple</p>
0
2016-10-19T06:43:42Z
[ "python", "mysql", "raspberry-pi" ]
Error in inserting python variable in mysql table
40,123,910
<p>I am working on a raspberry pi project, in which I'm fetching data from plc and storing it into mysql database.</p> <p>Here is my code:</p> <pre><code>import minimalmodbus import serial import mysql.connector instrument = minimalmodbus.Instrument('/dev/ttyAMA0',3,mode='rtu') instrument.serial.baudrate=115200 ins...
2
2016-10-19T06:37:00Z
40,125,006
<p>i think should be.</p> <pre><code>cursor.execute("insert into Register_Values values(%s)",(reg_value)) con.commit() </code></pre>
1
2016-10-19T07:37:03Z
[ "python", "mysql", "raspberry-pi" ]
understanding marshmallow nested schema with list data
40,123,990
<p>Am new to python and am usign <a href="https://marshmallow.readthedocs.io/en/latest/" rel="nofollow">marshmallow</a> serialization. unable to use the nested scehma. , my code </p> <pre><code>from sqlalchemy import Column, Float, Integer, String, Text, text,ForeignKey from sqlalchemy.ext.declarative import declar...
0
2016-10-19T06:40:36Z
40,131,490
<p>Self contained example using in-memory SQLite:</p> <pre><code>from flask import Flask, jsonify from flask.ext.sqlalchemy import SQLAlchemy from marshmallow import Schema, fields, pprint app = Flask(__name__) app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'super-secret' app.config['SQLALCHEMY_DATABASE_URI'] ...
1
2016-10-19T12:31:50Z
[ "python", "flask", "marshmallow" ]
the use of regular expression
40,124,242
<p>I'm new in regular expression, but I want to match a pattern in about 2 million strings. There three forms of the origin strings shown as follows:</p> <pre><code>EC-2A-07&lt;EC-1D-10&gt; EC-2-07 T1-ZJF-4 </code></pre> <p>I want to get three parts of substrings besides <code>-</code>, which is to say I want to ge...
-1
2016-10-19T06:55:43Z
40,124,727
<p>You can try this:</p> <pre><code>^(\w+)-(\w+)-(\w+)(?=\W).*$ </code></pre> <p><a href="https://regex101.com/r/5D9BeE/1" rel="nofollow">Explanation</a></p> <p><a href="https://repl.it/EAM9" rel="nofollow">Python Demo</a></p>
0
2016-10-19T07:20:42Z
[ "python", "regex", "string" ]
Python C Api: transfer dynamically allocated array to Python
40,124,249
<p>I am using Python and I want to do numerical calculations (Runge-Kutta for a scalar ODE, <em>dy/dt = f(t,y)</em> ) on huge arrays (size can be up to 8000 x 500 ). To speed it up, I implemented the routine in C. I am using the Python C API to pass the data to C, do the calculation and then send it back. Since such a ...
1
2016-10-19T06:56:00Z
40,124,509
<p>In your allocation, :</p> <pre><code>mag size = Nt*Nr, </code></pre> <p>In your loop, when i is max and k is max:</p> <pre><code>k=Nr-1, i=Nt-1, </code></pre> <p>Hence:</p> <p><code>a0=mag[k*Nt + i];</code> -> <code>(Nt-1)+Nt*(Nr-1)=Nt-1+NtNr-Nt=NtNr-1</code>, and you call</p> <p><code>a1=mag[k*Nt + i+1];</co...
1
2016-10-19T07:09:41Z
[ "python", "c", "python-c-api" ]
Error in NLTK file
40,124,399
<p>I have installed Anaconda3-4.2.0 for Windows (64 bit) and nltk-3.2.1. While i am running the following code in Jupyter Notebook</p> <pre><code>`para = "Hello World. It's good to see you. Thanks for buying this book." import nltk.data tokenizer = nltk.data.load('tokenizers/punkt/PY3/english.pickle') tokenizer.token...
0
2016-10-19T07:03:40Z
40,125,718
<p>It seems tokenizers/punkt/PY3/english.pickle file not exists. You need check it.</p> <p>NLTK can download pickle file use download function:</p> <pre><code>import nltk nltk.download() </code></pre>
0
2016-10-19T08:13:36Z
[ "python" ]
Weighted clustering of tags
40,124,423
<p>I have a list of products and each product is tagged and weights associated to it each tag. Now I want to cluster them into similar products. How do I go forward it. I have tried k-means of scikit-learn. But That is not helping much.</p> <pre><code>Product 1: a=2.5 b=3.5 c=1 d=1 Product 2: a=0.25 c=2 Product 3: e=2...
1
2016-10-19T07:04:42Z
40,124,530
<p>You could use a <a href="https://en.wikipedia.org/wiki/Mixture_model#Gaussian_mixture_model" rel="nofollow">Gaussian Mixture Model</a> which can be seen as a generalisation of k-means which allows soft clusters. You can have K clusters, and each entry belongs to all clusters with a certain amount. This amount is the...
0
2016-10-19T07:10:44Z
[ "python", "python-3.x", "machine-learning", "cluster-analysis", "data-mining" ]
Weighted clustering of tags
40,124,423
<p>I have a list of products and each product is tagged and weights associated to it each tag. Now I want to cluster them into similar products. How do I go forward it. I have tried k-means of scikit-learn. But That is not helping much.</p> <pre><code>Product 1: a=2.5 b=3.5 c=1 d=1 Product 2: a=0.25 c=2 Product 3: e=2...
1
2016-10-19T07:04:42Z
40,124,944
<p>If the direct and naïve application of k-means is <em>not helping much</em>, you may need to dig a bit deeper.</p> <p>Assuming you have <code>N</code> distinct tags of which <code>0..N</code> can be applied to each product <code>p</code>. Each assignment describes a weighted relationship with a positive weight <co...
0
2016-10-19T07:33:56Z
[ "python", "python-3.x", "machine-learning", "cluster-analysis", "data-mining" ]
How to set custom stop words for sklearn CountVectorizer?
40,124,476
<p>I'm trying to run LDA (Latent Dirichlet Allocation) on a non-English text dataset.</p> <p>From sklearn's tutorial, there's this part where you count term frequency of the words to feed into the LDA:</p> <pre><code>tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, max_features=n_fea...
1
2016-10-19T07:07:30Z
40,124,718
<p>You may just assign a <code>frozenset</code> of your own words to the <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/feature_extraction/stop_words.py" rel="nofollow"><code>stop_words</code> argument</a>, e.g.:</p> <pre><code>stop_words = frozenset(["word1", "word2","word3"]) </code></pre>...
0
2016-10-19T07:20:28Z
[ "python", "machine-learning", "scikit-learn", "nlp" ]
Serve uploaded files from NGINX server instead of gunicorn/Django
40,124,568
<p>I have separate servers one running NGINX and other running gunicorn/Django, I managed to serve static files from NGINX directly as recommended from Django documentation, but I have an issue with files uploaded by users, which will be upload to server has gunicorn, not the server has NGINX, thus users can't find th...
0
2016-10-19T07:12:43Z
40,125,586
<p>You need to implement a solution for sharing files from one server to another. NFS is the standard in Unixes like Linux. An alternative is to use live mirroring, i.e. create a copy of the media files directory in the nginx server and keep it synchronized. There are probably many options for setting this up; I've suc...
1
2016-10-19T08:06:48Z
[ "python", "django", "nginx", "gunicorn", "django-media" ]
How to add space after label in ModelForms of django
40,124,807
<p>I want to add space after "Mobile No: ",meaning in between label and text area. But by using django ModelForms I am not able to do that, it shows "Mobile No:" without any space between label and textarea.</p> <p>This is how I have described it in models.py file.</p> <pre><code>phone = models.CharField(max_length=1...
0
2016-10-19T07:25:22Z
40,125,208
<p>You should iterate through your form fields.</p> <p>Like this:</p> <pre><code>&lt;form method="post" &gt; {% csrf_token %} {% for field in form %} &lt;div class="form-group"&gt; &lt;label class="col-sm-4 control-label" for="{{ field.name }}"&gt;{{ field.label }} : &lt;/label&gt; ...
1
2016-10-19T07:47:37Z
[ "python", "django", "django-models", "django-forms" ]
How to add space after label in ModelForms of django
40,124,807
<p>I want to add space after "Mobile No: ",meaning in between label and text area. But by using django ModelForms I am not able to do that, it shows "Mobile No:" without any space between label and textarea.</p> <p>This is how I have described it in models.py file.</p> <pre><code>phone = models.CharField(max_length=1...
0
2016-10-19T07:25:22Z
40,125,212
<p>The layout and spacing of form labels and fields is a presentation matter and best handled through CSS.</p> <p>See also: <a href="http://stackoverflow.com/questions/5827590/css-styling-in-django-forms">CSS styling in Django forms</a></p>
2
2016-10-19T07:47:44Z
[ "python", "django", "django-models", "django-forms" ]
Replace characters in a string from a list and create a copy for each
40,124,811
<p>I'm not sure if it's even possible to do what I need with sed.</p> <p>I want to be able to replace a string in a file with another string from a list and create a separate copy for each version.</p> <p>For example, the original file has:</p> <pre><code>apple dog orange </code></pre> <p>I want to replace <code>do...
1
2016-10-19T07:25:38Z
40,124,913
<p>You could do it with python using regex.</p> <pre><code>import re import os filename = '/path/to/filename.txt' with open(filename, 'r') as f: text = f.read() names = ['cat', 'rabbit', 'duck'] for i, name in enumerate(names): new_text = re.sub(r'dog', name, text) base, ext = os.path.splitext(filename) ...
2
2016-10-19T07:32:16Z
[ "python", "string", "replace", "sed" ]
Replace characters in a string from a list and create a copy for each
40,124,811
<p>I'm not sure if it's even possible to do what I need with sed.</p> <p>I want to be able to replace a string in a file with another string from a list and create a separate copy for each version.</p> <p>For example, the original file has:</p> <pre><code>apple dog orange </code></pre> <p>I want to replace <code>do...
1
2016-10-19T07:25:38Z
40,125,022
<p>You can use regex</p> <pre><code>import re in_file = 'File1.txt' out_file = 'File2.txt' with open(filename, 'r') as in_f: s = f.read() # Reads whole file. Be careful for large files s = re.sub('dog', 'cat', s) with open(out_file, 'w') as out_f: f.write(s) </code></pre> <p>You can enclose the w...
1
2016-10-19T07:37:57Z
[ "python", "string", "replace", "sed" ]
Replace characters in a string from a list and create a copy for each
40,124,811
<p>I'm not sure if it's even possible to do what I need with sed.</p> <p>I want to be able to replace a string in a file with another string from a list and create a separate copy for each version.</p> <p>For example, the original file has:</p> <pre><code>apple dog orange </code></pre> <p>I want to replace <code>do...
1
2016-10-19T07:25:38Z
40,125,092
<p>You can do it simply using string replace method</p> <pre><code>import string f = open("file1") text = f.read() list_of_words = ['cat','rabbit','duck'] num =2 for word in list_of_words: new_text = string.replace(text,"dog",word,1) f_new = open("file"+str(num),"w") f_new.write(new_text) f_new.close()...
1
2016-10-19T07:41:52Z
[ "python", "string", "replace", "sed" ]
How do I set a specific action to happen when the "enter" key on my keyboard is pressed in python
40,124,901
<p>I am making a python calculator with GUI for school. </p> <p>I have got some basic code from the internet and I have to customize it by changing things around. So far I have added a <code>DEL</code> button, a <code>^2</code> button and a <code>sqrt()</code> button. </p> <p>I now want that if I type in an equation ...
0
2016-10-19T07:31:19Z
40,126,661
<p>You can use <code>bind()</code> to assign function to <code>Entry</code> which will be executed when you press <code>Enter</code></p> <p>Example:</p> <pre><code>import tkinter as tk def on_return(event): print('keycode:', event.keycode) print('text in entry:', event.widget.get()) root = tk.Tk() e = tk.E...
1
2016-10-19T08:59:00Z
[ "python", "user-interface", "tkinter" ]
Pydot won't create a graph
40,125,051
<p>yesterday I added pydot package by installing it via pip in command line. I can import the package and even create an object, but when I want to create a graph by:</p> <pre><code>graph.write_jpg('example1_graph.jpg') </code></pre> <p>I get the following error:</p> <pre><code>Exception: "dot.exe" not found in path...
0
2016-10-19T07:39:30Z
40,125,598
<p>Try manually adding the Graphviz\bin folder to your systems PATH.</p> <pre><code>&gt;&gt;&gt; import pydot &gt;&gt;&gt; pydot.find_graphviz() {'dot': 'C:\\Program Files (x86)\\Graphviz 2.28\\bin\\dot.exe'} #... &gt;&gt;&gt; print pydot.find_graphviz.__doc__ """ Locate Graphviz's executables in the system. Trie...
0
2016-10-19T08:07:37Z
[ "python", "pydot" ]
Trying to make an autocompleter for words in Python (Schoolwork)
40,125,081
<p>I have a University assigment(So I'd like to get informative hints rather than an all-out code-bunch to copy) where we're supposed to make a program that automaticaly completes words. (Gives out suggestions based on letters written.) The suggestions for these words are taken from a list called "alphabetical.csv", wh...
0
2016-10-19T07:41:00Z
40,125,958
<p>You will first need to <a href="https://docs.python.org/3.6/library/functions.html?highlight=open#open" rel="nofollow">open</a> a file and to <a href="https://docs.python.org/3.6/library/io.html#io.TextIOBase.read" rel="nofollow">read</a> it. Then you will have to search words which start with a substring, <a href="...
0
2016-10-19T08:26:03Z
[ "python", "autocomplete", "words" ]
Using multiple columns as ForeignKey to return in another table
40,125,110
<p>I'm new to Django so I make 3 simple tables to return a WishList. The thing is that I want whenever user asks for WishList, his/her <code>user_id</code> is used to make a <code>SELECT</code> query to return his/her own WishList. And I want to get product title and product url from my WishList table. I'm using <code>...
0
2016-10-19T07:42:45Z
40,125,643
<p>Django documentation is your friend, <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/" rel="nofollow">read it</a>.</p> <p>Im serious, read the entire <a href="https://docs.djangoproject.com/en/1.10/" rel="nofollow">documentation</a>.</p> <p>Moreover its not a good practice to override to_field to...
1
2016-10-19T08:10:14Z
[ "python", "django", "postgresql", "object", "django-models" ]
Merge multiple lists horizontally in python
40,125,126
<p>I have two different lists like below</p> <pre><code>A = [(Apple, Mango)] B = [Grapes] </code></pre> <p>Now I would like to get a merged list as follows</p> <pre><code>C = [(Apple,Mango,Grapes)] </code></pre> <p>Is there any predefined functions available in python to get above merged list.</p> <p>Note: Already...
-1
2016-10-19T07:43:57Z
40,125,281
<p>If A is list of tuples and B is normal list, this works</p> <pre><code>A = [('Apple', 'Mango')] B = ['Grapes'] print [ tuple( sum ( map(list,A), [] ) + B) ] </code></pre>
0
2016-10-19T07:51:13Z
[ "python" ]
Merge multiple lists horizontally in python
40,125,126
<p>I have two different lists like below</p> <pre><code>A = [(Apple, Mango)] B = [Grapes] </code></pre> <p>Now I would like to get a merged list as follows</p> <pre><code>C = [(Apple,Mango,Grapes)] </code></pre> <p>Is there any predefined functions available in python to get above merged list.</p> <p>Note: Already...
-1
2016-10-19T07:43:57Z
40,125,309
<p>For you example, you could do</p> <pre><code>C = list(A[0] + (B[0],)) </code></pre>
0
2016-10-19T07:53:08Z
[ "python" ]
Merge multiple lists horizontally in python
40,125,126
<p>I have two different lists like below</p> <pre><code>A = [(Apple, Mango)] B = [Grapes] </code></pre> <p>Now I would like to get a merged list as follows</p> <pre><code>C = [(Apple,Mango,Grapes)] </code></pre> <p>Is there any predefined functions available in python to get above merged list.</p> <p>Note: Already...
-1
2016-10-19T07:43:57Z
40,125,885
<p>If A and B is list of tuples then you can be use following recursive function</p> <p><strong>Input something like this</strong></p> <pre><code>A = [('Apple', 'Mango'), ('Mango1')] B = [('Grapes', 'Banana'), ('Apple1')] </code></pre> <p><strong>Recursive function</strong> </p> <pre><code>def recursive_fun(c, temp...
0
2016-10-19T08:22:42Z
[ "python" ]
Merge multiple lists horizontally in python
40,125,126
<p>I have two different lists like below</p> <pre><code>A = [(Apple, Mango)] B = [Grapes] </code></pre> <p>Now I would like to get a merged list as follows</p> <pre><code>C = [(Apple,Mango,Grapes)] </code></pre> <p>Is there any predefined functions available in python to get above merged list.</p> <p>Note: Already...
-1
2016-10-19T07:43:57Z
40,126,209
<p>here's an approach of flattening the tuple after the <code>zip</code>, it might perform less as for time complexity, but it will get what you want even for mixed type list, like <code>[str, tuple]</code> and <code>[tuple, str]</code></p> <pre><code>a = [("apple", "mango"), "orange"] # This is [tuple, str] b = [...
1
2016-10-19T08:37:48Z
[ "python" ]
Merge multiple lists horizontally in python
40,125,126
<p>I have two different lists like below</p> <pre><code>A = [(Apple, Mango)] B = [Grapes] </code></pre> <p>Now I would like to get a merged list as follows</p> <pre><code>C = [(Apple,Mango,Grapes)] </code></pre> <p>Is there any predefined functions available in python to get above merged list.</p> <p>Note: Already...
-1
2016-10-19T07:43:57Z
40,126,535
<p>Since tuples are not mutable, we can't append/add to <code>A[0]</code>. Let's just unpack and create a new tuple within a list:</p> <p><code>[(*A[0], *B)]</code></p>
0
2016-10-19T08:53:33Z
[ "python" ]
Python vectorization with a constant
40,125,236
<p>I have a series X of length n(=300,000). Using a window length of w (=40), I need to implement:</p> <p>mu(i)= X(i)-X(i-w)</p> <p>s(i) = sum{k=i-w to i} [X(k)-X(k-1) - mu(i)]^2</p> <p>I was wondering if there's a way to prevent loops here. The fact that mu(i) is constant in second equation is causing complications...
2
2016-10-19T07:49:07Z
40,126,109
<p><strong>Approach #1 :</strong> One vectorized approach would be using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code>N = X.shape[0] a = np.arange(N) k2D = a[:,None] - np.arange(w+1)[::-1] mu1D = X - X[a-w] out = ((X[k2D] - X[k2D...
1
2016-10-19T08:33:32Z
[ "python", "performance", "pandas", "numpy", "vectorization" ]
webpage access while using scrapy
40,125,256
<p>I am new to python and scrapy. I followed the tutorial and tried to crawl few webpages. I used the code in the <a href="https://doc.scrapy.org/en/latest/intro/tutorial.html" rel="nofollow">tutorial</a> and replaced the URLs - <code>http://www.city-data.com/advanced/search.php#body?fips=0&amp;csize=a&amp;sc=2&amp;sd=...
0
2016-10-19T07:49:48Z
40,127,973
<p>First of all, this website looks like a JavaScript-heavy one. Scrapy itself only downloads HTML from servers but does not interpret JavaScript statements.</p> <p>Second, the URL fragment (i.e. everything including and after <code>#body</code>) is not sent to the server and only <code>http://www.city-data.com/advanc...
0
2016-10-19T09:55:24Z
[ "python", "python-2.7", "web-scraping", "scrapy", "scrapy-spider" ]
Efficiently write SPSS data into Excel using Python
40,125,275
<p>I am trying to use Python to write data from an open SPSS dataset into an excel file. The below program works fine, but it takes about 35 seconds for a file with 1.4 million data-points (2500 cases, 700 variables). </p> <p>For now, I am looping through each case (as a tuple), then assigning each element of the tupl...
2
2016-10-19T07:50:46Z
40,126,359
<p>You could experiment with using the <code>win32com</code> approach. This is normally quite slow, but it does have the advantage of being able to do most of the data transfer in a single call. You would just need to prepare your data into a suitably sized list:</p> <pre><code>import win32com.client as win32 data = ...
1
2016-10-19T08:45:18Z
[ "python", "excel", "spss", "openpyxl" ]
Efficiently write SPSS data into Excel using Python
40,125,275
<p>I am trying to use Python to write data from an open SPSS dataset into an excel file. The below program works fine, but it takes about 35 seconds for a file with 1.4 million data-points (2500 cases, 700 variables). </p> <p>For now, I am looping through each case (as a tuple), then assigning each element of the tupl...
2
2016-10-19T07:50:46Z
40,127,235
<p>Make sure lxml is installed and use openpyxl's write-only mode, assuming you can work on a row-by-row basis. If this is not directly possible then you'll need some kind of intermediate structure that can give you rows.</p>
0
2016-10-19T09:22:40Z
[ "python", "excel", "spss", "openpyxl" ]
How to convert this Python code to c#?
40,125,289
<p>I'm fairly decent at python and just starting to learn C#.</p> <p>How would i write this peice of python code in c#?</p> <pre><code> d =" ".join(c.split()) </code></pre> <p>I'm a c# beginner so nothing too technical please.</p>
0
2016-10-19T07:51:46Z
40,125,399
<p>d = string.Join(null, c.Split(null)); //null is your separator where you can change it to " "</p>
0
2016-10-19T07:57:04Z
[ "c#", "python" ]
How to convert this Python code to c#?
40,125,289
<p>I'm fairly decent at python and just starting to learn C#.</p> <p>How would i write this peice of python code in c#?</p> <pre><code> d =" ".join(c.split()) </code></pre> <p>I'm a c# beginner so nothing too technical please.</p>
0
2016-10-19T07:51:46Z
40,125,405
<p>As far as I can see</p> <pre><code> c.split() </code></pre> <p>is splitting string <code>c</code> by default - <code></code> (space) - delimiter; C# equivalent is</p> <pre><code> c.Split(' '); </code></pre> <p>Pythonic</p> <pre><code> " ".join </code></pre> <p>is collection joining with <code>" "</code> being ...
2
2016-10-19T07:57:15Z
[ "c#", "python" ]
How to convert this Python code to c#?
40,125,289
<p>I'm fairly decent at python and just starting to learn C#.</p> <p>How would i write this peice of python code in c#?</p> <pre><code> d =" ".join(c.split()) </code></pre> <p>I'm a c# beginner so nothing too technical please.</p>
0
2016-10-19T07:51:46Z
40,125,424
<p>Its almost the same:</p> <pre><code>// splitting by space var d = string.Join (" ", c.Split (' ')); </code></pre>
0
2016-10-19T07:58:50Z
[ "c#", "python" ]
Jython : SyntaxError: invalid syntax
40,125,406
<p>am getting a syntax error in my code. Can anyone say what's wrong in the syntax? I am new to this language, don't have much of an idea.</p> <p>Error Message:</p> <blockquote> <p>WASX7017E: Exception received while running file "jdbcconnection.jy"; exception information: com.ibm.bsf.BSFException: exception from...
0
2016-10-19T07:57:28Z
40,125,581
<p>Your syntax would be invalid in any language. You have <code>'...Server='+serverName' ...'</code> - you are missing a <code>+</code> before the reopening of the quote.</p> <p>Of course, you should not be building up strings like that; you should be using one of the many string formatting features available in Pytho...
2
2016-10-19T08:06:32Z
[ "python", "jython" ]
modify pandas boxplot output
40,125,528
<p>I made this plot in pandas, according to the documentation:</p> <pre><code>import pandas as pd import numpy as np import pyplot as plt df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D']) df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20...
0
2016-10-19T08:04:19Z
40,126,090
<p>A number of things you can do already using the boxplot function in pandas, see the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.boxplot.html" rel="nofollow">documentation</a>. </p> <ul> <li><p>You can already modify the arrangement, and change the fontsize: </p> <pre><code>impor...
2
2016-10-19T08:32:33Z
[ "python", "pandas", "matplotlib" ]
modify pandas boxplot output
40,125,528
<p>I made this plot in pandas, according to the documentation:</p> <pre><code>import pandas as pd import numpy as np import pyplot as plt df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D']) df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4', 'model5', 'model6', 'model7'], 20...
0
2016-10-19T08:04:19Z
40,126,110
<ul> <li>For the arrangement use <code>layout</code></li> <li>For setting x label use <code>set_xlabel('')</code></li> <li>For figure title use <code>figure.subtitle()</code></li> <li>For changing the figure size use <code>figsize=(w,h)</code> (inches)</li> </ul> <p>note: the line <code>np.asarray(bp).reshape(-1)</cod...
2
2016-10-19T08:33:33Z
[ "python", "pandas", "matplotlib" ]
Is it possible to host endpoint and WSGIApplication application in the same app engine project
40,125,691
<p>I implemented endpoint project:</p> <pre><code>@endpoints.api(name='froom', version='v1', description='froom API') class FRoomApi(remote.Service): @endpoints.method(FbPutRoomRequest, RoomMessage, path='putroom/{id}', http_method='PUT', name='putroom') def put_room(self, request): entity = FRoom()...
0
2016-10-19T08:12:20Z
40,131,868
<p>The fundamental problem that needs to be addressed is defining the appropriate overall app request namespace so that routing to the appropriate sub-app can be made reliably, keeping in mind that:</p> <ul> <li><strong>only one sub-app</strong> can be designated as the default one (which will handle requests not matc...
1
2016-10-19T12:49:59Z
[ "python", "google-app-engine", "wsgi", "endpoint" ]
Starting virtualenv script rc local
40,125,708
<p>I'm very newbie in this field and hope someone can help me.</p> <p>So I have a backend project which I need to launch automatically when the computer switches on (I really don't care how, using systemd or rc.local, my boss told me rc.local, but I guess either will do). I just need to start a docker container, then ...
2
2016-10-19T08:13:10Z
40,128,669
<p>So, partially, the solution seems to set some variables instead of accesing them directly. At least this worked for me. Thanks Samer for giving us a big tip :)</p> <p><code>HOME=/home/backend #the project path docker start container . $HOME/venv/bin/activate #activates the virtualenv of the project /usr/bin/env pyt...
0
2016-10-19T10:24:47Z
[ "python", "linux", "virtualenv", "boot" ]
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' +HOST
40,125,860
<p>I am VERY new to programming and I found this program and APPLY IT BUT I FOUND THESE ERROR (I put error at the end of program), import requests import telnetlib import time import sys</p> <pre><code>import numpy as np import matplotlib import matplotlib.patches as mpatches import matplotlib.pyplot...
1
2016-10-19T08:21:52Z
40,125,982
<p>it should be <code>print ("\tlive \t=\tProcess live data from device ",HOST)</code> not <code>print ("\tlive \t=\tProcess live data from device ") + HOST</code></p>
0
2016-10-19T08:27:03Z
[ "python" ]
Optimal way to iterate through 3 files and generate a third file in python
40,125,895
<p>I have three txt files with a list of lists.</p> <p>File 1 (9.7 thousand lines):</p> <pre><code>ID1, data 1 </code></pre> <p>File 2 (2.1 million lines):</p> <pre><code>ID1, ID2 </code></pre> <p>File 3 (1.1 thousand lines):</p> <pre><code>ID2, data 3 </code></pre> <p>I want to make a file 4 that </p> <ul> <li...
1
2016-10-19T08:23:09Z
40,126,726
<p>Since your IDs are unique, as you write, you could use dictionaries instead of lists for file1 and file3. So your loop check to see if the ID is present reduces to a single lookup in the set of keys to those dictionaries. I don't know your original lists, but I presume that dictionaries are faster for your purpose. ...
1
2016-10-19T09:01:10Z
[ "python", "performance", "file", "optimization" ]
Unable to import modules from relative path
40,125,933
<p>I have a problem for importing modules from relative path with Python. I tried all I found on the web. Here is my directory structure:</p> <pre><code>starcipher/ __init__.py caesar.py tests/ __init__.py test_caesar.py </code></pre> <p>As you can tell, the <code>tests/</code> directory c...
0
2016-10-19T08:24:51Z
40,126,400
<p>Just so the solution is nicely visible, the fix is to delete <code>tests/__init__.py</code> file.</p> <p>However I am not really sure why that works and It would be great if someone could provide explanation.</p>
0
2016-10-19T08:47:06Z
[ "python", "import", "module" ]
Assign class' staticmethods in static variable in python
40,126,208
<p>I have the following class which produces an error:</p> <pre><code>class MyClass(object): QUERIES_AGGS = { 'query3': { "query": MyClass._make_basic_query, 'aggregations': MyClass._make_query_three_aggregations, 'aggregation_transformations': MyClass._make_query_three...
1
2016-10-19T08:37:46Z
40,128,760
<p>Change the order so that the dictionary is specified after the methods have been defined. Also don't use <code>MyClass</code> when doing so.</p> <pre><code>class MyClass(object): @staticmethod def _make_basic_query(): #some code here pass @staticmethod def _make_query_three_aggregati...
1
2016-10-19T10:29:04Z
[ "python" ]
get dictionary contains in list if key and value exists
40,126,260
<p>How to get complete dictionary data inside lists. but first I need to check them if key and value is exists and paired.</p> <pre><code>test = [{'a': 'hello' , 'b': 'world', 'c': 1}, {'a': 'crawler', 'b': 'space', 'c': 5}, {'a': 'jhon' , 'b': 'doe' , 'c': 8}] </code></pre> <p>when I try to make ...
2
2016-10-19T08:40:08Z
40,126,362
<p>Use comprehension:</p> <pre><code>data = [{'a': 'hello' , 'b': 'world', 'c': 1}, {'a': 'crawler', 'b': 'space', 'c': 5}, {'a': 'jhon' , 'b': 'doe' , 'c': 8}] print([d for d in data if d["c"] == 8]) # [{'c': 8, 'a': 'jhon', 'b': 'doe'}] </code></pre>
2
2016-10-19T08:45:28Z
[ "python", "list", "if-statement", "dictionary", "condition" ]
get dictionary contains in list if key and value exists
40,126,260
<p>How to get complete dictionary data inside lists. but first I need to check them if key and value is exists and paired.</p> <pre><code>test = [{'a': 'hello' , 'b': 'world', 'c': 1}, {'a': 'crawler', 'b': 'space', 'c': 5}, {'a': 'jhon' , 'b': 'doe' , 'c': 8}] </code></pre> <p>when I try to make ...
2
2016-10-19T08:40:08Z
40,126,369
<p><code>is</code> tests for identity, not for equality which means it compares the memory address not the values those variables are pointing to. So it is very likely it might return <code>False</code> for same values. You should use <code>==</code> instead for checking equality.</p> <p>As for your question, you can ...
2
2016-10-19T08:45:51Z
[ "python", "list", "if-statement", "dictionary", "condition" ]
Any way to replace pandas pd.merge?
40,126,274
<p>I have two dataframe </p> <pre><code>&gt;&gt;df1.info() &gt;&gt;&lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2598374 entries, 3975 to 3054366 Data columns (total 14 columns): ...... &gt;&gt;df2.info() &gt;&gt;&lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2520405 entries, 2066 to 2519507 ...
2
2016-10-19T08:40:43Z
40,126,424
<p>You can try <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a>:</p> <pre><code>df1 = pd.concat([df1.se...
1
2016-10-19T08:48:19Z
[ "python", "pandas" ]
Python: search string in ziped files
40,126,279
<p>There is any way to search some string in some file in zip file without unziping?</p> <p>I have following structure of directories:</p> <pre><code>. ├───some_zip_file.zip │ ├──some_directory.SAFE │ │ ├──some_dir │ │ ├──some_another_dir │ │ ├──manifest.saf...
-1
2016-10-19T08:40:59Z
40,126,624
<p>The <a href="https://docs.python.org/2/library/zipfile.html?highlight=zipfile#module-zipfile" rel="nofollow">zipfile</a> module could help you:</p> <ul> <li>It allows you to <a href="https://docs.python.org/2/library/zipfile.html?highlight=zipfile#zipfile.ZipFile.open" rel="nofollow">open</a> a file from the zip to...
0
2016-10-19T08:57:39Z
[ "python", "zip" ]
Get the speed of downloading a file using python
40,126,334
<p>I'm using requests lib to download a file, i got many info. about the response like: size,type and date. but i need to get the download speed and set a maximum and minimum for it. How could i get downloading speed ?</p> <p>Here's the code:</p> <pre><code>import requests import sys link = "https://upload.wikimedi...
1
2016-10-19T08:44:12Z
40,126,576
<p>I just added <code>import time</code>, the <code>start</code> variable and replaced the <code>sys.stdout.write</code> line with the one from: <a href="http://stackoverflow.com/questions/20801034/how-to-measure-download-speed-and-progress-using-requests">How to measure download speed and progress using requests?</a><...
1
2016-10-19T08:55:27Z
[ "python", "network-programming", "urllib" ]
Get SQLAlchemy to encode correctly strings with cx_Oracle
40,126,358
<p>My problem is that SQLAlchemy seems to be writing the text not properly encoded in my Oracle database.</p> <p>I include fragments of the code below:</p> <pre><code>engine = create_engine("oracle://%s:%s@%s:%s/%s?charset=utf8"%(db_username, db_password, db_hostname,db_port, db_database), encoding='utf8') connec...
-1
2016-10-19T08:45:16Z
40,134,794
<p>I found a related topic, that actually answers my question:</p> <p><a href="http://stackoverflow.com/questions/39780090/python-2-7-connection-to-oracle-loosing-polish-characters">Python 2.7 connection to oracle loosing polish characters</a></p> <p>You simply add the following line, before creating the database con...
0
2016-10-19T14:48:49Z
[ "python" ]
Inplace functions in Python
40,126,403
<p>In Python there is a concept of inplace functions. For example shuffle is inplace in that it returns none.</p> <p>How do I determine if a function will be inplace or not?</p> <pre><code>from random import shuffle print(type(shuffle)) &lt;class 'method'&gt; </code></pre> <p>So I know it's a <code>method</code> f...
3
2016-10-19T08:47:17Z
40,126,452
<p>You can't have a-priory knowledge about the operation for a given function. You need to either look at the source and deduce this information, or, examine the docstring for it and hope the developer documents this behavior.</p> <p>For example, in <code>list.sort</code>:</p> <pre><code>help(list.sort) Help on metho...
3
2016-10-19T08:49:35Z
[ "python", "function", "python-3.x" ]
Inplace functions in Python
40,126,403
<p>In Python there is a concept of inplace functions. For example shuffle is inplace in that it returns none.</p> <p>How do I determine if a function will be inplace or not?</p> <pre><code>from random import shuffle print(type(shuffle)) &lt;class 'method'&gt; </code></pre> <p>So I know it's a <code>method</code> f...
3
2016-10-19T08:47:17Z
40,126,548
<p>I don't think there is special variable that defines some function as in-place but a standard function should have a doc string that says that it is in-place and does not return any value. For example:</p> <p><code>&gt;&gt;&gt; print(shuffle.__doc__)</code></p> <p><code>Shuffle list x in place, and return None.</c...
2
2016-10-19T08:54:13Z
[ "python", "function", "python-3.x" ]
Split and shift RGB channels in Python
40,126,407
<p>What I'm trying to do is recreating what is commonly called an "RGB shift" effect, which is very easy to achieve with image manipulation programs. </p> <p>I imagine I can "split" the channels of the image by either opening the image as a matrix of triples or opening the image three times and every time operate just...
-1
2016-10-19T08:47:26Z
40,127,791
<p>Per color plane, replace the pixel at <code>(X, Y)</code> by the pixel at <code>(X-1, Y+3)</code>, for example. (Of course your shifts will be different.)</p> <p>You can do that in-place, taking care to loop by increasing or decreasing coordinate to avoid overwriting.</p> <p>There is no need to worry about transpa...
2
2016-10-19T09:46:49Z
[ "python", "image", "image-processing", "rgb" ]
Tkinter how to update second combobox automatically according this combobox
40,126,449
<p>I have encountered an issue with combobox updates in Tkinter Python.</p> <p>I have two comboboxes:</p> <ul> <li>combobox <code>A</code> with <code>values =['A','B','C']</code> and</li> <li>combobox <code>B</code></li> </ul> <p>What i want is that:</p> <ul> <li><p>when value <code>A</code> is selected in combobox...
0
2016-10-19T08:49:31Z
40,128,032
<p>Actually you don't need the global variable <code>ListB</code>. And you need to add <code>comboboxB.config(values=...)</code> at the end of <code>CallHotel()</code> to set the options of <code>comboboxB</code>:</p> <pre><code>def CallHotel(*args): sel = hotel.get() if sel == ListA[0]: ListB = ListB...
2
2016-10-19T09:58:06Z
[ "python", "tkinter", "combobox" ]
How to generate effectively a random number that only contains unique digits in Python?
40,126,683
<pre><code>import random def get_number(size): result = [random.randint(1,9)] digits = list(range(0,10)) digits.remove(result[0]) if(size &gt; 1): result += random.sample(digits,size-1) return ''.join(map(str,result)) print(get_number(4)) </code></pre> <p>I solved the problem, but I feel that it's clum...
3
2016-10-19T08:59:45Z
40,127,616
<p>Shuffle is the way to go as suggested by @jonrsharpe:</p> <pre><code>import random def get_number(size): l = [ str(i) for i in list(range(10))] while l[0] == '0': random.shuffle(l) return int("".join(l[:size])) </code></pre> <p>Limits:</p> <ul> <li>is you ask for a number of more than 10 digi...
1
2016-10-19T09:38:31Z
[ "python", "list", "random" ]
How to generate effectively a random number that only contains unique digits in Python?
40,126,683
<pre><code>import random def get_number(size): result = [random.randint(1,9)] digits = list(range(0,10)) digits.remove(result[0]) if(size &gt; 1): result += random.sample(digits,size-1) return ''.join(map(str,result)) print(get_number(4)) </code></pre> <p>I solved the problem, but I feel that it's clum...
3
2016-10-19T08:59:45Z
40,128,849
<p>Just use shuffle:</p> <pre><code>import string x = list(string.digits) random.shuffle(x) print int(str(random.choice(range(1, 10))) + "".join(x[:3])) </code></pre>
0
2016-10-19T10:32:09Z
[ "python", "list", "random" ]
Convert full month and day name to short ones
40,126,811
<p>I have a series of dates of this format: <code>'2015 08 01'</code> or <code>'2015 12 11'</code> and I want to convert them to this format: <code>'2015 8 1'</code> or <code>'2015 12 11'</code>. Basically, if the month and day sub-strings have a 0 at the start, that should be eliminated.</p> <p>For example: The <code...
0
2016-10-19T09:04:32Z
40,126,845
<p>it should be <code>d</code>:</p> <pre><code>&gt;&gt;&gt; data_conv = datetime.strptime(str_date, "%Y %m %d") &gt;&gt;&gt; data_conv datetime.datetime(2015, 8, 1, 0, 0) </code></pre>
1
2016-10-19T09:06:00Z
[ "python", "datetime" ]
Convert full month and day name to short ones
40,126,811
<p>I have a series of dates of this format: <code>'2015 08 01'</code> or <code>'2015 12 11'</code> and I want to convert them to this format: <code>'2015 8 1'</code> or <code>'2015 12 11'</code>. Basically, if the month and day sub-strings have a 0 at the start, that should be eliminated.</p> <p>For example: The <code...
0
2016-10-19T09:04:32Z
40,127,119
<p>Just remove the leading zeroes:</p> <pre><code>' '.join([x.lstrip('0') for x in str_date.split()]) </code></pre>
2
2016-10-19T09:17:42Z
[ "python", "datetime" ]
Fastest way to build a Matrix with a custom architecture
40,126,853
<p>What's the fastest way in numpy or pandas to build a matrix that has this form:</p> <pre><code>1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 </code></pre> <p>That preserves both odd and even architectures?</p>
2
2016-10-19T09:06:18Z
40,127,020
<p>Using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy brodacasting</code></a>!</p> <pre><code>In [289]: a = np.array([1,2,3,2,1]) In [290]: np.minimum(a[:,None],a) Out[290]: array([[1, 1, 1, 1, 1], [1, 2, 2, 2, 1], [1, 2, 3, 2, 1], [1, 2, 2,...
5
2016-10-19T09:12:56Z
[ "python", "pandas", "numpy" ]
Dump database table or work remotely for analysis?
40,126,979
<p>I have a table of <strong>80 million</strong> rows and I was given the task to do some light analysis like finding patterns for fields, which fields are mutually exclusive etc.</p> <p>My initial instinct was to dump the whole table into a CSV so I can work with Pandas or similar since I assumed it would be faster a...
0
2016-10-19T09:11:30Z
40,128,138
<p>Directly on the database with SQL is perfectly fine for any analysis <em>when you already know what you're looking for</em>.</p> <p>When you don't know what you're looking for, and you want to do e.g. pattern recognition, the effort to dump and process in another tool is probably worth it.</p> <p>Also consider the...
0
2016-10-19T10:02:21Z
[ "python", "oracle", "pandas", "data-analysis" ]
Remove illegal edges from the permuation set (python)
40,126,993
<p>I am trying to apply brute-force method to find the shortest path between an origin and a destination node (OD pair). I create the network using networkX and call the permutations followed by the application of brute force. <br/>If all the nodes in the network are connected with all others, this is ok. But if some o...
0
2016-10-19T09:11:53Z
40,132,174
<p>Exact solution for general TSP is recognized as non-polynomial. Enumerating all permutations, being the most straight-forward approach, is valid despite of its <code>O(n!)</code> complexity. Refer to <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem" rel="nofollow">wikipedia page of TSP</a> for more...
0
2016-10-19T13:02:06Z
[ "python", "shortest-path", "brute-force" ]
NetworkX: how to properly create a dictionary of edge lengths?
40,127,350
<p>Say I have a regular grid network made of <code>10x10</code> nodes which I create like this:</p> <pre><code>import networkx as nx from pylab import * import matplotlib.pyplot as plt %pylab inline ncols=10 N=10 #Nodes per side G=nx.grid_2d_graph(N,N) labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() ...
0
2016-10-19T09:26:42Z
40,127,920
<p>There is a lot going wrong in the last line, first and foremost that G.edges() is an iterator and not a valid dictionary key, and secondly, that G.edges() really just yields the edges, not the positions of the nodes.</p> <p>This is what you want instead: </p> <pre><code>lengths = dict() for source, target in G.edg...
1
2016-10-19T09:53:04Z
[ "python", "dictionary", "networkx" ]
Machine Learning Prediction - why and when beginning with PCA?
40,127,381
<p>From a very general point of view, when you have a dataset X and want to predict a label Y, what is the purpose of beginning with a PCA (principal component analysis) first, and then doing the prediction itself (with logistic regression , or random forest or whatever) from both intuitive and theoretical reason ? In ...
-2
2016-10-19T09:28:07Z
40,128,239
<p>I assume you mean PCA-based dimensionality reduction. Low-variance data often, but not always, has little predictive power, so removing low-variance dimensions of your dataset can be an effective way of improving predictor running time. In cases where it raises the signal to noise ratio, it can even improve predicti...
0
2016-10-19T10:06:31Z
[ "python", "machine-learning", "pca", "prediction" ]
Deleting blank rows and rows with text in them at the same time
40,127,532
<p>New to programming here. After going through google and the forums (aswell as much trial and error), I couldn't find a neat solution to my problem.</p> <p>I'd like to delete a few initial rows (first 10 rows) in my spreadsheet/CSV file and while I did find the solution to that using:</p> <pre><code> all(next(re...
0
2016-10-19T09:34:26Z
40,127,855
<p>Your for loop is just iterating over <em>filecsv</em>. It's not doing anything. You want something like</p> <p><code>non_blank_rows = [] for row in filecsv: if row: # empty strings are false-y non_blank_rows.append(row)</code></p> <p>Now at this point you could just set filecsv to be non_blank_rows. N...
0
2016-10-19T09:50:04Z
[ "python", "csv", "rows" ]
Deleting blank rows and rows with text in them at the same time
40,127,532
<p>New to programming here. After going through google and the forums (aswell as much trial and error), I couldn't find a neat solution to my problem.</p> <p>I'd like to delete a few initial rows (first 10 rows) in my spreadsheet/CSV file and while I did find the solution to that using:</p> <pre><code> all(next(re...
0
2016-10-19T09:34:26Z
40,128,698
<p>you can use as fallowing for writing new csv file after deleting particuler row's </p> <pre><code>import csv #read csv file csvfile = open('/home/17082016_ExpiryReport.csv', 'rb') filecsv = csv.reader(csvfile, delimiter=",") #following line increment pointer for blank line also up to range 10 lines [next(filecs...
0
2016-10-19T10:26:13Z
[ "python", "csv", "rows" ]
How to get latest unique entries from sqlite db with the counter of entries via Django ORM
40,127,698
<p>I have a SQLite db which looks like this:</p> <pre><code>|ID|DateTime|Lang|Details| |1 |16 Oct | GB | GB1 | |2 |15 Oct | GB | GB2 | |3 |17 Oct | ES | ES1 | |4 |13 Oct | ES | ES2 | |5 |15 Oct | ES | ES3 | |6 |10 Oct | CH | CH1 | </code></pre> <p>I need a Django query to select this:</p> <pre><cod...
-1
2016-10-19T09:42:32Z
40,128,426
<p>You can use Django annotate() and value() together: <a href="https://docs.djangoproject.com/el/1.10/topics/db/aggregation/#values" rel="nofollow">link</a>. </p> <blockquote> <p>when a values() clause is used to constrain the columns that are returned in the result set, the method for evaluating annotations is sli...
0
2016-10-19T10:14:17Z
[ "python", "django", "sqlite", "django-orm" ]
How to get latest unique entries from sqlite db with the counter of entries via Django ORM
40,127,698
<p>I have a SQLite db which looks like this:</p> <pre><code>|ID|DateTime|Lang|Details| |1 |16 Oct | GB | GB1 | |2 |15 Oct | GB | GB2 | |3 |17 Oct | ES | ES1 | |4 |13 Oct | ES | ES2 | |5 |15 Oct | ES | ES3 | |6 |10 Oct | CH | CH1 | </code></pre> <p>I need a Django query to select this:</p> <pre><cod...
-1
2016-10-19T09:42:32Z
40,129,564
<p>As you want distinct entries by "Lang" and latest entries by "DateTime", below query will help you,</p> <p>queryset = Model.objects.distinct("Lang").order_by("-DateTime")</p>
0
2016-10-19T11:01:15Z
[ "python", "django", "sqlite", "django-orm" ]
python , launch an external program with ulimit
40,127,732
<p>I need to launch an external program from my python script. This program crashes, so I need to get a core dump from it.</p> <p>what can i do?</p>
0
2016-10-19T09:44:27Z
40,127,861
<p>Check out the python <a href="https://docs.python.org/2.7/library/resource.html?highlight=resource#module-resource" rel="nofollow">resource</a> module. It will let you set the size of core files, etc., just like the ulimit command. Specifically, you want to do something like</p> <pre><code>resource.setrlimit(resour...
0
2016-10-19T09:50:09Z
[ "python", "ulimit" ]
Dictionary keys cannot be encoded as utf-8
40,127,739
<p>I am using the twitter streaming api (tweepy) to capture several tweets. I do this in python2.7. </p> <p>After I have collected a corpus of tweets I break each tweet into words and add each word to a dictionary as keys, where the values are the participation of each word in <code>positive</code> or <code>negative</...
0
2016-10-19T09:44:42Z
40,127,892
<p>Note that the error message says "'ascii' codec can't <strong>decode</strong> ...". That's because when you call <code>encode</code> on something that is already a bytestring in Python 2, it tries to decode it to Unicode first using the default codec.</p> <p>I'm not sure why you thought that encoding again would be...
1
2016-10-19T09:51:34Z
[ "python", "python-2.7", "encoding", "utf-8", "tweepy" ]
Dictionary keys cannot be encoded as utf-8
40,127,739
<p>I am using the twitter streaming api (tweepy) to capture several tweets. I do this in python2.7. </p> <p>After I have collected a corpus of tweets I break each tweet into words and add each word to a dictionary as keys, where the values are the participation of each word in <code>positive</code> or <code>negative</...
0
2016-10-19T09:44:42Z
40,127,946
<p>You get a <strong>decode</strong> error while you are trying to <strong>encode</strong> a string. This seems weird but it is due to implicit decode/encode mechanism of Python.</p> <p>Python allows to encode strings to obtain bytes and decode bytes to obtain strings. This means that Python can encode only strings an...
1
2016-10-19T09:54:26Z
[ "python", "python-2.7", "encoding", "utf-8", "tweepy" ]
merge two plot to one graph
40,127,746
<p>I have two dataframe, and I plot both of them. one is for female and the other for male.</p> <p><a href="https://i.stack.imgur.com/z7VwO.png" rel="nofollow"><img src="https://i.stack.imgur.com/z7VwO.png" alt="enter image description here"></a></p> <p>I want merge them in one graph with different color (since they ...
1
2016-10-19T09:44:57Z
40,128,333
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html" rel="nofollow"><code>DataFrame.plot.bar</code></a> with transposing <code>DataFrame</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow"><code...
1
2016-10-19T10:10:27Z
[ "python", "pandas", "matplotlib", "plot", "dataframe" ]
Why do I get garbage in the file when using "w+" instead of "a+" when the filehandles are stored in a Dict?
40,127,987
<p>I wrote a function that takes a list of items with several fields and write each item to one or several files depending on the content of some of the fields.</p> <p>The name of the files is based on the content of those fields, so for example an item with value <code>AAA</code> in the field <code>rating</code> and ...
0
2016-10-19T09:55:53Z
40,128,156
<p>You are <em>reopening</em> the file objects each time in the loop, even if already present in the dictionary. The expression:</p> <pre><code>mailLists.setdefault(filenameA,open(filenameA,"w+")) </code></pre> <p>opens the file <em>first</em>, as both arguments to <code>setdefault()</code> need to be available. Usin...
1
2016-10-19T10:03:04Z
[ "python", "io" ]
Tkinter Class structure (class per frame) issue with duplicating widgets
40,128,061
<p>Ive been trying out OOP for use with Tkinter - Im getting there (I think) slowly...</p> <p>I wanted to build a structure where each frame is handled by its own class, including all of its widgets and functions. Perhaps I am coming from the wrong angle but that is what makes most logical sense to me. - Feel free to ...
0
2016-10-19T09:59:27Z
40,130,619
<p>Your use of OOP is not very logical here. Your main program is in the class GUI_start. If your pages inherit from GUI_start, basically you create a whole new program with every page instance you create. You should instead inherit from Frame as Bryan Oakley has pointed our in the comments. Here is a somewhat repaired...
1
2016-10-19T11:49:08Z
[ "python", "python-2.7", "class", "oop", "tkinter" ]
Tkinter Class structure (class per frame) issue with duplicating widgets
40,128,061
<p>Ive been trying out OOP for use with Tkinter - Im getting there (I think) slowly...</p> <p>I wanted to build a structure where each frame is handled by its own class, including all of its widgets and functions. Perhaps I am coming from the wrong angle but that is what makes most logical sense to me. - Feel free to ...
0
2016-10-19T09:59:27Z
40,132,323
<p>The point of using classes is to encapsulate a bunch of behavior as a single unit. An object shouldn't modify anything outside of itself. At least, not by simply creating the object -- you can have methods that can have side effects.</p> <p>In my opinion, the proper way to create "pages" is to inherit from <code>Fr...
1
2016-10-19T13:08:59Z
[ "python", "python-2.7", "class", "oop", "tkinter" ]
Jython : SyntaxError: Lexical error at line 29, column 32. Encountered: "$" (36), after : ""
40,128,264
<p>I am getting a syntax error in my code. Can anyone say what's wrong in the syntax? I am new to this language, don't have much of an idea.</p> <p>Error Message:</p> <h2>WASX7017E: Exception received while running file "jdbcConn.jy"; exception information: com.ibm.bsf.BSFException: exception from Jython: Traceback (...
0
2016-10-19T10:07:29Z
40,128,315
<p>Change this line</p> <pre><code>classpath = ["classpath" , ${ORACLE_JDBC_DRIVER_PATH}/ojdbc6.jar ] </code></pre> <p>to this:</p> <pre><code>classpath = ["classpath" , "${ORACLE_JDBC_DRIVER_PATH}/ojdbc6.jar" ] </code></pre> <p>or better yet, just delete that line. Anyways, classpath is declared again later to the...
0
2016-10-19T10:09:50Z
[ "python", "jython" ]
Jython : SyntaxError: Lexical error at line 29, column 32. Encountered: "$" (36), after : ""
40,128,264
<p>I am getting a syntax error in my code. Can anyone say what's wrong in the syntax? I am new to this language, don't have much of an idea.</p> <p>Error Message:</p> <h2>WASX7017E: Exception received while running file "jdbcConn.jy"; exception information: com.ibm.bsf.BSFException: exception from Jython: Traceback (...
0
2016-10-19T10:07:29Z
40,128,362
<p>Your problem is in this line:</p> <pre><code>classpath = ["classpath" , ${ORACLE_JDBC_DRIVER_PATH}/ojdbc6.jar ] </code></pre> <p>Instead, do something like</p> <pre><code>opath = os.getenv("ORACLE_JDBC_DRIVER_PATH") classpath = ["classpath", "{}/ojdbc6.jar".format(opath)] </code></pre> <p>"${ORACLE_JDBC_DRIVER_P...
2
2016-10-19T10:11:24Z
[ "python", "jython" ]
Request returns partial page
40,128,383
<p>I'm trying to parse data of a website that loads when user scroll. There is a finite number of element that can appears while scrolling, but using this only gives the first part (25 out of 112):</p> <pre><code>url = "http://url/to/website" response = requests.get(url) soup = BeautifulSoup(response.text) </code></pr...
1
2016-10-19T10:12:24Z
40,128,528
<p>You can't. The question is based on a misunderstanding of what requests does; it loads the content of the page only. Endless scrolling is powered by Javascript, which requests won't do anything with.</p> <p>You'd need some browser automation tools like Selenium to do this; or find out what Ajax endpoint the scrolli...
4
2016-10-19T10:18:52Z
[ "python", "beautifulsoup", "python-requests" ]
Request returns partial page
40,128,383
<p>I'm trying to parse data of a website that loads when user scroll. There is a finite number of element that can appears while scrolling, but using this only gives the first part (25 out of 112):</p> <pre><code>url = "http://url/to/website" response = requests.get(url) soup = BeautifulSoup(response.text) </code></pr...
1
2016-10-19T10:12:24Z
40,128,869
<blockquote> <p>The only thing you should know is how serverlet works.</p> </blockquote> <p>Usually, <code>onScroll</code> or <code>onClick</code> or any other event will trigger <code>AJAX request</code> to the server. And the client side javascript will render those return (JSON/XML...) So the only thing you shoul...
2
2016-10-19T10:32:57Z
[ "python", "beautifulsoup", "python-requests" ]
Replace 0 with blank in dataframe Python pandas
40,128,388
<p>I made the following code that takes out all of the zero's from my df. However when there is a number containing a zero it takes them out as well.</p> <pre><code>e.g. 3016.2 316.2 0.235 .235 data_usage_df['Data Volume (MB)'] = data_usage_df['Data Volume (MB)'].str.replace('0', '') </code></pre> <p>Co...
1
2016-10-19T10:12:36Z
40,128,403
<p>I think you need add <code>^</code> for matching start of string and <code>$</code> for end of string:</p> <pre><code>data_usage_df['Data Volume (MB)']=data_usage_df['Data Volume (MB)'].str.replace('^0.0$', '') </code></pre> <p>Sample:</p> <pre><code>data_usage_df = pd.DataFrame({'Data Volume (MB)':[3016.2, 0.235...
0
2016-10-19T10:13:26Z
[ "python", "pandas", "replace" ]
Replace 0 with blank in dataframe Python pandas
40,128,388
<p>I made the following code that takes out all of the zero's from my df. However when there is a number containing a zero it takes them out as well.</p> <pre><code>e.g. 3016.2 316.2 0.235 .235 data_usage_df['Data Volume (MB)'] = data_usage_df['Data Volume (MB)'].str.replace('0', '') </code></pre> <p>Co...
1
2016-10-19T10:12:36Z
40,130,624
<pre><code>data_usage_df = data_usage_df.astype(str) data_usage_df['Data Volume (MB)'].replace(['0', '0.0'], '', inplace=True) </code></pre>
0
2016-10-19T11:49:17Z
[ "python", "pandas", "replace" ]
pairwise comparisons within a dataset
40,128,515
<p>My data is 18 vectors each with upto 200 numbers but some with 5 or other numbers.. organised as:</p> <pre><code>[2, 3, 35, 63, 64, 298, 523, 624, 625, 626, 823, 824] [2, 752, 753, 808, 843] [2, 752, 753, 843] [2, 752, 753, 808, 843] [3, 36, 37, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91...
1
2016-10-19T10:18:05Z
40,129,621
<p>You can use <code>itertools</code> to generate your pairwise comparisons. If you just want the items which are shared between two lists you can use a <code>set</code> intersection. Using your example:</p> <pre class="lang-python prettyprint-override"><code>import itertools a = [2, 3, 35, 63, 64, 298, 523, 624, 625...
1
2016-10-19T11:03:19Z
[ "python", "python-2.7", "numpy", "scipy", "cosine-similarity" ]
Index data from not related models in Django-Haystack Solr
40,128,623
<p>I have a model to which multiple other models point through foreign keys, like:</p> <pre><code>class MainModel(models.Model): name=models.CharField(max_length=40) class PointingModel1(models.Model): color=models.CharField(max_length=40) main_model=models.ForeignKey(MainModel) class PointingModel2(mode...
0
2016-10-19T10:22:33Z
40,128,761
<p>It's easy.</p> <pre><code>colors = PointingModel1.objects.filter(color='blue') for color in colors: name = color.main_model.name # now you can put `name` to a list or something else </code></pre>
0
2016-10-19T10:29:06Z
[ "python", "django", "solr" ]
Pyspark adding few seconds to time
40,128,673
<p>I am trying to add few seconds to time but I haven't been successful. Here is my example</p> <pre><code>import datetime str1 = sc.parallelize(["170745","140840"]) aa = str1.map(lambda l: datetime.datetime.strptime(l, '%H%M%S').strftime('%H:%M:%S')) </code></pre> <p>yields</p> <pre><code>['17:07:45', '14:08:40'] ...
1
2016-10-19T10:24:56Z
40,131,911
<p>You can add <code>datetime.timedelta(0,7)</code> after you have convert your string to dates:</p> <pre><code>import datetime str1 = sc.parallelize(["170745","140840"]) aa = str1.map(lambda l: (datetime.datetime.strptime(l, '%H%M%S') + datetime.timedelta(0,7)).strftime('%H:%M:%S')) </code></pre> <p><code>aa.collect...
1
2016-10-19T12:51:29Z
[ "python", "datetime", "pyspark" ]
Pyspark adding few seconds to time
40,128,673
<p>I am trying to add few seconds to time but I haven't been successful. Here is my example</p> <pre><code>import datetime str1 = sc.parallelize(["170745","140840"]) aa = str1.map(lambda l: datetime.datetime.strptime(l, '%H%M%S').strftime('%H:%M:%S')) </code></pre> <p>yields</p> <pre><code>['17:07:45', '14:08:40'] ...
1
2016-10-19T10:24:56Z
40,132,741
<p>You can use "+datetime.timedelta(seconds=7)" to solve this problem.</p> <pre><code>(datetime.datetime.strptime(l, '%H%M%S') + datetime.timedelta(seconds=7)).strftime('%H:%M:%S') </code></pre> <p>If you want to calculates the number of seconds between two times, minus two datetime.datetime object directly.</p> <pr...
0
2016-10-19T13:25:41Z
[ "python", "datetime", "pyspark" ]
Pythonista user- initiated programs do not run
40,128,684
<p>Hi I am using Pythonista 3:0 on the ipad. As a beginner I downloaded examples to try out. They worked for a while but now lwhen I try to run them there is no response. All the sample programs in the original Phthonista install work perfectly. </p> <p>This for example does not work. Nothing happens when I press th...
0
2016-10-19T10:25:40Z
40,132,180
<p>In my opinion, matplotlib of Pythonista might be upgraded from 0.9x to 1.x. You should use different syntax as follows.</p> <pre><code># -*- coding: utf-8 -*- import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from itertools import product, combinations fig = plt.figure() ax...
0
2016-10-19T13:02:17Z
[ "python", "ipad", "matplotlib", "pythonista" ]
NetworkX: how to add weights to an existing G.edges()?
40,128,692
<p>Given any graph G created in NetworkX, I want to be able to assign some weights to G.edges() <strong>after</strong> the graph is created. The graphs involved are grids, erdos-reyni, barabasi-albert, and so forth. </p> <p>Given my <code>G.edges()</code>:</p> <pre><code>[(0, 1), (0, 10), (1, 11), (1, 2), (2, 3), (2...
1
2016-10-19T10:25:59Z
40,129,408
<p>It fails because <code>edges</code> is a method.</p> <p>The <a href="https://networkx.github.io/documentation/development/reference/generated/networkx.Graph.get_edge_data.html" rel="nofollow">documentation</a> says to do this like:</p> <pre><code>G[source][target]['weight'] = weight </code></pre> <p>For example, ...
1
2016-10-19T10:55:15Z
[ "python", "algorithm", "graph", "networkx", "edges" ]
Semi-supervised learning for regression by scikit-learn
40,128,742
<p>Can Label Propagation be used for semi-supervised regression tasks in scikit-learn? According to its API, the answer is YES. <a href="http://scikit-learn.org/stable/modules/label_propagation.html" rel="nofollow">http://scikit-learn.org/stable/modules/label_propagation.html</a></p> <p>However, I got the error messag...
1
2016-10-19T10:28:19Z
40,140,691
<p>It looks like the error in the documentation, code itself clearly is classification only (beggining of the <code>.fit</code> call of the <a href="https://github.com/scikit-learn/scikit-learn/blob/412996f/sklearn/semi_supervised/label_propagation.py#L201" rel="nofollow">BasePropagation class</a>):</p> <pre><code> ...
0
2016-10-19T20:13:14Z
[ "python", "machine-learning", "scikit-learn", "regression" ]
How to create xml in Python dynamically?
40,128,776
<p>import xml.etree.ElementTree as ET</p> <pre><code> var3 = raw_input("Enter the root Element: \n") root = ET.Element(var3) var4 = raw_input("Enter the sub root Element: \n") doc = ET.SubElement(root, var4) no_of_rows=input("Enter the number of Element for XML files: - \n") def printme(): var = raw...
0
2016-10-19T10:29:34Z
40,129,499
<p>You are taking no. of elements from user but you are not using it. Use a loop and get element details from user within the loop as shown below: </p> <pre><code>import xml.etree.ElementTree as ET try: no_of_rows=int(input("Enter the number of Element for XML files: - \n")) root = input("Enter the root Ele...
0
2016-10-19T10:58:37Z
[ "python", "xml" ]
How to create xml in Python dynamically?
40,128,776
<p>import xml.etree.ElementTree as ET</p> <pre><code> var3 = raw_input("Enter the root Element: \n") root = ET.Element(var3) var4 = raw_input("Enter the sub root Element: \n") doc = ET.SubElement(root, var4) no_of_rows=input("Enter the number of Element for XML files: - \n") def printme(): var = raw...
0
2016-10-19T10:29:34Z
40,129,571
<p>If you want create xml you may just do this:</p> <pre><code>from lxml import etree try: root_text = raw_input("Enter the root Element: \n") root = etree.Element(root_text) child_tag = raw_input("Enter the child tag Element: \n") child_text = raw_input("Enter the child text Element: \n") child = etree...
-1
2016-10-19T11:01:38Z
[ "python", "xml" ]