title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
python: handling an array of XML items with element tree preferably "merge"
39,007,027
<p>I have an array called projectDet[]. It contains about 350 items.</p> <p><strong>EACH</strong> item in the array is xml information (single item below). The xml for each item is the same format but different id's and values. What I'd prefer is to have all of these into one big XML variable that I can pull Elements out of using element tree. Right now I don't know how to use Element tree to go through 300 items in an array.</p> <p>I have code that checks a different set of XML for the ID and then if the ID in XML data A matches the ID in xml data B, I take "billable hours" out and add it to a final CSV row that matches the id. This works with other XML that ISN'T in an array. So I feel like the easiest way is to use the code I have that works, but I'd need to somehow "merge" all of these entries into one variable that I can pipe into my existing functions.</p> <p>So is there a way to loop through this array and merge each item together in one xml. They'll all have the same tree structure.. i.e root/team_member/item and root/tasks/item</p> <p>Thanks for any advice.</p> <pre><code>&lt;root&gt; &lt;team_members type="list"&gt; &lt;item type="dict"&gt; &lt;id&gt;1137&lt;/id&gt; &lt;cost_rate type="float"&gt;76.0&lt;/cost_rate&gt; &lt;budget_spent_percentage type="null" /&gt; &lt;projected_hours type="float"&gt;0.0&lt;/projected_hours&gt; &lt;user_id type="int"&gt;1351480&lt;/user_id&gt; &lt;total_hours type="float"&gt;0.0&lt;/total_hours&gt; &lt;name&gt;Bob R&lt;/name&gt; &lt;budget_left type="null" /&gt; &lt;/item&gt; &lt;item type="dict"&gt; &lt;id&gt;1137&lt;/id&gt; &lt;cost_rate type="null" /&gt; &lt;budget_spent_percentage type="null" /&gt; &lt;projected_hours type="float"&gt;2072.0&lt;/projected_hours&gt; &lt;user_id type="null" /&gt; &lt;total_hours type="float"&gt;0.0&lt;/total_hours&gt; &lt;name&gt;Samm&lt;/name&gt; &lt;budget_left type="null" /&gt; &lt;/item&gt; &lt;/team_members&gt; &lt;nonbillable_detailed_report_url type="str"&gt;/reports/detailed/any&lt;/nonbillable_detailed_report_url&gt; &lt;detailed_report_url type="str"&gt;/reports/any&lt;/detailed_report_url&gt; &lt;billable_detailed_report_url type="str"&gt;/reports/any&lt;/billable_detailed_report_url&gt; &lt;tasks type="list"&gt; &lt;item type="dict"&gt; &lt;id&gt;1137&lt;/id&gt; &lt;budget_left type="null" /&gt; &lt;budget_spent_percentage type="null" /&gt; &lt;billed_rate type="float"&gt;0.0&lt;/billed_rate&gt; &lt;over_budget type="null" /&gt; &lt;/item&gt; &lt;item type="dict"&gt; &lt;id&gt;1137&lt;/id&gt; &lt;budget_left type="null" /&gt; &lt;budget_spent_percentage type="null" /&gt; &lt;billed_rate type="float"&gt;0.0&lt;/billed_rate&gt; &lt;over_budget type="null" /&gt; &lt;/item&gt; &lt;item type="dict"&gt; &lt;id&gt;1137&lt;/id&gt; &lt;budget_left type="null" /&gt; &lt;budget_spent_percentage type="null" /&gt; &lt;billed_rate type="float"&gt;0.0&lt;/billed_rate&gt; &lt;over_budget type="null" /&gt; &lt;total_hours type="float"&gt;0.0&lt;/total_hours&gt; &lt;budget type="null" /&gt; &lt;/item&gt; &lt;item type="dict"&gt; &lt;id&gt;1137&lt;/id&gt; &lt;budget_left type="null" /&gt; &lt;budget_spent_percentage type="null" /&gt; &lt;billed_rate type="float"&gt;0.0&lt;/billed_rate&gt; &lt;over_budget type="null" /&gt; &lt;total_hours type="float"&gt;0.0&lt;/total_hours&gt; &lt;budget type="null" /&gt; &lt;/item&gt; &lt;item type="dict"&gt; &lt;id&gt;1137&lt;/id&gt; &lt;budget_left type="null" /&gt; &lt;budget_spent_percentage type="null" /&gt; &lt;billed_rate type="float"&gt;0.0&lt;/billed_rate&gt; &lt;over_budget type="null" /&gt; &lt;total_hours type="float"&gt;0.0&lt;/total_hours&gt; &lt;budget type="null" /&gt; &lt;/item&gt; &lt;item type="dict"&gt; &lt;id&gt;1137&lt;/id&gt; &lt;budget_left type="null" /&gt; &lt;budget_spent_percentage type="null" /&gt; &lt;billed_rate type="float"&gt;0.0&lt;/billed_rate&gt; &lt;over_budget type="null" /&gt; &lt;total_hours type="float"&gt;0.0&lt;/total_hours&gt; &lt;budget type="null" /&gt; &lt;/item&gt; &lt;/tasks&gt; &lt;/root&gt; </code></pre>
0
2016-08-17T22:10:28Z
39,008,710
<p>Consider using <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.append" rel="nofollow"><code>append()</code></a> to append all children of the <code>&lt;root&gt;</code> iteratively across the list. But initially capture the first full element of <code>&lt;root&gt;</code> and then append thereafter:</p> <pre><code>import xml.etree.ElementTree as ET cnt = 1 for i in projectDet: if cnt == 1: main = ET.fromstring(i) else: team = ET.fromstring(i).findall('.//team_members') main.append(team[0]) nonbill = ET.fromstring(i).findall('.//nonbillable_detailed_report_url') main.append(nonbill[0]) detrpt = ET.fromstring(i).findall('.//detailed_report_url') main.append(detrpt[0]) bill = ET.fromstring(i).findall('.//billable_detailed_report_url') main.append(bill[0]) task = ET.fromstring(i).findall('.//tasks') main.append(task[0]) cnt+=1 # OUTPUT LARGE XML (main OBJ) print(ET.tostring(main).decode("UTF-8")) </code></pre>
1
2016-08-18T01:41:23Z
[ "python", "arrays", "xml", "elementtree" ]
Python: Replacing arbitrary substrings with substrings
39,007,082
<p>Sorry if this has been asked before, but I've been struggling with this for weeks now.</p> <p>I'm trying to figure out how to replace a particular substring within an arbitrary string with another particular substring.</p> <p>IE:</p> <p>If I get user to type in an arbitrary string, I want to replace any instance of "MAA" with something like "UOP".</p> <p><strong>My code:</strong></p> <pre><code>cstring = input("Enter a character string: ") for i in cstring: if ((i != 'M') and (i != 'U') and (i != 'I')): break else: if (cstring[-1] == 'I'): cstring = cstring + 'U' if (cstring[:1] == 'M'): cstring = cstring + cstring[1:] if ('III' in cstring): cstring = cstring[:i] + "U" + cstring[i:] if ('UU' in cstring): cstring = cstring[:i] + '' + cstring[i:] break print(cstring) </code></pre> <p>Thanks!</p>
-1
2016-08-17T22:14:17Z
39,007,119
<p>You can use the <code>String replace</code> method like this:</p> <p><code>cstring.replace("MAA,"UOP")</code></p> <p>However, if you want to code it yourself, this works:</p> <pre><code>cstring = input("Enter a character string: ") for i in range (0, len(cstring)): if (len(cstring[i:]) &gt;= 3 and cstring[i] == "M" and cstring[i+1] == "A" and cstring[i+2] == "A"): cstring = cstring[:i] + "UOP" + cstring[i+3:] print(cstring) </code></pre>
0
2016-08-17T22:17:54Z
[ "python", "string", "indexing", "slice" ]
Python: Replacing arbitrary substrings with substrings
39,007,082
<p>Sorry if this has been asked before, but I've been struggling with this for weeks now.</p> <p>I'm trying to figure out how to replace a particular substring within an arbitrary string with another particular substring.</p> <p>IE:</p> <p>If I get user to type in an arbitrary string, I want to replace any instance of "MAA" with something like "UOP".</p> <p><strong>My code:</strong></p> <pre><code>cstring = input("Enter a character string: ") for i in cstring: if ((i != 'M') and (i != 'U') and (i != 'I')): break else: if (cstring[-1] == 'I'): cstring = cstring + 'U' if (cstring[:1] == 'M'): cstring = cstring + cstring[1:] if ('III' in cstring): cstring = cstring[:i] + "U" + cstring[i:] if ('UU' in cstring): cstring = cstring[:i] + '' + cstring[i:] break print(cstring) </code></pre> <p>Thanks!</p>
-1
2016-08-17T22:14:17Z
39,007,238
<p>As other users have noted you can use <code>str.replace</code>. Here are some other options:</p> <h3>Regular Expressions</h3> <p>This is probably the way to go since you'll be able to replace any regex with your replacement string with all the advantages of the various re flags.</p> <pre><code>import re re.sub("MAA", "UOP", cstring) </code></pre> <h3>Validate String on Input</h3> <p>If your end goal is to work with a string with some simple replacements, you can also just try to enforce this in the input level. i.e.</p> <pre><code>cstring = input("Enter a valid character string: ") while bool(re.search("invalid_characters_regex", cstring)): print("Your input contained invalid characters, please try again.") cstring = input("Enter a valid character string: ") </code></pre>
0
2016-08-17T22:30:34Z
[ "python", "string", "indexing", "slice" ]
Not sure how to use sklearn with feature vectors which contain both text and numbers
39,007,083
<p>I just started to use sklearn and I want to categorize products. The products appear on order lines and have properties like, a description, a price, a manufacturer, order quantity etc. Some of these properties are text and others are numbers (integers or floats). I want to use these properties to predict if the product needs maintenance. Products we buy can be things like engines, pumps, etc but also nuts, hoses, filters etc. So far I did a prediction based on the price and quantity and I did other predictions based on the description or manufacturer. Now I want to combine these predictions but I'm not sure how to do that. I've seen the Pipeline and FeatureUnion pages but it is confusing to me. Does anybody have a simple example on how to predict data which has both text and number columns at the same time?</p> <p>I now have:</p> <pre><code>order_lines.head(5) Part No Part Description Quantity Price/Base Supplier Name Purch UoM Category 0 1112165 Duikwerkzaamheden 1.0 750.00 Duik &amp; Bergingsbedrijf Europa B.V. pcs 0 1 1112165 Duikwerkzaamheden bij de helling 1.0 500.00 Duik &amp; Bergingsbedrijf Europa B.V. pcs 0 2 1070285 Inspectie boegschroef, dd. 26-03-2012 1.0 0.01 Duik &amp; Bergingsbedrijf Europa B.V. pcs 0 3 1037024 Spare parts Albanie Acc. List 1.0 3809.16 Lastechniek Europa B.V. - 0 4 1037025 M_PO:441.35/BW_INV:0 1.0 0.00 Exalto pcs 0 category_column = order_lines['Category'] order_lines = order_lines[['Part Description', 'Quantity', 'Price/Base', 'Supplier Name', 'Purch UoM']] from sklearn.cross_validation import train_test_split features_train, features_test, target_train, target_test = train_test_split(order_lines, category_column, test_size=0.20) from sklearn.base import TransformerMixin, BaseEstimator class FeatureTypeSelector(TransformerMixin, BaseEstimator): FEATURE_TYPES = { 'price and quantity': [ 'Price/Base', 'Quantity', ], 'description, supplier, uom': [ 'Part Description', 'Supplier Name', 'Purch UoM', ], } def __init__(self, feature_type): self.columns = self.FEATURE_TYPES[feature_type] def fit(self, X, y=None): return self def transform(self, X): return X[self.columns] from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.svm import LinearSVC from sklearn.pipeline import make_union, make_pipeline from sklearn.preprocessing import RobustScaler preprocessor = make_union( make_pipeline( FeatureTypeSelector('price and quantity'), RobustScaler(), ), make_pipeline( FeatureTypeSelector('description, supplier, uom'), CountVectorizer(), ), ) preprocessor.fit_transform(features_train) </code></pre> <p>And then I got this error:</p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-51-f8b0db33462a&gt; in &lt;module&gt;() ----&gt; 1 preprocessor.fit_transform(features_train) C:\Anaconda3\lib\site-packages\sklearn\pipeline.py in fit_transform(self, X, y, **fit_params) 500 self._update_transformer_list(transformers) 501 if any(sparse.issparse(f) for f in Xs): --&gt; 502 Xs = sparse.hstack(Xs).tocsr() 503 else: 504 Xs = np.hstack(Xs) C:\Anaconda3\lib\site-packages\scipy\sparse\construct.py in hstack(blocks, format, dtype) 462 463 """ --&gt; 464 return bmat([blocks], format=format, dtype=dtype) 465 466 C:\Anaconda3\lib\site-packages\scipy\sparse\construct.py in bmat(blocks, format, dtype) 579 else: 580 if brow_lengths[i] != A.shape[0]: --&gt; 581 raise ValueError('blocks[%d,:] has incompatible row dimensions' % i) 582 583 if bcol_lengths[j] == 0: ValueError: blocks[0,:] has incompatible row dimensions </code></pre>
0
2016-08-17T22:14:23Z
39,012,920
<p>I would suggest not to make predictions on different feature types and then combining. You're better off using <code>FeatureUnion</code> as you suggest, which allows you to create separate preprocessing pipelines for each feature type. A construction I often use is the following...</p> <p>Let's define a toy example dataset to play around with:</p> <pre><code>import pandas as pd # create a pandas dataframe that contains your features X = pd.DataFrame({'quantity': [13, 7, 42, 11], 'item_name': ['nut', 'bolt', 'bolt', 'chair'], 'item_type': ['hardware', 'hardware', 'hardware', 'furniture'], 'item_price': [1.95, 4.95, 2.79, 19.95]}) # create corresponding target (this is often just one of the dataframe columns) y = pd.Series([0, 1, 1, 0], index=X.index) </code></pre> <p>I glue everything together using <code>Pipeline</code> and <code>FeatureUnion</code> (or rather their simpler shortcuts <code>make_pipeline</code> and <code>make_union</code>):</p> <pre><code>from sklearn.pipeline import make_union, make_pipeline from sklearn.feature_extraction import DictVectorizer from sklearn.preprocessing import RobustScaler from sklearn.linear_model import LogisticRegression # create your preprocessor that handles different feature types separately preprocessor = make_union( make_pipeline( FeatureTypeSelector('continuous'), RobustScaler(), ), make_pipeline( FeatureTypeSelector('categorical'), RowToDictTransformer(), DictVectorizer(sparse=False), # set sparse=True if you get MemoryError ), ) # example use of your combined preprocessor preprocessor.fit_transform(X) # choose some estimator estimator = LogisticRegression() # your prediction model can be created as follows model = make_pipeline(preprocessor, estimator) # and training is done as follows model.fit(X, y) # predict (preferably not on training data X) model.predict(X) </code></pre> <p>Here, I defined my own custom transformers <code>FeatureTypeSelector</code> and <code>RowToDictTransformer</code> as follows:</p> <pre><code>from sklearn.base import TransformerMixin, BaseEstimator class FeatureTypeSelector(TransformerMixin, BaseEstimator): """ Selects a subset of features based on their type """ FEATURE_TYPES = { 'categorical': [ 'item_name', 'item_type', ], 'continuous': [ 'quantity', 'item_price', ] } def __init__(self, feature_type): self.columns = self.FEATURE_TYPES[feature_type] def fit(self, X, y=None): return self def transform(self, X): return X[self.columns] class RowToDictTransformer(TransformerMixin, BaseEstimator): """ Prepare dataframe for DictVectorizer """ def fit(self, X, y=None): return self def transform(self, X): return (row[1] for row in X.iterrows()) </code></pre> <p>Hope that this example paints a some clearer image of how to do feature union.</p> <p>-Kris</p>
1
2016-08-18T08:06:17Z
[ "python", "machine-learning", "scikit-learn" ]
Pythonic way to handle config file installation when in a virtualenv?
39,007,132
<p>Assuming I am installing a python application from setup.py, and doing so within a virtualenv. Also, assuming that I have a need to provide the application sensitive configurations such as API keys / URIs.</p> <p>My virtualenv might be in a path such as:</p> <pre><code>/opt/appname/venv </code></pre> <p>I believe I want to be able to install a default config file for the user of the app to modify before successful execution.</p> <p>A default example might be installed to:</p> <pre><code>/etc/appname/config.sample </code></pre> <p>The problem is, if I am in a virtualenv, setup.py / setuptools really doesn't handle installing into a global path ( as far as I know ).</p> <p>What would be the best pythonic way to handle this fairly common scenario?</p>
-3
2016-08-17T22:19:09Z
39,108,700
<p>Assuming the config file alters Virtual Environment Variables and that is why it must be modified before the launch of the virtual environment, then you can modify the <code>activate</code> bash script located in <code>./venv/bin</code> to accomplish this. So if you want to add a global path from a config file, then last line in <code>activate</code> could be:</p> <pre><code>MY_GLOBAL_PATH=&lt;program that looks into config file and returns path&gt; </code></pre> <p>Then the virtual enviroment can be activated as it usual would:</p> <pre><code>source ./venv/bin/activate </code></pre>
1
2016-08-23T18:52:43Z
[ "python", "pip", "virtualenv", "setuptools", "packaging" ]
Pythonic way to handle config file installation when in a virtualenv?
39,007,132
<p>Assuming I am installing a python application from setup.py, and doing so within a virtualenv. Also, assuming that I have a need to provide the application sensitive configurations such as API keys / URIs.</p> <p>My virtualenv might be in a path such as:</p> <pre><code>/opt/appname/venv </code></pre> <p>I believe I want to be able to install a default config file for the user of the app to modify before successful execution.</p> <p>A default example might be installed to:</p> <pre><code>/etc/appname/config.sample </code></pre> <p>The problem is, if I am in a virtualenv, setup.py / setuptools really doesn't handle installing into a global path ( as far as I know ).</p> <p>What would be the best pythonic way to handle this fairly common scenario?</p>
-3
2016-08-17T22:19:09Z
39,170,378
<p>Have you tried using Python's <a href="https://docs.python.org/3/library/site.html" rel="nofollow">site-specific configuration</a> options? It seems to me like <code>.pth</code> files and a <code>sitecustomize.py</code> file might be helpful.<br> See also: <a href="http://stackoverflow.com/a/15209116/6051861">Accepted answer on "Using .pth files"</a>.</p> <p>Giving more precise detail on what might be done is difficult without a more specific example of the sort of "global path" you mean - even though this is a general style question to some extent.</p>
0
2016-08-26T16:02:20Z
[ "python", "pip", "virtualenv", "setuptools", "packaging" ]
Cx_freeze TypeError can only concatenate list (not "NoneType") to list using numpy dependency when pandas is an import
39,007,134
<p>I am trying to use cxfreeze to turn the following script into an executable</p> <pre><code>import datetime from calendar import monthrange from tia.bbg import LocalTerminal as Lt import pandas as pd from pypyodbc import connect, DatabaseError print 'Hello World!' </code></pre> <p>When running the following line in the command line:</p> <pre><code>cxfreeze test_freeze.py --target-dir test_freeze </code></pre> <p>I get the following traceback</p> <pre><code>Traceback (most recent call last): File "C:\Python27\Scripts\cxfreeze", line 5, in &lt;module&gt; main() File "C:\Python27\lib\site-packages\cx_Freeze\main.py", line 188, in main freezer.Freeze() File "C:\Python27\lib\site-packages\cx_Freeze\freezer.py", line 621, in Freeze self._FreezeExecutable(executable) File "C:\Python27\lib\site-packages\cx_Freeze\freezer.py", line 225, in _FreezeExecutable exe.copyDependentFiles, scriptModule) File "C:\Python27\lib\site-packages\cx_Freeze\freezer.py", line 602, in _WriteModules path = os.pathsep.join([origPath] + module.parent.path) TypeError: can only concatenate list (not "NoneType") to list </code></pre> <p>Surprisingly the file still gets created but when run I get this traceback:</p> <pre><code>C:\Python27\Scripts\test_freeze&gt;test_freeze.exe Traceback (most recent call last): File "C:\Python27\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in &lt;module&gt; exec(code, m.__dict__) File "test_freeze.py", line 3, in &lt;module&gt; File "C:\Python27\lib\site-packages\tia\bbg\__init__.py", line 1, in &lt;module&gt; from tia.bbg.v3api import * File "C:\Python27\lib\site-packages\tia\bbg\v3api.py", line 5, in &lt;module&gt; import pandas as pd File "C:\Python27\lib\site-packages\pandas\__init__.py", line 18, in &lt;module&gt; raise ImportError("Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy'] </code></pre> <p>Interesting things to note:</p> <p>I successfully ran this once (with the real not "hello world" code) and it compiled successfully, I changed one string for database purposes and I got this error.</p> <p>When I comment out the tia.bbg import and the pandas import the error stops and the program successfully freezes. It is essential to comment out tia as well because it is a wrapper built around pandas so that makes sense. I can say with confidence that tia is not the issue since only commenting that out throws the same pandas/numpy related errors</p> <p>I am using Windows 10 64bit, Python 2.7.12 64 bit amd, Pandas 0.18.1, and anything else that is relevant is also the newest version since I just freshly installed Python and all modules to avoid this problem. It had worked on the previous installation multiple times but then got the same error.</p> <p>My question is how do I get this script to run correctly and otherwise, which modules can I use to achieve the same goal?</p>
1
2016-08-17T22:19:23Z
39,122,902
<p>I had this problem. You can explicitly exclude all offending modules, but by debugging I think I found the responsible code and a small bugfix :). The following should help you get over this problem (and may lead you to the next one of missing dependencies ;) )</p> <p>Checking the code for freeze.py, there is a case that is not checked, so I made the following changes to freezer.py:</p> <p>line 600, from</p> <pre><code> try: if module.parent is not None: path = os.pathsep.join([origPath] + module.parent.path) os.environ["PATH"] = path self._CopyFile(module.file, target, copyDependentFiles) finally: os.environ["PATH"] = origPath </code></pre> <p>to:</p> <pre><code> try: if module.parent is not None: if module.parent.path is not None: path = os.pathsep.join([origPath] + module.parent.path) os.environ["PATH"] = path self._CopyFile(module.file, target, copyDependentFiles) else: path = os.pathsep.join([origPath, os.path.dirname(module.parent.file)]) os.environ["PATH"] = path print '========================================================' finally: os.environ["PATH"] = origPath </code></pre>
2
2016-08-24T12:08:08Z
[ "python", "pandas", "numpy", "executable", "cx-freeze" ]
Python 'yield' statements cause JSON not serializable errors in LAMBDA AWS test case
39,007,142
<p>I'm learning how to use Python in the Amazon AWS Lambda service. I'm trying to read characters from an S3 object, and write them to another S3 object. I realize I can copy the S3 object to a local tmp file, but I wanted to "stream" the S3 input into the script, process and output, without the local copy stage if possible. I'm using code from this <a href="http://stackoverflow.com/questions/7624900/how-can-i-use-boto-to-stream-a-file-out-of-amazon-s3-to-rackspace-cloudfiles" title="StackOverFlowExample">StackOverFlow</a> (Second answer) that suggests a solution for this.</p> <p>This code contains two "yield()" statements which are causing my otherwise working script to throw a "generator is noto JSON serializable" error. I'm trying to understand why a "yield()" statement would throw this error. Is this a Lambda environment restriction, or is this something specific to my code that is creating the serialization issue. (Likely due to using an S3 file object?).</p> <p>Here is my code that I run in Lambda. If I comment out the two yield statements it runs but the output file is empty. </p> <pre><code>from __future__ import print_function import json import urllib import uuid import boto3 import re print('Loading IO function') s3 = boto3.client('s3') def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type inbucket = event['Records'][0]['s3']['bucket']['name'] outbucket = "outlambda" inkey = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) outkey = "out" + inkey try: infile = s3.get_object(Bucket=inbucket, Key=inkey) except Exception as e: print(e) print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(inkey, bucket)) raise e tmp_path = '/tmp/{}{}'.format(uuid.uuid4(), "tmp.txt") # upload_path = '/tmp/resized-{}'.format(key) with open(tmp_path,'w') as out: unfinished_line = '' for byte in infile: byte = unfinished_line + byte #split on whatever, or use a regex with re.split() lines = byte.split('\n') unfinished_line = lines.pop() for line in lines: out.write(line) yield line # This line causes JSON error if uncommented yield unfinished_line # This line causes JSON error if uncommented # # Upload the file to S3 # tmp = open(tmp_path,"r") try: outfile = s3.put_object(Bucket=outbucket,Key=outkey,Body=tmp) except Exception as e: print(e) print('Error putting object {} from bucket {} Body {}. Make sure they exist and your bucket is in the same region as this function.'.format(outkey, outbucket,"tmp.txt")) raise e tmp.close() </code></pre>
0
2016-08-17T22:20:44Z
39,008,923
<p>A function includes <code>yield</code> is actually a <a href="https://wiki.python.org/moin/Generators" rel="nofollow">generator</a>, whereas the lambda handler needs to be a <a href="http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html" rel="nofollow">function</a> that optionally returns a json-serializable value.</p>
1
2016-08-18T02:13:55Z
[ "python", "json", "amazon-s3", "lambda" ]
Python 'yield' statements cause JSON not serializable errors in LAMBDA AWS test case
39,007,142
<p>I'm learning how to use Python in the Amazon AWS Lambda service. I'm trying to read characters from an S3 object, and write them to another S3 object. I realize I can copy the S3 object to a local tmp file, but I wanted to "stream" the S3 input into the script, process and output, without the local copy stage if possible. I'm using code from this <a href="http://stackoverflow.com/questions/7624900/how-can-i-use-boto-to-stream-a-file-out-of-amazon-s3-to-rackspace-cloudfiles" title="StackOverFlowExample">StackOverFlow</a> (Second answer) that suggests a solution for this.</p> <p>This code contains two "yield()" statements which are causing my otherwise working script to throw a "generator is noto JSON serializable" error. I'm trying to understand why a "yield()" statement would throw this error. Is this a Lambda environment restriction, or is this something specific to my code that is creating the serialization issue. (Likely due to using an S3 file object?).</p> <p>Here is my code that I run in Lambda. If I comment out the two yield statements it runs but the output file is empty. </p> <pre><code>from __future__ import print_function import json import urllib import uuid import boto3 import re print('Loading IO function') s3 = boto3.client('s3') def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type inbucket = event['Records'][0]['s3']['bucket']['name'] outbucket = "outlambda" inkey = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) outkey = "out" + inkey try: infile = s3.get_object(Bucket=inbucket, Key=inkey) except Exception as e: print(e) print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(inkey, bucket)) raise e tmp_path = '/tmp/{}{}'.format(uuid.uuid4(), "tmp.txt") # upload_path = '/tmp/resized-{}'.format(key) with open(tmp_path,'w') as out: unfinished_line = '' for byte in infile: byte = unfinished_line + byte #split on whatever, or use a regex with re.split() lines = byte.split('\n') unfinished_line = lines.pop() for line in lines: out.write(line) yield line # This line causes JSON error if uncommented yield unfinished_line # This line causes JSON error if uncommented # # Upload the file to S3 # tmp = open(tmp_path,"r") try: outfile = s3.put_object(Bucket=outbucket,Key=outkey,Body=tmp) except Exception as e: print(e) print('Error putting object {} from bucket {} Body {}. Make sure they exist and your bucket is in the same region as this function.'.format(outkey, outbucket,"tmp.txt")) raise e tmp.close() </code></pre>
0
2016-08-17T22:20:44Z
39,022,621
<p>Thanks to Lei Shi for answering the specific point I was asking about. Also Thanks to FujiApple for pointing out a missed coding mistake in the original code. I was able to develop a solution without using yield that seemed to work copying the input file to output. But with Lei Shi and FujiApples comments I was able to modify that code to create a sub function, called by the lambda handler which could be a generator. </p> <pre><code>from __future__ import print_function import json import urllib import uuid import boto3 import re print('Loading IO function') s3 = boto3.client('s3') def processFile( inbucket,inkey,outbucket,outkey): try: infile = s3.get_object(Bucket=inbucket, Key=inkey) except Exception as e: print(e) print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(inkey, bucket)) raise e inbody = infile['Body'] tmp_path = '/tmp/{}{}'.format(uuid.uuid4(), "tmp.txt") # upload_path = '/tmp/resized-{}'.format(key) with open(tmp_path,'w') as out: unfinished_line = '' bytes=inbody.read(4096) while( bytes ): bytes = unfinished_line + bytes #split on whatever, or use a regex with re.split() lines = bytes.split('\n') print ("bytes %s" % bytes) unfinished_line = lines.pop() for line in lines: print ("line %s" % line) out.write(line) yield line # if this line is commented out uncomment the unfinished line if() clause below bytes=inbody.read(4096) # if(unfinished_line): # out.write(unfinished_line) # # Upload the file to S3 # tmp = open(tmp_path,"r") try: outfile = s3.put_object(Bucket=outbucket,Key=outkey,Body=tmp) except Exception as e: print(e) print('Error putting object {} from bucket {} Body {}. Make sure they exist and your bucket is in the same region as this function.'.format(outkey, outbucket,"tmp.txt")) raise e tmp.close() def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event and show its content type inbucket = event['Records'][0]['s3']['bucket']['name'] outbucket = "outlambda" inkey = urllib.unquote_plus(event['Records'][0]['s3']['object'] ['key'].encode('utf8')) outkey = "out" + inkey processFile( inbucket,inkey,outbucket,outkey) </code></pre> <p>I'm posting the solution which uses yield in a sub "generator" function. Without the "yield" the code misses the last line, which was picked up by the if clause commented out.</p>
0
2016-08-18T15:52:39Z
[ "python", "json", "amazon-s3", "lambda" ]
Binning by value, except last bin
39,007,172
<p>I am trying to bin data as follows:</p> <pre><code>pd.cut(df['col'], np.arange(0,1.2, 0.2),include_lowest=True)) </code></pre> <p>But I would like to ensure that any data greater than 1 is also included in that last bin. I can do this in a couple lines, but wondering if anyone knows a one-liner/more pythonic way of doing this? </p> <p>PS - I am not looking to do a qcut-- I need the bins to be separated by their values, and not the count of records. </p>
1
2016-08-17T22:23:42Z
39,007,334
<p><strong>Solution 1:</strong> prepare <code>labels</code> (using first 5 rows of the DF) and replace <code>1</code> with <code>np.inf</code> in the <code>bins</code> parameter: </p> <pre><code>In [67]: df Out[67]: a b c 0 1.698479 0.337989 0.002482 1 0.903344 1.830499 0.095253 2 0.152001 0.439870 0.270818 3 0.621822 0.124322 0.471747 4 0.534484 0.051634 0.854997 5 0.980915 1.065050 0.211227 6 0.809973 0.894893 0.093497 7 0.677761 0.333985 0.349353 8 1.491537 0.622429 1.456846 9 0.294025 1.286364 0.384152 In [68]: labels = pd.cut(df.a.head(), np.arange(0,1.2, 0.2), include_lowest=True).cat.categories In [69]: pd.cut(df.a, np.append(np.arange(0, 1, 0.2), np.inf), labels=labels, include_lowest=True) Out[69]: 0 (0.8, 1] 1 (0.8, 1] 2 [0, 0.2] 3 (0.6, 0.8] 4 (0.4, 0.6] 5 (0.8, 1] 6 (0.8, 1] 7 (0.6, 0.8] 8 (0.8, 1] 9 (0.2, 0.4] Name: a, dtype: category Categories (5, object): [[0, 0.2] &lt; (0.2, 0.4] &lt; (0.4, 0.6] &lt; (0.6, 0.8] &lt; (0.8, 1]] </code></pre> <p><strong>Explanation:</strong></p> <pre><code>In [72]: np.append(np.arange(0, 1, 0.2), np.inf) Out[72]: array([ 0. , 0.2, 0.4, 0.6, 0.8, inf]) In [73]: labels Out[73]: Index(['[0, 0.2]', '(0.2, 0.4]', '(0.4, 0.6]', '(0.6, 0.8]', '(0.8, 1]'], dtype='object') </code></pre> <p><strong>Solution 2:</strong> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.clip.html" rel="nofollow">clip</a> all values greater than <code>1</code></p> <pre><code>In [70]: pd.cut(df.a.clip(upper=1), np.arange(0,1.2, 0.2),include_lowest=True) Out[70]: 0 (0.8, 1] 1 (0.8, 1] 2 [0, 0.2] 3 (0.6, 0.8] 4 (0.4, 0.6] 5 (0.8, 1] 6 (0.8, 1] 7 (0.6, 0.8] 8 (0.8, 1] 9 (0.2, 0.4] Name: a, dtype: category Categories (5, object): [[0, 0.2] &lt; (0.2, 0.4] &lt; (0.4, 0.6] &lt; (0.6, 0.8] &lt; (0.8, 1]] </code></pre> <p><strong>Explanation:</strong></p> <pre><code>In [75]: df.a Out[75]: 0 1.698479 1 0.903344 2 0.152001 3 0.621822 4 0.534484 5 0.980915 6 0.809973 7 0.677761 8 1.491537 9 0.294025 Name: a, dtype: float64 In [76]: df.a.clip(upper=1) Out[76]: 0 1.000000 1 0.903344 2 0.152001 3 0.621822 4 0.534484 5 0.980915 6 0.809973 7 0.677761 8 1.000000 9 0.294025 Name: a, dtype: float64 </code></pre>
2
2016-08-17T22:41:00Z
[ "python", "pandas", "dataframe", "categorical-data", "binning" ]
Python: write df to json
39,007,190
<p>I have dataframe</p> <pre><code>month 2015-05 2015-06 2015-07 2015-08 2015- 09 \ ID 00051f002f5a0c179d7ce191ca2c6401 0 0 0 1 1 0011ec51ddb5a41abb2d451fdfa0996a 0 0 0 1 1 0012ea90a6deb4eeb2924fb13e844136 1 1 1 1 1 0014ff1f6a95d789d3be3df5249cfe2f 0 0 0 1 1 </code></pre> <p>I try to write it to json and get smth like </p> <pre><code>{ "123": { "2015-12-14": 0, "2015-12-15": 1, "2015-12-16": 1, "2015-12-17": 0 }, "456": { "2015-12-14": 0, "2015-12-15": 1, "2015-12-12": 1, "2015-12-13": 1 } } </code></pre> <p>But I get </p> <pre><code>{ "2015-05": { "00051f002f5a0c179d7ce191ca2c6401": 0, "0011ec51ddb5a41abb2d451fdfa0996a": 0, "0012ea90a6deb4eeb2924fb13e844136": 1, "0014ff1f6a95d789d3be3df5249cfe2f": 0, "0017fbf132aac12d0f9f3ecb9ee7813d": 0, ... </code></pre> <p>How can I change that and get in first key ID?</p>
1
2016-08-17T22:25:52Z
39,007,270
<p>Try <code>df.to_json(orient="index")</code>, where <code>df</code> is your <code>DataFrame</code> object.</p> <p>For example,</p> <pre><code>In [32]: df Out[32]: a b c deadbeef foo 1 2.5 f005ba11 bar 3 4.5 7e1eca57 baz 5 6.5 In [33]: df.to_json(orient="index") Out[33]: '{"deadbeef":{"a":"foo","b":1,"c":2.5},"f005ba11":{"a":"bar","b":3,"c":4.5},"7e1eca57":{"a":"baz","b":5,"c":6.5}}' </code></pre> <p>Let's jump through some hoops to see a nicely formatted version of that string:</p> <pre><code>In [56]: s = df.to_json(orient="index") In [57]: print(json.dumps(json.loads(s), indent=4)) { "deadbeef": { "a": "foo", "c": 2.5, "b": 1 }, "7e1eca57": { "a": "baz", "c": 6.5, "b": 5 }, "f005ba11": { "a": "bar", "c": 4.5, "b": 3 } } </code></pre>
0
2016-08-17T22:33:56Z
[ "python", "json", "pandas", "dictionary" ]
python lxml etree applet information from yahoo
39,007,227
<p>Yahoo finance updated their website. I had an lxml/etree script that used to extract the analyst recommendations. Now, however, the analyst recommendations are there, but only as a graphic. You can see an example on <a href="https://finance.yahoo.com/quote/CSX/analysts?p=CSX">this page</a>. The graph called Recommendation Trends on the right hand column shows the number of analyst reports showing strong buy, buy, hold, underperform, and sell.</p> <p>My guess is that yahoo will make a few adjustments to the page over the coming little while, but it got me wondering whether such data was extractable in any reasonable way? </p> <ol> <li>I mean, is there a way to get the graphic to work with that? </li> <li>Even if one were successful, would there be a reasonable way to extract the data from the graphic?</li> </ol> <p>I used to get the source like this:</p> <pre><code>url = 'https://finance.yahoo.com/quote/'+code+'/analyst?p='+code tree = etree.HTML(urllib.request.urlopen(url).read()) </code></pre> <p>and then find the data in the html tree. But obviously that's impossible now.</p>
8
2016-08-17T22:29:29Z
39,178,177
<p>The page is <em>quite dynamic</em> and involves a lot of javascript executed in a browser. To follow the @Padraic's advice about switching to <a href="http://selenium-python.readthedocs.io/" rel="nofollow"><code>selenium</code></a>, here is a complete sample working code that produces a month-to-trend dictionary at the end. The values of each bar are calculated as proportions of bar heights:</p> <pre><code>from pprint import pprint 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.Chrome() driver.maximize_window() driver.get("https://finance.yahoo.com/quote/CSX/analysts?p=CSX") # wait for the chart to be visible wait = WebDriverWait(driver, 10) trends = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "section[data-reactid$=trends]"))) chart = trends.find_element_by_css_selector("svg.ratings-chart") # get labels month_names = [month.text for month in chart.find_elements_by_css_selector("g.x-axis g.tick")] trend_names = [trend.text for trend in trends.find_elements_by_css_selector("table tr &gt; td:nth-of-type(2)")] # construct month-to-trend dictionary data = {} months = chart.find_elements_by_css_selector("g[transform]:not([class])") for month_name, month_data in zip(month_names, months): total = month_data.find_element_by_css_selector("text.total").text data[month_name] = {'total': total} bars = month_data.find_elements_by_css_selector("g.bar rect") # let's calculate the values of bars as proportions of a bar height heights = {trend_name: int(bar.get_attribute("height")) for trend_name, bar in zip(trend_names[::-1], bars)} total_height = sum(heights.values()) for trend_name, bar in zip(trend_names, bars): data[month_name][trend_name] = heights[trend_name] * 100 / total_height driver.close() pprint(data) </code></pre> <p>Prints:</p> <pre><code>{u'Aug': {u'Buy': 19, u'Hold': 45, u'Sell': 3, u'Strong Buy': 22, u'Underperform': 8, 'total': u'26'}, u'Jul': {u'Buy': 18, u'Hold': 44, u'Sell': 3, u'Strong Buy': 25, u'Underperform': 7, 'total': u'27'}, u'Jun': {u'Buy': 21, u'Hold': 38, u'Sell': 3, u'Strong Buy': 28, u'Underperform': 7, 'total': u'28'}, u'May': {u'Buy': 21, u'Hold': 38, u'Sell': 3, u'Strong Buy': 28, u'Underperform': 7, 'total': u'28'}} </code></pre> <p>The <code>total</code> values are labels that you see on top of each bar.</p> <p>Hope this would at least be a good start for you. Let me know if you want me to elaborate on any part of the code or require any additional information.</p>
4
2016-08-27T06:28:21Z
[ "python", "python-3.x", "web-scraping", "lxml" ]
python lxml etree applet information from yahoo
39,007,227
<p>Yahoo finance updated their website. I had an lxml/etree script that used to extract the analyst recommendations. Now, however, the analyst recommendations are there, but only as a graphic. You can see an example on <a href="https://finance.yahoo.com/quote/CSX/analysts?p=CSX">this page</a>. The graph called Recommendation Trends on the right hand column shows the number of analyst reports showing strong buy, buy, hold, underperform, and sell.</p> <p>My guess is that yahoo will make a few adjustments to the page over the coming little while, but it got me wondering whether such data was extractable in any reasonable way? </p> <ol> <li>I mean, is there a way to get the graphic to work with that? </li> <li>Even if one were successful, would there be a reasonable way to extract the data from the graphic?</li> </ol> <p>I used to get the source like this:</p> <pre><code>url = 'https://finance.yahoo.com/quote/'+code+'/analyst?p='+code tree = etree.HTML(urllib.request.urlopen(url).read()) </code></pre> <p>and then find the data in the html tree. But obviously that's impossible now.</p>
8
2016-08-17T22:29:29Z
39,276,275
<p>As comments say they have moved to ReactJS, so <code>lxml</code> is no longer to the point because there's no data in the HTML page. Now you need to look around and find the endpoint where they are pulling the data from. In case of <em>Recommendation Trends</em> it's there.</p> <pre><code>#!/usr/bin/env python3 import json from pprint import pprint from urllib.request import urlopen from urllib.parse import urlencode def parse(): host = 'https://query2.finance.yahoo.com' path = '/v10/finance/quoteSummary/CSX' params = { 'formatted' : 'true', 'lang' : 'en-US', 'region' : 'US', 'modules' : 'recommendationTrend' } response = urlopen('{}{}?{}'.format(host, path, urlencode(params))) data = json.loads(response.read().decode()) pprint(data) if __name__ == '__main__': parse() </code></pre> <p>The output looks like this.</p> <pre><code>{ 'quoteSummary': { 'error': None, 'result': [{ 'recommendationTrend': { 'maxAge': 86400, 'trend': [{ 'buy': 0, 'hold': 0, 'period': '0w', 'sell': 0, 'strongBuy': 0, 'strongSell': 0 }, { 'buy': 0, 'hold': 0, 'period': '-1w', 'sell': 0, 'strongBuy': 0, 'strongSell': 0 }, { 'buy': 5, 'hold': 12, 'period': '0m', 'sell': 2, 'strongBuy': 6, 'strongSell': 1 }, { 'buy': 5, 'hold': 12, 'period': '-1m', 'sell': 2, 'strongBuy': 7, 'strongSell': 1 }, { 'buy': 6, 'hold': 11, 'period': '-2m', 'sell': 2, 'strongBuy': 8, 'strongSell': 1 }, { 'buy': 6, 'hold': 11, 'period': '-3m', 'sell': 2, 'strongBuy': 8, 'strongSell': 1 }] } }] } } </code></pre> <h1>How to look for data</h1> <p>What I did was roughly:</p> <ol> <li>Find some unique token in the target widget (say chart value or <em>Trend</em> string)</li> <li>Open source of the page (use some formatter for HTML and JS, e.g. <a href="http://jsbeautifier.org/" rel="nofollow">this</a>)</li> <li>Look for the token there (in the the page three is section that starts with <code>/* -- Data -- */</code>)</li> <li>Search for ".js" to get script tags (or programmatic inclusions, e.g. require.js) and look for token there</li> <li>Open network tab in Firebug or Chromium Developer Tools and inspect XHR requests</li> <li>Then use <a href="https://www.getpostman.com/" rel="nofollow">Postman</a> (or curl if you prefer terminal) to strip extra parameters and see how the endpoint reacts</li> </ol>
2
2016-09-01T16:07:33Z
[ "python", "python-3.x", "web-scraping", "lxml" ]
Python how to solve Unicode Error in string
39,007,232
<p>I'm getting the classical error:</p> <blockquote> <p>ascii' codec can't decode byte 0xc3 in position 28: ordinal not in range(128)</p> </blockquote> <p>This time, I can't solve it. The error comes from this line:</p> <pre><code>mensaje_texto_inmobiliaria = "%s, con el email %s y el teléfono %s está se ha contactado con Inmobiliar" % (nombre, email, telefono) </code></pre> <p>Specifically, from the <code>teléfono</code> word. I have tried adding <code># -*- coding: utf-8 -*-</code> to the beginning of the file, adding <code>unicode( &lt;string&gt; )</code> and also <code>&lt;string&gt;.encode("utf-8")</code>. Nothing worked. Any advice will help.</p>
0
2016-08-17T22:30:19Z
39,007,419
<p>This is in response to why this solves the issue OP is having, and somebackground on the issue OP is trying describe</p> <pre><code>from __future__ import unicode_literals from builtins import str </code></pre> <p>In the default iPython 2.7 kernel : </p> <p>(iPython session)</p> <pre><code>In [1]: type("é") # By default, quotes in py2 create py2 strings, which is the same thing as a sequence of bytes that given some encoding, can be decoded to a character in that encoding. Out[1]: str In [2]: type("é".decode("utf-8")) # We can get to the actual text data by decoding it if we know what encoding it was initially encoded in, utf-8 is a safe guess in almost every country but Myanmar. Out[2]: unicode In [3]: len("é") # Note that the py2 `str` representation has a length of 2. There's one byte for the "e" and one byte for the accent. Out[3]: 2 In [4]: len("é".decode("utf-8")) # the py2 `unicode` representation has length 1, since an accented e is a single character Out[4]: 1 </code></pre> <p>Some other things of note in python 2.7:</p> <ul> <li><code>"é"</code> is the same thing as <code>str("é")</code></li> <li><code>u"é"</code> is the same thing as <code>"é".decode('utf-8')</code> or <code>unicode("é", 'utf-8')</code></li> <li><code>u"é".encode('utf-8')</code> is the same thing as <code>str("é")</code></li> <li>You typically call decode with a py2 <code>str</code>, and encode with py2 <code>unicode</code>. <ul> <li>Due to early design issues, you can call both on either even though that doesn't really make any sense.</li> <li>In python3, <code>str</code>, which is the same as python2 <code>unicode</code>, can no longer be decoded since a string by definition is a decoded sequence of bytes. By default, it uses the utf-8 encoding.</li> </ul></li> <li>Byte sequences that were encoded with in the ascii codec behave exactly the same as their decoded counterparts. <ul> <li>In python 2.7 with no future imports : <code>type("a".decode('ascii'))</code> gives a unicode object, but this behaves nearly identically with <code>str("a")</code>. This is not the case in python3.</li> </ul></li> </ul> <p>With that said, here's what the snippets above do : </p> <ul> <li><code>__future__</code> is a module maintained by the core python team that backports python3 functionality to python2 to allow you to use python3 idioms within python2.</li> <li><code>from __future__ import unicode_literals</code> has the following effect : <ul> <li>Without the future import <code>"é"</code> is the same thing as <code>str("é")</code></li> <li>With the future import <code>"é"</code> is functionally the same thing as <code>unicode("é")</code></li> </ul></li> <li><code>builtins</code> is a module that is approved by the core python team, and contains safe aliases for using python3 idioms in python2 with the python3 api. <ul> <li>Due to reasons beyond me, the package itself is named "future", so to install the <code>builtins</code> module you run : <code>pip install future</code></li> </ul></li> <li><code>from builtins import str</code> has the following effect : <ul> <li>the <code>str</code> constructor now gives what you think it does, i.e. text data in the form of python2 unicode objects. So it's functionally the same thing as <code>str = unicode</code> </li> <li>Note : Python3 <code>str</code> is functionally the same as Python2 <code>unicode</code></li> <li>Note : To get bytes, you can use the "bytes" prefix, e.g. <code>b'é'</code></li> </ul></li> </ul> <p>The takeaway is this : </p> <ol> <li>Decode on read/Decode early on and encode on write/encode at the end</li> <li>Use <code>str</code> objects for bytes and <code>unicode</code> objects for text</li> </ol>
3
2016-08-17T22:50:13Z
[ "python", "unicode", "utf-8" ]
JSON file with input from filename using bash
39,007,279
<p>I am very new to bash scripting. </p> <p>I have set of JSON files as follows:</p> <pre><code>sub-285345_task-EMOTION_acq-LR_idir-acq-LR_epi.json sub-285345_task-EMOTION_acq-LR_idir-acq-RL_epi.json sub-285345_task-EMOTION_acq-RL_idir-acq-LR_epi.json sub-285345_task-EMOTION_acq-RL_idir-acq-RL_epi.json </code></pre> <p>Now looking at the each .json filename, I want to have key value pair inside the .json file. For eg: for file <code>sub-285345_task-EMOTION_acq-LR_idir-acq-LR_epi.json</code> i want to include following information: </p> <pre><code>{ "PhaseEncodingDirection": "-i", "TotalReadoutTime": 0.08346, "IntendedFor": "func/sub-285345_task-rest_acq-LR_run-01_bold.nii.gz" } </code></pre> <p><code>PhaseENcodingDirection</code> is derived from <code>idir-acq-LR</code> in the filename. For <code>LR</code> its <code>-i</code> and for <code>RL</code> its <code>i</code>.</p> <p>How can this be done using bash script preferably if not then in python. </p> <p>Any help is appreciated.</p>
0
2016-08-17T22:34:47Z
39,007,685
<p>You try below node js script</p> <pre><code>var fs = require('fs'); fs.readdir('.', function(err, files) { if (err) console.log(err); files.forEach(function(file) { var obj = { "TotalReadoutTime": 0.08346, }; if (file.indexOf("idir-acq-LR") &gt; -1) { console.log(file); obj.PhaseEncodingDirection = "-i"; var intendedForPart1 = file.replace(/'-EMOTION-acq-LR'/g,'-rest_acq-LR'); var intendedForPart2 = intendedForPart1.replace(/'_epi.json'/g,'_run-01_bold.nii.gz'); obj.IntendedFor = 'func/' + intendedForPart2; fs.writeFile(file, JSON.stringify(obj), 'utf-8'); } else if (file.indexOf("idir-acq-RL") &gt; -1) { console.log(file); obj.PhaseEncodingDirection = "i"; var intendedForPart1 = file.replace(/'-EMOTION-acq-RL'/g,'-rest_acq-RL'); var intendedForPart2 = intendedForPart1.replace(/'_epi.json'/g,'_run-01_bold.nii.gz'); obj.IntendedFor = 'func/' + intendedForPart2; //obj.IntendedFor = "func/sub-285345_task-rest_acq-RL_run-01_bold.nii.gz" fs.writeFile(file, JSON.stringify(obj), 'utf-8'); } }); }); </code></pre>
0
2016-08-17T23:22:06Z
[ "python", "json", "bash", "terminal" ]
assign variable to multiple argparse attributes
39,007,318
<p>I'm trying to assign multiple argument attributes based on their location in the attribute list. To give an example;</p> <pre><code>import argparse import sys def args_options: parser = argparse.ArgumentParser() parser.add_argument('-s', help='-s argument help', nargs=3) parser.add_argument('-k', help='-k argument help', nargs=3) arguments = parser.parse_args() return arguments def assign_arg(): args = args_options() if args.s or args.k: variable1 = args[1] # this is where I'm stuck as I know this won't work variable2 = args[2] # ^ </code></pre> <p>From the above, I'm trying to check if either arg.s or arg.k is true, and if so then the second and third attribute in the list of either argument is assigned to variables. </p> <p>Is it possible to do this with python? Or would I need to do;</p> <pre><code>if arg.s: variable1 = arg.s[1] variable2 = arg.s[2] elif arg.k: variable1 = arg.k[1] variable2 = arg.k[2] </code></pre> <p>The above would work, but I have a lot of options/attributes so the code could get long. Wanted to ask if there way to do it more efficiently by finding the attribute in the list of multiple argument options and assigning that to a variable. </p>
1
2016-08-17T22:39:49Z
39,007,724
<p>Run the parser with various inputs, and look at the results:</p> <pre><code>In [108]: def args_options(argv=None): ...: parser = argparse.ArgumentParser() ...: parser.add_argument('-s', help='-s argument help', nargs=3) ...: parser.add_argument('-k', help='-k argument help', nargs=3) ...: arguments = parser.parse_args(argv) ...: return arguments ...: </code></pre> <p>With no arguments - both <code>args.k</code> and <code>args.s</code> are <code>None</code>.</p> <pre><code>In [109]: args_options([]) Out[109]: Namespace(k=None, s=None) </code></pre> <p>With <code>-s</code> and the right number of arguments, <code>args.s</code> is a list of 3 strings.</p> <pre><code>In [110]: args_options(['-s','1','2','3']) Out[110]: Namespace(k=None, s=['1', '2', '3']) </code></pre> <p><code>-k</code> without arguments - error</p> <pre><code>In [111]: args_options(['-s','1','2','3', '-k']) usage: ipython3 [-h] [-s S S S] [-k K K K] ipython3: error: argument -k: expected 3 arguments An exception has occurred, use %tb to see the full traceback. SystemExit: 2 In [112]: args_options(['-s','1','2','3', '-k','4','5','6']) Out[112]: Namespace(k=['4', '5', '6'], s=['1', '2', '3']) </code></pre> <p>k and s - both as 3 element lists</p> <p>An example of tests we can do:</p> <pre><code>In [113]: args=args_options(['-k','1','2','3']) In [114]: args.s is None Out[114]: True In [115]: args.k is None Out[115]: False In [116]: a,b,c = args.k # unpack to variables In [117]: a Out[117]: '1' In [118]: b Out[118]: '2' In [119]: c Out[119]: '3' </code></pre> <p>Indexed access of list also works: <code>args.k[2]</code></p> <p><code>vars(args)</code> creates a dictionary from the <code>args</code> object, but I don't think that makes access any easier.</p> <p>The big message - print <code>args</code> to see what your parser produces. Do this again and again until you understand what it is doing and why.</p> <p>You could give <code>-k</code> a <code>default=[]</code>, in produce</p> <pre><code>In [123]: args=args_options(['-s','1','2','3']) In [124]: args Out[124]: Namespace(k=[], s=['1', '2', '3']) </code></pre> <p>You could define a <code>dest</code> for both, and end up with the values in the args attribute;</p> <pre><code>parser.add_argument('-k', '--ko', dest='something', default=[], nargs=3) </code></pre>
0
2016-08-17T23:26:48Z
[ "python", "namespaces", "argparse" ]
Python Tkinter visually display seating arrangements
39,007,368
<p>I am doing a school project, the purpose of the program is to sell tickets, the only problem i have is "Available and unavailable seats should be coloured/displayed differently and change when seat(s) are sold or returned.", i have a total of 250 seats, how to display them all on the screen? should i use a table or grid? or a canvas? i don't want you to code for me this is my assessment i just need an idea on how to tackle this problem efficiently.</p> <p>I have tried to manually use buttons to display the seats, not efficient for 250 of them.</p> <pre><code>Button(master, text="seat").grid(row=0,column=0) * 250 != efficient </code></pre> <p>i also tried to create the buttons dynamically with a For loop</p> <pre><code>self.seats = [] row_count = 0 for i in range(250): if(i &gt; 5): row_count += 1 #5 column table style if(i &lt; seats_taken): self.seats.append(Button(master, bg='#ff0000')) #So taken seats are red bg self.seats[i].grid(column=i+1 , row= row_count) else: self.seats.append(Button(master, bg='#ffffff')) #Available seats are white bg self.seats[i].grid(column=i+1 , row= row_count) </code></pre> <p>How would you takle this problem?</p>
0
2016-08-17T22:44:32Z
39,007,577
<p>I just approached this problem with a different scenario. You want some way to track the variables of each seat so you can come back and change the color. One way is to create a name for the tkinter widget, i.e. <code>seat1</code> Where <code>1</code> would change for the seat number. You probably want the layout similar to the layout of the event so you want some rows. May I suggest also putting a frame in a canvas with a specific height and width. This way you can scroll through a frame without changing the size of the window.</p> <p>Here's an example:</p> <pre><code>import tkinter as tk from tkinter import ttk class MainApp(ttk.Frame): def __init__(self, parent): ttk.Frame.__init__(self, parent) self.parent = parent self.mainframe = ttk.Frame(self.parent) self.canvas = tk.Canvas(self.mainframe) self.frame = ttk.Frame(self.canvas) self.gen_layout() self.column_row_config() def column_row_config(self): self.parent.rowconfigure(0, weight=1) self.parent.columnconfigure(0, weight=1) def gen_layout(self): self.mainframe.grid(row=0, column=0, sticky='nsew') self.canvas.grid(row=0, column=0, sticky='nsew') self.frame.grid(row=0, column=0, sticky='nsew') self.make_seats() self.access_seat_numb(1) def make_seats(self): # create 250 buttons on 10 rows seat_counter = 1 for x in range(10): for y in range(1, 26): # print('creating seat %d' % seat_counter) b = ttk.Button( self.frame, text='Seat%d' % seat_counter, name='seat%d' % seat_counter ) # doesn't matter that the columns won't line up b.grid(row=x, column=y) seat_counter += 1 def access_seat_numb(self, numb): # print(self.frame.children) for k, v in self.frame.children.items(): if k == 'seat%d' % numb: # run some code on a seat numb print(v._name) if __name__ == '__main__': root = tk.Tk() MainApp(root) root.mainloop() </code></pre> <p>Now <code>access_seat_numb</code> is a method that you can call and change that button.</p>
0
2016-08-17T23:06:58Z
[ "python", "tkinter" ]
offset randomforestclassifier scikit learn
39,007,386
<p>I wrote a program in python to use a machine learning algorithm to make predictions on data. I use the function RandomForestClassifier from Scikit Learn to create a random forest to make predictions. </p> <p>The purpose of the program is to predict if an unknown astrophysical source is a pulsar or an agn; so it trains the forest on known data of which it knows if sources are pulsar or agn, then it makes predictions on unknown data, but it doesn’t work. The program predict that unknown data are all pulsar or all agn and it rarely predicts a different result, but not correct.</p> <p>Below I describe the passages of my program.</p> <p>It creates a data frame with data for all the sources: all_df It is made of ten columns, nine used as predictors and one as target:</p> <pre><code>predictors=all_df[['spec_index','variab_index','flux_density','unc_ene_flux100','sign_curve','h_ratio_12','h_ratio_23','h_ratio_34','h_ratio_45']] targets=all_df['type'] </code></pre> <p>type column contains the label “pulsar” or “agn” for each source.</p> <p>The values of predictors and targets are used successively in the program to train the forest.</p> <p>The program divides the predictors and the targets in two sets, the train, which is the 70% of the total, and the test, which is the 30% of the total of all_df, using the function train_test_split from Scikit Learn:</p> <pre><code>pred_train, pred_test, tar_train, tar_test=train_test_split(predictors, targets, test_size=0.3) </code></pre> <p>Data in these sets are mixed, so the program orders the indexes of these sets, without changing data position:</p> <pre><code>pred_train=pred_train.reset_index(drop=True) pred_test=pred_test.reset_index(drop=True) tar_train=tar_train.reset_index(drop=True) tar_test=tar_test.reset_index(drop=True) </code></pre> <p>After that, the program creates and trains the random forest:</p> <pre><code>clf=RandomForestClassifier(n_estimators=1000,oob_score=True,max_features=None,max_depth=None,criterion='gini')#,random_state=1) clf=clf.fit(pred_train,tar_train) </code></pre> <p>Now the program makes prediction on the test set:</p> <pre><code>predictions=clf.predict(pred_test) </code></pre> <p>At this point, the program seems to work.</p> <p>Now it pass another data frame, with the unknown data, to the forest created above and I have the bad result described before. Can you help me? The problem could be an offset in randomforestclassifier, but I had no significative results modifying randomforestclassifier options. If you need, I can give further explanations. Thanks in advance.</p> <p>Bye, Fabio</p> <p>PS: I tried the cross validation too: I divided the train set into train and test again, with the same proportions (0.7 and 0.3), to create, train and test the forest before testing it on the initial test set, modifying randomforestclassifier options to obtain better results, but I had no improvements.</p>
0
2016-08-17T22:46:39Z
39,066,941
<p>Thanks for answering, guys.</p> <p>As suggested, I did plots of the predictors in the “test” data and in the “unknown” data; the distributions are generally similar, but I prefer to make histograms to say it. So I tried to do histograms, but I couldn’t both for the test and the unknown data, using:</p> <pre><code>pylab.hist(unid_df.spec_index,bins=30) </code></pre> <p>I obtained: TypeError: len() of unsized object</p> <p>I haven’t found a solution yet and I don’t know if this error can negatively act on the predictions. </p> <p>Additional information: the ranges of the various predictors are of different order of magnitude. The ranges are the same for corresponding predictors of test and unknown data, but in few cases test data ranges have larger order of magnitude from the corresponding predictor of the unknown data. This is due to some points that have values much bigger than the most of the other points in the set.</p> <p>Thanks again. Bye, Fabio</p>
0
2016-08-21T17:29:23Z
[ "python", "machine-learning", "scikit-learn", "random-forest" ]
Run Django workers servers with supervisor?
39,007,410
<p>I'm trying to deploy my Django application with supervisor. When I launch supervisor it starts daphne correctly, however the worker servers are not launched.</p> <p>Here's a code sample of supervisor.conf (the workers block): </p> <pre><code>[program:runworker] command=python /home/django/environment/myproject/manage.py runworker stopsignal=KILL killasgroup=true </code></pre> <p>The browser waits a long time and then it shows:</p> <pre><code> 503 Service Unavailable Worker server failed to respond within time limit. </code></pre> <p>I could also add that if I launch the processes independently (not using any process control system ) it actually works. I'm behind an Nginx reverse proxy, but I don't think that's the issue at all.. </p> <p>Here's the output of Supervisor:</p> <pre><code>2016-08-17 19:01:09,439 INFO supervisord started with pid 3473 2016-08-17 19:01:10,441 INFO spawned: 'runworker' with pid 3477 2016-08-17 19:01:10,442 INFO spawned: 'daphne' with pid 3478 2016-08-17 19:01:11,421 DEBG 'daphne' stderr output: 2016-08-17 23:01:11,421 INFO Starting server at 0.0.0.0:9000, channel layer myproject.asgi:channel_layer 2016-08-17 19:01:11,519 INFO success: runworker entered RUNNING state, process has stayed up for &gt; than 1 seconds (startsecs) 2016-08-17 19:01:11,519 INFO success: daphne entered RUNNING state, process has stayed up for &gt; than 1 seconds (startsecs) 2016-08-17 19:01:11,591 DEBG 'runworker' stderr output: 2016-08-17 23:01:11,591 - INFO - runworker - Running worker against channel layer default (asgi_redis.core.RedisChannelLayer) 2016-08-17 19:01:11,592 DEBG 'runworker' stderr output: 2016-08-17 23:01:11,592 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive </code></pre>
3
2016-08-17T22:49:02Z
39,007,629
<p>You probably need to set the DJANGO_SETTINGS_MODULE environment variable.</p> <p>This answer provides an example: <a href="http://stackoverflow.com/a/26732916/4193">http://stackoverflow.com/a/26732916/4193</a></p>
1
2016-08-17T23:15:06Z
[ "python", "django", "django-channels" ]
How to take an integer array and convert it into other types?
39,007,441
<p>I'm currently trying to take integer arrays that actually represent other data types and convert them into the correct datatype.</p> <p>So for example, if I had the integer array [1196773188, 542327116], I discover that this integer array represents a string from some other function, convert it, and realize it represents the string "DOUGLAS". The first number translates to the hexadecimal number 0x47554F44 and the second number represents the hexadecimal number 0x2053414C. Using a hex to string converter, these correspond to the strings 'GOUD' and 'SAL' respectively, spelling DOUGLAS in a little endian manner. The way the letters are backwards in individual elements of the array likely stem from the bytes being stored in a litte endian manner, although I might be mistaken on that.</p> <p>These integer arrays could represent a number of datatypes, including strings, booleans, and floats. </p> <p>I need to use Python 2.7, so I unfortunately can't use the bytes function. </p> <p>Is there a simple way to convert an integer array to its corresponding datatype?</p>
-3
2016-08-17T22:54:02Z
39,008,382
<p>It seems that the struct module is the best way to go when converting between different types like this:</p> <pre><code>import struct bufferstr = "" dougarray = [1196773188, 542327116] for num in dougarray: bufferstr += struct.pack("i", num) print bufferstr # Result is 'DOUGLAS' </code></pre> <p>From this point on we can easily convert 'DOUGLAS' to any datatype we want using struct.unpack():</p> <pre><code>print struct.unpack("f", bufferstr[0:4]) # Result is (54607.265625) </code></pre> <p>We can only unpack a certain number of bytes at a time however. Thank you all for the suggestions! </p>
2
2016-08-18T00:55:51Z
[ "python", "arrays", "python-2.7" ]
Best way to read a (ba)sh config file in python 2 or 3
39,007,551
<p>I have the the following config file </p> <pre><code># originally this was a (ba)sh config file, now read by python TEST=123 BAK=.bak # comment for next line TEST_2="cool spaced Value" MY_VAR2="space value" # With a Comment for the value </code></pre> <p>I have managed to read this with the following code</p> <pre><code>def parse_lines(self, lines): pattern = r'[ |\t]*([a-zA-Z_][a-zA-Z0-9_]*)=("([^\\"]|.*)"|([^# \t]*)).*[\r]*\n' prog = re.compile(pattern) hash={} for line in lines: result = prog.match(line) if not result is None: name = result.groups()[0] if result.groups()[2] is None: value= result.groups()[3] else: value= result.groups()[2] hash[name]=value return hash def read_shell_config(self, filename): with open(filename) as f: lines = f.readlines() hash = self.parse_lines(lines) return hash </code></pre> <p>Is there any better way (standard package?) to read a bash config file like the above with python?</p>
0
2016-08-17T23:04:10Z
39,007,711
<p>Implementing a real shell interpreter in Python is beyond feasibility -- but you can cheat:</p> <pre><code>#!/usr/bin/env python import subprocess import os script=''' set -a # export all variable definitions to the environment # record prior names declare -A prior_names=( ) while IFS= read -r varname; do prior_names[$varname]=1 done &lt; &lt;(compgen -v) source "$1" &gt;/dev/null while IFS= read -r varname; do [[ ${prior_names[$varname]} ]] &amp;&amp; continue # skip anything that was already present printf '%s\\0' "$varname" "${!varname}" done &lt; &lt;(compgen -v) ''' def getVars(configFile): p = subprocess.Popen(['bash', '-c', script, '_', configFile], stdout=subprocess.PIPE, env={'PATH': os.environ['PATH']}) items = p.communicate()[0].split('\0') keys = [val for (idx, val) in enumerate(items) if (idx % 2 == 0)] vals = [val for (idx, val) in enumerate(items) if (idx % 2 == 1)] return dict(zip(keys, vals)) if __name__ == '__main__': import sys print getVars(sys.argv[1]) </code></pre>
1
2016-08-17T23:25:33Z
[ "python", "bash", "config" ]
Running Jupyter with multiple Python and iPython paths
39,007,571
<p>I'd like to work with Jupyter notebooks, but have had difficulty doing basic imports (such as import matplotlib). I think this was because I have several user-managed python installations. For instance: </p> <pre><code>&gt; which -a python /usr/bin/python /usr/local/bin/python &gt; which -a ipython /Library/Frameworks/Python.framework/Versions/3.5/bin/ipython /usr/local/bin/ipython &gt; which -a jupyter /Library/Frameworks/Python.framework/Versions/3.5/bin/jupyter /usr/local/bin/jupyter </code></pre> <p>I used to have anaconda, but removed if from the ~/anaconda directory. Now, when I start a Jupyter Notebook, I get a Kernel Error:</p> <pre><code>File "/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho‌n3.5/subprocess.py", line 947, in init restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho‌n3.5/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: '/Users/npr1/anaconda/envs/py27/bin/python' </code></pre> <p>What should I do?!</p>
5
2016-08-17T23:06:12Z
39,022,003
<p>This is fairly straightforward to fix, but it involves understanding three different concepts:</p> <ol> <li>How Unix/Linux/OSX use <code>$PATH</code> to find executables</li> <li>How Python installs and finds packages</li> <li>How Jupyter knows what Python to use</li> </ol> <p>For the sake of completeness, I'll try to do a quick ELI5 on each of these, so you'll know how to solve this issue in the best way for you.</p> <h2>1. Unix/Linux/OSX $PATH</h2> <p>When you type any command at the prompt (say, <code>python</code>), the system has a well-defined sequence of places that it looks for the executable. This sequence is defined in a system variable called <code>PATH</code>, which the user can specify. To see your <code>PATH</code>, you can type <code>echo $PATH</code>.</p> <p>The result is a list of directories on your computer, which will be searched <strong>in order</strong> for the desired executable. From your output above, I assume that it contains this: </p> <pre><code>$ echo $PATH /usr/bin/:/Library/Frameworks/Python.framework/Versions/3.5/bin/:/usr/local/bin/ </code></pre> <p>Probably with some other paths interspersed as well. What this means is that when you type <code>python</code>, the system will go to <code>/usr/bin/python</code>. When you type <code>ipython</code>, the system will go to <code>/Library/Frameworks/Python.framework/Versions/3.5/bin/ipython</code>, because there is no <code>ipython</code> in <code>/usr/bin/</code>.</p> <p>It's always important to know what executable you're using, particularly when you have so many installations of the same program on your system. Changing the path is not too complicated; see e.g. <a href="http://stackoverflow.com/questions/14637979/how-to-permanently-set-path-on-linux">How to permanently set $PATH on Linux?</a>.</p> <h2>2. How Python finds packages</h2> <p>When you run python and do something like <code>import matplotlib</code>, Python has to play a similar game to find the package you have in mind. Similar to <code>$PATH</code> in unix, Python has <code>sys.path</code> that specifies these:</p> <pre><code>$ python &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/Users/jakevdp/anaconda/lib/python3.5', '/Users/jakevdp/anaconda/lib/python3.5/site-packages', ...] </code></pre> <p>Some important things: by default, the first entry in <code>sys.path</code> is the current directory. Also, unless you modify this (which you shouldn't do unless you know exactly what you're doing) you'll usually find something called <code>site-packages</code> in the path: this is the default place that Python puts packages when you install them using <code>python setup.py install</code>, or <code>pip</code>, or <code>conda</code>, or a similar means.</p> <p>The important thing to note is that <strong>each python installation has its own site-packages</strong>, where packages are installed <strong>for that specific Python version</strong>. In other words, if you install something for, e.g. <code>/usr/bin/python</code>, then <code>~/anaconda/bin/python</code> <strong>can't use that package</strong>, because it was installed on a different Python! This is why in our twitter exchange I recommended you focus on one Python installation, and fix your<code>$PATH</code> so that you're only using the one you want to use.</p> <p>There's another component to this: some Python packages come bundled with stand-alone scripts that you can run from the command line (examples are <code>pip</code>, <code>ipython</code>, <code>jupyter</code>, <code>pep8</code>, etc.) By default, these executables will be put in the <strong>same directory path</strong> as the Python used to install them, and are designed to work <strong>only with that Python installation</strong>.</p> <p>That means that, as your system is set-up, when you run <code>python</code>, you get <code>/usr/bin/python</code>, but when you run <code>ipython</code>, you get <code>/Library/Frameworks/Python.framework/Versions/3.5/bin/ipython</code> which is associated with the Python version at <code>/Library/Frameworks/Python.framework/Versions/3.5/bin/python</code>! Further, this means that the packages you can import when running <code>python</code> are entirely separate from the packages you can import when running <code>ipython</code>: you're using two completely independent Python installations.</p> <p>So how to fix this? Well, first make sure your <code>$PATH</code> variable is doing what you want it to. You likely have a startup script called something like <code>~/.bash_profile</code> or <code>~/.bashrc</code> that sets this <code>$PATH</code> variable. You can manually modify that if you want your system to search things in a different order. When you first install anaconda/miniconda, there will be an option to do this automatically: say yes to that, and then <code>python</code> will always point to <code>~/anaconda/python</code>, which is probably what you want.</p> <h2>3. How Jupyter knows what Python to use</h2> <p>We're not totally out of the water yet. You mentioned that in the Jupyter notebook, you're getting a kernel error: this indicates that Jupyter is looking for a non-existent Python version.</p> <p>Jupyter is set-up to be able to use a wide range of "kernels", or execution engines for the code. These can be Python 2, Python 3, R, Julia, Ruby... there are dozens of possible kernels to use. But in order for this to happen, Jupyter needs to know <em>where</em> to look for the associated executable: that is, it needs to know which path the <code>python</code> sits in.</p> <p>These paths are specified in jupyter's <code>kernelspec</code>, and it's possible for the user to adjust them to their desires. For example, here's the list of kernels that I have on my system:</p> <pre><code>$ jupyter kernelspec list Available kernels: python2.7 /Users/jakevdp/.ipython/kernels/python2.7 python3.3 /Users/jakevdp/.ipython/kernels/python3.3 python3.4 /Users/jakevdp/.ipython/kernels/python3.4 python3.5 /Users/jakevdp/.ipython/kernels/python3.5 python2 /Users/jakevdp/Library/Jupyter/kernels/python2 python3 /Users/jakevdp/Library/Jupyter/kernels/python3 </code></pre> <p>Each of these is a directory containing some metadata that specifies the kernel name, the path to the executable, and other relevant info. You can adjust kernels manually, editing the metadata inside the directories listed above.</p> <p>The command to install a kernel can change depending on the kernel. IPython relies on the <a href="https://pypi.python.org/pypi/ipykernel/">ipykernel package</a> which contains a command to install a python kernel: for example</p> <pre><code>$ python -m ipykernel install </code></pre> <p>It will create a kernelspec associated with the Python executable you use to run this command. You can then choose this kernel in the Jupyter notebook to run your code with that Python.</p> <p>You can see other options that ipykernel provides using the help command:</p> <pre><code>$ python -m ipykernel install --help usage: ipython-kernel-install [-h] [--user] [--name NAME] [--display-name DISPLAY_NAME] [--prefix PREFIX] [--sys-prefix] Install the IPython kernel spec. optional arguments: -h, --help show this help message and exit --user Install for the current user instead of system-wide --name NAME Specify a name for the kernelspec. This is needed to have multiple IPython kernels at the same time. --display-name DISPLAY_NAME Specify the display name for the kernelspec. This is helpful when you have multiple IPython kernels. --prefix PREFIX Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. --sys-prefix Install to Python's sys.prefix. Shorthand for --prefix='/Users/bussonniermatthias/anaconda'. For use in conda/virtual-envs. </code></pre> <p>Note: the recent version of <em>anaconda</em> ships with an extension for the notebook that should automatically detect your various conda environments if the <code>ipykernel</code> package is installed in it. </p> <h2>Wrap-up: Fixing your Issue</h2> <p>So with that background, your issue is quite easy to fix:</p> <ol> <li><p>Set your <code>$PATH</code> so that the desired Python version is first. For example, you could run <code>export PATH="/path/to/python/bin:$PATH"</code> to specify (one time) which Python you'd like to use. To do this permanently, add that line to your <code>.bash_profile</code>/<code>.bashrc</code> (note that anaconda can do this automatically for you when you install it). I'd recommend using the Python that comes with anaconda or miniconda: this will allow you to <code>conda install</code> all the tools you need.</p></li> <li><p>Make sure the packages you want to use are installed for <strong>that</strong> python. If you're using conda, you can type, e.g. <code>conda install notebook matplotlib scikit-learn</code> to install those packages for <code>anaconda/bin/python</code>.</p></li> <li><p>Make sure that your Jupyter kernels point to the Python versions you want to use. When you <code>conda install notebook</code> it should set this up for <code>anaconda/bin/python</code> automatically. Otherwise you can use the <code>jupyter kernelspec</code> command or <code>python -m ipykernel install</code> command to adjust existing kernels or install new ones.</p></li> </ol> <p>Hopefully that's clear... good luck!</p>
16
2016-08-18T15:23:59Z
[ "python", "ipython", "jupyter", "jupyter-notebook" ]
web2py python - ImportError cannot import name
39,007,601
<p>I keep getting this error: <code>&lt;type 'exceptions.ImportError'&gt; cannot import name get_cert_infos</code>. I'm pretty sure I'm importing everything correctly. The file with the problem is <code>participant.py</code> and has:</p> <pre><code>from datetime import date from widgets import SelectOrAdd, LabelSortedOptionsWidget, DynamicSelect, \ AutocompleteReferenceWidget from communication import handle_notification, send_email from utility import create_temp_password, hash_password from export import get_cert_infos, build_certificate </code></pre> <p>I have <code>exports.py</code> and the <code>get_cert_infos</code> and <code>build_certificate</code> methods do exist inside of there. I don't understand what the problem is.</p> <p>I looked at several of the other posts on this and they all seem to be saying that this is most likely a circular import problem</p> <p>I have <code>export</code> installed and updated <code>export==0.1.2</code></p> <p><a href="http://stackoverflow.com/q/9252543/5184092">ImportError: Cannot import name X</a></p>
0
2016-08-17T23:10:04Z
39,007,878
<p>Try double checking the spelling, I know it's dumb, but it happens.</p> <p>if it's not that, try writing this method in export </p> <pre><code>def hello_world(): print 'hello world' </code></pre> <p>then </p> <pre><code>import export export.hello_world() </code></pre> <p>if that works, it may be something wrong with the method itself, if it doesn't I imagine that the name <code>export</code> is reserved and is causing conflicts (my code editor doesn't mark it as reserved tho).</p> <p>is it necessary to import only those two methods? or could you import the whole module and use the needed methods as in the case of the hello_world? does that cause you troubles? if you delete <code>get_cert_infos</code> does <code>build_certificate</code> give you any troubles? </p>
1
2016-08-17T23:43:56Z
[ "python", "python-2.7", "import", "web2py", "importerror" ]
Production version of Django?
39,007,610
<p>So I have been working on a Badgr server for another department. I have built it using Python 2.7 and django. From what I have heard Django is only used for dev websites.</p> <p>I want to take this project and convert it to run on something meant for a production environment. But I really have no idea how to proceed. Sorry if this is a really noob question, I am a system administrator not a dev.</p> <p>(env)[root@badgr code]# ./manage.py runserver &amp; Performing system checks...</p> <p>System check identified no issues (0 silenced). August 08, 2016 - 16:31:48 Django version 1.7.1, using settings 'mainsite.settings' Starting development server at #####//127.0.0.1:8000/ Quit the server with CONTROL-C.</p> <p>But I can't seem to connect to it when I go to #####//myserver:8000,</p> <p>I know the traffic from my PC is hitting the server because I see it in tcpdump on TCP 8000. I have been told runserver blocks traffic from external sources because of it being meant for dev only.</p> <p>After talking with some people they recommend that I switch to Apache or Gunicorn? </p> <p>Here are some instructions I was sent from the Django documentation: <a href="https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/" rel="nofollow">https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/</a> Although I can't really make heads or tails of what I should do. Any input would be appreciated. Thanks</p>
-1
2016-08-17T23:11:38Z
39,007,736
<p>First of all, you should really be using a "long term support" version of Django, not 1.7.1. The current LTS release is 1.8.14; see <a href="https://www.djangoproject.com/download/" rel="nofollow">https://www.djangoproject.com/download/</a> for details.</p> <p>The Django documentation link you were given is just one part of what you need to understand. A better place to start is actually the first link on that page, which is <a href="https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/" rel="nofollow">https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/</a>.</p>
0
2016-08-17T23:27:48Z
[ "python", "django", "apache", "production" ]
Production version of Django?
39,007,610
<p>So I have been working on a Badgr server for another department. I have built it using Python 2.7 and django. From what I have heard Django is only used for dev websites.</p> <p>I want to take this project and convert it to run on something meant for a production environment. But I really have no idea how to proceed. Sorry if this is a really noob question, I am a system administrator not a dev.</p> <p>(env)[root@badgr code]# ./manage.py runserver &amp; Performing system checks...</p> <p>System check identified no issues (0 silenced). August 08, 2016 - 16:31:48 Django version 1.7.1, using settings 'mainsite.settings' Starting development server at #####//127.0.0.1:8000/ Quit the server with CONTROL-C.</p> <p>But I can't seem to connect to it when I go to #####//myserver:8000,</p> <p>I know the traffic from my PC is hitting the server because I see it in tcpdump on TCP 8000. I have been told runserver blocks traffic from external sources because of it being meant for dev only.</p> <p>After talking with some people they recommend that I switch to Apache or Gunicorn? </p> <p>Here are some instructions I was sent from the Django documentation: <a href="https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/" rel="nofollow">https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/</a> Although I can't really make heads or tails of what I should do. Any input would be appreciated. Thanks</p>
-1
2016-08-17T23:11:38Z
39,009,755
<p>I recommend you to use gunicorn and Nginx to run a Django project on your production server. Both are easy to google for official docs and recipes, and their combination is one of the fastest, as long as your code is not to slow. (Nginx+uWSGI is another good option, but a bit harder for beginners).</p> <p>Gunicorn can be installed with <code>pip install unicorn</code> or the same way you installed Django and then launched with simple <code>gunicorn yourproject.wsgi</code> (refer to docs for more configuration options).</p> <p>Nginx (use your distribution's package manager to install it) should be configured for reverse proxy mode and also to serve static/media files from your respective static/media root (<code>manage.py collectstatic</code> must be used to keep static files up-to-date). Read documentation to understand basic principles and use this except as an example for your <code>/etc/nginx/sites-enabled/yoursite.conf</code>:</p> <pre><code>server { listen 80 default; server_name example.com; root /path/to/project/root/static; location /media { alias /path/to/project/root/media; } location /static { alias /path/to/project/root/static; } location /favicon.ico { alias /path/to/project/root/static/favicon.ico; } location / { proxy_pass http://localhost:8000; include proxy_params; } } </code></pre> <p>There's more to it if you need ssl or www/non-www redirect (both are highly recommended to set up) but this example should be enough for you to get started.</p> <p>To run gunicorn automatically you can either use supervisor or system unit system (be it systemd or something else).</p> <p>Note: All of this assumes you're using linux. You probably should not use anything else on a production server anyway.</p> <p>Consider getting some professional help if you feel you can't understand how to deal with all this, there are many freelance sysadmins who would be happy to help you for a reasonable fee.</p>
0
2016-08-18T03:57:32Z
[ "python", "django", "apache", "production" ]
Showing a few figures without stopping calculations in matplotlib
39,007,654
<p>Hi I would like to show a few figures in matplotlib without stopping calculations. I would like the figure to show up right after the calculations that concern it are finished for example:</p> <pre><code>import numpy as np import pylab as py x=np.linspace(0,50,51) y=x fig, axs = plt.subplots(1, 1) cs = axs.plot(x, y) </code></pre> <p>now i want to show the plot without blocking the possibility to make some other calculations</p> <pre><code>plt.show(block=False) plt.pause(5) </code></pre> <p>I create the second plot</p> <pre><code>y1=2*x fig1, axs1 = plt.subplots(1, 1) cs1 = axs1.plot(x, y1) plt.show() </code></pre> <p>This works however the first freezes (after 5 secound pause which I added) until I call plt.show() at the end. It is crucial that the first figure shows and works, then after calculations another figure is added to it.</p>
0
2016-08-17T23:17:39Z
39,009,462
<p>The following code should do what you want. I did this in an IPython Notebook.</p> <pre><code>from IPython import display import matplotlib.pyplot as plt def stream_plot(iterable, plotlife=10.): for I in iterable: display.clear_output(wait=True) output = do_calculations_on_i(I) plt.plot(output) display.display(plt.gca()); time.sleep(plotlife); #how long to show the plot for </code></pre> <p>the wait=True will wait to clear the old plot until it has something new to plot, or any other output is printed.</p> <p>I put the sleep in there so I can observe each plot before it is wiped away. This was useful for having to observe distributions for several entities. You may or may not need it for what you want to do. </p>
0
2016-08-18T03:17:44Z
[ "python", "c++", "matplotlib" ]
How to turn my if statement into a while or for loop?
39,007,681
<p>So the program I'm trying to make is that an user can enter a path WHICH HAS TO BE CORRECT to continue. I thought that I would make a simple prompt to tell the user it is either a valid path or not.</p> <p>This is my prompt code:</p> <pre><code>if Path.find("Global") == -1: continue else: print "Not a valid path." </code></pre> <p>Of course I can't use continue in there but I just don't get how to make this prompt as a loop. The idea was that if the Path contains the word "Global" the program continues with another action and if it doesn't contain the word it will tell the user a message and tell the program to stop (break).</p>
0
2016-08-17T23:21:46Z
39,007,721
<p>Try this:</p> <pre><code>Path = raw_input("Please enter a valid Path") while Path.find("Global") == -1: print "This is not a valid Path." Path = raw_input("Please enter a valid Path") </code></pre>
-2
2016-08-17T23:26:23Z
[ "python" ]
How to turn my if statement into a while or for loop?
39,007,681
<p>So the program I'm trying to make is that an user can enter a path WHICH HAS TO BE CORRECT to continue. I thought that I would make a simple prompt to tell the user it is either a valid path or not.</p> <p>This is my prompt code:</p> <pre><code>if Path.find("Global") == -1: continue else: print "Not a valid path." </code></pre> <p>Of course I can't use continue in there but I just don't get how to make this prompt as a loop. The idea was that if the Path contains the word "Global" the program continues with another action and if it doesn't contain the word it will tell the user a message and tell the program to stop (break).</p>
0
2016-08-17T23:21:46Z
39,007,766
<pre><code>def get_path(): Path = raw_input("Please select the correct path: ") if Path.find("Global") == -1: # "Tell the user a message and tell the program to stop". print('{0} is not a correct path.'.format(Path)) return # "the program continues with another action." print('{0} is a correct path.'.format(Path)) </code></pre>
2
2016-08-17T23:30:45Z
[ "python" ]
How to turn my if statement into a while or for loop?
39,007,681
<p>So the program I'm trying to make is that an user can enter a path WHICH HAS TO BE CORRECT to continue. I thought that I would make a simple prompt to tell the user it is either a valid path or not.</p> <p>This is my prompt code:</p> <pre><code>if Path.find("Global") == -1: continue else: print "Not a valid path." </code></pre> <p>Of course I can't use continue in there but I just don't get how to make this prompt as a loop. The idea was that if the Path contains the word "Global" the program continues with another action and if it doesn't contain the word it will tell the user a message and tell the program to stop (break).</p>
0
2016-08-17T23:21:46Z
39,007,787
<p>You can break the loop unless your input matches condition, like this:</p> <pre><code>while True: if 'Global' in raw_input('Enter a valid path: '): continue else: print 'Not a valid path.' break </code></pre>
-1
2016-08-17T23:32:37Z
[ "python" ]
Exact string search in XML files?
39,007,743
<p>I need to search into some XML files (all of them have the same name, pom.xml) for the following text sequence exactly (also in subfolders), so in case somebody write some text or even a blank, I must get an alert:</p> <pre><code> &lt;!-- | Startsection |--&gt; &lt;!-- | Endsection |--&gt; </code></pre> <p>I'm running the following Python script, but still not matching exactly, I also get alert even when it's partially the text inside:</p> <pre><code>import re import os from os.path import join comment=re.compile(r"&lt;!--\s+| Startsection\s+|--&gt;\s+&lt;!--\s+| Endsection\s+|--&gt;") tag="&lt;module&gt;" for root, dirs, files in os.walk("."): if "pom.xml" in files: p=join(root, "pom.xml") print("Checking",p) with open(p) as f: s=f.read() if tag in s and comment.search(s): print("Matched",p) </code></pre> <p>UPDATE #3</p> <p>I am expecting to print out, the content of tag <code>&lt;module&gt;</code> if it exists between <code>|--&gt; &lt;!--</code> </p> <p>into the search:</p> <pre><code> &lt;!-- | Startsection |--&gt; &lt;!-- | Endsection |--&gt; </code></pre> <p>for instance print after Matched , and the name of the file, also print "example.test1" in the case below : </p> <pre><code> &lt;!-- | Startsection |--&gt; &lt;module&gt;example.test1&lt;/module&gt; &lt;!-- | Endsection |--&gt; </code></pre> <p>UPDATE #4</p> <p>Should be using the following :</p> <pre><code>import re import os from os.path import join comment=re.compile(r"&lt;!--\s+\| Startsection\s+\|--&gt;\s+&lt;!--\s+\| Endsection\s+\|--&gt;", re.MULTILINE) tag="&lt;module&gt;" for root, dirs, files in os.walk("/home/temp/test_folder/"): for skipped in ("test1", "test2", ".repotest"): if skipped in dirs: dirs.remove(skipped) if "pom.xml" in files: p=join(root, "pom.xml") print("Checking",p) with open(p) as f: s=f.read() if tag in s and comment.search(s): print("The following files are corrupted ",p) </code></pre> <p>UPDATE #5</p> <pre><code>import re import os import xml.etree.ElementTree as etree from bs4 import BeautifulSoup from bs4 import Comment from os.path import join comment=re.compile(r"&lt;!--\s+\| Startsection\s+\|--&gt;\s+&lt;!--\s+\| Endsection\s+\|--&gt;", re.MULTILINE) tag="&lt;module&gt;" for root, dirs, files in os.walk("myfolder"): for skipped in ("model", "doc"): if skipped in dirs: dirs.remove(skipped) if "pom.xml" in files: p=join(root, "pom.xml") print("Checking",p) with open(p) as f: s=f.read() if tag in s and comment.search(s): print("ERROR: The following file are corrupted",p) bs = BeautifulSoup(open(p), "html.parser") # Extract all comments comments=soup.find_all(string=lambda text:isinstance(text,Comment)) for c in comments: # Check if it's the start of the code if "Start of user code" in c: modules = [m for m in c.findNextSiblings(name='module')] for mod in modules: print(mod.text) </code></pre>
-1
2016-08-17T23:28:20Z
39,007,836
<p>The "|()" characters must be escaped, also add re.MULTILINE to the regex.</p> <p><code>comment=re.compile(r"&lt;!--\s+\| Start of user code \(user defined modules\)\s+\|--&gt;\s+&lt;!--\s+\| End of user code\s+\|--&gt;", re.MULTILINE)</code></p> <p>Edit: you can also place newline characters in your regex expression: \n</p> <p>Arbitrary (or no) white space would be: \s*</p> <p>You can find more information on python regex here: <a href="https://docs.python.org/2/library/re.html" rel="nofollow">https://docs.python.org/2/library/re.html</a></p>
0
2016-08-17T23:38:11Z
[ "python", "xml" ]
Exact string search in XML files?
39,007,743
<p>I need to search into some XML files (all of them have the same name, pom.xml) for the following text sequence exactly (also in subfolders), so in case somebody write some text or even a blank, I must get an alert:</p> <pre><code> &lt;!-- | Startsection |--&gt; &lt;!-- | Endsection |--&gt; </code></pre> <p>I'm running the following Python script, but still not matching exactly, I also get alert even when it's partially the text inside:</p> <pre><code>import re import os from os.path import join comment=re.compile(r"&lt;!--\s+| Startsection\s+|--&gt;\s+&lt;!--\s+| Endsection\s+|--&gt;") tag="&lt;module&gt;" for root, dirs, files in os.walk("."): if "pom.xml" in files: p=join(root, "pom.xml") print("Checking",p) with open(p) as f: s=f.read() if tag in s and comment.search(s): print("Matched",p) </code></pre> <p>UPDATE #3</p> <p>I am expecting to print out, the content of tag <code>&lt;module&gt;</code> if it exists between <code>|--&gt; &lt;!--</code> </p> <p>into the search:</p> <pre><code> &lt;!-- | Startsection |--&gt; &lt;!-- | Endsection |--&gt; </code></pre> <p>for instance print after Matched , and the name of the file, also print "example.test1" in the case below : </p> <pre><code> &lt;!-- | Startsection |--&gt; &lt;module&gt;example.test1&lt;/module&gt; &lt;!-- | Endsection |--&gt; </code></pre> <p>UPDATE #4</p> <p>Should be using the following :</p> <pre><code>import re import os from os.path import join comment=re.compile(r"&lt;!--\s+\| Startsection\s+\|--&gt;\s+&lt;!--\s+\| Endsection\s+\|--&gt;", re.MULTILINE) tag="&lt;module&gt;" for root, dirs, files in os.walk("/home/temp/test_folder/"): for skipped in ("test1", "test2", ".repotest"): if skipped in dirs: dirs.remove(skipped) if "pom.xml" in files: p=join(root, "pom.xml") print("Checking",p) with open(p) as f: s=f.read() if tag in s and comment.search(s): print("The following files are corrupted ",p) </code></pre> <p>UPDATE #5</p> <pre><code>import re import os import xml.etree.ElementTree as etree from bs4 import BeautifulSoup from bs4 import Comment from os.path import join comment=re.compile(r"&lt;!--\s+\| Startsection\s+\|--&gt;\s+&lt;!--\s+\| Endsection\s+\|--&gt;", re.MULTILINE) tag="&lt;module&gt;" for root, dirs, files in os.walk("myfolder"): for skipped in ("model", "doc"): if skipped in dirs: dirs.remove(skipped) if "pom.xml" in files: p=join(root, "pom.xml") print("Checking",p) with open(p) as f: s=f.read() if tag in s and comment.search(s): print("ERROR: The following file are corrupted",p) bs = BeautifulSoup(open(p), "html.parser") # Extract all comments comments=soup.find_all(string=lambda text:isinstance(text,Comment)) for c in comments: # Check if it's the start of the code if "Start of user code" in c: modules = [m for m in c.findNextSiblings(name='module')] for mod in modules: print(mod.text) </code></pre>
-1
2016-08-17T23:28:20Z
39,015,211
<p>Don't parse a XML file with regular expression. <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">The best Stackoverflow answer ever can explain you why</a></p> <p>You can use BeautifulSoup to help on that task</p> <p>Look how simple would be extract something from your code</p> <pre><code>from bs4 import BeautifulSoup content = """ &lt;!-- | Start of user code (user defined modules) |--&gt; &lt;!-- | End of user code |--&gt; """ bs = BeautifulSoup(content, "html.parser") print(''.join(bs.contents)) </code></pre> <p>Of course you can use your xml file instead of the literal I'm using</p> <pre><code>bs = BeautifulSoup(open("pom.xml"), "html.parser") </code></pre> <p>A small example using your expected input</p> <pre><code>from bs4 import BeautifulSoup from bs4 import Comment bs = BeautifulSoup(open(p), "html.parser") # Extract all comments comments=soup.find_all(string=lambda text:isinstance(text,Comment)) for c in comments: # Check if it's the start of the code if "Start of user code" in c: modules = [m for m in c.findNextSiblings(name='module')] for mod in modules: print(mod.text) </code></pre> <p>But if your code is always in a <strong>module</strong> tag I don't know why you should care about the comments before/after, you can just find the code inside the <strong>module</strong> tag directly</p>
1
2016-08-18T09:58:15Z
[ "python", "xml" ]
Can't find ghostscript in NLTK?
39,007,755
<p>I'm playing around with NLTK, when I try to use the chunk module </p> <pre><code>enter import nltk as nk Sentence = "Betty Botter bought some butter, but she said the butter is bitter, I f I put it in my batter, it will make my batter bitter." tokens = nk.word_tokenize(Sentence) tagged = nk.pos_tag(tokens) entities = nk.chunk.ne_chunk(tagged) </code></pre> <p>The code runs fine, when I type </p> <pre><code>&gt;&gt; entities </code></pre> <p>I get the following error message:</p> <pre><code>enter code here Out[2]: Tree('S', [Tree('PERSON', [('Betty', 'NNP')]), Tree('PERSON', [('Botter', 'NNP')]), ('bought', 'VBD'), ('some', 'DT'), ('butter', 'NN'), (',', ','), ('but', 'CC'), ('she', 'PRP'), ('said', 'VBD'), ('the', 'DT'), ('butter', 'NN'), ('is', 'VBZ'), ('bitter', 'JJ'), (',', ','), ('I', 'PRP'), ('f', 'VBP'), ('I', 'PRP'), ('put', 'VBD'), ('it', 'PRP'), ('in', 'IN'), ('my', 'PRP$'), ('batter', 'NN'), (',', ','), ('it', 'PRP'), ('will', 'MD'), ('make', 'VB'), ('my', 'PRP$'), ('batter', 'NN'), ('bitter', 'NN'), ('.', '.')])Traceback (most recent call last): File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\IPython\core\formatters.py", line 343, in __call__ return method() File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\tree.py", line 726, in _repr_png_ subprocess.call([find_binary('gs', binary_names=['gswin32c.exe', 'gswin64c.exe'], env_vars=['PATH'], verbose=False)] + File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 602, in find_binary binary_names, url, verbose)) File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 596, in find_binary_iter url, verbose): File "C:\Users\QP19\AppData\Local\Continuum\Anaconda2\lib\site-packages\nltk\internals.py", line 567, in find_file_iter raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div)) LookupError: =========================================================================== NLTK was unable to find the gs file! Use software specific configuration paramaters or set the PATH environment variable. =========================================================================== </code></pre> <p>According <a href="http://stackoverflow.com/a/37160385/3967806">to this post</a>, the solution is to install Ghostscript, since the chunker is trying to use it to display a parse tree, and is looking for one of 3 binaries: </p> <pre><code>file_names=['gs', 'gswin32c.exe', 'gswin64c.exe'] </code></pre> <p>to use. But even though I installed ghostscript and I can now find the binary in a windows search, but I am still getting the same error. </p> <p>What do I need to fix or update? </p> <hr> <p>Additional path information: </p> <pre><code>import os; print os.environ['PATH'] </code></pre> <p>Returns: </p> <pre><code>C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Scripts;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin;C:\Program Files (x86)\Parallels\Parallels Tools\Applications;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Oracle\RPAS14.1\RpasServer\bin;C:\Oracle\RPAS14.1\RpasServer\applib;C:\Program Files (x86)\Java\jre7\bin;C:\Program Files (x86)\Java\jre7\bin\client;C:\Program Files (x86)\Java\jre7\lib;C:\Program Files (x86)\Java\jre7\jre\bin\client;C:\Users\QP19\AppData\Local\Continuum\Anaconda2;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Scripts;C:\Users\QP19\AppData\Local\Continuum\Anaconda2\Library\bin; </code></pre>
1
2016-08-17T23:30:00Z
39,028,327
<p><strong>In short</strong>:</p> <p>Instead of <code>&gt;&gt;&gt; entities</code>, do this:</p> <pre><code>&gt;&gt;&gt; print entities.__repr__() </code></pre> <p>Or:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; from nltk import word_tokenize, pos_tag, ne_chunk &gt;&gt;&gt; path_to_gs = "C:\Program Files\gs\gs9.19\bin" &gt;&gt;&gt; os.environ['PATH'] += os.pathsep + path_to_gs &gt;&gt;&gt; sent = "Betty Botter bought some butter, but she said the butter is bitter, I f I put it in my batter, it will make my batter bitter." &gt;&gt;&gt; entities = ne_chunk(pos_tag(word_tokenize(sent))) &gt;&gt;&gt; entities </code></pre> <hr> <p><strong>In long</strong>:</p> <p>The problem lies in you trying to print the output of the <code>ne_chunk</code> and that will fire ghostscript to get the string and drawing representation of the NE tagged sentence, which is an <code>nltk.tree.Tree</code> object. And that will require ghostscript so you can use the widget to visualize it.</p> <p>Let's walkthrough this step by step.</p> <p>First when you use <code>ne_chunk</code>, you can directly import it at the top level as such:</p> <pre><code>from nltk import ne_chunk </code></pre> <p>And it's advisable to use namespaces for your imports, i.e.:</p> <pre><code>from nltk import word_tokenize, pos_tag, ne_chunk </code></pre> <p>And when you use <code>ne_chunk</code>, it comes from <a href="https://github.com/nltk/nltk/blob/develop/nltk/chunk/__init__.py" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/chunk/<strong>init</strong>.py</a></p> <p>It's unclear what kind of function is the pickle loading but after some inspection, we find that there's only one built-in NE chunker that isn't rule-based and since the name of the pickle binary states maxent, we can assume that it's a statistical chunker, so it most probably be comes from the <code>NEChunkParser</code> object in this: <a href="https://github.com/nltk/nltk/blob/develop/nltk/chunk/named_entity.py" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/chunk/named_entity.py</a> . There are ACE data API functions too, so as the name of the pickle binary.</p> <p>Now, whenever you can the <code>ne_chunk</code> function, it's actually calling the <code>NEChunkParser.parse()</code> function that returns a <code>nltk.tree.Tree</code> object: <a href="https://github.com/nltk/nltk/blob/develop/nltk/chunk/named_entity.py#L118" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/chunk/named_entity.py#L118</a></p> <pre><code>class NEChunkParser(ChunkParserI): """ Expected input: list of pos-tagged words """ def __init__(self, train): self._train(train) def parse(self, tokens): """ Each token should be a pos-tagged word """ tagged = self._tagger.tag(tokens) tree = self._tagged_to_parse(tagged) return tree def _train(self, corpus): # Convert to tagged sequence corpus = [self._parse_to_tagged(s) for s in corpus] self._tagger = NEChunkParserTagger(train=corpus) def _tagged_to_parse(self, tagged_tokens): """ Convert a list of tagged tokens to a chunk-parse tree. """ sent = Tree('S', []) for (tok,tag) in tagged_tokens: if tag == 'O': sent.append(tok) elif tag.startswith('B-'): sent.append(Tree(tag[2:], [tok])) elif tag.startswith('I-'): if (sent and isinstance(sent[-1], Tree) and sent[-1].label() == tag[2:]): sent[-1].append(tok) else: sent.append(Tree(tag[2:], [tok])) return sent </code></pre> <p>If we take a look at the <a href="https://github.com/nltk/nltk/blob/develop/nltk/tree.py" rel="nofollow"><code>nltk.tree.Tree</code></a>ject that's where the ghostscript problems appears when it's trying to call the <code>_repr_png_</code> function: <a href="https://github.com/nltk/nltk/blob/develop/nltk/tree.py#L702" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/tree.py#L702</a>:</p> <pre><code>def _repr_png_(self): """ Draws and outputs in PNG for ipython. PNG is used instead of PDF, since it can be displayed in the qt console and has wider browser support. """ import os import base64 import subprocess import tempfile from nltk.draw.tree import tree_to_treesegment from nltk.draw.util import CanvasFrame from nltk.internals import find_binary _canvas_frame = CanvasFrame() widget = tree_to_treesegment(_canvas_frame.canvas(), self) _canvas_frame.add_widget(widget) x, y, w, h = widget.bbox() # print_to_file uses scrollregion to set the width and height of the pdf. _canvas_frame.canvas()['scrollregion'] = (0, 0, w, h) with tempfile.NamedTemporaryFile() as file: in_path = '{0:}.ps'.format(file.name) out_path = '{0:}.png'.format(file.name) _canvas_frame.print_to_file(in_path) _canvas_frame.destroy_widget(widget) subprocess.call([find_binary('gs', binary_names=['gswin32c.exe', 'gswin64c.exe'], env_vars=['PATH'], verbose=False)] + '-q -dEPSCrop -sDEVICE=png16m -r90 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dSAFER -dBATCH -dNOPAUSE -sOutputFile={0:} {1:}' .format(out_path, in_path).split()) with open(out_path, 'rb') as sr: res = sr.read() os.remove(in_path) os.remove(out_path) return base64.b64encode(res).decode() </code></pre> <p>But note that it's strange that the python interpreter would fire <code>_repr_png</code> instead of <code>__repr__</code> when you use <code>&gt;&gt;&gt; entities</code> at the interpreter (see <a href="http://stackoverflow.com/questions/1984162/purpose-of-pythons-repr">Purpose of Python&#39;s __repr__</a>). It couldn't be how the native CPython interpreter work when trying to print out the representation of an object, so we take a look at <code>Ipython.core.formatters</code> and we see that it allows <code>_repr_png</code> to be fired at <a href="https://github.com/ipython/ipython/blob/master/IPython/core/formatters.py#L725" rel="nofollow">https://github.com/ipython/ipython/blob/master/IPython/core/formatters.py#L725</a>:</p> <pre><code>class PNGFormatter(BaseFormatter): """A PNG formatter. To define the callables that compute the PNG representation of your objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this. The return value of this formatter should be raw PNG data, *not* base64 encoded. """ format_type = Unicode('image/png') print_method = ObjectName('_repr_png_') _return_type = (bytes, unicode_type) </code></pre> <p>And we see that when IPython initializes a <code>DisplayFormatter</code> object, it tries to activate all formatters: <a href="https://github.com/ipython/ipython/blob/master/IPython/core/formatters.py#L66" rel="nofollow">https://github.com/ipython/ipython/blob/master/IPython/core/formatters.py#L66</a></p> <pre><code>def _formatters_default(self): """Activate the default formatters.""" formatter_classes = [ PlainTextFormatter, HTMLFormatter, MarkdownFormatter, SVGFormatter, PNGFormatter, PDFFormatter, JPEGFormatter, LatexFormatter, JSONFormatter, JavascriptFormatter ] d = {} for cls in formatter_classes: f = cls(parent=self) d[f.format_type] = f return d </code></pre> <p>Note that outside of <code>Ipython</code>, in the native CPython interpreter, it will only call the <code>__repr__</code> and not the <code>_repr_png</code>:</p> <pre><code>&gt;&gt;&gt; from nltk import ne_chunk &gt;&gt;&gt; from nltk import word_tokenize, pos_tag, ne_chunk &gt;&gt;&gt; Sentence = "Betty Botter bought some butter, but she said the butter is bitter, I f I put it in my batter, it will make my batter bitter." &gt;&gt;&gt; sentence = "Betty Botter bought some butter, but she said the butter is bitter, I f I put it in my batter, it will make my batter bitter." &gt;&gt;&gt; entities = ne_chunk(pos_tag(word_tokenize(sentence))) &gt;&gt;&gt; entities Tree('S', [Tree('PERSON', [('Betty', 'NNP')]), Tree('PERSON', [('Botter', 'NNP')]), ('bought', 'VBD'), ('some', 'DT'), ('butter', 'NN'), (',', ','), ('but', 'CC'), ('she', 'PRP'), ('said', 'VBD'), ('the', 'DT'), ('butter', 'NN'), ('is', 'VBZ'), ('bitter', 'JJ'), (',', ','), ('I', 'PRP'), ('f', 'VBP'), ('I', 'PRP'), ('put', 'VBD'), ('it', 'PRP'), ('in', 'IN'), ('my', 'PRP$'), ('batter', 'NN'), (',', ','), ('it', 'PRP'), ('will', 'MD'), ('make', 'VB'), ('my', 'PRP$'), ('batter', 'NN'), ('bitter', 'NN'), ('.', '.')]) </code></pre> <hr> <p>So now the solution:</p> <p><strong>Solution 1</strong>:</p> <p>When printing out the string output of the <code>ne_chunk</code>, you can use </p> <pre><code>&gt;&gt;&gt; print entities.__repr__() </code></pre> <p>instead of <code>&gt;&gt;&gt; entities</code> that way, IPython should explicitly call only the <code>__repr__</code> instead of call all possible formatters.</p> <p><strong>Solution 2</strong></p> <p>If you really need to use the <code>_repr_png_</code> to visualize the Tree object, then we will need to figure out how to add the ghostscript binary to the NLTK environmental variables. </p> <p>In your case, it seems like the default <code>nltk.internals</code> are unable to find the binary. More specifically, we're referring to <a href="https://github.com/nltk/nltk/blob/develop/nltk/internals.py#L599" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/internals.py#L599</a></p> <p>If we go back to <a href="https://github.com/nltk/nltk/blob/develop/nltk/tree.py#L726" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/tree.py#L726</a>, we see that, it's trying to look for the </p> <pre><code>env_vars=['PATH'] </code></pre> <p>And when NLTK tries to initialize it's environment variables, it is looking at <code>os.environ</code>, see <a href="https://github.com/nltk/nltk/blob/develop/nltk/internals.py#L495" rel="nofollow">https://github.com/nltk/nltk/blob/develop/nltk/internals.py#L495</a></p> <p>Note that <code>find_binary</code> calls <code>find_binary_iter</code> which calls <code>find_binary_iter</code> that tries to look for the <code>env_vars</code> by fetching <code>os.environ</code></p> <p>So if we add to the path:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; from nltk import word_tokenize, pos_tag, ne_chunk &gt;&gt;&gt; path_to_gs = "C:\Program Files\gs\gs9.19\bin" &gt;&gt;&gt; os.environ['PATH'] += os.pathsep + path_to_gs </code></pre> <p>Now this should work in Ipython:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; from nltk import word_tokenize, pos_tag, ne_chunk &gt;&gt;&gt; path_to_gs = "C:\Program Files\gs\gs9.19\bin" &gt;&gt;&gt; os.environ['PATH'] += os.pathsep + path_to_gs &gt;&gt;&gt; sent = "Betty Botter bought some butter, but she said the butter is bitter, I f I put it in my batter, it will make my batter bitter." &gt;&gt;&gt; entities = ne_chunk(pos_tag(word_tokenize(sent))) &gt;&gt;&gt; entities </code></pre>
1
2016-08-18T22:16:03Z
[ "python", "environment-variables", "ipython", "nltk", "ghostscript" ]
PyQt - Tabbed dialog not displaying embedded widgets
39,007,773
<p>I am trying to create a dialog with three tabs using PyQt. However, I am annoyed because although the dialog is displayed, the embedded widgets are not displayed!. I suppose this is a very simple problem with a correspondingly very simple solution, but I am struck! Can anyone give a hint? Thanks in advance!</p> <p>Here is my code so far:</p> <pre><code>import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class TabbedDialog(QDialog): def __init__(self, parent = None): super(TabbedDialog, self).__init__(parent) self.tabWidget = QTabWidget() self.tabWidget.tab1 = QWidget() self.tabWidget.tab2 = QWidget() self.tabWidget.tab3 = QWidget() self.tabWidget.addTab(self.tabWidget.tab1,"Tab 1") self.tabWidget.addTab(self.tabWidget.tab2,"Tab 2") self.tabWidget.addTab(self.tabWidget.tab3,"Tab 3") self.tab1UI() self.tab2UI() self.tab3UI() self.setWindowTitle("tab demo") def tab1UI(self): layout = QFormLayout() layout.addRow("Name",QLineEdit()) layout.addRow("Address",QLineEdit()) self.tabWidget.setTabText(0,"Contact Details") self.tabWidget.tab1.setLayout(layout) def tab2UI(self): layout = QFormLayout() sex = QHBoxLayout() sex.addWidget(QRadioButton("Male")) sex.addWidget(QRadioButton("Female")) layout.addRow(QLabel("Sex"),sex) layout.addRow("Date of Birth",QLineEdit()) self.tabWidget.setTabText(1,"Personal Details") self.tabWidget.tab2.setLayout(layout) def tab3UI(self): layout = QHBoxLayout() layout.addWidget(QLabel("subjects")) layout.addWidget(QCheckBox("Physics")) layout.addWidget(QCheckBox("Maths")) self.tabWidget.setTabText(2,"Education Details") self.tabWidget.tab3.setLayout(layout) if __name__ == '__main__': app = QApplication(sys.argv) form = TabbedDialog() retval = form.exec_() </code></pre>
0
2016-08-17T23:31:48Z
39,007,926
<p>here is my solution to the problem</p> <p>On the <strong>init</strong> method, I declared a layout, then added the 'tabWidget' widget to that layout and set that layout as the layout of your QDialog.</p> <pre><code>def __init__(self, parent = None): super(TabbedDialog, self).__init__(parent) self.tabWidget = QTabWidget() self.tabWidget.tab1 = QWidget() self.tabWidget.tab2 = QWidget() self.tabWidget.tab3 = QWidget() self.tabWidget.addTab(self.tabWidget.tab1,"Tab 1") self.tabWidget.addTab(self.tabWidget.tab2,"Tab 2") self.tabWidget.addTab(self.tabWidget.tab3,"Tab 3") self.tab1UI() self.tab2UI() self.tab3UI() self.setWindowTitle("tab demo") # Here is the addition to the code. mainLayout = QVBoxLayout() mainLayout.addWidget(self.tabWidget) self.setLayout(mainLayout) </code></pre>
1
2016-08-17T23:50:03Z
[ "python", "pyqt4", "tabwidget" ]
jpype accessing java mehtod/variable whose name is reserved name in python
39,007,823
<p>Any idea how this can be done? ie, if we have a variable defined in java as below</p> <p><code>public Class Foo { String pass = "foo"; }</code></p> <p>how can I access this via jpype since pass is a reserved keyword? I tried <code>getattr(Jpype.JClass(Foo)(), "pass")</code> but it fails to find the attribute named pass</p>
0
2016-08-17T23:37:01Z
39,007,952
<p>unfortunally Fields or methods conflicting with a python keyword can’t be accessed</p>
0
2016-08-17T23:52:18Z
[ "java", "python", "type-conversion", "reserved-words", "jpype" ]
jpype accessing java mehtod/variable whose name is reserved name in python
39,007,823
<p>Any idea how this can be done? ie, if we have a variable defined in java as below</p> <p><code>public Class Foo { String pass = "foo"; }</code></p> <p>how can I access this via jpype since pass is a reserved keyword? I tried <code>getattr(Jpype.JClass(Foo)(), "pass")</code> but it fails to find the attribute named pass</p>
0
2016-08-17T23:37:01Z
39,027,662
<p>Figured out that jpype appends an <code>"_"</code> at the end for those methods/fields in its source code. So you can access it by Jpype.JClass("Foo").pass_</p> <p>Wish it's documented somewhere </p>
0
2016-08-18T21:17:35Z
[ "java", "python", "type-conversion", "reserved-words", "jpype" ]
How to send a Python Variable to shell commands?
39,007,826
<p>I am trying to send a variable from my code in Python to a shell command in Ubuntu. Can anyone help me with how to do that? Currently, I have</p> <pre><code>import os s=5 command = os.popen('stress -c 5 -i 1 -m 1 --vm-bytes 128M -t s') </code></pre> <p>I want to send the <code>s</code> variable to this command instead of directly say the time of time-out. </p>
0
2016-08-17T23:37:18Z
39,007,855
<p>This is a string replacement operation which you can get all the info <a href="https://docs.python.org/2/library/stdtypes.html#string-formatting" rel="nofollow">here</a>.</p> <p>Or you can just concatenate the strings together. (<a href="http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python" rel="nofollow">good tutorial</a>)</p>
-2
2016-08-17T23:40:40Z
[ "python", "bash", "shell" ]
How to send a Python Variable to shell commands?
39,007,826
<p>I am trying to send a variable from my code in Python to a shell command in Ubuntu. Can anyone help me with how to do that? Currently, I have</p> <pre><code>import os s=5 command = os.popen('stress -c 5 -i 1 -m 1 --vm-bytes 128M -t s') </code></pre> <p>I want to send the <code>s</code> variable to this command instead of directly say the time of time-out. </p>
0
2016-08-17T23:37:18Z
39,007,863
<p>I'm assuming the 's' in your command string is what you want to assume the value of your variable 's'? All you need to do is this:</p> <pre><code>command = os.popen('stress -c 5 -i 1 -m 1 --vm-bytes 128M -t ' + str(s)) </code></pre> <p>If I misread it and you are trying to replace the 5, it is basically the same</p> <pre><code>command = os.popen('stress -c ' + str(s) + ' -i 1 -m 1 --vm-bytes 128M -t s') </code></pre>
0
2016-08-17T23:41:43Z
[ "python", "bash", "shell" ]
How to send a Python Variable to shell commands?
39,007,826
<p>I am trying to send a variable from my code in Python to a shell command in Ubuntu. Can anyone help me with how to do that? Currently, I have</p> <pre><code>import os s=5 command = os.popen('stress -c 5 -i 1 -m 1 --vm-bytes 128M -t s') </code></pre> <p>I want to send the <code>s</code> variable to this command instead of directly say the time of time-out. </p>
0
2016-08-17T23:37:18Z
39,007,922
<p>Use the standard subprocess module:</p> <pre><code>import subprocess s = 5 cmd = ['stress', '-c', '5', '-i', '1', '-m', '1', '--vm-bytes', '128M', '-t', str(s)] subprocess.call(cmd) </code></pre> <p>Using the subprocess module, allows each argument to be passed separately and distinctly. You only have to convert them to strings.</p>
4
2016-08-17T23:49:37Z
[ "python", "bash", "shell" ]
Python webscraping script on AWS keeps failing after 1.5 hours/fetching 10,000 xmls
39,007,827
<p>I wrote a Python script that runs from an AWS instance and fetches xml files off an S3 server to place in a folder on the instance. The script works fine, except for the fact that after about an hour and a half, or about the time it takes to fetch 10,000-15,000 xmls, I get the following error:</p> <pre><code>HTTP Error 500: Internal Server Error </code></pre> <p>Following this error, I am told that the folder I tell the script to place the fetched xml in can't be found, i.e. </p> <pre><code>[Errno 2] No such file or directory: </code></pre> <p>I have tried running this script both from ssh, using screen and using nohup, but I get the same issue each time. As I have about 200,000 xmls to fetch, I'd like to just run this script once and go do something else for the 20+ hours it needs to run. </p> <p>For reference, the script I wrote is below:</p> <pre><code>import os import feather df = feather.read_dataframe('avail.feather') import xmltodict urls = df['URL'] import urllib.request import time import requests ticker=0 start = time.time() for u in urls[ticker:len(urls)]: #os.chdir('/home/stan/Documents/Dissertation Idea Box/IRS_Data') ticker += 1 print("Starting URL",ticker, "of", len(urls),"........." ,(ticker/len(urls))*100, "percent done") if u is None: print("NO FILING") end = time.time() m, s = divmod(end-start, 60) h, m = divmod(m, 60) print("Elapsed Time:","%02d:%02d:%02d" % (h, m, s)) continue u = u.replace('https','http') r = requests.get(u) doc = xmltodict.parse(r.content) try: os.chdir("irs990s") urllib.request.urlretrieve(u, u.replace('http://s3.amazonaws.com/irs-form-990/','')) print("FETCHED!","..........",u) except Exception as e: print("ERROR!!!","..........",u) print(e) end = time.time() m, s = divmod(end-start, 60) h, m = divmod(m, 60) print("Elapsed Time:","%02d:%02d:%02d" % (h, m, s)) continue end = time.time() m, s = divmod(end-start, 60) h, m = divmod(m, 60) print("Elapsed Time:","%02d:%02d:%02d" % (h, m, s)) os.chdir('..') </code></pre>
1
2016-08-17T23:37:30Z
39,009,701
<p>I don't know the first thing about python, but the problem seems apparent enough, all the same.</p> <p>When the S3 error occurs, you <a href="https://docs.python.org/3/reference/simple_stmts.html#continue" rel="nofollow"><code>continue</code></a>, which skips the rest of the instructions within the closest loop, and continues with the next value, from the top of the loop... and this skips <code>os.chdir('..')</code> at the end of the loop, so your current working directory is still <code>irs990s</code>. On the next iteration, <code>os.chdir("irs990s")</code> will, of course, fail, because that is trying to find a directory called <code>irs990s</code> <em>inside</em> the then-current directory, which is of course already <code>irs990s</code>, so that would of course fail.</p> <p>There are a couple of lessons, here. </p> <p>Don't keep switching in and out of a directory using <code>os.chdir('..')</code> -- that's very bad form, prone to subtle bugs. Case in point, see above. Use absolute paths. If you really want relative paths, that's fine, but don't do it this way. Capture the working directory at startup or configure a base working directory and use that to fully-qualify your paths with chdir.</p> <p>Design your code to anticipate occasional errors from S3, or any web service, from any provider, and retry 5XX errors after a brief, incrementing delay -- <a href="http://docs.aws.amazon.com/general/latest/gr/api-retries.html" rel="nofollow">exponential backoff</a>.</p>
2
2016-08-18T03:49:05Z
[ "python", "linux", "amazon-web-services", "amazon-s3", "nohup" ]
Dynamically Update WTForm with SQL-Alchemy query
39,007,862
<p>I am trying to have a form dynamically update by retrieving information from my table then display one of the columns in a SelectField. When I type an asset tag, select a Task Title and hit submit simply nothing happens.</p> <p><strong>EDIT: I should add the form is updating fine - all my selections are there and being retrieved successfully. It's simply not executing any of my view function after that.</strong></p> <p>My form is as follows;</p> <pre><code>class AssignTasksForm(Form): asset_tag = StringField('asset_tag', validators=[DataRequired()]) task_title = SelectField('task_title', validators=[DataRequired()]) </code></pre> <p>My view function;</p> <pre><code>@tasks_blueprint.route('/assign_tasks', methods=['GET', 'POST']) @login_required def assign_tasks(): form = AssignTasksForm() form.task_title.choices = [(tc.task_id, tc.task_title) for tc in Tasks.query.order_by('task_id')] if request.method == 'POST': if form.validate_on_submit(): try: asset_tag = form.asset_tag.data asset = Motor.query.filter_by(asset_tag = asset_tag).first_or_404() task_title = form.task_title.data task = Tasks.query.filter_by(task_title = task_title).first_or_404() task.asset_tasks.append(asset) db.session.commit() except Exception as e: flash(e) db.session.rollback() return render_template('assign_tasks.html', form=form) </code></pre> <p>My terminal output leads me to believe the form may be becoming invalidated after the data is retrieved from the table:</p> <pre><code>2016-08-17 18:21:56,568 INFO sqlalchemy.engine.base.Engine {'id_1': 1, 'param_1': 1} 2016-08-17 18:21:56,577 INFO sqlalchemy.engine.base.Engine SELECT tasks."Task Title" AS "tasks_Task Title", tasks."Description" AS "tasks_Description", tasks.task_id AS tasks_task_id FROM tasks ORDER BY tasks.task_id 2016-08-17 18:21:56,577 INFO sqlalchemy.engine.base.Engine {} 108.168.36.217 - - [17/Aug/2016 18:21:56] "POST /tasks/assign_tasks HTTP/1.1" 200 - </code></pre> <p>You can see it run the query outlined in view and then post the webpage but it simply does not continue executing the rest of the view function.</p> <p>Here is my template:</p> <pre><code>{% extends "basehead.html" %} {% block content %} &lt;center&gt; &lt;div class="container"&gt; &lt;h2&gt;Assign Tasks Below&lt;/h2&gt; &lt;br&gt; &lt;form action="" method="post" name="submit"&gt; {{ form.hidden_tag() }} &lt;p&gt; {{ form.asset_tag(placeholder=" Enter Asset Tag") }} &lt;/p&gt; &lt;p&gt; {{ form.task_title }} &lt;/p&gt; &lt;input class="btn btn-default" type="submit" value="Submit"&gt; &lt;/form&gt; &lt;/div&gt; {% if result_message %} &lt;br&gt; &lt;p class="result_message"&gt; {{ result_message }} &lt;/p&gt; &lt;/br&gt; {% endif %} &lt;/center&gt; {% endblock %} </code></pre>
0
2016-08-17T23:41:37Z
39,008,940
<p>Try the following. <a href="http://hastebin.com/obojivosar.py" rel="nofollow">http://hastebin.com/obojivosar.py</a></p> <p>You don't need to check <code>if request.method == "POST":</code> I simply moved the populating of the choices to the bottom of the view. I never touch the form before <code>validate_on_submit</code> Also how does <code>result_message</code> get into the context of the template?</p>
1
2016-08-18T02:15:31Z
[ "python", "flask", "sqlalchemy", "flask-wtforms" ]
Dynamically Update WTForm with SQL-Alchemy query
39,007,862
<p>I am trying to have a form dynamically update by retrieving information from my table then display one of the columns in a SelectField. When I type an asset tag, select a Task Title and hit submit simply nothing happens.</p> <p><strong>EDIT: I should add the form is updating fine - all my selections are there and being retrieved successfully. It's simply not executing any of my view function after that.</strong></p> <p>My form is as follows;</p> <pre><code>class AssignTasksForm(Form): asset_tag = StringField('asset_tag', validators=[DataRequired()]) task_title = SelectField('task_title', validators=[DataRequired()]) </code></pre> <p>My view function;</p> <pre><code>@tasks_blueprint.route('/assign_tasks', methods=['GET', 'POST']) @login_required def assign_tasks(): form = AssignTasksForm() form.task_title.choices = [(tc.task_id, tc.task_title) for tc in Tasks.query.order_by('task_id')] if request.method == 'POST': if form.validate_on_submit(): try: asset_tag = form.asset_tag.data asset = Motor.query.filter_by(asset_tag = asset_tag).first_or_404() task_title = form.task_title.data task = Tasks.query.filter_by(task_title = task_title).first_or_404() task.asset_tasks.append(asset) db.session.commit() except Exception as e: flash(e) db.session.rollback() return render_template('assign_tasks.html', form=form) </code></pre> <p>My terminal output leads me to believe the form may be becoming invalidated after the data is retrieved from the table:</p> <pre><code>2016-08-17 18:21:56,568 INFO sqlalchemy.engine.base.Engine {'id_1': 1, 'param_1': 1} 2016-08-17 18:21:56,577 INFO sqlalchemy.engine.base.Engine SELECT tasks."Task Title" AS "tasks_Task Title", tasks."Description" AS "tasks_Description", tasks.task_id AS tasks_task_id FROM tasks ORDER BY tasks.task_id 2016-08-17 18:21:56,577 INFO sqlalchemy.engine.base.Engine {} 108.168.36.217 - - [17/Aug/2016 18:21:56] "POST /tasks/assign_tasks HTTP/1.1" 200 - </code></pre> <p>You can see it run the query outlined in view and then post the webpage but it simply does not continue executing the rest of the view function.</p> <p>Here is my template:</p> <pre><code>{% extends "basehead.html" %} {% block content %} &lt;center&gt; &lt;div class="container"&gt; &lt;h2&gt;Assign Tasks Below&lt;/h2&gt; &lt;br&gt; &lt;form action="" method="post" name="submit"&gt; {{ form.hidden_tag() }} &lt;p&gt; {{ form.asset_tag(placeholder=" Enter Asset Tag") }} &lt;/p&gt; &lt;p&gt; {{ form.task_title }} &lt;/p&gt; &lt;input class="btn btn-default" type="submit" value="Submit"&gt; &lt;/form&gt; &lt;/div&gt; {% if result_message %} &lt;br&gt; &lt;p class="result_message"&gt; {{ result_message }} &lt;/p&gt; &lt;/br&gt; {% endif %} &lt;/center&gt; {% endblock %} </code></pre>
0
2016-08-17T23:41:37Z
39,009,284
<p>I found the issue,</p> <p>WTForms wants to handle the returned data from the query as a string, however the IDs (integers) obviously are not strings, which must be why validation fails.</p> <p>By adding <code>coerce=int</code> to my <code>task_title</code> object in my form definition WTForms now knows to handle it as an int and passes validation.</p> <p>Fixed code:</p> <pre><code>class AssignTasksForm(Form): asset_tag = StringField('asset_tag', validators=[DataRequired()]) task_title = SelectField('task_title', coerce=int, validators=[DataRequired()]) </code></pre> <p>Source: <a href="http://stackoverflow.com/questions/13964152/not-a-valid-choice-for-dynamic-select-field-wtforms">Not a Valid Choice for Dynamic Select Field WTFORMS</a></p>
0
2016-08-18T02:55:43Z
[ "python", "flask", "sqlalchemy", "flask-wtforms" ]
getting article text using xpath but omit some tags
39,007,866
<p>I'm trying to parse (article) text only using xpath.</p> <p>I want to get all text which are direct children and all nested descendants text of a node, except for the following nodes/tags: <code>&lt;script&gt;, &lt;ul class="pager pagenav"&gt;, &lt;style&gt;</code>.</p> <p>Example html to match using xpath:</p> <pre><code>&lt;section class="entry-content"&gt; want this article text &lt;script&gt;dont want this&lt;/script&gt; more text i want &lt;p&gt;want this text too&lt;/p&gt; &lt;any&gt;also this&lt;/any&gt; &lt;style&gt;dont want this either&lt;/style&gt; &lt;ul class="pager pagenav"&gt;nope, dont want this &lt;a&gt;Prev Next&lt;/a&gt;&lt;/ul&gt; &lt;/section&gt; </code></pre> <p>Currently, i have something like:</p> <pre><code> result = tree.xpath('//section[@class="entry-content"]/*[not(descendant-or-self::script or self::ul[@class="pager pagenav"] or self::style)]/../descendant-or-self::text()') </code></pre> <p>..but it doesn't quite work.</p>
1
2016-08-17T23:42:25Z
39,007,929
<p>Use the <a href="https://www.w3.org/TR/xpath/#location-paths" rel="nofollow"><code>child::node()</code></a> to match both regular children and text child nodes: </p> <blockquote> <p><code>child::node()</code> selects all the children of the context node, whatever their node type</p> </blockquote> <p><code>self::</code> would help to filter unwanted elements having specific names: </p> <pre><code>//section[@class="entry-content"]/child::node()[not(self::script or self::ul or self::style)]/descendant-or-self::text() </code></pre>
1
2016-08-17T23:50:24Z
[ "python", "xpath" ]
Python array manipulation, pi*[n+1]^2 - pi*[n]^2
39,007,880
<p>I'm writing a script to subtract the inside cylinder from the outside cylinder for multiple cylinders.</p> <p>for example: <code>x = pi*[n+1]**2 - pi*[n]**2</code> </p> <p>However I'm not sure how to get n to change each time from for example 1 - 4, i want to be able to change n and have the code run through the new values without having to change everything.</p> <pre><code>x = pi*[1]**2 - pi*[0]**2 x = pi*[2]**2 - pi*[1]**2 x = pi*[3]**2 - pi*[2]**2 x = pi*[4]**2 - pi*[3]**2 </code></pre> <p>I was trying to get a while loop to work but i cant figure out how to reference n without specifically stating which number in the array i want to reference.</p> <p>Any help would be greatly appreciated.</p> <pre><code>rs = 0.2 # Radius of first cylinder rc = 0.4 # Radius of each cylinder (concrete) rg = 1 # Radius of each cylinder (soil) BW = 3 # No. cylinders (concrete) BG = 2 # No. cylinders (soil) v1 = np.linspace(rs, rc, num=BW) # Cylinders (concrete) v2 = np.linspace(rc * 1.5, rg, num=BG) # Cylinders (soil) n = np.concatenate((v1, v2)) # Combined cylinders for i in range(BW + BG): x = np.pi * (n[i + 1] ** 2) - np.pi * (n[i] ** 2) </code></pre>
1
2016-08-17T23:44:22Z
39,007,912
<p>Try this:</p> <pre><code>for n in range(4): # 0 to 3 x = pi*[n+1]**2 - pi*[n]**2 #[1] - [0], [2] - [1] and so on... # doSomething </code></pre> <p>If <code>[n]</code> is an index of an array with name <code>num</code>, replace <code>[n]</code> with <code>num[n]</code> like so:</p> <pre><code>for n in range(4): # 0 to 3 x = pi*(num[n+1]**2) - pi*(num[n]**2) #[1] - [0], [2] - [1] and so on... # doSomething </code></pre> <p>If instead it was simply <code>n</code>, replace <code>[n]</code> with <code>n</code> like so:</p> <pre><code>for n in range(4): # 0 to 3 x = pi*((n+1)**2) - pi*(n**2) #[1] - [0], [2] - [1] and so on... # doSomething </code></pre>
2
2016-08-17T23:48:25Z
[ "python", "arrays", "loops" ]
Python array manipulation, pi*[n+1]^2 - pi*[n]^2
39,007,880
<p>I'm writing a script to subtract the inside cylinder from the outside cylinder for multiple cylinders.</p> <p>for example: <code>x = pi*[n+1]**2 - pi*[n]**2</code> </p> <p>However I'm not sure how to get n to change each time from for example 1 - 4, i want to be able to change n and have the code run through the new values without having to change everything.</p> <pre><code>x = pi*[1]**2 - pi*[0]**2 x = pi*[2]**2 - pi*[1]**2 x = pi*[3]**2 - pi*[2]**2 x = pi*[4]**2 - pi*[3]**2 </code></pre> <p>I was trying to get a while loop to work but i cant figure out how to reference n without specifically stating which number in the array i want to reference.</p> <p>Any help would be greatly appreciated.</p> <pre><code>rs = 0.2 # Radius of first cylinder rc = 0.4 # Radius of each cylinder (concrete) rg = 1 # Radius of each cylinder (soil) BW = 3 # No. cylinders (concrete) BG = 2 # No. cylinders (soil) v1 = np.linspace(rs, rc, num=BW) # Cylinders (concrete) v2 = np.linspace(rc * 1.5, rg, num=BG) # Cylinders (soil) n = np.concatenate((v1, v2)) # Combined cylinders for i in range(BW + BG): x = np.pi * (n[i + 1] ** 2) - np.pi * (n[i] ** 2) </code></pre>
1
2016-08-17T23:44:22Z
39,007,951
<p>I think this should provide the results you are looking for:</p> <pre><code>rs = 0.2 # Radius of first cylinder rc = 0.4 # Radius of each cylinder (concrete) rg = 1 # Radius of each cylinder (soil) BW = 3 # No. cylinders (concrete) BG = 2 # No. cylinders (soil) v1 = np.linspace(rs, rc, num=BW) # Cylinders (concrete) v2 = np.linspace(rc * 1.5, rg, num=BG) # Cylinders (soil) n = np.concatenate((v1, v2)) results = [] for i, v in enumerate(n): if i+1 &lt; len(n): results.append(pi * n[i+1] ** 2 - pi * v ** 2) else: break </code></pre>
-1
2016-08-17T23:52:15Z
[ "python", "arrays", "loops" ]
Python array manipulation, pi*[n+1]^2 - pi*[n]^2
39,007,880
<p>I'm writing a script to subtract the inside cylinder from the outside cylinder for multiple cylinders.</p> <p>for example: <code>x = pi*[n+1]**2 - pi*[n]**2</code> </p> <p>However I'm not sure how to get n to change each time from for example 1 - 4, i want to be able to change n and have the code run through the new values without having to change everything.</p> <pre><code>x = pi*[1]**2 - pi*[0]**2 x = pi*[2]**2 - pi*[1]**2 x = pi*[3]**2 - pi*[2]**2 x = pi*[4]**2 - pi*[3]**2 </code></pre> <p>I was trying to get a while loop to work but i cant figure out how to reference n without specifically stating which number in the array i want to reference.</p> <p>Any help would be greatly appreciated.</p> <pre><code>rs = 0.2 # Radius of first cylinder rc = 0.4 # Radius of each cylinder (concrete) rg = 1 # Radius of each cylinder (soil) BW = 3 # No. cylinders (concrete) BG = 2 # No. cylinders (soil) v1 = np.linspace(rs, rc, num=BW) # Cylinders (concrete) v2 = np.linspace(rc * 1.5, rg, num=BG) # Cylinders (soil) n = np.concatenate((v1, v2)) # Combined cylinders for i in range(BW + BG): x = np.pi * (n[i + 1] ** 2) - np.pi * (n[i] ** 2) </code></pre>
1
2016-08-17T23:44:22Z
39,008,152
<p>How about this:</p> <pre><code>for i, value in enumerate(n[:-1]): print(np.pi * (n[i + 1] ** 2) - np.pi * (value ** 2)) </code></pre> <p>For me it prints:</p> <pre><code>0.157079632679 0.219911485751 0.628318530718 2.0106192983 </code></pre> <p>Perhaps you want this:</p> <pre><code>&gt;&gt;&gt; values = [np.pi * (n[i + 1] ** 2) - np.pi * (value ** 2) for i, value in enumerate(n[:-1])] &gt;&gt;&gt; values [0.15707963267948971, 0.2199114857512855, 0.62831853071795885, 2.0106192982974673] </code></pre> <p>Lets explain it:</p> <ul> <li>we must get all elements in the list but the last, because <code>n[i + 1]</code> fails for the last item, so we use <code>n[0:-1]</code> (we are allowed omit the start of the slice if it is 0 or the end if it is equal or greater than <code>len(n)</code>).</li> <li><code>enumerate(a_list)</code> returns something resembling a list of pairs in the form<br> <code>[(0, a_list[0]), (1, a_list[1]), ..., (n, a_list[n)]</code></li> <li><code>for i, value in ...</code> unpacks each pair into variables named <code>i</code> and <code>value</code></li> <li><code>[something for something in a_list]</code> returns a new list. You may do calculations, and filter the values. For example, if you want a list of the square of the even integers bellow 10:<br> <code>&gt;&gt;&gt; [x * x for x in range(10) if x % 2 == 1]</code><br> <code>[1, 9, 25, 49, 81]</code></li> </ul>
1
2016-08-18T00:21:31Z
[ "python", "arrays", "loops" ]
Python array manipulation, pi*[n+1]^2 - pi*[n]^2
39,007,880
<p>I'm writing a script to subtract the inside cylinder from the outside cylinder for multiple cylinders.</p> <p>for example: <code>x = pi*[n+1]**2 - pi*[n]**2</code> </p> <p>However I'm not sure how to get n to change each time from for example 1 - 4, i want to be able to change n and have the code run through the new values without having to change everything.</p> <pre><code>x = pi*[1]**2 - pi*[0]**2 x = pi*[2]**2 - pi*[1]**2 x = pi*[3]**2 - pi*[2]**2 x = pi*[4]**2 - pi*[3]**2 </code></pre> <p>I was trying to get a while loop to work but i cant figure out how to reference n without specifically stating which number in the array i want to reference.</p> <p>Any help would be greatly appreciated.</p> <pre><code>rs = 0.2 # Radius of first cylinder rc = 0.4 # Radius of each cylinder (concrete) rg = 1 # Radius of each cylinder (soil) BW = 3 # No. cylinders (concrete) BG = 2 # No. cylinders (soil) v1 = np.linspace(rs, rc, num=BW) # Cylinders (concrete) v2 = np.linspace(rc * 1.5, rg, num=BG) # Cylinders (soil) n = np.concatenate((v1, v2)) # Combined cylinders for i in range(BW + BG): x = np.pi * (n[i + 1] ** 2) - np.pi * (n[i] ** 2) </code></pre>
1
2016-08-17T23:44:22Z
39,008,303
<p>Since your numbers are in a numpy array, it's much more efficient to use broadcast operations across the array (or slices of it), rather than writing a explicit loop and operating on individual items. This is the main reason to use numpy!</p> <p>Try something like this:</p> <pre><code># compute your `n` array as before areas = pi * n**2 # this will be a new array with the area of each cylinder area_differences = areas[1:] - areas[:-1] # differences in area between adjacent cylinders </code></pre>
2
2016-08-18T00:44:20Z
[ "python", "arrays", "loops" ]
Removing List view for ArrayField Django
39,007,892
<p>How would I display the ArrayField in a template without the quotes and brackets. currently it looks like ['django']. I would like to have it look like: django</p> <p>Any suggestions would be great. </p>
0
2016-08-17T23:46:15Z
39,009,360
<p>If you need only the first value:</p> <pre><code>{{ object.arrya_field_name.0 }} </code></pre> <p>or with filter</p> <pre><code>{{ object.arrya_field_name|first }} </code></pre> <p>If you need all values, use loop:</p> <pre><code>{% for item in object.arrya_field_name %} {{ item }} {% endfor %} </code></pre> <p>or filter</p> <pre><code>{{ object.arrya_field_name|join:", " }} </code></pre>
0
2016-08-18T03:05:37Z
[ "python", "django" ]
5 most common words in text file python
39,007,968
<p>i have this code to search for the 5 most common words in a text file but i cant use the sort and reverse functions at the end of the program... how would i avoid using them?</p> <pre><code>words = open('romeo.txt').read().lower().split() uniques = [] for word in words: if word not in uniques: uniques.append(word) counts = [] for unique in uniques: count = 0 for word in words: if word == unique: count += 1 counts.append((count, unique)) counts.sort() counts.reverse() for i in range(min(5, len(counts))): count, word = counts[i] print('%s %d' % (word, count)) </code></pre>
0
2016-08-17T23:53:57Z
39,008,023
<p>Use the <code>sorted()</code> function and save the results in a variable then reverse it like this:</p> <pre><code>counts = sorted(counts, reverse=True) </code></pre> <p>That line of code will sort the list and reverse it for you and save the results in counts. Then you can use your count as required.</p>
0
2016-08-18T00:00:44Z
[ "python" ]
5 most common words in text file python
39,007,968
<p>i have this code to search for the 5 most common words in a text file but i cant use the sort and reverse functions at the end of the program... how would i avoid using them?</p> <pre><code>words = open('romeo.txt').read().lower().split() uniques = [] for word in words: if word not in uniques: uniques.append(word) counts = [] for unique in uniques: count = 0 for word in words: if word == unique: count += 1 counts.append((count, unique)) counts.sort() counts.reverse() for i in range(min(5, len(counts))): count, word = counts[i] print('%s %d' % (word, count)) </code></pre>
0
2016-08-17T23:53:57Z
39,008,054
<pre><code>from collections import Counter c = Counter(words) c.most_common(5) </code></pre>
4
2016-08-18T00:06:14Z
[ "python" ]
Parsing mutual fund JSON data
39,008,044
<p>I am trying to pull out data from interactive chart and I have the JSON file from this link</p> <p><a href="https://www.tadawul.com.sa/Charts/MutualFundChartDataDownloader?actionTarget=mutualFundChartData&amp;mutualFundSymbol=006038&amp;format=json" rel="nofollow">http://www.tadawul.com.sa/Charts/MutualFundChartDataDownloader</a></p> <p>I tried importing this to Python so I can extract the data, but I am facing errors</p> <p>The code I wrote:</p> <pre><code>import urllib import json htmltext = urllib.urlopen("https://www.tadawul.com.sa/Charts/MutualFundChartDataDownloader?actionTarget=mutualFundChartData&amp;mutualFundSymbol=006038&amp;format=json") data = json.load(htmltext) print data["unitPrice"] </code></pre> <p>What I am really trying to import is the following data</p> <pre><code>"valuationDate" "valudationDateAsDate" "mutualFundNav" "unitPrice" </code></pre> <p>I want to get these data one by one so I can copy it and use it in Excel.</p> <p>All is what I am trying to do is to get the prices for this chart</p>
0
2016-08-18T00:04:36Z
39,008,675
<p>Running your (slightly modified) code shows the website data you are actually getting.</p> <pre><code>import urllib htmltext = urllib.urlopen("https://www.tadawul.com.sa/Charts/MutualFundChartDataDownloader?actionTarget=mutualFundChartData&amp;mutualFundSymbol=006038&amp;format=json") print htmltext.read() </code></pre> <p>It's not what you expect, it returns a HTML doc with:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;title&gt;Request Rejected&lt;/title&gt;&lt;/head&gt;&lt;body ... &lt;/html&gt; </code></pre> <p>Your request for that URL is being blocked when calling from Python as opposed to a browser. This code makes a request that includes a user agent, which allows the download to work:</p> <pre><code>import urllib2 import json url = "https://www.tadawul.com.sa/Charts/MutualFundChartDataDownloader?actionTarget=mutualFundChartData&amp;mutualFundSymbol=006038&amp;format=json" request = urllib2.Request(url, headers={'User-Agent' : ''}) result = urllib2.urlopen(request) data = json.loads(result.read()) for entry in data: print entry[u'valuationDate'] </code></pre>
0
2016-08-18T01:37:18Z
[ "python", "json", "finance", "stocks" ]
R and Python in one Jupyter notebook
39,008,069
<p>Is it possible to run R and Python code in the same Jupyter notebook. What are all the alternatives available?</p> <ol> <li>Install r-essentials and create R notebooks in Jupyter.</li> <li>Install rpy2 and use rmagic functions.</li> <li>Use a beaker notebook.</li> </ol> <p>Which of above 3 options is reliable to run Python and R code snippets (sharing variables and visualizations) or is there a better option already?</p>
2
2016-08-18T00:09:03Z
39,008,107
<p>It will be hard for you to use both R and Python syntax in the same notebook, mostly because the underlying representation of objects in the two languages are different. That said, there is a project that does try to allow conversion of objects and different languages in the same notebook: <a href="http://beakernotebook.com/features" rel="nofollow">http://beakernotebook.com/features</a></p> <p>I haven't used it myself but it looks promising</p>
0
2016-08-18T00:15:33Z
[ "python", "python-2.7", "ipython", "jupyter-notebook" ]
Retrieve image from method called by URL in python
39,008,074
<p>I'm trying to retrieve an image that is returned through a given URL using python, for example this one:</p> <p><a href="http://fundamentus.com.br/graficos3.php?codcvm=2453&amp;tipo=108" rel="nofollow">http://fundamentus.com.br/graficos3.php?codcvm=2453&amp;tipo=108</a></p> <p>I am trying to do this by using urllib retrieve method:</p> <pre><code>import urllib urlStr = "http://fundamentus.com.br/graficos3.php?codcvm=2453&amp;tipo=108" filename = "image.png" urllib.urlretrieve(urlStr,filename) </code></pre> <p>I already used this for other URLs, (such as <a href="http://chart.finance.yahoo.com/z?s=CMIG4.SA&amp;t=9m" rel="nofollow">http://chart.finance.yahoo.com/z?s=CMIG4.SA&amp;t=9m</a>), but for the first one it's not working.</p> <p>Does anyone have an idea about how to make this for the given URL? Note: I'm using Python 2.7</p>
1
2016-08-18T00:09:42Z
39,008,140
<p>You need to use a session which you can do with <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a>:</p> <pre><code>import requests with requests.Session() as s: s.get("http://fundamentus.com.br/graficos.php?papel=CMIG4&amp;tipo=2") with open("out.png", "wb") as f: f.write(s.get("http://fundamentus.com.br/graficos3.php?codcvm=2453&amp;tipo=108").content) </code></pre> <p>It works in your browser as you had visited the initial page where the image was so any necessary cookies were set.</p>
2
2016-08-18T00:20:07Z
[ "python", "python-2.7", "urllib" ]
Retrieve image from method called by URL in python
39,008,074
<p>I'm trying to retrieve an image that is returned through a given URL using python, for example this one:</p> <p><a href="http://fundamentus.com.br/graficos3.php?codcvm=2453&amp;tipo=108" rel="nofollow">http://fundamentus.com.br/graficos3.php?codcvm=2453&amp;tipo=108</a></p> <p>I am trying to do this by using urllib retrieve method:</p> <pre><code>import urllib urlStr = "http://fundamentus.com.br/graficos3.php?codcvm=2453&amp;tipo=108" filename = "image.png" urllib.urlretrieve(urlStr,filename) </code></pre> <p>I already used this for other URLs, (such as <a href="http://chart.finance.yahoo.com/z?s=CMIG4.SA&amp;t=9m" rel="nofollow">http://chart.finance.yahoo.com/z?s=CMIG4.SA&amp;t=9m</a>), but for the first one it's not working.</p> <p>Does anyone have an idea about how to make this for the given URL? Note: I'm using Python 2.7</p>
1
2016-08-18T00:09:42Z
39,008,373
<p>While more verbose than @PadraicCunningham response. This should also do the trick. I'd run into a similar problem (host would only support certain browsers), so i had to start using urllib2 instead of just urllib. pretty powerful and is a module which comes with python.</p> <p>Basically, you capture all the information you need during your initial request, and add it to your next request and subsequent requests. The requests module seems to pretty much do all of this for you behind the scenes. If only I'd known about that all these years...</p> <pre><code>import urllib2 urlForCookie = 'http://fundamentus.com.br/graficos.php?papel=CMIG4&amp;tipo=2' urlForImage = 'http://fundamentus.com.br/graficos3.php?codcvm=2453&amp;tipo=108' initialRequest = urllib2.Request(urlForCookie) siteCookie = urllib2.urlopen(req1).headers.get('Set-Cookie') imageReq = urllib2.Request(urlForImage) imageReq.add_header('cookie', siteCookie) with open("image2.pny",'w') as f: f.write(urllib2.urlopen(req2).read()) f.close() </code></pre>
0
2016-08-18T00:53:14Z
[ "python", "python-2.7", "urllib" ]
"E1101" - Instance of "Class" has no "method" member
39,008,121
<p>I have classes organized like so:</p> <pre><code>class One: def funcOne(self): doSomething() class Two(One): def funcTwo(self): self.funcOne() </code></pre> <p>When I ran this, it worked, and Python's inheritance model allows for <code>Two</code> to be able to call <code>funcOne</code>. </p> <p>However, running <code>pylint</code> gives me the error:</p> <pre><code>[E1101 (no-member), myscript] Instance of 'Two' has no 'funcOne' member </code></pre> <p>I already looked at <a href="http://stackoverflow.com/questions/25245414/pylint-warnings-on-inherited-nested-class-members">another question on the site</a>, but that question concerned variables, and the only solution proposed was to put them in a dictionary, which you can't do with methods.</p> <p>How can I get <code>pylint</code> to recognize the inheritance behavior?</p> <hr> <p>EDIT: I'm running <code>pylint 1.1.0</code>, which is ridiculously old, maybe that's the cause?</p>
1
2016-08-18T00:18:19Z
39,008,169
<p>call <code>self.funcOne()</code></p> <p>also class One should inherit from object</p> <pre><code>class One(object): ... </code></pre>
0
2016-08-18T00:23:18Z
[ "python", "python-2.7", "pylint" ]
"E1101" - Instance of "Class" has no "method" member
39,008,121
<p>I have classes organized like so:</p> <pre><code>class One: def funcOne(self): doSomething() class Two(One): def funcTwo(self): self.funcOne() </code></pre> <p>When I ran this, it worked, and Python's inheritance model allows for <code>Two</code> to be able to call <code>funcOne</code>. </p> <p>However, running <code>pylint</code> gives me the error:</p> <pre><code>[E1101 (no-member), myscript] Instance of 'Two' has no 'funcOne' member </code></pre> <p>I already looked at <a href="http://stackoverflow.com/questions/25245414/pylint-warnings-on-inherited-nested-class-members">another question on the site</a>, but that question concerned variables, and the only solution proposed was to put them in a dictionary, which you can't do with methods.</p> <p>How can I get <code>pylint</code> to recognize the inheritance behavior?</p> <hr> <p>EDIT: I'm running <code>pylint 1.1.0</code>, which is ridiculously old, maybe that's the cause?</p>
1
2016-08-18T00:18:19Z
39,008,272
<p>It turns out that my version of <code>pylint</code> was severely out of date. I was running version <code>1.1.0</code>, and updated to the newest version <code>1.6.4</code>, and the warnings were gone!</p> <p>I assume this is a bug in <code>pylint</code> that was fixed between the versions</p>
0
2016-08-18T00:40:32Z
[ "python", "python-2.7", "pylint" ]
how to avoid typeerror while returning result from php to python
39,008,124
<p>I have the following code in php and python,I return $result from php to a python handler and running into below error..how should I return in python so that I don't run into this error?</p> <p>php</p> <pre><code> $result = [ "TRIGGER_STATUS" =&gt; "SUCCESS", "PW_LINK" =&gt; "https://pw.company.com/" ]; </code></pre> <p>Python</p> <pre><code> orderedResults = sorted(result['result'].items(), key=lambda kv: kv[1]['Order']) </code></pre> <p>Error:-</p> <pre><code> File "\\data\workspace\username\pwp4plugin\UI.py", line 269, i n &lt;lambda&gt; orderedResults = sorted(result['result'].items(), key=lambda kv: kv[1]['Orde r']) TypeError: string indices must be integers, not str </code></pre>
0
2016-08-18T00:18:32Z
39,009,452
<p>The issue is with <code>kv[1]['Order']</code> being passed to the <code>lambda</code> function being passed to <code>key</code>. Assuming the dict which Python has after doing <code>json.decode()</code> is this:</p> <pre><code>&gt;&gt;&gt; result = {'result': { ... "TRIGGER_STATUS": "SUCCESS", ... "PW_LINK": "https://pw.company.com/" ... } ... } &gt;&gt;&gt; &gt;&gt;&gt; # this is what .items() looks like: ... result['result'].items() [('PW_LINK', 'https://pw.company.com/'), ('TRIGGER_STATUS', 'SUCCESS')] </code></pre> <p>So in the loop, index 1 is <code>'https://pw.company.com/'</code> and <code>'SUCCESS'</code>:</p> <pre><code>&gt;&gt;&gt; for kv in result['result'].items(): ... print kv[1] ... https://pw.company.com/ SUCCESS </code></pre> <ol> <li><p>So <code>kv[1]['Order']</code> is attempting to lookup a <em>key</em> called 'Order' against each of the two strings. Whereas, what Python is expecting is an integer index to something in each of those strings. Example:</p> <pre><code>&gt;&gt;&gt; for kv in result['result'].items(): ... print kv[1][4] # the fifth letter in each string ... s E </code></pre></li> <li><p>In the PHP associative array you've given, there is no <em>key</em> <code>'Order'</code>. So it's unclear to us what you were trying to use. What is <code>result</code> in Python once the PHP result is parsed?</p></li> </ol>
1
2016-08-18T03:16:35Z
[ "php", "python" ]
Plotting lines over an image using the same projection
39,008,262
<p>I want to make a plot using .fits files (astronomical images) and I am experiencing two issues which I think they are related:</p> <p>Using this example from astropy:</p> <pre><code>from matplotlib import pyplot as plt from astropy.io import fits from astropy.wcs import WCS from astropy.utils.data import download_file fits_file = 'http://data.astropy.org/tutorials/FITS-images/HorseHead.fits' image_file = download_file(fits_file, cache=True) hdu = fits.open(image_file)[0] wcs = WCS(hdu.header) fig = plt.figure() fig.add_subplot(111, projection=wcs) plt.imshow(hdu.data, origin='lower', cmap='cubehelix') plt.xlabel('RA') plt.ylabel('Dec') plt.show() </code></pre> <p>I can generate this image:</p> <p><a href="http://i.stack.imgur.com/tpKPY.png" rel="nofollow"><img src="http://i.stack.imgur.com/tpKPY.png" alt="enter image description here"></a></p> <p>Now I would like to plot some points using the same coordinates as the image:</p> <pre><code>plt.scatter(85, -2, color='red') </code></pre> <p>However, when I do this:</p> <p><a href="http://i.stack.imgur.com/H8PpJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/H8PpJ.png" alt="enter image description here"></a></p> <p>I am ploting at the pixel coordinantes. Furthermore, the image no longer matches the frame size (although the coordinates seem fine)</p> <p>Any advice on how to deal with these issues?</p>
1
2016-08-18T00:39:12Z
39,020,724
<p>It is very easy to plot given coordinates. All you have to do is apply a <a href="http://wcsaxes.readthedocs.io/en/latest/overlays.html#world-coordinates" rel="nofollow"><code>transform</code></a>.</p> <p>I copied your example and added comments where I changed something and why.</p> <pre><code>from matplotlib import pyplot as plt from astropy.io import fits from astropy.wcs import WCS from astropy.utils.data import download_file fits_file = 'http://data.astropy.org/tutorials/FITS-images/HorseHead.fits' image_file = download_file(fits_file, cache=True) # Note that it's better to open the file with a context manager so no # file handle is accidentally left open. with fits.open(image_file) as hdus: img = hdus[0].data wcs = WCS(hdus[0].header) fig = plt.figure() # You need to "catch" the axes here so you have access to the transform-function. ax = fig.add_subplot(111, projection=wcs) plt.imshow(img, origin='lower', cmap='cubehelix') plt.xlabel('RA') plt.ylabel('Dec') # Apply a transform-function: plt.scatter(85, -2, color='red', transform=ax.get_transform('world')) </code></pre> <p>And the result is:</p> <p><a href="http://i.stack.imgur.com/JYz0X.png" rel="nofollow"><img src="http://i.stack.imgur.com/JYz0X.png" alt="enter image description here"></a></p> <p>Note that if you want the Canvas to only show the region of the image just apply the limits again afterwards:</p> <pre><code># Add a scatter point which is in the extend of the image: plt.scatter(85.3, -2.5, color='red', transform=ax.get_transform('world')) plt.ylim(0, img.shape[0]) plt.xlim(0, img.shape[1]) </code></pre> <p>which gives:</p> <p><a href="http://i.stack.imgur.com/KcmMT.png" rel="nofollow"><img src="http://i.stack.imgur.com/KcmMT.png" alt="enter image description here"></a></p> <p>A side note as well here. AstroPy has a great units support so instead of converting arcmins and arcsecs to degrees you can just define the "unit". You still need the transform though:</p> <pre><code>from astropy import units as u x0 = 85 * u.degree + 20 * u.arcmin y0 = -(2 * u.degree + 25 * u.arcmin) plt.scatter(x0, y0, color='red', transform=ax.get_transform('world')) </code></pre> <p><a href="http://i.stack.imgur.com/h7iWX.png" rel="nofollow"><img src="http://i.stack.imgur.com/h7iWX.png" alt="enter image description here"></a></p>
3
2016-08-18T14:23:57Z
[ "python", "image", "matplotlib", "astronomy", "astropy" ]
python dictionary (unordered selections key)
39,008,296
<p>I have a question about dic.has_key</p> <p>my code is </p> <pre><code>def insertToDic(dic,comSick): for datum in comSick : if dic.has_key(datum): dic[datum]+=1 else : dic[datum] =1 </code></pre> <p>if comSick is</p> <pre><code>comSick=[(A,B),(A,C),(B,A)] </code></pre> <p>dic will be </p> <pre><code>dic = {(A,B) : 1, (A,C) : 1, (B,A) : 1} </code></pre> <p>but what I want is unordered key (which means (A,B) = (B,A))</p> <pre><code>dic = {(A,B) : 2, (A,C) : 1} &lt;-- this is what I want </code></pre> <p>what should I do?</p>
-1
2016-08-18T00:43:28Z
39,008,356
<p>Try this:</p> <pre><code>def insertToDic(dic,comSick): for datum in comSick : sorted_datum = tuple(sorted(datum)) dic[sorted_datum] = dic.get(sorted_datum, 0) + 1 comSick=[('A', 'B'), ('A', 'C'), ('B', 'A')] dic = {} insertToDic(dic, comSick) print(dic) </code></pre> <p>I made some changes. I sorted the datum before updating the dictionary. This ensures that one of <code>(A,B)</code> and <code>(B,A)</code> will be changed to the other. It is not clear what <code>A</code> and <code>B</code> are, so <code>B</code> may be lower than <code>A</code>. Did you mean the strings <code>'A'</code> and <code>'B'</code>? That's what I used.</p> <p>I also changed how you increment the value. The <code>get()</code> method will return the current value if it exists or the given default value if it doesn't--in this case, zero.</p> <p>Also note that the final dictionary has no inherent order, so you may get the answer <code>{('A', 'C'): 1, ('A', 'B'): 2}</code>, which is what I got in my Python 3.5.2 in Anaconda.</p>
1
2016-08-18T00:50:36Z
[ "python", "dictionary", "unordered" ]
python dictionary (unordered selections key)
39,008,296
<p>I have a question about dic.has_key</p> <p>my code is </p> <pre><code>def insertToDic(dic,comSick): for datum in comSick : if dic.has_key(datum): dic[datum]+=1 else : dic[datum] =1 </code></pre> <p>if comSick is</p> <pre><code>comSick=[(A,B),(A,C),(B,A)] </code></pre> <p>dic will be </p> <pre><code>dic = {(A,B) : 1, (A,C) : 1, (B,A) : 1} </code></pre> <p>but what I want is unordered key (which means (A,B) = (B,A))</p> <pre><code>dic = {(A,B) : 2, (A,C) : 1} &lt;-- this is what I want </code></pre> <p>what should I do?</p>
-1
2016-08-18T00:43:28Z
39,010,406
<p>Use</p> <p>frozenset(('A', 'B')) </p> <p>as the key.</p>
1
2016-08-18T05:12:36Z
[ "python", "dictionary", "unordered" ]
Error in Vim: "YouCompleteMe unavailable: This package should not be accessible on Python 3"
39,008,318
<p>When I attempt to use the YouCompleteMe plugin in vim, I get the following error: </p> <p><code>YouCompleteMe unavailable: This package should not be accessible on Python 3. Either you are trying to run from the python-future src folder or your installation of python-future is corrupted</code></p> <p>However, I only get this error when I open vim within my virtual environment. It works fine when a virtualenv is not active. My guess is that YouCompleteMe is written in python 2, and for some reason can't see the python2 interpreter from inside the virtual environment, but I am not sure how to fix it. There does not appear to be a Stack Overflow question on the subject, but a similar issue came up in the ycm-users Google Group and went unanswered.</p> <p>I'm on Ubuntu 14.04, using vim version 7.4.</p>
2
2016-08-18T00:46:22Z
39,009,346
<p>It sounds as if you are using using python 3 inside virtualenv. As far as vim is concerned, you are running python 3 which is not supported by ycm</p> <p><a href="https://github.com/Valloric/YouCompleteMe/issues/1140" rel="nofollow">https://github.com/Valloric/YouCompleteMe/issues/1140</a></p> <p>A workaround would be to just open vim from outside your virtualenv</p>
0
2016-08-18T03:04:07Z
[ "python", "python-3.x", "vim", "virtualenv", "youcompleteme" ]
Error in Vim: "YouCompleteMe unavailable: This package should not be accessible on Python 3"
39,008,318
<p>When I attempt to use the YouCompleteMe plugin in vim, I get the following error: </p> <p><code>YouCompleteMe unavailable: This package should not be accessible on Python 3. Either you are trying to run from the python-future src folder or your installation of python-future is corrupted</code></p> <p>However, I only get this error when I open vim within my virtual environment. It works fine when a virtualenv is not active. My guess is that YouCompleteMe is written in python 2, and for some reason can't see the python2 interpreter from inside the virtual environment, but I am not sure how to fix it. There does not appear to be a Stack Overflow question on the subject, but a similar issue came up in the ycm-users Google Group and went unanswered.</p> <p>I'm on Ubuntu 14.04, using vim version 7.4.</p>
2
2016-08-18T00:46:22Z
39,022,588
<p>Looks like it's a bug:</p> <p><a href="https://github.com/Valloric/ycmd/pull/578" rel="nofollow">https://github.com/Valloric/ycmd/pull/578</a></p> <blockquote> <p>In PR #448, I made the assumption that the site-packages paths are always placed after the standard library path so that if we insert the python-future module just before the first site-packages path, it would necessary be after the standard library. Turns out that it is not true when a site-packages path is added to the PYTHONPATH environment variable, e.g, when using the software ROS. See issue Valloric/YouCompleteMe#2186. When this happens, the python-future module will raise the following exception on Python 3:</p> <pre><code> ImportError: This package should not be accessible on Python 3. Either you are trying to run from the python-future src folder or your installation of python-future is corrupted. </code></pre> <p>We prevent this by looking for the standard library path in sys.path and by inserting the python-future module just after it. If we can't find it, we raise an exception since YCM and ycmd cannot work without it.</p> <p>Fixes <a href="https://github.com/Valloric/YouCompleteMe/issues/2186" rel="nofollow">Valloric/YouCompleteMe#2186</a></p> </blockquote> <p>With the above pull request merged, you should be able to fix the issue by pulling the updates--or cloning the repo if haven't already--and reinstalling.</p>
1
2016-08-18T15:51:07Z
[ "python", "python-3.x", "vim", "virtualenv", "youcompleteme" ]
How to transform Dask.DataFrame to pd.DataFrame?
39,008,391
<p>How can I transform my resulting dask.DataFrame into pandas.DataFrame (let's say I am done with heavy lifting, and just want to apply sklearn to my aggregate result)?</p>
0
2016-08-18T00:56:53Z
39,008,635
<p>You can call the .compute() method to transform a dask.dataframe to a pandas dataframe:</p> <pre><code>df = df.compute() </code></pre>
3
2016-08-18T01:32:58Z
[ "python", "pandas", "dask" ]
Two strings and unicodes that are exactly the same do not return true when evaluated with each other
39,008,407
<p>This makes no sense to me. The ultimate goal of what I need to do is break down a very long string into respective words and compare each word with something.. I am only posting a snippet of the total output not to overwhelm and clutter this post with unnecessary data.</p> <p>I created a simple setup to compare if these two 'words' are the same. In raw form they come out as unicode, but evaluating them as unicode or converting them to string does not return True.. here is a sample output</p> <pre><code>u'altmer'/&lt;type 'unicode'&gt; | u'altmer'&lt;type 'unicode'&gt; | False </code></pre> <p>Here is the code that compares the two.</p> <pre><code>ch.msg("%r/%r | %r%r | %s" % (color_entrytxt_list[index].lower(), type(color_entrytxt_list[index].lower()), entry, type(entry), "True" if color_entrytxt_list[index].lower() == entry.lower() else "False")) * note I have also tried is instead of '==' ** I have also tried converting each unicode to string via str(unicode) </code></pre> <p>I don't understand why this is evaluating to false?</p> <p>EDIT:</p> <p>Thank you everyone for helping with this question. As mentioned by a few folks, the problem actually did reside that the two strings were not structurally the same, the problem was some characters weren't outputted to the screen.</p>
0
2016-08-18T00:59:37Z
39,008,478
<p>You need to use <code>==</code> to check for equality instead of <code>is</code> which checks if they occupy the same memory location.</p> <pre><code>s1 = 'abc' * 10000 s2 = 'abc' * 10000 &gt;&gt;&gt; id(s1) 4480540672 &gt;&gt;&gt; id(s2) 4480570880 &gt;&gt;&gt; s1 is s2 False &gt;&gt;&gt; s1 == s2 True </code></pre> <p>If the string is short enough, they will use the same memory location. Once it gets larger, however, they will each get there own.</p>
0
2016-08-18T01:10:56Z
[ "python", "unicode", "formatting" ]
How do I launch Powershell locally on NanoServer?
39,008,462
<p>I have created NS image with 'Development' switch using Windows 2016 Technical Preview 5. I am deploying the NS image onto a physical machine.I want to run Python interactive shell on local Powershell but it appears that there is no local PS console on NanoServer.</p>
0
2016-08-18T01:08:11Z
39,020,077
<p>Nano Server is designed to be administered remotely, the local 'console' only allows you to set firewall rules and network config.</p> <p>You'll need to do everything via a remote session with Nano Server. If that's not suitable for you the only option is to move to the full Server 2016 OS instead as this has the standard local console with GUI.</p>
0
2016-08-18T13:54:35Z
[ "python", "powershell", "window-server", "nano-server" ]
When to use a database depending on need to filter/sort data?
39,008,463
<p>I'm currently building a Flask web app, and I am trying to figure out if I need a database for the information that I'm displaying. I have looked at other posts, and found that depending on the size of data, it could better to just use objects instead. I started using objects, however I need to have the ability to filter/sort my data, and MySQL queries are faster then python sort. Also, my data gets updated daily, and contains about 400 data points. Is the trade off of adding a database worth the speed I'll gain from using a DB? Or should I look into other options like storing the data to a file?</p>
0
2016-08-18T01:08:42Z
39,008,499
<p>It might be worthwhile taking a look at the following. <a href="http://programmers.stackexchange.com/questions/190482/why-use-a-database-instead-of-just-saving-your-data-to-disk">http://programmers.stackexchange.com/questions/190482/why-use-a-database-instead-of-just-saving-your-data-to-disk</a></p> <p>Reiterating the excellent points Robert Harvey had made regarding why you should look at using a DB rather than storing to a file:</p> <p>1.You can query data in a database (ask it questions).</p> <p>2.You can look up data from a database relatively rapidly.</p> <p>3.You can relate data from two different tables together using JOINs.</p> <p>4.You can create meaningful reports from data in a database.</p> <p>5.Your data has a built-in structure to it.</p> <p>6.Information of a given type is always stored only once.</p> <p>7.Databases are ACID.</p> <p>8.Databases are fault-tolerant.</p> <p>9.Databases can handle very large data sets.</p> <p>10.Databases are concurrent; multiple users can use them at the same time without corrupting the data.</p> <p>11.Databases scale well.</p>
0
2016-08-18T01:14:16Z
[ "python", "mysql" ]
Print function in python giving strings with brackets?
39,008,491
<p>When I print a statement in python it is given in the form ['Hello World']. I'm not certain why and am looking to fix this problem and I believe it may be related to the formatting of the code.</p> <pre><code>query = input("Enter your query: ").lower() brands = ["apple", "android", "windows"] brand = set(brands).intersection(query.split()) brand = str(brand.translate({ord('['): '', ord(']'): ''})) print(brand) </code></pre> <p>which gives me the output (from the print function) when given a correct query of apple:</p> <pre><code>{'apple'} </code></pre> <p>I would appreciate any solutions,</p> <p>Thanks,</p> <p>Python Shell: v3.5.2</p>
0
2016-08-18T01:13:24Z
39,008,621
<p>Curly braces '{' and '}' are used for sets and dictionaries.</p> <pre><code># e.g. print(set(brands)) {'apple', 'android', 'windows'} </code></pre> <p>In your case you create a set by intersecting set(brands) with the query, then you convert the set to a string, which will include the curly braces.</p> <p>One simple solution to exclude the braces, while still separating all possible matches is:</p> <pre><code>brand = set(brands).intersection(query.split()) print(', '.join(brand)) </code></pre>
0
2016-08-18T01:30:17Z
[ "python", "arrays", "string", "brackets" ]
How can I redirect without revealing URI fields in flask?
39,008,497
<p>I would like to make a post request sending a username and password to a page named showInternal; I currently accomplish this via:</p> <pre><code>username = "johnsmith" password = "password1234" return redirect(url_for('showInternal', username=username, password=password)) </code></pre> <p>for the redirect and</p> <pre><code>@app.route('/internal', methods=['GET']) @login_required def showInternal(): return render_template('internal.html') </code></pre> <p>for the destination page. This sorta works in the sense that it takes me to <code>/internal?password=password1234&amp;username=johnsmith</code>.</p> <p>However, I don't want to show the user's username and password in the url. I've tried replacing the phrase <code>methods=['GET']</code> with <code>methods=['POST']</code> but then I get an error about that method not being allowed, and the data stays in the url anyhow.</p> <p>How can I pass these data without it showing up in the url?</p>
0
2016-08-18T01:13:46Z
39,008,563
<p>Import the JSON and requests module: <code>import json, request</code></p> <p>Use the request module to send a post request:</p> <pre><code>requests.post('&lt;full-url&gt;', data=json.dumps({'username': 'johnsmith', 'password': 'password1234'})) </code></pre> <p>Then edit your route:</p> <pre><code>@app.route('/internal', methods=['POST']) </code></pre>
0
2016-08-18T01:22:02Z
[ "python", "redirect", "post", "flask" ]
Most efficient way to modify variables within a custom grammar?
39,008,505
<p>I'm working with a propriety driving simulator which generates "scenario" files in a customised version of <a href="http://www.scilab.org/" rel="nofollow">Scilab</a>. I am provided a single 11,000 line long "master" file, and from this I need to replace certain values to generate <em>n</em> versions of the scenario. </p> <p>A minimal example of the syntax for a single parent <code>TASK</code> would be something like this:</p> <pre><code>TYPEOF TASK (57) { LABEL="Dot 3a"/*replace with name for name in list */ TASK_KIND="0" TYPEOF VARIABLE (53) { LABEL="Time1" TYPE="FLOAT" VALUE="14.000000" /* replace with random.integer() */ INTERACTIVE="VOID" TYPEOF VARIABLE (54) { LABEL="X_pos1" TYPE="FLOAT" VALUE="23.600000" INTERACTIVE="VOID" TYPEOF TASK (58) { LABEL="Task: ISI" TASK_KIND="0" TYPEOF RULE (115) { LABEL="Rule: Go to subtask after Time1 seconds" TYPEOF CONDITION (SUPERIOR) { IS_EXPANDED="1" MODIFIER="BECOMES_TRUE" TYPEOF PARAMETER (OPERAND_1) { KIND="FUNCTION" TYPEOF FUNCTION (GET_TASK_CLOCK) { } OWNER_FILE="" } TYPEOF PARAMETER (OPERAND_2) { KIND="VARIABLE" VALUE="53" OWNER_FILE="" } } TYPEOF ACTION (GOTO_TASK) { IS_EXPANDED="1" TYPEOF PARAMETER (TASK_NUMBER) { KIND="ENUM" VALUE="GOTO_NEXT_TASK" OWNER_FILE="" } } } } </code></pre> <p>I need to replace certain values in this script with standard input. For instance, have a list of names which will replace the value of <code>LABEL</code> under a parent level <code>TASK</code>; and have to replace <code>VALUE</code> for first parent <code>VARIABLE</code> with a random number between 6 and 16.</p> <p>My first solution was Python REGEX based, something like follows (but for every value I seek to change):</p> <pre><code>for row in scenarioInput: parenttaskmatch = re.search("^\t\tTYPEOF TASK",row) if parenttaskmatch: replacementrow = re.sub(r"([0-9]{1,3})",repl,row) </code></pre> <p>It was suggested to me that I could write a custom grammar with something like Parsimonious and then regenerate the output with Mustache. </p> <pre><code>from parsimonious.grammar import Grammar grammar = Grammar(r""" any = task / data task = "TYPEOF " key " (" number ")" newline open_curly any+ close_curly data = key "=" quote text quote newline open_curly = "{" newline close_curly = "}" newline key = ~"[A-Z 0-9_]*" text = ~"[A-Z0-9 ]*"i number = ~"[0-9]*" newline = "\n" space = " " quote = "\"" """) text = open('example_driving_rule.sci').read() grammar.parse(text) # Note doesn't work </code></pre> <p>As you can see, this is not an efficient solution to the problem either. What do you guys think is a better solution?</p>
1
2016-08-18T01:15:22Z
39,019,639
<p>May be you can transform your file to a Scilab Script which generate a file with the new values.</p> <p>The transformation is quite simple First in Scilab (to be done once)</p> <pre><code> T=mgetl("Task_file");mputl(sci2exp(T),"Task_file.sce") </code></pre> <p>For each experiment, with a text editor modify the generated script to replace the default values by the expected one (may be by reading these values from a file, or ....)</p> <p>See the example below Time1 value is generated by grand, X_pos1 is read from Scilab console</p> <pre><code> T=["TYPEOF TASK (57)" "{" " LABEL=""Dot 3a""/*replace with name for name in list */" " TASK_KIND=""0""" "" " TYPEOF VARIABLE (53)" " {" " LABEL=""Time1""" " TYPE=""FLOAT""" " VALUE="""+string(grand(1,1,"uin",6,16)+"""" /* replace with random.integer() */" " INTERACTIVE=""VOID""" "" " TYPEOF VARIABLE (54)" " {" " LABEL=""X_pos1""" " TYPE=""FLOAT""" " VALUE=""""+string(input("X_pos1")+"""" " INTERACTIVE=""VOID""" "" "" " TYPEOF TASK (58)" " {" " LABEL=""Task: ISI""" " TASK_KIND=""0""" "" " TYPEOF RULE (115)" " {" " LABEL=""Rule: Go to subtask after Time1 seconds""" "" " TYPEOF CONDITION (SUPERIOR)" " {" " IS_EXPANDED=""1""" " MODIFIER=""BECOMES_TRUE""" "" " TYPEOF PARAMETER (OPERAND_1)" " {" " KIND=""FUNCTION""" "" " TYPEOF FUNCTION (GET_TASK_CLOCK)" " {" " }" " OWNER_FILE=""""" " }" "" " TYPEOF PARAMETER (OPERAND_2)" " {" " KIND=""VARIABLE""" " VALUE=""53""" " OWNER_FILE=""""" " }" " }" "" " TYPEOF ACTION (GOTO_TASK)" " {" " IS_EXPANDED=""1""" "" " TYPEOF PARAMETER (TASK_NUMBER)" " {" " KIND=""ENUM""" " VALUE=""GOTO_NEXT_TASK""" " OWNER_FILE=""""" " }" " }" " }" " }"]; muptl(T,"Task") </code></pre>
0
2016-08-18T13:34:09Z
[ "python", "grammar", "scilab" ]
Python statefull socket programming
39,008,558
<p>I have a client-server socket python script. I want to keep the state of each connection, such that i identify whether or not the client is its first connection. I unsuccessfully wrote the following code:</p> <p>` </p> <pre><code>import socket,sys,SocketServer from threading import Thread class EchoRequestHandler(SocketServer.BaseRequestHandler): def setup(self): self.clients = {} print self.client_address, 'connected!' self.request.send('hi ' + str(self.client_address) + '\n') def setup(self): print self.client_address, 'connected!' self.request.send('hi ' + str(self.client_address) + '\n') def getFile(self): fle = self.request.makefile('r') filename = fle.readline() print("Got filename {}\n".format(filename)) data = 'fnord' # just something to be there for the first comparison with open(filename[:-1], 'w') as outfile: while data: #data = self.request.recv(1024) data = fle.read() #print('writing {!r} to file ....'.format(data)) outfile.write(data) print("Finish {}\n".format(filename)) print("finish handle") def handle(self): addr = self.client_address[0] print(self.clients) if addr not in self.clients: print("firsttime") self.clients[addr]=1 print(self.clients) self.getFile() def finish(self): print self.client_address, 'disconnected!' #self.request.send('bye ' + str(self.client_address) + '\n') class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass if __name__=='__main__': #server = SocketServer.ThreadingTCPServer(('localhost', 50000), EchoRequestHandler) server = ThreadedTCPServer(('localhost', 60000), EchoRequestHandler) server.serve_forever() </code></pre> <p>Each time the client connect I am getting an empty clients dictionary. Seems like each time there is a connection setup is being called and empties the dictionary <code>clients</code>. How i can keep its state at each connection?</p>
0
2016-08-18T01:21:39Z
39,009,212
<p>The threaded socket server creates a new instance of <code>EchoRequestHandler</code> for each connection, so storing the clients in that class instance would not be correct.</p> <p>Each request handler instance has a <code>self.server</code> member that knows its server, so you can store it there instead.</p> <p>Below is modified from a Python 2.7 SocketServer example in the module's help:</p> <pre><code>#!python2 import time import socket import threading import SocketServer class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): self.server.clients.add(self.client_address) print 'connected from',self.client_address print 'all clients =',self.server.clients data = self.request.recv(1024) cur_thread = threading.current_thread() response = "{}: {}".format(cur_thread.name, data) self.request.sendall(response) time.sleep(2) print 'disconnected' class ThreadedTCPServer(SocketServer.ThreadingTCPServer): def __init__(self,*args,**kwargs): SocketServer.ThreadingTCPServer.__init__(self,*args,**kwargs) self.clients = set() def client(ip, port, message): sock = socket.socket() sock.connect((ip, port)) try: sock.sendall(message) response = sock.recv(1024) print "Received: {}".format(response) finally: sock.close() if __name__ == "__main__": # Port 0 means to select an arbitrary unused port HOST, PORT = "localhost", 0 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) ip, port = server.server_address # Start a thread with the server -- that thread will then start one # more thread for each request server_thread = threading.Thread(target=server.serve_forever) # Exit the server thread when the main thread terminates server_thread.daemon = True server_thread.start() print "Server loop running in thread:", server_thread.name client(ip, port, "Hello World 1\n") client(ip, port, "Hello World 2\n") client(ip, port, "Hello World 3\n") server.shutdown() server.server_close() </code></pre> <p>Output:</p> <pre><code>Server loop running in thread: Thread-1 connected from ('127.0.0.1', 2360) all clients = set([('127.0.0.1', 2360)]) Received: Thread-2: Hello World 1 connected from ('127.0.0.1', 2361) all clients = set([('127.0.0.1', 2361), ('127.0.0.1', 2360)]) Received: Thread-3: Hello World 2 connected from ('127.0.0.1', 2362) all clients = set([('127.0.0.1', 2361), ('127.0.0.1', 2362), ('127.0.0.1', 2360)]) Received: Thread-4: Hello World 3 disconnected disconnected disconnected </code></pre>
1
2016-08-18T02:47:49Z
[ "python", "sockets", "python-sockets" ]
Count vectorizing into bigrams for one document, and then taking the average
39,008,652
<p>I'm trying to write a function that takes in one document, count vectorizes the bigrams for that document. This shouldn't have any zeroes, as I'm only doing this to one document at a time. Then I want to take the average of those numbers to get a sense of bigram repetition.</p> <p>Any problems with this code?</p> <pre><code>def avg_bigram(x): bigram_vectorizer = CountVectorizer(stop_words='english', ngram_range=(2,2)) model = bigram_vectorizer.fit_transform(x) vector = model.toarray() return vector.mean() </code></pre> <p>I've tested it with text that I know contains more than stop words, and I get back</p> <p>"empty vocabulary; perhaps the documents only contain stop words"</p> <p>Thank you for any help!</p>
0
2016-08-18T01:35:06Z
39,008,774
<p><code>CountVectorizer</code> expects a corpus, while you are giving a single doc. Just wrap your doc in a <code>list</code>. E.g:</p> <pre><code>model = bigram_vectorizer.fit_transform([x]) </code></pre>
1
2016-08-18T01:51:05Z
[ "python", "nlp", "scikit-learn" ]
i am getting need more than one value to unpack value error
39,008,742
<p>Help me out..This is my pgm</p> <pre><code>from sys import argv script, first, second, third = argv print ("the script is:", script) print("the first variable is:", first) print("the second variable is:", second) print ("the third variable is:", third) </code></pre> <p>==========================================================</p> <h2>The error is:</h2> <blockquote> <p>Traceback (most recent call last): File "C:/Users/ravikishore/PycharmProjects/Test/.idea/MyPython.py", line 2, in [script, first, second, third] = argv ValueError: need more than 1 value to unpack</p> </blockquote> <p>===========================================================================</p>
-1
2016-08-18T01:46:14Z
39,008,780
<p>That code works just <em>fine,</em> assuming that you actually <em>give</em> it three arguments to unpack, as with:</p> <pre><code>c:\pax&gt; python yourProg.py A B C the script is: yourProg.py the first variable is: A the second variable is: B the third variable is: C </code></pre> <p>The problem occurs when you <em>don't</em> give it enough arguments:</p> <pre><code>c:\pax&gt; python yourProg.py A Traceback (most recent call last): File "yourProg.py", line 2, in &lt;module&gt; script, first, second, third = argv ValueError: not enough values to unpack (expected 4, got 2) </code></pre> <p>If you want to ensure there are enough arguments before trying to unpack them, you can use <code>len(argv)</code> to get the argument count, and compare that to what you need, something like:</p> <pre><code>import sys if len(sys.argv) != 4: print("Need three arguments after script name") sys.exit(1) script, first, second, third = sys.argv print ("the script is:", script) print("the first variable is:", first) print("the second variable is:", second) print ("the third variable is:", third) </code></pre>
1
2016-08-18T01:51:35Z
[ "python" ]
i am getting need more than one value to unpack value error
39,008,742
<p>Help me out..This is my pgm</p> <pre><code>from sys import argv script, first, second, third = argv print ("the script is:", script) print("the first variable is:", first) print("the second variable is:", second) print ("the third variable is:", third) </code></pre> <p>==========================================================</p> <h2>The error is:</h2> <blockquote> <p>Traceback (most recent call last): File "C:/Users/ravikishore/PycharmProjects/Test/.idea/MyPython.py", line 2, in [script, first, second, third] = argv ValueError: need more than 1 value to unpack</p> </blockquote> <p>===========================================================================</p>
-1
2016-08-18T01:46:14Z
39,008,874
<p><code>argv</code> is a list:</p> <pre><code>&gt;&gt;&gt; from sys import argv &gt;&gt;&gt; type(argv) &lt;type 'list'&gt; </code></pre> <p>So you're attempting to do a conversion from a list to a tuple, which only works if the number of elements in the tuple <strong>exactly</strong> matches the list length:</p> <pre><code>&gt;&gt;&gt; a,b,c = [1] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: need more than 1 value to unpack &gt;&gt;&gt; a,b,c = [1,2] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: need more than 2 values to unpack &gt;&gt;&gt; a,b,c = [1,2,3] &gt;&gt;&gt; a,b,c = [1,2,3,4] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: too many values to unpack </code></pre> <p>So you need to add some checks on the <code>argv</code> length prior to attempting the conversion.</p>
2
2016-08-18T02:05:06Z
[ "python" ]
Create Nested JSON from Pandas for Org Chart
39,008,860
<p>I'm trying to create a nested JSON object from a hierarchical DataFrame (python 3.5) to feed into JavaScript to render an Org Chart. I'm essentially trying to create the structure found in the answer of this question: <a href="http://stackoverflow.com/questions/30926539/organization-chart-tree-online-dynamic-collapsible-pictures-in-d3">Organization chart - tree, online, dynamic, collapsible, pictures - in D3</a></p> <p>An example dataframe:</p> <pre><code>df = pd.DataFrame({\ 'Manager_Name':['Mike' ,'Jon', 'Susan' ,'Susan' ,'Joe'],\ 'Manager_Title':['Level1' ,'Level2' ,'Level3' ,"Level3", 'Level4'],\ 'Employee_Name':['Jon' ,'Susan' ,'Josh' ,'Joe' ,'Jimmy'],\ 'Employee_Title':["Level2" ,"Level3" ,"Level4" ,"Level4" ,"Level5"]}) </code></pre> <p>The desired output would be:</p> <pre><code>"Name": "Mike" "Title": "Level1" "Employees": [{ "Name": "Jon" "Title": "Level2" "Employees": [{ "Name": "Susan" "Title": "Level3" "Employees": [{ ... ... ... }] }] }] </code></pre> <p>I know this isn't a code generating service but I've tried applying other similarly related answers and can't seem to apply those answers here. I also haven't worked with dictionaries that much (I'm more of an R person) so there's probably some noobishness to this question. I've more time than I should on this yet I'm sure someone here can do this in a few minutes. </p> <p>Other questions: </p> <ul> <li><a href="http://stackoverflow.com/questions/24374062/pandas-groupby-to-nested-json">pandas groupby to nested json</a></li> <li><a href="http://stackoverflow.com/questions/23255512/creating-nested-json-structure-with-multiple-key-values-in-python-from-json">Creating nested Json structure with multiple key values in Python from Json</a></li> <li><a href="http://stackoverflow.com/questions/37713329/how-to-build-a-json-file-with-nested-records-from-a-flat-data-table?noredirect=1&amp;lq=1">How to build a JSON file with nested records from a flat data table?</a></li> </ul> <p>Thanks in advance!</p>
0
2016-08-18T02:03:15Z
39,021,065
<p>Consider filtering out dataframe by Level and converting dfs to dictionary with pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="nofollow"><code>to_dict()</code></a> which are continually rolled into one list across levels. Below defined function walks from last level to first to roll up individual Employee Levels dictionaries. But first you should concatenate Manager and Employee <em>Name</em> and <em>Title</em> columns.</p> <pre><code>import json import pandas as pd cdf = pd.concat([df[['Manager_Name', 'Manager_Title']].\ rename(index=str, columns={'Manager_Name':'Name', 'Manager_Title':'Title'}), df[['Employee_Name', 'Employee_Title']].\ rename(index=str, columns={'Employee_Name':'Name', 'Employee_Title':'Title'})]) cdf = cdf.drop_duplicates().reset_index(drop=True) print(cdf) # Name Title # 0 Mike Level1 # 1 Jon Level2 # 2 Susan Level3 # 3 Joe Level4 # 4 Josh Level4 # 5 Jimmy Level5 def jsondict(): inner = [''] for i in ['Level5', 'Level4', 'Level3', 'Level2']: if i == 'Level5': inner[0] = cdf[cdf['Title']==i].to_dict(orient='records') else: tmp = cdf[cdf['Title']==i].copy().reset_index(drop=True) if len(tmp) == 1: tmp['Employees'] = [inner[0]] else: for d in range(0,len(tmp)): tmp.ix[d, 'Employees'] = [inner[0]] lvltemp = tmp.to_dict(orient='records') inner[0] = lvltemp return(inner) jsondf = cdf[cdf['Title']=='Level1'].copy() jsondf['Employees'] = jsondict() jsondata = jsondf.to_json(orient='records') </code></pre> <p><strong>Output</strong></p> <pre><code>[{"Name":"Mike","Title":"Level1","Employees": [{"Name":"Jon","Title":"Level2","Employees": [{"Name":"Susan","Title":"Level3","Employees": [{"Name":"Joe","Title":"Level4","Employees": [{"Name":"Jimmy","Title":"Level5"}]}, {"Name":"Josh","Title":"Level4","Employees": [[{"Name":"Jimmy","Title":"Level5"}]]}]}]}]}] </code></pre> <p>Or pretty printed</p> <pre><code>[ { "Name": "Mike", "Title": "Level1", "Employees": [ { "Name": "Jon", "Title": "Level2", "Employees": [ { "Name": "Susan", "Title": "Level3", "Employees": [ { "Name": "Joe", "Title": "Level4", "Employees": [ { "Name": "Jimmy", "Title": "Level5" } ] }, { "Name": "Josh", "Title": "Level4", "Employees": [ [ { "Name": "Jimmy", "Title": "Level5" } ] ] } ] } ] } ] } ] </code></pre>
0
2016-08-18T14:38:03Z
[ "python", "json", "python-3.x" ]
How to remove apostrophes and parathenses in output?
39,009,098
<pre><code>a=str(input("Enter string: ")) b=str(input("Enter another: ")) def switch(x, y): x, y = y, x return x, y print (switch(a, b)) </code></pre> <p>output is for example: ('there', 'hello') I want to remove parathenses and ''</p>
0
2016-08-18T02:34:02Z
39,009,123
<p>Assuming you want to keep the output of your function the same (a tuple), you can use use <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> to print the tuple separated by a space:</p> <pre><code>a = input("Enter string: ") b = input("Enter another: ") def switch(x, y): return y, x print(' '.join(switch(a, b))) </code></pre> <p><strong>Small note</strong>: I changed the method to just be <code>return y, x</code>, since the other two lines in the method did not seem needed in this case :)</p>
1
2016-08-18T02:37:48Z
[ "python", "python-3.x", "output" ]
How to remove apostrophes and parathenses in output?
39,009,098
<pre><code>a=str(input("Enter string: ")) b=str(input("Enter another: ")) def switch(x, y): x, y = y, x return x, y print (switch(a, b)) </code></pre> <p>output is for example: ('there', 'hello') I want to remove parathenses and ''</p>
0
2016-08-18T02:34:02Z
39,011,001
<p>The return value of <code>switch</code> is a tuple of 2 items (a pair), which is passed to the <code>print</code> function as a single argument. And <code>print</code> converts each of its arguments to a string with implicit <code>str</code>, and the <code>('', '')</code> come from the string representation of this tuple.</p> <p>What you want is to pass each item in the pair separately.</p> <p>As this is Python 3, you just need to add one character:</p> <pre><code>print(*switch(a, b)) </code></pre> <p>The <code>*</code> means "pass the elements of the following iterable as separate positional arguments", so it is shorthand (in this case) for</p> <pre><code>value = switch(a, b) print(value[0], value[1]) </code></pre> <p>Print normally prints the values separated by a single space. If you want another separator, for example <code>,</code>, you can use the <code>sep</code> keyword argument:</p> <pre><code>print(*switch(a, b), sep=', ') </code></pre> <hr> <p>Finally, the <code>str()</code> in your example seem unnecessary.</p>
1
2016-08-18T06:09:02Z
[ "python", "python-3.x", "output" ]
Iterating Over Every Item in a Series in Pandas With A Custom Function
39,009,122
<p>I have a dataframe in Pandas that lists its information like this:</p> <pre><code> Player Year Height 1 Stephen Curry 2015-16 6-3 2 Mirza Teletovic 2015-16 6-10 3 C.J. Miles 2015-16 6-7 4 Robert Covington 2015-16 6-9 </code></pre> <p>Right now data['Height'] stores its values as strings and I'd like to convert these values into inches stores as integers for further calculation.</p> <p>I've tried a few approaches, including what's listed in the Pandas documentation, but to no avail. </p> <p><strong>First Attempt</strong></p> <pre><code>def true_height(string): new_str = string.split('-') inches1 = new_str[0] inches2 = new_str[1] inches1 = int(inches1)*12 inches2 = int(inches2) return inches1 + inches2 </code></pre> <p>If you run </p> <pre><code>true_height(data.iloc[0, 2]) </code></pre> <p>It returns 75, the correct answer. </p> <p>To run it on the entire series I changed this line of code:</p> <pre><code>new_str = string.**str**.split('-') </code></pre> <p>And then ran:</p> <pre><code>data['Height'].apply(true_height(data['Height'])) </code></pre> <p>And got the following error message:</p> <pre><code>int() argument must be a string or a number, not 'list' </code></pre> <p>I then tried using a for loop, thinking that might solve the trick, and so I modified the original formula to this:</p> <pre><code>def true_height(strings): for string in strings: new_str = string.split('-') inches1 = new_str[0] inches2 = new_str[1] inches1 = int(inches1)*12 inches2 = int(inches2) return inches1 + inches2 </code></pre> <p>And now I get the following error:</p> <pre><code>'int' object is not callable </code></pre> <p>When I run:</p> <pre><code>data['Height'].apply(true_height(data['Height'])) </code></pre> <p>I'm a little stumped. Any help would be appreciated. Thank you.</p>
1
2016-08-18T02:37:45Z
39,009,170
<p>You can use apply on the <code>Height</code> column after it gets splitted into lists and pass a lambda function to it for conversion:</p> <pre><code>df['Height'] = df.Height.str.split("-").apply(lambda x: int(x[0]) * 12 + int(x[1])) df # Player Year Height # 1 Stephen Curry 2015-16 75 # 2 Mirza Teletovic 2015-16 82 # 3 C.J. Miles 2015-16 79 # 4 Robert Covington 2015-16 81 </code></pre> <p>Or use your originally defined <code>true_height</code> function (1st attempt) with <code>apply</code>:</p> <pre><code>df['Height'] = df.Height.apply(true_height) </code></pre> <p>You just don't need to pass the <code>df.Height</code> to function since apply receives a function as a parameter.</p>
1
2016-08-18T02:44:12Z
[ "python", "pandas" ]
Iterating Over Every Item in a Series in Pandas With A Custom Function
39,009,122
<p>I have a dataframe in Pandas that lists its information like this:</p> <pre><code> Player Year Height 1 Stephen Curry 2015-16 6-3 2 Mirza Teletovic 2015-16 6-10 3 C.J. Miles 2015-16 6-7 4 Robert Covington 2015-16 6-9 </code></pre> <p>Right now data['Height'] stores its values as strings and I'd like to convert these values into inches stores as integers for further calculation.</p> <p>I've tried a few approaches, including what's listed in the Pandas documentation, but to no avail. </p> <p><strong>First Attempt</strong></p> <pre><code>def true_height(string): new_str = string.split('-') inches1 = new_str[0] inches2 = new_str[1] inches1 = int(inches1)*12 inches2 = int(inches2) return inches1 + inches2 </code></pre> <p>If you run </p> <pre><code>true_height(data.iloc[0, 2]) </code></pre> <p>It returns 75, the correct answer. </p> <p>To run it on the entire series I changed this line of code:</p> <pre><code>new_str = string.**str**.split('-') </code></pre> <p>And then ran:</p> <pre><code>data['Height'].apply(true_height(data['Height'])) </code></pre> <p>And got the following error message:</p> <pre><code>int() argument must be a string or a number, not 'list' </code></pre> <p>I then tried using a for loop, thinking that might solve the trick, and so I modified the original formula to this:</p> <pre><code>def true_height(strings): for string in strings: new_str = string.split('-') inches1 = new_str[0] inches2 = new_str[1] inches1 = int(inches1)*12 inches2 = int(inches2) return inches1 + inches2 </code></pre> <p>And now I get the following error:</p> <pre><code>'int' object is not callable </code></pre> <p>When I run:</p> <pre><code>data['Height'].apply(true_height(data['Height'])) </code></pre> <p>I'm a little stumped. Any help would be appreciated. Thank you.</p>
1
2016-08-18T02:37:45Z
39,009,308
<pre><code>df['feet'], df['inches'] = zip(*df.Height.str.split('-')) df['feet'] = df.feet.astype(int) df['inches'] = df.inches.astype(float) df['height_inches'] = df.feet * 12 + df.inches &gt;&gt;&gt; df Player Year Height feet inches height_inches 1 Stephen Curry 2015-16 6-3 6 3 75 2 Mirza Teletovic 2015-16 6-10 6 10 82 3 C.J. Miles 2015-16 6-7 6 7 79 4 Robert Covington 2015-16 6-9 6 9 81 </code></pre>
1
2016-08-18T02:59:00Z
[ "python", "pandas" ]
Scraping eBay featured collections for product page links
39,009,134
<p>I'm attempting to build a web scraping tool using Python and BeautifulSoup that enters an eBay Featured Collection and retrieves the URLs of all the products within the collection (most collections have 17 products, although some have a few more or less). Here's the URL for the collection I attempt to scrape in my code: <a href="http://www.ebay.com/cln/ebayhomeeditor/Surface-Study/324079803018" rel="nofollow">http://www.ebay.com/cln/ebayhomeeditor/Surface-Study/324079803018</a></p> <p>Here's my code so far:</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'http://www.ebay.com/cln/ebayhomeeditor/Surface-Study/324079803018' soup = BeautifulSoup(requests.get(url).text, 'html.parser') product_links = [] item_thumb = soup.find_all('div', attrs={'class':'itemThumb'}) for link in item_thumb: product_links.append(link.find('a').get('href')) print product_links </code></pre> <p>This scraper should append 17 links to the list product_links. However, it only works partway. Specifically, it only scrapes the first 12 product links every time, leaving the remaining 5 untouched, even though all 17 links are found within the same HTML tags and attributes. Looking more closely at the page's HTML code, the only difference I found is that the first 12 links and the final 5 are separated by a piece of XML script that I have included here:</p> <pre><code>&lt;script escape-xml="true"&gt; if (typeof(collectionState) != 'object') { var collectionState = { itemImageSize: {sWidth: 280, sHeight: 280, lWidth: 580, lHeight: 620}, page: 1, totalPages: 2, totalItems: 17, pageId: '2057253', currentUser: '', collectionId: '323101965012', serviceHost: 'svcs.ebay.com/buying/collections/v1', owner: 'ebaytecheditor', csrfToken: '', localeId: 'en-US', siteId: 'EBAY-US', countryId: 'US', collectionCosEnabled: 'true', collectionCosHostExternal: 'https://api.ebay.com/social/collection/v1', collectionCosEditEnabled: 'true', isCollectionReorderEnabled: 'false', isOwnerSignedIn: false || false, partiallySignedInUser: '@@__@@__@@', baseDomain: 'ebay.com', currentDomain: 'www.ebay.com', isTablet: false, isMobile: false, showViewCount: true }; } &lt;/script&gt; </code></pre> <p>What is the function of this script? Is it possible that this script is the reason my scraper neglects to scrape the final 5 links? Is there a way to work around this and scape the final five?</p>
1
2016-08-18T02:38:42Z
39,017,753
<p>The last few are generated through an <em>ajax</em> request to <em><a href="http://www.ebay.com/cln/_ajax/2/ebayhomeeditor/324079803018" rel="nofollow">http://www.ebay.com/cln/_ajax/2/ebayhomeeditor/324079803018</a></em>:</p> <p><a href="http://i.stack.imgur.com/2gENp.png" rel="nofollow"><img src="http://i.stack.imgur.com/2gENp.png" alt="enter image description here"></a></p> <p>The url is made up using <em>ebayhomeeditor</em> and what must be some product id <em>324079803018</em> which are both in the original url of the page you visit.</p> <p>The only param that is essential to get data back is the <em>itemsPerPage</em> but you can play around with the rest and see what effect they have.</p> <pre><code>params = {"itemsPerPage": "10"} soup= BeautifulSoup(requests.get("http://www.ebay.com/cln/_ajax/2/ebayhomeeditor/324079803018", params=params).content) print([a["href"] for a in soup.select("div.itemThumb div.itemImg.image.lazy-image a[href]")]) </code></pre> <p>Which would give you:</p> <pre><code>['http://www.ebay.com/itm/yamazaki-home-tower-book-end-white-stationary-holder-desktop-organizing-steel/171836462366?hash=item280240551e', 'http://www.ebay.com/itm/tetris-constructible-interlocking-desk-lamp-neon-light-nightlight-by-paladone/221571335719?hash=item3396ae4627', 'http://www.ebay.com/itm/iphone-docking-station-dock-native-union-new-in-box/222202878086?hash=item33bc52d886', 'http://www.ebay.com/itm/turnkey-pencil-sharpener-silver-office-home-school-desk-gift-peleg-design/201461359979?hash=item2ee808656b', 'http://www.ebay.com/itm/himori-weekly-times-desk-notepad-desktop-weekly-scheduler-30-weeks-planner/271985620013?hash=item3f539b342d'] </code></pre> <p>So putting it together to get all urls:</p> <pre><code>In [23]: params = {"itemsPerPage": "10"} In [24]: with requests.Session() as s: ....: soup1 = BeautifulSoup(s.get('http://www.ebay.com/cln/ebayhomeeditor/Surface-Study/324079803018').content, ....: "html.parser") ....: main_urls = [a["href"] for a in soup1.select("div.itemThumb div.itemImg.image.lazy-image a[href]")] ....: soup2 = BeautifulSoup(s.get("http://www.ebay.com/cln/_ajax/2/ebayhomeeditor/324079803018", params=params).content, ....: "html.parser") ....: print(len(main_urls)) ....: main_urls.extend(a["href"] for a in soup2.select("div.itemThumb div.itemImg.image.lazy-image a[href]")) ....: print(main_urls) ....: print(len(main_urls)) ....: 12 ['http://www.ebay.com/itm/archi-desk-accessories-pen-cup-designed-by-hsunli-huang-for-moma/262435041373?hash=item3d1a58f05d', 'http://www.ebay.com/itm/moorea-seal-violet-light-crane-scissors/201600302323?hash=item2ef0507cf3', 'http://www.ebay.com/itm/kikkerland-photo-holder-with-6-magnetic-wooden-clothespin-mh69-cable-47-long/361394782932?hash=item5424cec2d4', 'http://www.ebay.com/itm/authentic-22-design-studio-merge-concrete-pen-holder-desk-office-pencil/331846509549?hash=item4d4397e3ed', 'http://www.ebay.com/itm/supergal-bookend-by-artori-design-ad103-metal-black/272273290322?hash=item3f64c0b452', 'http://www.ebay.com/itm/elago-p2-stand-for-ipad-tablet-pcchampagne-gold/191527567203?hash=item2c97eebf63', 'http://www.ebay.com/itm/this-is-ground-mouse-pad-pro-ruler-100-authentic-natural-retail-100/201628986934?hash=item2ef2062e36', 'http://www.ebay.com/itm/hot-fuut-foot-rest-hammock-under-desk-office-footrest-mini-stand-hanging-swing/152166878943?hash=item236dda4edf', 'http://www.ebay.com/itm/unido-silver-white-black-led-desk-office-lamp-adjustable-neck-brightness-level/351654910666?hash=item51e0441aca', 'http://www.ebay.com/itm/in-house-black-desk-office-organizer-paper-clips-memo-notes-monkey-business/201645856763?hash=item2ef30797fb', 'http://www.ebay.com/itm/rifle-paper-co-2017-maps-desk-calendar-illustrated-worldwide-cities/262547131670?hash=item3d21074d16', 'http://www.ebay.com/itm/muji-erasable-pen-black/262272348079?hash=item3d10a66faf', 'http://www.ebay.com/itm/rifle-paper-co-2017-maps-desk-calendar-illustrated-worldwide-cities/262547131670?hash=item3d21074d16', 'http://www.ebay.com/itm/muji-erasable-pen-black/262272348079?hash=item3d10a66faf', 'http://www.ebay.com/itm/yamazaki-home-tower-book-end-white-stationary-holder-desktop-organizing-steel/171836462366?hash=item280240551e', 'http://www.ebay.com/itm/tetris-constructible-interlocking-desk-lamp-neon-light-nightlight-by-paladone/221571335719?hash=item3396ae4627', 'http://www.ebay.com/itm/iphone-docking-station-dock-native-union-new-in-box/222202878086?hash=item33bc52d886', 'http://www.ebay.com/itm/turnkey-pencil-sharpener-silver-office-home-school-desk-gift-peleg-design/201461359979?hash=item2ee808656b', 'http://www.ebay.com/itm/himori-weekly-times-desk-notepad-desktop-weekly-scheduler-30-weeks-planner/271985620013?hash=item3f539b342d'] 19 In [25]: </code></pre> <p>There is a little overlap with what gets returned so just use a set to store the main_urls or call set on the list:</p> <pre><code>In [25]: len(set(main_urls)) Out[25]: 17 </code></pre> <p>Not sure why that happens and have not really tried to figure it out, if it bothers you then you could parse "totalItems: 17" from the ajax call returned source and subtract the length of <code>main_urls</code> after the first call and set <code>{"itemsPerPage": str(len(main_urls) - int(parsedtotal))}</code> but I would not worry too much about it. </p>
0
2016-08-18T12:03:15Z
[ "python", "xml", "web-scraping", "beautifulsoup", "ebay" ]
Download a picture from certain URL with Python
39,009,195
<p>I learned how to download a picture from a certain URL with python as:</p> <pre><code>import urllib imgurl="http://www.digimouth.com/news/media/2011/09/google-logo.jpg" resource = urllib.urlopen(imgurl) output = open("test.jpg","wb") output.write(resource.read()) output.close() </code></pre> <p>and it worked well, but when i changed the URL to </p> <pre><code> imgurl="http://farm1.static.flickr.com/96/242125326_607a826afe_o.jpg" </code></pre> <p>it did not work, and gave the information</p> <pre><code>File "face_down.py", line 3, in &lt;module&gt; resource = urllib2.urlopen(imgurl) File "D:\Python27\another\Lib\urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "D:\Python27\another\Lib\urllib2.py", line 431, in open response = self._open(req, data) File "D:\Python27\another\Lib\urllib2.py", line 449, in _open '_open', req) File "D:\Python27\another\Lib\urllib2.py", line 409, in _call_chain result = func(*args) File "D:\Python27\another\Lib\urllib2.py", line 1227, in http_open return self.do_open(httplib.HTTPConnection, req) File "D:\Python27\another\Lib\urllib2.py", line 1197, in do_open raise URLError(err) urllib2.URLError: &lt;urlopen error [Errno 10060] &gt; </code></pre> <p>and I tried to open the latter image URL, and it could be shown as the former, I have no idea to solve it~~ help~~~~</p>
0
2016-08-18T02:46:15Z
39,009,434
<p>I looked up both of the addresses and the second one does not lead anywhere. That is probably the problem. </p> <pre><code>import urllib imgurl="webpage url" openimg = urllib.urlopen(imgurl) #opens image (prepares it) img = open("test.jpg","wb") #opens the img to read it img.write(openimg.read()) #prints it to the console img.close() #closes img </code></pre> <p>Try the link again in your webpage and if it turns up with "webpage not available" that is probably the problem.</p>
0
2016-08-18T03:14:23Z
[ "python", "image" ]
Download a picture from certain URL with Python
39,009,195
<p>I learned how to download a picture from a certain URL with python as:</p> <pre><code>import urllib imgurl="http://www.digimouth.com/news/media/2011/09/google-logo.jpg" resource = urllib.urlopen(imgurl) output = open("test.jpg","wb") output.write(resource.read()) output.close() </code></pre> <p>and it worked well, but when i changed the URL to </p> <pre><code> imgurl="http://farm1.static.flickr.com/96/242125326_607a826afe_o.jpg" </code></pre> <p>it did not work, and gave the information</p> <pre><code>File "face_down.py", line 3, in &lt;module&gt; resource = urllib2.urlopen(imgurl) File "D:\Python27\another\Lib\urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "D:\Python27\another\Lib\urllib2.py", line 431, in open response = self._open(req, data) File "D:\Python27\another\Lib\urllib2.py", line 449, in _open '_open', req) File "D:\Python27\another\Lib\urllib2.py", line 409, in _call_chain result = func(*args) File "D:\Python27\another\Lib\urllib2.py", line 1227, in http_open return self.do_open(httplib.HTTPConnection, req) File "D:\Python27\another\Lib\urllib2.py", line 1197, in do_open raise URLError(err) urllib2.URLError: &lt;urlopen error [Errno 10060] &gt; </code></pre> <p>and I tried to open the latter image URL, and it could be shown as the former, I have no idea to solve it~~ help~~~~</p>
0
2016-08-18T02:46:15Z
39,010,340
<p>You can try using <strong>requests</strong> module. The response will be some bytes. So, you can iterate over those byte chunks and write to the file.</p> <pre><code>import requests url = "http://farm1.static.flickr.com/96/242125326_607a826afe_o.jpg" r = requests.get(url) path = "filename.jpg" with open(path, 'wb') as f: for chunk in r: f.write(chunk) </code></pre>
1
2016-08-18T05:04:00Z
[ "python", "image" ]
Flip bits in array using python
39,009,304
<p>You are given an integer array with <code>N</code> elements: <code>d[0], d[1], ... d[N - 1]</code>. You can perform AT MOST one move on the array: choose any two integers <code>[L, R]</code>, and flip all the elements between (and including) the <code>L</code>-th and <code>R</code>-th bits. <code>L</code> and <code>R</code> represent the left-most and right-most index of the bits marking the boundaries of the segment which you have decided to flip.</p> <p>What is the maximum number of <code>1</code>-bits (indicated by <code>S</code>) which you can obtain in the final bit-string? </p> <p>'Flipping' a bit means, that a <code>0</code> is transformed to a <code>1</code> and a <code>1</code> is transformed to a <code>0</code> (<code>0-&gt;1</code>,<code>1-&gt;0</code>). </p> <p>Input Format: An integer <code>N</code>, next line contains the <code>N</code> bits, separated by spaces: <code>d[0] d[1] ... d[N - 1]</code></p> <p>Output: <code>S</code> </p> <p>Constraints: </p> <pre><code>1 &lt;= N &lt;= 100000, d[i] can only be 0 or 1 , 0 &lt;= L &lt;= R &lt; n , </code></pre> <p>Sample Input: </p> <pre><code>8 1 0 0 1 0 0 1 0 </code></pre> <p>Sample Output: <code>6</code> </p> <p>Explanation: </p> <p>We can get a maximum of 6 ones in the given binary array by performing either of the following operations: </p> <pre><code>Flip [1, 5] ==&gt; 1 1 1 0 1 1 1 0 </code></pre>
3
2016-08-18T02:58:41Z
39,011,421
<h3> Cleaned up and made Pythonic </h3> <pre><code>arr1 = [1, 0, 0, 1, 0, 0, 1, 0] arr2 = [1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1] arr3 = [0,0,0,1,1,0,1,0,1,1,0,0,1,1,1] def maximum_ones(arr): """ Returns max possible number of ones after flipping a span of bit array """ total_one = 0 net = 0 maximum = 0 for bit in arr: if bit: total_one += 1 net -= 1 else: net += 1 maximum = max(maximum, net) if net &lt; 0: net = 0 return total_one + maximum print(maximum_ones(arr1)) print(maximum_ones(arr2)) print(maximum_ones(arr3)) </code></pre> <p>Output:</p> <pre><code>6 14 11 </code></pre> <h3>If we want the L and R indices</h3> <p>Not so sure about this one. It can probably be made cleaner.</p> <pre><code>arr1 = [1, 0, 0, 1, 0, 0, 1, 0] arr2_0 = [1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1] arr2_1 = [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1] arr2_2 = [1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1] arr3 = [0,0,0,1,1,0,1,0,1,1,0,0,1,1,1] def maximum_ones(arr): """ Returns max possible number of ones after flipping a span of bit array and the (L,R) indices (inclusive) of such a flip """ total_one = 0 net = 0 maximum = 0 L = R = 0 started_flipping = False for i, bit in enumerate(arr): if bit: total_one += 1 net -= 1 else: net += 1 if not started_flipping: started_flipping = True L = i if net &gt; maximum: maximum = net R = i if net &lt; 0: net = 0 if i &lt; R: L = i return (total_one + maximum, (L,R)) print(maximum_ones(arr1)) print(maximum_ones(arr2_0)) print(maximum_ones(arr2_1)) print(maximum_ones(arr2_2)) print(maximum_ones(arr3)) </code></pre> <p>Output:</p> <pre><code>(6, (1, 5)) (14, (1, 16)) (14, (2, 16)) (14, (3, 16)) (11, (0, 2)) </code></pre> <h3>First Iteration</h3> <p>Here is what I had originally, if you want to see the evolution of the thought processes. Here, I was essentially transliterating what I came up with on paper.</p> <p>Essentially, we traverse the array and start flipping bits (ok, not really), keeping track of cumulative flipped zeros and cumulative flipped ones in two separate arrays along with the total flipped ones in an integer counter. If the difference between flipped ones and zeroes at a given index - the "net" - drops below zero, we 'reset' the cumulative counts back at zero at that index (but nothing else). Along the way, we also keep track of the maximum net we've achieved and the index at which that occurs. Thus, the total is simply the total 1's we've seen, plus the net at the maximum index. </p> <pre><code>arr = [1, 0, 0, 1, 0, 0, 1, 0] total_one = 0 one_flip = [0 for _ in range(len(arr))] zero_flip = [0 for _ in range(len(arr))] # deal with first element of array if arr[0]: total_one += 1 else: zero_flip[0] = 1 maximum = dict(index=0,value=0) #index, value i = 1 # now deal with the rest while i &lt; len(arr): # if element is 1 we definitely increment total_one, else, we definitely flip if arr[i]: total_one += 1 one_flip[i] = one_flip[i-1] + 1 zero_flip[i] = zero_flip[i-1] else: zero_flip[i] = zero_flip[i-1] + 1 one_flip[i] = one_flip[i-1] net = zero_flip[i] - one_flip[i] if net &gt; 0: if maximum['value'] &lt; net: maximum['value'] = net maximum['index'] = i else: # net == 0, we restart counting our "net" one_flip[i] = 0 zero_flip[i] = 0 i += 1 maximum_flipped = total_one - one_flip[maximum['index']] + zero_flip[maximum['index']] </code></pre> <p>Results:</p> <pre><code>print(total_one, -one_flip[maximum['index']], zero_flip[maximum['index']] ) print(maximum_flipped) print('________________________________________________') print(zero_flip, arr, one_flip, sep='\n') print('maximum index', maximum['index']) </code></pre> <p>Output:</p> <pre><code>3 -1 4 6 ________________________________________________ [0, 1, 2, 2, 3, 4, 4, 5] [1, 0, 0, 1, 0, 0, 1, 0] [0, 0, 0, 1, 1, 1, 2, 2] maximum index 5 </code></pre> <p>if <p><code>arr = [1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1]</code></p></p> <pre><code>6 -4 12 14 ________________________________________________ [0, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 9, 10, 10, 11, 12, 12] [1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1] [0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5] maximum index 16 </code></pre> <p>Finally, if <p> <code>arr = [0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1]</code> </p></p> <pre><code>8 0 3 11 ________________________________________________ [1, 2, 3, 3, 3, 4, 4, 5, 5, 0, 1, 2, 2, 0, 0] [0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1] [0, 0, 0, 1, 2, 2, 3, 3, 4, 0, 0, 0, 1, 0, 0] maximum index 2 </code></pre> <h2> Great, now tear it apart, people!</h2>
3
2016-08-18T06:37:18Z
[ "python", "algorithm", "list", "bit-manipulation", "bits" ]
Flip bits in array using python
39,009,304
<p>You are given an integer array with <code>N</code> elements: <code>d[0], d[1], ... d[N - 1]</code>. You can perform AT MOST one move on the array: choose any two integers <code>[L, R]</code>, and flip all the elements between (and including) the <code>L</code>-th and <code>R</code>-th bits. <code>L</code> and <code>R</code> represent the left-most and right-most index of the bits marking the boundaries of the segment which you have decided to flip.</p> <p>What is the maximum number of <code>1</code>-bits (indicated by <code>S</code>) which you can obtain in the final bit-string? </p> <p>'Flipping' a bit means, that a <code>0</code> is transformed to a <code>1</code> and a <code>1</code> is transformed to a <code>0</code> (<code>0-&gt;1</code>,<code>1-&gt;0</code>). </p> <p>Input Format: An integer <code>N</code>, next line contains the <code>N</code> bits, separated by spaces: <code>d[0] d[1] ... d[N - 1]</code></p> <p>Output: <code>S</code> </p> <p>Constraints: </p> <pre><code>1 &lt;= N &lt;= 100000, d[i] can only be 0 or 1 , 0 &lt;= L &lt;= R &lt; n , </code></pre> <p>Sample Input: </p> <pre><code>8 1 0 0 1 0 0 1 0 </code></pre> <p>Sample Output: <code>6</code> </p> <p>Explanation: </p> <p>We can get a maximum of 6 ones in the given binary array by performing either of the following operations: </p> <pre><code>Flip [1, 5] ==&gt; 1 1 1 0 1 1 1 0 </code></pre>
3
2016-08-18T02:58:41Z
39,017,130
<p>Traverse the whole array. Keep a <code>count</code> in the following way:</p> <ul> <li><p>Do <code>+1</code> for every 0 bit encountered.</p></li> <li><p>Do <code>-1</code> for every 1.</p></li> </ul> <p>If this count reaches -ve at any stage, reset it to 0. Keep track of <code>max</code> value of this <code>count</code>. Add this <code>max_count</code> to number of <code>1's</code> in input array. This will be your answer.</p> <p><strong>Code:</strong></p> <pre><code>arr = [1, 0, 0, 1, 0, 0, 1, 0] # I'm taking your sample case. Take the input the way you want count,count_max,ones = 0,0,0 for i in arr: if i == 1: ones += 1 count -= 1 if i == 0: count += 1 if count_max &lt; count: count_max = count if count &lt; 0: count = 0 print (ones + count_max) </code></pre> <p>Small and simple :)</p>
1
2016-08-18T11:32:39Z
[ "python", "algorithm", "list", "bit-manipulation", "bits" ]
replace previous print output with new print output or add characters to previous output
39,009,312
<p>I'm pretty new to Python programming, and I'm attempting to create a simple little game with a little "initialization" on boot up.</p> <p>I pretty much want it to spell out "Welcome", but with all of the letters popping up every <strong>100ms</strong>.</p> <p>I've got the <code>sleep</code> function down pat, however, rather than adding on each character to the end of the previous line, it is simply printing it all out on a new line.</p> <p>This is what I'm currently getting:</p> <pre><code>W e l c o m e . </code></pre> <p>I'd prefer it to just be <code>Welcome.</code></p> <p>This is my current code:</p> <pre><code>print("W") time.sleep(0.1) print("e") time.sleep(0.1) print("l") time.sleep(0.1) print("c") time.sleep(0.1) print("o") time.sleep(0.1) print("m") time.sleep(0.1) print("e") </code></pre> <p>I have looked around, but have failed to understand how to implement the function into Python. So an explanation would be extremely appreciated!</p> <p>Thanks.</p>
1
2016-08-18T02:59:22Z
39,009,350
<p>Use <code>end=''</code> when calling <code>print()</code>:</p> <pre><code>import time for c in "Welcome": print(c, end='') time.sleep(0.1) </code></pre>
2
2016-08-18T03:04:32Z
[ "python" ]
replace previous print output with new print output or add characters to previous output
39,009,312
<p>I'm pretty new to Python programming, and I'm attempting to create a simple little game with a little "initialization" on boot up.</p> <p>I pretty much want it to spell out "Welcome", but with all of the letters popping up every <strong>100ms</strong>.</p> <p>I've got the <code>sleep</code> function down pat, however, rather than adding on each character to the end of the previous line, it is simply printing it all out on a new line.</p> <p>This is what I'm currently getting:</p> <pre><code>W e l c o m e . </code></pre> <p>I'd prefer it to just be <code>Welcome.</code></p> <p>This is my current code:</p> <pre><code>print("W") time.sleep(0.1) print("e") time.sleep(0.1) print("l") time.sleep(0.1) print("c") time.sleep(0.1) print("o") time.sleep(0.1) print("m") time.sleep(0.1) print("e") </code></pre> <p>I have looked around, but have failed to understand how to implement the function into Python. So an explanation would be extremely appreciated!</p> <p>Thanks.</p>
1
2016-08-18T02:59:22Z
39,009,364
<p>Python's <code>print()</code> function normally prints outputs on a new line, meaning that every time you print something, it appears on another line. To print everything on the same line, as you're asking, use the <code>print()</code> function like this:</p> <pre><code>print("W", end="") </code></pre> <p>Notice the second argument which tells Python to continue printing on the same line. The <code>print()</code> function defaults to an ending of <code>\n</code>, or new line. Setting <code>end</code> equal to "" replaced the <code>\n</code> with an empty string.</p> <p>In the event that you need to use the <code>print()</code> function after you print out "Welcome", the last <code>print()</code> function you use to print out the 'e' should be normal, like this:</p> <pre><code>print("e") </code></pre> <p>This way if you print anything after "Welcome", it will print on a new line.</p>
1
2016-08-18T03:06:07Z
[ "python" ]
replace previous print output with new print output or add characters to previous output
39,009,312
<p>I'm pretty new to Python programming, and I'm attempting to create a simple little game with a little "initialization" on boot up.</p> <p>I pretty much want it to spell out "Welcome", but with all of the letters popping up every <strong>100ms</strong>.</p> <p>I've got the <code>sleep</code> function down pat, however, rather than adding on each character to the end of the previous line, it is simply printing it all out on a new line.</p> <p>This is what I'm currently getting:</p> <pre><code>W e l c o m e . </code></pre> <p>I'd prefer it to just be <code>Welcome.</code></p> <p>This is my current code:</p> <pre><code>print("W") time.sleep(0.1) print("e") time.sleep(0.1) print("l") time.sleep(0.1) print("c") time.sleep(0.1) print("o") time.sleep(0.1) print("m") time.sleep(0.1) print("e") </code></pre> <p>I have looked around, but have failed to understand how to implement the function into Python. So an explanation would be extremely appreciated!</p> <p>Thanks.</p>
1
2016-08-18T02:59:22Z
39,009,726
<p>How about this - </p> <pre><code>for c in "Welcome": print '\b%s' % c, time.sleep(0.1) </code></pre>
0
2016-08-18T03:52:20Z
[ "python" ]
Is it possible to use an argument's value in a default argument value assignment in Python?
39,009,317
<p>I am trying to use the left-side argument's value in the below function inside of the default argument value to the right. </p> <pre><code>def function(var, vartwo = var*2): return vartwo print(function(7)) #should print 14 print(function(7,6)) #should print 6 </code></pre> <p>However I am getting NameError: name 'var' is not defined. Is it not possible use an argument's value in a default argument value in Python? How would you suggest I tackle this problem?</p>
0
2016-08-18T03:00:03Z
39,009,372
<p>It's not possible; how about this?</p> <pre><code>def function(var, vartwo = None): if vartwo is None: vartwo = var*2 return vartwo print(function(7)) print(function(7,6)) </code></pre> <p>The hack is to set the default value to <code>None</code>, then set it internally. If not none, then return whatever was entered by the user.</p>
3
2016-08-18T03:07:26Z
[ "python" ]
Is it possible to use an argument's value in a default argument value assignment in Python?
39,009,317
<p>I am trying to use the left-side argument's value in the below function inside of the default argument value to the right. </p> <pre><code>def function(var, vartwo = var*2): return vartwo print(function(7)) #should print 14 print(function(7,6)) #should print 6 </code></pre> <p>However I am getting NameError: name 'var' is not defined. Is it not possible use an argument's value in a default argument value in Python? How would you suggest I tackle this problem?</p>
0
2016-08-18T03:00:03Z
39,009,399
<p>What your doing won't work because var hasn't been declared. Here's a different approach:</p> <pre><code>def function(var, multiply=False): if multiply: return var * 2 else: return var print(function(7, True)) # 14 print(function(6)) # 6 </code></pre>
0
2016-08-18T03:10:54Z
[ "python" ]
Is it possible to use an argument's value in a default argument value assignment in Python?
39,009,317
<p>I am trying to use the left-side argument's value in the below function inside of the default argument value to the right. </p> <pre><code>def function(var, vartwo = var*2): return vartwo print(function(7)) #should print 14 print(function(7,6)) #should print 6 </code></pre> <p>However I am getting NameError: name 'var' is not defined. Is it not possible use an argument's value in a default argument value in Python? How would you suggest I tackle this problem?</p>
0
2016-08-18T03:00:03Z
39,009,405
<p>Pass the buck:</p> <pre><code>def function(var, *args): return (lambda var, vartwo=var * 2: vartwo)(var, *args) print(function(7)) # should print 14 print(function(7, 6)) # should print 6 </code></pre> <blockquote> <p>I know about lambda functions but mind adding explanation?</p> </blockquote> <p>Since we can't use <code>var</code> in <code>vartwo</code>'s definition, we delay by setting up a new argument list, via a <code>lambda</code>, where <code>var</code> is now defined and the default for <code>vartwo</code> is legal.</p> <p>I've made this somewhat confusing by reusing the <code>var</code> variable name to represent two different variables (a formal parameter to <code>function</code> and a formal parameter to <code>lambda</code>) and also act as a positional place holder.</p> <p>I could, and probably should, have written this more simply as:</p> <pre><code>def function(var, *args): return (lambda vartwo=var * 2: vartwo)(*args) </code></pre> <p>But I wanted to retain the flavor of the original problem.</p>
2
2016-08-18T03:11:42Z
[ "python" ]
Is it possible to use an argument's value in a default argument value assignment in Python?
39,009,317
<p>I am trying to use the left-side argument's value in the below function inside of the default argument value to the right. </p> <pre><code>def function(var, vartwo = var*2): return vartwo print(function(7)) #should print 14 print(function(7,6)) #should print 6 </code></pre> <p>However I am getting NameError: name 'var' is not defined. Is it not possible use an argument's value in a default argument value in Python? How would you suggest I tackle this problem?</p>
0
2016-08-18T03:00:03Z
39,010,353
<p>No, it is not possible to use a value that is not defined outside of the function as a argument value for that function.</p> <p>For an alternative, I'm late to the party, but how about something short and simple that will work if <code>None</code> is the second parameter?</p> <pre><code>def function(var, *args): return args[0] if args else var * 2 print(function(7)) # prints 14 print(function(7, 6)) # prints 6 print(function(7, None)) # prints 'None' </code></pre> <p>Here, <code>args</code> is the list of arguments provided after <code>var</code>, and could be an empty list. We then return the first element of this list if the list is not empty (which is equivalent to the second argument). If the list is empty, we return <code>var * 2</code>.</p> <p>The caveat here is that this will not throw the appropriate error if more than two arguments are provided. You can choose to manually raise a <code>TypeError</code> if <code>len(args) &gt; 1</code> (remembering that <code>args</code> are parameters <em>after</em> the first one) if this is important to enforce.</p>
0
2016-08-18T05:05:25Z
[ "python" ]
Is it possible to use an argument's value in a default argument value assignment in Python?
39,009,317
<p>I am trying to use the left-side argument's value in the below function inside of the default argument value to the right. </p> <pre><code>def function(var, vartwo = var*2): return vartwo print(function(7)) #should print 14 print(function(7,6)) #should print 6 </code></pre> <p>However I am getting NameError: name 'var' is not defined. Is it not possible use an argument's value in a default argument value in Python? How would you suggest I tackle this problem?</p>
0
2016-08-18T03:00:03Z
39,010,825
<p>It is not possible to use the value of another argument in default value. The reason is very simple: the default values are evaluated exactly once: at the time when the function definition was executed.</p> <p>One common pattern to use is to have the second argument be set to a special sentinel value by default, then test if the argument was set again within the function:</p> <pre><code>SENTINEL = object() def function(var, vartwo=SENTINEL): # was vartwo set? if vartwo is not SENTINEL: return vartwo return var * 2 </code></pre> <p>This way the function would return <code>vartwo</code> correctly even when you'd pass in <code>None</code> or any other value for it, unless you specifically passed the <code>SENTINEL</code> constant.</p>
0
2016-08-18T05:55:17Z
[ "python" ]
new to coding and python. trying to force type (int) for a float answer
39,009,379
<pre><code>balance = 50 - 0.12 * 15 tracks_left = balance / 0.12 round (tracks_left, 0) print 'you have', tracks_left,"to download" </code></pre> <p>The answer is <code>you have 401.666666667 to download</code> I've tried <code>round(tracks_left, 0)</code> and <code>int (tracks_left)</code>. What am I doing wrong?</p>
0
2016-08-18T03:08:26Z
39,009,427
<p><code>round(tracks_left, 0)</code> does not mutate tracks_left, but instead returns a new value. Likewise with <code>int(tracks_left)</code>. </p> <p>Try:</p> <pre><code>tracks_left = round(tracks_left, 0) </code></pre> <p>Or:</p> <pre><code>tracks_left = int(tracks_left) </code></pre> <p>Note: <code>int</code> always rounds down. </p>
2
2016-08-18T03:13:46Z
[ "python" ]
new to coding and python. trying to force type (int) for a float answer
39,009,379
<pre><code>balance = 50 - 0.12 * 15 tracks_left = balance / 0.12 round (tracks_left, 0) print 'you have', tracks_left,"to download" </code></pre> <p>The answer is <code>you have 401.666666667 to download</code> I've tried <code>round(tracks_left, 0)</code> and <code>int (tracks_left)</code>. What am I doing wrong?</p>
0
2016-08-18T03:08:26Z
39,009,438
<p><code>round(tracks_left, 0)</code> doesn't change <code>tracks_left</code>. It just returns the value. You have to assign it to something.</p> <pre><code>&gt;&gt;&gt; balance = 50 - 0.12 * 15 &gt;&gt;&gt; tracks_left = balance / 0.12 &gt;&gt;&gt; tracks_left_rounded = round(tracks_left, 0) &gt;&gt;&gt; print('You have', tracks_left_rounded) You have 402.0 </code></pre> <p>You could as well do this:</p> <pre><code>&gt;&gt;&gt; balance = 50 - 0.12 * 15 &gt;&gt;&gt; tracks_left = round(balance / 0.12) </code></pre> <p>You can also try <code>int</code>:</p> <pre><code>&gt;&gt;&gt; tracks_left_rounded = int(tracks_left) &gt;&gt;&gt; print('You have', tracks_left_rounded) You have 401 </code></pre> <p>I hope it helps!</p>
1
2016-08-18T03:14:27Z
[ "python" ]
Execute a code at some point of time
39,009,564
<p>I am creating a web app made of python flask.. What I want is if I created an invoice it automatically send an e-mail on its renewal date to notify that the invoice is renewed and so on.. Please take note that renewal occurs every 3 months The code is something like:</p> <pre><code>def some_method(): // An API Enpoint that adds an invoice from a request // Syntax that inserts the details to the database // Let's assume that the the start of the renewal_date is December 15, 2016 </code></pre> <p>How will the automatic email execution be achieved? Without putting too much stress in the backend? Because I'm guessing that if there are 300 invoices then the server might be stressed out</p>
0
2016-08-18T03:34:10Z
39,009,812
<p>You can use crontab in Linux, The syntax look like this</p> <pre><code>crontab -e 1 2 3 4 5 /path/to/command arg1 arg2 </code></pre> <p>Or maybe you can have a look at Celery, Which I think is a good tool to handle Task Queue, and you may find something useful here.<a href="http://docs.celeryproject.org/en/latest/reference/celery.schedules.html" rel="nofollow">celery.schedules</a></p> <h3>EDIT</h3> <p><a href="http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/" rel="nofollow">Schedule Tasks on Linux Using Crontab</a></p> <p><a href="http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/" rel="nofollow">HowTo: Add Jobs To cron Under Linux or UNIX?</a></p> <p><a href="http://www.howtogeek.com/101288/how-to-schedule-tasks-on-linux-an-introduction-to-crontab-files/" rel="nofollow">How to Schedule Tasks on Linux: An Introduction to Crontab Files</a></p>
1
2016-08-18T04:04:15Z
[ "python", "flask" ]
Execute a code at some point of time
39,009,564
<p>I am creating a web app made of python flask.. What I want is if I created an invoice it automatically send an e-mail on its renewal date to notify that the invoice is renewed and so on.. Please take note that renewal occurs every 3 months The code is something like:</p> <pre><code>def some_method(): // An API Enpoint that adds an invoice from a request // Syntax that inserts the details to the database // Let's assume that the the start of the renewal_date is December 15, 2016 </code></pre> <p>How will the automatic email execution be achieved? Without putting too much stress in the backend? Because I'm guessing that if there are 300 invoices then the server might be stressed out</p>
0
2016-08-18T03:34:10Z
39,009,883
<p>If I understand correctly, you'll want to get the date when you generate the invoice, then add 3 months (90 days). You can use <code>datetime.timedelta(days=90)</code> in Python for this. Take a look at: <a href="http://stackoverflow.com/questions/6871016/adding-5-days-to-a-date-in-python">Adding 5 days to a date in Python</a>.</p> <p>From there, you <em>could theoretically</em> spawn a thread with <code>Threading.timer()</code> (as seen here: <a href="http://stackoverflow.com/questions/11523918/python-start-a-function-at-given-time">Python - Start a Function at Given Time</a>), but I would recommend against using Python for this part because, as you mention, it would put undue stress on the server (not to mention if the server goes down, you lose all your scheduling).</p> <p><strong>Option A (Schedule a task for each invoice)</strong>:</p> <p>What would be better is using the OS to schedule a task in the future. If your backend is Linux-based, Cron should work nicely. Take a look at this for ideas: <a href="http://stackoverflow.com/questions/5473780/how-to-setup-cron-to-run-a-file-just-once-at-a-specific-time-in-future">How to setup cron to run a file just once at a specific time in future?</a>. Personally, I like <a href="http://stackoverflow.com/a/5473853/1003959">this answer</a>, which suggests creating a file in <code>/etc/cron.d</code> for each task and having the script delete its own file when it has finished executing.</p> <p><strong>Option B (Check daily if reminders should be sent):</strong></p> <p>I know it's not what you asked, but I'll also suggest it might be cleaner to handle this as a daily task. You can schedule a daily cron job like this:</p> <pre><code>0 22 * * * /home/emailbot/bin/send_reminder_emails.py </code></pre> <p>So, in this example, at min 0, hour 22 (10pm) every day, every month, every day-of-the-week, check to see if we should send reminder emails.</p> <p>In your send_reminder_emails.py script, you check a record (could be a JSON or YML file, or your database, or a custom format) for any reminders that need to be sent "today". If there's none, the script just exits, and if there is, you send out a reminder to each person on the list. Optionally, you can clean up the entries in the file as the reminders expire, or periodically.</p> <p>Then all you have to do is add an entry to the reminder file every time an invoice is generated.</p> <pre><code>with open("reminder_list.txt", "a") as my_file: my_file.write("Invoice# person@email.com 2016-12-22") </code></pre> <p>An added benefit of this method is that if your server is down for maintenance, you can keep entries and send them tomorrow by checking if the email date has passed <code>datetime.datetime.now() &gt;= datetime(2016,12,22)</code>. If you do that, you'll also want to keep a true/false flag that indicates whether the email has already been sent (so that you don't spam customers).</p>
0
2016-08-18T04:13:10Z
[ "python", "flask" ]
Execute a code at some point of time
39,009,564
<p>I am creating a web app made of python flask.. What I want is if I created an invoice it automatically send an e-mail on its renewal date to notify that the invoice is renewed and so on.. Please take note that renewal occurs every 3 months The code is something like:</p> <pre><code>def some_method(): // An API Enpoint that adds an invoice from a request // Syntax that inserts the details to the database // Let's assume that the the start of the renewal_date is December 15, 2016 </code></pre> <p>How will the automatic email execution be achieved? Without putting too much stress in the backend? Because I'm guessing that if there are 300 invoices then the server might be stressed out</p>
0
2016-08-18T03:34:10Z
39,010,982
<p>"Write it yourself." No, really.</p> <p>Keep a database table of invoices to be sent. Every invoice has a status (values such as <code>pending</code>, <code>sent</code>, <code>paid</code>, ...) and an invoice date (which may be in the future). Use <code>cron</code> or similar to periodically run (e.g. 1/hour, 1/day) a program that queries the table for pending invoices for which the invoice date/time has arrived/passed, yet no invoice has yet been sent. This invoicing process sends the invoice, updates the status, and finishes. This invoicer utility will not be integral to your Flask web app, but live beside it as a support program.</p> <p>Why? It's simple and direct approach. It keeps the invoicing code in Python, close to your chosen app language and database. It doesn't require much excursion into external systems or middleware. It's straightforward to debug and monitor, using the same database, queries, and skills as writing the app itself. Simple, direct, reliable, done. What's not to love?</p> <p>Now, I fully understand that a "write it yourself" recommendation runs contrary to typical "buy not build" doctrine. But I have tried all the main alternatives such as <a href="https://en.wikipedia.org/wiki/Cron" rel="nofollow">cron</a> and <a href="http://www.celeryproject.org/" rel="nofollow">Celery</a>; my experience with a revenue-producing web app says they're not the way to go for a few hundred long-term invoicing events. </p> <p><strong>The TL;DR--Why Not Cron and Celery?</strong></p> <p><code>cron</code> and its latter-day equivalents (e.g. <code>launchd</code> or <a href="https://elements.heroku.com/addons/scheduler" rel="nofollow">Heroku Scheduler</a>) run recurring events. Every 10 minutes, every hour, once a day, every other Tuesday at 3:10am UTC. They generally don't solve the "run this once, at time and date X in the future" problem, but they are great for periodic work.</p> <p>Now that last statement isn't strictly true. It describes <code>cron</code> and some of its replacements. But even traditional Unix provides <a href="https://en.wikipedia.org/wiki/At_(Unix)" rel="nofollow">at</a> as side-car to <code>cron</code>, and some <code>cron</code> follow-ons (e.g. <code>launchd</code>, <code>systemd</code>) bundle recurring and future event scheduling together (along with other kitchen appliances and the proverbial sink). Evens so, there are some issues:</p> <ol> <li>You're relying on external scheduling systems. That means another interface to learn, monitor, and debug if something goes wrong. There's significant impedance mismatch between those system-level schedulers and your Python app. Even if you farm out "run event at time X," you still need to write the Python code to send the invoice and properly move it along your business workflow.</li> <li>Those systems, beautiful for a handful of events, generally lack interfaces that make reviewing, modifying, monitoring, or debugging hundreds of outstanding events straightforward. Debugging production app errors amidst an ocean of scheduled events is <em>harrowing</em>. You're talking about committing 300+ pending events to this external system. You must also consider how you'll monitor and debug that use.</li> <li>Those schedulers are designed for "regular" not "high value" or "highly available" operations. As just one gotcha, what if an event is scheduled, but then you take downtime (planned or unplanned)? If the event time passes before the system is back up, what then? Most of the <code>cron</code>-like schedulers lack provisions for robustly handling "missed" events or "making them up at the earliest opportunity." That can be, in technical terms, "a bummer, man." Say the event triggered money collection--or in your case, invoice issuance. You have hundreds of invoices, and issuing those invoices is presumably business-critical. The capability gaps between system-level schedulers and your operational needs can be genuinely painful, especially as you scale.</li> </ol> <p>Okay, what about driving those events into an external event scheduler like Celery? This is a <em>much</em> better idea. Celery is designed to run large number of app events. It supports various backend engines (e.g. RabbitMQ) proven in practice to handle thousands upon untold thousands of events, and it has user interface options to help deal with event multitudes. So far so good! But:</p> <ol> <li>You will find yourself dealing with the complexities of installing, configuring, and operating external middleware (e.g. RabbitMQ). The effort yields very high achievable scale, but the startup and operational costs are real. This is true even if you farm much of it to a cloud service like Heroku.</li> <li>More important, while great as a job dispatcher for near-term events, Celery is not ideal as a long-wait-time scheduler. In production I've seen serious issues with "long throw" events (those posted a month, or in your case three months, in the future). While the problems aren't identical, just like <code>cron</code> etc., Celery long-throw events intersect ungracefully with normal app update and restart cycles. This is environment-dependent, but happens on popular cloud services like Heroku. </li> </ol> <p>The Celery issues are not entirely unsolvable or fatal, but long-delay events don't enjoy the same "Wow! Celery made everything work so much better!" magic that you get for swarms of near-term events. And you must become a bit of a Celery, RabbitMQ, etc. engineer and caretaker. That's a high price and a lot of work for just scheduling a few hundred invoices.</p> <p>In summary: While future invoice scheduling may seem like something to farm out, in practice it will be easier, faster, and more immediately robust to keep that function in your primary app code (not directly in your Flask web app, but as an associated utility), and just farm out the "remind me to run this N times a day" low-level tickler to a system-level job scheduler.</p>
2
2016-08-18T06:07:23Z
[ "python", "flask" ]
Trying to read a file and loop through at the same time
39,009,633
<p>I'm pretty new to this so please move this topic if it's in the wrong place or something else. </p> <p><strong>Problem:</strong> <em>(Quick note: This is all in Python)</em> I am trying to go through these 100 or so files, each with the same number of columns, and take certain columns of the input (the same ones for each file) and write them in a new file. However, these 100 files don't necessarily all have the same number of rows. In the code below, filec is in a loop and continues altering throughout the 100 files. I am trying to get these certain columns that I want by looking at the number of rows in each txt file and looping that many times then taking the numbers I want.</p> <pre><code> filec = open(string,'r').read().split(',') x = len(filec.readlines()) </code></pre> <p>I realize the issue is that filec has become a list after using the split function and was originally a string when I used .read(). How would one go about finding the number of lines, so I can loop through the number of rows and get the positions in each row that I want?</p> <p>Thank you!</p>
0
2016-08-18T03:41:22Z
39,009,721
<p>You could do it like this:</p> <pre><code>filec = open (filename, 'r') lines = filec.readlines () for line in lines: words = line.split(',') # Your code here </code></pre> <p>Excuse me if there are any errors, I'm doing this on mobile.</p>
0
2016-08-18T03:51:51Z
[ "python" ]
Trying to read a file and loop through at the same time
39,009,633
<p>I'm pretty new to this so please move this topic if it's in the wrong place or something else. </p> <p><strong>Problem:</strong> <em>(Quick note: This is all in Python)</em> I am trying to go through these 100 or so files, each with the same number of columns, and take certain columns of the input (the same ones for each file) and write them in a new file. However, these 100 files don't necessarily all have the same number of rows. In the code below, filec is in a loop and continues altering throughout the 100 files. I am trying to get these certain columns that I want by looking at the number of rows in each txt file and looping that many times then taking the numbers I want.</p> <pre><code> filec = open(string,'r').read().split(',') x = len(filec.readlines()) </code></pre> <p>I realize the issue is that filec has become a list after using the split function and was originally a string when I used .read(). How would one go about finding the number of lines, so I can loop through the number of rows and get the positions in each row that I want?</p> <p>Thank you!</p>
0
2016-08-18T03:41:22Z
39,009,818
<p>As you are just looking for the count of rows, then how about this -</p> <pre><code>t = tuple(open(filepath\filename.txt, 'r')) print len(t) </code></pre>
0
2016-08-18T04:05:14Z
[ "python" ]
Trying to read a file and loop through at the same time
39,009,633
<p>I'm pretty new to this so please move this topic if it's in the wrong place or something else. </p> <p><strong>Problem:</strong> <em>(Quick note: This is all in Python)</em> I am trying to go through these 100 or so files, each with the same number of columns, and take certain columns of the input (the same ones for each file) and write them in a new file. However, these 100 files don't necessarily all have the same number of rows. In the code below, filec is in a loop and continues altering throughout the 100 files. I am trying to get these certain columns that I want by looking at the number of rows in each txt file and looping that many times then taking the numbers I want.</p> <pre><code> filec = open(string,'r').read().split(',') x = len(filec.readlines()) </code></pre> <p>I realize the issue is that filec has become a list after using the split function and was originally a string when I used .read(). How would one go about finding the number of lines, so I can loop through the number of rows and get the positions in each row that I want?</p> <p>Thank you!</p>
0
2016-08-18T03:41:22Z
39,009,824
<p>I tried to keep the code clear, it is very possible to do with fewer lines. take in a list of file names, give out a dictionary, mapping the filename to the column you wanted (as a list).</p> <pre><code>def read_col_from_files(file_names, column_number): ret = {} for file_name in file_names: with open(file_name) as fp: column_for_file = [] for line in fp: columns = line.split('\t') column_for_file.append(columns[column_number]) ret[file_name] = column_for_file return ret </code></pre> <p>I have assumed you have tab delimited columns. Call it like this:</p> <pre><code>data = read_col_from_files(["file_1.txt", "/tmp/file_t.txt"], 5) </code></pre> <p>Here is a sensible shortening of the code using a list comprehension</p> <pre><code>def read_col_from_files(file_names, column_number): ret = {} for file_name in file_names: with open(file_name) as fp: ret[file_name] = [line.split('\t')[column_number] for line in fp] return ret </code></pre> <p>And here is how to do it on the command line:</p> <pre><code>cat FILENAMES | awk '{print $3}' </code></pre>
0
2016-08-18T04:06:05Z
[ "python" ]
How to combine flask and requests in python?
39,009,752
<p>On the page <code>internallogin</code>, if the user authenticates, I'd like to make a post request. To that effect, I have the following code.</p> <pre><code>@app.route('/internallogin', methods=['POST', "GET"]) def showInternallogin(): uname = request.form.get("name") passw = request.form.get("pass") if is_valid_login(uname, passw): print("legal_login") req = requests.Request(method="POST", url='http://localhost:5000/internal', data={"name": uname, "passw": passw}) return req else: return redirect('/login') </code></pre> <p>What happtens is immidiately after printing "legal_login" is that I get the error that <code>TypeError: 'Request' object is not callable</code>. How can I make a post request using flask?</p>
-2
2016-08-18T03:57:22Z
39,009,875
<p>You can issue a post using <a href="http://docs.python-requests.org/en/master/user/quickstart/" rel="nofollow"><code>requests</code></a> like so:</p> <pre><code>response = requests.post('http://localhost:5000/internal', data={...}) </code></pre> <p>However, it's generally unnecessary to call a server from itself. You should consider abstracting out the logic within your <code>/internal</code> route and just calling it directly in this route.</p>
3
2016-08-18T04:12:26Z
[ "python", "flask", "python-requests" ]
How to combine flask and requests in python?
39,009,752
<p>On the page <code>internallogin</code>, if the user authenticates, I'd like to make a post request. To that effect, I have the following code.</p> <pre><code>@app.route('/internallogin', methods=['POST', "GET"]) def showInternallogin(): uname = request.form.get("name") passw = request.form.get("pass") if is_valid_login(uname, passw): print("legal_login") req = requests.Request(method="POST", url='http://localhost:5000/internal', data={"name": uname, "passw": passw}) return req else: return redirect('/login') </code></pre> <p>What happtens is immidiately after printing "legal_login" is that I get the error that <code>TypeError: 'Request' object is not callable</code>. How can I make a post request using flask?</p>
-2
2016-08-18T03:57:22Z
39,011,851
<p>The following is right from @Karin answer</p> <pre><code>response = requests.post('http://localhost:5000/internal', data={...}) </code></pre> <p>Here might be the reason why you are receiving that error.</p> <p><a href="http://stackoverflow.com/questions/19568950/return-a-requests-response-object-from-flask">Return a requests.Response object from Flask</a></p> <blockquote> <p>If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status, headers) where at least one item has to be in the tuple. The status value will override the status code and headers can be a list or dictionary of additional header values.</p> </blockquote> <p>This should likely solve it.</p> <pre><code>return (req.text, req.status_code, req.headers.items()) </code></pre>
0
2016-08-18T07:03:30Z
[ "python", "flask", "python-requests" ]