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 |
|---|---|---|---|---|---|---|---|---|---|
graphlab create sframe combine two column | 39,091,454 | <p>I have two columns with strings. let's say col1 and col2
now how can we combine the content of col1 and col2 into col3 with graphlab SFrame? </p>
<pre><code>col1 col2
23 33
42 11
........
</code></pre>
<p>into </p>
<pre><code>col3
23,33
42,11
....
</code></pre>
<p>unstack will only give sarray or dict, i only one a bag of words</p>
<p>tried </p>
<pre><code>user_info['X5']=user_info['X3'].apply(lambda x:x+','+user_info['X4'].apply(lambda y:y))
</code></pre>
<p>doesnt seem to be right</p>
<p>any idea?</p>
| 0 | 2016-08-23T02:35:49Z | 39,091,575 | <p>Using pandas:</p>
<pre><code>In [271]: df
Out[271]:
col1 col2
0 23 33
1 42 11
In [272]: df['col3'] = (df['col1'].map(str) + ',' + df['col2'].map(str))
In [273]: df
Out[273]:
col1 col2 col3
0 23 33 23,33
1 42 11 42,11
</code></pre>
<p>Using graphlab:</p>
<pre><code>In [17]: sf
Out[17]:
Columns:
col1 int
col2 int
Rows: 2
Data:
+------+------+
| col1 | col2 |
+------+------+
| 23 | 33 |
| 42 | 11 |
+------+------+
[2 rows x 2 columns]
In [18]: sf['col3'] = sf['col1'].apply(str) + ',' + sf['col2'].apply(str)
In [19]: sf
Out[19]:
Columns:
col1 int
col2 int
col3 str
Rows: 2
Data:
+------+------+-------+
| col1 | col2 | col3 |
+------+------+-------+
| 23 | 33 | 23,33 |
| 42 | 11 | 42,11 |
+------+------+-------+
[2 rows x 3 columns]
</code></pre>
| 1 | 2016-08-23T02:51:20Z | [
"python",
"pandas",
"graphlab"
] |
parsing output from command call | 39,091,469 | <p>So I'm trying to execute a shell command from python and then either store it in an array or directly parse the piped shell command.</p>
<p>I am piping the shell data via the subprocess command and verified the output using print statement and it worked just fine.</p>
<pre><code>a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read()
print(b)
</code></pre>
<p>Now, I am trying to parse out data out of an unknown amount of rows and 6 columns. Since b should be one long string, I tried to parse the string and store the salient characters into another array to be used however I want to analyze the data.</p>
<pre><code>i = 0
a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read()
for line in b.split("\n\n"): #to scan each row with a blank line separating each row
salient_Chars[i, 0] = line.split(" ")[3] #stores the third set of characters and stops at the next blank space
salient_Chars2[i, 0] = line.split(" ")[4] #stores the fourth set of characters and stops at the next blank space
i = i + 1
</code></pre>
<p>I get an error [TypeError: a bytes-like object is required, not 'str']. I searched this error and it means that I stored bytes and not a string using the Popen which I am not sure why since I verified it was a string with the print command. I tried using check_output after searching for how to pipe shell commands into a string.</p>
<pre><code>from subprocess import check_output
a = check_output('file/path/command')
</code></pre>
<p>This gives me a permission error so I would like to use Popen command if possible.</p>
<p>How do I get the piped shell command into a string and then how do I properly parse through a string that is divided into rows and columns with spaces in between columns and blank lines in between rows? </p>
| 2 | 2016-08-23T02:37:38Z | 39,104,350 | <p>Quoting <a href="http://stackoverflow.com/users/2603/aaron-maenpaa">Aaron Maenpaa</a>'s <a href="http://stackoverflow.com/a/606199/4396006">answer</a>:</p>
<blockquote>
<p>You need to decode the bytes object to produce a string:</p>
<pre><code>>>> b"abcde"
b'abcde'
# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8")
'abcde'
</code></pre>
</blockquote>
<p>Therefore your code would look like:</p>
<pre><code>i = 0
a = subprocess.Popen('filepath/command', shell=True, stdout=subprocess.PIPE)
b = a.stdout.read().decode("utf-8") # note the decode method
for line in b.split("\n\n"): #to scan each row with a blank line separating each row
salient_Chars[i, 0] = line.split(" ")[3] #stores the third set of characters and stops at the next blank space
salient_Chars2[i, 0] = line.split(" ")[4] #stores the fourth set of characters and stops at the next blank space
i = i + 1
</code></pre>
<p>By the way, I don't really understand your parsing code, that will give you a <code>TypeError: list indices must be integers, not tuple</code> since you are passing a tuple to the list index in <code>salient_Chars</code> (assuming it is a list). </p>
<h2>Edit</h2>
<p>Note that calling the <code>print</code> built-in method is <em>not</em> a way of checking whether the arguments passed are a plain string-type object. From the OP from the quoted answer:</p>
<blockquote>
<p>The communicate() method returns an array of bytes:</p>
<pre><code>>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
</code></pre>
<p>However, I'd like to work with the output as a normal Python string.
So that I could print it like this:</p>
<pre><code>>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
</code></pre>
</blockquote>
| 1 | 2016-08-23T14:46:55Z | [
"python",
"string",
"subprocess",
"stdout",
"popen"
] |
matplotlib does not show legend in scatter plot | 39,091,515 | <p>I am trying to work on a clustering problem for which I need to plot a scatter plot for my clusters.</p>
<pre><code>%matplotlib inline
import matplotlib.pyplot as plt
df = pd.merge(dataframe,actual_cluster)
plt.scatter(df['x'], df['y'], c=df['cluster'])
plt.legend()
plt.show()
</code></pre>
<blockquote>
<p>df['cluster'] is the actual cluster number. So I want that to be my color code.</p>
</blockquote>
<p><a href="http://i.stack.imgur.com/pLqDt.png" rel="nofollow"><img src="http://i.stack.imgur.com/pLqDt.png" alt="enter image description here"></a></p>
<p>It shows me a plot but it does not show me the legend. it does not give me error as well.</p>
<p>Am I doing something wrong?</p>
| 0 | 2016-08-23T02:43:43Z | 39,091,893 | <p><strong>EDIT:</strong></p>
<p>Generating some random data:</p>
<pre><code>from scipy.cluster.vq import kmeans2
n_clusters = 10
df = pd.DataFrame({'x':np.random.randn(1000), 'y':np.random.randn(1000)})
_, df['cluster'] = kmeans2(df, n_clusters)
</code></pre>
<p>Plotting:</p>
<pre><code>fig, ax = plt.subplots()
cmap = plt.cm.get_cmap('jet')
for i, cluster in df.groupby('cluster'):
_ = ax.scatter(cluster['x'], cluster['y'], c=cmap(i/n_clusters), label=i)
ax.legend()
</code></pre>
<p>Result:</p>
<p><a href="http://i.stack.imgur.com/r6Av0.png" rel="nofollow"><img src="http://i.stack.imgur.com/r6Av0.png" alt="enter image description here"></a>
Explanation:</p>
<p>Not going into too much into nitty gritty details of matplotlib internals, plotting one cluster at a time sort of solves the issue.
More specifically, <code>ax.scatter()</code> returns a <code>PathCollection</code> object which we are explicitly throwing away here but which <em>seems to</em> be passed internally to some sort of legend handler. Plotting all at once generates only one <code>PathCollection</code>/label pair, while plotting one cluster at a time generates <code>n_clusters</code> <code>PathCollection</code>/label pairs. You can see those objects by calling <code>ax.get_legend_handles_labels()</code> which returns something like:</p>
<pre><code>([<matplotlib.collections.PathCollection at 0x7f60c2ff2ac8>,
<matplotlib.collections.PathCollection at 0x7f60c2ff9d68>,
<matplotlib.collections.PathCollection at 0x7f60c2ff9390>,
<matplotlib.collections.PathCollection at 0x7f60c2f802e8>,
<matplotlib.collections.PathCollection at 0x7f60c2f809b0>,
<matplotlib.collections.PathCollection at 0x7f60c2ff9908>,
<matplotlib.collections.PathCollection at 0x7f60c2f85668>,
<matplotlib.collections.PathCollection at 0x7f60c2f8cc88>,
<matplotlib.collections.PathCollection at 0x7f60c2f8c748>,
<matplotlib.collections.PathCollection at 0x7f60c2f92d30>],
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
</code></pre>
<p>So actually <code>ax.legend()</code> is equivalent to <code>ax.legend(*ax.get_legend_handles_labels())</code>.</p>
<p>NOTES:</p>
<ol>
<li><p>If using Python 2, make sure <code>i/n_clusters</code> is a <code>float</code></p></li>
<li><p>Omitting <code>fig, ax = plt.subplots()</code> and using <code>plt.<method></code> instead
of <code>ax.<method></code> works fine, but I always prefer to explicitly
specify the <code>Axes</code> object I am using rather then implicitly use the
"current axes" (<code>plt.gca()</code>).</p></li>
</ol>
<hr>
<p><strong>OLD SIMPLE SOLUTION</strong></p>
<p>In case you are ok with a colorbar (instead of discrete value labels), you can use Pandas built-in Matplotlib functionality:</p>
<pre><code>df.plot.scatter('x', 'y', c='cluster', cmap='jet')
</code></pre>
<p><a href="http://i.stack.imgur.com/KY85w.png" rel="nofollow"><img src="http://i.stack.imgur.com/KY85w.png" alt="enter image description here"></a></p>
| 0 | 2016-08-23T03:32:17Z | [
"python",
"matplotlib",
"plot",
"cluster-analysis"
] |
Python Flask + AngularJS + DevExtreme | 39,091,519 | <p>First, I am fairly new to javascript but I know my way around python. I am trying to learn javascript and I may be out of my league with trying this, but that is how you learn right.</p>
<p>Secondly, Flask and AngularJS play well together with a little help. Special thanks goes to shea256 (<a href="https://github.com/shea256/angular-flask" rel="nofollow">https://github.com/shea256/angular-flask</a>)</p>
<p>Now, I am able to get the 'test application' up and running fairly easily.</p>
<p>However, I want to add DevExtreme to this stack and I am having some issues.</p>
<p>Here is what I have:</p>
<p>index.html</p>
<pre><code> <!doctype html>
<html lang="en" ng-app="AngularFlask">
<head>
<meta charset="utf-8">
<title>AngularFlask</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/main.css">
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.common.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.light.css" />
<!--<script src="/static/lib/jquery/jquery.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <!--2.7.0-->
<!--<script src="/static/lib/angular/angular.js"></script>
<script src="/static/lib/angular/angular-resource.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-sanitize.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/globalize/0.1.1/globalize.min.js"></script>
<!--<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
-->
<script type="text/javascript" src="http://cdn3.devexpress.com/jslib/16.1.5/js/dx.web.js"></script>
<script src="/static/js/app.js"></script>
<script src="/static/js/controllers.js"></script>
<script src="/static/js/services.js"></script>
<script src="/static/lib/bootstrap/bootstrap.min.js"></script>
</head>
<body>
<div id="header" class="header navbar navbar-static-top">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
</button>
<a class="brand" href="/">AngularFlask</a>
<div class="nav-collapse collapse">
<ul class="nav pull-right">
<li class="">
<a href="/">Home</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="container page">
<div id="content" class="container main" ng-view>
</div>
<hr>
<footer id="footer" class="footer">
<div class="footer-left">
<a href="/about">About</a> |
<a href="/">Home</a>
</div>
<div class="footer-right">
<span>&copy; 2013 AngularFlask</span>
</div>
</footer>
</div>
</body>
</html>
</code></pre>
<p>controllers.js</p>
<pre><code>function IndexController($scope) {
}
function AboutController($scope) {
}
function PostListController($scope, Post) {
var postsQuery = Post.get({}, function(posts) {
$scope.posts = posts.objects;
});
}
function PostDetailController($scope, $routeParams, Post) {
var postQuery = Post.get({ postId: $routeParams.postId }, function(post) {
$scope.post = post;
});
}
</code></pre>
<p>app.js</p>
<pre><code>'use strict';
angular.module('AngularFlask', ['angularFlaskServices', 'dx'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'static/partials/landing.html',
controller: IndexController
})
.when('/about', {
templateUrl: 'static/partials/about.html',
controller: AboutController
})
.when('/post', {
templateUrl: 'static/partials/post-list.html',
controller: PostListController
})
.when('/post/:postId', {
templateUrl: '/static/partials/post-detail.html',
controller: PostDetailController
})
/* Create a "/blog" route that takes the user to the same place as "/post" */
.when('/blog', {
templateUrl: 'static/partials/post-list.html',
controller: PostListController
})
.otherwise({
redirectTo: '/'
})
;
$locationProvider.html5Mode(true);
}])
;
</code></pre>
<p>With this, when I navigate to localhost:5000, this error is reported</p>
<p><a href="https://docs.angularjs.org/error/" rel="nofollow">https://docs.angularjs.org/error/</a>$injector/modulerr?p0=AngularFlask&p1=%5B$injector:unpr%5D%20http:%2F%2Ferrors.angularjs.org%2F1.5.7%2F$injector%2Funpr%3Fp0%3D%2524routeProvider%0AO%2F%3C@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:6:412%0Adb%2Fn.$injector%3C@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:43:84%0Ad@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:40:344%0Ae@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:41:78%0Ah%2F%3C.invoke@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:41:163%0Ad@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:313%0Ag%2F%3C@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:445%0Ar@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:7:353%0Ag@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:39:222%0Adb@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:43:246%0ABc%2Fc@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:20:359%0ABc@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:21:163%0Age@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:19:484%0A@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.7%2Fangular.min.js:315:135%0An.Callbacks%2Fi@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:27444%0An.Callbacks%2Fj.fireWith@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:28213%0A.ready@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:30004%0AK@https:%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.12.4%2Fjquery.min.js:2:30366%0AO%2F%3C()%20angular.min.js:6g%2F%3C()%20angular.min.js:40r()%20angular.min.js:7g()%20angular.min.js:39db()%20angular.min.js:43Bc%2Fc()%20angular.min.js:20Bc()%20angular.min.js:21ge()%20angular.min.js:19%3Canonymous%3E%20angular.min.js:315n.Callbacks%2Fi()%20jquery.min.js:2n.Callbacks%2Fj.fireWith()%20jquery.min.js:2.ready()%20jquery.min.js:2K()%20jquery.min.js:21%20angular.min.js:6:412 </p>
<p>It may be worth mentioning that if I use AngularJS 1.0.7 (included with Angular-Flask) the issue is cleared up until I add my html dev tag</p>
<pre><code><div dx-button="{
text: 'Generate random value'
}"></div>
</code></pre>
<p>then these are the errors:</p>
<pre><code>Error: e.$$postDigest is not a function
Error: t.$root is undefined
Error: a.$watch is not a function
Error: c.$watch is not a function
Error: a.$watch is not a function
Error: t.dxTemplateModel is undefined
</code></pre>
<p>So this tells me that DevExpress is missing some functions in AngularJS 1.0.7; However, when using AngularJS 1.2.X Angular-Flask breaks. Is there anyway to get these two to play well together?</p>
| 1 | 2016-08-23T02:44:06Z | 39,095,838 | <p><a href="http://js.devexpress.com/Documentation/Guide/Common/3rd-Party_Libraries_and_Frameworks_Integration/?version=16_1#Data_Binding_and_SPA_Frameworks" rel="nofollow">DevExtreme supports</a> AngularJS 1.2 - 1.4. Your try to use too old version of AngularJS. Scripts in this <a href="https://github.com/shea256/angular-flask/tree/master/angular_flask/static/lib/angular" rel="nofollow">repo</a> were updated 3 years ago. But you can easily use another angularjs version. Your flask layout can look like below:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }} - My Flask Application</title>
<link rel="stylesheet" type="text/css" href="/static/content/site.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.common.css" />
<link rel="stylesheet" type="text/css" href="http://cdn3.devexpress.com/jslib/16.1.5/css/dx.light.css" />
</head>
<body class="dx-theme-generic-typography" ng-app="myApp">
<div ng-controller="defaultCtrl">
<div dx-button="buttonOptions"></div>
</div>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular-sanitize.js"></script>
<script src="http://cdn3.devexpress.com/jslib/16.1.5/js/dx.all.js"></script>
<script src="/static/scripts/application.js"></script>
</body>
</html>
</code></pre>
<p>And the <code>/static/scripts/application.js</code> file:</p>
<pre><code>var myApp = angular.module("myApp", ["dx"]);
myApp.controller("defaultCtrl", function($scope) {
$scope.buttonOptions = {
text: "My button",
onClick: function(){
alert("Hi!");
}
};
});
</code></pre>
| 1 | 2016-08-23T08:15:46Z | [
"python",
"angularjs",
"flask",
"devexpress"
] |
ImportError: No module named pandas. Pandas installed | 39,091,520 | <p>I am pretty new to programming and am having issues importing pandas to my program. Hoping someone could point me in the right direction to fix this. I am running OSX</p>
<p><strong>regresson.py</strong></p>
<pre><code>import pandas as pd
import Quandl
df = Quandl.get('WIKI/GOOGL')
print df.head
</code></pre>
<p>and am getting the error:</p>
<pre><code>import pandas as pd
ImportError: No module named panda
</code></pre>
<p>I have anaconda on my system.</p>
<p>Pandas 0.17.1</p>
<p>Numpy 1.11.1</p>
<p>Scipy 0.18.0</p>
<p>Pytz 2016.6.1</p>
| -2 | 2016-08-23T02:44:36Z | 39,091,612 | <p>make sure to activate your conda environment </p>
<p>in your terminal-</p>
<pre><code>conda create -n environment_name quandl pandas
cd path_to_env
activate environment_name
(environment_name)conda list (make sure u have the right packages)
(environment_name) your_program.py
</code></pre>
| 0 | 2016-08-23T02:56:21Z | [
"python",
"osx",
"pandas",
"anaconda"
] |
Can't use column name list to create SQLite View in Python | 39,091,581 | <p>I've created a database and am able to create a simple view using the following command:</p>
<pre><code>CREATE VIEW IF NOT EXISTS monthly_terminals (year, month) AS
SELECT reportYear, reportMonth FROM osMonthlyTerminals
</code></pre>
<p>This command works just fine if I paste into the SQLite Manager plugin on FireFox:</p>
<p><a href="http://i.stack.imgur.com/9dmWG.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/9dmWG.jpg" alt="enter image description here"></a></p>
<p>I then drop this view and try to use the exact same command in the following Python 3 code to create this view...</p>
<pre><code>import sqlite3
db_name = "../data/OsReportMerchants.sqlite"
conn = sqlite3.connect(db_name)
cur = conn.cursor()
cur.execute("CREATE VIEW IF NOT EXISTS monthly_terminals (year, month) AS SELECT reportYear, reportMonth FROM osMonthlyTerminals")
</code></pre>
<p>... but I get the following error:</p>
<pre><code>sqlite3.OperationalError: near "(": syntax error
</code></pre>
<p>More specifically, it looks like this in ipython:</p>
<p><a href="http://i.stack.imgur.com/JE56U.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/JE56U.jpg" alt="enter image description here"></a></p>
<p>Yes, I know I should be parameterizing this and I have tried to do so, but keep running into this same snag.</p>
<p>I look at this: <a href="https://www.sqlite.org/lang_createview.html" rel="nofollow">https://www.sqlite.org/lang_createview.html</a> and it says that column lists are supported in 3.9 and later, so I updated to version 3.13 of sqlite3 and still ran into this issue.</p>
<p>When I remove the column list and use this:</p>
<pre><code>import sqlite3
db_name = "../data/OsReportMerchants.sqlite"
conn = sqlite3.connect(db_name)
cur = conn.cursor()
cur.execute("CREATE VIEW IF NOT EXISTS monthly_terminals AS SELECT reportYear, reportMonth FROM osMonthlyTerminals")
</code></pre>
<p>it works fine. Not sure why it works in one context and not in the other.</p>
| 0 | 2016-08-23T02:52:20Z | 39,094,726 | <p>Python has its own copy of the SQLite library (see <code>sqlite3.sqlite_version</code>).</p>
<p>If the latest Python version does not have a recent enough version of SQLite, the only way to update it would be to recompile Python, or use some other DB driver like <a href="https://rogerbinns.github.io/apsw/" rel="nofollow">APSW</a>.</p>
| 1 | 2016-08-23T07:19:19Z | [
"python",
"sqlite3",
"anaconda"
] |
Spotify - Audio Feature exception | 39,091,665 | <p>I've been successufully retrieving <code>audio_features</code> from <code>Spotify</code>'s <code>recommendations</code> <code>endpoint</code>, like so. </p>
<pre><code>features = sp.audio_features(tracks_ids)
</code></pre>
<p>However, if I provide a list of <code>id</code>'s retrieved using <code>search</code> <code>endpoint</code> and pass them in the exact same fashion to <code>sp.audio_features()</code>, I get this:</p>
<p><code>spotipy.client.SpotifyException: http status: 414, code:-1 - https://api.spotify.com/v1/audio-features?ids=2ujuUDGDg6t5zsN6WZ3CFp,2EOThFm0IhwLkdpQzbvunO,40f9IDTMDpFf3CnTcPhY5F,78qoim2GGUkspkxV8kUtVv,4WZJ5W4gZJXvlqgliLkPCn,4mHS76nxzGrwo25KpzQwiX,1jRHh8JcdUV9zTiAmyzhU9...etc</code></p>
<p>is there a different authentication flow? what is going on here?</p>
<p>thanks in advance.</p>
| 0 | 2016-08-23T03:02:02Z | 39,096,859 | <p>You are getting a <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.15" rel="nofollow">414 status code</a>, which indicates that the requested URI is too long.</p>
<p>If you are providing 100 or less ids, then this is a bug on Spotify's end. In this case I would recommend you to file a ticket in their <a href="https://github.com/spotify/web-api/issues" rel="nofollow">GitHub repo</a> where they track issues with the Web API.</p>
| 0 | 2016-08-23T09:05:03Z | [
"python",
"spotify",
"spotipy"
] |
Python Blackjack Count | 39,091,677 | <p>Not so much a problem or question, just wanted to know how other people would approach this. I'm working in python to make a blackjack game through python's class structure and I've made the deck an array with the cards as strings. This helps with the fact that 4 cards are worth 10 in blackjack and an Ace can be worth 1 or 11. But, calculating a hand's value is hard. The deck is in the <strong>init</strong>. How could this be better? I considered a dictionary but that doesn't handle duplicates. Any thoughts are appreciated. Sorry if this is a bad post, I'm new here.</p>
<pre><code> self.deck = [['2']*4, ['3']*4, ['4']*4, ['5']*4, ['6']*4, ['7']*4, \
['8']*4, ['9']*4, ['10']*4, ['J']*4, ['Q']*4, ['K']*4, \
['A']*4]
def bust(self, person):
count = 0
for i in self.cards[person]:
if i == 'A':
count += 1
elif i == '2':
count += 2
elif i == '3':
count += 3
elif i == '4':
count += 4
elif i == '5':
count += 5
elif i == '6':
count += 6
</code></pre>
| 1 | 2016-08-23T03:03:06Z | 39,091,815 | <p>Do yourself a favor, get an explicit map of card values:</p>
<pre><code>CARD_VALUE = {
'2': 2,
'3': 3,
# etc
'A': 1,
'J': 12,
'Q': 13,
'K': 14,
}
# Calculate the value of a hand;
# a hand is a list of cards.
hand_value = sum(CARD_VALUE[card] for card in hand)
</code></pre>
<p>For different games, you can have different value mappings, e.g. with Ace worth 1 or 11. You can put these mappings into a dictionary named by game's name.</p>
<p>Also, I'd not keep my hand representation as a simple list of cards. Instead I'd pack the repeating values using counts:</p>
<pre><code># Naive storage, even unsorted:
hand = ['2', '2', '3', '2', 'Q', 'Q']
# Grouped storage using a {card: count} dictionary:
hand = {'2': 3, '3': 1, 'Q': 2}
# Allows for neat operations
got_a_queen = 'Q' in hand
how_many_twos = hand['2'] # only good for present cards.
how_many_fives = hand.get('5', 0) # 0 returned since '5' not found.
hand_value = sum(CARD_VALUE(card) * hand[card] for card in hand)
</code></pre>
<p>Hope this helps.</p>
| 1 | 2016-08-23T03:22:06Z | [
"python",
"list",
"dictionary",
"blackjack"
] |
Python Blackjack Count | 39,091,677 | <p>Not so much a problem or question, just wanted to know how other people would approach this. I'm working in python to make a blackjack game through python's class structure and I've made the deck an array with the cards as strings. This helps with the fact that 4 cards are worth 10 in blackjack and an Ace can be worth 1 or 11. But, calculating a hand's value is hard. The deck is in the <strong>init</strong>. How could this be better? I considered a dictionary but that doesn't handle duplicates. Any thoughts are appreciated. Sorry if this is a bad post, I'm new here.</p>
<pre><code> self.deck = [['2']*4, ['3']*4, ['4']*4, ['5']*4, ['6']*4, ['7']*4, \
['8']*4, ['9']*4, ['10']*4, ['J']*4, ['Q']*4, ['K']*4, \
['A']*4]
def bust(self, person):
count = 0
for i in self.cards[person]:
if i == 'A':
count += 1
elif i == '2':
count += 2
elif i == '3':
count += 3
elif i == '4':
count += 4
elif i == '5':
count += 5
elif i == '6':
count += 6
</code></pre>
| 1 | 2016-08-23T03:03:06Z | 39,091,825 | <p><a href="http://codereview.stackexchange.com/questions/57849/blackjack-game-with-classes-instead-of-functions">SOURCE</a></p>
<p>So here is what you can do :</p>
<p>Make your deck a string</p>
<pre><code>import random
cards = 'A'*4 + '2'*4 + ... + 'K'*4
self.deck = ''.join(random.sample(cards,len(cards)))
values = {'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'T': 10,
'J': 10,
'Q': 10,
'K': 10
}
</code></pre>
<p>Then you define a hand as a string and use a count method :</p>
<pre><code>def counth(hand):
"""Evaluates the "score" of a given hand. """
count = 0
for i in hand:
if i in values:
count += values[i]
else:
pass
for x in hand:
if x == 'A':
## makes exception for aces
if count + 11 > 21:
count += 1
elif hand.count('A') == 1:
count += 11
else:
count += 1
else:
pass
return count
</code></pre>
| 0 | 2016-08-23T03:23:47Z | [
"python",
"list",
"dictionary",
"blackjack"
] |
regarding using dtype.newbyteorder | 39,091,765 | <p>I once read the following function in a given program, but I am not very clear about what is this function used for? According <code>SciPy.org</code>, </p>
<blockquote>
<p>dtype.newbyteorder(new_order='S')
Return a new dtype with a different byte order.</p>
</blockquote>
<p>I do not quite understand what does it mean?</p>
<pre><code>def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
</code></pre>
| 1 | 2016-08-23T03:16:25Z | 39,093,664 | <p>Here's a simple example:</p>
<pre><code>>>> dt = np.dtype(np.uint32)
>>> val = np.frombuffer(b'\x01\x02\x03\x04', dtype=dt)
>>> hex(val)
'0x4030201'
>>> val2 = np.frombuffer(b'\x01\x02\x03\x04', dtype=dt.newbyteorder('>'))
>>> hex(val2)
'0x1020304'
</code></pre>
<p>Byte order describes which order to pack a series of bytes (in this case, a <code>bytes</code> object from a <code>b"..."</code> literal) into the data type you asked for.</p>
| 0 | 2016-08-23T06:17:36Z | [
"python",
"numpy",
"scipy"
] |
Reviving pandas KeyErrors seemingly at random, without changing my code. Possible memory errors? | 39,091,791 | <p>I'm working through a sklearn tutorial book, that had this section:</p>
<pre><code>Next, we create a TfidfVectorizer. Recall from Chapter 3, Feature Extraction and Preprocessing, that TfidfVectorizer combines CountVectorizer and TfidfTransformer. We fit it with the training messages, and transform both the training and test messages:
>>> vectorizer = TfidfVectorizer()
>>> X_train = vectorizer.fit_transform(X_train_raw)
>>> X_test = vectorizer.transform(X_test_raw)
Finally, we create an instance of LogisticRegression and train our model. Like LinearRegression, LogisticRegression implements the fit() and predict() methods. As a sanity check, we printed a few predictions for manual inspection:
>>> classifier = LogisticRegression()
>>> classifier.fit(X_train, y_train)
>>> predictions = classifier.predict(X_test)
>>> for i, prediction in enumerate(predictions[:5]):
>>> print 'Prediction: %s. Message: %s' % (prediction, X_test_raw[i])
The following is the output of the script:
Prediction: ham. Message: If you don't respond imma assume you're still asleep and imma start calling n shit
Prediction: spam. Message: HOT LIVE FANTASIES call now 08707500020 Just 20p per min NTT Ltd, PO Box 1327 Croydon CR9 5WB 0870 is a national rate call
Prediction: ham. Message: Yup... I havent been there before... You want to go for the yoga? I can call up to book
Prediction: ham. Message: Hi, can i please get a &lt;#&gt; dollar loan from you. I.ll pay you back by mid february. Pls.
Prediction: ham. Message: Where do you need to go to get it?
</code></pre>
<p>And I followed along:</p>
<pre><code>ddir = (sys.argv[1])
df = pd.read_csv(ddir + '/SMSSpamCollection', delimiter='\t', header=None)
#print df.head
#print 'Number of spam messages: ', df[df[0] == 'spam'][0].count()
#print 'Number of ham messages: ', df[df[0] == 'ham'][0].count()
X_train_raw, X_test_raw, y_train, y_test = train_test_split(df[1], df[0])
vectorizer = TfidfVectorizer()
X_train = vectorizer.fit_transform(X_train_raw)
X_test = vectorizer.transform(X_test_raw)
classifier = LogisticRegression()
classifier.fit(X_train, y_train)
predictions = classifier.predict(X_test)
for i, pdn in enumerate(predictions):
print 'Prediction: %s. Message: %s' % (pdn, X_test_raw[i])
</code></pre>
<p>However, for some reason, this gave me an error. Thinking it was my modifications, I rewrote my code to follow the book line for line:</p>
<pre><code>for i, prediction in enumerate(predictions[:5]):
print 'Prediction: %s. Message: %s' % (prediction, X_test_raw[i])
</code></pre>
<p>and yet, this only printed two answers before crashing:</p>
<pre><code>Number of spam messages: 747
Number of ham messages: 4825
['ham' 'ham' 'ham' ..., 'ham' 'ham' 'ham']
Prediction: ham. Message: Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...
Prediction: ham. Message: Ok lar... Joking wif u oni...
Traceback (most recent call last):
File "Chapter4[B-FLGTLG][Y-SF]--[DC].py", line 38, in <module>
print 'Prediction: %s. Message: %s' % (prediction, X_test_raw[i])
File "/usr/local/lib/python2.7/dist-packages/pandas/core/series.py", line 583, in __getitem__
result = self.index.get_value(self, key)
File "/usr/local/lib/python2.7/dist-packages/pandas/indexes/base.py", line 1980, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/index.pyx", line 103, in pandas.index.IndexEngine.get_value (pandas/index.c:3332)
File "pandas/index.pyx", line 111, in pandas.index.IndexEngine.get_value (pandas/index.c:3035)
File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)
File "pandas/hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6610)
File "pandas/hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6554)
KeyError: 2
</code></pre>
<p>Now here's the problem: I ran the exact same script, without changing a single line, a second time, and it gave me a <em>different error</em>:</p>
<pre><code>Number of spam messages: 747
Number of ham messages: 4825
['ham' 'ham' 'ham' ..., 'ham' 'ham' 'ham']
Traceback (most recent call last):
File "Chapter4[B-FLGTLG][Y-SF]--[DC].py", line 38, in <module>
print 'Prediction: %s. Message: %s' % (prediction, X_test_raw[i])
File "/usr/local/lib/python2.7/dist-packages/pandas/core/series.py", line 583, in __getitem__
result = self.index.get_value(self, key)
File "/usr/local/lib/python2.7/dist-packages/pandas/indexes/base.py", line 1980, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/index.pyx", line 103, in pandas.index.IndexEngine.get_value (pandas/index.c:3332)
File "pandas/index.pyx", line 111, in pandas.index.IndexEngine.get_value (pandas/index.c:3035)
File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)
File "pandas/hashtable.pyx", line 303, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6610)
File "pandas/hashtable.pyx", line 309, in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:6554)
KeyError: 0
</code></pre>
<p>How is this even possible? Do I have some low-level ram bug messing with python itself? The data is here: <a href="http://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection" rel="nofollow">http://archive.ics.uci.edu/ml/datasets/SMS+Spam+Collection</a> in case anyone wants to follow along.</p>
| 1 | 2016-08-23T03:19:15Z | 39,114,121 | <p>UPDATE</p>
<p>I found a solution from here: <a href="https://stackoverflow.com/questions/29305131/problems-with-pandas?answertab=votes#tab-top">Problems with Pandas</a></p>
<p>I changed:</p>
<pre><code>print 'Prediction: %s. Message: %s' % (pdn, X_test_raw[i])
</code></pre>
<p>to</p>
<pre><code>print 'Prediction: %s. Message: %s' % (pdn, X_test_raw.iloc[i])
</code></pre>
<p>and now it works fine:</p>
<pre><code>Number of spam messages: 747
Number of ham messages: 4825
['ham' 'spam' 'ham' ..., 'spam' 'ham' 'ham']
Prediction: ham. Message: Well done, blimey, exercise, yeah, i kinda remember wot that is, hmm.
Prediction: spam. Message: U have won a nokia 6230 plus a free digital camera. This is what u get when u win our FREE auction. To take part send NOKIA to 83383 now. POBOX114/14TCR/W1 16
Prediction: ham. Message: I doubt you could handle 5 times per night in any case...
Prediction: ham. Message: I've told you everything will stop. Just dont let her get dehydrated.
Prediction: ham. Message: AH POOR BABY!HOPE URFEELING BETTERSN LUV! PROBTHAT OVERDOSE OF WORK HEY GO CAREFUL SPK 2 U SN LOTS OF LOVEJEN XXX.
</code></pre>
| 0 | 2016-08-24T03:50:34Z | [
"python",
"csv",
"pandas",
"memory",
"keyerror"
] |
Python: OpenGL Error 1280 Invalid Enumerant with glEnd() | 39,091,819 | <p>I am working on creating a flashlight app in Python using Numba for my kernel and OpenGL (code below) . It is very close to finished but when I run it I run into an error with glEnd error 1280. The terminal output for when the code is run is also below. I can't figure out what exactly is causing the issue and helping narrow it down would be very helpful.</p>
<pre><code>from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL.ARB.vertex_buffer_object import *
from OpenGL.GL.ARB.pixel_buffer_object import *
import numpy as np
import sys
import pycuda.gl as cuda_gl
import pycuda.driver as cuda_driver
import math
from numba import jit, cuda as nbcuda
W = 600
H = 600
loc = np.array([W/2, H/2], dtype = 'float32')
dragMode = False
TX = 32
TY = 32
pbo, tex, pycuda_pbo, distanceKernel = [None] * 4
class ExternalMemory(object):
"""
Provide an externally managed memory.
Interface requirement: __cuda_memory__, device_ctypes_pointer, _cuda_memize_
"""
__cuda_memory__ = True
def __init__(self, ptr, size):
self.device_ctypes_pointer = ctypes.c_void_p(ptr)
self._cuda_memsize_ = size
def render():
global pycuda_pbo, pbo
assert pbo is not None
pycuda_pbo.unregister()
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, long(pbo))
pycuda_pbo = cuda_gl.BufferObject(long(pbo))
pbo_mapping = pycuda_pbo.map()
source_ptr = ExternalMemory(pbo_mapping.device_ptr(), W*H * 4)
d_out = nbcuda.devicearray.DeviceNDArray(shape = W*H * 4,
strides = (1,),
dtype = np.dtype('uint8'),
gpu_data = source_ptr)
blockSize = (TX, TY)
gridSize = ((W + TX - 1)/TX, (H + TY - 1)/TY)
distanceKernel[gridSize, blockSize](d_out, W, H, loc)
cuda_driver.Context.synchronize()
pbo_mapping.unmap()
glBindTexture(GL_TEXTURE_2D, tex)
def drawTexture():
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, W, H, 0, GL_RGBA, GL_UNSIGNED_BYTE, None)
glEnable(GL_TEXTURE_2D)
glBegin(GL_TEXTURE_2D)
glBegin(GL_QUADS)
glTexCoord2f(0.0, 0.0); glVertex2f(0,0)
glTexCoord2f(0.0, 1.0); glVertex2f(0,H)
glTexCoord2f(1.0, 1.0); glVertex2f(W,H)
glTexCoord2f(1.0, 0.0); glVertex2f(W,0)
glEnd()
glDisable(GL_TEXTURE_2D)
def display():
render()
drawTexture()
glutSwapBuffers()
def create_PBO():
global pbo, pycuda_pbo
data = np.zeros((W*H,4), dtype = 'uint8')
pbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, pbo)
glBufferData(GL_ARRAY_BUFFER, data, GL_DYNAMIC_DRAW)
glBindBuffer(GL_ARRAY_BUFFER, 0)
pycuda_pbo = cuda_gl.BufferObject(long(pbo))
def create_texture():
global tex
tex = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, tex)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
def exitfunc():
glBindBuffer(GL_ARRAY_BUFFER, long(pbo))
glDeleteBuffers(1, long(pbo));
glBindBuffer(GL_ARRAY_BUFFER, 0)
pbo = None
glDeleteTextures(tex);
tex = None
def keyboard(key, x, y):
if key == '\033': #\033 is escape key
exit()
elif key == 'a':
dragMode = not dragMode
elif key == 27:
exit()
glutPostRedisplay()
def mouseMove(x, y):
if dragMode == True:
loc[0] = x
loc[1] = y
glutPostRedisplay()
def mouseDrag(x, y):
if dragMode == False:
loc[0] = x
loc[1] = y
glutPostRedisplay()
def handleSpecialKeypress(key, x, y):
if key == GLUT_KEY_LEFT:
loc[0] -= DELTA
if key == GLUT_KEY_RIGHT:
loc[0] += DELTA
if key == GLUT_KEY_UP:
loc[1] -= DELTA
if key == GLUT_KEY_DOWN:
loc[1] += DELTA
glutPostRedisplay()
def printInstructions():
print "flashlight instructions"
print "a: toggle mouse tracking mode"
print "arrow keys: move ref location"
print "esc: close graphics window"
def main():
global cuda_gl, cuda_driver, distanceKernel
printInstructions();
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE)
glutCreateWindow("flashlight: distance image display app")
gluOrtho2D(0, W, H, 0)
glutDisplayFunc(display)
glutKeyboardFunc(keyboard)
glutSpecialFunc(handleSpecialKeypress)
glutPassiveMotionFunc(mouseMove)
glutMotionFunc(mouseDrag)
create_texture()
#Sets up GL interop
import pycuda.gl.autoinit
import pycuda.gl
cuda_gl = pycuda.gl
cuda_driver = pycuda.driver
# force compilation here
@nbcuda.jit(device = True)
def clip(n):
if n > 255:
n = 255
elif n < 0:
n = 0
return n
@nbcuda.jit("(uint8[::1], int32, int32, float32[::1])")
def distanceKernel(d_out, w, h, pos):
c = nbcuda.blockIdx.x*nbcuda.blockDim.x + nbcuda.threadIdx.x
r = nbcuda.blockIdx.y*nbcuda.blockDim.y + nbcuda.threadIdx.y
i = (r*w + c) * 4
if c >= w or r >= h:
return
d = math.sqrt((c - pos[0]) * (c - pos[0]) + (r - pos[1]) * (r - pos[1]))
intensity = clip(255 - d)
d_out[i] = intensity
d_out[i+1] = intensity
d_out[i+2] = 0
d_out[i+3] = 255
create_PBO()
glutMainLoop()
atexit(exitfunc)
main()
</code></pre>
<p>This is what the terminal spits out as OpenGL runs</p>
<pre><code>flashlight instructions
a: toggle mouse tracking mode
arrow keys: move ref location
esc: close graphics window
cuInit
cuDeviceGetCount
cuDeviceGetCount
cuDeviceGet
cuGLCtxCreate
cuCtxGetDevice
cuGLRegisterBufferObject
cuGLUnregisterBufferObject
cuGLRegisterBufferObject
cuGLMapBufferObject
cuCtxSynchronize
cuGLUnmapBufferObject
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 314, in 'calling callback function'
File "stackcode.py", line 80, in display
drawTexture()
File "stackcode.py", line 75, in drawTexture
glEnd()
File "latebind.pyx", line 44, in OpenGL_accelerate.latebind.Curry.__call__ (src/latebind.c:1201)
File "/home/uchytilc/anaconda2/lib/python2.7/site-packages/OpenGL/GL/exceptional.py", line 46, in glEnd
return baseFunction( )
File "/home/uchytilc/anaconda2/lib/python2.7/site-packages/OpenGL/platform/baseplatform.py", line 402, in __call__
return self( *args, **named )
File "errorchecker.pyx", line 53, in OpenGL_accelerate.errorchecker._ErrorChecker.glCheckError (src/errorchecker.c:1218)
OpenGL.error.GLError: GLError(
err = 1280,
description = 'invalid enumerant',
baseOperation = glEnd,
cArguments = ()
)
cuCtxPopCurrent
cuCtxPushCurrent
cuGLUnregisterBufferObject
cuGLUnregisterBufferObject failed with code 1
PyCUDA WARNING: a clean-up operation failed (dead context maybe?)
cuGLUnregisterBufferObject failed: invalid argument
cuCtxPopCurrent
cuCtxPushCurrent
cuCtxDetach
</code></pre>
| 0 | 2016-08-23T03:22:45Z | 39,095,592 | <p>The problem might come from this line:</p>
<pre><code>glBegin(GL_TEXTURE_2D)
</code></pre>
<p>glBegin does not allow for this parameter. It only accepts primitive types (which TEXTURE_2D is not). Have a look at the <a href="https://www.opengl.org/sdk/docs/man2/xhtml/glBegin.xml" rel="nofollow">documentation</a> about supported values.</p>
| 1 | 2016-08-23T08:03:56Z | [
"python",
"opengl",
"cuda",
"numba"
] |
Python getting element value for specific element | 39,091,827 | <p>I am attempting to parse the below XML file but having difficulty getting a specific element value. I am trying to specify element 'Item_No_2' to get the related value <code><v>2222222222</v></code> but am unable to do it using get.element('Item_No_2'). Am I using the get.element value incorrectly?</p>
<p>XML File:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="Data.xsl"?>
<abc>
<md>
<mi>
<datetime>20160822020003</datetime>
<period>3600</period>
<it>Item_No_1</it>
<it>Item_No_2</it>
<it>Item_No_3</it>
<it>Item_No_4</it>
<it>Item_No_5</it>
<it>Item_No_6</it>
<it>Item_No_7</it>
<ovalue>
<v>1111111111</v>
<v>2222222222</v>
<v>3333333333</v>
<v>4444444444</v>
<v>5555555555</v>
<v>6666666666</v>
<v>7777777777</v>
</ovalue>
</mi>
</md>
</abc>
</code></pre>
<p>My Code:</p>
<pre><code>from xml.etree.ElementTree import parse
doc = parse('test.xml').getroot()
for element in doc.findall('md/mi/'):
print(element.text)
for element in doc.findall('md/mi/ovalue/'):
print(element.text)
</code></pre>
<p>The current output gets them separately but I can't seem to understand how to call a specific element value.</p>
<p>Output:</p>
<pre><code>20160822020003
3600
Item_No_1
Item_No_2
Item_No_3
Item_No_4
Item_No_5
Item_No_6
Item_No_7
1111111111
2222222222
3333333333
4444444444
5555555555
6666666666
7777777777
</code></pre>
<p>Tried this but did not work:</p>
<pre><code>for element in doc.findall('md/mi/ovalue/'):
print(element.get('Item_No_1'))
</code></pre>
| 1 | 2016-08-23T03:24:02Z | 39,091,977 | <p>There is no <code>Item_No_1</code> at the elements that are found by <code>doc.findall('md/mi/ovalue/')</code>. </p>
<p>I think what you may try to do is get both lists</p>
<pre><code>items = [e.text for e in doc.findall('md/mi/it')]
values = [e.text for e in doc.findall('md/mi/ovalue/v')]
</code></pre>
<p>Then find the index of the string <code>'Item_No_1'</code> from <code>items</code>, and then index into <code>values</code> with that number. </p>
<p>Alternatively, <code>zip</code> the two lists together and check when you find one element. </p>
<pre><code>for item,value in zip(doc.findall('md/mi/it'), doc.findall('md/mi/ovalue/v')):
if item.text == 'Item_No_1':
print(value.text)
</code></pre>
<p>There might be a better way, but those are the first ways that come to mind</p>
| 1 | 2016-08-23T03:43:01Z | [
"python",
"xml",
"elementtree"
] |
odoo get the value of maximum array index | 39,091,852 | <p>I got a function to append data into array :</p>
<pre><code>def _get_state(self, cr, uid, context=None):
idemployee = _default_employee(self, cr, uid, context=None)
sql = " SELECT C.id AS id, C.sequence, C.name \
FROM wf_group_member A \
LEFT JOIN wf_group B ON B.id = A.group_id \
LEFT JOIN wf_process BB ON BB.id = B.process_id\
LEFT JOIN wf_state C ON C.group_id = B.id \
LEFT JOIN hr_employee D ON D.id = A.member_id \
WHERE LOWER(code) = 'ca' AND member_id = %s ORDER BY sequence "
res = []
cr.execute(sql, [(idemployee)])
ardata = cr.fetchall()
for data in ardata:
res.append((data[1], data[2]))
return res
</code></pre>
<p>and then I tried to get the value of maximum array index :</p>
<pre><code>def _get_maxstate(self, cr, uid, context=None):
res = []
arr_state = _get_state(self, cr, uid, context)
states = len(arr_state) - 1
res = arr_state[0][states]
return res
</code></pre>
<p>But when I call _get_maxstate in action button, it raise error :</p>
<pre><code>res = arr_state[0][states]
IndexError: tuple index out of range
</code></pre>
<p>What's wrong with my code, help me please</p>
| 0 | 2016-08-23T03:26:33Z | 39,091,882 | <p><code>states</code> is an index to the last element of <code>arr_state</code>. However you do not index <code>arr_state</code> with <code>states</code>, you index it with <code>0</code> and then index the result with <code>states</code>. It seems like you probably want to just index the other way around, i.e. <code>arr_state[states][0]</code>.</p>
| 1 | 2016-08-23T03:30:40Z | [
"python",
"openerp"
] |
Edited aug 24 9pm - number game isn't working as I would like | 39,091,899 | <p>I have a number guessing game working but I would like it to count without pick numbers without having them have any with a single increment. What I am trying to say is 2 4 17 27 not 2 3 4 17 27 I would like it to go through all the possibilities from low to high like it is, just not with any in a single increment IE 1 2 3 or 5 6.</p>
<p>I would also like it to be able to do from 1 to 100 and the count length to go to 10. If I try and put anymore than 6 in it will not work.</p>
<pre><code>It gives me a result like this now
Please enter the lower limit: 2
Please enter the upper limit: 9
Please enter the number of values in sequences: 6
Possible sequences. Spot the missing one!
[2, 3, 4, 5, 6, 7] #I do not want it to have them all 1 digit up at a time
[2, 3, 4, 5, 6, 8] #like this
[2, 3, 4, 5, 6, 9]
[2, 3, 4, 5, 7, 8]
[2, 3, 4, 5, 7, 9]
[2, 3, 4, 5, 8, 9]
[2, 3, 4, 6, 7, 8]
[2, 3, 4, 6, 7, 9]
[2, 3, 4, 6, 8, 9]
[2, 3, 4, 7, 8, 9]
[2, 3, 5, 6, 7, 8]
[2, 3, 5, 6, 7, 9]
[2, 3, 5, 6, 8, 9]
[2, 3, 5, 7, 8, 9]
[2, 3, 6, 7, 8, 9]
Please enter the lower limit: 2
Please enter the upper limit: 13
Please enter the number of values in sequences: 6
[2, 4, 6, 8, 10] #I would like it more like this
[2, 4, 7, 9, 11] #so it go's through low to high but with out 1 digit
[2, 5, 7, 9, 11] #increments
[2, 5, 9, 11, 13]
[2, 6, 9, 11, 13]
[2, 7, 9, 11, 13,]
</code></pre>
<p>If anyone has any suggestions please let me know.</p>
<pre><code>import itertools
import random
DEBUG = False
ALLOWED_GUESSES = 3
def get_game_parameters():
while True:
try:
lower_limit = int(input("Please enter the lower limit: "))
upper_limit = int(input("Please enter the upper limit: "))
consecutive_length = int(input("Enter The Number Limit For Consecutive Increments: "))
if lower_limit > upper_limit:
raise ValueError("Lower limit must not exceed upper limit")
sequence_length = int(input("Please enter the number of values in sequences: "))
if upper_limit - lower_limit < sequence_length:
raise ValueError("Difference in limits must be greater than sequence length")
except ValueError as e:
print("Invalid value entered:", e)
continue
else:
sequence_range = range(lower_limit, upper_limit + 2)
return sequence_range, sequence_length
###input ("Enter The Number Limit For Consecutive Increments: ")
def prompt_user_to_guess(chosen_sequence, required_sequence_length):
guesses_made = 0
while True:
try:
user_input = input(
"Please enter your guess for the hidden sequence, " +\
"separating terms by commas (e.g. '1, 2, 3, 4'): ")
guessed_sequence = [int(x) for x in user_input.split(",")]
if len(guessed_sequence) != required_sequence_length:
raise ValueError("Incorrect number of arguments")
except ValueError as e:
print("Invalid guess:", e)
continue
else:
guesses_made += 1
if guessed_sequence == chosen_sequence:
print("You guessed the correct sequence. Well done!")
return
elif guesses_made < ALLOWED_GUESSES:
remaining_guesses = ALLOWED_GUESSES - guesses_made
print("Incorrect guess! {} attempt(s) remaining.".format(remaining_guesses))
continue
else:
print("I'm sorry, you're out of guesses. The correct sequence was {}".format(chosen_sequence))
return
def generate_possible_sequences(sequence_range, sequence_length):
def is_monotonic_increasing(l):
return all(x < y for x, y in zip(l, l[1:]))
for permutation in itertools.permutations(sequence_range, sequence_length):
if is_monotonic_increasing(permutation):
yield list(permutation)
def main():
sequence_range, sequence_length = get_game_parameters()
possible_sequences = list(generate_possible_sequences(sequence_range, sequence_length))
chosen_sequence = possible_sequences.pop(random.randrange(len(possible_sequences)))
assert chosen_sequence not in possible_sequences
if DEBUG:
print("\nChosen sequence: {}".format(chosen_sequence))
print("\nPossible sequences. Spot the missing one!\n")
for sequence in possible_sequences:
print(sequence)
prompt_user_to_guess(chosen_sequence, sequence_length)
if __name__ == '__main__':
main()
</code></pre>
| -1 | 2016-08-23T03:32:50Z | 39,092,156 | <p>I'm not clear on what exactly you are answering, and we need a better explanation of "it will not work". However, it looks like you generate far too many options in <code>generate_possible_sequences()</code> which probably results in either memory filling up or far too long an execution time. A better approach is to just shuffle numbers in range, then sort a sub-sequence, like so:</p>
<pre><code>sequence_range, sequence_length = get_game_parameters()
vals = range(1, sequence_range + 1)
random.shuffle(vals)
chosen_sequence = sorted(vals[:sequence_length])
</code></pre>
<p>This will work almost instantly for <code>sequence_range</code> values well into the thousands, and you can step through it interactively to see how the code it working. However, for millions of elements (or just shorter code overall), the <code>random.sample()</code> function does what you want in just one line and without shuffling the complete list:</p>
<pre><code>sequence_range, sequence_length = get_game_parameters()
chosen_sequence = sorted(random.sample(xrange(1, sequence_range + 1), sequence_length))
</code></pre>
<p>The <code>xrange()</code> here avoids creating an actual list in memory; this line gives an out of memory error:</p>
<pre><code>random.sample(range(1, 999999999), 4)
</code></pre>
<p>This line works:</p>
<pre><code>random.sample(xrange(1, 999999999), 4)
</code></pre>
<p>You probably also want:</p>
<pre><code>guessed_sequence.sort()
</code></pre>
<p>This allows the user to input in any order.</p>
| 1 | 2016-08-23T04:03:58Z | [
"python"
] |
Changing values of tuple elements | 39,091,908 | <p>I entered the following at the command line:</p>
<pre class="lang-py prettyprint-override"><code>>>>a = 25
>>>b = 50
>>>t = (a, b)
>>>t
(25, 50)
>>>a = 50
>>>t
(25, 50)
>>>t = (a, b)
>>>t
(50, 50)
</code></pre>
<p>Why do I have to reassign the tuple <code>(a, b)</code> to <code>t</code> to see the change in <code>a</code>'s value?</p>
| -1 | 2016-08-23T03:34:02Z | 39,092,001 | <p>This has less to do with tuples and more to do with how assignment works in Python which copies vs references.</p>
<p>This works for other container types (lists) and plain variables.</p>
<pre><code>>>> a = 2
>>> b = [1, a]
>>> a = 7
>>> b
[1, 2]
>>> c = 1
>>> d = c
>>> c = 2
>>> d
1
</code></pre>
| 1 | 2016-08-23T03:45:26Z | [
"python",
"tuples"
] |
Changing values of tuple elements | 39,091,908 | <p>I entered the following at the command line:</p>
<pre class="lang-py prettyprint-override"><code>>>>a = 25
>>>b = 50
>>>t = (a, b)
>>>t
(25, 50)
>>>a = 50
>>>t
(25, 50)
>>>t = (a, b)
>>>t
(50, 50)
</code></pre>
<p>Why do I have to reassign the tuple <code>(a, b)</code> to <code>t</code> to see the change in <code>a</code>'s value?</p>
| -1 | 2016-08-23T03:34:02Z | 39,092,015 | <p>You can understand it in this way:- </p>
<pre><code>>>> a =25
>>> b = 50
>>> id(a)
6070712
>>> t = (a, b)
>>> id(t[0])
6070712
>>> a = 50
>>> id(a)
6070412
# When you assigned a = 50, it created new object,
#id(t[0]) and a is not same now, so t is still (25, 50)
</code></pre>
<p>This happened because <code>int</code> is immutable, every time you assign a value to it, new object would be created.</p>
<p>Repeat same with mutable type(which can be modified in place)</p>
<pre><code>>>> ls1 = [1,2]
>>> ls2 = [3,4]
>>> t = (ls1, ls2)
>>> ls1[0] = 23
>>> t
([23, 2], [3, 4])
>>> id(ls1)
54696136
>>> id(t[0])
54696136
#here t[0] and ls1 are same object because we could modify ls1 in place
</code></pre>
<p>I hope it would help.</p>
| 1 | 2016-08-23T03:46:24Z | [
"python",
"tuples"
] |
Changing values of tuple elements | 39,091,908 | <p>I entered the following at the command line:</p>
<pre class="lang-py prettyprint-override"><code>>>>a = 25
>>>b = 50
>>>t = (a, b)
>>>t
(25, 50)
>>>a = 50
>>>t
(25, 50)
>>>t = (a, b)
>>>t
(50, 50)
</code></pre>
<p>Why do I have to reassign the tuple <code>(a, b)</code> to <code>t</code> to see the change in <code>a</code>'s value?</p>
| -1 | 2016-08-23T03:34:02Z | 39,092,040 | <p>At first, the value in tuple in python can not be changed. You can only declare a new tuple.</p>
<p><code>a = 25</code> means <code>a</code> is a variable. However, the <code>a</code> in <code>t</code> belong to the tuple t. It does not have any relationship with variable <code>a</code>. </p>
<p>The second <code>t = (a, b)</code> as same as <code>t = (50, 50)</code></p>
<p>Furthermore, you can use <code>id(a)</code> and <code>id(t)</code> to see the difference in your memory address.</p>
| 1 | 2016-08-23T03:49:47Z | [
"python",
"tuples"
] |
Changing values of tuple elements | 39,091,908 | <p>I entered the following at the command line:</p>
<pre class="lang-py prettyprint-override"><code>>>>a = 25
>>>b = 50
>>>t = (a, b)
>>>t
(25, 50)
>>>a = 50
>>>t
(25, 50)
>>>t = (a, b)
>>>t
(50, 50)
</code></pre>
<p>Why do I have to reassign the tuple <code>(a, b)</code> to <code>t</code> to see the change in <code>a</code>'s value?</p>
| -1 | 2016-08-23T03:34:02Z | 39,092,100 | <p>If we do an assign action like a = b and b is immutable(number, string, tuple etc)ï¼assign will make a copy rather than make reference. As a result, modify to the b do not effect a.</p>
<p>For mutable situation:</p>
<pre><code>>>> a = []
>>> b = 3
>>> c = (a, b)
>>> c
([], 3)
>>> a.append(1)
>>> c
((1], 3)
</code></pre>
| 0 | 2016-08-23T03:57:05Z | [
"python",
"tuples"
] |
Changing values of tuple elements | 39,091,908 | <p>I entered the following at the command line:</p>
<pre class="lang-py prettyprint-override"><code>>>>a = 25
>>>b = 50
>>>t = (a, b)
>>>t
(25, 50)
>>>a = 50
>>>t
(25, 50)
>>>t = (a, b)
>>>t
(50, 50)
</code></pre>
<p>Why do I have to reassign the tuple <code>(a, b)</code> to <code>t</code> to see the change in <code>a</code>'s value?</p>
| -1 | 2016-08-23T03:34:02Z | 39,092,492 | <p>It is simple. In Python, the names, such as <code>a</code> and <code>b</code> and <code>t</code> are not <em>objects</em>, they just point to objects. When you enter</p>
<pre><code>>>> a = 25
>>> b = 50
</code></pre>
<p>Python sets the name <code>a</code> to point to an <code>int</code> object with value <code>25</code> and <code>b</code> to point to <code>int</code> object with value <code>50</code>.</p>
<p>when you create a tuple with</p>
<pre><code>>>> t = a, b
</code></pre>
<p>(no parenthesis required here!) you're telling Python that "please make a new tuple of 2 elements, the first position of which should point to the object that <code>a</code> <em>now</em> points to and the second position should point to the object that <code>b</code> <em>now</em> points to. Actually it would work similarly with a list, or set as well:</p>
<pre><code>>>> l = [a, b]
>>> s = {a, b}
</code></pre>
<p>Now the next statement:</p>
<pre><code>>>> a = 50
</code></pre>
<p>Means "now, set <code>a</code> to point to an <code>int</code> object with value of <code>50</code>". The first element of the tuple still continues to point to <code>25</code>. Actually all assignments to variables behave this way in Python, be the value in <code>a</code> mutable or not:</p>
<pre><code>>>> a = [1, 2]
>>> b = [3, 4]
>>> t = a, b
>>> a = [5, 6]
>>> t
([1, 2], [3, 4])
</code></pre>
<p>Even though <code>a</code> points to a mutable value, a list, then <code>a, b</code> means *make a new tuple with first element being the object that <code>a</code> points to at this very moment, and second element being the object that <code>b</code> points to at this very moment; and then <code>a = [5, 6]</code> means *create a new list ... and now make <code>a</code> point to it`. The variables (names) in Python indeed are not "boxes", but they're sort of signs that point to the values. </p>
| 0 | 2016-08-23T04:42:16Z | [
"python",
"tuples"
] |
How to put JSON file on a local server? | 39,091,910 | <p>I've driven myself insane for the last two hours attempting to find an answer for the issue that I'm encountering. I was trying to access a local JSON file called, data.json, which I placed inside my project directory. My console returned this error: </p>
<p>Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.</p>
<p>I now know that I cannot access this file locally and I must do so through an external server. How does someone setup a local server with this file? Can someone please explain how to do it using python, json-server, and node,js? I am completely lost.</p>
<p>Here is my code: </p>
<pre><code>$(function (){
var $orders = $("#orders");
var $name = $('#name');
var $drink = $('#drink');
$.ajax({
type: 'GET',
datatype: 'json',
url: 'data.json',
success: function(orders) {
$.each(orders, function(i, order) {
$orders.append('<li>Name: ' + order.name + ', Drink: ' + order.drink + '</li>');
});
},
error: function() {
alert('error loading orders');
}
});
$('#add-order').on('click', function() {
var order = {
name: $name.val(),
drink: $drink.val()
};
$.ajax({
type: 'POST',
url: 'data.json',
data: order,
success: function(newOrder) {
$orders.append('<li>Name: ' + newOrder.name + ', Drink: ' + newOrder.drink + '</li>');
},
error: function () {
alert("error saving order");
}
});
});
});
</code></pre>
| -1 | 2016-08-23T03:34:15Z | 39,092,132 | <blockquote>
<p>How does someone setup a local server with this file?</p>
</blockquote>
<p>A very simple web server in Python can be launched with a single command. This would allow you to fetch the contents over HTTP.</p>
<p>From the directory where your <code>data.json</code> file resides, you can run one of the following...</p>
<ul>
<li><p>if you are running Python 2:</p>
<ul>
<li><code>$ python -m SimpleHTTPServer 8000</code></li>
</ul></li>
<li><p>or if you are running Python 3:</p>
<ul>
<li><code>$ python -m http.server 8000</code></li>
</ul></li>
</ul>
<p>After launching the server, it will be listening for requests on port 8000.</p>
<p>You would access it by sending an HTTP GET request to localhost (<a href="http://127.0.0.1:8000/data.json" rel="nofollow">http://127.0.0.1:8000/data.json</a>)</p>
| 1 | 2016-08-23T04:00:18Z | [
"python",
"json",
"ajax",
"node.js",
"localserver"
] |
Search Functionality on a Django Site | 39,091,914 | <p>I'm trying to add a search function to my website but I'm having some issues. It's currently telling me that "Search" is not defined, but I have the class in my views file. This is what I have thus far:</p>
<p>urls.py</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^player/(?P<pk>\d+)/$', views.player, name='player'),
url(r'^season/(?P<pk>\d+)/$', views.season, name='season'),
url(r'^seasons/$', views.seasons, name='seasons'),
url(r'^search/$', Search.as_view(), name='search'),
]
</code></pre>
<p>views.py</p>
<pre><code>from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView
from .models import Player, Season, PxS, Statistics
def home(request):
seasons = Season.objects.order_by('sid')
return render(request, 'webapp/home.html', {'seasons': seasons})
def player(request, pk):
player = get_object_or_404(Player, pk=pk)
return render(request, 'webapp/player.html', {'player': player, 'seasons': player.season_set.order_by('sid'), 'statistics': player.statistics_set.all()})
def season(request, pk):
season = get_object_or_404(Season, pk=pk)
return render(
request,
'webapp/season.html',
{'season': season, 'players': season.players.order_by('lastname')}
)
def seasons(request):
seasons = Season.objects.order_by('sid')
return render(request, 'webapp/seasons.html', {'seasons': seasons})
class Search(ListView):
template_name = 'search.html'
model = Player
context_object_name = 'list'
def get_context_data(self, **kwargs):
context = super(Search, self).get_context_data(**kwargs)
context['count'] = self.get_queryset().count()
return context
def get_queryset(self):
pobj = Player.objects.all()
var_get_search = self.request.GET.get('search_box')
var_get_order_by = self.request.GET.get('pid')
if var_get_search is not None:
pobj = pobj.filter(playername__icontains=var_get_search)
if var_get_order_by is not None:
pobj = pobj.order_by(var_get_order_by)
return pobj
</code></pre>
<p>Any insight is greatly appreciated. I'm kind of just piecing this stuff together little by little. Thanks!</p>
| 0 | 2016-08-23T03:34:55Z | 39,092,585 | <p>The problem is in the urls.py</p>
<p>Give url(r'^search/$', views.Search.as_view(), name='search'),</p>
<p>instead of just Search. </p>
| 3 | 2016-08-23T04:51:58Z | [
"python",
"django"
] |
Use a json file stored on fs/disk as output for an Ansible module | 39,091,956 | <p>I am struggling with an <code>ansible</code> module I needed to create. Everything is done, the module gets a <code>json</code> file delivered from a third party onto the <code>fs</code>. This <code>json</code> file is expected to be the (only) output to be able to access to register the <code>json</code> file and access the content - or at least make the output somehow properly accessible.</p>
<p>The output file consists of a proper <code>json</code> file and I have tried various stuff to reach my goal.</p>
<p>Including:</p>
<ul>
<li><p>Simply print out the <code>json</code> file using <code>print</code> or <code>os.stdout.write</code>, because according to the documentation, <code>ansible</code> simply takes the <code>stdout</code>.</p></li>
<li><p>Importing the <code>json</code> and dump is using <code>json.dumps(data)</code> or like this:</p>
<pre><code>with open('path-to-file', 'r') as tmpfile:
data = json.load(tmpfile)
module.exit_json(changed=True, message="API call to %s successfull" % endpoint, meta=data)
</code></pre>
<ul>
<li>This ended up having the json in the output, but in an escaped variant and <code>ansible</code> refuses to access the escaped part.</li>
</ul></li>
</ul>
<p>What would be the correct way to make the <code>json</code> data accessible for further usage? </p>
<p>Edit:</p>
<p>The <code>json</code> looks like this (well, itâs a huge <code>json</code>, this is simply a part of it):</p>
<pre><code>{
"total_results": 51,
"total_pages": 2,
"prev_url": null,
"next_url": "/v2/apps?order-direction=asc&page=2&results-per-page=50",
</code></pre>
<p>After <code>register</code>, the <code>debug</code> output looks like this and I cannot access <code>output.meta.total_results</code> for example.</p>
<pre><code>ok: [localhost] => {
"output": {
"changed": true,
"message": "API call filtering /v2/apps with name and yes-no was successfull",
"meta": "{\"total_results\": 51, \"next_url\": \"/v2/apps?order-direction=asc&page=2&results-per-page=50\", \"total_pages\": 2, \"prev_url\": null, (...)
</code></pre>
<p>The <code>ansible</code> output when trying to access the var:</p>
<pre><code>ok: [localhost] => {
"output.meta.total_results": "VARIABLE IS NOT DEFINED!"
}
</code></pre>
| -1 | 2016-08-23T03:39:32Z | 39,104,544 | <p>Interesting. My tests using <code>os.stdout.write</code> somehow failed, but using <code>print json.dumps(data)</code> works. </p>
<p>This is solved.</p>
| 0 | 2016-08-23T14:56:05Z | [
"python",
"json",
"ansible"
] |
Parsing human readable relative times | 39,091,969 | <p>I would like to parse human terms like <code>3 days ago</code> in <code>python 2.7</code> to get a timedelta equivalent.</p>
<p>For example:</p>
<pre><code>>>> relativetimeparer.parser('3 days ago')
datetime.timedelta(3)
</code></pre>
<p>I have tried the <code>dateparser</code> module.</p>
<pre><code>>>> import dateparser
>>> dateparser.parse('3 days ago')
datetime.datetime(2016, 8, 20, 2, 57, 23, 372538)
>>> datetime.now() - dateparser.parse('3 days ago')
datetime.timedelta(3, 35999, 999232)
</code></pre>
<p>It parses relative time directly to <code>datetime</code> without the option of returning a <code>timedelta</code>. It also seems to think that 3 days ago is actually 3 days and 10 hours ago. So it seems to be invoking my timezone offset from Greenwich too (+10 hours). </p>
<p>Is there a better module for parsing human readable relative times?</p>
| 1 | 2016-08-23T03:42:01Z | 39,092,154 | <p>You could specify the <code>RELATIVE_BASE</code> setting:</p>
<pre><code>>>> now = datetime.datetime.now()
>>> res = dateparser.parse('3 days ago', settings={'RELATIVE_BASE': now})
>>> now - res
datetime.timedelta(3)
</code></pre>
| 1 | 2016-08-23T04:03:09Z | [
"python",
"time"
] |
Jupyter Notebook only has Python [conda root] and Python [default] kernels | 39,092,008 | <p>So I've been struggling with this and I'm new to programming so please be gentle. I followed all the steps outlined in the other Python [root] posts, but still cannot get the python2 and python3 kernels to show up. See photo below. I have Anaconda3 installed (the 3.5 version). Any help would be greatly appreciated. Thank you!</p>
<p><a href="http://i.stack.imgur.com/6b98t.png" rel="nofollow">Jupyter Screenshot</a>
<a href="http://i.stack.imgur.com/CSriO.png" rel="nofollow">Conda Screenshot</a></p>
| 2 | 2016-08-23T03:45:56Z | 40,051,941 | <p>I had a similar issue but i had python 2.7.12 installed from anaconda and the default one came with Mac is 2.7.10.</p>
<p>When i open jupiter notebook, i used to get Python[conda root] and Python[default], after lot of struggling i did the following</p>
<p><strong>conda update conda</strong> </p>
<p><strong>conda uninstall ipython</strong></p>
<p><strong>conda install jupyter</strong></p>
<p>now i see only 'Python 2' in my Jupiter notebook</p>
<p>hope this helps</p>
| 0 | 2016-10-14T21:02:58Z | [
"python",
"kernel",
"jupyter",
"conda"
] |
Save and Restore dockwidgets position and size | 39,092,010 | <p>I can't quite figure out how the save and restore are suppose to work, so that I may save the dockwidgets geometrics, when the application is closed and opened again. I have 5 dockwidgets, which I'd like to have this feature.</p>
<p>I assume I have to use both <code>restoreState</code> and <code>saveState</code> respectively in <code>init</code> and <code>close</code>. But how do I configure it?</p>
<p>MainWindow class</p>
<pre><code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from DockWindowGraph import Dock
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.centralWindow_ = QFrame()
self.setCentralWidget(None)
self.CreateWidgets()
self.settings = QSettings()
self.restoreState()
def CreateWidgets(self):
self.toolbar = self.addToolBar('Toolbar')
self.toolbar.setMovable(False)
exitA = QAction(QIcon('Images/gj.png'), 'Exit', self)
exitA.setShortcut('Ctrl+Q')
exitA.setStatusTip('Exit application')
exitA.triggered.connect(self.close)
self.toolbar.addAction(exitA)
openDock_ = QAction(QIcon('Images/gj.png'), 'Open', self)
openDock_.setShortcut('Ctrl+E')
openDock_.setStatusTip('Open Dock')
openDock_.triggered.connect(self.OpenDockWindow)
self.toolbar.addAction(openDock_)
self.setWindowTitle("We do not sow")
self.showFullScreen()
self.firstDock_ = Dock(self, 'First')
self.firstDock_.setObjectName('First')
self.addDockWidget(Qt.LeftDockWidgetArea, self.firstDock_)
self.secondDock_ = Dock(self, 'Second')
self.firstDock_.setObjectName('Second')
self.addDockWidget(Qt.LeftDockWidgetArea, self.secondDock_)
self.thirdDock_ = Dock(self, 'Third')
self.thirdDock_.setObjectName('Third')
self.splitDockWidget(self.firstDock_, self.thirdDock_, Qt.Horizontal)
self.fDock_ = Dock(self, 'Fourth')
self.fDock_.setObjectName('Fourth')
self.splitDockWidget(self.firstDock_, self.fDock_, Qt.Horizontal)
self.fiDock_ = Dock(self, 'Fifth')
self.fiDock_.setObjectName('Fifth')
self.splitDockWidget(self.firstDock_, self.fiDock_, Qt.Vertical)
self.setTabPosition(Qt.AllDockWidgetAreas, QTabWidget.North)
def OpenDockWindow(self):
dock_ = Dock((self.frameGeometry().width() / 2), self.firstDock_)
self.addDockWidget(Qt.RightDockWidgetArea, dock_)
self.tabifyDockWidget(self.secondDock_, dock_)
def closeEvent(self, event):
print('closing')
settings_ = QSettings()
self.saveState()
app = QApplication(sys.argv)
app.setOrganizationDomain('ltd')
app.setOrganizationName('Alg')
w = Window()
sys.exit(app.exec_())
</code></pre>
<p>my Dock class:</p>
<pre><code>from PyQt4.QtCore import *
from PyQt4.QtGui import *
from DockWindowFrame import Frame
class Dock(QDockWidget):
def __init__(self, title, parent=None):
super(Dock, self).__init__(parent)
self.setAllowedAreas(Qt.RightDockWidgetArea | Qt.LeftDockWidgetArea | Qt.TopDockWidgetArea | Qt.BottomDockWidgetArea)
self.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable )
self.frame = Frame()
self.frame.setStyleSheet("QWidget { background-color: rgba(0,220,0,100%)}")
self.setWidget(self.frame)
def ReturnFrame(self):
return self.frame
</code></pre>
<p>EDIT: Error after trying below answer.</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Rasmus\workspace\PyQtLearning\src\gg.py", line 90, in <module>
main()
File "C:\Users\Rasmus\workspace\PyQtLearning\src\gg.py", line 86, in main
w = Window()
File "C:\Users\Rasmus\workspace\PyQtLearning\src\gg.py", line 14, in __init__
self.readSettings()
File "C:\Users\Rasmus\workspace\PyQtLearning\src\gg.py", line 72, in readSettings
self.restoreGeometry(settings.value("geometry").toByteArray())
AttributeError: 'NoneType' object has no attribute 'toByteArray'
</code></pre>
| 0 | 2016-08-23T03:46:08Z | 39,092,887 | <p>This works here:</p>
<pre><code>def __init__(self):
self.readSettings()
def closeEvent(self, event):
print('closing')
settings = QSettings()
settings.setValue('geometry',self.saveGeometry())
settings.setValue('windowState',self.saveState())
super(Window, self).closeEvent(event)
def readSettings(self):
settings = QSettings()
self.restoreGeometry(settings.value("geometry").toByteArray())
self.restoreState(settings.value("windowState").toByteArray())
</code></pre>
<p>Referenceï¼
<a href="http://doc.qt.io/qt-4.8/qmainwindow.html#saveState" rel="nofollow">QMainWindow.saveState()</a>
<a href="http://doc.qt.io/qt-4.8/qmainwindow.html#restoreState" rel="nofollow">QMainWindow.restoreState()</a></p>
<p>Full code:</p>
<pre><code># coding = u8
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Window(QMainWindow):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.centralWindow_ = QFrame()
self.setCentralWidget(None)
self.CreateWidgets()
self.readSettings()
def CreateWidgets(self):
self.toolbar = self.addToolBar('Toolbar')
self.toolbar.setMovable(False)
exitA = QAction(QIcon('Images/gj.png'), 'Exit', self)
exitA.setShortcut('Ctrl+Q')
exitA.setStatusTip('Exit application')
exitA.triggered.connect(self.close)
self.toolbar.addAction(exitA)
openDock_ = QAction(QIcon('Images/gj.png'), 'Open', self)
openDock_.setShortcut('Ctrl+E')
openDock_.setStatusTip('Open Dock')
openDock_.triggered.connect(self.OpenDockWindow)
self.toolbar.addAction(openDock_)
self.setWindowTitle("We do not sow")
self.showFullScreen()
self.firstDock_ = Dock(self, 'First')
self.firstDock_.setObjectName('First')
self.addDockWidget(Qt.LeftDockWidgetArea, self.firstDock_)
self.secondDock_ = Dock(self, 'Second')
self.firstDock_.setObjectName('Second')
self.addDockWidget(Qt.LeftDockWidgetArea, self.secondDock_)
self.thirdDock_ = Dock(self, 'Third')
self.thirdDock_.setObjectName('Third')
self.splitDockWidget(self.firstDock_, self.thirdDock_, Qt.Horizontal)
self.fDock_ = Dock(self, 'Fourth')
self.fDock_.setObjectName('Fourth')
self.splitDockWidget(self.firstDock_, self.fDock_, Qt.Horizontal)
self.fiDock_ = Dock(self, 'Fifth')
self.fiDock_.setObjectName('Fifth')
self.splitDockWidget(self.firstDock_, self.fiDock_, Qt.Vertical)
self.setTabPosition(Qt.AllDockWidgetAreas, QTabWidget.North)
def OpenDockWindow(self):
dock_ = Dock((self.frameGeometry().width() / 2), self.firstDock_)
self.addDockWidget(Qt.RightDockWidgetArea, dock_)
self.tabifyDockWidget(self.secondDock_, dock_)
def closeEvent(self, event):
print('closing')
settings = QSettings()
settings.setValue('geometry',self.saveGeometry())
settings.setValue('windowState',self.saveState())
super(Window, self).closeEvent(event)
def readSettings(self):
settings = QSettings()
self.restoreGeometry(settings.value("geometry").toByteArray())
self.restoreState(settings.value("windowState").toByteArray())
class Dock(QDockWidget):
def __init__(self, title, parent=None):
super(Dock, self).__init__(parent)
self.setAllowedAreas(Qt.RightDockWidgetArea | Qt.LeftDockWidgetArea | Qt.TopDockWidgetArea | Qt.BottomDockWidgetArea)
self.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable )
def main():
app = QApplication(sys.argv)
app.setOrganizationDomain('ltd')
app.setOrganizationName('Alg')
w = Window()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
| 2 | 2016-08-23T05:16:02Z | [
"python",
"pyqt"
] |
Time complexity calculation for my algorithm | 39,092,049 | <p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. You may assume the string contain only lowercase letters.</p>
<p>I'm going to define a hash that tracks the occurrence of characters. Traverse the string from left to right, check if the current character is in the hash, continue if yes, otherwise in another loop traverse the rest of the string to see if the current character exists. Return the index if not and update the hash if it exists.</p>
<pre><code>def firstUniqChar(s):
track = {}
for index, i in enumerate(s):
if i in track:
continue
elif i in s[index+1:]: # For the last element, i in [] holds False
track[i] = 1
continue
else:
return index
return -1
firstUniqChar('timecomplexity')
</code></pre>
<p>What's the time complexity (average and worst) of my algorithm?</p>
| 5 | 2016-08-23T03:50:33Z | 39,092,153 | <p>Your algorithm is O(n<sup>2</sup>), because you have a "hidden" iteration over a slice of <code>s</code> inside the loop over <code>s</code>.</p>
<p>A faster algorithm would be:</p>
<pre><code>def first_unique_character(s):
good = {} # char:idx
bad = set() # char
for index, ch in enumerate(s):
if ch in bad:
continue
if ch in good: # new repeat
bad.add(ch)
del good[ch]
else:
good[ch] = index
if not good:
return -1
return min(good.values())
</code></pre>
<p>This is O(n) because the <code>in</code> lookups use hash tables, and the number of distinct characters should be much less than <code>len(s)</code>.</p>
| 4 | 2016-08-23T04:03:08Z | [
"python",
"algorithm"
] |
Time complexity calculation for my algorithm | 39,092,049 | <p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. You may assume the string contain only lowercase letters.</p>
<p>I'm going to define a hash that tracks the occurrence of characters. Traverse the string from left to right, check if the current character is in the hash, continue if yes, otherwise in another loop traverse the rest of the string to see if the current character exists. Return the index if not and update the hash if it exists.</p>
<pre><code>def firstUniqChar(s):
track = {}
for index, i in enumerate(s):
if i in track:
continue
elif i in s[index+1:]: # For the last element, i in [] holds False
track[i] = 1
continue
else:
return index
return -1
firstUniqChar('timecomplexity')
</code></pre>
<p>What's the time complexity (average and worst) of my algorithm?</p>
| 5 | 2016-08-23T03:50:33Z | 39,092,576 | <p><s>As others have noted, your algorithm is <code>O(n²)</code> due to nested linear search.</s> As discovered by @Antti, the OP's algorithm is linear and bound by <code>O(kn)</code> for <code>k</code> as the number of all possible lowercase letters.</p>
<p>My proposition for an <code>O(n)</code> solution:</p>
<pre><code>from collections import OrderedDict
def first_unique_char(string):
duplicated = OrderedDict() # ordered dict of char to boolean indicating duplicate existence
for s in string:
duplicated[s] = s in duplicated
for char, is_duplicate in duplicated.items():
if not is_duplicate:
return string.find(char)
return -1
print(first_unique_char('timecomplexity')) # 4
</code></pre>
| 6 | 2016-08-23T04:50:58Z | [
"python",
"algorithm"
] |
Time complexity calculation for my algorithm | 39,092,049 | <p>Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. You may assume the string contain only lowercase letters.</p>
<p>I'm going to define a hash that tracks the occurrence of characters. Traverse the string from left to right, check if the current character is in the hash, continue if yes, otherwise in another loop traverse the rest of the string to see if the current character exists. Return the index if not and update the hash if it exists.</p>
<pre><code>def firstUniqChar(s):
track = {}
for index, i in enumerate(s):
if i in track:
continue
elif i in s[index+1:]: # For the last element, i in [] holds False
track[i] = 1
continue
else:
return index
return -1
firstUniqChar('timecomplexity')
</code></pre>
<p>What's the time complexity (average and worst) of my algorithm?</p>
| 5 | 2016-08-23T03:50:33Z | 39,092,904 | <p>Your algorithm has time complexity of <code>O(kn)</code> where <code>k</code> is the number of unique characters in the string. If <code>k</code> is a constant then it is <code>O(n)</code>. As the problem description clearly bounds the number of alternatives for elements ("assume lower-case (ASCII) letters"), thus <code>k</code> is constant and your algorithm runs in <code>O(n)</code> time on this problem. Even though n will grow to infinite, you will only make <code>O(1)</code> slices of the string and your algorithm will remain <code>O(n)</code>. If you removed <code>track</code>, then it would be <code>O(n²)</code>:</p>
<pre><code>In [36]: s = 'abcdefghijklmnopqrstuvwxyz' * 10000
In [37]: %timeit firstUniqChar(s)
100 loops, best of 3: 18.2 ms per loop
In [38]: s = 'abcdefghijklmnopqrstuvwxyz' * 20000
In [37]: %timeit firstUniqChar(s)
10 loops, best of 3: 36.3 ms per loop
In [38]: s = 'timecomplexity' * 40000 + 'a'
In [39]: %timeit firstUniqChar(s)
10 loops, best of 3: 73.3 ms per loop
</code></pre>
<p>It pretty much holds there that the <code>T(n)</code> is still of <code>O(n)</code> complexity - it scales exactly linearly with number of characters in the string, even though this is the worst-case scenario for your algorithm - there is no single character that is be unique.</p>
<hr>
<p>I will present a not-that efficient, but simple and smart method here; count the character histogram first with <code>collections.Counter</code>; then iterate over the characters finding the one </p>
<pre><code>from collections import Counter
def first_uniq_char_ultra_smart(s):
counts = Counter(s)
for i, c in enumerate(s):
if counts[c] == 1:
return i
return -1
first_uniq_char('timecomplexity')
</code></pre>
<p>This has time complexity of <code>O(n)</code>; <code>Counter</code> counts the histogram in <code>O(n)</code> time and we need to enumerate the string again for <code>O(n)</code> characters. However in practice I believe my algorithm has low constants, because it uses a standard dictionary for <code>Counter</code>.</p>
<p>And lets make a very stupid brute-force algorithm. Since you can assume that the string contains only lower-case letters, then use that assumption:</p>
<pre><code>import string
def first_uniq_char_very_stupid(s):
indexes = []
for c in string.ascii_lowercase:
if s.count(c) == 1:
indexes.append(s.find(c))
# default=-1 is Python 3 only
return min(indexes, default=-1)
</code></pre>
<p>Let's test my algorithm and some algorithms found in the other answers, on Python 3.5. I've chosen a case that is pathologically bad for <em>my</em> algorithm:</p>
<pre><code>In [30]: s = 'timecomplexity' * 10000 + 'a'
In [31]: %timeit first_uniq_char_ultra_smart(s)
10 loops, best of 3: 35 ms per loop
In [32]: %timeit karin(s)
100 loops, best of 3: 11.7 ms per loop
In [33]: %timeit john(s)
100 loops, best of 3: 9.92 ms per loop
In [34]: %timeit nicholas(s)
100 loops, best of 3: 10.4 ms per loop
In [35]: %timeit first_uniq_char_very_stupid(s)
1000 loops, best of 3: 1.55 ms per loop
</code></pre>
<p>So, my stupid algorithm is the fastest, because it finds the <code>a</code> at the end and bails out. And my smart algorithm is slowest, One more reason for bad performance of my algorithm besides this being worst case is that <code>OrderedDict</code> is written in C on Python 3.5, and <code>Counter</code> is in Python.</p>
<hr>
<p>Let's make a better test here:</p>
<pre><code>In [60]: s = string.ascii_lowercase * 10000
In [61]: %timeit nicholas(s)
100 loops, best of 3: 18.3 ms per loop
In [62]: %timeit karin(s)
100 loops, best of 3: 19.6 ms per loop
In [63]: %timeit john(s)
100 loops, best of 3: 18.2 ms per loop
In [64]: %timeit first_uniq_char_very_stupid(s)
100 loops, best of 3: 2.89 ms per loop
</code></pre>
<p>So it appears that the "stupid" algorithm of mine isn't all that stupid at all, it exploits the speed of C while minimizing the number of iterations of Python code being run, and wins clearly in this problem.</p>
| 9 | 2016-08-23T05:18:34Z | [
"python",
"algorithm"
] |
confused by numpy meshgrid output | 39,092,106 | <p>Using Python 2.7 with miniconda interpreter. I am confused by what means N-D coordinate in the following statements, and could anyone tell how in the below sample <code>xv</code> and <code>yv</code> are calculated, it will be great.</p>
<p>"Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn."</p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html</a></p>
<pre><code>>>> nx, ny = (3, 2)
>>> x = np.linspace(0, 1, nx)
>>> y = np.linspace(0, 1, ny)
>>> xv, yv = meshgrid(x, y)
>>> xv
array([[ 0. , 0.5, 1. ],
[ 0. , 0.5, 1. ]])
>>> yv
array([[ 0., 0., 0.],
[ 1., 1., 1.]])
</code></pre>
<p>regards,
Lin</p>
| -1 | 2016-08-23T03:57:43Z | 39,092,261 | <p><code>xv,yv</code> are simply defined as:</p>
<pre><code>xv = np.array([x for _ in y])
yv = np.array([y for _ in x]).T
</code></pre>
<p>so that for every index pair <code>(i,j)</code>, you have</p>
<pre><code>xv[i,j] = x[i]
yv[i,j] = y[j]
</code></pre>
<p>which is useful especially for plotting 2D maps.</p>
| 1 | 2016-08-23T04:15:18Z | [
"python",
"python-2.7",
"numpy"
] |
argparse: How to make mutually exclusive arguments optional? | 39,092,149 | <p>I want to use my script like this:</p>
<pre><code>python test.py run
python test.py stop
</code></pre>
<p>and my code is like this:</p>
<pre><code>parser = argparse.ArgumentParser()
command_group = parser.add_mutually_exclusive_group(required=True)
command_group.add_argument('run', help='run it', action='store_true')
command_group.add_argument('stop', help='stop it', action='store_true')
</code></pre>
<p>when I execute it, an exception is raised:</p>
<pre><code>ValueError: mutually exclusive arguments must be optional
</code></pre>
<p>so I try to add <code>required=False</code> when I add each argument.Then I get another exception:</p>
<pre><code>TypeError: 'required' is an invalid argument for positionals
</code></pre>
<p>I'm confused. </p>
| 2 | 2016-08-23T04:02:33Z | 39,092,229 | <p>A better way to do this is to add a single positional argument that can have two choices. Since you want it to be optional, use <code>nargs='?'</code>, which means zero or one times:</p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument('run', help='run or stop', nargs='?', choices=('run', 'stop'))
</code></pre>
<p>If <code>run</code> is given, the value will be <code>'run'</code>. If <code>stop</code> is given, it will be <code>'stop'</code>. If neither is given, it will be <code>None</code>.</p>
<hr>
<p>If you really want to use a mutually-exclusive group, I'm not sure if you can do it exactly how you want. You <em>can</em>, however, make them optional arguments by adding a hyphen:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
command_group = parser.add_mutually_exclusive_group()
command_group.add_argument('-run', help='run it', action='store_true')
command_group.add_argument('-stop', help='stop it', action='store_true')
</code></pre>
<p>Of course the problem with that is that the user also needs to provide the hyphen, but that's the sort of problem you can expect if you limit yourself like that.</p>
| 2 | 2016-08-23T04:11:37Z | [
"python",
"python-2.7"
] |
Subtracting the values of two dictionaries | 39,092,224 | <p>I am trying to subtract dict1 - dict2. It does not matter if the result is a negative number for the dogs, I am just interested in learning the concept :) </p>
<pre><code>owner = ['Bob', 'Sarah', 'Ann']
dict1 = {'Bob': {'shepherd': [4,6,3],'collie': [23, 3, 45], 'poodle':[2,0,6]}, {'Sarah': {'shepherd': [1,2,3],'collie': [3, 31, 4], 'poodle': [21,5,6]},{'Ann': {'shepherd': [4,6,3],'collie': [23, 3, 45], 'poodle': [2,10,8]}}
dict2 = {'Bob': {'shepherd': 10,'collie': 15,'poodle': 34},'Sarah': {'shepherd': 3,'collie': 25,'poodle': 4},'Ann': {'shepherd': 2,'collie': 1,'poodle': 0}}
</code></pre>
<p>I want:</p>
<pre><code>wanted = dict1 = {'Bob': {'shepherd': [-6,-4,-7],'collie': [8, -12, 30], 'poodle':[-32,-34,-28]}, {'Sarah': {'shepherd': [-2,-1,0],'collie': [-22, 6, -21], 'poodle': [17,1,2]},{'Ann': {'shepherd': [2,4,1],'collie': [22, 2, 44], 'poodle': [2,10,8]}}
</code></pre>
<p>I am still new to dictionaries so here is what I have been trying but get NoneType error. I am assuming it is because dict1 has more values than dict2, but I cannot find a way to perform the above computation.</p>
<pre><code>wanted = {}
for i in owner:
wanted.update({i: dict1.get(i) - dict2.get(i)})
</code></pre>
| 3 | 2016-08-23T04:11:23Z | 39,092,283 | <p>You can use a nested dictionary comprehension. I tweaked your dictionary a bit because it wasn't correct syntax (there were a few extra curly braces). There is no need for an owners array because we can just use the keys in the dictionaries.</p>
<pre><code>dict1 = {
'Bob': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 0, 6],
},
'Sarah': {
'shepherd': [1, 2, 3],
'collie': [3, 31, 4],
'poodle': [21, 5, 6],
},
'Ann': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 10, 8],
}
}
dict2 = {
'Bob': {'shepherd': 10, 'collie': 15, 'poodle': 34},
'Sarah': {'shepherd': 3, 'collie': 25, 'poodle': 4},
'Ann': {'shepherd': 2, 'collie': 1, 'poodle': 0},
}
wanted = {
owner: {
dog: [num - dict2[owner][dog] for num in num_list]
for dog, num_list in dog_dict.iteritems()
} for owner, dog_dict in dict1.iteritems()
}
print wanted
</code></pre>
<p>Output:</p>
<pre><code>{
'Sarah': {
'shepherd': [-2, -1, 0],
'collie': [-22, 6, -21],
'poodle': [17, 1, 2]
},
'Bob': {
'shepherd': [-6, -4, -7],
'collie': [8, -12, 30],
'poodle': [-32, -34, -28]
},
'Ann': {
'shepherd': [2, 4, 1],
'collie': [22, 2, 44],
'poodle': [2, 10, 8]
}
}
</code></pre>
<p>This is assuming that dict2 has all of the same keys as dict1. If that's not the case, you'll need to set some default values to avoid a <code>KeyError</code>.</p>
<p><strong>EDIT</strong>: Here's a brief explanation of how to interpret the dictionary comprehension for those not familiar with it. If you're more comfortable with list comprehensions, a dictionary comprehension is very similar, only you create a dictionary instead of a list. So, <code>{i: str(i) for i in xrange(10)}</code> will give you a dictionary of <code>{0: '0', 1: '1', ..., 9: '9'}</code>.</p>
<p>Now we can apply that to the solution. This code:</p>
<pre><code>wanted = {
owner: {
dog: [num - dict2[owner][dog] for num in num_list]
for dog, num_list in dog_dict.iteritems()
} for owner, dog_dict in dict1.iteritems()
}
</code></pre>
<p>is equivalent to:</p>
<pre><code>wanted = {}
for owner, dog_dict in dict1.iteritems():
wanted[owner] = {}
for dog, num_list in dog_dict.iteritems():
wanted[owner][dog] = [num - dict2[owner][dog] for num in num_list]
</code></pre>
| 5 | 2016-08-23T04:18:02Z | [
"python",
"python-2.7",
"dictionary"
] |
Residual white pixels in transparent background from PIL | 39,092,325 | <p>I used this following code from another stackoverflow post</p>
<pre><code>from PIL import Image as image
img = image.open('output.png')
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save("img2.png", "PNG")
</code></pre>
<p>to transform my png's background to transparent. However, when I tried to add some shapes in powerpoint underneath the transparent image, it still has some residual white pixels left. Anyone know how to solve this?</p>
<p><a href="http://i.stack.imgur.com/WaJQS.png" rel="nofollow"><img src="http://i.stack.imgur.com/WaJQS.png" alt="enter image description here"></a></p>
| 1 | 2016-08-23T04:24:21Z | 39,111,459 | <p>Those pixels are <em>not</em> exactly "white". The color you are testing against and removing from the image <em>is</em>, with its value of <code>#FFFFFF</code>. But those slanted lines are heavily antialiased, "fading" from the pure white of the background to the pure color of the center of the lines.</p>
<p>This can be seen when zooming in just a teeny bit:</p>
<p><a href="http://i.stack.imgur.com/xxz9R.png" rel="nofollow"><img src="http://i.stack.imgur.com/xxz9R.png" alt="antialiasing at work"></a></p>
<p>You can lower the threshold of when to make a pixel entirely transparent:</p>
<pre><code>if item[0] > 240 and item[1] > 240 and item[2] > 240:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
</code></pre>
<p>but no matter how much you do this, you will always end up with either visibly lighter pixels around the lines, or â when only matching the center "line" color <em>exactly</em> â with disconnected pixels, not resembling the original lines anymore.</p>
<p>But there is no reason to use a Yes/No mask with PNG images! PNG supports full 8-bit transparency, and so you can make the 'solid' center lines fully opaque, the solid white fully transparent, and have the gradually darkening pixels fade between these values.</p>
<p>This works best if you know the exact original color that was used to draw the lines with. Measuring it with Adobe PhotoShop, I get something like <code>#818695</code>. Plugging in these values into your program and adjusting the 'tint' (towards white) to transparency, flattened towards the full possible range, I suggest this code:</p>
<pre><code>from PIL import Image as image
img = image.open('input.png')
img = img.convert("RGBA")
datas = img.getdata()
retain = (0x81,0x86,0x95)
retain_gray = (39*retain[0] + 50*retain[1] + 11*retain[2])
newData = []
for item in datas:
if item[0] > retain[0] and item[1] > retain[1] and item[2] > retain[2]:
# convert to grayscale
val = 39*item[0] + 50*item[1] + 11*item[2]
# invert
val = 25500 - val;
# difference with 'retain'
val = retain_gray - val
# scale down
val = 255*val/retain_gray
# invert to act as transparency
transp = 255-val
# apply transparency to original 'full' color value
newData.append((retain[0], retain[1], retain[2], transp ))
else:
newData.append(item)
img.putdata(newData)
img.save("output.png", "PNG")
print "done"
</code></pre>
<p>What it essentially does is converting the input image to grayscale, scaling it (because the scale from darkest to lightest should be in the full transparency range of 0..255), then using this as the 'transparent' byte. The result is way better than your on/off approach:</p>
<p><a href="http://i.stack.imgur.com/AyF1q.png" rel="nofollow"><img src="http://i.stack.imgur.com/AyF1q.png" alt="transparency added"></a></p>
| 2 | 2016-08-23T22:10:23Z | [
"python",
"png",
"python-imaging-library"
] |
Sklearn Pipeline - How to inherit get_params in custom Transformer (not Estimator) | 39,092,383 | <p>I have a pipeline in scikit-learn that uses a custom transformer I define like below:</p>
<pre><code>class MyPipelineTransformer(TransformerMixin):
</code></pre>
<p>which defines functions </p>
<pre><code>__init__, fit() and transform()
</code></pre>
<p>However, when I use the pipeline inside RandomizedSearchCV, I get the following error: </p>
<blockquote>
<p>'MyPipelineTransformer' object has no attribute 'get_params'</p>
</blockquote>
<p>I've read online (e.g. links below) </p>
<p><a href="http://stackoverflow.com/questions/27810855/python-sklearn-how-to-pass-parameters-to-the-customize-modeltransformer-clas">(Python - sklearn) How to pass parameters to the customize ModelTransformer class by gridsearchcv</a></p>
<p><a href="http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html</a></p>
<p>that I could get 'get_params' by inheriting from BaseEstimator, instead of my current code inheriting just from TransformerMixin. But my transformer is not an estimator. Is there any downside to having a non-estimator inherit from BaseEstimator? Or is that the recommended way to get get_params for any transformer (estimator or not) in a pipeline?</p>
| 1 | 2016-08-23T04:30:57Z | 39,093,021 | <p>Yes it looks like this is the standard way of achieving this. For example in the source for <code>sklearn.preprocessing</code> we have</p>
<pre><code>class FunctionTransformer(BaseEstimator, TransformerMixin)
</code></pre>
| 1 | 2016-08-23T05:30:23Z | [
"python",
"inheritance",
"scikit-learn",
"pipeline"
] |
Drop Multi-index and auto rename columns | 39,092,466 | <p>I'd like to transform the below output into: </p>
<ul>
<li><p>remove the multiindex(it should just be one row of index) </p></li>
<li><p>numbered accordingly Job 1, Job Effective Date 1, Job 2, Job Effective Date 2, etc.</p></li>
<li><p>I'd like this to be scalable if I choose to add or remove additional variables, I'd like to not have to modify the code to accommodate it (this is example is scaled down).</p></li>
</ul>
<p><strong>Some Data:</strong></p>
<pre><code>import pandas as pd
import numpy as np
data1 = {'Name': ["Joe", "Joe", "Joe","Jane","Jane"],
'Job': ["Analyst","Manager","Director","Analyst","Manager"],
'Job Eff Date': ["1/1/2015","1/1/2016","7/1/2016","1/1/2015","1/1/2016"]}
df2 = pd.DataFrame(data1, columns=['Name', 'Job', 'Job Eff Date'])
def tgrp(df):
df = df.drop('Name', axis=1)
return df.reset_index(drop=True).T
df2.groupby('Name').apply(tgrp).unstack()
</code></pre>
<p><a href="http://i.stack.imgur.com/IXcOj.png" rel="nofollow"><img src="http://i.stack.imgur.com/IXcOj.png" alt="enter image description here"></a></p>
| 1 | 2016-08-23T04:39:52Z | 39,092,607 | <p>Try:</p>
<pre><code>df3.columns = ['{} {}'.format(col[1], col[0]) for col in df3.columns]
</code></pre>
<p>if you are OK with 0-based indexing. Otherwise change to <code>col[0] + 1</code></p>
| 5 | 2016-08-23T04:53:45Z | [
"python",
"pandas",
"dataframe",
"group-by",
"multi-index"
] |
Drop Multi-index and auto rename columns | 39,092,466 | <p>I'd like to transform the below output into: </p>
<ul>
<li><p>remove the multiindex(it should just be one row of index) </p></li>
<li><p>numbered accordingly Job 1, Job Effective Date 1, Job 2, Job Effective Date 2, etc.</p></li>
<li><p>I'd like this to be scalable if I choose to add or remove additional variables, I'd like to not have to modify the code to accommodate it (this is example is scaled down).</p></li>
</ul>
<p><strong>Some Data:</strong></p>
<pre><code>import pandas as pd
import numpy as np
data1 = {'Name': ["Joe", "Joe", "Joe","Jane","Jane"],
'Job': ["Analyst","Manager","Director","Analyst","Manager"],
'Job Eff Date': ["1/1/2015","1/1/2016","7/1/2016","1/1/2015","1/1/2016"]}
df2 = pd.DataFrame(data1, columns=['Name', 'Job', 'Job Eff Date'])
def tgrp(df):
df = df.drop('Name', axis=1)
return df.reset_index(drop=True).T
df2.groupby('Name').apply(tgrp).unstack()
</code></pre>
<p><a href="http://i.stack.imgur.com/IXcOj.png" rel="nofollow"><img src="http://i.stack.imgur.com/IXcOj.png" alt="enter image description here"></a></p>
| 1 | 2016-08-23T04:39:52Z | 39,092,851 | <p>Another solution with <code>join</code>:</p>
<pre><code>df.columns = [' '.join((col[1], str(col[0] + 1))) for col in df.columns]
print (df)
Job 1 Job Eff Date 1 Job 2 Job Eff Date 2 Job 3 Job Eff Date 3
Name
Jane Analyst 1/1/2015 Manager 1/1/2016 NaN NaN
Joe Analyst 1/1/2015 Manager 1/1/2016 Director 7/1/2016
</code></pre>
<p>If need remove index name, use <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p>
<pre><code>df.columns = [' '.join((col[1], str(col[0] + 1))) for col in df.columns]
df = df.rename_axis(None)
print (df)
Job 1 Job Eff Date 1 Job 2 Job Eff Date 2 Job 3 Job Eff Date 3
Jane Analyst 1/1/2015 Manager 1/1/2016 NaN NaN
Joe Analyst 1/1/2015 Manager 1/1/2016 Director 7/1/2016
</code></pre>
<p>How it work:</p>
<p>List comprehension convert <code>MultiIndex</code> to <code>list</code> of <code>tuples</code>, which are joined by <code>join</code>, but first is necessary add <code>1</code> and convert <code>int</code> to <code>str</code> of each first item of tuples:</p>
<pre><code>print ([col for col in df.columns])
[(0, 'Job'), (0, 'Job Eff Date'),
(1, 'Job'), (1, 'Job Eff Date'),
(2, 'Job'), (2, 'Job Eff Date')]
</code></pre>
<p>Output is list of strings, which is assigned to column names:</p>
<pre><code>print ([' '.join((col[1], str(col[0] + 1))) for col in df.columns])
['Job 1', 'Job Eff Date 1', 'Job 2', 'Job Eff Date 2', 'Job 3', 'Job Eff Date 3']
</code></pre>
| 4 | 2016-08-23T05:12:45Z | [
"python",
"pandas",
"dataframe",
"group-by",
"multi-index"
] |
Implementing functions with dataframes in python | 39,092,584 | <p><a href="http://i.stack.imgur.com/we38M.png" rel="nofollow"><img src="http://i.stack.imgur.com/we38M.png" alt="enter image description here"></a>I have this problem where I am stuck for quite a number of days.</p>
<p>I have this function :</p>
<pre><code>def cal_score(research, citations, teaching, international, income):
return .3 **research + .3 **citations + .3 **teaching +.075 **international + .025 **income
</code></pre>
<p>where âresearchâ, âcitationsâ, âteachingâ, âinternationalâ and âincomeâ are columns of the dataset. I want to add a new column in the dataset whose values should be calculated based on the function mentioned above. I tried different procedures but none worked. </p>
<p>Example : If we have a row as below</p>
<pre><code>university_name Indian Institute of Technology Bombay
teaching 43.8
international 14.3
research 24.2
citations 8,327
income 14.9
Total Score Ranking
</code></pre>
<p>Then the total score should be calculated as</p>
<pre><code>Total Score = .3 **research + .3 **citations + .3 **teaching +.075 **international + .025 **income.
</code></pre>
<p>This should apply for all the rows in the dataset.</p>
<p>Can anyone please help me in implementing this requirement. I am stuck at this for quite sometime now. :-(</p>
<p>Indian_univ.head(10).to_dict()</p>
<pre><code>{'citations': {510: 38.799999999999997,
832: 39.0,
856: 45.600000000000001,
959: 45.799999999999997,
1232: 84.700000000000003,
1360: 38.5,
1361: 41.799999999999997,
1362: 35.299999999999997,
1363: 53.600000000000001,
1679: 51.600000000000001},
'country': {510: 'India',
832: 'India',
856: 'India',
959: 'India',
1232: 'India',
1360: 'India',
1361: 'India',
1362: 'India',
1363: 'India',
1679: 'India'},
'female_male_ratio': {510: '16 : 84',
832: '15 : 85',
856: '16 : 84',
959: '17 : 83',
1232: '46 : 54',
1360: '18 : 82',
1361: '13 : 87',
1362: '15 : 85',
1363: '17 : 83',
1679: '19 : 81'},
'income': {510: '24.2',
832: '72.4',
856: '52.7',
959: '70.4',
1232: '28.4',
1360: '-',
1361: '42.4',
1362: '-',
1363: '64.8',
1679: '37.9'},
'international': {510: '14.3',
832: '16.1',
856: '19.9',
959: '15.6',
1232: '29.3',
1360: '15.3',
1361: '17.3',
1362: '14.7',
1363: '15.6',
1679: '18.2'},
'international_students': {510: '1%',
832: '0%',
856: '1%',
959: '1%',
1232: '1%',
1360: '1%',
1361: '0%',
1362: '0%',
1363: '1%',
1679: '1%'},
'num_students': {510: '8,327',
832: '9,928',
856: '8,327',
959: '8,061',
1232: '16,691',
1360: '8,371',
1361: '6,167',
1362: '9,928',
1363: '8,061',
1679: '3,318'},
'research': {510: 15.699999999999999,
832: 45.299999999999997,
856: 33.100000000000001,
959: 13.699999999999999,
1232: 14.0,
1360: 23.0,
1361: 25.199999999999999,
1362: 30.0,
1363: 12.300000000000001,
1679: 39.5},
'student_staff_ratio': {510: 14.9,
832: 17.5,
856: 14.9,
959: 18.699999999999999,
1232: 23.899999999999999,
1360: 17.300000000000001,
1361: 12.199999999999999,
1362: 17.5,
1363: 18.699999999999999,
1679: 8.1999999999999993},
'teaching': {510: 43.799999999999997,
832: 44.200000000000003,
856: 47.299999999999997,
959: 30.399999999999999,
1232: 25.800000000000001,
1360: 33.799999999999997,
1361: 31.300000000000001,
1362: 39.299999999999997,
1363: 25.100000000000001,
1679: 32.600000000000001},
'total_score': {510: 29.489999999999995,
832: 38.549999999999997,
856: 37.799999999999997,
959: 26.969999999999999,
1232: 37.350000000000001,
1360: 28.589999999999996,
1361: 29.489999999999998,
1362: 31.379999999999995,
1363: 27.299999999999997,
1679: 37.109999999999999},
'university_name': {510: 'Indian Institute of Technology Bombay',
832: 'Indian Institute of Technology Kharagpur',
856: 'Indian Institute of Technology Bombay',
959: 'Indian Institute of Technology Roorkee',
1232: 'Panjab University',
1360: 'Indian Institute of Technology Delhi',
1361: 'Indian Institute of Technology Kanpur',
1362: 'Indian Institute of Technology Kharagpur',
1363: 'Indian Institute of Technology Roorkee',
1679: 'Indian Institute of Science'},
'world_rank': {510: '301-350',
832: '226-250',
856: '251-275',
959: '351-400',
1232: '226-250',
1360: '351-400',
1361: '351-400',
1362: '351-400',
1363: '351-400',
1679: '276-300'},
'year': {510: 2012,
832: 2013,
856: 2013,
959: 2013,
1232: 2014,
1360: 2014,
1361: 2014,
1362: 2014,
1363: 2014,
1679: 2015}}
</code></pre>
| 1 | 2016-08-23T04:51:56Z | 39,092,697 | <p>I think you can use:</p>
<pre><code>df['Total Score'] = .3 **df.research +
.3 **df.citations +
.3 **df.teaching +
.075 **df.international +
.025 **df.income
</code></pre>
<p>If need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> function, what is very often slowier:</p>
<pre><code>def cal_score(x):
return .3 **x.research +
.3 **x.citations +
.3 **x.teaching +
.075 **x.international +
.025 **x.income
df['Total Score'] = df.apply(cal_score, axis=1)
</code></pre>
<p>EDIT with data:</p>
<p>You need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>replace</code></a> columns <code>num_students</code> and <code>income</code> and then convert to <code>float</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a>:</p>
<p>EDIT2 by sample of data:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'citations': {510: 38.799999999999997, 832: 39.0, 856: 45.600000000000001, 959: 45.799999999999997, 1232: 84.700000000000003, 1360: 38.5, 1361: 41.799999999999997, 1362: 35.299999999999997, 1363: 53.600000000000001, 1679: 51.600000000000001}, 'country': {510: 'India', 832: 'India', 856: 'India', 959: 'India', 1232: 'India', 1360: 'India', 1361: 'India', 1362: 'India', 1363: 'India', 1679: 'India'}, 'female_male_ratio': {510: '16 : 84', 832: '15 : 85', 856: '16 : 84', 959: '17 : 83', 1232: '46 : 54', 1360: '18 : 82', 1361: '13 : 87', 1362: '15 : 85', 1363: '17 : 83', 1679: '19 : 81'}, 'income': {510: '24.2', 832: '72.4', 856: '52.7', 959: '70.4', 1232: '28.4', 1360: '-', 1361: '42.4', 1362: '-', 1363: '64.8', 1679: '37.9'}, 'international': {510: '14.3', 832: '16.1', 856: '19.9', 959: '15.6', 1232: '29.3', 1360: '15.3', 1361: '17.3', 1362: '14.7', 1363: '15.6', 1679: '18.2'}, 'international_students': {510: '1%', 832: '0%', 856: '1%', 959: '1%', 1232: '1%', 1360: '1%', 1361: '0%', 1362: '0%', 1363: '1%', 1679: '1%'}, 'num_students': {510: '8,327', 832: '9,928', 856: '8,327', 959: '8,061', 1232: '16,691', 1360: '8,371', 1361: '6,167', 1362: '9,928', 1363: '8,061', 1679: '3,318'}, 'research': {510: 15.699999999999999, 832: 45.299999999999997, 856: 33.100000000000001, 959: 13.699999999999999, 1232: 14.0, 1360: 23.0, 1361: 25.199999999999999, 1362: 30.0, 1363: 12.300000000000001, 1679: 39.5}, 'student_staff_ratio': {510: 14.9, 832: 17.5, 856: 14.9, 959: 18.699999999999999, 1232: 23.899999999999999, 1360: 17.300000000000001, 1361: 12.199999999999999, 1362: 17.5, 1363: 18.699999999999999, 1679: 8.1999999999999993}, 'teaching': {510: 43.799999999999997, 832: 44.200000000000003, 856: 47.299999999999997, 959: 30.399999999999999, 1232: 25.800000000000001, 1360: 33.799999999999997, 1361: 31.300000000000001, 1362: 39.299999999999997, 1363: 25.100000000000001, 1679: 32.600000000000001}, 'total_score': {510: 29.489999999999995, 832: 38.549999999999997, 856: 37.799999999999997, 959: 26.969999999999999, 1232: 37.350000000000001, 1360: 28.589999999999996, 1361: 29.489999999999998, 1362: 31.379999999999995, 1363: 27.299999999999997, 1679: 37.109999999999999}, 'university_name': {510: 'Indian Institute of Technology Bombay', 832: 'Indian Institute of Technology Kharagpur', 856: 'Indian Institute of Technology Bombay', 959: 'Indian Institute of Technology Roorkee', 1232: 'Panjab University', 1360: 'Indian Institute of Technology Delhi', 1361: 'Indian Institute of Technology Kanpur', 1362: 'Indian Institute of Technology Kharagpur', 1363: 'Indian Institute of Technology Roorkee', 1679: 'Indian Institute of Science'}, 'world_rank': {510: '301-350', 832: '226-250', 856: '251-275', 959: '351-400', 1232: '226-250', 1360: '351-400', 1361: '351-400', 1362: '351-400', 1363: '351-400', 1679: '276-300'}, 'year': {510: 2012, 832: 2013, 856: 2013, 959: 2013, 1232: 2014, 1360: 2014, 1361: 2014, 1362: 2014, 1363: 2014, 1679: 2015}})
</code></pre>
<pre><code>#replace , to empty string
df['num_students'] = df.num_students.str.replace(',', '')
#replace - to '0'
df['income'] = df['income'].str.replace('-', '0')
#convert columns to float
df[['teaching', 'international', 'research', 'citations', 'income']] =
df[['teaching', 'international', 'research', 'citations', 'income']].astype(float)
df['Total Score'] = .3 **df.research +
.3 **df.citations +
.3 **df.teaching +
.075 **df.international +
.025 **df.income
</code></pre>
<pre><code>print (df)
citations country female_male_ratio income international \
510 38.8 India 16 : 84 24.2 14.3
832 39.0 India 15 : 85 72.4 16.1
856 45.6 India 16 : 84 52.7 19.9
959 45.8 India 17 : 83 70.4 15.6
1232 84.7 India 46 : 54 28.4 29.3
1360 38.5 India 18 : 82 0.0 15.3
1361 41.8 India 13 : 87 42.4 17.3
1362 35.3 India 15 : 85 0.0 14.7
1363 53.6 India 17 : 83 64.8 15.6
1679 51.6 India 19 : 81 37.9 18.2
international_students num_students research student_staff_ratio \
510 1% 8327 15.7 14.9
832 0% 9928 45.3 17.5
856 1% 8327 33.1 14.9
959 1% 8061 13.7 18.7
1232 1% 16691 14.0 23.9
1360 1% 8371 23.0 17.3
1361 0% 6167 25.2 12.2
1362 0% 9928 30.0 17.5
1363 1% 8061 12.3 18.7
1679 1% 3318 39.5 8.2
teaching total_score university_name \
510 43.8 29.49 Indian Institute of Technology Bombay
832 44.2 38.55 Indian Institute of Technology Kharagpur
856 47.3 37.80 Indian Institute of Technology Bombay
959 30.4 26.97 Indian Institute of Technology Roorkee
1232 25.8 37.35 Panjab University
1360 33.8 28.59 Indian Institute of Technology Delhi
1361 31.3 29.49 Indian Institute of Technology Kanpur
1362 39.3 31.38 Indian Institute of Technology Kharagpur
1363 25.1 27.30 Indian Institute of Technology Roorkee
1679 32.6 37.11 Indian Institute of Science
world_rank year Total Score
510 301-350 2012 6.177371e-09
832 226-250 2013 7.776087e-19
856 251-275 2013 4.928529e-18
959 351-400 2013 6.863746e-08
1232 226-250 2014 4.782972e-08
1360 351-400 2014 1.000000e+00
1361 351-400 2014 6.664022e-14
1362 351-400 2014 1.000000e+00
1363 351-400 2014 3.703322e-07
1679 276-300 2015 9.003721e-18
</code></pre>
| 3 | 2016-08-23T05:00:55Z | [
"python",
"pandas",
"dataframe",
"dataset",
"data-science"
] |
Implementing functions with dataframes in python | 39,092,584 | <p><a href="http://i.stack.imgur.com/we38M.png" rel="nofollow"><img src="http://i.stack.imgur.com/we38M.png" alt="enter image description here"></a>I have this problem where I am stuck for quite a number of days.</p>
<p>I have this function :</p>
<pre><code>def cal_score(research, citations, teaching, international, income):
return .3 **research + .3 **citations + .3 **teaching +.075 **international + .025 **income
</code></pre>
<p>where âresearchâ, âcitationsâ, âteachingâ, âinternationalâ and âincomeâ are columns of the dataset. I want to add a new column in the dataset whose values should be calculated based on the function mentioned above. I tried different procedures but none worked. </p>
<p>Example : If we have a row as below</p>
<pre><code>university_name Indian Institute of Technology Bombay
teaching 43.8
international 14.3
research 24.2
citations 8,327
income 14.9
Total Score Ranking
</code></pre>
<p>Then the total score should be calculated as</p>
<pre><code>Total Score = .3 **research + .3 **citations + .3 **teaching +.075 **international + .025 **income.
</code></pre>
<p>This should apply for all the rows in the dataset.</p>
<p>Can anyone please help me in implementing this requirement. I am stuck at this for quite sometime now. :-(</p>
<p>Indian_univ.head(10).to_dict()</p>
<pre><code>{'citations': {510: 38.799999999999997,
832: 39.0,
856: 45.600000000000001,
959: 45.799999999999997,
1232: 84.700000000000003,
1360: 38.5,
1361: 41.799999999999997,
1362: 35.299999999999997,
1363: 53.600000000000001,
1679: 51.600000000000001},
'country': {510: 'India',
832: 'India',
856: 'India',
959: 'India',
1232: 'India',
1360: 'India',
1361: 'India',
1362: 'India',
1363: 'India',
1679: 'India'},
'female_male_ratio': {510: '16 : 84',
832: '15 : 85',
856: '16 : 84',
959: '17 : 83',
1232: '46 : 54',
1360: '18 : 82',
1361: '13 : 87',
1362: '15 : 85',
1363: '17 : 83',
1679: '19 : 81'},
'income': {510: '24.2',
832: '72.4',
856: '52.7',
959: '70.4',
1232: '28.4',
1360: '-',
1361: '42.4',
1362: '-',
1363: '64.8',
1679: '37.9'},
'international': {510: '14.3',
832: '16.1',
856: '19.9',
959: '15.6',
1232: '29.3',
1360: '15.3',
1361: '17.3',
1362: '14.7',
1363: '15.6',
1679: '18.2'},
'international_students': {510: '1%',
832: '0%',
856: '1%',
959: '1%',
1232: '1%',
1360: '1%',
1361: '0%',
1362: '0%',
1363: '1%',
1679: '1%'},
'num_students': {510: '8,327',
832: '9,928',
856: '8,327',
959: '8,061',
1232: '16,691',
1360: '8,371',
1361: '6,167',
1362: '9,928',
1363: '8,061',
1679: '3,318'},
'research': {510: 15.699999999999999,
832: 45.299999999999997,
856: 33.100000000000001,
959: 13.699999999999999,
1232: 14.0,
1360: 23.0,
1361: 25.199999999999999,
1362: 30.0,
1363: 12.300000000000001,
1679: 39.5},
'student_staff_ratio': {510: 14.9,
832: 17.5,
856: 14.9,
959: 18.699999999999999,
1232: 23.899999999999999,
1360: 17.300000000000001,
1361: 12.199999999999999,
1362: 17.5,
1363: 18.699999999999999,
1679: 8.1999999999999993},
'teaching': {510: 43.799999999999997,
832: 44.200000000000003,
856: 47.299999999999997,
959: 30.399999999999999,
1232: 25.800000000000001,
1360: 33.799999999999997,
1361: 31.300000000000001,
1362: 39.299999999999997,
1363: 25.100000000000001,
1679: 32.600000000000001},
'total_score': {510: 29.489999999999995,
832: 38.549999999999997,
856: 37.799999999999997,
959: 26.969999999999999,
1232: 37.350000000000001,
1360: 28.589999999999996,
1361: 29.489999999999998,
1362: 31.379999999999995,
1363: 27.299999999999997,
1679: 37.109999999999999},
'university_name': {510: 'Indian Institute of Technology Bombay',
832: 'Indian Institute of Technology Kharagpur',
856: 'Indian Institute of Technology Bombay',
959: 'Indian Institute of Technology Roorkee',
1232: 'Panjab University',
1360: 'Indian Institute of Technology Delhi',
1361: 'Indian Institute of Technology Kanpur',
1362: 'Indian Institute of Technology Kharagpur',
1363: 'Indian Institute of Technology Roorkee',
1679: 'Indian Institute of Science'},
'world_rank': {510: '301-350',
832: '226-250',
856: '251-275',
959: '351-400',
1232: '226-250',
1360: '351-400',
1361: '351-400',
1362: '351-400',
1363: '351-400',
1679: '276-300'},
'year': {510: 2012,
832: 2013,
856: 2013,
959: 2013,
1232: 2014,
1360: 2014,
1361: 2014,
1362: 2014,
1363: 2014,
1679: 2015}}
</code></pre>
| 1 | 2016-08-23T04:51:56Z | 39,092,731 | <p>Here is the most straightforward way:</p>
<pre><code>df.assign(TotalScore=.3 **df.research + .3 **df.citations + .3 **df.teaching +.075 **df.international + .025 **df.income)
</code></pre>
| 1 | 2016-08-23T05:03:35Z | [
"python",
"pandas",
"dataframe",
"dataset",
"data-science"
] |
How to print amount_to_text in Indian Rupees format in Odoo reports.? | 39,092,619 | <p>I was trying to print the invoice amount in words in Odoo, </p>
<p>Following is the code in .py</p>
<pre><code>@api.multi
def amount_to_text(self, amount_total, currency='INR'):
return amount_to_text(amount_total, currency)
</code></pre>
<p>and following was the code in qweb report,</p>
<pre><code><div class="row">
<div class="col-xs-10">
<strong><td>Total in words:</td></strong>
<span t-esc="o.amount_to_text(o.amount_total,
'INR')"/>
</div>
</div>
</code></pre>
<p>but the report always shows the words in euros(as in the below image), not able to print it in INR format. Is there any over-riding of amount_to_text method.</p>
<p><a href="http://i.stack.imgur.com/jvKrO.png" rel="nofollow"><img src="http://i.stack.imgur.com/jvKrO.png" alt="Amount in Euro words"></a></p>
| 1 | 2016-08-23T04:54:40Z | 39,110,206 | <p>First of all go to Settings -> Reports -> Reports and search for <code>invoices</code> in order to find the Invoice report that interests you. Open it, and uncheck <code>Reload from attachment</code>.</p>
<p>If <code>Reload from attachment</code> is checked only the first time the report will be generated for a record and it will be saved in the database. If you try to re-print the report (for the same record), Odoo will fetch the saved one and will not re-render a new one.</p>
<p>Also, I checked the definition of this method of Odoo and it does not match your definition.</p>
<p>On <code>openerp/tools/amount_to_text.py</code> around line 170 you will find the definition of this method. You can see that it is a static method that is offered as a tool so the proper way to use this method would be:</p>
<p><code>from openerp.tools.amount_to_text import amount_to_text</code></p>
<p>Now you can call the method with the relevant arguments. The method is sufficiently documented and you can figure out easily how it is used.</p>
| 1 | 2016-08-23T20:34:10Z | [
"python",
"openerp",
"odoo-8"
] |
Numpy 2D- Array from Buffer? | 39,092,664 | <p>I have an memory map, which contains a 2D array and I would like to make a numpy array from it. Ideally, i would like to avoid copying, since the involved array can be big.</p>
<p>My code looks like this:</p>
<pre><code>n_bytes = 10000
tagname = "Some Tag from external System"
map = mmap.mmap(-1, n_bytes, tagname)
offsets = [0, 5000]
columns = []
for offset in offsets:
#type and count vary in the real code, but for this dummy code I simply made them up. But I know the count and type for every column.
np_type = np.dtype('f4')
column_data = np.frombuffer(map, np_type, count=500, offset=offset)
columns.append(column_data)
# this line seems to copy the data, which I would like to avoid
data = np.array(columns).T
</code></pre>
| 0 | 2016-08-23T04:57:40Z | 39,093,256 | <p>I haven't used <code>frombuffer</code> much, but I think the <code>np.array</code> works with those arrays as it does with conventionally constructed ones.</p>
<p>Each <code>column_data</code> array will have its own data buffer - the mmap you assigned it. But <code>np.array(columns)</code> reads the values from each array in the list, and constructs a new array from them, with its own data buffer.</p>
<p>I like to use <code>x.__array_interface__</code> to look at the data buffer location (and to see other key attributes). Compare that dictionary for each element of <code>columns</code> and for <code>data</code>.</p>
<p>You can construct a 2d array from a mmap - using a contiguous block. Just make the 1d <code>frombuffer</code> array, and <code>reshape</code> it. Even <code>transpose</code> will continue to use that buffer (with <code>F</code> order). Slices and views also use it.</p>
<p>But unless you are real careful you'll quickly get copies that put the data elsewhere. Simply <code>data1 = data+1</code> makes a new array, or advance indexing <code>data[[1,3,5],:]</code>. Same for any <code>concatenation</code>.</p>
<p>2 arrays from bytestring buffers:</p>
<pre><code>In [534]: x=np.frombuffer(b'abcdef',np.uint8)
In [535]: y=np.frombuffer(b'ghijkl',np.uint8)
</code></pre>
<p>a new array by joining them</p>
<pre><code>In [536]: z=np.array((x,y))
In [538]: x.__array_interface__
Out[538]:
{'data': (3013090040, True),
'descr': [('', '|u1')],
'shape': (6,),
'strides': None,
'typestr': '|u1',
'version': 3}
In [539]: y.__array_interface__['data']
Out[539]: (3013089608, True)
In [540]: z.__array_interface__['data']
Out[540]: (180817384, False)
</code></pre>
<p>the data buffer locations for <code>x,y,z</code> are totally different</p>
<p>But the data for reshaped <code>x</code> doesn't change</p>
<pre><code>In [541]: x.reshape(2,3).__array_interface__['data']
Out[541]: (3013090040, True)
</code></pre>
<p>nor does the 2d transpose</p>
<pre><code>In [542]: x.reshape(2,3).T.__array_interface__
Out[542]:
{'data': (3013090040, True),
'descr': [('', '|u1')],
'shape': (3, 2),
'strides': (1, 3),
'typestr': '|u1',
'version': 3}
</code></pre>
<p>Same data, different view</p>
<pre><code>In [544]: x
Out[544]: array([ 97, 98, 99, 100, 101, 102], dtype=uint8)
In [545]: x.reshape(2,3).T
Out[545]:
array([[ 97, 100],
[ 98, 101],
[ 99, 102]], dtype=uint8)
In [546]: x.reshape(2,3).T.view('S1')
Out[546]:
array([[b'a', b'd'],
[b'b', b'e'],
[b'c', b'f']],
dtype='|S1')
</code></pre>
| 1 | 2016-08-23T05:48:19Z | [
"python",
"numpy"
] |
How to delete a dictionary in a list, if the same dictionary is in another list (Python 2.7) | 39,092,701 | <p>I have two lists that include same dictionaries in the format of:</p>
<p>List 1:</p>
<pre><code>[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads','title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}, {'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]
</code></pre>
<p>List 2:</p>
<pre><code>[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads', 'title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}]
</code></pre>
<p>What I wanted to do:
I would like to delete the dictionary(both url and title) in list 1 which is also present in list2.</p>
<p>I have tried the following,</p>
<pre><code>list1[:] = [d for d in list1 if d.get('title') != (fail for fail in list2 if fail.get('title'))]
</code></pre>
<p>but couldn't manage to do it</p>
<p>Expected Result:</p>
<pre><code>list1 = [{'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]
</code></pre>
| 0 | 2016-08-23T05:01:15Z | 39,092,839 | <p>Just do a simple comparison:</p>
<pre><code>>>> final = [i for i in one if i not in two]
>>> final
[{'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]
</code></pre>
<p>Then you can do <code>list1 = final</code> if you really want.</p>
| 5 | 2016-08-23T05:11:23Z | [
"python",
"python-2.7",
"dictionary",
"list-comprehension"
] |
How to delete a dictionary in a list, if the same dictionary is in another list (Python 2.7) | 39,092,701 | <p>I have two lists that include same dictionaries in the format of:</p>
<p>List 1:</p>
<pre><code>[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads','title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}, {'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]
</code></pre>
<p>List 2:</p>
<pre><code>[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads', 'title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}]
</code></pre>
<p>What I wanted to do:
I would like to delete the dictionary(both url and title) in list 1 which is also present in list2.</p>
<p>I have tried the following,</p>
<pre><code>list1[:] = [d for d in list1 if d.get('title') != (fail for fail in list2 if fail.get('title'))]
</code></pre>
<p>but couldn't manage to do it</p>
<p>Expected Result:</p>
<pre><code>list1 = [{'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]
</code></pre>
| 0 | 2016-08-23T05:01:15Z | 39,092,841 | <p>If I understand correctly, you want <code>list1</code> to consist only of the entries whose title does not exist in <code>list2</code>. This is probably best done with a two step process, to avoid repeated linear scans of <code>list2</code> for each element in <code>list1</code>:</p>
<pre><code># Make a set of all titles defined by the dicts in list2
titles_in_list2 = {d['title'] for d in list2 if 'title' in d}
# Filter the contents of list1 to only items with titles not found in list2
list1[:] = [d for d in list1 if d.get('title') not in titles_in_list2]
</code></pre>
<p>Note: The <code>.get</code> call in the second comprehension, and the <code>if</code> check in the first aren't needed if all entries are guaranteed to have a <code>title</code> key defined. The <code>.get</code> would become straight lookup, <code>d['title'] not in titles_in_list2</code>, and the <code>if 'title' in d</code> check would be dropped entirely. You also don't need the slice assignment unless other references to <code>list1</code> might exist and must be changed; if that's not a concern, <code>list1 = [...]</code> is fine.</p>
| 1 | 2016-08-23T05:11:48Z | [
"python",
"python-2.7",
"dictionary",
"list-comprehension"
] |
How to delete a dictionary in a list, if the same dictionary is in another list (Python 2.7) | 39,092,701 | <p>I have two lists that include same dictionaries in the format of:</p>
<p>List 1:</p>
<pre><code>[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads','title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}, {'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]
</code></pre>
<p>List 2:</p>
<pre><code>[{'url': u'http://www.bloomberg.com/news/articles/2016-08-17/you-can-get-a-50-phone-from-amazon-if-you-don-t-mind-the-ads', 'title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads'}]
</code></pre>
<p>What I wanted to do:
I would like to delete the dictionary(both url and title) in list 1 which is also present in list2.</p>
<p>I have tried the following,</p>
<pre><code>list1[:] = [d for d in list1 if d.get('title') != (fail for fail in list2 if fail.get('title'))]
</code></pre>
<p>but couldn't manage to do it</p>
<p>Expected Result:</p>
<pre><code>list1 = [{'url': u'http://www.bloomberg.com/news/features/2016-08-18/uber-s-first-self-driving-fleet-arrives-in-pittsburgh-this-month-is06r7on', 'title': u'Uber\u2019s First Self-Driving Fleet Arrives in Pittsburgh This Month'}]
</code></pre>
| 0 | 2016-08-23T05:01:15Z | 39,093,523 | <p>Burhan Khalid's answer is perfect.
In case, you want a solution matching to your line of previous thoughts, here it is :
<br/>
<code>list1 = [d for d in list1 if d.get('title') not in [f.get('title') for f in list2]]</code></p>
| 0 | 2016-08-23T06:07:31Z | [
"python",
"python-2.7",
"dictionary",
"list-comprehension"
] |
Tkinter pack Entry Widgets Based On OptionMenu Value, pack_forget Otherwise | 39,092,707 | <p>When <code>tk.OptionMenu</code> is equivalent to <code>CUSTOM</code>, the code below displays two <code>tk.Entry</code> fields. How does one hide the <code>tk.Entry</code> fields from view after a <code>tk.OptionMenu</code> is selected that's not <code>CUSTOM</code>?</p>
<p>For example, the code below displays two fields if user selects <code>CUSTOM</code> from the dropdown, but if the user goes to select another option, I want to remove the two fields that were added from view and display them again if <code>CUSTOM</code> is selected from the dropdown again. In a sense, toggle them.</p>
<p>My research has turned up <strong>pack_forget</strong>, <strong>destroy</strong>, <strong>trace</strong>. I can't seem to figure it out.</p>
<p><a href="http://i.stack.imgur.com/Clszd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Clszd.png" alt="tkinter"></a></p>
<pre><code>import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
def func(*args):
if date_var.get() == 'CUSTOM':
new_frame = tk.Frame(frame)
new_frame.pack(side=tk.LEFT)
field1 = tk.Entry(new_frame)
field2 = tk.Entry(new_frame)
field1.pack()
field2.pack()
else:
try:
new_frame.destroy()
except:
pass
date_var = tk.StringVar()
date_var.trace('w', func)
date_var.set('LAST_10_DAYS')
date_options = ['CUSTOM', 'LAST_10_DAYS', 'LAST_50_DAYS', 'LAST_10_MILLION_YEARS']
date = tk.OptionMenu(frame, date_var, *date_options)
date.pack(pady=10)
root.mainloop()
</code></pre>
| 1 | 2016-08-23T05:01:49Z | 39,104,384 | <p>I got it to work by putting <code>field1</code> and <code>field2</code> in a <code>new_frame</code> (<code>tk.Frame</code>) <strong>outside of the function</strong>. Then I let an if statement determine whether to <code>pack</code> or <code>pack_forget</code> <code>new_frame</code> based on the value from the <code>OptionMenu</code>. Can't say if this is the best way but it works for now.</p>
<pre><code>import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
new_frame = tk.Frame(frame)
field1 = tk.Entry(new_frame)
field2 = tk.Entry(new_frame)
field1.pack()
field2.pack()
def func(*args):
if date_var.get() == 'CUSTOM':
new_frame.pack(side=tk.LEFT)
else:
new_frame.pack_forget()
date_var = tk.StringVar()
date_var.trace('w', func)
date_var.set('LAST_10_DAYS')
date_options = ['CUSTOM', 'LAST_10_DAYS', 'LAST_50_DAYS', 'LAST_10_MILLION_YEARS']
date = tk.OptionMenu(frame, date_var, *date_options)
date.pack(pady=10)
root.mainloop()
</code></pre>
| 1 | 2016-08-23T14:48:35Z | [
"python",
"tkinter",
"trace",
"entry",
"optionmenu"
] |
allen brain institute - brain observatory example | 39,092,740 | <p>I'm trying to follow the example of <a href="https://alleninstitute.github.io/AllenSDK/_static/examples/nb/brain_observatory.html" rel="nofollow">brain observatory ipython notebook</a>.</p>
<p>However, I became stuck loading the <code>nwb</code> file like below.</p>
<pre><code>from allensdk.core.brain_observatory_cache import BrainObservatoryCache
boc = BrainObservatoryCache(manifest_file='boc/manifest.json')
data_set = boc.get_ophys_experiment_data(501940850) # problem here
</code></pre>
<p>So, I opened the <code>nwb</code> file by <a href="https://www.hdfgroup.org/products/java/hdfview/" rel="nofollow">HDFview</a>.</p>
<p>All of the brain observatory <code>nwb</code> files were not opened except for <code>502376461.nwb</code>.</p>
<p>When I tried to open the <code>502376461.nwb</code> in the ipython notebook example from allen, it worked!! But the others (<code>501940850</code>, <code>503820068</code>...) failed like above.</p>
| 1 | 2016-08-23T05:04:23Z | 39,358,028 | <p>Summarizing the thread from github: </p>
<p><a href="https://github.com/AllenInstitute/AllenSDK/issues/22" rel="nofollow">https://github.com/AllenInstitute/AllenSDK/issues/22</a></p>
<p>The files were partially downloaded or corrupted somehow. No exceptions were reported during the download, so urllib must not have noticed a problem.</p>
<p>AllenSDK developers are investigating some sort of file consistency check and/or a different HTTP library.</p>
<p><a href="https://github.com/AllenInstitute/AllenSDK/issues/28" rel="nofollow">https://github.com/AllenInstitute/AllenSDK/issues/28</a></p>
<p>If others run into this, you can delete the bad file and re-run the download function (<code>BrainObservatoryCache.get_ophys_experiment_data</code>). Files are downloaded into a subdirectory of the BrainObservatoryCache <a href="http://alleninstitute.github.io/AllenSDK/_static/examples/nb/brain_observatory.html#Experiment-Containers" rel="nofollow">manifest file</a>, which defaults to the current working directory if unspecified.</p>
| 0 | 2016-09-06T21:20:50Z | [
"python",
"validation",
"neuroscience",
"neuron-simulator"
] |
automatically change object colors in pymol from python | 39,092,780 | <p>I am trying to change the color of many objects in pymol from python. I made this for loop </p>
<pre><code>obs = ['R8', 'R1X', 'R2X', 'R11']
for i in obs:
print "color gray, %s" % i
</code></pre>
<p>from pymol I run </p>
<pre><code>run myscript.py
</code></pre>
<p>but the pymol interface simply prints the the command that should change the color, and does not change the color of the structure. </p>
| 0 | 2016-08-23T05:07:33Z | 39,190,186 | <p>In order to execute Pymol commands from python you need to use <a href="http://pymol.org/pymol-command-ref.html" rel="nofollow"><code>cmd</code></a>. In your case this would be:</p>
<pre><code>cmd.color('gray', i)
</code></pre>
| 1 | 2016-08-28T10:10:09Z | [
"python",
"colors",
"pymol"
] |
python unicode to original text character when being used as string not when printing | 39,092,924 | <p>I want an unicoded string I am getting from a method, I want to look like original text character rather than an unicode.</p>
<pre><code>a=u'\u2018\u0997\u09c7\u09ae\u09bf\u0982 \u09aa\u09cd\u09b2\u09be\u099f\u09ab\u09b0\u09cd\u09ae\u2019 \u09a4\u09c8\u09b0\u09bf \u0995\u09b0\u09ac\u09c7 \u09ab\u09c7\u09b8\u09ac\u09c1\u0995'
print a #âà¦à§à¦®à¦¿à¦ পà§à¦²à¦¾à¦à¦«à¦°à§à¦®â তà§à¦°à¦¿ à¦à¦°à¦¬à§ ফà§à¦¸à¦¬à§à¦
</code></pre>
<p>Print always works, but my use case is different. The things that it is printing, I want it put it on my RESTful API, or at least I want to use it as a string of original character and if I leave as it is my clients who will be using it on html won't be able to use it easily, I suspect.</p>
<p>The end result should look like this:</p>
<pre><code>{title: âà¦à§à¦®à¦¿à¦ পà§à¦²à¦¾à¦à¦«à¦°à§à¦®â তà§à¦°à¦¿ à¦à¦°à¦¬à§ ফà§à¦¸à¦¬à§à¦ }
</code></pre>
<p>but json dumps is like:</p>
<pre><code>json.dumps({'a': u})
'{"a": "\\\\u0996\\\\u09be\\\\u09b2\\\\u09bf\\\\u09df\\\\u09be\\\\u099c\\\\u09c1\\\\u09b0\\\\u09c0\\\\u09a4\\\\u09c7 \\\\u09a6\\\\u09c1\\\\u0987 \\\\u0997\\\\u09cd\\\\u09b0\\\\u09c1\\\\u09aa\\\\u09c7\\\\u09b0 \\\\u09b8\\\\u0982\\\\u0998\\\\u09b0\\\\u09cd\\\\u09b7\\\\u09c7 \\\\u09a8\\\\u09be\\\\u09b0\\\\u09c0\\\\u09b8\\\\u09b9 \\\\u0986\\\\u09b9\\\\u09a4 \\\\u09e7\\\\u09e6"}'
</code></pre>
<p>So, chances are I would need something like,</p>
<pre><code>blog={}
blog['title']= str(a) # or something else
</code></pre>
<p>I have tried following so far, but no luck so far:</p>
<pre><code>>>> str(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
>>> a.encode('utf-8')
'\xe2\x80\x98\xe0\xa6\x97\xe0\xa7\x87\xe0\xa6\xae\xe0\xa6\xbf\xe0\xa6\x82 \xe0\xa6\xaa\xe0\xa7\x8d\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\x9f\xe0\xa6\xab\xe0\xa6\xb0\xe0\xa7\x8d\xe0\xa6\xae\xe2\x80\x99 \xe0\xa6\xa4\xe0\xa7\x88\xe0\xa6\xb0\xe0\xa6\xbf \xe0\xa6\x95\xe0\xa6\xb0\xe0\xa6\xac\xe0\xa7\x87 \xe0\xa6\xab\xe0\xa7\x87\xe0\xa6\xb8\xe0\xa6\xac\xe0\xa7\x81\xe0\xa6\x95'
>>> a.encode('utf8')
'\xe2\x80\x98\xe0\xa6\x97\xe0\xa7\x87\xe0\xa6\xae\xe0\xa6\xbf\xe0\xa6\x82 \xe0\xa6\xaa\xe0\xa7\x8d\xe0\xa6\xb2\xe0\xa6\xbe\xe0\xa6\x9f\xe0\xa6\xab\xe0\xa6\xb0\xe0\xa7\x8d\xe0\xa6\xae\xe2\x80\x99 \xe0\xa6\xa4\xe0\xa7\x88\xe0\xa6\xb0\xe0\xa6\xbf \xe0\xa6\x95\xe0\xa6\xb0\xe0\xa6\xac\xe0\xa7\x87 \xe0\xa6\xab\xe0\xa7\x87\xe0\xa6\xb8\xe0\xa6\xac\xe0\xa7\x81\xe0\xa6\x95'
>>> a.__str__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
>>> a.decode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
</code></pre>
| 1 | 2016-08-23T05:20:23Z | 39,093,193 | <p>You're misunderstanding the <code>repr</code> of a Python object. Those escapes in your literal string are actually being converted internally to the "real" characters that Python is displaying when you <code>print</code> (that is, internally, it's storing a single Unicode ordinal for each of the escapes, not the escapes themselves). You don't need to encode it unless you need the raw bytes in a particular encoding (and decoding it is nonsensical; <code>unicode</code> objects have that method in Py2, but it's usually wrong to use it, because <code>unicode</code> is by definition not encoded bytes).</p>
<p>Basically, just use the <code>unicode</code> object you've got and it's the text you expect, it just may not display that way when you're using the interactive interpreter (which is echoing <code>repr</code>s of the object, which displays the escapes instead of the actual characters, partially to ensure it won't error out if you lack the fonts or language support to display the real characters). Unicode friendly libraries will work with it exactly the way you expect, the length is usually the character count (in Py2, on 16 bit <code>wchar</code> systems with non-BMP ordinals, this may not be true, but it's usually true).</p>
<p>That said, I'd recommend switching to Python 3 for any non-ASCII intensive work; Python 2 support for Unicode is less consistent and has many more gaps and pitfalls. Many third party packages, and even some built-in packages (<em>cough</em> <code>csv</code> <em>cough</em>) are not <code>unicode</code> friendly, so you end up needing to explicitly <code>encode</code> to use them, then <code>decode</code> their results.</p>
| 3 | 2016-08-23T05:44:25Z | [
"python",
"html",
"string",
"unicode",
"utf-8"
] |
Install Openalpr in Windows python | 39,092,992 | <p>I am using <strong>Windows 10</strong> and I want to install <strong>openalpr</strong> and import the library to <strong>python</strong>. </p>
<p>However, after downloaded the <strong>Pre-compiled Windows binaries</strong>, I dont know how ti import alpr in python</p>
<p>I follow the instruction in <a href="https://github.com/openalpr/openalpr" rel="nofollow">OpenAlpr</a></p>
<p>I downloaded the <strong>openalpr-2.3.0-win-64bit.zip</strong> <a href="https://github.com/openalpr/openalpr/releases" rel="nofollow">here</a> and unzipped it.</p>
<p>Afterwards, I can run <code>alpr</code> in command line but I cannot import it.</p>
<p>Can anyone teach me how I can import Openalpr in python. Thank you.</p>
| 4 | 2016-08-23T05:27:51Z | 39,215,441 | <p>When you've downloaded the binary distribution, navigate to <code>python</code> subdirectory and run <code>python setup.py</code>. This would install OpenALPR as package, so then you would be able to import it from anywhere, not just from ALPR's directory.</p>
<p><strong>Explaination</strong>:
To be importable, it requires that the package you're trying to import been else:</p>
<ol>
<li>In current directory, from where you run <code>python</code></li>
<li>Specified via <code>PYTHONPATH</code> environment variable</li>
<li>Part of standard library</li>
<li>Specified in one of <code>.pth</code> files</li>
<li>Located in <code>site-packages</code> dir</li>
<li>Added to <code>sys.path</code> by hand</li>
</ol>
<p>And when you run <code>setup.py</code> script, it kicks distutils to properly copy package's distribution to <code>site-packages</code>, thus adding it to your libs. </p>
<p>For more information, see <a href="https://pythonhosted.org/an_example_pypi_project/setuptools.html#using-setup-py" rel="nofollow">setup.py usage</a> and <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">how import system works</a></p>
| 2 | 2016-08-29T21:22:57Z | [
"python",
"python-2.7",
"python-3.x",
"open-source",
"openalpr"
] |
Install Openalpr in Windows python | 39,092,992 | <p>I am using <strong>Windows 10</strong> and I want to install <strong>openalpr</strong> and import the library to <strong>python</strong>. </p>
<p>However, after downloaded the <strong>Pre-compiled Windows binaries</strong>, I dont know how ti import alpr in python</p>
<p>I follow the instruction in <a href="https://github.com/openalpr/openalpr" rel="nofollow">OpenAlpr</a></p>
<p>I downloaded the <strong>openalpr-2.3.0-win-64bit.zip</strong> <a href="https://github.com/openalpr/openalpr/releases" rel="nofollow">here</a> and unzipped it.</p>
<p>Afterwards, I can run <code>alpr</code> in command line but I cannot import it.</p>
<p>Can anyone teach me how I can import Openalpr in python. Thank you.</p>
| 4 | 2016-08-23T05:27:51Z | 39,245,480 | <p>I setted up the same environment as you:</p>
<ul>
<li>Anaconda 4.0 installed into <code>C:\Users\user\Anaconda</code></li>
<li>OpenAlpr installed into <code>C:\Users\user\Downloads\openalpr-2.3.0-win-64bit</code></li>
</ul>
<p>So I can call <code>python</code> from the console (<code>cmd</code>) and get:</p>
<pre><code>Python 2.7.11 |Anaconda 4.0.0 (64-bit)
...
</code></pre>
<hr>
<h1>The module</h1>
<p>As the bindings are not shipped with the pre-compiled Windows binaries, you have to install the module manually:</p>
<ul>
<li>download the <a href="https://github.com/openalpr/openalpr/archive/master.zip" rel="nofollow">GitHub repo as ZIP</a>;</li>
<li>extract the archive to a temporary folder, let's say <code>C:\Users\user\Downloads\openalpr-master</code>;</li>
<li>Python binding is into the <code>C:\Users\user\Downloads\openalpr-master\src\bindings\python</code> folder;</li>
<li>open a console into this directory and type <code>python setup.py install</code></li>
</ul>
<p>Voilà , the Python module OpenAlpr is installed!.</p>
<p>Call <code>python_test.bat</code> from the OpenAlpr directory to see it works.</p>
<hr>
<h1>Usage</h1>
<p>To be able to import OpenAlpr module from Python, two solutions.</p>
<p>Solution 1: you will need to work into the OpenAlpr directory where DLL files are located.
Then, it should works as expected:</p>
<pre><code>>>> from openalpr import Alpr
>>> alpr = Alpr('us', 'openalpr.conf', 'runtime_data')
>>> alpr.is_loaded()
True
</code></pre>
<p>Solution 2 (best I think): you update the <code>PATH</code> to include the OpenAlpr folder:</p>
<pre><code>>>> from os import environ
>>> alpr_dir ='C:\Users\user\Downloads\openalpr-2.3.0-win-64bit\openalpr_64'
>>> environ['PATH'] = alpr_dir + ';' + environ['PATH']
>>> from openalpr import Alpr
>>> alpr = Alpr('us', alpr_dir + '/openalpr.conf', alpr_dir + '/runtime_data')
>>> alpr.is_loaded()
True
</code></pre>
| -1 | 2016-08-31T09:15:31Z | [
"python",
"python-2.7",
"python-3.x",
"open-source",
"openalpr"
] |
Extracting date and time from a list in python | 39,093,089 | <p>I have a very simple list like this :</p>
<pre><code>['Monday,30 December,2013', 'Delivered_it', '19:23', '1']
</code></pre>
<p>Please guide me how to extract from this list the date , status and time </p>
<p><strong>NOTE</strong> : I don't simply want to extract it like a string but as a <strong>date.time</strong> objects so that I could do some analysis on it .</p>
| -2 | 2016-08-23T05:35:04Z | 39,119,010 | <pre><code>import datetime
data = ['Monday,30 December,2013', 'Delivered_it', '19:23', '1']
data = '{} {}'.format(data[0], data[2])
timestamp = datetime.datetime.strptime(data, '%A,%d %B,%Y %H:%M')
print timestamp # 2013-12-30 19:23:00
</code></pre>
| 1 | 2016-08-24T09:08:50Z | [
"python",
"list",
"python-2.7",
"date",
"time"
] |
Python module already installed but getting import error | 39,093,092 | <p>I have started getting this error for a few modules in python after I 'brew installed python' on my OS X El Capitan. I know that Mac comes with python 2.7 but due to some issues I had to install python explicitly using brew. Now I get this error. </p>
<pre><code>~/Desktop â 10:57:29
$ python f.py
Traceback (most recent call last):
File "f.py", line 1, in <module>
import youtube_dl
ImportError: No module named youtube_dl
~/Desktop â 10:57:30
$ pip install youtube_dl
Requirement already satisfied (use --upgrade to upgrade): youtube_dl in /usr/local/lib/python2.7/site-packages
</code></pre>
| 0 | 2016-08-23T05:35:23Z | 39,094,939 | <p>This error may come from :</p>
<ol>
<li><p>The python you run by default isnât the same that you call by your script : To check this, Please check this command (<code>$ which python</code>)
Is this what you put on the top of your script?</p></li>
<li><p>Brew doesnât make symbol link, itâs common issue : Please take a look here(<a href="http://stackoverflow.com/questions/5157678/python-homebrew-by-default">python homebrew by default</a>)</p></li>
</ol>
<p>I highly recommend to you virtualenv (<a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">https://virtualenv.pypa.io/en/stable/</a>) so you can mange different version of python without altering your OS installation.</p>
<p>Using (<code>pip install youtube_dl</code>) like this, install the package for the current version of python. To be sure, just type (<code>$ pip freeze</code>). </p>
<p>Hope this helps. Good luck :)</p>
| 1 | 2016-08-23T07:29:42Z | [
"python",
"module",
"pip",
"youtube-dl"
] |
How can I write a MapReduce code in Python to implement a matrix transpose. | 39,093,171 | <p>Assume the input file is a .txt and I am trying to run it on a cluster(like EMR on AWS) to test.</p>
| 0 | 2016-08-23T05:42:41Z | 39,094,305 | <p>The problem with what you want is that you demand that the order of the lines will be kept, meaning</p>
<p>if you have:<br>
a,b,c<br>
d,e,f<br>
g,h,i </p>
<p>you want the output to be<br>
a,d,g<br>
b,e,h<br>
c,f,i </p>
<p>But the MapReduce does not work like this.
The MR will get the file and split the file to different map reduce task,
I could have given you a code that will produce something like the transpose,
meaning</p>
<p>it can be:<br>
a,g,d<br>
g,e,h<br>
i,c,f </p>
<p>because the line will be send to the same map, but the order of the lines is not kept.</p>
<p>unless you can do some preprocessing on the file and add also line number as a parameter to each line.</p>
<p>if you could do that, the code is very simple:</p>
<p>lets say this is your file (the number on the left is line index)</p>
<ol>
<li>a,b,c,d </li>
<li>e,f,g,h </li>
<li>i,j,k,l </li>
</ol>
<p>then, when its flow in the emr cluster, the emr breaks the file to lines.
lets say the line index is first like this:<br>
1,a,b,c<br>
2,d,e,f<br>
3,g,h,i </p>
<pre><code>def map():
for line in sys.stdin:
splitted_line = line.strip().split()
line_index, values = splitted_line[0], splitted_line[1:]
for column_index, value in enumerate(values):
# emits a record were the key in the column index,
# and the value is the line number and the value.
# the '\t' is the delimiter the emr use by default to
# identify the separator between the key and value
# the line looks like this:
# "<column_index>|\t|<line_index>|<value>"
print '|'.join(column_index,'\t',line_index,value)
def reduce():
old_column_index = None
line_to_emit = list()
for line in sys.stdin:
values = line.split("|")
column_index, line_index, value = values[0], values[2], values[3]
if not old_column_index:
old_column_index = column_index
if column_index == old_column_index:
line_to_emit.append((line_index,value))
else:
old_column_index = column_index
sorted_line = sorted(line_to_emit, key=lambda value:value[0])
only_values_line = [value[1] for value in sorted_line]
print ','.join(only_values_line)
</code></pre>
<p>But still even after all this, the lines in the output will not be in the order you need. and you will have to sort them yourself, possible way, pass the index of the new line yourself.</p>
| 0 | 2016-08-23T06:57:17Z | [
"python",
"mapreduce",
"elastic-map-reduce"
] |
Scrapy - offsite request to be processed based on a regex | 39,093,211 | <p>I have to crawl 5-6 domains. I wanted to write a the crawler as such that the offsite requests if contains a some substrings example set as [ aaa,bbb,ccc]
if the offsite url contain a substring from the above set then it should be processed and not filter out. Should i write a custom middleware or can i just use regular expression in the allowed domains. </p>
| -1 | 2016-08-23T05:46:14Z | 39,098,601 | <p>Offsite middleware already uses regex by default, however it's no exposed. It compiles the domains you provide into regex, but the domains are escaped so providing regex code in <code>allowed_domains</code> would not work.</p>
<p>What you can do though is extend that middleware and override <code>get_host_regex()</code> method to implement your own offsite policy.</p>
<p>The original code in <code>scrapy.spidermiddlewares.offsite.OffsiteMiddleware</code>:</p>
<pre><code>def get_host_regex(self, spider):
"""Override this method to implement a different offsite policy"""
allowed_domains = getattr(spider, 'allowed_domains', None)
if not allowed_domains:
return re.compile('') # allow all by default
regex = r'^(.*\.)?(%s)$' % '|'.join(re.escape(d) for d in allowed_domains if d is not None)
return re.compile(regex)
</code></pre>
<p>You can just override to return your own regex:</p>
<pre><code># middlewares.py
class MyOffsiteMiddleware(OffsiteMiddleware):
def get_host_regex(self, spider):
allowed_regex = getattr(spider, 'allowed_regex', '')
return re.compile(allowed_regex)
# spiders/myspider.py
class MySpider(scrapy.Spider):
allowed_regex = '.+?\.com'
# settings.py
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.MyOffsiteMiddleware': 666,
}
</code></pre>
| 1 | 2016-08-23T10:26:05Z | [
"python",
"regex",
"scrapy"
] |
PyQt5 QListView sluggish first drag/drop on windows - python 3.5/3.4 32bit, pyqt5 from sourceforge | 39,093,226 | <p>I have installed 32bit Python 3.4 and 3.5 and PyQt5 on our windows 7 work machine via the executable available from <a href="https://sourceforge.net/projects/pyqt/" rel="nofollow">https://sourceforge.net/projects/pyqt/</a>, however I now find that when I run my simple drag and drop test code it is very sluggish moving the first element (the ui freezes for about 4-5 seconds before completing the move). All subsequent drag and drop operations happen without that delay.</p>
<p>By "ui freezes" I mean that the selection remains highlit and in its original place when i move the cursor away and the drag and drop guide graphics (a line appearing where the items would move to if i let the mouse button go at that time, the mouse cursor changing to a different icon to indicate that drag and drop is occuring) do not appear. If I release the mouse button during this time the selected elements are moved to that location but not until the 4-5 second wait time has elapsed.</p>
<p>The code is as follows:</p>
<pre><code>from PyQt5.QtWidgets import QMainWindow, QApplication, QListView, QAbstractItemView
from PyQt5.QtGui import QStandardItemModel, QStandardItem
def createModel():
model = QStandardItemModel()
for i in range(0,101):
item = QStandardItem(str(i))
item.setText(str(i))
item.setEditable(False)
item.setDropEnabled(False)
model.appendRow(item)
return model
class TestListView(QMainWindow):
def __init__(self, parent=None):
super(TestListView, self).__init__(parent)
self.listView = QListView()
self.setCentralWidget(self.listView)
self.listView.setModel(createModel())
self.listView.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.listView.setDragEnabled(True)
self.listView.setDragDropMode(QAbstractItemView.InternalMove)
def main():
app = QApplication([])
lvt = TestListView()
lvt.show()
app.exec_()
if __name__ == '__main__':
main()
</code></pre>
<p>I am hoping someone can point out a foolish mistake I've made that is the cause of this issue (like when I earlier had passed ints to the QStandardItems constructor instead of strings, resulting in a crash each time I tried to drag and drop), but if that isn't the case, if anyone is able to recommend a combination of pyqt5 and 32bit (64bit is not an option for us) python components that they've found that does not exhibit this behaviour? I don't really care if it's python 3.x or python 2.x (although I haven't seen any pyqt5/python2 combinations previously), as long as it works.</p>
<p>I've tried the python-qt5 package that pip installs (after following the instructions here <a href="https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/" rel="nofollow">https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/</a> by installing visual c++ build tools) in both 3.4 and 3.5, but the full version of this script will use .ui files from QtCreator, and the pip version of python-qt5 throws an error:</p>
<pre><code> File "testReorder.py", line 2, in <module>
from PyQt5 import uic
File "c:\python35-32\lib\site-packages\PyQt5\uic\__init__.py", line 43, in <module>
from .Compiler import indenter, compiler
File "c:\python35-32\lib\site-packages\PyQt5\uic\Compiler\compiler.py", line 43, in <module>
from ..properties import Properties
File "c:\python35-32\lib\site-packages\PyQt5\uic\properties.py", line 46, in <module>
from .icon_cache import IconCache
File "c:\python35-32\lib\site-packages\PyQt5\uic\icon_cache.py", line 27, in <module>
from .port_v3.as_string import as_string
ImportError: No module named 'PyQt5.uic.port_v3'
</code></pre>
<p>when I include the import line</p>
<pre><code>from PyQt5 import uic
</code></pre>
<p>in the code.</p>
<p>Edit: Having gotten home and tested the code on my linux machine (and seen no signs of sluggishness), I'm thinking this issue must be either specific to the combination of the pyqt, python and windows version, or something specific to that particular windows installation, and not a problem with my code.</p>
<p>I'd still be interested in hearing of anyone able to run the same code and not see the same issues on a windows (especially windows 7) machine, but I'm thinking it's less likely that I can assign the blame for this behaviour solely at pyqt's door.</p>
| 0 | 2016-08-23T05:46:38Z | 39,325,880 | <p>Ran same code on another windows 7 computer with same packages installed. The issue is not seen there, so is obviously a problem with something specific to this machine rather than the code I've written/versions of python I'm using/version of pyqt.</p>
| 0 | 2016-09-05T07:43:10Z | [
"python",
"windows",
"drag-and-drop",
"pyqt5"
] |
List index out of range error in web scraping | 39,093,330 | <p>I am now building a web-scraping program with Python 3.5 and bs4. In the code below I tried to retrieve the data from two tables in the url. I succeed in the first table, but error pops out for the second one. The error is "IndexError: list index out of range" for "D.append(cells[0].find(text=True))". I have checked the list indices for "cells', which gives me 0,1,2, so should be no problem. Could anyone suggest any ideas on solving this issue? </p>
<pre><code>import tkinter as tk
def test():
from bs4 import BeautifulSoup
import urllib.request
import pandas as pd
url_text = 'http://www.sce.hkbu.edu.hk/future-students/part-time/short-courses-regular.php?code=EGE1201'
resp = urllib.request.urlopen(url_text)
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))
all_tables=soup.find_all('table')
print (all_tables)
right_table=soup.find('table', {'class' : 'info'})
A=[]
B=[]
C=[]
for row in right_table.findAll("tr"):
cells = row.findAll('td')
A.append(cells[0].find(text=True))
B.append(cells[1].find(text=True))
C.append(cells[2].find(text=True))
df=pd.DataFrame()
df[""]=A
df["EGE1201"]=C
print(df)
D=[]
E=[]
F=[]
right_table=soup.find('table', {'class' : 'schedule'})
for row in right_table.findAll("tr"):
try:
cells = row.findAll('th')
except:
cells = row.findAll('td')
D.append(cells[0].find(text=True))
E.append(cells[1].find(text=True))
F.append(cells[2].find(text=True))
df1=pd.DataFrame()
df[D[0]]=D[1]
df[E[0]]=E[1]
df[F[0]]=F[1]
print(df1)
if __name__ == '__main__':
test()
</code></pre>
| 1 | 2016-08-23T05:53:50Z | 39,093,512 | <p>It looks like you're expecting this code to choose between 'th' and 'td', but it will not. It will always choose 'th' and will return an empty list when there is no 'th' in that row.</p>
<pre><code> try:
cells = row.findAll('th')
except:
cells = row.findAll('td')
</code></pre>
<p>Instead, I would change the code to check if the list is empty and then request 'td':</p>
<pre><code> cells = row.findAll('th')
if not cells:
cells = row.findAll('td')
</code></pre>
<p>Alternatively you can shorten the code to this:</p>
<pre><code> cells = row.findAll('th') or row.findAll('td')
</code></pre>
| 1 | 2016-08-23T06:06:52Z | [
"python",
"web-scraping"
] |
Error while connecting remote sql express database which is on windows -- connction using pyodbc | 39,093,348 | <p>I am using Ubuntu system and I want to connect to remote database SQL Express. </p>
<p>I have tried the same using <strong>pyodbc</strong> using following steps.</p>
<ol>
<li><code>sudo apt-get install python-pyodbc</code></li>
<li>Python code as follows :</li>
</ol>
<p></p>
<pre><code> import pyodbc
cnxn = pyodbc.connect(DRIVER='{SQL Server}', SERVER='REMOTE_SERVER_IP', DATABASE='REMOTE_SERVER_DB_NAME', UID='redbytes', PWD='REMOTE_SERVER_DB_PASSWORD')
cursor = cnxn.cursor()
</code></pre>
<p>But I am facing problem as follows :</p>
<pre><code>pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')
</code></pre>
| 0 | 2016-08-23T05:54:55Z | 39,093,565 | <p>Have you checked the name of the driver in your ~/.odbc.ini file? This person had the same error as you and fixing that solved their problem:</p>
<p><a href="http://stackoverflow.com/questions/16280304/pyodbc-data-source-name-not-found-and-no-default-driver-specified">Pyodbc - "Data source name not found, and no default driver specified"</a></p>
| 0 | 2016-08-23T06:09:55Z | [
"python",
"sql-server",
"ubuntu-14.04",
"pyodbc"
] |
numpy.ndarray syntax understanding for confirmation | 39,093,472 | <p>I am referring the code example here (<a href="http://scikit-learn.org/stable/auto_examples/linear_model/plot_iris_logistic.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/linear_model/plot_iris_logistic.html</a>), and specifically confused by this line <code>iris.data[:, :2]</code>, since iris.data is 150 (row) * 4 (column) dimensional I think it means, select all rows, and the first two columns. I ask here to confirm if my understanding is correct, since I take time but cannot find such syntax definition official document.</p>
<p>Another question is, I am using the following code to get # of rows and # of columns, not sure if better more elegant ways? My code is more Python native style and not sure if numpy has better style to get the related values.</p>
<pre><code>print len(iris.data) # for number of rows
print len(iris.data[0]) # for number of columns
</code></pre>
<p>Using Python 2.7 with miniconda interpreter.</p>
<pre><code>print(__doc__)
# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, datasets
# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :2] # we only take the first two features.
Y = iris.target
h = .02 # step size in the mesh
logreg = linear_model.LogisticRegression(C=1e5)
# we create an instance of Neighbours Classifier and fit the data.
logreg.fit(X, Y)
# Plot the decision boundary. For that, we will assign a color to each
# point in the mesh [x_min, m_max]x[y_min, y_max].
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1, figsize=(4, 3))
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())
plt.show()
</code></pre>
<p>regards,
Lin</p>
| 0 | 2016-08-23T06:04:27Z | 39,093,793 | <p>You are right. The first syntax selects the first 2 columns/features. Another way to query dimensions is to look at <code>iris.data.shape</code>. This will return a n-dimensional tuple with the length. You can find some documentation here: <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a></p>
<pre><code>import numpy as np
x = np.random.rand(100, 200)
# Select the first 2 columns
y = x[:, :2]
# Get the row length
print (y.shape[0])
# Get the column length
print (y.shape[1])
# Number of dimensions
print (len(y.shape))
</code></pre>
| 1 | 2016-08-23T06:26:06Z | [
"python",
"python-2.7",
"numpy",
"machine-learning",
"logistic-regression"
] |
how to join incorporate splitted lines with replacing data from a file into the same string | 39,093,525 | <p>So as most of us are thinking it's a duplicate which is not, so what I'm trying to achieve is let's say there is a Master string like the below and couple of files mentioned in it then we need to open the files and check if there are any other files included in it, if so we need to copy that into the line where we fetched that particular text.</p>
<p>Master String:</p>
<blockquote>
<p>Welcome<br>
How are you<br>
file.txt<br>
everything alright<br>
signature.txt<br>
Thanks </p>
</blockquote>
<p>file.txt</p>
<p>ABCD<br>EFGH<br>tele.txt</p>
<p>tele.txt</p>
<blockquote>
<p>IJKL</p>
</blockquote>
<p>signature.txt</p>
<blockquote>
<p>SAK</p>
</blockquote>
<p>Output:</p>
<p><p>Welcome<br>
How are you<br>
ABCD<br>
EFGH<br>
IJKL<br>
everything alright <br>
SAK <br>
Thanks <br></p>
<pre><code>for msplitin [stext.split('\n')]:
for num, items in enumerate(stext,1):
if items.strip().startswith("here is") and items.strip().endswith(".txt"):
gmsf = open(os.path.join(os.getcwd()+"\txt", items[8:]), "r")
gmsfstr = gmsf.read()
newline = items.replace(items, gmsfstr)
</code></pre>
<p>How to join these replace items in the same string format.</p>
<p>Also, any idea on how to re-iterate the same function until there are no ".txt". So, once the join is done there might be other ".txt" inside a ".txt.</p>
<p>Thanks for your help in advance.</p>
| 1 | 2016-08-23T06:07:41Z | 39,093,753 | <p>You can try:</p>
<pre><code>s = """Welcome
How are you
here is file.txt
everything alright
here is signature.txt
Thanks"""
data = s.split("\n")
match = ['.txt']
all_matches = [s for s in data if any(xs in s for xs in match)]
for index, item in enumerate(data):
if item in all_matches:
data[index] ="XYZ"
data = "\n".join(data)
print data
</code></pre>
<p>Output:</p>
<pre><code>Welcome
How are you
XYZ
everything alright
XYZ
Thanks
</code></pre>
<p><strong>Added new requirement:</strong></p>
<pre><code>def file_obj(filename):
fo = open(filename,"r")
s = fo.readlines()
data = s.split("\n")
match = ['.txt']
all_matches = [s for s in data if any(xs in s for xs in match)]
for index, item in enumerate(data):
if item in all_matches:
file_obj(item)
data[index] ="XYZ"
data = "\n".join(data)
print data
file_obj("first_filename")
</code></pre>
| 1 | 2016-08-23T06:23:00Z | [
"python",
"python-2.7",
"python-3.x"
] |
how to join incorporate splitted lines with replacing data from a file into the same string | 39,093,525 | <p>So as most of us are thinking it's a duplicate which is not, so what I'm trying to achieve is let's say there is a Master string like the below and couple of files mentioned in it then we need to open the files and check if there are any other files included in it, if so we need to copy that into the line where we fetched that particular text.</p>
<p>Master String:</p>
<blockquote>
<p>Welcome<br>
How are you<br>
file.txt<br>
everything alright<br>
signature.txt<br>
Thanks </p>
</blockquote>
<p>file.txt</p>
<p>ABCD<br>EFGH<br>tele.txt</p>
<p>tele.txt</p>
<blockquote>
<p>IJKL</p>
</blockquote>
<p>signature.txt</p>
<blockquote>
<p>SAK</p>
</blockquote>
<p>Output:</p>
<p><p>Welcome<br>
How are you<br>
ABCD<br>
EFGH<br>
IJKL<br>
everything alright <br>
SAK <br>
Thanks <br></p>
<pre><code>for msplitin [stext.split('\n')]:
for num, items in enumerate(stext,1):
if items.strip().startswith("here is") and items.strip().endswith(".txt"):
gmsf = open(os.path.join(os.getcwd()+"\txt", items[8:]), "r")
gmsfstr = gmsf.read()
newline = items.replace(items, gmsfstr)
</code></pre>
<p>How to join these replace items in the same string format.</p>
<p>Also, any idea on how to re-iterate the same function until there are no ".txt". So, once the join is done there might be other ".txt" inside a ".txt.</p>
<p>Thanks for your help in advance.</p>
| 1 | 2016-08-23T06:07:41Z | 39,097,002 | <p>We can create temporary file object and keep the replaced line in that temporary file object and once everything line is processed then we can replace with the new content to original file. This temporary file will be deleted automatically once its come out from the 'with' statement. </p>
<pre><code>import tempfile
import re
file_pattern = re.compile(ur'(((\w+)\.txt))')
original_content_file_name = 'sample.txt'
"""
sample.txt should have this content.
Welcome
How are you
here is file.txt
everything alright
here is signature.txt
Thanks
"""
replaced_file_str = None
def replace_file_content():
"""
replace the file content using temporary file object.
"""
def read_content(file_name):
# matched file name is read and returned back for replacing.
content = ""
with open(file_name) as fileObj:
content = fileObj.read()
return content
# read the file and keep the replaced text in temporary file object(tempfile object will be deleted automatically).
with open(original_content_file_name, 'r') as file_obj, tempfile.NamedTemporaryFile() as tmp_file:
for line in file_obj.readlines():
if line.strip().startswith("here is") and line.strip().endswith(".txt"):
file_path = re.search(file_pattern, line).group()
line = read_content(file_path) + '\n'
tmp_file.write(line)
tmp_file.seek(0)
# assign the replaced value to this variable
replaced_file_str = tmp_file.read()
# replace with new content to the original file
with open(original_content_file_name, 'w+') as file_obj:
file_obj.write(replaced_file_str)
replace_file_content()
</code></pre>
| 0 | 2016-08-23T09:11:29Z | [
"python",
"python-2.7",
"python-3.x"
] |
how to join incorporate splitted lines with replacing data from a file into the same string | 39,093,525 | <p>So as most of us are thinking it's a duplicate which is not, so what I'm trying to achieve is let's say there is a Master string like the below and couple of files mentioned in it then we need to open the files and check if there are any other files included in it, if so we need to copy that into the line where we fetched that particular text.</p>
<p>Master String:</p>
<blockquote>
<p>Welcome<br>
How are you<br>
file.txt<br>
everything alright<br>
signature.txt<br>
Thanks </p>
</blockquote>
<p>file.txt</p>
<p>ABCD<br>EFGH<br>tele.txt</p>
<p>tele.txt</p>
<blockquote>
<p>IJKL</p>
</blockquote>
<p>signature.txt</p>
<blockquote>
<p>SAK</p>
</blockquote>
<p>Output:</p>
<p><p>Welcome<br>
How are you<br>
ABCD<br>
EFGH<br>
IJKL<br>
everything alright <br>
SAK <br>
Thanks <br></p>
<pre><code>for msplitin [stext.split('\n')]:
for num, items in enumerate(stext,1):
if items.strip().startswith("here is") and items.strip().endswith(".txt"):
gmsf = open(os.path.join(os.getcwd()+"\txt", items[8:]), "r")
gmsfstr = gmsf.read()
newline = items.replace(items, gmsfstr)
</code></pre>
<p>How to join these replace items in the same string format.</p>
<p>Also, any idea on how to re-iterate the same function until there are no ".txt". So, once the join is done there might be other ".txt" inside a ".txt.</p>
<p>Thanks for your help in advance.</p>
| 1 | 2016-08-23T06:07:41Z | 39,105,614 | <p>A recursive approach that works with any level of file name nesting:</p>
<pre><code>from os import linesep
def get_text_from_file(file_path):
with open(file_path) as f:
text = f.read()
return SAK_replace(text)
def SAK_replace(s):
lines = s.splitlines()
for index, l in enumerate(lines):
if l.endswith('.txt'):
lines[index] = get_text_from_file(l)
return linesep.join(lines)
</code></pre>
| 1 | 2016-08-23T15:47:19Z | [
"python",
"python-2.7",
"python-3.x"
] |
Python with MySql unicode problems | 39,093,532 | <p>I need to call MySQL stored procedure from my python script. As one of parameters I'm passing a unicode string (Russian language), but I get an error;</p>
<blockquote>
<p>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)</p>
</blockquote>
<p>My script:</p>
<pre><code> self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName")
self.cursor=self.db.cursor()
args=("какой-Ñо ÑекÑÑ") #this is string in russian
self.cursor.callproc('pr_MyProc', args)
self.cursor.execute('SELECT @_pr_MyProc_2') #getting result from sp
result=self.cursor.fetchone()
self.db.commit()
</code></pre>
<p>I've read that setting <code>charset='utf8'</code> shuld resolve this problem, but when I use string:</p>
<pre><code>self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName", charset='utf8')
</code></pre>
<p>This gives me another error;</p>
<blockquote>
<p>UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd1' in position 20: surrogates not allowed</p>
</blockquote>
<p>Also I've trying to set parametr <code>use_unicode=True</code>, that's not working.</p>
| 9 | 2016-08-23T06:07:55Z | 39,107,719 | <p>More things to check on:
<a href="http://mysql.rjweb.org/doc.php/charcoll#python">http://mysql.rjweb.org/doc.php/charcoll#python</a></p>
<p>Likely items:</p>
<ul>
<li>Start code file with <code># -*- coding: utf-8 -*-</code> -- (for literals in code) </li>
<li>Literals should be u'...' </li>
</ul>
<p>Can you extract the HEX? <code>какой-Ñо ÑекÑÑ</code> should be this in utf8: <code>D0BA D0B0 D0BA D0BE D0B9 2D D182 D0BE D182 20 D0B5 D0BA D181 D182</code></p>
| 5 | 2016-08-23T17:47:47Z | [
"python",
"mysql",
"unicode",
"utf-8",
"character-encoding"
] |
Python with MySql unicode problems | 39,093,532 | <p>I need to call MySQL stored procedure from my python script. As one of parameters I'm passing a unicode string (Russian language), but I get an error;</p>
<blockquote>
<p>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)</p>
</blockquote>
<p>My script:</p>
<pre><code> self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName")
self.cursor=self.db.cursor()
args=("какой-Ñо ÑекÑÑ") #this is string in russian
self.cursor.callproc('pr_MyProc', args)
self.cursor.execute('SELECT @_pr_MyProc_2') #getting result from sp
result=self.cursor.fetchone()
self.db.commit()
</code></pre>
<p>I've read that setting <code>charset='utf8'</code> shuld resolve this problem, but when I use string:</p>
<pre><code>self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName", charset='utf8')
</code></pre>
<p>This gives me another error;</p>
<blockquote>
<p>UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd1' in position 20: surrogates not allowed</p>
</blockquote>
<p>Also I've trying to set parametr <code>use_unicode=True</code>, that's not working.</p>
| 9 | 2016-08-23T06:07:55Z | 39,142,011 | <p>The MySQLdb module is not compatible with python 3. That might be why you are getting problems. I would advise to use a different connector, like <a href="https://github.com/PyMySQL/PyMySQL%20%22PyMySQL" rel="nofollow">PyMySQL</a> or <a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">mysqlclient</a>.</p>
<p>Related: <a href="http://stackoverflow.com/questions/23376103/python-3-4-0-with-mysql-database">23376103</a>.</p>
| 2 | 2016-08-25T09:52:14Z | [
"python",
"mysql",
"unicode",
"utf-8",
"character-encoding"
] |
Python with MySql unicode problems | 39,093,532 | <p>I need to call MySQL stored procedure from my python script. As one of parameters I'm passing a unicode string (Russian language), but I get an error;</p>
<blockquote>
<p>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)</p>
</blockquote>
<p>My script:</p>
<pre><code> self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName")
self.cursor=self.db.cursor()
args=("какой-Ñо ÑекÑÑ") #this is string in russian
self.cursor.callproc('pr_MyProc', args)
self.cursor.execute('SELECT @_pr_MyProc_2') #getting result from sp
result=self.cursor.fetchone()
self.db.commit()
</code></pre>
<p>I've read that setting <code>charset='utf8'</code> shuld resolve this problem, but when I use string:</p>
<pre><code>self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName", charset='utf8')
</code></pre>
<p>This gives me another error;</p>
<blockquote>
<p>UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd1' in position 20: surrogates not allowed</p>
</blockquote>
<p>Also I've trying to set parametr <code>use_unicode=True</code>, that's not working.</p>
| 9 | 2016-08-23T06:07:55Z | 39,148,601 | <p>Here are some thoughts. Maybe not a response. I've been playing with python/mysql/utf-8/unicode in the past and this is the things i remember:</p>
<p>Looking at Saltstack mysql module's comment :</p>
<p><a href="https://github.com/saltstack/salt/blob/develop/salt/modules/mysql.py#L314-L322" rel="nofollow">https://github.com/saltstack/salt/blob/develop/salt/modules/mysql.py#L314-L322</a></p>
<pre><code># MySQLdb states that this is required for charset usage
# but in fact it's more than it's internally activated
# when charset is used, activating use_unicode here would
# retrieve utf8 strings as unicode() objects in salt
# and we do not want that.
#_connarg('connection_use_unicode', 'use_unicode')
connargs['use_unicode'] = False
_connarg('connection_charset', 'charset')
</code></pre>
<p>We see that to avoid altering the result string the use_unicode is set to False, while the charset (which could be utf-8) is set as a parameter. use_unicode is more a 'request' to get responses as unicode strings.</p>
<p>You can check real usage in the tests, here:
<a href="https://github.com/saltstack/salt/blob/develop/tests/integration/modules/mysql.py#L315-L365" rel="nofollow">https://github.com/saltstack/salt/blob/develop/tests/integration/modules/mysql.py#L315-L365</a> with a database named 'æ¨æºèª'.</p>
<p>Now about the message <strong>UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd1' **. You are using **unicode</strong> but you tell the module it is <strong>utf-8</strong>. It is not <strong>utf-8</strong> until you encode your unicode string in utf-8.</p>
<p>Maybe you should try with:</p>
<pre><code>args=(u"какой-Ñо ÑекÑÑ".encode('utf-8'))
</code></pre>
<p>At least in python3 this is required, because your "какой-Ñо ÑекÑÑ" is not in utf-8 by default.</p>
| 3 | 2016-08-25T14:57:26Z | [
"python",
"mysql",
"unicode",
"utf-8",
"character-encoding"
] |
Python with MySql unicode problems | 39,093,532 | <p>I need to call MySQL stored procedure from my python script. As one of parameters I'm passing a unicode string (Russian language), but I get an error;</p>
<blockquote>
<p>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)</p>
</blockquote>
<p>My script:</p>
<pre><code> self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName")
self.cursor=self.db.cursor()
args=("какой-Ñо ÑекÑÑ") #this is string in russian
self.cursor.callproc('pr_MyProc', args)
self.cursor.execute('SELECT @_pr_MyProc_2') #getting result from sp
result=self.cursor.fetchone()
self.db.commit()
</code></pre>
<p>I've read that setting <code>charset='utf8'</code> shuld resolve this problem, but when I use string:</p>
<pre><code>self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName", charset='utf8')
</code></pre>
<p>This gives me another error;</p>
<blockquote>
<p>UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd1' in position 20: surrogates not allowed</p>
</blockquote>
<p>Also I've trying to set parametr <code>use_unicode=True</code>, that's not working.</p>
| 9 | 2016-08-23T06:07:55Z | 39,217,383 | <p>What's your database's charset?
<br>use :</p>
<pre><code>show variables like "characetr%";
</code></pre>
<p>or see your database's charset</p>
| 1 | 2016-08-30T01:09:40Z | [
"python",
"mysql",
"unicode",
"utf-8",
"character-encoding"
] |
Python with MySql unicode problems | 39,093,532 | <p>I need to call MySQL stored procedure from my python script. As one of parameters I'm passing a unicode string (Russian language), but I get an error;</p>
<blockquote>
<p>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)</p>
</blockquote>
<p>My script:</p>
<pre><code> self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName")
self.cursor=self.db.cursor()
args=("какой-Ñо ÑекÑÑ") #this is string in russian
self.cursor.callproc('pr_MyProc', args)
self.cursor.execute('SELECT @_pr_MyProc_2') #getting result from sp
result=self.cursor.fetchone()
self.db.commit()
</code></pre>
<p>I've read that setting <code>charset='utf8'</code> shuld resolve this problem, but when I use string:</p>
<pre><code>self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName", charset='utf8')
</code></pre>
<p>This gives me another error;</p>
<blockquote>
<p>UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd1' in position 20: surrogates not allowed</p>
</blockquote>
<p>Also I've trying to set parametr <code>use_unicode=True</code>, that's not working.</p>
| 9 | 2016-08-23T06:07:55Z | 39,228,907 | <p>Maybe you can reload your <code>sys</code> in <code>utf-8</code> and try to decode the string into <code>utf-8</code> as following :</p>
<pre><code>import sys
reload(sys)
sys.setdefaultencoding("utf-8")
...
stringUtf8 = u''.join(string_original).decode('utf-8')
</code></pre>
| 2 | 2016-08-30T13:30:38Z | [
"python",
"mysql",
"unicode",
"utf-8",
"character-encoding"
] |
Python with MySql unicode problems | 39,093,532 | <p>I need to call MySQL stored procedure from my python script. As one of parameters I'm passing a unicode string (Russian language), but I get an error;</p>
<blockquote>
<p>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)</p>
</blockquote>
<p>My script:</p>
<pre><code> self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName")
self.cursor=self.db.cursor()
args=("какой-Ñо ÑекÑÑ") #this is string in russian
self.cursor.callproc('pr_MyProc', args)
self.cursor.execute('SELECT @_pr_MyProc_2') #getting result from sp
result=self.cursor.fetchone()
self.db.commit()
</code></pre>
<p>I've read that setting <code>charset='utf8'</code> shuld resolve this problem, but when I use string:</p>
<pre><code>self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName", charset='utf8')
</code></pre>
<p>This gives me another error;</p>
<blockquote>
<p>UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd1' in position 20: surrogates not allowed</p>
</blockquote>
<p>Also I've trying to set parametr <code>use_unicode=True</code>, that's not working.</p>
| 9 | 2016-08-23T06:07:55Z | 39,229,820 | <p>I see here two problems.</p>
<ol>
<li><p>You have unicode but you try to define it as utf-8 by setting parameter "charset". You should first encode your unicode to utf-8 or another encoding system.</p></li>
<li><p>If it however doesn't work, try to do so with <strong>init_command='SET NAMES UTF8'</strong> parameter.</p></li>
</ol>
<p>So it will look like: </p>
<pre><code>conn = MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8')
</code></pre>
<p>You can try also this:</p>
<pre><code>cursor = db.cursor()
cursor.execute("SET NAMES UTF8;")
</code></pre>
| 1 | 2016-08-30T14:10:01Z | [
"python",
"mysql",
"unicode",
"utf-8",
"character-encoding"
] |
Python with MySql unicode problems | 39,093,532 | <p>I need to call MySQL stored procedure from my python script. As one of parameters I'm passing a unicode string (Russian language), but I get an error;</p>
<blockquote>
<p>UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)</p>
</blockquote>
<p>My script:</p>
<pre><code> self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName")
self.cursor=self.db.cursor()
args=("какой-Ñо ÑекÑÑ") #this is string in russian
self.cursor.callproc('pr_MyProc', args)
self.cursor.execute('SELECT @_pr_MyProc_2') #getting result from sp
result=self.cursor.fetchone()
self.db.commit()
</code></pre>
<p>I've read that setting <code>charset='utf8'</code> shuld resolve this problem, but when I use string:</p>
<pre><code>self.db=MySQLdb.connect("localhost", "usr", "pass", "dbName", charset='utf8')
</code></pre>
<p>This gives me another error;</p>
<blockquote>
<p>UnicodeEncodeError: 'utf-8' codec can't encode character '\udcd1' in position 20: surrogates not allowed</p>
</blockquote>
<p>Also I've trying to set parametr <code>use_unicode=True</code>, that's not working.</p>
| 9 | 2016-08-23T06:07:55Z | 39,230,058 | <p>I had a similar problem very recently but with PostgreSQL. After trying tons of suggestions from SO/ internet, I realized the issue was with my database. I had to drop my database and reinstall Postgres, because for some reason it was not allowing me to change the database's default collation. I was in a hurry so couldn't find a better solution, but would recommend the same, since I was only starting my application in the deployment environment.
All the best.</p>
| 2 | 2016-08-30T14:19:27Z | [
"python",
"mysql",
"unicode",
"utf-8",
"character-encoding"
] |
python sort tuple by different criteria | 39,093,546 | <p>I have a list <code>a = [(1,'a'), (1,'b'), (2,'c')]</code>, and I want to get this list: <code>[(2,'c'), (1,'a'), (1,'b')]</code></p>
<p>If I do this:</p>
<pre><code>sorted(a, reverse=True)
</code></pre>
<p>I can only get:</p>
<pre><code>[(2,'c'), (1,'b'), (1,'a')]
</code></pre>
<p>How can I get the list I want?</p>
| -1 | 2016-08-23T06:08:40Z | 39,093,757 | <p>Try this,</p>
<pre><code>from operator import itemgetter
sorted(a, key=itemgetter(0),reverse=True)
</code></pre>
<p><strong>Result</strong></p>
<pre><code>[(2, 'c'), (1, 'a'), (1, 'b')]
</code></pre>
| 0 | 2016-08-23T06:23:06Z | [
"python",
"list",
"sorting",
"tuples"
] |
python sort tuple by different criteria | 39,093,546 | <p>I have a list <code>a = [(1,'a'), (1,'b'), (2,'c')]</code>, and I want to get this list: <code>[(2,'c'), (1,'a'), (1,'b')]</code></p>
<p>If I do this:</p>
<pre><code>sorted(a, reverse=True)
</code></pre>
<p>I can only get:</p>
<pre><code>[(2,'c'), (1,'b'), (1,'a')]
</code></pre>
<p>How can I get the list I want?</p>
| -1 | 2016-08-23T06:08:40Z | 39,093,760 | <p>If you want to preserve the sort order in the original list, but sort only by the first element, you can do</p>
<pre><code>>>> from operator import itemgetter
>>> a = [(1,'a'), (1, 'x'), (1,'b'), (2,'c')]
>>> sorted(a, key=itemgetter(0), reverse=True)
[(2, 'c'), (1, 'a'), (1, 'x'), (1, 'b')]
</code></pre>
<p>In Python the <code>sort</code> and <code>sorted</code> functions use the <a href="https://en.wikipedia.org/wiki/Timsort" rel="nofollow">TimSort</a> algorithm, which is a stable sort. Being stable means that the original relative ordering is preserved for those elements that compare equal to each other.</p>
<p>If you want to sort by multiple criteria <em>at the same time</em>, you can use a function for the key in case of integers, returning the opposite number of the number for reversing, but in general case you could do so by sorting several times, in reverse order:</p>
<pre><code>>>> b = sorted(a, key=itemgetter(1)) # sort by second element, ascending
>>> b.sort(key=itemgetter(0), reverse=True) # sort by first element, descending
>>> b
[(2, 'c'), (1, 'a'), (1, 'b'), (1, 'x')]
</code></pre>
| 1 | 2016-08-23T06:23:20Z | [
"python",
"list",
"sorting",
"tuples"
] |
python sort tuple by different criteria | 39,093,546 | <p>I have a list <code>a = [(1,'a'), (1,'b'), (2,'c')]</code>, and I want to get this list: <code>[(2,'c'), (1,'a'), (1,'b')]</code></p>
<p>If I do this:</p>
<pre><code>sorted(a, reverse=True)
</code></pre>
<p>I can only get:</p>
<pre><code>[(2,'c'), (1,'b'), (1,'a')]
</code></pre>
<p>How can I get the list I want?</p>
| -1 | 2016-08-23T06:08:40Z | 39,094,013 | <p>You may achieve this by using <code>lambda</code> function with <code>sorted</code>:</p>
<pre><code>>>> sorted(a, key=lambda x: (-x[0], x[1]))
[(2, 'c'), (1, 'a'), (1, 'b')]
</code></pre>
<p>This will sort the list in descending order of the value at index 0, and then ascending order of value at index 1</p>
| 1 | 2016-08-23T06:39:42Z | [
"python",
"list",
"sorting",
"tuples"
] |
Tensorflow RNN cells weight sharing | 39,093,627 | <p>I am wondering if in the following code the weights of the two stacked cells are shared: </p>
<pre><code>cell = rnn_cell.GRUCell(hidden_dim)
stacked_cell = tf.nn.rnn_cell.MultiRNNCell([cell] * 2)
</code></pre>
<p>If they are not shared, how to force sharing in any RNNs? </p>
<p>Note:
I might more probably want to share weights in a nested input-to-output connected RNN configuration where the first layer is cloned many times for every input of the second layer (e.g. sentences where 1st layer represents letters and 2nd layer represents words gathered from iterating 1st layer's outputs)</p>
| 0 | 2016-08-23T06:14:48Z | 39,134,388 | <p>You can see that the weights are not shared by executing the following script:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
with tf.variable_scope("scope1") as vs:
cell = tf.nn.rnn_cell.GRUCell(10)
stacked_cell = tf.nn.rnn_cell.MultiRNNCell([cell] * 2)
stacked_cell(tf.Variable(np.zeros((100, 100), dtype=np.float32), name="moo"), tf.Variable(np.zeros((100, 100), dtype=np.float32), "bla"))
# Retrieve just the LSTM variables.
vars = [v.name for v in tf.all_variables()
if v.name.startswith(vs.name)]
print vars
</code></pre>
<p>You will see that besides dummy variables it returns two sets of GRU weights: those with "Cell1" and those with "Cell0".</p>
<p>To make them shared, you can implement your own cell class that inherits from <code>GRUCell</code> and always reuses the weights by the means of always using the same variable scope:</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
class SharedGRUCell(tf.nn.rnn_cell.GRUCell):
def __init__(self, num_units, input_size=None, activation=tf.nn.tanh):
tf.nn.rnn_cell.GRUCell.__init__(self, num_units, input_size, activation)
self.my_scope = None
def __call__(self, a, b):
if self.my_scope == None:
self.my_scope = tf.get_variable_scope()
else:
self.my_scope.reuse_variables()
return tf.nn.rnn_cell.GRUCell.__call__(self, a, b, self.my_scope)
with tf.variable_scope("scope2") as vs:
cell = SharedGRUCell(10)
stacked_cell = tf.nn.rnn_cell.MultiRNNCell([cell] * 2)
stacked_cell(tf.Variable(np.zeros((20, 10), dtype=np.float32), name="moo"), tf.Variable(np.zeros((20, 10), dtype=np.float32), "bla"))
# Retrieve just the LSTM variables.
vars = [v.name for v in tf.all_variables()
if v.name.startswith(vs.name)]
print vars
</code></pre>
<p>This way the variables between the two GRUCells are shared. Note that you need to be careful with shapes, since the same cell need to work with both the raw input and the output of itself.</p>
| 1 | 2016-08-24T23:14:35Z | [
"python",
"machine-learning",
"tensorflow",
"deep-learning",
"recurrent-neural-network"
] |
matplotlib - faster frame rate? | 39,093,656 | <p>I have written a simple script based on the code from <a href="https://jakevdp.github.io/blog/2013/02/16/animating-the-lorentz-system-in-3d/" rel="nofollow">here</a></p>
<p>I just need to display dots, no lines needed.</p>
<p>The script below displays the dots correctly but I would like to see the dots move much faster, in a configurable manner at a frame rate of let's say 30fps.</p>
<pre><code>import matplotlib
matplotlib.use('TKAgg')
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation
NbOfObjects = 3
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('on')
ax.set_xlim((-1.5, 1.5))
ax.set_ylim((-1.5, 1.5))
ax.set_zlim((0, 1.5))
ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(30, 30)
# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, NbOfObjects))
# set up points
pts = sum([ax.plot([], [], [], 'o', c=c)
for c in colors], [])
data = [[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 0.0, 0.0], [0.0, -1.0, 1.0], [-1.0, 1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [-1.0, -1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]],
[[0.0, 0.0, 0.0], [-1.0, -1.0, 1.0], [1.0, 1.0, 1.0]]]
# initialization function: plot the background of each frame
def init():
for pt in pts:
pt.set_data([], [])
pt.set_3d_properties([])
return pts
def animate(i):
print "i: ", i
for pt, positon in zip (pts, data[i]):
x = positon[0]
y = positon[1]
z = positon[2]
pt.set_data(x, y)
pt.set_3d_properties(z)
fig.canvas.draw()
return pts
anim = animation.FuncAnimation(fig, animate, init_func=init, interval=1, frames=len(data), blit=True, repeat=False)
plt.show()
</code></pre>
<ol>
<li><p>How does the display of the frames on the screen relate to the "interval" parameter in <code>animation.FuncAnimation</code>? (I can't get it to display the 50 frames in less than 5 secs)</p></li>
<li><p>Is this design the best way to deal with a large number of dots (10+) at potentially 30fps over a long duration? ("data" would be pretty big for a 1h duration).</p></li>
</ol>
<p>I'm still studying the various examples but none show a simple 3D animated scatter plot.</p>
<p>Thanks.</p>
| 1 | 2016-08-23T06:17:02Z | 39,093,939 | <ol>
<li><p>From <a href="http://matplotlib.org/api/animation_api.html#matplotlib.animation.FuncAnimation" rel="nofollow">the documentation</a>:</p>
<blockquote>
<p>kwargs include <code>repeat</code>, <code>repeat_delay</code>, and <code>interval</code>: <code>interval</code> draws a new frame <strong>every <code>interval</code> milliseconds</strong>. <code>repeat</code> controls whether the animation should repeat when the sequence of frames is completed. <code>repeat_delay</code> optionally adds a delay in milliseconds before repeating the animation.</p>
</blockquote>
<p>However, this only sets an upper bound on the frame rate - if it takes too long to draw a frame, then you'll see a slower frame rate</p></li>
<li><p>If you have a larger number of dots, you'll want to do something like:</p>
<pre><code>data = np.array(data)
# in init, get a single mpl_toolkits.mplot3d.art3d.Line3D object
# the comma is important!
pts, = ax.plot([], [], [], 'o', c=colors)
# in update()
pts.set_data(data[i,:,0], data[i,:,1])
pts.set_3d_properties(data[i,:,2])
</code></pre>
<p>So that you can eliminate the for loop</p></li>
</ol>
| 0 | 2016-08-23T06:35:25Z | [
"python",
"animation",
"matplotlib"
] |
Python sys.argv utf-8 to unicode not working | 39,093,768 | <p>I have the following code which is acting very weirdly.</p>
<p>When I do the following, the utf-8 got converted into unicode nicely.</p>
<pre><code>print u'\xE1\x80\x96\xE1\x80\xBB\xE1\x80\xB1\xE1\x80\xAC\xE1\x80\xBA\xE1\x80\x9B\xE1\x80\x8A\xE1\x80\xBA'.encode('raw_unicode_escape')
</code></pre>
<p>This works fine. However, when I get the utf-8 string from sys.argv, it doesn't work.</p>
<pre><code>import sys
if __name__ == "__main__":
args = sys.argv
input_string = args[1]
if type(input_string) is not unicode:
input_string = unicode(input_string, "utf-8")
print type(input_string)
print input_string
</code></pre>
<p>When I run like the following,</p>
<pre><code>python test_print.py "\xE1\x80\x96\xE1\x80\xBB\xE1\x80\xB1\xE1\x80\xAC\xE1\x80\xBA\xE1\x80\x9B\xE1\x80\x8A\xE1\x80\xBA"
</code></pre>
<p>I got the following same string, it doesn't get converted into unicode.</p>
<pre><code><type 'unicode'>
\xE1\x80\x96\xE1\x80\xBB\xE1\x80\xB1\xE1\x80\xAC\xE1\x80\xBA\xE1\x80\x9B\xE1\x80\x8A\xE1\x80\xBA
</code></pre>
<p>I need to convert the input from sys.argv into unicode chars.</p>
<p>Please help.</p>
<p>Thanks.</p>
| -1 | 2016-08-23T06:24:02Z | 39,094,099 | <p>Actual Python level string literals (for <code>str</code> and <code>unicode</code>) are the only place character escapes are parsed by Python automatically. If you want to convert outside strings that use literal escapes like this, you'd do something like this to <a href="https://docs.python.org/2/library/codecs.html#python-specific-encodings" rel="nofollow">explicitly invoke the literal escape interpretation machinery</a>:</p>
<pre><code># Converts from str to str interpreting escapes, then decodes those bytes
# using the UTF-8 encoding
input_string = args[1].decode('string_escape').decode('utf-8')
</code></pre>
<p>The exact steps are slightly different in Python 3 (you have to use <code>unicode_escape</code> and the <code>codecs</code> module, and add an extra step to convert the literal decoded <code>str</code> to <code>latin-1</code> <code>bytes</code> before decoding as <code>utf-8</code> because text->text encoding and decoding isn't supported), but it's a similar process.</p>
| 1 | 2016-08-23T06:45:08Z | [
"python",
"unicode",
"encoding",
"utf-8"
] |
How to do some operations like groupby() and value_counts() in pandas? | 39,093,811 | <p>Here is a pandas Dataframe defined as follow:</p>
<pre><code>df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three', 'two'],
'C' : [0, 1, 0, 1, 1, 2, 0, 2, 1]})
>>> df
A B C
0 foo one 0
1 bar one 1
2 foo two 0
3 bar three 1
4 foo two 1
5 bar two 2
6 foo one 0
7 foo three 2
8 foo two 1
</code></pre>
<p>I want to do two operations.</p>
<p>First, group the Dataframe by column <code>A</code> and <code>B</code>. Thus, 6 groups are obtained in this case. This operation is similar to groupby() function in pandas.</p>
<p>Then, for each group, do the count operation for column <code>C</code> since it can be three different values (0, 1 and 2) in this case. This operation is similar to value_counts() function in pandas.</p>
<p>Finally, I want a new Dataframe like this.</p>
<pre><code> A B C_value0 C_value1 C_value2
0 foo one 2 0 0
1 foo two 1 2 0
2 foo three 0 0 1
3 bar one 0 1 0
4 bar two 0 0 1
5 bar three 0 1 0
</code></pre>
<p>Could somebody tell me how to achieve this? Thanks!</p>
| 1 | 2016-08-23T06:27:37Z | 39,093,870 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with aggregating <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a>, then replace <code>NaN</code> to <code>0</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>, convert to <code>int</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html" rel="nofollow"><code>astype</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.add_prefix.html" rel="nofollow"><code>add_prefix</code></a>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and last <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p>
<pre><code>print (df.groupby(['A','B', 'C'])['C'].size()
.unstack()
.fillna(0)
.astype(int)
.add_prefix('C_value')
.reset_index()
.rename_axis(None, axis=1))
A B C_value0 C_value1 C_value2
0 bar one 0 1 0
1 bar three 0 1 0
2 bar two 0 0 1
3 foo one 2 0 0
4 foo three 0 0 1
5 foo two 1 2 0
</code></pre>
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a>:</p>
<pre><code>print (pd.crosstab([df.A, df.B], df.C)
.add_prefix('C_value')
.reset_index()
.rename_axis(None, axis=1))
A B C_value0 C_value1 C_value2
0 bar one 0 1 0
1 bar three 0 1 0
2 bar two 0 0 1
3 foo one 2 0 0
4 foo three 0 0 1
5 foo two 1 2 0
</code></pre>
| 1 | 2016-08-23T06:31:37Z | [
"python",
"pandas",
"dataframe",
"group-by",
"crosstab"
] |
Counter not working | 39,093,920 | <p>I am trying to do some grouping with the usage of counters, such that it will increment accordingly.. I apologize if my title gives the wrong impression but...</p>
<p>Anyway, when I have 2 or more selections and as I execute my code, instead of seeing groups with naming such as - TEST_1_GRP, TEST_2_GRP, TEST_3_GRP etc., I am getting TEST_1_GRP, TEST_1_GRP1, TEST_1_GRP2 as my results...</p>
<p>I tried placing some of the line for the counter portion around (like within/ before the for sentence), I am getting nowhere..</p>
<p>Below is my code:</p>
<pre><code>def fix_shapes():
all_geos = cmds.ls(sl = True)
for geo in all_geos:
shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)
if len(shapes) == 1:
continue
new_listing = []
listing.append(shapes[:1])
# pop out the first shape, since we don't have to fix it
multi_shapes = shapes[1:]
for multi_shape in multi_shapes:
new_transform = cmds.duplicate(multi_shape, parentOnly=True)
new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
listing.append(new_geos)
# remove the shape from its original transform
cmds.parent(multi_shape, removeObject=True, shape=True)
# counter to 'version' up new_geos group naming
counter = 0
new_group_name = cmds.group(em=True, name = 'TEST_' + str(counter + 1) + '_GRP')
for item in new_listing:
counter = counter + 1
new_geos_parent_name = cmds.listRelatives(item, parent = True)
cmds.parent(new_geos_parent_name, new_group_name)
</code></pre>
| 0 | 2016-08-23T06:34:18Z | 39,094,539 | <p>Move your counter as follows, you aren't using the counter in your last loop so remove it from that. Check this does what you want?</p>
<pre><code>def fix_shapes():
all_geos = cmds.ls(sl = True)
counter = 0
for geo in all_geos:
shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)
if len(shapes) == 1:
continue
new_listing = []
listing.append(shapes[:1])
# pop out the first shape, since we don't have to fix it
multi_shapes = shapes[1:]
for multi_shape in multi_shapes:
new_transform = cmds.duplicate(multi_shape, parentOnly=True)
new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
listing.append(new_geos)
# remove the shape from its original transform
cmds.parent(multi_shape, removeObject=True, shape=True)
# counter to 'version' up new_geos group naming
new_group_name = cmds.group(em=True, name = 'TEST_' + str(counter + 1) + '_GRP')
for item in new_listing:
new_geos_parent_name = cmds.listRelatives(item, parent = True)
cmds.parent(new_geos_parent_name, new_group_name)
</code></pre>
| 0 | 2016-08-23T07:10:11Z | [
"python",
"maya"
] |
Counter not working | 39,093,920 | <p>I am trying to do some grouping with the usage of counters, such that it will increment accordingly.. I apologize if my title gives the wrong impression but...</p>
<p>Anyway, when I have 2 or more selections and as I execute my code, instead of seeing groups with naming such as - TEST_1_GRP, TEST_2_GRP, TEST_3_GRP etc., I am getting TEST_1_GRP, TEST_1_GRP1, TEST_1_GRP2 as my results...</p>
<p>I tried placing some of the line for the counter portion around (like within/ before the for sentence), I am getting nowhere..</p>
<p>Below is my code:</p>
<pre><code>def fix_shapes():
all_geos = cmds.ls(sl = True)
for geo in all_geos:
shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)
if len(shapes) == 1:
continue
new_listing = []
listing.append(shapes[:1])
# pop out the first shape, since we don't have to fix it
multi_shapes = shapes[1:]
for multi_shape in multi_shapes:
new_transform = cmds.duplicate(multi_shape, parentOnly=True)
new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
listing.append(new_geos)
# remove the shape from its original transform
cmds.parent(multi_shape, removeObject=True, shape=True)
# counter to 'version' up new_geos group naming
counter = 0
new_group_name = cmds.group(em=True, name = 'TEST_' + str(counter + 1) + '_GRP')
for item in new_listing:
counter = counter + 1
new_geos_parent_name = cmds.listRelatives(item, parent = True)
cmds.parent(new_geos_parent_name, new_group_name)
</code></pre>
| 0 | 2016-08-23T06:34:18Z | 39,296,911 | <p>I believe this may solve your problem. Keep in mind that the first time you execute your code, it will work as expected and produce groups named <code>TEST_1_GRP TEST_2_GRP</code> etc. However, the second time it will be named <code>TEST_1_GRP1 TEST_2_GRP1</code> etc. because you're not saving or checking if the name exists. To work around this you can either store a global variable, check during names during execution, or store the counted value in the scene file or someplace else. I'll leave this to you.</p>
<pre><code>def fix_shapes():
all_geos = cmds.ls(sl = True)
counter = 0 ### moved counter outside loop
for geo in all_geos:
shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)
if len(shapes) == 1:
continue
listing = [] ### fixed naming, was new_listing, not coherent
listing.append(shapes[:1])
# pop out the first shape, since we don't have to fix it
multi_shapes = shapes[1:]
for multi_shape in multi_shapes:
new_transform = cmds.duplicate(multi_shape, parentOnly=True)
new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
listing.append(new_geos)
# remove the shape from its original transform
cmds.parent(multi_shape, removeObject=True, shape=True)
# counter to 'version' up new_geos group naming
new_group_name = cmds.group(em=True, name = 'TEST_' + str(counter + 1) + '_GRP')
counter += 1 ### simpler way to increment instead of "counter = counter + 1"
for item in listing: ### fixed new_listing name here as well
new_geos_parent_name = cmds.listRelatives(item, parent = True)
cmds.parent(new_geos_parent_name, new_group_name)
</code></pre>
<p>I've marked the changes with ### with some comments.</p>
| 0 | 2016-09-02T16:22:10Z | [
"python",
"maya"
] |
Counter not working | 39,093,920 | <p>I am trying to do some grouping with the usage of counters, such that it will increment accordingly.. I apologize if my title gives the wrong impression but...</p>
<p>Anyway, when I have 2 or more selections and as I execute my code, instead of seeing groups with naming such as - TEST_1_GRP, TEST_2_GRP, TEST_3_GRP etc., I am getting TEST_1_GRP, TEST_1_GRP1, TEST_1_GRP2 as my results...</p>
<p>I tried placing some of the line for the counter portion around (like within/ before the for sentence), I am getting nowhere..</p>
<p>Below is my code:</p>
<pre><code>def fix_shapes():
all_geos = cmds.ls(sl = True)
for geo in all_geos:
shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)
if len(shapes) == 1:
continue
new_listing = []
listing.append(shapes[:1])
# pop out the first shape, since we don't have to fix it
multi_shapes = shapes[1:]
for multi_shape in multi_shapes:
new_transform = cmds.duplicate(multi_shape, parentOnly=True)
new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
listing.append(new_geos)
# remove the shape from its original transform
cmds.parent(multi_shape, removeObject=True, shape=True)
# counter to 'version' up new_geos group naming
counter = 0
new_group_name = cmds.group(em=True, name = 'TEST_' + str(counter + 1) + '_GRP')
for item in new_listing:
counter = counter + 1
new_geos_parent_name = cmds.listRelatives(item, parent = True)
cmds.parent(new_geos_parent_name, new_group_name)
</code></pre>
| 0 | 2016-08-23T06:34:18Z | 39,327,738 | <pre><code>def fix_shapes():
all_geos = cmds.ls(sl = True)
counter = 0
for geo in all_geos:
shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)
if len(shapes) == 1:
continue
new_listing = []
new_listing.append(shapes[:1])
# pop out the first shape, since we don't have to fix it
multi_shapes = shapes[1:]
for multi_shape in multi_shapes:
new_transform = cmds.duplicate(multi_shape, parentOnly=True)
new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
new_listing.append(new_geos)
# remove the shape from its original transform
cmds.parent(multi_shape, removeObject=True, shape=True)
# counter to 'version' up new_geos group naming
new_grp_id = "TEST_{0}_GRP".format(counter)
if not cmds.objExists(new_grp_id):
new_group_name = cmds.group(em=True, name = new_grp_id)
counter += 1
else:
for o in reversed(xrange(100)):
if cmds.objExists("TEST_{0}_GRP".format(o)):
counter = o + 1
break
new_group_name = cmds.group(em=True, name = "TEST_{0}_GRP".format(counter))
counter += 1
for item in new_listing:
new_geos_parent_name = cmds.listRelatives(item, parent = True)
cmds.parent(new_geos_parent_name, new_group_name)
</code></pre>
<p>for the second iteration you need something like max range counter,
so we have build some checks .... so now it will do create grps and add items to it, by next iterations it will find the max value of "TEST_n_GRP" and increase that, think that it will find the biggest int, not the between integers, eg: in scene: grp_1 and grp_3, the next biggest number is the grp_4, but it will not find grp_2! you can remove the reversed operator, for that.
with the reversed operator you will find really fast the biggest/last integers but not the between ints </p>
| 0 | 2016-09-05T09:37:52Z | [
"python",
"maya"
] |
Access .rds file from Python | 39,093,931 | <p>I am working on a project where I have got an .rds file which consist of trained model as per my requirement generated by R code.</p>
<p>Now I need to load the trained model in python and use it in processing the records. </p>
<p>Is there any way to do so? If not what are the alternatives.</p>
<p>Thanks</p>
| 0 | 2016-08-23T06:34:44Z | 39,094,052 | <p>We can use feather: </p>
<pre><code>import feather
path = 'my_data.feather'
feather.write_dataframe(df, path)
df = feather.read_dataframe(path)
</code></pre>
| 1 | 2016-08-23T06:41:51Z | [
"python"
] |
Access .rds file from Python | 39,093,931 | <p>I am working on a project where I have got an .rds file which consist of trained model as per my requirement generated by R code.</p>
<p>Now I need to load the trained model in python and use it in processing the records. </p>
<p>Is there any way to do so? If not what are the alternatives.</p>
<p>Thanks</p>
| 0 | 2016-08-23T06:34:44Z | 39,094,076 | <p>Look at this website, maybe this can help too.</p>
<p><a href="http://mgimond.github.io/ES218/Week02b.html" rel="nofollow">http://mgimond.github.io/ES218/Week02b.html</a></p>
| 0 | 2016-08-23T06:43:39Z | [
"python"
] |
Python - can I add UTF8 BOM to a file without opening it? | 39,094,125 | <p>How to add an utf8-bom to a text file without open() it?</p>
<p>Theoretically, we just need to add utf8-bom to the beginning of the file, we don't need to read-in 'all' the content? </p>
| 1 | 2016-08-23T06:46:28Z | 39,094,533 | <p>You need to read in the data because you need to move all the data to make room for the BOM. Files can't just prepend arbitrary data. Doing it in place is harder than just writing a new file with the BOM followed by the original data, then replacing the original file, so the easiest solution is usually something like:</p>
<pre><code>import os
import shutil
from os.path import dirname, realpath
from tempfile import NamedTemporaryFile
infile = ...
# Open original file as UTF-8 and tempfile in same directory to add sig
indir = dirname(realpath(infile))
with NamedTemporaryFile(dir=indir, mode='w', encoding='utf-8-sig') as tf:
with open(infile, encoding='utf-8') as f:
# Copy from one file to the other by blocks
# (avoids memory use of slurping whole file at once)
shutil.copyfileobj(f, tf)
# Optional: Replicate metadata of original file
tf.flush()
shutil.copystat(f.name, tf.name) # Replicate permissions of original file
# Atomically replace original file with BOM marked file
os.replace(tf.name, f.name)
# Don't try to delete temp file if everything worked
tf.delete = False
</code></pre>
<p>This also verifies that the input file was in fact UTF-8 by side-effect, and the original file never exists in an inconsistent state; it's either the old or the new data, not the intermediate working copy.</p>
<p>If your files are large and your disk space is limited (so you can't have two copies on disk at once), then in-place mutation might be acceptable. The easiest way to do this is the <code>mmap</code> module which simplifies the process of moving the data around considerably vs. using in-place file object operations:</p>
<pre><code>import codecs
import mmap
# Open file for read and write and then immediately map the whole file for write
with open(infile, 'r+b') as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_WRITE) as mm:
origsize = mm.size()
bomlen = len(codecs.BOM_UTF8)
# Allocate additional space for BOM
mm.resize(origsize+bomlen)
# Copy file contents down to make room for BOM
# This reads and writes the whole file, and is unavoidable
mm.move(bomlen, 0, origsize)
# Insert the BOM before the shifted data
mm[:bomlen] = codecs.BOM_UTF8
</code></pre>
| 3 | 2016-08-23T07:09:38Z | [
"python",
"unicode",
"utf-8",
"byte-order-mark"
] |
Python - can I add UTF8 BOM to a file without opening it? | 39,094,125 | <p>How to add an utf8-bom to a text file without open() it?</p>
<p>Theoretically, we just need to add utf8-bom to the beginning of the file, we don't need to read-in 'all' the content? </p>
| 1 | 2016-08-23T06:46:28Z | 39,095,381 | <p>If you need in-place update, something like</p>
<pre><code>def add_bom(fname, bom=None, buf_size=None):
bom = bom or BOM
buf_size = buf_size or max(resource.getpagesize(), len(bom))
buf = bytearray(buf_size)
with open(fname, 'rb', 0) as in_fd, open(fname, 'rb+', 0) as out_fd:
# we cannot just just read until eof, because we
# will be writing to that very same file, extending it.
out_fd.seek(0, 2)
nbytes = out_fd.tell()
out_fd.seek(0)
# Actually, we want to pass buf[0:n_bytes], but
# that doesn't result in in-place updates.
in_bytes = in_fd.readinto(buf)
if in_bytes < len(bom) or not buf.startswith(bom):
# don't write the BOM if it's already there
out_fd.write(bom)
while nbytes > 0:
# if we still need to write data, do so.
# but only write as much data as we need
out_fd.write(buffer(buf, 0, min(in_bytes, nbytes)))
nbytes -= in_bytes
in_bytes = in_fd.readinto(buf)
</code></pre>
<p>should do the trick.</p>
<p>As you can see, in-place updates are a little finnicky, because you are</p>
<ol>
<li>Writing data to the place you've just read from. The read must always stay ahead of the write, otherwise you are overwriting not-yet-processed data.</li>
<li>Extending the file you are reading, so reading till EOF doesn't work.</li>
</ol>
<p>In addition, this may leave the file in an inconsistent state. The copy to temporary -> move temporary to original method is much preferred if possible.</p>
| 1 | 2016-08-23T07:52:32Z | [
"python",
"unicode",
"utf-8",
"byte-order-mark"
] |
learning Python the hard way argv and file | 39,094,156 | <p>I am learning python from past weeks </p>
<pre><code>from sys import argv
script,filename = argv
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write something to your file"
line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()
</code></pre>
<p>I want to view the contents of the file ,but when i use <code>print filename</code> or <code>print filen</code> it show name and open file on variable <code>filen</code></p>
| -3 | 2016-08-23T06:48:49Z | 39,094,243 | <p>you can read data using <code>filen.read()</code> or <code>filen.readline()</code> or <code>filen.readlines()</code></p>
<p>1) read</p>
<pre><code>fo = open(filename,read)
fo.seek(0, 0) #seek is used to change the file position.This requires only for read method
fo.read(10) #This reads 1st 10 characters
fo.close()
</code></pre>
<p>2) readline</p>
<pre><code>fo = open(filename,read)
fo.readline() #This will read a single line from the file. You can add for loop to iterate all the data
fo.close()
</code></pre>
<p>3) readlines.</p>
<pre><code>fo = open(filename,read)
fo.readline() #read all the lines of a file in a list
fo.close()
</code></pre>
<p>Below document will give you better idea.
<a href="https://docs.python.org/2/tutorial/inputoutput.html" rel="nofollow">https://docs.python.org/2/tutorial/inputoutput.html</a></p>
| 0 | 2016-08-23T06:54:24Z | [
"python",
"file",
"argv",
"filehandle"
] |
learning Python the hard way argv and file | 39,094,156 | <p>I am learning python from past weeks </p>
<pre><code>from sys import argv
script,filename = argv
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write something to your file"
line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()
</code></pre>
<p>I want to view the contents of the file ,but when i use <code>print filename</code> or <code>print filen</code> it show name and open file on variable <code>filen</code></p>
| -3 | 2016-08-23T06:48:49Z | 39,094,916 | <p>If you want to print the content of the file you opened, just use: <code>print filen.read()</code>.</p>
| 0 | 2016-08-23T07:28:38Z | [
"python",
"file",
"argv",
"filehandle"
] |
learning Python the hard way argv and file | 39,094,156 | <p>I am learning python from past weeks </p>
<pre><code>from sys import argv
script,filename = argv
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write something to your file"
line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()
</code></pre>
<p>I want to view the contents of the file ,but when i use <code>print filename</code> or <code>print filen</code> it show name and open file on variable <code>filen</code></p>
| -3 | 2016-08-23T06:48:49Z | 39,098,172 | <p>At its simplest:</p>
<pre><code>from sys import argv
script,filename = argv
with open(filename) as f:
print f.readlines()
</code></pre>
<p>which dumps the files contents
or:</p>
<pre><code>from sys import argv
script,filename = argv
with open(filename) as f:
lines=f.readlines()
for line in lines:
print line
</code></pre>
<p>which prints the lines out 1 by 1</p>
| 0 | 2016-08-23T10:06:31Z | [
"python",
"file",
"argv",
"filehandle"
] |
How to resize and crop in a video player using GStreamer in python TKinter? | 39,094,171 | <p>I wrote a small media player in python using TKinter and GStreamer which is embedded in my application. The player is based on the code below which is a small modification to <a href="http://stackoverflow.com/questions/7227162">Way to play video files in Tkinter?</a> which works.</p>
<pre><code>import os, sys
import Tkinter as tkinter
import threading
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstVideo', '1.0')
gi.require_version('GdkX11', '3.0')
from gi.repository import Gst, GObject, GdkX11, GstVideo
def set_frame_handle(bus, message, frame_id):
if not message.get_structure() is None:
print message.get_structure().get_name()
if message.get_structure().get_name() == 'prepare-window-handle':
display_frame = message.src
display_frame.set_property('force-aspect-ratio', True)
display_frame.set_window_handle(frame_id)
window = tkinter.Tk()
window.title('')
window.geometry('500x400')
GObject.threads_init()
Gst.init(None)
display_frame = tkinter.Canvas(window, bg='#030')
display_frame.pack(side=tkinter.TOP,expand=tkinter.YES,fill=tkinter.BOTH)
frame_id = display_frame.winfo_id()
player = Gst.ElementFactory.make('playbin', None)
filepath = os.path.realpath('kbps.mp4')
filepath2 = "file:///" + filepath.replace('\\', '/').replace(':', '|')
player.set_property('uri', filepath2)
bus = player.get_bus()
bus.enable_sync_message_emission()
bus.connect('sync-message::element', set_frame_handle, frame_id)
player.set_state(Gst.State.PLAYING)
window.mainloop()
</code></pre>
<p>I need to zoom in in some part of the video and therefore I need to use the the GStreamer Base Plugins called <strong>videocrop</strong> and <strong>videoscale</strong> which are both part of GStreamer 1.0.</p>
<p>Unfortunately after spending several days of research, I have not been able to find a simple python example on how these plugins can be used in TKiinter (I am not using Gtk nor any other library).</p>
<p>Could anyone provide me an example on how these could be used? Any help would be much appreciated. Thanks in advanceâ¦</p>
| 0 | 2016-08-23T06:49:19Z | 39,102,389 | <p>I figured it out, and it can be done by adding a video-filter element. the code to add is the following:</p>
<pre><code>VideoCrop = Gst.ElementFactory.make('videocrop', 'VideoCrop')
VideoCrop.set_property('top', 100)
VideoCrop.set_property('bottom', 100)
VideoCrop.set_property('left', 50)
VideoCrop.set_property('right', 150)
player.set_property('video-filter', VideoCrop)
</code></pre>
<p>and below id the entire source code, tested on both linux and Windows</p>
<pre><code>import os, sys
import Tkinter as tkinter
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstVideo', '1.0')
gi.require_version('GdkX11', '3.0')
from gi.repository import Gst, GObject, GdkX11, GstVideo
def set_frame_handle(bus, message, frame_id):
if not message.get_structure() is None:
print message.get_structure().get_name()
if message.get_structure().get_name() == 'prepare-window-handle':
display_frame = message.src
display_frame.set_property('force-aspect-ratio', True)
display_frame.set_window_handle(frame_id)
window = tkinter.Tk()
window.title('')
window.geometry('500x400')
GObject.threads_init()
Gst.init(None)
# can aslo use display_frame = tkinter.Frame(window)
display_frame = tkinter.Canvas(window, bg='#030')
display_frame.pack(side=tkinter.TOP,expand=tkinter.YES,fill=tkinter.BOTH)
frame_id = display_frame.winfo_id()
player = Gst.ElementFactory.make('playbin', None)
filepath = os.path.realpath('kbps.mp4')
filepath2 = "file:///" + filepath.replace('\\', '/').replace(':', '|')
player.set_property('uri', filepath2)
VideoCrop = Gst.ElementFactory.make('videocrop', 'VideoCrop')
VideoCrop.set_property('top', 100)
VideoCrop.set_property('bottom', 100)
VideoCrop.set_property('left', 50)
VideoCrop.set_property('right', 150)
player.set_property('video-filter', VideoCrop)
bus = player.get_bus()
bus.enable_sync_message_emission()
bus.connect('sync-message::element', set_frame_handle, frame_id)
player.set_state(Gst.State.PLAYING)
window.mainloop()
</code></pre>
| 0 | 2016-08-23T13:18:31Z | [
"python",
"tkinter",
"resize",
"gstreamer",
"crop"
] |
xml to CSV - AttributeError: 'NoneType' object has no attribute 'text' | 39,094,234 | <pre><code> for tm in teamtree.iter('team_members'):
</code></pre>
<p>I'm trying to output these fields into a CSV using the above function.
The xml data is stored in a variable called (projectDetJoined)</p>
<p>I'm getting this error.</p>
<pre><code>Traceback (most recent call last):
File "10Other.py", line 481, in <module>
parseXMLTaskDetails()
File "10Other.py", line 355, in parseXMLTaskDetails
taskcid = (t.find('cid').text)
AttributeError: 'NoneType' object has no attribute 'text'
</code></pre>
<p>The items exist in the xml data. </p>
<p>Any ideas why its not finding it? I have a similar function that is structured the same way but does work.</p>
| -2 | 2016-08-23T06:53:52Z | 39,096,766 | <p><strong>Ilja Everilä's</strong> comment solved my problem.</p>
<blockquote>
<p>In your XML the team_members element does not have subelements like
cid etc. It has item subelements. Perhaps you meant for tm in
teamtree.iterfind('team_members/item'). If your CSV headers didn't
have different case for some items, you could've just mapped
tm.findtext over them in the for-loop body to extract the values for
writing. Don't reopen the file all the time for append, but move the
XML extraction to the with-block that initially creates the file and
csv-writer. The final csvfile.close() is also redundant.</p>
</blockquote>
| 0 | 2016-08-23T09:00:56Z | [
"python",
"xml",
"csv"
] |
scikit learn decision tree model evaluation | 39,094,267 | <p>Here are the related code and document, wondering for the default <code>cross_val_score</code> without explicitly specify <code>score</code>, the output array means precision, AUC or some other metrics? </p>
<p>Using Python 2.7 with miniconda interpreter.</p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html</a></p>
<pre><code>>>> from sklearn.datasets import load_iris
>>> from sklearn.cross_validation import cross_val_score
>>> from sklearn.tree import DecisionTreeClassifier
>>> clf = DecisionTreeClassifier(random_state=0)
>>> iris = load_iris()
>>> cross_val_score(clf, iris.data, iris.target, cv=10)
...
...
array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,
0.93..., 0.93..., 1. , 0.93..., 1. ])
</code></pre>
<p>regards,
Lin</p>
| 0 | 2016-08-23T06:55:38Z | 39,094,466 | <p>If a scoring argument isn't given, <code>cross_val_score</code> will default to using the <code>.score</code> method of the estimator you're using. For <code>DecisionTreeClassifier</code>, it's mean accuracy (as shown in the docstring below): </p>
<pre><code>In [11]: DecisionTreeClassifier.score?
Signature: DecisionTreeClassifier.score(self, X, y, sample_weight=None)
Docstring:
Returns the mean accuracy on the given test data and labels.
In multi-label classification, this is the subset accuracy
which is a harsh metric since you require for each sample that
each label set be correctly predicted.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Test samples.
y : array-like, shape = (n_samples) or (n_samples, n_outputs)
True labels for X.
sample_weight : array-like, shape = [n_samples], optional
Sample weights.
Returns
-------
score : float
Mean accuracy of self.predict(X) wrt. y.
</code></pre>
| 1 | 2016-08-23T07:05:28Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"decision-tree"
] |
scikit learn decision tree model evaluation | 39,094,267 | <p>Here are the related code and document, wondering for the default <code>cross_val_score</code> without explicitly specify <code>score</code>, the output array means precision, AUC or some other metrics? </p>
<p>Using Python 2.7 with miniconda interpreter.</p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html</a></p>
<pre><code>>>> from sklearn.datasets import load_iris
>>> from sklearn.cross_validation import cross_val_score
>>> from sklearn.tree import DecisionTreeClassifier
>>> clf = DecisionTreeClassifier(random_state=0)
>>> iris = load_iris()
>>> cross_val_score(clf, iris.data, iris.target, cv=10)
...
...
array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,
0.93..., 0.93..., 1. , 0.93..., 1. ])
</code></pre>
<p>regards,
Lin</p>
| 0 | 2016-08-23T06:55:38Z | 39,094,469 | <p>From the <a href="http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation" rel="nofollow">user guide</a>:</p>
<blockquote>
<p>By default, the score computed at each CV iteration is the score
method of the estimator. It is possible to change this by using the
scoring parameter:</p>
</blockquote>
<p>From the DecisionTreeClassifier <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier.score" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>Returns the mean accuracy on the given test data and labels. In
multi-label classification, this is the subset accuracy which is a
harsh metric since you require for each sample that each label set be
correctly predicted.</p>
</blockquote>
<p>Don't be confused by "mean accuracy," it's just the regular way one computes accuracy. Follow the links to the <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/base.py#L285" rel="nofollow">source</a>:</p>
<pre><code> from .metrics import accuracy_score
return accuracy_score(y, self.predict(X), sample_weight=sample_weight)
</code></pre>
<p>Now the <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/metrics/classification.py#L171" rel="nofollow">source</a> for <code>metrics.accuracy_score</code></p>
<pre><code>def accuracy_score(y_true, y_pred, normalize=True, sample_weight=None):
...
# Compute accuracy for each possible representation
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
if y_type.startswith('multilabel'):
differing_labels = count_nonzero(y_true - y_pred, axis=1)
score = differing_labels == 0
else:
score = y_true == y_pred
return _weighted_sum(score, sample_weight, normalize)
</code></pre>
<p>And if you <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/metrics/classification.py#L103" rel="nofollow">still aren't convinced:</a></p>
<pre><code>def _weighted_sum(sample_score, sample_weight, normalize=False):
if normalize:
return np.average(sample_score, weights=sample_weight)
elif sample_weight is not None:
return np.dot(sample_score, sample_weight)
else:
return sample_score.sum()
</code></pre>
<p>Note: for <code>accuracy_score</code> normalize parameter defaults to <code>True</code>, thus it simply returns <code>np.average</code> of the boolean numpy arrays, thus it's simply the average number of correct predictions. </p>
| 1 | 2016-08-23T07:05:46Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"decision-tree"
] |
How to query max to min in Django? | 39,094,365 | <p>I want to query from max entry to min entry in a topic. Such that:</p>
<p><strong>models.py</strong></p>
<pre><code>class Topic(models.Model):
title = models.CharField(max_length=140, unique=True, verbose_name=_("Title"))
created_at = models.DateTimeField(auto_now=True, verbose_name=_("Created at"))
</code></pre>
<p><strong>And other model is :</strong></p>
<pre><code>class Entry(models.Model):
topic = models.ForeignKey(Topic, verbose_name=_("Topic"))
content = models.TextField(verbose_name=_("Content"))
created_at = models.DateTimeField(auto_now=True,verbose_name=_("Created at"))
</code></pre>
<p>Firstly, I want to filter only today's entries from <strong>Topic.py</strong>. Is that correct? :</p>
<pre><code>def get_topic_today(self):
return self.filter(date=datetime.date.today()).order_by('title')
</code></pre>
<p>And also I want to query popular topic max to min. I think we can use select_related with reverse foreign keys from entry to topic models. But I can not do it. For example, the topic which has most entry number must be first and going on lowest.</p>
| 2 | 2016-08-23T06:59:54Z | 39,094,487 | <p>For min and max dates</p>
<pre><code>### please use range for selecting between dates
def get_topic_today(self):
return self.filter(created_at__range=[min_date, max_date]).order_by('title')
### (or) use greater than or lesser than
def get_topic_today(self):
return self.filter(created_at__gte=min_date, created_at__lte=max_date).order_by('title')
</code></pre>
| 0 | 2016-08-23T07:06:37Z | [
"python",
"django"
] |
How to query max to min in Django? | 39,094,365 | <p>I want to query from max entry to min entry in a topic. Such that:</p>
<p><strong>models.py</strong></p>
<pre><code>class Topic(models.Model):
title = models.CharField(max_length=140, unique=True, verbose_name=_("Title"))
created_at = models.DateTimeField(auto_now=True, verbose_name=_("Created at"))
</code></pre>
<p><strong>And other model is :</strong></p>
<pre><code>class Entry(models.Model):
topic = models.ForeignKey(Topic, verbose_name=_("Topic"))
content = models.TextField(verbose_name=_("Content"))
created_at = models.DateTimeField(auto_now=True,verbose_name=_("Created at"))
</code></pre>
<p>Firstly, I want to filter only today's entries from <strong>Topic.py</strong>. Is that correct? :</p>
<pre><code>def get_topic_today(self):
return self.filter(date=datetime.date.today()).order_by('title')
</code></pre>
<p>And also I want to query popular topic max to min. I think we can use select_related with reverse foreign keys from entry to topic models. But I can not do it. For example, the topic which has most entry number must be first and going on lowest.</p>
| 2 | 2016-08-23T06:59:54Z | 39,094,526 | <p>If you want to filter a DateTimeField to a specific day, you can use the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#day" rel="nofollow"><code>__day</code> lookup</a>.</p>
<pre><code>def get_topic_today(self):
return self.filter(created_at__day=datetime.date.today()).order_by('title')
</code></pre>
<p>To get the count of a related model, use the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#id7" rel="nofollow"><code>Count</code> annotation</a>, then do a descending sort on it:</p>
<pre><code>Topic.objects.annotate(entry_count=Count('entry')).order_by('-entry_count')
</code></pre>
| 2 | 2016-08-23T07:09:09Z | [
"python",
"django"
] |
How to query max to min in Django? | 39,094,365 | <p>I want to query from max entry to min entry in a topic. Such that:</p>
<p><strong>models.py</strong></p>
<pre><code>class Topic(models.Model):
title = models.CharField(max_length=140, unique=True, verbose_name=_("Title"))
created_at = models.DateTimeField(auto_now=True, verbose_name=_("Created at"))
</code></pre>
<p><strong>And other model is :</strong></p>
<pre><code>class Entry(models.Model):
topic = models.ForeignKey(Topic, verbose_name=_("Topic"))
content = models.TextField(verbose_name=_("Content"))
created_at = models.DateTimeField(auto_now=True,verbose_name=_("Created at"))
</code></pre>
<p>Firstly, I want to filter only today's entries from <strong>Topic.py</strong>. Is that correct? :</p>
<pre><code>def get_topic_today(self):
return self.filter(date=datetime.date.today()).order_by('title')
</code></pre>
<p>And also I want to query popular topic max to min. I think we can use select_related with reverse foreign keys from entry to topic models. But I can not do it. For example, the topic which has most entry number must be first and going on lowest.</p>
| 2 | 2016-08-23T06:59:54Z | 39,094,644 | <p>If you want to order popular topic from max entry to min:</p>
<pre><code>def get_topic_today(self):
return self.filter(created_at__date=datetime.date.today()).annotate(entry_count=models.Count('entry_set')).order_by('-entry_count')
</code></pre>
| 1 | 2016-08-23T07:14:54Z | [
"python",
"django"
] |
find all elements and indices larger than threshold in list of lists | 39,094,459 | <p>I have a list of lists like:</p>
<pre><code> j=[[1,2,3],[4,5,6],[7,8,9,10],[11,12,13,14,15]]
</code></pre>
<p>and I want to get a list of all elements from the list of lists larger than a certain threshold. I know when having a list there is the Syntax:</p>
<pre><code>k=[1,2,3,4,5,6,7]
k2=[i for i in k if i>5]
k2=[6,7]
</code></pre>
<p>Is there a similar way when having a lists of lists as an Input?
Is it additionally possible to get the indices of the elements larger than that threshold?</p>
| 0 | 2016-08-23T07:05:16Z | 39,094,500 | <p>Is this what you mean?</p>
<pre><code>In [3]: l1 = [[1,2,3],[4,5,6],[7,8,9,10],[11,12,13,14,15]]
In [4]: [e for l2 in l1 for e in l2 if e>5]
Out[4]: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
</code></pre>
<p>To get the index (of the inner lists), you can use <code>enumerate</code>:</p>
<pre><code>In [5]: [(i2, e) for l2 in l1 for i2, e in enumerate(l2) if e>5]
Out[5]:
[(2, 6),
(0, 7),
(1, 8),
(2, 9),
(3, 10),
(0, 11),
(1, 12),
(2, 13),
(3, 14),
(4, 15)]
</code></pre>
<p>If you want the indices in a separate list (un)zip:</p>
<pre><code>In [6]: list(zip(*[(i2, e) for l2 in l1 for i2, e in enumerate(l2) if e>5]))
Out[6]: [(2, 0, 1, 2, 3, 0, 1, 2, 3, 4), (6, 7, 8, 9, 10, 11, 12, 13, 14, 15)]
</code></pre>
<p>[You don't need the <code>list</code> call if you're using Python 2]. A similar approach will give you indexes into both the outer and inner lists:</p>
<pre><code>In [7]: [((i1,i2), e) for (i1,l2) in enumerate(l1) for i2, e in enumerate(l2) if e>5]
Out[7]:
[((1, 2), 6),
((2, 0), 7),
((2, 1), 8),
((2, 2), 9),
((2, 3), 10),
((3, 0), 11),
((3, 1), 12),
((3, 2), 13),
((3, 3), 14),
((3, 4), 15)]
</code></pre>
<p>or, unzipped:</p>
<pre><code>In [8]: idx, items = list(zip(*[((i1,i2), e) for (i1,l2) in enumerate(l1)
for i2, e in enumerate(l2) if e>5]))
In [8]: idx
Out[8]:
((1, 2),
(2, 0),
(2, 1),
(2, 2),
(2, 3),
(3, 0),
(3, 1),
(3, 2),
(3, 3),
(3, 4))
In [9]: items
Out[9]: (6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
</code></pre>
| 6 | 2016-08-23T07:07:28Z | [
"python",
"list"
] |
Odoo: _get_state() takes at least 4 arguments (4 given) in xml view | 39,094,524 | <p>Here is mycode. I want to get id_employee of current record before define its model class:</p>
<pre><code>def _get_state(self, cr, uid, context=None):
idemployee = ""
for adv in self.browse(cr, uid, ids, context):
id_employee = adv.id_employee
if id_employee is None:
idemployee = _default_employee(self, cr, uid, context=None)
else:
idemployee = id_employee
sql = " SELECT C.id AS id, C.sequence, C.name \
FROM wf_group_member A \
LEFT JOIN wf_group B ON B.id = A.group_id \
LEFT JOIN wf_process BB ON BB.id = B.process_id \
LEFT JOIN wf_state C ON C.group_id = B.id \
LEFT JOIN hr_employee D ON D.id = A.member_id \
WHERE LOWER(code) = 'ca' AND member_id = %s ORDER BY sequence "
res = []
cr.execute(sql, [(idemployee)])
ardata = cr.fetchall()
for data in ardata:
res.append((data[1], data[2]))
return res
</code></pre>
<p>and this is my model class that I put it after _get_state function</p>
<pre><code>class cashadvance(osv.osv):
_name = 'ga.cashadvance'
_columns = {
'id_user' : fields.many2one('res.users', string='User', required=True, readonly=True),
'state' : fields.selection(_get_state, 'Status', readonly=True),
'id_employee' : fields.many2one('hr.employee', string='Employee', required=True, readonly=True),
}
</code></pre>
<p>When I call _get_state function, it raised error :</p>
<pre><code>Error details:
global name 'ids' is not defined
None" while parsing /opt/custom-addons/comben/views/cashadvance_view.xml:4, near
<record id="cashadvance_list" model="ir.ui.view">
<field name="name">cashadvance_list</field>
<field name="model">ga.cashadvance</field>
<field name="arch" type="xml">
<tree string="Cashadvance List">
<field name="id_employee"/>
<field name="category_id"/>
<field name="est_date_from" string="Est Date From"/>
<field name="est_date_to" string="Est Date To"/>
<field name="description"/>
<field name="state"/>
</tree>
</field>
</record>
</code></pre>
<p>can somebady help me please, thanks</p>
| 1 | 2016-08-23T07:08:54Z | 39,138,502 | <p><code>_get_state</code> has to be part of the class for you to use it not outside the class, the self you're passing in there is not seen as the python <code>self</code> i.e the current instance, it's seen as a normal argument of the function.</p>
<p>Python isn't passing in self for you, let me deviate a little and reproduce the error you're getting. look at this code</p>
<pre><code>def func(self,cr, uid, ids, context=None):
pass
class func_test:
def __init__(self):
func(1, 1, 1, context=1)
a = func_test()
</code></pre>
<p>This is the Error raised (make sure you run this with python2)</p>
<pre><code>Traceback (most recent call last):
File "script.py", line 8, in <module>
a = func_test()
File "script.py", line 6, in __init__
func(1, 1, 1, context=1)
TypeError: func() takes at least 4 arguments (4 given)
</code></pre>
<p>python is actually correct even though it's misleading, the function expects at least four arguments because context is a keyword argument and has been filled in at the time of the function definition, but it's still missing one parameter, because the function is outside a class so the first argument which is usually called <code>self</code> is taken as a normal parameter (since it's a function) not a method (function in a class). so starting from left to right <code>self</code>, <code>cr</code>, <code>uid</code> would be filled in as <code>1</code> <code>1</code> <code>1</code> leaving <code>ids</code> and at this point python would cry out for help because no value was found for that argument, if we move that function into the class and call it with <code>self.func</code>, the current instance automatically gets passed for us.</p>
<pre><code>class func_test:
def func(self,cr, uid, ids, context=None):
pass
def __init__(self):
self.func(1, 1, 1, context=1)
a = func_test()
</code></pre>
<p>Of course you could still have <code>func(self, 1, 1, 1, context=1)</code> but that would be defeating the purpose of methods</p>
<p>But note that python3 is smarter and handles this scenario better than python2, this is a python3 traceback</p>
<pre><code>Traceback (most recent call last):
File "script.py", line 8, in <module>
a = func_test()
File "script.py", line 6, in __init__
func(1, 1, 1, context=1)
TypeError: func() missing 1 required positional argument: 'ids'
</code></pre>
<p>It plainly tells us that no value was provided for <code>ids</code> in the function call</p>
<p>so going back to Odoo your code should look like this</p>
<pre><code>from openerp.osv import osv, fields
class cashadvance(osv.osv):
_name='comben.cashadvance'
def _get_state(self, cr, uid, context=None):
idemployee = ""
ids = self.search(cr, uid, [], context=context) # you probably want to search for all the records
for adv in self.browse(cr, uid, ids, context=context):
id_employee = adv.id_employee
if id_employee is None:
idemployee = self._default_employee(cr, uid, ids, context=None) # might raise singleton error if more than one record is returned
else:
idemployee = id_employee.id
sql = " SELECT C.id AS id, C.sequence, C.name \
FROM wf_group_member A \
LEFT JOIN wf_group B ON B.id = A.group_id \
LEFT JOIN wf_process BB ON BB.id = B.process_id \
LEFT JOIN wf_state C ON C.group_id = B.id \
LEFT JOIN hr_employee D ON D.id = A.member_id \
WHERE LOWER(code) = 'ca' AND member_id = %s ORDER BY sequence "
res = []
cr.execute(sql, [(idemployee)])
ardata = cr.fetchall()
for data in ardata:
res.append((data[1], data[2]))
return res
_columns = {
'id_user': fields.many2one('res.users', string='User', required=True, readonly=True),
'state': fields.selection(_get_state, string='Status', readonly=True),
'id_employee': fields.many2one('hr.employee', string='Employee', required=True, readonly=True),
}
</code></pre>
<p>and also move <code>_default_employee</code> into the class body, so you can call it like this</p>
<pre><code>self._default_employee(cr, uid, context=None) # python implicitly passes self for you
</code></pre>
<p>xml view</p>
<pre><code><record id="cashadvance_list" model="ir.ui.view">
<field name="name">cashadvance list</field>
<field name="model">comben.cashadvance</field>
<field name="arch" type="xml">
<tree string="Cashadvance List">
<field name="id_employee"/>
<field name="id_user"/>
<field name="state"/>
</tree>
</field>
</record>
</code></pre>
| 1 | 2016-08-25T06:50:33Z | [
"python",
"openerp"
] |
Odoo: _get_state() takes at least 4 arguments (4 given) in xml view | 39,094,524 | <p>Here is mycode. I want to get id_employee of current record before define its model class:</p>
<pre><code>def _get_state(self, cr, uid, context=None):
idemployee = ""
for adv in self.browse(cr, uid, ids, context):
id_employee = adv.id_employee
if id_employee is None:
idemployee = _default_employee(self, cr, uid, context=None)
else:
idemployee = id_employee
sql = " SELECT C.id AS id, C.sequence, C.name \
FROM wf_group_member A \
LEFT JOIN wf_group B ON B.id = A.group_id \
LEFT JOIN wf_process BB ON BB.id = B.process_id \
LEFT JOIN wf_state C ON C.group_id = B.id \
LEFT JOIN hr_employee D ON D.id = A.member_id \
WHERE LOWER(code) = 'ca' AND member_id = %s ORDER BY sequence "
res = []
cr.execute(sql, [(idemployee)])
ardata = cr.fetchall()
for data in ardata:
res.append((data[1], data[2]))
return res
</code></pre>
<p>and this is my model class that I put it after _get_state function</p>
<pre><code>class cashadvance(osv.osv):
_name = 'ga.cashadvance'
_columns = {
'id_user' : fields.many2one('res.users', string='User', required=True, readonly=True),
'state' : fields.selection(_get_state, 'Status', readonly=True),
'id_employee' : fields.many2one('hr.employee', string='Employee', required=True, readonly=True),
}
</code></pre>
<p>When I call _get_state function, it raised error :</p>
<pre><code>Error details:
global name 'ids' is not defined
None" while parsing /opt/custom-addons/comben/views/cashadvance_view.xml:4, near
<record id="cashadvance_list" model="ir.ui.view">
<field name="name">cashadvance_list</field>
<field name="model">ga.cashadvance</field>
<field name="arch" type="xml">
<tree string="Cashadvance List">
<field name="id_employee"/>
<field name="category_id"/>
<field name="est_date_from" string="Est Date From"/>
<field name="est_date_to" string="Est Date To"/>
<field name="description"/>
<field name="state"/>
</tree>
</field>
</record>
</code></pre>
<p>can somebady help me please, thanks</p>
| 1 | 2016-08-23T07:08:54Z | 39,141,934 | <p>In this case, you want this :</p>
<pre><code>def _get_state(self, cr, uid, ids, context=None):
current_record=self.browse(cr, uid, ids)
idemployee = current_record[0].id_employee
sql = " SELECT C.id AS id, C.sequence, C.name \
FROM wf_group_member A \
LEFT JOIN wf_group B ON B.id = A.group_id \
LEFT JOIN wf_process BB ON BB.id = B.process_id \
LEFT JOIN wf_state C ON C.group_id = B.id \
LEFT JOIN hr_employee D ON D.id = A.member_id \
WHERE LOWER(code) = 'ca' AND member_id = %s ORDER BY sequence "
res = []
cr.execute(sql, [(idemployee)])
ardata = cr.fetchall()
for data in ardata:
res.append((data[1], data[2]))
return res
</code></pre>
| 0 | 2016-08-25T09:48:59Z | [
"python",
"openerp"
] |
Pandas slicing and indexing use with fillna | 39,094,651 | <p>I have a pandas dataframe <strong>tdf</strong>
I am extracting a slice based on boolean labels</p>
<pre><code>idx = tdf['MYcol1'] == 1
myslice = tdf.loc[idx] //I want myslice to be a view not a copy
</code></pre>
<p>Now i want to fill the missing values in a column of <strong>myslice</strong> and i want this to be reflected in <strong>tdf</strong> my original dataframe</p>
<pre><code>myslice.loc[:,'MYcol2'].fillna(myslice['MYcol2'].mean(), inplace = True) // 1
myslice.ix[:,'MYcol2'].fillna(myslice['MYcol2'].mean(), inplace = True) // 2
</code></pre>
<p>Both 1 and 2 above throw the warning that: A value is trying to be set on a copy of a slice from a DataFrame</p>
<p>What am i doing wrong?</p>
| 0 | 2016-08-23T07:15:35Z | 39,095,026 | <p>When you assign it to a new variable, it creates a copy. The things you do after that are irrelevant. Consider this:</p>
<pre><code>tdf
Out:
A B C
0 NaN 0.195070 -1.781563
1 -0.729045 0.196557 0.354758
2 0.616887 0.008628 NaN
3 NaN NaN 0.037006
4 0.767902 NaN NaN
5 -0.805627 NaN NaN
6 1.133080 NaN -0.659892
7 -1.139802 0.784958 -0.554310
8 -0.470638 -0.216950 NaN
9 -0.392389 -3.046143 0.543312
idx = tdf['A'] > 0
myslice = tdf.loc[idx]
</code></pre>
<p>Fill NaN's in myslice:</p>
<pre><code>myslice.loc[:,'B'].fillna(myslice['B'].mean(), inplace = True)
C:\Anaconda3\envs\p3\lib\site-packages\pandas\core\generic.py:3191: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self._update_inplace(new_data)
myslice
Out:
A B C
2 0.616887 0.008628 NaN
4 0.767902 0.008628 NaN
6 1.133080 0.008628 -0.659892
tdf
Out:
A B C
0 NaN 0.195070 -1.781563
1 -0.729045 0.196557 0.354758
2 0.616887 0.008628 NaN
3 NaN NaN 0.037006
4 0.767902 NaN NaN
5 -0.805627 NaN NaN
6 1.133080 NaN -0.659892
7 -1.139802 0.784958 -0.554310
8 -0.470638 -0.216950 NaN
9 -0.392389 -3.046143 0.543312
</code></pre>
<p>It is not reflected in tdf, because:</p>
<pre><code>myslice.is_copy
Out: <weakref at 0x000001CC842FD318; to 'DataFrame' at 0x000001CC8422D6A0>
</code></pre>
<p>If you change it to:</p>
<pre><code>tdf.loc[:, 'B'].fillna(tdf.loc[idx, 'B'].mean(), inplace=True)
tdf
Out:
A B C
0 NaN 0.195070 -1.781563
1 -0.729045 0.196557 0.354758
2 0.616887 0.008628 NaN
3 NaN 0.008628 0.037006
4 0.767902 0.008628 NaN
5 -0.805627 0.008628 NaN
6 1.133080 0.008628 -0.659892
7 -1.139802 0.784958 -0.554310
8 -0.470638 -0.216950 NaN
9 -0.392389 -3.046143 0.543312
</code></pre>
<p>then it works. In the last part you can also use <code>myslice['B'].mean()</code> because you are not updating those values. But the left side should be the original DataFrame.</p>
| 2 | 2016-08-23T07:33:47Z | [
"python",
"pandas"
] |
how to pass null values as arguments from java to python | 39,094,662 | <p>I have a java method that passes some arguments to a python file. I am passing the the arguments this way :</p>
<pre><code>String name=null; //can be null or some value in some cases.
....
String[] cmd = {
"python",
"C:/Python34/myscript.py",
name,
username,
pwd};
Process p=Runtime.getRuntime().exec(cmd);
</code></pre>
<p>the variable name would be null in some execution and it might not but when it becomes null i am getting <code>java.lang.NullPointerException</code>.</p>
<p>My python file <code>myscript.py</code> will run with null values if i am running it from command prompt but i am not able to from java.</p>
<p>How can i pass null value without the exception. Can you help me with this?</p>
| 2 | 2016-08-23T07:16:04Z | 39,094,760 | <p>Instead of passing them as null, do a NullPointer check and pass in empty strings.</p>
<pre><code>name = name == null ? "" : name;
</code></pre>
<p>That way your python script will just need to check for empty strings instead of nulls. And you can check for both by a simple if check. Something like below will work.</p>
<pre><code>if not name:
# this will check for both None and "" empty string
print "name was not passed"
</code></pre>
| 0 | 2016-08-23T07:21:01Z | [
"java",
"python"
] |
how to pass null values as arguments from java to python | 39,094,662 | <p>I have a java method that passes some arguments to a python file. I am passing the the arguments this way :</p>
<pre><code>String name=null; //can be null or some value in some cases.
....
String[] cmd = {
"python",
"C:/Python34/myscript.py",
name,
username,
pwd};
Process p=Runtime.getRuntime().exec(cmd);
</code></pre>
<p>the variable name would be null in some execution and it might not but when it becomes null i am getting <code>java.lang.NullPointerException</code>.</p>
<p>My python file <code>myscript.py</code> will run with null values if i am running it from command prompt but i am not able to from java.</p>
<p>How can i pass null value without the exception. Can you help me with this?</p>
| 2 | 2016-08-23T07:16:04Z | 39,094,762 | <p>Since python and java are different processes you are communicating between using system calls, you cannot convert Java <code>null</code> to the command line.</p>
<p>(What you call <code>null</code> in Python is actually <code>None</code>)</p>
<p>What you can do is: pass empty string (<code>""</code> not <code>null</code>) to the python program, and the python program can interpret empty strings and convert them to <code>None</code>.</p>
<p>Or decide a convention: if <code>"<NULL>"</code> string is passed from java then assume <code>None</code> from python side when parsing the args.</p>
<p>Other solutions like Jython would maybe allow this because they do no involve system calls.</p>
| 0 | 2016-08-23T07:21:08Z | [
"java",
"python"
] |
Memory not released when a pyqtgraph Plot is closed | 39,094,764 | <p>My Python QApplication has a button (on the main window) which, when clicked, launches a pyqtgraph Plot. The code below shows how the plot is generated within a class.</p>
<pre><code>self.win = pg.GraphicsWindow()
self.win.setWindowTitle(self.title)
self.p = self.win.addPlot()
self.curve = self.p.plot(self.Data1)
</code></pre>
<p>One of the things I have noticed is that when I close the plot window in my application, the memory is not released. So for example, before the button is pressed, the Application takes around 20Mb. Once the plot is launched by clicking the button, this increases to 25Mb. But when I close the plot (by clicking on the x in the top right corner), the Application memory footprint stays at 25Mb. Is there any way to release this 5Mb of memory when the plot is closed (note that I have the line <code>self.curve.clear()</code> so there is no leak while the plot is being updated in real-time).</p>
<p>Is it a case of modifying the <code>close()</code> or <code>closeEvent()</code> method. Or somehow deleting the reference to the object (though not sure how that would be done).</p>
<p>Many thanks for reading!</p>
| 0 | 2016-08-23T07:21:20Z | 39,094,887 | <p>A couple of things.</p>
<ol>
<li>Just closing the window doesn't explicitly deallocate anything. Yes, internally, Window structures aren't used any more, but that doesn't mean it would be wise for the GUI toolkit to throw away everything it has calculated â maybe parts of that would be relevant for the next window, too?</li>
<li>Python has a non-deterministic (from a program runtime point of view) Garbage Collection, typical. So there's no guarantee that losing the last reference to an object would instantly free the memory the object uses</li>
<li>This might be a misconsception: It's not uncommon for scripting language runtimes to not instantly <code>free</code> the memory they have allocated the moment it's not immediately used any more â that would be a terrible strategy, because heuristically, it's pretty likely that you'll need at least parts of that again. And seriously, 5MB of memory (reserved? mapped?) aren't that much on a machine that runs a Python GUI, so there's no benefit of freeing them early. Doing so would probably be criticized as bad runtime design.</li>
</ol>
| 0 | 2016-08-23T07:26:47Z | [
"python",
"pyqtgraph"
] |
Django deserialization of JSON stored in a model field | 39,094,946 | <p>I'm new to Django/Python and currently working on a project with a friend. His android app sends data to me in JSON format that looks like this: </p>
<pre><code>"datum_isteka": "2",
"e_mail": "null",
"adress": "null",
"goods": "[
{\"price\":\"2\",
\"good\":\"dobro1\",
\"tax_value\":\"2\",
\"quantity\":\"pdv %1\"},
{\"price\":\"3\",
\"good\":\"dobro 2\",
\"tax_value\":\"3\",
\"quantity\":\"pdv %3\"}
]",
"taxes": 5,
"order_num": 477456,
"store_user": 2
</code></pre>
<p>In my models this is stored in one field (the <code>goods</code>) and in my view i get this whole <code>goods</code> part of this JSON represented like this up here... My question is how do i turn this JSON field <code>goods</code> to something that is readable to a user. I'm using DRF for communication with android app.</p>
<p>Model: </p>
<pre><code>class Obraz(models.Model):
datum_isteka = models.CharField(max_length=100,blank=True,
default='', null=True)
e_mail = models.CharField(max_length=100, blank=True,
default='', null=True)
adress = models.CharField(max_length=100, blank=True, null=True)
taxes = models.CharField(max_length=100)
order_num = models.CharField(max_length=100, blank=True, default='',
null=True)
goods = models.CharField(max_length=10000)
store_user=models.ForeignKey(Owner, default='Owner')
</code></pre>
<p>Model serializer:</p>
<pre><code>class ObrazSerializer(serializers.ModelSerializer):
class Meta:
model = Obraz
fields = ('datum_isteka', 'e_mail', 'adress', 'taxes',
'order_num','goods ', 'store_user',)
</code></pre>
| 1 | 2016-08-23T07:29:58Z | 39,097,195 | <p>I'd use a <a href="https://pypi.python.org/pypi/django-jsonfield" rel="nofollow">JSONField</a> on the model</p>
<pre><code>class Obraz(models.Model):
...
goods = jsonfield.JSONField()
</code></pre>
<p>and a <a href="http://www.django-rest-framework.org/api-guide/fields/#jsonfield" rel="nofollow">JSONField</a> (notice it's not the same field) on the serializer:</p>
<pre><code>class ObrazSerializer(serializers.ModelSerializer):
goods = serializers.JSONField()
class Meta:
model = Obraz
fields = ('datum_isteka', 'e_mail', 'adress', 'taxes',
'order_num','goods', 'store_user',)
</code></pre>
<p>hope this helps</p>
| 0 | 2016-08-23T09:19:14Z | [
"python",
"json",
"django",
"serialization",
"django-rest-framework"
] |
Theanos Installation error linux compilation error | 39,094,982 | <p>So I was trying to setup theano on my Linux14.04 machine .
Steps done so far : </p>
<ul>
<li>Installed miniconda</li>
<li>installed dependencies - <code>conda install numpy scipy mkl <nose> <sphinx> <pydot-ng></code></li>
<li>Did not install the GPU drivers .... do not need the higher computation as of now.</li>
<li>Tried installing theano with : <code><sudo> pip install <--user> Theano[test, doc]
</code></li>
</ul>
<p>It exited with the following error :<br>
<a href="https://gist.github.com/crazysal/2c1990360a4ca0750d182e4217de998d" rel="nofollow">Theano terminal error gist</a></p>
<p>Been trying to solve the same, max online references are related to upgrading pip :
Ran this :
<code>pip install --upgrade pip
Requirement already up-to-date: pip in ./miniconda2/lib/python2.7/site-packages</code> </p>
| 0 | 2016-08-23T07:31:42Z | 39,096,469 | <p>Package error :
Solved by installing : </p>
<pre><code>sudo apt-get install python-dev
</code></pre>
<p>Gave error for installing dependencies Theano[test, doc] :
Clean install with only : </p>
<pre><code>sudo pip install Theano
</code></pre>
| 0 | 2016-08-23T08:47:17Z | [
"python",
"linux",
"theano"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.