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
Creating functions from following code in python
38,821,414
<p>I'm trying to create functions from the following code but am having trouble. I've posted the code i want to make functions out of up top and my failed attempt at the bottom. Thanks for your help </p> <pre><code>inputFile = open(inputPath) name = "" for line in inputFile: lineSegment = line.split(", ") if name != lineSegment[0]: if len(pointList) &gt; 0: # Create new polyline object and insert it into featureclass polyline = arcpy.Polyline(pointList) cursor.insertRow((name, polyline)) print "Added " + name varialbe temporarily name = lineSegment[0] pointList = arcpy.Array() point = arcpy.Point(lineSegment[1], lineSegment[2]) pointList.add(point) else: point = arcpy.Point(lineSegment[1], lineSegment[2]) pointList.add(point) polyline = arcpy.Polyline(pointList) cursor.insertRow((name, polyline)) print "Added " + name </code></pre> <p>This is what I have done so far.</p> <pre><code>inputFile = open(inputPath) pointList = arcpy.Array() name = "" polyline = arcpy.Polyline(pointList) lineSegment = line.split(", ") name = lineSegment[0] point = arcpy.Point(lineSegment[1], lineSegment[2]) lines = "" def createlines(inputfile): newlines = "" for line in inputFile: lineSegment = line.split(", ") if name != lineSegment[0]: if len(pointList) &gt; 0: cursor.insertRow((name, polyline)) pointList.add(point) else: pointList.add(point) return newlines def polyline(): polyline = arcpy.Polyline(pointList) cursor.insertRow((name, polyline)) return polyline </code></pre>
0
2016-08-08T04:41:40Z
38,821,482
<p><code>open()</code> returns a file object, and is most commonly used with two arguments: <code>open(filename, mode)</code>.</p>
-3
2016-08-08T04:49:55Z
[ "python", "arcpy" ]
How to make a drop down menu and connect the choice to a CBGV
38,821,480
<p>I am new to Django and am struggling to understand how to make a user accessible connection between two models.</p> <p>models.py:</p> <pre><code>class StudyGroup(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() ex_1_trial = models.IntegerField(blank=True, null=True, default=None) ex_2_trial = models.IntegerField(blank=True, null=True, default=None) ... def __str__(self): return self.studygroup_name class Patient(models.Model): type = models.CharField('Type', max_length=20, db_index=True, help_text='s', primary_key=True) patient_name = models.CharField('Name', max_length=200, db_index=True, help_text='n') studygroup = models.ForeignKey(StudyGroup, verbose_name='StudyGroup') ... def __str__(self): return self.patient_name </code></pre> <p>views.py:</p> <pre><code>class SidebarList(object): def get_context_data(self, **kwargs): context = super(SidebarList, self).get_context_data(**kwargs) context['my_patient_list'] = Patient.objects.order_by('company_name') return context class PatientStatsView(SidebarList, DetailView): model = Patient template_name = 'screener/patient_stats.html' def get_context_data(self, **kwargs): context = super(CompanyStatsView, self).get_context_data(**kwargs) ... some sorting and stuff here ... context['blah'] = some_values return context </code></pre> <p>Now I want to make a drop down menu with the list of available studygroups in it and allow the user to select one to associate with a particular patient in the template associated with PatientStatsView. If a studygroup is already associated with a the patient instance, then that studygroup needs to be selected by default in the drop down.</p> <p>I am unclear about the best ways to achieve this and to have the selection verified and saved in the patient model.</p> <p>Is this best done in the form.py? </p>
0
2016-08-08T04:49:46Z
38,852,548
<p>The best way I see it can be done is via the <code>forms.py</code>, indeeed. Especially, that you will be altering the data in your database. You would want to use <code>POST</code> method together with <code>CSRF</code>, because of that.</p> <p>So you first of all you need to create <code>forms.py</code> with a <a href="https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield" rel="nofollow"><code>ModelChoiceField</code></a>(I find it most suitable for your task), which</p> <blockquote> <p>Allows the selection of a single model object, suitable for representing a foreign key.</p> </blockquote> <p>and set <a href="https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField.queryset" rel="nofollow"><code>queryset</code></a> parameter on it.</p> <blockquote> <p>A <strong>QuerySet</strong> of model objects from which the choices for the field will be derived, and which will be used to validate the user’s selection.</p> </blockquote> <p>You could do it for example like this:</p> <pre><code># forms.py ... class PatientForm(forms.Form): studygroups = forms.ModelChoiceField(queryset=StudyGroup.objects.all(), label='Study groups') ... </code></pre> <p>Then you would check in your view if the page was requested via <code>POST</code> or <code>GET</code> method. If user views the form for the first time - via <code>GET</code> method, then you would want to set the default value of user's <code>StudyGroup</code> if user is assigned to one, else return <code>None</code>. For example:</p> <h2>CBV:</h2> <pre><code>class HomeView(View): form_class = PatientForm template_name = 'home.html' def get(self, request, *args, **kwargs): initial = {'studygroups': request.user.patient.studygroup.pk} form = self.form_class(initial=initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): ... return HttpResponseRedirect('/success/') return render(request, self.template_name, {'form': form}) </code></pre> <h2>CBGV:</h2> <pre><code>class HomeView(FormView): form_class = PatientForm template_name = 'home.html' success_url = '/success/' def get_initial(self): initial = super(HomeView, self).get_initial() initial['studygroups'] = self.request.user.patient.studygroup.pk return initial def form_valid(self, form, *args, **kwargs): return super(HomeView, self).form_valid(form) </code></pre> <h2>FBV:</h2> <pre><code>... if request.method == 'POST': form = PatientForm(data=request.POST) if form.is_valid(): ... form.save() else: # some logic which would assign the patient studygroup's pk # to default_group_pk variable. # or None if no default group should be selected # i.e. user is not logged in or is not assigned to any studygroup. # You could get logged in Patient's studygroup via: # default_group_pk = request.user.patient.studygroup.pk form = PatientForm(initial={'studygroups': default_group_pk}) ... </code></pre> <p>Then simply render the form in your html:</p> <pre><code>&lt;form action="." method="post"&gt; {{ form.as_p}} {% csrf_token %} &lt;p&gt;&lt;input type="submit" value="Save"&gt;&lt;/p&gt; &lt;/form&gt; </code></pre>
0
2016-08-09T13:45:23Z
[ "python", "django", "django-templates", "django-views" ]
Write one element by row in a csv file with scrapy
38,821,485
<p>I'm scraping this page:</p> <p><a href="http://www.mymcpl.org/cfapps/botb/movie.cfm" rel="nofollow">http://www.mymcpl.org/cfapps/botb/movie.cfm</a></p> <p>Extracting four items: book, author, movie,movie_year</p> <p>I want to save this in a CSV file where each row contain records of one movie.</p> <p>This is the spider I wrote:</p> <pre><code>class simple_spider(scrapy.Spider): name = 'movies_spider' allowed_domains = ['mymcpl.org'] download_delay = 1 start_urls = ['http://www.mymcpl.org/cfapps/botb/movie.cfm?browse={}'.format(letter) for letter in string.uppercase] # ['http://www.mymcpl.org/cfapps/botb/movie.cfm'] def parse(self, response): xpaths = {'book':'//*[@id="main"]/tr[{}]/td[2]/text()[1]', 'author':'//*[@id="main"]/tr[{}]/td[2]/a/text()', 'movie':'//*[@id="main"]/tr[{}]/td[1]/text()[1]', 'movie_year':'//*[@id="main"]/tr[{}]/td[1]/a/text()'} data = {key:[] for key in xpaths} for row in range(2,len(response.xpath('//*[@id="main"]/tr').extract()) + 1): for key in xpaths.keys(): value = response.xpath(xpaths[key].format(row)).extract_first() data[key] = (value) yield data.values() </code></pre> <p>to run the spider:</p> <pre><code>scrapy runspider m_spider.py output.csv </code></pre> <p>I'm having two problems here:</p> <p>1) Each row of the CSV file contains no only the current record but all the previous records too even though I'm not appending the values in the dictionary</p> <p>2) the spider is only scraping only the firt page of start_urls.</p>
0
2016-08-08T04:50:18Z
38,822,724
<p>Scrapy already has in-built csv exporter. All you have to do is yield items and scrapy will output those items to csv file.</p> <pre><code>def parse(self, response): xpaths = {'book':'//*[@id="main"]/tr[{}]/td[2]/text()[1]', 'author':'//*[@id="main"]/tr[{}]/td[2]/a/text()', 'movie':'//*[@id="main"]/tr[{}]/td[1]/text()[1]', 'movie_year':'//*[@id="main"]/tr[{}]/td[1]/a/text()'} return {key:[] for key in xpaths} </code></pre> <p>Then just:</p> <pre><code>scrapy crawl myspider --output results.csv </code></pre> <p>* note the csv part, scrapy can also output to .json and .jl (json lines) instead of csv, just change the file extension in the argument.</p>
1
2016-08-08T06:42:10Z
[ "python", "csv", "web-scraping", "scrapy", "yield" ]
Pycharm manage.py autocomplete error
38,821,565
<p>In every django project manage.py commands work but no autocomplete</p> <p>Failed to get real commands on module "projects_name" python died with code 1 File opt/Pycharm/helpers/.../jb_manage_tasks_provider.py File opt/pycharm/helpers.../parser.py File my virtual env folder/lib/python3.5/site packages/django/core/management/base.py AttributeError Command object has no attribute 'args'</p> <p>Reinstalling pycharm didnt help</p>
3
2016-08-08T04:58:59Z
38,821,846
<p>i've been using django 1.10 and pycharm not supporting it yet. Downgraded to 1.9.8 and now autocompletion works without errors</p>
3
2016-08-08T05:27:41Z
[ "python", "django" ]
Pycharm manage.py autocomplete error
38,821,565
<p>In every django project manage.py commands work but no autocomplete</p> <p>Failed to get real commands on module "projects_name" python died with code 1 File opt/Pycharm/helpers/.../jb_manage_tasks_provider.py File opt/pycharm/helpers.../parser.py File my virtual env folder/lib/python3.5/site packages/django/core/management/base.py AttributeError Command object has no attribute 'args'</p> <p>Reinstalling pycharm didnt help</p>
3
2016-08-08T04:58:59Z
38,841,790
<p>You can use helper from community edition which support django 1.10+ Replace file JetBrains\PyCharm 2016.2\helpers\pycharm\django_manage_commands_provider_parser\parser.py</p> <p>with <a href="https://github.com/JetBrains/intellij-community/blob/master/python/helpers/pycharm/django_manage_commands_provider/_parser/parser.py" rel="nofollow">this</a></p>
1
2016-08-09T03:58:43Z
[ "python", "django" ]
One line to check if string or list, then convert to list in Python
38,821,586
<p>Suppose I have an object <code>a</code> that can either be a string (like <code>'hello'</code> or <code>'hello there'</code>) or a list (like <code>['hello', 'goodbye']</code>). I need to check if <code>a</code> is a string or list. If it's a string, then I want to convert it to a one element list (so convert <code>'hello there'</code> to <code>['hello there']</code>). If it's a list, then I want to leave it alone as a list.</p> <p>Is there a Pythonic one-line piece of code to do this? I know I can do:</p> <pre><code>if isinstance(a, str): a = [a] </code></pre> <p>But I'm wondering if there's a more direct, more Pythonic one-liner to do this.</p>
1
2016-08-08T05:00:33Z
38,821,619
<p>You can use a ternary operator:</p> <pre><code>a = [a] if isinstance(a, str) else a </code></pre>
1
2016-08-08T05:03:57Z
[ "python" ]
One line to check if string or list, then convert to list in Python
38,821,586
<p>Suppose I have an object <code>a</code> that can either be a string (like <code>'hello'</code> or <code>'hello there'</code>) or a list (like <code>['hello', 'goodbye']</code>). I need to check if <code>a</code> is a string or list. If it's a string, then I want to convert it to a one element list (so convert <code>'hello there'</code> to <code>['hello there']</code>). If it's a list, then I want to leave it alone as a list.</p> <p>Is there a Pythonic one-line piece of code to do this? I know I can do:</p> <pre><code>if isinstance(a, str): a = [a] </code></pre> <p>But I'm wondering if there's a more direct, more Pythonic one-liner to do this.</p>
1
2016-08-08T05:00:33Z
38,821,625
<pre><code>[a] if isinstance(a, str) else a </code></pre>
0
2016-08-08T05:05:03Z
[ "python" ]
One line to check if string or list, then convert to list in Python
38,821,586
<p>Suppose I have an object <code>a</code> that can either be a string (like <code>'hello'</code> or <code>'hello there'</code>) or a list (like <code>['hello', 'goodbye']</code>). I need to check if <code>a</code> is a string or list. If it's a string, then I want to convert it to a one element list (so convert <code>'hello there'</code> to <code>['hello there']</code>). If it's a list, then I want to leave it alone as a list.</p> <p>Is there a Pythonic one-line piece of code to do this? I know I can do:</p> <pre><code>if isinstance(a, str): a = [a] </code></pre> <p>But I'm wondering if there's a more direct, more Pythonic one-liner to do this.</p>
1
2016-08-08T05:00:33Z
38,821,657
<p>I prefer the other option rather than <code>isinstance</code>:</p> <pre><code>b = [a] if type(a) is str else a print(b) </code></pre> <p>And it's possible to do the other way around:</p> <pre><code>b = a if type(a) is list else [a] </code></pre> <p>And even make it a little ore robust:</p> <pre><code>b = a if type(a) in [list, tuple] else [a] </code></pre> <p>if you deal with tuples as well.</p>
0
2016-08-08T05:08:44Z
[ "python" ]
How does .apply in Graphlab work?
38,821,591
<p>I have been programming in Java and am trying to learn Python and Graphlab now.</p> <p>I looked at the Graphlab documentation here but it is insufficient for me to understand how .apply works. There does not seem to be much on Google either.</p> <p>There are two examples of usage I am trying to figure out:</p> <ol> <li><p>Where I have a column of country names, and a function to convert "USA" to "United States":</p> <pre><code>def transform_country(country) if country == 'USA': return 'United States' else: return country </code></pre> <p>how does the following command / apply work, so that it replaces all instances of "USA" with "United States"? What is .apply doing?</p> <pre><code>table['Country'] = sf['Country'].apply(transform_country) </code></pre></li> <li><p>In comparison, where I have a column containing a dictionary, say "and" => 5, "stink" => 1, "because = "1", how does .apply work with the function below to display the number associated with "and"?</p> <p>Function:</p> <pre><code>def awesome_count(word_count): if 'and' in word_count: return word_count['and'] else: return 0 </code></pre> <p>Command:</p> <pre><code>products['awesome'] = products['word_count'].apply(awesome_count) </code></pre></li> </ol>
0
2016-08-08T05:01:15Z
40,030,242
<p>Here is a quick demo on use of apply. Its creating a new column in the sframe from an existing sframe column. The new column is squared.</p> <pre><code>train_data['bedrooms_squared'] = train_data['bedrooms'].apply(lambda x: x**2) </code></pre>
0
2016-10-13T20:20:12Z
[ "python", "graphlab" ]
Automate outlook web app by using selenium , python
38,821,726
<p>I am trying to send email automatically from my office outlook web app. I have successfully automated the login process of outlook. But after login, there is no inspect element on new tab for sending mail. So how can i click on this new tab with selenium. Do i need to use some other framework for that.</p> <p>Flow of automation is: Selenium will first click on webapps->email->india after that login in outlook web app and outlook web app will open after login</p> <p>here is my code: here is my code:class LoginTest(unittest.TestCase):</p> <pre><code>def setUp(self): self.driver=webdriver.Firefox() userName="username" password="password" self.driver.get("http://sparshv2/") ''' aa=self.driver.switch_to.alert; aa.send_keys(userName+ Keys.COMMAND + "t") aa.send_keys(password+ Keys.COMMAND + "t") aa.accept() ''' def test_outlook(self): driver=self.driver userName="username" password="password" #time.sleep(10) aa=driver.switch_to.alert; #aa.authenticate(userName, password) aa.send_keys(userName) #aa.send_keys(Keys.TAB) #ele_id=driver.execute_script("return window.document.activeElement.id") #time.sleep(5) aa.send_keys(password) #aa.send_keys(Keys.TAB) aa.accept() web_apps_link="Web Apps" emailId="Email **" country="India" webAppsElementId=WebDriverWait(driver,10).until(lambda driver:driver.find_element_by_link_text(web_apps_link)) webAppsElementId.click() #time.sleep(20) #webAppsElementId.send_keys(Keys.CONTROL + Keys.RETURN) aa=driver.switch_to.alert; aa.send_keys(userName+ str(KEY_ENTER)) aa.send_keys(password+ str(KEY_ENTER)) aa.accept() ahdElementId=WebDriverWait(driver,10).until(lambda driver:driver.find_element_by_partial_link_text(emailId)) ahdElementId.click() #time.sleep(20) driver.switch_to_window(driver.window_handles[1]) # country=input("You are from which country: india or outside india") # if(country.lower()=="india"): countryElementId=WebDriverWait(driver,10).until(lambda driver:driver.find_element_by_link_text(country)) countryElementId.click() #elif(country.lower()=="outside india"): # countryElementId=WebDriverWait(driver,20).until(lambda driver:driver.find_element_by_link_text("Overseas")) # countryElementId.click() driver.switch_to_window(driver.window_handles[2]) emailElementId = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id(userNameId)) emailElementId.clear() emailElementId.send_keys(userName) passwordElementId = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id(passwordId)) passwordElementId.clear() passwordElementId.send_keys(password) signElementId = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_class_name(signInButton)) signElementId.click() </code></pre>
0
2016-08-08T05:16:52Z
38,823,472
<p>Using <code>Selenium</code> for email generation is not the best idea. I advise you to look toward <a href="https://win32com.goermezer.de/content/view/227/291/" rel="nofollow"><code>win32com.client</code></a> or <a href="https://docs.python.org/2/library/smtplib.html" rel="nofollow"><code>smtplib</code></a></p> <p>In common this will looks like</p> <pre><code>import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = 'to address' mail.Subject = 'Message subject' mail.body = 'Message body' mail.send </code></pre>
0
2016-08-08T07:27:58Z
[ "python", "selenium", "automation" ]
Automate outlook web app by using selenium , python
38,821,726
<p>I am trying to send email automatically from my office outlook web app. I have successfully automated the login process of outlook. But after login, there is no inspect element on new tab for sending mail. So how can i click on this new tab with selenium. Do i need to use some other framework for that.</p> <p>Flow of automation is: Selenium will first click on webapps->email->india after that login in outlook web app and outlook web app will open after login</p> <p>here is my code: here is my code:class LoginTest(unittest.TestCase):</p> <pre><code>def setUp(self): self.driver=webdriver.Firefox() userName="username" password="password" self.driver.get("http://sparshv2/") ''' aa=self.driver.switch_to.alert; aa.send_keys(userName+ Keys.COMMAND + "t") aa.send_keys(password+ Keys.COMMAND + "t") aa.accept() ''' def test_outlook(self): driver=self.driver userName="username" password="password" #time.sleep(10) aa=driver.switch_to.alert; #aa.authenticate(userName, password) aa.send_keys(userName) #aa.send_keys(Keys.TAB) #ele_id=driver.execute_script("return window.document.activeElement.id") #time.sleep(5) aa.send_keys(password) #aa.send_keys(Keys.TAB) aa.accept() web_apps_link="Web Apps" emailId="Email **" country="India" webAppsElementId=WebDriverWait(driver,10).until(lambda driver:driver.find_element_by_link_text(web_apps_link)) webAppsElementId.click() #time.sleep(20) #webAppsElementId.send_keys(Keys.CONTROL + Keys.RETURN) aa=driver.switch_to.alert; aa.send_keys(userName+ str(KEY_ENTER)) aa.send_keys(password+ str(KEY_ENTER)) aa.accept() ahdElementId=WebDriverWait(driver,10).until(lambda driver:driver.find_element_by_partial_link_text(emailId)) ahdElementId.click() #time.sleep(20) driver.switch_to_window(driver.window_handles[1]) # country=input("You are from which country: india or outside india") # if(country.lower()=="india"): countryElementId=WebDriverWait(driver,10).until(lambda driver:driver.find_element_by_link_text(country)) countryElementId.click() #elif(country.lower()=="outside india"): # countryElementId=WebDriverWait(driver,20).until(lambda driver:driver.find_element_by_link_text("Overseas")) # countryElementId.click() driver.switch_to_window(driver.window_handles[2]) emailElementId = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id(userNameId)) emailElementId.clear() emailElementId.send_keys(userName) passwordElementId = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id(passwordId)) passwordElementId.clear() passwordElementId.send_keys(password) signElementId = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_class_name(signInButton)) signElementId.click() </code></pre>
0
2016-08-08T05:16:52Z
39,256,136
<p>I used Firebug Plugin of Firefox to inspect and now I am able to see elements. Thanks everybody for providing the answer.</p>
0
2016-08-31T17:57:17Z
[ "python", "selenium", "automation" ]
python: "while (len(list1)>0) or (len(list2)>0)" doesn't work
38,821,756
<p>Im taking the Google Python Course and I am solving the below problem:</p> <blockquote> <p>Given two lists sorted in increasing order, create and return a merged >list of all the elements in sorted order. You may modify the passed in >lists. Ideally, the solution should work in "linear" time, making a single >pass of both lists.</p> </blockquote> <p>And my solution is below:</p> <pre><code>def linear_merge(list1, list2): # +++your code here+++ a = [] while (len(list1)&gt;0) or (len(list2)&gt;0): if list1[-1] &gt; list2[-1]: a.append(list1.pop(-1)) elif list1[-1] &lt; list2[-1]: a.append(list2.pop(-1)) else: a.append(list1.pop(-1)) a.append(list2.pop(-1)) #Have to force check if (len(list1)==0): break if (len(list2)==0): break if len(list1)&gt;0: res = (a+list1) return res[::-1] else: res = (a+list2) return res[::-1] </code></pre> <p>My issue is even though I check if both lists are empty, I get a list index out of range error. I have to force check if either list is empty at the end of the while loop to prevent the error from occurring.</p> <p>Why is the while loop failing to correctly see that one of the lists is empty? I am new to python and I am looking for some clarification on why this happens.</p>
0
2016-08-08T05:19:14Z
38,821,789
<blockquote> <p>My issue is even though I check if both lists are empty...</p> </blockquote> <p>No, you are checking if <strong>either one of them is not empty</strong>.</p> <hr> <p>Change this:</p> <pre><code>while (len(list1)&gt;0) or (len(list2)&gt;0) </code></pre> <p>To this:</p> <pre><code>while (len(list1)&gt;0) and (len(list2)&gt;0) </code></pre> <p>And at the end of the <code>while</code> loop continue working on the one list which is still not empty.</p>
1
2016-08-08T05:21:50Z
[ "python" ]
manytomany relation does not exist. It's in a different schema
38,821,937
<p>I use AbstractBaseUser together with CustomPermissionsMixin. CustomPermissionsMixin is kind of the same with django PermissionsMixin the difference is I changed related_name and related_query_name for user_permissions and groups so it won't clashing with django PermissionsMixin related_name</p> <pre><code>@python_2_unicode_compatible class CustomPermissionsMixin(models.Model): """ A mixin class that adds the fields and methods necessary to support Django's Group and Permission model using the ModelBackend. """ is_superuser = models.BooleanField( _('superuser status'), default=False, help_text=_( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) groups = models.ManyToManyField( Group, verbose_name=_('groups'), blank=True, help_text=_( 'The groups this user belongs to. A user will get all permissions ' 'granted to each of their groups.' ), related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) user_permissions = models.ManyToManyField( Permission, verbose_name=_('student user permissions'), blank=True, help_text=_('Specific permissions for this user.'), related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) class Meta: abstract = True .... </code></pre> <p>I have the same Student class in two different apps. One is in App1 and another in App2 with slightly different fields. I use postgresql. App1 is in schema public while App2 in schema krt5jdjtrx.(using django tenant schema. created programmatically) Both uses AbstractBaseUser and CustomPermissionsMixin</p> <pre><code>class Student(AbstractBaseUser, CustomPermissionsMixin): ... </code></pre> <p>I also use DRF DjangoModelPermissions</p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions', </code></pre> <p>And custom authentication backend</p> <pre><code>class CustomBackend(ModelBackend): .... </code></pre> <p>The problem is at <code>_get_user_permissions</code> inside django ModelBackend. Say <code>user_obj</code> is of type <code>app1.Student</code>, <code>user_obj.user_permissions.all().query</code> sometimes use <code>app1_student_user_permissions</code> or <code>app2_student_user_permissions</code>. How come the query uses <code>app2_student_user_permissions</code> while the <code>user_ob</code>j is indeed app1 not app2? . It'll create django.db.utils.ProgrammingError: relation does not exist.</p> <pre><code>def _get_user_permissions(self, user_obj): print('inside _get_user_perm !!!!!!!!!!!!!!!!!!!!!!!') print(user_obj) print(type(user_obj)) print(user_obj.user_permissions.all().query) return user_obj.user_permissions.all() </code></pre> <p>this is the raw queryset </p> <pre><code>SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename" FROM "auth_permission" INNER JOIN "app2_student_user_permissions" ON ("auth_permission"."id" = "app2_student_user_permissions"."permission_id") INNER JOIN "django_content_type" ON ("auth_permission"."content_type_id" = "django_content_type"."id") WHERE "app2_student_user_permissions"."student_id" = 1 ORDER BY "django_content_type"."app_label" ASC, "django_content_type"."model" ASC, "auth_permission"."codename" ASC </code></pre> <hr> <p><strong>EDIT</strong></p> <p>App2 student's schema/table will not be created until some point later in the program. Since App2 student has manytomany relation to Permissions, Permissions now has app1 relation and app2 relation. I think it's registered by ManyRelatedManager. (Permissions sees these two relations as public schema)</p> <p>If I do student1_of_app1.user_permissions.all(), Django will iterate over the relations that Permissions has. Including the non existing App2 table. Thus it'll create django.db.utils.ProgrammingError: relation does not exist.</p> <p>However, sometimes there is no error because Django gets into app1 relation first, but sometimes Django gets into app2 relation, hence the error.</p> <p>How can I prevent this from happening?</p>
5
2016-08-08T05:37:38Z
38,932,776
<p>I found the problem was about django tenant schemas and not django. <s>The migrate_schema --shared actually migrates the whole makemigration files regardless of the app being shared or tenant.</s> Both apps (shared and tenant) are registered in <code>django_content_type</code> table which also registered in <code>auth_permissions</code>. Hence, the relation doesn't exist because tenant tables are not created yet at that point but manytomany relation has been registered for Permissions.</p>
3
2016-08-13T12:33:21Z
[ "python", "django", "postgresql", "django-models", "django-rest-framework" ]
Processing/Transposing Pandas Dataframe
38,821,985
<p>I got the following pandas dataframe: </p> <pre><code>Id Category 1 type 2 1 type 3 1 type 2 2 type 1 2 type 2 </code></pre> <p>I need to process and transpose the above data frame to:</p> <pre><code>Id Category_type_1 Category_type_2 Category_type_3 1 0 2 1 2 1 1 0 </code></pre> <p>Appreciate if anyone could shows the easiest way to code this in python. </p>
3
2016-08-08T05:42:55Z
38,822,028
<pre><code>pd.crosstab(df['Id'], df['Category']) Out: Category type 1 type 2 type 3 Id 1 0 2 1 2 1 1 0 </code></pre>
3
2016-08-08T05:47:14Z
[ "python", "pandas", "dataframe", "pivot-table", "crosstab" ]
Processing/Transposing Pandas Dataframe
38,821,985
<p>I got the following pandas dataframe: </p> <pre><code>Id Category 1 type 2 1 type 3 1 type 2 2 type 1 2 type 2 </code></pre> <p>I need to process and transpose the above data frame to:</p> <pre><code>Id Category_type_1 Category_type_2 Category_type_3 1 0 2 1 2 1 1 0 </code></pre> <p>Appreciate if anyone could shows the easiest way to code this in python. </p>
3
2016-08-08T05:42:55Z
38,822,035
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p> <pre><code>print (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0)) Category type 1 type 2 type 3 Id 1 0 2 1 2 1 1 0 </code></pre> <p><strong>Timings</strong>:</p> <p><code>Small DataFrame - len(df)=5</code>:</p> <pre><code>In [63]: %timeit df.groupby(df.columns.tolist()).size().unstack().fillna(0) 1000 loops, best of 3: 1.33 ms per loop In [64]: %timeit (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0)) 100 loops, best of 3: 3.77 ms per loop In [65]: %timeit pd.crosstab(df['Id'], df['Category']) 100 loops, best of 3: 4.82 ms per loop </code></pre> <p><code>Large DataFrame - len(df)=5k</code>:</p> <pre><code>df = pd.concat([df]*1000).reset_index(drop=True) In [59]: %timeit df.groupby(df.columns.tolist()).size().unstack().fillna(0) 1000 loops, best of 3: 1.73 ms per loop In [60]: %timeit (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0)) 100 loops, best of 3: 4.64 ms per loop In [61]: %timeit pd.crosstab(df['Id'], df['Category']) 100 loops, best of 3: 5.46 ms per loop </code></pre> <p><code>Very large DataFrame - len(df)=5m</code>:</p> <pre><code>df = pd.concat([df]*1000000).reset_index(drop=True) In [55]: %timeit df.groupby(df.columns.tolist()).size().unstack().fillna(0) 1 loop, best of 3: 514 ms per loop In [56]: %timeit (df.pivot_table(index='Id', columns='Category', aggfunc=len, fill_value=0)) 1 loop, best of 3: 907 ms per loop In [57]: %timeit pd.crosstab(df['Id'], df['Category']) 1 loop, best of 3: 822 ms per loop </code></pre>
2
2016-08-08T05:48:02Z
[ "python", "pandas", "dataframe", "pivot-table", "crosstab" ]
Processing/Transposing Pandas Dataframe
38,821,985
<p>I got the following pandas dataframe: </p> <pre><code>Id Category 1 type 2 1 type 3 1 type 2 2 type 1 2 type 2 </code></pre> <p>I need to process and transpose the above data frame to:</p> <pre><code>Id Category_type_1 Category_type_2 Category_type_3 1 0 2 1 2 1 1 0 </code></pre> <p>Appreciate if anyone could shows the easiest way to code this in python. </p>
3
2016-08-08T05:42:55Z
38,823,489
<p>I'd <code>groupby</code> and use <code>size</code></p> <pre><code>df.groupby(df.columns.tolist()).size().unstack().fillna(0) </code></pre> <p><a href="http://i.stack.imgur.com/mzcAD.png" rel="nofollow"><img src="http://i.stack.imgur.com/mzcAD.png" alt="enter image description here"></a></p>
4
2016-08-08T07:29:01Z
[ "python", "pandas", "dataframe", "pivot-table", "crosstab" ]
Cannot install python package tables
38,822,105
<pre><code>[root@e06e8f90e201 optimus]# pip install tables Collecting tables Downloading tables-3.2.3.1.tar.gz (7.1MB) 100% |################################| 7.1MB 120kB/s Complete output from command python setup.py egg_info: /usr/bin/ld: cannot find -lhdf5 collect2: error: ld returned 1 exit status * Using Python 2.7.5 (default, Nov 20 2015, 02:00:19) * USE_PKGCONFIG: True .. ERROR:: Could not find a local HDF5 installation. You may need to explicitly state where your local HDF5 headers and library can be found by setting the ``HDF5_DIR`` environment variable or by using the ``--hdf5`` command-line option. ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-SvZePF/tables/ </code></pre> <p>Has anyone got any idea what this means? I have not explicitly/knowningly installed tables before, so maybe it does not exist on my local pc?</p>
0
2016-08-08T05:55:23Z
38,822,223
<p>From the blurp on <code>tables</code> on PyPI: </p> <blockquote> <p>PyTables is built on top of the HDF5 library ...</p> </blockquote> <p>Therefore you have to have the libhdf5.[so/a] library installed, which is also mentioned in the <a href="http://www.pytables.org/usersguide/installation.html" rel="nofollow">prerequisites</a>. </p> <p>On Debian (or derived) systems you should be able to install with your package manager:</p> <pre><code>apt-get install libhdf5-dev </code></pre> <p>( on <code>yum</code> based systems search with something like <code>yum --enablerepo=epel provides \*/libhdf5.so</code>).</p>
1
2016-08-08T06:05:35Z
[ "python", "pip", "hdf5" ]
PSQL - How to filter out if a column value equals a specific string
38,822,255
<p>I created a database with column called option where the value is a varchar of either 'Call', 'Put', or None. When I set up the database I made the default value None if there was no Call or Put.</p> <p>I'm trying to filter out the rows that contain 'Call' or 'Put' for option. However, when I write the query</p> <p>SELECT * FROM holdings h WHERE h.option != 'Call' AND h.option != 'Put';</p> <pre><code>I get this error: curr.execute('SELECT option FROM holdings WHERE option != 'Call';') ^ SyntaxError: invalid syntax </code></pre> <p>When I try to use NOT LIKE '%Call%' I get this error:</p> <pre><code>curr.execute('SELECT option FROM holdings AS h WHERE option NOT LIKE '%Call%';') NameError: name 'Call' is not defined </code></pre> <p>Any help would be appreciated</p> <p>Thanks!</p> <p>Code looks like this:</p> <pre><code>import psycopg2 import csv conn = psycopg2.connect('dbname = db user = asmith') curr = conn.cursor() curr.execute('SELECT option FROM holdings h WHERE option NOT LIKE '%Call%';') tups = curr.fetchall() for tup in tups: print tup </code></pre> <p>Edit: When I run these two lines: </p> <pre><code>curr.execute('SELECT * FROM holdings h WHERE option = \'Call\' OR option = \'Put\';') curr.execute('SELECT * FROM holdings h WHERE option != \'Call\' AND option != \'Put\';') </code></pre> <p>The first query gives me all the rows with a Call or Put, but when I run the second query I get nothing, even though it should theoretically give me all of the rows with option that are None. Does anyone know why that is?</p>
1
2016-08-08T06:08:23Z
38,822,481
<p>There is logic error in statement. You should write this instead:</p> <pre><code>SELECT * FROM holdings h WHERE h.option != 'Call' OR h.option != 'Put'; </code></pre> <p>or this:</p> <pre><code>SELECT * FROM holdings h WHERE h.option NOT IN ( 'Call' , 'Put'); </code></pre> <p>Thanks.</p>
0
2016-08-08T06:25:19Z
[ "python", "postgresql" ]
PSQL - How to filter out if a column value equals a specific string
38,822,255
<p>I created a database with column called option where the value is a varchar of either 'Call', 'Put', or None. When I set up the database I made the default value None if there was no Call or Put.</p> <p>I'm trying to filter out the rows that contain 'Call' or 'Put' for option. However, when I write the query</p> <p>SELECT * FROM holdings h WHERE h.option != 'Call' AND h.option != 'Put';</p> <pre><code>I get this error: curr.execute('SELECT option FROM holdings WHERE option != 'Call';') ^ SyntaxError: invalid syntax </code></pre> <p>When I try to use NOT LIKE '%Call%' I get this error:</p> <pre><code>curr.execute('SELECT option FROM holdings AS h WHERE option NOT LIKE '%Call%';') NameError: name 'Call' is not defined </code></pre> <p>Any help would be appreciated</p> <p>Thanks!</p> <p>Code looks like this:</p> <pre><code>import psycopg2 import csv conn = psycopg2.connect('dbname = db user = asmith') curr = conn.cursor() curr.execute('SELECT option FROM holdings h WHERE option NOT LIKE '%Call%';') tups = curr.fetchall() for tup in tups: print tup </code></pre> <p>Edit: When I run these two lines: </p> <pre><code>curr.execute('SELECT * FROM holdings h WHERE option = \'Call\' OR option = \'Put\';') curr.execute('SELECT * FROM holdings h WHERE option != \'Call\' AND option != \'Put\';') </code></pre> <p>The first query gives me all the rows with a Call or Put, but when I run the second query I get nothing, even though it should theoretically give me all of the rows with option that are None. Does anyone know why that is?</p>
1
2016-08-08T06:08:23Z
38,823,045
<p>Looks like Syntax error here:</p> <p><code>curr.execute('SELECT option FROM holdings h WHERE option NOT LIKE '%Call%';')</code></p> <p>String 1 is <code>'SELECT option FROM holdings h WHERE option NOT LIKE '</code>, breaks with <code>'</code> (before <code>%Call%</code>), then some variable named Call (which Your compiler cannot find) and then String 2 <code>';'</code></p> <p>You have to escape <code>'</code> with backslash like this:</p> <p><code>curr.execute('SELECT option FROM holdings AS h WHERE option NOT LIKE \'%Call%\';')</code></p>
3
2016-08-08T07:02:42Z
[ "python", "postgresql" ]
Getting a sane default date axis in matplotlib
38,822,294
<p>I am often working interactively in an ipython shell or ipython notebook. Say, I had a <code>pandas.DataFrame</code> with a <code>DatetimeIndex</code>, like this:</p> <pre><code>idx = pd.date_range("12:00", periods=400000, freq="S") df = pd.DataFrame({"temp":np.random.normal(size=len(idx))}, index=idx) </code></pre> <p>In order to plot it, I can simply do:</p> <pre><code>plt.plot(df.temp, '.') </code></pre> <p><a href="http://i.stack.imgur.com/0CVZq.png" rel="nofollow"><img src="http://i.stack.imgur.com/0CVZq.png" alt="enter image description here"></a></p> <p>As one can see, neither do I have to specify the x-axis data, as it is nicely inferred from the DataFrame, nor do I have to specify that I actually want the x-axis to be date based. (Gone are the times of <code>plt.plot_date</code>) That's awesome!</p> <p>But the x-axis looks ugly in two ways:</p> <ul> <li>the labels overlap and are hard to read.</li> <li>the labels show hours instead of dates.</li> </ul> <p>One can <em>almost</em> repair this problem like, e.g. like this:</p> <pre><code>plt.plot(df.temp, '.') import matplotlib.dates as mdates plt.gca().xaxis.set_major_formatter( mdates.DateFormatter('%d-%m-%Y %H:%M:%S')) plt.gcf().autofmt_xdate() </code></pre> <p>As one can see in the resulting plot, the leftmost date label is clipped. <a href="http://i.stack.imgur.com/zXheX.png" rel="nofollow"><img src="http://i.stack.imgur.com/zXheX.png" alt="leftmost date label is clipped"></a></p> <p>So by increasing the code size by 300% one can almost get a nice plot.</p> <hr> <p>Now to my question:</p> <p>I can for my life not remember these 2..3 lines, which I'll have to type in always, when making date based plots. It makes the interface feel clumsy and slow. I always have to google for the solution ...</p> <p>Can I setup matplotlib in a way, that it kind of remembers what my personal defaults are with regard to date based plotting?</p> <p>I guess, I could actually hack into the <code>plot</code> function. But maybe there is a way using these <code>matplotlib.rc_params</code>, which I wasn't able to find.</p> <p>As I said above, <code>plt.plot</code> is going a long way to actually guess what I want. It guesses the x-axis data to be the index of the DataFrame .. and it guesses it should actually plot a date based x-axis instead of a the numerical representation of the dates. How can I <em>add</em> something to this?</p> <p>I'm thinking of maybe even give it some hints like:</p> <pre><code>plt.plot(df.temp, '.', date_fmt='%d-%m-%Y %H:%M:%S') </code></pre> <p>or</p> <pre><code>plt.plot(df.temp, '.', autofmt_xdate=True) </code></pre>
2
2016-08-08T06:10:56Z
38,822,426
<p>You can use <a href="http://matplotlib.org/api/dates_api.html#matplotlib.dates.DateFormatter" rel="nofollow"><code>DateFormatter</code></a>:</p> <pre><code>import matplotlib.dates as mdates fig, ax = plt.subplots(figsize=(8,5)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y %H:%M:%S')) #rotates the tick labels automatically fig.autofmt_xdate() ax.plot(df["T"], '.') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/V8UHO.png" rel="nofollow"><img src="http://i.stack.imgur.com/V8UHO.png" alt="graph"></a></p>
2
2016-08-08T06:21:10Z
[ "python", "datetime", "pandas", "matplotlib" ]
Why does Python return an escaping backslash in a string?
38,822,301
<pre><code>'\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered' </code></pre> <p>gives as output:</p> <pre><code>'"atg is a codon, isn\'t it?" "Yes, it is", he answered' </code></pre> <p>Why is the escape character showing up in the output? </p> <p>When I type the string below, this doesn't happen.</p> <pre><code>'This is a codon, isn\'t it?' </code></pre> <p>The output I get is this:</p> <pre><code>"This is a codon, isn't it?" </code></pre>
0
2016-08-08T06:11:22Z
38,822,332
<p>because in first one the whole string is in one-quote so another one-quotes should be escaped. Whereas in second one the whole string is in double quote.</p> <pre><code>&gt;&gt;&gt; '\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered' '"atg is a codon, isn\'t it?" "Yes, it is", he answered' ^ ^ &gt;&gt;&gt; &gt;&gt;&gt; 'This is a codon, isn\'t it?' "This is a codon, isn't it?" # there is no need to escape the one-quote between double-quotes ^ ^ </code></pre>
2
2016-08-08T06:13:49Z
[ "python", "string", "syntax", "escaping" ]
Why does Python return an escaping backslash in a string?
38,822,301
<pre><code>'\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered' </code></pre> <p>gives as output:</p> <pre><code>'"atg is a codon, isn\'t it?" "Yes, it is", he answered' </code></pre> <p>Why is the escape character showing up in the output? </p> <p>When I type the string below, this doesn't happen.</p> <pre><code>'This is a codon, isn\'t it?' </code></pre> <p>The output I get is this:</p> <pre><code>"This is a codon, isn't it?" </code></pre>
0
2016-08-08T06:11:22Z
38,822,339
<p>The escape character is needed because that is the string that, if typed out exactly, would reproduce the string. The string contains both single and double quotes, so whichever type encloses the string will need to be escaped within the string.</p>
0
2016-08-08T06:14:19Z
[ "python", "string", "syntax", "escaping" ]
Why does Python return an escaping backslash in a string?
38,822,301
<pre><code>'\"atg is a codon, isn\'t it?\" \"Yes, it is\", he answered' </code></pre> <p>gives as output:</p> <pre><code>'"atg is a codon, isn\'t it?" "Yes, it is", he answered' </code></pre> <p>Why is the escape character showing up in the output? </p> <p>When I type the string below, this doesn't happen.</p> <pre><code>'This is a codon, isn\'t it?' </code></pre> <p>The output I get is this:</p> <pre><code>"This is a codon, isn't it?" </code></pre>
0
2016-08-08T06:11:22Z
38,822,877
<p>You get to choose either single quotes or double quotes to enclose a string. Any occurrences of your enclosing quote character must be escaped with a '\'.</p> <pre><code>&gt;&gt;&gt; b = 'Hello\'s' &gt;&gt;&gt; a = "Hello's" &gt;&gt;&gt; b = 'Hello\'s' &gt;&gt;&gt; c = 'Hello"s' &gt;&gt;&gt; d = "Hello\"s" &gt;&gt;&gt; a "Hello's" &gt;&gt;&gt; b "Hello's" &gt;&gt;&gt; c 'Hello"s' &gt;&gt;&gt; d 'Hello"s' &gt;&gt;&gt; </code></pre>
0
2016-08-08T06:51:38Z
[ "python", "string", "syntax", "escaping" ]
Interaction with Python cmd module
38,822,323
<p>I have a program that uses <code>cmd</code> module and looks like this:</p> <pre><code>import cmd class Prog(cmd.Cmd): prompt = '&gt;&gt;' def do_reverse(self, line): print line[::-1] def do_exit(self, line): return True if __name__ == '__main__': Prog().cmdloop() </code></pre> <p>I want to write to programs <code>stdin</code> and read from its <code>stdout</code> programmatically. I'm trying to achieve that as follows:</p> <pre><code>from subprocess import Popen, PIPE class ShellDriver(object): def __init__(self, process): self.process = process self.prompt = '&gt;&gt;' self.output = '' self.read() def read(self): while not self.output.endswith(self.prompt): chars = self.process.stdout.read(1) if chars == '': break self.output += chars result = self.output.replace('\n' + self.prompt, '') self.output = '' return result def execute(self, command): self.process.stdin.write(command + '\n') return self.read() if __name__ == '__main__': p = Popen(['python', 'prog.py'], stdin=PIPE, stdout=PIPE) cmd = ShellDriver(p) print cmd.execute('reverse abc') cmd.execute('exit') </code></pre> <p>However when I ran this code from PyCharm it works fine, but when I ran it from command line it hangs. As I understood there is a conflict between consoles (console that reader script is running from and programs console) since they are trying to use the same pipes, and this issue doesn't exist in PyCharm because it redirects I\O to its own console.</p> <p>Is there a way to get this working in the system console?</p> <p>I'm on Windows (cross platform solution is preferable) and Python 2.7</p>
0
2016-08-08T06:13:00Z
38,884,680
<p>Finally found an answer. By default interpreter works in buffered mode sending data to stdout in chunks, in order to avoid that it should be running in unbuffered mode with <code>-u</code> command line argument:</p> <pre><code>p = Popen(['python', '-u', 'prog.py'], stdin=PIPE, stdout=PIPE) </code></pre>
0
2016-08-10T22:37:53Z
[ "python", "windows", "cmd", "stdout", "stdin" ]
user uploaded image is not displaying
38,822,342
<p>Image uploaded by user is not displaying though i have not done wrong in template. Also i have defined MEDIA_URL and MEDIA_ROOT. What might be the reason for not getting image displayed?</p> <p><strong>Code</strong> </p> <pre><code> image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) </code></pre> <p>project/urls.py(urls.py of main project)</p> <pre><code>from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('shop.urls', namespace='shop')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre> <p>Settings.py</p> <pre><code>MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') </code></pre> <p>templates/shop/product/list.html</p> <pre><code>&lt;a href="{{ product.get_absolute_url }}"&gt; &lt;img src="{% if product.image %} {{ product.image.url }} {% else %} {% static 'img/no_image.png' %} {% endif %}" &gt; &lt;/a&gt; </code></pre> <p>I know this question is asked multiple times but my code took after the documentation and still i could not display image. Could anyone help me, please?</p>
0
2016-08-08T06:14:23Z
38,830,873
<p>It is working now after fresh restart of the server. So the above code and process of serving media files is correct.</p>
0
2016-08-08T13:45:38Z
[ "python", "django", "django-templates", "django-1.10" ]
slicing multiple arrays where their indices are not the same
38,822,385
<p>I have four time series signals that turns on at different times and later turns off at different times as well. time = [(0,23),(5,15),(9,20),(12,25)]</p> <p>For example, channel0 turned on at time 0 and off at 23sec. channel two turned on at time =5sec and turned off at 15.</p> <p>I want to segment each array according to their content in the following time grid: [(0,4),(5,8),(9,11),(12,14),(15,19),(20,22),(23,24)] if the signal didn't start yet or the signal is over, I want my list to contain an empty slot.</p> <p>Eventually, I want to produce a list similar to Signals0,Signals1,Signal2,Signals3. the time grid would be </p> <p>Here is a minimal example describing my problem:</p> <pre><code>import numpy as np Signals=[np.random.normal(0,1,23),np.random.normal(0,1,10),np.random.normal(0,1,11),np.random.normal(0,1,13)] np.set_printoptions(precision=3) print Signals time = [(0,23),(5,15),(9,20),(12,25)] print time Signals0=[[-0.585, 0.005, -0.932, -0.322, -0.527], [0.246, 1.95 , -0.673,0.389] [0.285,0.245, 1.226], [0.41,-0.184, 1.642], [0.463,0.813, 0.021, 0.531, -0.59], [0.694, -0.528, 0.924], [] ] Signals1 = [[], [ 0.74 , -0.692, -0.302, 0.558], [0.475, -1.605, 0.438], [ -1.106,-0.02 , 0.042], [], [], [] ] Signals2 = [[], [], [1.435, 0.855, -2.098], [0.532, -0.596, 1.415], [0.727, 0.617,-1.88 , -1.203, -0.918], [], [] ] Signals3 = [[], [], [], [2.462, -1.198, -0.098], [-2.152, 1.081, -0.519, 0.675, -0.077], [1.491, 0.071, -0.267, 1.243], [-1.507] ] </code></pre> <p>This is how my channels look like</p> <pre><code>[array([-0.585, 0.005, -0.932, -0.322, -0.527, 0.246, 1.95 , -0.673, 0.389, 0.285, 0.245, 1.226, 0.41 , -0.184, 1.642, 0.463, 0.813, 0.021, 0.531, -0.59 , 0.694, -0.528, 0.924]), array([ 0.74 , -0.692, -0.302, 0.558, 0.475, -1.605, 0.438, -1.106, -0.02 , 0.042]), array([ 1.435, 0.855, -2.098, 0.532, -0.596, 1.415, 0.727, 0.617, -1.88 , -1.203, -0.918]), array([ 2.462, -1.198, -0.098, -2.152, 1.081, -0.519, 0.675, -0.077, 1.491, 0.071, -0.267, 1.243, -1.507])] </code></pre>
0
2016-08-08T06:17:14Z
38,822,627
<p>First don't use upper case for variable name so <code>signals</code> and not <code>Signals</code>.</p> <pre><code>all_signals = [[s[slice(max(0,lg-lt),max(0,ug-lt+1))] for (lg,ug) in grid] for (lt,ut),s in zip(time, signals)] for i,s in enumerate(all_signals): print "\nsignal",i for g in s: print g </code></pre> <p>gives:</p> <pre><code>signal 0 [-0.585 0.005 -0.932 -0.322 -0.527] [ 0.246 1.95 -0.673 0.389] [ 0.285 0.245 1.226] [ 0.41 -0.184 1.642] [ 0.463 0.813 0.021 0.531 -0.59 ] [ 0.694 -0.528 0.924] [] signal 1 [] [ 0.74 -0.692 -0.302 0.558] [ 0.475 -1.605 0.438] [-1.106 -0.02 0.042] [] [] [] signal 2 [] [] [ 1.435 0.855 -2.098] [ 0.532 -0.596 1.415] [ 0.727 0.617 -1.88 -1.203 -0.918] [] [] signal 3 [] [] [] [ 2.462 -1.198 -0.098] [-2.152 1.081 -0.519 0.675 -0.077] [ 1.491 0.071 -0.267] [ 1.243 -1.507] </code></pre>
1
2016-08-08T06:34:24Z
[ "python", "numpy" ]
conv2d_transpose is dependent on batch_size when making predictions
38,822,411
<p>I have a neural network currently implemented in tensorflow, but I am having a problem making predictions after training, because I have a conv2d_transpose operations, and the shapes of these ops are dependent on the batch size. I have a layer that requires output_shape as an argument:</p> <pre><code>def deconvLayer(input, filter_shape, output_shape, strides): W1_1 = weight_variable(filter_shape) output = tf.nn.conv2d_transpose(input, W1_1, output_shape, strides, padding="SAME") return output </code></pre> <p>That is actually used in a larger model I have constructed like the following:</p> <pre><code> conv3 = layers.convLayer(conv2['layer_output'], [3, 3, 64, 128], use_pool=False) conv4 = layers.deconvLayer(conv3['layer_output'], filter_shape=[2, 2, 64, 128], output_shape=[batch_size, 32, 40, 64], strides=[1, 2, 2, 1]) </code></pre> <p>The problem is, if I go to make a prediction using the trained model, my test data has to have the same batch size, or else I get the following error.</p> <pre><code>tensorflow.python.framework.errors.InvalidArgumentError: Conv2DBackpropInput: input and out_backprop must have the same batch size </code></pre> <p>Is there some way that I can get a prediction for an input with variable batch size? When I look at the trained weights, nothing seems to depend on batch size, so I can't see why this would be a problem.</p>
0
2016-08-08T06:19:38Z
38,838,883
<p>So I came across a solution based on the issues forum of tensorflow at <a href="https://github.com/tensorflow/tensorflow/issues/833" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/833</a>.</p> <p>In my code</p> <pre><code> conv4 = layers.deconvLayer(conv3['layer_output'], filter_shape=[2, 2, 64, 128], output_shape=[batch_size, 32, 40, 64], strides=[1, 2, 2, 1]) </code></pre> <p>my output shape that get passed to deconvLayer was hard coded with a predetermined batch shape when training. By altering this to the following:</p> <pre><code>def deconvLayer(input, filter_shape, output_shape, strides): W1_1 = weight_variable(filter_shape) dyn_input_shape = tf.shape(input) batch_size = dyn_input_shape[0] output_shape = tf.pack([batch_size, output_shape[1], output_shape[2], output_shape[3]]) output = tf.nn.conv2d_transpose(input, W1_1, output_shape, strides, padding="SAME") return output </code></pre> <p>This allows the shape to be dynamically inferred at run time and can handle a variable batch size. </p> <p>Running the code, I no longer receive this error when passing in any batch size of test data. I believe this is necessary due to the fact that the inference of shapes for transpose ops is not as straightforward at the moment as it is for normal convolutional ops. So where we would usually use None for the batch_size in normal convolutional ops, we must provide a shape, and since this could vary based on input, we must go through the effort of dynamically determining it.</p>
0
2016-08-08T21:35:56Z
[ "python", "tensorflow", "deep-learning" ]
convert pandas dataframe to list of tuples and drop all pandas datatypes
38,822,486
<p>I need to convert a dataframe into a format that can be inserted into a sql table. </p> <pre><code>data_tuples = [tuple(row) for row in df.values] </code></pre> <p>How do I remove all the non python datatypes from a pandas dataframe (including np ints and nans and NaTs)?</p>
1
2016-08-08T06:25:48Z
38,822,831
<p>if you want to do it efficiently, use corresponding pandas method - <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow">to_sql()</a>:</p> <pre><code>from sqlalchemy import create_engine # conn = create_engine('postgresql://user:password@host:port/dbname') conn = create_engine('postgresql+psycopg2://user:password@host:port/dbname') df.to_sql('table_name', conn) </code></pre> <p>where <code>conn</code> is a SQLAlchemy engine connection object</p> <p><a href="http://docs.sqlalchemy.org/en/latest/core/engines.html#postgresql" rel="nofollow">Docs: using SQLAlchemy with PostgreSQL</a></p>
3
2016-08-08T06:49:12Z
[ "python", "pandas", "numpy", "dataframe" ]
Python insert value to foreign key attribute (MYSQL)
38,822,540
<p>i created two table in MySQL database </p> <p>Staff table:</p> <pre><code>+----+-----------+------------- | ID | NAME | +----+-----------+------------- | No data available in table | +----+-----------+------------- </code></pre> <p>Qualification table:</p> <pre><code>+----+----------+--------------+ | ID | title | staff_ID | +----+----------+--------------+ | No data available in table | +----+--------------+----------- </code></pre> <p>ID of both table is primary key and staff_ID of qualification table is foreign key. My python code is like</p> <pre><code>con=pymysql.connect(host='localhost',port=3306,user='root',password='admin',db='mydb') cursor=con.cursor() cursor.execute("INSERT INTO Staff (ID,Name)VALUES (%s,%s)",(1001,"MR Tan")) cursor.execute("INSERT INTO Qualification VALUES (%s,%s,%s)",(2001,"Professor","select ID from Staff where ID=1001")) con.commit() cursor.close() con.close() </code></pre> <p>i try to insert value to foreign key attribute but i get "TypeError: not all arguments converted during string formatting"</p>
0
2016-08-08T06:29:38Z
38,822,622
<p>Why are you executing the <code>SELECT</code> statement. You already have the ID available. Pass it as such:</p> <pre><code>con = pymysql.connect(host='localhost',port=3306,user='root',password='admin',db='mydb') cursor = con.cursor() cursor.execute( "INSERT INTO Staff (ID,Name) VALUES (%d,%s)", (1001,"MR Tan") ) cursor.execute( "INSERT INTO Qualification VALUES (%d,%s,%d)", (2001,"Professor",1001) ) </code></pre>
0
2016-08-08T06:34:12Z
[ "python", "mysql", "database" ]
Python insert value to foreign key attribute (MYSQL)
38,822,540
<p>i created two table in MySQL database </p> <p>Staff table:</p> <pre><code>+----+-----------+------------- | ID | NAME | +----+-----------+------------- | No data available in table | +----+-----------+------------- </code></pre> <p>Qualification table:</p> <pre><code>+----+----------+--------------+ | ID | title | staff_ID | +----+----------+--------------+ | No data available in table | +----+--------------+----------- </code></pre> <p>ID of both table is primary key and staff_ID of qualification table is foreign key. My python code is like</p> <pre><code>con=pymysql.connect(host='localhost',port=3306,user='root',password='admin',db='mydb') cursor=con.cursor() cursor.execute("INSERT INTO Staff (ID,Name)VALUES (%s,%s)",(1001,"MR Tan")) cursor.execute("INSERT INTO Qualification VALUES (%s,%s,%s)",(2001,"Professor","select ID from Staff where ID=1001")) con.commit() cursor.close() con.close() </code></pre> <p>i try to insert value to foreign key attribute but i get "TypeError: not all arguments converted during string formatting"</p>
0
2016-08-08T06:29:38Z
38,822,682
<p>2 ways :</p> <p>You can try</p> <pre><code>cursor.execute("INSERT INTO Staff (ID,Name)VALUES (%d,%s)",(1001,"MR Tan")) cursor.execute("INSERT INTO Qualification VALUES (%d,%s,%s)",(2001,"Professor","select ID from Staff where ID=1001")) </code></pre> <p>or </p> <pre><code>cursor.execute("INSERT INTO Staff (ID,Name)VALUES (%s,%s)",("1001","MR Tan")) cursor.execute("INSERT INTO Qualification VALUES (%s,%s,%s)",("2001","Professor","select ID from Staff where ID=1001")) </code></pre>
0
2016-08-08T06:38:42Z
[ "python", "mysql", "database" ]
How to iterate through a list of tuple within tuple in python?
38,822,546
<p>Let's say I have a list like so: <code>[(1, (1,2)), (2, (23, -10)), (3, (4, 5))...]</code></p> <p>I want to get (1,2), (23, -10), etc</p> <p>edit: Thanks for help. I didn't know about list comprehension as I'm not too familiar with python</p>
-5
2016-08-08T06:29:49Z
38,822,644
<p>Yes, you can iterate over all tuples and then take the second element:</p> <pre><code>list = [(1, (1,2)), (2, (23, -10)), (3, (4, 5))] for elem in list: print(elem[1]) </code></pre> <p>In each iteration elem value its <code>(1,(1,2)) -&gt; (2,(23,-10))</code> -> .... Then you take the second item of the tuple (index 1)</p>
-2
2016-08-08T06:35:38Z
[ "python" ]
How to iterate through a list of tuple within tuple in python?
38,822,546
<p>Let's say I have a list like so: <code>[(1, (1,2)), (2, (23, -10)), (3, (4, 5))...]</code></p> <p>I want to get (1,2), (23, -10), etc</p> <p>edit: Thanks for help. I didn't know about list comprehension as I'm not too familiar with python</p>
-5
2016-08-08T06:29:49Z
38,822,734
<p>Try Something like this:-</p> <p>Here is List and get other list of tuples:-</p> <pre><code>a = [(1, (1,2)), (2, (23, -10)), (3, (4, 5))...] b = map(lambda item: item[1], a) print b </code></pre>
-1
2016-08-08T06:42:47Z
[ "python" ]
How can I use 2 submit buttons in a single form in HTML & Django?
38,822,641
<p>In this, only second button is working. If I delete the second button, then the first button is worked.I want to work both buttons.How can I work them?</p> <p>HTML template IInd_std.html</p> <pre><code> &lt;form method="get" action="#"&gt; &lt;table style="width:100%"&gt; &lt;tr&gt; &lt;th&gt;Slno&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Attendance&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;Abijith&lt;/td&gt; &lt;td&gt;{{ u }} &lt;input type="submit" value="present" name="add20"/&gt; &lt;input type="submit" value="absent" name="add21"/&gt; {{ v }} &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>views.py</p> <pre><code>u = 1; v = 1 def IInd_std(request): global u,v my_dictionary = { "u" : u, "v" : v } if request.GET.get('add20'): u = u+1 my_dictionary = { "u" : u, } if request.GET.get('add21'): v = v+1 my_dictionary = { "v" : v, } return render(request, 'blog/IInd_std.html', my_dictionary) </code></pre>
0
2016-08-08T06:35:21Z
38,822,753
<p>Try changing it to:</p> <pre><code>request.GET['add20']: </code></pre> <p>and</p> <pre><code>request.GET['add21']: </code></pre> <p>Also, you are re-initializing <code>my_dictionary</code> in your if statements.</p> <p>Change it to:</p> <pre><code>my_dictionary["u"] = u </code></pre> <p>and</p> <pre><code>my_dictionary["v"] = v </code></pre>
0
2016-08-08T06:44:38Z
[ "python", "html", "django" ]
Django could not import settings after import a model in a python script
38,822,725
<p>After import one of my models in a python script, when I run the localhost server, I get this <strong>erro</strong>r, I have been reading, but all my tries were a fail:</p> <pre><code>ubuntu@INN0095_VM2:~/env_Compass4D/Compass4D$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 9, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 261, in fetch_command commands = get_commands() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 107, in get_commands apps = settings.INSTALLED_APPS File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 54, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 49, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 132, in __init__ % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'Compass4D.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named Compass4D.settings </code></pre> <p><strong>My sys.path:</strong></p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.path ['', '/usr/lib/pymodules/python2.7', '/usr/local/lib/python2.7/site-packages', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol'] </code></pre> <p><strong>manage.py:</strong></p> <pre><code>#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Compass4D.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) </code></pre> <p><strong>wsgi.py:</strong></p> <pre><code>import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Compass4D.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() </code></pre> <p>Thanks for your help!</p>
0
2016-08-08T06:42:13Z
38,823,161
<p>I confirm the problem was that I had manage.py, settings.py and wsgi.py in the same folder, then you can not write appName.settings in the path import conf, thanks guys.</p>
0
2016-08-08T07:08:55Z
[ "python", "django", "django-wsgi" ]
Python re.search anomaly
38,822,730
<p>I have a routine that searches through a directory of files and extracts a customer number from the filename:</p> <pre><code>import os import re suffix= '.csv' # For each file in input folder, extract customer number input_list = os.listdir(path_in) for input_file in input_list: fileInput = os.path.join(path_in,input_file) customer_ID = re.search('custID_(.+?)'+suffix,fileInput).group(1) print(customer_ID) </code></pre> <p>With <code>suffix='.csv'</code> and a folder full of csv files:</p> <blockquote> <p>avg_hrly_custID_8147611.csv, avg_hrly_custID_8147612.csv, avg_hrly_custID_8147613.csv ...</p> </blockquote> <p>I get the expected output:</p> <blockquote> <p>8147611, 8147612, 8147613...</p> </blockquote> <p>BUT, with <code>suffix = '.png'</code> and a folder of .png image files,:</p> <blockquote> <p>yearly_average_plot_custID_8147611.png, yearly_average_plot_custID_8147612.png, yearly_average_plot_custID_8147613.png ...</p> </blockquote> <p>I get this error:</p> <blockquote> <p>AttributeError: 'NoneType' object has no attribute 'group'</p> </blockquote> <p>Why won't it work for image files? </p>
0
2016-08-08T06:42:16Z
38,840,479
<p>@BrenBarn spotted the cause of the problem. The regex failed because there was a subdirectory in the directory who's name didn't match. I've solved it by introducing <code>try....except</code> </p> <pre><code>import os import re suffix= '.png' # For each file in input folder, extract customer number input_list = os.listdir(path_in) for input_file in input_list: fileInput = os.path.join(path_in,input_file) try: customer_ID = re.search('custID_(.+?)'+suffix,fileInput).group(1) print(customer_ID) except: pass </code></pre>
0
2016-08-09T00:56:12Z
[ "python", "search", "substring" ]
Convert bytes to long in python
38,822,736
<p>Here is my C++ code:</p> <pre><code> int r; // result of log_2(v) goes here union { unsigned int u[2]; double d; } t; // temp t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] = 0x43300000; t.u[__FLOAT_WORD_ORDER!=LITTLE_ENDIAN] = v; t.d -= 4503599627370496.0; r = (t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] &gt;&gt; 20) - 0x3FF; return r; </code></pre> <p>I am trying to replicate this piece code exactly in python and so far my code is :</p> <pre><code>class s(Structure): _fields_ = [("u", c_ulonglong), ("d", c_double)] t = s() t.u = pack('&lt;Q', c_ulonglong(int("0x43300000", 16))) # Error cannot convert argument to integer t.u = pack('&gt;Q', c_ulonglong(v)) t.d -= 4503599627370496.0 r = (t.u &gt;&gt; 20) - 0x3FF </code></pre> <p>I am getting an error while packing the hex number into "u" the way it is mentioned in the c++ code. I would like to solve this error and successfully complete this code in python.</p>
-1
2016-08-08T06:42:58Z
38,879,187
<p>It helps to have a complete example (lots of undefined values here), but this is closer to the intent. Note the use of <code>Union</code> and <code>c_int * 2</code>:</p> <pre><code>class s(Union): _fields_ = [("u", c_int * 2), ("d", c_double)] t = s() t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] = 0x43300000 t.u[__FLOAT_WORD_ORDER!=LITTLE_ENDIAN] = v # whatever that is t.d -= 4503599627370496.0 r = (t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] &gt;&gt; 20) - 0x3FF return r </code></pre>
0
2016-08-10T16:43:55Z
[ "python", "c", "struct", "ctypes", "little-endian" ]
SQLAlchemy raises QueuePool limit of size 10 overflow 10 reached, connection timed out after some time
38,822,829
<p>While using Flask-SQLAlchemy I get the error 'QueuePool limit of size 10 overflow 10 reached, connection timed out' consistently, after some time. I tried to increase connection pool size, but it only deferred the problem. </p> <pre><code>def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) initialize_db(app) db = SQLAlchemy() def initialize_db(app): db.init_app(app) SQLALCHEMY_POOL_SIZE = 100 </code></pre>
1
2016-08-08T06:49:07Z
38,955,433
<p></p> <p>I figured out the problem. The issue was sometimes database connection was going to lost state, which is causing pool size to be Exhausted after some interval.<br> To fix the issue I made the MySQL server configuration change for query timeout and made it 1 second.<br> After 1 second if the query didn't respond it will throw Exception and I added except block in code where that query was invoked(In my case it was GET query). In the Except block, I issued rollback command. </p> <p></p>
1
2016-08-15T12:50:08Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Why does next() always display the same value?
38,822,840
<p>I was practicing the <code>yield</code> statement. I have written the following function in Python 2.7:</p> <pre><code>&gt;&gt;&gt; def mygen(): ... i = 0 ... j = 3 ... for k in range(i, j): ... yield k ... &gt;&gt;&gt; mygen().next() 0 &gt;&gt;&gt; mygen().next() 0 &gt;&gt;&gt; mygen().next() 0 </code></pre> <p>Whenever I call the <code>mygen().next()</code> it always displays output as <code>0</code>, instead of <code>0</code>, <code>1</code>, <code>2</code> &amp; <code>StopIteration</code>. Can anybody please explain this?</p>
3
2016-08-08T06:49:37Z
38,822,868
<p>You are <em>recreating</em> the generator each time, so it starts from the beginning each time.</p> <p>Create the generator <strong>once</strong>:</p> <pre><code>gen = mygen() gen.next() gen.next() gen.next() </code></pre> <p>Generator functions produce a new iterator every time you call them; that way you can produce multiple independent copies. Each independent iterator is an invocation of the function that can be stepped through separately from the others:</p> <pre><code>&gt;&gt;&gt; def mygen(): ... i = 0 ... j = 3 ... for k in range(i, j): ... yield k ... &gt;&gt;&gt; gen1 = mygen() &gt;&gt;&gt; gen2 = mygen() &gt;&gt;&gt; gen1.next() 0 &gt;&gt;&gt; gen1.next() 1 &gt;&gt;&gt; gen2.next() 0 &gt;&gt;&gt; gen2.next() 1 &gt;&gt;&gt; gen1.next() 2 &gt;&gt;&gt; gen1.next() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration </code></pre> <p>Note that you probably want to use the <a href="https://docs.python.org/2/library/functions.html#next" rel="nofollow"><code>next()</code> function</a> instead of calling <code>generator.next()</code> directly:</p> <pre><code>next(gen) </code></pre> <p><code>generator.next()</code> is considered a hook (Python 3 renamed it to <code>generator.__next__()</code> and the <code>next()</code> function is the official API to invoke it in a cross-version compatible way.</p>
10
2016-08-08T06:51:13Z
[ "python", "python-2.7", "generator", "yield" ]
Why does next() always display the same value?
38,822,840
<p>I was practicing the <code>yield</code> statement. I have written the following function in Python 2.7:</p> <pre><code>&gt;&gt;&gt; def mygen(): ... i = 0 ... j = 3 ... for k in range(i, j): ... yield k ... &gt;&gt;&gt; mygen().next() 0 &gt;&gt;&gt; mygen().next() 0 &gt;&gt;&gt; mygen().next() 0 </code></pre> <p>Whenever I call the <code>mygen().next()</code> it always displays output as <code>0</code>, instead of <code>0</code>, <code>1</code>, <code>2</code> &amp; <code>StopIteration</code>. Can anybody please explain this?</p>
3
2016-08-08T06:49:37Z
38,823,621
<p>A function definition containing a yield statement returns a generator. You have to apply the next function to that generator in stead of the function itself. To clarify, your function definition is equivalent to:</p> <pre><code> def mygen(): i, j = 0, 3 return (k for k in range(i, j)) </code></pre> <p>or:</p> <pre><code> mygen = lambda :(k for k in range(0, 3)) </code></pre> <p>So you would use it like this:<br></p> <pre><code> gen1 = mygen() gen2 = mygen() next(gen1) // returns 0 next(gen1) // returns 1 list(gen1) // returns [2] list(gen2) // returns [0, 1, 2] </code></pre>
0
2016-08-08T07:36:34Z
[ "python", "python-2.7", "generator", "yield" ]
Sorting and Grouping Nested Lists Consists of Class Objects
38,822,843
<p>I have hundreds of text files that i need to parse according to the username and the date. I tried to put useful data in the text files in lists like that:</p> <pre><code> [ ['1234245@gmail.com', '34209809' '1434546354', '2016-07-18 00:20:58'], ['abcd@gmail.com', '234534345', '09402380',, '2016-07-18 00:20:03'], ['username@gmail.com', '345315531','1098098098', '2016-07-18 02:40:00'], ['abcd@gmail.com', '345431353', '231200023', '2016-07-18 15:45:49'], ['1234245@gmail.com', '23232424', '234809809', '2016-07-18 20:45:40'] ] </code></pre> <p>However, I would like to sort them according to the datetime and group by usernames so the output will be like:</p> <pre><code> [ ['1234245@gmail.com', '23232424', '234809809', '2016-07-18 20:45:40'], ['1234245@gmail.com', '34209809' '1434546354', '2016-07-18 00:20:58'], ['abcd@gmail.com', '345431353', '231200023', '2016-07-18 15:45:49'], ['abcd@gmail.com', '234534345', '09402380',, '2016-07-18 00:20:03'], ['username@gmail.com', '345315531','1098098098', '2016-07-18 02:40:00'] ] </code></pre> <p>Here is my code:</p> <pre><code> import glob from operator import itemgetter from itertools import groupby def read_large_file(filename): matrix=[] global username username=[] for myfile in glob.glob(filename): infile = open(myfile, "r") for row in infile: row=row.strip() array=row.split(';') username.append(array[9]) matrix.append(cdr(array[9],array[17],array[18],array[8])) return matrix class cdr(object): def__init__(self,username,total_seconds_since_start,download_bytes,date_time): self.username=username self.total_seconds_since_start=total_seconds_since_start self.download_bytes=download_bytes self.date_time=date_time def GroupByUsername(matrix): new_matrix=[] new_matrix=groupby(matrix, itemgetter(0)) return new_matrix matrix=read_large_file('C:\Users\ceren\.spyder2/test/*') matrix_new=GroupByUsername(matrix) </code></pre> <p>I tried to use the solution in this link : <a href="http://stackoverflow.com/questions/409370/sorting-and-grouping-nested-lists-in-python">Sorting and Grouping Nested Lists in Python</a> however i've got these errors:</p> <pre><code> 'cdr' object does not support indexing 'cdr' object is not iterable </code></pre>
-1
2016-08-08T06:49:46Z
38,822,892
<p>You can probably just use the simple Python built-in sort.</p> <pre><code>sorted_list = sorted(data, key=lambda user_info: (user_info[0], user_info[3])) </code></pre> <p>The lambda key tells Python how to sort the list (ascending). For each entry in <code>data</code>, <code>user_info</code> will be the list of 4 attributes. So, <code>user_info[0]</code> will be the email, and <code>user_info[3]</code> will be the datetime.</p>
2
2016-08-08T06:52:38Z
[ "python", "list", "sorting", "object", "grouping" ]
How to return my cursor automatically after an indentation in Python?
38,822,876
<p>any code editor knows where to indent in python since python uses <code>:</code> as its indent flag, but after completing a code block, we will want our cursor to go back in the last place it was, like this: </p> <pre><code>def test_func(): print("Here we have an auto indent") # but how to # return, without pressing the backspace key </code></pre>
0
2016-08-08T06:51:32Z
38,823,314
<p>No, it is not possible for an IDE to know when your block is ending in all cases.</p> <p>The are a few <em>exceptions</em> where it is reasonable to <em>guess</em> that you wanted to end the current indentation level. E.g. using <code>pass</code> to leave a block 'empty' where the Python grammar requires you to use a block, or using <code>return</code>, <code>break</code> or <code>continue</code>, statements that make it impossible for Python to reach the remainder of the indented block.</p> <p>However, <em>because</em> you must un-indent to signal the end of a block in Python, your IDE can't know in all cases when a block ends <em>either</em>. You can easily follow a <code>print()</code> call with several empty lines, then another line of code at the same indentation level, and it'll still be part of <code>test_func()</code> body.</p> <p>It depends entirely on your editor if they implement auto-indentation rules at all, but any that does, is bound by the same limitations inherent in Python.</p>
2
2016-08-08T07:17:43Z
[ "python", "vim", "syntax", "editor", "indentation" ]
Return null inside the class
38,823,086
<p>I'm wondering why my code below return null, however print command return proper value, could anyone explain my that? </p> <pre><code>class Newclass: def __init__(self,portal): config = configparser.ConfigParser() config.read("config.ini") self.connection_source=config.get(portal,'Sources') def getPortalSources(self): # print (connection_source) ## Sources return self.connection_source emp1 = Newclass('portalname') emp1.getPortalSources() </code></pre>
0
2016-08-08T07:05:03Z
38,823,148
<p>You are calling the function but doing nothing with its return value.</p> <p>Try to actually fetch and print it:</p> <pre><code>emp1 = Newclass('portalname') value = emp1.getPortalSources() print(value) </code></pre> <p>You may also want to catch that <code>configparser.NoOptionError</code> that waits to happen if <code>Sources</code> is not in the config file:</p> <pre><code>try: self.connection_source = config.get(portal,'Sources') except configparser.NoOptionError: print("Couldn't find 'Sources' in conf file") </code></pre>
2
2016-08-08T07:08:25Z
[ "python" ]
Return null inside the class
38,823,086
<p>I'm wondering why my code below return null, however print command return proper value, could anyone explain my that? </p> <pre><code>class Newclass: def __init__(self,portal): config = configparser.ConfigParser() config.read("config.ini") self.connection_source=config.get(portal,'Sources') def getPortalSources(self): # print (connection_source) ## Sources return self.connection_source emp1 = Newclass('portalname') emp1.getPortalSources() </code></pre>
0
2016-08-08T07:05:03Z
38,823,786
<pre><code>import configparser, os class ConfigIni(dict, configparser.ConfigParser): def __init__(self, file): configparser.ConfigParser.__init__(self) self.iniFile=file if os.path.isfile(self.iniFile): self.read(self.iniFile) for section in self.sections(): self[section] = {} for var in self.options(section): val = self.get(section, var) self[section][var] = val f=os.path.join(os.getcwd(), 'config.ini') print(ConfigIni(f)) </code></pre>
1
2016-08-08T07:47:16Z
[ "python" ]
Python: Best way to frame a loop with 2 alternating tasks
38,823,146
<p>I have a list of items that I need to process. Easy enough: just a simple <code>for x in list</code>.</p> <p>However, the commands inside the for loop need to be slightly different, on an alternating basis. So <br/><code>n = 0</code> is handled one way, then <code>n = 1</code> a different way; then <code>n = 2</code> the same as <code>n = 0</code>. Note that <code>n</code> and <code>x</code> are different!</p> <p>At the moment, the only way I can think of doing this is with an incremental counter and if statements. I'm presuming there's an easier way? </p> <p>Hope this makes sense. Thanks</p>
2
2016-08-08T07:08:18Z
38,823,252
<p>Check out enumeration:</p> <pre><code>for n, item in enumerate(my_list): if n % 2 == 0: # do things for even-indexed items else: # do things for odd-indexed items </code></pre>
1
2016-08-08T07:14:13Z
[ "python" ]
Python: Best way to frame a loop with 2 alternating tasks
38,823,146
<p>I have a list of items that I need to process. Easy enough: just a simple <code>for x in list</code>.</p> <p>However, the commands inside the for loop need to be slightly different, on an alternating basis. So <br/><code>n = 0</code> is handled one way, then <code>n = 1</code> a different way; then <code>n = 2</code> the same as <code>n = 0</code>. Note that <code>n</code> and <code>x</code> are different!</p> <p>At the moment, the only way I can think of doing this is with an incremental counter and if statements. I'm presuming there's an easier way? </p> <p>Hope this makes sense. Thanks</p>
2
2016-08-08T07:08:18Z
38,823,256
<p>You could use <a href="https://docs.python.org/3.4/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> and <a href="https://docs.python.org/3.4/reference/expressions.html#binary-arithmetic-operations" rel="nofollow">modulo</a> to alternate:</p> <pre><code>li = ['a', 'b', 'c'] for idx, ch in enumerate(li): if idx % 2 == 0: # do A else: # do B </code></pre>
2
2016-08-08T07:14:17Z
[ "python" ]
Python: Best way to frame a loop with 2 alternating tasks
38,823,146
<p>I have a list of items that I need to process. Easy enough: just a simple <code>for x in list</code>.</p> <p>However, the commands inside the for loop need to be slightly different, on an alternating basis. So <br/><code>n = 0</code> is handled one way, then <code>n = 1</code> a different way; then <code>n = 2</code> the same as <code>n = 0</code>. Note that <code>n</code> and <code>x</code> are different!</p> <p>At the moment, the only way I can think of doing this is with an incremental counter and if statements. I'm presuming there's an easier way? </p> <p>Hope this makes sense. Thanks</p>
2
2016-08-08T07:08:18Z
38,823,257
<p>You can handle using map and a apply function, each function must be in the same position as the value it needs to operate with. functional approach</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import operator import functools import itertools def apply(f, e): return f(e) elems = range(10) functs = itertools.cycle([functools.partial(operator.add, 1), functools.partial(operator.add, 2)]) results = list(itertools.starmap(apply, zip(functs, elems))) print results [1, 3, 3, 5, 5, 7, 7, 9, 9, 11] </code></pre> <p><code>apply</code> method just takes a function and a value, returns the result of applying that function to that value. the you <code>starmap</code> apply to the list of functions zipped to the list of elements or values, is like zipping 2 lists but one of them contains functions that will consume the other lists values.</p>
1
2016-08-08T07:14:20Z
[ "python" ]
Python: Best way to frame a loop with 2 alternating tasks
38,823,146
<p>I have a list of items that I need to process. Easy enough: just a simple <code>for x in list</code>.</p> <p>However, the commands inside the for loop need to be slightly different, on an alternating basis. So <br/><code>n = 0</code> is handled one way, then <code>n = 1</code> a different way; then <code>n = 2</code> the same as <code>n = 0</code>. Note that <code>n</code> and <code>x</code> are different!</p> <p>At the moment, the only way I can think of doing this is with an incremental counter and if statements. I'm presuming there's an easier way? </p> <p>Hope this makes sense. Thanks</p>
2
2016-08-08T07:08:18Z
38,823,956
<p>python comprehensions can be useful for things like this in a very simple way where in another language you have to write functions and control statements in python you can just do: </p> <pre><code>new_list = [f2(list_item) for i, list_item in zip(range(len(old_list)), old_list) if i%2==0 else f1(list_item)] </code></pre>
1
2016-08-08T07:57:22Z
[ "python" ]
spotipy auth workflow results in error=state_mismatch in browser
38,823,180
<p>I am attempting to run through the Spotify authentication workflow via <code>spotipy</code> and it's <code>prompt_for_user_token</code> utility. I am following the directions <a href="https://developer.spotify.com/web-api/tutorial/" rel="nofollow">here</a>, the official Spotify web API tutorial, verbatim from what I can tell. And using the examples from Paul Lamere's Spotipy project <a href="https://github.com/plamere/spotipy/tree/master/examples" rel="nofollow">here</a></p> <p>I have a premium Spotify account and a registered application with a client id and client secret (both 32 character strings) and the redirect URI given in the example (<code>...//localhost:8888/callback</code>). all shown on my application page (<code>...//developer.spotify.com/my-applications</code>)</p> <p>Start my application server from <code>app.js</code> the "authentication_code" example in the tutorial (which has been modified to contain my app's client id, client secret, and redirect URI).</p> <pre><code>$node app.js Listening on 8888 </code></pre> <p>after exporting my app's <code>CLIENT_ID</code>, <code>CLIENT_SECRET</code>, and <code>REDIRECT_URI</code> into my environment as described in the tutorial, I run the <code>user_playlists.py</code> example script from Paul Lamere's <code>spotipy</code> examples with my username (really user "id" - 9 digit number) as it's only command line argument.</p> <p>The browser (chrome) has opened previously with the option to log in to Spotify via Facebook or password. I choose Facebook and I then get a browser alert that reads:</p> <pre><code>localhost:8888 says: There was an error during the authentication. </code></pre> <p>With the browser url at:</p> <pre><code>...localhost:8888/#error=state_mismatch </code></pre> <p>And the <code>prompt_for_user_token</code> function never returns. Every time I run the example script now the browser opens, but to a blank page, with the same browser alert and URL.</p> <p>Is it obvious to anyone what I'm doing wrong or how to find out what the nature or any details of the authentication error are or how to resolve the <code>state_mismatch</code> error or even what it means?</p>
0
2016-08-08T07:09:52Z
38,840,369
<p>I found a great and basic example of spotify oauth workflow via spotipy which doesn't depend on node or util.prompt_for_user_token <a href="http://stackoverflow.com/a/34973812/2403318">here</a> contributed by perelin.</p> <p>In addition the spoti<strong>py</strong> documentation does not indicate which of several user level scopes is required for any given spoti<strong>py</strong> method which would be helpful. But moreover it's a good idea to understand <a href="https://developer.spotify.com/web-api/using-scopes/" rel="nofollow">scopes</a> before you start writing client code for spotify. For example: "playlist-read-private" is required for user_playlists as opposed to, "user-library-read", which isn't made clear in the spoti<strong>py</strong> documentation so you need to look at the official spotify web api documentation and be aware of which scope your spoti<strong>py</strong> method will (probably) require.</p>
0
2016-08-09T00:34:08Z
[ "python", "authentication", "oauth-2.0", "spotify", "spotipy" ]
How to remove part of the string after specific word in Python
38,823,270
<p>I get API-responses as a string which can be in two different formats:</p> <p>1) <code>This is a message. &lt;br&gt;&lt;br&gt;This message was created by Jimmy.</code> </p> <p>2) </p> <pre><code>This is a message. Text can be in the new row. This message was created by Jimmy. </code></pre> <p>I want to remove text "This message was created by ['name']" from every message. Expected result:</p> <blockquote> <p>This is a message.</p> </blockquote> <p>This is what I have tried:<br> <code>modified_message = re.search('(.+?)&lt;br&gt;&lt;br&gt;', message).group(1)</code></p> <p>It works with the 1) example, but it doesn't with 2) of course. </p> <p>How could I filter the text off from 2) example as it is multiline string or could it be possible with one expression?</p>
-3
2016-08-08T07:15:19Z
38,823,715
<p>Please check this. Added code to handle multiline strings.</p> <pre><code>import re data1 = "This is a message. &lt;br&gt;&lt;br&gt;This message was created by Jimmy." data2 = """ This is a message. This message was created by Jimmy. """ print "First case..." print data1 output1 = re.findall('(.*?)This message was created',data1,re.DOTALL)[0].replace("&lt;br&gt;",'') print "Output is ..." print(output1) print "----------------------------------------" print "Second Case..." print data2 print "Output is ..." output2 = re.findall('(.*?)This message was created',data1,re.DOTALL)[0].replace("&lt;br&gt;",'') print(output2) </code></pre> <p>Output:</p> <pre><code>C:\Users&gt;python main.py First case... This is a message. &lt;br&gt;&lt;br&gt;This message was created by Jimmy. Output is ... This is a message. ---------------------------------------- Second Case... This is a message. This message was created by Jimmy. Output is ... This is a message. </code></pre>
1
2016-08-08T07:42:14Z
[ "python" ]
Copy nested dictionary to another dictionary with all the levels.
38,823,327
<p>For some third party APIs, there is a huge data that needs to be sent in the API parameters. And input data comes to our application in the CSV format. </p> <p>I receive all the rows of the CSV containing around 120 columns, in a plane dict format by CSV DictReader. </p> <pre><code>file_data_obj = csv.DictReader(open(file_path, 'rU')) </code></pre> <p>This gives me each row in following format:</p> <pre><code>CSV_PARAMS = { 'param7': "Param name", 'param6': ["some name"], 'param5': 1234, 'param4': 999999999, 'param3': "some ", 'param2': {"x name":"y_value"}, 'param1': None, 'paramA': "", 'paramZ': 2.687 } </code></pre> <p>And there is one nested dictionary containing all the third-party API parameters as keys with blank value.</p> <pre><code>eg. API_PARAMS = { "param1": "", "param2": "", "param3": "", "param4": { "paramA": "", "paramZ": {"test1":1234, "name":{"hello":1}}, ... }, "param5": { "param6": "", "param7": "" }, ... } </code></pre> <p>I have to map all the CSV Values to API parameters dynamically. following code works but upto 3 level nesting only. </p> <pre><code>def update_nested_params(self, paramdict, inpdict, result={}): """Iterate over nested dictionary up to level 3 """ for k, v in paramdict.items(): if isinstance(v, dict): for k1, v1 in v.items(): if isinstance(v1, dict): for k2, _ in v1.items(): result.update({k:{k1:{k2: inpdict.get(k2, '')}}}) else: result.update({k:{k1: inpdict.get(k1, '')}}) else: result.update({k: inpdict.get(k, '')}) return result self.update_nested_params(API_PARAMS, CSV_PARAMS) </code></pre> <p>Is there any other efficient way to achieve this for n number of nestings of the API Parameters?</p>
0
2016-08-08T07:18:29Z
38,823,542
<p>You could use recursion:</p> <pre><code>def update_nested_params(self, template, source): result = {} for key, value in template.items(): if key in source: result[key] = source[key] elif not isinstance(value, dict): # assume the template value is a default result[missing] = value else: # recurse result[missing] = self.update_nested_params(value, source) return result </code></pre> <p>This copies the 'template' (<code>API_PARAMS</code>) recursively, taking any key it finds from <code>source</code> if available, and recurses if not but the value in <code>template</code> is another dictionary. This handles nesting up to <code>sys.getrecursionlimit()</code> levels (default 1000).</p>
1
2016-08-08T07:31:45Z
[ "python", "csv", "dictionary" ]
How do I vectorize a conditional timedelta operation?
38,823,331
<p>I wanted to avoid the for loops in Python pandas, but I didn't make it due to lack of exposure. I wanted to derive a new column based on an existing column by adding some amount of information to it.</p> <p>My Scenario:</p> <pre><code>for each in data['days']: if each&lt;100000: clsdate.append(datetime.now()+ relativedelta(days=each)) else: clsdate.append(datetime.now()) data['clsdate'] = clsdate </code></pre> <p>data['days'] contains a int number. Here, I am iterating the whole column and doing the sum </p> <blockquote> <p>today's date + no.of days = Closing date</p> </blockquote> <p>and appending the value to a list. Then adding the list to the dataframe based on the if condition i.e., range of the value.</p> <p>How to avoid this looping and adding in a single shot.</p>
0
2016-08-08T07:18:56Z
38,823,361
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>Series.apply</code></a>: </p> <pre><code>data['clsdate'] = data['days'].apply(lambda x: datetime.now() + relativedelta(days=x)) </code></pre>
0
2016-08-08T07:20:58Z
[ "python", "loops", "pandas" ]
How do I vectorize a conditional timedelta operation?
38,823,331
<p>I wanted to avoid the for loops in Python pandas, but I didn't make it due to lack of exposure. I wanted to derive a new column based on an existing column by adding some amount of information to it.</p> <p>My Scenario:</p> <pre><code>for each in data['days']: if each&lt;100000: clsdate.append(datetime.now()+ relativedelta(days=each)) else: clsdate.append(datetime.now()) data['clsdate'] = clsdate </code></pre> <p>data['days'] contains a int number. Here, I am iterating the whole column and doing the sum </p> <blockquote> <p>today's date + no.of days = Closing date</p> </blockquote> <p>and appending the value to a list. Then adding the list to the dataframe based on the if condition i.e., range of the value.</p> <p>How to avoid this looping and adding in a single shot.</p>
0
2016-08-08T07:18:56Z
38,823,468
<p>You can use pandas' datetime functions:</p> <pre><code>df = pd.DataFrame() df['days'] = [1, 3, 2, 4] pd.to_datetime('now') + pd.to_timedelta(df['days'], unit='days') Out: 0 2016-08-09 07:25:22 1 2016-08-11 07:25:22 2 2016-08-10 07:25:22 3 2016-08-12 07:25:22 Name: days, dtype: datetime64[ns] </code></pre>
3
2016-08-08T07:27:35Z
[ "python", "loops", "pandas" ]
Using py2exe packing python program with ply got strange error?
38,823,400
<p>I downloaded the <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a>, and ran a simple test in <code>ply3.8/test/calclex.py</code></p> <pre><code># ----------------------------------------------------------------------------- # calclex.py # ----------------------------------------------------------------------------- import sys if ".." not in sys.path: sys.path.insert(0,"..") import ply.lex as lex tokens = ( 'NAME','NUMBER', 'PLUS','MINUS','TIMES','DIVIDE','EQUALS', 'LPAREN','RPAREN', ) # Tokens t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_EQUALS = r'=' t_LPAREN = r'\(' t_RPAREN = r'\)' t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' def t_NUMBER(t): r'\d+' try: t.value = int(t.value) except ValueError: print("Integer value too large %s" % t.value) t.value = 0 return t t_ignore = " \t" def t_newline(t): r'\n+' t.lexer.lineno += t.value.count("\n") def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1) # Build the lexer lexer = lex.lex() </code></pre> <p>it works well. But when I use <code>py2exe</code> packing it to executable file. When run it, I get an error like:</p> <pre><code>Traceback (most recent call last): File "calclex.py", line 46, in &lt;module&gt; lexer = lex.lex() File "ply\lex.pyc", line 906, in lex File "ply\lex.pyc", line 580, in validate_all File "ply\lex.pyc", line 822, in validate_rules File "ply\lex.pyc", line 833, in validate_module File "inspect.pyc", line 690, in getsourcelines File "inspect.pyc", line 526, in findsource File "inspect.pyc", line 403, in getfile TypeError: &lt;module '__main__' (built-in)&gt; is a built-in module </code></pre> <p>Has anyone tried to pack the ply to executable file?<br> And my <code>setup.py</code> is as follows:</p> <pre><code>from distutils.core import setup import py2exe setup(console=["calclex.py"]) </code></pre>
0
2016-08-08T07:23:59Z
38,836,056
<p>Ply insists that its grammars be defined in real files, not virtualized filesystems. So it won't work with py2exe or pyinstaller or other such programmers which attempt to pack python source files into single archives. (See also <a href="http://stackoverflow.com/q/35589881">Pyinstaller and Ply IOError: source code not available</a>.)</p> <p>I don't know of a simple workaround. Perhaps it should be reported as a feature request to the Ply maintainers.</p>
0
2016-08-08T18:25:31Z
[ "python", "py2exe", "ply" ]
Scrape 'deep' audio features using Spotipy python library
38,823,403
<p>For the past few days, I've been using the excellent <a href="http://spotipy.readthedocs.io/en/latest/" rel="nofollow">Spotipy</a> python library for the Spotify Web API. Having navigated my way to accessing the basic information, however (track/artist/album names, urls, uris, etc), I'm now trying to find some deeper track features (BPM, tempo, etc). </p> <p>I know that Spotify makes this information publicly available because <a href="http://static.echonest.com/SortYourMusic/" rel="nofollow">some enterprising services</a> have already integrated these into their offerings. My question is, is there any way to access this sort of information through the <code>spotipy.Spotify()</code> object or is it simply not attainable as of the latest spotipy release (v2.3.8)?</p> <p>Any assistance would be greatly appreciated!</p>
0
2016-08-08T07:24:13Z
38,824,511
<p>That link is not an enterprising service, it is part of the examples for the Echo nest parts of the Spotify Web API.</p> <p><a href="https://developer.spotify.com/web-api/code-examples/#echo-nest-example-apps" rel="nofollow">https://developer.spotify.com/web-api/code-examples/#echo-nest-example-apps</a> <a href="https://github.com/plamere/SortYourMusic" rel="nofollow">https://github.com/plamere/SortYourMusic</a></p> <p>What might be confusing is that the attributes are not available on the track object, but you need to call a new method called audio_features.</p> <p><a href="https://developer.spotify.com/web-api/get-several-audio-features/" rel="nofollow">https://developer.spotify.com/web-api/get-several-audio-features/</a> <a href="http://spotipy.readthedocs.io/en/latest/#spotipy.client.Spotify.audio_features" rel="nofollow">http://spotipy.readthedocs.io/en/latest/#spotipy.client.Spotify.audio_features</a></p> <p>This worked for me:</p> <pre class="lang-python prettyprint-override"><code>import spotipy import spotipy.oauth2 credentials = spotipy.oauth2.SpotifyClientCredentials() spotify = spotipy.Spotify(client_credentials_manager=credentials) print spotify.audio_features(['4uLU6hMCjMI75M1A2tKUQC']) </code></pre>
0
2016-08-08T08:30:27Z
[ "python", "api", "spotify", "bpm", "spotipy" ]
Django-DRF See all posts from friends
38,823,485
<p>I just started toying around with the Django Rest Framework, so I'm still not entirely sure what exactly is going on. But I have a user model, a friend model, and a post model, I also have my serializers and views in order. But, I can't figure out how to return all the posts from my user's friends. Any help would be greatly appreciated.</p> <p>models.py</p> <pre><code>class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField('email address', unique=True, db_index=True) password1 = models.CharField(max_length=50) username = models.CharField('username', max_length=50, unique=True, db_index=True) image = models.FileField(upload_to='photos', null=True, blank=True) joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] objects = CustomUserManager() def __unicode__(self): return self.username class Meta: unique_together = (('username', 'password1'),) class Friendship(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey(CustomUser, related_name="friendship_creator") friend = models.ForeignKey(CustomUser, related_name="friends") class Post(models.Model): poster = models.ForeignKey(CustomUser) body = models.CharField(max=200) def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) </code></pre> <p>serializers.py</p> <pre><code>class FriendSerializer(HyperlinkedModelSerializer): class Meta: model = Friendship fields = ('creator', 'friend', 'created_at') readonly_fields = 'created_at' class CustomUserSerializer(HyperlinkedModelSerializer): friends = FriendSerializer(many=True) class Meta: model = CustomUser fields = ('email', 'username', 'password1', 'image', 'friends') readonly_fields = 'image' </code></pre> <p>views.py</p> <pre><code>class FriendViewSet(ModelViewSet): queryset = CustomUser.objects.all() serializer_class = FriendSerializer class UserProfileViewSet(RetrieveModelMixin, UpdateModelMixin, GenericViewSet): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer </code></pre>
0
2016-08-08T07:28:55Z
38,825,596
<p>This may get you started,</p> <p>So what you need to do first is get all the friends, you can do that by using</p> <pre><code>friends = &lt;user_objects&gt;.Friendship_set.all() </code></pre> <p>Read more about is <a href="https://docs.djangoproject.com/ja/1.9/topics/db/queries/#related-objects" rel="nofollow">here</a>.</p> <p>Now that you have all the friends of that particular user, covert their IDs to list and use the in list filter.</p> <pre><code>Post.objects.filter(poster__id__in=[list_of_ids_of_friends]) </code></pre> <p>See <a href="http://stackoverflow.com/questions/1981524/django-filtering-on-foreign-key-properties">this answer</a> for filtering on foreign key properties.</p>
1
2016-08-08T09:28:13Z
[ "python", "django", "django-rest-framework" ]
How to read data in specific column of XLSX file using python script
38,823,609
<p>I want to read the data given in 2nd and 3rd column from XLSX file.</p> <pre><code>import xlrd workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb") sheet = workbook.sheet_by_index(0) for row in range(sheet.nrows): cols = (sheet.row_values(row,1)) and (sheet.row_values(row,2)) print(cols) </code></pre> <p>But is gives below error when i executed above script..</p> <pre><code>biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File C:\Python27\.....\xlrd_init_.py", line 1323, in getbof raise XLRDError('Expected BOF record; found 0x%04x' % opcode) xlrd.biffh.XLRDError: Expected BOF record; found 0x4b50 </code></pre>
1
2016-08-08T07:35:55Z
38,824,150
<p>This example read all the content of the excel sheet and puts it in a matrix (list of lists), then you can use the columns you need:</p> <pre><code>import xlrd workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb") sheet = workbook.sheet_by_index(0) rows = [] for i in range(sheet.nrows): columns = [] for j in range(range.ncols): columns.append(sheet.cell(i, j).value) rows.append(columns) print rows </code></pre>
0
2016-08-08T08:08:43Z
[ "python", "python-2.7" ]
How to read data in specific column of XLSX file using python script
38,823,609
<p>I want to read the data given in 2nd and 3rd column from XLSX file.</p> <pre><code>import xlrd workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb") sheet = workbook.sheet_by_index(0) for row in range(sheet.nrows): cols = (sheet.row_values(row,1)) and (sheet.row_values(row,2)) print(cols) </code></pre> <p>But is gives below error when i executed above script..</p> <pre><code>biff_version = bk.getbof(XL_WORKBOOK_GLOBALS) File C:\Python27\.....\xlrd_init_.py", line 1323, in getbof raise XLRDError('Expected BOF record; found 0x%04x' % opcode) xlrd.biffh.XLRDError: Expected BOF record; found 0x4b50 </code></pre>
1
2016-08-08T07:35:55Z
38,824,277
<p>Try this</p> <pre><code>import xlrd workbook = xlrd.open_workbook("C:/Users/File.xlsx","rb") sheets = workbook.sheet_names() required_data = [] for sheet_name in sheets: sh = workbook.sheet_by_name(sheet_name) for rownum in range(sh.nrows): row_valaues = sh.row_values(rownum) required_data.append((row_valaues[0], row_valaues[1])) print required_data </code></pre>
0
2016-08-08T08:17:30Z
[ "python", "python-2.7" ]
youtube-dl package - Python, SyntaxError: invalid syntax
38,823,965
<p>I installed youtube-dl using pip <code>sudo pip install youtube-dl</code>and the install was successful. When I run import youtube-dl from a python script, it says invalid syntax.</p> <pre><code>python youtube_downloader.py File "youtube_downloader.py", line 1 import youtube-dl ^ SyntaxError: invalid syntax </code></pre> <p>I tried upgrading the same, with <code>sudo pip install youtube-dl --upgrade</code>. It says requirement already satisfied. </p> <p><code>Requirement already up-to-date: youtube-dl in ./Library/Python/2.7/lib/python/site-packages</code></p> <p>I removed the package and installed <code>youtube-dl</code> with <code>brew install youtube-dl</code> also. The same thing again, installation was successful but when I import, it says syntax error.</p>
-1
2016-08-08T07:57:47Z
38,824,002
<p>You can't have the <code>-</code> sign in <code>import</code> statements, as the interpreter thinks you are trying to subtract.</p> <p>Use an underscore instead:</p> <pre><code>&gt;&gt; import youtube_dl &gt;&gt; </code></pre> <p>This is also described in the <a href="https://github.com/rg3/youtube-dl/blob/master/README.md#developer-instructions" rel="nofollow">documentation</a>.</p>
1
2016-08-08T07:59:54Z
[ "python", "python-2.7", "pip", "homebrew", "youtube-dl" ]
Getting variable from other class
38,823,985
<p>as totally beginner I need to ask you for some help. I defined class Config which take from config.ini file some information and put them into variable. Now I define class : Connection, which base of result from class Config. I was trying to do it many ways, but finally give up. Could anyone take a look ? </p> <pre><code>class Config: def __init__(self,system): self.config = configparser.ConfigParser() self.config.read("config.ini") self.connection_source=self.config.get(system,'Source') self.system=system def getsystemSources(self): return self.connection_source def getConnection(self,source): self.source=source self.connection_string=self.config.get('CONNECTION',self.system+'_'+source+'_'+'connectstring') ## Connection self.connection_user=self.config.get('CONNECTION',self.system+'_'+source+'_'+'user') ## Connection user self.connection_password=self.config.get('CONNECTION',self.system+'_'+source+'_'+'password') ## Connection pass class Connection(Config): def __init__ (self): self.connection_string=Config.connection_string self.connection_user=Config.connection_user self.connection_password=Config.connection_user self.connection_source=Config.connection_source def conn_function(self): print (self.connection_string) print (self.connection_user) print (self.connection_password) emp1 = Config('Windows') value=emp1.getsystemSources() print (value) emp2 = Connection() -&gt; how to run it ? </code></pre>
0
2016-08-08T07:59:01Z
38,824,033
<p>You simply pass the config object into the <code>__init__</code> function</p> <pre><code>class Config: def __init__(self,system): self.config = configparser.ConfigParser() self.config.read("config.ini") self.connection_source=self.config.get(system,'Source') self.getConnection(self.connection_source) self.system=system class Connection(Config): def __init__ (self, system): Config.__init__(self, system) emp1 = Connection('Windows') emp1.conn_function() </code></pre>
1
2016-08-08T08:01:53Z
[ "python" ]
regular expressions, the meaning of curly braces
38,824,038
<p>I am currently working on some python code, and it uses the "re" python package to search for an item with a regular expression pattern in a given list of items.</p> <p>While I was looking into the code, I encountered something I cannot understand about curly braces of the regular expression.</p> <p>The code fragment is like this.</p> <pre><code>regex = re.search("mov .* ptr \[(?P&lt;dst&gt;([(rax)|(rbx)|(rcx)|(rdx)|(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(r14)|(r15)]{3}))\], (?P&lt;src&gt;([(rax)|(rbx)|(rcx)|(rdx)|(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(r14)|(r15)]{3}))$", f) </code></pre> <p>f is a given input and looks like this.</p> <p>regex becomes 1, I printed the content of f, and it shows like this.</p> <p>"mov qword ptr [rsi], rdi"</p> <p>What I can't understand is the curly braces in the regular expression, which in this case "{3}". As far as I understand, the curly braces with only one number 'n' are used to indicate that the preceding expression needs to appear exactly 'n' times in order to match (three times in my case). (for instance, ab{3} would result in abbb to match) </p> <p>So, if that is correct, I think one of "(rax), (rbx), (rcx), etc.." needs to appear exactly three times in order to match, but regarding the content of f shown above, that is not the case.</p> <p>So I was wondering what point I am missing and how I can understand the curly braces in the regular expression above. </p>
0
2016-08-08T08:02:15Z
38,824,311
<p>The provided regex is using square brackets incorrectly. Brackets denote a set of characters, and so a <code>{3}</code> after those characters indicates any combination of three of those characters will match. You can see the documentation <a href="https://docs.python.org/2/library/re.html#regular-expression-syntax" rel="nofollow">here</a>, under <code>[]</code>.</p> <p>I believe the correct regex would be something like:</p> <pre><code>regex = re.search( 'mov .* ptr ' '\[(?P&lt;dst&gt;(rax|rbx|rcx|rdx|rsi|rdi|r9|r10|r11|r12|r13|r14|r15))\], ' '(?P&lt;src&gt;(rax|rbx|rcx|rdx|rsi|rdi|r9|r10|r11|r12|r13|r14|r15))$', f) </code></pre>
2
2016-08-08T08:18:58Z
[ "python", "regex" ]
regular expressions, the meaning of curly braces
38,824,038
<p>I am currently working on some python code, and it uses the "re" python package to search for an item with a regular expression pattern in a given list of items.</p> <p>While I was looking into the code, I encountered something I cannot understand about curly braces of the regular expression.</p> <p>The code fragment is like this.</p> <pre><code>regex = re.search("mov .* ptr \[(?P&lt;dst&gt;([(rax)|(rbx)|(rcx)|(rdx)|(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(r14)|(r15)]{3}))\], (?P&lt;src&gt;([(rax)|(rbx)|(rcx)|(rdx)|(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(r14)|(r15)]{3}))$", f) </code></pre> <p>f is a given input and looks like this.</p> <p>regex becomes 1, I printed the content of f, and it shows like this.</p> <p>"mov qword ptr [rsi], rdi"</p> <p>What I can't understand is the curly braces in the regular expression, which in this case "{3}". As far as I understand, the curly braces with only one number 'n' are used to indicate that the preceding expression needs to appear exactly 'n' times in order to match (three times in my case). (for instance, ab{3} would result in abbb to match) </p> <p>So, if that is correct, I think one of "(rax), (rbx), (rcx), etc.." needs to appear exactly three times in order to match, but regarding the content of f shown above, that is not the case.</p> <p>So I was wondering what point I am missing and how I can understand the curly braces in the regular expression above. </p>
0
2016-08-08T08:02:15Z
38,824,320
<p>What you have there is a bogus regular expression. It doesn't do quite what whoever wrote it meant it to do.</p> <p>To demonstrate this, I fed it an invalid input:</p> <pre><code>$ python2 ... &gt;&gt;&gt; s = ("mov .* ptr \[(?P&lt;dst&gt;([(rax)|(rbx)|(rcx)|(rdx)|" ... "(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(r14)|" ... "(r15)]{3}))\], (?P&lt;src&gt;([(rax)|(rbx)|(rcx)|(rdx)|" ... "(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(r14)|(r15)]{3}))$") &gt;&gt;&gt; import re &gt;&gt;&gt; r2 = re.search(s, "mov qword ptr [r5i], rdi") &gt;&gt;&gt; r2 &lt;_sre.SRE_Match object at 0x800684ca8&gt; &gt;&gt;&gt; r2.group('dst') 'r5i' &gt;&gt;&gt; r2 = re.search(s, "mov qword ptr [(5i], rdi") &gt;&gt;&gt; r2.group('dst') '(5i' &gt;&gt;&gt; </code></pre> <p>It's difficult to say what went through the mind of whoever wrote the expression, and how they came up with what they eventually used. You are correct, though, that the <code>{3}</code> means "repeat exactly three times".</p>
0
2016-08-08T08:19:41Z
[ "python", "regex" ]
regular expressions, the meaning of curly braces
38,824,038
<p>I am currently working on some python code, and it uses the "re" python package to search for an item with a regular expression pattern in a given list of items.</p> <p>While I was looking into the code, I encountered something I cannot understand about curly braces of the regular expression.</p> <p>The code fragment is like this.</p> <pre><code>regex = re.search("mov .* ptr \[(?P&lt;dst&gt;([(rax)|(rbx)|(rcx)|(rdx)|(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(r14)|(r15)]{3}))\], (?P&lt;src&gt;([(rax)|(rbx)|(rcx)|(rdx)|(rsi)|(rdi)|(r9)|(r10)|(r11)|(r12)|(r13)|(r14)|(r15)]{3}))$", f) </code></pre> <p>f is a given input and looks like this.</p> <p>regex becomes 1, I printed the content of f, and it shows like this.</p> <p>"mov qword ptr [rsi], rdi"</p> <p>What I can't understand is the curly braces in the regular expression, which in this case "{3}". As far as I understand, the curly braces with only one number 'n' are used to indicate that the preceding expression needs to appear exactly 'n' times in order to match (three times in my case). (for instance, ab{3} would result in abbb to match) </p> <p>So, if that is correct, I think one of "(rax), (rbx), (rcx), etc.." needs to appear exactly three times in order to match, but regarding the content of f shown above, that is not the case.</p> <p>So I was wondering what point I am missing and how I can understand the curly braces in the regular expression above. </p>
0
2016-08-08T08:02:15Z
38,824,446
<p>The others have answered it correctly, I just show you a way to visualize/test your regex patterns.</p> <p><img src="https://www.debuggex.com/i/WOX4TAA8eqlEp69E.png" alt="Regular expression visualization"></p> <p><a href="https://www.debuggex.com/r/WOX4TAA8eqlEp69E" rel="nofollow">Debuggex Demo</a></p>
0
2016-08-08T08:27:08Z
[ "python", "regex" ]
Regular expression for class with whitestaces using Beautifulsoup
38,824,121
<p>I found that method BeautifulSoup.find() splits class attribute by whitespaces. In that case I couldn't use regular expression as show in code below. Could you somebody help me to get right way find all 'tree children' elements:</p> <pre><code>import re from bs4 import BeautifulSoup r_html = "&lt;div class='root'&gt;" \ "&lt;div class='tree children1'&gt;text children 1 &lt;/div&gt;" \ "&lt;div class='tree children2'&gt;text children 2 &lt;/div&gt;" \ "&lt;div class='tree children3'&gt;text children 3 &lt;/div&gt;" \ "&lt;/div&gt;" bs_tab = BeautifulSoup(r_html, "html.parser") workspace_box_visible = bs_tab.findAll('div', {'class':'tree children1'}) print workspace_box_visible # result: [&lt;div class="tree children1"&gt;textchildren 1 &lt;/div&gt;] workspace_box_visible = bs_tab.findAll('div', {'class':re.compile('^tree children\d')}) print workspace_box_visible # result: [] &gt;&gt;&gt;&gt; empty array because #class name was splited by whitespace character&lt;&lt;&lt;&lt; # &gt;&gt;&gt;&gt;&gt;&gt; print all element classes &lt;&lt;&lt;&lt;&lt;&lt;&lt; def print_class(class_): print class_ return False workspace_box_visible = bs_tab.find('div', {'class': print_class}) # expected: # root # tree children1 # tree children2 # tree children3 # actual: # root # tree # children1 # tree # children2 # tree # children3 </code></pre> <p>Thanks in advance,</p> <p><strong><em>==== comments ==========</em></strong></p> <p>stackoverflow site don't allow add comments more than 500 characters, so I added comments here: </p> <p>Above, it was example to show how to BeautifulSoup looking for required classes.</p> <p>But, If I have DOM structure like: </p> <pre><code> r_html = "&lt;div class='root'&gt;" \ "&lt;div class='tree children'&gt;zero&lt;/div&gt;" \ "&lt;div class='tree children first'&gt;first&lt;/div&gt;" \ "&lt;div class='tree children second'&gt;second&lt;/div&gt;" \ "&lt;div class='tree children third'&gt;third&lt;/div&gt;" \ "&lt;/div&gt;" </code></pre> <p>and when need to select controls with class attributes: '<strong><em>tree children</em></strong>' and '<strong><em>tree children first</em></strong>', All of the methods described in your(Padraic Cunningham) post aren't work.</p> <p>I found a solution with using regex: </p> <pre><code>controls = bs_tab.findAll('div') for control in controls: if re.search("^tree children|^tree children first", " ".join(control.attrs['class'] if control.attrs.has_key('class') else "")): print control </code></pre> <p>and another solution: </p> <pre><code>bs_tab.findAll('div', class_='tree children') + bs_tab.findAll('div', class_='tree children first') </code></pre> <p>I know, it's not good solution. and I hope that BeautifulSoup module has appropriate method for that.</p>
1
2016-08-08T08:06:58Z
38,825,064
<p>There are a few different ways depending on the structure of the html, they are css classes so you could just use <code>class_=..</code> or a css selector using <em>.select</em>:</p> <pre><code>In [3]: bs_tab.find_all('div', class_="tree") Out[3]: [&lt;div class="tree children1"&gt;text children 1 &lt;/div&gt;, &lt;div class="tree children2"&gt;text children 2 &lt;/div&gt;, &lt;div class="tree children3"&gt;text children 3 &lt;/div&gt;] In [4]: bs_tab.select("div.tree") Out[4]: [&lt;div class="tree children1"&gt;text children 1 &lt;/div&gt;, &lt;div class="tree children2"&gt;text children 2 &lt;/div&gt;, &lt;div class="tree children3"&gt;text children 3 &lt;/div&gt;] </code></pre> <p>But if you had another <em>tree</em> class elsewhere that would find then also.</p> <p>You could use a selector to find divs that contains <em>children</em> in the class:</p> <pre><code>In [5]: bs_tab.select("div[class*=children]") Out[5]: [&lt;div class="tree children1"&gt;text children 1 &lt;/div&gt;, &lt;div class="tree children2"&gt;text children 2 &lt;/div&gt;, &lt;div class="tree children3"&gt;text children 3 &lt;/div&gt;] </code></pre> <p>But again if there were other tag classes with children in the name they would also be picked up.</p> <p>You could be a bit more specific with a regex and look for <em>children</em> followed by one or more digits:</p> <pre><code>In [6]: bs_tab.find_all('div', class_=re.compile("children\d+")) Out[6]: [&lt;div class="tree children1"&gt;text children 1 &lt;/div&gt;, &lt;div class="tree children2"&gt;text children 2 &lt;/div&gt;, &lt;div class="tree children3"&gt;text children 3 &lt;/div&gt;] </code></pre> <p>Or find all the <em>div.tree's</em> and see if the last names in <em>tag["class"]</em> <em>starstwith</em> <em>children</em>.</p> <pre><code>In [7]: [t for t in bs_tab.select("div.tree") if t["class"][-1].startswith("children")] Out[7]: [&lt;div class="tree children1"&gt;text children 1 &lt;/div&gt;, &lt;div class="tree children2"&gt;text children 2 &lt;/div&gt;, &lt;div class="tree children3"&gt;text children 3 &lt;/div&gt;] </code></pre> <p>Or look for children and see if the first css class name is equal to <em>tree</em></p> <pre><code>In [8]: [t for t in bs_tab.select("div[class*=children]") if t["class"][0] == "tree"] Out[8]: [&lt;div class="tree children1"&gt;text children 1 &lt;/div&gt;, &lt;div class="tree children2"&gt;text children 2 &lt;/div&gt;, &lt;div class="tree children3"&gt;text children 3 &lt;/div&gt;] </code></pre>
2
2016-08-08T09:00:22Z
[ "python", "beautifulsoup" ]
Print the consecutive 3 line at the pattern match
38,824,144
<p>I have a huge file where i need to sort and merge 3 line which are having pattern match "vm" and need them into One Single Line, like Below</p> <p>kfg-ap4 is the Server name , we can have it Only Once that will be nice while sorting .. I tried awk with getline but somehow i am missing to fit it ..</p> <p>awk '/vm/ {printf $0 " ";getline; print $0}' mem_overc</p> <pre><code>**[kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0** [kfg-ap4] Executing task 'moc' [kfg-ap4] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap4] out: [kfg-ap4] out: We trust you have received the usual lecture from the local System [kfg-ap4] out: Administrator. It usually boils down to these three things: [kfg-ap4] out: [kfg-ap4] out: #1) Respect the privacy of others. [kfg-ap4] out: #2) Think before you type. [kfg-ap4] out: #3) With great power comes great responsibility. [kfg-ap4] out: [kfg-ap4] out: sudo password: </code></pre> <blockquote> <pre><code>[kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0 </code></pre> </blockquote> <pre><code>[kfg-ap4] out: </code></pre> <p>======================================================================</p> <h1>Actual Data is as below and rest of the data is same except server names</h1> <pre><code>[kfg-ap3] Executing task 'moc' [kfg-ap3] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap3] out: [kfg-ap3] out: We trust you have received the usual lecture from the local System [kfg-ap3] out: Administrator. It usually boils down to these three things: [kfg-ap3] out: [kfg-ap3] out: #1) Respect the privacy of others. [kfg-ap3] out: #2) Think before you type. [kfg-ap3] out: #3) With great power comes great responsibility. [kfg-ap3] out: [kfg-ap3] out: sudo password: [kfg-ap3] out: vm.overcommit_memory = 0 [kfg-ap3] out: vm.overcommit_ratio = 50 [kfg-ap3] out: vm.nr_overcommit_hugepages = 0 [kfg-ap3] out: [kfg-ap4] Executing task 'moc' [kfg-ap4] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap4] out: [kfg-ap4] out: We trust you have received the usual lecture from the local System [kfg-ap4] out: Administrator. It usually boils down to these three things: [kfg-ap4] out: [kfg-ap4] out: #1) Respect the privacy of others. [kfg-ap4] out: #2) Think before you type. [kfg-ap4] out: #3) With great power comes great responsibility. [kfg-ap4] out: [kfg-ap4] out: sudo password: [kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0 [kfg-ap4] out: </code></pre>
0
2016-08-08T08:08:24Z
38,824,271
<p>You were almost there: Just accumulate in a variable and print in the end:</p> <pre><code>awk 'BEGIN{s="";} /vm/ {s = s $0 " "} END {print s}' log.txt </code></pre> <p>You can also use your exact construction and convert the newlines:</p> <pre><code>awk '/vm/ {printf $0 " ";getline; print $0}' log.txt | tr "\n" " " </code></pre>
2
2016-08-08T08:17:00Z
[ "python", "awk", "sed" ]
Print the consecutive 3 line at the pattern match
38,824,144
<p>I have a huge file where i need to sort and merge 3 line which are having pattern match "vm" and need them into One Single Line, like Below</p> <p>kfg-ap4 is the Server name , we can have it Only Once that will be nice while sorting .. I tried awk with getline but somehow i am missing to fit it ..</p> <p>awk '/vm/ {printf $0 " ";getline; print $0}' mem_overc</p> <pre><code>**[kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0** [kfg-ap4] Executing task 'moc' [kfg-ap4] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap4] out: [kfg-ap4] out: We trust you have received the usual lecture from the local System [kfg-ap4] out: Administrator. It usually boils down to these three things: [kfg-ap4] out: [kfg-ap4] out: #1) Respect the privacy of others. [kfg-ap4] out: #2) Think before you type. [kfg-ap4] out: #3) With great power comes great responsibility. [kfg-ap4] out: [kfg-ap4] out: sudo password: </code></pre> <blockquote> <pre><code>[kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0 </code></pre> </blockquote> <pre><code>[kfg-ap4] out: </code></pre> <p>======================================================================</p> <h1>Actual Data is as below and rest of the data is same except server names</h1> <pre><code>[kfg-ap3] Executing task 'moc' [kfg-ap3] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap3] out: [kfg-ap3] out: We trust you have received the usual lecture from the local System [kfg-ap3] out: Administrator. It usually boils down to these three things: [kfg-ap3] out: [kfg-ap3] out: #1) Respect the privacy of others. [kfg-ap3] out: #2) Think before you type. [kfg-ap3] out: #3) With great power comes great responsibility. [kfg-ap3] out: [kfg-ap3] out: sudo password: [kfg-ap3] out: vm.overcommit_memory = 0 [kfg-ap3] out: vm.overcommit_ratio = 50 [kfg-ap3] out: vm.nr_overcommit_hugepages = 0 [kfg-ap3] out: [kfg-ap4] Executing task 'moc' [kfg-ap4] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap4] out: [kfg-ap4] out: We trust you have received the usual lecture from the local System [kfg-ap4] out: Administrator. It usually boils down to these three things: [kfg-ap4] out: [kfg-ap4] out: #1) Respect the privacy of others. [kfg-ap4] out: #2) Think before you type. [kfg-ap4] out: #3) With great power comes great responsibility. [kfg-ap4] out: [kfg-ap4] out: sudo password: [kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0 [kfg-ap4] out: </code></pre>
0
2016-08-08T08:08:24Z
38,825,607
<pre><code>$ awk '/vm/ {printf "%s%s", $0, (++i%3?OFS:ORS)}' log.txt [kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0 [kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0 </code></pre> <p>Walk-thru:</p> <pre><code>/vm/ { # if vm on the record printf "%s%s", $0, (++i%3?OFS:ORS) # print record and OFS } # every 3rd time print ORS </code></pre> <p>Since there in fact was more that 3 rows in a group, use this:</p> <pre><code>$ awk '/vm/ {buf=buf OFS $0; next} buf!="" {print buf; buf=""}' </code></pre> <p>It buffers records and prints them out after it encounters a record that doesn't match <code>/vm/</code>. It may case a problem if you have consecutive groups in your file. You may end-up with longer-than expected lines.</p> <pre><code>$ cat &gt; process.awk /vm/ { # if vm string in the record buf=buf OFS $0 # append the record $0 to the buffer variable buf next # skip the rest of script for this record, ie. } # only records without vm match get past this point buf!="" { # if the buffer is not empty print buf # print it out buf="" # empty the buffer } $ awk -f process.awk log.txt </code></pre>
1
2016-08-08T09:28:38Z
[ "python", "awk", "sed" ]
Print the consecutive 3 line at the pattern match
38,824,144
<p>I have a huge file where i need to sort and merge 3 line which are having pattern match "vm" and need them into One Single Line, like Below</p> <p>kfg-ap4 is the Server name , we can have it Only Once that will be nice while sorting .. I tried awk with getline but somehow i am missing to fit it ..</p> <p>awk '/vm/ {printf $0 " ";getline; print $0}' mem_overc</p> <pre><code>**[kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0** [kfg-ap4] Executing task 'moc' [kfg-ap4] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap4] out: [kfg-ap4] out: We trust you have received the usual lecture from the local System [kfg-ap4] out: Administrator. It usually boils down to these three things: [kfg-ap4] out: [kfg-ap4] out: #1) Respect the privacy of others. [kfg-ap4] out: #2) Think before you type. [kfg-ap4] out: #3) With great power comes great responsibility. [kfg-ap4] out: [kfg-ap4] out: sudo password: </code></pre> <blockquote> <pre><code>[kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0 </code></pre> </blockquote> <pre><code>[kfg-ap4] out: </code></pre> <p>======================================================================</p> <h1>Actual Data is as below and rest of the data is same except server names</h1> <pre><code>[kfg-ap3] Executing task 'moc' [kfg-ap3] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap3] out: [kfg-ap3] out: We trust you have received the usual lecture from the local System [kfg-ap3] out: Administrator. It usually boils down to these three things: [kfg-ap3] out: [kfg-ap3] out: #1) Respect the privacy of others. [kfg-ap3] out: #2) Think before you type. [kfg-ap3] out: #3) With great power comes great responsibility. [kfg-ap3] out: [kfg-ap3] out: sudo password: [kfg-ap3] out: vm.overcommit_memory = 0 [kfg-ap3] out: vm.overcommit_ratio = 50 [kfg-ap3] out: vm.nr_overcommit_hugepages = 0 [kfg-ap3] out: [kfg-ap4] Executing task 'moc' [kfg-ap4] sudo: /sbin/sysctl -A | grep overcommit [kfg-ap4] out: [kfg-ap4] out: We trust you have received the usual lecture from the local System [kfg-ap4] out: Administrator. It usually boils down to these three things: [kfg-ap4] out: [kfg-ap4] out: #1) Respect the privacy of others. [kfg-ap4] out: #2) Think before you type. [kfg-ap4] out: #3) With great power comes great responsibility. [kfg-ap4] out: [kfg-ap4] out: sudo password: [kfg-ap4] out: vm.overcommit_memory = 0 [kfg-ap4] out: vm.overcommit_ratio = 50 [kfg-ap4] out: vm.nr_overcommit_hugepages = 0 [kfg-ap4] out: </code></pre>
0
2016-08-08T08:08:24Z
38,830,029
<p>Another answer using <code>sed</code> only</p> <pre><code>/vm/{ H x s/\n/ /g s/ \[kfg-ap.\] out: / / x blab } x p :lab </code></pre> <p>invoke like this (save above file as <code>filter.sed</code>):</p> <pre><code>sed -n -f filter.sed text.txt </code></pre> <p>If <code>vm</code> is matched, then stores in the hold buffer. Then swaps the whole buffer to remove newlines and useless kfg prefixes in the line, swap again.</p> <p>If not matched, swap the buffer again and print.</p> <p>Rather simple &amp; works great (cornercase: if log ends with the vm lines they may be omitted)</p>
0
2016-08-08T13:06:57Z
[ "python", "awk", "sed" ]
howto instantiate certain class from string in python project packed by pyinstaller?
38,824,177
<p>i am using getattr, but i cant make it working with pyinstaller</p> <p>short summary:</p> <ul> <li>Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:49:46) [MSC v.1900 64 bit (AMD64)] on win32</li> <li>i have project, packed by pyinstaller to single file</li> <li>i have external text file with script (Subs.py)</li> </ul> <p>my project cant instantiate class Subs in Subs.py ..</p> <p>before i pack project by pyinstaller, i can create instance of Subs from Subs.py.. can you please advise, whats wrong on example below ?</p> <p>in order to show my problem, i prepared very simple example. <code> folder structure: root- #folder -to #folder -__init__.py #file -Subs.py #file -main.py #file </code></p> <p>main.py:</p> <pre><code>import importlib MyClass = getattr(importlib.import_module("to.Subs"), "Subs") instance = MyClass() instance.test() </code></pre> <p>Subs.py:</p> <pre><code>class Subs(): def test(self): print("test") </code></pre> <p>at this moment, execution return as expected:</p> <pre><code>python main.py test </code></pre> <p>but if i pack project with pyinstaller ( latest installed via pip ) pyinstaller main.py -F then i am moving main.exe to root and executing:</p> <pre><code>main.exe Traceback (most recent call last): File "main.py", line 3, in &lt;module&gt; MyClass = getattr(importlib.import_module("to.Subs"), "Subs") File "importlib\__init__.py", line 126, in import_module File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 944, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 956, in _find_and_load_unlocked ImportError: No module named 'to' Failed to execute script main </code></pre> <p>any idea, what i am missing/doing wrogly ? ?</p>
0
2016-08-08T08:10:51Z
38,931,490
<p>"You are right. Simply using --hidden-import=Subs won't work. You have to use it with the -p DIR option and point to the folder that includes your modules. If that fails, you can also try to bundle the files as additional data. – Aug 8 at 14:31 " i am marking this as answer, as i could successfuly instan.class by using --hidden-import &amp; -b...</p> <p>credit goes to ->Repiklis</p>
0
2016-08-13T09:52:28Z
[ "python", "pyinstaller" ]
Considering Highest Peak Curve From Two Sets of Data Points
38,824,201
<p>I have two columns which would correspond to x and y-axis in which I will be eventually graphing that sets of data points to a curve like graph. <br></p> <p>The problem is that based on the nature of the datapoints, when graphing it, I end up having two peaks however, I want to pick only the highest peak when graphing and discard the lowest peak(s) (not the highest point but the entire the highest peak graphed). <br></p> <p>Is there away to do that in Python? I don't show the codes here because I am not sure how to do the coding at all.</p> <p>Here is the datapoints (input) as well as the graph!</p> <p><a href="http://i.stack.imgur.com/tfVce.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/tfVce.jpg" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/d7CWm.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/d7CWm.jpg" alt="enter image description here"></a></p>
0
2016-08-08T08:12:55Z
38,825,426
<p>You can use <code>scipy</code> argrelextrema to get all the peaks, work out the maximum and then build up a mask array for the peak you want to plot. This will give you full control based on your data, using things like mincutoff to work out what determines a separate peak,</p> <pre><code>import numpy as np from scipy.signal import argrelextrema import matplotlib.pyplot as plt #Setup and plot data fig, ax = plt.subplots(1,2) y = np.array([0,0,0,0,0,6.14,7.04,5.6,0,0,0,0,0,0,0,0,0,0,0,16.58,60.06,99.58,100,50,0.,0.,0.]) x = np.linspace(3.92,161,y.size) ax[0].plot(x,y) #get peaks peaks_indx = argrelextrema(y, np.greater)[0] peaks = y[peaks_indx] ax[0].plot(x[peaks_indx],y[peaks_indx],'o') #Get maxpeak maxpeak = 0. for p in peaks_indx: print(p) if y[p] &gt; maxpeak: maxpeak = y[p] maxpeak_indx = p #Get mask of data around maxpeak to plot mincutoff = 0. indx_to_plot = np.zeros(y.size, dtype=bool) for i in range(maxpeak_indx): if y[maxpeak_indx-i] &gt; mincutoff: indx_to_plot[maxpeak_indx-i] = True else: indx_to_plot[maxpeak_indx-i] = True break for i in range(y.size-maxpeak_indx): if y[maxpeak_indx+i] &gt; mincutoff: indx_to_plot[maxpeak_indx+i] = True else: indx_to_plot[maxpeak_indx+i] = True break ax[1].plot(x[indx_to_plot],y[indx_to_plot]) plt.show() </code></pre> <p>The result is then,</p> <p><a href="http://i.stack.imgur.com/7aFcU.png" rel="nofollow"><img src="http://i.stack.imgur.com/7aFcU.png" alt="enter image description here"></a></p> <p>UPDATE: Code to plot only the largest peak.</p> <pre><code>import numpy as np from scipy.signal import argrelextrema import matplotlib.pyplot as plt #Setup and plot data y = np.array([0,0,0,0,0,6.14,7.04,5.6,0,0,0,0,0,0, 0,0,0,0,0,16.58,60.06,99.58,100,50,0.,0.,0.]) x = np.linspace(3.92,161,y.size) #get peaks peaks_indx = argrelextrema(y, np.greater)[0] peaks = y[peaks_indx] #Get maxpeak maxpeak = 0. for p in peaks_indx: print(p) if y[p] &gt; maxpeak: maxpeak = y[p] maxpeak_indx = p #Get mask of data around maxpeak to plot mincutoff = 0. indx_to_plot = np.zeros(y.size, dtype=bool) for i in range(maxpeak_indx): if y[maxpeak_indx-i] &gt; mincutoff: indx_to_plot[maxpeak_indx-i] = True else: indx_to_plot[maxpeak_indx-i] = True break for i in range(y.size-maxpeak_indx): if y[maxpeak_indx+i] &gt; mincutoff: indx_to_plot[maxpeak_indx+i] = True else: indx_to_plot[maxpeak_indx+i] = True break #Plot just the highest peak plt.plot(x[indx_to_plot],y[indx_to_plot]) plt.show() </code></pre> <p>I would still suggest plotting both peaks to ensure the algorithm is working correctly... I think you will find that identifying an arbitrary peak is probably not always trivial with messy data.</p>
1
2016-08-08T09:19:52Z
[ "python", "matplotlib", "graphing" ]
Iterate over nested keys in Python dict and break on first occurence
38,824,205
<p>I have a JSON dict like the following :</p> <pre><code> "{ "a":1, "b":{ "b1":False, "b2":{"b21": 2, "b22":8} }, "c": { "b1":True, "b2":2, "b4":8 }, "d":{ "b1":False, "d1":89 } }" </code></pre> <p>I want to check the value of the key <code>"b1"</code> in the dictionary, and get out when I find <code>b1=True</code>. If I check the entire dict (nested keys included), and I don't find b1=True, then I would like to return False. For the example above, my function should return True.</p> <p>Basically I want to break the code on the first occurrence of <code>b1=True</code> and iterate over all the keys of the dict (in all levels), and if this occurrence does not exist, return False.</p> <p>This is what I came up with :</p> <pre><code>def isb1True(jsonDoc): found = False for (key,value) in jsonDoc.iteritems(): if key=='b1': if value==True : found=True break else: isb1True(value) return found </code></pre> <p>My code always returns <code>False</code>.</p>
0
2016-08-08T08:13:03Z
38,824,326
<p>You need to return from the <em>recursive</em> calls too, and use that to inform wether or not you are going to continue looping; your code ignores what the recursive <code>isb1True(value)</code> call returns.</p> <p>You can use the <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any()</code> function</a> to short-circuit testing recursive values:</p> <pre><code>def isb1true(d): if not isinstance(d, dict): return False return any(v if k == 'b1' else isb1true(v) for k, v in d.iteritems()) </code></pre> <p>The above recurses for any key that is not <code>'b1'</code>, and recursion stops when that value is not a dictionary (in which case it won't be <code>b1</code> so that result is not a <code>'b1': True</code> case).</p> <p>I'm assuming that <code>'b1'</code> is always set to a boolean; the above returns <code>True</code> for any 'truthy' value for that key.</p> <p>Some test cases:</p> <pre><code>&gt;&gt;&gt; isb1true({'b1': True}) True &gt;&gt;&gt; isb1true({'b1': False}) False &gt;&gt;&gt; isb1true({'b': {'b1': True}}) True &gt;&gt;&gt; isb1true({'b': {'b1': False}}) False &gt;&gt;&gt; isb1true({'b': {'c': True, 'spam': 'eggs', 'ham': {'bar': 'baz', 'b1': True}}}) True &gt;&gt;&gt; isb1true({'b': {'c': True, 'spam': 'eggs', 'ham': {'bar': 'baz'}}}) False </code></pre>
4
2016-08-08T08:20:01Z
[ "python", "dictionary", "nested", "key" ]
django custom filters not working
38,824,339
<p>Here is my folders organization :</p> <p><a href="http://i.stack.imgur.com/gmohP.png" rel="nofollow"><img src="http://i.stack.imgur.com/gmohP.png" alt="enter image description here"></a></p> <p>core_extras.py content :</p> <pre><code>from django.contrib.auth.models import Group from django.conf import settings from django import template register = template.Library() @register.simple_tag def get_develop_state(): return settings.DEVELOP @register.filter(is_safe=True) def in_group(user, group_name): group = Group.objects.get(name=group_name) return user.groups.filter(name=group_name).exists() @register.filter def do_nothing(value): return value </code></pre> <p>How I load custom tag/filter in html :</p> <pre><code>{% load i18n staticfiles core_extras %} {% get_develop_state as DEVELOP %} </code></pre> <p>How I use my tag/filter :</p> <pre><code>{% if DEVELOP or request.user|in_group:"testers" %} </code></pre> <p>The <code>get_develop_state</code> is working correctly, but for my filter <code>in_group</code>, I got the error <code>Invalid filter: 'in_group'</code>.</p> <p>The application <code>core</code> is in my <code>INSTALLED_APPS</code>.</p> <p>Why is my filter not registered ?</p>
0
2016-08-08T08:20:36Z
38,824,538
<p>I'm stupid.</p> <p>I loaded <code>{% load i18n staticfiles core_extras %}</code> in a base html file which I extend then on child html files. The <code>get_develop_state</code> was working because I import it as a variable <code>DEVELOP</code> which is available on the child html files but not the filter <code>in_group</code>. I just loaded <code>{% load in_group %}</code> in the child html and everything works...</p>
1
2016-08-08T08:31:53Z
[ "python", "django" ]
import css using 'static' template in Django
38,824,544
<p>I have been importing JS files into my template using:</p> <pre><code> &lt;script src="{% static 'inventory/js/panel.js' %}" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>while importin CSS using</p> <pre><code> &lt;link href="{{ STATIC_URL }}common/css/form.css" rel="stylesheet" type="text/css"&gt; </code></pre> <p>Can you tell me how to import CSS files using the static template tag like in importing JS files. Thanks</p>
0
2016-08-08T08:32:18Z
38,824,582
<p>It's almost the same as your js:</p> <pre><code>{% load staticfiles %} &lt;link href="{% static "css/base.css" %}" rel="stylesheet"/&gt; </code></pre>
1
2016-08-08T08:34:46Z
[ "javascript", "python", "html", "css", "django" ]
BeautifulSoup, TypeError:'NoneType' object is not callable. from book: Web Scraping With Python
38,824,579
<p>This train from a book, Python Web Scraping With Python by Ryan Mitchell,in Chinese version p23.and I find any others are similar.who can tell me how fix it? thank you in advance. I has posted picture. code as follow:</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup import re html = urlopen("http://www.pythonscraping.com/pages/page3.html") bsObj = BeautifulSoup(html,"html.parser") images = bsObj.findALL("img",{"src":re.compile("\.\.\/img\/gifts\/img.*\.jpg")}) for image in images: print(image["src"]) </code></pre>
0
2016-08-08T08:34:35Z
38,825,308
<p>It is actually the <code>*findALL*</code> it should be lowercase <em>l's</em> i.e <code>findAll</code> or better to use <code>*find_all*</code> as <em>findAll</em> is deprecated.:</p> <pre><code> images = bsObj.find_all("img",{"src":re.compile("\.\./img/gifts/img.*\.jpg")}) </code></pre> <p>Which will give you:</p> <pre><code>../img/gifts/img1.jpg ../img/gifts/img2.jpg ../img/gifts/img3.jpg ../img/gifts/img4.jpg ../img/gifts/img6.jpg </code></pre> <p>Unless there were other images with <code>../img/gifts/img</code> in their path you could use a <em>css selector</em> in place of the regex to find images that had <em>/img/gifts/img</em> in their <em>src</em> attribute.</p> <pre><code>images = bsObj.select("img[src*=../img/gifts/img]") </code></pre>
1
2016-08-08T09:13:39Z
[ "python", "beautifulsoup", "nonetype" ]
Automate the boring stuff with Python: Comma Code
38,824,634
<p>Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:</p> <blockquote> <p>takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the <strong>below</strong> spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.</p> </blockquote> <pre><code>spam = ['apples', 'bananas', 'tofu', 'cats'] </code></pre> <p>My solution to the problem (Which works perfectly fine):</p> <pre><code>spam= ['apples', 'bananas', 'tofu', 'cats'] def list_thing(list): new_string = '' for i in list: new_string = new_string + str(i) if list.index(i) == (len(list)-2): new_string = new_string + ', and ' elif list.index(i) == (len(list)-1): new_string = new_string else: new_string = new_string + ', ' return new_string print (list_thing(spam)) </code></pre> <p>My only question, is there any way I can shorten my code? or make it more 'pythonic'? </p>
0
2016-08-08T08:37:42Z
38,824,699
<p>Use <code>str.join()</code> to join a sequence of strings with a delimiter. If you do so for all words <em>except</em> for the last, you can insert <code>' and '</code> there instead:</p> <pre><code>def list_thing(words): if len(words) == 1: return words[0] return '{}, and {}'.format(', '.join(words[:-1]), words[-1]) </code></pre> <p>Breaking this down:</p> <ul> <li><p><code>words[-1]</code> takes the last element of a list. <code>words[:-1]</code> <em>slices</em> the list to produce a new list with all words <em>except</em> the last one.</p></li> <li><p><code>', '.join()</code> produces a new string, with all strings of the argument to <code>str.join()</code> joined with <code>', '</code>. If there is just <em>one</em> element in the input list, that one element is returned, unjoined.</p></li> <li><p><code>'{}, and {}'.format()</code> inserts the comma-joined words and the last word into a template (complete with Oxford comma).</p></li> </ul> <p>If you pass in an empty list, the above function will raise an <code>IndexError</code> exception; you could specifically test for that case in the function if you feel an empty list is a valid use-case for the function.</p> <p>So the above joins <em>all words except the last</em> with <code>', '</code>, then adds the last word to the result with <code>' and '</code>.</p> <p>Note that if there is just one word, you get that one word; there is nothing to join in that case. If there are two, you get <code>'word1 and word 2'</code>. More words produces <code>'word1, word2, ... and lastword'</code>.</p> <p>Demo:</p> <pre><code>&gt;&gt;&gt; def list_thing(words): ... if len(words) == 1: ... return words[0] ... return '{}, and {}'.format(', '.join(words[:-1]), words[-1]) ... &gt;&gt;&gt; spam = ['apples', 'bananas', 'tofu', 'cats'] &gt;&gt;&gt; list_thing(spam[:1]) 'apples' &gt;&gt;&gt; list_thing(spam[:2]) 'apples, and bananas' &gt;&gt;&gt; list_thing(spam[:3]) 'apples, bananas, and tofu' &gt;&gt;&gt; list_thing(spam) 'apples, bananas, tofu, and cats' </code></pre>
3
2016-08-08T08:41:47Z
[ "python" ]
Automate the boring stuff with Python: Comma Code
38,824,634
<p>Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:</p> <blockquote> <p>takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the <strong>below</strong> spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.</p> </blockquote> <pre><code>spam = ['apples', 'bananas', 'tofu', 'cats'] </code></pre> <p>My solution to the problem (Which works perfectly fine):</p> <pre><code>spam= ['apples', 'bananas', 'tofu', 'cats'] def list_thing(list): new_string = '' for i in list: new_string = new_string + str(i) if list.index(i) == (len(list)-2): new_string = new_string + ', and ' elif list.index(i) == (len(list)-1): new_string = new_string else: new_string = new_string + ', ' return new_string print (list_thing(spam)) </code></pre> <p>My only question, is there any way I can shorten my code? or make it more 'pythonic'? </p>
0
2016-08-08T08:37:42Z
38,824,761
<p>Others have given great one-liner solutions, but a good way to improve your actual implementation - and fix the fact that it does not work when elements are repeated - is to use <code>enumerate</code> in the for loop to keep track of the index, rather than using <code>index</code> which always finds the <em>first</em> occurrence of the target.</p> <pre><code>for counter, element in enumerate(list): new_string = new_string + str(element) if counter == (len(list)-2): ... </code></pre>
1
2016-08-08T08:44:32Z
[ "python" ]
Automate the boring stuff with Python: Comma Code
38,824,634
<p>Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:</p> <blockquote> <p>takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the <strong>below</strong> spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.</p> </blockquote> <pre><code>spam = ['apples', 'bananas', 'tofu', 'cats'] </code></pre> <p>My solution to the problem (Which works perfectly fine):</p> <pre><code>spam= ['apples', 'bananas', 'tofu', 'cats'] def list_thing(list): new_string = '' for i in list: new_string = new_string + str(i) if list.index(i) == (len(list)-2): new_string = new_string + ', and ' elif list.index(i) == (len(list)-1): new_string = new_string else: new_string = new_string + ', ' return new_string print (list_thing(spam)) </code></pre> <p>My only question, is there any way I can shorten my code? or make it more 'pythonic'? </p>
0
2016-08-08T08:37:42Z
38,825,157
<p>I tried this, hope this is what you are looking for :- </p> <pre><code>spam= ['apples', 'bananas', 'tofu', 'cats'] def list_thing(list): #creating a string then splitting it as list with two items, second being last word new_string=', '.join(list).rsplit(',', 1) #Using the same method used above to recreate string by replacing the separator. new_string=' and'.join(new_string) return new_string print(list_thing(spam)) </code></pre>
2
2016-08-08T09:06:02Z
[ "python" ]
Automate the boring stuff with Python: Comma Code
38,824,634
<p>Currently working my way through this beginners book and have completed one of the practice projects 'Comma Code' which asks the user to construct a program which:</p> <blockquote> <p>takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the <strong>below</strong> spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.</p> </blockquote> <pre><code>spam = ['apples', 'bananas', 'tofu', 'cats'] </code></pre> <p>My solution to the problem (Which works perfectly fine):</p> <pre><code>spam= ['apples', 'bananas', 'tofu', 'cats'] def list_thing(list): new_string = '' for i in list: new_string = new_string + str(i) if list.index(i) == (len(list)-2): new_string = new_string + ', and ' elif list.index(i) == (len(list)-1): new_string = new_string else: new_string = new_string + ', ' return new_string print (list_thing(spam)) </code></pre> <p>My only question, is there any way I can shorten my code? or make it more 'pythonic'? </p>
0
2016-08-08T08:37:42Z
38,826,787
<p>Here's a solution that handles the <a href="https://en.wikipedia.org/wiki/Serial_comma" rel="nofollow">Oxford comma</a> properly. It also copes with an empty list, in which case it returns an empty string.</p> <pre><code>def list_thing(seq): return (' and '.join(seq) if len(seq) &lt;= 2 else '{}, and {}'.format(', '.join(seq[:-1]), seq[-1])) spam = ['apples', 'bananas', 'tofu', 'cats'] for i in range(1 + len(spam)): seq = spam[:i] s = list_thing(seq) print(i, seq, repr(s)) </code></pre> <p><strong>output</strong></p> <pre><code>0 [] '' 1 ['apples'] 'apples' 2 ['apples', 'bananas'] 'apples and bananas' 3 ['apples', 'bananas', 'tofu'] 'apples, bananas, and tofu' 4 ['apples', 'bananas', 'tofu', 'cats'] 'apples, bananas, tofu, and cats' </code></pre>
3
2016-08-08T10:25:14Z
[ "python" ]
Get the content HTML of an API
38,824,786
<p>I'm tring to get the content of an API result in python.<br/> This is an HTML template with an image inside.</p> <p>I tried lot of method to get the content but it don't work everytime.</p> <p><strong>The fuction</strong> :</p> <pre><code>def screenshotlayer(self, access_key, secret_keyword, domain, args): domain = "http://" + domain url = "http://api.screenshotlayer.com/api/capture?access_key=API_KEY&amp;url=http://google.com&amp;viewport=1440x900&amp;width=250" html = urllib2.urlopen(url).read() print html soup = BeautifulSoup(html, 'html.parser') return soup.findAll('img')[0]['src'] </code></pre> <p>When I <code>print html</code>, there is lot of incomprehensible characters.<br> Can someone help me to resove this problem ?</p> <p>Thank you so much.</p>
0
2016-08-08T08:45:36Z
38,824,910
<p>The api does not returns html, but a raw image file (default to png).</p> <p>You need to see if the <code>status_code</code> was 200, and if so, simply save the result into a file.</p> <pre><code>import requests res = requests.get( 'http://api.screenshotlayer.com/api/capture', params={ 'access_key': 'API_KEY', 'url': 'http://google.com&amp;viewport=1440x900&amp;width=250' } ) if(res.status_code == 200) with open('output.png', 'w+b') as f: f.write(res.content.encode('utf8')) else: print('Api returns error: %s' % res.content) </code></pre>
3
2016-08-08T08:52:43Z
[ "python", "scrapy", "urllib" ]
Python: How to catch inner exception of exception chain?
38,824,798
<p>Consider the simple example:</p> <pre><code>def f(): try: raise TypeError except TypeError: raise ValueError f() </code></pre> <p>I want to catch <code>TypeError</code> object when <code>ValueError</code> is thrown after <code>f()</code> execution. Is it possible to do it?</p> <p>If I execute function <code>f()</code> then python3 print to stderr all raised exceptions of exception chain (<a href="https://www.python.org/dev/peps/pep-3134/" rel="nofollow">PEP-3134</a>) like</p> <pre><code>Traceback (most recent call last): File "...", line 6, in f raise TypeError TypeError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "...", line 11, in &lt;module&gt; f() File "...", line 8, in f raise ValueError ValueError </code></pre> <p>So I would get the list of all exceptions of exception chain <strong>or</strong> check if exception of some type (<code>TypeError</code> in the above example) exists in exception chain.</p>
0
2016-08-08T08:46:12Z
38,824,962
<p>Python 3 has a beautiful syntactic enhancement on exceptions handling. Instead of plainly raising ValueError, you should raise it from a caught exception, i.e.:</p> <pre><code>try: raise TypeError('Something awful has happened') except TypeError as e: raise ValueError('There was a bad value') from e </code></pre> <p>Notice the difference between the tracebacks. This one uses <code>raise from</code> version: </p> <pre><code>Traceback (most recent call last): File "/home/user/tmp.py", line 2, in &lt;module&gt; raise TypeError('Something awful has happened') TypeError: Something awful has happened The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/tmp.py", line 4, in &lt;module&gt; raise ValueError('There was a bad value') from e ValueError: There was a bad value </code></pre> <p>Though the result may seem similar, in fact it is rather different! <code>raise from</code> saves the context of the original exception and allows one to trace all the exceptions chain back - which is impossible with simple <code>raise</code>. </p> <p>To get the original exception, you simply have to refer to new exception's <code>__context__</code> attribute, i.e.</p> <pre><code>try: try: raise TypeError('Something awful has happened') except TypeError as e: raise ValueError('There was a bad value') from e except ValueError as e: print(e.__context__) &gt;&gt;&gt; Something awful has happened </code></pre> <p>Hopefully that is the solution you were looking for.</p> <p>For more details, see <a href="https://www.python.org/dev/peps/pep-3134/" rel="nofollow">PEP 3134 -- Exception Chaining and Embedded Tracebacks</a> </p>
6
2016-08-08T08:55:49Z
[ "python", "python-3.x", "exception-handling" ]
Instead of printing, returning the value of whole the string instead
38,825,039
<p>Currently working on an assignment where I want to print stars as triangles, the code is currently looking like this (very basic, I know):</p> <pre><code>def triangelbasupp(n,m): for a in range(0,m): print((n*" "),(m*"*")) m=m-2 n=n+1 if m&lt;=0: break </code></pre> <p>When I enter, for example (3,1) I will get first 3 stars in the first row, then 1 star. This code is working fine, the problem is that for the assignment, I want to ONLY return the whole string that constitutes the triangle, it also has to contain the '\n' for switching row. Does anyone have a clue how I can do this?</p>
1
2016-08-08T08:59:32Z
38,825,141
<p>Instead of printing, initialize an empty string and use the <a class='doc-link' href="http://stackoverflow.com/documentation/python/1019/string-formatting/14479/string-concatenation#t=201608080908078797832">string concatenation</a> operator to build the string:</p> <pre><code>def triangelbasupp(n,m): s = "" for a in range(0,m): s += n*" " + m*"*" + "\n" m=m-2 n=n+1 if m&lt;=0: break return s </code></pre>
2
2016-08-08T09:04:21Z
[ "python" ]
Instead of printing, returning the value of whole the string instead
38,825,039
<p>Currently working on an assignment where I want to print stars as triangles, the code is currently looking like this (very basic, I know):</p> <pre><code>def triangelbasupp(n,m): for a in range(0,m): print((n*" "),(m*"*")) m=m-2 n=n+1 if m&lt;=0: break </code></pre> <p>When I enter, for example (3,1) I will get first 3 stars in the first row, then 1 star. This code is working fine, the problem is that for the assignment, I want to ONLY return the whole string that constitutes the triangle, it also has to contain the '\n' for switching row. Does anyone have a clue how I can do this?</p>
1
2016-08-08T08:59:32Z
38,825,159
<p>Collect the lines in a list, then <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> them with <code>\n</code> and return.</p> <pre><code>def triangelbasupp(n,m): lines = [] for a in range(0,m): lines.append(n*" " + m*"*") ... return "\n".join(lines) </code></pre> <p>Or shorter:</p> <pre><code>def triangelbasupp(n, m): return "\n".join(("*"*i).center(n) for i in range(m, 0, -2)) </code></pre>
2
2016-08-08T09:06:05Z
[ "python" ]
how to write random numbers to file in python
38,825,082
<p>I would like to store 100 randomly drawn numbers in a file. How can I write random numbers to a list, using a file? How can I read a file? How can I separate draw numbers</p> <pre><code>import random draw = [] while True: numbers_lotto = random.randint(1,50) draw.append(numbers_lotto) if len(draw) == 5 # the numbers? break </code></pre>
-3
2016-08-08T09:01:15Z
38,825,219
<pre><code>import random file_name = 'random_numbers.txt' with open ('file_name', 'w') as a_file: for i in range (100): a_file.write ('{}\n'.format (random.random ())) with open ('file_name', 'r') as a_file: a_list = [float (word) for word in a_file.read () .split ()] print (a_list) </code></pre> <p>or</p> <pre><code>import random import pickle file_name = 'random_numbers.txt' with open (file_name, 'wb') as a_file: pickle.dump ([random.random () for i in range (100)], a_file) with open (file_name, 'rb') as a_file: a_list = pickle.load (a_file) print (a_list) </code></pre>
1
2016-08-08T09:09:29Z
[ "python", "list", "file" ]
Python pandas remove rows where multiple conditions are not met
38,825,087
<p>Lets say I have a dataframe like this:</p> <pre><code> id num 0 1 1 1 2 2 2 3 1 3 4 2 4 1 1 5 2 2 6 3 1 7 4 2 </code></pre> <p>The above can be generated with this for testing purposes:</p> <pre><code>test = pd.DataFrame({'id': np.array([1,2,3,4] * 2,dtype='int32'), 'num': np.array([1,2] * 4,dtype='int32') }) </code></pre> <p>Now, I want to keep only the rows where a certain condition is met: <code>id</code> is not 1 AND <code>num</code> is not 1. Essentially I want to remove the rows with index 0 and 4. For my actual dataset its easier to remove the rows I dont want rather than to specify the rows that I do want</p> <p>I have tried this:</p> <pre><code>test = test[(test['id'] != 1) &amp; (test['num'] != 1)] </code></pre> <p>However, that gives me this:</p> <pre><code> id num 1 2 2 3 4 2 5 2 2 7 4 2 </code></pre> <p>It seems to have removed all rows where <code>id</code> is 1 OR <code>num</code> is 1</p> <p>I've seen a number of other questions where the answer is the one I used above but it doesn't seem to be working out in my case</p>
1
2016-08-08T09:01:28Z
38,825,127
<p>If you change the boolean condition to be equality and invert the combined boolean conditions by enclosing both in additional parentheses then you get the desired behaviour:</p> <pre><code>In [14]: test = test[~((test['id'] == 1) &amp; (test['num'] == 1))] test Out[14]: id num 1 2 2 2 3 1 3 4 2 5 2 2 6 3 1 7 4 2 </code></pre> <p>I also think your understanding of boolean syntax is incorrect what you want is to <code>or</code> the conditions:</p> <pre><code>In [22]: test = test[(test['id'] != 1) | (test['num'] != 1)] test Out[22]: id num 1 2 2 2 3 1 3 4 2 5 2 2 6 3 1 7 4 2 </code></pre> <p>If you think about what this means the first condition excludes any row where 'id' is equal to 1 and similarly for the 'num' column:</p> <pre><code>In [24]: test[test['id'] != 1] Out[24]: id num 1 2 2 2 3 1 3 4 2 5 2 2 6 3 1 7 4 2 In [25]: test[test['num'] != 1] Out[25]: id num 1 2 2 3 4 2 5 2 2 7 4 2 </code></pre> <p>So really you wanted to <code>or</code> (<code>|</code>) the above conditions</p>
3
2016-08-08T09:03:56Z
[ "python", "pandas", "dataframe" ]
Counting login attempts in Flask
38,825,111
<p>I'm a total newbie to web development, and here is what I've tried:</p> <pre><code>@app.route('/login', methods=['GET', 'POST']) def login(): attempt = 0 form = LoginForm() if form.validate_on_submit(): flash('Login requested for OpenID="%s", remember_me=%s' % (form.openid.data, str(form.remember_me.data))) return redirect('/index') attempt += 1 flash('Attempt(s)="%d"' % attempt) return render_template('login.html', title='Sign In', form=form) </code></pre> <p>The output is always <code>Attempt(s)="1"</code>, while I expect the number to increase by 1 each time <code>form.validate_on_submit()</code> fails.</p> <p>I observed that when I press <code>Sign In</code> button, <code>login</code> page is refreshed. However, all text I inputted in the text fields remained there, so I suppose <code>form = LoginForm()</code> wasn't executed.(If a brand new <code>LoginForm</code> is created, how can these text still be there?) Thus I put the statement <code>attempt = 0</code> above <code>form = LoginForm()</code>, hoping it not to be executed each time <code>Sign In</code> is pressed, but apparently this does't work.</p> <p>I think the problem is that I don't know what happened when I pressed <code>Sign In</code>. Is the function <code>login</code> called again? If so, it's called by whom?</p> <p>Here is the content of <code>login.html</code>:</p> <pre><code>{% extends "base.html" %} {% block content %} &lt;h1&gt;Sign In&lt;/h1&gt; &lt;form action="" method="post" name="login"&gt; {{ form.hidden_tag() }} &lt;p&gt; Please enter your OpenID:&lt;br&gt; {{ form.openid(size=80) }}&lt;br&gt; &lt;/p&gt; &lt;p&gt;{{ form.remember_me }} Remember Me&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Sign In"&gt;&lt;/p&gt; &lt;/form&gt; {% endblock %} </code></pre>
0
2016-08-08T09:03:02Z
38,825,189
<p>The web is stateless. Every time you press a submit button, your browser calls the URL associated with that form; that URL is routed to your <code>login()</code> handler function, which runs from the start. The function itself has no memory of previous calls (and nor would you want it to, otherwise all users of your site would get the same login count). The form is populated from the data sent in the submit request, which is sent automatically to the form instantation by the flask-wtf library.</p> <p>You need to store that count somewhere between calls. A good place to do that is in a cookie; Flask includes the <a href="http://flask.pocoo.org/docs/0.11/quickstart/#sessions" rel="nofollow">sessions API</a> to make this simpler.</p>
4
2016-08-08T09:08:06Z
[ "python", "flask", "flask-wtforms" ]
Optimal Directed Dijkstra search in Python
38,825,253
<p>I've played around writing my own heap and trying out the directed Dijkstra's algorithm using a heap to store the distances. </p> <p>I've cross-checked the answers with Bellman-Ford (and also on paper) so I'm confident it runs correctly, however it seems to be too slow for my liking. I've also made my own Graph class to hold the value of vertices/the length/head/tail of edges</p> <pre><code>def dijkstra(G,root): ###Initialize values root.value=0 h=heap.Heap(root) for v in G.vertices: if v==root: continue v.value=float('inf') h.insert(v) while len(h.nodes)&gt;1: m=h.extractmin() ##Only works for directed graphs for E in m.edges: if (E.v in h.nodes) and E.v.value&gt;m.value+E.d: #If head of the min vrtx is in the heap E.v.value=m.value+E.d h.check_parent(h.nodes.index(E.v)) #percolate up </code></pre> <p>On an input of 50k edges and 1k nodes, it takes >30sec to complete. Is this a reasonable time to expect with python? Assuming that the algorithm is correct, would my heap be the limiting factor?</p> <p>(Also I know that I'm directly modifying/accessing members of the class, ie v.value=... , is that bad practice? I haven't specifically declared them private)</p> <p>Thanks for the input!</p>
1
2016-08-08T09:11:06Z
38,840,803
<blockquote> <p>Is this a reasonable time to expect with python?</p> </blockquote> <p>Unable to answer this without knowing your system specifications. Try comparing against a pre-built data structure e.g. <a href="https://docs.python.org/2/library/heapq.html" rel="nofollow">https://docs.python.org/2/library/heapq.html</a></p> <blockquote> <p>would my heap be the limiting factor?</p> </blockquote> <p>Yes.</p> <blockquote> <p>is that bad practice?</p> </blockquote> <p>This question is a bit out of place. You are asking about OO at the same time as asking about Algorithms.</p> <p>Finally, ensure that your heap implementation can achieve the following in <code>O(1)</code> instead of <code>O(n)</code>:</p> <pre><code>if (E.v in h.nodes) </code></pre> <p>You don't have to support the operation in your heap, btw. You can simply have another Boolean property for the vertices and set <code>v.inHeap = True</code> when it's added to the heap, and set it to <code>False</code> when it is extracted from the heap.</p>
0
2016-08-09T01:44:12Z
[ "python", "algorithm", "performance", "dijkstra", "conventions" ]
Django model update on fetch
38,825,430
<p>My model has a field that should change if it's within a date range.</p> <p>It would look like this:</p> <pre><code>class Election(models.Model) start_date = models.DateTimeField(verbose_name = 'Start Date') end_date = models.DateTimeField(verbose_name = 'End date') active = models.BooleanField(default=False) def updateActive(self): now = timezone.now() if self.start_date &lt; now and self.end_date &gt; now: self.active=True else: self.active=False self.save() </code></pre> <p>RIght now, every time I query for this model, I call <code>updateActive()</code> from my <code>views.py</code>.</p> <p>So, my question is: Is there a way to call <code>updateActive()</code> every time I fetch an <code>Election</code> object? Or keeping it constant updated?</p> <p>Any idea is welcome.</p>
1
2016-08-08T09:20:24Z
38,826,669
<p>You can write a custom manager for the model. While you can set the active attribute for the instances in the query itself, it doesn't seem correct from a design point of view(A get method shouldn't mutate the data it is querying). It makes sense to have an active attribute as you may want to invalidate a certain instance later manually. You could either update the active field using a background job, this way your manager would look like </p> <pre><code>class ElectionManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(active=True) class Election(models.Model): start_date = models.DateTimeField(verbose_name = 'Start Date') end_date = models.DateTimeField(verbose_name = 'End date') active = models.BooleanField(default=False) elections = ElectionManager() </code></pre> <p>This way Election.elections.all() would return only active elections. If you want to filter out the query via a class method, then you can use list comprehension or generators to get the required queryset in the ElectionManager.get_queryset method.</p>
0
2016-08-08T10:19:00Z
[ "python", "django" ]
Django model update on fetch
38,825,430
<p>My model has a field that should change if it's within a date range.</p> <p>It would look like this:</p> <pre><code>class Election(models.Model) start_date = models.DateTimeField(verbose_name = 'Start Date') end_date = models.DateTimeField(verbose_name = 'End date') active = models.BooleanField(default=False) def updateActive(self): now = timezone.now() if self.start_date &lt; now and self.end_date &gt; now: self.active=True else: self.active=False self.save() </code></pre> <p>RIght now, every time I query for this model, I call <code>updateActive()</code> from my <code>views.py</code>.</p> <p>So, my question is: Is there a way to call <code>updateActive()</code> every time I fetch an <code>Election</code> object? Or keeping it constant updated?</p> <p>Any idea is welcome.</p>
1
2016-08-08T09:20:24Z
38,834,349
<p>The best method would be not to have the <code>active</code> field at all in your model. The main reason is that when a value can be generated from a simple calculation, it should not be stored in the database. The second reason is that BooleanField cannot be effectively indexed and queries involving this field will be slow. Therefore you do not lose anything by doing the calculation instead of doing the field. The best way is to add a custom queryset like this:</p> <pre><code>class ElectionQuerySet(models.QuerySet): def is_active(self): return self.filter(start_date__lt=timezone.now()).filter(end_date__gt=timezone.now()) </code></pre> <p>Now your model is really simple.</p> <p>class Election(models.Model): start_date = models.DateTimeField(verbose_name = 'Start Date') end_date = models.DateTimeField(verbose_name = 'End date')</p> <pre><code>objects = ElectionQuerySet.as_manager() </code></pre> <p>Now your model is realy simple. </p> <pre><code>class Election(models.Model): start_date = models.DateTimeField(verbose_name = 'Start Date') end_date = models.DateTimeField(verbose_name = 'End date') objects = ElectionQuerySet.as_manager() </code></pre> <p>Yes that's all. There is no need to update the database everytime you fetch an object! You can use a simple method to find out what's active or not</p> <pre><code>Election.objects.is_active() </code></pre> <p>The result from is_active is a queryset, and you can chain it as usual</p> <pre><code>Election.objects.is_active().filter(...) </code></pre> <p>if you want to check if an election is active in the template you can do :</p> <pre><code>class Election(models.Model): def is_active() if self.start_date &lt; now and self.end_date &gt; now: return True </code></pre>
1
2016-08-08T16:33:54Z
[ "python", "django" ]
Odd character popping up when writing to a file
38,825,492
<p>New to python. I'm testing out files and I'm trying to get a number (taken as raw input) to be written to a file. Then I want a function I've made to take that number as it's input parameter and perform an equation with it.</p> <p>For some reason though, when writing to the file a strange character pops up. When I tried to copy-paste it to look it up, it just copied as this weird block of numbers or as an empty space. <a href="http://i.stack.imgur.com/oYtim.png" rel="nofollow">weird character in notepad</a></p> <p>Here is my code so far:</p> <pre><code>def function(x): y = x + 1 return y Input = raw_input('Number?') with open('in_test.txt','w+') as inFile_test: inFile_test.write(Input) lines = inFile_test.readline() lines_int = [int(x) for x in lines.split()] print str(lines_int) f_test = function(lines_int) print str(f_test) </code></pre> <p>I've also tried changing the file format to r+, checking the encoding type in notepad (ANSI), and looking up the error that comes up.</p> <pre><code> lines_int = [int(x) for x in lines.split()] ValueError: invalid literal for int() with base 10: '\x02' </code></pre> <p>I'm assuming the error is caused by the weird character but I'm not sure what's causing the weird character.</p>
0
2016-08-08T09:23:19Z
38,826,048
<p>You need to reset the file pointer back to the beginning. You can check the current position of the file pointer with the tell() function.</p> <pre><code>with open('in_test.txt','w+') as inFile_test: inFile_test.write(Input) print inFile_test.tell() inFile_test.seek(0) # re-position the file pointer to the beginning lines = inFile_test.readline() lines_int = [int(x) for x in lines.split()] print str(lines_int) </code></pre> <p>Also, the call to function() is incorrect, you've defined it to accept an int but are calling it with a list argument.</p>
0
2016-08-08T09:49:46Z
[ "python", "python-2.7", "file", "character", "file-writing" ]
Run python script in VB.net on button click
38,825,514
<p>I want to run a Python script in cmd when a button is clicked in VB.Net. Do you need to call the Python script in a batch file? Or can you do it directly in VB?</p> <p>I tried this</p> <pre><code>Dim ps As New ProcessStartInfo("cmd.exe") ps.Arguments = "C:\yourbatfile.bat" Process.Start(ps) </code></pre> <p>But that only opens the cmd window and doesn't execute the bat file.</p>
3
2016-08-08T09:24:28Z
38,826,342
<pre><code>Dim psi = New ProcessStartInfo("c:\python27\python.exe", "myPythonScript.py") Dim proc = Process.Start(psi) proc.WaitForExit() If proc.ExitCode &lt;&gt; 0 then throw new Exception(" Script Failed") </code></pre>
2
2016-08-08T10:03:38Z
[ "python", "vb.net", "cmd" ]
Jupyter keyboard shortcut for running a specific cell
38,825,528
<p>In my workflow with Jupyter notebook, I have a cell like:</p> <pre><code>%run myscript.py </code></pre> <p>Which loads the latest version of a script with functions I'm using. I am constantly updating this script and using its function in my notebook. Therefore, I find myself constantly going back to the first cell and running it. It would be very convenient if there was a keyboard shortcut to do that (e.g. run the first cell). Does it exist?</p>
2
2016-08-08T09:24:51Z
38,828,414
<p>You can click "Ctrl + Enter" to run only the chosen cell no matter it is "edit mode" or "command mode".</p> <p>If you want to know more available commands, just input <code>Esc</code> to change you current mode to "command mode" and input "h" to show the Keyboard shortcuts modal.</p>
2
2016-08-08T11:46:41Z
[ "python", "keyboard-shortcuts", "jupyter", "jupyter-notebook" ]
how can i call mutiple files(bash files) from subprocess.call in python
38,825,530
<p>#i am trying to run all the bash scripts in plugin folder </p> <pre><code>import sys,os,subprocess folder_path=os.listdir(os.path.join(os.path.dirname(__file__),'plugins')) sys.path.append(os.path.join(os.path.dirname(__file__),'plugins')) for file in folder_path: if file == '~': continue elif file.split('.')[1]=="sh": print file subprocess.call(['./plugins/${file} what'],shell=True,executable='/bin/bash') it shows error: bash: /bin/bash: ./plugins/: Is a directory </code></pre>
0
2016-08-08T09:24:53Z
38,825,600
<p>You'll need to actually insert the <code>file</code> variable into the subprocess call string:</p> <pre><code>subprocess.call(['./plugins/%s what' % file],shell=True,executable='/bin/bash') </code></pre>
1
2016-08-08T09:28:18Z
[ "python", "bash", "subprocess" ]
time in strings format: python
38,825,562
<p>I am using a function to bring my date consistent in a column, it goes like this</p> <pre><code>from dateutil.parser import parse def dateconv1(x): c = parse(x) return c </code></pre> <p>so if i will use it as, it works fine </p> <pre><code>In[15]:dateconv1("1 / 22 / 2016 15:03") Out[15]:datetime.datetime(2016, 1, 22, 15, 3) </code></pre> <p>But when I pass it in variable like this </p> <pre><code>a= 1 / 22 / 2016 15:03 In[16]:dateconv1(str(a)) </code></pre> <p>It doesn't work, so how to bring it in quotes or as a string, every help will be appreciating </p>
0
2016-08-08T09:26:30Z
38,825,656
<p>What you have is not a valid syntax for defining a Python variable. You should wrap with <code>''</code> or <code>""</code> to make it a string:</p> <pre><code>a = "1 / 22 / 2016 15:03" dateconv1(a) </code></pre>
0
2016-08-08T09:31:38Z
[ "python", "string", "datetime", "pandas", "dataframe" ]
time in strings format: python
38,825,562
<p>I am using a function to bring my date consistent in a column, it goes like this</p> <pre><code>from dateutil.parser import parse def dateconv1(x): c = parse(x) return c </code></pre> <p>so if i will use it as, it works fine </p> <pre><code>In[15]:dateconv1("1 / 22 / 2016 15:03") Out[15]:datetime.datetime(2016, 1, 22, 15, 3) </code></pre> <p>But when I pass it in variable like this </p> <pre><code>a= 1 / 22 / 2016 15:03 In[16]:dateconv1(str(a)) </code></pre> <p>It doesn't work, so how to bring it in quotes or as a string, every help will be appreciating </p>
0
2016-08-08T09:26:30Z
38,826,094
<p>assuming that <a href="http://stackoverflow.com/questions/38825562/time-in-strings-format-python/38826094#comment65017630_38825656">you are talking about pandas dataset</a>, you can use pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to_datetime()</a> method:</p> <pre><code>In [66]: dates = ['1 / 22 / 2016 15:03', 'Jul 22 2016 12:32PM', 'Jul 22 2016 5:40PM', ....: 'Jul 22 2016 8:31PM', 'Jul 23 2016 2:01PM', 'Jul 23 2016 7:24PM', ....: 'Jul 24 2016 4:30PM', 'Aug 1 2016 4:00PM', 'Aug 1 2016 7:49PM'] In [67]: df = pd.DataFrame({'d':dates}) In [68]: df.dtypes Out[68]: d object dtype: object </code></pre> <p><code>d object</code> - means that the <code>d</code> column is of a string (object) dtype</p> <pre><code>In [69]: df Out[69]: d 0 1 / 22 / 2016 15:03 1 Jul 22 2016 12:32PM 2 Jul 22 2016 5:40PM 3 Jul 22 2016 8:31PM 4 Jul 23 2016 2:01PM 5 Jul 23 2016 7:24PM 6 Jul 24 2016 4:30PM 7 Aug 1 2016 4:00PM 8 Aug 1 2016 7:49PM </code></pre> <p>let's convert it to <code>datetime</code> dtype:</p> <pre><code>In [70]: df.d = pd.to_datetime(df.d) In [71]: df Out[71]: d 0 2016-01-22 15:03:00 1 2016-07-22 12:32:00 2 2016-07-22 17:40:00 3 2016-07-22 20:31:00 4 2016-07-23 14:01:00 5 2016-07-23 19:24:00 6 2016-07-24 16:30:00 7 2016-08-01 16:00:00 8 2016-08-01 19:49:00 </code></pre> <p>check dtype again:</p> <pre><code>In [72]: df.dtypes Out[72]: d datetime64[ns] dtype: object </code></pre>
1
2016-08-08T09:52:26Z
[ "python", "string", "datetime", "pandas", "dataframe" ]
can't put text to .txt file using python
38,825,660
<p>This is flow what i want in my program:<br> - Read latest data in text file<br> - add up latest data with specific data what i want<br> - write the sum into text file in starts at the beginning of the file<br><br></p> <p>I've got what I want to make but there is an error. What should I do?<br> Here's my python code:</p> <pre><code>f = open('uangmasuk.txt', 'r+') latest = f.readline() data = int(latest) + 1000 f.write(data) f.close() </code></pre> <p>Here's my text file:</p> <pre><code>0 1000 2000 </code></pre> <p>Error Message:</p> <pre><code> File "test.py", line 4, in &lt;module&gt; f.write(data) TypeError: expected a character buffer object </code></pre>
-1
2016-08-08T09:31:43Z
38,825,813
<p>Your code needs a fix at <code>f.write</code>, which takes a string as parameter and not an integer:</p> <pre><code>f.write(str(data) + '\n') # |&lt;- cast integer to string # |&lt;- add new line character </code></pre>
0
2016-08-08T09:39:17Z
[ "python", "text-files", "python-2.x" ]
Convert measurement from String to Int or Float
38,825,669
<p>I have the string</p> <pre><code>var = '7 msecs' #var = int(var) #var = float(var) </code></pre> <p>And I want to convert that to an integer (7), or float (7.0). This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.</p> <p>How can I do this in Python?</p> <p>I want a good way to do this, without having to do</p> <pre><code>var = int(var.split(' ')[0]) </code></pre> <p>It should also work for:</p> <pre><code>'10mm' or '10.55€' </code></pre> <p>Considered duplicate (<a href="http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string">Python: Extract numbers from a string</a>)</p> <p>This question is different, as I'm trying to replicate the ability of parseInt/parseFloat in javascript which only returns the numbers at the beginning of a string. This other question is looking for all numbers in a string. </p> <pre><code>#What I want: '123mm' -&gt; 123 '123mm1' -&gt; 123 </code></pre>
-2
2016-08-08T09:32:14Z
38,825,820
<p>If &nbsp;&nbsp;<code>var = '7 msecs'</code></p> <p>By <strong>filter</strong>:</p> <pre><code>int(filter(str.isdigit, var)) </code></pre> <p>By <strong>Regex</strong>:</p> <pre><code>import re p = re.compile(ur'\d') re.search(p, var) </code></pre> <p>Or By <strong>join</strong>:</p> <pre><code>s = ''.join(x for x in var if x.isdigit()) print int(s) 7 </code></pre>
-1
2016-08-08T09:39:32Z
[ "python", "string", "int", "measurement" ]
Convert measurement from String to Int or Float
38,825,669
<p>I have the string</p> <pre><code>var = '7 msecs' #var = int(var) #var = float(var) </code></pre> <p>And I want to convert that to an integer (7), or float (7.0). This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.</p> <p>How can I do this in Python?</p> <p>I want a good way to do this, without having to do</p> <pre><code>var = int(var.split(' ')[0]) </code></pre> <p>It should also work for:</p> <pre><code>'10mm' or '10.55€' </code></pre> <p>Considered duplicate (<a href="http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string">Python: Extract numbers from a string</a>)</p> <p>This question is different, as I'm trying to replicate the ability of parseInt/parseFloat in javascript which only returns the numbers at the beginning of a string. This other question is looking for all numbers in a string. </p> <pre><code>#What I want: '123mm' -&gt; 123 '123mm1' -&gt; 123 </code></pre>
-2
2016-08-08T09:32:14Z
38,825,885
<p>This is already answered here: <a href="http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string">Python: Extract numbers from a string</a></p> <p>You could use a regular expression to extract all numbers from a string:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "7 msecs" &gt;&gt;&gt; re.findall(r"\d+", s) ["7"] </code></pre> <p>If you only want the first number from the string as int, you could use:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "7 msecs" &gt;&gt;&gt; int(re.findall(r"\d+", s)[0]) 7 </code></pre>
-1
2016-08-08T09:42:04Z
[ "python", "string", "int", "measurement" ]
Convert measurement from String to Int or Float
38,825,669
<p>I have the string</p> <pre><code>var = '7 msecs' #var = int(var) #var = float(var) </code></pre> <p>And I want to convert that to an integer (7), or float (7.0). This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.</p> <p>How can I do this in Python?</p> <p>I want a good way to do this, without having to do</p> <pre><code>var = int(var.split(' ')[0]) </code></pre> <p>It should also work for:</p> <pre><code>'10mm' or '10.55€' </code></pre> <p>Considered duplicate (<a href="http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string">Python: Extract numbers from a string</a>)</p> <p>This question is different, as I'm trying to replicate the ability of parseInt/parseFloat in javascript which only returns the numbers at the beginning of a string. This other question is looking for all numbers in a string. </p> <pre><code>#What I want: '123mm' -&gt; 123 '123mm1' -&gt; 123 </code></pre>
-2
2016-08-08T09:32:14Z
38,825,987
<p>If you want to avoid importing regex, you can try using <a href="https://docs.python.org/2/library/stdtypes.html#str.isdigit" rel="nofollow"><code>isdigit()</code></a>. But for what it's worth, I'd prefer <code>int(var.split()[0])</code> to this:</p> <pre><code>var = '7 msecs' numeric_end = 0 for i in xrange(len(var)): if not var[i].isdigit(): numeric_end = i break print int(var[:numeric_end]) </code></pre> <p>I chose to track the index of the first non-digit character instead of building a string for slight memory/performance reasons. This also only extracts the first number in the string.</p> <p>This will of course, only work for ints. For a float, you would have to also accept the <code>.</code> character (and probably keep track of whether or not you already have to determine if it's a valid float string).</p>
-1
2016-08-08T09:46:49Z
[ "python", "string", "int", "measurement" ]
Convert measurement from String to Int or Float
38,825,669
<p>I have the string</p> <pre><code>var = '7 msecs' #var = int(var) #var = float(var) </code></pre> <p>And I want to convert that to an integer (7), or float (7.0). This conversion works in javascript, as it seems to take the first value before the following, non-numerical values.</p> <p>How can I do this in Python?</p> <p>I want a good way to do this, without having to do</p> <pre><code>var = int(var.split(' ')[0]) </code></pre> <p>It should also work for:</p> <pre><code>'10mm' or '10.55€' </code></pre> <p>Considered duplicate (<a href="http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string">Python: Extract numbers from a string</a>)</p> <p>This question is different, as I'm trying to replicate the ability of parseInt/parseFloat in javascript which only returns the numbers at the beginning of a string. This other question is looking for all numbers in a string. </p> <pre><code>#What I want: '123mm' -&gt; 123 '123mm1' -&gt; 123 </code></pre>
-2
2016-08-08T09:32:14Z
38,826,667
<p>If you have white space, use <code>split</code>:</p> <pre><code>&gt;&gt;&gt; s = "123 msecs2" &gt;&gt;&gt; int(s.split()[0]) 123 </code></pre> <p>If you want to take the numbers from the start of a string only without white space (or using regex), try this:</p> <pre><code>&gt;&gt;&gt; s = "123msecs2" &gt;&gt;&gt; int("".join(list(next(iter(())) if not x.isdigit() else x for x in s))) 123 </code></pre> <p>Note, it takes inspiration from the discussion <a href="http://stackoverflow.com/questions/9572833/break-list-comprehension">here</a> about breaking out of list comprehensions.</p>
1
2016-08-08T10:18:58Z
[ "python", "string", "int", "measurement" ]
best match algorithm in python
38,825,712
<p>What should be optimal implementation for best match in python.</p> <p>I have a txt file which has some country codes mapping e.g.</p> <h1>CODES NAME</h1> <p>123 ABC</p> <p>1234 DEF</p> <p>1235 GHI</p> <p>124 JKL</p> <p>1241 MNO</p> <p>This txt file is big(13500 records) I'm just putting some sample.</p> <p>Further I have some CDR files where I get country code(numeric) in each record(row) which I want to convert to country name.</p> <p>Now what I mean by best match is, say the CDR record contains country code "1234" then country name would be "DEF", if it is "1235" the country name would be "GHI" but if the country code is "1236" then perfect match fails and it should fall back to "ABC" since "123" is available.</p> <p>I don't know is there is a standard name for this kinda search. like greedy search in regular expressions.</p> <p>What can be best implementation for this kind search, since the CDR files are really big(upto 25GB).</p>
-3
2016-08-08T09:35:11Z
38,834,124
<p>Dictionaries are the easiest way to implement this. See below solution:</p> <ol> <li>Convert</li> </ol> <p>123 ABC</p> <p>1234 DEF</p> <p>1235 GHI</p> <p>124 JKL</p> <p>1241 MNO</p> <p>to {1241: 'MNO', 1234: 'DEF', 123: 'ABC', 124: 'JKL', 1235: 'GHI'}</p> <ol start="2"> <li>Read CDR file with country codes and then search in dictionary</li> <li>if code not found remove unit's place and search again.</li> <li>Still not found- print 'No match found'</li> </ol> <p>Below is the code for the same-</p> <pre><code>country_name = {} with open('U:\countrynames.csv','r') as f: for line in f: linesplit = line.split() country_name[int(linesplit[0])] = linesplit[1] with open('U:\countrycodesCDR.csv','r') as f: for line in f: country_code = int(line.strip()) while country_code != 0: if country_code in country_name: print country_name[country_code] break else: country_code /=10 else: print 'No match found' </code></pre>
-1
2016-08-08T16:20:48Z
[ "python", "algorithm", "search" ]
Checking time for executing if statement
38,825,824
<p>I'm practising Python and I want to write a program that checks current time and see if it matches 2:12 pm and says: <code>its lunch time</code> So first I figured out using <code>import time</code> module, but I don't know how?</p> <p>My problem is I don't know how to use time module for that. Or I'm using right syntax or not?</p> <p>My code:</p> <pre><code>import time bake=time() if bake == '2:12': print ('its time to eating lunch') else : print ('its not the time for eating lunch') </code></pre>
-3
2016-08-08T09:39:43Z
38,825,941
<p>I suggest the datetime module, which is more practicale in this case (as polku suggested). You will then directly access only hour and minute to check if it is lunch time.</p> <p>Further information can be found here: <a href="http://stackoverflow.com/questions/30071886/how-to-get-current-time-in-python-and-break-up-into-year-month-day-hour-minu">How to get current time in python and break up into year, month, day, hour, minute?</a></p> <pre><code>import datetime now = datetime.datetime.now() if now.hour == 14 and now.minute == 12: print ('its time to eating lunch') else : print ('its not the time for eating lunch') </code></pre>
1
2016-08-08T09:45:11Z
[ "python" ]
Checking time for executing if statement
38,825,824
<p>I'm practising Python and I want to write a program that checks current time and see if it matches 2:12 pm and says: <code>its lunch time</code> So first I figured out using <code>import time</code> module, but I don't know how?</p> <p>My problem is I don't know how to use time module for that. Or I'm using right syntax or not?</p> <p>My code:</p> <pre><code>import time bake=time() if bake == '2:12': print ('its time to eating lunch') else : print ('its not the time for eating lunch') </code></pre>
-3
2016-08-08T09:39:43Z
38,826,164
<pre><code>import datetime as da lunch = "02:12 PM" now = da.datetime.now().strftime("%I:%M %p") if now == lunch: print("lunch time") else: print("not lunch time") </code></pre>
-2
2016-08-08T09:56:04Z
[ "python" ]