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
Remove numbers conditionally?
38,793,863
<p>I'm sorry if the title isn't very descriptive. I don't exactly know how to sum up my problem in a few words.</p> <p>Here's my issue. I'm cleaning addresses and some of them are causing some issues.</p> <p>I have a list of delimiters (avenue, street, road, place, etc etc etc) named <code>patterns</code>.</p> <p>Let's say I have this address for example: <code>SUITE 1603 200 PARK AVENUE SOUTH NEW YORK</code></p> <p>I would like the output to be <code>SUITE 200 PARK AVENUE SOUTH NEW YORK</code></p> <p>Is there any way I could somehow look to see if there are 2 batches of numbers (in this case <code>1603</code> and <code>200</code>) before one of my patterns and if so, strip the first batch of numbers from my string? i.e remove <code>1603</code> and keep <code>200</code>.</p> <p>Update: I've added this line to my code: </p> <p><code>address = re.sub("\d+", "", address)</code> however it's currently removing all the numbers. I thought that by putting ,1 after address it would only remove the first occurrence but that wasn't the case</p>
1
2016-08-05T16:25:54Z
38,794,500
<p>If you want to apply this replacement <em>only</em> when one of your "separator" words is used, and <em>only</em> when there are two numbers, you can use a fancier regular expression.</p> <pre><code>import re pattern = r"\d+ +(\d+ .*(STREET|AVENUE|ROAD|WHATEVER))" input = "SUITE 1603 200 PARK AVENUE SOUTH NEW YORK" output = re.sub(pattern, "\\1", input) print(output) #SUITE 200 PARK AVENUE SOUTH NEW YORK </code></pre>
3
2016-08-05T17:06:37Z
[ "python" ]
Parsing '\n' to '\n ctrl-l' with Python
38,793,990
<p>I have a program that can access Python from inside within it's initial file, that looks like</p> <blockquote> <p>#initial file<br> source py_commands.py<br> py_cmd </p> </blockquote> <p>I want to grep from inside that program <code>\n</code> and parse it to <code>\n ctrl-l</code>. Ctrl-l is just a combined key stroke like in bash, screen or other TUI and invokes a command in this program, which I otherwise always have manually to type and should only be invoked after a <code>\n</code>.</p> <p>I tried this without success:</p> <pre><code>x = raw_input() print(x + '\u000C') </code></pre> <p>I'm not well versed in Python and only need this one piece. Any help is appreciated.</p>
0
2016-08-05T16:34:14Z
38,968,979
<p><code>raw_input()</code> strips the trailing newline. If you want the string to end with <code>\n</code> <code>\f</code> (Ctrl-L is <em>Form Feed</em>), you have to add both.</p> <pre><code>x = raw_input() print(x+'\n\f') </code></pre>
1
2016-08-16T07:30:50Z
[ "python", "linux", "parsing" ]
Selenium Python : extract field from json data in <a> tag
38,794,012
<p>On a particular webpage, I have the following tag :</p> <pre><code>&lt;a id="AAA" class="BBB" data-json="{"link":"thelink","field1":1,"field2":5}"&gt; Load more &lt;/a&gt; </code></pre> <p>I am using Selenium / Python. I want to click 5 times on this tag, where 5 is the value from "field2" in "data-json".</p> <p>The XPATH is ".//*[@id='AAA']" (thanks to FireXPath) so I want to use 5 times the following command:</p> <pre><code>browser.findElement(By.XATH(".//*[@id='AAA']")).click(); </code></pre> <p>Question is : how to extract this "5" from &lt; a tag > / data-json / field2 ?</p>
0
2016-08-05T16:35:35Z
38,794,172
<p>To get the value of an attribute you can use the function <code>get_attribute</code> <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.get_attribute" rel="nofollow">link</a>, in this particular case we have to parse the data-json to a dict and get the number. My suggest is:</p> <pre><code>import json json_dict = json.loads(browser.findElement(By.ID('AAA')).get_attribute('data-json')) number_times = json_dict["field2"] </code></pre>
1
2016-08-05T16:46:58Z
[ "python", "json", "selenium", "xpath" ]
Selenium Python : extract field from json data in <a> tag
38,794,012
<p>On a particular webpage, I have the following tag :</p> <pre><code>&lt;a id="AAA" class="BBB" data-json="{"link":"thelink","field1":1,"field2":5}"&gt; Load more &lt;/a&gt; </code></pre> <p>I am using Selenium / Python. I want to click 5 times on this tag, where 5 is the value from "field2" in "data-json".</p> <p>The XPATH is ".//*[@id='AAA']" (thanks to FireXPath) so I want to use 5 times the following command:</p> <pre><code>browser.findElement(By.XATH(".//*[@id='AAA']")).click(); </code></pre> <p>Question is : how to extract this "5" from &lt; a tag > / data-json / field2 ?</p>
0
2016-08-05T16:35:35Z
38,794,272
<p>As mentionned by peers, it would be far better with <strong>id</strong>.</p> <p>You can use <code>get_attribute</code> and json convertion:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; data = browser.find_element_by_id("AAA").get_attribute("data-json") &gt;&gt;&gt; json.loads(data)["field2"] &gt;&gt;&gt; 5 </code></pre>
0
2016-08-05T16:53:09Z
[ "python", "json", "selenium", "xpath" ]
Creating class object from pandas series and applying methods
38,794,077
<p>I have a function that reads in a bunch of raw data with some user-input and compiles it into a Pandas series. In the example below I call it <code>create_data</code> and it just builds a random Series of length <code>n</code>. </p> <pre><code>&gt;&gt;&gt; def create_data(n): ... return pd.Series(np.random.randint(1, 100, n)) ... &gt;&gt;&gt; &gt;&gt;&gt; function_result=create_data(10) &gt;&gt;&gt; function_result 0 73 1 91 2 31 3 44 4 19 5 30 6 42 7 56 8 69 9 70 dtype: int32 </code></pre> <p>Then I have a set of functions that want to be able to apply to this series. In this example, I create one that calculates the correlation between the series and its first-degree difference.</p> <pre><code>&gt;&gt;&gt; def temporal_corr(x): ... return pd.concat([x, x.shift()], 1).corr().iloc[0, 1] ... </code></pre> <p>I can obviously just apply it to series by calling the function...</p> <pre><code>&gt;&gt;&gt; temporal_corr(function_result) 0.38714413906049816 </code></pre> <p>But let's say I have several different functions that I want to use on this series. Would it make more sense (or is it possible), to create a class that constructs an object using the function <code>create_data</code> and then have a set of functions within the class that can be applied as methods? I create a class and define this function below.</p> <pre><code>&gt;&gt;&gt; class myobj: ... def __init__(self, myobj): ... self.myobj = myobj ... ... def temporal_corr(self): ... return pd.concat([self.myobj, self.myobj.shift()], 1).corr().iloc[0, 1] ... &gt;&gt;&gt; a = myobj(function_result) &gt;&gt;&gt; a.temporal_corr() 0.38714413906049816 </code></pre> <p>What is the best way to have the class object <code>myobj</code> be created as a result of the function <code>create_data</code>? I would like to be able to call <code>create_data</code> and have the result be an object from which I can call <code>temporal_corr()</code>. </p>
1
2016-08-05T16:40:12Z
38,855,563
<p>Essentially you're looking for an object that acts like a <code>Series</code> but is more <em>specialized</em>, so, just create a class that inherits from <code>pd.Series</code>:</p> <pre><code>import pandas as pd from numpy.random import randint class mySeries(pd.Series): def __init__(self, n): super().__init__(randint(0, 100, n)) # initialize series # Add your custom methods: def temporal_corr(self): return pd.concat([self, self.shift()], 1).corr().iloc[0, 1] </code></pre> <p>Then, <code>create_data</code> can be your factory function for your specialized <code>Series</code> objects:</p> <pre><code>def create_data(n): return mySeries(n) </code></pre> <p>which you can extend and add checks according to your needs.</p>
1
2016-08-09T16:02:44Z
[ "python", "pandas" ]
Creating class object from pandas series and applying methods
38,794,077
<p>I have a function that reads in a bunch of raw data with some user-input and compiles it into a Pandas series. In the example below I call it <code>create_data</code> and it just builds a random Series of length <code>n</code>. </p> <pre><code>&gt;&gt;&gt; def create_data(n): ... return pd.Series(np.random.randint(1, 100, n)) ... &gt;&gt;&gt; &gt;&gt;&gt; function_result=create_data(10) &gt;&gt;&gt; function_result 0 73 1 91 2 31 3 44 4 19 5 30 6 42 7 56 8 69 9 70 dtype: int32 </code></pre> <p>Then I have a set of functions that want to be able to apply to this series. In this example, I create one that calculates the correlation between the series and its first-degree difference.</p> <pre><code>&gt;&gt;&gt; def temporal_corr(x): ... return pd.concat([x, x.shift()], 1).corr().iloc[0, 1] ... </code></pre> <p>I can obviously just apply it to series by calling the function...</p> <pre><code>&gt;&gt;&gt; temporal_corr(function_result) 0.38714413906049816 </code></pre> <p>But let's say I have several different functions that I want to use on this series. Would it make more sense (or is it possible), to create a class that constructs an object using the function <code>create_data</code> and then have a set of functions within the class that can be applied as methods? I create a class and define this function below.</p> <pre><code>&gt;&gt;&gt; class myobj: ... def __init__(self, myobj): ... self.myobj = myobj ... ... def temporal_corr(self): ... return pd.concat([self.myobj, self.myobj.shift()], 1).corr().iloc[0, 1] ... &gt;&gt;&gt; a = myobj(function_result) &gt;&gt;&gt; a.temporal_corr() 0.38714413906049816 </code></pre> <p>What is the best way to have the class object <code>myobj</code> be created as a result of the function <code>create_data</code>? I would like to be able to call <code>create_data</code> and have the result be an object from which I can call <code>temporal_corr()</code>. </p>
1
2016-08-05T16:40:12Z
38,878,992
<p>If I understand your question correctly, I think you're looking to do the following:</p> <pre><code>import pandas as pd import numpy as np class MyObjMaker(object): def __init__(self, n): self.myobj = pd.Series(np.random.randint(1, 100, n)) def temporal_corr(self): return pd.concat([self.myobj, self.myobj.shift()], 1).corr().iloc[0, 1] def create_data(n): return MyObjMaker(n) </code></pre> <p>Here, the function <code>create_data</code> creates an object from the class, and that has your <code>temporal_corr</code> function. For example, I'd use it as follows:</p> <pre><code>In [2]: a = create_data(10) # `a` is now an instance of MyObjMaker In [4]: type(a) # proof that `a` is now an instance of MyObjMaker Out[4]: __main__.MyObjMaker In [5]: a.temporal_corr() # `temporal_corr` works Out[5]: -0.18294239972101703 </code></pre> <p>Jim's solution should be fine too, but it sub-classes off of <code>pd.Series</code> - if you don't need all the other methods in <code>pd.Series</code> then there's no point sub-classing off of it.</p>
0
2016-08-10T16:32:28Z
[ "python", "pandas" ]
Django ForeignKeys not saving
38,794,192
<p>Currently have a problem where I will assign a both Client foreignkey to a Signin and its not saving either reference. Heres the Signin Model</p> <pre><code>#Sign-ins require just a user class Signin(models.Model): employee = models.ForeignKey(Employee) sign_in_time = models.DateTimeField(null=True) sign_out_time = models.DateTimeField(null=True) sign_in_number = models.CharField(max_length=15, default="00000000000") sign_out_number = models.CharField(max_length=15, default="00000000000") client_in_obj = models.ForeignKey(Clients, related_name="client_in", null=True) client_out_obj = models.ForeignKey(Clients, related_name="client_out", null=True) client_in = models.CharField(max_length=100, default="Unkown") client_out = models.CharField(max_length=100, null=True) # Start of Sign in Function def save(self, *args, **kwargs): self.client_out_obj.save() self.client_in_obj.save() super(Signin, self).save(*args, **kwargs) def __str__(self): return self.employee.first_name + " " + self.employee.last_name + " : " + str(self.sign_in_time)+ " to " + str(self.sign_out_time) </code></pre> <p>Now the employee field IS saving, but the two client_in_obj,and client_out_obj are NOT saving. I will assign them and then when refreshing the page they are not set.</p> <p>Here is the client Model </p> <pre><code>class Clients(models.Model): name = models.CharField(max_length=40, blank=True, null=True) alt_name = models.CharField(max_length=25, blank=True, null=True) address1 = models.CharField(max_length=35, blank=True, primary_key=True) address2 = models.CharField(max_length=35, blank=True, null=True) rate = models.FloatField(blank=True, null=True) contact_email = models.CharField(max_length=40, blank=True, null=True) contact_name = models.CharField(max_length=30, blank=True, null=True) phone = models.CharField(max_length=40, blank=True, null=True) billing_name = models.CharField(max_length=30, blank=True, null=True) billing_email_field = models.CharField(db_column='billing_email_', max_length=12, blank=True, null=True) # Field renamed because it ended with '_'. def __str__(self): return self.name + ", " + self.address1 class Meta: managed = False db_table = 'clients' </code></pre> <p>They client_in and client_out fields were my hackey way of trying to get by it for now.</p> <p>My relations I would like to keep are as followed - An employee will have Many Sign ins, and each Sign in only needs an employee at first, each other field will be filled in over the course of a day.</p>
0
2016-08-05T16:47:58Z
38,797,031
<p>I found the answer! </p> <p>So the problem was followed. Im dealing with a legacy database in mySQL, the problem was that when django was assigning the client id it was thinking the primary key was an integer field, so when it tried assigning the key (which was a varchar) it ran into an integer field, so it didn't like it and didn't save. Hopefully that helps anyone who runs into this problem later!</p>
1
2016-08-05T20:04:32Z
[ "python", "django" ]
Python - Internationalization for Telegram bots
38,794,237
<p>I'm using Python <strong>gettext</strong> to translate my Telegram bot messages to pt_BR or leave them in en_US. This is my code:</p> <pre><code># Config the translations lang_pt = gettext.translation("pt_BR", localedir="locale", languages=["pt_BR"]) def _(msg): return msg # Connecting to Redis db db = redis.StrictRedis(host="localhost", port=6379, db=0) def user_language(func): @wraps(func) def wrapped(bot, update, *args, **kwargs): lang = db.get(str(update.message.chat_id)) if lang == b"pt_BR": # If language is pt_BR, translates _ = lang_pt.gettext else: # If not, leaves as en_US def _(msg): return msg result = func(bot, update, *args, **kwargs) return result return wrapped @user_language def unknown(bot, update): """ Placeholder command when the user sends an unknown command. """ msg = _("Sorry, I don't know what you're asking for.") bot.send_message(chat_id=update.message.chat_id, text=msg) </code></pre> <p>But, even when the language is pt_BR, the text remains as en_US. It seems that the first declaration of function <code>_()</code> (line 3), translates all messages at once, and even when the <code>_()</code> function changes in the decorator, the messages doesn't get translated another time.</p> <p>How can I force the messages to be translated again in the decorator?</p>
1
2016-08-05T16:51:20Z
38,799,001
<p>Solved!</p> <p>I just forgot to declare the <strong>_()</strong> as being global. Here is the right code:</p> <pre><code>def user_language(func): @wraps(func) def wrapped(bot, update, *args, **kwargs): lang = db.get(str(update.message.chat_id)) global _ if lang == b"pt_BR": # If language is pt_BR, translates _ = lang_pt.gettext else: # If not, leaves as en_US def _(msg): return msg result = func(bot, update, *args, **kwargs) return result return wrapped </code></pre>
0
2016-08-05T23:22:15Z
[ "python", "internationalization", "telegram" ]
NoReverseMatch for Createview
38,794,348
<p>I am using the CreateView (CBV) with a template that has a form to review lawyers. </p> <p>When I try to use the URL routing in the template, I get this error:</p> <pre><code>Exception Value: Reverse for 'lawyerreview_create' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['fathers/lawyers/(?P&lt;lawyerreview_slug&gt;[\\w-]+)/createreview/$'] </code></pre> <p>I would like to reverse to this URL, for example: fathers/lawyers/lawyer-name/createreview. But after two days of trying different things, I am no closer to that goal. Can someone tell me what I am doing wrong? I am not just looking for an answer, I humbly asking that someone ELI5 proper linking in django.</p> <p>models:</p> <pre><code>class Lawyer(models.Model): name = models.CharField(max_length=100, default='') lawyer_slug = models.SlugField(default='') def __str__(self): return self.name class Review(models.Model): lawyer = models.ForeignKey(Lawyer, null=True) review_title = models.CharField(max_length=69, default='') review_created = models.DateTimeField('Date of Review', auto_now_add=True) user_name = models.CharField(max_length=100) rating = models.IntegerField() review_comment = models.TextField(default='') review_slug = models.SlugField(default='') </code></pre> <p>views.py</p> <pre><code>from django.views.generic import ListView, DetailView from django.views.generic import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from .models import Lawyer, Review class LawyerDetail(DetailView): model = Lawyer template = 'lawyer_detail.html' context_object_name = 'lawyers' def get_object(self): lawyer_slug = Lawyer.objects.get( lawyer_slug=self.kwargs.get('lawyer_slug') ) return lawyer_slug def get_context_data(self, **kwargs): context = super(LawyerDetail, self).get_context_data(**kwargs) context['lawyer_review'] = self.object.review_set.all() return context class LawyerReviewCreate(CreateView): model = Review fields = ['lawyer', 'rating', 'dos', 'review_comment'] class LawyerReviewUpdate(UpdateView): model = Review fields = ['lawyer', 'rating', 'dos', 'review_comment'] class LawyerReviewDelete(DeleteView): model = Review success_url = reverse_lazy('lawyer_detail') </code></pre> <p>template.html (the section that generates the NoReverseMatch error)</p> <pre><code>{% if lawyer_review %} {% for review in lawyer_review %} &lt;div class="review_buttom_wrapper"&gt; &lt;button class="review_button" href="{% url 'lawyerreview_create' lawyer.lawyerreview_create %}"&gt; &lt;strong&gt;Review&lt;/strong&gt; {{ review.lawyer.name }} &lt;/button&gt; &lt;/div&gt; </code></pre> <p>urls.py</p> <pre><code>url(r'^lawyers/(?P&lt;lawyer_slug&gt;[\w-]+)/$', LawyerDetail.as_view(), name='lawyer_detail'), url(r'^lawyers/(?P&lt;lawyer_slug&gt;[\w-]+)/createreview/$', LawyerReviewCreate.as_view(), name='lawyer_createreview'), url(r'^lawyers/(?P&lt;lawyer_slug&gt;[\w-]+)/update/$', LawyerReviewUpdate.as_view(), name='lawyer_editreview'), url(r'^lawyers/(?P&lt;lawyer_slug&gt;[\w-]+)/delete/$', LawyerReviewDelete.as_view(), name='lawyer_deletereview'), </code></pre> <p>Error generated after using wobbily_col's solution:</p> <pre><code>Exception Value: Reverse for 'lawyerreview_create' with arguments '()' and keyword arguments '{'lawyerreview_slug': ''}' not found. 0 pattern(s) tried: [] </code></pre> <p>Changed template to:</p> <pre><code>&lt;button class="review_button" href="{% url 'lawyerreview_create' review.lawyer.lawyer_slug %}"&gt; </code></pre> <p>Getting this error now:</p> <pre><code>Exception Value: Reverse for 'lawyerreview_create' with arguments '('michael-ferrin',)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] </code></pre> <p>The lawyer's name is now showing up in the URL.</p> <p>Edited template to this:</p> <pre><code>&lt;a href="{% url 'lawyer_createreview' review.review_slug %}"&gt; &lt;button class="review_button"&gt; &lt;strong&gt;Review&lt;/strong&gt; {{ review.lawyer.name }} &lt;/button&gt; &lt;/a&gt; </code></pre> <p>It is now properly linking to review_form template. However on submit, I get this error:</p> <pre><code>Exception Value: Reverse for 'lawyer_createreview' with arguments '()' and keyword arguments '{'review_slug': ''}' not found. 1 pattern(s) tried: ['fathers/lawyers/(?P&lt;lawyer_slug&gt;[\\w-]+)/createreview/$'] </code></pre> <p>I was expecting to be routed back to the page that sent me to the review form. </p>
0
2016-08-05T16:57:47Z
38,794,880
<p>The url tag takes the reverse name and arguments / keyword arguments as paramaters:</p> <pre><code>url(r'^lawyers/(?P&lt;lawyerreview_slug&gt;[\w-]+)/createreview/$', LawyerReviewCreate.as_view(), name='lawyerreview_create'), </code></pre> <p>so in this case it expects your urls name (lawyerview_create) and the lawyerreview_slug as a keyword argument. You are passing it a positional argument that doesn't seem to exist (lawyer.lawyerreview_create).</p> <p>Pass the lawyer_slug in like this:</p> <pre><code> &lt;button class="review_button" href="{% url 'lawyerreview_create' lawyerreview_slug=lawyer_review.lawyer.lawyer_slug %}"&gt; </code></pre>
1
2016-08-05T17:31:08Z
[ "python", "django", "url" ]
Replace dictionary's empty values python
38,794,388
<p>First of all, I'm modifying another guy's code.</p> <p>I'm trying to print the values of dictionary that correspond to a <code>key</code> like so: </p> <p><code>print (map(str, dict[key]))</code></p> <p>All works fine, but there are some fields that are printed with just the double quotes, like so <code>['some_value', '', 'other_value', etc...]</code>, what I'm trying to accomplish here, is to replace the single quotes <code>''</code>, with <code>n/a</code> </p> <p>my approach, at first, was to do this: <code>print (map(str.replace("\'\'", "n/a"), dict[key]))</code>, but I get the <code>TypeError</code> message: <code>TypeError: replace() takes at least 2 arguments (1 given)</code></p> <p>How can I work around this?</p>
0
2016-08-05T16:59:44Z
38,794,537
<p>Try using </p> <pre><code>print([k if k else "n/a" for k in map(str, dict[key])]) </code></pre>
0
2016-08-05T17:10:06Z
[ "python", "dictionary" ]
Replace dictionary's empty values python
38,794,388
<p>First of all, I'm modifying another guy's code.</p> <p>I'm trying to print the values of dictionary that correspond to a <code>key</code> like so: </p> <p><code>print (map(str, dict[key]))</code></p> <p>All works fine, but there are some fields that are printed with just the double quotes, like so <code>['some_value', '', 'other_value', etc...]</code>, what I'm trying to accomplish here, is to replace the single quotes <code>''</code>, with <code>n/a</code> </p> <p>my approach, at first, was to do this: <code>print (map(str.replace("\'\'", "n/a"), dict[key]))</code>, but I get the <code>TypeError</code> message: <code>TypeError: replace() takes at least 2 arguments (1 given)</code></p> <p>How can I work around this?</p>
0
2016-08-05T16:59:44Z
38,794,620
<p>map function needs func and iterable</p> <pre><code>data = { '':'',1:'a'} print (map( lambda x: x if x else 'n/a', data.values())) ['n/a', 'a'] </code></pre> <p>for value as list:</p> <pre><code>data = { 'a' :[1,'',2]} print (map( lambda x: str(x) if x else 'n/a', data['a'])) ['1', 'n/a', '2'] </code></pre>
0
2016-08-05T17:14:24Z
[ "python", "dictionary" ]
Replace dictionary's empty values python
38,794,388
<p>First of all, I'm modifying another guy's code.</p> <p>I'm trying to print the values of dictionary that correspond to a <code>key</code> like so: </p> <p><code>print (map(str, dict[key]))</code></p> <p>All works fine, but there are some fields that are printed with just the double quotes, like so <code>['some_value', '', 'other_value', etc...]</code>, what I'm trying to accomplish here, is to replace the single quotes <code>''</code>, with <code>n/a</code> </p> <p>my approach, at first, was to do this: <code>print (map(str.replace("\'\'", "n/a"), dict[key]))</code>, but I get the <code>TypeError</code> message: <code>TypeError: replace() takes at least 2 arguments (1 given)</code></p> <p>How can I work around this?</p>
0
2016-08-05T16:59:44Z
38,794,641
<p>You should probably just expand to a for loop and write:</p> <pre><code>for value in dict.values(): if value == "": print("n/a") else: print(str(value)) </code></pre>
0
2016-08-05T17:15:44Z
[ "python", "dictionary" ]
Replace dictionary's empty values python
38,794,388
<p>First of all, I'm modifying another guy's code.</p> <p>I'm trying to print the values of dictionary that correspond to a <code>key</code> like so: </p> <p><code>print (map(str, dict[key]))</code></p> <p>All works fine, but there are some fields that are printed with just the double quotes, like so <code>['some_value', '', 'other_value', etc...]</code>, what I'm trying to accomplish here, is to replace the single quotes <code>''</code>, with <code>n/a</code> </p> <p>my approach, at first, was to do this: <code>print (map(str.replace("\'\'", "n/a"), dict[key]))</code>, but I get the <code>TypeError</code> message: <code>TypeError: replace() takes at least 2 arguments (1 given)</code></p> <p>How can I work around this?</p>
0
2016-08-05T16:59:44Z
38,794,693
<p>You could solve your problem in a more simple way without using map(). Just use list() than you can loop on every single character of your string (diz[key]) and then replace the empty space with the 'n/a' string as you wish.</p> <pre><code>diz[key] = 'a val' [w.replace(' ', 'n/a') for w in list(diz[key])] &gt;&gt; ['a', 'n/a', 'v', 'a', 'l'] </code></pre>
0
2016-08-05T17:18:54Z
[ "python", "dictionary" ]
int() argument must be a string or a number, not 'SimpleLazyObject' in django
38,794,393
<p>I have this problem catching the pk of the Selfie model, i'm trying to save a comment, but i have this error, the mistake is in the CreateComment class in the views.py, please guys i need a hand</p> <p><strong>in models.py</strong></p> <pre><code>class Selfie(models.Model): selfie_title = models.CharField(max_length=50) selfie_description = models.TextField(null=True, blank=True) selfie_image = models.ImageField(upload_to="images/", width_field="selfie_width", height_field="selfie_height", ) selfie_height = models.IntegerField(default=0) selfie_width = models.IntegerField(default=0) selfie_favorite = models.BooleanField() selfie_user = models.ForeignKey("auth.User") selfie_timestamp = models.DateTimeField(auto_now=True) def __unicode__(self): return unicode(self.selfie_title) def __str__(self): return self.selfie_title class Comment(models.Model): comment_user = models.ForeignKey("auth.User") body_comment = models.TextField() timestamp_comment = models.DateTimeField(auto_now=True) post_comment = models.ForeignKey("Selfie") def __unicode__(self): return unicode(self.body_comment[:20]) def __str__(self): return self.body_comment[:20] </code></pre> <p><strong>in views.py</strong></p> <pre><code>class SelfieDetail(DetailView): template_name = "SelfieDetail.html" model = Selfie def get_context_data(self, **kwargs): context = super(SelfieDetail, self).get_context_data(**kwargs) context['form'] = CommentForm if self.request.POST: context['form'] = CommentForm(self.request.POST) else: context['form'] = CommentForm() return context class CreateComment(FormView): form_class = CommentForm success_url = '../login' template_name = "SelfieDetail.html" def get_form_kwargs(self): form_kwargs = super(CreateComment, self).get_form_kwargs() if 'pk' in self.kwargs: form_kwargs['instance'] = models.Selfie.objects.get(pk=int(self.kwargs['pk'])) return form_kwargs def form_valid(self, form, *args, **kwargs): context = self.get_context_data() form = context['form'] obj = form.save(commit=False) obj.comment_user_id = self.request.user #obj.post_comment_id = kwargs={'pk': Selfie.pk} .... self.request.POST.get('comment') obj.post_comment_id = self.request.GET.get( 'post_comment_id' ) obj.save() return redirect('/login') </code></pre> <p><strong>template</strong></p> <pre><code>&lt;form method="POST" action="{% url 'createComment' %}"&gt; {% csrf_token %} {{ form.as_p }} &lt;button type="submit" class="btn btn-lg"&gt;(Comentar)&lt;/button&gt; &lt;/form&gt; </code></pre> <p><strong>traceback</strong></p> <pre><code>Environment: Request Method: POST Request URL: http://127.0.0.1:8000/comment/ Django Version: 1.9 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stylizrApp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post 221. return self.form_valid(form) File "/home/l/Desktop/stylizr/src/stylizrApp/views.py" in form_valid 49. obj.save() File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/base.py" in save 700. force_update=force_update, update_fields=update_fields) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base 728. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table 812. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert 851. using=using, raw=raw) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method 122. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/query.py" in _insert 1039. return query.get_compiler(using=using).execute_sql(return_id) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql 1064. cursor.execute(sql, params) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 79. return super(CursorDebugWrapper, self).execute(sql, params) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__ 95. six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/l/Desktop/stylizr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) Exception Type: IntegrityError at /comment/ Exception Value: null value in column "post_comment_id" violates not-null constraint DETAIL: Failing row contains (22, asda, 2016-08-05 17:18:07.513423+00, 1, null). </code></pre>
0
2016-08-05T17:00:09Z
38,794,616
<p>You can't assign the <code>user</code> to <code>comment_user_id</code> because it expects an integer. Either of the following would work:</p> <pre><code>obj.comment_user_id = self.request.user.id obj.comment_user = self.request.user </code></pre>
1
2016-08-05T17:14:17Z
[ "python", "django" ]
Why is matplotlib's notched boxplot folding back on itself?
38,794,406
<p>I tried to make a notched boxplot using matplotlib, but found the notched box tends to overextend and then fold back on itself. This does not happen when I make a regular boxplot. </p> <p>This can be seen with the following code and the resulting plot that gets generated:</p> <pre><code>import matplotlib.pyplot as plt data = [[-0.056, -0.037, 0.010, 0.077, 0.082], [-0.014, 0.021, 0.051, 0.073, 0.079]] # Set 2 plots with vertical layout (1 on top of other) fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True) ax1.boxplot(data, 1) #Notched boxplot ax2.boxplot(data, 0) #Standard boxplot ax1.set_ylim([-0.1, 0.1]) ax2.set_ylim([-0.1, 0.1]) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/DTvDw.png" rel="nofollow"><img src="http://i.stack.imgur.com/DTvDw.png" alt="Bad Notched Boxplot and Std. boxplot"></a></p> <p>Does anyone know what I'm doing wrong and how I can fix this?</p>
1
2016-08-05T17:00:55Z
38,795,446
<p>It means that the distribution of the data is skewed. If two boxes' notches do not overlap, there is 95% confidence their medians differ.</p> <p>The Notch displays the confidence interval around the median which is normally based on : <a href="http://i.stack.imgur.com/1GROL.png" rel="nofollow"><img src="http://i.stack.imgur.com/1GROL.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/urPEC.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/urPEC.jpg" alt="enter image description here"></a></p> <p>Maybe, you can alter the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.boxplot" rel="nofollow"><code>bootstrap</code></a> parameter of the <code>boxplot</code> to tighten up the median's confidence interval.</p>
2
2016-08-05T18:08:44Z
[ "python", "matplotlib" ]
Python unreachable variable assignment resulting in UnboundLocalError
38,794,409
<p>I am trying to understand how variables are managed internally by Python. </p> <pre><code>x = 10 def ex1(): if False: x=1 print(x) ex1() </code></pre> <p>When ex1() is executed, it shows an UnboundLocalError since local variable 'x' is not referenced. </p> <p>How does this happen? Does the parsing happen in an initial pass and just create the symbol table and specifies scope followed by the interpretation which happens in another pass and skips <code>x=1</code> as it is unreachable?</p>
2
2016-08-05T17:01:08Z
38,794,614
<p>Python doesn't have variable declarations, so when variables are created/used it has to determine the scope itself. Python scoping is lexical, meaning that it can access a variable in its enclosed scope, it cannot modify them. The way ex1() is written, x=1 is local to ex1(). However, when you go to run ex1() it tries to read x=10 as it is local, and throws your UnboundLocalError. So, the way that the variable is managed, is it sees a local declaration, runs the function, and sees another local declaration, and due to scope, cannot relate the two. </p>
0
2016-08-05T17:14:15Z
[ "python", "variables", "scope", "interpreter" ]
Python unreachable variable assignment resulting in UnboundLocalError
38,794,409
<p>I am trying to understand how variables are managed internally by Python. </p> <pre><code>x = 10 def ex1(): if False: x=1 print(x) ex1() </code></pre> <p>When ex1() is executed, it shows an UnboundLocalError since local variable 'x' is not referenced. </p> <p>How does this happen? Does the parsing happen in an initial pass and just create the symbol table and specifies scope followed by the interpretation which happens in another pass and skips <code>x=1</code> as it is unreachable?</p>
2
2016-08-05T17:01:08Z
38,794,934
<p>Conceptually this make sense. I can't tell how its implemented but I can tell why.</p> <p>When you affect a variable it gets affected in the local scope unless you explicitly tell by using the keyword <code>global</code>. If you only access it and there is no affectation it will implicitly use the global variable since no local variable is defined.</p> <pre><code>x = 10 def access_global(): print x def affect_local(): x = 0 print x def affect_global(): global x x = 1 print x access_global() # 10 affect_local() # 0 print x # 10 affect_global() # 1 print x # 10 </code></pre> <p>If you do this inside a nested function, class or module the rules are similar:</p> <pre><code>def main(): y = 10 def access(): print y def affect(): y = 0 print y access() # 10 affect() # 0 print y # 10 main() </code></pre> <p>This is probably saving hours of painful debugging by never overwriting variable of parent scopes unless its explicitly stated.</p> <p><strong>EDIT</strong></p> <p>disassembling the python byte code gives us some additional information to understand:</p> <pre><code>import dis x = 10 def local(): if False: x = 1 def global_(): global x x = 1 print local dis.dis(local) print global_ dis.dis(global_) &lt;function local at 0x7fa01ec6cde8&gt; 37 0 LOAD_GLOBAL 0 (False) 3 POP_JUMP_IF_FALSE 15 38 6 LOAD_CONST 1 (1) 9 STORE_FAST 0 (x) 12 JUMP_FORWARD 0 (to 15) &gt;&gt; 15 LOAD_CONST 0 (None) 18 RETURN_VALUE &lt;function global_ at 0x7fa01ec6ce60&gt; 42 0 LOAD_CONST 1 (1) 3 STORE_GLOBAL 0 (x) 6 LOAD_CONST 0 (None) 9 RETURN_VALUE </code></pre> <p>We can see that the byte code for the <code>local</code> function is calling <code>STORE_FAST</code> and the <code>global_</code> function calls <code>STORE_GLOBAL</code>.</p> <p>This question also explain why its more performant to translate function to byte code to avoid compiling every time the function is called: <a href="http://stackoverflow.com/questions/888100/why-python-compile-the-source-to-bytecode-before-interpreting">Why python compile the source to bytecode before interpreting?</a></p>
0
2016-08-05T17:34:57Z
[ "python", "variables", "scope", "interpreter" ]
Asynchronious email sending in Django
38,794,571
<p>I'm trying to figure out how to send email asynchroniously so <code>User</code> don't have to wait until <code>email</code> is sent. </p> <p>I've installer <code>celery</code> and <code>django-celery-email</code> and added <code>django-celery-email</code> into my <code>settings.py</code> - <code>djcelery_email</code>.</p> <p>I've also changed database backend:</p> <pre><code>EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' </code></pre> <p>Now I've tried to do an action which sends email but it freezes and no email has been sent.</p> <p>Do you know what to do?</p> <p>Here is a traceback from cmd:</p> <pre><code>Internal Server Error: /ajax/reservation/confirm/ Traceback (most recent call last): File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\dolava_app\views.py", line 68, in reservation_confirm reservation.save() File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\dolava_app\models.py", line 150, in save notifications.AdminNotifications.new_pair(self, paired_reservation) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\dolava_app\notifications.py", line 79, in new_pair send_message_to_admin(subject,message) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\dolava_app\notifications.py", line 8, in send_message_to_admin mail.send() File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\django\core\mail\message.py", line 292, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\djcelery_email\backends.py", line 17, in send_messages result_tasks.append(send_emails.delay(chunk, self.init_kwargs)) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\celery\app\task.py", line 453, in delay return self.apply_async(args, kwargs) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\celery\app\task.py", line 565, in apply_async **dict(self._get_exec_options(), **options) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\celery\app\base.py", line 354, in send_task reply_to=reply_to or self.oid, **options File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\celery\app\amqp.py", line 310, in publish_task **kwargs File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\messaging.py", line 172, in publish routing_key, mandatory, immediate, exchange, declare) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 457, in _ensured interval_max) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 369, in ensure_connection interval_start, interval_step, interval_max, callback) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\utils\__init__.py", line 246, in retry_over_time return fun(*args, **kwargs) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 237, in connect return self.connection File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 742, in connection self._connection = self._establish_connection() File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\connection.py", line 697, in _establish_connection conn = self.transport.establish_connection() File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\kombu\transport\pyamqp.py", line 116, in establish_connection conn = self.Connection(**opts) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\amqp\connection.py", line 165, in __init__ self.transport = self.Transport(host, connect_timeout, ssl) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\amqp\connection.py", line 186, in Transport return create_transport(host, connect_timeout, ssl) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\amqp\transport.py", line 299, in create_transport return TCPTransport(host, connect_timeout) File "C:\Users\Milano\PycharmProjects\FutileStudio\dolava\venv\lib\site-packages\amqp\transport.py", line 95, in __init__ raise socket.error(last_err) error: [Errno 10061] No connection could be made because the target machine actively refused it </code></pre>
0
2016-08-05T17:11:47Z
38,809,391
<h2>Problem</h2> <p>From <a href="https://github.com/pmclanahan/django-celery-email" rel="nofollow">https://github.com/pmclanahan/django-celery-email</a></p> <blockquote> <p>By default django-celery-email will use Django's builtin SMTP email backend for the actual sending of the mail.</p> </blockquote> <p>This means you need to run an SMTP server locally to accept the email. That is why you are getting a socket error - cause you don't have any SMTP server set to receive the email.</p> <p><br></p> <h2>Possible Solutions - Local Development</h2> <h3>A. Start an SMTP server and use your own client</h3> <p><strong>Option 1</strong></p> <p>Run a combined SMTP server and client. <a href="https://mailcatcher.me/" rel="nofollow">Mailcatcher</a> is great for this.</p> <p>It even comes with <a href="https://mailcatcher.me/" rel="nofollow">django setup instructions</a>!</p> <p>Set it up then fire it up with:</p> <p><code>$ mailcatcher -fv</code></p> <p>Note: mailcatcher requires gem (ruby package manager) to install. So you will have to install that first. Its probably worth the effort, as mailcatcher works quite nicely and gives you html and text representations of the email in a browser tab.</p> <p>For docker users you can get a <a href="https://hub.docker.com/r/schickling/mailcatcher/" rel="nofollow">mailcatcher docker image</a></p> <p><br> <strong>Option 2</strong></p> <p>Run your own SMTP server and a separate mail client.</p> <p>e.g. Use a simple python SMTP server From the command line <code>python -m smtpd -n -c DebuggingServer localhost:1025</code></p> <p>in your django settings:</p> <p><code> EMAIL_HOST = 'localhost' EMAIL_HOST_USER = None EMAIL_HOST_PASSWORD = None EMAIL_PORT = 1025 EMAIL_USE_TLS = False </code></p> <p>Then you will need to setup a client to get those emails.</p> <p><br></p> <h3>B. Don't use SMTP as a backend in your settings</h3> <p>Instead print to the console:</p> <p><code>EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'</code></p> <p>Problem with this is ugly formatting. HTML will appear as text which makes the email very hard to read. You can output this to a file by manually copying and pasting it into a .html file and opening it in a browser, but that will get boring very fast.</p> <p><br></p> <h2>Solution - Continuous Integration Server</h2> <p>Use this for making email accessible to the django test client, so you can check that emails got sent, check the content of email programatically etc. <code>EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'</code> <br> <br></p> <h2>Solution - Production Server</h2> <p>You will need to use a SMTP server again. Either you can run your own or use Sendgrid, Mailgun, Mandrill or something similar.</p>
0
2016-08-06T22:43:22Z
[ "python", "django", "django-celery", "django-email" ]
How to get constant function to keep shape in NumPy
38,794,622
<p>I have a <code>NumPy</code> array <code>A</code> with shape <code>(m,n)</code> and want to run all the elements through some function <code>f</code>. For a non-constant function such as for example <code>f(x) = x</code> or <code>f(x) = x**2</code> broadcasting works perfectly fine and returns the expected result. For <code>f(x) = 1</code>, applying the function to my array <code>A</code> however just returns the <em>scalar</em> 1. </p> <p>Is there a way to force broadcasting to keep the shape, i.e. in this case to return an array of 1s?</p>
0
2016-08-05T17:14:26Z
38,794,679
<p><code>F(x) = 1</code> is not a function you need to create a function with <code>def</code> or <code>lambda</code> and return 1. Then use <code>np.vectorize</code> to apply the function on your array.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; f = lambda x: 1 &gt;&gt;&gt; &gt;&gt;&gt; f = np.vectorize(f) &gt;&gt;&gt; &gt;&gt;&gt; f(np.arange(10).reshape(2, 5)) array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]) </code></pre>
1
2016-08-05T17:18:12Z
[ "python", "numpy", "numpy-broadcasting" ]
How to get constant function to keep shape in NumPy
38,794,622
<p>I have a <code>NumPy</code> array <code>A</code> with shape <code>(m,n)</code> and want to run all the elements through some function <code>f</code>. For a non-constant function such as for example <code>f(x) = x</code> or <code>f(x) = x**2</code> broadcasting works perfectly fine and returns the expected result. For <code>f(x) = 1</code>, applying the function to my array <code>A</code> however just returns the <em>scalar</em> 1. </p> <p>Is there a way to force broadcasting to keep the shape, i.e. in this case to return an array of 1s?</p>
0
2016-08-05T17:14:26Z
38,794,707
<p>Use <code>x.fill(1)</code>. Make sure to return it properly as <code>fill</code> doesn't return a new variable, it modifies <code>x</code></p>
0
2016-08-05T17:19:31Z
[ "python", "numpy", "numpy-broadcasting" ]
How to get constant function to keep shape in NumPy
38,794,622
<p>I have a <code>NumPy</code> array <code>A</code> with shape <code>(m,n)</code> and want to run all the elements through some function <code>f</code>. For a non-constant function such as for example <code>f(x) = x</code> or <code>f(x) = x**2</code> broadcasting works perfectly fine and returns the expected result. For <code>f(x) = 1</code>, applying the function to my array <code>A</code> however just returns the <em>scalar</em> 1. </p> <p>Is there a way to force broadcasting to keep the shape, i.e. in this case to return an array of 1s?</p>
0
2016-08-05T17:14:26Z
38,794,735
<p>This sounds like a job for <code>np.ones_like</code>, or <code>np.full_like</code> in the general case:</p> <pre><code>def f(x): result = np.full_like(x, 1) # or np.full_like(x, 1, dtype=int) if you don't want to # inherit the dtype of x if result.shape == 0: # Return a scalar instead of a 0D array. return result[()] else: return result </code></pre>
0
2016-08-05T17:21:07Z
[ "python", "numpy", "numpy-broadcasting" ]
Python split multiples comma
38,794,692
<p>I have a CSV string like this : </p> <pre><code>foo = "value0,value1,value2,value3,value4".split(",") test(foo) </code></pre> <p>I'm using split to split this string in an array. Then I've a function that takes the array and assign these value to some internal variables :</p> <pre><code>def test(foo): var0 = foo[0] var1 = foo[1] var2 = foo[2] var3 = foo[3] var4 = foo[4] return </code></pre> <p>The problem is that I can have some missing value like this :</p> <pre><code>foo = "value0,value1,,,value4".split(",") </code></pre> <p>Split in these situation creates a smaller array :</p> <pre><code>print(foo) # ['value0','value1','value4'] </code></pre> <p>So when I call my function it doesn't work and the value4 is wrongly associated to the var2 ( it should be associated to the var4 ).</p> <p>Is there a way to force split to create empty element ? Thanks for any tips.</p>
-2
2016-08-05T17:18:53Z
38,794,760
<p>You need to remove/filter the empty strings after splitting the string, and since you are not aware of the length of your items you can use a dictionary in order to preserve your strings.</p> <pre><code>my_vars = {'var{}'.format(i):j for i, j in enumerate(mystr.split(',')) if j} </code></pre> <p>Here is a Demo:</p> <pre><code>&gt;&gt;&gt; foo = "value0,value1,,,value4" &gt;&gt;&gt; my_vars = {'var{}'.format(i):j for i, j in enumerate(foo.split(',')) if j} &gt;&gt;&gt; my_vars {'var4': 'value4', 'var1': 'value1', 'var0': 'value0'} </code></pre> <p>After that you can simply access your items with a simple indexing:</p> <pre><code>&gt;&gt;&gt; my_vars['var1'] 'value1' </code></pre>
0
2016-08-05T17:22:58Z
[ "python", "arrays", "split" ]
Python split multiples comma
38,794,692
<p>I have a CSV string like this : </p> <pre><code>foo = "value0,value1,value2,value3,value4".split(",") test(foo) </code></pre> <p>I'm using split to split this string in an array. Then I've a function that takes the array and assign these value to some internal variables :</p> <pre><code>def test(foo): var0 = foo[0] var1 = foo[1] var2 = foo[2] var3 = foo[3] var4 = foo[4] return </code></pre> <p>The problem is that I can have some missing value like this :</p> <pre><code>foo = "value0,value1,,,value4".split(",") </code></pre> <p>Split in these situation creates a smaller array :</p> <pre><code>print(foo) # ['value0','value1','value4'] </code></pre> <p>So when I call my function it doesn't work and the value4 is wrongly associated to the var2 ( it should be associated to the var4 ).</p> <p>Is there a way to force split to create empty element ? Thanks for any tips.</p>
-2
2016-08-05T17:18:53Z
38,794,802
<p>Simply use <code>splitlines</code> with <code>split</code>, it working fine on my system or you can Try this</p> <pre><code>for lines in foo.splitlines(): print (lines.split(',')) </code></pre> <p>will produce this result</p> <pre><code>['value0', 'value1', '', '', 'value4'] </code></pre> <p>where foo was <code>foo = "value0,value1,,,value4"</code></p>
-1
2016-08-05T17:25:37Z
[ "python", "arrays", "split" ]
How to Multithreading Python with my laptop
38,794,706
<p>I have project in python, structure of my project like this :</p> <pre><code>def makeRecommendation: .....do something here.... insertRecomenderToDB(result) def insertRecomenderToDB(result): .....do something here.... if __name__ == '__main__': makeRecommendation() </code></pre> <p><strong>My laptop " Core i7 with number of cores : 4, processors(logical processors) : 8</strong></p> <p>Everytime i run my project, its run only one processor. I want make all 8 processors running, i read about Multithreading but not really understand how to make all 8 processors run in my laptop.</p> <p>How i can make 8 processors with my project ?</p> <p>Thanks very much for help me !</p>
-2
2016-08-05T17:19:30Z
38,801,021
<p>Python's multithreading cannot make use of multicore. The only way is to use multi-processing. There are several modules that you could use:</p> <p><a href="https://docs.python.org/3.5/library/multiprocessing.html" rel="nofollow">multiprocessing</a>: This module gives you complete control over new process.<br> <a href="https://docs.python.org/3/library/concurrent.futures.html" rel="nofollow">concurrent.futures</a>: This is more convenient, it allows you to create a process pool quickly.</p> <p>Hope it helps.</p>
0
2016-08-06T05:54:00Z
[ "python", "multithreading", "multiprocessing" ]
How to visualize a layered graph (for GraphPlan planning algorithm)
38,794,714
<p>I did a quick web search and having not found readily available (and library-provided) solutions for what I think is a well specified and fairly standard visualization problem, decided to quickly implement it myself. But before doing this, though, I wanted to get a sanity advice from the community.</p> <p>I need to visualize a very specific kind of graph (this is why I don't wanna deal with any of those force-directed generic layouts that are hard to read), which seems like a version of a multipartite graph for the GraphPlan planning algorithm. </p> <p>For those unfamiliar, a typical layout is essentially the same as that of a multi-layer neural net: <a href="http://i.stack.imgur.com/R2Aev.png" rel="nofollow"><img src="http://i.stack.imgur.com/R2Aev.png" alt="enter image description here"></a></p> <p>For simplicity, I am only considering even-numbered layers (since odd ones will essentially become edge labels)</p> <p>At this point it is sufficient to represent colums of nodes simply as a table with <em>tabulate</em>. The only catch is that I need the backpointers (that is edges) also.</p> <p>I am thinking in the direction of matplotlib's grid but would prefer not to go too low-level. I just need to connect arbitrary items, from <em>strictly</em> adjacent columns in this grid, after all. Pretty simple, indeed.</p>
0
2016-08-05T17:20:04Z
38,798,362
<p>Turned out not too terrible: <a href="http://i.stack.imgur.com/P2OW5.png" rel="nofollow"><img src="http://i.stack.imgur.com/P2OW5.png" alt="enter image description here"></a></p> <p>Basically:</p> <ol> <li>Stored my objects in a 2d array</li> <li>Generated Xs and Ys for a scatter plot grid (some additional care was needed to handle variable column height via the <code>zip(*izip_longest(*my2darray))</code> trick)</li> <li>Iterated over my 2d array elements to pull out their labels</li> <li>For each of them also drew line segments to each of their children from the previous column.</li> </ol>
0
2016-08-05T22:05:40Z
[ "python", "matplotlib", "graph", "visualization" ]
Bit field specialization in python
38,794,715
<p>Here is a code in C++:</p> <pre><code>void sign_extending(int x) { int r; // resulting sign extended number goes here struct {signed int x:5 ;} s; r = s.x = x; cout &lt;&lt; r; } void Run() { int x=29; // this 29 is -3 ( 11101 ) in 5 bits // convert this from using 5 bits to a full int sign_extending(x); } </code></pre> <p>The output of this code is -3. When i try to reproduce this code in python the bit field of 11101 is generated but when the answer is converted to an int the answer of 29 is given .</p> <p>the following is code of python:</p> <pre><code>from bitarray import * def sign_extending(x) : s = bitarray(5) r = s = bin(x) #resulting sign extended number goes in r print (int(r, 2)) x = 29 #this 29 is -3 ( 11101 ) in 5 bits. Convert this from using 5 bits to a full int sign_extending(x) </code></pre> <p>I also used ctypes structures as an alternative code but no use :</p> <pre><code>from ctypes import * def sign_extending(x, b): class s(Structure): _fields_ = [("x", c_int, 5)] r = s.x = x return r #resulting sign extended number goes in r x = 29; #this 29 is -3 ( 11101 ) in 5 bits. r = sign_extending(x, 5) #Convert this from using 5 bits to a full int print r </code></pre> <p>My question is that how would i produce this result using bit arrays or any other method that gives the correct answer.</p>
1
2016-08-05T17:20:04Z
38,795,330
<p>I think that this might possibly do what you want (as long as x is non-negative and can be written using b bits).</p> <pre><code>def sign_extend(x, b): if x &gt;= 2 ** (b - 1): return x - 2 ** b else: return x </code></pre>
1
2016-08-05T18:00:14Z
[ "python", "ctypes", "bit-fields", "sign-extension" ]
Bit field specialization in python
38,794,715
<p>Here is a code in C++:</p> <pre><code>void sign_extending(int x) { int r; // resulting sign extended number goes here struct {signed int x:5 ;} s; r = s.x = x; cout &lt;&lt; r; } void Run() { int x=29; // this 29 is -3 ( 11101 ) in 5 bits // convert this from using 5 bits to a full int sign_extending(x); } </code></pre> <p>The output of this code is -3. When i try to reproduce this code in python the bit field of 11101 is generated but when the answer is converted to an int the answer of 29 is given .</p> <p>the following is code of python:</p> <pre><code>from bitarray import * def sign_extending(x) : s = bitarray(5) r = s = bin(x) #resulting sign extended number goes in r print (int(r, 2)) x = 29 #this 29 is -3 ( 11101 ) in 5 bits. Convert this from using 5 bits to a full int sign_extending(x) </code></pre> <p>I also used ctypes structures as an alternative code but no use :</p> <pre><code>from ctypes import * def sign_extending(x, b): class s(Structure): _fields_ = [("x", c_int, 5)] r = s.x = x return r #resulting sign extended number goes in r x = 29; #this 29 is -3 ( 11101 ) in 5 bits. r = sign_extending(x, 5) #Convert this from using 5 bits to a full int print r </code></pre> <p>My question is that how would i produce this result using bit arrays or any other method that gives the correct answer.</p>
1
2016-08-05T17:20:04Z
38,799,936
<p>In your code <code>s</code> is a class and the class <code>x</code> member actually represents the field type, so assigning <code>s.x = 29</code> essentially destroys that object and assigns a normal Python int to it. Example:</p> <pre><code>&gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; class S(Structure): ... _fields_ = [('x',c_int,5)] ... &gt;&gt;&gt; S.x &lt;Field type=c_long, ofs=0:0, bits=5&gt; &gt;&gt;&gt; S.x = 29 &gt;&gt;&gt; S.x 29 </code></pre> <p>Also, even if you create an instance first, <code>r = s.x = 29</code> does not do <code>s.x = 29</code> then <code>r = s.x</code> as in C/C++ but essentially <code>r=29</code> and <code>s.x=29</code>. Example:</p> <pre><code>&gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; class S(Structure): ... _fields_ = [('x',c_int,5)] ... &gt;&gt;&gt; s=S() &gt;&gt;&gt; r=s.x=29 &gt;&gt;&gt; s.x -3 &gt;&gt;&gt; r 29 </code></pre> <p>So to fix, instantiate the class, assign <code>s.x = 29</code> and return it:</p> <pre><code>from ctypes import * def sign_extending(x, b): class S(Structure): _fields_ = [("x", c_int, b)] s=S() s.x = x return s.x x = 29; #this 29 is -3 ( 11101 ) in 5 bits. r = sign_extending(x, 5) #Convert this from using 5 bits to a full int print r </code></pre> <p>Output:</p> <pre><code>-3 </code></pre>
2
2016-08-06T02:05:49Z
[ "python", "ctypes", "bit-fields", "sign-extension" ]
Python get last month and year
38,794,935
<p>I am trying to get last month and current year in the format: July 2016.</p> <p>I have tried (but that didn't work) and it does not print July but the number:</p> <pre><code>import datetime now = datetime.datetime.now() print now.year, now.month(-1) </code></pre>
1
2016-08-05T17:34:58Z
38,794,963
<pre><code>now = datetime.datetime.now() last_month = now.month-1 if now.month &gt; 1 else 12 last_year = now.year - 1 </code></pre> <p>to get the month name you can use</p> <pre><code>"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[last_month-1] </code></pre>
1
2016-08-05T17:37:20Z
[ "python", "date", "datetime" ]
Python get last month and year
38,794,935
<p>I am trying to get last month and current year in the format: July 2016.</p> <p>I have tried (but that didn't work) and it does not print July but the number:</p> <pre><code>import datetime now = datetime.datetime.now() print now.year, now.month(-1) </code></pre>
1
2016-08-05T17:34:58Z
38,795,214
<pre><code>def subOneMonth(dt): day = dt.day res = dt.replace(day=1) - datetime.timedelta(days =1) try: res.replace(day= day) except ValueError: pass return res print subOneMonth(datetime.datetime(2016,07,11)).strftime('%d, %b %Y') 11, Jun 2016 print subOneMonth(datetime.datetime(2016,01,11)).strftime('%d, %b %Y') 11, Dec 2015 print subOneMonth(datetime.datetime(2016,3,31)).strftime('%d, %b %Y') 29, Feb 2016 </code></pre>
2
2016-08-05T17:53:22Z
[ "python", "date", "datetime" ]
Python get last month and year
38,794,935
<p>I am trying to get last month and current year in the format: July 2016.</p> <p>I have tried (but that didn't work) and it does not print July but the number:</p> <pre><code>import datetime now = datetime.datetime.now() print now.year, now.month(-1) </code></pre>
1
2016-08-05T17:34:58Z
38,795,233
<p>An alternative solution using Pandas which converts today to a monthly period and then subtracts one (month). Converted to desired format using <code>strftime</code>.</p> <pre><code>import datetime as dt import pandas as pd &gt;&gt;&gt; (pd.Period(dt.datetime.now(), 'M') - 1).strftime('%B %Y') u'July 2016' </code></pre>
1
2016-08-05T17:54:36Z
[ "python", "date", "datetime" ]
Python get last month and year
38,794,935
<p>I am trying to get last month and current year in the format: July 2016.</p> <p>I have tried (but that didn't work) and it does not print July but the number:</p> <pre><code>import datetime now = datetime.datetime.now() print now.year, now.month(-1) </code></pre>
1
2016-08-05T17:34:58Z
38,795,526
<p>If you're manipulating dates then the <a href="https://pypi.python.org/pypi/python-dateutil">dateutil</a> library is always a great one to have handy for things the Python stdlib doesn't cover easily.</p> <pre><code>from datetime import datetime from dateutil.relativedelta import relativedelta # Returns the same day of last month if possible otherwise end of month # (eg: March 31st-&gt;29th Feb an July 31st-&gt;June 30th) last_month = datetime.now() - relativedelta(months=1) # Create string of month name and year... text = format(last_month, '%B %Y') </code></pre> <p>Gives you:</p> <pre><code>'July 2016' </code></pre>
5
2016-08-05T18:13:45Z
[ "python", "date", "datetime" ]
Pointing bash to a python installed on windows
38,794,937
<p>I am using Windows 10 and have Python installed. The new update brought bash to windows, but when I call python from inside bash, it refers to the Python installation which came with the bash, not to my Python installed on Windows. So, for example, I can't use the modules which I have already installed on Windows and would have to install them separately on the bash installation.</p> <p>How can I (and can I?) make bash point to my original Windows Python installation? I see that in /usr/bin I have a lot of links with "python" inside their name, but I am unsure which ones to change, and if changing them to Windows directories would even work because of different executable formats.</p>
3
2016-08-05T17:35:17Z
38,797,880
<p>I do not have Windows 10 installed, but I use Babun and I had the same problem. As I read aliases work well in Windows 10 shell so simply add alias in your .bashrc pointing to your Python installation directory:</p> <pre><code>alias python /mnt/c/Python27/python </code></pre>
0
2016-08-05T21:17:53Z
[ "python", "windows", "bash", "wsl" ]
Pointing bash to a python installed on windows
38,794,937
<p>I am using Windows 10 and have Python installed. The new update brought bash to windows, but when I call python from inside bash, it refers to the Python installation which came with the bash, not to my Python installed on Windows. So, for example, I can't use the modules which I have already installed on Windows and would have to install them separately on the bash installation.</p> <p>How can I (and can I?) make bash point to my original Windows Python installation? I see that in /usr/bin I have a lot of links with "python" inside their name, but I am unsure which ones to change, and if changing them to Windows directories would even work because of different executable formats.</p>
3
2016-08-05T17:35:17Z
38,797,912
<p>You have at least four options:</p> <ol> <li>Specify the complete absolute path to the python executable you want to use.</li> <li>Define an alias in your .bashrc file</li> <li>Modify the PATH variable in your .bashrc file to include the location of the python version you wish to use.</li> <li>Create a symlink in a directory which is already in your PATH.</li> </ol>
0
2016-08-05T21:20:48Z
[ "python", "windows", "bash", "wsl" ]
Pointing bash to a python installed on windows
38,794,937
<p>I am using Windows 10 and have Python installed. The new update brought bash to windows, but when I call python from inside bash, it refers to the Python installation which came with the bash, not to my Python installed on Windows. So, for example, I can't use the modules which I have already installed on Windows and would have to install them separately on the bash installation.</p> <p>How can I (and can I?) make bash point to my original Windows Python installation? I see that in /usr/bin I have a lot of links with "python" inside their name, but I am unsure which ones to change, and if changing them to Windows directories would even work because of different executable formats.</p>
3
2016-08-05T17:35:17Z
39,480,122
<p>You currently cannot run Windows apps from within Bash but this is a feature we're working on for a future release. If you're keen to be among the first to receive and run this feature when it's complete, be sure to sign up for the Windows 10 Insider Fast-Ring.</p>
0
2016-09-13T22:50:30Z
[ "python", "windows", "bash", "wsl" ]
Django error on admin search: Cannot resolve keyword 'username' into field
38,794,986
<p>I am having a problem in my admin in Django. I have a list of users, I can add, edit and delete them without any problem. However, when I use the search bar to find specific users, i get the error: </p> <pre><code>Cannot resolve keyword 'username' into field. Choices are: bookreader, date_joined, email, full_name, groups, id, is_active, is_staff, is_superuser, is_verified, last_login, logentry, password, profile, reading, user_permissions, usuário, virtualcurrency </code></pre> <p>I dont know why this is happening. Here is my User Model:</p> <pre><code>class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email'), unique=True, blank=False) full_name = models.CharField(_('name'), max_length=30, blank=False) is_verified = models.BooleanField(_('verified'), default=False) is_staff = models.BooleanField(_('staff status'), default=False) is_active = models.BooleanField(_('active'), default=True) date_joined = models.DateTimeField(_('date joined'), default=now) objects = UserManager() USERNAME_FIELD = 'email' class Meta: verbose_name = _('user') def __str__(self): return self.email def get_short_name(self): return self.full_name.partition(' ')[0] def get_full_name(self): return self.full_name def send_verification_mail(self, request): if not self.pk: self.save() return send_template_mail( 'Verificação de email', 'users/user_verification_email.html', { 'user': self, 'verification_url': request.build_absolute_uri( reverse('users:user_verify', kwargs={ 'uidb64': urlsafe_base64_encode(force_bytes(self.pk)), 'token': default_token_generator.make_token(self) }) ) }, [self.email] ) </code></pre> <p>And the UserAdmin in admin.py:</p> <pre><code>class UserAdmin(UserAdmin_): list_display = ('email', 'full_name', 'is_staff') ordering = ('email',) fieldsets = ( (None, {'fields': ('email', 'password')}), (_('Personal info'), {'fields': ('full_name',)}), (_('Permissions'), {'fields': ( 'is_active', 'is_verified', 'is_staff', 'is_superuser', 'groups', 'user_permissions' )}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password'), }), ) form = UserChangeForm add_form = UserSignupForm admin.site.register(User, UserAdmin) </code></pre> <p>Why I am getting this error?</p>
0
2016-08-05T17:38:51Z
38,795,220
<p>The <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields" rel="nofollow"><code>search_fields</code></a> option for the <code>UserAdmin</code> class contains <code>username</code>, <code>first_name</code> and <code>last_name</code> (<a href="https://github.com/django/django/blob/1.10/django/contrib/auth/admin.py#L65" rel="nofollow">source code</a>). This is not compatible with your <code>User</code> model, because your model does not have these fields.</p> <p>You should change <code>search_fields</code> for your <code>UserAdmin</code> class, so that it is compatible with your user model. For example:</p> <pre><code>class UserAdmin(UserAdmin_): search_fields = ('email', 'full_name') </code></pre>
1
2016-08-05T17:53:41Z
[ "python", "django", "python-3.x", "django-admin" ]
Python - Tweepy Regex
38,795,153
<p>I'm using Tweepy streamer to collect some tweets for certain tags, in this case #python. The streamer part of the script works fine but where I'm struggling is extracting the information from the output. </p> <p>Tweepy sample: {"created_at":"Fri Aug 05 17:27:00 +0000 2016","id":761614496666361857,"id_str":"761614496666361857","text":<strong>"Use different Python version with virtualenv #py thon #virtualenv #virtualenvwrapper https://t.co/ecedKrCX0L"</strong>,"source":</p> <p>From the sample, I want to extract and print the bold text however I can't seem to get this to work properly. So far I've come up with:</p> <pre><code>class MyListener(StreamListener): def on_data(self, data): try: pattern = re.compile(r'"text":"(.*?)","') for line in data: x = pattern.search(data) f = open('tmp', 'a') f.write(data) f.close return True else: pass except BaseException as e: print("Error on_data: %s" % str(e)) return True </code></pre> <p>However this doesn't extract the specifics I'm after and continues to print a full tweepy output. </p> <p>Any assistance would be appreciated! </p> <p>Thanks</p>
0
2016-08-05T17:49:21Z
38,797,181
<p>The easisest way if you want to extract the text is with json module.</p> <pre><code>import json class MyListener(StreamListener): def on_data(self, data): try: json.loads(data) f = open('tmp', 'a') f.write(data["text"]) f.close() except BaseException as e: print("Error on_data: %s" % str(e)) return True </code></pre> <p>But if you want to use a regular expression this will be the code:</p> <pre><code>class MyListener(StreamListener): def on_data(self, data): try: pattern = re.compile(r'"text":"([^",]*)","') for line in data: x = pattern.search(data) f = open('tmp', 'a') f.write(data) f.close return True else: pass except BaseException as e: print("Error on_data: %s" % str(e)) return True </code></pre>
1
2016-08-05T20:16:07Z
[ "python", "regex", "tweepy" ]
Numpy ValueError: setting an array element with a sequence reading in list
38,795,183
<p>I have this code that reads numbers and is meant to calculate std and %rms using numpy </p> <pre><code>import numpy as np import glob import os values = [] line_number = 6 road = '/Users/allisondavis/Documents/HCl' for pbpfile in glob.glob(os.path.join(road, 'pbpfile*')): lines = open(pbpfile, 'r').readlines() while line_number &lt; len(lines) : variables = lines[line_number].split() values.append(variables) line_number = line_number + 3 a = np.asarray(values).astype(np.float) std = np.std(a) rms = std * 100 print rms </code></pre> <p>However I keep getting the error code:</p> <pre><code>Traceback (most recent call last): File "rmscalc.py", line 17, in &lt;module&gt; a = np.asarray(values).astype(np.float) ValueError: setting an array element with a sequence. </code></pre> <p>Any idea how to fix this? I am new to python/numpy. If I print my values it looks something like this:</p> <pre><code>[[1,2,3,4],[2,4,5,6],[1,3,5,6]] </code></pre>
0
2016-08-05T17:51:19Z
38,799,276
<p>I can think of a modification to your code which can potentially fix your problem:</p> <p>Initialize values as a numpy array, and use numpy append or concatenate:</p> <pre><code>values = np.array([], dtype=float) </code></pre> <p>Then inside loop:</p> <pre><code>values = np.append(values, [variables], axis=0) # or variables = np.array(lines[line_number].split(), dtype=float) values = np.concatenate((values, variables), axis=0) </code></pre> <hr> <hr> <p>Alternatively, if you files are .csv (or any other type <a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/io.html" rel="nofollow">Pandas can read</a>):</p> <pre><code>import pandas as pd # Replace `read_csv` with your appropriate file reader a = pd.concat([pd.read_csv(pbpfile) for pbpfile in glob.glob(os.path.join(road, 'pbpfile*'))]).values # or a = np.concatenate([pd.read_csv(pbpfile).values for pbpfile in glob.glob(os.path.join(road, 'pbpfile*'))], axis=0) </code></pre>
0
2016-08-06T00:02:58Z
[ "python", "arrays", "numpy" ]
Use specific instance of DLL with ctypes
38,795,189
<p>Is it possible to use a specific instance of a DLL using ctypes? Basically my application is as follows: We have a C DLL accessed by a C# DLL and then a C# WPF front end. I wrote a separate wrapper using ctypes to access the C DLL directly and bypass the C# all together. </p> <p>We currently use an internal IronPython window in our program to allow users to script things in Python, and that connects to the middle C# layer and through that to the C dll. Because of the limitations of IronPython, I would like to see if it's possible to allow users to write Python code that can, using my library, directly access the C dll, but the same instance of it as the C# is using so they can be synced. Is this even remotely possible?</p>
2
2016-08-05T17:51:38Z
38,795,386
<p>You have a program which loads a C# DLL which loads a C DLL. The same program also runs IronPython and you want Python to load the same C DLL.</p> <p>I assume you are using <code>ctypes.windll.LoadLibrary(path)</code> in Python. So you just need to find the right path. For C# some ideas are here: <a href="http://stackoverflow.com/questions/4764680/how-to-get-the-location-of-the-dll-currently-executing">How to get the location of the DLL currently executing?</a></p> <p>Specifically, you can try this: <a href="https://msdn.microsoft.com/en-us/library/system.reflection.assembly.codebase(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/system.reflection.assembly.codebase(v=vs.110).aspx</a></p> <p>You may be able to do it from IronPython directly, but if not, you can do it in your C# DLL and expose it.</p>
0
2016-08-05T18:04:08Z
[ "python", "ctypes" ]
Django filter returning duplicates after order_by based on multiple criteria
38,795,292
<p>I'm having difficulty returning unique <code>Clazz</code> objects based off my criteria and ordering. <code>Clazz</code> and <code>Session</code> are two separate models and a class can have many sessions.</p> <p>Once I introduced the <code>order_by</code> I'm seeing duplicate <code>Clazz</code> objects. How can I remove the duplicates? A simple <code>distinct()</code> doesn't seem to work.</p> <pre><code>classes = Clazz.objects.filter(location=loc).distinct().order_by('session__start_date', 'session__end_date') </code></pre>
0
2016-08-05T17:57:47Z
38,796,492
<p>After @Alasdair's response, ended up just doing this:</p> <pre><code>dup_list = [] class_list = [] for c in classes: if c not in dup_list: dup_list.append(c) class_list.append(c) classes = class_list </code></pre>
0
2016-08-05T19:25:01Z
[ "python", "django" ]
Django filter returning duplicates after order_by based on multiple criteria
38,795,292
<p>I'm having difficulty returning unique <code>Clazz</code> objects based off my criteria and ordering. <code>Clazz</code> and <code>Session</code> are two separate models and a class can have many sessions.</p> <p>Once I introduced the <code>order_by</code> I'm seeing duplicate <code>Clazz</code> objects. How can I remove the duplicates? A simple <code>distinct()</code> doesn't seem to work.</p> <pre><code>classes = Clazz.objects.filter(location=loc).distinct().order_by('session__start_date', 'session__end_date') </code></pre>
0
2016-08-05T17:57:47Z
38,797,032
<p>I guess you can do something like this:</p> <pre><code>classes = Clazz.objects.filter(location=loc).annotate( startdate=Max('session__start_date'), end_date=Max('session__end_date') ).order_by('startdate', 'end_date') </code></pre>
0
2016-08-05T20:04:33Z
[ "python", "django" ]
How to pull a datetime object out of multiple file names?
38,795,315
<p>I have a mutiple files that I want to create a datetime object from, an example is as such: </p> <pre><code>corr_20060122_082009_vt_unfolded </code></pre> <p>and I wanted to created a datetime object. 2006 is year, 01 month, 22 day, 08 hour, 20 mins, 09 seconds, time is in the 24 hour format (military time) in the file name. For all the filenames how can I pull a datetime object? Is there some way of extracting the datetime from multiple files? Thank you.</p>
1
2016-08-05T17:59:30Z
38,795,396
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; s = re.findall(r'\d+_\d+', 'corr_20060122_082009_vt_unfolded')[0] &gt;&gt;&gt; datetime.strptime(s, '%Y%m%d_%H%M%S') datetime.datetime(2006, 1, 22, 8, 20, 9) </code></pre>
1
2016-08-05T18:05:14Z
[ "python", "datetime", "filenames", "jupyter-notebook" ]
Django REST Framework - Fake objects for unit tests
38,795,394
<p>I'm writing unit tests for my Django app. Currently I'm using <a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow">factory_boy</a> to make fake objects for testing. This works fine for most of my tests, but I'm having the following problem: <strong>My factory_boy objects aren't showing up in <code>{model}.objects</code></strong>. For example, I'm trying to test the following method in my serializer:</p> <pre><code>def get_can_edit(self, obj): request = self.context.get('request') user = request.user admin = SimpleLazyObject(obj.admin) user = User.objects.get(username=request.user) return user == obj.admin </code></pre> <p>Going through it with a debugger, I've determined that request.user correctly has my fake user, but User.objects does not have my fake user.</p> <p>I'm wondering if there's a simple alternative to factory_boy that will actually add my fake objects to <code>{model}.objects</code> or if I'm just using factory_boy incorrectly? Or maybe there's a whole different approach... who knows.</p> <p>Here's the code:</p> <p><a href="https://github.com/TomHeatwole/osf-meetings/blob/feature/conference-tests/meetings/conferences/serializers.py" rel="nofollow">The serializer</a></p> <p><a href="https://github.com/TomHeatwole/osf-meetings/blob/feature/conference-tests/meetings/conferences/tests.py" rel="nofollow">The test</a></p>
3
2016-08-05T18:04:48Z
38,795,493
<p>You need to <strong>inherit from <a href="http://factoryboy.readthedocs.io/en/latest/orms.html#the-djangomodelfactory-subclass" rel="nofollow"><code>DjangoModelFactory</code></a> instead of <code>Factory</code></strong> base class in your <code>UserFactory</code> for objects to be saved onto the database.</p> <p>From <a href="http://factoryboy.readthedocs.io/en/latest/orms.html#the-djangomodelfactory-subclass" rel="nofollow"><code>factory_boy</code> docs:</a></p> <blockquote> <p>All factories for a Django <code>Model</code> <strong>should use the <code>DjangoModelFactory</code></strong> base class.</p> </blockquote> <pre><code>class UserFactory(factory.DjangoModelFactory): # use DjangoModelFactory base class class Meta: model = models.User </code></pre>
2
2016-08-05T18:11:35Z
[ "python", "django", "unit-testing", "django-rest-framework" ]
How to refence current object (F object) within RawSQL
38,795,403
<p>My <code>Order</code> model looks like this:</p> <pre><code>class Order(models.Model): ... billing_email = models.EmailField() ... </code></pre> <p>Desired output I am looking for is a <code>ValuesQuerySet</code> that would contain some fields values and a calculated value of the amount of orders with the same <code>billing_email</code>.</p> <p>I was trying to reference <code>billing_email</code> with <code>F</code> object but doing the following results into error:</p> <pre><code>In [68]: orders = Order.objects.annotate( total_orders=RawSQL( "SELECT COUNT(*) FROM appname_order WHERE billing_email = %s", (F('billing_email'),) # current instance's billing_email ), ) In [69]: orders Out [70]: ProgrammingError: can't adapt type 'F' </code></pre> <p>Pretty much the value I need to evaluate and output as an extra field for each instance is:</p> <pre><code>Order.objects.filter(billing_email__iexact=&lt;current_billing_email&gt;).count() </code></pre> <p>for each instance and I really wouldn't want to loop through actual instances and reconstruct. I must be missing some simple solution here.</p> <p>Thanks in advance for help.</p>
2
2016-08-05T18:05:53Z
38,876,636
<p>You can reference the "current" row using the table name of your Model:</p> <pre><code>RawSQL( "SELECT COUNT(*) FROM appname_order order WHERE order.billing_email =appname_order.billing_email",[]) </code></pre>
0
2016-08-10T14:44:05Z
[ "python", "django", "postgresql" ]
Flask-sqlalchemy disable autoflush for the whole session
38,795,414
<p>I am using Flask-sqlalchemy, how can I just configure it for <code>no autoflush</code>. Currently I am doing something like </p> <pre><code>db = SQLAlchemy() ... db.init_app(app) ... db.session.configure(autoflush=False) </code></pre> <p>But it gives error. How to fix this. </p>
1
2016-08-05T18:06:27Z
38,805,820
<p>The <code>session_options</code> parameter can be used to override session options. If provided it’s a dict of parameters passed to the session’s constructor.</p> <pre><code> db = SQLAlchemy(session_options={"autoflush": False}) </code></pre>
1
2016-08-06T15:23:47Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Passing a command line argument to a py.test fixture as a parameter
38,795,482
<p>Admittedly it is not the best way to do it to start with and more importantly the fixture parameters are resolved i.e. Options.get_option() is called before everything else. Recommendations and suggestions would be appreciated.</p> <p>From config.py</p> <pre><code>class Options(object): option = None @classmethod def get_option(cls): return cls.option </code></pre> <p>From conftest.py</p> <pre><code>@pytest.yield_fixture(scope='session', autouse=True) def session_setup(): Options.option = pytest.config.getoption('--remote') def pytest_addoption(parser): parser.addoption("--remote", action="store_true", default=False, help="Runs tests on a remote service.") @pytest.yield_fixture(scope='function', params=Options.get_option()) def setup(request): if request.param is None: raise Exception("option is none") </code></pre>
1
2016-08-05T18:10:54Z
38,804,497
<p>Don't use custom <code>Options</code> class but directly ask for option from config.</p> <p><code>pytest_generate_tests</code> may be used for parametrizing fixture-like argument for tests.</p> <p>conftest.py</p> <pre><code>def pytest_addoption(parser): parser.addoption("--pg_tag", action="append", default=[], help=("Postgres server versions. " "May be used several times. " "Available values: 9.3, 9.4, 9.5, all")) def pytest_generate_tests(metafunc): if 'pg_tag' in metafunc.fixturenames: tags = set(metafunc.config.option.pg_tag) if not tags: tags = ['9.5'] elif 'all' in tags: tags = ['9.3', '9.4', '9.5'] else: tags = list(tags) metafunc.parametrize("pg_tag", tags, scope='session') @pytest.yield_fixture(scope='session') def pg_server(pg_tag): # pg_tag is parametrized parameter # the fixture is called 1-3 times depending on --pg_tag cmdline </code></pre> <p><strong>Edit</strong>: Replaced old example with <code>metafunc.parametrize</code> usage.</p>
1
2016-08-06T12:53:54Z
[ "python", "py.test" ]
Why does the MSE sklearn library give me a different squared error compared to the l2 norm squared error?
38,795,494
<p>I was trying to compute the mean squared error as in:</p> <p><a href="http://i.stack.imgur.com/xXvG4.png" rel="nofollow"><img src="http://i.stack.imgur.com/xXvG4.png" alt="enter image description here"></a></p> <p>in python. I saw that <a href="http://scikit-learn.org/stable/modules/model_evaluation.html#mean-squared-error" rel="nofollow">scipt/sklearn</a> had an implementation for it already. However, when I tried comparing it to my own implementation they did <em>NOT</em> agree. Why is that? My implementation simply uses the norm 2 (or the Frobenius norm not matching) and nothing else fancy.</p> <p>To test this I wrote the following script:</p> <pre><code>import sklearn from sklearn.decomposition import PCA from sklearn.metrics import mean_squared_error import numpy as np from numpy import linalg as LA X_truth = np.ones((5,6)) X_pred = 1.7*np.ones((5,6)) print 'LA error: ', (1.0/5)*LA.norm(X_truth - X_pred)**2 print 'LA error: ', (1.0/X_truth.shape[0])*LA.norm(X_truth - X_pred)**2 print 'LA error:: ', (1.0/5)*LA.norm(X_truth - X_pred, 'fro')**2 print 'LA error: ', LA.norm(X_truth - X_pred)**2 print 'LA error: ', LA.norm(X_truth - X_pred) print 'LA error: ', (1.0/X_truth.shape[0])*LA.norm(X_truth - X_pred) print 'sklearn MSE error: ', mean_squared_error(X_truth, X_pred) </code></pre> <p>I literally tested every combination I could think of and I still can't have them to match. Any ideas?</p>
0
2016-08-05T18:11:36Z
38,795,656
<p>The formula that's used is a little unusual in that it doesn't take the square root of the sum of squares, whereas <code>LA.norm</code> does.</p> <p>If you look carefully at the docs, you can recreate the formula</p> <p><code>np.sum((X_truth-X_pred)**2)/X_truth.size</code></p> <p>gives 0.49 just like</p> <p><code>mean_squared_error(X_truth, X_pred)</code></p> <p>or </p> <p><code>LA.norm(X_truth - X_pred)**2/X_truth.size</code></p>
2
2016-08-05T18:25:15Z
[ "python", "numpy", "machine-learning", "scipy", "scikit-learn" ]
Autoranging PlotWidget without padding (pyqtgraph)
38,795,508
<p>I was searching for a half of day for this without luck. I have a PlotWidget that I want to autorange. Yet if it does, it has this "padding" (in other words the range is a bit larger then actual range). Do you know a way of avoiding this padding while keeping autoranging.</p>
0
2016-08-05T18:12:37Z
38,804,586
<p>The <code>autoRange</code> method actually has a padding parameter. By default this is <code>None</code> which means the padding is between 0.02 and 0.1 depending on the size of the ViewBox. See the docs <a href="http://www.pyqtgraph.org/documentation/graphicsItems/viewbox.html#pyqtgraph.ViewBox.autoRange" rel="nofollow">here</a>.</p> <p>By setting <code>padding=0</code> you get no padding. </p>
0
2016-08-06T13:05:09Z
[ "python", "pyqt", "pyqtgraph" ]
Performance between Python and Java drivers with OrientDB
38,795,545
<p>I want to develop a project that need a noSQL database. After searching a lot, I chose OrientDB. I want to make an API Rest that can connect to OrientDB. </p> <p>Firstly, I wanted to use Flask to develop but I don't know if it's better to use Java native driver between Python binary driver to connect with database.</p> <p>Anyone have results of performance between these drivers?</p>
0
2016-08-05T18:15:11Z
38,802,276
<p>AFAIK on <em>remote</em> connection (with a standalone OrientDB server) performance would be the same. The great advantage of using the Java native driver is the option to go embedded. If your deployment scenario allows it, you can avoid the standalone server and use OrientDB embedded into your Java application, avoiding network overhead. </p>
0
2016-08-06T08:37:09Z
[ "java", "python", "performance", "orientdb" ]
Why does OSX fail on parsing the extras_require section of my setup.py file?
38,795,583
<p>In my <code>setup.py</code> file, I have the following:</p> <pre><code>setup( ... extras_require={ ':python_version&lt;="2.7"': [ 'pydot&gt;1.0', ], ':python_version&gt;="3.5"': [ 'pydot3k', ], ... ) </code></pre> <p>This works fine on Linux (on Travis CI) and Windows (on AppVeyor) but fails on OSX (also on Travis) with the error message:</p> <blockquote> <p>error in mypackage setup command: Invalid environment marker: python_version&lt;="2.7"</p> </blockquote> <p>What is the reason for this failure, and how can I avoid it?</p>
0
2016-08-05T18:19:27Z
38,803,004
<p>The problem was solved by adding <code>- pip install --upgrade setuptools</code> to my <code>.travis.yml</code> file.</p>
0
2016-08-06T10:01:40Z
[ "python", "osx", "travis-ci", "setup.py" ]
Python crawler to get DOM info by using Selenium and PhantomJS
38,795,628
<p>I used <strong>Selenium</strong> and <strong>PhantomJS</strong> hoping to get data from a website which using javascript to build the DOM.</p> <p>The simple code below works, but it's not always valid. I meant that most of time it would return an empty website which didn't execute the javascript. It could seldom get the correct info I want.</p> <pre><code>from selenium import webdriver from bs4 import BeautifulSoup url = 'http://mall.pchome.com.tw/prod/QAAO6V-A9006XI59' driver = webdriver.PhantomJS driver.get(url) print(driver.page_source, file=open('output.html','w')) soup = BeautifulSoup(driver.page_source,"html5lib") print(soup.select('#MetaDescription')) </code></pre> <p>It has a high probability to return an empty string :</p> <pre><code>[&lt;meta content="" id="MetaDescription" name="description"/&gt;] </code></pre> <p>Is the website server not allowing web crawlers? What can I do to fix my code?</p> <p>What's more, all the info I need could be find in the <code>&lt;head&gt;</code> 's <code>&lt;meta&gt;</code>tag. (Like showing above, the data has an id <code>MetaDescription</code>)</p> <p>Or is there any simpler way to just get the data in <code>&lt;head&gt;</code> tag?</p>
-1
2016-08-05T18:23:18Z
38,796,128
<p>First of all, <code>driver = webdriver.PhantomJS</code> is not a correct way to initialize a selenium webdriver in Python, replace it with:</p> <pre><code>driver = webdriver.PhantomJS() </code></pre> <p>The symptoms you are describing are similar to when you have the timing issues. <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">Add a wait</a> to wait for the desired element(s) to be present <em>before trying to get the page source</em>:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait driver = webdriver.PhantomJS() driver.get(url) # waiting for presence of an element wait = WebDriverWait(driver, 10) wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#MetaDescription"))) print(driver.page_source, file=open('output.html','w')) driver.close() # further HTML parsing here </code></pre> <hr> <p>You may also need to <a href="http://%20http://stackoverflow.com/questions/23581291/python-selenium-with-phantomjs-empty-page-source" rel="nofollow">ignore SSL errors and set the SSL protocol to <code>any</code></a>. In some cases, <a href="http://stackoverflow.com/a/18433763/771848">pretending not be PhantomJS</a> helps as well.</p>
1
2016-08-05T18:59:00Z
[ "javascript", "python", "python-3.x", "selenium", "phantomjs" ]
Pandas: Spliting cells in one column according to a character, then adding the part to other columns via a conditional?
38,795,768
<p>I was wondering if there's an optimal way to perform this sort of action. I have a column of file paths, we'll call <em>C Drive</em>, which contains paths like </p> <pre><code>user\library\photos\item </code></pre> <p>This is a column in a dataframe, and the other columns are <em>Dir [1], Dir [2], ..., Dir [n], ITEM</em></p> <p>I want to split the cells in <em>C Drive</em> by "\", such that the last string is appended to the <em>ITEM</em> column, and the others are appended to the previous directories according to quantity. </p> <p>My current coarse of action is a few While loops, but is there a better way to go about this in Pandas? I'm new to the library.</p> <p>Would also like to mention that <strong>I do know Pandas isn't made for this kind of stuff</strong>, I'm using it in part to learn the library.</p> <p>Cheers!</p>
0
2016-08-05T18:33:39Z
38,798,979
<p>You can use the <code>split</code> function accessed by the <code>str</code> attribute of a Series to split your drive path into the constituent directories. Then convert the resulting Series of lists into a DataFrame. It can be done in one line, as follows:</p> <pre><code>dir_df = pd.DataFrame(df['C Drive'].str.split('\\').tolist()) dir_df.columns = ['Dir [{}]'.format(col) for col in dir_df.columns] dir_df.columns[-1] = 'ITEM' </code></pre> <p>If you want the <code>'C Drive'</code> column in <code>dir_df</code> as well, you can simply add it like so:</p> <pre><code>dir_df['C Drive'] = df['C Drive'] </code></pre> <p>By the way, you might want to escape '\'. Either convert it to '/' or '\' while reading the data in. Or else, weird things might happen.</p>
0
2016-08-05T23:19:57Z
[ "python", "pandas", "dataframe" ]
Read contents of files on s3 bucket without downloading
38,795,783
<p>I am quite new to aws and s3 so pardon if this looks like I haven't tried anything. I want to traverse the directories and files, read the files and retrieve specific lines from the publicly accessible s3 bucket: <code>s3://cgl-rnaseq-recompute-fixed/</code> without downloading it. I want to just be able perform basic tasks like <code>grep/cat</code> on the file contents. </p> <p>For e.g. I should be able to get lines containing <code>MYCN</code> from all the files and folders on the s3 bucket. </p> <p>What is the most efficient way to do it? Are there packages in R/Python that can help traverse s3 buckets? </p> <p>Thanks!</p>
0
2016-08-05T18:34:40Z
38,796,090
<p><a href="http://boto.readthedocs.io/en/latest/s3_tut.html" rel="nofollow">http://boto.readthedocs.io/en/latest/s3_tut.html</a></p> <pre><code>conn = boto.s3.connection.S3Connection( aws_access_key_id='xxx', aws_secret_access_key='yyy' ) for key in conn.list(prefix='logs/*.log'): print key </code></pre>
0
2016-08-05T18:56:47Z
[ "python", "amazon-s3" ]
python multiprocessing pool with expensive initialization
38,795,826
<p>Here is a complete simple working example</p> <pre><code>import multiprocessing as mp import time import random class Foo: def __init__(self): # some expensive set up function in the real code self.x = 2 print('initializing') def run(self, y): time.sleep(random.random() / 10.) return self.x + y def f(y): foo = Foo() return foo.run(y) def main(): pool = mp.Pool(4) for result in pool.map(f, range(10)): print(result) pool.close() pool.join() if __name__ == '__main__': main() </code></pre> <p>How can I modify it so Foo is only initialized once by each worker, not every task? Basically I want the init called 4 times, not 10. I am using python 3.5</p>
3
2016-08-05T18:37:34Z
38,795,986
<p>most obvious, lazy load</p> <pre><code>_foo = None def f(y): global _foo if not _foo: _foo = Foo() return _foo.run(y) </code></pre>
1
2016-08-05T18:49:06Z
[ "python", "python-multiprocessing", "pool", "object-initializers" ]
python multiprocessing pool with expensive initialization
38,795,826
<p>Here is a complete simple working example</p> <pre><code>import multiprocessing as mp import time import random class Foo: def __init__(self): # some expensive set up function in the real code self.x = 2 print('initializing') def run(self, y): time.sleep(random.random() / 10.) return self.x + y def f(y): foo = Foo() return foo.run(y) def main(): pool = mp.Pool(4) for result in pool.map(f, range(10)): print(result) pool.close() pool.join() if __name__ == '__main__': main() </code></pre> <p>How can I modify it so Foo is only initialized once by each worker, not every task? Basically I want the init called 4 times, not 10. I am using python 3.5</p>
3
2016-08-05T18:37:34Z
38,796,161
<p>The intended way to deal with things like this is via the optional <code>initializer</code> and <code>initargs</code> arguments to the <code>Pool()</code> constructor. They exist precisely to give you a way to do stuff exactly once when a worker process is created. So, e.g., add:</p> <pre><code>def init(): global foo foo = Foo() </code></pre> <p>and change the <code>Pool</code> creation to:</p> <pre><code>pool = mp.Pool(4, initializer=init) </code></pre> <p>If you needed to pass arguments to your per-process initialization function, then you'd also add an appropriate <code>initargs=...</code> argument.</p> <p>Note: of course you should also remove the</p> <pre><code>foo = Foo() </code></pre> <p>line from <code>f()</code>, so that your function <em>uses</em> the global <code>foo</code> created by <code>init()</code>.</p>
2
2016-08-05T19:02:01Z
[ "python", "python-multiprocessing", "pool", "object-initializers" ]
Emulating bash's [ctrl]-l, **refreshing**
38,795,864
<p>I need a Python code snippet, that emulates Bash's clear-screen for <strong>refreshing</strong> the screen if it's messed up.</p> <p>I need to use it in Bash, not in the Python interpreter.</p>
-1
2016-08-05T18:40:08Z
38,795,946
<p>Here's a simple way to clear the terminal's screen in python:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.system('clear') </code></pre> <p>And in bash, you simply have to type <code>clear</code> in the terminal.</p>
0
2016-08-05T18:46:01Z
[ "python", "linux", "bash", "refresh", "screen" ]
Is it possible to increase the number of centroids in KMeans during fitting?
38,795,912
<p>I am attempting to use MiniBatchKMeans to stream NLP data in and cluster it, but have no way of determining how many clusters I need. What I would like to do is periodically take the silhouette score and if it drops below a certain threshold, increase the number of centroids. But as far as I can tell, <code>n_clusters</code> is set when you initialize the clusterer and can't be changed without restarting. Am I wrong here? Is there another way to approach this problem that would avoid this issue?</p>
0
2016-08-05T18:43:11Z
38,803,263
<p>It is not a good idea to do this during optimization, because it changes the optimization procedure substantially. It will essentially reset the whole optimization. There are strategies such as bisecting k-means that try to learn the value of k during clustering, but they are a bit more tricky than increasing k by one - they decide upon one particular cluster to split, and try to choose good initial centroids for this cluster to keep things somewhat stable.</p> <p>Furthermore, increasing k will not necessarily improve Silhouette. It will trivially improve SSQ, so you cannot use SSQ as a heuristic for choosing k, either.</p> <p>Last but not least, computing the Silhouette is O(n^2). It is too expensive to run often. If you have large enough amount of data to require MiniBatchKMeans (which <em>really</em> is only for massive data), then you clearly cannot afford to compute Silhouette at all.</p>
2
2016-08-06T10:29:55Z
[ "python", "scikit-learn", "cluster-analysis", "k-means" ]
How to send JSON data using SSL
38,795,935
<p>I'm trying to send JSON data using socket, but get this error</p> <blockquote> <p>b'HTTP/0.9 413 Request Entity Too Large\r\nServer: inets/5.10.2\r\nDate: Fri, 05 Aug 2016 18:19:38 GMT\r\nContent-Type: text/html\r\nContent-Length: 202\r\n\r\n'</p> </blockquote> <p>my code:</p> <pre><code>def single_contract(amount, service_key): current_date = datetime.now() fee = 0 if amount &gt; 10000.0: fee = amount * 0.01 if os.path.exists('./Files/Point.txt'): with open('./Files/Point.txt') as opened_file: point_id = opened_file.read() json_data = dict() json_data["single_contract"] = dict() json_data["single_contract"]["point_id"] = point_id.strip() json_data["single_contract"]["datetime"] = datetime.strftime(current_date, '%Y-%m-%d %H:%M:%S') json_data["single_contract"]["external_transaction_id"] = randint(999999999, 9999999999) json_data["single_contract"]["service_id"] = 1001351861392575516 json_data["single_contract"]["amount"] = amount json_data["single_contract"]["service_key"] = service_key json_data["single_contract"]["fee"] = round(fee, 2) json_data["single_contract"]["params"] = None with open('./Files/sending_file.json', mode='w', encoding='utf-8') as json_file: json.dump(json_data, json_file) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sslcontext = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) sslcontext.load_verify_locations('./Files/ca-cert.pem') sslcontext.load_cert_chain(certfile='./Files/com-cert.pem', keyfile='./Files/com-key.pem') host = '***.***.***.***' port = **** ssl_socket = sslcontext.wrap_socket(sock, server_hostname=host) ssl_socket.connect((host, port)) with open('./Files/sending_file.json', mode='rb') as f: ssl_socket.sendfile(f) with open('./Files/answer.txt', mode='w', encoding='utf-8') as reply: reply.write(str(ssl_socket.recv())) ssl_socket.close() print('End of connection') else: print('No such file or directory.') </code></pre> <p>What am I doing wrong here? Thanks</p>
2
2016-08-05T18:44:54Z
38,796,064
<p>You are sending too much data. You need to either decrease the size of what you are sending or, if you have control of the server, adjust it's settings to allow it to receive larger Https requests.</p> <p><a href="http://cnedelcu.blogspot.com/2013/09/nginx-error-413-request-entity-too-large.html" rel="nofollow">http://cnedelcu.blogspot.com/2013/09/nginx-error-413-request-entity-too-large.html</a></p>
0
2016-08-05T18:54:44Z
[ "python", "sockets", "python-3.x", "ssl" ]
Why is this python generator function running correctly only once?
38,796,024
<p>This is almost certainly a result of my ignorance of how generators work, but I am completely lost.</p> <p>If I interactively create the following generator:</p> <pre><code>def neighborhood(iterable): iterator = iter(iterable) prev = None item = next(iterator) for post in iterator: yield (prev,item,post) prev = item item = post yield (prev,item,None) </code></pre> <p>and then test it like:</p> <pre><code>for prev,item,next in neighborhood([1,2,3,4,5]): print(prev, item, next) </code></pre> <p>It produces:</p> <pre><code>None 1 2 1 2 3 2 3 4 3 4 5 4 5 None </code></pre> <p>as expected. If I run it again, or try to redefine it in any way, I get a</p> <blockquote> <p>'NoneType' object is not callable"</p> </blockquote> <p>error.</p>
2
2016-08-05T18:52:27Z
38,796,094
<p>When you did</p> <pre><code>for prev,item,next in ... # ^^^^ </code></pre> <p>you shadowed the built-in <code>next</code> function. The next time you try to use your generator, it fails because it gets your <code>next</code> variable instead of the function it needed.</p>
7
2016-08-05T18:57:02Z
[ "python", "python-3.x", "generator" ]
Why is this python generator function running correctly only once?
38,796,024
<p>This is almost certainly a result of my ignorance of how generators work, but I am completely lost.</p> <p>If I interactively create the following generator:</p> <pre><code>def neighborhood(iterable): iterator = iter(iterable) prev = None item = next(iterator) for post in iterator: yield (prev,item,post) prev = item item = post yield (prev,item,None) </code></pre> <p>and then test it like:</p> <pre><code>for prev,item,next in neighborhood([1,2,3,4,5]): print(prev, item, next) </code></pre> <p>It produces:</p> <pre><code>None 1 2 1 2 3 2 3 4 3 4 5 4 5 None </code></pre> <p>as expected. If I run it again, or try to redefine it in any way, I get a</p> <blockquote> <p>'NoneType' object is not callable"</p> </blockquote> <p>error.</p>
2
2016-08-05T18:52:27Z
38,796,095
<p>It's because you're using a variable named <code>next</code> in your test code. Use a name that doesn't shadow the built-in function <code>next</code>.</p>
3
2016-08-05T18:57:08Z
[ "python", "python-3.x", "generator" ]
Python Using Keyword and variable number of arguments in same function
38,796,059
<p>I am wondering if there is a way to do something like this in python 2.7.12</p> <pre><code>def saveValues(file,*data,delim="|"): buf="" for d in data: buf+=str(d) + delim open(file,"w").write(buf[:-1]) </code></pre> <p>So that I have the option to pass delim, or take the default.</p>
3
2016-08-05T18:54:23Z
38,796,124
<p>It's possible in python3. The python2 workaround is usually this:</p> <pre><code>def saveValues(file, *data, **kwargs): delim = kwargs.pop('delim', '|') ... </code></pre>
7
2016-08-05T18:58:44Z
[ "python", "python-2.7", "function", "arguments" ]
efficiently merging tables on substrings, not perfect matches
38,796,153
<p>I want to merge two tables in R or Python, each with tens of thousands of rows. However, <strong>I won't be able to merge on perfect matches.</strong> I'm looking for cases when one key is a substring of another. The matching substring can contain multiple words. <strong>I'm looking for a solution that is faster than my brute force code below.</strong></p> <p><a href="http://stackoverflow.com/users/170352/brandon-bertelsen">http://stackoverflow.com/users/170352/brandon-bertelsen</a> gave a nice answer, based toy data I originally suggested. However, it only matches on single word substrings. (I hadn't originally made this requirement explicit.)</p> <p>Here's the code I would use for this situation.</p> <pre><code>library(SPARQL) library(parallel) library(Hmisc) library(tidyr) library(dplyr) my.endpoint &lt;- "http://sparql.hegroup.org/sparql/" go.query &lt;- 'select * where { graph &lt;http://purl.obolibrary.org/obo/merged/GO&gt; { ?goid &lt;http://www.geneontology.org/formats/oboInOwl#hasOBONamespace&gt; "biological_process"^^&lt;http://www.w3.org/2001/XMLSchema#string&gt; . ?goid rdfs:label ?goterm}}' go.result &lt;- SPARQL(url = my.endpoint, query = go.query) go.result.frame &lt;- go.result[[1]] anat.query &lt;- 'select distinct ?anatterm ?anatid where { graph &lt;http://purl.obolibrary.org/obo/merged/UBERON&gt; { ?anatid &lt;http://www.geneontology.org/formats/oboInOwl#hasDbXref&gt; ?xr . ?anatid rdfs:label ?anatterm}}' anat.result &lt;- SPARQL(url = my.endpoint, query = anat.query) anat.result.frame &lt;- anat.result[[1]] # slow but recognizes multi-word substrings loop.solution &lt;- mclapply( X = sort(anat.result.frame$anatid), mc.cores = 7, FUN = function(one.anat.id) { one.anat.term &lt;- anat.result.frame$anatterm[anat.result.frame$anatid == one.anat.id] temp &lt;- grepl(pattern = paste0('\\b', one.anat.term, '\\b'), x = go.result.frame$goterm) temp &lt;- go.result.frame[temp , ] if (nrow(temp) &gt; 0) { temp$anatterm &lt;- one.anat.term temp$anatid &lt;- one.anat.id return(temp) } } ) loop.solution &lt;- do.call(rbind, loop.solution) # from Brandon # fast, but doesn't recognize multi-word matches sep.gather.soln &lt;- separate(go.result.frame, goterm, letters, sep = " ", remove = FALSE) %&gt;% gather(goid, goterm) %&gt;% na.omit() %&gt;% setNames(c("goid", "goterm", "code", "anatterm")) %&gt;% select(goid, goterm, anatterm) %&gt;% left_join(anat.result.frame) %&gt;% na.omit() </code></pre>
-2
2016-08-05T19:01:20Z
38,796,249
<pre><code>library(tidyr) library(dplyr) df1 &lt;- data.frame( mealtime = c("breakfast","lunch","dinner","dinner"), dish = c( "cheese omelette", "turkey sandwich", "bean soup", "something very long like this") ) df2 &lt;- read.table(textConnection( 'ingredient category bean legume beef meat carrot vegetable cheese dairy milk dairy omelette eggs sandwich bread turkey meat'), header = TRUE) df1 &lt;- separate(df1, dish, letters, sep = " ", remove = FALSE) %&gt;% gather(mealtime, dish) %&gt;% na.omit() %&gt;% setNames(c("mealtime","dish","code","ingredient")) %&gt;% select(mealtime, dish, ingredient) %&gt;% left_join(df2) %&gt;% na.omit() df1 </code></pre> <p><code> mealtime dish ingredient category 1 breakfast cheese omelette cheese dairy 2 lunch turkey sandwich turkey meat 3 dinner bean soup bean legume 5 breakfast cheese omelette omelette eggs 6 lunch turkey sandwich sandwich bread </code></p>
0
2016-08-05T19:08:20Z
[ "python", "string", "optimization" ]
efficiently merging tables on substrings, not perfect matches
38,796,153
<p>I want to merge two tables in R or Python, each with tens of thousands of rows. However, <strong>I won't be able to merge on perfect matches.</strong> I'm looking for cases when one key is a substring of another. The matching substring can contain multiple words. <strong>I'm looking for a solution that is faster than my brute force code below.</strong></p> <p><a href="http://stackoverflow.com/users/170352/brandon-bertelsen">http://stackoverflow.com/users/170352/brandon-bertelsen</a> gave a nice answer, based toy data I originally suggested. However, it only matches on single word substrings. (I hadn't originally made this requirement explicit.)</p> <p>Here's the code I would use for this situation.</p> <pre><code>library(SPARQL) library(parallel) library(Hmisc) library(tidyr) library(dplyr) my.endpoint &lt;- "http://sparql.hegroup.org/sparql/" go.query &lt;- 'select * where { graph &lt;http://purl.obolibrary.org/obo/merged/GO&gt; { ?goid &lt;http://www.geneontology.org/formats/oboInOwl#hasOBONamespace&gt; "biological_process"^^&lt;http://www.w3.org/2001/XMLSchema#string&gt; . ?goid rdfs:label ?goterm}}' go.result &lt;- SPARQL(url = my.endpoint, query = go.query) go.result.frame &lt;- go.result[[1]] anat.query &lt;- 'select distinct ?anatterm ?anatid where { graph &lt;http://purl.obolibrary.org/obo/merged/UBERON&gt; { ?anatid &lt;http://www.geneontology.org/formats/oboInOwl#hasDbXref&gt; ?xr . ?anatid rdfs:label ?anatterm}}' anat.result &lt;- SPARQL(url = my.endpoint, query = anat.query) anat.result.frame &lt;- anat.result[[1]] # slow but recognizes multi-word substrings loop.solution &lt;- mclapply( X = sort(anat.result.frame$anatid), mc.cores = 7, FUN = function(one.anat.id) { one.anat.term &lt;- anat.result.frame$anatterm[anat.result.frame$anatid == one.anat.id] temp &lt;- grepl(pattern = paste0('\\b', one.anat.term, '\\b'), x = go.result.frame$goterm) temp &lt;- go.result.frame[temp , ] if (nrow(temp) &gt; 0) { temp$anatterm &lt;- one.anat.term temp$anatid &lt;- one.anat.id return(temp) } } ) loop.solution &lt;- do.call(rbind, loop.solution) # from Brandon # fast, but doesn't recognize multi-word matches sep.gather.soln &lt;- separate(go.result.frame, goterm, letters, sep = " ", remove = FALSE) %&gt;% gather(goid, goterm) %&gt;% na.omit() %&gt;% setNames(c("goid", "goterm", "code", "anatterm")) %&gt;% select(goid, goterm, anatterm) %&gt;% left_join(anat.result.frame) %&gt;% na.omit() </code></pre>
-2
2016-08-05T19:01:20Z
38,926,710
<p>I am using your original post data.<br> first split term <br> second check the associated item in dictionary<br> third combine together</p> <pre><code>terms =["cheese omelette","turkey sandwich","bean soup",] dictionary ={'turkey': 'meat', 'cheese': 'dairy', 'sandwich': 'bread', 'beef': 'meat', 'omelette': 'eggs', 'bean': 'legume', 'carrot': 'vegetable', 'milk': 'dairy'} res = set( term +' '+ cat for term in terms for cat in set([ dictionary .get(word,'') for word in term.split()]) if cat) for i in res: print i output: cheese omelette dairy bean soup legume turkey sandwich meat turkey sandwich bread cheese omelette eggs </code></pre>
1
2016-08-12T21:29:52Z
[ "python", "string", "optimization" ]
Django form unittest with ChoiceField and MultipleChoiceField failing is_valid()
38,796,191
<p>I'm running into a small problem with writing a unit test for a Django form. I really just want to check the is_valid() method and have seen examples but my code isn't working and after a day or so of reading up on Google I've yet to find the answer I'm looking for. Below is the code for the forms.py and test_forms.py</p> <h1>forms.py</h1> <pre><code>class DataSelectForm(forms.Form): #these are done in the init funct. result_type = forms.ChoiceField(widget=forms.Select(attrs={'class': 'field-long'})) band_selection = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'multiselect field-long'})) title = forms.CharField(widget=forms.HiddenInput()) description = forms.CharField(widget=forms.HiddenInput()) def __init__(self, result_list=None, band_list=None, *args, **kwargs): super(DataSelectForm, self).__init__(*args, **kwargs) if result_list is not None and band_list is not None: self.fields["result_type"] = forms.ChoiceField(choices=result_list, widget=forms.Select(attrs={'class': 'field-long'})) self.fields["band_selection"] = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'multiselect field-long'}), choices=band_list </code></pre> <h1>test_forms.py</h1> <pre><code> def test_data_select_form(self): results = ResultType.objects.all() results_value = [] for result in results: results_value.append(result.result_type) bands = SatelliteBand.objects.all() bands_value = [] for band in bands: bands_value.append(band.band_name) form_data = {'result_type': results_value, 'band_selection': bands_value, 'title': 'a title', 'description': 'some description'} form = DataSelectForm(data = form_data) print(form['title'].value()) print(form['description'].value()) print(form['result_type'].value()) print(form['band_selection'].value()) self.assertTrue(form.is_valid()) </code></pre> <p>The only thing I get when I run the test case is "AssertionError: False is not true" I understand the error, just not why I'm getting it. I'm passing in all the data and I can see it when I run the print statements. I've tried taking the result_type and band_selection and passing it into the constructor instead of it being a part of the form_data but that didn't work either. What am I missing?</p>
0
2016-08-05T19:04:24Z
38,796,529
<p>You need to pass <code>result_list</code> and <code>band_list</code> when you construct your form.</p> <pre><code># These aren't the actual choices you want, I'm just showing that # choices should be a list of 2-tuples. result_list = [('result1', 'result1'), ('result2', 'result2'), ...] band_list = [('band1', 'band1'), ('band2', 'band2'), ...] DataSelectForm(result_list=result_list, band_list=band_list, data=form_data) </code></pre> <p>If you don't pass the values to the form, then you don't set the choices for the fields. If the fields don't have any choices, then the values in the <code>data</code> dict cannot be valid, so the form will always be invalid.</p>
2
2016-08-05T19:27:18Z
[ "python", "django", "forms", "unit-testing", "choicefield" ]
ModelForm won't create instance of model
38,796,217
<p>I am trying to create a frontend form in my Django site that will allow users to add entries to my SQL database. </p> <p><strong>But when I use the form nothing happens in my database. What am I doing wrong?</strong></p> <p>I thought the right way would be to use the ModelForm technique.</p> <p>My models looks like this:</p> <pre><code>class Actor(models.Model): name = models.CharField(max_length=200) wage = models.IntegerField(default=3100) def __str__(self): return self.name </code></pre> <p>So I wrote this in my <em>forms.py</em>:</p> <pre><code>from django import forms from .models import Actor class ActorForm(forms.ModelForm): class Meta: model = Actor fields = ['name', 'wage'] form = ActorForm() </code></pre> <p>I then added this to my <em>views.py</em>:</p> <pre><code>def get_actor(request): if request.method == 'POST': form = ActorForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/scenes/thanks/') else: form = ActorForm() return render(request, 'scenes/actor.html', {'form': form}) def thanks(request): return render(request, 'scenes/thanks.html',) </code></pre> <p>And this in a template called <em>actors.html</em></p> <pre><code>&lt;form action="/scenes/actor/" method="post"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" value="Submit" /&gt; </code></pre> <p></p>
0
2016-08-05T19:06:24Z
38,796,365
<p>You have to call the model form's <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#the-save-method" rel="nofollow"><code>save()</code></a> method after checking that it's valid:</p> <pre><code>def get_actor(request): if request.method == 'POST': form = ActorForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/scenes/thanks/') else: form = ActorForm() return render(request, 'scenes/actor.html', {'form': form}) </code></pre>
0
2016-08-05T19:16:35Z
[ "python", "django", "django-forms" ]
How do I get a single piece of data from Quickbooks Online?
38,796,225
<p>I've got a client who uses Quickbooks Online for accounts, and he wants to be able to read data from it programmatically. We're using Clojure, so any solution in Java will work, or http gets etc can be made directly if necessary.</p> <p>They've got what appears to be a nice RESTFUL interface to their stuff, and a java library for accessing it, but I can't make head or tail of their documentation: <a href="https://developer.intuit.com/docs?redirectid=accounting" rel="nofollow">https://developer.intuit.com/docs?redirectid=accounting</a>, which all seems to be about webapps and OAuth and other stuff.</p> <p>All I want to be able to do is get, say, a single customer record.</p> <p>Can anyone point me to the simplest possible Hello World type program, in any language? (Preferably Java or something easy to read like python)</p> <p>I'd imagine that what I'm looking for would look something like:</p> <pre><code>import quickbooksapi username='fluffy' password='doom' cus=quickbooksapi.get_customer(username,password,id=4) print(cus) </code></pre> <p>or something?</p> <p>Or have I just got the wrong end of some gigantic stick here?</p>
0
2016-08-05T19:06:38Z
38,808,492
<p>This looks the best available documentation:</p> <p><a href="https://developer.intuit.com/hub/blog/2016/04/25/quick-start-to-quickbooks-online-rest-api-with-oauth1-0" rel="nofollow">https://developer.intuit.com/hub/blog/2016/04/25/quick-start-to-quickbooks-online-rest-api-with-oauth1-0</a></p> <p>It's a recent blog post by a Quickbooks developer, showing how to get Oauth keys and then use curl to access the REST API. </p> <p>It seems that you have to pretend to make a SaaS app in order to get one bit of gubbins and then there's another thing where you can get the rest of the gubbins.</p> <p>After that you can use curl, putting all the gubbins in the headers. (The postman extension for chrome that he uses can generate curl commands and equivalents in many other languages)</p> <p>It works exactly as advertised (6th August 2016).</p> <p>That's enough. I can take it from there.</p>
0
2016-08-06T20:36:54Z
[ "java", "python", "clojure", "quickbooks-online" ]
Connecting a Tun to a socket
38,796,252
<p>I want to connect a Tun to a socket so that whatever data is stored in the Tun file will then end up being pushed out to a socket which will receive the data. I am struggling with the higher level conceptual understanding of how I am supposed to connect the socket and the Tun. Does the Tun get a dedicated socket that then communicates with another socket (the receive socket)? Or does the Tun directly communicate with the receive socket? Or am I way off all together? Thanks!</p>
0
2016-08-05T19:08:32Z
38,833,280
<p>If I am understanding your problem, you should be able to write an application that connects to the tun device and also maintains another network socket. You will need some sort of multiplexing such as epoll or select. But, basically, whenever you see data on the tun interface, you can receive the data into a buffer and then provide this buffer (with the correct number of received octets) to the send call of the other socket. Typically you use such a setup when you insert some custom header or something to e.g., implement a custom VPN solution. </p>
0
2016-08-08T15:34:47Z
[ "python", "sockets", "networking", "tun" ]
how to install hypothesis Python package?
38,796,441
<p>I'm using Wing IDE, how do I install hypothesis Python package to my computer? I have already download the zip file, do I use command prompt to install it or there is an option in Wing IDE to do it?</p>
0
2016-08-05T19:20:58Z
38,796,484
<p><code>pip install hypothesis</code></p> <p>Assuming you have pip.</p> <p>If you want to install it from the downloaded package just open command prompt and <code>cd</code> to the directory where you downloaded it and do</p> <p><code>python setup.py install</code></p>
1
2016-08-05T19:24:43Z
[ "python", "wing-ide", "python-packaging" ]
how to install hypothesis Python package?
38,796,441
<p>I'm using Wing IDE, how do I install hypothesis Python package to my computer? I have already download the zip file, do I use command prompt to install it or there is an option in Wing IDE to do it?</p>
0
2016-08-05T19:20:58Z
38,796,568
<p>As shakesbeer and hleggs wrote, and also by giving:</p> <pre><code> easy_install hypothesis </code></pre> <p>hope this helps :)</p>
0
2016-08-05T19:29:53Z
[ "python", "wing-ide", "python-packaging" ]
Python Unit Testing with Unordered Set for Tree Data Structure
38,796,442
<h2>Background</h2> <p>I am trying to add unit tests for a tree data structure I am building (python 3). The tree structure uses sets (unordered) and I am struggling to find ways to test certain methods of my tree class.</p> <h2>Example</h2> <p>Given the diagramed tree...I have a method that will detach a node (say #2) and then choose one of it's children (3 or 4) to take it's place instead of parenting them both to node 1. (This is useful in the case that say #2 is the root and we still want 3 and 4 to be related when 2 is discarded.)</p> <pre><code> 1----------+ 2 1----------+ | | | | +---2---+ | Detaching Node "2" 3---+ | | | 11 --&gt; /|\ | 11 3 4 /| \ 5 6 7 | /| \ /|\ /|\ 12 13 14 4 12 13 14 5 6 7 8 9 10 /|\ 8 9 10 </code></pre> <h2>The Problem</h2> <p>Sets are unordered and the way I select the child (out of 3 and 4) is to check if node 2 has children, then pop off a child from his set of children and make that the one. Because sets are unordered, I get (seemingly) random results in my test cases when I pop the child off. </p> <h2>Question</h2> <p>What should my strategy be to test a method like this (I've read about testing difficulties when using the random module, but I've also read that sets do have some sort of a predictable order)? Should I just test <em>around</em> this problem? Should I try to figure out what order the set will be "popped" in?</p>
3
2016-08-05T19:21:04Z
38,796,532
<p>Test whether the method does the thing it's supposed to do. After the operation, has the correct node been replaced by one of its children? If so, great! If not, report a failure.</p> <p>You don't need to assert that it's been replaced by any specific child.</p>
1
2016-08-05T19:27:34Z
[ "python", "unit-testing", "random", "tree", "unordered-set" ]
Singly linked list is not reversing when using recursion
38,796,550
<p>I'm having trouble figuring out what's missing. I've taken a several looks at other solutions online, and those don't seem to work when I apply the differences. I've spent a good amount of time trying to debug. Here's my code:</p> <pre><code>def recurse_reverse(self, curr, level): print('-' * level, 'curr:', curr.value, '| next:', curr.next.value if curr.next else curr.next) if (not curr) or (not curr.next): # if there's 0 or 1 node return curr # p = self.recurse_reverse(curr.next, level + 1) self.recurse_reverse(curr.next, level + 1) print('-' * level, 'curr:', curr.value, '-&gt;', curr.next.value, '-&gt;', curr.next.next.value if curr.next.next else curr.next.next) curr.next.next = curr # checking if pointer moved print('-' * level, 'curr:', curr.value, '-&gt;', curr.next.value, '-&gt;', curr.next.next.value if curr.next.next else curr.next.next) # curr.next = None # return p </code></pre> <p>The output I get when I call</p> <pre><code>my_list = SinglyLinkedList() my_list.add_to_tail(1) my_list.add_to_tail(2) my_list.add_to_tail(3) my_list.add_to_tail(4) print(my_list._head.value) # 1 print(my_list._head.next.value) # 2 print(my_list._head.next.next.value) # 3 print(my_list._head.next.next.next.value) # 4 my_list.recurse_reverse(my_list._head, 1) </code></pre> <p>is this:</p> <pre><code>- curr: 1 | next: 2 -- curr: 2 | next: 3 --- curr: 3 | next: 4 ---- curr: 4 | next: None --- curr: 3 -&gt; 4 -&gt; None --- curr: 3 -&gt; 4 -&gt; 3 -- curr: 2 -&gt; 3 -&gt; 4 -- curr: 2 -&gt; 3 -&gt; 2 - curr: 1 -&gt; 2 -&gt; 3 - curr: 1 -&gt; 2 -&gt; 1 </code></pre> <p>So printing at each level, it seems that the pointers are being moved correctly. However when I try to print the linked list's head and tail I call <code>recurse_reverse</code>, I get 1 and 3, respectively; yet, what I would expect is 4 and 1.</p> <p>In many solutions I've seen, the last line of the code is <code>curr.next = None</code>, to remove the <code>next</code> pointer of the current node, but when include that in my code, I get <code>AttributeError: 'NoneType' object has no attribute 'value'</code></p> <p>I've also tried setting </p> <pre><code>p = self.recurse_reverse(curr.next, level + 1) </code></pre> <p>and then <code>return p</code> on the last line, but that doesn't work either.</p> <p>Here's my implementation:</p> <pre><code>class _LinkNode: def __init__(self, value): self.value = value self.next = None class SinglyLinkedList: def __init__(self): self._head = None self._tail = None self._length = 0 def add_to_tail(self, value): """ Add a new node to the tail of the linked list. Parameters ---------- value : int, float, string, dict, list, etc. """ new_node = _LinkNode(value) if self._head is None: # if linked list is empty self._head = new_node if self._tail: # if linked list has a tail, i.e. &gt; 1 node self._tail.next = new_node self._tail = new_node # regardless of current length, update tail self._length += 1 def recurse_reverse(self, curr, level): # see above </code></pre>
0
2016-08-05T19:28:43Z
38,797,106
<p>There are two issues with your code. First if list contains more than one element you don't swap <code>_head.next</code>, after <code>recurse_reverse</code> it will still point to second element of the original list and thus the last two elements of reversed list form a loop.The second issue is what you don't swap <code>_head</code> and <code>_tail</code> anywhere in your code. </p> <p>Here's one way to to implement the reversal recursively:</p> <pre><code>@staticmethod def reverse(prev, node): # Recurse until end of the list if node: SinglyLinkedList.reverse(node, node.next) node.next = prev def recurse_reverse(self): # Reverse nodes SinglyLinkedList.reverse(None, self._head) # Swap head &amp; tail since they are reversed now self._head, self._tail = self._tail, self._head </code></pre>
1
2016-08-05T20:09:41Z
[ "python", "recursion", "linked-list", "reverse" ]
Django - UNIQUE constraint failed: auth_user.username
38,796,713
<p>I'm writing unit tests for a <code>Django REST Framework</code> app and using <a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow"><code>factory_boy</code></a> to create my fake testing data. I'm getting the following error when I run my test: </p> <pre><code>File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 254, in _find_tests module = self._get_module_from_name(name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name __import__(name) File "/Users/thomasheatwole/osf-meetings/meetings/conferences/tests.py", line 27, in &lt;module&gt; class SubmissionFactory(factory.DjangoModelFactory): File "/Users/thomasheatwole/osf-meetings/meetings/conferences/tests.py", line 34, in SubmissionFactory username = 'contributor' File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/base.py", line 67, in __call__ return cls.create(**kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/base.py", line 594, in create return cls._generate(True, attrs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/base.py", line 519, in _generate obj = cls._prepare(create, **attrs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/base.py", line 494, in _prepare return cls._create(model_class, *args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/django.py", line 181, in _create return manager.create(*args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/query.py", line 401, in create obj.save(force_insert=True, using=self.db) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 74, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/base.py", line 708, in save force_update=force_update, update_fields=update_fields) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/base.py", line 736, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/base.py", line 820, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/base.py", line 859, in _do_insert using=using, raw=raw) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql cursor.execute(sql, params) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute return Database.Cursor.execute(self, query, params) IntegrityError: UNIQUE constraint failed: auth_user.username </code></pre> <p>Not really sure what it means or what's causing it. Here's where the factory is defined:</p> <pre><code>class UserFactory(factory.DjangoModelFactory): class Meta: model = User </code></pre> <p>Here's where an instance is created:</p> <pre><code>contributor = UserFactory( username = 'contributor' ) </code></pre> <p>Here's the full file: <a href="https://github.com/TomHeatwole/osf-meetings/blob/feature/conference-tests/meetings/conferences/tests.py" rel="nofollow">tests.py</a></p> <p>Let me know if there's an easy fix. Thanks!</p>
-1
2016-08-05T19:41:19Z
38,796,820
<p>Turns out I was calling the factory twice so both Users were getting <code>username = 'contributor'</code>. Simple fix is to not define the username inside the factory but to define it when you call the factory.</p>
0
2016-08-05T19:49:37Z
[ "python", "django", "django-rest-framework", "factory-boy" ]
Django - UNIQUE constraint failed: auth_user.username
38,796,713
<p>I'm writing unit tests for a <code>Django REST Framework</code> app and using <a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow"><code>factory_boy</code></a> to create my fake testing data. I'm getting the following error when I run my test: </p> <pre><code>File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 254, in _find_tests module = self._get_module_from_name(name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name __import__(name) File "/Users/thomasheatwole/osf-meetings/meetings/conferences/tests.py", line 27, in &lt;module&gt; class SubmissionFactory(factory.DjangoModelFactory): File "/Users/thomasheatwole/osf-meetings/meetings/conferences/tests.py", line 34, in SubmissionFactory username = 'contributor' File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/base.py", line 67, in __call__ return cls.create(**kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/base.py", line 594, in create return cls._generate(True, attrs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/base.py", line 519, in _generate obj = cls._prepare(create, **attrs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/base.py", line 494, in _prepare return cls._create(model_class, *args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/factory/django.py", line 181, in _create return manager.create(*args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/query.py", line 401, in create obj.save(force_insert=True, using=self.db) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 74, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/base.py", line 708, in save force_update=force_update, update_fields=update_fields) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/base.py", line 736, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/base.py", line 820, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/base.py", line 859, in _do_insert using=using, raw=raw) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql cursor.execute(sql, params) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/thomasheatwole/.virtualenvs/django/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 323, in execute return Database.Cursor.execute(self, query, params) IntegrityError: UNIQUE constraint failed: auth_user.username </code></pre> <p>Not really sure what it means or what's causing it. Here's where the factory is defined:</p> <pre><code>class UserFactory(factory.DjangoModelFactory): class Meta: model = User </code></pre> <p>Here's where an instance is created:</p> <pre><code>contributor = UserFactory( username = 'contributor' ) </code></pre> <p>Here's the full file: <a href="https://github.com/TomHeatwole/osf-meetings/blob/feature/conference-tests/meetings/conferences/tests.py" rel="nofollow">tests.py</a></p> <p>Let me know if there's an easy fix. Thanks!</p>
-1
2016-08-05T19:41:19Z
38,802,864
<p>As stated in your response, the problem is that you're using a fixed value for a <code>unique=True</code> field.</p> <p>One solution is to pass the <code>username</code> on each call to <code>UserFactory</code>; however, the goal of <code>factory_boy</code> is to avoid having to specify such fields unless the test needs a specific value.</p> <p>In your example, you should use a definition inspired from the following:</p> <pre><code>class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User username = factory.Faker('username') </code></pre> <p>With that definition, each call to <code>UserFactory</code> will provide a <code>User</code> with a different username.</p> <p>And, if the <code>username</code> has to be set for a specific test, simply call <code>UserFactory(username='john')</code>.</p>
0
2016-08-06T09:46:55Z
[ "python", "django", "django-rest-framework", "factory-boy" ]
How to figure out when k means converges for tf idf?
38,796,898
<p>I am fairly new with working with text data.</p> <p>I have a data frame of about 300,000 unique product names and I am trying to use k means to cluster similar names together. I used sklearn's tfidfvectorizer to vectorize the names and convert to a tf-idf matrix.</p> <p>After I transformed it to a sparse matrix I fit k means with 5-10 clusters but I do not know if I am converging.</p> <p>How can I figure this out?</p>
0
2016-08-05T19:55:29Z
38,806,540
<p>According to <a href="https://github.com/scikit-learn/scikit-learn/blob/51a765a/sklearn/cluster/k_means_.py#L814" rel="nofollow">the source</a> the attribute <code>n_iter_</code> should hold the number k-means iterations. If <code>n_iter_ &lt; max_iter</code>, then the algorithm converged within the given tolerance.</p> <p>If what you are trying to accomplish is to determine the optimal number of clusters, you can use the <a href="https://en.wikipedia.org/wiki/Elbow_method_(clustering)" rel="nofollow">elbow method</a> with the <code>inertia_</code> attribute.</p>
1
2016-08-06T16:43:42Z
[ "python", "scikit-learn", "k-means", "tf-idf", "convergence" ]
pytest unicode syntaxerror with '£' symbol
38,796,927
<p>I have a test file: <code>test_pytest.py</code>:</p> <pre><code>def test_pytest(): s = '£' assert True </code></pre> <p>Using pytest, I run it like this: <code>python -m pytest test_pytest.py</code></p> <p>The result:</p> <pre><code>&gt; python -m pytest test_pytest.py ============================= test session starts ============================= platform win32 -- Python 3.5.2, pytest-2.9.2, py-1.4.31, pluggy-0.3.1 rootdir: c:\temp, inifile: collected 0 items / 1 errors =================================== ERRORS ==================================== _______________________ ERROR collecting test_pytest.py _______________________ c:\projects\aio-rpc\venv\lib\site-packages\_pytest\python.py:611: in _importtestmodule mod = self.fspath.pyimport(ensuresyspath=importmode) c:\projects\aio-rpc\venv\lib\site-packages\py\_path\local.py:650: in pyimport __import__(modname) E File "c:\temp\test_pytest.py", line 3 E SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xa3 in position 0: invalid start byte =========================== 1 error in 0.07 seconds =========================== </code></pre> <p>What gives?</p> <p>Note that commenting the <code>s='£'</code> allows the test to pass</p>
-1
2016-08-05T19:57:46Z
38,802,021
<p>Silly me, my Vim was saving the file with latin1 encoding instead of utf-8. Changing the encoding of the file to utf-8 fixed the problem. </p>
0
2016-08-06T08:08:12Z
[ "python", "unit-testing", "testing", "py.test", "python-3.5" ]
Kivy Spinner Autoupdate
38,796,943
<p>I have a spinner in kivy that I cannot seem to get the "text_autoupdate" feature working. The documentation can be found here: <a href="https://kivy.org/docs/api-kivy.uix.spinner.html" rel="nofollow">https://kivy.org/docs/api-kivy.uix.spinner.html</a></p> <p>My .py code: </p> <pre><code>from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.spinner import Spinner from kivy.uix.button import Button from kivy.properties import ListProperty, BooleanProperty class Port_Selection(Widget): # list all serial ports ports = ["[None]"] selection = ListProperty(['hit refresh']) def port_refresh(self): port = ["1","2","3"] if port == []: # if none found message = {"None"} # return "none" port = message self.ports = port print self.ports class SensorTest(Widget): pass class Sensor(App): def build(self): return SensorTest() if __name__ == '__main__': Sensor().run() </code></pre> <p>And my .kv code: </p> <pre><code>#:kivy 1.0.9 &lt;Port_Selection&gt;: Spinner: text: 'Select Port' text_autoupdate: True values: root.ports pos: root.x,root.y Button: text: 'Refresh Ports' pos: root.x+100, root.y on_press: root.port_refresh(); &lt;SensorTest&gt;: Label: font_size: 45 center_x: root.width/2 center_y: root.top - 50 text: "Sensor Testing" Port_Selection: pos: self.pos </code></pre> <p>How do I get the "text_autoupdate" feature working properly?</p>
0
2016-08-05T19:58:33Z
38,797,931
<p>You forgot to define ports as ListProperty </p> <p>Change:<br> <code>ports = ["[None]"]</code></p> <p>To:<br> <code>ports = ListProperty(["[None]"])</code></p>
0
2016-08-05T21:21:34Z
[ "python", "spinner", "kivy" ]
Python Convert Excel tabs to CSV files
38,796,951
<p>I've edited the post to reflect the changes recommended.</p> <pre><code>def Excel2CSV(ExcelFile, Sheetname, CSVFile): import xlrd import csv workbook = xlrd.open_workbook('C:\Users\aqureshi\Desktop\Programming\consolidateddataviewsyellowed.xlsx') worksheet = workbook.sheet_by_name (ARC) csvfile = open (ARC.csv,'wb') wr = csv.writer (csvfile, quoting = csv.QUOTE_ALL) for rownum in xrange (worksheet.nrows): wr.writerow( list(x.encode('utf-8') if type (x) == type (u'') else x for x in worksheet.row_values (rownum))) csvfile.close() Excel2CSV("C:\Users\aqureshi\Desktop\Programming\consolidateddataviewsyellowed.xlsx","ARC","output.csv") </code></pre> <p>It displays the following error.</p> <p>Traceback (most recent call last): File "C:/Users/aqureshi/Desktop/Programming/ExceltoCSV.py", line 18, in Excel2CSV("C:\Users\aqureshi\Desktop\Programming\consolidateddataviewsyellowed.xlsx","ARC","output.csv") File "C:/Users/aqureshi/Desktop/Programming/ExceltoCSV.py", line 2, in Excel2CSV import xlrd ImportError: No module named xlrd</p> <p>Any help will be greatly appreciated.</p>
1
2016-08-05T19:58:53Z
38,797,455
<p><strong>Response to edited code</strong></p> <p><code>No module named xlrd</code> indicates that you have not installed the <code>xlrd</code> library. Bottom line, you need to install the xlrd module. Installing a module is an important skill which beginner python users must learn and it can be a little hairy if you aren't tech savvy. Here's where to get started.</p> <p>First, check if you have pip (a module used to install other modules for python). If you installed python recently and have up-to-date software, you almost certainly already have pip. If not, see this detailed how-to answer elsewhere on stackoverflow: <a href="http://stackoverflow.com/questions/4750806/how-do-i-install-pip-on-windows">How do I install pip on Windows?</a></p> <p>Second, use pip to install the xlrd module. The internet already has a trove of tutorials on this subject, so I will not outline this here. Just Google: "how to pip install a module on <em>your OS here</em>"</p> <p>Hope this helps!</p> <p><strong>Old Answer</strong></p> <p>your code looks good.. Here's the test case I ran using mostly what your wrote. Note that I changed your function so that it uses the arguments rather than hardcoded values. that may be where your trouble is?</p> <pre><code>def Excel2CSV(ExcelFile, Sheetname, CSVFile): import xlrd import csv workbook = xlrd.open_workbook (ExcelFile) worksheet = workbook.sheet_by_name (Sheetname) csvfile = open (CSVFile,'wb') wr = csv.writer (csvfile, quoting = csv.QUOTE_ALL) for rownum in xrange(worksheet.nrows): wr.writerow( list(x.encode('utf-8') if type (x) == type (u'') else x for x in worksheet.row_values (rownum))) csvfile.close() Excel2CSV("C:\Users\R\Desktop\pythontestfile.xlsx","Sheet1","output.csv") </code></pre> <p>Double check that the arguments you are passing are all correct. </p>
1
2016-08-05T20:38:57Z
[ "python", "excel", "csv", "character-encoding", "file-conversion" ]
How to find the minimum element from two arrays in given time complexity in python
38,797,001
<p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p> <p>Like , if <code>A = [1,3,2,1]</code> &amp; <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A &amp; B. My code below works for this case, but for some cases it doesn't work. I don't know how to fix it. Please help! </p> <pre><code>def findMin(A, B): A.sort() B.sort() i = 0 for x in A: if i &lt; len(B) - 1 and B[i] &lt; x: i += 1 if x == B[i]: return x return -1 </code></pre> <p>Also, I want the worst case time complexity to be <code>O((N+M)*log(N+M))</code></p>
-2
2016-08-05T20:01:45Z
38,797,068
<p>Itertools chain aproach:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; A = [1,3,2,1] &gt;&gt;&gt; B = [4,2,5,3,2] &gt;&gt;&gt; min(x for x in itertools.chain(A, B) if x in A and x in B) 2 </code></pre>
1
2016-08-05T20:07:20Z
[ "python", "time-complexity", "minimum" ]
How to find the minimum element from two arrays in given time complexity in python
38,797,001
<p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p> <p>Like , if <code>A = [1,3,2,1]</code> &amp; <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A &amp; B. My code below works for this case, but for some cases it doesn't work. I don't know how to fix it. Please help! </p> <pre><code>def findMin(A, B): A.sort() B.sort() i = 0 for x in A: if i &lt; len(B) - 1 and B[i] &lt; x: i += 1 if x == B[i]: return x return -1 </code></pre> <p>Also, I want the worst case time complexity to be <code>O((N+M)*log(N+M))</code></p>
-2
2016-08-05T20:01:45Z
38,797,073
<pre><code>a = [1,2,3,4,5,6] b = [3,5,7,9] shared = (set(a).intersection(b)) shared = sorted(shared) print shared[0] </code></pre> <p>Returns <code>3</code></p>
2
2016-08-05T20:07:34Z
[ "python", "time-complexity", "minimum" ]
How to find the minimum element from two arrays in given time complexity in python
38,797,001
<p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p> <p>Like , if <code>A = [1,3,2,1]</code> &amp; <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A &amp; B. My code below works for this case, but for some cases it doesn't work. I don't know how to fix it. Please help! </p> <pre><code>def findMin(A, B): A.sort() B.sort() i = 0 for x in A: if i &lt; len(B) - 1 and B[i] &lt; x: i += 1 if x == B[i]: return x return -1 </code></pre> <p>Also, I want the worst case time complexity to be <code>O((N+M)*log(N+M))</code></p>
-2
2016-08-05T20:01:45Z
38,797,090
<p>I'd suggest using <code>set</code>s because it would be much faster due to its implementation. You just need to use <code>min</code> function over the intersection of two lists converted to <code>set</code>s. It's too easy, performant and doesn't require any sorting.</p> <pre><code>min(set(A) &amp; set(B)) </code></pre> <p>To get your initial algorithm working you just need to replace the first <code>if</code> by <code>while</code> loop:</p> <pre><code>while i &lt; len(B) - 1 and B[i] &lt; x: </code></pre>
0
2016-08-05T20:08:30Z
[ "python", "time-complexity", "minimum" ]
How to find the minimum element from two arrays in given time complexity in python
38,797,001
<p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p> <p>Like , if <code>A = [1,3,2,1]</code> &amp; <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A &amp; B. My code below works for this case, but for some cases it doesn't work. I don't know how to fix it. Please help! </p> <pre><code>def findMin(A, B): A.sort() B.sort() i = 0 for x in A: if i &lt; len(B) - 1 and B[i] &lt; x: i += 1 if x == B[i]: return x return -1 </code></pre> <p>Also, I want the worst case time complexity to be <code>O((N+M)*log(N+M))</code></p>
-2
2016-08-05T20:01:45Z
38,797,091
<p>You're throwing in sort there which you don't really need, find the intersection of the two using a set, then take the min...</p> <pre><code>&gt;&gt;&gt; A = [1,3,2,1] &gt;&gt;&gt; B = [4,2,5,3,2] &gt;&gt;&gt; min(set(A).intersection(B)) 2 </code></pre> <p>Which would make your function:</p> <pre><code>def findMin(A, B, default=-1): return min(set(A).intersection(B), default=default) </code></pre> <p>The default argument is what gets returned if there's no intersection between the two lists (you appear to have chosen -1), but that's a Python 3.x addition, if you're stuck with Python 2.x, you need to potentially handle it via exceptions, eg:</p> <pre><code>def findMin(A, B, default=-1): try: return min(set(A).intersection(B)) except ValueError: return default </code></pre> <p>As to complexity, its worst case is <code>O(len(A) * len(B))</code> for the intersection, although the average case is <code>O(min(len(A), len(B))</code> (see <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">time complexity</a>), then the <code>min</code> operation you need to add on top is <code>O(N)</code>.</p>
5
2016-08-05T20:08:30Z
[ "python", "time-complexity", "minimum" ]
How to find the minimum element from two arrays in given time complexity in python
38,797,001
<p>I have 2 arrays A and B. I'm trying to find the minimum from the elements which are common in the arrays A and B.</p> <p>Like , if <code>A = [1,3,2,1]</code> &amp; <code>B = [4,2,5,3,2]</code>, so it should return <code>2</code> because it is the minimum element which comes in both A &amp; B. My code below works for this case, but for some cases it doesn't work. I don't know how to fix it. Please help! </p> <pre><code>def findMin(A, B): A.sort() B.sort() i = 0 for x in A: if i &lt; len(B) - 1 and B[i] &lt; x: i += 1 if x == B[i]: return x return -1 </code></pre> <p>Also, I want the worst case time complexity to be <code>O((N+M)*log(N+M))</code></p>
-2
2016-08-05T20:01:45Z
38,797,617
<p>In case there's a big difference in size of the arrays faster way is to create a <code>set</code> out of smaller one for the <code>intersection</code>:</p> <pre><code>def find(a, b): small, large = sorted([a, b], key=len) return min(set(small).intersection(large), default=-1) </code></pre> <p>Comparison with <code>100000</code> and <code>10000</code> elements:</p> <pre><code>import random import timeit def find_no_sort(a, b): return min(set(a).intersection(b), default=-1) a = [random.randrange(0, 100000) for _ in range(100000)] random.shuffle(a) b = [random.randrange(0, 100000) for _ in range(10000)] random.shuffle(b) print('Sorted: ', timeit.timeit('find(a, b)', number=100, globals=globals())) print('Not sorted: ', timeit.timeit('find_no_sort(a, b)', number=100, globals=globals())) </code></pre> <p>Output (Python 3.5.1 on Windows 8):</p> <pre><code>Sorted: 0.8935029393830678 Not sorted: 1.7727491360998975 </code></pre>
0
2016-08-05T20:53:09Z
[ "python", "time-complexity", "minimum" ]
How to compare list and dictionary values and assign a variable
38,797,037
<p>I have a list with a certain amount of winners from fights, entered by the user e.g. <code>winners = ['Hunt', 'Nunes', 'Cormier']</code></p> <p>I then have a dictionary with each player's correct guess as values and their names as keys and my program then compares the list of winners with the values for each key and tells each player how many fights they guessed correctly</p> <pre><code>for name in player_dict: player_dict[name].sort() player_dict[name] = set(player_dict[name]) &amp; set(winners) wins = (len(player_dict[name])) print(name + ' guessed ' + str(wins) + ' fights correctly.') </code></pre> <p>What I want to be able to do is give each fight a value depending on how many people guessed correctly and then use this value to determine how much of the pot each player who correctly guessed the winner of that fight will get. </p> <p>EDIT: Here is the entirety of my code to help provide clarity</p> <pre><code>#! python3 #fight_gambler.py - a program that lets players gamble on fights with friends players = [] while len(players) &gt;= 0: name = input('Enter a name: ') players.append(name) if name == '': players.pop() break else: pass player_dict = {name: [] for name in players} #creates a key for each name with that name as the key print(player_dict) fight_amount = int(input('How many fights are there? ')) fight_number = 1 for name in player_dict: #adds fight winner prediction as values to each name fight_number = 1 while fight_number &lt;= fight_amount: answer = input(name + ', who will win fight ' + str(fight_number) + '? ') player_dict[name].append(answer) fight_number = fight_number + 1 fight_number = 1 winners = [] while fight_number &lt;= fight_amount: # creates a list of fight winners winner = input('Who won fight ' + str(fight_number) + '? ') winners.append(winner) fight_number = fight_number + 1 winners.sort() for name in player_dict: player_dict[name].sort() player_dict[name] = set(player_dict[name]) &amp; set(winners) wins = (len(player_dict[name])) print(name + ' guessed ' + str(wins) + ' fights correctly.') </code></pre>
0
2016-08-05T20:04:50Z
38,797,217
<p>The following calculates the number of <em>correct</em> guess' a player in the <code>players</code> dictionary has made. If so you can do this with the <code>intersection()</code> of a <code>list</code> with a <code>set</code> of <code>winners</code>. </p> <p>To add to this, a list of the winners' names is added to a running <code>total</code>, this is then converted to a <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">Counter</a> collection (<em>accepts an iterable and returns a <strong>key/value</strong> data structure that keeps count of occurrences of the same keys found in the list</em>). From this we can extrapolate the necessary guessing data. </p> <pre><code>from collections import Counter winners = set([['Hunt', 'Nunes', 'Cormier']) players = {'player1': ['Nunes', 'Cormier', 'test1', 'test2'], 'player2': ['Nunes','test1', 'test2','test3', 'test4'], 'player3' : ['Hunt', 'Nunes', 'Cormier']} total = [] for player, picks in players.iteritems(): inter = winners.intersection(picks) total.extend(inter) # Add to list of winner names. print player, 'guessed:', len(inter), 'fights correctly.' for fighter, guess in Counter(total).iteritems(): print fighter,'was guessed correctly',guess,'times.' if guess&gt;1 else 'time.' </code></pre> <p>or you could go for a more <strong>functional programming</strong> approach (<em>inspired by user: <a href="http://stackoverflow.com/users/3141234/alexander-momchliov"><strong>@AMomchilov's</strong></a> idea</em>).</p> <pre><code>players_num_correct_picks = dict((k, winners.intersection(v)) for (k, v) in players.items()) for player, picks in players_num_correct_picks.items(): print player, 'guessed:', len(picks), 'fights correctly.' total = Counter(item for sublist in players_num_correct_picks.values() for item in sublist) for fighter, guess in total.items(): print fighter,'was guessed correctly',guess,'times.' if guess&gt;1 else 'time.' </code></pre> <p><strong>Sample Output:</strong></p> <pre><code>&gt;&gt;&gt; player2 guessed: 1 fights correctly. &gt;&gt;&gt; player3 guessed: 3 fights correctly. &gt;&gt;&gt; player1 guessed: 2 fights correctly. &gt;&gt;&gt; Cormier was guessed correctly 2 times. &gt;&gt;&gt; Nunes was guessed correctly 3 times. &gt;&gt;&gt; Hunt was guessed correctly 1 time. </code></pre>
1
2016-08-05T20:19:03Z
[ "python", "list", "dictionary", "comparison" ]
Scroll tkinter ttk Entry text to the End in Python
38,797,116
<p>I am trying to create a GUI form using Python tkinter. For a ttk Entry widget, I want to set a default text. I do that using the insert() as shown below-</p> <pre><code>from tkinter import * from tkinter import ttk root = Tk() e = ttk.Entry(root, width=20) e.pack() e.insert(0, 'text greater than width of the widget') </code></pre> <p>The widget shows the beginning portion of the inserted text. Is there a way that I can make it scroll to the end of the inserted text by default?</p>
2
2016-08-05T20:10:38Z
38,797,670
<p>You can call the <code>xview</code> method to scroll a given index into view:</p> <pre><code>e.xview("end") </code></pre>
1
2016-08-05T20:58:08Z
[ "python", "tkinter" ]
Django Storages Boto Bad Digest
38,797,175
<p>I'm using S3 file storage through django-storages boto storage on Python 3. When I try to upload a file, I get this error:</p> <pre><code>boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Error&gt;&lt;Code&gt;BadDigest&lt;/Code&gt; &lt;Message&gt;The Content-MD5 you specified did not match what we received.&lt;/Message&gt; ... </code></pre> <p>The file I am trying to save is a file being downloaded with requests. The gist of it is:</p> <pre><code>import requests from django.core.files.base import ContentFile response = requests.get("http://example.com/some_file.pdf") document_contents = ContentFile(response.text) my_model.save("filename", document_contents) </code></pre> <p>What am I doing wrong?</p>
0
2016-08-05T20:15:35Z
38,797,176
<p>See this relevant boto issue: <a href="https://github.com/boto/boto/issues/2868" rel="nofollow">https://github.com/boto/boto/issues/2868</a></p> <p>Boto has some problems with string encodings in Python3. If you know the encoding, you Using <code>response.content</code> instead of <code>response.text</code> fixes the problem:</p> <pre><code>document_contents = ContentFile(response.content) </code></pre>
0
2016-08-05T20:15:35Z
[ "python", "django", "python-3.x", "amazon-s3", "django-storage" ]
running python files from ipython and passing an object in as the argument
38,797,177
<p><strong>The overall goal</strong></p> <p>I am trying to debug functions that I have written to analyze large data files. It takes too long to read the files into pandas dataframes for each debugging run. And so I am running an ipython console where I want to read the data in, then debug my functions. If I end the debugging session then I will still have the data read into dataframes in the ipython console. Jupyter notebook would be preferable, however it has no debugging functionality.</p> <p><strong>The question</strong></p> <p>How do I run the debugger on a python file from within a ipython console and then pass a python object into the file as an argument? </p>
0
2016-08-05T20:15:40Z
38,797,284
<p>Just use <a href="http://ipython.org/ipython-doc/rel-1.1.0/interactive/reference.html" rel="nofollow">IPython.embed()</a> where you're currently using <code>code.InteractiveConsole(globals()).interact('')</code>.</p> <p>Make sure you're importing IPython before you do that, though:</p> <pre><code>import IPython # lots of code # even more code IPython.embed() </code></pre> <p>You can also save some variables in IPython, so you don't have to run them again. You can refer to this <a class='doc-link' href="http://stackoverflow.com/documentation/ipython/3400/the-ipython-repl-shell/18167/store-variables-on-ipython#t=201608052028158649775">link</a>.</p>
0
2016-08-05T20:24:55Z
[ "python", "debugging", "pandas", "ipython" ]
hackerrank new year chaos code optimization
38,797,194
<p>I'm trying to optimize my solution for Hackerranks's 'New Year Chaos' problem. The gist of the problem goes like this (link to the problem <a href="https://www.hackerrank.com/challenges/new-year-chaos" rel="nofollow">here</a>): there's a queue of n people, labeled 1 through n, and each person can bribe the person directly in front of them to swap places and get closer to the front of the queue (in this case, index 0 of the list/array). Each person can only bribe a maximum of two times (and they cannot bribe someone who has already bribed them). You are given the order of the people after all of the bribes have taken place and your job is to determine how many bribes took place to get to that point. For example, if you were given [3, 2, 1] then the answer would be 3 bribes (person 3 bribed person 1, 2 and person 2 bribed person 1). My solution was, for each person i, count the number of people to the left of i that have a label greater than i (they would've had to bribe person i to get to the left of them). To complicate things (slightly), some of the test cases given would only be possible if someone bribed more than 2 times (ie [4, 1, 2, 3] - person 4 bribed person 3, then 2, then 1 to get to the front). If this is the case, simply output "Too chaotic". Anyway here's the code:</p> <pre><code># n is the number of people in the list # q is the order of the people after the bribery has taken place ex. [1, 3, 2, 5, 4] for i in range(1, n + 1): # for each person i in the list index = q.index(i) if i - index &gt; 3: # more than two bribes bribes = "Too chaotic" break for j in range(index): # for each number to the left of i, if greater than i, count it as a bribe if q[j] &gt; i: bribes = bribes + 1 print bribes </code></pre> <p>My problem is that the code times out with some of the larger test cases (you're only given so much time for each test case to run). How can I optimize the algorithm so that it doesn't time out? Should I be trying this problem in another language?</p> <p>Many thanks in advance for your assistance.</p>
0
2016-08-05T20:17:08Z
39,414,942
<p>There are two problems in your code.</p> <p>First, you should iterate the given array from end to the beginning, not the other way around. The reason is that if you iterate from the beginning, you need to iterate the whole array in the inner loop. But if you iterate from the last element, you just need to check left two numbers of each number to count the inversion. I think this is why your code "time out" on large test cases. </p> <p>Second, when you print out bribes at the last line, you should check if you "break out" from the outer loop, or it finished at <code>i == n</code>. Otherwise, it might print out "<code>Too chaotic</code>" and some bribes you already computed.</p>
0
2016-09-09T15:23:40Z
[ "python", "optimization" ]
How to turn off logging for favicon and robots in nginx for flask (python) apps
38,797,219
<p>I'm trying to find a way to turn off logging for favicon.ico and robots.txt in my <strong>NGINX</strong> web server powering a <strong>Flask (Python)</strong> app through <strong>uWSGI</strong>.</p> <p>So, the first part of my nginx config is:</p> <pre><code>location / { try_files $uri @app; } location @app { include uwsgi_params; uwsgi_pass unix:/srv/www/uwsgi.sock; } </code></pre> <p>Now, when I add (above the code block displayed above)</p> <pre><code>location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } </code></pre> <p>I get <strong>404 not found errors</strong> when I visit those URIs. Now when I remove the <strong>=</strong> sign in <strong>location = /...</strong> the URI does work and I see the favicon and robots file. But for some reason it still access logs those requests.</p> <p>What seems to be going on here?</p>
0
2016-08-05T20:19:11Z
38,797,743
<p><code>location</code> sections are not combined, try:</p> <pre><code>location = /favicon.ico { access_log off; log_not_found off; try_files $uri @app; } location = /robots.txt { access_log off; log_not_found off; try_files $uri @app; } </code></pre>
0
2016-08-05T21:04:14Z
[ "python", "nginx", "flask", "uwsgi" ]
get first and last values in a groupby
38,797,271
<p>I have a dataframe <code>df</code></p> <pre><code>df = pd.DataFrame(np.arange(20).reshape(10, -1), [['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd'], ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']], ['X', 'Y']) </code></pre> <p>How do I get the first and last rows, grouped by the first level of the index?</p> <p>I tried</p> <pre><code>df.groupby(level=0).agg(['first', 'last']).stack() </code></pre> <p>and got</p> <pre><code> X Y a first 0 1 last 6 7 b first 8 9 last 12 13 c first 14 15 last 16 17 d first 18 19 last 18 19 </code></pre> <p>This is so close to what I want. How can I preserve the level 1 index and get this instead:</p> <pre><code> X Y a a 0 1 d 6 7 b e 8 9 g 12 13 c h 14 15 i 16 17 d j 18 19 j 18 19 </code></pre>
7
2016-08-05T20:23:54Z
38,797,283
<h3>Option 1</h3> <pre><code>def first_last(df): return df.ix[[0, -1]] df.groupby(level=0, group_keys=False).apply(first_last) </code></pre> <p><a href="http://i.stack.imgur.com/PBecd.png" rel="nofollow"><img src="http://i.stack.imgur.com/PBecd.png" alt="enter image description here"></a></p> <hr> <h3>Option 2 - only works if index is unique</h3> <pre><code>idx = df.index.to_series().groupby(level=0).agg(['first', 'last']).stack() df.loc[idx] </code></pre> <hr> <h3>Option 3 - per notes below, this only makes sense when there are no NAs</h3> <p>I also abused the <code>agg</code> function. The code below works, but is far uglier.</p> <pre><code>df.reset_index(1).groupby(level=0).agg(['first', 'last']).stack() \ .set_index('level_1', append=True).reset_index(1, drop=True) \ .rename_axis([None, None]) </code></pre> <hr> <h1>Note</h1> <p>per @unutbu: <code>agg(['first', 'last'])</code> take the firs non-na values.</p> <p>I interpreted this as, it must then be necessary to run this column by column. Further, forcing index level=1 to align may not even make sense.</p> <p>Let's include another test</p> <pre><code>df = pd.DataFrame(np.arange(20).reshape(10, -1), [list('aaaabbbccd'), list('abcdefghij')], list('XY')) df.loc[tuple('aa'), 'X'] = np.nan </code></pre> <hr> <pre><code>def first_last(df): return df.ix[[0, -1]] df.groupby(level=0, group_keys=False).apply(first_last) </code></pre> <p><a href="http://i.stack.imgur.com/MQNBt.png" rel="nofollow"><img src="http://i.stack.imgur.com/MQNBt.png" alt="enter image description here"></a></p> <pre><code>df.reset_index(1).groupby(level=0).agg(['first', 'last']).stack() \ .set_index('level_1', append=True).reset_index(1, drop=True) \ .rename_axis([None, None]) </code></pre> <p><a href="http://i.stack.imgur.com/34k3s.png" rel="nofollow"><img src="http://i.stack.imgur.com/34k3s.png" alt="enter image description here"></a></p> <p>Sure enough! This second solution is taking the first valid value in column X. It is now nonsensical to have forced that value to align with the index a.</p>
8
2016-08-05T20:24:39Z
[ "python", "pandas", "dataframe", "group-by" ]
Looping through Wagtail Streamfield Items
38,797,281
<p>I'm trying to create an index page containing links to multiple photo galleries in Wagtail. The GalleryIndexPage model looks like this:</p> <pre><code>class GalleryIndexPage(Page): subpage_types = ['home.GalleryPage'] gallery_thumb = StreamField ([ ('cover_photo', ImageChooserBlock()), ('title', blocks.CharBlock()), ('link', URLBlock()), ]) content_panels = Page.content_panels + [ StreamFieldPanel('gallery_thumb'), ] </code></pre> <p>I'm having difficulty rendering it into the template with a "gallery-item" class around each set of data. I realize that it is currently looping through and adding a class of "gallery-item" to each block inside the Streamfield, rather than around the whole Streamfield set. Here is my template code:</p> <pre><code>&lt;div class="photo-gallery"&gt; {% for block in self.gallery_thumb %} &lt;div class="gallery-item"&gt; {% if block.block_type == 'cover_photo' %} &lt;div class="thumb"&gt; {% image block.value fill-200x150 %} &lt;/div&gt; {% endif %} {% if block.block_type == 'title' %} &lt;div class="title"&gt; &lt;p&gt;{{ block.value }}&lt;/p&gt; &lt;/div&gt; {% endif %} {% if block.block_type == 'link' %} &lt;div class="link"&gt; &lt;a href="{{ block.value }}"&gt;View Gallery&lt;/a&gt; &lt;/div&gt; {% endif %} &lt;/div&gt; {% endfor %} </code></pre> <p></p> <p>Is there another way I should approach this?</p> <p>EDIT: I have added a StructBlock within my StreamField like so:</p> <pre><code>class GalleryIndexPage(Page): subpage_types = ['home.GalleryPage'] gallery = StreamField ([ ('gallery_item', blocks.StructBlock([ ('cover_photo', ImageChooserBlock()), ('title', blocks.CharBlock()), ('link', URLBlock()), ], icon='user')) ]) content_panels = Page.content_panels + [ StreamFieldPanel('gallery'), ] </code></pre> <p>I'm not sure how to access these values in my template? Here is what I have so far: </p> <pre><code> &lt;div class="photo-gallery"&gt; {% for block in self.gallery %} &lt;div class="gallery-item"&gt; &lt;div class="thumb"&gt; {% image self.cover_photo width-200 %} &lt;/div&gt; &lt;div class="title"&gt; &lt;p&gt;{{ self.title }}&lt;/p&gt; &lt;/div&gt; &lt;div class="link"&gt; &lt;a href="{{ self.link }}"&gt;&gt;&gt; View Gallery&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; </code></pre>
0
2016-08-05T20:24:30Z
38,797,557
<p>It seems like what you want is a single gallery_item block that consists of an image, title, and link. You can do this by creating your own block type out of simpler block types. See <a href="http://docs.wagtail.io/en/v1.5.3/topics/streamfield.html#structural-block-types" rel="nofollow">http://docs.wagtail.io/en/v1.5.3/topics/streamfield.html#structural-block-types</a></p> <p>You could do something like this:</p> <pre><code>('gallery_item', blocks.StructBlock([ ('title', blocks.CharBlock()), ('link', blocks.URLBlock()), ('image', ImageChooserBlock()), ], icon='xyz')) </code></pre> <p>You can also create this as a Python class, which is what I usually prefer to do, this is covered in the last part of the section I linked to above.</p> <p>You can create your own template for this block.</p> <p>Within the template, each block has two properties, <code>value</code> and <code>block_type</code>. So you would access, for example, the <code>title</code> with <code>{{ self.title.value }}</code>.</p> <p>See <a href="http://docs.wagtail.io/en/v1.5.3/topics/streamfield.html#template-rendering" rel="nofollow">http://docs.wagtail.io/en/v1.5.3/topics/streamfield.html#template-rendering</a></p>
0
2016-08-05T20:47:58Z
[ "python", "django", "templates", "wagtail", "wagtail-streamfield" ]
Looping through Wagtail Streamfield Items
38,797,281
<p>I'm trying to create an index page containing links to multiple photo galleries in Wagtail. The GalleryIndexPage model looks like this:</p> <pre><code>class GalleryIndexPage(Page): subpage_types = ['home.GalleryPage'] gallery_thumb = StreamField ([ ('cover_photo', ImageChooserBlock()), ('title', blocks.CharBlock()), ('link', URLBlock()), ]) content_panels = Page.content_panels + [ StreamFieldPanel('gallery_thumb'), ] </code></pre> <p>I'm having difficulty rendering it into the template with a "gallery-item" class around each set of data. I realize that it is currently looping through and adding a class of "gallery-item" to each block inside the Streamfield, rather than around the whole Streamfield set. Here is my template code:</p> <pre><code>&lt;div class="photo-gallery"&gt; {% for block in self.gallery_thumb %} &lt;div class="gallery-item"&gt; {% if block.block_type == 'cover_photo' %} &lt;div class="thumb"&gt; {% image block.value fill-200x150 %} &lt;/div&gt; {% endif %} {% if block.block_type == 'title' %} &lt;div class="title"&gt; &lt;p&gt;{{ block.value }}&lt;/p&gt; &lt;/div&gt; {% endif %} {% if block.block_type == 'link' %} &lt;div class="link"&gt; &lt;a href="{{ block.value }}"&gt;View Gallery&lt;/a&gt; &lt;/div&gt; {% endif %} &lt;/div&gt; {% endfor %} </code></pre> <p></p> <p>Is there another way I should approach this?</p> <p>EDIT: I have added a StructBlock within my StreamField like so:</p> <pre><code>class GalleryIndexPage(Page): subpage_types = ['home.GalleryPage'] gallery = StreamField ([ ('gallery_item', blocks.StructBlock([ ('cover_photo', ImageChooserBlock()), ('title', blocks.CharBlock()), ('link', URLBlock()), ], icon='user')) ]) content_panels = Page.content_panels + [ StreamFieldPanel('gallery'), ] </code></pre> <p>I'm not sure how to access these values in my template? Here is what I have so far: </p> <pre><code> &lt;div class="photo-gallery"&gt; {% for block in self.gallery %} &lt;div class="gallery-item"&gt; &lt;div class="thumb"&gt; {% image self.cover_photo width-200 %} &lt;/div&gt; &lt;div class="title"&gt; &lt;p&gt;{{ self.title }}&lt;/p&gt; &lt;/div&gt; &lt;div class="link"&gt; &lt;a href="{{ self.link }}"&gt;&gt;&gt; View Gallery&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/div&gt; </code></pre>
0
2016-08-05T20:24:30Z
38,833,620
<p>I was able to access the values of the StructBlock in my template using this code: </p> <pre><code>&lt;div class="photo-gallery"&gt; {% for block in self.gallery %} &lt;div class="gallery-item"&gt; &lt;div class="thumb"&gt; {% image block.value.cover_photo fill-200x150 %} &lt;/div&gt; &lt;div class="title"&gt; &lt;p&gt;{{ block.value.title }}&lt;/p&gt; &lt;/div&gt; &lt;div class="link"&gt; &lt;a href="{{ block.value.link }}"&gt;&gt;&gt;View Gallery&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} </code></pre> <p></p> <p>Thanks so much for your assistance!</p>
0
2016-08-08T15:53:24Z
[ "python", "django", "templates", "wagtail", "wagtail-streamfield" ]
Openpyxl 2.3.2 Change Tab Color/Fit To Page Properties?
38,797,468
<p>I am trying to modify an excel spreadsheet to alter the colors of the tabs using Openpyxl 2.3.2 (using Anaconda), but can't seem to get the code to work. I am using the following code, where bdws is a worksheet already in the workbook, and bdws2 is a worksheet I added later. </p> <p>I can't get either of the sheets to change color.</p> <p>As well, I can't seem to adjust other page properties like <code>fitToPage</code>, using the same worksheets. Just wondering if anyone might know why that is.</p> <pre><code>bdwb = load_workbook(checkFileName(finalBDFileName)) bdws = bdwb[finalBDSheetName] bdws.sheet_properties.tabcolor ='FFFF00' bdws.sheet_properties.pageSetUpPr.fitToPage = True bdws2.sheet_properties.tabcolor = 'FF00FF' bdws2.sheet_properties.pageSetUpPr.fitToPage = True bdwb.save("new bd.xlsx") </code></pre> <p>Thank you.</p>
0
2016-08-05T20:40:14Z
39,001,045
<p>You just need to capitalize your Color :)</p> <pre><code>bdws.sheet_properties.tabColor ='FFFF00' bdws.sheet_properties.pageSetUpPr.fitToPage = True bdws2.sheet_properties.tabColor = 'FF00FF' bdws2.sheet_properties.pageSetUpPr.fitToPage = True </code></pre> <p>should do it for you.</p>
1
2016-08-17T15:44:57Z
[ "python", "openpyxl" ]
un-slicing numpy arrays
38,797,494
<p>Given a sliced numpy array as follows:</p> <pre><code>b = [a[..., i] for i in a.shape[-1]] </code></pre> <p>What is the most simple way I can recreate <code>a</code> from <code>b</code>?</p> <p>Something like:</p> <pre><code>for i in range(a.shape[-1]): c[..., i] = b[i] </code></pre>
0
2016-08-05T20:42:29Z
38,797,744
<p>Instead of that list comprehension, your original operation should have been</p> <pre><code>b = numpy.rollaxis(a, axis=-1) </code></pre> <p>which produces a view of <code>a</code> as a new array instead of a list of arrays.</p> <p>The reverse operation is</p> <pre><code>c = numpy.rollaxis(b, axis=0, start=b.ndim) </code></pre>
1
2016-08-05T21:04:22Z
[ "python", "numpy" ]
TypeError: 'NoneType' does not support the buffer interface: when Transforming XML using XSLT
38,797,546
<p>Related to <a href="http://stackoverflow.com/questions/38248286/changing-loop-to-organize-and-reduce-xml-output">earlier question</a>, I want to thank @Parfait for helping me develop an XSLT foundation for my project with the current XSLT code being used. However I am getting an error when I run the python Module it says.</p> <pre class="lang-none prettyprint-override"><code>File "nsnindex.py", line 17, in &lt;module&gt; xmlfile.write(tree_out) TypeError: 'NoneType' does not support the buffer interface. </code></pre> <p>The overall plan is for XPATH to go straight to the third child node </p> <pre><code>&lt;national_stock_number_cross_reference_index&gt; </code></pre> <p>and use the data in that section to output to a new file. At the moment, python spits out all of the data in one blob, without tags, and gives me the error above.</p> <h1>XML Input</h1> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;lsar030 xsi:schemaLocation="places" xmlns="place2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;head&gt; &lt;requester&gt;Guy&lt;/requester&gt; &lt;time&gt;12:23:44 PM&lt;/time&gt; &lt;date&gt;Aug 2, 2016&lt;/date&gt; &lt;eiac&gt;ABC&lt;/eiac&gt; &lt;item_name&gt;Thing&lt;/item_name&gt; &lt;start_lcn&gt;start34&lt;/start_lcn&gt; &lt;alc&gt;00&lt;/alc&gt; &lt;lcn_type&gt;P&lt;/lcn_type&gt; &lt;stop_lcn&gt;AA01AA13AB&lt;/stop_lcn&gt; &lt;useable_on_code&gt;ABC&lt;/useable_on_code&gt; &lt;technical_manual_code&gt;000&lt;/technical_manual_code&gt; &lt;technical_manual_number&gt;15241&lt;/technical_manual_number&gt; &lt;report_format&gt;STUFF&lt;/report_format&gt; &lt;kit_option&gt;45&lt;/kit_option&gt; &lt;part_number_cross_reference_index&gt;true&lt;/part_number_cross_reference_index&gt; &lt;national_stock_number_cross_reference_index&gt;true&lt;/national_stock_number_cross_reference_index&gt; &lt;reference_designation_cross_reference_index&gt;false&lt;/reference_designation_cross_reference_index&gt; &lt;figure_item_number_cross_reference_index&gt;false&lt;/figure_item_number_cross_reference_index&gt; &lt;include_drawings_in_output&gt;No&lt;/include_drawings_in_output&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 204&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 205&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 208&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 207&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;11&lt;/technical_manual_functional_group_code&gt; &lt;header&gt; FIGURE 501 &lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;12&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 505&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 201&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 202&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 203/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 200&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;865/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 503&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;865&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 502&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;865&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 504&lt;/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;technical_manual_functional_group_code_header&gt; &lt;section&gt;2&lt;/section&gt; &lt;technical_manual_functional_group_code&gt;132&lt;/technical_manual_functional_group_code&gt; &lt;header&gt;FIGURE 206/header&gt; &lt;/technical_manual_functional_group_code_header&gt; &lt;baseline_comparison&gt;false&lt;/baseline_comparison&gt; &lt;usmc_option&gt;No&lt;/usmc_option&gt; &lt;/head&gt; &lt;body&gt; &lt;repair_parts_list&gt; &lt;repair_parts_fgc_group&gt; &lt;repair_part&gt; &lt;item_number&gt;1&lt;/item_number&gt; &lt;smr&gt;PAFDD&lt;/smr&gt; &lt;cage_code&gt;53711&lt;/cage_code&gt; &lt;reference_number&gt;7102539&lt;/reference_number&gt; &lt;technical_manual_indenture_code&gt;1&lt;/technical_manual_indenture_code&gt; &lt;item_name&gt;DINGLE&lt;/item_name&gt; &lt;useable_on_code&gt;EAU&lt;/useable_on_code&gt; &lt;fully_effective&gt;true&lt;/fully_effective&gt; &lt;quantity&gt;1&lt;/quantity&gt; &lt;qpei&gt;1&lt;/qpei&gt; &lt;figure_number&gt;101&lt;/figure_number&gt; &lt;technical_manual_functional_group_code&gt;0000000000A&lt;/technical_manual_functional_group_code&gt; &lt;federal_supply_classification&gt;1234&lt;/federal_supply_classification&gt; &lt;national_item_identification_number&gt;000000000&lt;/national_item_identification_number&gt; &lt;system_or_end_item_provisioning_contract_control_number&gt;A1ABC&lt;/system_or_end_item_provisioning_contract_control_number&gt; &lt;plisn&gt;ABCD&lt;/plisn&gt; &lt;effectivity_flag&gt;false&lt;/effectivity_flag&gt; &lt;effectivity_label&gt;BERRY&lt;/effectivity_label&gt; &lt;/repair_part&gt; &lt;/repair_parts_fgc_group&gt; &lt;/repair_parts_list&gt; &lt;part_number_cross_reference_index&gt; &lt;work_package_sequence_number&gt;0005&lt;/work_package_sequence_number&gt; &lt;part_number_cross_reference&gt; &lt;reference_number&gt;XXXXXX&lt;/reference_number&gt; &lt;figure_number&gt;1&lt;/figure_number&gt; &lt;item_number&gt;10&lt;/item_number&gt; &lt;/part_number_cross_reference&gt; &lt;/part_number_cross_reference_index&gt; &lt;national_stock_number_cross_reference_index&gt; &lt;work_package_sequence_number&gt;0001&lt;/work_package_sequence_number&gt; &lt;national_stock_number_cross_reference&gt; &lt;federal_supply_classification&gt;1234&lt;/federal_supply_classification&gt; &lt;national_item_identification_number&gt;000000000&lt;/national_item_identification_number&gt; &lt;figure_number&gt;1&lt;/figure_number&gt; &lt;item_number&gt;1&lt;/item_number&gt; &lt;/national_stock_number_cross_reference&gt;&lt;national_stock_number_cross_reference&gt; &lt;federal_supply_classification&gt;1234&lt;/federal_supply_classification&gt; &lt;national_item_identification_number&gt;000000000&lt;/national_item_identification_number&gt; &lt;figure_number&gt;2&lt;/figure_number&gt; &lt;item_number&gt;4&lt;/item_number&gt; &lt;/national_stock_number_cross_reference&gt;&lt;national_stock_number_cross_reference&gt; &lt;federal_supply_classification&gt;1234&lt;/federal_supply_classification&gt; &lt;national_item_identification_number&gt;000000000&lt;/national_item_identification_number&gt; &lt;figure_number&gt;3&lt;/figure_number&gt; &lt;item_number&gt;2&lt;/item_number&gt; &lt;/national_stock_number_cross_reference&gt;&lt;national_stock_number_cross_reference&gt; &lt;federal_supply_classification&gt;1235&lt;/federal_supply_classification&gt; &lt;national_item_identification_number&gt;111111111&lt;/national_item_identification_number&gt; &lt;figure_number&gt;1&lt;/figure_number&gt; &lt;item_number&gt;1&lt;/item_number&gt; &lt;/national_stock_number_cross_reference&gt;&lt;national_stock_number_cross_reference&gt; &lt;federal_supply_classification&gt;1235&lt;/federal_supply_classification&gt; &lt;national_item_identification_number&gt;111111111&lt;/national_item_identification_number&gt; &lt;figure_number&gt;2&lt;/figure_number&gt; &lt;item_number&gt;3&lt;/item_number&gt; &lt;/national_stock_number_cross_reference&gt; &lt;/national_stock_number_cross_reference_index&gt;&lt;national_stock_number_cross_reference&gt; &lt;federal_supply_classification&gt;1236&lt;/federal_supply_classification&gt; &lt;national_item_identification_number&gt;212121212&lt;/national_item_identification_number&gt; &lt;figure_number&gt;2&lt;/figure_number&gt; &lt;item_number&gt;3&lt;/item_number&gt; &lt;/national_stock_number_cross_reference&gt; &lt;/national_stock_number_cross_reference_index&gt; &lt;/body&gt; &lt;/lsar030&gt; </code></pre> <h1>XSLT Code:</h1> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output method="xml" encoding="UTF-8" indent="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:key name="numkey" match="lsar030/body/national_stock_number_cross_reference_index/national_stock_number_cross_reference" use="concat(federal_supply_classification, national_item_identification_number)"/&gt; &lt;xsl:template match="lsar030/body/national_stock_number_cross_reference_index"&gt; &lt;xsl:apply-templates select="national_stock_number_cross_reference[generate-id() = generate-id(key('numkey', concat(federal_supply_classification, national_item_identification_number))[1])]"/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="lsar030/body/national_stock_number_cross_reference_index/national_stock_number_cross_reference"&gt; &lt;nsnindxrow&gt; &lt;nsn&gt; &lt;fsc&gt;&lt;xsl:value-of select="federal_supply_classification"/&gt;&lt;/fsc&gt; &lt;niin&gt;&lt;xsl:value-of select="national_item_identification_number"/&gt;&lt;/niin&gt; &lt;/nsn&gt; &lt;xsl:for-each select="key('numkey', concat(federal_supply_classification, national_item_identification_number))"&gt; &lt;callout&gt; &lt;xsl:attribute name="assocfig"&gt;&lt;xsl:value-of select="concat('fig', figure_number)"/&gt;&lt;/xsl:attribute&gt; &lt;xsl:attribute name="label"&gt;&lt;xsl:value-of select="item_number"/&gt;&lt;/xsl:attribute&gt; &lt;/callout&gt; &lt;/xsl:for-each&gt; &lt;/nsnindxrow&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <h1>Python Code:</h1> <pre><code>import lxml.etree as ET # LOAD XML AND XSL FILES dom = ET.parse('lsar030.xml') xslt = ET.parse('XSLTScript.xsl') # TRANSFORM SOURCE transform = ET.XSLT(xslt) newdom = transform(dom) print(newdom) # OUTPUT TRANSFORMED TREE TO STRING tree_out = ET.tostring(newdom, encoding='UTF-8', pretty_print=True, xml_declaration=True) # OUTPUT STRING TO FILE xmlfile = open('Output.xml', 'wb') xmlfile.write(tree_out) xmlfile.close() </code></pre> <h1>OUTPUT</h1> <pre><code>&lt;nsnindxrow&gt; &lt;nsn&gt; &lt;fsc&gt;5310&lt;/fsc&gt; &lt;niin&gt;00-880-5978&lt;/niin&gt; &lt;/nsn&gt; &lt;callout assocfig="fig700" label="34"&gt; &lt;callout assocfig="fig701" label="10"&gt; &lt;callout assocfig="fig703" label="9"&gt; &lt;/nsnindxrow&gt; </code></pre> <p>Anyone know what I am doing wrong? is it my XPATH? @Parfait 's program worked when the root tag was just <code>&lt;national_stock_number_cross_reference_index&gt;</code>, but it stopped working properly once I changed the path to match the more complex file.</p>
2
2016-08-05T20:47:00Z
38,798,481
<p>Two issues in XML emerge affecting the XSLT transformation: </p> <ol> <li>An undeclared namespace prefix (<code>xmlns="place2"</code>) where the <em>xmlns</em> special attribute in header does not have a colon separated identifier. Therefore, XSLT must declare a prefix.</li> <li>Additional element levels where parent nodes and their siblings above <code>national_stock_number_cross_reference_index</code> element must be parsed out. Therefore, XSLT must use additional templates.</li> </ol> <p>Consider following adjusted XSLT, declaring a <code>doc</code> prefix which is prefixed in all other XPath expressions. Use same Python code to process.</p> <p><strong>XSLT</strong></p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:doc="place2" exclude-result-prefixes="doc"&gt; &lt;xsl:output method="xml" encoding="UTF-8" indent="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:key name="numkey" match="doc:national_stock_number_cross_reference" use="concat(doc:federal_supply_classification, doc:national_item_identification_number)"/&gt; &lt;xsl:template match="/doc:lsar030"&gt; &lt;xsl:apply-templates select="doc:head"/&gt; &lt;xsl:apply-templates seect="doc:body"/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="doc:head"/&gt; &lt;xsl:template match="doc:body"&gt; &lt;xsl:apply-templates select="doc:national_stock_number_cross_reference_index"/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="doc:national_stock_number_cross_reference_index"&gt; &lt;nsnindxrows&gt; &lt;xsl:apply-templates select="doc:national_stock_number_cross_reference[generate-id() = generate-id(key('numkey', concat(doc:federal_supply_classification, doc:national_item_identification_number))[1])]"/&gt; &lt;nsnindxrows&gt; &lt;/xsl:template&gt; &lt;xsl:template match="doc:national_stock_number_cross_reference"&gt; &lt;nsnindxrow&gt; &lt;nsn&gt; &lt;fsc&gt;&lt;xsl:value-of select="doc:federal_supply_classification"/&gt;&lt;/fsc&gt; &lt;niin&gt;&lt;xsl:value-of select="doc:national_item_identification_number"/&gt;&lt;/niin&gt; &lt;/nsn&gt; &lt;xsl:for-each select="key('numkey', concat(doc:federal_supply_classification, doc:national_item_identification_number))"&gt; &lt;callout&gt; &lt;xsl:attribute name="assocfig"&gt;&lt;xsl:value-of select="concat('fig', doc:figure_number)"/&gt;&lt;/xsl:attribute&gt; &lt;xsl:attribute name="label"&gt;&lt;xsl:value-of select="doc:item_number"/&gt;&lt;/xsl:attribute&gt; &lt;/callout&gt; &lt;/xsl:for-each&gt; &lt;/nsnindxrow&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>Output</strong> </p> <p><em>(unlike earlier question's XML, only one callout renders due to this XML's one pairing of <code>&lt;federal_supply_classification&gt;</code> and <code>&lt;national_item_identification_number&gt;</code>)</em>.</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;nsnindxrows&gt; &lt;nsnindxrow&gt; &lt;nsn&gt; &lt;fsc&gt;1234&lt;/fsc&gt; &lt;niin&gt;000000000&lt;/niin&gt; &lt;/nsn&gt; &lt;callout assocfig="fig1" label="1"/&gt; &lt;callout assocfig="fig2" label="4"/&gt; &lt;callout assocfig="fig3" label="2"/&gt; &lt;/nsnindxrow&gt; &lt;nsnindxrow&gt; &lt;nsn&gt; &lt;fsc&gt;1235&lt;/fsc&gt; &lt;niin&gt;111111111&lt;/niin&gt; &lt;/nsn&gt; &lt;callout assocfig="fig1" label="1"/&gt; &lt;callout assocfig="fig2" label="3"/&gt; &lt;/nsnindxrow&gt; &lt;nsnindxrow&gt; &lt;nsn&gt; &lt;fsc&gt;1236&lt;/fsc&gt; &lt;niin&gt;212121212&lt;/niin&gt; &lt;/nsn&gt; &lt;callout assocfig="fig2" label="3"/&gt; &lt;/nsnindxrow&gt; &lt;/nsnindxrows&gt; </code></pre>
1
2016-08-05T22:19:18Z
[ "python", "xml", "xslt", "xpath", "nonetype" ]
if-if-else and if-elif-else statement
38,797,578
<p>Why is the 'else' statement getting printed even if a correct choice is picked? </p> <pre><code> ch=0 print"Do you need Ice-Cream?" ans=raw_input() if ans=='y': print"Pick a flavor" ch=raw_input() # ch is a string if ch=='1': print"Vanilla" if ch=='2': print"Chocolate" if ch=='3': print"Strawberry" if ch=='4': print"Kiwi" if ch=='5': print"orange" if ch=='6': print"mango" if ch=='7': print"pineapple" if ch=='8': print"grapes" print"You are done picking up a flavor, pay now" if ans=='n': print"Good, you can go!" else: print"wrong choice" </code></pre> <p>Output is printing "wrong choice" even if a valid choice is selected.</p>
-2
2016-08-05T20:49:17Z
38,797,592
<p>Because the if-statement checking "y" and the second if-statement checking "n" are two different. The else is only connected to the second if-statement with the "n"-check. You want to have the outermost statements like</p> <pre><code>if "y": .... elif "n": .... else: .... </code></pre>
5
2016-08-05T20:51:01Z
[ "python", "if-statement" ]
if-if-else and if-elif-else statement
38,797,578
<p>Why is the 'else' statement getting printed even if a correct choice is picked? </p> <pre><code> ch=0 print"Do you need Ice-Cream?" ans=raw_input() if ans=='y': print"Pick a flavor" ch=raw_input() # ch is a string if ch=='1': print"Vanilla" if ch=='2': print"Chocolate" if ch=='3': print"Strawberry" if ch=='4': print"Kiwi" if ch=='5': print"orange" if ch=='6': print"mango" if ch=='7': print"pineapple" if ch=='8': print"grapes" print"You are done picking up a flavor, pay now" if ans=='n': print"Good, you can go!" else: print"wrong choice" </code></pre> <p>Output is printing "wrong choice" even if a valid choice is selected.</p>
-2
2016-08-05T20:49:17Z
38,797,597
<p><code>ans</code> isn't <code>'n'</code> so the <code>else</code> clause fires. You probably want an <code>elif</code>:</p> <pre><code>if ans == 'y': ... elif ans == 'n': ... else: ... </code></pre>
1
2016-08-05T20:51:23Z
[ "python", "if-statement" ]
if-if-else and if-elif-else statement
38,797,578
<p>Why is the 'else' statement getting printed even if a correct choice is picked? </p> <pre><code> ch=0 print"Do you need Ice-Cream?" ans=raw_input() if ans=='y': print"Pick a flavor" ch=raw_input() # ch is a string if ch=='1': print"Vanilla" if ch=='2': print"Chocolate" if ch=='3': print"Strawberry" if ch=='4': print"Kiwi" if ch=='5': print"orange" if ch=='6': print"mango" if ch=='7': print"pineapple" if ch=='8': print"grapes" print"You are done picking up a flavor, pay now" if ans=='n': print"Good, you can go!" else: print"wrong choice" </code></pre> <p>Output is printing "wrong choice" even if a valid choice is selected.</p>
-2
2016-08-05T20:49:17Z
38,797,605
<p>It appears that you're conflating your series of <code>if</code>s with a series of <code>if</code>-<code>elifs</code>. </p> <p>Note that this:</p> <pre><code>if cond0: ... if cond1: ... else: bar() </code></pre> <p>is <em>not</em> the same as:</p> <pre><code>if cond0: ... elif cond1: ... else: bar() </code></pre> <p>If <code>cond0</code> is <code>True</code>, then the former will call <code>bar()</code>, while the latter will not. In the former, it is just an <code>if</code> followed by a <em>completely separate</em> <code>if-else</code>.</p> <p>It might help to write the former like this:</p> <pre><code>if cond0: ... # Note spacing here, emphasizing that the above construct is separate from the one below. if cond1: ... else: bar() </code></pre>
2
2016-08-05T20:52:00Z
[ "python", "if-statement" ]
if-if-else and if-elif-else statement
38,797,578
<p>Why is the 'else' statement getting printed even if a correct choice is picked? </p> <pre><code> ch=0 print"Do you need Ice-Cream?" ans=raw_input() if ans=='y': print"Pick a flavor" ch=raw_input() # ch is a string if ch=='1': print"Vanilla" if ch=='2': print"Chocolate" if ch=='3': print"Strawberry" if ch=='4': print"Kiwi" if ch=='5': print"orange" if ch=='6': print"mango" if ch=='7': print"pineapple" if ch=='8': print"grapes" print"You are done picking up a flavor, pay now" if ans=='n': print"Good, you can go!" else: print"wrong choice" </code></pre> <p>Output is printing "wrong choice" even if a valid choice is selected.</p>
-2
2016-08-05T20:49:17Z
38,797,614
<p>The <code>else</code> in this chunk of code is only referring to the <code>if ans=='n'</code>.</p> <p>It's not taking into account your first if statement. You're going to want to change it to this</p> <pre><code>elif ans=='n': print"Good, you can go!" else: print"wrong choice" </code></pre>
1
2016-08-05T20:52:45Z
[ "python", "if-statement" ]
if-if-else and if-elif-else statement
38,797,578
<p>Why is the 'else' statement getting printed even if a correct choice is picked? </p> <pre><code> ch=0 print"Do you need Ice-Cream?" ans=raw_input() if ans=='y': print"Pick a flavor" ch=raw_input() # ch is a string if ch=='1': print"Vanilla" if ch=='2': print"Chocolate" if ch=='3': print"Strawberry" if ch=='4': print"Kiwi" if ch=='5': print"orange" if ch=='6': print"mango" if ch=='7': print"pineapple" if ch=='8': print"grapes" print"You are done picking up a flavor, pay now" if ans=='n': print"Good, you can go!" else: print"wrong choice" </code></pre> <p>Output is printing "wrong choice" even if a valid choice is selected.</p>
-2
2016-08-05T20:49:17Z
38,797,798
<p>You have two conditions not one.</p> <ol> <li><p>The first condition checks <code>ans</code> against <code>'y'</code>.</p> <p>If <code>ans</code> is <code>'y'</code> the user gets to input an integer 1-8 and the appropriate string will be printed to the console. Processing then moves to the second condition (#2).</p> <p>If <code>ans</code> is not <code>'y'</code> then the user dose not give any input and processing moves to the second condition (#2).</p></li> <li><p>The second condition checks <code>ans</code> against <code>'n'</code>.</p> <p>If <code>ans</code> is <code>'n'</code> then "Good, you can go!" is printed to the console and processing continues skipping the <code>else</code> block. </p> <p>If <code>ans</code> is not <code>'n'</code> (which would be the case that user entered <code>'y'</code>) then the <code>else</code> block is executed printing "wrong choice" to the console.</p></li> </ol> <p>What is happening is you have your logic setup that any input other than <code>'n'</code> will print "wrong choice" eventually. You want a single decision from the users initial input. Currently your logic makes two. </p> <p>Use the <code>if elif else</code> construct.</p>
0
2016-08-05T21:09:24Z
[ "python", "if-statement" ]
How to host flower on a remote machine that can also be accessed over the internet
38,797,696
<p>I am trying to run <code>flower</code> on a remote ubuntu server. However, I am unsure on what address/port to run it on so that other people can login (I have the basic auth set up) and check their <code>celery</code> workers. The ubuntu server is actually an EC2 instance, so am I supposed to use its private or public ip address? Do I just open any standard port? In their docs, they use their example setup with <a href="http://localhost/5555" rel="nofollow">http://localhost/5555</a> but I do not think that will work if <code>flower</code> will be running on a remote server. Any advice?</p>
-1
2016-08-05T20:59:56Z
38,797,858
<p>Flower runs on 5555 by default- which port are you running it on? The private IP is only available if the requests are coming from INSIDE your amazon network, so probably public.</p> <p>So, if my guesses are right, you want to create an AWS security rule allowing traffic from "anywhere" to port 5555 and apply that to your instance, and then access that instance using its public ip like <a href="http://50.31.10.99:5555" rel="nofollow">http://50.31.10.99:5555</a></p>
1
2016-08-05T21:15:45Z
[ "python", "celery", "flower" ]
Algorithm to match arrays of occurrences by time
38,797,806
<p>Let's say that there's a "master" array of times with these values:</p> <pre><code>master = [1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0] </code></pre> <p>I want to find the most "compatible" array among several candidates:</p> <pre><code>candidates = [ [0.01, 0.48, 1.03, 1.17, 1.5], [1.25, 1.4, 1.5, 1.9, 2.0], ... ] </code></pre> <p>In this case I consider the first candidate most compatible because after adding <code>1</code> to each value, 4 of the values are very close to values that exist in <code>master</code> (the 2nd candidate only has 3 values that match `master'), and order matters (though we can say the arrays are already sorted with no duplicate values, since they represent times).</p> <p>A physical example could be that <code>master</code> is an array of beat onsets for a clean recording of an audio track, while the candidates are arrays of beat onsets for various audio recordings that may or may not be of the same audio track. I'd like to find the candidate that is most likely to be a recording of (at least a portion of) the same audio track.</p> <p>I'm not sure of an algorithm to choose among these candidates. I've done some searching that led me to topics like cross-correlation, string distance, and fuzzy matching, but I'd like to know if I'm missing the forest for the trees here. I'm most familiar with data analysis in NumPy and Pandas, so I will tag the question as such.</p>
1
2016-08-05T21:10:02Z
38,798,544
<p>One way would be to create those sliding 1D arrays as a stacked 2D array with <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> and then get the distances against the <code>2D</code> array with <a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow"><code>Scipy's cdist</code></a>. Finally, we get the minimum distance along each row and choose the row with minimum of such distances. Thus, we would have an implementation like so -</p> <pre><code>from scipy.spatial.distance import cdist Na = a.shape[1] Nb = b.size b2D = b[np.arange(Nb-Na+1)[:,None] + np.arange(Na)] closesetID = cdist(a,b2D).min(1).argmin() </code></pre> <p>Sample run -</p> <pre><code>In [170]: a = np.random.randint(0,99,(400,500)) In [171]: b = np.random.randint(0,99,(700)) In [172]: b[100:100+a.shape[1]] = a[77,:] + np.random.randn(a.shape[1]) # Make b starting at 100th col same as 77th row from 'a' with added noise In [173]: Na = a.shape[1] ...: Nb = b.size ...: b2D = b[np.arange(Nb-Na+1)[:,None] + np.arange(Na)] ...: closesetID = cdist(a,b2D).min(1).argmin() ...: In [174]: closesetID Out[174]: 77 </code></pre> <p><strong>Note:</strong> To me it looked like using the default option of <code>cdist</code>, which is the euclidean distance made sense for such a problem. There are numerous other options as listed in the docs that are based on differentiation between inputs and as such could replace the default one.</p>
1
2016-08-05T22:28:12Z
[ "python", "pandas", "numpy", "pattern-matching" ]