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
listlengths
1
5
How to use Selenium to get this index?
38,538,032
<p>I'm trying to retrieve the fear index from the link <a href="http://money.cnn.com/data/fear-and-greed/" rel="nofollow">http://money.cnn.com/data/fear-and-greed/</a>. The index is dynamically changing. When I inspect the element, it shows the coding below. I'm just wondering how to use python Selenium to get the 84 and other indexes? I tried to use the code below but only got blank. Any ideas?</p> <pre><code>cr = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH,"//*[contains(text(), 'Fear &amp; Greed Now')]"))) </code></pre> <p>Below is the webpage code</p> <pre><code>&lt;div id="needleChart" style="background-image:url('http://money.cnn.com/.element/img/5.0/data/feargreed/1.png');"&gt; &lt;ul&gt; &lt;li&gt;Fear &amp;amp; Greed Now: 84 (Extreme Greed) &lt;/li&gt; &lt;li&gt;Fear &amp;amp; Greed Previous Close: 86 (Extreme Greed)&lt;/li&gt; &lt;li&gt;Fear &amp;amp; Greed 1 Week Ago: 89 (Extreme Greed)&lt;/li&gt; &lt;li&gt;Fear &amp;amp; Greed 1 Month Ago: 57 (Greed)&lt;/li&gt; &lt;li&gt;Fear &amp;amp; Greed 1 Year Ago: 16 (Extreme Fear)&lt;/li&gt; &lt;/ul&gt; </code></pre>
3
2016-07-23T04:02:35Z
38,538,132
<p>Try as below :-</p> <pre><code>elements = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID,"needleChart"))).find_elements_by_tag_name("li") for li in elements: text = li.get_attribute("innerHTML") s = ''.join(x for x in text if x.isdigit()) print(s) </code></pre> <p>Hope it helps...:)</p>
0
2016-07-23T04:21:09Z
[ "python", "selenium" ]
How do I initialize and fill in a list of lists of different lengths?
38,538,264
<p>I'm writing a small Python program that will simulate a certain TV show (it's for fun guys ok please don't judge me). </p> <p>In this program, I am trying to randomly sort the contestants into a list of lists (to emulate a Team Challenge, as you may say). I wrote a function that (is intended) to take in an unsorted list of Contestant objects (because I want to access the name attribute of each Contestant object) and a list that contains the information about the sizes of each individual list in the 2D list I intend to return in the end. </p> <p>To further explain the second parameter, I'll give an example. Let's say the Queens need to be divided into 2 teams of 5 and 6. The numTeams will then be [5,6].</p> <p>This is full function that I have written so far:</p> <pre><code> def sortIntoTeams(contest_obj, numTeams): # where I will eventually store all the names of the individuals queenList = [] # creates 2D list, however, I just initialized the first subscript # part, so to speak teamShuffledList = len(numTeams) * [[None]] # this was just a test, but I made another for loop to # fill the second subscript part of the 2D list, so to speak too for i in range(0, len(numTeams)): count = numTeams[i] teamShuffledList[i] = count * [0] # for loop to fill queenList with all the names of the Queen # objects in the contest_obj for i in range(0, countRemaining(contest_obj)): queenList.append(contest_obj[i].name) # from random import shuffle, to shuffle queenList shuffle(queenList) </code></pre> <p>Now, what I intend to do is fill the teamShuffledList with queenList, but the teamShuffledList has lists of different lengths. Is there any easy way to keep tracks of the different lengths? Any help would be greatly appreciated, thanks so much.</p> <p>EDIT: Even though it's sorta self-explanatory, the countRemaining(contest_obj) is a different function that I wrote that just counts the remaining contestant objects in the list.</p>
1
2016-07-23T04:46:35Z
38,538,334
<pre><code>def sortIntoTeams(contest_obj, numTeams): # Create a randomly-ordered copy of the contestants' names random_contestants = [x.name for x in contest_obj] random.shuffle(random_contestants) result = [] for teamsize in numTeams: # Take the first &lt;teamsize&gt; contestants from the list result.append(random_contestants[:teamsize]) # Remove those contestants, since they now have a team random_contestants = random_contestants[teamsize:] return result </code></pre> <p>There is no need to "initialize" anything.</p>
0
2016-07-23T04:58:12Z
[ "python", "arrays", "list", "sorting", "python-3.x" ]
How do I initialize and fill in a list of lists of different lengths?
38,538,264
<p>I'm writing a small Python program that will simulate a certain TV show (it's for fun guys ok please don't judge me). </p> <p>In this program, I am trying to randomly sort the contestants into a list of lists (to emulate a Team Challenge, as you may say). I wrote a function that (is intended) to take in an unsorted list of Contestant objects (because I want to access the name attribute of each Contestant object) and a list that contains the information about the sizes of each individual list in the 2D list I intend to return in the end. </p> <p>To further explain the second parameter, I'll give an example. Let's say the Queens need to be divided into 2 teams of 5 and 6. The numTeams will then be [5,6].</p> <p>This is full function that I have written so far:</p> <pre><code> def sortIntoTeams(contest_obj, numTeams): # where I will eventually store all the names of the individuals queenList = [] # creates 2D list, however, I just initialized the first subscript # part, so to speak teamShuffledList = len(numTeams) * [[None]] # this was just a test, but I made another for loop to # fill the second subscript part of the 2D list, so to speak too for i in range(0, len(numTeams)): count = numTeams[i] teamShuffledList[i] = count * [0] # for loop to fill queenList with all the names of the Queen # objects in the contest_obj for i in range(0, countRemaining(contest_obj)): queenList.append(contest_obj[i].name) # from random import shuffle, to shuffle queenList shuffle(queenList) </code></pre> <p>Now, what I intend to do is fill the teamShuffledList with queenList, but the teamShuffledList has lists of different lengths. Is there any easy way to keep tracks of the different lengths? Any help would be greatly appreciated, thanks so much.</p> <p>EDIT: Even though it's sorta self-explanatory, the countRemaining(contest_obj) is a different function that I wrote that just counts the remaining contestant objects in the list.</p>
1
2016-07-23T04:46:35Z
38,538,347
<pre><code>def sortIntoTeams(contest_obj, numTeams): counter = 0 teams = [] for k in numTeams: teams.append(contest_obj[counter:counter + k]) counter = counter + k return teams </code></pre>
0
2016-07-23T05:02:00Z
[ "python", "arrays", "list", "sorting", "python-3.x" ]
How to standard scale a large numpy matrix with sklearn? (batch processing)
38,538,376
<p>I am working in a classification problem with gradient boosting. As usual before classifiying I would like to scale my feature matrix (<code>878049, 3208</code>). </p> <pre><code>A = LabelEncoder().fit_transform(training_data['col1'].values.reshape(-1, 1).ravel()) B = LabelEncoder().fit_transform(training_data['col2'].values.reshape(-1, 1).ravel()) C = LabelEncoder().fit_transform(training_data['col3'].values.reshape(-1, 1).ravel()) </code></pre> <p>Then:</p> <pre><code>A_1 = OneHotEncoder().fit_transform(A.reshape(-1, 1)).A B_2 = OneHotEncoder().fit_transform(B.reshape(-1, 1)).A C_3 = OneHotEncoder().fit_transform(C.reshape(-1, 1)).A D_4 = CountVectorizer().fit_transform(training_data['Col_4'].values) </code></pre> <p>Then:</p> <pre><code>print(A_1.shape, B_2.shape, C_3.shape, D_4.shape) &gt;&gt;&gt; (878049, 10) (878049, 2249) (878049, 7) (878049, 942) X = np.column_stack((A_1.A, B_2, C_3, D_4)) </code></pre> <p>Here is when everything freeze:</p> <pre><code>scaler = StandardScaler() X_new = scaler.partial_fit(X) </code></pre> <p>However, although I tried to <code>partial_fit()</code> function, my whole computer freeze. Thus, what can I do in a situation like this?.</p> <p>I also tried to scale each feature before sticking the arrays. Nevertheless, I belive that actually wrong. Any suggestion guys?.</p> <p><strong>update</strong> I also tried to feature select before scaling. However, I believe it is wrong.</p>
0
2016-07-23T05:07:37Z
38,544,754
<p>The <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler.partial_fit" rel="nofollow">docs</a> of <code>partial_fit</code> explain what's happening. The following is the relevant part: </p> <blockquote> <p>partial_fit(X, y=None) </p> <p>All of X is processed as a single batch</p> </blockquote> <p>So it's <strong>your task to call partial_fit multiple times with partial-data</strong> (as opposed to call it one-time with all your data like you are doing).</p> <p>Just try something like this (untested code; just to give you the idea):</p> <pre><code>scaler = StandardScaler() n = X.shape[0] # number of rows batch_size = 1000 # number of rows in each call to partial_fit index = 0 # helper-var while index &lt; n: partial_size = min(batch_size, n - index) # needed because last loop is possibly incomplete partial_x = X[index:index+partial_size] scaler.partial_fit(partial_x) index += partial_size </code></pre> <h3>Remarks</h3> <ul> <li><code>partial_fit</code> returns <code>None</code> (which is also wrongly used in your code)</li> <li>after using <code>partial_fit</code> within the loop, you can use <code>scaler.transform</code> to get your rescaled data: <em>maybe you need to this within a loop too</em></li> </ul>
2
2016-07-23T17:41:39Z
[ "python", "numpy", "scipy", "scikit-learn" ]
Python filter numbers within optional bounds (use less if-else)
38,538,386
<p>I want to select elements from list of numbers within lower and upper bounds, each of which is optional. I can write it as a series of if and else for all possible cases. Can we reduce these branching and write in a concise way?</p> <pre><code>def select_within_bounds(li, lower=None, upper=None): if lower is None: if upper is None: return li else: return [v for v in li if v &lt;= upper] else: if upper is None: return [v for v in li if v &gt;= lower] else: return [v for v in li if lower &lt;= v &lt;= upper] #example: my_list = [1, 4, 5, 3, 6, 9] print(select_within_bounds(my_list)) print(select_within_bounds(my_list, 3, 8)) print(select_within_bounds(my_list, lower=3)) print(select_within_bounds(my_list, upper=8)) print(select_within_bounds(my_list, lower=3,upper=8)) #results in [1, 4, 5, 3, 6, 9] [4, 5, 3, 6] [4, 5, 3, 6, 9] [1, 4, 5, 3, 6] [4, 5, 3, 6] </code></pre>
3
2016-07-23T05:10:43Z
38,538,397
<p>You know the answer when the numeric bounds are always present. So, you can first derive the bounds and then apply the same logic. That is:</p> <pre><code>def select_within_bounds(li, lower=None, upper=None): lower = min(li) if lower is None else lower upper = max(li) if upper is None else upper return [v for v in li if lower &lt;= v &lt;= upper] </code></pre> <p><strong>Updated:</strong> based on @Copperfield's comment: we can avoid calumniating min/max by using default boundaries as symbolic infinities (linear vs constant cost)</p> <pre><code>lower = float("-inf") if lower is None else lower upper = float("inf") if upper is None else upper </code></pre>
0
2016-07-23T05:13:14Z
[ "python", "if-statement" ]
Python filter numbers within optional bounds (use less if-else)
38,538,386
<p>I want to select elements from list of numbers within lower and upper bounds, each of which is optional. I can write it as a series of if and else for all possible cases. Can we reduce these branching and write in a concise way?</p> <pre><code>def select_within_bounds(li, lower=None, upper=None): if lower is None: if upper is None: return li else: return [v for v in li if v &lt;= upper] else: if upper is None: return [v for v in li if v &gt;= lower] else: return [v for v in li if lower &lt;= v &lt;= upper] #example: my_list = [1, 4, 5, 3, 6, 9] print(select_within_bounds(my_list)) print(select_within_bounds(my_list, 3, 8)) print(select_within_bounds(my_list, lower=3)) print(select_within_bounds(my_list, upper=8)) print(select_within_bounds(my_list, lower=3,upper=8)) #results in [1, 4, 5, 3, 6, 9] [4, 5, 3, 6] [4, 5, 3, 6, 9] [1, 4, 5, 3, 6] [4, 5, 3, 6] </code></pre>
3
2016-07-23T05:10:43Z
38,538,420
<p>Yes you can, using python's <a href="https://docs.python.org/2/library/functions.html#filter" rel="nofollow">filter</a> built-in function. Like so:</p> <pre><code>def select_within_bounds(li, lower=None, upper=None): return filter(lambda x: (x if lower is None else lower) &lt;= x &lt;= (x if upper is None else upper), li) </code></pre>
3
2016-07-23T05:16:49Z
[ "python", "if-statement" ]
Python filter numbers within optional bounds (use less if-else)
38,538,386
<p>I want to select elements from list of numbers within lower and upper bounds, each of which is optional. I can write it as a series of if and else for all possible cases. Can we reduce these branching and write in a concise way?</p> <pre><code>def select_within_bounds(li, lower=None, upper=None): if lower is None: if upper is None: return li else: return [v for v in li if v &lt;= upper] else: if upper is None: return [v for v in li if v &gt;= lower] else: return [v for v in li if lower &lt;= v &lt;= upper] #example: my_list = [1, 4, 5, 3, 6, 9] print(select_within_bounds(my_list)) print(select_within_bounds(my_list, 3, 8)) print(select_within_bounds(my_list, lower=3)) print(select_within_bounds(my_list, upper=8)) print(select_within_bounds(my_list, lower=3,upper=8)) #results in [1, 4, 5, 3, 6, 9] [4, 5, 3, 6] [4, 5, 3, 6, 9] [1, 4, 5, 3, 6] [4, 5, 3, 6] </code></pre>
3
2016-07-23T05:10:43Z
38,538,676
<pre><code>def select_within_bounds(li, lower=float('-inf'), upper=float('inf')): return [v for v in li if lower &lt;= v &lt;= upper] </code></pre>
3
2016-07-23T05:55:42Z
[ "python", "if-statement" ]
Why do we use format identifier python
38,538,406
<p>I am a beginner and learning Python. My question is python can read a variable in a string without format identifier, then why has format identifiers been provided for?</p> <p>Ex:</p> <pre><code>carPoolTotal = 4 print "We have total", carPoolTotal, "people in carpooling." print "We have total %d people in carpooling." % carPoolTotal </code></pre> <p>Both works the same thing, then why exactly is identifier introduced in Python?</p>
0
2016-07-23T05:15:01Z
38,538,432
<p>Format identifiers help if you want to provide non-default formatting for your values. For example, you might want to format a long decimal as a decimal with a maximum of two decimal places.</p>
2
2016-07-23T05:18:23Z
[ "python", "python-2.7" ]
Subtracting a fixed date from a column in Pandas
38,538,479
<p>Consider </p> <pre><code>In [99]: d = pd.to_datetime({'year':[2016], 'month':[06], 'day':[01]}) In [100]: d1 = pd.to_datetime({'year':[2016], 'month':[01], 'day':[01]}) In [101]:d - d1 Out[101]: 0 152 days dtype: timedelta64[ns] </code></pre> <p>But when I try to do this for a whole column, it gives me trouble. Consider:</p> <pre><code>df['Age'] = map(lambda x:x - pd.to_datetime({'year':[2016], 'month':[06], 'day':[01]}), df['Manager_DoB']) </code></pre> <p><code>df['Manager_Dob']</code> is a column of datetime objects. It flags the following error:</p> <p><code>TypeError: can only operate on a datetime with a rhs of a timedelta/DateOffset for addition and subtraction, but the operator [__rsub__] was passed</code></p>
2
2016-07-23T05:26:19Z
38,538,945
<p>You don't need to use map*, you can subtract a Timestamp from a datetime column/Series:</p> <pre><code>In [11]: d = pd.to_datetime({'year':[2016], 'month':[6], 'day':[1]}) In [12]: d Out[12]: 0 2016-06-01 dtype: datetime64[ns] In [13]: d[0] # This is the Timestamp you are actually interested in subtracting Out[13]: Timestamp('2016-06-01 00:00:00') In [14]: dates = pd.date_range(start="2016-01-01", periods=4) In [15]: dates - d[0] Out[15]: TimedeltaIndex(['-152 days', '-151 days', '-150 days', '-149 days'], dtype='timedelta64[ns]', freq=None) </code></pre> <p>You can get the Timestamp more directly using the constructor:</p> <pre><code>In [21]: pd.Timestamp("2016-06-01") Out[21]: Timestamp('2016-06-01 00:00:00') </code></pre> <p>*<em>You should never use python's map with pandas, prefer <code>.apply</code>.</em></p>
2
2016-07-23T06:37:04Z
[ "python", "pandas" ]
Password: Invalid password format or unknown hashing algorithm even after setting in the create user function
38,538,491
<p>I have a custom user model:</p> <pre><code>class CustomUserManager(BaseUserManager): def _create_user(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, is_active, is_admin, is_superuser): if not email: raise ValueError('Email must be set') email = self.normalize_email(email) now = timezone.now() user = self.model( email=email, username=email, first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, gender=gender, mobile_number=mobile_number, date_joined=now, is_active=is_active, is_admin=is_admin, is_superuser=is_superuser, ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, **extra_fields): user = self._create_user( email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, True, False, False, **extra_fields ) user.save(using=self._db) return user def create_superuser(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, **extra_fields): user = self._create_user( email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, True, True, True, **extra_fields ) user.save(using=self._db) return user GENDERTYPE = ( ('1', 'Male'), ('2', 'Female'), ('3', 'Other') ) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) username = models.CharField(_('user name'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30) date_of_birth = models.DateField() gender = models.CharField(choices=GENDERTYPE, max_length=1) mobile_number = models.IntegerField(unique=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number'] </code></pre> <p>And the form to process:</p> <pre><code>class UserCreationForm(forms.ModelForm): class Meta: model = CustomUser fields = ('email', 'username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number') class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = CustomUser fields = ( 'email', 'username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number', 'is_active', 'is_admin' ) def clean_password(self): return self.initial["password"] </code></pre> <p>I can save the new user without any problems. </p> <p>However, when I try to login with the user credentials, I am not authenticated. Also when viewing the password, I get the errors in the admin interface.</p> <blockquote> <p>Password: Invalid password format or unknown hashing algorithm.</p> </blockquote> <p>Admins.py:</p> <pre><code>class CustomUserAdmin(UserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('first_name', 'last_name', 'email', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ( 'email', 'password' )}), ('Personal info', {'fields': ( ('first_name', 'last_name'), 'username', 'date_of_birth', 'gender', 'mobile_number' )}), ('Permissions', {'fields': ( 'is_active', 'is_admin' )}), ) add_fieldsets = ( (None, {'fields': ( 'email', 'password' )}), ('Personal info', {'fields': ( ('first_name', 'last_name'), 'username', 'date_of_birth', 'gender', 'mobile_number' )}), ) search_fields = ('first_name', 'last_name', 'email',) ordering = ('first_name', 'email',) filter_horizontal = () admin.site.register(CustomUser, CustomUserAdmin) </code></pre> <p>Although I am saving it in the <code>def _create_user()</code> function, with the password, its not setting the password. What am I doing wrong?</p>
1
2016-07-23T05:28:08Z
38,908,989
<p>i was also getting the same issue while calling create method of my custom model <code>Account</code> , <code>Account.objects.create( username='demo',email='demo12@demo.com', password='prakashsharma24#')</code></p> <p>I have just used <strong>create_user</strong> method and go the result </p> <pre><code>Account.objects.create_user(username='abcdef',email='abcdef@demo.com',password='prakashsharma24#') </code></pre> <p>Here is my working code:</p> <p><strong>models.py</strong></p> <pre><code>from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import BaseUserManager from django.db import models class AccountManager(BaseUserManager): def create_user(self, email, date_of_birth=None,password=None, **kwargs): print email, date_of_birth ,password,kwargs if not email: raise ValueError('Users must have a valid email address.') if not kwargs.get('username'): raise ValueError('Users must have a valid username.') account = self.model( email=self.normalize_email(email), username=kwargs.get('username'), date_of_birth=date_of_birth, ) account.set_password(password) user.save(using=self._db) account.save() # user.save(using=self._db) return account # user = Account.objects.create_user(username='admin', 'webkul.com', 'adminpassword') def create_superuser(self, email, date_of_birth,password, **kwargs): account = self.create_user(email,date_of_birth, password, **kwargs) account.is_admin = True account.is_staff = True account.save(using=self._db) return account class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email address', max_length=255,unique=True) date_of_birth = models.DateField(null=True) username = models.CharField(max_length=40, unique=True) first_name = models.CharField(max_length=40, blank=True) last_name = models.CharField(max_length=40, blank=True) tagline = models.CharField(max_length=140, blank=True) street = models.CharField(max_length=100, blank=True) street1 = models.CharField(max_length=100, blank=True) phone = models.CharField(max_length=40, blank=True) website = models.CharField(max_length=40, blank=True) city = models.CharField(max_length=40, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = AccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username','date_of_birth'] def __unicode__(self): return self.email def get_full_name(self): return ' '.join([self.first_name, self.last_name]) def get_short_name(self): return self.first_name def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True </code></pre> <p><strong>admin.py</strong></p> <pre><code>from django.contrib import admin # Register your models here. from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from authentication.models import Account class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = Account fields = ('email', 'date_of_birth','password') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = Account fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('email', 'date_of_birth', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('date_of_birth',)}), ('Permissions', {'fields': ('is_admin',)}), ) # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'date_of_birth', 'password1', 'password2')} ), ) search_fields = ('email',) ordering = ('email',) filter_horizontal = () admin.site.register(Account, UserAdmin) admin.site.unregister(Group) </code></pre>
0
2016-08-12T02:35:38Z
[ "python", "django", "django-models", "django-forms", "django-admin" ]
Python odeint- Initial condition y0 must be one-dimensional
38,538,584
<p>I am trying to simulate a dynamic system in state space form with odeint. My A matrix is 12*12 and B matrix is 12*4 (rows * cols) so my initial state vector is 12*1 as it suggests.</p> <p>My code is as follows </p> <pre><code>import numpy as np from scipy.integrate import odeint tmp = np.loadtxt("system.txt", skiprows =2) A=np.matrix(tmp)[0:12,0:12] B=np.matrix(tmp)[0:12,12:] control = np.matrix([[0.0],[0.0],[-0.6310],[0.0]]) def aircraft(state, t): return A*state + B*control state0 = np.array([[6.809827628],[0.439572153],[0.0],[0.0],[0.0],[0.0],[0.0],[0.0],[0.0],[0.0],[0.0],[0.0]]) t = np.arange(0.0, 10.0, 0.1) state = odeint(aircraft, state0, t) </code></pre> <p>I am getting this error </p> <pre><code>Traceback (most recent call last): File "sim.py", line 17, in &lt;module&gt; state = odeint(aircraft, state0, t) File "/home/aluminium/anaconda2/lib/python2.7/site-packages/scipy/integrate/odepack.py", line 215, in odeint ixpr, mxstep, mxhnil, mxordn, mxords) ValueError: Initial condition y0 must be one-dimensional. </code></pre> <p>Only way I can think of defining state vector is as a column vector. Can you please let me know how to define a initial state vector to overcome this problem ?</p> <p>Thanks so much in advance.</p>
0
2016-07-23T05:43:08Z
38,541,683
<p>Ive got the answer and thought of sharing it here with the hope that someone with the same problem in the future will benefit.</p> <p>odeint seems to expect 1d array as an state variable to call the function and 1d array return from the function as well.</p> <p>So I reshaped the variables accordingly. here is the code. </p> <pre><code>def aircraft(state, t): xdot= A*state.reshape(12,1) + B*control return np.squeeze(np.asarray(xdot)) state0 = np.array([6.809827628,0.439572153,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]) </code></pre> <p>Cheers</p>
0
2016-07-23T12:15:30Z
[ "python", "odeint" ]
How to run a webserver script on remote server through SSH?
38,538,592
<p>I am currently hosting a couple servers on my AWS EC2 Ubuntu 14.04 server. By default, the server doesn't have a GUI, but I installed one along with xRDP.</p> <p>If I run the script from the terminal, it will continuously run <strong>until</strong> the terminal is closed. <strong>But</strong>, if I run the script by simply double clicking it, it will run in the background and keep running regardless of whether the terminal window is open.</p> <p>This is a problem, because with xRDP sessions, when they close, the running windows in that session close as well. I want to be able to start and stop the servers using SSH, instead of having to manually remote desktop in.</p> <p>I have a way to easily kill the servers: <code>sudo killall -v python2.7</code>, and I can do this via SSH easily. The problem is, I cannot open the scripts for starting each server, because when I do, it runs the server in the terminal instance that is created on <em>my</em> computer. When I close that instance, the server closes as well.</p> <p>So the basic, TL;DR version is that I want to be able to run a script <strong>in the background</strong> via ssh. Does anyone have any ideas?</p> <p>Thanks!</p> <p>Justin</p>
-2
2016-07-23T05:44:05Z
38,538,831
<p>What I use for things like this is the <code>screen</code> command putting my command in a disconnected screen session. I can connect to it later if I need to.</p>
0
2016-07-23T06:20:29Z
[ "python", "ubuntu", "ssh", "amazon-ec2", "server" ]
Sklearn Spectral Clustering error in fit_predict : k must be between 1 and the order of the square input matrix
38,538,608
<p>I'm using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html" rel="nofollow">Spectral Clustering Library</a> in Python and similarity matrix is its main argument. My matrix looks like:</p> <pre><code>[[ 1. 0.85018854 0.85091491 0.85717652] [ 0.85018854 1. 0.99720197 0.99732831] [ 0.85091491 0.99720197 1. 0.9972462 ] [ 0.85717652 0.99732831 0.9972462 1. ]] </code></pre> <p>And my code similar to the documentation samples:</p> <pre><code>cl = SpectralClustering(n_clusters=4,affinity='precomputed') y = cl.fit_predict(matrix) </code></pre> <p>But the following error occurs:</p> <pre><code>Traceback (most recent call last): File "/home/mahmood/PycharmProjects/sentence2vec/graphClustering.py", line 22, in &lt;module&gt; y = cl.fit_predict(matrix) File "/usr/local/lib/python2.7/dist-packages/scikit_learn-0.17.1-py2.7-linux-x86_64.egg/sklearn/base.py", line 371, in fit_predict self.fit(X) File "/usr/local/lib/python2.7/dist-packages/scikit_learn-0.17.1-py2.7-linux-x86_64.egg/sklearn/cluster/spectral.py", line 454, in fit assign_labels=self.assign_labels) File "/usr/local/lib/python2.7/dist-packages/scikit_learn-0.17.1-py2.7-linux-x86_64.egg/sklearn/cluster/spectral.py", line 258, in spectral_clustering eigen_tol=eigen_tol, drop_first=False) File "/usr/local/lib/python2.7/dist-packages/scikit_learn-0.17.1-py2.7-linux-x86_64.egg/sklearn/manifold/spectral_embedding_.py", line 254, in spectral_embedding tol=eigen_tol) File "/usr/lib/python2.7/dist-packages/scipy/sparse/linalg/eigen/arpack/arpack.py", line 1507, in eigsh raise ValueError("k must be between 1 and the order of the " ValueError: k must be between 1 and the order of the square input matrix. </code></pre> <p>I have no idea and I need to know what is the problem and maybe it's solution.</p>
-2
2016-07-23T05:45:55Z
38,546,342
<p>You have 4 data points.</p> <p>You request 4 clusters.</p> <p>What do you expect to happen?</p> <p>There is only the trivial solution (every point is different) so spectral clustering refuses to run. For sensible solutions, the number of clusters must be at least 2, and at most n-1 if you have n points, obviously.</p>
1
2016-07-23T20:55:47Z
[ "python", "numpy", "matrix", "scikit-learn", "cluster-analysis" ]
When I visit django Project WebPage, the log remind me:not found favicon
38,538,615
<p>Why django project receive favicon request?<br></p> <p>like this<br> <strong>Not Found: /favicon.ico<br> [23/Jul/2016 11:37:11] "GET /favicon.ico HTTP/1.1" 404 1941</strong></p> <p>Where did the request come from?</p> <p>I find request from my browser.<br> Can I control it? How to close it?<br> Thanks everyone that care this question...(Bab English, sorry)</p>
-3
2016-07-23T05:47:12Z
38,552,949
<p>Please collect all your static data using "python manage.py collectstatic" </p> <p>If you have already done that, make sure favicon.ico is part of static directory</p>
0
2016-07-24T14:12:49Z
[ "python", "django", "favicon" ]
TensorFlow Returning nan When Implementing Logistic Regression
38,538,635
<p>I've been trying to implement Logistic Regression in TensorFlow following the MNIST example but with data from a CSV. Each row is one sample and has 12 dimensions. My code is the following:</p> <pre><code>batch_size = 5 learning_rate = .001 x = tf.placeholder(tf.float32,[None,12]) y = tf.placeholder(tf.float32,[None,2]) W = tf.Variable(tf.zeros([12,2])) b = tf.Variable(tf.zeros([2])) mult = tf.matmul(x,W) pred = tf.nn.softmax(mult+b) cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1)) optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) sess = tf.Session() sess.run(tf.initialize_all_variables()) avg_cost = 0 total_batch = int(len(Xtrain)/batch_size) for i in range(total_batch): batch_xs = Xtrain[i*batch_size:batch_size*i+batch_size] batch_ys = ytrain[i*batch_size:batch_size*i+batch_size] _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,y: batch_ys}) print(c) </code></pre> <p>Xtrain is a 252x10 numpy array, and ytrain is a 252x2 one hot numpy array. </p> <p><strong>The Problem:</strong> the cost c gets calculated for the first iteration (value is 0.6931...), but for every iteration after, it returns 'nan.'</p> <p><strong>Things I've Tried:</strong> I made sure every component aspect of the model was working. The issue happens entirely after the first iteration. I've played around with the learning rate, but that doesn't do anything. I've tried initializing the weights as truncated_normal (which I shouldn't need to do for logistic regression anyway), but that doesn't help either. </p> <p>So, any thoughts? I've spent around 3 hours trying to fix it and have run out of ideas. It seems like something just isn't working when TensorFlow goes to optimize the cost function.</p>
2
2016-07-23T05:49:57Z
38,538,835
<p>The issue you are having is because log(pred) is not defined for pred = 0. The "hacky" way around this is to use <code>tf.maximum(pred, 1e-15)</code> or <code>tf.clip_by_value(pred, 1e-15, 1.0)</code>.</p> <p>An even better solution, however, is using <code>tf.nn.softmax_cross_entropy_with_logits(pred)</code> instead of applying softmax and cross-entropy separately, which deals with edge cases like this (hence all your problems) automatically!</p> <p>For further reading, I'd recommend this great answer: <a href="http://stackoverflow.com/a/34243720/5829427">http://stackoverflow.com/a/34243720/5829427</a></p>
2
2016-07-23T06:20:49Z
[ "python", "numpy", "tensorflow", "logistic-regression" ]
Cannot see my web application using Docker container
38,538,651
<p>I am trying to test my web application using a docker container, but I am not able to see it when I try to access it through my browser.</p> <p>The docker compose file looks like </p> <pre><code>version: '2' services: db: image: postgres volumes: - ~/pgdata:/var/lib/postgresql/data/pgdata environment: POSTGRES_PASSWORD: "dbpassword" PGDATA: "/var/lib/postgresql/data/pgdata" ports: - "5432:5432" web: build: context: . dockerfile: Dockerfile-web ports: - "5000:5000" volumes: - ./web:/web depends_on: - db backend: build: context: . dockerfile: Dockerfile-backend volumes: - ./backend:/backend depends_on: - db </code></pre> <p>The dockerfile-web looks like</p> <pre><code>FROM python ADD web/requirements.txt /web/requirements.txt ADD web/bower.json /web/bower.json WORKDIR /web RUN \ wget https://nodejs.org/dist/v4.4.7/node-v4.4.7-linux-x64.tar.xz &amp;&amp; \ tar xJf node-*.tar.xz -C /usr/local --strip-components=1 &amp;&amp; \ rm -f node-*.tar.xz RUN npm install -g bower RUN bower install --allow-root RUN pip install -r requirements.txt RUN export MYFLASKAPP_SECRET='makethewebsite' CMD python manage.py server </code></pre> <p>The ip for my docker machine is </p> <p>docker-machine ip 192.168.99.100</p> <p>But when I try <a href="http://192.168.99.100:5000/" rel="nofollow">http://192.168.99.100:5000/</a> in my browser it just says that the site cannot be reached. It seems like it is refusing the connection.</p> <p>When I ping my database in the browser I can see that my database response in a log <a href="http://192.168.99.100:5432/" rel="nofollow">http://192.168.99.100:5432/</a></p> <p>So I tried wget inside the container and got</p> <pre><code>$ docker exec 3bb5246a0623 wget http://localhost:5000/ --2016-07-23 05:25:16-- http://localhost:5000/ Resolving localhost (localhost)... ::1, 127.0.0.1 Connecting to localhost (localhost)|::1|:5000... failed: Connection refused. Connecting to localhost (localhost)|127.0.0.1|:5000... connected. HTTP request sent, awaiting response... 200 OK Length: 34771 (34K) [text/html] Saving to: ‘index.html.1’ 0K .......... .......... .......... ... 100% 5.37M=0.006s 2016-07-23 05:25:16 (5.37 MB/s) - ‘index.html.1’ saved [34771/34771] </code></pre> <p>Anyone know how I can get my web application to show up through my browser?</p>
-1
2016-07-23T05:51:56Z
38,538,778
<p>I had to enable external visibility for my flask application. You can see it here <a href="http://stackoverflow.com/questions/30554702/cant-connect-to-flask-web-service-connection-refused">Can&#39;t connect to Flask web service, connection refused</a></p>
0
2016-07-23T06:12:12Z
[ "python", "web-applications", "docker", "flask", "docker-compose" ]
django float or decimal are rounded unintentionally when saving
38,538,773
<p>I want to save latitude and longitude in Place model. I tried two fields, floatfield and decimalfield.</p> <h1>1. FloatField model</h1> <pre><code>class Place1(models.Model): latitude = models.FloatField() longitude = models.FloatField() </code></pre> <h1>2. DecimalField model</h1> <pre><code>class Place2(models.Model): latitude = models.DecimalField(max_digits=18, decimal_places=16) longitude = models.DecimalField(max_digits=19, decimal_places=16) </code></pre> <p>Both Fields work well on below values.</p> <blockquote> <p>10.1<br>10.12<br>10.123<br>10.1234<br>...<br>10.1234567890123</p> </blockquote> <p>However, after 16th number(not 'sixteen decimal places'), it's unintentionally rounded <b>when saving.</b></p> <pre><code>place1 = Place1.objects.create( latitude=10.123456789012345, longitude=100.123456789012345 ) &gt;&gt;place1.latitude 10.123456789012345 # works well &gt;&gt;place1.longitude 100.123456789012345 # works well # Unintentionally rounded when I get object from db. &gt;&gt;Place.objects.last().latitude 10.12345678901235 # unintentionally rounded &gt;&gt;Place.objects.last().longitude 100.1234567890123 # unintentionally rounded place2 = Place2.objects.create( latitude=Decimal('10.123456789012345'), longitude=Decimal('100.123456789012345') ) &gt;&gt;place2.latitude Decimal('10.1234567890123450') # works well &gt;&gt;place2.longitude Decimal('100.1234567890123450') # works well # Unintentionally rounded when I get object from db. &gt;&gt;Place.objects.last().latitude Decimal('10.1234567890123500') # unintentionally rounded &gt;&gt;Place.objects.last().longitude Decimal('100.1234567890123000') # unintentionally rounded </code></pre> <p>I can't find any explanation about this 'unintentional round' in django document. Please help. Thanks.</p>
3
2016-07-23T06:11:17Z
38,540,062
<p>You can not find 'unintentional rounding' in django docs because django is not the culprit here.</p> <p>Its the MYSQL that does the rounding when your column data type is Float. </p> <blockquote> <p>For maximum portability, code requiring storage of approximate numeric data values should use <strong>FLOAT</strong> or <strong>DOUBLE PRECISION</strong> with no specification of precision or number of digits. </p> <p>Because floating-point values are approximate and not stored as exact values, attempts to treat them as exact in comparisons may lead to problems. They are also subject to platform or implementation dependencies.</p> </blockquote> <p>But for exactness of values you should use <strong>DecimalField</strong>.</p> <p>You said you have used <strong>DecimalField</strong> and the numbers are still rounding-off. That might be happening because your <em>table column</em> is still type <strong>Float</strong> and not <strong>Decimal</strong>. </p> <p>Change you table column type to Decimal and you can see the change.</p> <p>Example SQL syntax <code>ALTER TABLE your_table MODIFY latitude decimal(m,n);</code>, OR </p> <p>If you are using MYSQL Workbench or any UI interface, change it directly from the columns info tab (they have one)</p> <blockquote> <p>The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision</p> <p>In a DECIMAL column declaration, the precision and scale can be (and usually is) specified; for example: latitude DECIMAL(m,n)</p> <p>The precision <strong>(m)</strong> represents the number of significant digits that are stored for values, and the scale <strong>(n)</strong> represents the number of digits that can be stored following the decimal point . </p> </blockquote> <p><em>Help yourself here for the the precision scale you want for your fields latitude and longitude</em></p> <p>See <a href="https://dev.mysql.com/doc/refman/5.5/en/fixed-point-types.html" rel="nofollow">here</a> for more info on Decimal data type and <a href="https://dev.mysql.com/doc/refman/5.5/en/problems-with-float.html" rel="nofollow">here</a> for info on the issue you are encountering.</p>
1
2016-07-23T09:06:22Z
[ "python", "django", "floating-point", "decimal", "latitude-longitude" ]
possible unique combinations between between two arrays(of different size) in python?
38,538,786
<pre><code>arr1=['One','Two','Five'],arr2=['Three','Four'] </code></pre> <p>like <code>itertools.combinations(arr1,2)</code> gives us <br><code>('OneTwo','TwoFive','OneFive')</code><br> I was wondering is there any way applying this to two different arrays.?I mean for arr1 and arr2.</p> <p><code>Output should be OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour</code></p>
2
2016-07-23T06:13:48Z
38,538,848
<p>If all you wanted is <code>OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour</code> then a double <code>for</code> loop will do the trick for you:</p> <pre><code>&gt;&gt;&gt; for x in arr1: for y in arr2: print(x+y) OneThree OneFour TwoThree TwoFour FiveThree FiveFour </code></pre> <p>Or if you want the result in a list:</p> <pre><code>&gt;&gt;&gt; [x+y for x in arr1 for y in arr2] ['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour'] </code></pre>
1
2016-07-23T06:22:45Z
[ "python", "arrays", "python-3.x", "python-3.4", "itertools" ]
possible unique combinations between between two arrays(of different size) in python?
38,538,786
<pre><code>arr1=['One','Two','Five'],arr2=['Three','Four'] </code></pre> <p>like <code>itertools.combinations(arr1,2)</code> gives us <br><code>('OneTwo','TwoFive','OneFive')</code><br> I was wondering is there any way applying this to two different arrays.?I mean for arr1 and arr2.</p> <p><code>Output should be OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour</code></p>
2
2016-07-23T06:13:48Z
38,538,867
<p>You are looking for <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>.product()</code></a>:</p> <p>From the doc, it does this:</p> <pre><code>product('ABCD', 'xy') --&gt; Ax Ay Bx By Cx Cy Dx Dy product(range(2), repeat=3) --&gt; 000 001 010 011 100 101 110 111 </code></pre> <p>Sample code:</p> <pre><code>&gt;&gt;&gt; x = itertools.product(arr1, arr2) &gt;&gt;&gt; for i in x: print i ('One', 'Three') ('One', 'Four') ('Two', 'Three') ('Two', 'Four') ('Five', 'Three') ('Five', 'Four') </code></pre> <p>To combine them:</p> <pre><code># This is the full code import itertools arr1 = ['One','Two','Five'] arr2 = ['Three','Four'] combined = ["".join(x) for x in itertools.product(arr1, arr2)] </code></pre>
2
2016-07-23T06:26:27Z
[ "python", "arrays", "python-3.x", "python-3.4", "itertools" ]
possible unique combinations between between two arrays(of different size) in python?
38,538,786
<pre><code>arr1=['One','Two','Five'],arr2=['Three','Four'] </code></pre> <p>like <code>itertools.combinations(arr1,2)</code> gives us <br><code>('OneTwo','TwoFive','OneFive')</code><br> I was wondering is there any way applying this to two different arrays.?I mean for arr1 and arr2.</p> <p><code>Output should be OneThree,OneFour,TwoThree,TwoFour,FiveThree,FiveFour</code></p>
2
2016-07-23T06:13:48Z
38,538,868
<pre><code>["".join(v) for v in itertools.product(arr1, arr2)] #results in ['OneThree', 'OneFour', 'TwoThree', 'TwoFour', 'FiveThree', 'FiveFour'] </code></pre>
1
2016-07-23T06:26:49Z
[ "python", "arrays", "python-3.x", "python-3.4", "itertools" ]
How to swap blue and green channel in an image using OpenCV
38,538,952
<p>I am facing a little bit of problem in swapping the channels (specifically red and blue) of an image. I am using Opencv 3.0.0 and Python 2.7.12. Following is my code for swapping the channels</p> <pre><code>import cv2 img = cv2.imread("input/car1.jpg") #The obvious approach Cimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #Manual Approach red = img[:,:,2] blue = img[:,:,0] img[:,:,0] = red img[:,:,2] = blue cv2.imshow("frame",Cimg) cv2.imshow("frame2", img) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <p>I am unable to figure out why the same image undergoing through the same(probably) operation is giving two different outputs. Can someone throw some light on what's going wrong?</p> <p>Thanks!</p> <p>Original Image <a href="http://i.stack.imgur.com/q4Myt.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/q4Myt.jpg" alt="The original Image"></a> </p> <p>Manual Operation <a href="http://i.stack.imgur.com/dtjaK.png" rel="nofollow"><img src="http://i.stack.imgur.com/dtjaK.png" alt="The manual operation"></a></p> <p>COLOR_BGR2RGB <a href="http://i.stack.imgur.com/1jMsb.png" rel="nofollow"><img src="http://i.stack.imgur.com/1jMsb.png" alt="The cv2.COLOR_BGR2RGB operation"></a></p>
0
2016-07-23T06:37:54Z
38,539,027
<p><code>red</code> and <code>blue</code> are just views of your image. When you do <code>img[:,:,0] = red</code> this changes <code>img</code> but also <code>blue</code> which is just a view (basically just a reference to the sub-array <code>img[:,:,0]</code>) not a copy, so you loose the original blue channel values. Basically what you assume is a temp copy just is not. Add <code>.copy()</code> and it will work. </p> <pre><code>img = np.arange(27).reshape((3,3,3)) red = img[:,:,2].copy() blue = img[:,:,0].copy() img[:,:,0] = red img[:,:,2] = blue print("with copy:\n", img) img = np.arange(27).reshape((3,3,3)) red = img[:,:,2] blue = img[:,:,0] img[:,:,0] = red img[:,:,2] = blue print("without copy:\n",img) </code></pre> <p>results:</p> <pre><code>with copy: [[[ 2 1 0] [ 5 4 3] [ 8 7 6]] [[11 10 9] [14 13 12] [17 16 15]] [[20 19 18] [23 22 21] [26 25 24]]] without copy: [[[ 2 1 2] [ 5 4 5] [ 8 7 8]] [[11 10 11] [14 13 14] [17 16 17]] [[20 19 20] [23 22 23] [26 25 26]]] </code></pre> <p>Note: you actually only need 1 temp copy of 1 channel. Or you could also simply do <code>img[:,:,::-1]</code> this will create a view again but with swapped channels, <code>img</code> will stay unchanged, unless you reassign it:</p> <pre><code>img = np.arange(27).reshape((3,3,3)) print(img[:,:,::-1]) print(img) img = img[:,:,::-1] print(img) </code></pre> <p>results:</p> <pre><code>[[[ 2 1 0] [ 5 4 3] [ 8 7 6]] [[11 10 9] [14 13 12] [17 16 15]] [[20 19 18] [23 22 21] [26 25 24]]] [[[ 0 1 2] [ 3 4 5] [ 6 7 8]] [[ 9 10 11] [12 13 14] [15 16 17]] [[18 19 20] [21 22 23] [24 25 26]]] [[[ 2 1 0] [ 5 4 3] [ 8 7 6]] [[11 10 9] [14 13 12] [17 16 15]] [[20 19 18] [23 22 21] [26 25 24]]] </code></pre>
1
2016-07-23T06:50:29Z
[ "python", "opencv" ]
Modifying PDF (compatible with Acrobat 6.0 and higher) by objects shuffling
38,538,963
<p>I'm trying to get PDF file, with changed order of objects (index is not changed, only location of objects inside file). After then, I'm making new xref stream with new offsets of objects</p> <p>I implemented the program in Python, but produced file is always damaged.</p> <p>Questions:</p> <ol> <li>How to make file unlinearized? Currently, I'm removing linearisation object from file and its xref-entry</li> <li>Token "endstream" should be clearly separated from its content by \r\n, or it's not necessary?</li> <li>....</li> </ol> <p>May be I missed some important facts and nuances? I will appreciate any help</p>
-1
2016-07-23T06:40:08Z
38,567,624
<p>As you neither show your code nor describe the nature of the damage to the result file (let alone share sample original and reordered files), it is difficult to help you.</p> <blockquote> <ol> <li>How to make file unlinearized? Currently, I'm removing linearisation object from file and its xref-entry</li> </ol> </blockquote> <p>Removing the Linearization Parameter Dictionary is a good idea. Concerning the cross references be aware that the entries in both tables are relevant.</p> <blockquote> <ol start="2"> <li>Token "endstream" should be clearly separated from its content by \r\n, or it's not necessary?</li> </ol> </blockquote> <p>To quote the PDF specification:</p> <blockquote> <p>There should be an end-of-line marker after the data and before endstream</p> <p><em>(section 7.3.8 Stream Objects - ISO 32000-1)</em></p> </blockquote> <p>"Should" indicates a strong recommendation but not a requirement. Thus, your code has to expect to be confronted with PDFs which don't have an end-of-line marker there.</p> <p>By the way,</p> <blockquote> <p>The CARRIAGE RETURN (0Dh) and LINE FEED (0Ah) characters, also called newline characters, shall be treated as end-of-line (EOL) markers. The combination of a CARRIAGE RETURN followed immediately by a LINE FEED shall be treated as one EOL marker.</p> <p><em>(section 7.2.2 Character Set - ISO 32000-1)</em></p> </blockquote> <p>Thus, even if there is an end-of-line marker, it is not necessarily <code>\r\n</code>, it might also be a single <code>\r</code> or <code>\n</code>.</p>
0
2016-07-25T12:20:52Z
[ "python", "pdf" ]
dask distributed memory error
38,539,044
<p>I got the following error on the scheduler while running Dask on a distributed job:</p> <pre><code>distributed.core - ERROR - Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/distributed/core.py", line 269, in write frames = protocol.dumps(msg) File "/usr/local/lib/python3.4/dist-packages/distributed/protocol.py", line 81, in dumps frames = dumps_msgpack(small) File "/usr/local/lib/python3.4/dist-packages/distributed/protocol.py", line 153, in dumps_msgpack payload = msgpack.dumps(msg, use_bin_type=True) File "/usr/local/lib/python3.4/dist-packages/msgpack/__init__.py", line 47, in packb return Packer(**kwargs).pack(o) File "msgpack/_packer.pyx", line 231, in msgpack._packer.Packer.pack (msgpack/_packer.cpp:231) File "msgpack/_packer.pyx", line 239, in msgpack._packer.Packer.pack (msgpack/_packer.cpp:239) MemoryError </code></pre> <p>Is this running out of memory on the scheduler or on one of the workers? Or both??</p>
1
2016-07-23T06:52:23Z
38,542,459
<p>The most common cause of this error is trying to collect too much data, such as occurs in the following example using dask.dataframe:</p> <pre><code>df = dd.read_csv('s3://bucket/lots-of-data-*.csv') df.compute() </code></pre> <p>This loads all of the data into RAM across the cluster (which is fine), and then tries to bring the entire result back to the local machine by way of the scheduler (which probably can't handle your 100's of GB of data all in one place.) Worker-to-client communications pass through the Scheduler, so it is the first single machine to receive all of the data and the first machine likely to fail.</p> <p>If this is the case then you instead probably want to use the <code>Executor.persist</code> method, to trigger computation but leave it on the cluster.</p> <pre><code>df = dd.read_csv('s3://bucket/lots-of-data-*.csv') df = e.persist(df) </code></pre> <p>Generally we only use <code>df.compute()</code> for small results that we want to view in our local session.</p>
0
2016-07-23T13:43:39Z
[ "python", "dask" ]
sympy Matrices within a sympy Matrix remains unevaluated on substitution
38,539,095
<p>While my issue seems linked to the sympy github issue <a href="https://github.com/sympy/sympy/issues/6557" rel="nofollow">here</a>, it either doesn't seem directly related, or remains an open, unsolved issue (from 2012).</p> <p>My issue is that I have a 'matrix' (really, it's just a vector but is my only option due to how sympy deals with things) within my matrix represented by a symbol, that when substituted, shows up a matrix rather than evaluating it.</p> <p>Below is a sample block of code that will demonstrate this:</p> <pre><code>import numpy as np import sympy x = np.random.rand(15, 3) l_syms = sympy.MatrixSymbol('l', 1, 3) m = sympy.Matrix(x/l_syms) m.subs({l_syms:sympy.Matrix([[1,1,1]])}) </code></pre> <p>Each value in the <code>matrix</code> [[1,1,1]] should be divided into each element of the <code>m</code> matrix, but the matrix sits as-is, with the index notation remaining.</p> <pre><code>Matrix([ [ 0.98979011265311*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.833576329284127*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.575808048824554*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.523263044342704*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.320197709246721*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.592365354846089*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.943288501064919*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.996020450969247*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.964522394691641*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.763752929521655*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.690054409108757*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.417629855595703*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.213578356927868*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.362782611339912*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.892921288169683*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.068921237699985*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.244310349677818*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.977494896836049*Matrix([[1, 1, 1]])[0, 2]**(-1)], [0.0169721915631557*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.254316922886399*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.682785271511585*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.768287921847173*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.679243253034139*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.790710466097621*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.892115183428169*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.988514816033581*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.537769900907173*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.275725750770885*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.928279364723852*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.18023576064915*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.71421202332017*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.663585719630706*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.43460735199406*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.770814091341355*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.0650430822905173*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.0845773234523002*Matrix([[1, 1, 1]])[0, 2]**(-1)], [0.0398441324212175*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.0358479090409692*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.0801076763216808*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.89937521111821*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.21500916688666*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.661216039738327*Matrix([[1, 1, 1]])[0, 2]**(-1)], [ 0.866641224226343*Matrix([[1, 1, 1]])[0, 0]**(-1), 0.0506005171711028*Matrix([[1, 1, 1]])[0, 1]**(-1), 0.791277139679317*Matrix([[1, 1, 1]])[0, 2]**(-1)]]) </code></pre> <p>I don't seem to be able to find a way to <em>evaluate</em> all those Matrix objects and their indices - the only thing remotely related was the github issue linked above, but using <code>xreplace</code> is for my intentions even less optimal/correct, as it leaves the symbol in place rather than substituting the matrix in.</p> <p>Any help greatly appreciated.</p>
1
2016-07-23T06:58:33Z
38,579,076
<p><code>doit</code> will evaluate the expression</p> <pre><code>In [9]: print(m.subs({l_syms:sympy.Matrix([[1,1,1]])}).doit()) Matrix([[0.391482321650262, 0.261165517803277, 0.142349217414644], [0.273871679444907, 0.753721446526393, 0.915204734923647], [0.689284430582533, 0.509755263016457, 0.828178833602631], [0.258602302969241, 0.561852165820955, 0.926528186168350], [0.932268817842373, 0.275670112515102, 0.313790471533159], [0.815965494794080, 0.00638263457666399, 0.728986133320254], [0.771288596688822, 0.159602759327409, 0.846541783656596], [0.703501924167250, 0.168463436323684, 0.496465192945264], [0.265617558320534, 0.727288058464723, 0.301561940789455], [0.134747729067062, 0.315683443879649, 0.741893699540517], [0.763480667163729, 0.459612818589501, 0.295897102504639], [0.519647253027057, 0.884505816757734, 0.823849322619653], [0.0499379745242409, 0.333299403033741, 0.960531610086280], [0.658552664971765, 0.788381947436270, 0.609862319604282], [0.748840147759344, 0.434013189476355, 0.747584770109250]]) </code></pre>
1
2016-07-25T23:51:50Z
[ "python", "matrix", "lazy-evaluation", "sympy", "substitution" ]
Groupby Aggregate method is returning NaN always
38,539,204
<p>Hi I am running into this issue where my datasource events looks like this:</p> <pre><code> event_id device_id timestamp longitude latitude 0 1 29182687948017175 2016-05-01 00:55:25 121.38 31.24 1 2 -6401643145415154744 2016-05-01 00:54:12 103.65 30.97 2 3 -4833982096941402721 2016-05-01 00:08:05 106.60 29.7 </code></pre> <p>I am trying to group the events by the device_id and then get the sum/mean/std of the variable over every event with that device_id:</p> <pre><code>events['latitude_mean'] = events.groupby(['device_id'])['latitude'].aggregate(np.sum) </code></pre> <p>But my Output is always:</p> <pre><code>event_id device_id timestamp longitude latitude 0 1 29182687948017175 2016-05-01 00:55:25 121.38 31.24 1 2 -6401643145415154744 2016-05-01 00:54:12 103.65 30.97 2 3 -4833982096941402721 2016-05-01 00:08:05 106.60 29.70 3 4 -6815121365017318426 2016-05-01 00:06:40 104.27 23.28 4 5 -5373797595892518570 2016-05-01 00:07:18 115.88 28.66 latitude_mean 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN </code></pre> <p>What am I doing wrong to keep getting the return value to be NaN for each row?</p>
3
2016-07-23T07:14:12Z
38,539,407
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow">pandas.core.groupby.GroupBy.transform(aggfunc)</a> method, which applies <code>aggfunc</code> to all rows in each group:</p> <pre><code>In [32]: events['latitude_mean'] = events.groupby(['device_id'])['latitude'].transform('sum') In [33]: events Out[33]: event_id device_id timestamp longitude latitude latitude_mean 0 1 29182687948017175 2016-05-01 00:55:25 121.38 31.24 62.55 1 2 29182687948017175 2016-05-30 12:12:12 777.77 31.31 62.55 2 3 -6401643145415154744 2016-05-01 00:54:12 103.65 30.97 64.30 3 4 -6401643145415154744 2016-01-01 11:11:11 111.11 33.33 64.30 </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation" rel="nofollow">Here you may find some usage examples</a></p> <p><strong>Explanation:</strong> when you group your DF - as a result you usually have a series containing less rows and with different index, so pandas doesn't know how to align it when assigning it to a new column and as a result you have NaN's:</p> <pre><code>In [31]: events.groupby(['device_id'])['latitude'].agg(np.sum) Out[31]: device_id -6401643145415154744 64.30 29182687948017175 62.55 Name: latitude, dtype: float64 </code></pre> <p>so when you try to assign it to a new column, pandas does something like this:</p> <pre><code>In [36]: events['nans'] = pd.Series([1,2], index=['a','b']) In [38]: events[['event_id','nans']] Out[38]: event_id nans 0 1 NaN 1 2 NaN 2 3 NaN 3 4 NaN </code></pre> <p>Data:</p> <pre><code>In [30]: events Out[30]: event_id device_id timestamp longitude latitude 0 1 29182687948017175 2016-05-01 00:55:25 121.38 31.24 1 2 29182687948017175 2016-05-30 12:12:12 777.77 31.31 2 3 -6401643145415154744 2016-05-01 00:54:12 103.65 30.97 3 4 -6401643145415154744 2016-01-01 11:11:11 111.11 33.33 </code></pre>
2
2016-07-23T07:40:16Z
[ "python", "pandas" ]
django - Cannot login with the user credentials
38,539,318
<p>I have a custom user model and its user manager.</p> <pre><code>class CustomUserManager(BaseUserManager): def _create_user(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, is_active, is_admin, is_superuser): """ Creates and saves a user with given email and password """ if not email: raise ValueError('Email must be set') email = self.normalize_email(email) now = timezone.now() user = self.model( email=email, username=username, first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, gender=gender, mobile_number=mobile_number, date_joined=now, is_active=is_active, is_admin=is_admin, is_superuser=is_superuser, ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, **extra_fields): user = self._create_user(email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, True, False, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self, email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, **extra_fields): user = self._create_user(email, username, password, first_name, last_name, date_of_birth, gender, mobile_number, True, True, True, **extra_fields) user.save(using=self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) username = models.CharField(_('user name'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30) date_of_birth = models.DateField() gender = models.CharField(choices=GENDERTYPE, max_length=1) mobile_number = models.IntegerField(unique=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number'] ... ... </code></pre> <p>And to process the model, I have a custom user creation forms.py</p> <pre><code>class UserCreationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) class Meta: model = CustomUser fields = ('email', 'username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number') def save(self, commit=True): # Save the provided password in hashed format user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) print self.cleaned_data["password"] if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = CustomUser fields = ( 'email', 'username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number', 'is_active', 'is_admin' ) def clean_password(self): return self.initial["password"] </code></pre> <p>I can save and create a new user. Also I can see the hashed password in the admin. However when I try to login with the <code>email</code> and <code>password</code> of the new user, I am not being authenticated. I also tried to login with the <code>username</code> and the <code>password</code>, but that didn't work either. To check if I am actually getting any password, I tried printing the <code>self.cleaned_data["password"]</code> in the <strong>UserCreationForm</strong>, and in the console I can see the password I gave. However, if I try to login in the admin, I not able to login. But again, with the superuser's credentials, I can login. What am I doing wrong here? Please help me.</p> <p>Thank you.</p>
0
2016-07-23T07:28:40Z
38,539,669
<p>If you are trying to login to the admin site, make sure your new user has admin privileges </p> <p><code>is_admin=True</code></p>
1
2016-07-23T08:15:47Z
[ "python", "django", "django-models", "django-forms", "django-admin" ]
Sort list of dicts by sub-key value
38,539,381
<p>I have following list of dictionaries:</p> <pre><code>test_list = [ {'sr_no': 1, 'recipe_type': 'Main Dish', 'name': 'Salmon &amp; Brown Rice'}, {'sr_no': 2, 'recipe_type': 'Side Dish', 'name': 'Cupcakes'}, {'sr_no': 3, 'recipe_type': 'Main Dish', 'name': 'Whole chicken'}, {'sr_no': 4, 'recipe_type': 'Desserts', 'name': 'test'} ] </code></pre> <p>I need to sort it on base of <code>name</code> index value alphabetically. As below:</p> <pre><code>test_list = [ {'sr_no': 2, 'recipe_type': 'Side Dish', 'name': 'Cupcakes'}, {'sr_no': 1, 'recipe_type': 'Main Dish', 'name': 'Salmon &amp; Brown Rice'}, {'sr_no': 4, 'recipe_type': 'Desserts', 'name': 'test'} {'sr_no': 3, 'recipe_type': 'Main Dish', 'name': 'Whole chicken'}, ] </code></pre> <p>I have searched this on SO and google but find no definite answer.</p>
0
2016-07-23T07:37:31Z
38,539,415
<p>You can pass <code>key</code> function that returns <code>name</code> from each dict to <a href="https://docs.python.org/3.5/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a>:</p> <pre><code>&gt;&gt;&gt; import pprint &gt;&gt;&gt; test_list = [ ... {'sr_no': 1, 'recipe_type': 'Main Dish', 'name': 'Salmon &amp; Brown Rice'}, ... {'sr_no': 2, 'recipe_type': 'Side Dish', 'name': 'Cupcakes'}, ... {'sr_no': 3, 'recipe_type': 'Main Dish', 'name': 'Whole chicken'}, ... {'sr_no': 4, 'recipe_type': 'Desserts', 'name': 'test'} ... ] &gt;&gt;&gt; pprint.pprint(sorted(test_list, key=lambda x: x['name'].lower())) [{'name': 'Cupcakes', 'recipe_type': 'Side Dish', 'sr_no': 2}, {'name': 'Salmon &amp; Brown Rice', 'recipe_type': 'Main Dish', 'sr_no': 1}, {'name': 'test', 'recipe_type': 'Desserts', 'sr_no': 4}, {'name': 'Whole chicken', 'recipe_type': 'Main Dish', 'sr_no': 3}] </code></pre>
2
2016-07-23T07:41:15Z
[ "python", "python-2.7", "dictionary" ]
How to save data in a for loop by Python
38,539,393
<p>I am new in Python programming. I want to save the field output request </p> <p><code>[mdb.models['Model-1'].fieldOutputRequests['F-Output-1'].setValues(variables=('S', 'U', 'SF'))]</code></p> <p>as a text file for each loop j by changing boundary displacement. Can anybody help me regrading this issue? I have attached the code.</p> <p>Thanks! D. Bhuiyan</p> <pre><code>from part import * from material import * from section import * from assembly import * from step import * from interaction import * from load import * from mesh import * from optimization import * from job import * from sketch import * from visualization import * from connectorBehavior import * ### PART ### mdb.models['Model-1'].ConstrainedSketch(name='__profile__', sheetSize=2.0) mdb.models['Model-1'].sketches['__profile__'].Spot(point=(0.0, 0.0)) mdb.models['Model-1'].sketches['__profile__'].Spot(point=(1.0, 0.0)) mdb.models['Model-1'].sketches['__profile__'].Line(point1=(0.0, 0.0), point2=(1.0, 0.0)) mdb.models['Model-1'].sketches['__profile__'].HorizontalConstraint(addUndoState=False, entity=mdb.models['Model-1'].sketches['__profile__'].geometry[2]) mdb.models['Model-1'].Part(dimensionality=TWO_D_PLANAR, name='Part-1', type=DEFORMABLE_BODY) mdb.models['Model-1'].parts['Part-1'].BaseWire(sketch=mdb.models['Model-1'].sketches['__profile__']) del mdb.models['Model-1'].sketches['__profile__'] ### MATERIAL &amp; SECTION ### mdb.models['Model-1'].Material(name='Material-1') mdb.models['Model-1'].materials['Material-1'].Density(table=((7800.0, ), )) mdb.models['Model-1'].materials['Material-1'].Elastic(table=((206000000000.0, 0.3), )) ### SET &amp; SURFACE ### mdb.models['Model-1'].CircularProfile(name='Circ_profile', r=0.015) mdb.models['Model-1'].BeamSection(consistentMassMatrix=False, integration= DURING_ANALYSIS, material='Material-1', name='Beam_section', poissonRatio=0.0, profile='Circ_profile', temperatureVar=LINEAR) mdb.models['Model-1'].parts['Part-1'].Set(edges= mdb.models['Model-1'].parts['Part-1'].edges.getSequenceFromMask(('[#1 ]', ), ), name='Beam') mdb.models['Model-1'].parts['Part-1'].SectionAssignment(offset=0.0, offsetField='', offsetType=MIDDLE_SURFACE, region= mdb.models['Model-1'].parts['Part-1'].sets['Beam'], sectionName='Beam_section', thicknessAssignment=FROM_SECTION) mdb.models['Model-1'].rootAssembly.DatumCsysByDefault(CARTESIAN) mdb.models['Model-1'].rootAssembly.Instance(dependent=ON, name='Part-1-1', part=mdb.models['Model-1'].parts['Part-1']) ### STEP, BC &amp; LOAD ### mdb.models['Model-1'].StaticStep(description= 'Apply Displacement in the DOFs at node', initialInc=1.0, name='Step-1', previous='Initial') mdb.models['Model-1'].fieldOutputRequests['F-Output-1'].setValues(variables=('S', 'U', 'SF')) del mdb.models['Model-1'].historyOutputRequests['H-Output-1'] mdb.models['Model-1'].parts['Part-1'].seedEdgeBySize(constraint=FINER, deviationFactor=0.1, edges= mdb.models['Model-1'].parts['Part-1'].edges.getSequenceFromMask(('[#1 ]', ), ), size=2.0) mdb.models['Model-1'].parts['Part-1'].setElementType(elemTypes=(ElemType( elemCode=B23, elemLibrary=STANDARD), ), regions=(mdb.models['Model-1'].parts['Part-1'].edges.getSequenceFromMask(('[#1 ]', ), ), )) mdb.models['Model-1'].parts['Part-1'].setElementType(elemTypes=(ElemType( elemCode=B23, elemLibrary=STANDARD), ), regions=(mdb.models['Model-1'].parts['Part-1'].edges.getSequenceFromMask(('[#1 ]', ), ), )) mdb.models['Model-1'].parts['Part-1'].generateMesh() mdb.models['Model-1'].rootAssembly.regenerate() del mdb.models['Model-1'].rootAssembly.features['Part-1-1'] mdb.models['Model-1'].rootAssembly.Instance(dependent=ON, name='Part-1-1', part=mdb.models['Model-1'].parts['Part-1']) mdb.models['Model-1'].parts['Part-1'].deleteMesh(regions=mdb.models['Model-1'].parts['Part-1'].edges.getSequenceFromMask(('[#1 ]', ), )) mdb.models['Model-1'].parts['Part-1'].seedEdgeByNumber(constraint=FINER, edges= mdb.models['Model-1'].parts['Part-1'].edges.getSequenceFromMask(('[#1 ]', ), ), number=2) mdb.models['Model-1'].parts['Part-1'].setElementType(elemTypes=(ElemType( elemCode=B23, elemLibrary=STANDARD), ), regions=(mdb.models['Model-1'].parts['Part-1'].edges.getSequenceFromMask(('[#1 ]', ), ), )) mdb.models['Model-1'].parts['Part-1'].generateMesh() mdb.models['Model-1'].rootAssembly.regenerate() del mdb.models['Model-1'].rootAssembly.features['Part-1-1'] mdb.models['Model-1'].rootAssembly.Instance(dependent=ON, name='Part-1-1', part=mdb.models['Model-1'].parts['Part-1']) mdb.models['Model-1'].parts['Part-1'].Set(name='Sensor@node2', nodes= mdb.models['Model-1'].parts['Part-1'].nodes.getSequenceFromMask(mask=('[#2 ]', ), )) mdb.models['Model-1'].rootAssembly.regenerate() mdb.models['Model-1'].parts['Part-1'].sets.changeKey(fromName='Sensor@node2', toName='node2') mdb.models['Model-1'].parts['Part-1'].Set(name='node1', nodes= mdb.models['Model-1'].parts['Part-1'].nodes.getSequenceFromMask(mask=('[#1 ]', ), )) mdb.models['Model-1'].parts['Part-1'].Set(name='node3', nodes= mdb.models['Model-1'].parts['Part-1'].nodes.getSequenceFromMask(mask=('[#4 ]', ), )) mdb.models['Model-1'].rootAssembly.regenerate() ## for loop A1=([0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0]) for j in range(len(A1)): f=A1[j] mdb.models['Model-1'].DisplacementBC(amplitude=UNSET, createStepName='Step-1', distributionType=UNIFORM, fieldName='', fixed=OFF, localCsys=None, name= 'BC-1', region=mdb.models['Model-1'].rootAssembly.instances['Part-1-1'].sets['node1'], u1=f[0], u2=f[1], ur3=f[2]) mdb.models['Model-1'].DisplacementBC(amplitude=UNSET, createStepName='Step-1', distributionType=UNIFORM, fieldName='', fixed=OFF, localCsys=None, name= 'BC-2', region= mdb.models['Model-1'].rootAssembly.instances['Part-1-1'].sets['node2'], u1=f[3], u2=f[4], ur3=f[5]) mdb.models['Model-1'].DisplacementBC(amplitude=UNSET, createStepName='Step-1', distributionType=UNIFORM, fieldName='', fixed=OFF, localCsys=None, name= 'BC-3', region=mdb.models['Model-1'].rootAssembly.instances['Part-1-1'].sets['node3'], u1=f[6], u2=f[7], ur3=f[8]) mdb.models['Model-1'].parts['Part-1'].assignBeamSectionOrientation(method= N1_COSINES, n1=(0.0, 0.0, -1.0), region=mdb.models['Model-1'].parts['Part-1'].sets['Beam']) ## Job ## mdb.Job(atTime=None, contactPrint=OFF, description='', echoPrint=OFF, explicitPrecision=SINGLE, getMemoryFromAnalysis=True, historyPrint=OFF, memory=90, memoryUnits=PERCENTAGE, model='Model-1', modelPrint=OFF, name='Job-1', nodalOutputPrecision=SINGLE, queue=None, resultsFormat=ODB, scratch='', type=ANALYSIS, userSubroutine='', waitHours=0, aitMinutes=0) </code></pre>
-4
2016-07-23T07:38:56Z
38,539,935
<p>The basics to creating a file is:</p> <pre><code>file = open("newfile.txt", "w") file.write("This is your first line") file.write("This is your second line") file.close() </code></pre> <p>In this case:</p> <pre><code>file = open("newfile.txt", "w") for j in range(len(A1)): to_write = mdb.models['Model-1'].fieldOutputRequests['F-Output-1'].setValues(variables=('S', 'U', 'SF')) del mdb.models['Model-1'].historyOutputRequests['H-Output-1'] file.write(to_write) </code></pre> <p>You should make clear what you mean by boundary displacement?</p>
0
2016-07-23T08:50:28Z
[ "python", "stack-overflow" ]
What is the difference between these os.popen calls?
38,539,445
<p>I have two scripts:</p> <p>The first works well:</p> <pre><code>import os os.popen(‘grep abc filename’) </code></pre> <p>The second does not work:</p> <pre><code>import os os.popen(‘grep abc’ + ’filename’) </code></pre> <p>But this does:</p> <pre><code>os.popen(‘grep abc filename’ + ‘&gt;’ + ‘filename2’) </code></pre> <p>So, I can’t understand the difference. What is wrong about the second version?</p>
0
2016-07-23T07:44:49Z
38,539,506
<p>You forgot the space after <code>abc</code> in the second version. It should be</p> <pre><code>import os os.popen(‘grep abc ’ + ’filename’) </code></pre> <p>i.e. <code>abc˽'</code> vs <code>abc'</code>.</p>
1
2016-07-23T07:53:26Z
[ "python" ]
Object (simple shapes) Detection in Image
38,539,503
<p>I've got the following image. </p> <p><a href="http://i.stack.imgur.com/Xxzjk.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Xxzjk.jpg" alt="enter image description here"></a> </p> <p><a href="http://imgur.com/a/UXYTq" rel="nofollow">Other Samples</a></p> <p>I want to detect the six square-shaped green portions and the one circular portion above them. I basically want a binary image with these portions marked 1 (white) and everything else 0 (black). </p> <p><strong>What have I done so far?</strong> </p> <p>I found a range of H, S, and V within which these colors fall which works fine for a single image, but I've got multiple such images, some under different illumination (brightness) conditions and the ranges do not work in those cases. What should I do to make the thresholding as invariant to brightness as possible? Is there a different approach I should take for thresholding? </p>
2
2016-07-23T07:53:07Z
38,539,627
<p>What you did was manually analyze the values you need for thresholding for a specific image, and then apply that. What you see is that analysis done on one image doesn't necessarily fit other images. </p> <p>The solution is to do the analysis automatically for each image. This can be achieved by creating a histogram for each of the channels, and if you're working in HSV, I'm guessing that the H channel would be pretty much useless in this case.</p> <p>Anyway, once you have the histograms, you should analyze the threshold using something like Lloyd-Max, which is basically a K-Means type clustering of intensities. This should give the centroids for the intensity of the white background, and the other colors. Then you choose the threshold based on the cluster standard deviation.</p> <p>For example, in the image you gave above, the histogram of the S channel looks like:</p> <p><a href="http://i.stack.imgur.com/i4nuf.png" rel="nofollow"><img src="http://i.stack.imgur.com/i4nuf.png" alt="Histogram of S channel"></a></p> <p>You can see the large blob near 0 is the white background that has the lowest saturation.</p>
1
2016-07-23T08:10:01Z
[ "python", "opencv", "image-processing" ]
How to handle complexType arguments in python soap module zeep?
38,539,568
<p>Zeep documentation example :</p> <pre><code>from zeep import Client client = Client('http://my-enterprise-endpoint.com') client.service.submit_order(user_id=1, order={ 'number': '1234', 'price': 99, }) </code></pre> <p>My use case :</p> <p>I want to call a webservice that needs a parameter 'findCriteria'</p> <p>Example : </p> <pre><code>findcriteria = { 'Criteria' : [{ 'ColumnName' : 'Closed', 'Value' : 0 }, { 'ColumnName' : 'AssignToQueueID', 'Value' : queueid }, { 'ColumnName' : 'SupportCallType', 'Value' : 'I' } ] } </code></pre> <p>Calling the service :</p> <p>print client.service.GetCount(findCriteria = findcriteria)</p> <p>This is the XML that is created:</p> <p> </p> <pre><code>&lt;soap-env:Body&gt; &lt;ns1:GetCount&gt; &lt;ns1:findCriteria/&gt; &lt;/ns1:GetCount&gt; &lt;/soap-env:Body&gt; &lt;/soap-env:Envelope&gt; </code></pre> <p>Problem:</p> <p>Although the service returns the count, the criteria are not applied.</p> <p>When I feed the service a raw XML payload the results are OK.</p> <p>The problem is in the <code>&lt;ns1:findCriteria/&gt;</code> part.</p> <p>For each column there should be created a Criteria element.</p> <p>Results of grep GetCount on WSDL:</p> <pre><code>&lt;s:element name="GetCount"&gt; &lt;s:element name="GetCountResponse"&gt; &lt;s:element minOccurs="1" maxOccurs="1" name="GetCountResult" type="s:int" /&gt; &lt;wsdl:message name="GetCountSoapIn"&gt; &lt;wsdl:part name="parameters" element="tns:GetCount" /&gt; &lt;wsdl:message name="GetCountSoapOut"&gt; &lt;wsdl:part name="parameters" element="tns:GetCountResponse" /&gt; &lt;wsdl:operation name="GetCount"&gt; &lt;wsdl:input message="tns:GetCountSoapIn" /&gt; &lt;wsdl:output message="tns:GetCountSoapOut" /&gt; &lt;wsdl:operation name="GetCount"&gt; &lt;soap:operation soapAction="http://&lt;server&gt;/webservices/SupportCall/GetCount" style="document" /&gt; &lt;wsdl:operation name="GetCount"&gt; &lt;soap12:operation soapAction="http://&lt;server&gt;/webservices/SupportCall/GetCount" style="document" /&gt; </code></pre>
1
2016-07-23T08:02:12Z
39,154,496
<p>Inspect your wsdl with following command: <code>python -mzeep &lt;wsdl&gt;</code></p> <p>You will find details of your service in the output: <code>ns1:GetCount(FindCriteria:findCriteria)</code></p> <p>Sample code based on above inspection output:</p> <pre><code>find_criteria_type = client.get_type('ns1:findCriteria') find_criteria = find_criteria_type() client.service.GetCount(FindCriteria=find_criteria) </code></pre> <p>If you XML is something like this:</p> <pre><code>&lt;soap-env:Body&gt; &lt;ns1:GetCount&gt; &lt;ns1:findCriteria&gt; &lt;ns1:param1&gt;val1&lt;/ns1:param1&gt; &lt;ns1:param2&gt;val2&lt;/ns1:param1&gt; &lt;/ns1:findCriteria&gt; &lt;/ns1:GetCount&gt; &lt;/soap-env:Body&gt; </code></pre> <p>you need to pass the params when creating the obj:</p> <pre><code>find_criteria = find_criteria_type(param1=val1, param2=val2) </code></pre>
0
2016-08-25T20:48:21Z
[ "python", "web-services", "soap" ]
How to handle complexType arguments in python soap module zeep?
38,539,568
<p>Zeep documentation example :</p> <pre><code>from zeep import Client client = Client('http://my-enterprise-endpoint.com') client.service.submit_order(user_id=1, order={ 'number': '1234', 'price': 99, }) </code></pre> <p>My use case :</p> <p>I want to call a webservice that needs a parameter 'findCriteria'</p> <p>Example : </p> <pre><code>findcriteria = { 'Criteria' : [{ 'ColumnName' : 'Closed', 'Value' : 0 }, { 'ColumnName' : 'AssignToQueueID', 'Value' : queueid }, { 'ColumnName' : 'SupportCallType', 'Value' : 'I' } ] } </code></pre> <p>Calling the service :</p> <p>print client.service.GetCount(findCriteria = findcriteria)</p> <p>This is the XML that is created:</p> <p> </p> <pre><code>&lt;soap-env:Body&gt; &lt;ns1:GetCount&gt; &lt;ns1:findCriteria/&gt; &lt;/ns1:GetCount&gt; &lt;/soap-env:Body&gt; &lt;/soap-env:Envelope&gt; </code></pre> <p>Problem:</p> <p>Although the service returns the count, the criteria are not applied.</p> <p>When I feed the service a raw XML payload the results are OK.</p> <p>The problem is in the <code>&lt;ns1:findCriteria/&gt;</code> part.</p> <p>For each column there should be created a Criteria element.</p> <p>Results of grep GetCount on WSDL:</p> <pre><code>&lt;s:element name="GetCount"&gt; &lt;s:element name="GetCountResponse"&gt; &lt;s:element minOccurs="1" maxOccurs="1" name="GetCountResult" type="s:int" /&gt; &lt;wsdl:message name="GetCountSoapIn"&gt; &lt;wsdl:part name="parameters" element="tns:GetCount" /&gt; &lt;wsdl:message name="GetCountSoapOut"&gt; &lt;wsdl:part name="parameters" element="tns:GetCountResponse" /&gt; &lt;wsdl:operation name="GetCount"&gt; &lt;wsdl:input message="tns:GetCountSoapIn" /&gt; &lt;wsdl:output message="tns:GetCountSoapOut" /&gt; &lt;wsdl:operation name="GetCount"&gt; &lt;soap:operation soapAction="http://&lt;server&gt;/webservices/SupportCall/GetCount" style="document" /&gt; &lt;wsdl:operation name="GetCount"&gt; &lt;soap12:operation soapAction="http://&lt;server&gt;/webservices/SupportCall/GetCount" style="document" /&gt; </code></pre>
1
2016-07-23T08:02:12Z
39,272,059
<p>I had a similar problem and I managed to solve it, but to help you I need either a sample correct XML (how it should look like) or at least a default request generated using SoapUI. </p> <p>In the meantime, perhaps the code below might help you: Here the complex argument was credentials and it consisted of 2 login items, the login and the domain.</p> <pre><code>&lt;soap-env:Envelope xmlns:ns1="http://xml.kamsoft.pl/ws/kaas/login_types" xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap-env:Body&gt; &lt;ns1:login&gt; &lt;ns1:credentials&gt; &lt;ns1:item&gt; &lt;ns1:name&gt;login&lt;/ns1:name&gt; &lt;ns1:value&gt; &lt;ns1:stringValue&gt;login_here&lt;/ns1:stringValue&gt; &lt;/ns1:value&gt; &lt;/ns1:item&gt; &lt;ns1:item&gt; &lt;ns1:name&gt;domain&lt;/ns1:name&gt; &lt;ns1:value&gt; &lt;ns1:stringValue&gt;domain_here&lt;/ns1:stringValue&gt; &lt;/ns1:value&gt; &lt;/ns1:item&gt; &lt;/ns1:credentials&gt; &lt;ns1:password&gt;password_here&lt;/ns1:password&gt; &lt;/ns1:login&gt; &lt;/soap-env:Body&gt; &lt;/soap-env:Envelope&gt; </code></pre> <p>And here is the code that generated this XML:</p> <pre><code>domain = "domain_here" login = "login_here" password = "password_here" credentials = {"item": [{"name": "login", 'value': {"stringValue": login}}, {"name": "domain", 'value': {"stringValue": domain}}]} client.service.login(credentials=credentials, password=password) </code></pre>
0
2016-09-01T12:51:08Z
[ "python", "web-services", "soap" ]
For loop outout numbers to a string
38,539,581
<p>Well i just wrote a code that get's a starting number, ending number and a step (it's a range) and prints all numbers in bettwen. It works great but i want the output to be also as a string.</p> <p>This is my code:</p> <pre><code>def count(num1,num2,steps): getfirstnum=int(raw_input(num1)) getsecondenum=int(raw_input(num2)) getsteps=int(raw_input(steps)) for num in range(getfirstnum,getsecondenum,getsteps): print 'in bettwen: ',num return num def Main(): Getnum=count('Give me the 1st number: ','Give me the 2nd number: ','How many Steps?: ') if __name__ == "__main__": Main() </code></pre> <p>Now if i will insert: 1st number: 1 2nd number: 10 Step: 2</p> <p>I will get the result:</p> <pre><code>in bettwen: 1 in bettwen: 3 in bettwen: 5 in bettwen: 7 in bettwen: 9 </code></pre> <p>How can i make my output to be a string? Thanks.</p>
-3
2016-07-23T08:03:35Z
38,539,615
<p>Try this:</p> <pre><code>def whatever(start, stop): result = '' for num in range(start,stop): result += str(num) return result print(whatever(0,5)) </code></pre> <hr> <pre><code>01234 </code></pre>
1
2016-07-23T08:08:15Z
[ "python", "string", "function", "for-loop" ]
For loop outout numbers to a string
38,539,581
<p>Well i just wrote a code that get's a starting number, ending number and a step (it's a range) and prints all numbers in bettwen. It works great but i want the output to be also as a string.</p> <p>This is my code:</p> <pre><code>def count(num1,num2,steps): getfirstnum=int(raw_input(num1)) getsecondenum=int(raw_input(num2)) getsteps=int(raw_input(steps)) for num in range(getfirstnum,getsecondenum,getsteps): print 'in bettwen: ',num return num def Main(): Getnum=count('Give me the 1st number: ','Give me the 2nd number: ','How many Steps?: ') if __name__ == "__main__": Main() </code></pre> <p>Now if i will insert: 1st number: 1 2nd number: 10 Step: 2</p> <p>I will get the result:</p> <pre><code>in bettwen: 1 in bettwen: 3 in bettwen: 5 in bettwen: 7 in bettwen: 9 </code></pre> <p>How can i make my output to be a string? Thanks.</p>
-3
2016-07-23T08:03:35Z
38,539,619
<pre><code>def count(num1,num2,steps): string_output = "" getfirstnum=int(raw_input(num1)) getsecondenum=int(raw_input(num2)) getsteps=int(raw_input(steps)) for num in range(getfirstnum,getsecondenum,getsteps): string_output += str(num) return string_output </code></pre>
1
2016-07-23T08:08:28Z
[ "python", "string", "function", "for-loop" ]
For loop outout numbers to a string
38,539,581
<p>Well i just wrote a code that get's a starting number, ending number and a step (it's a range) and prints all numbers in bettwen. It works great but i want the output to be also as a string.</p> <p>This is my code:</p> <pre><code>def count(num1,num2,steps): getfirstnum=int(raw_input(num1)) getsecondenum=int(raw_input(num2)) getsteps=int(raw_input(steps)) for num in range(getfirstnum,getsecondenum,getsteps): print 'in bettwen: ',num return num def Main(): Getnum=count('Give me the 1st number: ','Give me the 2nd number: ','How many Steps?: ') if __name__ == "__main__": Main() </code></pre> <p>Now if i will insert: 1st number: 1 2nd number: 10 Step: 2</p> <p>I will get the result:</p> <pre><code>in bettwen: 1 in bettwen: 3 in bettwen: 5 in bettwen: 7 in bettwen: 9 </code></pre> <p>How can i make my output to be a string? Thanks.</p>
-3
2016-07-23T08:03:35Z
38,539,806
<pre><code>... print 'in bettwen: ' + str(num) ... </code></pre> <p>Or if you are looking for something different like:</p> <pre><code>string = 'in bettwen: ' for num in range(getfirstnum,getsecondenum,getsteps): string += " " + str(num) return num </code></pre>
0
2016-07-23T08:33:02Z
[ "python", "string", "function", "for-loop" ]
For loop outout numbers to a string
38,539,581
<p>Well i just wrote a code that get's a starting number, ending number and a step (it's a range) and prints all numbers in bettwen. It works great but i want the output to be also as a string.</p> <p>This is my code:</p> <pre><code>def count(num1,num2,steps): getfirstnum=int(raw_input(num1)) getsecondenum=int(raw_input(num2)) getsteps=int(raw_input(steps)) for num in range(getfirstnum,getsecondenum,getsteps): print 'in bettwen: ',num return num def Main(): Getnum=count('Give me the 1st number: ','Give me the 2nd number: ','How many Steps?: ') if __name__ == "__main__": Main() </code></pre> <p>Now if i will insert: 1st number: 1 2nd number: 10 Step: 2</p> <p>I will get the result:</p> <pre><code>in bettwen: 1 in bettwen: 3 in bettwen: 5 in bettwen: 7 in bettwen: 9 </code></pre> <p>How can i make my output to be a string? Thanks.</p>
-3
2016-07-23T08:03:35Z
38,544,173
<p>Use <code>join</code> and a generator:</p> <pre><code>&gt;&gt;&gt; ''.join(str(n) for n in range(1,10,2)) '13579' </code></pre> <p>This is the equivalent of:</p> <pre><code>&gt;&gt;&gt; s = '' &gt;&gt;&gt; for n in range(1,10,2): ... s += str(n) ... &gt;&gt;&gt; s '13579' </code></pre>
0
2016-07-23T16:47:07Z
[ "python", "string", "function", "for-loop" ]
Killing a process within a python script running on linux
38,539,607
<p>I have Raspbian as the linux distro running on my RPI. I've setup a small socket server using twisted and it receives certain commands from an iOS app. These commands are strings. I started a process when I received "st" and now I want to kill it when i get "sp". This is the way I tried:</p> <ol> <li>Imported OS </li> <li>Used os.system("...") //to start process</li> <li>os.system("...") // to kill process</li> </ol> <p>Lets say the service is named xyz. This is the exact way I tried to kill it:</p> <p>os.system('ps axf | grep xyz | grep -v grep | awk '{print "kill " $1 }' | sh')</p> <p>But I got a syntax error. That line runs perfectly when I try it in terminal separately. Is this a wrong way to do this in a python script? How do I fix it?</p>
0
2016-07-23T08:07:01Z
38,539,621
<p>You will need to escape the quotes in your string:</p> <pre><code>os.system('ps axf | grep xyz | grep -v grep | awk \'{print "kill " $1 }\' | sh') </code></pre> <p>Or use a triple quote:</p> <pre><code>os.system('''ps axf | grep xyz | grep -v grep | awk '{print "kill " $1 }' | sh''') </code></pre>
0
2016-07-23T08:09:17Z
[ "python", "linux", "bash", "shell", "awk" ]
Killing a process within a python script running on linux
38,539,607
<p>I have Raspbian as the linux distro running on my RPI. I've setup a small socket server using twisted and it receives certain commands from an iOS app. These commands are strings. I started a process when I received "st" and now I want to kill it when i get "sp". This is the way I tried:</p> <ol> <li>Imported OS </li> <li>Used os.system("...") //to start process</li> <li>os.system("...") // to kill process</li> </ol> <p>Lets say the service is named xyz. This is the exact way I tried to kill it:</p> <p>os.system('ps axf | grep xyz | grep -v grep | awk '{print "kill " $1 }' | sh')</p> <p>But I got a syntax error. That line runs perfectly when I try it in terminal separately. Is this a wrong way to do this in a python script? How do I fix it?</p>
0
2016-07-23T08:07:01Z
38,539,711
<p>Alternatively, open the process with <code>Popen(...).pid</code> and then use <code>os.kill()</code> </p> <pre><code>my_pid = Popen('/home/rolf/test1.sh',).pid os.kill(int(my_pid), signal.SIGKILL) </code></pre> <p>Remember to include a shebang in your script (#!/bin/sh)</p> <p>Edit: On second thoughts, perhaps</p> <pre><code>os.kill(int(my_pid), signal.SIGTERM) </code></pre> <p>is probably a better way to end the process, it at least gives the process the chance to close down gracefully.</p>
0
2016-07-23T08:21:04Z
[ "python", "linux", "bash", "shell", "awk" ]
How can I get Skyfield to agree with the Nautical Almanac for the Sun's Declination?
38,539,625
<p>Here's a sample script that calculates the sun's declination on 2016/7/23 at 00:00:00 GMT using both PyEphem and Skyfield:</p> <pre><code>import ephem sun1 = ephem.Sun('2016/7/23 00:00:00') dec1 = sun1.dec print 'PyEphem Declination:', dec1 #------------------------------------- from skyfield.api import load planets = load('de421.bsp') earth = planets['earth'] sun2 = planets['sun'] ts = load.timescale() time2 = ts.utc(2016, 7, 23) dec2 = earth.at(time2).observe(sun2).apparent().radec()[1] print 'Skyfield Declination:', dec2 </code></pre> <p>When I run this I get:</p> <pre><code>PyEphem Declination: 20:01:24.0 Skyfield Declination: +20deg 04' 30.0" </code></pre> <p>The Nautical Almanac gives 20deg 01.4' for that time. I'm not sure what I'm doing incorrectly to cause this discrepancy. Thanks!</p> <p>P.S. I'm using Python 2.7, and Skyfield 0.8.</p>
1
2016-07-23T08:09:46Z
38,588,860
<p>The answer that PyEphem is giving you is in exact agreement with the almanac, but expressed in traditional hours-minutes-seconds of arc instead of in hours and decimal minutes. The fraction <code>.4</code> that is part of the minutes-of-arc quantity <code>1.4</code> becomes, if expressed as arcseconds, 60 × 0.4 = 24 arcseconds. So:</p> <p>20°1.4′ = 20°1′24″</p> <p>Skyfield is giving you, by default, coordinates in the permanent GCRS coordinate system that is the updated replacement for J2000. But the Almanac does not use the equator-and-equinox coordinate system of the year 2000, but of the current year — and in fact the exact moment ­— of each datum that it reports. To ask Skyfield to express the declination in year-2016 coordinates, give it the <code>epoch</code> value <code>"date"</code>:</p> <pre><code>from skyfield.api import load ts = load.timescale() planets = load('de421.bsp') earth = planets['earth'] sun = planets['sun'] t = ts.utc(2016, 7, 23) ra, dec, distance = earth.at(t).observe(sun).apparent().radec(epoch='date') print(dec) </code></pre> <p>The result:</p> <pre><code>+20deg 01' 24.0" </code></pre>
0
2016-07-26T11:37:12Z
[ "python", "pyephem", "skyfield" ]
Managing sessions when scraping with Requests library in python
38,539,676
<p>I am having trouble creating and keeping new sessions when I am scraping my page. I am initiating a session within my script using the Requests library and then parsing values to a web form. However, it's is returning a "Your session has timed out" page.</p> <p>Here is my source:</p> <pre><code>import requests session = requests.Session() params = {'Rctl00$ContentPlaceHolder1$txtName': 'Andrew'} r = session.post("https://www.searchiqs.com/NYALB/SearchResultsMP.aspx", data=params) print(r.text) </code></pre> <p>The url I want to search from is this <a href="https://www.searchiqs.com/NYALB/SearchAdvancedMP.aspx" rel="nofollow">https://www.searchiqs.com/NYALB/SearchAdvancedMP.aspx</a></p> <p>I am searching for a Party 1 name called "Andrew". I have identified the form element holding this search box as 'Rctl00$ContentPlaceHolder1$txtName'. The action url is SearchResultsMP.aspx. </p> <p>When i do it from a browser, it gives the first page of results. When i do it in the terminal it gives me the session expired page. Any ideas?</p>
0
2016-07-23T08:16:26Z
38,555,884
<p>First, I would refer you to the advanced documentation related to use of sessions within the <code>requests</code> Python module.</p> <p><a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">http://docs.python-requests.org/en/master/user/advanced/</a></p> <p>I also notice that navigating to the base URL in your invocation of <code>sessions.post</code> redirects to:</p> <p><a href="https://www.searchiqs.com/NYALB/InvalidLogin.aspx?InvLogInCode=OldSession%2007/24/2016%2004:19:37%20AM" rel="nofollow">https://www.searchiqs.com/NYALB/InvalidLogin.aspx?InvLogInCode=OldSession%2007/24/2016%2004:19:37%20AM</a></p> <p>I "hacked" the URL to navigate to:</p> <p><a href="https://www.searchiqs.com/NYALB" rel="nofollow">https://www.searchiqs.com/NYALB/</a></p> <p>...and notice that if I click on the <code>Show Login Fields</code> link on that page, I am prompted a form appears with prompts for <code>User ID</code> and <code>Password</code>. Your attempts to programmatically do your searches are likely failing because you have not done any sorts of authentication. It likely works in your browser because you have been permitted to access this, either by some previous authentication you have completed and may have forgotten about, or some sort of server side access rules that don't ask for this based upon some criteria.</p> <p>Running those commands in a local interpreter, I can see that the site owner did not bother to return a status code indicative of failed auth. If you check, the <code>r.status_code</code> is 200 but your <code>r.text</code> will be the <code>Invalid Login</code> page. I know nada about ASP, but am guessing that HTTP status codes should be indicative of what actually happened.</p> <p>Here is some code, that does not really work, but may illustrate how you may want to interact with the site and sessions.</p> <pre><code>import requests # Create dicts with our login and search data login_params = {'btnGuestLogin': 'Log+In+as+GUEST'} search_params = {'ctl00$ContentPlaceHolder1$txtName': 'Andrew'} full_params = {'btnGuestLogin': 'Log+In+as+GUEST', 'ctl00$ContentPlaceHolder1$txtName': 'Andrew'} # Create session and add login params albany_session = requests.session() albany_session.params = login_params # Login and confirm login via searching for the 'ASP.NET_SessionId' cookie. # Use the login page, not the search page first. albany_session.post('https://www.searchiqs.com/NYALB/LogIn.aspx') print(albany_session.cookies) # Prepare a your search request search_req = requests.Request('POST', 'https://www.searchiqs.com/NYALB/SearchAdvancedMP.aspx',data=search_params) prepped_search_req = albany_session.prepare_request(search_req) # Probably should work but does not seem to, for "reasons" unknown to me. search_response = albany_session.send(prepped_search_req) print(search_response.text) </code></pre> <p>An alternative may be for you to consider is Selenium browser automation with Python bindings.</p> <p><a href="http://selenium-python.readthedocs.io/" rel="nofollow">http://selenium-python.readthedocs.io/</a></p>
0
2016-07-24T19:24:55Z
[ "python", "asp.net", "python-requests", "screen-scraping", "robobrowser" ]
StratifiedKFold output handling
38,539,780
<p>I have a series with 20 rows and 60 columns i.e 20 examples each with 60 parameters.</p> <p>kfold = StratifiedKFold(y=encoded_Y, n_folds=10, shuffle=True, random_state=seed) <a href="http://i.stack.imgur.com/8B3or.png" rel="nofollow">The output consists of two columns</a></p> <p>I would like to know what does the second column mean and on what basis does it choose the two indexes. Why not take three indexes?</p> <p>Furthur, I would like to know how does the cross validation function take this series as an input for the "cv" argument. "cv" is generally an integer.</p> <p>results = cross_val_score(estimator, X, encoded_Y, cv=kfold)</p>
1
2016-07-23T08:30:06Z
38,540,179
<p>As with all of the cross validators in <a href="http://scikit-learn.org/stable/modules/classes.html#module-sklearn.cross_validation" rel="nofollow"><code>sklearn.cross_validation</code></a> this is an iterator over pairs of indices. In each pair, the first item is the list of train indices, and the second item is the list of test indices. </p> <p>In <a href="http://i.stack.imgur.com/8B3or.png" rel="nofollow">the example you bring</a> the first item contains a pair where everything except 1, 17 is the train indices, and 1, 17 are the test indices.</p>
0
2016-07-23T09:24:13Z
[ "python", "machine-learning", "scikit-learn", "cross-validation" ]
Abort and restart batch execution
38,539,848
<p>I have a python program that I run with a batch-file to store all the launch parameters. The program runs in an endless loop. I'd like to abort the python loop after 10 minutes and restart the python program again. How can I achieve this in a bat-file? Are there better solutions? Calls, quits and exits don't seem to work with nerver ending programs.</p> <p>Cheers!</p>
-1
2016-07-23T08:38:46Z
38,540,349
<p>Show your code.... Can get better help that way. Try <code>Taskkill /?</code> or <code>timeout /?</code>, and <code>start</code>. For example: <code>Taskkill /IM notepad.exe /F timeout 10 &gt;nul start notepad.exe</code></p>
0
2016-07-23T09:43:37Z
[ "python", "loops", "batch-file", "execution" ]
Abort and restart batch execution
38,539,848
<p>I have a python program that I run with a batch-file to store all the launch parameters. The program runs in an endless loop. I'd like to abort the python loop after 10 minutes and restart the python program again. How can I achieve this in a bat-file? Are there better solutions? Calls, quits and exits don't seem to work with nerver ending programs.</p> <p>Cheers!</p>
-1
2016-07-23T08:38:46Z
38,540,388
<pre><code>:test python &lt;your script&gt; taskkill /F /IM python.exe /T goto:test </code></pre> <p>You can do it in the above way, but it is good to do everything in python using while loops.</p>
0
2016-07-23T09:47:38Z
[ "python", "loops", "batch-file", "execution" ]
Evaluating multiple conditions in if-then-else block in a Pandas DataFrame
38,539,910
<p>I want to create a new column in a Pandas DataFrame by evaluating multiple conditions in an if-then-else block. </p> <pre><code>if events.hour &lt;= 6: events['time_slice'] = 'night' elif events.hour &lt;= 12: events['time_slice'] = 'morning' elif events.hour &lt;= 18: events['time_slice'] = 'afternoon' elif events.hour &lt;= 23: events['time_slice'] = 'evening' </code></pre> <p>When I run this, I get the error below:</p> <blockquote> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p>So I tried to solve this by adding the any statement like shown below:</p> <pre><code>if (events.hour &lt;= 6).any(): events['time_slice'] = 'night' elif (events.hour &lt;= 12).any(): events['time_slice'] = 'morning' elif (events.hour &lt;= 18).any(): events['time_slice'] = 'afternoon' elif (events.hour &lt;= 23).any(): events['time_slice'] = 'evening' </code></pre> <p>Now I do not get any error, but when I check the unique values of time_slice, it only shows 'night'</p> <pre><code>np.unique(events.time_slice) </code></pre> <blockquote> <p>array(['night'], dtype=object)</p> </blockquote> <p>How can I solve this, because my data contains samples that should get 'morning', 'afternoon' or 'evening'. Thanks!</p>
1
2016-07-23T08:46:49Z
38,539,947
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow">pd.cut()</a> method in order to categorize your data:</p> <p>Demo:</p> <pre><code>In [66]: events = pd.DataFrame(np.random.randint(0, 23, 10), columns=['hour']) In [67]: events Out[67]: hour 0 5 1 17 2 12 3 2 4 20 5 22 6 20 7 11 8 14 9 8 In [71]: events['time_slice'] = pd.cut(events.hour, bins=[-1, 6, 12, 18, 23], labels=['night','morning','afternoon','evening']) In [72]: events Out[72]: hour time_slice 0 5 night 1 17 afternoon 2 12 morning 3 2 night 4 20 evening 5 22 evening 6 20 evening 7 11 morning 8 14 afternoon 9 8 morning </code></pre>
3
2016-07-23T08:52:21Z
[ "python", "pandas", "dataframe", "conditional" ]
Evaluating multiple conditions in if-then-else block in a Pandas DataFrame
38,539,910
<p>I want to create a new column in a Pandas DataFrame by evaluating multiple conditions in an if-then-else block. </p> <pre><code>if events.hour &lt;= 6: events['time_slice'] = 'night' elif events.hour &lt;= 12: events['time_slice'] = 'morning' elif events.hour &lt;= 18: events['time_slice'] = 'afternoon' elif events.hour &lt;= 23: events['time_slice'] = 'evening' </code></pre> <p>When I run this, I get the error below:</p> <blockquote> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p>So I tried to solve this by adding the any statement like shown below:</p> <pre><code>if (events.hour &lt;= 6).any(): events['time_slice'] = 'night' elif (events.hour &lt;= 12).any(): events['time_slice'] = 'morning' elif (events.hour &lt;= 18).any(): events['time_slice'] = 'afternoon' elif (events.hour &lt;= 23).any(): events['time_slice'] = 'evening' </code></pre> <p>Now I do not get any error, but when I check the unique values of time_slice, it only shows 'night'</p> <pre><code>np.unique(events.time_slice) </code></pre> <blockquote> <p>array(['night'], dtype=object)</p> </blockquote> <p>How can I solve this, because my data contains samples that should get 'morning', 'afternoon' or 'evening'. Thanks!</p>
1
2016-07-23T08:46:49Z
38,539,980
<p>You could create a function:</p> <pre><code>def time_slice(hour): if hour &lt;= 6: return 'night' elif hour &lt;= 12: return 'morning' elif hour &lt;= 18: return 'afternoon' elif hour &lt;= 23: return 'evening' </code></pre> <p>then <code>events['time_slice'] = events.hour.apply(time_slice)</code> should do the trick.</p>
2
2016-07-23T08:55:23Z
[ "python", "pandas", "dataframe", "conditional" ]
Evaluating multiple conditions in if-then-else block in a Pandas DataFrame
38,539,910
<p>I want to create a new column in a Pandas DataFrame by evaluating multiple conditions in an if-then-else block. </p> <pre><code>if events.hour &lt;= 6: events['time_slice'] = 'night' elif events.hour &lt;= 12: events['time_slice'] = 'morning' elif events.hour &lt;= 18: events['time_slice'] = 'afternoon' elif events.hour &lt;= 23: events['time_slice'] = 'evening' </code></pre> <p>When I run this, I get the error below:</p> <blockquote> <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p>So I tried to solve this by adding the any statement like shown below:</p> <pre><code>if (events.hour &lt;= 6).any(): events['time_slice'] = 'night' elif (events.hour &lt;= 12).any(): events['time_slice'] = 'morning' elif (events.hour &lt;= 18).any(): events['time_slice'] = 'afternoon' elif (events.hour &lt;= 23).any(): events['time_slice'] = 'evening' </code></pre> <p>Now I do not get any error, but when I check the unique values of time_slice, it only shows 'night'</p> <pre><code>np.unique(events.time_slice) </code></pre> <blockquote> <p>array(['night'], dtype=object)</p> </blockquote> <p>How can I solve this, because my data contains samples that should get 'morning', 'afternoon' or 'evening'. Thanks!</p>
1
2016-07-23T08:46:49Z
38,540,072
<p>Here's a NumPy approach to it -</p> <pre><code>tags = ['night','morning','afternoon','evening'] events['time_slice'] = np.take(tags,((events.hour.values-1)//6).clip(min=0)) </code></pre> <p>Sample run -</p> <pre><code>In [130]: events Out[130]: hour time_slice 0 0 night 1 8 morning 2 16 afternoon 3 20 evening 4 2 night 5 14 afternoon 6 7 morning 7 18 afternoon 8 8 morning 9 22 evening </code></pre>
2
2016-07-23T09:08:25Z
[ "python", "pandas", "dataframe", "conditional" ]
Extraction of different views of a pixel from 3D volumetric data
38,539,911
<p>I have 3D CT data. I want to extract three different patches centering a particular pixel corresponding to three 3 different views (axial, coronal, sagittal). Can anyone please tell me how to do that in python?</p>
-3
2016-07-23T08:46:56Z
38,705,878
<p>If your volume is I and the point that you want to extract the patch around it is x0,yo,zo and the patch size is p than</p> <pre><code>I[xo,y0-p/2:y0+p/2,z0-p/2:z0+p/2] = Pach1 I[xo-p/2:x0+p/2,y0-p/2:y0+p/2,z0] = Pach2 I[xo-p/2:x0+p/2,y0,z0-p/2:z0+p/2] = Pach3 </code></pre>
0
2016-08-01T18:40:06Z
[ "python", "python-2.7", "computer-vision" ]
How to create directory in django media file (best way)?
38,539,946
<p>I want to save downloaded images to a path that like so: media/images/[user.pk]/ directly from urlretrieve from urllib library is that possible and what is the most elegant way? </p> <p>This are the used code snippets:</p> <ul> <li><p>here I use urlretrieve with path like .../media/images/[user.pk]/[filename.jpg]</p> <pre><code>file_path, header = urlretrieve(image_url, os.path.join( MEDIA_ROOT, get_image_path( self, 'profile_image_'+str( datetime.utcnow().strftime("%Y%m%d_%H%M"))+'.jpg </code></pre></li> <li><p>Here is the defined function that returns desired path with filename</p> <pre><code>def get_image_path(instance, filename): return os.path.join('images', str(instance.pk), filename) </code></pre></li> </ul> <p>when I run I get an error since the file does not exists:</p> <p>FileNotFoundError at /rest/oauth2/google [Errno 2] No such file or directory: 'C:\xampp\htdocs\BookProjectFresh\media\images\21\profile_image_20160723_0801.jpg'</p> <p>I know I can achieve that by first loading file into temp folder and then load from there and put into the django model and it will automatically create file path if it does not exists, but then I have 2 files on my pc with same content. Or would be the best way to do it with os.path.makedirs? Please if you know any other way share it. </p>
0
2016-07-23T08:52:01Z
38,540,103
<p>I solved a problem like so:</p> <pre><code>def save_image_from_url(self, image_url): if self.profile_image_url != image_url or not os.path.isfile(self.profile_image.path): if not os.path.exists(get_image_path(self, os.path.join(MEDIA_ROOT, get_image_path( self, '')))): os.makedirs(get_image_path(self, os.path.join(MEDIA_ROOT, get_image_path( self, '')))) self.profile_image_url = image_url file_path, header = urlretrieve(image_url, os.path.join(MEDIA_ROOT, get_image_path( self, 'profile_image_'+str(datetime.utcnow().strftime("%Y%m%d_%H%M"))+'.jpg'))) self.profile_image = file_path self.save() </code></pre>
0
2016-07-23T09:12:21Z
[ "python", "django", "urllib", "file-not-found" ]
Named colors in tkinter
38,539,993
<p>How can I get a list of all named colors in tkinter? I need to choose colors randomly and print their names to the user.</p> <p>I found a list of all colors here: <a href="http://stackoverflow.com/questions/4969543/colour-chart-for-tkinter-and-tix-using-python">Colour chart for Tkinter and Tix Using Python</a> I would rather get the list from the library than to hardcode it in my program.</p>
1
2016-07-23T08:56:39Z
38,541,020
<p>In case of linux (debian) there is a file <em>/etc/X11/rgb.txt</em> that has lines like </p> <pre><code>255 250 250 snow </code></pre> <p>and should be easy to parse. Your program could read color definitions from that file (or a copy of it) to a list, and then select a random color from that list.</p>
1
2016-07-23T11:02:34Z
[ "python", "colors", "tkinter" ]
Python-String parsing for extraction of date and time
38,540,016
<p>The datetime is given in the format <strong>YY-MM-DD HH:MM:SS</strong> in a dataframe.I want new Series of <strong>year,month and hour</strong> for which I am trying the below code. But the problem is that Month and Hour are getting the same value,Year is fine.</p> <p>Can anyone help me with this ? I am using Ipthon notebook and Pandas and numpy.</p> <p>Here is the code :</p> <pre><code> def extract_hour(X): cnv=datetime.strptime(X, '%Y-%m-%d %H:%M:%S') return cnv.hour def extract_month(X): cnv=datetime.strptime(X, '%Y-%m-%d %H:%M:%S') return cnv.month def extract_year(X): cnv=datetime.strptime(X, '%Y-%m-%d %H:%M:%S') return cnv.year #month column train['Month']=train['datetime'].apply((lambda x: extract_month(x))) test['Month']=test['datetime'].apply((lambda x: extract_month(x))) #year column train['Year']=train['datetime'].apply((lambda x: extract_year(x))) test['Year']=test['datetime'].apply((lambda x: extract_year(x))) #Hour column train['Hour']=train['datetime'].apply((lambda x: extract_hour(x))) test['Hour']=test['datetime'].apply((lambda x: extract_hour(x))) </code></pre>
1
2016-07-23T08:59:41Z
38,540,052
<p>you can use <code>.dt</code> accessors instead: <code>train['datetime'].dt.month</code>, <code>train['datetime'].dt.year</code>, <code>train['datetime'].dt.hour</code> (see the full list below)</p> <p>Demo:</p> <pre><code>In [81]: train = pd.DataFrame(pd.date_range('2016-01-01', freq='1999H', periods=10), columns=['datetime']) In [82]: train Out[82]: datetime 0 2016-01-01 00:00:00 1 2016-03-24 07:00:00 2 2016-06-15 14:00:00 3 2016-09-06 21:00:00 4 2016-11-29 04:00:00 5 2017-02-20 11:00:00 6 2017-05-14 18:00:00 7 2017-08-06 01:00:00 8 2017-10-28 08:00:00 9 2018-01-19 15:00:00 In [83]: train.datetime.dt.year Out[83]: 0 2016 1 2016 2 2016 3 2016 4 2016 5 2017 6 2017 7 2017 8 2017 9 2018 Name: datetime, dtype: int64 In [84]: train.datetime.dt.month Out[84]: 0 1 1 3 2 6 3 9 4 11 5 2 6 5 7 8 8 10 9 1 Name: datetime, dtype: int64 In [85]: train.datetime.dt.hour Out[85]: 0 0 1 7 2 14 3 21 4 4 5 11 6 18 7 1 8 8 9 15 Name: datetime, dtype: int64 In [86]: train.datetime.dt.day Out[86]: 0 1 1 24 2 15 3 6 4 29 5 20 6 14 7 6 8 28 9 19 Name: datetime, dtype: int64 </code></pre> <p>List of all <code>.dt</code> accessors:</p> <pre><code>In [77]: train.datetime.dt. train.datetime.dt.ceil train.datetime.dt.hour train.datetime.dt.month train.datetime.dt.to_pydatetime train.datetime.dt.date train.datetime.dt.is_month_end train.datetime.dt.nanosecond train.datetime.dt.tz train.datetime.dt.day train.datetime.dt.is_month_start train.datetime.dt.normalize train.datetime.dt.tz_convert train.datetime.dt.dayofweek train.datetime.dt.is_quarter_end train.datetime.dt.quarter train.datetime.dt.tz_localize train.datetime.dt.dayofyear train.datetime.dt.is_quarter_start train.datetime.dt.round train.datetime.dt.week train.datetime.dt.days_in_month train.datetime.dt.is_year_end train.datetime.dt.second train.datetime.dt.weekday train.datetime.dt.daysinmonth train.datetime.dt.is_year_start train.datetime.dt.strftime train.datetime.dt.weekday_name train.datetime.dt.floor train.datetime.dt.microsecond train.datetime.dt.time train.datetime.dt.weekofyear train.datetime.dt.freq train.datetime.dt.minute train.datetime.dt.to_period train.datetime.dt.year </code></pre>
1
2016-07-23T09:05:32Z
[ "python", "datetime", "numpy", "pandas" ]
AttributeError: 'module' object has no attribute 'login'
38,540,033
<pre><code>import gspread gc = gspread.login(‘the.email.address@gmail.com’,’password’) </code></pre> <p>AttributeError: 'module' object has no attribute 'login'</p>
-8
2016-07-23T09:01:42Z
38,540,085
<p>The <a href="https://github.com/burnash/gspread" rel="nofollow"><code>gsspread</code></a> that I know of doesn't have the <code>login</code> method! </p> <p>I guess what you are looking for is <code>authorize</code>.</p> <p>You would ideally do something like this:</p> <pre><code>import gspread gc = gspread.authorize(credentials) # check link below on how to obtain the credentials </code></pre> <p>The procedure on how to obtain the <code>credentials</code> is very well documented by gsspread here - <a href="http://gspread.readthedocs.io/en/latest/oauth2.html" rel="nofollow">http://gspread.readthedocs.io/en/latest/oauth2.html</a></p>
0
2016-07-23T09:09:48Z
[ "python", "gspread" ]
Symbolic definition of a binomial using SymPy
38,540,092
<p>I am trying to symbolically define the Binomial function using Sympy. My first attempt was as follows:</p> <pre><code>import numpy as np import scipy.stats as st import sklearn.linear_model as lm import matplotlib.pyplot as plt import sympy as sp sp.interactive.printing.init_printing(use_latex=True) n = sp.Symbol('n', integer=True, positive=True) r = sp.Symbol('r', integer=True, positive=True) theta = sp.Symbol('theta') #Create the function symbolically from sympy import factorial cNkLambda= lambda n,r : (factorial(n))/ (factorial(r) *factorial(n- r)) binomLambda= lambda theta, n, r: cNkLambda(n,r)*((theta **r)*(1-theta)**(n-r)) print binomLambda (0.5, 10,5) </code></pre> <p>However, I realized I am not using any Sympy features here and nothing is evaluated symbolically. </p> <p>In my second attempt, i removed the Lambda definition, so that the Symbolic function is correctly defined, however this results in an exception:</p> <pre><code>%reset -f import numpy as np import scipy.stats as st import sklearn.linear_model as lm import matplotlib.pyplot as plt import sympy as sp #from sympy import binomial #from sympy import Symbol, Rational, factorial, binomial, expand_func sp.interactive.printing.init_printing(use_latex=True) n = sp.Symbol('n', integer=True, positive=True) r = sp.Symbol('r', integer=True, positive=True) theta = sp.Symbol('theta') #Create the function symbolically from sympy import factorial cNkLambda= (factorial(n))/ (factorial(r) *factorial(n-r)) #cNkLambda_fied = sp.lambdify((n,r), cNkLambda, modules='numpy') cNkLambda.evalf() # this works binomLambda= cNkLambda(n,r)*((theta **r)*(1-theta)**(n-r)) #Convert it to a Numpy-callable function #bin_likelihood = sp.lambdify((theta,r,n), binomLambda, modules='numpy') #print binomLambda (0.5, 10,5) </code></pre> <hr> <p>TypeError Traceback (most recent call last) in () 23 cNkLambda.evalf() # this works 24 ---> 25 binomLambda= cNkLambda(n,r)<em>((theta <strong>r)</em>(1-theta)</strong>(n-r)) 26 # Convert it to a Numpy-callable function 27 #bin_likelihood = sp.lambdify((theta,r,n), binomLambda, modules='numpy')</p> <p>TypeError: 'Mul' object is not callable</p> <p>My question is: how to correctly define the function so that it is symbolic all the way through. </p> <p><strong>Edit 1:</strong> Found this reference about this error: <a href="https://github.com/sympy/sympy/issues/8562" rel="nofollow">https://github.com/sympy/sympy/issues/8562</a>, but I can not deduce where in my code I am doing the same.</p> <p><strong>Edit 2:</strong> I updated the question,changed:</p> <pre><code>binomLambda= cNkLambda(n,r)*((theta **r)*(1-theta)**(n-r)) </code></pre> <p>to :</p> <pre><code>binomLambda= cNkLambda*((theta **r)*(1-theta)**(n-r)) </code></pre> <p>However now when I try to lamdify the symbolic function as follows: binomLambda.subs({theta:0.5,r:5,n:10}) # this works</p> <pre><code>#Convert it to a Numpy-callable function binomRealLambda = sp.lambdify((theta,r,n), binomLambda, modules='numpy') print binomRealLambda(0.5,5,10) </code></pre> <h2>This results in:</h2> <p>NameError Traceback (most recent call last) in () 27 binomRealLambda = sp.lambdify((theta,r,n), binomLambda, modules='numpy') 28 ---> 29 print binomRealLambda(0.5,5,10)</p> <p>/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/<strong>init</strong>.pyc in (_Dummy_46, _Dummy_47, _Dummy_48)</p> <p>NameError: global name 'factorial' is not defined</p> <p><strong>Edit 3:</strong> I got this fully working:</p> <pre><code> #----------------------Symbolic beta-------------------------------# a = sp.Symbol('a', integer=False, positive=True) b = sp.Symbol('b', integer=False, positive=True) mu = sp.Symbol('mu', integer=False, positive=True) # Create the function symbolically G = sp.gamma # The normalisation factor BetaNormSym = G(a + b)/(G(a)*G(b)) # The functional form BetaFSym = mu**(a-1) * (1-mu)**(b-1) BetaSym=BetaNormSym * BetaFSym BetaSym.evalf() # this works # Turn Beta into a function BetaLambda = sp.Lambda((mu,a,b), BetaSym) maths(r"\operatorname{Beta}(\mu|a,b) = ") display(BetaSym) BetaLambda(0.5,1,1) BetaSym.subs({mu:0.5,a:1,b:1}) #----------------------Symbolic beta-------------------------------# </code></pre> <p>Thanks, </p>
2
2016-07-23T09:11:09Z
38,540,536
<p><code>cNkLambda</code> is a SymPy expression which is defined in terms of <code>n</code> and <code>r</code>. It's not a function, so do not call it with <code>cNkLambda(n,r)</code>. <code>binomLambda</code> can then be defined by:</p> <pre><code>binomLambda = cNkLambda*((theta **r)*(1-theta)**(n-r)) </code></pre> <hr> <pre><code>In [18]: cNkLambda Out[20]: n! ─────────── r!⋅(n - r)! In [22]: cNkLambda*((theta **r)*(1-theta)**(n-r)) Out[22]: r n - r θ ⋅(-θ + 1) ⋅n! ─────────────────── r!⋅(n - r)! </code></pre> <hr> <p>To make a numeric function out of <code>binomLambda</code>, you could use <code>sympy.lambdify</code>. Note, however, that <code>binomLambda</code> uses factorials, and NumPy does not define a factorial function. </p> <p>You could either call <code>math.factorial</code> or <code>scipy.misc.factorial</code>:</p> <pre><code>bin_likelihood = sy.lambdify((theta,r,n), binomLambda, modules='math') </code></pre> <p>or </p> <pre><code>bin_likelihood2 = sy.lambdify((theta,r,n), binomLambda, modules=[{'factorial':misc.factorial}]) </code></pre> <hr> <p>For example,</p> <pre><code>import scipy.misc as misc import numpy as np import sympy as sy sy.interactive.printing.init_printing(use_latex=True) n = sy.Symbol('n', integer=True, positive=True) r = sy.Symbol('r', integer=True, positive=True) theta = sy.Symbol('theta') cNkLambda= (sy.factorial(n))/ (sy.factorial(r) * sy.factorial(n-r)) binomLambda = cNkLambda*((theta **r)*(1-theta)**(n-r)) bin_likelihood = sy.lambdify((theta,r,n), binomLambda, modules='math') print(bin_likelihood(np.linspace(0,2*np.pi,4), 2, 5)) # [ 0.00000000e+00 -5.74962672e+01 -5.68925055e+03 -5.82166577e+04] bin_likelihood2 = sy.lambdify((theta,r,n), binomLambda, modules=[{'factorial':misc.factorial}]) print(bin_likelihood2(np.linspace(0,2*np.pi,4), 2, 5)) # [ 0.00000000e+00 -5.74962672e+01 -5.68925055e+03 -5.82166577e+04] </code></pre>
1
2016-07-23T10:06:01Z
[ "python", "sympy" ]
Efficient way to pass system properties in python 3
38,540,208
<p>I'm using python 3 for an application. For that utility, I need to pass command line arguments as following, </p> <pre><code>python3 -m com.xxx.executor -Denvironment=dev -Dtoggle=False </code></pre> <p>Both the parameter <code>environment</code> and <code>toggle</code> are present in a property file too. If the value is specified in command line, it should override what is present on property file.</p> <p>I'm basically a java guy and in java, the properties passed in the form <code>-Dkey=value</code> will be set as system property. Then these properties can be read from code as <code>System.getProperty(key, defaultVal)</code>.</p> <p>But when I try the same in python 3, it didn't work. </p> <p>After referring python docs, it seems to me like the sys._xoptions are suitable for my requirement. </p> <pre><code> python3 -Xenvironment=dev -Xtoggle=False -m com.xxx.executor </code></pre> <p>Then read the properties using, <code>sys._xoptions</code></p> <p>I'm using Cpython. The aim of the thread is to ensure that, the way I'm proceeding is right or not. Or is there any other better ways in python to implement the same.</p> <p>Python veterans, please guide !</p>
1
2016-07-23T09:27:23Z
38,541,556
<p>For argument parsing, I use the <code>argparse</code> module (<a href="https://docs.python.org/3.5/library/argparse.html#module-argparse" rel="nofollow">docs</a>) to define which are valid named and/or positional arguments. </p> <p>There are third-party modules as well such as <a href="http://click.pocoo.org/5/" rel="nofollow">click</a> and <a href="http://docopt.org" rel="nofollow">docopt</a>. You should use what you feel most comfortable with and whether or not you can use third-party modules. The click documentation contains a (possibly biased) comparison between it, argparse and docopt.</p> <p>I've never used <code>sys._xoptions</code>, nor did I know of its existence. Seems a bit strange that a function starting with an <a href="http://stackoverflow.com/a/1301369">underscore</a> (normally used to indicate a "private" function) is mentioned in the docs. Perhaps someone else can shed some light on this.</p> <p>For the parsing of a property file, I use the <code>configparser</code> module (<a href="https://docs.python.org/3.5/library/configparser.html#module-configparser" rel="nofollow">docs</a>). Of course, you could opt for a JSON or YAML config file if you'd prefer that.</p> <p>That said, you'll have to come up with the necessary code to overrule properties when specified as arguments (though that shouldn't be too difficult).</p>
0
2016-07-23T12:00:39Z
[ "python", "python-2.7", "python-3.x" ]
Efficient way to pass system properties in python 3
38,540,208
<p>I'm using python 3 for an application. For that utility, I need to pass command line arguments as following, </p> <pre><code>python3 -m com.xxx.executor -Denvironment=dev -Dtoggle=False </code></pre> <p>Both the parameter <code>environment</code> and <code>toggle</code> are present in a property file too. If the value is specified in command line, it should override what is present on property file.</p> <p>I'm basically a java guy and in java, the properties passed in the form <code>-Dkey=value</code> will be set as system property. Then these properties can be read from code as <code>System.getProperty(key, defaultVal)</code>.</p> <p>But when I try the same in python 3, it didn't work. </p> <p>After referring python docs, it seems to me like the sys._xoptions are suitable for my requirement. </p> <pre><code> python3 -Xenvironment=dev -Xtoggle=False -m com.xxx.executor </code></pre> <p>Then read the properties using, <code>sys._xoptions</code></p> <p>I'm using Cpython. The aim of the thread is to ensure that, the way I'm proceeding is right or not. Or is there any other better ways in python to implement the same.</p> <p>Python veterans, please guide !</p>
1
2016-07-23T09:27:23Z
38,541,926
<p>From <a href="https://docs.python.org/3.4/using/cmdline.html#cmdoption-X" rel="nofollow">the docs on -X args</a></p> <blockquote> <p>Reserved for various implementation-specific options. CPython currently defines the following possible values:</p> </blockquote> <p>That means you probably shouldn't be hijacking these for your own purposes. As Kristof mentioned, argparse is a pretty reasonable choice. Since you want both a file and command line arguments, here's a quick example using a <code>json</code> file-based config:</p> <pre><code>import json import argparse argparser = argparse.ArgumentParser() argparser.add_argument('--environment') argparser.add_argument('--toggle', action='store_true') try: with open('config.json') as f: args = json.load(f) except (IOError, ValueError) as e: # If the file doesn't exist or has invalid JSON args = {} args.update(vars(argparser.parse_args())) print(args) </code></pre> <p>There are other possible alternatives for the file-based config, like the <a href="https://docs.python.org/3/library/configparser.html" rel="nofollow">configparser</a> module.</p>
0
2016-07-23T12:43:33Z
[ "python", "python-2.7", "python-3.x" ]
(flask) python mysql - how to pass selected data though a for loop and return it?
38,540,256
<p>In my Flask project, I want to select everything from a table in database and print each row in separate line?</p> <p>How should I pass data through a for loop in this script below?</p> <p>And how can I return it?</p> <p>In app.py:</p> <pre><code>from flask import Flask, render_template import MySQLdb app = Flask(__name__) @app.route('/') def db(): db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" ) cursor = db.cursor() cursor.execute("SELECT * from p_user") cursor.fetchall() db.close() return if __name__ == '__main__': app.run() </code></pre> <p>===============================================</p> <p>Even this try didn't work.</p> <p>I edited 2 lines in app.py like this:</p> <pre><code>data = str(cursor.fetchall()) return render_template('db.html', data = data) </code></pre> <p>And created db.html like this:</p> <pre><code>{% for each in data %} print {{ each }}&lt;br&gt; {% endfor %} </code></pre> <p>And the output was:</p> <pre><code>print ( print ( print 1 print , print print ' print s print h .... </code></pre> <p>There is a list of tuples, how I can reach each index.</p>
0
2016-07-23T09:30:55Z
38,540,354
<p>Try something like this:</p> <pre><code>row=cursor.fetchone() while row is not None: print row # you can access to each column by looping over row # for column in row: # print row row=cursor.fetchone() </code></pre>
0
2016-07-23T09:43:48Z
[ "python", "mysql", "select", "flask", "connection" ]
(flask) python mysql - how to pass selected data though a for loop and return it?
38,540,256
<p>In my Flask project, I want to select everything from a table in database and print each row in separate line?</p> <p>How should I pass data through a for loop in this script below?</p> <p>And how can I return it?</p> <p>In app.py:</p> <pre><code>from flask import Flask, render_template import MySQLdb app = Flask(__name__) @app.route('/') def db(): db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" ) cursor = db.cursor() cursor.execute("SELECT * from p_user") cursor.fetchall() db.close() return if __name__ == '__main__': app.run() </code></pre> <p>===============================================</p> <p>Even this try didn't work.</p> <p>I edited 2 lines in app.py like this:</p> <pre><code>data = str(cursor.fetchall()) return render_template('db.html', data = data) </code></pre> <p>And created db.html like this:</p> <pre><code>{% for each in data %} print {{ each }}&lt;br&gt; {% endfor %} </code></pre> <p>And the output was:</p> <pre><code>print ( print ( print 1 print , print print ' print s print h .... </code></pre> <p>There is a list of tuples, how I can reach each index.</p>
0
2016-07-23T09:30:55Z
38,540,504
<p>Normally, <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchall.html" rel="nofollow"><code>cursor.fetchall()</code></a> returns a list of tuples, so just save that list into a variable and <code>return</code> it, then loop through the returned value, this way</p> <pre><code>@app.route('/') def db(): db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" ) cursor = db.cursor() cursor.execute("SELECT * from p_user") rows = cursor.fetchall() db.close() return rows rows = db() for row in rows: print(row) </code></pre> <p>Or even simply and efficiently (by saving memory if you have a huge table) without calling <code>cursor.fetchall</code> at all:</p> <pre><code>@app.route('/') def db(): db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" ) cursor = db.cursor() cursor.execute("SELECT * from p_user") rows = [] for row in cursor: rows.append(row) print(row) return rows </code></pre> <p>EDIT:</p> <p>No need to <code>str</code> the results, just pass them as they are(list of tuples) to your template, this way:</p> <pre><code>data = cursor.fetchall() return render_template('db.html', data = data) </code></pre> <p>And your template should look like:</p> <pre><code>&lt;table border="1" cellpadding="5" cellspacing="5"&gt; {% for row in data %} &lt;tr&gt; {% for d in row %} &lt;td&gt;{{ d }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>This should print them as a table.</p>
1
2016-07-23T10:03:09Z
[ "python", "mysql", "select", "flask", "connection" ]
(flask) python mysql - how to pass selected data though a for loop and return it?
38,540,256
<p>In my Flask project, I want to select everything from a table in database and print each row in separate line?</p> <p>How should I pass data through a for loop in this script below?</p> <p>And how can I return it?</p> <p>In app.py:</p> <pre><code>from flask import Flask, render_template import MySQLdb app = Flask(__name__) @app.route('/') def db(): db = MySQLdb.connect("localhost","myusername","mypassword","mydbname" ) cursor = db.cursor() cursor.execute("SELECT * from p_user") cursor.fetchall() db.close() return if __name__ == '__main__': app.run() </code></pre> <p>===============================================</p> <p>Even this try didn't work.</p> <p>I edited 2 lines in app.py like this:</p> <pre><code>data = str(cursor.fetchall()) return render_template('db.html', data = data) </code></pre> <p>And created db.html like this:</p> <pre><code>{% for each in data %} print {{ each }}&lt;br&gt; {% endfor %} </code></pre> <p>And the output was:</p> <pre><code>print ( print ( print 1 print , print print ' print s print h .... </code></pre> <p>There is a list of tuples, how I can reach each index.</p>
0
2016-07-23T09:30:55Z
38,544,717
<p>Use an ORM like Flask-SQLAlchemy, Define your table using the model class and then use it to fetch data</p> <pre><code>class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(128)) body = db.Column(db.Text) def __init__(self, title, body): self.title = title self.body = body @app.route('/' ) def index(): post = Post.query.all() </code></pre> <p>return render_template('index.html', post=post)</p> <p>There is great example at <a href="https://techarena51.com/index.php/flask-sqlalchemy-tutorial/" rel="nofollow">https://techarena51.com/index.php/flask-sqlalchemy-tutorial/</a></p>
0
2016-07-23T17:38:03Z
[ "python", "mysql", "select", "flask", "connection" ]
Access only links with given format from a python list
38,540,391
<p>I have written a code that fetches the html code of any given site and then fetch all links from it and save it inside a list. My goal is that I want to change all the relative links in html file with absolute links. </p> <p>Here are the links:</p> <pre><code>src="../styles/scripts/jquery-1.9.1.min.js" href="/PhoneBook.ico" href="../css_responsive/fontsss.css" src="http://www.google.com/adsense/search/ads.js" L.src = '//www.google.com/adsense/search/async-ads.js' href="../../" src='../../images/plus.png' vrUrl ="search.aspx?searchtype=cat" </code></pre> <p>These are few links that I have copied from html file to keep the question simple and less error prone. </p> <p>Following are the different URLs used in html file:</p> <blockquote> <pre><code>http://yourdomain.com/images/example.png //yourdomain.com/images/example.png /images/example.png images/example.png ../images/example.png ../../images/example.png </code></pre> </blockquote> <p>Python code:</p> <pre><code>linkList = re.findall(re.compile(u'(?&lt;=href=").*?(?=")|(?&lt;=href=\').*?(?=\')|(?&lt;=src=").*?(?=")|(?&lt;=src=\').*?(?=\')|(?&lt;=action=").*?(?=")|(?&lt;=vrUrl =").*?(?=")|(?&lt;=\')//.*?(?=\')'), str(html)) newLinks = [] for link1 in linkList: if (link1.startswith("//")): newLinks.append(link1) elif (link1.startswith("../")): newLinks.append(link1) elif (link1.startswith("../../")): newLinks.append(link1) elif (link1.startswith("http")): newLinks.append(link1) elif (link1.startswith("/")): newLinks.append(link1) else: newLinks.append(link1) </code></pre> <p>At this point what happens is when it comes to second condition which is "../" it gives me all the urls which starts with "../" as well as "../../". This is the behavior which I don't need. Same goes for "/"; it also fetches urls starting with "//". I also tried to used the beginning and end parameters of "startswith" function but that doesn't solve the issue.</p>
0
2016-07-23T09:47:44Z
38,551,020
<p>How about using <code>str.count</code> method:</p> <pre><code>&gt;&gt;&gt; src="../styles/scripts/jquery-1.9.1.min.js" &gt;&gt;&gt; src2='../../images/plus.png' &gt;&gt;&gt; src.count('../') 1 &gt;&gt;&gt; src2.count('../') 2 </code></pre> <p>This seems to be true as <code>../</code> only exists at the beginning of urls</p>
1
2016-07-24T10:25:59Z
[ "python", "html", "regex", "python-3.x" ]
Difficulties with my python tic-tac-toe
38,540,394
<p>I am following Charles Dierbach's book, Introduction to Computer Science using Python.</p> <p>I am on chapter 5. I am trying to do this exercise on tic-tac-toe automate play.</p> <p>I am having difficulties creating a function for the pc to select an empty box ([]). </p> <p>Here is my code</p> <pre><code>import re import random def template(): mylst = list() for i in range(0, 3): my_temp = [] for j in range(0, 3): my_temp.append([]) mylst.append(my_temp) return mylst def template_2(alst): print() al = ("A", "B", "C") for a in al: if a == "A": print (format(a, "&gt;6"), end="") if a == "B": print (format(a, "&gt;5"), end="") if a == "C": print (format(a, "&gt;5"), end="") print() for j in range(len(alst)): print(str(j + 1), format( " ", "&gt;1"), end="") print(alst[j]) print() def print_template(alst): print() al = ("A", "B", "C") for a in al: if a == "A": print (format(a, "&gt;6"), end="") if a == "B": print (format(a, "&gt;4"), end="") if a == "C": print (format(a, "&gt;3"), end="") print() for j in range(len(alst)): print(str(j + 1), format( " ", "&gt;1"), end="") print(alst[j]) print() def first_player(lst): print() print ("Your symbol is 'X'. ") alpha = ("A", "B", "C") #check it was entered correctly check = True temp_lst1 = [] while check: correct_entry = False while not correct_entry: coord = input("Please enter your coordinates ") player_regex = re.compile(r'(\w)(\d)') aSearch = player_regex.search(coord) if aSearch == None: correct_entry = False if aSearch.group(1) != "A" or aSearch.group(1) != "B" or aSearch.group(1) != "C" or aSearch.group(2) != 1 or aSearch.group(2) == 2 or aSearch.group(3) != 3: correct_entry = False if aSearch.group(1) == "A" or aSearch.group(1) == "B" or aSearch.group(1) == "C" or aSearch.group(2) == 1 or aSearch.group(2) == 2 or aSearch.group(3) == 3: correct_entry = True else: correct_entry = True blank = False while not blank: if lst[(int(coord[-1])) - 1][alpha.index(coord[0])] == []: lst[(int(coord[-1])) - 1][alpha.index(coord[0])] = "X" temp_lst1.append((int(coord[-1])-1)) temp_lst1.append((alpha.index(coord[0]))) blank = True else: blank = True correct_entry = False if blank == True and correct_entry == True: check = False return True def pc_player(lst): print() print ("PC symbol is 'O'. ") alpha = ("A", "B", "C") num_list = (0, 1, 2) for i in range(0, len(lst)): for j in range(0, len(lst[i])): if lst[i][j] ==[]: lst[i][j] = "O" break break return True def check_1st_player(lst): if lst[0][0] == "X" and lst[0][1] == "X" and lst[0][2] == "X": return True elif lst[1][0] == "X" and lst[1][1] == "X" and lst[1][2] == "X": return True elif lst[2][0] == "X" and lst[2][1] == "X" and lst[2][2] == "X": return True elif lst[0][0] == "X" and lst[1][0] == "X" and lst[2][0] == "X": return True elif lst[0][1] == "X" and lst[1][1] == "X" and lst[2][1] == "X": return True elif lst[0][2] == "X" and lst[1][2] == "X" and lst[2][2] == "X": return True elif lst[0][0] == "X" and lst[1][1] == "X" and lst[2][2] == "X": return True elif lst[2][0] == "X" and lst[1][1] == "X" and lst[0][2] == "X": return True else: return False def check_pc_player(lst): if lst[0][0] == "O" and lst[0][1] == "O" and lst[0][2] == "O": return True elif lst[1][0] == "O" and lst[1][1] == "O" and lst[1][2] == "O": return True elif lst[2][0] == "O" and lst[2][1] == "O" and lst[2][2] == "O": return True elif lst[0][0] == "O" and lst[1][0] == "O" and lst[2][0] == "O": return True elif lst[0][1] == "O" and lst[1][1] == "O" and lst[2][1] == "O": return True elif lst[0][2] == "O" and lst[1][2] == "O" and lst[2][2] == "O": return True elif lst[0][0] == "O" and lst[1][1] == "O" and lst[2][2] == "O": return True elif lst[2][0] == "O" and lst[1][1] == "O" and lst[0][2] == "O": return True else: return False def play_game(): ask = input("Do you want to play a two player game of Tic-Tac-Toe game? (y/n) ") if ask in yes_response: # contruct the template for tic-tac-toe print() print("How many rounds do you want to play? " ) print("Please enter only odd integers" ) print("Please enter your coordinates", end="") print(" using format A1 or B2") print("New Round") return True def play_again(): tell_me = input("Do you want you play a game ? (y/n)") if tell_me == "Y" or "y": return True else: return False def is_full(lst): count = 0 for i in lst: for j in i: if j != []: count += 1 if count == 9: return True # #-- main print("Welcome to Awesome 2 Player Tic-Tac-Toe Game? ") print() answer = False yes_response =("Y", "y") no_response = ("N", "n") while not answer: print("Enter an even integer to exit") ask = int(input("How many matches do you want to play? (odd integers only)? " )) game = play_game() structure = template() print_template(structure) if ask % 2 == 1: score_player1 = 0 score_pc = 0 count = 0 while count &lt; ask: pc_lst = [] if count &gt;= 1: structure = template() print_template(structure) while game: check_pc = True while check_pc: pc_player(structure) template_2(structure) check_pc = False check_pc_winner = True while check_pc_winner: game_pc = check_pc_player(structure) check_pc_winner = False if game_pc == True: print("Congratulations PC won") score_pc += 1 game = False break check_player1 = True while check_player1: first_player(structure) template_2(structure) check_player1 = False check_first_winner = True while check_first_winner: game_first = check_1st_player(structure) check_first_winner = False if game_first == True: print("Congratulations Player 1 won") score_player1 += 1 game = False break board_full = False while not board_full: check_board = is_full(structure) board_full = True if check_board == True: print("This round was a tie.") game = False print("Player 1 : ", score_player1, " PC : ", score_pc) count += 1 game = True if score_player1 &gt; score_pc: print("Player 1 won") elif score_player1 &lt; score_pc: print("PC won") if play_again() == False: answer = True else: answer = False </code></pre> <p>The problem I have is at <code>def pc_player():</code></p> <p>I would like to know how to loop the list and sublists so that AI can select an empty box as its choice to place an "O"</p> <p>My current for loop does not work. AI only selects the first box. </p>
0
2016-07-23T09:48:23Z
38,540,616
<blockquote> <p>My current for loop does not work. AI only selects the first box.</p> </blockquote> <p>I suppose you refer to this part:</p> <pre><code>def pc_player(lst): print() print ("PC symbol is 'O'. ") alpha = ("A", "B", "C") num_list = (0, 1, 2) for i in range(0, len(lst)): for j in range(0, len(lst[i])): if lst[i][j] ==[]: lst[i][j] = "O" break break return True </code></pre> <p>The <code>break</code> instructions together with the way you initialize the <code>for</code> loops will only attempt to set <code>lst[0][0]</code>. Other cells are not considered.</p> <p>To make an evenly distributed random choice, it is essential to gather the possibilities first. For this, it is convenient to have all cells in a plain list first:</p> <pre><code>from itertools import chain all_cells = list(chain.from_iterable(lst)) </code></pre> <p>Then, you can filter out non-empty cells:</p> <pre><code>empty_cells = filter(lambda l: len(l) == 0, all_cells) # empty_cells = filter(lambda l: not l, all_cells) # empty_cells = [cell for cell in all_cells if not cell] </code></pre> <p>Based on this you can now trigger your random selection and symbol placement:</p> <pre><code>import random cell_to_place = random.choice(empty_cells) cell_to_place.append('O') </code></pre> <hr> <p>If you need the index of the cell being modified, you can do the following:</p> <pre><code>import itertools indices = list(itertools.product(range(3), range(3))) indexed_cells = zip(indices, map(lambda (i, j): lst[i][j], indices)) indexed_cells = filter(lambda (_, l): not l, indexed_cells) # filter non-empty (i,j), cell_to_place = random.choice(indexed_cells) # ... </code></pre> <hr> <p>These code samples <em>do not</em> take into account that there could be no empty cell left. Also, your code has some general design issues. For example:</p> <ul> <li>Why do you use lists as cell items in the first place? You could simply use <code>None</code>, <code>'X'</code> and <code>'O'</code> as the elements of the 2-dimensional list.</li> <li><code>check_pc_player</code> and <code>check_1st_player</code> can be easily generalized by making the symbol to check for a parameter of the function.</li> <li><p>Why is this a while-loop?</p> <pre><code> while check_first_winner: game_first = check_1st_player(structure) check_first_winner = False </code></pre></li> </ul>
1
2016-07-23T10:15:22Z
[ "python", "function", "for-loop", "artificial-intelligence", "tic-tac-toe" ]
Difficulties with my python tic-tac-toe
38,540,394
<p>I am following Charles Dierbach's book, Introduction to Computer Science using Python.</p> <p>I am on chapter 5. I am trying to do this exercise on tic-tac-toe automate play.</p> <p>I am having difficulties creating a function for the pc to select an empty box ([]). </p> <p>Here is my code</p> <pre><code>import re import random def template(): mylst = list() for i in range(0, 3): my_temp = [] for j in range(0, 3): my_temp.append([]) mylst.append(my_temp) return mylst def template_2(alst): print() al = ("A", "B", "C") for a in al: if a == "A": print (format(a, "&gt;6"), end="") if a == "B": print (format(a, "&gt;5"), end="") if a == "C": print (format(a, "&gt;5"), end="") print() for j in range(len(alst)): print(str(j + 1), format( " ", "&gt;1"), end="") print(alst[j]) print() def print_template(alst): print() al = ("A", "B", "C") for a in al: if a == "A": print (format(a, "&gt;6"), end="") if a == "B": print (format(a, "&gt;4"), end="") if a == "C": print (format(a, "&gt;3"), end="") print() for j in range(len(alst)): print(str(j + 1), format( " ", "&gt;1"), end="") print(alst[j]) print() def first_player(lst): print() print ("Your symbol is 'X'. ") alpha = ("A", "B", "C") #check it was entered correctly check = True temp_lst1 = [] while check: correct_entry = False while not correct_entry: coord = input("Please enter your coordinates ") player_regex = re.compile(r'(\w)(\d)') aSearch = player_regex.search(coord) if aSearch == None: correct_entry = False if aSearch.group(1) != "A" or aSearch.group(1) != "B" or aSearch.group(1) != "C" or aSearch.group(2) != 1 or aSearch.group(2) == 2 or aSearch.group(3) != 3: correct_entry = False if aSearch.group(1) == "A" or aSearch.group(1) == "B" or aSearch.group(1) == "C" or aSearch.group(2) == 1 or aSearch.group(2) == 2 or aSearch.group(3) == 3: correct_entry = True else: correct_entry = True blank = False while not blank: if lst[(int(coord[-1])) - 1][alpha.index(coord[0])] == []: lst[(int(coord[-1])) - 1][alpha.index(coord[0])] = "X" temp_lst1.append((int(coord[-1])-1)) temp_lst1.append((alpha.index(coord[0]))) blank = True else: blank = True correct_entry = False if blank == True and correct_entry == True: check = False return True def pc_player(lst): print() print ("PC symbol is 'O'. ") alpha = ("A", "B", "C") num_list = (0, 1, 2) for i in range(0, len(lst)): for j in range(0, len(lst[i])): if lst[i][j] ==[]: lst[i][j] = "O" break break return True def check_1st_player(lst): if lst[0][0] == "X" and lst[0][1] == "X" and lst[0][2] == "X": return True elif lst[1][0] == "X" and lst[1][1] == "X" and lst[1][2] == "X": return True elif lst[2][0] == "X" and lst[2][1] == "X" and lst[2][2] == "X": return True elif lst[0][0] == "X" and lst[1][0] == "X" and lst[2][0] == "X": return True elif lst[0][1] == "X" and lst[1][1] == "X" and lst[2][1] == "X": return True elif lst[0][2] == "X" and lst[1][2] == "X" and lst[2][2] == "X": return True elif lst[0][0] == "X" and lst[1][1] == "X" and lst[2][2] == "X": return True elif lst[2][0] == "X" and lst[1][1] == "X" and lst[0][2] == "X": return True else: return False def check_pc_player(lst): if lst[0][0] == "O" and lst[0][1] == "O" and lst[0][2] == "O": return True elif lst[1][0] == "O" and lst[1][1] == "O" and lst[1][2] == "O": return True elif lst[2][0] == "O" and lst[2][1] == "O" and lst[2][2] == "O": return True elif lst[0][0] == "O" and lst[1][0] == "O" and lst[2][0] == "O": return True elif lst[0][1] == "O" and lst[1][1] == "O" and lst[2][1] == "O": return True elif lst[0][2] == "O" and lst[1][2] == "O" and lst[2][2] == "O": return True elif lst[0][0] == "O" and lst[1][1] == "O" and lst[2][2] == "O": return True elif lst[2][0] == "O" and lst[1][1] == "O" and lst[0][2] == "O": return True else: return False def play_game(): ask = input("Do you want to play a two player game of Tic-Tac-Toe game? (y/n) ") if ask in yes_response: # contruct the template for tic-tac-toe print() print("How many rounds do you want to play? " ) print("Please enter only odd integers" ) print("Please enter your coordinates", end="") print(" using format A1 or B2") print("New Round") return True def play_again(): tell_me = input("Do you want you play a game ? (y/n)") if tell_me == "Y" or "y": return True else: return False def is_full(lst): count = 0 for i in lst: for j in i: if j != []: count += 1 if count == 9: return True # #-- main print("Welcome to Awesome 2 Player Tic-Tac-Toe Game? ") print() answer = False yes_response =("Y", "y") no_response = ("N", "n") while not answer: print("Enter an even integer to exit") ask = int(input("How many matches do you want to play? (odd integers only)? " )) game = play_game() structure = template() print_template(structure) if ask % 2 == 1: score_player1 = 0 score_pc = 0 count = 0 while count &lt; ask: pc_lst = [] if count &gt;= 1: structure = template() print_template(structure) while game: check_pc = True while check_pc: pc_player(structure) template_2(structure) check_pc = False check_pc_winner = True while check_pc_winner: game_pc = check_pc_player(structure) check_pc_winner = False if game_pc == True: print("Congratulations PC won") score_pc += 1 game = False break check_player1 = True while check_player1: first_player(structure) template_2(structure) check_player1 = False check_first_winner = True while check_first_winner: game_first = check_1st_player(structure) check_first_winner = False if game_first == True: print("Congratulations Player 1 won") score_player1 += 1 game = False break board_full = False while not board_full: check_board = is_full(structure) board_full = True if check_board == True: print("This round was a tie.") game = False print("Player 1 : ", score_player1, " PC : ", score_pc) count += 1 game = True if score_player1 &gt; score_pc: print("Player 1 won") elif score_player1 &lt; score_pc: print("PC won") if play_again() == False: answer = True else: answer = False </code></pre> <p>The problem I have is at <code>def pc_player():</code></p> <p>I would like to know how to loop the list and sublists so that AI can select an empty box as its choice to place an "O"</p> <p>My current for loop does not work. AI only selects the first box. </p>
0
2016-07-23T09:48:23Z
38,540,617
<p>Start by finding all empty boxes:</p> <pre><code>empty= [(i,j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j]==[]] </code></pre> <p>Then choose a random one:</p> <pre><code>import random chosen_i, chosen_j= random.choice(empty) </code></pre> <p>And finally put an <code>O</code> there:</p> <pre><code>lst[chosen_i][chosen_j]= 'O' </code></pre>
0
2016-07-23T10:15:35Z
[ "python", "function", "for-loop", "artificial-intelligence", "tic-tac-toe" ]
Overwrite previous output in jupyter notebook
38,540,395
<p>Let's assume I have a part of code that runs for some specific amount of time and each 1 second outputs something like this: <code>iteration X, score Y</code>. I will substitute this function with my black box function:</p> <pre><code>from random import uniform import time def black_box(): i = 1 while True: print 'Iteration', i, 'Score:', uniform(0, 1) time.sleep(1) i += 1 </code></pre> <p>Now when I run it in <a href="https://tmp55.tmpnb.org/user/tqEpj95wJzL3/tree" rel="nofollow">Jupyter notebook</a>, it output a new line after each second:</p> <pre><code>Iteration 1 Score: 0.664167449844 Iteration 2 Score: 0.514757592404 ... </code></pre> <p>Yes, after when the output becomes too big, the html becomes scrollable, but the thing is that I do not need any of these lines except of currently the last one. So instead of having <code>n</code> lines after <code>n</code> seconds, I want to have only <code>1</code> line (the last one) shown. </p> <p>I have not found anything like this in documentation or looking through magic. <a href="http://stackoverflow.com/questions/37956788/how-to-overwrite-the-previous-print-line-in-jupyter-ipython">A question</a> with almost the same title but irrelevant.</p>
2
2016-07-23T09:48:28Z
38,541,614
<p>The usual (documented) way to do what you describe (that only works with Python 3) is:</p> <pre><code>print('Iteration', i, 'Score:', uniform(0, 1), end='\r') </code></pre> <p>In Python 2 we have to <code>sys.stdout.flush()</code> after the print, as it shows in this <a href="http://stackoverflow.com/a/11018255/2757226">answer</a>:</p> <pre><code>print('Iteration', i, 'Score:', uniform(0, 1), end='\r') sys.stdout.flush() </code></pre> <p>Using IPython notebook I had to concatenate the string to make it work:</p> <pre><code>print('Iteration ' + str(i) + ', Score: ' + str(uniform(0, 1)), end='\r') </code></pre> <p>And finally, to make it work with Jupyter, I used this:</p> <pre><code>print('\r', 'Iteration', i, 'Score:', uniform(0, 1), end='') </code></pre> <p>Or you could split the <code>print</code>s before and after the <code>time.sleep</code> if it makes more sense, or you need to be more explicit:</p> <pre><code>print('Iteration', i, 'Score:', uniform(0, 1), end='') time.sleep(1) print('', end='\r') # or even print('\r', end='') </code></pre>
1
2016-07-23T12:07:12Z
[ "python", "jupyter", "jupyter-notebook" ]
Why do python Subprocess.stdin.write() kill PyQt Gui
38,540,410
<p>I have a PyQt5 app that need to write input for the subprocess to stop.</p> <p>However it also kills my PyQt5 <code>Mainwindow</code>, if input button is used without using subprocess button first.</p> <p>If i use subprocess button first, and then use input button , with <code>self.bob.stdin.write("b")</code> app stays open, but if i press input button first without pressing subprocess button <code>self.bob.stdin.write("b")</code> it kills my app and Mainwindow.</p> <p>So why do <code>self.bob.stdin.write("b")</code> kill app ,and how do i stop it from killing my MainWindow, if i press input button first ?</p> <p>The dilemma can be seen in this test code.</p> <pre class="lang-py prettyprint-override"><code>from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(308, 156) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.Button_2 = QtWidgets.QPushButton(self.centralwidget) self.Button_2.setGeometry(QtCore.QRect(20, 40, 121, 71)) self.Button_2.setObjectName("subprocessButton_2") self.Button_1 = QtWidgets.QPushButton(self.centralwidget) self.Button_1.setGeometry(QtCore.QRect(170, 40, 121, 71)) self.Button_1.setObjectName("inputbutton") MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate self.Button_2.setText(_translate("MainWindow", "subprocess")) self.Button_1.setText(_translate("MainWindow", "input")) self.Button_2.clicked.connect(self.sub) self.Button_1.clicked.connect(self.input) def sub(self): import subprocess from subprocess import Popen, PIPE from subprocess import Popen, PIPE self.bob = subprocess.Popen('cmd ',stdin=PIPE, shell=True) def input(self): self.bob.stdin.write("q") if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre>
0
2016-07-23T09:50:53Z
38,540,547
<p>Without understanding all your code, here's what I think your code converted into a script does:</p> <pre><code>import subprocess from subprocess import Popen, PIPE # sub button handler bob = subprocess.Popen('echo',stdin=PIPE, shell=True) # input button handler bob.stdin.write(b"text") </code></pre> <p>I'll let you think about what hapens when you don't do step 1.</p>
0
2016-07-23T10:08:11Z
[ "python", "pyqt", "subprocess" ]
Python N-body simulation code giving incorrect answer
38,540,415
<p>I have written some python code to solve the N-body problem using the Euler method. The code runs without problems and seems to give a reasonable answer (e.g. if there are two particles then the start moving towards each other). However when I run this simulation over a large number of iterations I see that the particles (say I run it with two particles) pass by each other (I do not consider collisions) and keep going in their directions indefinitely. This violates the conservation of energy and so there must be a flaw in my code but I am unable to find it. Could anyone please find it and explain my mistake.</p> <p>Thank you.</p> <p>Thanks to @samgak for pointing out that I was updating the particles twice. I have now fixed this but the problem still keeps coming. I have also replicated the output I get when I run this simulation with two stationary particles at (0,0) and (1,0) with a time step of 1 second and 100000 iterations:</p> <p>Particle with mass: 1 and position: [234.8268420043934, 0.0] and velocity: [0.011249111128594091, 0.0]</p> <p>Particle with mass: 1 and position: [-233.82684200439311, 0.0] and velocity: [-0.011249111128594091, 0.0]</p> <p>Also thanks to @PM2Ring for pointing out some optimizations I could make and the perils of using the Euler method.</p> <p>Code:</p> <pre><code>import math class Particle: """ Class to represent a single particle """ def __init__(self,mass,position,velocity): """ Initialize the particle """ self.G = 6.67408*10**-11 #fixed throughout the simulation self.time_interval = 10**0 #fixed throughout the simulation, gives the interval between updates self.mass = mass self.position = position #should be a list self.velocity = velocity #should be a list self.updated_position = position self.updated_velocity = velocity def __str__(self): """ String representation of particle """ return "Particle with mass: " + str(self.mass) + " and position: " + str(self.position) + " and velocity: " + str(self.velocity) def get_mass(self): """ Returns the mass of the particle """ return self.mass def get_position(self): """ returns the position of the particle """ return self.position def get_velocity(self): """ returns the velocity of the particle """ return self.velocity def get_updated_position(self): """ calculates the future position of the particle """ for i in range(len(self.position)): self.updated_position[i] = self.updated_position[i] + self.time_interval*self.velocity[i] def update_position(self): """ updates the position of the particle """ self.position = self.updated_position.copy() def get_distance(self,other_particle): """ returns the distance between the particle and another given particle """ tot = 0 other = other_particle.get_position() for i in range(len(self.position)): tot += (self.position[i]-other[i])**2 return math.sqrt(tot) def get_updated_velocity(self,other_particle): """ updates the future velocity of the particle due to the acceleration by another particle """ distance_vector = [] other = other_particle.get_position() for i in range(len(self.position)): distance_vector.append(self.position[i]-other[i]) distance_squared = 0 for item in distance_vector: distance_squared += item**2 distance = math.sqrt(distance_squared) force = -self.G*self.mass*other_particle.get_mass()/(distance_squared) for i in range(len(self.velocity)): self.updated_velocity[i] = self.updated_velocity[i]+self.time_interval*force*(distance_vector[i])/(self.mass*(distance)) def update_velocity(self): """ updates the velocity of the particle """ self.velocity = self.updated_velocity.copy() def update_particles(particle_list): """ updates the position of all the particles """ for i in range(len(particle_list)): for j in range(i+1,len(particle_list)): particle_list[i].get_updated_velocity(particle_list[j]) particle_list[j].get_updated_velocity(particle_list[i]) for i in range(len(particle_list)): particle_list[i].update_velocity() particle_list[i].get_updated_position() for i in range(len(particle_list)): particle_list[i].update_position() #the list of particles partList = [Particle(1,[0,0],[0,0]),Particle(1,[1,0],[0,0])] #how many iterations I perform for i in range(100000): update_particles(partList) #prints out the final position of all the particles for item in partList: print(item) </code></pre> <p>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Further Edit:</p> <p>I decided to implement the Leapfrog method and I have developed some code that once again runs and seems to work well (at least in the command line). However when I added plotting functionality and analysed it there seemed to be another problem. Again the system seemed to go too far and the energy again increased without bound. I have attached a picture of the output I get to showcase the problem. If I again had just two particles of equal mass they again pass each other and continue away from each other without stopping. Thus there must be a bug in my code I am not finding.</p> <p>If anyone can help it will be much appreciated.</p> <p>My Code:</p> <pre><code>import math import matplotlib.pyplot as plt class Particle: """ Represents a single particle """ def __init__(self,mass,position,velocity): """ Initialize the particle """ self.G = 6.67408*10**-11 self.time_step = 10**2 self.mass = mass self.dimensions = len(position) self.position = position self.velocity = velocity self.acceleration = [0 for i in range(len(position))] self.next_position = position self.next_velocity = velocity self.next_acceleration = [0 for i in range(len(position))] def __str__(self): """ A string representation of the particle """ return "A Particle with mass: " + str(self.mass) + " and position: " + str(self.position) + " and velocity:" + str(self.velocity) def get_mass(self): return self.mass def get_position(self): return self.position def get_velocity(self): return self.velocity def get_acceleration(self): return self.acceleration def get_next_position(self): return self.next_position def put_next_position(self): for i in range(self.dimensions): self.next_position[i] = self.position[i] + self.time_step*self.velocity[i]+0.5*self.time_step**2*self.acceleration[i] def put_next_velocity(self): for i in range(self.dimensions): self.next_velocity[i] = self.velocity[i] + 0.5*self.time_step*(self.acceleration[i]+self.next_acceleration[i]) def update_position(self): self.position = self.next_position.copy() def update_velocity(self): self.velocity = self.next_velocity.copy() def update_acceleration(self): self.acceleration = self.next_acceleration.copy() def reset_acceleration(self): self.acceleration = [0 for i in range(self.dimensions)] def reset_future_acceleration(self): self.next_acceleration = [0 for i in range(self.dimensions)] def calculate_acceleration(self,other_particle): """ Increments the acceleration of the particle due to the force from a single other particle """ distances = [] other = other_particle.get_position() distance_squared = 0 for i in range(self.dimensions): distance_squared += (self.position[i]-other[i])**2 distances.append(self.position[i]-other[i]) distance = math.sqrt(distance_squared) force = -self.G*self.mass*other_particle.get_mass()/distance_squared acc = [] for i in range(self.dimensions): acc.append(force*distances[i]/(distance*self.mass)) for i in range(self.dimensions): self.acceleration[i] += acc[i] def calculate_future_acceleration(self,other_particle): """ Increments the future acceleration of the particle due to the force from a single other particle """ distances = [] other = other_particle.get_next_position() distance_squared = 0 for i in range(self.dimensions): distance_squared += (self.next_position[i]-other[i])**2 distances.append(self.next_position[i]-other[i]) distance = math.sqrt(distance_squared) force = -self.G*self.mass*other_particle.get_mass()/distance_squared acc = [] for i in range(self.dimensions): acc.append(force*distances[i]/(distance*self.mass)) for i in range(self.dimensions): self.next_acceleration[i] += acc[i] def update_all(particleList): for i in range(len(particleList)): particleList[i].reset_acceleration() for j in range(len(particleList)): if i != j: particleList[i].calculate_acceleration(particleList[j]) for i in range(len(particleList)): particleList[i].put_next_position() for i in range(len(particleList)): particleList[i].reset_future_acceleration() for j in range(len(particleList)): if i != j: particleList[i].calculate_future_acceleration(particleList[j]) for i in range(len(particleList)): particleList[i].put_next_velocity() for i in range(len(particleList)): particleList[i].update_position() particleList[i].update_velocity() partList = [Particle(1,[0,0],[0,0]),Particle(1,[1,0],[0,0])] Alist = [[],[]] Blist = [[],[]] for i in range(10000): Alist[0].append(partList[0].get_position()[0]) Alist[1].append(partList[0].get_position()[1]) Blist[0].append(partList[1].get_position()[0]) Blist[1].append(partList[1].get_position()[1]) update_all(partList) plt.scatter(Alist[0],Alist[1],color="r") plt.scatter(Blist[0],Blist[1],color="b") plt.grid() plt.show() for item in partList: print(item) </code></pre> <p><a href="http://i.stack.imgur.com/0PHtE.png" rel="nofollow"><img src="http://i.stack.imgur.com/0PHtE.png" alt="A zoomed in plot"></a> </p> <p>Could someone please tell me where is the error I am making in my code.</p>
4
2016-07-23T09:51:29Z
38,541,134
<p>The main problem in the code is that it uses the Euler method which is quite inaccurate as the number of iterations increase (just O(h) compared to other methods which can be O(h^4) or even better). To fix this would require a fundamental restructure of the code and so I would say that this code is not really accurate for an N-body simulation (it plays up for 2 particles, as I add more and more the error can only increase). </p> <p>Thanks to @samgak and @PM2Ring for helping me remove a bug and optimize my code but overall this code is unusable...</p> <p>EDIT: I have implemented the leapfrog method mentioned in the comments from scratch and have found it to work perfectly. It is very simple to understand and implement and it works too!</p> <p>Further EDIT: I thought I had the leapfrog method working. Turns out that there was another bug in it I only saw when I added GUI functionality.</p>
1
2016-07-23T11:14:54Z
[ "python", "matplotlib", "physics" ]
Open Power Shell as Admin on remote VM
38,540,424
<p>I have a python that uses pyvmomi library of VMWare to perform operations on remote VM. I open the remote VM cmd prompt using Pyvmomi library like this </p> <pre><code>vim.vm.guest.ProcessManager.ProgramSpec( programPath="C:\\Windows\\System32\\cmd.exe") </code></pre> <p>Is there any way to open Power Shell as Admin or any code that can be added in the script to run it as Admin.</p>
0
2016-07-23T09:52:17Z
38,546,433
<p>You have to run the powershell script as administrator:</p> <p><a href="http://stackoverflow.com/a/25247612/1763602">http://stackoverflow.com/a/25247612/1763602</a></p> <p>You can create another script that will launch your script with elevated privileges.</p>
0
2016-07-23T21:08:11Z
[ "python", "windows", "powershell", "admin", "pyvmomi" ]
picking dl directory w/ youtube_dl
38,540,473
<p>Using youtube_dl, I'm writing an interface tool that downloads video.</p> <p>I import youtube_dl and run,</p> <pre><code>with youtube_dl.YoutubeDL(opts) as ydl: ydl.download([address]) </code></pre> <p>However I remain uncertain as to how I specify download directory using youtube_dl alone. What is the option or command framed for Python</p>
0
2016-07-23T09:59:10Z
38,540,830
<p>As documented in the <a href="https://github.com/rg3/youtube-dl/blob/master/README.md#embedding-youtube-dl" rel="nofollow">embedding instructions</a> of youtube-dl, you can find the list of all options in <a href="https://github.com/rg3/youtube-dl/blob/master/youtube_dl/YoutubeDL.py#L129-L279" rel="nofollow">YoutubeDL.py</a>.</p> <p>In your case, try</p> <pre><code>import youtube_dl address = 'http://www.youtube.com/watch?v=BaW_jenozKc' opts = { 'outtmpl': '/my/download/directory/%(title)s-%(id)s.%(ext)s', } with youtube_dl.YoutubeDL(opts) as ydl: ydl.download([address]) </code></pre> <p>Refer to the <a href="https://github.com/rg3/youtube-dl/blob/master/README.md#filesystem-options" rel="nofollow">documentation</a> for more information about <code>outtmpl</code>.</p>
1
2016-07-23T10:39:09Z
[ "python", "youtube-dl" ]
Anyone know how to set group volume in soco (python)?
38,540,517
<p>I am trying to set group volume in soco (python) for my Sonos speakers. It is straightforward to set individual speaker volume but I have not found any way to set volume on group level (without iterating through each speaker setting the volume individually). Any idea to do this?</p>
0
2016-07-23T10:04:11Z
38,955,622
<p>you can easily iterate over the group, and change all their volumes, for example to increate the volume on all speakers by 5:</p> <p>for each_speaker in my_zone.group: each_speaker.volume += 5</p> <p>(assuming my_zone is you speaker object)</p>
0
2016-08-15T13:02:54Z
[ "python", "sonos" ]
Determine protocol of the link using Python alternatives
38,540,629
<p>I need to find out the best way to determine what protocol is used to access a particular link. The input: string link address (starting with <code>protocol://...</code>)</p> <p>This is what I find the most convenient way to implement the necessary functionality:</p> <pre><code>def detectProtocol(url): ind = url.find("://") return url[0:ind] if (ind != -1) else 'default_prot' </code></pre> <p>Yet I'm interested what is the best way from the performance point of view. Maybe using <code>re</code> matching would be better? (but not that user friendly)</p> <p>Thanks in advance!</p> <p>P.S. If you have your very own alternatives you are welcome to share them </p>
2
2016-07-23T10:17:05Z
38,540,745
<p>You could use regex for that (<code>r'^[a-zA-Z]+://'</code>), and compile it before checking if it is valid or not.</p> <p>But you have a built-in functions for that:</p> <pre><code>import urlparse url = urlparse.urlparse('https://www.wwww.com') print url.scheme </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; https </code></pre>
1
2016-07-23T10:29:06Z
[ "python", "regex", "parsing" ]
Determine protocol of the link using Python alternatives
38,540,629
<p>I need to find out the best way to determine what protocol is used to access a particular link. The input: string link address (starting with <code>protocol://...</code>)</p> <p>This is what I find the most convenient way to implement the necessary functionality:</p> <pre><code>def detectProtocol(url): ind = url.find("://") return url[0:ind] if (ind != -1) else 'default_prot' </code></pre> <p>Yet I'm interested what is the best way from the performance point of view. Maybe using <code>re</code> matching would be better? (but not that user friendly)</p> <p>Thanks in advance!</p> <p>P.S. If you have your very own alternatives you are welcome to share them </p>
2
2016-07-23T10:17:05Z
38,541,040
<p>If you're looking for a cross-python version solution:</p> <pre><code>try: import urlparse except ImportError: import urllib.parse as urlparse url = urlparse.urlparse('https://www.example.com') print(url.scheme) </code></pre> <p>You can add <code>from __future__ import print_function</code> to the top of your script if you want print to be the same thing.</p>
1
2016-07-23T11:04:57Z
[ "python", "regex", "parsing" ]
Determine protocol of the link using Python alternatives
38,540,629
<p>I need to find out the best way to determine what protocol is used to access a particular link. The input: string link address (starting with <code>protocol://...</code>)</p> <p>This is what I find the most convenient way to implement the necessary functionality:</p> <pre><code>def detectProtocol(url): ind = url.find("://") return url[0:ind] if (ind != -1) else 'default_prot' </code></pre> <p>Yet I'm interested what is the best way from the performance point of view. Maybe using <code>re</code> matching would be better? (but not that user friendly)</p> <p>Thanks in advance!</p> <p>P.S. If you have your very own alternatives you are welcome to share them </p>
2
2016-07-23T10:17:05Z
38,541,042
<h1>Performance comparison</h1> <p>This comparison ignores stability of the functions used and other aspects like synergetic effects. <code>urlparse</code> for example provides more information than only the scheme and could hence be used to provide data for other needs.</p> <h3>Python 2.7.11+</h3> <pre><code>Testing detect_protocol_by_index 1.56482505798 Testing detect_protocol_by_urlparse 9.13317012787 Testing detect_protocol_by_regex 3.11044311523 </code></pre> <h3>Python 3.5.1+</h3> <pre><code>Testing detect_protocol_by_index 1.5673476169999958 Testing detect_protocol_by_urlparse 15.466406801000176 Testing detect_protocol_by_regex 3.0660895540004276 </code></pre> <h3>Source</h3> <pre><code>import sys import timeit import re if sys.version_info &gt;= (3, 0): from urllib.parse import urlparse else: from urlparse import urlparse def detect_protocol_by_index(url): ind = url.find("://") return url[0:ind] if (ind != -1) else 'default_prot' def detect_protocol_by_urlparse(url): scheme = urlparse(url).scheme return scheme if scheme else 'default_prot' regex = re.compile('^[^:]+(?=:\/\/)') def detect_protocol_by_regex(url): match = regex.match(url) return match.group(0) if match else 'default_prot' ### TEST SETUP ### test_urls = ['www.example.com', 'http://example.com', 'https://example.com', 'ftp://example.com'] def run_test(func): for url in test_urls: func(url) def run_tests(): funcs = [detect_protocol_by_index, detect_protocol_by_urlparse, detect_protocol_by_regex] for func in funcs: print("Testing {}".format(func.__name__)) print(timeit.timeit('run_test({})'.format(func.__name__), setup="from __main__ import run_test, {}".format(func.__name__))) if __name__ == '__main__': run_tests() </code></pre>
4
2016-07-23T11:05:13Z
[ "python", "regex", "parsing" ]
Cause of slow Scrapy scraper
38,540,708
<p><b>I have created a new scrapy spider that is extremely slow.</b> It only scrapes around two pages per second, whereas the other Scrapy crawlers that I have created have been crawling a lot faster.</p> <p>I was wondering what is it that could cause this issue, and how to possibly fix that. The code is not much different from the other spiders and I am not sure it has something to do, but I'll add it if you think it may be involved.</p> <p>In fact, I have the impression that the requests are not asynchronous. I have never run into this kind of problem, and I am fairly new to Scrapy.</p> <p><b>EDIT</b></p> <p>Here's the spider :</p> <pre><code>class DatamineSpider(scrapy.Spider): name = "Datamine" allowed_domains = ["domain.com"] start_urls = ( 'http://www.domain.com/en/search/results/smth/smth/r101/m2108m', ) def parse(self, response): for href in response.css('.searchListing_details .search_listing_title .searchListing_title a::attr("href")'): url = response.urljoin(href.extract()) yield scrapy.Request(url, callback=self.parse_stuff) next_page = response.css('.pagination .next a::attr("href")') next_url = response.urljoin(next_page.extract()[0]) yield scrapy.Request(next_url, callback=self.parse) def parse_stuff(self, response): item = Item() item['value'] = float(response.xpath('//*[text()="Price" and not(@class)]/../../div[2]/span/text()').extract()[0].split(' ')[1].replace(',','')) item['size'] = float(response.xpath('//*[text()="Area" and not(@class)]/../../div[2]/text()').extract()[0].split(' ')[0].replace(',', '.')) try: item['yep'] = float(response.xpath('//*[text()="yep" and not(@class)]/../../div[2]/text()').extract()[0]) except IndexError: print "NO YEP" else: yield item </code></pre>
0
2016-07-23T10:24:56Z
38,547,649
<p>There are only two potential reasons, given that your spiders indicate that you're quite careful/experienced.</p> <ol> <li>Your target site's response time is very low</li> <li>Every page has only 1-2 listing pages (the ones that you parse with <code>parse_stuff()</code>).</li> </ol> <p>Highly likely the latter is the reason. It's reasonable to have a response time of half a second. This means that by following the pagination (next) link, you will be effectively be crawling 2 index pages per second. Since you're browsing - I guess - as single domain, your maximum concurrency will be ~ <code>min(CONCURRENT_REQUESTS, CONCURRENT_REQUESTS_PER_DOMAIN)</code>. This typically is 8 for the default settings. But you won't be able to utilise this concurrency because you don't create listing URLs fast enough. If your <code>.searchListing_details .search_listing_title .searchListing_title a::attr("href")</code> expression creates just a single URL, the rate with which you create listing URLs is just 2/second whereas to fully utilise your downloader with a concurrency level of 8 you should be creating at least 7 URLs/index page.</p> <p>The only good solution is to "shard" the index and start crawling e.g. multiple categories in parallel by setting many non-overlaping <code>start_urls</code>. E.g. you might want to crawl TVs, Washing machines, Stereos or whatever other categories in parallel. If you have 4 such categories and Scrapy "clicks" their 'next' button for each one of them 2 times a second, you will be creating 8 listing pages/second and roughly speaking, you would utilise much better your downloader.</p> <p>P.S. <code>next_page.extract()[0]</code> == <code>next_page.extract_first()</code></p> <p>Update after discussing this offline: Yes... I don't see anything extra-weird on this website apart from that it's slow (either due to throttling or due to their server capacity). Some specific tricks to go faster. Hit the indices 4x as fast by settings 4 <code>start_urls</code> instead of 1.</p> <pre><code>start_urls = ( 'http://www.domain.com/en/search/results/smth/sale/r176/m3685m', 'http://www.domain.com/en/search/results/smth/smth/r176/m3685m/offset_200', 'http://www.domain.com/en/search/results/smth/smth/r176/m3685m/offset_400', 'http://www.domain.com/en/search/results/smth/smth/r176/m3685m/offset_600' ) </code></pre> <p>Then use higher concurrency to allow for more URLs to be loaded in parallel. Essentially "deactivate" <code>CONCURRENT_REQUESTS_PER_DOMAIN</code> by setting it to a large value e.g. 1000 and then tune your concurrency by setting <code>CONCURRENT_REQUESTS</code> to 30. By default your concurrency is limited by <code>CONCURRENT_REQUESTS_PER_DOMAIN</code> to 8 which in, for example, your case where the response time for listing pages is >1.2 sec, means a max of 6 listing pages per second crawling speed. So call your spider like this:</p> <pre><code>scrapy crawl MySpider -s CONCURRENT_REQUESTS_PER_DOMAIN=1000 -s CONCURRENT_REQUESTS=30 </code></pre> <p>and it should do better.</p> <p>One more thing. I observe from your target site, that you can get all the information you need including <code>Price</code>, <code>Area</code> and <code>yep</code> from the index pages themselves without having to "hit" any listing pages. This would instantly 10x your crawling speed since you don't need to download all these listing pages in with the <code>for href...</code> loop. Just parse the listings from the index page.</p>
0
2016-07-24T00:37:06Z
[ "python", "web-scraping", "scrapy", "web-crawler", "scrapy-spider" ]
Python: Beautiful Soup: Can't grab a full title from parsing
38,540,799
<p>I am attempting to practice scraping by going to a video website, and scraping all the titles of the videos on the homepage. My only issue is, if the title is too long, it gets cut short using the .string function in BeautifulSoup. </p> <p>Here is example HTML for parsing:</p> <pre class="lang-html prettyprint-override"><code>&lt;head&gt;...&lt;/head&gt; &lt;body class="home"&gt; &lt;div id="main"&gt; &lt;div id="content"&gt; &lt;div id="vid_28" class="thumb-block "&gt; &lt;div class="thumb-inside"&gt;...&lt;/div&gt; &lt;p&gt; &lt;a href="/vid_28/0/this_is_a_great_video_" title="this is a great video"&gt;this is a great vi...&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>Here is the code I am attempting to print the title with:</p> <pre><code>import requests from bs4 import BeautifulSoup url = "example" r = requests.get(url) soup = BeautifulSoup(r.content, "lxml") links = soup.find_all("div", {"class":"thumb-block"}) for link in links: for tag in link.find_all("a") print(tag.string) </code></pre> <p>This code is working how I want it, except it's printing the string "this is a great vi..." which is cut short. </p> <p>If you notice in the HTML, the text after "title=" never gets cut short. </p> <p>How can I modify my code to acquire the text in parentheses after the "title=" within the element, instead of acquiring the text that is cut off?</p>
0
2016-07-23T10:35:41Z
38,541,033
<p>I've figured out my problem, I found it in documentation after re-reading it multiple times.</p> <p>If you want to print any attribute which I wanted the "title=", I had to change the <code>print(tag.string)</code> to <code>print(tag['title'])</code></p> <p>This is what @Rawring and @ChaoticTwist suggested first, but I wasn't sure what they meant by access the title attribute until now. </p> <p>Thank you all for your time. </p>
0
2016-07-23T11:03:35Z
[ "python", "html", "web-scraping", "beautifulsoup", "python-requests" ]
In what order should Python’s list.__contains__ invoke __eq__?
38,540,991
<p>Consider the following Python program:</p> <pre><code>class Foo(object): def __init__(self, bar): self.bar = bar def __repr__(self): return 'Foo(%r)' % (self.bar,) def __eq__(self, other): print('Foo.__eq__(%r, %r)' % (self, other)) return self.bar == other foo1 = Foo('A') foo2 = Foo('B') assert foo1 not in [foo2] </code></pre> <p>Under CPython 2.7.11 and 3.5.1, it prints:</p> <pre><code>Foo.__eq__(Foo('A'), Foo('B')) Foo.__eq__(Foo('B'), 'A') </code></pre> <p>But under PyPy 5.3.1 (2.7), it prints:</p> <pre><code>Foo.__eq__(Foo('B'), Foo('A')) Foo.__eq__(Foo('A'), 'B') </code></pre> <p>Although Python 3.5’s documentation <a href="https://docs.python.org/3.5/reference/expressions.html#value-comparisons" rel="nofollow">states</a> that equality should be symmetric “if possible”, sometimes it is not. In that case, the order of arguments to <code>Foo.__eq__</code> becomes important.</p> <p>So, is the above CPython behavior an implementation detail, or is it a part of <code>list</code>’s public interface (meaning that PyPy has a bug)? Please explain why you think so.</p>
0
2016-07-23T11:00:02Z
38,541,058
<p>Per <a href="https://docs.python.org/3/reference/expressions.html#membership-test-details" rel="nofollow">the language reference</a>:</p> <blockquote> <p>For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression <code>x in y</code> is equivalent to <code>any(x is e or x == e for e in y)</code>.</p> </blockquote> <p>The other examples in the same section show the same ordering for the equality test. This suggests that the comparison should be <code>item_maybe_in_list.__eq__(item_actually_in_list)</code>, in which case this could be considered a bug in PyPy. Additionally, CPython is the reference implementation, so in any discrepancy that version wins!</p> <p>That said, you should raise it with that community to see how they feel about it. </p>
3
2016-07-23T11:06:55Z
[ "python", "cpython", "pypy" ]
How to monkey patch a `__call__` method?
38,541,015
<p>I don't seem to be able to monkey patch a <code>__call__</code> method of class instance (and yes, I want to patch just single instances, not all of them).</p> <p>The following code:</p> <pre><code>class A(object): def test(self): return "TEST" def __call__(self): return "EXAMPLE" a = A() print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) a.__call__ = lambda : "example" a.test = lambda : "test" print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) print(a()) print("Explicit call: {0}".format(a.__call__())) print(a.test()) </code></pre> <p>Outputs this:</p> <pre><code>call method: &lt;bound method A.__call__ of &lt;__main__.A object at 0x7f3f2d60b6a0&gt;&gt; test method: &lt;bound method A.test of &lt;__main__.A object at 0x7f3f2d60b6a0&gt;&gt; call method: &lt;function &lt;lambda&gt; at 0x7f3f2ef4ef28&gt; test method: &lt;function &lt;lambda&gt; at 0x7f3f2d5f8f28&gt; EXAMPLE Explicit call: example test </code></pre> <p>While I'd like it to output:</p> <pre><code>... example Explicit call: example test </code></pre> <p><strong>How do I monkeypatch <code>__call__()</code>? Why I can't patch it the same way as I patch other methods?</strong></p> <p>While <a href="http://stackoverflow.com/a/14590308/462370">this answer</a> tells how to do it (supposedly, I haven't tested it yet), it doesn't explain the <em>why</em> part of the question.</p>
5
2016-07-23T11:02:10Z
38,541,146
<blockquote> <p>For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. That behaviour is the reason why the following code raises an exception:</p> <pre><code>&gt;&gt;&gt; class C: ... pass ... &gt;&gt;&gt; c = C() &gt;&gt;&gt; c.__len__ = lambda: 5 &gt;&gt;&gt; len(c) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: object of type 'C' has no len() </code></pre> </blockquote> <p>Source: <a href="https://docs.python.org/3/reference/datamodel.html#special-lookup" rel="nofollow">https://docs.python.org/3/reference/datamodel.html#special-lookup</a></p>
3
2016-07-23T11:16:20Z
[ "python", "monkeypatching" ]
How to monkey patch a `__call__` method?
38,541,015
<p>I don't seem to be able to monkey patch a <code>__call__</code> method of class instance (and yes, I want to patch just single instances, not all of them).</p> <p>The following code:</p> <pre><code>class A(object): def test(self): return "TEST" def __call__(self): return "EXAMPLE" a = A() print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) a.__call__ = lambda : "example" a.test = lambda : "test" print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) print(a()) print("Explicit call: {0}".format(a.__call__())) print(a.test()) </code></pre> <p>Outputs this:</p> <pre><code>call method: &lt;bound method A.__call__ of &lt;__main__.A object at 0x7f3f2d60b6a0&gt;&gt; test method: &lt;bound method A.test of &lt;__main__.A object at 0x7f3f2d60b6a0&gt;&gt; call method: &lt;function &lt;lambda&gt; at 0x7f3f2ef4ef28&gt; test method: &lt;function &lt;lambda&gt; at 0x7f3f2d5f8f28&gt; EXAMPLE Explicit call: example test </code></pre> <p>While I'd like it to output:</p> <pre><code>... example Explicit call: example test </code></pre> <p><strong>How do I monkeypatch <code>__call__()</code>? Why I can't patch it the same way as I patch other methods?</strong></p> <p>While <a href="http://stackoverflow.com/a/14590308/462370">this answer</a> tells how to do it (supposedly, I haven't tested it yet), it doesn't explain the <em>why</em> part of the question.</p>
5
2016-07-23T11:02:10Z
38,541,437
<p>So, as <a href="http://stackoverflow.com/users/5781248/j-j-hakala">J.J. Hakala</a> commented, what Python really does, is to call:</p> <pre><code>type(a).__call__(a) </code></pre> <p>as such, if I want to override the <code>__call__</code> method, I <strong>must</strong> override the <code>__call__</code> of a class, but if I don't want to affect behaviour of other instances of the same class, I need to create a new class with the overriden <code>__call__</code> method.</p> <p>So an example of how to override <code>__call__</code> would look like this:</p> <pre><code>class A(object): def test(self): return "TEST" def __call__(self): return "EXAMPLE" def patch_call(instance, func): class _(type(instance)): def __call__(self, *arg, **kwarg): return func(*arg, **kwarg) instance.__class__ = _ a = A() print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) patch_call(a, lambda : "example") a.test = lambda : "test" print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) print("{0}".format(a())) print("Explicit a.__call__: {0}".format(a.__call__())) print("{0}".format(a.test())) print("Check instance of a: {0}".format(isinstance(a, A))) </code></pre> <p>Running it produces following output:</p> <pre><code>call method: &lt;bound method A.__call__ of &lt;__main__.A object at 0x7f404217a5f8&gt;&gt; test method: &lt;bound method A.test of &lt;__main__.A object at 0x7f404217a5f8&gt;&gt; call method: &lt;bound method patch_call.&lt;locals&gt;._.__call__ of &lt;__main__.patch_call.&lt;locals&gt;._ object at 0x7f404217a5f8&gt;&gt; test method: &lt;function &lt;lambda&gt; at 0x7f404216d048&gt; example Explicit a.__call__: example test Check instance of a: True </code></pre>
3
2016-07-23T11:47:38Z
[ "python", "monkeypatching" ]
Linebreak for buttons
38,541,108
<p>Here is my problem :<br> I have a <code>labelframe</code> (I tested in a classic label too) which contains some buttons with a left alignment for the "-side" option.</p> <p>These buttons are generated by a loop and I would like to add a "wraplength" to the label for that my buttons can jump a line instead of follow each other side by side.</p> <p>The loop &amp; buttons code :</p> <pre><code> with open('data.txt', 'r') as data: for line in data: line = line.rstrip('\n') status = CheckStatus(line) NewButton = Button(labelframe, state = status, text = line, command = lambda x=line:run(str(x))) NewButton.pack(side = LEFT, padx = 5, pady = 5) </code></pre> <p>The frame which contains the loop :</p> <pre><code>labelframe = LabelFrame(Window, width = 400, height = 150) labelframe.pack() labelframe.pack_propagate(False) #I Try this to fix the size of the labelframe. </code></pre>
0
2016-07-23T11:12:24Z
38,550,789
<p>Okay, so, finally, I added an incremental variable &amp; a <code>if</code> in my loop. When the variable is equal to 5, a new frame (which contains the buttons) is created. Not sure if it's the most optimized method but I didn't found anything else...</p> <pre><code>def LoadButtons(): FrameInfoText.config(justify = CENTER, text = 'Initialization...') FrameInfoText.update() LineFrame = Frame(labelframe) LineFrame.pack() ButtonsPerLine = 0 with open('data.txt', 'r') as data: for line in data: line = line.rstrip('\n') StreamPerLine += 1 if ButtonsPerLine &gt; 5: LineFrame = Frame(labelframe) LineFrame.pack() ButtonsPerLine = 1 status = CheckStatus(line) NewButton = Button(LineFrame, state = status, text = line, command = lambda x=line:run(str(x))) NewButton.pack(side = LEFT, padx = 5, pady = 5) FrameInfoText.config(text = 'Loading...\n'+line) FrameInfoText.update() </code></pre>
0
2016-07-24T09:57:39Z
[ "python", "button", "tkinter", "label" ]
To match a word from a pool of sentences using Python
38,541,129
<p>I have two different files File "Sentence" contains a pool of sentences, please find the snapshot below. <a href="http://i.stack.imgur.com/oG9WD.jpg" rel="nofollow">Sentence Snapshot</a></p> <p>File "Word" contians pool of words, please find the snapshot below.</p> <p><a href="http://i.stack.imgur.com/dkvMX.jpg" rel="nofollow">Word file snap shot</a></p> <p>I want to map words from word file to sentence file if any word match with the sentence, I want the result in form of sentence and matched word</p> <p>for example: Sentence Match Words Linux and open stack is great Linux Open stack</p> <p>Please find my code below, when I am trying to extract the result in to csv, its showing error.</p> <pre><code>import pandas as pd import csv sentence_xlsx = pd.ExcelFile('C:\Python\Seema\Sentence.xlsx') sentence_all = sentence_xlsx.parse('Sheet1') #print(sentence_all) word_xlsx = pd.ExcelFile('C:\Python\Seema\Word.xlsx') word_all = word_xlsx.parse('Sheet1') for sentence in sentence_all['Article']: sentences = sentence.lower() for word in sentences.split(): if word in ('linux','openstack'): result = word,sentence results = open('C:\Python\Seema\result.csv', 'wb') writer = csv.writer(results, dialect='excel') writer.writerows(result) results.close() Traceback (most recent call last): File "Word_Finder2.py", line 25, in &lt;module&gt; results = open('C:\Python\Seema\result.csv', 'wb') IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\\Python\\Seema\result.c sv' </code></pre>
0
2016-07-23T11:14:11Z
38,541,567
<p>The <code>'\result.csv'</code> part of your path has its <code>'\r'</code> being read as a carriage return character. To fix this, append a leading <code>r</code> to the path to make it a raw string literal (credit @georg).</p> <hr> <p>Then to use <code>writerows</code>, the result from all the iterations should be accumulated into a list and not just the last result.</p> <pre><code>result = [] # create list to hold result from each iteration for sentence in sentence_all['Article']: sentences = sentence.lower() for word in sentences.split(): if word in ('linux','openstack'): # append result of iteration to result result.append([sentence, word]) #|&lt;- creates list of rows suitable for 'writerows' results = open(r'C:\Python\Seema\result.csv', 'wb') # ^ prevents \r... from being read as a special character writer = csv.writer(results, dialect='excel') writer.writerows(result) results.close() </code></pre>
1
2016-07-23T12:01:41Z
[ "python", "string", "string-matching" ]
Python, distance between two points type issue
38,541,153
<p>I am trying to use a simple approximation for a solution to the travelling salesman problem for 100 random points on a Cartesian grid between values of 0 - 100 on both the x and y axis using the <strong>numpy</strong> method.</p> <p>I have created various integers that are unique and fill up three lists:</p> <pre><code>xList = [np.round(np.random.rand()*100)] #Generates random x,y coordinates yList = [np.round(np.random.rand()*100)] orderList = [np.round(np.random.rand()*100)] </code></pre> <p>I have defined a function that will find the shortest distance between two points on a Cartesian plane:</p> <pre><code>def distance(x1, x2, y1, y2): return np.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) </code></pre> <p>I then iterate through this list to find the total length if a specific path travels randomly between points:</p> <pre><code>totalLength = 0 for i in range(0, 98): stuff = distance(int(xList[orderList[i]]), int(xList[orderList[i+1]]), int(yList[orderList[i]]), int(yList[orderList[i+1]])) totalLength = totalLength + stuff shortestLength = totalLength </code></pre> <p>It seems that the typing is a problem for my predefined function getting the message:</p> <pre><code>stuff = distance(int(xList[orderList[i]]), int(xList[orderList[i+1]]), int(yList[orderList[i]]), int(yList[orderList[i+1]]))*** TypeError: list indices must be integers, not numpy.float64 </code></pre> <p>I have no idea about how to properly define types in python so I would like some advice about converting the <code>float.numpy64</code> type to an integer or allowing my predefined function to work for the correct types.</p>
0
2016-07-23T11:16:57Z
38,541,196
<p><code>numpy.round</code> does not yield integers:</p> <pre><code>&gt; print(type(np.round(13.4))) &lt;type 'numpy.float64'&gt; </code></pre> <p>Possible solutions:</p> <pre><code>&gt; int(np.round(13.4)) 13 # type int &gt; np.int(13.4) 13 # type int &gt; math.trunc(13.4) 13 # type int </code></pre> <hr> <p>Consider the following reformulation of your code:</p> <pre><code>import numpy as np import random import scipy.spatial.distance as distance points = np.rollaxis(np.random.randn(2, 100), 1) indices = range(points.size) # distance.euclidean(points[5], points[10]) </code></pre>
0
2016-07-23T11:21:21Z
[ "python", "list", "numpy", "types" ]
Python, distance between two points type issue
38,541,153
<p>I am trying to use a simple approximation for a solution to the travelling salesman problem for 100 random points on a Cartesian grid between values of 0 - 100 on both the x and y axis using the <strong>numpy</strong> method.</p> <p>I have created various integers that are unique and fill up three lists:</p> <pre><code>xList = [np.round(np.random.rand()*100)] #Generates random x,y coordinates yList = [np.round(np.random.rand()*100)] orderList = [np.round(np.random.rand()*100)] </code></pre> <p>I have defined a function that will find the shortest distance between two points on a Cartesian plane:</p> <pre><code>def distance(x1, x2, y1, y2): return np.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) </code></pre> <p>I then iterate through this list to find the total length if a specific path travels randomly between points:</p> <pre><code>totalLength = 0 for i in range(0, 98): stuff = distance(int(xList[orderList[i]]), int(xList[orderList[i+1]]), int(yList[orderList[i]]), int(yList[orderList[i+1]])) totalLength = totalLength + stuff shortestLength = totalLength </code></pre> <p>It seems that the typing is a problem for my predefined function getting the message:</p> <pre><code>stuff = distance(int(xList[orderList[i]]), int(xList[orderList[i+1]]), int(yList[orderList[i]]), int(yList[orderList[i+1]]))*** TypeError: list indices must be integers, not numpy.float64 </code></pre> <p>I have no idea about how to properly define types in python so I would like some advice about converting the <code>float.numpy64</code> type to an integer or allowing my predefined function to work for the correct types.</p>
0
2016-07-23T11:16:57Z
38,541,253
<p>Your <code>orderList</code> should be a numpy array (or normal Python list) of integers, not random floating-point numbers. </p> <p>I assume it should be a shuffled list of numbers in the range 0 - 100. You can construct such a list in pure Python like this:</p> <pre><code>import random listsize = 10 orderList = list(range(listsize)) random.shuffle(orderList) print(orderList) </code></pre> <p><strong>typical output</strong></p> <pre><code>[6, 5, 1, 2, 0, 4, 9, 3, 7, 8] </code></pre> <p>(I've set <code>listsize</code> to 10 to keep the output small).</p> <p>You can also pass a Numpy array to <code>random.shuffle</code>:</p> <pre><code>import random import numpy as np listsize = 10 orderList = np.arange(listsize) random.shuffle(orderList) print(orderList) </code></pre> <p><strong>typical output</strong></p> <pre><code>[6 9 0 1 3 7 2 5 8 4] </code></pre> <p>The <em>dtype</em> of the elements of this <code>orderList</code> is int32.</p> <p>Actually, Numpy has its own <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.shuffle.html" rel="nofollow">random.shuffle</a> function, so you can replace <code>random.shuffle(orderList)</code> in the previous snippet with</p> <pre><code>np.random.shuffle(orderList) </code></pre>
0
2016-07-23T11:28:16Z
[ "python", "list", "numpy", "types" ]
Python high-order functions
38,541,296
<p>Given the following code, i cant understand why f and fib behaves differently. the example taken from Barkley cs61a course</p> <pre><code>def fib(n): if n==1 or n==0: return n else: return fib(n-1) + fib(n-2) def decor(f): def counted(*args): counted.call_count += 1 return f(*args) counted.call_count = 0 return counted </code></pre> <p>when i load the code into the interpreter i got this output:</p> <pre><code>&gt;&gt;&gt; fib(6) 8 &gt;&gt;&gt; f = decor(fib) &gt;&gt;&gt; fib = decor(fib) &gt;&gt;&gt; # f and fib are both vars that represents a decorated fib function &gt;&gt;&gt; f(6) 8 &gt;&gt;&gt; f.call_count # why 1 ??? 1 &gt;&gt;&gt; &gt;&gt;&gt; fib(6) 8 &gt;&gt;&gt; fib.call_count # 49 calls, that's fine 49 </code></pre>
1
2016-07-23T11:33:48Z
38,541,378
<p><code>f.call_count</code> is 1 because <code>f</code> calls <code>fib</code>, and then <code>fib</code> recursively calls itself to calculate the result. In this whole procedure, <code>f</code> is only called once.</p> <p>But when you do <code>fib = decor(fib)</code>, you're overwriting the <code>fib</code> function in the global scope, so from that moment on <code>fib</code> will recursively call the <em>decorated</em> <code>fib</code>.</p>
2
2016-07-23T11:41:13Z
[ "python", "functional-programming" ]
Python high-order functions
38,541,296
<p>Given the following code, i cant understand why f and fib behaves differently. the example taken from Barkley cs61a course</p> <pre><code>def fib(n): if n==1 or n==0: return n else: return fib(n-1) + fib(n-2) def decor(f): def counted(*args): counted.call_count += 1 return f(*args) counted.call_count = 0 return counted </code></pre> <p>when i load the code into the interpreter i got this output:</p> <pre><code>&gt;&gt;&gt; fib(6) 8 &gt;&gt;&gt; f = decor(fib) &gt;&gt;&gt; fib = decor(fib) &gt;&gt;&gt; # f and fib are both vars that represents a decorated fib function &gt;&gt;&gt; f(6) 8 &gt;&gt;&gt; f.call_count # why 1 ??? 1 &gt;&gt;&gt; &gt;&gt;&gt; fib(6) 8 &gt;&gt;&gt; fib.call_count # 49 calls, that's fine 49 </code></pre>
1
2016-07-23T11:33:48Z
38,541,417
<p>You are overwriting <code>fib</code> and then <code>f</code> calls <code>fib</code> instead of itself:</p> <pre><code>def fib(n): if n==1 or n==0: return n else: print("fib is: " + repr(fib)) return fib(n-1) + fib(n-2) def decor(f): def counted(*args): counted.call_count += 1 return f(*args) counted.call_count = 0 return counted f = decor(fib) fib = decor(fib) print("=== f ===") print(f(6)) print(f.call_count) print("=== fib ===") print(fib(6)) print(fib.call_count) </code></pre> <p>When I run this the output is:</p> <pre><code>=== f === fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; 8 1 === fib === fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; fib is: &lt;function counted at 0x7fa844639758&gt; 8 49 </code></pre> <p>Note that <code>fib is</code> function at <code>0x7fa844639758</code> all the time.</p>
0
2016-07-23T11:45:06Z
[ "python", "functional-programming" ]
Access and webscrape dynamic pages using python
38,541,353
<p>I am trying to access a web page using it's form parameters. I found the form parameters using Network headers in chrome's developer tab. But it's not working, instead it's just opening the page before these parameters are used (i.e <a href="http://www.irishancestors.ie/search/townlands/ded_index.php" rel="nofollow">www.irishancestors.ie/search/townlands/ded_index.php</a>)</p> <pre><code>import webbrowser webbrowser.open('http://www.irishancestors.ie/search/townlands/ded_index.php?action=listp&amp;parish=Aghagallon') </code></pre> <p>My intention is to retrieve all the tables of each District Electoral Division of all the counties.</p> <p><a href="http://i.stack.imgur.com/1MTeO.png" rel="nofollow"><img src="http://i.stack.imgur.com/1MTeO.png" alt="enter image description here"></a></p>
0
2016-07-23T11:38:42Z
38,541,395
<p>webbrowser doesn't do what you think it does.</p> <p>If you want to get/post data to a webpage, you should use <a href="http://docs.python-requests.org/en/master/user/quickstart/" rel="nofollow">requests</a></p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; r = requests.get('https://api.github.com/events') &gt;&gt;&gt; r = requests.post('http://httpbin.org/post', data = {'key':'value'}) </code></pre> <p><code>webbrowser</code> is for launching your web browser.</p> <p>Note that this won't work very well if there's a bunch of javascript in use (well, it might, but it requires a lot more work on your part). If you have a lot of Javascript, it may be easier to use <a href="http://www.seleniumhq.org/" rel="nofollow">selenium</a></p>
1
2016-07-23T11:42:56Z
[ "python", "dynamic", "web-scraping", "web-crawler", "http-post" ]
In kivy, why does size_hint behave differently for images than for buttons?
38,541,429
<p>I'm building a card game using kivy 1.9.1. I Had the cards displaying correctly, relative to the size of the root window, via size_hint. The cards class was inheriting from the image class and worked great. I realized that I needed to make the cards clickable, so I modified the class to inherit from the button class instead. For some reason, this did not size the same as an image. The background .png file became distorted. Please help. This is driving me nuts. I generally turn off size_hint to avoid this issue, but I need everything scaled based on root window size.</p> <pre><code>ScreenManagement: CardTableScreen: &lt;Card&gt;: size_hint: (.25, .25) pos_hint: ({'left': .05}) &lt;CardTableScreen&gt;: name: 'cardTable' Card: name: 'card0' id: card0 pos: (self.width *.20 , root.height / 2) Card: name: 'card1' id: card1 pos: (self.width * .75, root.height / 2) Card: name: 'card2' id: card2 pos: (self.width * 1.30 , root.height / 2) Card: name: 'card3' id: card3 pos: (self.width * 1.85, root.height / 2) Card: name: 'card4' id: card4 pos: (self.width * 2.40, root.height / 2) Label: name: 'handType' id: handType pos: (-(card0.width *.125), root.height * .30) font_size: '18sp' &lt;Layout&gt;: orientation: 'vertical' canvas.before: Color: rgba: 0,.25,0,1 Rectangle: pos: self.pos size: self.size </code></pre> <p>python:</p> <pre><code>from kivy.uix.button import Button class(Button): pass </code></pre>
0
2016-07-23T11:46:26Z
38,542,460
<p>Turns out, the solution is to inherit from the image class and the button behavior class, like so:</p> <p>from kivy.uix.behaviors import ButtonBehavior<br> from kivy.uix.image import Image</p> <p>class Cards(ButtonBehavior, Image): pass </p>
0
2016-07-23T13:43:49Z
[ "python", "image", "button", "scale", "kivy" ]
How to motion blur with ImageMagick using wand?
38,541,457
<p>I want to use motion blur with ImageMagick. <a href="http://www.imagemagick.org/Usage/blur/#motion-blur" rel="nofollow">Motion blur in ImageMagick documentation.</a></p> <p>But in Wand there is only gaussian_blur. <a href="http://docs.wand-py.org/en/0.4.3/wand/image.html" rel="nofollow">Gaussian blur in Wand documentation.</a></p> <p>Is motion blur missing in wand? </p>
-1
2016-07-23T11:49:33Z
38,588,482
<blockquote> <p>Is motion blur missing in wand?</p> </blockquote> <p>Yes, as of <em>0.4.3</em> there is no <code>wand.image.Image.motion_blur</code> method implemented on <a href="/questions/tagged/wand" class="post-tag" title="show questions tagged &#39;wand&#39;" rel="tag">wand</a> library.</p> <p>You'll need to extend wand's API to include <a href="http://www.imagemagick.org/api/magick-image.php#MagickMotionBlurImage" rel="nofollow"><code>MagickMotionBlurImage</code></a>. </p> <pre class="lang-py prettyprint-override"><code>import ctypes from wand.image import Image from wand.api import library # Tell Python about the C method library.MagickMotionBlurImage.argtypes = (ctypes.c_void_p, # wand ctypes.c_double, # radius ctypes.c_double, # sigma ctypes.c_double) # angle # Extend wand.image.Image class to include method signature (remember error handling) class MyImage(Image): def motion_blur(self, radius=0.0, sigma=0.0, angle=0.0): library.MagickMotionBlurImage(self.wand, radius, sigma, angle) # Example usage with MyImage(filename='rose:') as img: img.motion_blur(radius=8.0, sigma=4.0, angle=-57.0) img.save(filename='rose_motion.png') </code></pre> <p><a href="http://i.stack.imgur.com/Of75q.png" rel="nofollow"><img src="http://i.stack.imgur.com/Of75q.png" alt="enter image description here"></a></p>
0
2016-07-26T11:19:26Z
[ "python", "imagemagick", "blur", "motion", "wand" ]
Update all POS order using python
38,541,514
<p>I am trying to update the all POS order, but as I having around 50,000 record so when if any error occurs or stops execution forcefully. Then the number of records which executed must be updated but It was not storing the records when stops the script in middle. So please give me some solution for this...</p> <p>Code I am using to update record ...</p> <pre><code>@api.multi def update_all_amount(self): for order in self.search([('copy_amount_total', '=', 0)]): self._cr.execute("""update pos_order set copy_amount_total=%s where id = %s"""\ % (str(order.amount_total), str(order.id))) # print "\nupdated amount --- &gt;", order.copy_amount_total, print "success" </code></pre>
0
2016-07-23T11:54:49Z
38,542,022
<p>Just put commit after each update, then it won't roll back all those records which are committed. </p> <pre><code>@api.multi def update_all_amount(self): for order in self.search([('copy_amount_total', '=', 0)]): self._cr.execute("""update pos_order set copy_amount_total=%s where id = %s"""\ % (str(order.amount_total), str(order.id))) # print "\nupdated amount --- &gt;", order.copy_amount_total, self._cr.commit() print "success" </code></pre>
0
2016-07-23T12:54:14Z
[ "python", "openerp", "psql" ]
Counting number of links for each row and adding the counts as a new column
38,541,690
<p>I am trying to count the 'href' instances within the 'Body' column and add the count value as a new column corresponding for each row.</p> <p>I can get the count of links using this:</p> <pre><code>dataframe1['Body'].str.contains('href').sum() </code></pre> <p>However, this finds the link count for all rows not per row, which is 1770. I tried the following, it assigned again the link count for all rows (i.e., 1770). So, it also did not work:</p> <pre><code>dataframe1['LinkCount'] = dataframe1['Body'].str.contains('href').sum() </code></pre> <p>I thought, <code>apply()</code> would work, but it returned NaN value as the count value:</p> <pre><code>dataframe1['LinkCount'] = dataframe1[['Body']].apply(lambda x: x.str.contains('href').sum()) </code></pre> <p>Can anyone help me? What am I doing wrong?</p>
1
2016-07-23T12:16:01Z
38,541,767
<pre><code>&gt; import pandas as pd &gt; df = pd.DataFrame([["AAAAAAAA"], ["AAABBB"]], columns=['body']) &gt; df['count'] = df.apply(lambda r: r.body.count('A'), axis=1) # df['count'] = df.body.count('A') # (better) alternative, as in the answer of MaxU &gt; df body count 0 AAAAAAAA 8 1 AAABBB 3 </code></pre> <p>This should also work for multi-line strings, but does not respect HTML formatting, escaping, comments and so on. Of course, you have to adapt <code>r.body.count('A')</code> to your needs. But I suppose, <code>r.body.str.contains('href').sum()</code> should work out straight-forward.</p>
1
2016-07-23T12:25:39Z
[ "python", "pandas" ]
Counting number of links for each row and adding the counts as a new column
38,541,690
<p>I am trying to count the 'href' instances within the 'Body' column and add the count value as a new column corresponding for each row.</p> <p>I can get the count of links using this:</p> <pre><code>dataframe1['Body'].str.contains('href').sum() </code></pre> <p>However, this finds the link count for all rows not per row, which is 1770. I tried the following, it assigned again the link count for all rows (i.e., 1770). So, it also did not work:</p> <pre><code>dataframe1['LinkCount'] = dataframe1['Body'].str.contains('href').sum() </code></pre> <p>I thought, <code>apply()</code> would work, but it returned NaN value as the count value:</p> <pre><code>dataframe1['LinkCount'] = dataframe1[['Body']].apply(lambda x: x.str.contains('href').sum()) </code></pre> <p>Can anyone help me? What am I doing wrong?</p>
1
2016-07-23T12:16:01Z
38,541,824
<p>try this:</p> <pre><code>In [134]: df Out[134]: Body 0 aaa 1 href...href 2 bbb 3 href 4 href aaa href bbb href ccc href In [135]: df['count'] = df.Body.str.findall('href').apply(len) In [136]: df Out[136]: Body count 0 aaa 0 1 href...href 2 2 bbb 0 3 href 1 4 href aaa href bbb href ccc href 4 </code></pre>
1
2016-07-23T12:32:39Z
[ "python", "pandas" ]
Return javascript variable in Python / Flask
38,541,744
<p>I am working on a small Flask app and I am having trouble finding the way to access a javascript array from Python to be printed as csv.</p> <p>The general setup of my Flask file is (I am trying to print in the console to see if this is working, then I can write as csv later):</p> <pre><code>from flask import Flask, render_template, request @app.route('/assemblies', methods=['GET', 'POST']) def assemblies(): myColours = request.form.get('colours', type=str) print myColours return render_template('assemblies.html') if __name__ == '__main__': app.run(debug=True) </code></pre> <p>Then, in my html I have a dropdown selector:</p> <pre class="lang-html prettyprint-override"><code>&lt;select id="Layer1"&gt; &lt;option value="0"&gt;Empty&lt;/option&gt; &lt;option value="1"&gt;Blue&lt;/option&gt; &lt;option value="2"&gt;Red&lt;/option&gt; &lt;option value="3"&gt;White&lt;/option&gt; &lt;option value="4"&gt;Gray&lt;/option&gt; &lt;/select&gt;&lt;br&gt; </code></pre> <p>I access the selected value in Javascript like this:</p> <pre><code>function getColours() { var c = document.getElementById("Layer1"); var colour = c.options[c.selectedIndex].value; return colour; } </code></pre> <p>And in html I use a form to post the results:</p> <pre class="lang-html prettyprint-override"><code>&lt;form method="post"&gt; &lt;button onclick="getColours()" type="submit" value="colour"&gt;Click me&lt;/button&gt; &lt;/form&gt; </code></pre> <p>I know the html button is posting but I cannot access the results in Python. I am new to Flask and cannot find the problem in other questions or tutorials. Any help would be more than welcome.</p>
2
2016-07-23T12:23:10Z
38,541,857
<p>Let's assume your python is right and you need to post to assemblies your code would be like this:</p> <pre><code>&lt;form action="/assemblies" method="post"&gt; &lt;select name="colours"&gt; &lt;option value="0"&gt;Empty&lt;/option&gt; &lt;option value="1"&gt;Blue&lt;/option&gt; &lt;option value="2"&gt;Red&lt;/option&gt; &lt;option value="3"&gt;White&lt;/option&gt; &lt;option value="4"&gt;Gray&lt;/option&gt; &lt;/select&gt; &lt;br&gt; &lt;button type="submit"&gt;Click me&lt;/button&gt; &lt;/form&gt; </code></pre> <p>JS should be avoided where it can be avoided :) and this is not something dynamic, so this will send a post request with colours="0" for example if Empty is selected</p>
1
2016-07-23T12:37:11Z
[ "javascript", "python", "html", "flask" ]
Return javascript variable in Python / Flask
38,541,744
<p>I am working on a small Flask app and I am having trouble finding the way to access a javascript array from Python to be printed as csv.</p> <p>The general setup of my Flask file is (I am trying to print in the console to see if this is working, then I can write as csv later):</p> <pre><code>from flask import Flask, render_template, request @app.route('/assemblies', methods=['GET', 'POST']) def assemblies(): myColours = request.form.get('colours', type=str) print myColours return render_template('assemblies.html') if __name__ == '__main__': app.run(debug=True) </code></pre> <p>Then, in my html I have a dropdown selector:</p> <pre class="lang-html prettyprint-override"><code>&lt;select id="Layer1"&gt; &lt;option value="0"&gt;Empty&lt;/option&gt; &lt;option value="1"&gt;Blue&lt;/option&gt; &lt;option value="2"&gt;Red&lt;/option&gt; &lt;option value="3"&gt;White&lt;/option&gt; &lt;option value="4"&gt;Gray&lt;/option&gt; &lt;/select&gt;&lt;br&gt; </code></pre> <p>I access the selected value in Javascript like this:</p> <pre><code>function getColours() { var c = document.getElementById("Layer1"); var colour = c.options[c.selectedIndex].value; return colour; } </code></pre> <p>And in html I use a form to post the results:</p> <pre class="lang-html prettyprint-override"><code>&lt;form method="post"&gt; &lt;button onclick="getColours()" type="submit" value="colour"&gt;Click me&lt;/button&gt; &lt;/form&gt; </code></pre> <p>I know the html button is posting but I cannot access the results in Python. I am new to Flask and cannot find the problem in other questions or tutorials. Any help would be more than welcome.</p>
2
2016-07-23T12:23:10Z
38,541,901
<p>Sorry to post directly as answer due to less reputation, but it should be comment.</p> <p>Your <strong>select</strong> has no <code>name</code> attribute; it'll never be sent as part of the POST. Give it a name attribute as well as a value:</p> <pre><code>&lt;select id="Layer1" name="layer"&gt; </code></pre> <p>You can retrieve all values of the list using <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.MultiDict.getlist" rel="nofollow">MultiDict.getlist()</a>:</p> <pre><code>request.form.getlist('layer') </code></pre>
0
2016-07-23T12:41:36Z
[ "javascript", "python", "html", "flask" ]
Return javascript variable in Python / Flask
38,541,744
<p>I am working on a small Flask app and I am having trouble finding the way to access a javascript array from Python to be printed as csv.</p> <p>The general setup of my Flask file is (I am trying to print in the console to see if this is working, then I can write as csv later):</p> <pre><code>from flask import Flask, render_template, request @app.route('/assemblies', methods=['GET', 'POST']) def assemblies(): myColours = request.form.get('colours', type=str) print myColours return render_template('assemblies.html') if __name__ == '__main__': app.run(debug=True) </code></pre> <p>Then, in my html I have a dropdown selector:</p> <pre class="lang-html prettyprint-override"><code>&lt;select id="Layer1"&gt; &lt;option value="0"&gt;Empty&lt;/option&gt; &lt;option value="1"&gt;Blue&lt;/option&gt; &lt;option value="2"&gt;Red&lt;/option&gt; &lt;option value="3"&gt;White&lt;/option&gt; &lt;option value="4"&gt;Gray&lt;/option&gt; &lt;/select&gt;&lt;br&gt; </code></pre> <p>I access the selected value in Javascript like this:</p> <pre><code>function getColours() { var c = document.getElementById("Layer1"); var colour = c.options[c.selectedIndex].value; return colour; } </code></pre> <p>And in html I use a form to post the results:</p> <pre class="lang-html prettyprint-override"><code>&lt;form method="post"&gt; &lt;button onclick="getColours()" type="submit" value="colour"&gt;Click me&lt;/button&gt; &lt;/form&gt; </code></pre> <p>I know the html button is posting but I cannot access the results in Python. I am new to Flask and cannot find the problem in other questions or tutorials. Any help would be more than welcome.</p>
2
2016-07-23T12:23:10Z
38,542,510
<pre><code>from flask import Flask, request, render_template app = Flask(__name__) @app.route('/assemblies') def assemblies(): mycolours = request.form.get('colours') return render_template('assemblies.html', mycolours=mycolours) @app.route('/select') def select(): return render_template('select.html') if (__name__ == "__main__"): app.run(debug=True) </code></pre> <p>select.html</p> <pre><code>&lt;form action="/assemblies" method=['GET', 'POST']&gt; &lt;select name="colours"&gt; &lt;option value="0"&gt;Empty&lt;/option&gt; &lt;option value="1"&gt;Blue&lt;/option&gt; &lt;option value="2"&gt;Red&lt;/option&gt; &lt;option value="3"&gt;White&lt;/option&gt; &lt;option value="4"&gt;Gray&lt;/option&gt; &lt;/select&gt; &lt;br&gt; &lt;input type="submit" value="submit"&gt; &lt;/form&gt; </code></pre> <p>assemblies.html template:</p> <pre><code>&lt;p&gt;{{mycolours}}&lt;/p&gt; </code></pre> <p>The output for mycolours is the value you select. For example if you select <code>empty</code> it prints <code>0</code> and if you select <code>white</code> it prints <code>3</code>.</p>
1
2016-07-23T13:49:51Z
[ "javascript", "python", "html", "flask" ]
python-iptables installation error
38,541,828
<p>I am trying to install <code>python-iptables</code> for Python27 but I get the following error after using <code>pip install python-iptables</code> and <code>easy_install python-iptables</code></p> <blockquote> <p>libxtwrapper/wrapper.c(5) : fatal error C1083: Cannot open include file: 'sys/utsname.h': No such file or directory error: command 'C:\Users\pinso\AppData\Local\Programs\Common\Microsoft\visual C++ for Python\9.0\VC\Bin\cl.exe' failed with exit status 2</p> </blockquote> <p><a href="http://i.stack.imgur.com/vsBgl.png" rel="nofollow">Full log</a></p>
0
2016-07-23T12:33:07Z
38,542,000
<p>You install python-tables in windows OS, it only supports <code>POSIX :: Linux</code><a href="https://github.com/ldx/python-iptables/blob/master/README.md" rel="nofollow">python-iptables readme</a></p>
0
2016-07-23T12:51:53Z
[ "python", "python-iptables" ]
Numpy: Using a matrix as indices for another matrix to create a tensor?
38,541,860
<p>how would the following code work? </p> <pre><code>k = np.array([[ 0., 0.07142857, 0.14285714], [ 0.21428571, 0.28571429, 0.35714286], [ 0.42857143, 0.5, 0.57142857], [ 0.64285714, 0.71428571, 0.78571429], [ 0.85714286, 0.92857143, 1. ]]) y = np.array([[0, 3, 1, 2], [2, 1, 0, 3]]) b = k[y] </code></pre> <p>The shapes are:</p> <blockquote> <blockquote> <blockquote> <p>k shape: (5, 3)</p> <p>y shape: (2, 4)</p> <p>b shape: (2, 4, 3)</p> </blockquote> </blockquote> </blockquote> <p>Why would a numpy matrix accept another matrix as its index and how would k find the correct output? Why is a tensor produced instead? </p> <p>The output of b is</p> <pre><code> [[[ 0. 0.07142857 0.14285714] [ 0.64285714 0.71428571 0.78571429] [ 0.21428571 0.28571429 0.35714286] [ 0.42857143 0.5 0.57142857]] [[ 0.42857143 0.5 0.57142857] [ 0.21428571 0.28571429 0.35714286] [ 0. 0.07142857 0.14285714] [ 0.64285714 0.71428571 0.78571429]]] </code></pre>
2
2016-07-23T12:37:27Z
38,541,993
<p>This is called <strong><a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing" rel="nofollow">integer array indexing</a>.</strong> </p> <blockquote> <p>Integer array indexing allows selection of arbitrary items in the array based on their N-dimensional index. Each integer array represents a number of indexes into that dimension.</p> </blockquote> <p>Example - </p> <pre><code>x = array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11]]) rows = np.array([[0, 0], [3, 3]], dtype=np.intp) columns = np.array([[0, 2], [0, 2]], dtype=np.intp) x[rows, columns] </code></pre> <p>Output - </p> <pre><code>array([[ 0, 2], [ 9, 11]]) </code></pre> <p>In this case as you can see we are selecting the corner elements by giving the "coordinates" of the elements. And if you try just giving a single 2d matrix it'll just evaluate it like - </p> <pre><code>x[rows] </code></pre> <p>Output - </p> <pre><code>array([[[ 0, 1, 2], [ 0, 1, 2]], [[ 9, 10, 11], [ 9, 10, 11]]]) </code></pre>
3
2016-07-23T12:51:18Z
[ "python", "numpy", "matrix" ]
How can I make my GUI program(tkinter) work on computers with no python installed such that no console window appears?
38,541,974
<p>Here's what I have done so far: -I made a desktop search program/GUI using python and tkinter. </p> <p>-Then I used py2exe to convert it to an exe.</p> <p>-Now the software perfectly works on a machine(windows) without python installed, but the problem is that a creepy black window just appears along with the GUI when the .exe is opened. </p> <p>Is there any way to make it look less creepy to an end user?</p>
0
2016-07-23T12:48:48Z
38,542,029
<p>Change the file extension from .py to .pyw (You must have Python installed for this to work.)</p> <p>Duplicate: <a href="http://stackoverflow.com/questions/5523867/hide-console-window-with-tkinter-and-cx-freeze">Hide console window with Tkinter and cx_Freeze</a></p>
0
2016-07-23T12:54:43Z
[ "python", "user-interface", "tkinter" ]
Computer guessing a user-selected number within a defined range
38,542,083
<p>This is my code for a game in which the computer must guess a user defined number within a given range. This is a challenge from a beginners course/ book.</p> <p>I'd like to draw your attention to the 'computerGuess()' function. I think there must be a more eloquent way to achieve the same result? What I have looks to me like a botch job! </p> <p>The purpose of the function is to return the middle item in the list (hence middle number in the range of numbers which the computer chooses from). The 0.5 in the 'index' variable equation I added because otherwise the conversion from float-int occurs, the number would round down.</p> <p>Thanks.</p> <p>Code:</p> <pre><code># Computer Number Guesser # By Dave # The user must pick a number (1-100) and the computer attempts to guess # it in as few attempts as possible print("Welcome to the guessing game, where I, the computer, must guess your\ number!\n") print("You must select a number between 1 and 100.") number = 0 while number not in range(1, 101): number = int(input("\nChoose your number: ")) computerNumber = 0 computerGuesses = 0 higherOrLower = "" lowerNumber = 1 higherNumber = 101 def computerGuess(lowerNumber, higherNumber): numberList = [] for i in range(lowerNumber, higherNumber): numberList.append(i) index = int((len(numberList)/2 + 0.5) -1) middleValue = numberList[index] return middleValue while higherOrLower != "c": if computerGuesses == 0: computerNumber = computerGuess(lowerNumber, higherNumber) elif higherOrLower == "l": higherNumber = computerNumber computerNumber = computerGuess(lowerNumber, higherNumber) elif higherOrLower == "h": lowerNumber = computerNumber + 1 computerNumber = computerGuess(lowerNumber, higherNumber) print("\nThankyou. My guess is {}.".format(computerNumber)) computerGuesses += 1 higherOrLower = input("\nHow did I do? If this is correct, enter\ 'c'. If your number is higher, enter 'h'. If it is lower, enter 'l': ") print("\nHaha! I got it in {} attempt(s)! How great am I?".format\ (computerGuesses)) input("\n\nPress the enter key to exit.") </code></pre>
0
2016-07-23T13:00:34Z
38,542,209
<p>Like this ? </p> <pre><code>import math def computerGuess(lowerNumber, higherNumber): return int((lowerNumber+higherNumber)/2) </code></pre>
0
2016-07-23T13:14:56Z
[ "python", "list", "indexing" ]
Check if a python script is running properly and if it isn't re-run it?
38,542,084
<p>I have a script which is really buggy and every couple of hours it stops due to an error. I don't code in Python but I know the basics so I would like to know how can I make a script that check another script for errors and if it's true just re-run it? Sorry for not giving any examples but I think you get the idea and because I'm not good at Python doing this is easier than trying to understand the script and edit it. Any help is greatly appreciated.</p>
-1
2016-07-23T13:00:39Z
38,542,114
<p>By far the simplest way is to just wait for it to exit and always restart it when it crashes; the following <code>bash</code> loop will do nothing while the program is running, and will restart it as soon as it exits:</p> <pre class="lang-bash prettyprint-override"><code>while true do python buggy_script.py arguments echo oops, restarting... done </code></pre> <p>And that's it. It'll run forever, until you kill the bash script that's running it.</p> <p>PS. Of course this assumes you are on OS X or Linux; if you're on Windows, use an equivalent batch or PowerShell script.</p>
2
2016-07-23T13:04:31Z
[ "python", "python-2.7" ]
Check if a python script is running properly and if it isn't re-run it?
38,542,084
<p>I have a script which is really buggy and every couple of hours it stops due to an error. I don't code in Python but I know the basics so I would like to know how can I make a script that check another script for errors and if it's true just re-run it? Sorry for not giving any examples but I think you get the idea and because I'm not good at Python doing this is easier than trying to understand the script and edit it. Any help is greatly appreciated.</p>
-1
2016-07-23T13:00:39Z
38,542,245
<p>You can create a daemon for the script.</p> <p>Basically keep the main functionality in a loop that will run forever. <code> import logging import time if __name__ == '__main__': while True: //log errors logging.basicConfig(filename='log_file.log', level=logging.DEBUG) // use try except to handle exceptions try: // your code statements and function calls except Exception as e: // log the error for debugging logging.error(str(e)) // sleep the program if you want it to for desired amount of time. time.sleep(delay) </code></p> <p>The level of logging I set is debug. You can set it to any other of your own choice. </p> <p>References : </p> <p>Logging Docs - <a href="https://docs.python.org/3/library/logging.html" rel="nofollow">https://docs.python.org/3/library/logging.html</a></p> <p>Handling exceptions - <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="nofollow">https://docs.python.org/3/tutorial/errors.html#handling-exceptions</a></p>
0
2016-07-23T13:19:17Z
[ "python", "python-2.7" ]
Mongo DB Radius Units for GeoQuerys
38,542,108
<p>I am trying to work out what unit MongoDB queries use...</p> <p>I have the following query:</p> <pre><code>User.objects(address__point__geo_within_center=[[lat, long],maxDistance]) </code></pre> <p>I would like to user meters e.g. 10 meters within maxDistance.</p> <p>But in the documention (<a href="https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center</a>) it says </p> <blockquote> <p>"The circle’s radius, as measured in the units used by the coordinate system"</p> </blockquote> <p>I can not find a reference to "units" anywhere?</p> <p>I have been using <a href="http://docs.mongoengine.org/guide/querying.html" rel="nofollow">http://docs.mongoengine.org/guide/querying.html</a> for ref.</p> <p>What are the units?</p> <p>Can i set the units?</p> <p>Thanks</p>
0
2016-07-23T13:03:33Z
38,542,672
<p>You are trying to use $center which is only supported by the 2d index. You should be using the 2dshpere index and its supported operations. For that, the <a href="https://docs.mongodb.com/manual/core/2dsphere/" rel="nofollow">2dsphere docs</a> is a good place to start.</p> <p>The <a href="https://docs.mongodb.com/manual/reference/operator/query/nearSphere/#op._S_nearSphere" rel="nofollow">$nearSphere</a> geospatial query operator should do what you want. Note that operator uses distance in <strong>meters</strong>.</p> <p>The <a href="http://docs.mongoengine.org/guide/querying.html#geo-queries" rel="nofollow">mongoengine docs</a> show a geo_within_sphere operator, which is probably what you want.</p>
0
2016-07-23T14:07:40Z
[ "python", "mongodb", "flask", "mongoengine", "flask-mongoengine" ]
Example Decorator Error
38,542,122
<p>I'm trying to understand Python decorators and have written this code:</p> <pre><code>def hello_world(fn): print('hello world') fn() pass @hello_world def decorate(): print('hello decoatrion') return decorate() </code></pre> <p>I was aiming to print 'hello world' before 'hello decoration', but the output is the following:</p> <pre class="lang-none prettyprint-override"><code>hello world hello decoatrion Traceback (most recent call last): File "test_decortor.py", line 11, in &lt;module&gt; decorate() TypeError: 'NoneType' object is not callable </code></pre>
-1
2016-07-23T13:05:20Z
38,542,155
<p>The decorator must <strong>return the decorated function</strong>. You probably wanted something along these lines:</p> <pre><code>def hello_world(fn): def inner(): print('hello world') fn() return inner @hello_world def decorate(): print('hello decoatrion') return decorate() #output: hello world # hello decoatrion </code></pre> <p>You can read up on decorators <a class='doc-link' href="http://stackoverflow.com/documentation/python/229/decorators#t=201607231313506140223">here</a>.</p>
3
2016-07-23T13:09:31Z
[ "python", "python-decorators" ]
Example Decorator Error
38,542,122
<p>I'm trying to understand Python decorators and have written this code:</p> <pre><code>def hello_world(fn): print('hello world') fn() pass @hello_world def decorate(): print('hello decoatrion') return decorate() </code></pre> <p>I was aiming to print 'hello world' before 'hello decoration', but the output is the following:</p> <pre class="lang-none prettyprint-override"><code>hello world hello decoatrion Traceback (most recent call last): File "test_decortor.py", line 11, in &lt;module&gt; decorate() TypeError: 'NoneType' object is not callable </code></pre>
-1
2016-07-23T13:05:20Z
38,542,195
<p>Decorator syntax is shorthand for</p> <pre><code>decorated = decorate(decorated) </code></pre> <p>So if you have:</p> <pre><code>def hello_world(fn): print('hello world') fn() pass def decorate(): print('hello decoatrion') return decorate = hello_world(decorate) </code></pre> <p>You should see what the problem is (also note that <code>pass</code> does nothing here).</p> <pre><code>def hello_world(fn): def says_hello(): print('hello world') return fn() return says_hello def decorate(): print('hello decoration') decorate = hello_world(decorate) </code></pre> <p>will do what you want. Or you could write it:</p> <pre><code>@hello_world def decorate(): print('hello decoration') </code></pre>
3
2016-07-23T13:13:00Z
[ "python", "python-decorators" ]
Python Smptlib Email (Wrong subject & message field)
38,542,212
<p>Everytime I send an email with this function, it doesn't add the subject and the message to the right fields, but instead of that, it adds it to the 'from:' or something. <a href="http://i.stack.imgur.com/Kn5ux.png" rel="nofollow">Here's the image of it.</a> Any idea how this can be fixed? Thanks for answer</p> <pre><code>import smtplib ## NON-ANONYMOUS EMAIL def email(): # Parts of an email SERVER = 'smtp.gmail.com' PORT = 587 USER = 'something@gmail.com' PASS = 'something' FROM = USER TO = ['something@riseup.net'] #SUBJECT = 'Test' MESSAGE = 'Test message.' # Connects all parts of email together message = "From: %s\r\n To: %s\r\n %s" % (FROM, ", ".join(TO), MESSAGE) # Sends an email email = smtplib.SMTP() email.connect(SERVER,PORT) email.starttls() email.login(USER,PASS) email.sendmail(FROM, TO, message) email.quit() email() </code></pre>
0
2016-07-23T13:15:05Z
38,544,003
<p>You cannot have a space after the <code>\r\n</code>. An email header line is continued by indenting it, so your code is creating a really long <code>From:</code> header with all the data you are trying to put in different fields.</p> <p>Anyway, manually gluing together snippets of plain text is a really crude and error-prone way to construct an email message. You will soon find that you need the various features of the Python <code>email</code> module anyway (legacy email is 7-bit single part ASCII only; you'll probably want one or more of attachments, content encoding, character set support, multipart messages, or one of the many other MIME features). This also coincidentally offers much better documentation for how to correcty create a trivial email message.</p>
1
2016-07-23T16:33:04Z
[ "python", "email", "smtplib" ]
Python Smptlib Email (Wrong subject & message field)
38,542,212
<p>Everytime I send an email with this function, it doesn't add the subject and the message to the right fields, but instead of that, it adds it to the 'from:' or something. <a href="http://i.stack.imgur.com/Kn5ux.png" rel="nofollow">Here's the image of it.</a> Any idea how this can be fixed? Thanks for answer</p> <pre><code>import smtplib ## NON-ANONYMOUS EMAIL def email(): # Parts of an email SERVER = 'smtp.gmail.com' PORT = 587 USER = 'something@gmail.com' PASS = 'something' FROM = USER TO = ['something@riseup.net'] #SUBJECT = 'Test' MESSAGE = 'Test message.' # Connects all parts of email together message = "From: %s\r\n To: %s\r\n %s" % (FROM, ", ".join(TO), MESSAGE) # Sends an email email = smtplib.SMTP() email.connect(SERVER,PORT) email.starttls() email.login(USER,PASS) email.sendmail(FROM, TO, message) email.quit() email() </code></pre>
0
2016-07-23T13:15:05Z
38,556,353
<p>Following on from @tripleee suggestion to use the <code>email</code> module, here's a basic example using your current code:</p> <pre><code>import smtplib from email.mime.text import MIMEText ## NON-ANONYMOUS EMAIL def email(): # Parts of an email SERVER = 'smtp.gmail.com' PORT = 587 USER = 'something@gmail.com' PASS = 'something' FROM = USER TO = ['something@riseup.net'] SUBJECT = 'Test' # Create the email message = MIMEText('Test message.') message['From'] = FROM message['To'] = ",".join(TO) message['Subject'] = SUBJECT # Sends an email email = smtplib.SMTP() email.connect(SERVER,PORT) email.starttls() email.login(USER,PASS) email.sendmail(FROM, TO, message.as_string()) email.quit() </code></pre> <p>Notice how much easier it is to define the parts of the email using <em>keys</em> like <code>message['Subject']</code> instead of attempting to build a string or 'gluing parts together' as tripleee put it.</p> <p>The different fields (From, To, Subject, et cetera) you can access are defined in <a href="https://tools.ietf.org/html/rfc2822.html#section-3.6" rel="nofollow">RFC 2822 - Internet Message Format</a>. </p> <p>These documents are not easy to read, so here's a list of some of the fields' keys you can use: <code>To</code>, <code>From</code>, <code>Cc</code>, <code>Bcc</code>, <code>Reply-To</code>, <code>Sender</code>, <code>Subject</code>.</p> <blockquote> <p>You cannot have a space after the \r\n. An email header line is continued by indenting it, so your code is creating a really long From: header with all the data you are trying to put in different fields.</p> </blockquote> <p>As triplee and the RFC-2822 document says, if you are wanting to build the email string manually look at the field definitions in that document which look similar to this example:</p> <blockquote> <p>from = "From:" mailbox-list CRLF</p> </blockquote> <p>You can translate this into Python code when building an email string like so:</p> <p><code>"From: something@riseup.net \r\n"</code></p>
0
2016-07-24T20:15:30Z
[ "python", "email", "smtplib" ]