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
TypeError when converting Pandas to Spark
39,862,211
<p>So I have looked up this question on here but previous solutions have not worked for me. I have a DataFrame in this format</p> <pre><code>mdf.head() dbn boro bus 0 17K548 Brooklyn B41, B43, B44-SBS, B45, B48, B49, B69 1 09X543 Bronx Bx13, Bx15, Bx17, Bx21, Bx35, Bx4, Bx41, Bx4A,... 4 28Q680 Queens Q25, Q46, Q65 6 14K474 Brooklyn B24, B43, B48, B60, Q54, Q59 </code></pre> <p>There are a couple more columns but I have excluded them (subway lines and test scores). When I try to convert this DataFrame into a Spark DataFrame I am given an error which is this.</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-30-1721be5c2987&gt; in &lt;module&gt;() ----&gt; 1 sparkdf = sqlc.createDataFrame(mdf) /usr/local/Cellar/apache-spark/1.6.2/libexec/python/pyspark/sql/context.pyc in createDataFrame(self, data, schema, samplingRatio) 423 rdd, schema = self._createFromRDD(data, schema, samplingRatio) 424 else: --&gt; 425 rdd, schema = self._createFromLocal(data, schema) 426 jrdd = self._jvm.SerDeUtil.toJavaArray(rdd._to_java_object_rdd()) 427 jdf = self._ssql_ctx.applySchemaToPythonRDD(jrdd.rdd(), schema.json()) /usr/local/Cellar/apache-spark/1.6.2/libexec/python/pyspark/sql/context.pyc in _createFromLocal(self, data, schema) 339 340 if schema is None or isinstance(schema, (list, tuple)): --&gt; 341 struct = self._inferSchemaFromList(data) 342 if isinstance(schema, (list, tuple)): 343 for i, name in enumerate(schema): /usr/local/Cellar/apache-spark/1.6.2/libexec/python/pyspark/sql/context.pyc in _inferSchemaFromList(self, data) 239 warnings.warn("inferring schema from dict is deprecated," 240 "please use pyspark.sql.Row instead") --&gt; 241 schema = reduce(_merge_type, map(_infer_schema, data)) 242 if _has_nulltype(schema): 243 raise ValueError("Some of types cannot be determined after inferring") /usr/local/Cellar/apache-spark/1.6.2/libexec/python/pyspark/sql/types.pyc in _merge_type(a, b) 860 nfs = dict((f.name, f.dataType) for f in b.fields) 861 fields = [StructField(f.name, _merge_type(f.dataType, nfs.get(f.name, NullType()))) --&gt; 862 for f in a.fields] 863 names = set([f.name for f in fields]) 864 for n in nfs: /usr/local/Cellar/apache-spark/1.6.2/libexec/python/pyspark/sql/types.pyc in _merge_type(a, b) 854 elif type(a) is not type(b): 855 # TODO: type cast (such as int -&gt; long) --&gt; 856 raise TypeError("Can not merge type %s and %s" % (type(a), type(b))) 857 858 # same type TypeError: Can not merge type &lt;class 'pyspark.sql.types.StringType'&gt; and &lt;class 'pyspark.sql.types.DoubleType'&gt; </code></pre> <p>From what I have read this might be a problem with the headers being treated as data. It is my understanding you can't remove the headers from a DataFrame so how would I proceed with solving this error and converting this DataFrame into a Spark one?</p> <p>Edit: Here is the code for how I created the Pandas DF and worked my way around the problem.</p> <pre><code>sqlc = SQLContext(sc) df = pd.DataFrame(pd.read_csv('hsdir.csv', encoding = 'utf_8_sig')) df = df[['dbn', 'boro', 'bus', 'subway', 'total_students']] df1 = pd.DataFrame(pd.read_csv('sat_r.csv', encoding = 'utf_8_sig')) df1 = df1.rename(columns = {'Num of SAT Test Takers': 'num_test_takers', 'SAT Critical Reading Avg. Score': 'read_avg', 'SAT Math Avg. Score' : 'math_avg', 'SAT Writing Avg. Score' : 'write_avg'}) mdf = pd.merge(df, df1, left_on = 'dbn', right_on = 'DBN', how = 'left') mdf = mdf[pd.notnull(mdf['DBN'])] mdf.to_csv('merged.csv', encoding = 'utf-8') ndf = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").option("inferSchema", "true").load("merged.csv") </code></pre> <p>The last line of this code, loading it from my local machine ended up allowing me to convert the CSV properly to a Data Frame however my question still remains. Why did it not work in the first place?</p>
0
2016-10-04T21:40:38Z
39,862,349
<p>You could use reflection to infer the schema from an RDD of <code>Row</code> objects, e.g., </p> <pre><code>from pyspark.sql import Row mdfRows = mdf.map(lambda p: Row(dbn=p[0], boro=p[1], bus=p[2])) dfOut = sqlContext.createDataFrame(mdfRows) </code></pre> <p>Does that achieve the desired result? </p>
0
2016-10-04T21:51:20Z
[ "python", "pandas", "apache-spark", "pyspark" ]
NMaximize in Mathematica equivalent in Python
39,862,283
<p>I am trying to find a equivalent of "NMaximize" optimization command in Mathematica in Python. I tried googling but did not help much. </p>
0
2016-10-04T21:46:25Z
39,863,045
<p>The <a href="https://reference.wolfram.com/language/ref/NMaximize.html" rel="nofollow">mathematica docs</a> describe the methods usable within <code>NMaximize</code> as: <code>Possible settings for the Method option include "NelderMead", "DifferentialEvolution", "SimulatedAnnealing", and "RandomSearch".</code>.</p> <p>Have a look at <a href="http://docs.scipy.org/doc/scipy/reference/optimize.html" rel="nofollow">scipy's optimize</a> which also supports:</p> <ul> <li>NelderMead</li> <li>DifferentialEvolution</li> <li>and much more...</li> </ul> <p>It is very important to find the correct tool for <em>your optimization problem</em>! This is at least dependent on:</p> <ul> <li>Discrete variables?</li> <li>Smooth optimization function?</li> <li>Linear, Conic, Non-convex optimization problem?</li> <li>and again: much more...</li> </ul> <p>Compared to Mathematica's approach, you will have to choose the method a-priori within scipy (at some extent).</p>
2
2016-10-04T23:01:46Z
[ "python", "optimization", "wolfram-mathematica", "mathematical-optimization" ]
Tensorflow: Why Doesn't Out of Graph Cost Calculation Work
39,862,366
<p>I have a standard experiment loop that looks like this:</p> <pre class="lang-py prettyprint-override"><code>cross_entropy_target = tf.reduce_mean(tf.reduce_mean(tf.square(target_pred - target))) cost = cross_entropy_target opt_target = tf.train.AdamOptimizer(learning_rate=0.00001).minimize(cost) for epoch in range(num_epochs): for mini_batch in range(num_samples / batch_size): mb_train_x, mb_train_target = get_mini_batch_stuffs() sess.run(opt_target, feed_dict={x: mb_train_x, target: mb_train_target}) </code></pre> <p>This runs and converges to a good prediction loss. Now, same code with a slight modification: </p> <pre class="lang-py prettyprint-override"><code>cross_entropy_target = tf.reduce_mean(tf.reduce_mean(tf.square(target_pred - target))) cross_entropy_target_variable = tf.Variable(0.0) cost = cross_entropy_target_variable opt_target = tf.train.AdamOptimizer(learning_rate=0.00001).minimize(cost) for epoch in range(num_epochs): for mini_batch in range(num_samples / batch_size): mb_train_x, mb_train_target = get_mini_batch_stuffs() new_target_cost = sess.run(cross_entropy_target, feed_dict={x: mb_train_x, time: mb_train_time, target: mb_train_target}) sess.run(tf.assign(cross_entropy_target_variable, new_target_cost)) sess.run(opt_target, feed_dict={x: mb_train_x, target: mb_train_target}) </code></pre> <p>Now, instead of the <code>cross_entropy_target</code> being calculated as part of the <code>opt_target</code> graph, I am pre-calculating it, assigning it to a tensorflow variable, and expecting it to make use of that value. This doesn't work at all. The network's outputs never change. </p> <p>I would expect these two code snippets to have equivalent outcomes. In both cases a feed forward is used to populate the values of <code>target</code> and <code>target_pred</code>, which is then reduced to the scalar value <code>cross_entropy_target</code>. This scalar value is used to inform the magnitude and direction of the gradient updates on the optimizer's <code>.minimize()</code>.</p> <p>In this toy example there is no advantage to my calculating the cross_entropy_target "out of graph" and then assigning it to an in-graph <code>tf.Variable</code> for use in the <code>opt_target</code> run. However, I have a real use case where my cost function is very complex and I have not been able to define it in terms of Tensorflow's existing tensor transforms. Either way, I'd like to understand why using a <code>tf.Variable</code> for an optimizer's cost is incorrect use.</p> <p>An interesting oddity that may be a byproduct of the solution to this: If I set <code>cross_entropy_target_variable = tf.Variable(0.0, trainable=False)</code>, running the <code>opt_target</code> will crash. It requires that the cost value is modifiable. Indeed, printing out its value before and after running the <code>opt_target</code> produces different values:</p> <p><code>cross_entropy_target before = 0.345796853304 cross_entropy_target after = 0.344796866179 </code></p> <p>Why does running <code>minimize()</code> modify the value of the cost variable?</p>
0
2016-10-04T21:53:01Z
39,878,048
<p>In your <code>tf.train.AdamOptimizer(</code> line, it looks at <code>cost</code>, which is <code>cross_entropy_target</code>, which is a <code>tf.Variable</code> op, and creates an optimizer which does nothing, since <code>cross_entropy_target</code> doesn't depend on any variables. Modifying <code>cross_entropy</code> target later has no effect because the optimizer has already been created.</p>
1
2016-10-05T15:25:24Z
[ "python", "tensorflow" ]
How to maintain or recover Dataframe indexing after running Pairwise Distance function?
39,862,383
<p>I'm using sklearn's pairwise distance function, which saved my life when computing a huge matrix, but the problem I'm having is that I lose my indices.</p> <p>Specifically, I initially have a huge dataframe of 17000 x 300, which I break down into 4 different dataframes based on some class condition. The 4 separate dataframes keep the original indices, but after I run the pairwise distance function on one of those dataframes, it gives me back a 2d array with correct values but the indices have been reset from 0 up.</p> <p><strong>How do I keep or recover the original indices</strong>?</p> <p><code>distance1 = pair.pairwise_distances(df1, metric='euclidean')</code></p>
1
2016-10-04T21:54:55Z
39,862,542
<p>You can create a DataFrame with matching indices using the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">DataFrame constructor</a> taking the <code>index</code> parameter:</p> <pre><code>pd.DataFrame(distance1, index=df1.index) </code></pre> <p>Furthermore, if you would like to concatenate it horizontally to your existing DataFrame, you can use</p> <pre><code>pd.concat((df1, pd.DataFrame(distance1, index=df1.index)), axis=1) </code></pre>
3
2016-10-04T22:10:25Z
[ "python", "pandas", "indexing", "dataframe", "distance" ]
Failure during project creation using 'djangocms' command
39,862,388
<ul> <li>Django CMS 3.4.1</li> <li>Django 1.10.2</li> <li>pip modules: <a href="http://pastebin.com/vJWvZVfA" rel="nofollow">http://pastebin.com/vJWvZVfA</a></li> <li>pip 8.1.2</li> <li>Python 2.7.12</li> <li>OS: Amazon Linux AMI release 2016.03</li> </ul> <p>I'm new to Django CMS, Django, and Python. My previous CMS experience has been with WordPress and I'm try to try out Django CMS as an alternative to WordPress, but am getting an error that I can not seem to figure out. I have updated the pip modules and installed others as suggested in threads on StackOverflow, but to no avail. </p> <p>I followed the <a href="http://docs.django-cms.org/en/release-3.3.x/introduction/install.htm" rel="nofollow">tutorial the instructions</a>, with the exception of the <code>djangocms</code> command, which is incorrect in the tutorial. (It's missing the -w flag.)</p> <p>EDIT: As requested, here is the output with the <code>--verbose</code> flag added:</p> <pre><code>(env)[ec2-user@(redacted) tutorial-project]$ djangocms -d postgres://(redacted) -e no --permissions yes -l "en-CA, en-US, en, fr-CA, fr-FR" -p . --starting-page yes --verbose --utc mysite Creating the project Please wait while I install dependencies Package install command: install django-cms&lt;3.5 djangocms-admin-style&gt;=1.2,&lt;1.3 django-treebeard&gt;=4.0,&lt;5.0 psycopg2 djangocms-text-ckeditor&gt;=3.2.1 djangocms-link&gt;=1.8 djangocms-style&gt;=1.7 djangocms-googlemap&gt;=0.5 djangocms-snippet&gt;=1.9 djangocms-video&gt;=2.0 djangocms-column&gt;=1.6 easy_thumbnails django-filer&gt;=1.2 cmsplugin-filer&gt;=1.1 Django&lt;1.9 pytz django-classy-tags&gt;=0.7 html5lib&gt;=0.999999,&lt;0.99999999 Pillow&gt;=3.0 django-sekizai&gt;=0.9 django-select2&lt;5.0six Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-duWZSN/psycopg2/ The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/home/ec2-user/env/bin/djangocms", line 11, in &lt;module&gt; sys.exit(execute()) File "/home/ec2-user/env/local/lib/python2.7/site-packages/djangocms_installer/main.py", line 33, in execute verbose=config_data.verbose File "/home/ec2-user/env/local/lib/python2.7/site-packages/djangocms_installer/install/__init__.py", line 91, in requirements output = subprocess.check_output(['pip'] + args) File "/usr/lib64/python2.7/subprocess.py", line 574, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '[u'pip', u'install', u'django-cms&lt;3.5', u'djangocms-admin-style&gt;=1.2,&lt;1.3', u'django-treebeard&gt;=4.0,&lt;5.0', u'psycopg2', u'djangocms-text-ckeditor&gt;=3.2.1', u'djangocms-link&gt;=1.8', u'djangocms-style&gt;=1.7', u'djangocms-googlemap&gt;=0.5', u'djangocms-snippet&gt;=1.9', u'djangocms-video&gt;=2.0', u'djangocms-column&gt;=1.6', u'easy_thumbnails', u'django-filer&gt;=1.2', u'cmsplugin-filer&gt;=1.1', u'Django&lt;1.9', u'pytz', u'django-classy-tags&gt;=0.7', u'html5lib&gt;=0.999999,&lt;0.99999999', u'Pillow&gt;=3.0', u'django-sekizai&gt;=0.9', u'django-select2&lt;5.0six']' returned non-zero exit status 1 </code></pre> <p>EDIT 2: (moved to answer)</p> <p>EDIT 3:</p> <p>After solving the first part, another error remains. I'll include it in this post since it still falls under the topic of the title:</p> <pre><code>Creating the project Project creation command: /home/ec2-user/env/bin/python2.7 /home/ec2-user/env/bin/django-admin.py startproject mysite /home/ec2-user/tutorial-project Database setup commands: /home/ec2-user/env/bin/python2.7 -W ignore manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 191, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 118, in connect conn_params = self.get_connection_params() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 158, in get_connection_params "settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/home/ec2-user/env/bin/djangocms", line 11, in &lt;module&gt; sys.exit(execute()) File "/home/ec2-user/env/local/lib/python2.7/site-packages/djangocms_installer/main.py", line 41, in execute django.setup_database(config_data) File "/home/ec2-user/env/local/lib/python2.7/site-packages/djangocms_installer/django/__init__.py", line 388, in setup_database output = subprocess.check_output(command, env=env) File "/usr/lib64/python2.7/subprocess.py", line 574, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['/home/ec2-user/env/bin/python2.7', u'-W', u'ignore', u'manage.py', u'migrate']' returned non-zero exit status 1 </code></pre> <p>I'm going to guess that the problem lies in the message:</p> <p><code>settings.DATABASES is improperly configured. Please supply the NAME value. The installation has failed.</code></p> <p>I'm using PostgreSQL, so I assume that the error is caused by the schema not being provided in the command argument. There was nothing in the guide that I saw indicating how to provide it, so I'll have to search some more.</p>
-1
2016-10-04T21:55:08Z
39,862,494
<p>The error message tells me absolutely nothing. It only tells me that Django tried to use pip to install something and for whatever reason it failed. In order to figure out what went wrong, try enabling verbose mode (python -v). If that gives the same output, or that isn't an option because you're using a program that calls Python (which it sounds like you are), let me know and prepare to go into the source code. Trust me, I have taken many a dive into source code for Python utilities, and as long as you don't do anything stupid (like delete a file) it's pretty hard to mess anything up. Even if you do you can always reinstall Django (or make a backup first). Don't worry about messing up your computer. You'd have to work hard to make Django do that!</p>
0
2016-10-04T22:06:25Z
[ "python", "django", "pip", "django-cms" ]
Failure during project creation using 'djangocms' command
39,862,388
<ul> <li>Django CMS 3.4.1</li> <li>Django 1.10.2</li> <li>pip modules: <a href="http://pastebin.com/vJWvZVfA" rel="nofollow">http://pastebin.com/vJWvZVfA</a></li> <li>pip 8.1.2</li> <li>Python 2.7.12</li> <li>OS: Amazon Linux AMI release 2016.03</li> </ul> <p>I'm new to Django CMS, Django, and Python. My previous CMS experience has been with WordPress and I'm try to try out Django CMS as an alternative to WordPress, but am getting an error that I can not seem to figure out. I have updated the pip modules and installed others as suggested in threads on StackOverflow, but to no avail. </p> <p>I followed the <a href="http://docs.django-cms.org/en/release-3.3.x/introduction/install.htm" rel="nofollow">tutorial the instructions</a>, with the exception of the <code>djangocms</code> command, which is incorrect in the tutorial. (It's missing the -w flag.)</p> <p>EDIT: As requested, here is the output with the <code>--verbose</code> flag added:</p> <pre><code>(env)[ec2-user@(redacted) tutorial-project]$ djangocms -d postgres://(redacted) -e no --permissions yes -l "en-CA, en-US, en, fr-CA, fr-FR" -p . --starting-page yes --verbose --utc mysite Creating the project Please wait while I install dependencies Package install command: install django-cms&lt;3.5 djangocms-admin-style&gt;=1.2,&lt;1.3 django-treebeard&gt;=4.0,&lt;5.0 psycopg2 djangocms-text-ckeditor&gt;=3.2.1 djangocms-link&gt;=1.8 djangocms-style&gt;=1.7 djangocms-googlemap&gt;=0.5 djangocms-snippet&gt;=1.9 djangocms-video&gt;=2.0 djangocms-column&gt;=1.6 easy_thumbnails django-filer&gt;=1.2 cmsplugin-filer&gt;=1.1 Django&lt;1.9 pytz django-classy-tags&gt;=0.7 html5lib&gt;=0.999999,&lt;0.99999999 Pillow&gt;=3.0 django-sekizai&gt;=0.9 django-select2&lt;5.0six Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-duWZSN/psycopg2/ The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/home/ec2-user/env/bin/djangocms", line 11, in &lt;module&gt; sys.exit(execute()) File "/home/ec2-user/env/local/lib/python2.7/site-packages/djangocms_installer/main.py", line 33, in execute verbose=config_data.verbose File "/home/ec2-user/env/local/lib/python2.7/site-packages/djangocms_installer/install/__init__.py", line 91, in requirements output = subprocess.check_output(['pip'] + args) File "/usr/lib64/python2.7/subprocess.py", line 574, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '[u'pip', u'install', u'django-cms&lt;3.5', u'djangocms-admin-style&gt;=1.2,&lt;1.3', u'django-treebeard&gt;=4.0,&lt;5.0', u'psycopg2', u'djangocms-text-ckeditor&gt;=3.2.1', u'djangocms-link&gt;=1.8', u'djangocms-style&gt;=1.7', u'djangocms-googlemap&gt;=0.5', u'djangocms-snippet&gt;=1.9', u'djangocms-video&gt;=2.0', u'djangocms-column&gt;=1.6', u'easy_thumbnails', u'django-filer&gt;=1.2', u'cmsplugin-filer&gt;=1.1', u'Django&lt;1.9', u'pytz', u'django-classy-tags&gt;=0.7', u'html5lib&gt;=0.999999,&lt;0.99999999', u'Pillow&gt;=3.0', u'django-sekizai&gt;=0.9', u'django-select2&lt;5.0six']' returned non-zero exit status 1 </code></pre> <p>EDIT 2: (moved to answer)</p> <p>EDIT 3:</p> <p>After solving the first part, another error remains. I'll include it in this post since it still falls under the topic of the title:</p> <pre><code>Creating the project Project creation command: /home/ec2-user/env/bin/python2.7 /home/ec2-user/env/bin/django-admin.py startproject mysite /home/ec2-user/tutorial-project Database setup commands: /home/ec2-user/env/bin/python2.7 -W ignore manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 191, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 135, in _cursor self.ensure_connection() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 130, in ensure_connection self.connect() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 118, in connect conn_params = self.get_connection_params() File "/home/ec2-user/env/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 158, in get_connection_params "settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. The installation has failed. ***************************************************************** Check documentation at https://djangocms-installer.readthedocs.io ***************************************************************** Traceback (most recent call last): File "/home/ec2-user/env/bin/djangocms", line 11, in &lt;module&gt; sys.exit(execute()) File "/home/ec2-user/env/local/lib/python2.7/site-packages/djangocms_installer/main.py", line 41, in execute django.setup_database(config_data) File "/home/ec2-user/env/local/lib/python2.7/site-packages/djangocms_installer/django/__init__.py", line 388, in setup_database output = subprocess.check_output(command, env=env) File "/usr/lib64/python2.7/subprocess.py", line 574, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['/home/ec2-user/env/bin/python2.7', u'-W', u'ignore', u'manage.py', u'migrate']' returned non-zero exit status 1 </code></pre> <p>I'm going to guess that the problem lies in the message:</p> <p><code>settings.DATABASES is improperly configured. Please supply the NAME value. The installation has failed.</code></p> <p>I'm using PostgreSQL, so I assume that the error is caused by the schema not being provided in the command argument. There was nothing in the guide that I saw indicating how to provide it, so I'll have to search some more.</p>
-1
2016-10-04T21:55:08Z
39,864,076
<h1>Original error</h1> <p>The non-verbose error message indicates the error in a cryptic way, and using --verbose provides a more understandable message.</p> <p>I was missing one required module (psycopg2) and four others were versions which were too new (easy_thumbnails, Django, html5lib, django-select2).</p> <p>I uninstalled the four modules and then reinstalled them using the version requirement in the command. e.g. pip install 'Django&lt;1.10'.</p> <p>psycopg2 required extra steps, as I got an error message when trying to install it indicating that it could not find pg_config. Another SO answer advised that I just had to install postgresql-devel. After I did that, (sudo yum install postgresql-devel), I also uninstalled postgresql8-libs, as postgresql-devel came with a newer version. I didn't do it before since yum indicated a PHP dependency, and I wasn't sure if it would cause problems if I did.</p> <h1>Second error</h1> <p>Pretty simple. I was missing the /NAME component of the database URL (postgres://USER:PASSWORD@HOST:PORT/NAME).</p>
0
2016-10-05T01:24:20Z
[ "python", "django", "pip", "django-cms" ]
How to disable vertical / horizontal mouse movement in pygame?
39,862,440
<p>I want to prevent an object from moving vertically on the surface when moving the mouse around while horizontal movements will still be allowed. </p> <p>How do I do that?</p> <p>I have managed to let the object move around freely using:</p> <pre><code> if event.type == pygame.MOUSEMOTION: x, y = event.pos </code></pre> <p>But don't know how disable y from responding and allow only x to move.</p> <p>Any advice will be appreciated.</p> <p>BTW - I have read similar questions but nothing was related specifically to this issue.</p>
0
2016-10-04T22:00:37Z
39,862,497
<p>I don't remember much of Pygame, so I might be missing something, but it looks kinda obvious:</p> <pre><code>if event.type == pygame.MOUSEMOTION: x = event.pos[0] </code></pre>
0
2016-10-04T22:06:34Z
[ "python", "python-3.x", "pygame" ]
Directly write to encrypted file in Python
39,862,516
<p>In python, using the gnupg package, is it possible to take a value in memory, then write it an encrypted file rather than writing to file THEN encrypting? </p> <p>I was hoping something like this would work:</p> <pre><code>import gnupg gpg = gnupg.GPG(gnupghome='keydirectory') l = [['a', '1'], ['b', '2'], ['c', '3']] gpg.encrypt_file(l, recipients=['test@test.com'], output='encryptedfile.asc') </code></pre> <p>I was hoping there was a write concept like this to loop over line-by-line, but I can't find one. </p> <pre><code>with open('regularfile.txt', 'w') as file: for i in l: file.write(i) </code></pre> <p>Ideally, I could connect to a database and output a file by writing directly. </p>
1
2016-10-04T22:08:28Z
39,862,581
<p>Just use the <code>gpg.encrypt()</code> function instead of <code>encrypt_file()</code> and then write to a file.</p>
0
2016-10-04T22:13:24Z
[ "python", "gnupg" ]
Directly write to encrypted file in Python
39,862,516
<p>In python, using the gnupg package, is it possible to take a value in memory, then write it an encrypted file rather than writing to file THEN encrypting? </p> <p>I was hoping something like this would work:</p> <pre><code>import gnupg gpg = gnupg.GPG(gnupghome='keydirectory') l = [['a', '1'], ['b', '2'], ['c', '3']] gpg.encrypt_file(l, recipients=['test@test.com'], output='encryptedfile.asc') </code></pre> <p>I was hoping there was a write concept like this to loop over line-by-line, but I can't find one. </p> <pre><code>with open('regularfile.txt', 'w') as file: for i in l: file.write(i) </code></pre> <p>Ideally, I could connect to a database and output a file by writing directly. </p>
1
2016-10-04T22:08:28Z
40,126,111
<p>The <a href="https://python-gnupg.readthedocs.io/en/latest/gnupg.html#gnupg.GPG.encrypt" rel="nofollow">documentation for the <code>GPG.encrypt</code> method</a> shows that is what you want.</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; import gnupg &gt;&gt;&gt; gpg = gnupg.GPG(homedir="doctests") &gt;&gt;&gt; key_settings = gpg.gen_key_input( ... key_type='RSA', ... key_length=1024, ... key_usage='ESCA', ... passphrase='foo') &gt;&gt;&gt; key = gpg.gen_key(key_settings) &gt;&gt;&gt; message = "The crow flies at midnight." &gt;&gt;&gt; encrypted = str(gpg.encrypt(message, key.printprint)) &gt;&gt;&gt; assert encrypted != message &gt;&gt;&gt; assert not encrypted.isspace() &gt;&gt;&gt; decrypted = str(gpg.decrypt(encrypted)) &gt;&gt;&gt; assert not decrypted.isspace() &gt;&gt;&gt; decrypted 'The crow flies at midnight.' </code></pre>
0
2016-10-19T08:33:35Z
[ "python", "gnupg" ]
Determine default protocol version used by SSL package?
39,862,559
<p>In python, how can I determine which SSL or TLS protocol is used by SSL package, or requests, by default.</p> <p>As in, say TLSv1 vs SSLv3.</p>
1
2016-10-04T22:11:38Z
40,070,533
<p>The <a href="https://docs.python.org/2/library/ssl.html#socket-creation" rel="nofollow">SSL socket creation</a> section of the Python docs has the information on the SSL package:</p> <blockquote> <p>The parameter <code>ssl_version</code> specifies which version of the SSL protocol to use. Typically, the server chooses a particular protocol version, and the client must adapt to the server’s choice. Most of the versions are not interoperable with the other versions. If not specified, the default is <a href="https://docs.python.org/2/library/ssl.html#ssl.PROTOCOL_SSLv23" rel="nofollow">PROTOCOL_SSLv23</a> it provides the most compatibility with other versions.</p> <p>Here’s a table showing which versions in a client (down the side) can connect to which versions in a server (along the top):</p> <pre><code>| client / server | SSLv2 | SSLv3 | SSLv23 | TLSv1 | TLSv1.1 | TLSv1.2 | |-----------------|-------|-------|--------|-------|---------|---------| | SSLv2 | yes | no | yes | no | no | no | | SSLv3 | no | yes | yes | no | no | no | | SSLv23 | no | yes | yes | yes | yes | yes | | TLSv1 | no | no | yes | yes | no | no | | TLSv1.1 | no | no | yes | no | yes | no | | TLSv1.2 | no | no | yes | no | no | yes | </code></pre> <blockquote> <p><strong>Note:</strong></p> <p>Which connections succeed will vary depending on the version of OpenSSL. For example, before OpenSSL 1.0.0, an SSLv23 client would always attempt SSLv2 connections.</p> </blockquote> </blockquote>
0
2016-10-16T13:00:52Z
[ "python", "ssl", "python-requests", "pyopenssl" ]
How to redirect stdout to screen and at the same time save to a variable
39,862,573
<p>I am trying to redirect stdout to screen and at the same time save to a variable and running into error <code>AttributeError: __exit__</code> at line <code>with proc.stdout:</code>,can anyone tell me how to accomplish this?</p> <pre><code>............... proc = subprocess.Popen(cmd.split(' '), stderr=subprocess.PIPE) try: proc.wait(timeout=time_out) except TimeoutExpired as e: print e proc.kill() with proc.stdout: for line in proc.stdout: print line </code></pre> <p>Error:-</p> <pre><code> with proc.stdout: AttributeError: __exit__ </code></pre> <p><strong>UPDATE:-</strong></p> <pre><code>proc = subprocess.Popen(cmd.split(' '),stdout=subprocess.PIPE ) print "Executing %s"%cmd try: proc.wait(timeout=time_out)//HUNG here until timeout kicks-in except TimeoutExpired as e: print e proc.kill() with proc.stdout as stdout: for line in stdout: print line, </code></pre>
2
2016-10-04T22:12:47Z
39,862,644
<p>When creating your Popen object you have the stderr set. When you go to open the stdout subprocess can't open it because you have stderr set instead. You can fix this by either adding <code>stdout=subprocess.PIPE</code> to the Popen object args, or by doing <code>with proc.stderr</code> instead of <code>with proc.stderr</code>. Also, you want to change your with statement a little, like this.</p> <pre><code>with proc.stdout as stdout: for line in stdout: sys.stdout.write(line) </code></pre>
0
2016-10-04T22:20:45Z
[ "python" ]
How to redirect stdout to screen and at the same time save to a variable
39,862,573
<p>I am trying to redirect stdout to screen and at the same time save to a variable and running into error <code>AttributeError: __exit__</code> at line <code>with proc.stdout:</code>,can anyone tell me how to accomplish this?</p> <pre><code>............... proc = subprocess.Popen(cmd.split(' '), stderr=subprocess.PIPE) try: proc.wait(timeout=time_out) except TimeoutExpired as e: print e proc.kill() with proc.stdout: for line in proc.stdout: print line </code></pre> <p>Error:-</p> <pre><code> with proc.stdout: AttributeError: __exit__ </code></pre> <p><strong>UPDATE:-</strong></p> <pre><code>proc = subprocess.Popen(cmd.split(' '),stdout=subprocess.PIPE ) print "Executing %s"%cmd try: proc.wait(timeout=time_out)//HUNG here until timeout kicks-in except TimeoutExpired as e: print e proc.kill() with proc.stdout as stdout: for line in stdout: print line, </code></pre>
2
2016-10-04T22:12:47Z
39,863,094
<p>Once you make <code>stdout</code> a <code>PIPE</code> you can just create a loop that reads the pipe and writes it to as many places as you want. Dealing with <code>stderr</code> makes the situation a little trickier because you need a background reader for it also. So, create a thread and a utility that writes to multiple files and you are done.</p> <pre><code>import sys import threading from StringIO import StringIO import subprocess as subp import shlex def _file_copy_many(fp, *write_to): """Copy from one file object to one or more file objects""" while True: buf = fp.read(65536) if not buf: return for fp in write_to: fp.write(buf) # for test cmd = "ls -l" # will hold stdout and stderr outbuf = StringIO() errbuf = StringIO() # run the command and close its stdin proc = subp.Popen(shlex.split(cmd), stdin=subp.PIPE, stdout=subp.PIPE, stderr=subp.PIPE) proc.stdin.close() # background thread to write stderr to buffer stderr_thread = threading.Thread(target=_file_copy_many, args=(proc.stderr, errbuf)) stderr_thread.start() # write stdout to screen and buffer then wait for program completion _file_copy_many(proc.stdout, sys.stdout, outbuf) return_code = proc.wait() # wait for err thread stderr_thread.join() # use buffers print outbuf.tell(), errbuf.tell() outbuf.seek(0) errbuf.seek(0) </code></pre> <p>This is similar to what <code>subprocess.Popen.communicate</code> does but writes to more destinations.</p>
0
2016-10-04T23:07:07Z
[ "python" ]
pandas.concat of multiple data frames using only common columns
39,862,654
<p>I have multiple pandas data frame objects cost1, cost2 , cost3 ....</p> <ol> <li>They have different column names (and number of columns) but have some in common.</li> <li>Number of columns are fairly large in each dataframe, hence handpicking the common columns manually will be painful.</li> </ol> <p>How can I append rows from all of these data frames into one single data frame while retaining elements from only the common column names ?</p> <p>As of now I have</p> <p>frames=[cost1,cost2,cost3...]</p> <p>new_combined = pd.concat( frames,ignore_index=True)</p> <p>This obviously contains columns which are not common across all data frames.</p>
0
2016-10-04T22:21:22Z
39,862,735
<p>You can find the common columns with Python's <a href="https://docs.python.org/2/library/sets.html" rel="nofollow"><code>set.intersection</code></a>:</p> <pre><code>common_cols = list(set.intersection(*(set(df.columns) for df in frames))) </code></pre> <p>To concatenate using only the common columns, you can use</p> <pre><code>pd.concat([df[common_cols] for df in frames], ignore_index=True) </code></pre>
1
2016-10-04T22:28:34Z
[ "python", "pandas", "dataframe" ]
Differences in __dict__ between classes with and without an explicit base class
39,862,662
<p>Why does a class that (implicitly) derives from <code>object</code> have more items in its <code>__dict__</code> attribute than a class that has an explicit base class? (python 3.5).</p> <pre><code>class X: pass class Y(X): pass X.__dict__ ''' mappingproxy({'__dict__': &lt;attribute '__dict__' of 'X' objects&gt;, '__doc__': None, '__module__': '__main__', '__weakref__': &lt;attribute '__weakref__' of 'X' objects&gt;}) ''' Y.__dict__ ''' mappingproxy({'__doc__': None, '__module__': '__main__'}) ''' </code></pre>
2
2016-10-04T22:21:52Z
39,863,089
<p>The definition of <code>__weakref__</code> and <code>__dict__</code> is so the appropriate descriptor gets invoked to access the "real" location of the weak reference list and the instance dictionary of instances of the class when Python level code looks for it. The base class <code>object</code> is bare bones, and does not reserve space for <code>__weakref__</code> or <code>__dict__</code> on instances (<code>weakref.ref(object())</code> will fail, as will <code>setattr(object(), 'foo', 0)</code>).</p> <p>For a user-defined class, it needs to define descriptors that can find those values (in CPython, these accessors are usually bypassed because there are direct pointers at the C layer, but if you explicitly reference <code>instance.__dict__</code>, it needs to know how to find it through the instance's class). The first child of <code>object</code> (without <code>__slots__</code>) needs to define these descriptors, so they can be found. The subclasses don't need to, because the location of <code>__dict__</code> and <code>__weakref__</code> doesn't change; they can continue to use the accessor for the base class, since their instances have those attributes at the same relative offset.</p> <p>Basically, the first non-<code>__slot__</code>-ed user defined class is creating an idea of an instance as a C struct of the form:</p> <pre><code>struct InstanceObject { ... common object stuff ... ... anything defined by __slots__ in super class(es), if anything ... PyObject *location_of___dict__; PyObject *location_of___weakref__; } </code></pre> <p>and the accessors are implemented to check the type to determine the offset of those <code>location*</code> struct members, then retrieve them. The <code>struct</code> definition of a child class doesn't change the offset of those <code>location*</code> members (if new <code>__slots__</code> are added, they're just appended), so it can reuse the same accessor from the parent.</p>
3
2016-10-04T23:06:09Z
[ "python", "python-3.x" ]
Generate coordinates in grid that lie within a circle
39,862,709
<p>I've found <a href="http://stackoverflow.com/a/12364749/3928184">this answer</a>, which seems to be somewhat related to this question, but I'm wondering if it's possible to generate the coordinates one by one without the additional ~22% (1 - pi / 4) loss of comparing each point to the radius of the circle (by computing the distance between the circle's center and that point).</p> <p>So far I have the following function in Python. I know by <a href="http://mathworld.wolfram.com/GausssCircleProblem.html" rel="nofollow">Gauss' circle problem</a> the <em>number</em> of coordinates I will end up with, but I'd like to generate those points one by one as well.</p> <pre><code>from typing import Iterable from math import sqrt, floor def circCoord(sigma: float =1.0, centroid: tuple =(0, 0)) -&gt; Iterable[tuple]: r""" Generate all coords within $3\vec{\sigma}$ of the centroid """ # The number of least iterations is given by Gauss' circle problem: # http://mathworld.wolfram.com/GausssCircleProblem.html maxiterations = 1 + 4 * floor(3 * sigma) + 4 * sum(\ floor(sqrt(9 * sigma**2 - i**2)) for i in range(1, floor(3 * sigma) + 1) ) for it in range(maxiterations): # `yield` points in image about `centroid` over which we loop </code></pre> <p>What I'm trying to do is iterate over only those pixels lying within 3 * sigma of a pixel (at <code>centroid</code> in the above function).</p>
0
2016-10-04T22:26:22Z
39,862,846
<p>What about simply something like this (for a circle at origin)?</p> <pre><code>X = int(R) # R is the radius for x in range(-X,X+1): Y = int((R*R-x*x)**0.5) # bound for y given x for y in range(-Y,Y+1): yield (x,y) </code></pre> <p>This can easily be adapted to the general case when the circle is not centred at the origin. </p>
1
2016-10-04T22:39:07Z
[ "python", "generator" ]
How do I break down this list comprehension in Python?
39,862,745
<p>I seen a question earlier on how to find the characters to a specific word from a list of strings. It got deleted I think because I can't find it anymore.</p> <p>So for example:</p> <pre><code>&gt;&gt;&gt;findTheLetters(["hello", "world"], "hold") &gt;&gt;&gt;True &gt;&gt;&gt;findTheLetters(["hello", "world"], "holn") &gt;&gt;&gt;False (because of no "n") </code></pre> <p>So I seen a post by someone on here saying to use list comprehension like so:</p> <pre><code>return all((any(letter in word for word in myList)) for letter in myString) </code></pre> <p>my question is, is how would I break down that list comprehension so I can understand how it works? I've used simple(newbie) list comprehension but nothing like that.</p> <p>My attempt:</p> <pre><code>def findTheLetters(myList, myString): for word in myList: for letter in word: #something goes here? return letter in myString </code></pre> <p>That is the farthest I've gotten. It works sometimes like with "lord" and "hold", but like if I try "hell" or "woe" for example it still gives me false even though the characters "h" "e" "l" "l" and "w" "o" "e" are in the list of words. I am unsure what I need to add to make it work like the comprehension does.</p>
0
2016-10-04T22:29:50Z
39,862,884
<p>Here's a little educative example to show you what that algorithm is doing behind the curtains:</p> <pre><code>def findTheLetters(myList, myString): return all((any(letter in word for word in myList)) for letter in myString) def findTheLetters1(myList, myString): res1 = [] for letter in myString: res2 = [] for word in myList: res2.append(letter in word) print(letter, res2, any(res2)) res1.append(any(res2)) print('-' * 80) print(res1, all(res1)) print('-' * 80) return all(res1) findTheLetters1(["hello", "world"], "hold") findTheLetters1(["hello", "world"], "holn") </code></pre> <p>Output:</p> <pre><code>h [True, False] True o [True, True] True l [True, True] True d [False, True] True -------------------------------------------------------------------------------- [True, True, True, True] True -------------------------------------------------------------------------------- h [True, False] True o [True, True] True l [True, True] True n [False, False] False -------------------------------------------------------------------------------- [True, True, True, False] False -------------------------------------------------------------------------------- </code></pre> <p>I'd recommend you learn &amp; read a about any/all operators and also about nested comprehension lists to know the order of execution.</p> <p>Hope it helps</p>
2
2016-10-04T22:43:23Z
[ "python", "string", "list", "python-3.x", "list-comprehension" ]
Django not saving the multi-select option from form right
39,862,882
<p>I have a form that has a select multiple option for a model with a Many2Many. This seems to work but upon actually using the form if I select multiple things and click save, it only saves one of the items.</p> <p>The pertinent info int he views.py is located showing where this is happening.</p> <p>Also the output from the transaction is here, it looks like it is doing an insert every time. I think I want to fore a create? Though not sure if I did that (or how to) if it would also do that every time the change what groups the provider belongs to.</p> <p>Output:</p> <pre><code>(0.000) BEGIN; args=None (0.001) DELETE FROM "ipaswdb_providerlocations" WHERE "ipaswdb_providerlocations"."provider_id" = 1; args=(1,) here!IPANM Made a location! here!IPAABQ Made a location! (0.000) BEGIN; args=None (0.000) INSERT INTO "ipaswdb_providerlocations" ("provider_id", "group_location_id", "created_at", "updated_at") VALUES (1, 2, '2016-10-04', '2016-10-04'); args=[1, 2, u'2016-10-04', u'2016-10-04'] Id: 42 </code></pre> <p>forms.py</p> <pre><code>class ProviderForm(forms.ModelForm): phone = forms.RegexField(required=False, regex=r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$', error_message = ("Phone number must be entered in the format: '555-555-5555 or 5555555555'. Up to 15 digits allowed."), widget = forms.TextInput(attrs={'tabindex':'8', 'placeholder': '555-555-5555 or 5555555555'})) fax = forms.RegexField(required=False, regex=r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$', error_message = ("Fax number must be entered in the format: '555-555-5555 or 5555555555'. Up to 15 digits allowed."), widget = forms.TextInput(attrs={'tabindex':'9', 'placeholder': '555-555-5555 or 5555555555'})) class Meta: model=Provider fields = ('first_name', 'last_name', 'date_of_birth', 'license_number', 'license_experation', 'dea_number', 'dea_experation', 'phone', 'fax', 'caqh_number', 'effective_date', 'provider_npi', 'provisional_effective_date', 'date_joined', 'provider_contact', 'credentialing_contact', 'notes', 'hospital_affiliation', 'designation', 'specialty', 'group_locations') widgets = { 'designation' : Select(attrs={'tabindex':'1'}), 'first_name': TextInput(attrs={'tabindex':'2', 'placeholder':'Provider\'s first name'}), 'last_name' : TextInput(attrs={'tabindex':'3', 'placeholder':'Provider\'s last name'}), 'specialty' : Select(attrs={'tabindex':'4'}), 'date_of_birth' : TextInput(attrs= { 'class':'datepicker', 'tabindex' : '5', 'placeholder' : 'MM/DD/YYYY' }), 'license_number': TextInput(attrs={'tabindex':'6', 'placeholder':'License #'}), 'license_experation' : TextInput(attrs= { 'class':'datepicker', 'tabindex' : '7', 'placeholder' : 'MM/DD/YYYY' }), 'dea_number' : TextInput(attrs={'tabindex':'8', 'placeholder':'DEA #'}), 'dea_experation' : TextInput(attrs= { 'class':'datepicker', 'tabindex' : '9', 'placeholder' : 'MM/DD/YYYY' }), 'ptan': TextInput(attrs={'tabindex':'10', 'placeholder':'Provider\'s PTAN #'}), 'caqh_number': TextInput(attrs={'tabindex':'11', 'placeholder':'Provider\'s CAQH #'}), 'effective_date' : TextInput(attrs= { 'class':'datepicker', 'tabindex' : '12', 'placeholder' : 'MM/DD/YYYY' }), 'provider_npi': TextInput(attrs={'tabindex':'13', 'placeholder':'Provider\'s NPI #'}), 'provisional_effective_date' : TextInput(attrs= { 'class':'datepicker', 'tabindex' : '14', 'placeholder' : 'MM/DD/YYYY' }), 'date_joined' : TextInput(attrs= { 'class':'datepicker', 'tabindex' : '15', 'placeholder' : 'MM/DD/YYYY' }), 'provider_contact': TextInput(attrs={'tabindex':'16', 'placeholder':'Provider\'s Contact'}), 'credentialing_contact': TextInput(attrs={'tabindex':'17', 'placeholder':'Credentialer\'s Contact'}), 'notes' : Textarea(attrs={'tabindex':'18', 'placeholder':'Provider\'s notes'}), 'hospital_affiliation': TextInput(attrs={'tabindex':'19', 'placeholder':'Provider\'s Hospital Affiliation'}), } </code></pre> <p>views.py</p> <pre><code>class ProviderUpdateView(UpdateView): model = Provider form_class = ProviderForm template_name = 'ipaswdb/provider/provider_form.html' success_url = 'ipaswdb/provider/' def form_valid(self, form): self.object = form.save(commit=False) ProviderLocations.objects.filter(provider=self.object).delete() for group_location in form.cleaned_data['group_locations']: print("here!" + group_location.doing_business_as) location = ProviderLocations() print("Made a location!") #executes twice location.provider = self.object location.group_location = group_location location.save() print("Id: " + str(location.id)) #executes once return super(ModelFormMixin, self).form_valid(form) </code></pre> <p>models.py</p> <pre><code>class Provider(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) date_of_birth = models.DateField(auto_now_add=False) license_number = models.CharField(max_length = 50) license_experation= models.DateField(auto_now_add=False) dea_number = models.CharField(max_length = 50) dea_experation = models.DateField(auto_now_add=False) phone = models.CharField(max_length = 50) fax = models.CharField(max_length = 50, null=True, blank=True) ptan = models.CharField(max_length = 50) caqh_number = models.CharField(max_length = 50) effective_date = models.DateField(auto_now_add=False) provider_npi = models.CharField(max_length = 50) provisional_effective_date = models.DateField(auto_now_add=False) date_joined = models.DateField(auto_now_add=False) provider_contact = models.CharField(max_length = 50, blank=True, null=True) credentialing_contact = models.CharField(max_length = 50, blank=True, null=True) notes = models.TextField(max_length = 255, blank=True, null=True) hospital_affiliation= models.CharField(max_length = 50, null=True, blank=True) designation = models.ForeignKey('Designation', on_delete=models.SET_NULL, null=True, blank=True) specialty = models.ForeignKey('Specialty', on_delete=models.SET_NULL, null=True, blank=True) group_locations = models.ManyToManyField('GroupLocations', through='ProviderLocations', blank=True, null=True) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.first_name #really think this is just broken too I really want something like the #screen in billings for the provider to have a manytomany field on the grouplocations #do i need a special method to get this data together or can i do it through through fields?? #look at billings when it boots up. class ProviderLocations(models.Model): #group_location = models.ForeignKey('GroupLocations', on_delete=models.CASCADE) provider = models.ForeignKey('Provider', on_delete=models.CASCADE) group_location = models.ForeignKey('GroupLocations', on_delete=models.CASCADE) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.provider.first_name #i really think provider should go away here class GroupLocations(models.Model): address = models.ForeignKey('Address', on_delete= models.SET_NULL, null=True) group = models.ForeignKey('Group', on_delete=models.CASCADE) doing_business_as = models.CharField(max_length = 255) created_at=models.DateField(auto_now_add=True) updated_at=models.DateField(auto_now=True) def __str__(self): return self.doing_business_as class Group(models.Model): group_name = models.CharField(max_length=50) group_contact= models.CharField(max_length=50) tin = models.CharField(max_length=50) class Address(models.Model): city = models.CharField(max_length=50) state = models.CharField(max_length=50) zip_code = models.CharField(max_length=50) </code></pre>
0
2016-10-04T22:43:12Z
39,862,898
<p>You might try taking the return statement out of the for loop in your views.py</p> <pre><code>def form_valid(self, form): self.object = form.save(commit=False) ProviderLocations.objects.filter(provider=self.object).delete() for group_location in form.cleaned_data['group_locations']: print("here!" + group_location.doing_business_as) location = ProviderLocations() print("Made a location!") #executes twice location.provider = self.object location.group_location = group_location location.save() print("Id: " + str(location.id)) #executes once return super(ModelFormMixin, self).form_valid(form) </code></pre>
0
2016-10-04T22:45:12Z
[ "python", "django", "django-forms", "django-views" ]
How do I pause this thread after x minutes
39,862,982
<p>How to pause this thread from running every 300 seconds for 500 seconds? I need to suspend it from running all the functions every x minutes to prevent API breaches. Timer objects seem to only start the code, whereas the objective is to pause, wait, resume.</p> <pre><code>from TwitterFollowBot import TwitterBot from threading import Thread import random my_bot = TwitterBot() my_bot.sync_follows() def a(): my_bot.auto_fav("@asco", count=1000) def b(): my_bot.auto_fav("ATSO", count=1000) def c(): my_bot.auto_fav("BCY3", count=1000) lof = [a, b, c] random.shuffle(lof) for z in lof: Thread(target=z).start() </code></pre> <p>Credit to @Farhan.K for assisting with the code.</p>
1
2016-10-04T22:54:30Z
39,865,064
<p>Maybe something like this for your threads?</p> <pre><code>import time def sleep_thread(sleepWait, sleepTime): timeStart = time.time() timeElapsed = 0 while timeElapsed &lt;= sleepWait: timeElapsed = time.time() - timeStart print 'time elapsed = ' + str(timeElapsed) time.sleep(1) print 'going to sleep. zzz....' # Sleep for x time.sleep(sleepTime) print 'im awake!' sleep_thread(5, 3) </code></pre>
1
2016-10-05T03:41:17Z
[ "python", "multithreading", "bots", "python-multithreading" ]
how to connect external libraries in Kivy
39,863,004
<p>When you try to build the application. Application normally collected and only runs if there is no outside application libraries. When you attempt to connect networkx library. Appendix normally gather. But when you try to run directly on the device. Pops saver "Loadind ..." and the application falls. What you need to change to get everything working. Attached is the application code:</p> <pre><code>from kivy.app import App from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.floatlayout import FloatLayout from kivy.uix.scatter import Scatter from kivy.uix.boxlayout import BoxLayout from kivy.graphics.vertex_instructions import * from kivy.graphics.context_instructions import Color import networkx as nx G = nx.Graph() G.add_node(1) G.add_node(2) G.add_node(3) G.add_node(4) G.add_edge(1,2) G.add_edge(1,3) G.add_edge(3,4) G.add_edge(2,3) class SimpleKivy(App): def build(self): b = BoxLayout() l = Label(text=str(nx.shortest_path(G,1,4))) textinput1 = TextInput(text=str(nx.shortest_path(G,1,4))) textinput1.bind(text=l.setter('text')) f = FloatLayout() s = Scatter() s.add_widget(l) f.add_widget(s) b.add_widget(f) b.add_widget(textinput1) return b if __name__ == "__main__": SimpleKivy().run() </code></pre>
0
2016-10-04T22:56:13Z
39,880,918
<p>In your <code>buildozer.spec</code> file, line <code>39</code> add your third-party requirments.</p> <pre><code>requirements = kivy,networkx, # or what ever </code></pre>
1
2016-10-05T18:07:43Z
[ "android", "python", "kivy", "networkx" ]
Separate the words by a space in a string using python
39,863,103
<pre><code>text = "Avalon:Sydney 04March2009Bondi Street at a conferencemeeting room234". </code></pre> <p>I would like to process the above string in such as way that the words are separated and not joined. </p> <p>I would like the string to be printed as follows:</p> <p><code>"Avalon Sydney 04 March 2009 Bondi Street at a conference metting room 234"</code></p> <p>The string is now separated into individual words. </p> <p>I would like to use the regular expressions but I failed. </p> <pre><code>text = "Avalon:Sydney 04March2009Bondi Street at a conferencemeeting room234" newtext = re.sub('[a-zA-Z0-9_:]','',text) print text </code></pre> <p>the above code does not work. Is there a better regular expression I can use to separate the words. </p> <p>The regular expression should not be specific to the above sentence only, but a universal regular expression that can observe the above patters and separate into individual words in the same string.</p>
0
2016-10-04T23:08:27Z
39,863,273
<p>To replace the colon with a space, use <code>.replace</code>:</p> <pre><code>text = text.replace(':', ' ') </code></pre> <p>To split parts of the text alternating between numbers and letters, you can use a <em>positive look behind</em> to catch words preceded by numbers or numbers preceded by words, and then substitute with a back reference with a leading space:</p> <pre><code>text = re.sub(r'((?&lt;=[a-zA-Z_])\d|(?&lt;=\d)[a-zA-Z_])', r' \1', text) print text # 'Avalon Sydney 04 March 2009 Bondi Street at a conferencemeeting room 234' </code></pre> <p>The splitting of <code>conferencemeeting</code> into separate words is not something that is up to regex, except of course, you could define a rule on which the splitting should be done.</p>
0
2016-10-04T23:31:37Z
[ "python" ]
Slice a dataframe with a hierarchy index
39,863,176
<p>I have two dataframes. One has stock transactions (things like buy date, buy price, sell date, sell price). The other dataframe has all the prices in date order with an hierarchy index of <code>['symbol', 'date']</code> indexing <code>'close'</code> price called <code>dfPrice</code>.</p> <p>Not knowing a better way of submitting a dataframe to this group, I have made a record of the first 10 lines by:</p> <pre><code>ra = dfPrice.to_records() </code></pre> <p>yielding an <code>ra</code> of:</p> <pre><code>rec.array([('A', Timestamp('2000-09-01 00:00:00'), 39.84), ('A', Timestamp('2000-09-05 00:00:00'), 39.8), ('A', Timestamp('2000-09-06 00:00:00'), 38.63), ('A', Timestamp('2000-09-07 00:00:00'), 39.84), ('A', Timestamp('2000-09-08 00:00:00'), 38.15), ('A', Timestamp('2000-09-11 00:00:00'), 36.54), ('A', Timestamp('2000-09-12 00:00:00'), 35.41), ('A', Timestamp('2000-09-13 00:00:00'), 35.41), ('A', Timestamp('2000-09-14 00:00:00'), 35.89), ('A', Timestamp('2000-09-15 00:00:00'), 36.7)], dtype=[('symbol', 'S1'), ('date', 'O'), ('close', '&lt;f8')]) </code></pre> <p>you can get the <code>dfPrice</code> by:</p> <pre><code>dfPrice = DataFrame(ra) dfPrice.set_index(['symbol', 'date'], inplace=True) </code></pre> <p>what I want is to use the buy date and sell date and look up the minimum price in the interval I held the stock. </p> <p>If I bought stock 'A' on 2000-09-07 and sold on 2000-09-14 (keeping it over the weekend without any price entries) I thought I could get the minimum price over that interval by using something like:</p> <pre><code>minPrice = dfPrice.min['A', '2000-09-07':'2000-09-14'] </code></pre> <p>The answer is 35.41.</p> <p>I have looked on Stack Overflow, but came up empty. What can I use to get what I want?</p>
0
2016-10-04T23:19:36Z
39,863,609
<p>There might be a more straightforward way to do so, but I managed to get <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#advanced-indexing-with-hierarchical-index" rel="nofollow">advanced indexing</a> to work using a tuple for your hierarchical indices:</p> <pre><code>&gt;&gt;&gt; dfPrice[('A','2000-09-07'):('A','2000-09-14')] close symbol date 'A' 2000-09-07 39.84 2000-09-08 38.15 2000-09-11 36.54 2000-09-12 35.41 2000-09-13 35.41 2000-09-14 35.89 &gt;&gt;&gt; dfPrice[('A','2000-09-07'):('A','2000-09-14')].min() close 35.41 dtype: float64 </code></pre> <p>So for one you have to use advanced indexing in order to slice into your second level of indices, and you have to apply the <code>.min()</code> method to a sliced dataframe (rather than trying to put indices inside the call to <code>.min()</code>).</p>
0
2016-10-05T00:17:20Z
[ "python", "indexing", "dataframe", "slice", "hierarchy" ]
How to pip install bcrypt on Azure webapp?
39,863,193
<p>Disclosure : First time Azure experience</p> <p>I am deploying a Flask app to Azure Webapp. All deployment steps are fine till I hit the bcrypt package installation and it fails.</p> <p>After much research based on error log output, I found out that I might need to install bcrypt using wheelhouse (*.WHL)</p> <p>I downloaded the below files from <a href="https://pypi.python.org/pypi/bcrypt/3.1.0" rel="nofollow">here</a></p> <ul> <li>bcrypt-3.1.0-cp27-cp27m-win32.whl</li> <li>bcrypt-3.1.0-cp27-cp27m-win_amd64.whl</li> </ul> <p>and I copied them to <code>D:\home\site\repository\wheelhouse</code></p> <p>Then, I activated the virtualenv through KUDU and I run this command: </p> <pre><code>d:\home\site\wwwroot\env\scripts\pip install -r requirements.txt --find-links d:\home\site\repository\wheelhouse </code></pre> <p>I get no messages or any log output. When I run a <code>pip freeze &gt; tmp.txt</code> I get a blank file.</p> <p>But when I run <code>d:\python27\scripts\pip install -r requirements.txt --find-links d:\home\site\repository\wheelhouse</code></p> <p>It starts installing the packages until it gets to bcrypt and it errs out with this message:</p> <blockquote> <p>Skipping bcrypt-3.1.0-cp27-cp27m-win32.whl because it is not compatible with this Python</p> </blockquote> <p>Which is a confusing message because the wheel is for Python 2.7</p> <p>Since my Flask app works fine on both my Linux and Windows dev machines, I went ahead and created my own brypt wheel file in my Windows computer which runs the same Python version on Azure. I uploaded the new <code>.whl</code>, redid the steps above and I still get the same error message</p> <p>Extra notes:</p> <ul> <li>python -V on Azure console returns 2.7.8</li> <li>python -V while virtualenv is activated also returns 2.7.8</li> <li>Azure portal > Application Settings shows "Python version 2.7" and "Platform 32bits".</li> <li>After deployment, all packages in requirements.txt are installed except bcrypt.</li> <li>Visiting the web page gives a 500 error (which i expect due to missing lib)</li> <li>I removed the virtualenv and GIT pushed the repo with <code>--find-links wheelhouse</code> at the top of requirements.txt as stated <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-python-configure/#_build-wheels-requires-windows" rel="nofollow">here</a>.<br> However, I get a <code>Unable to find vcvarsall.bat</code> error. That's why I m trying to manually install via wheel</li> <li><p>I deleted the whole virtualenv, uploaded wheel files for all required packages to \repository\wheelhouse and added <code>--no-index</code> to my pip install command. Everything gets installed except bcrypt.</p></li> <li><p>I tried <code>bcrypt==3.1.1</code>, <code>bcrypt==3.1.0</code> and just <code>bcrypt</code> without specifying the version and it doesnt make any difference.</p></li> </ul> <p>I ran out of ideas. Anyone knows what's wrong? How do I go about installing bcrypt on Azure webapp?</p>
0
2016-10-04T23:22:21Z
39,879,209
<p>I was finally able to get the Flask app working on Azure Webapps. Unfortunately, I couldn't do it using my usual dev tools. </p> <p><strong>Solution</strong>:</p> <ul> <li>I created a VirtualEnv in Visual Studio using my <code>requirements.txt</code> file</li> <li>Moved my Flask code to Visual Studio</li> <li>Click on Publish to Azure Webapps</li> </ul> <p>It does what it does and once completed, you may still get a 500 error. If that is the case, use KUDU and take a look at your <code>web.config</code> file and modify the <code>WSGI_ALT_VIRTUALENV_HANDLER</code> value to match your Flask app name.</p> <p>This is the only way I was able to get <code>bcrypt</code> to install correctly for my Flask app to work. I hope this saves someone valuable time.</p> <p>That's all folks.</p>
0
2016-10-05T16:23:38Z
[ "python", "azure", "pip", "virtualenv", "bcrypt" ]
Display output from python in aspx page
39,863,217
<p>Question from a .net newbie</p> <p>Hello,</p> <p>I am trying to display output from my python code in aspx page.</p> <p>Below is .net c# code that executes by the click of Button1.</p> <pre><code>protected void Button1_Click1(object sender, EventArgs e) { ScriptEngine eng = Python.CreateEngine(); dynamic scope = eng.CreateScope(); eng.ExecuteFile(@"C:\path\hello.py", scope); Label1.Text = //display output in Label1 } </code></pre> <p>Below is the sample python script.</p> <pre><code>print "hello" </code></pre> <p>Could you please tell me how to display "hello" in Label1.Text?</p> <p>Also any kind of information regarding passing data between python and asp.net is appreciated.</p> <p>Thanks,</p>
0
2016-10-04T23:25:48Z
39,863,950
<p>You can put all your result in variable a</p> <p>Example:</p> <p>Python</p> <pre><code>a = "" a += "hello world\n" a += "===========" </code></pre> <p>In C#</p> <pre><code>ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); engine.ExecuteFile(@"C:\path\hello.py", scope); var result = scope.GetVariable("a"); Console.WriteLine(result); Console.ReadLine(); </code></pre>
0
2016-10-05T01:05:42Z
[ "c#", "python", "asp.net", "visual-studio", "ironpython" ]
Python Program Correction
39,863,218
<p>I need help I am trying to open the terminal and type ifconfig and enter then read the output on a mac then il transition this later to kali but I am getting a error with the file path to terminal and I cant start it, here is my code. </p> <pre><code>import os,sys #opens terminal terminal = os.open('/Applications/Utilities/Terminal.app', os.O_RDWR|os.O_APPEND) #writes ifconfig os.write(terminal, 'ifconfig') os.close(terminal) </code></pre>
-1
2016-10-04T23:25:53Z
39,863,299
<p>I suggest you use <code>subprocess</code></p> <pre><code>import subprocess def popen(executable): sb = subprocess.Popen( '%s' % executable, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, ) stdout, stderr = sb.communicate() return stdout, stderr, sb.returncode </code></pre> <p>you can pass <code>ifconfig</code> to this method and it will execute the command and return the output for you.</p>
1
2016-10-04T23:33:59Z
[ "python", "osx", "terminal", "filepath" ]
Python Program Correction
39,863,218
<p>I need help I am trying to open the terminal and type ifconfig and enter then read the output on a mac then il transition this later to kali but I am getting a error with the file path to terminal and I cant start it, here is my code. </p> <pre><code>import os,sys #opens terminal terminal = os.open('/Applications/Utilities/Terminal.app', os.O_RDWR|os.O_APPEND) #writes ifconfig os.write(terminal, 'ifconfig') os.close(terminal) </code></pre>
-1
2016-10-04T23:25:53Z
39,863,352
<p>I agree with using <a href="https://docs.python.org/3/library/subprocess.html#subprocess.check_output" rel="nofollow">subprocess</a>. To add to Amin's answer, for something this simple that you just want the output from:</p> <pre><code>import subprocess print(subprocess.check_output(['ifconfig'])) </code></pre> <p>Edit: </p> <p>What I was talking about in my comment is the new <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow">run</a> function that returns a <a href="https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess" rel="nofollow">CompletedProcess</a> class that holds all the relevant information for you. That way you no longer have to have three different variables holding your stdout, sterr and returncode.</p>
1
2016-10-04T23:40:43Z
[ "python", "osx", "terminal", "filepath" ]
SQLAlchemy ORM with dynamic table schema
39,863,337
<p>I am trying to task <strong>SQLAlchemy ORM</strong> to create class <code>Field</code> that describes all fields in my database:</p> <pre><code>from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Field(Base): __tablename__ = 'fields' __table_args__ = {'schema':'SCM'} id = Column(String(20), primary_key=True) </code></pre> <p>The issue is that table <code>fields</code> describes different fields in different schemas, i.e. </p> <pre><code>SCM.fields TDN.fields ... </code></pre> <p>I need class Field to</p> <ul> <li>Be initialized with object <code>fieldset</code> before records can be read from db</li> <li>Schema determined by <code>fieldset.get_schema()</code> before table <code>&lt;schema&gt;.fields</code> is read.</li> </ul> <p>Something like this:</p> <p>session.query(Field(fieldset))).filter(Field.id=='some field')</p> <p>However, adding </p> <pre><code>def __init__(self, fieldset) pass </code></pre> <p>to <code>class Field</code> results in </p> <blockquote> <p><code>__init__() takes 1 positional argument...</code></p> </blockquote> <ul> <li>I could lump all <code>fields</code> tables into one schema and add column 'schema_name' but I still need Field have link to its fieldset.</li> </ul> <p>Can this be done using <strong>SQLAlchemy ORM</strong> or should I switch to <strong>SqlAlchemy Core</strong> where I would have more control over object instantiation?</p>
0
2016-10-04T23:38:24Z
39,966,105
<p>So the problem is solvable and the solution is documented as <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#augmenting-the-base" rel="nofollow">Augmenting the Base</a></p> <pre><code>from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declared_attr, declarative_base class Field: __tablename__ = 'fields' @declared_attr def __table_args__(cls): # schema will be part of class name, which works for me # Example: class FieldSCM --&gt; Field with schema SCM return dict(schema=cls.__name__[5:].upper()) id = Column(String(20), primary_key=True) Field = declarative_base(cls=Field) class FieldSet: def __init__(self, schema): self.fieldtype = type('Field' + schema.upper(), (Field,), {}) </code></pre> <p>Proof of concept:</p> <pre><code>FieldSet('ork').fieldtype.__table__ </code></pre> <blockquote> <p>Table('fields', MetaData(bind=None), Column('id', String(length=20), table=, primary_key=True, nullable=False), schema='ORK')</p> </blockquote>
0
2016-10-10T20:17:50Z
[ "python", "sqlalchemy" ]
Having trouble finding the greatest length of whitespace in string
39,863,377
<p>I need to find the greatest length of white space in the string. No idea whats wrong. </p> <pre><code>def check1(x): cc = () for i in x: if i != " ": lis.append(cc) cc=0 else: cc +=1 new.append(cc) print(cc) </code></pre> <p>I'm not sure whats wrong, its not adding to the appending list. </p>
0
2016-10-04T23:44:50Z
39,863,397
<p>Use <code>regex</code>es and builtin <code>max</code>:</p> <pre><code>import re max_len = max(map(len, re.findall(' +', sentence))) </code></pre> <hr> <p><code>re.findall(' +', sentence)</code> will find all the occurrences of one or more whitespaces.</p> <p><code>map(len, ...)</code> will transform this array into the array of the corresponding string lengths.</p> <p><code>max(...)</code> will get the highest value of these string lengths. </p>
2
2016-10-04T23:47:17Z
[ "python", "string" ]
Having trouble finding the greatest length of whitespace in string
39,863,377
<p>I need to find the greatest length of white space in the string. No idea whats wrong. </p> <pre><code>def check1(x): cc = () for i in x: if i != " ": lis.append(cc) cc=0 else: cc +=1 new.append(cc) print(cc) </code></pre> <p>I'm not sure whats wrong, its not adding to the appending list. </p>
0
2016-10-04T23:44:50Z
39,863,421
<p>You could use a simple <code>itertools.groupby</code>:</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; s = 'foo bar baz lalala' &gt;&gt;&gt; max(len(list(v)) for is_sp, v in groupby(s, str.isspace) if is_sp) 10 </code></pre> <p>The groupby will find consecutive runs of whitespace (<code>is_sp == True</code>) and consecutive runs of non-whitespace (<code>is_sp == False</code>). In our case, we only care about the runs of whitespace, so we filter the non-whitespace cases away and then get the length of the consecutive runs. Finally, the only thing that is left is to pick the largest of all of lengths.</p>
1
2016-10-04T23:50:35Z
[ "python", "string" ]
Pandas Compare two columns matching text and printing full row of matching
39,863,444
<p>I am looking to take a hash from one df and find that hash in another df.hash column and print the full row of the matches. </p> <p>df1: <code> hash 11dd7da7faa0130dac2560930e90c8b1 11dd7da7faa0130dac2560930e90c8b2 11dd7da7faa0130dac2560930e90c8b3 11dd7da7faa0130dac2560930e90c8b4 </code> df2: <code> filepath hash C:\windows 11dd7da7faa0130dac2560930e90c8b5 C:\Temp 11dd7da7faa0130dac2560930e90c8b6 C:\foundya 11dd7da7faa0130dac2560930e90c8b1 C:\Windows\temp 11dd7da7faa0130dac2560930e90c8b2 </code></p> <p>Expected output: <code> filepath hash C:\foundya 11dd7da7faa0130dac2560930e90c8b1 C:\Windows\temp 11dd7da7faa0130dac2560930e90c8b2 </code> Failed Attempts: <code> print(df2[['hash','filepath']][~df2['hash'].isin(df1)]) print(df2[['hash','filepath']][~df1.isin(df2['hash'])]) </code></p>
0
2016-10-04T23:55:15Z
39,863,494
<p>what about a simple merge here?</p> <pre><code>df1.merge(df2, on ='hash', how ='inner') </code></pre>
1
2016-10-05T00:00:56Z
[ "python", "pandas" ]
AWS SDK | List of waiters for Elastic Beanstalk
39,863,448
<p>I'm interested in this <a href="https://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html#ElasticBeanstalk.Client.get_waiter" rel="nofollow">method</a> <code>get_waiter(waiter_name)</code>. Examples of waiters are in this <a href="http://boto3.readthedocs.io/en/latest/guide/clients.html#waiters" rel="nofollow">page</a>. I looked everywhere but I couldn't find a complete list of waiters for this particular service (for Python and PHP as well). </p> <p>Basically, what I want to happen is to get the status of app or environment and verify it's good before moving on to the next task.</p> <p>My current approach is to use <code>while</code> loop and <code>break</code> if the status from AWS response matches the status that I was expecting. I think this is not the best way to deal with this. Please correct me if I'm wrong.</p> <p>Here's the snippet from my code written in Python:</p> <pre><code># Check the application status while True: try: response = eb.describe_application_versions( ApplicationName=app_name, VersionLabels=[ new_app_version ] ) status = 'PROCESSED' app_status = response['ApplicationVersions'][0]['Status'] if status == app_status: print('Application Status:\t', app_status) break except: raise # Deploy the app to Elastic Beanstalk try: response = eb.update_environment( ApplicationName=app_name, EnvironmentId=env_id, VersionLabel=new_app_version ) except: raise # Check environment health while True: try: response = eb.describe_environment_health( EnvironmentId=env_id, AttributeNames=[ 'Status' ] ) status = 'Ready' env_status = response['Status'] if status == env_status: print('Environment Status:\t', env_status) break except: raise </code></pre>
0
2016-10-04T23:55:55Z
39,880,451
<p>There are no waiters for that service yet. If there were, you would see them in the docs. For example compare the <a href="http://boto3.readthedocs.io/en/latest/reference/services/elasticbeanstalk.html" rel="nofollow">elasticbeanstalk boto3 docs</a> with the <a href="http://boto3.readthedocs.io/en/latest/reference/services/cloudfront.html" rel="nofollow">cloudfront docs</a>. The cloudfront docs have a <a href="http://boto3.readthedocs.io/en/latest/reference/services/cloudfront.html#waiters" rel="nofollow">waiters section</a>.</p>
1
2016-10-05T17:39:09Z
[ "python", "amazon-web-services", "sdk", "boto" ]
PYTHON: Making an array with n-many elements
39,863,461
<p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements. I am having trouble setting up this array since I don't know how many elements it will have. I have tried several different ways to make it work. This is my latest attempt:</p> <pre><code>N = input("How many inputs: ") i=1 a = [] while i &lt;= N: a.append = input("Enter value for flux: ") i = i+1 </code></pre> <p>Surely there is something simple that I am missing; this seems like something that would be common.</p>
0
2016-10-04T23:57:08Z
39,863,481
<p>You are misusing the API for <code>list.append</code>. As it is, you are throwing away that list's <code>append</code> method and replacing it with the user's input, repeatedly. That line should be as follows:</p> <pre><code>a.append(input("Enter value for flux: ")) </code></pre> <p>The user's input is passed as an argument to the <code>a.append</code> method, appending it to that list.</p>
0
2016-10-04T23:59:33Z
[ "python", "arrays" ]
PYTHON: Making an array with n-many elements
39,863,461
<p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements. I am having trouble setting up this array since I don't know how many elements it will have. I have tried several different ways to make it work. This is my latest attempt:</p> <pre><code>N = input("How many inputs: ") i=1 a = [] while i &lt;= N: a.append = input("Enter value for flux: ") i = i+1 </code></pre> <p>Surely there is something simple that I am missing; this seems like something that would be common.</p>
0
2016-10-04T23:57:08Z
39,863,499
<p>You're doing append= that is not valid, try it like this:</p> <pre><code>N = input("How many inputs: ") i=1 a = [] while i &lt;= N: value = input("Enter value for flux: ") a.append(value) i = i+1 </code></pre>
0
2016-10-05T00:01:21Z
[ "python", "arrays" ]
PYTHON: Making an array with n-many elements
39,863,461
<p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements. I am having trouble setting up this array since I don't know how many elements it will have. I have tried several different ways to make it work. This is my latest attempt:</p> <pre><code>N = input("How many inputs: ") i=1 a = [] while i &lt;= N: a.append = input("Enter value for flux: ") i = i+1 </code></pre> <p>Surely there is something simple that I am missing; this seems like something that would be common.</p>
0
2016-10-04T23:57:08Z
39,863,533
<p>Maybe the range can help you. Also be sure to int the answer and to try/except the <code>int</code>. I leave that to you.</p> <pre><code>a = [] for i in range(N): a.append(int(input('&gt; '))) i += 1 </code></pre>
0
2016-10-05T00:05:11Z
[ "python", "arrays" ]
PYTHON: Making an array with n-many elements
39,863,461
<p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements. I am having trouble setting up this array since I don't know how many elements it will have. I have tried several different ways to make it work. This is my latest attempt:</p> <pre><code>N = input("How many inputs: ") i=1 a = [] while i &lt;= N: a.append = input("Enter value for flux: ") i = i+1 </code></pre> <p>Surely there is something simple that I am missing; this seems like something that would be common.</p>
0
2016-10-04T23:57:08Z
39,863,546
<p>there you go.</p> <pre><code>N = input("How many inputs: ") a = [] for _ in xrange(N): a.append(input("Enter value for flux: ")) </code></pre>
0
2016-10-05T00:06:26Z
[ "python", "arrays" ]
PYTHON: Making an array with n-many elements
39,863,461
<p>I am trying to write a program that will first ask for the number of inputs, then will ask for the value of each input. I need to find the mean and root-mean-square of the values from input, so I am trying to make an array of n-many (usually 2, but up to 6) elements. I am having trouble setting up this array since I don't know how many elements it will have. I have tried several different ways to make it work. This is my latest attempt:</p> <pre><code>N = input("How many inputs: ") i=1 a = [] while i &lt;= N: a.append = input("Enter value for flux: ") i = i+1 </code></pre> <p>Surely there is something simple that I am missing; this seems like something that would be common.</p>
0
2016-10-04T23:57:08Z
39,863,573
<p>Cast the inputs to integer.</p> <pre><code>N = int(input("How many inputs: ")) a = [] for elem in range(N): a.append(int(input("Enter value for flux: "))) </code></pre>
0
2016-10-05T00:11:48Z
[ "python", "arrays" ]
Configuring a Postgresql POSTGIS database
39,863,476
<p>First off, I am new to django. I am trying to use GeoLite(GeoIP2) datasets in my POSTGIS database in Django 1.10. When I attempt to configure the myapp/settings.py file, i get error messages.There seem to be database backends in different paths in the django directory;Can you please clarify why?</p> <ol> <li>django\contrib\gis\db\backends\postgis </li> <li>django\db\backends</li> </ol> <p>After activating my python3 virtual environment, when i try to set the default database in my settings.py file as postgresql('django.db.backends.postgresql'), i get an error:</p> <pre><code>AttributeError:”Database Operations’ object has no attribute ‘geo_db_type’. </code></pre> <p>When i try to use POSTGIS as my database engine (i set the GDAL_LIBRARY_PATH in my virtual environment), i get an error: </p> <pre><code>django.contrib.gis.db.backends.postgis' is not an available database backend. Try using 'django.db.backends.XXX', where XXX is one of 'mysql', 'oracle', 'postgresql',and 'sqlite'. Error was: Cannot import name ‘GDALRaster’. </code></pre> <p>Can you suggest possible solutions to the above error messages? Thank you.</p>
0
2016-10-04T23:59:06Z
39,927,332
<p>Installed GDAL from Christopher Gohlke’s site (32 bit GDAL-2.0.3-cp35-cp35m-win32.whl)into the virtual environment. Download OSGEO4W (32 bit) and install the Express Web option. Create Environment Variables. Set the environment variables as below:</p> <blockquote> <p>set PYTHON_ROOT=C:\Python35-32 set GDAL_DATA=C:\Program Files\PostgreSQL\9.6\gdal-data set PROJ_LIB=C:\Program Files\PostgreSQL\9.6\share\contrib\postgis\proj set PATH=%PATH%;%PYTHON_ROOT%;%OSGEO4W_ROOT%\bin reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_EXPAND_SZ /f /d "%PATH%" reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v GDAL_DATA /t REG_EXPAND_SZ /f /d "%GDAL_DATA%" reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PROJ_LIB /t REG_EXPAND_SZ /f /d "%PROJ_LIB%"</p> </blockquote> <p>I also set LD_LIBRARY_PATH as C:\Python35-32\myvenv_python3\Lib\site-packages\osgeo. Then, the database is Improperly configured and cannot import 'GDALRaster' went away.From your django project directory, it would be possible to migrate now using: python manage.py migrate</p>
0
2016-10-08T00:05:41Z
[ "python", "django", "database", "postgresql", "geodjango" ]
pandas reorder subset of columns from a grouped data frame
39,863,487
<p>I have forecast data that I grouped by month. The original dataframe <em>something</em> like this:</p> <pre><code>&gt;&gt;clean_table_grouped[0:5] STYLE COLOR SIZE FOR MONTH 01/17 10/16 11/16 12/16 0 ####### ###### #### 0.0 15.0 15.0 15.0 1 ####### ###### #### 0.0 15.0 15.0 15.0 2 ####### ###### #### 0.0 15.0 15.0 15.0 3 ####### ###### #### 0.0 15.0 15.0 15.0 4 ####### ###### #### 0.0 15.0 15.0 15.0 &gt;&gt;clean_table_grouped.ix[0:,"FOR"][0:5] MONTH 01/17 10/16 11/16 12/16 0 0.0 15.0 15.0 15.0 1 0.0 15.0 15.0 15.0 2 0.0 15.0 15.0 15.0 3 0.0 15.0 15.0 15.0 4 0.0 15.0 15.0 15.0 </code></pre> <p>I simply want reorder these 4 columns in the follow way: </p> <p>(keeping the rest of the dataframe untouched)</p> <pre><code>MONTH 10/16 11/16 12/16 01/17 0 15.0 15.0 15.0 0.0 1 15.0 15.0 15.0 0.0 2 15.0 15.0 15.0 0.0 3 15.0 15.0 15.0 0.0 4 15.0 15.0 15.0 0.0 </code></pre> <p>My attempted solution was to reorder the columns of the subset following the post below: <a href="http://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns">How to change the order of DataFrame columns?</a></p> <p>I went about it by grabbing the column list and sorting it first</p> <pre><code> &gt;&gt;for_cols = clean_table_grouped.ix[:,"FOR"].columns.tolist() &gt;&gt;for_cols.sort(key = lambda x: x[0:2]) #sort by month ascending &gt;&gt;for_cols.sort(key = lambda x: x[-2:]) #then sort by year ascending </code></pre> <p>Querying the dataframe works just fine</p> <pre><code>&gt;&gt;clean_table_grouped.ix[0:,"FOR"][for_cols] MONTH 10/16 11/16 12/16 01/17 0 15.0 15.0 15.0 0.0 1 15.0 15.0 15.0 0.0 2 15.0 15.0 15.0 0.0 3 15.0 15.0 15.0 0.0 4 15.0 15.0 15.0 0.0 </code></pre> <p>However, when I try to set values in the original table, I get a table of "NaN":</p> <pre><code>&gt;&gt;clean_table_grouped.ix[0:,"FOR"] = clean_table_grouped.ix[0:,"FOR"][for_cols] &gt;&gt;clean_table_grouped.ix[0:,"FOR"] MONTH 01/17 10/16 11/16 12/16 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN 4 NaN NaN NaN NaN 5 NaN NaN NaN NaN </code></pre> <p>I have also tried zipping to avoid chained syntax (.ix[][]). This avoids the NaN, however, it doesn't change the dataframe -__-</p> <pre><code>&gt;&gt;for_cols = zip(["FOR", "FOR", "FOR", "FOR"], for_cols) &gt;&gt;clean_table_grouped.ix[0:,"FOR"] = clean_table_grouped.ix[0:,for_cols] &gt;&gt;clean_table_grouped.ix[0:,"FOR"] MONTH 01/17 10/16 11/16 12/16 0 0.0 15.0 15.0 15.0 1 0.0 15.0 15.0 15.0 2 0.0 15.0 15.0 15.0 3 0.0 15.0 15.0 15.0 4 0.0 15.0 15.0 15.0 </code></pre> <p>I realize I'm using ix to reassign values. However, I've used this technique in the past on dataframes that are not grouped and it has worked just fine.</p> <p>If this question as already been answered in another post (in a CLEAR way), please provide the link. I searched but could not find anything similar.</p> <p><strong>EDIT:</strong> I have found a solution. Manually reindex by creating a new multiindex dataframe in the order you want your columns sorted. I posted the solution below.</p>
3
2016-10-05T00:00:13Z
39,869,214
<p>Sort the column names containing date strings and later use it as a subset to return the columns in that particular order:</p> <pre><code>from datetime import datetime df[sorted(df.columns, key=lambda x: datetime.strptime(x, '%m/%y'))] </code></pre> <p><a href="http://i.stack.imgur.com/iYDPP.png" rel="nofollow"><img src="http://i.stack.imgur.com/iYDPP.png" alt="Image"></a></p> <hr> <p><strong><em>Toy Data:</em></strong></p> <pre><code>from datetime import datetime np.random.seed(42) cols = [['STYLE', 'COLOR', 'SIZE', 'FOR', 'FOR', 'FOR', 'FOR'], ['', '', '', '01/17', '10/16', '11/16', '12/16']] tups = list(zip(*cols)) index = pd.MultiIndex.from_tuples(tups, names=[None, 'MONTH']) clean_table_grouped = pd.DataFrame(np.random.randint(0, 100, (100, 7)), index=np.arange(100), columns=index) clean_table_grouped = clean_table_grouped.head() clean_table_grouped </code></pre> <p><a href="http://i.stack.imgur.com/57842.png" rel="nofollow"><img src="http://i.stack.imgur.com/57842.png" alt="Image"></a></p> <p>Split the multi-index <code>DF</code> into two with the one containing the forecast values and the other the remaining <code>DF</code>.</p> <pre><code>for_df = clean_table_grouped[['FOR']] clean_table_grouped = clean_table_grouped.drop(['FOR'], axis=1, level=0) </code></pre> <p>Forecast <code>DF</code>:</p> <pre><code>for_df </code></pre> <p><a href="http://i.stack.imgur.com/H2hbF.png" rel="nofollow"><img src="http://i.stack.imgur.com/H2hbF.png" alt="Image"></a></p> <p>Remaining <code>DF</code>:</p> <pre><code>clean_table_grouped </code></pre> <p><a href="http://i.stack.imgur.com/Usr7L.png" rel="nofollow"><img src="http://i.stack.imgur.com/Usr7L.png" alt="Image"></a></p> <p>Sorting the columns in the forecast <code>DF</code> by applying the same procedure as done in the pre-edited post.</p> <pre><code>order = sorted(for_df['FOR'].columns.tolist(), key=lambda x: datetime.strptime(x, '%m/%y')) </code></pre> <p>Making the <code>DF</code> in the same order by subsetting the sorted <code>list</code> of columns.</p> <pre><code>for_df = for_df['FOR'][order] </code></pre> <p>Concatenate the forecast <code>DF</code> with itself to create a multi-index like column.</p> <pre><code>for_df = pd.concat([for_df, for_df], axis=1, keys=['FOR']) </code></pre> <p>Finally, join them on the common index.</p> <pre><code>clean_table_grouped.join(for_df) </code></pre> <p><a href="http://i.stack.imgur.com/4cHZk.png" rel="nofollow"><img src="http://i.stack.imgur.com/4cHZk.png" alt="Image"></a></p>
1
2016-10-05T08:41:40Z
[ "python", "pandas", "multiple-columns", "swap", "multi-index" ]
pandas reorder subset of columns from a grouped data frame
39,863,487
<p>I have forecast data that I grouped by month. The original dataframe <em>something</em> like this:</p> <pre><code>&gt;&gt;clean_table_grouped[0:5] STYLE COLOR SIZE FOR MONTH 01/17 10/16 11/16 12/16 0 ####### ###### #### 0.0 15.0 15.0 15.0 1 ####### ###### #### 0.0 15.0 15.0 15.0 2 ####### ###### #### 0.0 15.0 15.0 15.0 3 ####### ###### #### 0.0 15.0 15.0 15.0 4 ####### ###### #### 0.0 15.0 15.0 15.0 &gt;&gt;clean_table_grouped.ix[0:,"FOR"][0:5] MONTH 01/17 10/16 11/16 12/16 0 0.0 15.0 15.0 15.0 1 0.0 15.0 15.0 15.0 2 0.0 15.0 15.0 15.0 3 0.0 15.0 15.0 15.0 4 0.0 15.0 15.0 15.0 </code></pre> <p>I simply want reorder these 4 columns in the follow way: </p> <p>(keeping the rest of the dataframe untouched)</p> <pre><code>MONTH 10/16 11/16 12/16 01/17 0 15.0 15.0 15.0 0.0 1 15.0 15.0 15.0 0.0 2 15.0 15.0 15.0 0.0 3 15.0 15.0 15.0 0.0 4 15.0 15.0 15.0 0.0 </code></pre> <p>My attempted solution was to reorder the columns of the subset following the post below: <a href="http://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns">How to change the order of DataFrame columns?</a></p> <p>I went about it by grabbing the column list and sorting it first</p> <pre><code> &gt;&gt;for_cols = clean_table_grouped.ix[:,"FOR"].columns.tolist() &gt;&gt;for_cols.sort(key = lambda x: x[0:2]) #sort by month ascending &gt;&gt;for_cols.sort(key = lambda x: x[-2:]) #then sort by year ascending </code></pre> <p>Querying the dataframe works just fine</p> <pre><code>&gt;&gt;clean_table_grouped.ix[0:,"FOR"][for_cols] MONTH 10/16 11/16 12/16 01/17 0 15.0 15.0 15.0 0.0 1 15.0 15.0 15.0 0.0 2 15.0 15.0 15.0 0.0 3 15.0 15.0 15.0 0.0 4 15.0 15.0 15.0 0.0 </code></pre> <p>However, when I try to set values in the original table, I get a table of "NaN":</p> <pre><code>&gt;&gt;clean_table_grouped.ix[0:,"FOR"] = clean_table_grouped.ix[0:,"FOR"][for_cols] &gt;&gt;clean_table_grouped.ix[0:,"FOR"] MONTH 01/17 10/16 11/16 12/16 0 NaN NaN NaN NaN 1 NaN NaN NaN NaN 2 NaN NaN NaN NaN 3 NaN NaN NaN NaN 4 NaN NaN NaN NaN 5 NaN NaN NaN NaN </code></pre> <p>I have also tried zipping to avoid chained syntax (.ix[][]). This avoids the NaN, however, it doesn't change the dataframe -__-</p> <pre><code>&gt;&gt;for_cols = zip(["FOR", "FOR", "FOR", "FOR"], for_cols) &gt;&gt;clean_table_grouped.ix[0:,"FOR"] = clean_table_grouped.ix[0:,for_cols] &gt;&gt;clean_table_grouped.ix[0:,"FOR"] MONTH 01/17 10/16 11/16 12/16 0 0.0 15.0 15.0 15.0 1 0.0 15.0 15.0 15.0 2 0.0 15.0 15.0 15.0 3 0.0 15.0 15.0 15.0 4 0.0 15.0 15.0 15.0 </code></pre> <p>I realize I'm using ix to reassign values. However, I've used this technique in the past on dataframes that are not grouped and it has worked just fine.</p> <p>If this question as already been answered in another post (in a CLEAR way), please provide the link. I searched but could not find anything similar.</p> <p><strong>EDIT:</strong> I have found a solution. Manually reindex by creating a new multiindex dataframe in the order you want your columns sorted. I posted the solution below.</p>
3
2016-10-05T00:00:13Z
39,923,156
<p>My own solution was based upon the below post's second answer: <a href="http://stackoverflow.com/questions/11194610/how-can-i-reorder-multi-indexed-dataframe-columns-at-a-specific-level">How can I reorder multi-indexed dataframe columns at a specific level</a></p> <p>Pretty much... just create a new dataframe with the multiindex you want. Trying to insert values using .ix,.loc,.iloc isn't well supported with multiindexed dataframes. If you're looking to completely change the values of the subset of columns (not just swap), Nickil's solution of separating and re-joining the tables is definitely the way to go. However, if you're only looking to swap the columns, the below works perfectly fine. I selected this as the answer over Nickil's solution because this solution worked better for me as I had other data besides 'FOR' grouped by month and it gave me <em>more flexibility in reordering the columns</em>.</p> <p>First, store the lists IN THE ORDER YOU WANT IT:</p> <pre><code>&gt;&gt;reindex_list = ['STYLE','COLOR','SIZE','FOR'] #desired order &gt;&gt;month_list = clean_table_grouped.ix[0:,"FOR"].columns.tolist() &gt;&gt;month_list.sort(key = lambda x: x[0:2]) #sort by month ascending &gt;&gt;month_list.sort(key = lambda x: x[-2:]) #sort by year ascending </code></pre> <p>Then create a zipped listed where style, color, size get zipped with '', and 'FOR' gets zipped with each month. Like so:</p> <pre><code>[('STYLE',''),('COLOR',''),..., ('FOR','10/16'), ('FOR','11/16'), ...] </code></pre> <p>Here is an algorithm that does it automagically:</p> <pre><code>&gt;&gt;zip_list = [] &gt;&gt; for i in reindex_list: if i in ['FOR']: for j in month_list: if j != '': zip_list.append(zip([i],[j])[0]) else: zip_list.append(zip([i],[''])[0]) </code></pre> <p>Then create a multi index from the tuple list you just zipped:</p> <pre><code>&gt;&gt;multi_cols = pd.MultiIndex.from_tuples(zip_list, names=['','MONTH']) </code></pre> <p>And finally, create a new dataframe from the old with the new multiindex:</p> <pre><code>&gt;&gt;clean_table_grouped_ordered = pd.DataFrame(clean_table_grouped, columns=multi_cols) &gt;&gt;clean_table_grouped_ordered[0:5] STYLE COLOR SIZE FOR MONTH 10/16 11/16 12/16 01/17 #### #### ### 15.0 15.0 15.0 0.0 #### #### ### 15.0 15.0 15.0 0.0 #### #### ### 15.0 15.0 15.0 0.0 #### #### ### 15.0 15.0 15.0 0.0 #### #### ### 15.0 15.0 15.0 0.0 #### #### ### 15.0 15.0 15.0 0.0 </code></pre>
0
2016-10-07T17:47:40Z
[ "python", "pandas", "multiple-columns", "swap", "multi-index" ]
converting list to graph?
39,863,521
<p>suppose I have a 2D list of booleans such as:</p> <pre><code>[[False, True , False], [True, False, False]] </code></pre> <p>would it be possible to convert this into a graph such that all the adjacent vals of the list are connected to each other? adjacency meaning just another value either directly next to, above/under, or one diagonal space away from each other. I'm working on a problem that I think would be easier to accomplish with a graph but my input is a list and I was curious if there was a way of doing that?</p>
-2
2016-10-05T00:04:04Z
39,863,767
<p>What exactly do you mean by 'convert into a graph'?</p> <p>One possibility is for you to create a structure for representing the graph. I suggest you read the top answer to this question: <a href="http://stackoverflow.com/questions/19472530/representing-graphs-data-structure-in-python">Representing graphs (data structure) in Python</a></p> <p>Then, you create the proper connections and create the graph.</p> <p>This code assumes all sublists are of equal length and graph is undirected.</p> <pre><code>def getConnections(input_list): connections = [] directions = [(-1,-1),(0,-1),(1,-1),(1,0)] for i in range(0,len(input_list)): for j in range(0,len(input_list[0])): for x,y in directions: if (i+y &gt;= 0 and i+y &lt; len(input_list) and j+x &gt;= 0 and j+x &lt; len(input_list)) pair = (input_list[i][j], input_list[i+y][j+x]) connections.append(pair) return connections myList = [[False, True , False], [True, False, False]] connections = getConnections(myList) myGraph = new Graph(connections, directed = false) </code></pre>
1
2016-10-05T00:38:24Z
[ "python", "list", "python-2.7", "graph" ]
python recursion: create all possible sentence of certain length using a key-value dictionary of word
39,863,565
<p>So, let's say we have a dictionary</p> <pre><code>&gt;&gt;&gt; dictionary {'and': ['the'], 'the': ['cat', 'dog'], 'cat': ['and']} </code></pre> <p>We want to create all possible sentences of certain length (say 5 in our case), where each sentence starts with a <code>key</code> in the dictionary followed by an element from it's values, then the chosen value becomes the key for next step (if the value is also in the set of keys) and so on until we hit the desired sentence length. </p> <p>To elaborate, say, in one of the sentences( denote <code>s</code>) we are producing our first key is <code>and</code>, then it will be followed by <code>the</code> since <code>(and,the)</code> is key-value pair. So, now we have <code>s = "and the"</code>. While extending <code>s</code>, now we will use <code>the</code> as the key. We have two possible values for <code>the</code> that is <code>cat</code> and <code>dog</code>. So, from <code>s</code>, we have <code>s1 = "and the cat"</code> and <code>s2 = "and the dog"</code>. Now, <code>dog</code> is not a <code>key</code> in the dictionary, so we cannot pursue this road anymore to achieve a sentence of length 5. So, we stop here. But we can continue for <code>s1</code> by extending it to <code>s1 = "and the cat and"</code> and so on...</p> <p>For the given dictionary, we should get the following sentences:</p> <pre><code>'and the cat and the', 'the cat and the dog', 'the cat and the cat', 'cat and the cat and' </code></pre> <p>I am trying it with recursive backtracking like following:</p> <pre><code>dictionary = {'and': ['the'], 'the': ['cat', 'dog'], 'cat': ['and']} sentence_list = [] sentence_length = 5 def recurse(split_sentence,key): if len(split_sentence) &gt;= sentence_length: sentence_list.append(split_sentence) return elif key not in dictionary.keys(): return else: for value in dictionary[key]: split = split_sentence split.append(value) recurse(split,value) return for key in dictionary.keys(): split_sentence = [] recurse(split_sentence, key) for elem in sentence_list: sentence = " ".join(elem) print sentence + "\n" </code></pre> <p>But it's giving me output </p> <pre><code>the cat and the cat dog dog the cat and the cat dog dog the cat and the cat dog dog cat and the cat and dog dog cat and the cat and dog dog cat and the cat and dog dog and the cat and the dog and the cat and the dog </code></pre> <p>Could someone help me figure out where I am doing it wrong?</p>
0
2016-10-05T00:10:37Z
39,863,733
<p>The problem is that you are modifying <code>split_sentence</code> in your loop around the recursive call; assigning it to another variable just means you have a new name for the same list. Making a new list to make the recursive call with can be done like so:</p> <pre><code> for value in dictionary[key]: recurse(split_sentence+[value],value) </code></pre>
1
2016-10-05T00:33:25Z
[ "python", "dictionary", "recursion", "dynamic-programming", "backtracking" ]
context manager I/O operation in file
39,863,577
<p>I am using a context manager to wrap the text which would show in terminal and write to file at the same time.</p> <p>I faced this problem and got the solution, please check <a href="http://stackoverflow.com/questions/39629435/writing-terminal-output-to-terminal-and-to-a-file">Writing terminal output to terminal and to a file?</a></p> <p>Cannot change the functions (etc. func1 and func2) problem is after the 'with' statement any output as sys.stdout.write its showing value error: I/O operation in closed file</p> <p>sample code:</p> <pre><code>import sys, datetime class FileWrite(object): def __init__(self,log_file_name, stdout): self.log_file_name = log_file_name self.stdout = stdout def __enter__(self): self.log_file = open(self.log_file_name, 'a', 0) return self def __exit__(self, exc_type, exc_value, exc_traceback): self.log_file.close() def write(self, data): self.log_file.write(data) self.stdout.write(data) self.stdout.flush() def func1(): sys.stdout.write('A') def func2(): sys.stdout.write('B') def main(): with FileWrite(..........., sys.stdout) as sys.stdout: func1() func2() sys.stdout.write('test') main() ............................ # both output A and B is showing in terminal and writing in file ............................ # writing 'test' only in terminal...... I/O operation in closed file </code></pre>
0
2016-10-05T00:12:25Z
39,863,589
<p><code>with FileWrite(..........., sys.stdout) as sys.stdout:</code></p> <p>You are overwriting <code>sys.stdout</code>, just chose a real name for your file like <code>output</code> or whatever but <code>sys.stdout</code>.</p> <p>Example:</p> <pre><code>with FileWrite(..........., sys.stdout) as output: output.write('A') output.write('B') sys.stdout.write("test") </code></pre> <hr> <p><strong>EDIT</strong><br> Since you don't really want to write on the standard output, pass your <code>FileWrite</code> instance as parameter to your methods.</p> <pre><code>def func1(output): output.write('A') with FileWrite(..........., sys.stdout) as output: func1(output) </code></pre> <p>Do the same for func2.</p>
1
2016-10-05T00:14:15Z
[ "python" ]
context manager I/O operation in file
39,863,577
<p>I am using a context manager to wrap the text which would show in terminal and write to file at the same time.</p> <p>I faced this problem and got the solution, please check <a href="http://stackoverflow.com/questions/39629435/writing-terminal-output-to-terminal-and-to-a-file">Writing terminal output to terminal and to a file?</a></p> <p>Cannot change the functions (etc. func1 and func2) problem is after the 'with' statement any output as sys.stdout.write its showing value error: I/O operation in closed file</p> <p>sample code:</p> <pre><code>import sys, datetime class FileWrite(object): def __init__(self,log_file_name, stdout): self.log_file_name = log_file_name self.stdout = stdout def __enter__(self): self.log_file = open(self.log_file_name, 'a', 0) return self def __exit__(self, exc_type, exc_value, exc_traceback): self.log_file.close() def write(self, data): self.log_file.write(data) self.stdout.write(data) self.stdout.flush() def func1(): sys.stdout.write('A') def func2(): sys.stdout.write('B') def main(): with FileWrite(..........., sys.stdout) as sys.stdout: func1() func2() sys.stdout.write('test') main() ............................ # both output A and B is showing in terminal and writing in file ............................ # writing 'test' only in terminal...... I/O operation in closed file </code></pre>
0
2016-10-05T00:12:25Z
39,863,830
<p>You don't really need (or want) to use <code>as</code> here. If the goal is to convert any write to <code>sys.stdout</code> to a write to both <code>sys.stdout</code> and your log file, you need to backup <code>sys.stdout</code> on <code>__enter__</code> and restore it on <code>__exit__</code>, but don't explicitly pass <code>sys.stdout</code> to the constructor, and don't use the <code>__enter__</code> return to replace <code>sys.stdout</code>, because that bypasses the <code>__enter__</code>/<code>__exit__</code> code. Instead, have <code>__enter__</code> and <code>__exit__</code> do the replacing work for you:</p> <pre><code>class tee_stdout(object): def __init__(self, log_file_name): self.log_file_name = log_file_name self.stdout = None def __enter__(self): self.log_file = open(self.log_file_name, 'a', 0) # Replace sys.stdout while backing it up self.stdout, sys.stdout = sys.stdout, self def __exit__(self, exc_type, exc_value, exc_traceback): sys.stdout = self.stdout # Restore original sys.stdout self.log_file.close() def write(self, data): self.log_file.write(data) self.stdout.write(data) self.stdout.flush() </code></pre> <p>Now, usage is just:</p> <pre><code> with tee_stdout(logfilename): ... do stuff that uses sys.stdout, explicitly or implicitly ... ... when block exits, sys.stdout restored, so normal behavior resumes ... </code></pre> <p>Note: If you're targeting Python 3.4 or higher, I'd recommend implementing the class with just <code>write</code>, and then using <code>contextlib.redirect_stdout</code> to avoid reinventing the wheel:</p> <pre><code>from contextlib import redirect_stdout class tee_output: def __init__(self, *targets): self.targets = targets def write(self, data): for tgt in self.targets: tgt.write(data) tgt.flush() with open(logfilename, 'a') as log, redirect_stdout(tee_output(log, sys.stdout)): ... logs to logfilename and sys.stdout when sys.stdout written to ... ... undoes redirection ... </code></pre> <p>Note: All the above aside, usually, you want to just use <a href="https://docs.python.org/3/library/logging.html" rel="nofollow">the <code>logging</code> module</a> and logger methods for stuff like this. You can pre-configure different loggers, some that go to <code>sys.stdout</code>, some that go to a log file and <code>sys.stdout</code>, some that go just to log files, and use the appropriate one when needed.</p>
2
2016-10-05T00:48:29Z
[ "python" ]
How to scrape 'Click to Display' fields with BeautifulSoup
39,863,607
<p>I am trying to scrape the number of schools and names of schools that basketball players get offers from verbalcommits.com</p> <p>Using this page as an example: <a href="http://www.verbalcommits.com/players/jarrey-foster" rel="nofollow">http://www.verbalcommits.com/players/jarrey-foster</a></p> <p>It's easy to access the first offer (SMU) but all of the other offers are hidden behind the "Show other offers" button. When I inspect the page, I can see the offers but my scraper doesn't get to them. I've been using the following:</p> <pre><code>page=urllib.request.urlopen("http://www.verbalcommits.com/players/jarrey-foster") #opens page soup = BeautifulSoup(page, 'html.parser') #makes page into a BS python object schools = soup.body.findAll('span',{"class":"team_name"}) print(schools) </code></pre> <p>This returns the first span that has the team name in it, but not the rest of the spans that are hidden. What do I need to add to access the rest of the page that is hidden?</p>
1
2016-10-05T00:16:51Z
39,863,674
<p>You can't get other data because when you click button then JavaScript reads it from server from </p> <p><a href="http://www.verbalcommits.com/player_divs/closed_offers?player_id=17766&amp;_=1475626846752" rel="nofollow">http://www.verbalcommits.com/player_divs/closed_offers?player_id=17766&amp;_=1475626846752</a></p> <p>Now you can use this url with BS to get data.</p> <p>I used <code>Firebug</code> in Firefox or <code>Developer Tools</code> in Chrome to find this url.</p> <hr> <p><strong>EDIT:</strong> inside HTML I found <code>data-player-id="17766"</code> - it is first argument in above url. Maybe you can find second argument so you could generate url using Python.</p> <hr> <p><strong>EDIT:</strong> I checked url </p> <p><a href="http://www.verbalcommits.com/player_divs/closed_offers?player_id=17766" rel="nofollow">http://www.verbalcommits.com/player_divs/closed_offers?player_id=17766</a> </p> <p>and it gives the same data so you don't need second argument.</p>
1
2016-10-05T00:26:01Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
How to scrape 'Click to Display' fields with BeautifulSoup
39,863,607
<p>I am trying to scrape the number of schools and names of schools that basketball players get offers from verbalcommits.com</p> <p>Using this page as an example: <a href="http://www.verbalcommits.com/players/jarrey-foster" rel="nofollow">http://www.verbalcommits.com/players/jarrey-foster</a></p> <p>It's easy to access the first offer (SMU) but all of the other offers are hidden behind the "Show other offers" button. When I inspect the page, I can see the offers but my scraper doesn't get to them. I've been using the following:</p> <pre><code>page=urllib.request.urlopen("http://www.verbalcommits.com/players/jarrey-foster") #opens page soup = BeautifulSoup(page, 'html.parser') #makes page into a BS python object schools = soup.body.findAll('span',{"class":"team_name"}) print(schools) </code></pre> <p>This returns the first span that has the team name in it, but not the rest of the spans that are hidden. What do I need to add to access the rest of the page that is hidden?</p>
1
2016-10-05T00:16:51Z
39,875,254
<p>To elaborate more on <a href="http://stackoverflow.com/a/39863674/771848">@furas's great answer</a>. Here is how you can extract the player id and make a second request to get the "closed offers". For this, we are going to <a class='doc-link' href="http://stackoverflow.com/documentation/python/1792/web-scraping-with-python/8152/maintaining-web-scraping-session-with-requests#t=201610051326031908792">maintain a web-scraping session with <code>requests</code></a>:</p> <pre><code>import requests from bs4 import BeautifulSoup with requests.Session() as session: response = session.get("http://www.verbalcommits.com/players/jarrey-foster") # get the player id soup = BeautifulSoup(response.content, "html.parser") player_id = soup.select_one("h1.player-name").get("data-player-id") # get closed offers response = session.get("http://www.verbalcommits.com/player_divs/closed_offers", params={"player_id": player_id}) soup = BeautifulSoup(response.content, "html.parser") # print team names for team in soup.select(".team_name"): print(team.get_text()) </code></pre> <p>Prints team names for demonstration purposes:</p> <pre><code>UTEP Sam Houston State New Hampshire Rice Temple Liberty UL Lafayette </code></pre>
2
2016-10-05T13:26:07Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Twitter Streaming without Keyword
39,863,716
<p>I'm trying to stream Twitter using Tweepy and I was wondering if it is possible to stream without giving a keyword? Therefore I would be able to stream all tweets instead of only ones with a given keyword. The code I'm following can be found here: <a href="https://gist.github.com/bonzanini/af0463b927433c73784d" rel="nofollow">https://gist.github.com/bonzanini/af0463b927433c73784d</a> Someone commented saying that this isn't possible and I just wanted to double check that this is true or if there is a work around without having to buy the Firehose.</p>
0
2016-10-05T00:31:26Z
39,867,744
<p>You can access a <em>sample</em> of all tweets by using this endpoint</p> <p><code>https://dev.twitter.com/streaming/reference/get/statuses/sample</code></p> <p>As is made clear in <a href="https://dev.twitter.com/streaming/reference/get/statuses/sample" rel="nofollow">the documentation</a>:</p> <blockquote> <p>Returns a small random sample of all public statuses. </p> </blockquote> <p>If you want <em>all</em> tweets then, yes, you need to pay for access.</p>
1
2016-10-05T07:21:40Z
[ "python", "twitter", "tweepy" ]
How can I log outside of main Flask module?
39,863,718
<p>I have a Python Flask application, the entry file configures a logger on the app, like so:</p> <pre><code>app = Flask(__name__) handler = logging.StreamHandler(sys.stdout) app.logger.addHandler(handler) app.logger.setLevel(logging.DEBUG) </code></pre> <p>I then do a bunch of logging using </p> <p><code>app.logger.debug("Log Message")</code></p> <p>which works fine. However, I have a few API functions like:</p> <pre><code>@app.route('/api/my-stuff', methods=['GET']) def get_my_stuff(): db_manager = get_manager() query = create_query(request.args) service = Service(db_manager, query) app.logger.debug("Req: {}".format(request.url)) </code></pre> <p>What I would like to know is how can I do logging within that <code>Service</code> module/python class. Do I have to pass the app to it? That seems like a bad practice, but I don't know how to get a handle to the app.logger from outside of the main Flask file...</p>
3
2016-10-05T00:31:36Z
39,863,901
<p>Even though this is a possible duplicate I want to write out a tiny bit of python logging knowledge. </p> <p>DON'T pass loggers around. You can always access any given logger by <code>logging.getLogger(&lt;log name as string&gt;)</code>. By default it looks like* flask uses the name you provide to the <code>Flask</code> class. </p> <p>So if your main module is called 'my_tool', you would want to do <code>logger = logging.getLogger('my_tool')</code>in the <code>Service</code> module. </p> <p>To add onto that, I like to be explicit about naming my loggers and packages, so I would do <code>Flask('my_tool')</code>** and in other modules, have sub level loggers like. <code>logger = logging.getLogger('my_tool.services')</code> that all use the same root logger (and handlers).</p> <p>* No experience, based off other answer. </p> <p>** Again, don't use flask, dk if that is good practice</p> <p><strong>Edit: Super simple stupid example</strong></p> <p><strong>Main Flask app</strong></p> <pre><code>import sys import logging import flask from module2 import hi app = flask.Flask('tester') handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s')) app.logger.addHandler(handler) app.logger.setLevel(logging.DEBUG) @app.route("/index") def index(): app.logger.debug("TESTING!") hi() return "hi" if __name__ == '__main__': app.run() </code></pre> <p><strong>module2</strong></p> <pre><code>import logging log = logging.getLogger('tester.sub') def hi(): log.warning('warning test') </code></pre> <p><strong>Outputs</strong></p> <pre><code>127.0.0.1 - - [04/Oct/2016 20:08:29] "GET /index HTTP/1.1" 200 - 2016-10-04 20:08:29,098 - tester - DEBUG - TESTING! 2016-10-04 20:08:29,098 - tester.sub - WARNING - warning test </code></pre> <p><strong>Edit 2: Messing with subloggers</strong> </p> <p>Totally unneeded, just for general knowledge. </p> <p>By defining a child logger, done by adding a <code>.something</code> after the root logger name in <code>logging.getLogger('root.something')</code> it gives you basiclly a different namespace to work with. </p> <p>I personally like using it to group functionality in logging. So have some <code>.tool</code> or <code>.db</code> to know what type of code is logging. But it also allows so that those child loggers can have their own handlers. So if you only want some of your code to print to <code>stderr</code>, or to a log you can do so. Here is an example with a modified <code>module2</code>.</p> <p><strong>module2</strong> </p> <pre><code>import logging import sys log = logging.getLogger('tester.sub') handler = logging.StreamHandler(sys.stderr) handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s')) log.addHandler(handler) log.setLevel(logging.INFO) def hi(): log.warning("test") </code></pre> <p>Output</p> <pre><code>127.0.0.1 - - [04/Oct/2016 20:23:18] "GET /index HTTP/1.1" 200 - 2016-10-04 20:23:18,354 - tester - DEBUG - TESTING! tester.sub - WARNING - test 2016-10-04 20:23:18,354 - tester.sub - WARNING - test </code></pre>
2
2016-10-05T00:58:15Z
[ "python", "logging", "flask" ]
Extract Text from Javascript using Python
39,863,723
<p>I've been looking at examples of how to do this but can't quite figure it out. I'm using beautifulsoup to scrape some data - I am able to use it to find the data I want, but it is contained in the following block of code. I'm trying to extract the timestamp information from it. I have a feeling regular expressions work here but I can't seem to figure it out - any suggestions?? </p> <pre><code> &lt;script class="code" type="text/javascript"&gt; $(document).ready(function(){ line1 = [['2009-02-23 10 AM', 5203], ['2009-02-08 10 AM', 3898], ['2009-02-09 10 AM', 4923], ['2009-02-22 10 AM', 3682], ['2009-02-21 10 AM', 3238], ['2009-02-20 10 AM', 4648]]; options1 = { etc other text } }); &lt;/script&gt; </code></pre>
0
2016-10-05T00:32:20Z
39,863,780
<p>You can't use BS to get this data - BS works only with HTML/XML, not JavaScript. </p> <p>You have to use <code>regular expressions</code> or standart string functions.</p> <hr> <p><strong>EDIT:</strong></p> <pre><code>text = '''&lt;script class="code" type="text/javascript"&gt; $(document).ready(function(){ line1 = [['2009-02-23 10 AM', 5203], ['2009-02-08 10 AM', 3898], ['2009-02-09 10 AM', 4923], ['2009-02-22 10 AM', 3682], ['2009-02-21 10 AM', 3238], ['2009-02-20 10 AM', 4648]]; options1 = { etc other text } }); &lt;/script&gt;''' import re re.findall("'([^']*)'", text) </code></pre> <p>result:</p> <pre><code>['2009-02-23 10 AM', '2009-02-08 10 AM', '2009-02-09 10 AM', '2009-02-22 10 AM', '2009-02-21 10 AM', '2009-02-20 10 AM'] </code></pre>
1
2016-10-05T00:39:59Z
[ "javascript", "python", "beautifulsoup" ]
Extract Text from Javascript using Python
39,863,723
<p>I've been looking at examples of how to do this but can't quite figure it out. I'm using beautifulsoup to scrape some data - I am able to use it to find the data I want, but it is contained in the following block of code. I'm trying to extract the timestamp information from it. I have a feeling regular expressions work here but I can't seem to figure it out - any suggestions?? </p> <pre><code> &lt;script class="code" type="text/javascript"&gt; $(document).ready(function(){ line1 = [['2009-02-23 10 AM', 5203], ['2009-02-08 10 AM', 3898], ['2009-02-09 10 AM', 4923], ['2009-02-22 10 AM', 3682], ['2009-02-21 10 AM', 3238], ['2009-02-20 10 AM', 4648]]; options1 = { etc other text } }); &lt;/script&gt; </code></pre>
0
2016-10-05T00:32:20Z
39,875,529
<p>One another alternative to using regular expressions to parse javascript code would be to use a JavaScript parser like <a href="https://pypi.python.org/pypi/slimit" rel="nofollow"><code>slimit</code></a>. Working code:</p> <pre><code>import json from bs4 import BeautifulSoup from slimit import ast from slimit.parser import Parser from slimit.visitors import nodevisitor data = """&lt;script class="code" type="text/javascript"&gt; $(document).ready(function(){ line1 = [['2009-02-23 10 AM', 5203], ['2009-02-08 10 AM', 3898], ['2009-02-09 10 AM', 4923], ['2009-02-22 10 AM', 3682], ['2009-02-21 10 AM', 3238], ['2009-02-20 10 AM', 4648]]; options1 = {}; }); &lt;/script&gt;""" soup = BeautifulSoup(data, "html.parser") parser = Parser() tree = parser.parse(soup.script.get_text()) for node in nodevisitor.visit(tree): if isinstance(node, ast.Assign) and getattr(node.left, 'value', '') == 'line1': values = json.loads(node.right.to_ecma().replace("'", '"').strip()) print(values) break </code></pre> <p>Prints a Python list:</p> <pre><code>[[u'2009-02-23 10 AM', 5203], [u'2009-02-08 10 AM', 3898], [u'2009-02-09 10 AM', 4923], [u'2009-02-22 10 AM', 3682], [u'2009-02-21 10 AM', 3238], [u'2009-02-20 10 AM', 4648]] </code></pre>
0
2016-10-05T13:37:43Z
[ "javascript", "python", "beautifulsoup" ]
Handle Fortran Character Arrays from Python with F2PY
39,863,836
<p>I have a legacy Fortran library I've wrapped with F2PY. However, I'm at a loss for how to properly read character arrays declared as module data, from Python. The data data comes through, but the array is transposed in such a way that it is indiscernible. How can I get Numpy to correctly handle my array? I'd be satisfied with a 2 dimensional array of characters if they were in an intelligible order.</p> <p>The character arrays are declared and populated in Fortran like so:</p> <pre><code>module plot_mod implicit none CHARACTER*4, JSP(39) ... JSP = (/ &amp; 'SF ', 'WF ', 'GF ', 'AF ', 'RF ', 'SS ', 'NF ', &amp; 'YC ', 'IC ', 'ES ', 'LP ', 'JP ', 'SP ', 'WP ', &amp; 'PP ', 'DF ', 'RW ', 'RC ', 'WH ', 'MH ', 'BM ', &amp; 'RA ', 'WA ', 'PB ', 'GC ', 'AS ', 'CW ', 'WO ', &amp; 'WJ ', 'LL ', 'WB ', 'KP ', 'PY ', 'DG ', 'HT ', &amp; 'CH ', 'WI ', ' ', 'OT '/) end module plot_mod </code></pre> <p>In Python 2.7 (previous version of numpy) I could do this:</p> <pre><code>x = numpy.frombuffer(fvslib.plot_mod.jsp.data, numpy.dtype('a4')) </code></pre> <p>But now Python (3.4.4) and Numpy (1.10.4) raises an error, <code>BufferError: memoryview: underlying buffer is not C-contiguous</code>.</p> <p>I know I should be able to get Numpy to handle this for me by reshaping, or using stride tricks, but I can't seem to figure it out. The array is reported as F-contiguous, so at least that seems correct.</p> <p>If I simply print the array it looks like this:</p> <pre><code>array([[b'S', b' ', b' ', b'L'], [b'F', b'L', b' ', b' '], [b' ', b'P', b'B', b' '], [b' ', b' ', b'M', b'W'], [b'W', b' ', b' ', b'B'], [b'F', b'J', b' ', b' '], [b' ', b'P', b'R', b' '], [b' ', b' ', b'A', b'K'], [b'G', b' ', b' ', b'P'], [b'F', b'S', b' ', b' '], [b' ', b'P', b'W', b' '], [b' ', b' ', b'A', b'P'], [b'A', b' ', b' ', b'Y'], [b'F', b'W', b' ', b' '], [b' ', b'P', b'P', b' '], [b' ', b' ', b'B', b'D'], [b'R', b' ', b' ', b'G'], [b'F', b'P', b' ', b' '], [b' ', b'P', b'G', b' '], [b' ', b' ', b'C', b'H'], [b'S', b' ', b' ', b'T'], [b'S', b'D', b' ', b' '], [b' ', b'F', b'A', b' '], [b' ', b' ', b'S', b'C'], [b'N', b' ', b' ', b'H'], [b'F', b'R', b' ', b' '], [b' ', b'W', b'C', b' '], [b' ', b' ', b'W', b'W'], [b'Y', b' ', b' ', b'I'], [b'C', b'R', b' ', b' '], [b' ', b'C', b'W', b' '], [b' ', b' ', b'O', b' '], [b'I', b' ', b' ', b' '], [b'C', b'W', b' ', b' '], [b' ', b'H', b'W', b' '], [b' ', b' ', b'J', b'O'], [b'E', b' ', b' ', b'T'], [b'S', b'M', b' ', b' '], [b' ', b'H', b'L', b' ']], dtype='|S1') </code></pre> <p>What I would like an array like this:</p> <pre><code>[['SF '] , ['WF '] , ['GF '] , ['AF '] , ['RF '] , ['SS '] , ['NF '] , ['YC '] , ['IC '] , ['ES '] , ['LP '] , ['JP '] , ['SP '] , ['WP '] , ['PP '] , ['DF '] , ['RW '] , ['RC '] , ['WH '] , ['MH '] , ['BM '] , ['RA '] , ['WA '] , ['PB '] , ['GC '] , ['AS '] , ['CW '] , ['WO '] , ['WJ '] , ['LL '] , ['WB '] , ['KP '] , ['PY '] , ['DG '] , ['HT '] , ['CH '] , ['WI '] , [' '] , ['OT ']] </code></pre>
1
2016-10-05T00:49:18Z
39,863,929
<p>I haven't tried running f2py on your module, but if I define the array you show as:</p> <pre><code>In [11]: s = array([[b'S', b' ', b' ', b'L'], ...: [b'F', b'L', b' ', b' '], ...: [b' ', b'P', b'B', b' '], ...: [b' ', b' ', b'M', b'W'], ...: [b'W', b' ', b' ', b'B'], ...: [b'F', b'J', b' ', b' '], ...: [b' ', b'P', b'R', b' '], ...: [b' ', b' ', b'A', b'K'], ...: [b'G', b' ', b' ', b'P'], ...: [b'F', b'S', b' ', b' '], ...: [b' ', b'P', b'W', b' '], ...: [b' ', b' ', b'A', b'P'], ...: [b'A', b' ', b' ', b'Y'], ...: [b'F', b'W', b' ', b' '], ...: [b' ', b'P', b'P', b' '], ...: [b' ', b' ', b'B', b'D'], ...: [b'R', b' ', b' ', b'G'], ...: [b'F', b'P', b' ', b' '], ...: [b' ', b'P', b'G', b' '], ...: [b' ', b' ', b'C', b'H'], ...: [b'S', b' ', b' ', b'T'], ...: [b'S', b'D', b' ', b' '], ...: [b' ', b'F', b'A', b' '], ...: [b' ', b' ', b'S', b'C'], ...: [b'N', b' ', b' ', b'H'], ...: [b'F', b'R', b' ', b' '], ...: [b' ', b'W', b'C', b' '], ...: [b' ', b' ', b'W', b'W'], ...: [b'Y', b' ', b' ', b'I'], ...: [b'C', b'R', b' ', b' '], ...: [b' ', b'C', b'W', b' '], ...: [b' ', b' ', b'O', b' '], ...: [b'I', b' ', b' ', b' '], ...: [b'C', b'W', b' ', b' '], ...: [b' ', b'H', b'W', b' '], ...: [b' ', b' ', b'J', b'O'], ...: [b'E', b' ', b' ', b'T'], ...: [b'S', b'M', b' ', b' '], ...: [b' ', b'H', b'L', b' ']], ...: dtype='|S1') </code></pre> <p>I can get an array that looks like what you want with:</p> <pre><code>In [12]: s.T.reshape(-1, 4).view('S4') Out[12]: array([[b'SF '], [b'WF '], [b'GF '], [b'AF '], [b'RF '], [b'SS '], [b'NF '], [b'YC '], [b'IC '], [b'ES '], [b'LP '], [b'JP '], [b'SP '], [b'WP '], [b'PP '], [b'DF '], [b'RW '], [b'RC '], [b'WH '], [b'MH '], [b'BM '], [b'RA '], [b'WA '], [b'PB '], [b'GC '], [b'AS '], [b'CW '], [b'WO '], [b'WJ '], [b'LL '], [b'WB '], [b'KP '], [b'PY '], [b'DG '], [b'HT '], [b'CH '], [b'WI '], [b' '], [b'OT ']], dtype='|S4') </code></pre> <p>Note that the data type is <code>'S4'</code>, to match the declared size of the Fortran array.</p> <p>That result leaves a trivial second dimension, so you might want to convert it to a one-dimensional array, e.g.</p> <pre><code>In [22]: s.T.reshape(-1, 4).view('S4')[:,0] Out[22]: array([b'SF ', b'WF ', b'GF ', b'AF ', b'RF ', b'SS ', b'NF ', b'YC ', b'IC ', b'ES ', b'LP ', b'JP ', b'SP ', b'WP ', b'PP ', b'DF ', b'RW ', b'RC ', b'WH ', b'MH ', b'BM ', b'RA ', b'WA ', b'PB ', b'GC ', b'AS ', b'CW ', b'WO ', b'WJ ', b'LL ', b'WB ', b'KP ', b'PY ', b'DG ', b'HT ', b'CH ', b'WI ', b' ', b'OT '], dtype='|S4') </code></pre>
1
2016-10-05T01:02:42Z
[ "python", "numpy", "fortran" ]
Handle Fortran Character Arrays from Python with F2PY
39,863,836
<p>I have a legacy Fortran library I've wrapped with F2PY. However, I'm at a loss for how to properly read character arrays declared as module data, from Python. The data data comes through, but the array is transposed in such a way that it is indiscernible. How can I get Numpy to correctly handle my array? I'd be satisfied with a 2 dimensional array of characters if they were in an intelligible order.</p> <p>The character arrays are declared and populated in Fortran like so:</p> <pre><code>module plot_mod implicit none CHARACTER*4, JSP(39) ... JSP = (/ &amp; 'SF ', 'WF ', 'GF ', 'AF ', 'RF ', 'SS ', 'NF ', &amp; 'YC ', 'IC ', 'ES ', 'LP ', 'JP ', 'SP ', 'WP ', &amp; 'PP ', 'DF ', 'RW ', 'RC ', 'WH ', 'MH ', 'BM ', &amp; 'RA ', 'WA ', 'PB ', 'GC ', 'AS ', 'CW ', 'WO ', &amp; 'WJ ', 'LL ', 'WB ', 'KP ', 'PY ', 'DG ', 'HT ', &amp; 'CH ', 'WI ', ' ', 'OT '/) end module plot_mod </code></pre> <p>In Python 2.7 (previous version of numpy) I could do this:</p> <pre><code>x = numpy.frombuffer(fvslib.plot_mod.jsp.data, numpy.dtype('a4')) </code></pre> <p>But now Python (3.4.4) and Numpy (1.10.4) raises an error, <code>BufferError: memoryview: underlying buffer is not C-contiguous</code>.</p> <p>I know I should be able to get Numpy to handle this for me by reshaping, or using stride tricks, but I can't seem to figure it out. The array is reported as F-contiguous, so at least that seems correct.</p> <p>If I simply print the array it looks like this:</p> <pre><code>array([[b'S', b' ', b' ', b'L'], [b'F', b'L', b' ', b' '], [b' ', b'P', b'B', b' '], [b' ', b' ', b'M', b'W'], [b'W', b' ', b' ', b'B'], [b'F', b'J', b' ', b' '], [b' ', b'P', b'R', b' '], [b' ', b' ', b'A', b'K'], [b'G', b' ', b' ', b'P'], [b'F', b'S', b' ', b' '], [b' ', b'P', b'W', b' '], [b' ', b' ', b'A', b'P'], [b'A', b' ', b' ', b'Y'], [b'F', b'W', b' ', b' '], [b' ', b'P', b'P', b' '], [b' ', b' ', b'B', b'D'], [b'R', b' ', b' ', b'G'], [b'F', b'P', b' ', b' '], [b' ', b'P', b'G', b' '], [b' ', b' ', b'C', b'H'], [b'S', b' ', b' ', b'T'], [b'S', b'D', b' ', b' '], [b' ', b'F', b'A', b' '], [b' ', b' ', b'S', b'C'], [b'N', b' ', b' ', b'H'], [b'F', b'R', b' ', b' '], [b' ', b'W', b'C', b' '], [b' ', b' ', b'W', b'W'], [b'Y', b' ', b' ', b'I'], [b'C', b'R', b' ', b' '], [b' ', b'C', b'W', b' '], [b' ', b' ', b'O', b' '], [b'I', b' ', b' ', b' '], [b'C', b'W', b' ', b' '], [b' ', b'H', b'W', b' '], [b' ', b' ', b'J', b'O'], [b'E', b' ', b' ', b'T'], [b'S', b'M', b' ', b' '], [b' ', b'H', b'L', b' ']], dtype='|S1') </code></pre> <p>What I would like an array like this:</p> <pre><code>[['SF '] , ['WF '] , ['GF '] , ['AF '] , ['RF '] , ['SS '] , ['NF '] , ['YC '] , ['IC '] , ['ES '] , ['LP '] , ['JP '] , ['SP '] , ['WP '] , ['PP '] , ['DF '] , ['RW '] , ['RC '] , ['WH '] , ['MH '] , ['BM '] , ['RA '] , ['WA '] , ['PB '] , ['GC '] , ['AS '] , ['CW '] , ['WO '] , ['WJ '] , ['LL '] , ['WB '] , ['KP '] , ['PY '] , ['DG '] , ['HT '] , ['CH '] , ['WI '] , [' '] , ['OT ']] </code></pre>
1
2016-10-05T00:49:18Z
39,864,132
<p>For completeness I'll include this alternative solution. Same results as @Warren Weckesser, but requires an additional import.</p> <pre><code>from numpy.lib import stride_tricks spp = stride_tricks.as_strided(jsp, strides=(jsp.shape[1],1)) # View as S4 and strip whitespace spp = np.char.strip(spp.view('S4')) </code></pre>
0
2016-10-05T01:31:13Z
[ "python", "numpy", "fortran" ]
How do I place multiple searched tweets into string
39,863,871
<p>I have a program set up so it searches tweets based on the hashtag I give it and I can edit how many tweets to search and display but I can't figure out how to place the searched tweets into a string. this is the code I have so far</p> <pre><code> while True: for status in tweepy.Cursor(api.search, q=hashtag).items(2): tweet = [status.text] print tweet </code></pre> <p>when this is run it only outputs 1 tweet when it is set to search 2 </p>
0
2016-10-05T00:54:32Z
39,864,327
<p>Your code looks like there's nothing to break out of the <code>while</code> loop. One method that comes to mind is to set a variable to an empty list and then with each tweet, append that to the list. </p> <pre><code>foo = [] for status in tweepy.Cursor(api.search, q=hashtag).items(2): tweet = status.text foo.append(tweet) print foo </code></pre> <p>Of course, this will print a list. If you want a string instead, use the string <em>join()</em> method. Adjust the last line of code to look like this:</p> <pre><code>bar = ' '.join(foo) print bar </code></pre>
1
2016-10-05T01:59:55Z
[ "python", "string", "output", "tweepy", "tweets" ]
psycopg2 not all arguments converted during string formatting
39,863,881
<p>I am trying to use psycopg2 to insert a row into a table from a python list, but having trouble with the string formatting.</p> <p>The table has 4 columns of types (1043-varchar, 1114-timestamp, 1043-varchar, 23-int4). I have also made attempts with 1082-date instead of timestamp, and 21-int2 instead of int4.</p> <p>The following statement works fine in pgAdmin or through a psycopg2 cursor execution without string formatting:</p> <pre><code>INSERT INTO ssurgo.distmd VALUES ('5', '2015-01-01', 'Successful', 4891); </code></pre> <p>However, if I do:</p> <pre><code>sql_text = "INSERT INTO ssurgo.distmd VALUES %s ;" data = ['5', '2015-01-01', 'Successful', 4891] data[1] = date.today() # ensure psycopg2 recognizes a date using datetime print(curs.mogrify(sql_text, data)) </code></pre> <p>I get:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>I get the same error if I keep the date as a '2015-01-01' string instead of a datetime.date object, and if I use curs.execute(sql_text, data) rather than mogrify.</p> <p>I am passing a list, so I don't think this is related to the more common single tuple error I found in other questions that is necessary to create a non-string sequence, and explicitly converting to a tuple did not fix the error.</p> <p>Does anyone know why the psycopg2 string formatting is giving an error?</p>
0
2016-10-05T00:55:56Z
39,864,325
<p>Thanks to @Keith for the help. I was expecting psycopg2 to do more than it actually does. Since I am developing a script to iterate through several hundred text files for import to different tables, I want something that can work with different table sizes and made the following modification:</p> <pre><code>sql_text = "INSERT INTO ssurgo.distmd VALUES (%s);" data = ['5', '2015-01-01', 'Successful', 4891] data[1] = date.today() # ensure psycopg2 recognizes a date using datetime placehold = ['%s' for _fld in data] sql_text = sql_text % ', '.join(placehold) print(curs.mogrify(sql_text, data)) </code></pre>
0
2016-10-05T01:59:22Z
[ "python", "postgresql", "python-2.7", "psycopg2" ]
psycopg2 not all arguments converted during string formatting
39,863,881
<p>I am trying to use psycopg2 to insert a row into a table from a python list, but having trouble with the string formatting.</p> <p>The table has 4 columns of types (1043-varchar, 1114-timestamp, 1043-varchar, 23-int4). I have also made attempts with 1082-date instead of timestamp, and 21-int2 instead of int4.</p> <p>The following statement works fine in pgAdmin or through a psycopg2 cursor execution without string formatting:</p> <pre><code>INSERT INTO ssurgo.distmd VALUES ('5', '2015-01-01', 'Successful', 4891); </code></pre> <p>However, if I do:</p> <pre><code>sql_text = "INSERT INTO ssurgo.distmd VALUES %s ;" data = ['5', '2015-01-01', 'Successful', 4891] data[1] = date.today() # ensure psycopg2 recognizes a date using datetime print(curs.mogrify(sql_text, data)) </code></pre> <p>I get:</p> <pre><code>TypeError: not all arguments converted during string formatting </code></pre> <p>I get the same error if I keep the date as a '2015-01-01' string instead of a datetime.date object, and if I use curs.execute(sql_text, data) rather than mogrify.</p> <p>I am passing a list, so I don't think this is related to the more common single tuple error I found in other questions that is necessary to create a non-string sequence, and explicitly converting to a tuple did not fix the error.</p> <p>Does anyone know why the psycopg2 string formatting is giving an error?</p>
0
2016-10-05T00:55:56Z
39,869,263
<p>You can keep your original code but pass a tuple in instead of a list:</p> <pre><code>sql_text = "INSERT INTO ssurgo.distmd VALUES %s ;" data = ('5', date.today(), 'Successful', 4891) print(curs.mogrify(sql_text, [data])) </code></pre> <p>Notice that you are passing a single value so it is necessary to wrap it in an iterable which is what Psycopg expects. The tuple will be adapted by Psycopg to the correct <code>values</code> syntax: a record</p>
0
2016-10-05T08:43:54Z
[ "python", "postgresql", "python-2.7", "psycopg2" ]
/usr/bin/env: python, No such file or directory
39,863,896
<p>I write code working with mapreduce in Ubuntu System in Vmware. Now I have two snippets of code with the same header but one is right and another one report </p> <pre><code>/usr/bin/env: python : No such file or directory </code></pre> <p>error. This is the one report error:</p> <pre><code>#!/usr/bin/env python import sys if __name__ == '__main__': rowNum = 100 colNum = 100 for line in sys.stdin: type, row, col, val = line.strip().split() if type == 'A': for k in range(colNum): print '%s,%s\t%s:%s,%s' % (row, k, type, col, val) elif type == 'B': for k in range(rowNum): #index1, index2, element = line.split(',') print '%s,%s\t%s:%s,%s' % (k, col, type, row, val) else: continue </code></pre> <p>This is correct one. It works well.</p> <pre><code>#!/usr/bin/env python import sys # input comes from STDIN (standard input) if __name__ == '__main__': for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # split the line into words words = line.split() # increase counters for word in words: # write the results to STDOUT (standard output); # what we output here will be the input for the # Reduce step, i.e. the input for reducer.py # # tab-delimited; the trivial word count is 1 print '%s\t%s' % (word, 1) </code></pre> <p>I search the whole website and try their method to fix it. But none of them worked, including finding the path is correct or not, checking whether there is a carriage return. I was stun in them whole day because they have the same header but one can not find it.</p>
-1
2016-10-05T00:57:34Z
39,864,047
<p>You have an colon : after the /usr/bin/env you need to remove it.</p>
-1
2016-10-05T01:21:18Z
[ "python", "shell" ]
/usr/bin/env: python, No such file or directory
39,863,896
<p>I write code working with mapreduce in Ubuntu System in Vmware. Now I have two snippets of code with the same header but one is right and another one report </p> <pre><code>/usr/bin/env: python : No such file or directory </code></pre> <p>error. This is the one report error:</p> <pre><code>#!/usr/bin/env python import sys if __name__ == '__main__': rowNum = 100 colNum = 100 for line in sys.stdin: type, row, col, val = line.strip().split() if type == 'A': for k in range(colNum): print '%s,%s\t%s:%s,%s' % (row, k, type, col, val) elif type == 'B': for k in range(rowNum): #index1, index2, element = line.split(',') print '%s,%s\t%s:%s,%s' % (k, col, type, row, val) else: continue </code></pre> <p>This is correct one. It works well.</p> <pre><code>#!/usr/bin/env python import sys # input comes from STDIN (standard input) if __name__ == '__main__': for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # split the line into words words = line.split() # increase counters for word in words: # write the results to STDOUT (standard output); # what we output here will be the input for the # Reduce step, i.e. the input for reducer.py # # tab-delimited; the trivial word count is 1 print '%s\t%s' % (word, 1) </code></pre> <p>I search the whole website and try their method to fix it. But none of them worked, including finding the path is correct or not, checking whether there is a carriage return. I was stun in them whole day because they have the same header but one can not find it.</p>
-1
2016-10-05T00:57:34Z
39,866,726
<p>The fact that the error message prints the word 'python' in one line and the ': No such file or directory' in the next line, suggests that there is some invisible character after <em>python</em>. Do a hexdump of your file to find out.</p>
0
2016-10-05T06:20:58Z
[ "python", "shell" ]
create sub lists by grouping with conditional check on two consecutive zeros
39,863,989
<p>I have a list:</p> <pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10] </code></pre> <p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p> <p>so my intermediate list would like </p> <pre><code>newlst = [-7,-8,-4,[-6,-4,-29,-10,-16],[2,3,18,-1,-2],[21,10,-10,-12,3,-5,-10]] </code></pre> <p>whereas the final output will be sum of sublists:</p> <pre><code>[-7,-8,-4,-65,18,-3] </code></pre> <p>I tried using the index number in a for loop with enumerate but i'm not getting my desired output.</p>
2
2016-10-05T01:12:57Z
39,864,197
<p>Here is an option with a <code>for</code> loop:</p> <pre><code>zeros = 0 result = [0] for i in lst: if i == 0: zeros += 1 elif zeros &gt;= 2: # if there are more than two zeros, append the new # element to the result result.append(i) zeros = 0 else: # Otherwise add it to the last element result[-1] += i zeros = 0 result # [-7, -8, -4, -65, 20, -3] </code></pre> <p>To get the corresponding index, you can use <code>enumerate</code>:</p> <pre><code>zeros = 0 reSum = [0] reInd = [[]] for i, v in enumerate(lst): if v == 0: zeros += 1 elif zeros &gt;= 2: zeros = 0 reSum.append(v) reInd.append([i]) ​ else: zeros = 0 reSum[-1] += v reInd[-1] += [i] reSum # [-7, -8, -4, -65, 20, -3] reInd # [[1], # [4], # [7], # [11, 13, 14, 15, 17], # [20, 21, 23, 24, 25], # [32, 33, 34, 36, 37, 38, 39]] </code></pre>
2
2016-10-05T01:41:45Z
[ "python", "python-2.7" ]
create sub lists by grouping with conditional check on two consecutive zeros
39,863,989
<p>I have a list:</p> <pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10] </code></pre> <p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p> <p>so my intermediate list would like </p> <pre><code>newlst = [-7,-8,-4,[-6,-4,-29,-10,-16],[2,3,18,-1,-2],[21,10,-10,-12,3,-5,-10]] </code></pre> <p>whereas the final output will be sum of sublists:</p> <pre><code>[-7,-8,-4,-65,18,-3] </code></pre> <p>I tried using the index number in a for loop with enumerate but i'm not getting my desired output.</p>
2
2016-10-05T01:12:57Z
39,864,265
<p>I group pairs of adjacent numbers by whether they hold any truth. Then take the truthy groups and sum them. Might be a bit too complicated, but I like using the <code>any</code> key.</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; [sum(a for a, _ in g) for k, g in groupby(zip(lst, lst[1:] + [0]), any) if k] [-7, -8, -4, -65, 20, -3] </code></pre> <p>(Thanks to blhsing and ShadowRanger for improvements.)</p> <p>Bit shorter way to turn the pairs back into singles (first is Python 2, second is Python 3):</p> <pre><code>&gt;&gt;&gt; [sum(zip(*g)[0]) for k, g in groupby(zip(lst, lst[1:] + [0]), any) if k] &gt;&gt;&gt; [sum(next(zip(*g))) for k, g in groupby(zip(lst, lst[1:] + [0]), any) if k] </code></pre>
6
2016-10-05T01:48:47Z
[ "python", "python-2.7" ]
create sub lists by grouping with conditional check on two consecutive zeros
39,863,989
<p>I have a list:</p> <pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10] </code></pre> <p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p> <p>so my intermediate list would like </p> <pre><code>newlst = [-7,-8,-4,[-6,-4,-29,-10,-16],[2,3,18,-1,-2],[21,10,-10,-12,3,-5,-10]] </code></pre> <p>whereas the final output will be sum of sublists:</p> <pre><code>[-7,-8,-4,-65,18,-3] </code></pre> <p>I tried using the index number in a for loop with enumerate but i'm not getting my desired output.</p>
2
2016-10-05T01:12:57Z
39,864,268
<p>Cheesy solution if your values all occur in <code>range(-128, 128)</code> is to use the <code>split</code> and <code>replace</code> methods of <code>bytearray</code> (which conveniently converts to and from <code>int</code>) to do the splitting:</p> <pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10] # Adjust all values up by 0x80 so they fall in bytearray's expected 0-255 range bts = bytearray(x + 0x80 for x in lst) # Split on double \x80 (the value of 0 after adjustment) # then remove single \x80 from each part parts = [b.replace(b'\x80', b'') for b in bts.split(b'\x80\x80')] # Undo adjustment and unpack (and filter empty sublists out completely) newlst = [b[0] - 0x80 if len(b) == 1 else [x - 0x80 for x in b] for b in parts if b] # Or to just get the sums, no need to create newlst, just filter and sum en masse: sums = [sum(b) - 0x80 * len(b) for b in parts if b] </code></pre>
0
2016-10-05T01:49:30Z
[ "python", "python-2.7" ]
create sub lists by grouping with conditional check on two consecutive zeros
39,863,989
<p>I have a list:</p> <pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10] </code></pre> <p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p> <p>so my intermediate list would like </p> <pre><code>newlst = [-7,-8,-4,[-6,-4,-29,-10,-16],[2,3,18,-1,-2],[21,10,-10,-12,3,-5,-10]] </code></pre> <p>whereas the final output will be sum of sublists:</p> <pre><code>[-7,-8,-4,-65,18,-3] </code></pre> <p>I tried using the index number in a for loop with enumerate but i'm not getting my desired output.</p>
2
2016-10-05T01:12:57Z
39,864,396
<pre><code>list = lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10] lastElement = None new_list=[] sub_list=[] for element in list: if element == 0 == lastElement: if sub_list == []: continue new_list.append(sub_list) sub_list = [] elif element == 0: pass else: sub_list.append(element) lastElement = element new_list.append(sub_list) print(new_list) [[-7], [-8], [-4], [-6, -4, -29, -10, -16], [2, 3, 18, -1, -2], [21, 10, -10, -12, 3, -5, -10]] </code></pre>
0
2016-10-05T02:08:59Z
[ "python", "python-2.7" ]
create sub lists by grouping with conditional check on two consecutive zeros
39,863,989
<p>I have a list:</p> <pre><code>lst = [0, -7, 0, 0, -8, 0, 0, -4, 0, 0, 0, -6, 0, -4, -29, -10, 0, -16, 0, 0, 2, 3, 0, 18, -1, -2, 0, 0, 0, 0, 0, 0, 21, 10, -10, 0, -12, 3, -5, -10] </code></pre> <p>I want to create group of sublists with conditional break when a value is followed by two consecutive zeros.</p> <p>so my intermediate list would like </p> <pre><code>newlst = [-7,-8,-4,[-6,-4,-29,-10,-16],[2,3,18,-1,-2],[21,10,-10,-12,3,-5,-10]] </code></pre> <p>whereas the final output will be sum of sublists:</p> <pre><code>[-7,-8,-4,-65,18,-3] </code></pre> <p>I tried using the index number in a for loop with enumerate but i'm not getting my desired output.</p>
2
2016-10-05T01:12:57Z
39,867,407
<pre><code>map(lambda x:eval(re.sub('^,','',x,1).replace(',','+')) if(len(x))&gt;3 else eval(x.replace(',','+')),filter(lambda x:x!=',0',re.split(r',0,0,|\|',"|".join(re.split(r'(,0){3,}',l))))) </code></pre>
0
2016-10-05T07:02:54Z
[ "python", "python-2.7" ]
What is the most efficient way to compare 45 Million rows of Text File to about 200k rows text file and produce non matches from the smaller file?
39,864,096
<p>I have a 45 million row txt file that contains hashes. What would be the most efficient way to compare the file to another file, and provide only items from the second file that are not in the large txt file? </p> <p>Current working: </p> <pre><code>comm -13 largefile.txt smallfile.txt &gt;&gt; newfile.txt </code></pre> <p>This works pretty fast but I am looking to push this into python to run regardless of os? </p> <p>Attempted with memory issues:</p> <pre><code>tp = pd.read_csv(r'./large file.txt',encoding='iso-8859-1', iterator=True, chunksize=50000) full = pd.concat(tp, ignore_index=True)` </code></pre> <p>This method taps me out in memory usage and generally faults for some reason. </p> <p>Example:</p> <pre><code>&lt;large file.txt&gt; hashes fffca07998354fc790f0f99a1bbfb241 fffca07998354fc790f0f99a1bbfb242 fffca07998354fc790f0f99a1bbfb243 fffca07998354fc790f0f99a1bbfb244 fffca07998354fc790f0f99a1bbfb245 fffca07998354fc790f0f99a1bbfb246 &lt;smaller file.txt&gt; hashes fffca07998354fc790f0f99a1bbfb245 fffca07998354fc790f0f99a1bbfb246 fffca07998354fc790f0f99a1bbfb247 fffca07998354fc790f0f99a1bbfb248 fffca07998354fc790f0f99a1bbfb249 fffca07998354fc790f0f99a1bbfb240 </code></pre> <p>Expected Output</p> <pre><code>&lt;new file.txt&gt; hashes fffca07998354fc790f0f99a1bbfb247 fffca07998354fc790f0f99a1bbfb248 fffca07998354fc790f0f99a1bbfb249 fffca07998354fc790f0f99a1bbfb240 </code></pre>
3
2016-10-05T01:26:35Z
39,865,301
<p>Hash table. Or in Python terms, just use a <code>set</code>.</p> <p>Put each item from the <strong><em>smaller</em></strong> file into the set. 200K items is perfectly fine. Enumerate each item in the larger file to see if it exists in the smaller file. If there is a match, remove the item from the the hash table.</p> <p>When you are done, any item remaining in the set represents an item not found in the larger file.</p> <p>My Python is a little rusty, but it would go something like this:</p> <pre><code>s = set() with open("small_file.txt") as f: content = f.readlines() for line in content: line = line.strip() s.add(line) with open("large_file.txt") as f: for line in f: if line in s: s.discard(line.strip()) for i in s: print(i) </code></pre>
1
2016-10-05T04:09:56Z
[ "python", "pandas", "iteration", "large-files" ]
What is the most efficient way to compare 45 Million rows of Text File to about 200k rows text file and produce non matches from the smaller file?
39,864,096
<p>I have a 45 million row txt file that contains hashes. What would be the most efficient way to compare the file to another file, and provide only items from the second file that are not in the large txt file? </p> <p>Current working: </p> <pre><code>comm -13 largefile.txt smallfile.txt &gt;&gt; newfile.txt </code></pre> <p>This works pretty fast but I am looking to push this into python to run regardless of os? </p> <p>Attempted with memory issues:</p> <pre><code>tp = pd.read_csv(r'./large file.txt',encoding='iso-8859-1', iterator=True, chunksize=50000) full = pd.concat(tp, ignore_index=True)` </code></pre> <p>This method taps me out in memory usage and generally faults for some reason. </p> <p>Example:</p> <pre><code>&lt;large file.txt&gt; hashes fffca07998354fc790f0f99a1bbfb241 fffca07998354fc790f0f99a1bbfb242 fffca07998354fc790f0f99a1bbfb243 fffca07998354fc790f0f99a1bbfb244 fffca07998354fc790f0f99a1bbfb245 fffca07998354fc790f0f99a1bbfb246 &lt;smaller file.txt&gt; hashes fffca07998354fc790f0f99a1bbfb245 fffca07998354fc790f0f99a1bbfb246 fffca07998354fc790f0f99a1bbfb247 fffca07998354fc790f0f99a1bbfb248 fffca07998354fc790f0f99a1bbfb249 fffca07998354fc790f0f99a1bbfb240 </code></pre> <p>Expected Output</p> <pre><code>&lt;new file.txt&gt; hashes fffca07998354fc790f0f99a1bbfb247 fffca07998354fc790f0f99a1bbfb248 fffca07998354fc790f0f99a1bbfb249 fffca07998354fc790f0f99a1bbfb240 </code></pre>
3
2016-10-05T01:26:35Z
39,865,306
<p>Haven't tested, but I think this would be non memory intensive (no idea on speed): </p> <pre><code>unique = [] with open('large_file.txt') as lf, open('small_file.txt') as sf: for small_line in sf: for large_line in lf: if small_line == large_line: break else: unique.append(small_line) lf.seek(0) </code></pre>
0
2016-10-05T04:10:21Z
[ "python", "pandas", "iteration", "large-files" ]
Remove double quotes from csv row
39,864,097
<p>I have two files: src.csv and dst.csv. The code below reads the second row from src.csv and appends it to dst.csv. The issue is the output in dst.csv is contained within double quotes (""). </p> <p>Expected result:</p> <pre><code>10, 5, 5, 10, 1 </code></pre> <p>Output:</p> <pre><code>"10, 5, 5, 10, 1" </code></pre> <p>I have tried using <code>quoting=csv.QUOTE_NONE, escapechar=' '</code> in csv.writer and it does remove the quotes though the output now contains a blank space after each csv value.</p> <p>Here is my code:</p> <pre><code>import csv with open('src.csv', 'r') as src, open('dst.csv', 'a', newline='') as dst: wr = csv.writer(dst, dialect='excel', delimiter=',', quoting=csv.QUOTE_NONE, escapechar=' ') next(src) for row in src: wr.writerow([row.rstrip('\n')]) </code></pre> <p>Any suggestions?</p>
0
2016-10-05T01:26:38Z
39,864,172
<p>I think you have to use <code>csv.reader()</code> to read row as list of number - now you read row as one string and csv.writer has to add <code>""</code> because you have <code>,</code> in this string.</p>
0
2016-10-05T01:36:58Z
[ "python", "python-3.x", "csv" ]
Remove double quotes from csv row
39,864,097
<p>I have two files: src.csv and dst.csv. The code below reads the second row from src.csv and appends it to dst.csv. The issue is the output in dst.csv is contained within double quotes (""). </p> <p>Expected result:</p> <pre><code>10, 5, 5, 10, 1 </code></pre> <p>Output:</p> <pre><code>"10, 5, 5, 10, 1" </code></pre> <p>I have tried using <code>quoting=csv.QUOTE_NONE, escapechar=' '</code> in csv.writer and it does remove the quotes though the output now contains a blank space after each csv value.</p> <p>Here is my code:</p> <pre><code>import csv with open('src.csv', 'r') as src, open('dst.csv', 'a', newline='') as dst: wr = csv.writer(dst, dialect='excel', delimiter=',', quoting=csv.QUOTE_NONE, escapechar=' ') next(src) for row in src: wr.writerow([row.rstrip('\n')]) </code></pre> <p>Any suggestions?</p>
0
2016-10-05T01:26:38Z
39,864,180
<p>You don't split the source file rows into columns so you just ended up writing a 1 column csv. Use a reader instead:</p> <pre><code>import csv with open('src.csv', 'r') as src, open('dst.csv', 'a', newline='') as dst: wr = csv.writer(dst, dialect='excel', delimiter=',', quoting=csv.QUOTE_NONE, escapechar=' ') next(src) reader = csv.reader(src) for row in reader: wr.writerow(row) </code></pre>
1
2016-10-05T01:38:42Z
[ "python", "python-3.x", "csv" ]
I want to put tickers in brackets
39,864,134
<p>I want to put AEM into brackets, so that text will look like: Agnico Eagle Mines Limited (AEM)</p> <pre><code>text = "Agnico Eagle Mines Limited AEM" def add_brackets(test): for word in test: if word.isupper(): word = "(" + word + ")" print(test) print(add_brackets(text)) </code></pre> <p>What's wrong with the code? I get the original text. </p>
0
2016-10-05T01:31:25Z
39,864,152
<p>Two things, 1 you are checking per character, not per word. 2 you are not modifying <code>text</code> you are just setting <code>word</code> and not doing anything with it. </p> <pre><code>text = "Agnico Eagle Mines Limited AEM" def add_brackets(test): outstr = "" for word in test.split(" "): if word.isupper(): outstr += " (" + word + ")" else: outstr += " " + word return outstr.strip() print(add_brackets(text)) </code></pre> <p>Edit: Fancier</p> <pre><code>text = "Agnico Eagle Mines Limited AEM" def add_brackets(test): return " ".join(["({})".format(word) if word.isupper() else word for word in test.split(" ")]) print(add_brackets(text)) </code></pre>
1
2016-10-05T01:33:49Z
[ "python" ]
I want to put tickers in brackets
39,864,134
<p>I want to put AEM into brackets, so that text will look like: Agnico Eagle Mines Limited (AEM)</p> <pre><code>text = "Agnico Eagle Mines Limited AEM" def add_brackets(test): for word in test: if word.isupper(): word = "(" + word + ")" print(test) print(add_brackets(text)) </code></pre> <p>What's wrong with the code? I get the original text. </p>
0
2016-10-05T01:31:25Z
39,887,191
<p>This would be pretty concise with a regular expression substitution:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; text = "Agnico Eagle Mines Limited AEM" &gt;&gt;&gt; re.sub(r'\b([A-Z]+)\b', r'(\1)', text) 'Agnico Eagle Mines Limited (AEM)' </code></pre> <p>This looks for multiple uppercase characters together, with word boundaries (like whitespace) on either side, then substitutes that matched group with the same text (the <code>\1</code>) with the addition of parentheses.</p> <p>In a function:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; def add_brackets(s): ... return re.sub(r'\b([A-Z]+)\b', r'(\1)', s) ... &gt;&gt;&gt; print(add_brackets(text)) Agnico Eagle Mines Limited (AEM) </code></pre>
0
2016-10-06T03:45:44Z
[ "python" ]
Renaming python.exe to python3.exe for co-existence with python2 on Windows
39,864,184
<p>I would like to install both python 2.7 and python 3.5 on my Windows 10 PC. Both python executables use the same name <code>python.exe</code>.</p> <p>Is it a good idea to change <code>python.exe</code> to <code>python3.exe</code> as a quick fix for co-existence? Are there any side-effects or other things that I need to be aware?</p>
2
2016-10-05T01:38:59Z
39,864,221
<p>You'll need to run <code>python3</code> instead of <code>python</code> if that's not obvious. This is definitely, as you described, a "quick fix" </p> <p>My suggested fix is to use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> and pass in the Python executable you would like to use as so:</p> <p><code>virtualenv -p /usr/bin/python3.5 /my/virtualenv/&gt;</code></p>
1
2016-10-05T01:43:53Z
[ "python", "windows", "python-2.7", "python-3.x" ]
Renaming python.exe to python3.exe for co-existence with python2 on Windows
39,864,184
<p>I would like to install both python 2.7 and python 3.5 on my Windows 10 PC. Both python executables use the same name <code>python.exe</code>.</p> <p>Is it a good idea to change <code>python.exe</code> to <code>python3.exe</code> as a quick fix for co-existence? Are there any side-effects or other things that I need to be aware?</p>
2
2016-10-05T01:38:59Z
39,864,232
<p>You don't need to rename anything for co-existence of different versions of Python.</p> <p>The different versions of python are installed on different folders automatically.</p> <p>When use the command prompt you can use the commands <code>py2</code> or <code>py3</code> to refer to the different versions of python. The next works too:</p> <pre><code>C:\Users\user1&gt;py -2 </code></pre> <p>and</p> <pre><code>C:\Users\user1&gt;py -3 </code></pre> <p>This also works with <code>pip2</code> and <code>pip3</code> for install new packages.</p> <p>For more details, you can read this article: <a href="https://docs.python.org/3/using/windows.html?#python-launcher-for-windows" rel="nofollow" title="Python Launcher for Windows">Python Launcher for Windows</a>.</p>
4
2016-10-05T01:45:19Z
[ "python", "windows", "python-2.7", "python-3.x" ]
How to show truncated X-axis in matplotlib (seaboard) heatmap
39,864,211
<p>I have the following image:</p> <p><a href="http://i.stack.imgur.com/sUDks.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/sUDks.jpg" alt="enter image description here"></a></p> <p>Created with this code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # create some random data data = pd.DataFrame(np.random.rand(11, 5), columns=['A', 'B', 'C', 'D', 'E'], index = ['yyyyyyyy - ' + str(x) for x in range(2000, 2011, 1)]) # plot heatmap ax = sns.heatmap(data.T) # turn the axis label for item in ax.get_yticklabels(): item.set_rotation(0) for item in ax.get_xticklabels(): item.set_rotation(90) # save figure plt.savefig('seabornPandas.png', dpi=100) plt.close() </code></pre> <p>My question is how can I adjust the image so that the truncated x-axis showed its full string? </p>
0
2016-10-05T01:43:04Z
39,864,505
<p>There's a convenient way to do this through a <code>subplots_adjust</code> method: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # create some random data data = pd.DataFrame(np.random.rand(11, 5), columns=['A', 'B', 'C', 'D', 'E'], index = ['yyyyyyyy - ' + str(x) for x in range(2000, 2011, 1)]) # plot heatmap plt.ion() ax = sns.heatmap(data.T) # adjust to taste ax.figure.subplots_adjust(bottom = 0.25) # turn the axis label for item in ax.get_yticklabels(): item.set_rotation(0) for item in ax.get_xticklabels(): item.set_rotation(90) # save figure plt.savefig('seabornPandas.png', dpi=100) </code></pre> <p><a href="http://i.stack.imgur.com/X8gIC.png" rel="nofollow"><img src="http://i.stack.imgur.com/X8gIC.png" alt="xaxis-space"></a></p>
1
2016-10-05T02:25:27Z
[ "python", "pandas", "matplotlib", "seaborn" ]
Nested Loops all
39,864,292
<p>I am using python. The assignment is simple, I understand the concept, I have zero knowledge of computer programming, so be gentle and please try to explain everything in much detail as if I know nothing, I am trying my best to learn. This is to show that with all combinations ijk, ikj, jik, jki, kij, and kji return the same result. The next step is to do the same thing with 4000. (try to figure how to put 4000 in matrix, shoot myself.) I know there are things like numpy but I have no idea how to use that, but I was going to try and start with the basics, straight from windows terminal. I would like to thank you for your time and help here guys! thanks!!!enter code here</p> <pre><code>enter code here X = [[1,2,3,4,5], [6,7,8,9,10]] Y = [[1,2], [3,4], [5,6], [7,8], [9,10]] result = [[0,0], [0,0]] empty = [[0,0], [0,0]] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] print"" for i in range(len(X)): for k in range(len(Y)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r del r[:] print"" for i in range(len(X)): for k in range(len(Y)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] del range[:] print"" for j in range(len(Y[0])): for i in range(len(X)): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] for j in range(len(Y[0])): for k in range(len(Y)): for i in range(len(X)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] for k in range(len(Y)): for i in range(len(X)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] for k in range(len(Y)): for j in range(len(Y[0])): for i in range(len(X)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] </code></pre> <p>The problem, is the index, when running the code for the 3rd set, there is a problem with the index, I can't figure that out.</p> <pre><code> result[i][j] += X[i][k] * Y[k][j] IndexError: list index out of range </code></pre>
0
2016-10-05T01:53:06Z
39,864,370
<pre><code>for i in range(len(X)): for k in range(len(Y)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] </code></pre> <p><code>result[i][j]</code> is a <code>2x2</code> matrix <code>len(X)</code> and <code>len(Y)</code> are both <code>2</code>. Meanwhile <code>k</code> is going all the way up to <code>5</code>. This is what gives you your <code>list index out of range</code> error</p> <p>You have to make your matrix sizes match up. </p>
0
2016-10-05T02:05:45Z
[ "python", "loops", "matrix", "indexing", "nested" ]
Nested Loops all
39,864,292
<p>I am using python. The assignment is simple, I understand the concept, I have zero knowledge of computer programming, so be gentle and please try to explain everything in much detail as if I know nothing, I am trying my best to learn. This is to show that with all combinations ijk, ikj, jik, jki, kij, and kji return the same result. The next step is to do the same thing with 4000. (try to figure how to put 4000 in matrix, shoot myself.) I know there are things like numpy but I have no idea how to use that, but I was going to try and start with the basics, straight from windows terminal. I would like to thank you for your time and help here guys! thanks!!!enter code here</p> <pre><code>enter code here X = [[1,2,3,4,5], [6,7,8,9,10]] Y = [[1,2], [3,4], [5,6], [7,8], [9,10]] result = [[0,0], [0,0]] empty = [[0,0], [0,0]] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] print"" for i in range(len(X)): for k in range(len(Y)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r del r[:] print"" for i in range(len(X)): for k in range(len(Y)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] del range[:] print"" for j in range(len(Y[0])): for i in range(len(X)): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] for j in range(len(Y[0])): for k in range(len(Y)): for i in range(len(X)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] for k in range(len(Y)): for i in range(len(X)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] for k in range(len(Y)): for j in range(len(Y[0])): for i in range(len(X)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r result = empty del r[:] </code></pre> <p>The problem, is the index, when running the code for the 3rd set, there is a problem with the index, I can't figure that out.</p> <pre><code> result[i][j] += X[i][k] * Y[k][j] IndexError: list index out of range </code></pre>
0
2016-10-05T01:53:06Z
39,864,479
<p>I printed <code>i</code>, <code>j</code>, <code>k</code> and <code>result[i][j]</code>, <code>X[i][k]</code>, <code>Y[k][j]</code> in 3rd set and found:</p> <p>You forgot <code>result = empty</code></p> <p>But there is another problem: <code>result = empty</code> doesn't duplicate list but assigns the same list to two variables. So when you delete <code>r[:]</code> the you delete <code>result</code> and <code>empty</code> and get empty list <code>[]</code> and doesn't exist even <code>result[0][0]</code>.</p> <p>You need <code>result = empty[:]</code> to duplicate <code>empty</code> and assign to <code>result</code>. </p> <pre><code>X = [[1,2,3,4,5], [6,7,8,9,10]] Y = [[1,2], [3,4], [5,6], [7,8], [9,10]] result = [[0,0], [0,0]] empty = [[0,0], [0,0]] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r print result = empty[:] for i in range(len(X)): for k in range(len(Y)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r print result = empty[:] for i in range(len(X)): for k in range(len(Y)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r print result = empty[:] for j in range(len(Y[0])): for i in range(len(X)): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r print result = empty[:] for j in range(len(Y[0])): for k in range(len(Y)): for i in range(len(X)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r print result = empty[:] for k in range(len(Y)): for i in range(len(X)): for j in range(len(Y[0])): result[i][j] += X[i][k] * Y[k][j] for r in result: print r print result = empty[:] for k in range(len(Y)): for j in range(len(Y[0])): for i in range(len(X)): result[i][j] += X[i][k] * Y[k][j] for r in result: print r print result = empty[:] </code></pre>
0
2016-10-05T02:21:16Z
[ "python", "loops", "matrix", "indexing", "nested" ]
How to use subprocess and 'cat' to read in data line by line?
39,864,304
<p>I'm having trouble understanding how to use <code>subprocess</code> for a problem on mine. </p> <p>Let's say I have a tab-delimited text file <code>tabdelimited1.txt</code> in my subdiretory which I would like to read into a pandas dataframe. </p> <p>Naturally, you could simply import the data as follows: </p> <pre><code>import pandas as pd df = pd.read_csv("tabdelimited1.txt", header=None, sep="\s+") </code></pre> <p>However, let's say we wanted to use <code>subprocess</code>. In the command line, <code>$cat tabdelimited1.txt</code> will output all of the lines. </p> <p>Now, I want to use subprocess to read the output of <code>cat tabdelimited1.txt</code>. How does one do this? </p> <p>We could use </p> <pre><code>import subprocess task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) data = task.stdout.read() </code></pre> <p>but (1) I get an error for <code>shell=True</code> and (2) I would like to read in the data line-by-line. </p> <p>How can I use <code>subprocess</code> to read <code>tabdelimited1.txt</code> line-by-line? The script should look something like this:</p> <pre><code>import subprocess import pandas as pd df = pd.DataFrame() task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) # while lines exist: # line = subprocess std df=pd.concat([df, line]) </code></pre> <p>EDITED</p>
0
2016-10-05T01:56:03Z
39,864,368
<p>You can skip the shell completely by breaking the command into a list. Then its just a matter of iterating the process stdout:</p> <pre><code>import subprocess import pandas as pd df = pd.DataFrame() task = subprocess.Popen(["cat", "file.txt"], stdout=subprocess.PIPE) for line in task.stdout: df=pd.concat([df, line]) task.wait() </code></pre>
2
2016-10-05T02:05:42Z
[ "python", "python-3.x", "csv", "subprocess", "cat" ]
How to use subprocess and 'cat' to read in data line by line?
39,864,304
<p>I'm having trouble understanding how to use <code>subprocess</code> for a problem on mine. </p> <p>Let's say I have a tab-delimited text file <code>tabdelimited1.txt</code> in my subdiretory which I would like to read into a pandas dataframe. </p> <p>Naturally, you could simply import the data as follows: </p> <pre><code>import pandas as pd df = pd.read_csv("tabdelimited1.txt", header=None, sep="\s+") </code></pre> <p>However, let's say we wanted to use <code>subprocess</code>. In the command line, <code>$cat tabdelimited1.txt</code> will output all of the lines. </p> <p>Now, I want to use subprocess to read the output of <code>cat tabdelimited1.txt</code>. How does one do this? </p> <p>We could use </p> <pre><code>import subprocess task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) data = task.stdout.read() </code></pre> <p>but (1) I get an error for <code>shell=True</code> and (2) I would like to read in the data line-by-line. </p> <p>How can I use <code>subprocess</code> to read <code>tabdelimited1.txt</code> line-by-line? The script should look something like this:</p> <pre><code>import subprocess import pandas as pd df = pd.DataFrame() task = subprocess.Popen("cat file.txt", shell=True, stdout=subprocess.PIPE) # while lines exist: # line = subprocess std df=pd.concat([df, line]) </code></pre> <p>EDITED</p>
0
2016-10-05T01:56:03Z
39,864,561
<pre><code>import sys for line in sys.stdin: print(line.split()) </code></pre> <p>can be used with a shell command like:</p> <pre><code>0025:~/mypy$ cat x.txt | python3 stack39864304.py ['1', '3', 'test1;'] ['2', '2', 'test2;'] ['3', '2', 'test3;'] </code></pre> <p>Otherwise in an interactive session I can do:</p> <pre><code>In [269]: task = subprocess.Popen("cat x.txt", shell=True, stdout=subprocess.PIPE) In [270]: for line in task1.stdout:print(line.split()) [b'1', b'3', b'test1;'] [b'2', b'2', b'test2;'] [b'3', b'2', b'test3;'] </code></pre> <p>(py3 bytestrings)</p> <p><code>python3 stack39864304.py &lt; x.txt</code> is another way of sending this file to the script.</p> <p><code>cat afile | ...</code> is perhaps too simple, and raise all the objections about why not read directly. But <code>cat</code> can be replaced by <code>head</code>, <code>tail</code> or even <code>ls -l | python3 stack39864304.py</code> to get a directory list with this <code>split</code>.</p> <p>I use <code>ipython</code> for most of my interactive python coding; many of its <code>%magic</code> use subprocesses; I use <code>cat x.txt</code>, <code>ls</code> all the time from within this session.</p>
0
2016-10-05T02:33:29Z
[ "python", "python-3.x", "csv", "subprocess", "cat" ]
Opening a HTML file from my computer in web browser
39,864,306
<p>I would like to open a HTML file that is stored in my computer on a web browser but I'm getting an error (see below).</p> <pre><code>from urllib import urlopen from webbrowser import open as webopen from os import getcwd from os.path import normpath </code></pre> <p>I have this code:</p> <pre><code>def open_html_file(): path = normpath.abspath('New_News.html') url = 'file://' + path with open(path, 'w') as f: f.write(html) webopen.open(url) </code></pre> <p>and I'm getting this error when the code is run:</p> <pre class="lang-none prettyprint-override"><code>AttributeError: 'function' object has no attribute 'abspath' </code></pre>
0
2016-10-05T01:56:16Z
39,864,324
<p><code>normpath</code> is a function, and doesn't have a <code>abspath</code> attribute. I think you meant to do that:</p> <pre><code>from os.path import abspath path = abspath('New_News.html') </code></pre>
0
2016-10-05T01:59:14Z
[ "python", "html", "os.path", "python-webbrowser" ]
Google App Engine - storing key into ndb KeyProperty
39,864,359
<p>I am creating a commenting system using Google App Engine with webapp2 using ndb datastore. I created a property KeyProperty so I can fetch comments associated with posts with the same key. </p> <p>However, I keep receiving an error message whenever I try to store the key of a post into ndb.KeyProperty. I tried changing the KeyProperty to </p> <pre><code>p_key= ndb.KeyProperty(Post), p_key= ndb.KeyProperty(kind="Post"), p_key= ndb.KeyProperty(kind=Post, repeated=True) but none of these worked. </code></pre> <p>When I was using db model with ReferenceProperty, the app was behaving the way I wanted to.</p> <p>Here's the Code.</p> <pre><code>def question_key(name = 'default'): return ndb.Key('questions', name) class Post(ndb.Model): question = ndb.StringProperty(required = True) created = ndb.DateTimeProperty(auto_now_add = True) last_modified = ndb.DateTimeProperty(auto_now = True) user = ndb.StringProperty() def render(self): self._render_text = self.question.replace('\n', '&lt;br&gt;') return render_str("post.html", p = self) class Reply(ndb.Model): content = ndb.TextProperty(required = True) p_key= ndb.KeyProperty(kind=Post) user = ndb.StringProperty() created = ndb.DateTimeProperty(auto_now_add = True) last_modified = ndb.DateTimeProperty(auto_now = True) def render(self): self._render_text = self.content.replace('\n', '&lt;br&gt;') return self._render_text class PostPage(Handler): def get(self, post_id): key = ndb.Key('Post', int(post_id), parent=question_key()) post = key.get() params = dict(post=post) #retrieve all the comments and then filter it by key if Reply.query(): reply = Reply.query(Reply.p_key == key) params['reply'] = reply if self.user: params['current_user'] = self.user.name if not post: self.error(404) return self.render("permalink.html", **params) def post(self, post_id): reply_content = self.request.get('reply') p_key = self.request.get('p_key') #get post key from template user = self.user if reply_content: r = Reply(content=reply_content, p_key=p_key, user=user) r.put() self.redirect('/stories/%s' % str(post_id)) else: error = "error" self.redirect('/stories/%s' % str(post_id)) class NewPost(Handler): def get(self): if self.user: self.render("newpost.html") else: self.redirect("/login") def post(self): if not self.user: self.redirect('/') question = self.request.get('question') user=self.user.name if question: p = Post(parent = question_key(), question = question, user=user) p.put() self.redirect('/stories/%s' % str(p.key.id())) else: error = "error" self.render("newpost.html", error=error) app = webapp2.WSGIApplication([('/', MainPage), ('/stories/([0-9]+)', PostPage), ('/stories/newpost', NewPost), ], debug=True) </code></pre> <p>Below is the error message.</p> <pre><code>Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1535, in __call__ rv = self.handle_exception(request, response, e) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1529, in __call__ rv = self.router.dispatch(request, response) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 1102, in __call__ return handler.dispatch() File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 572, in dispatch return self.handle_exception(e, self.app.debug) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "/Users/young-junpark/kloupod-143223/main.py", line 240, in post r = Reply(content=reply_content, p_key=p_key, user=user) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2947, in __init__ self._set_attributes(kwds) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 2993, in _set_attributes prop._set_value(self, value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 1145, in _set_value value = self._do_validate(value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 1092, in _do_validate value = self._call_shallow_validation(value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 1284, in _call_shallow_validation return call(value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 1331, in call newvalue = method(self, value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/ndb/model.py", line 1781, in _validate (value,)) BadValueError: Expected string, got User(key=Key('users', 'default', 'User', 5629499534213120), created=datetime.datetime(2016, 10, 4, 23, 12, 27, 1990), email=u'youngtheabsolute@gmail.com', name=u'\ubc15\uc6a9\uc900', pw_hash=u'JsIho,9c9f5b4b3a19213e8a84318db6d2e94179678d2d7f22cce6af9b30a558423b28', verification_code=u'12345', verified=False) </code></pre> <p>I really appreciate your help! </p>
1
2016-10-05T02:03:54Z
39,864,532
<p>The error tells you what's happening:</p> <pre><code>BadValueError: Expected string, got User </code></pre> <p>If you look a little further back in the traceback, you see:</p> <pre><code>post r = Reply(content=reply_content, p_key=p_key, user=user) </code></pre> <p>In your <code>Reply</code> class, you set <code>user</code> to be a <code>ndb.StringProperty</code>, but in that line of code, it looks like you are passing a full <code>User</code> object, not just a string.</p> <p>If you change the <code>user</code> attribute of <code>Reply</code> to be a <code>User</code> type not a <code>StringProperty</code>, then it looks like everything should work correctly.</p> <p>You can accomplish this using <a href="https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#structured" rel="nofollow">structured properties</a>:</p> <pre><code>user = ndb.StructuredProperty(User) </code></pre> <p>UPDATE: After going through your comments, it seems you have another problem.</p> <p>You create the <code>ndb.Key("Post", post_id, parent=question_key())</code> which you then send to a template in <code>PostPage.get()</code>. This key is encoded as a string in the template that looks something like:</p> <pre><code>u"Key('question', 'default', 'Post', 123123213123) </code></pre> <p>I'm assuming that you send that key back to <code>PostPage.post()</code>. So when you try and create a <code>Reply</code> using that key in:</p> <pre><code>r = Reply(content=reply_content, p_key=p_key, user=user) </code></pre> <p>It fails saying that it expected a <code>ndb.Key</code> but instead received a string that looks like a key. You should consider using <code>urlsafe</code> keys. <a href="https://cloud.google.com/appengine/docs/python/ndb/creating-entities" rel="nofollow">This page</a> on Google has a good explanation of how to use <code>ndb</code>.</p>
1
2016-10-05T02:28:48Z
[ "python", "google-app-engine", "google-cloud-datastore", "webapp2", "google-app-engine-python" ]
Calling functions inside a function in python?
39,864,563
<p>Trying to find a way to call each function inside the function, thirdQues. I don't want them to be global, and keep receiving an unexpected indentation error when I show they are nested within thirdQues in the main. I also plan to nest thirdQues in functions around the same size as itself. Any help appreciated. </p> <pre><code>import time def thirdQues(a = ("Questions_7.txt"), b = ("Questions_8.txt"), c = ("Questions_9.txt")): myName=("none") def intro3(): Intro1 = open(Intro3.txt, "r") print(Intro1) def announce3(): input() print('"TT(Announcing):.... BIENVIENDOS AL CORO CIRCUIT! HOY TENENMOS.....(Welcome to the Coro Circuit! Today we have.....)"') time.sleep(5) print('" El jefe..... El mysterio..... El campeón de peso pesado......(The boss....... The mysterious........ the heavy weight champion....."') time.sleep(5) print('"Senor........ Diego!"') time.sleep(3) print('(Crowd electrifies the arena in excitement)') print('Diego:(Staring you down with a neutral experssion and arms crossed): \n "HMPH.... "') input() print('"TT(Announcing): ANNNND.....HONING IN FROM SU CASA CUIDAD, (Their hometown)"') time.sleep(3) print('".....VEN EL UN.....(Comes the one.....)"') time.sleep(2) print('"........EL SOLO......(The ONLY.....)"') time.sleep(3) print('"........CON DOS GANADORS DESPUES SU CINTURON......(With 2 wins under their belt.....)"') time.sleep(3) print('".......El' +(myName)+ '!!!!') input() print('(The same woman from the last matches is now holding a small Japanese flag and blowing kisses towards you.') print('TT: VAMOS A EMPEZAR CORO CIRCUIT! (LET"S GO CORO CIRCUIT!)') input() #I wanted to have the print statements timed instead of reading the announcements from a file to add depth. def Preguntas3(): text_file = open(a, "r") wholefile = text_file.read() print(wholefile) ans = '' ans = input() yes = [] yup = [] right = [] print('TT: Eres Cierto? (Are you sure? Be sure to properly spell out your answer.) \n (TYPE Y OR N)') sure = '' sure = input() if sure == str('y' or 'Y'): answer = '' answer=str(ans) else: print('"TT: Lo siento, could you say that again?"') answer = input() time.sleep(3) if answer == str('To win is to adapt.'): print('..... '+(myName)+ ' seals the first hit!') time.sleep(3) print('TT: Whoa, that is an outrageous uppercut!') time.sleep(4) print('Diego:......(Gives you a dark look and retains his stance)') time.sleep(3) print('TT: Seems you cannot win without adaptation....') print('TT: Next question') yes=['Si'] else: print('TT: And Diego swipes the stage with a gizalle punch!') time.sleep(3) print('TT: Estoy sin palabras!!! (I am speechless!)') time.sleep(4) print('Diego:..... Eres loco.... (You are foolish.)') time.sleep(3) print('TT: Next Question!') input() text_file = open(b , "r") wholefile = text_file.read() print(wholefile) ans = '' ans = input() correct = [] print('TT: Eres Cierto? (Are you sure? Be sure to properly spell out your answer.) (FULL SENTENCES NEED PERIODS.) \n (TYPE Y OR N)') sure = '' sure = input() if sure == str('y' or 'Y'): answer = '' answer=str(ans) else: print('"TT: Lo siento, could you say that again?"') answer = input() time.sleep(3) if answer == str('Believe in yourself.'): print('.....(Crowd goes rampid).... TT: '+(myName)+' tiene el fuego! (Has the fire!) ') time.sleep(3) print('TT: Gosh! What a spectacular Haymaker!') time.sleep(4) print('Diego:.........(Looks away briefly)') time.sleep(1) print('TT: Next question') yup=['Tu'] else: print('......(Crowd goes insane) TT: We have got a pull counter de Senor Diego!') time.sleep(3) print('TT: NO PUEDO MIRAR, NO PUEDO MIRAR! ( I cannot look! I cannot look!') time.sleep(4) print('Diego:.......Eres un inutil....(....You suck....') time.sleep(3) print('TT: IT IS TIME FOR THE FINAL QUESTION OF THE CORO CIRCUIT!!!') time.sleep(2) print('(The Crowd is shuffling like fireworks!)') time.sleep(4) input() print('(Diego stares at you with the harshest eyes you have ever seen in your life.)') print('(He retains his stance and looks as if he is about to parry)') print('(You swallow deeply intimadation and discover what you must do next...)') text_file = open(c, "r") wholefile = text_file.read() print(wholefile) ans = '' ans = input() print('TT: Eres Cierto? (Are you sure? Be sure to properly spell out your answer.) \n (TYPE Y OR N)') sure = '' sure = input() if sure == str('y' or 'Y'): answer = '' answer=str(ans) else: print('"TT: Lo siento, could you say that again?"') answer = input() time.sleep(3) if answer == str('As always'): print('And....'+(myName)+' GETS THE HIT!') time.sleep(3) print('TT:..........') time.sleep(4) print('Diego:..........') time.sleep(4) print('(Crowd:.........!)') time.sleep(4) print('Woman in the crowd: Anata o shinrai shite imasu!!(I believe in you!)') input() right=['Ganas'] else: print('TT: Anddd: Diego GETS THE LAST HIT!!!!') time.sleep(3) print('TT:..........') time.sleep(4) print('(Crowd:.........!)') time.sleep(4) print('Woman in the crowd:.......(She ducks her head in sadness.) ') time.sleep(4) print('Diego:.......Soy el mejor......(....I am the best.....) ') input() print('(.........You have had enough of this and decide to charge him force with all you might. \n He does the same....)') input() print('TT: AY DIAS MIA! (OH MY GOD!) THEY ARE GOING AT IT RANDOMLY NOW NON STOP!?!.... GONNA HAVE TO DECLARE THE WINNER IN.......') time.sleep(2) advance = (yes + yup + right) if advance == ['Si','Tu','Ganas'] or ['Si', 'Tu',] or ['Tu', 'Ganas'] or ['Si', 'Ganas'] : print('TT:10') time.sleep(1) print('TT:9') time.sleep(1) print('TT:8') time.sleep(1) print('TT:7') time.sleep(1) print('TT:6') time.sleep(1) print('TT:5') time.sleep(1) print('TT:4') time.sleep(2) print('TT:3') time.sleep(2) print('TT:2') time.sleep(4) print('......1') time.sleep(1) print('TT: AND THE GANADOR(Winner) ISSSSSSSS,' , +(myName)+ '!' 'Congratulations! YOU HAVE WON THE CORO CIRCUIT!') print('Diego:........ Anata wa jibun o shinjite...... (He bows down for you and then vanishes in thin air.)') else: print('TT:10') time.sleep(1) print('TT:9') time.sleep(1) print('TT:8') time.sleep(1) print('TT:7') time.sleep(1) print('TT:6') time.sleep(1) print('TT:5') time.sleep(1) print('TT:4') time.sleep(2) print('TT:3') time.sleep(2) print('TT:2') time.sleep(4) print('......1') time.sleep(1) print('TT: AND THE GANADOR(Winner) ISSSSSSS, DIEGO! Congratulations!') input() ## print('Ricka: Me das asco........\n(You disgust me...... \n(He lifts his arms and glares at the crowd)') ## input() ## print('Ricka: RICKAKAKKKKAKAKKAAKKAKKAKAKKKAAKA!') ## input() ## print('(...... you pass out, unable to bear with blows of your opponent.... \n Until you wake up from this nightmare.... \n ') ## input() ## print('(Reality sets in, it is only 2:30 AM and you ask yourself.....)') #### playAgain = 'yes' ## while playAgain == 'yes' or playAgain == 'y': ## firstQues() ## a = ("Questions1.txt") ## b = ("Questions_2.txt") ## c = ("Questions_3.txt") ## print('Do you want to go back to bed and finish this dream? \n (TYES YES OR Y) Or do you want to wake up and start your miserable day? \n (TYPE NO OR N)') ## playAgain=input() ## def main(): thirdQues(a = "Questions_7.txt", b = "Questions_8.txt" ,c = "Questions_9.txt") intro3() announce3() Preguntas3() main() </code></pre>
-1
2016-10-05T02:33:35Z
39,866,413
<p>This indentation is wrong:</p> <pre><code>def main(): thirdQues(a = "Questions_7.txt", b = "Questions_8.txt" ,c = "Questions_9.txt") intro3() </code></pre> <p>You cannot indent <code>intro3()</code> here.</p> <p>Besides that, use 4 spaces for indentation, rather than 8. Both are syntactically valid, but 4 spaces are always used. It just looks better and everyone is used to that.</p>
0
2016-10-05T05:59:47Z
[ "python", "python-3.x" ]
Python .replace running twice
39,864,581
<p>Still pretty new to python and first time using .replace and I am running into a weird issue.</p> <pre><code>url_base = 'http://sfbay.craigslist.org/search/eby/apa' params = dict(bedrooms=1, is_furnished=1) rsp = requests.get(url_base, params=params) # BS4 can quickly parse our text, make sure to tell it that you're giving html html = bs4(rsp.text, 'html.parser') # BS makes it easy to look through a document #print(html.prettify()[:1000]) # BS4 can quickly parse our text, make sure to tell it that you're giving html html = bs4(rsp.text, 'html.parser') # BS makes it easy to look through a document print(html.prettify()[:1000]) # find_all will pull entries that fit your search criteria. # Note that we have to use brackets to define the `attrs` dictionary # Because "class" is a special word in python, so we need to give a string. apts = html.find_all('p', attrs={'class': 'row'}) print(len(apts)) # We can see that there's a consistent structure to a listing. # There is a 'time', a 'name', a 'housing' field with size/n_brs, etc. this_appt = apts[15] print(this_appt.prettify()) # So now we'll pull out a couple of things we might be interested in: # It looks like "housing" contains size information. We'll pull that. # Note that `findAll` returns a list, since there's only one entry in # this HTML, we'll just pull the first item. size = this_appt.findAll(attrs={'class': 'housing'})[0].text print(size) , 'this is the size' def find_size_and_brs(size): split = size.strip('/- ').split(' - ') print len(split) if 'br' in split[0] and 'ft2' in split[0]: print 'We made it into 1' n_brs = split[0].replace('br -', '',) this_size = split[0].replace('ft2 -', '') elif 'br' in split[0]: print 'we are in 2' # It's the n_bedrooms n_brs = split[0].replace('br', '') this_size = np.nan elif 'ft2' in split[0]: print 'we are in 3' # It's the size this_size = split[0].replace('ft2', '') n_brs = np.nan print n_brs print this_size return float(this_size), float(n_brs) this_size, n_brs = find_size_and_brs(size) </code></pre> <p>This outputs:</p> <pre><code>We made it into 1 1 800ft2 - 1br - 800 </code></pre> <p>I can't figure out why it prints out the data twice, replacing the data a single time for each data point. </p> <p>Thoughts? Thanks</p>
0
2016-10-05T02:35:34Z
39,864,817
<p>Now works for me. I made some modifications with <code>strip</code>, <code>split</code> and add comment <code># &lt;- here</code></p> <pre><code>url_base = 'http://sfbay.craigslist.org/search/eby/apa' params = dict(bedrooms=1, is_furnished=1) rsp = requests.get(url_base, params=params) # BS4 can quickly parse our text, make sure to tell it that you're giving html html = bs4(rsp.text, 'html.parser') # BS makes it easy to look through a document #print(html.prettify()[:1000]) # BS4 can quickly parse our text, make sure to tell it that you're giving html html = bs4(rsp.text, 'html.parser') # BS makes it easy to look through a document #print(html.prettify()[:1000]) # find_all will pull entries that fit your search criteria. # Note that we have to use brackets to define the `attrs` dictionary # Because "class" is a special word in python, so we need to give a string. apts = html.find_all('p', attrs={'class': 'row'}) #print(len(apts)) # We can see that there's a consistent structure to a listing. # There is a 'time', a 'name', a 'housing' field with size/n_brs, etc. this_appt = apts[15] #print(this_appt.prettify()) # So now we'll pull out a couple of things we might be interested in: # It looks like "housing" contains size information. We'll pull that. # Note that `findAll` returns a list, since there's only one entry in # this HTML, we'll just pull the first item. size = this_appt.findAll(attrs={'class': 'housing'})[0].text #print(size) , 'this is the size' def find_size_and_brs(size): split = size.strip().split(' - ') # &lt;- here strip() #print len(split) if 'br' in split[0] and 'ft2' in split[0]: print 'We made it into 1' two = split[0].split('\n') # &lt;- here split() n_brs = two[0].replace('br -', '',).strip() # &lt;- here two[0] and strip() this_size = two[1].replace('ft2 -', '').strip() # &lt;- here two[1] and strip() #print '&gt;', n_brs, '&lt;' #print '&gt;', this_size, '&lt;' elif 'br' in split[0]: print 'we are in 2' # It's the n_bedrooms n_brs = split[0].replace('br', '') this_size = np.nan elif 'ft2' in split[0]: print 'we are in 3' # It's the size this_size = split[0].replace('ft2', '') n_brs = np.nan print n_brs print this_size return float(this_size), float(n_brs) this_size, n_brs = find_size_and_brs(size) print '&gt;', this_size, '&lt;' print '&gt;', n_brs, '&lt;' </code></pre> <p>ps. I use <code>&gt;</code>, <code>&lt;</code> in <code>print</code> to see spaces.</p>
0
2016-10-05T03:08:57Z
[ "python" ]
Python perfect number calculation
39,864,603
<p>I am having issues with calculating perfect numbers in python. Apparently the code is working in VBA so I am sure I am making some mistake in syntax / indentation. Please help!</p> <p>Here is my code:</p> <pre><code>Mynum=int(input("How many perfect numbers do you want?: ")) counter=0 k=0 j=2 i=1 while counter&lt;Mynum: for i in range (1,j-1): if (j%i)==0: k=k+1 if k==j: counter=counter+1 print(i) k=0 j=j+1 </code></pre>
0
2016-10-05T02:39:23Z
39,864,774
<p>Your screenshot code, which is the better of the two, is broken in a couple of ways: your <code>k = k + 1</code> expression should be <code>k = k + i</code> as you want to sum the factors, not count them; you <code>print(i)</code> when your should print <code>j</code> or <code>k</code>:</p> <pre><code>Mynum = int(input("How many perfect numbers do you want?: ")) counter = 0 j = 2 while counter &lt; Mynum: k = 0 for i in range (1, j): if (j % i) == 0: k += i if k == j: counter += 1 print(j) j += 1 </code></pre> <p>However, in the bigger picture, this is the wrong approach for looking for perfect numbers -- using this method you're not likely to find more than the first four:</p> <pre><code>How many perfect numbers do you want?: 5 6 28 496 8128 </code></pre> <p>so you might as well just go for those and forget about asking how many the user wants.</p> <p>An example better approach would be to search for Mersenne primes using a <a href="https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test" rel="nofollow">Lucas-Lehmer primality test</a> and when you find one, compute the <a href="https://en.wikipedia.org/wiki/Mersenne_prime#Perfect_numbers" rel="nofollow">companion perfect number</a> from that. This doesn't take too much code and will leap frog your current approach.</p>
1
2016-10-05T03:03:39Z
[ "python", "perfect-numbers" ]
Python perfect number calculation
39,864,603
<p>I am having issues with calculating perfect numbers in python. Apparently the code is working in VBA so I am sure I am making some mistake in syntax / indentation. Please help!</p> <p>Here is my code:</p> <pre><code>Mynum=int(input("How many perfect numbers do you want?: ")) counter=0 k=0 j=2 i=1 while counter&lt;Mynum: for i in range (1,j-1): if (j%i)==0: k=k+1 if k==j: counter=counter+1 print(i) k=0 j=j+1 </code></pre>
0
2016-10-05T02:39:23Z
39,864,801
<p>Here's another solution to the perfect number:</p> <pre><code>import itertools as it def perfect(): for n in it.count(1): if sum(i for i in range(1, n+1) if n%i == 0) == 2*n: yield n &gt;&gt;&gt; list(it.islice(perfect(), 3)) [6, 28, 496] 100 loops, best of 3: 12.6 ms per loop </code></pre> <p>Or you can use factors (for a slightly faster solution):</p> <pre><code>def factors(n): for a in range(1, int(n**0.5)+1): if n % a: continue x = n // a yield a if a != x: yield x def perfect(): for n in it.count(1): if sum(factors(n))==2*n: yield n &gt;&gt;&gt; list(it.islice(perfect(), 3)) [6, 28, 496] 1000 loops, best of 3: 1.43 ms per loop </code></pre> <p>You can improve this even further using a fast prime number version.<br> Taking a simple prime generator from <a href="http://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python/3796442#3796442">How to implement an efficient infinite generator of prime numbers in Python?</a>)</p> <pre><code>import itertools as it import functools as ft def primegen(): yield 2 D = {} for q in it.count(3, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: x = q + 2*p while x in D: x += 2*p D[x] = p def ll(p): # Lucas-Lehmer if p == 2: return True m = 2**p - 1 return ft.reduce(lambda s, _: (s**2 - 2) % m, range(3, p+1), 4) == 0 def perfect(): for p in primegen(): if ll(p): yield (2**p-1)*(2**(p-1)) &gt;&gt;&gt; list(it.islice(perfect(), 3)) [6, 28, 496] 100000 loops, best of 3: 7.94 µs per loop &gt;&gt;&gt; list(it.islice(perfect(), 10)) [6, 28, 496, 8128, 33550336, 8589869056, 137438691328, 2305843008139952128, 2658455991569831744654692615953842176, 191561942608236107294793378084303638130997321548169216] 1000 loops, best of 3: 613 µs per loop </code></pre> <p>These get very big very quickly, e.g. the 20th perfect number has 2663 digits.</p>
0
2016-10-05T03:06:36Z
[ "python", "perfect-numbers" ]
How do I execute a function in a certain way after importing it in another python file?
39,864,618
<p>This is a function that returns a list of length of random numbers from 0 to 9.</p> <pre><code>import random def makeList(): y=[] n=int(raw_input("Enter number")) for x in range(0,n): x=random.randint(0,9) y.append(x) print y def main(): makeList() if __name__ == '__main__': main() </code></pre> <p>Now i am creating another python file called main.py and importing this function this is the code i wrote in main.py . The name of the file is myFunc.</p> <pre><code>from myFuncs import makeList makeList() </code></pre> <p>Now, I want to create a list of ( say 10 random numbers.) what should i write inside the main.py file to achieve this ?</p>
0
2016-10-05T02:41:35Z
39,864,705
<p>Changing <code>print y</code> to <code>return y</code> in the first file. (and <code>print(makeList())</code> under <code>main()</code>) </p> <p>In the new file, <code>new_list = makeList()</code></p> <p>then new_list is that generated list.</p> <p>Edit: More pythonic version</p> <p><strong>File 1</strong></p> <pre><code>import random def make_list(length=10): return [random.randint(0,9) for _ in range(length)] def main(): amount = int(raw_input("Enter number")) print(make_list(amount)) if __name__ == '__main__': main() </code></pre> <p><strong>File 2</strong></p> <pre><code>from myFuncs import make_list new_list = make_list() print(new_list) # will be default 10 </code></pre> <p><strong>--</strong></p> <p>If you want to keep the input in that same function it is possible, here is one way: </p> <pre><code>def make_list(length=0): if not length: length= int(raw_input("Enter number")) return [random.randint(0,9) for _ in range(length)] def main(): print(make_list()) </code></pre> <p>Then specify <code>make_list(10)</code> in the second file</p>
0
2016-10-05T02:53:45Z
[ "python", "python-2.7" ]
Parsing Messy Data
39,864,658
<p>I'm relatively new to python and was wondering if I could get some assistance in parsing data so that it is easier to analyze.</p> <hr> <p>My data is in the following form (each is an entire line):</p> <pre><code>20160930-07:06:54.481737|I|MTP_4|CL:BF K7-M7-N7 Restrict for maxAggressive: -4.237195 20160930-07:06:54.481738|I|MTP_4|CL:BF K7-M7-N7 BidPrice: -5.0 mktBestBid: -5.0 bidTheo: -4.096774 bidSeedEdge: 0.195028 bidUnseedEdge: CL:BF K7-M7-N7 = 0.14042 Min Bid: -6.0 Max Ticks Offset: 1 Max Aggressive Ticks: 1 </code></pre> <p>This is my code so far</p> <pre><code># Output file output_filename = os.path.normpath("Mypath/testList.log") # Overwrites the file with open(output_filename, "w") as out_file: out_file.write("") # Open output file with open(output_filename, "a") as out_file: # Open input file in 'read' mode with open("mypath/tradedata.log", "r") as in_file: # Loop over each log line, Grabs lines with necessary data for line in islice(in_file, 177004, 8349710): out_file.write(line) </code></pre> <p>Would it be easiest to just go through and do it by keywords like; bidUnseedEdge, mktBesdBid, etc. ?</p>
0
2016-10-05T02:46:55Z
40,022,431
<pre><code>infilename = "path/data.log" outfilename = "path/OutputData.csv" with open(infilename, 'r') as infile,\ open(outfilename, "w") as outfile: lineCounter = 0 for line in infile: lineCounter += 1 if lineCounter % 1000000 == 0: print lineCounter data = line.split("|") if len(data) &lt; 4: continue bidsplit = data[3].split("bidTheo:") namebid = data[3].split("BidPrice:") if len(bidsplit) == 2: bid = float(bidsplit[1].strip().split()[0]) bidname = namebid[0].strip().split(",")[0] #print "bidTheo," + data[0] + "," + str(bid) outfile.write("bidTheo," + data[0] + "," + bidname + "," + str(bid) + "\n") offersplit = data[3].split("offerTheo:") nameoffer = data[3].split("AskPrice:") if len(offersplit) == 2: offer = float(offersplit[1].strip().split()[0]) offername = nameoffer[0].strip().split(",")[0] #print "offerTheo," + data[0] + "," + str(offer) outfile.write("offerTheo," + data[0] + "," + offername + "," + str(offer) + "\n") print "Done" </code></pre>
0
2016-10-13T13:30:41Z
[ "python" ]
Count number of occurences of specific number in numpy arrary in Excel sheet using python
39,864,754
<pre><code>import numpy as np from openpyxl import load_workbook wb = load_workbook('Book1.xlsx') sheet_1 = wb.get_sheet_by_name('Sheet1') x1 = np.zeros(sheet_1.max_row) for i in range(0,sheet_1.max_row): x1[i]=sheet_1.cell(row=i+1, column=1).value x2[i] = np.count_nonzero(x1[i]) collections.Counter(x2[i])[0] </code></pre> <p>I wanted to count the number of occurrence of 0 in the same column and add them up and find out the total number of element in the excel sheet.so the results expecting should be 3.It seems that numpy is unable to count. I have tried sum but it only adds up the element in the array. Appreciate any help from you guys. </p> <p>Error Message: TypeError: 'numpy.float64' object is not iterable</p> <p>Excel sheet: 5 5 3 3 4 5 5 0 0 0</p>
0
2016-10-05T03:00:41Z
39,874,505
<p>A straight forward numpy-only solution to the <em>"counting occurence of a specific number in a numpy array"</em> question would be this:</p> <pre><code># Note that I cast x1 to np.int because "arr==x" is not reliable with floats x1=np.array([5,5,3,3,4,5,5,0,0,0],dtype=np.int) #(x1==0) is boolean array that is True only where 0s are. #summing that array gives the count of 0s count_0=np.sum(x1==0) count_5=np.sum(x1==5) print("# of 0 : ",count_0) print("# of 5 : ",count_5) </code></pre> <p>Output :</p> <pre><code># of 0 : 3 # of 5 : 4 </code></pre> <p><strong>An other solution (the one you where seemingly trying implement)</strong> using <code>Counter</code> would read :</p> <pre><code>count=collections.Counter(x1) print("# of 0 : ",count[0]) print("# of 5 : ",count[5]) </code></pre>
0
2016-10-05T12:52:15Z
[ "python", "excel", "numpy" ]
How to scrape charts from a website with python?
39,864,796
<p><strong>EDIT:</strong> </p> <p>So I have save the script codes below to a text file but using re to extract the data still doesn't return me anything. My code is: </p> <pre><code>file_object = open('source_test_script.txt', mode="r") soup = BeautifulSoup(file_object, "html.parser") pattern = re.compile(r"^var (chart[0-9]+) = new Highcharts.Chart\(({.*?})\);$", re.MULTILINE | re.DOTALL) scripts = soup.find("script", text=pattern) profile_text = pattern.search(scripts.text).group(1) profile = json.loads(profile_text) print profile["data"], profile["categories"] </code></pre> <hr> <p>I would like to extract the chart's data from a website. The following is the source code of the chart. </p> <pre><code> &lt;script type="text/javascript"&gt; jQuery(function() { var chart1 = new Highcharts.Chart({ chart: { renderTo: 'chart1', defaultSeriesType: 'column', borderWidth: 2 }, title: { text: 'Productions' }, legend: { enabled: false }, xAxis: [{ categories: [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016], }], yAxis: { min: 0, title: { text: 'Productions' } }, series: [{ name: 'Productions', data: [1,1,0,1,6,4,9,15,15,19,24,18,53,42,54,53,61,36] }] }); }); &lt;/script&gt; </code></pre> <p>There are several charts like that from the website, called "chart1", "chart2", etc. I would like to extract the following data: the categories line and the data line, for each chart: </p> <pre><code>categories: [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016] data: [1,1,0,1,6,4,9,15,15,19,24,18,53,42,54,53,61,36] </code></pre>
0
2016-10-05T03:06:12Z
39,866,327
<p>I'd go a combination of regex and yaml parser. Quick and dirty below - you may need to tweek the regex but it works with example:</p> <pre><code>import re import sys import yaml chart_matcher = re.compile(r'^var (chart[0-9]+) = new Highcharts.Chart\(({.*?})\);$', re.MULTILINE | re.DOTALL) script = sys.stdin.read() m = chart_matcher.findall(script) for name, data in m: print name try: chart = yaml.safe_load(data) print "categories:", chart['xAxis'][0]['categories'] print "data:", chart['series'][0]['data'] except Exception, e: print e </code></pre> <p>Requires the yaml library (<code>pip install PyYAML</code>) and you should use BeautifulSoup to extract the correct <code>&lt;script&gt;</code> tag before passing it to the regex.</p> <p><strong>EDIT</strong> - full example</p> <p>Sorry I didn't make myself clear. You use BeautifulSoup to parse the HTML and extract the <code>&lt;script&gt;</code> elements, and then use PyYAML to parse the javascript object declaration. You can't use the built in json library because its not valid JSON but plain javascript object declarations (ie with no functions) are a subset of YAML.</p> <pre><code>from bs4 import BeautifulSoup import yaml import re file_object = open('source_test_script.txt', mode="r") soup = BeautifulSoup(file_object, "html.parser") pattern = re.compile(r"var (chart[0-9]+) = new Highcharts.Chart\(({.*?})\);", re.MULTILINE | re.DOTALL | re.UNICODE) charts = {} # find every &lt;script&gt; tag in the source using beautifulsoup for tag in soup.find_all('script'): # tabs are special in yaml so remove them first script = tag.text.replace('\t', '') # find each object declaration for name, obj_declaration in pattern.findall(script): try: # parse the javascript declaration charts[name] = yaml.safe_load(obj_declaration) except Exception, e: print "Failed to parse {0}: {1}".format(name, e) # extract the data you want for name in charts: print "## {0} ##".format(name); print "categories:", charts[name]['xAxis'][0]['categories'] print "data:", charts[name]['series'][0]['data'] print </code></pre> <p>Output:</p> <pre><code>## chart1 ## categories: [1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016] data: [22, 1, 0, 1, 6, 4, 9, 15, 15, 19, 24, 18, 53, 42, 54, 53, 61, 36] </code></pre> <p>Note I had to tweek the regex to make it handle the unicode output and whitespace from BeautifulSoup - in my original example I just piped your source directly to the regex.</p> <p><strong>EDIT 2</strong> - no yaml</p> <p>Given that the javascript looks to be partially generated the best you can hope for is to grab the lines - not elegant but will probably work for you.</p> <pre><code>from bs4 import BeautifulSoup import json import re file_object = open('citec.repec.org_p_c_pcl20.html', mode="r") soup = BeautifulSoup(file_object, "html.parser") pattern = re.compile(r"var (chart[0-9]+) = new Highcharts.Chart\(({.*?})\);", re.MULTILINE | re.DOTALL | re.UNICODE) charts = {} for tag in soup.find_all('script'): # tabs are special in yaml so remove them first script = tag.text values = {} # find each object declaration for name, obj_declaration in pattern.findall(script): for line in obj_declaration.split('\n'): line = line.strip('\t\n ,;') for field in ('data', 'categories'): if line.startswith(field + ":"): data = line[len(field)+1:] try: values[field] = json.loads(data) except: print "Failed to parse %r for %s" % (data, name) charts[name] = values print charts </code></pre> <p>Note that it fails for chart7 because that references another variable.</p>
0
2016-10-05T05:53:05Z
[ "python", "graph", "screen-scraping" ]
How to scrape charts from a website with python?
39,864,796
<p><strong>EDIT:</strong> </p> <p>So I have save the script codes below to a text file but using re to extract the data still doesn't return me anything. My code is: </p> <pre><code>file_object = open('source_test_script.txt', mode="r") soup = BeautifulSoup(file_object, "html.parser") pattern = re.compile(r"^var (chart[0-9]+) = new Highcharts.Chart\(({.*?})\);$", re.MULTILINE | re.DOTALL) scripts = soup.find("script", text=pattern) profile_text = pattern.search(scripts.text).group(1) profile = json.loads(profile_text) print profile["data"], profile["categories"] </code></pre> <hr> <p>I would like to extract the chart's data from a website. The following is the source code of the chart. </p> <pre><code> &lt;script type="text/javascript"&gt; jQuery(function() { var chart1 = new Highcharts.Chart({ chart: { renderTo: 'chart1', defaultSeriesType: 'column', borderWidth: 2 }, title: { text: 'Productions' }, legend: { enabled: false }, xAxis: [{ categories: [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016], }], yAxis: { min: 0, title: { text: 'Productions' } }, series: [{ name: 'Productions', data: [1,1,0,1,6,4,9,15,15,19,24,18,53,42,54,53,61,36] }] }); }); &lt;/script&gt; </code></pre> <p>There are several charts like that from the website, called "chart1", "chart2", etc. I would like to extract the following data: the categories line and the data line, for each chart: </p> <pre><code>categories: [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016] data: [1,1,0,1,6,4,9,15,15,19,24,18,53,42,54,53,61,36] </code></pre>
0
2016-10-05T03:06:12Z
39,887,073
<p>I tried the code as you suggested but kept getting this:</p> <pre><code>"Failed to parse chart1: while parsing a flow mapping in "&lt;unicode string&gt;", line 29, column 16: tooltip: { ^ expected ',' or '}', but got '{'" </code></pre> <p>My entire code: </p> <pre><code>import json import urllib2 import re import sys import yaml from selenium.webdriver import Chrome as Browser from bs4 import BeautifulSoup URL = ("http://citec.repec.org/p/c/pcl20.html") browser=Browser() browser.get(URL) source = browser.page_source #file_object = open('source_test.txt', mode="r") soup = BeautifulSoup(source, "html.parser") pattern = re.compile(r"var (chart[0-9]+) = new Highcharts.Chart\(({.*?})\);", re.MULTILINE | re.DOTALL | re.UNICODE) charts = {} # find every &lt;script&gt; tag in the source using beautifulsoup for tag in soup.find_all('script'): # tabs are special in yaml so remove them first script = tag.text.replace('\t', '') # find each object declaration for name, obj_declaration in pattern.findall(script): try: # parse the javascript declaration charts[name] = yaml.safe_load(obj_declaration) except Exception, e: print "Failed to parse {0}: {1}".format(name, e) # extract the data you want for name in charts: print "## {0} ##".format(name); print "categories:", charts[name]['xAxis'][0]['categories'] print "data:", charts[name]['series'][0]['data'] print </code></pre>
0
2016-10-06T03:32:31Z
[ "python", "graph", "screen-scraping" ]
Weighted K-means with GPS Data
39,864,921
<p><strong>OBJECTIVE</strong></p> <ul> <li><p>Aggregate store locations GPS information (longitude, latitude) </p></li> <li><p>Aggregate size of population in surrounding store area (e.g 1,000,000 residents) </p></li> <li>Use K-means to determine optimal distribution centers, given store GPS data and local population (i.e distribution centers are located closer to urban stores vs. rural stores due to higher demand).</li> </ul> <p><strong>ISSUES</strong></p> <ol> <li>I've been <a href="http://cs.au.dk/~simina/weighted.pdf" rel="nofollow">researching</a> on how to add weighted variables to a k-means algorithm, but am unsure on the <em>actual</em> process of weighting the variables. For example, if I have the [lat, long, and population (in thousands)] (e.g "New York" = <code>[40.713, 74.005, 8406]</code>) wouldn't this construct the centriod in 3-dimensional space? If so, wouldn't the distances be improperly skewed and mis-represent the best location for a warehouse distribution center?</li> <li>Additional <a href="https://www-users.cs.umn.edu/~kumar/dmbook/ch8.pdf" rel="nofollow">research</a> alludes to UPGMA, "Unweighted Pair Group Method" where the size of the cluster is taken into account. However, I haven't fully reviewed this method and the intricacies associated with this method. </li> </ol> <p><strong>REFERENCES</strong></p> <p>Reference 1: <a href="http://cs.au.dk/~simina/weighted.pdf" rel="nofollow">http://cs.au.dk/~simina/weighted.pdf</a> (page 5)</p> <blockquote> <p>It can also be shown that a few other algorithms similar to k-means, namely k-median and k-mediods are also weight-separable. The details appear in the appendix. Observe that all of these popular objective functions are highly responsive to weight.</p> </blockquote> <p>Reference 2: <a href="https://www-users.cs.umn.edu/~kumar/dmbook/ch8.pdf" rel="nofollow">https://www-users.cs.umn.edu/~kumar/dmbook/ch8.pdf</a> (page 39: "Ability to Handle Different cluster sizes"</p>
0
2016-10-05T03:22:27Z
39,870,707
<p>1) You only want to do k-means in the (longitude, latitude) space. If you add population as a 3rd dimension, you will bias your centroids towards the midpoint between large population centres, which are often far apart.</p> <p>2) The simplest hack to incorporate a weighting in k-means is to repeat a point (longitude, latitude) according to its population weight. </p> <p>3) k-means is probably not the best clustering algorithm for the job, as travel times do not scale linearly with distance. Also, you are basically guaranteed to never have a distribution centre bang in the middle of a large population centre, which is probably not what you want. I would use DBSCAN, for which scikit-learn has a nice implementation: <a href="http://scikit-learn.org/stable/modules/clustering.html" rel="nofollow">http://scikit-learn.org/stable/modules/clustering.html</a></p>
1
2016-10-05T09:48:28Z
[ "python", "numpy", "statistics", "k-means" ]
image_url = soup.select('.image a')[0]['href'] IndexError: list index out of range
39,864,939
<p>I used part of this code to retrieve the images from imgur when the URL doesn't end in an image extension like .png/.jpg. However I am getting these errors. Please have a look and suggest fixes:</p> <p><a href="https://github.com/asweigart/imgur-hosted-reddit-posted-downloader/blob/master/imgur-hosted-reddit-posted-downloader.py" rel="nofollow">https://github.com/asweigart/imgur-hosted-reddit-posted-downloader/blob/master/imgur-hosted-reddit-posted-downloader.py</a></p> <pre><code>import datetime import praw import re import urllib import requests from bs4 import BeautifulSoup sub = 'dog' imgurUrlPattern = re.compile(r'(http://i.imgur.com/(.*))(\?.*)?') r = praw.Reddit(user_agent = "download all images from a subreddit", user_site = "lamiastella") already_done = [] #checkWords = ['i.imgur.com', 'jpg', 'png',] check_words = ['jpg', 'png'] subreddit = r.get_subreddit(sub) for submission in subreddit.get_hot(limit=10000): is_image = any(string in submission.url for string in check_words) print '[LOG] Getting url: ' + submission.url if submission.id not in already_done and is_image: if submission.url.endswith('/'): modified_url = submission.url[:len(submission.url)-1] try: urllib.urlretrieve(modified_url, '/home/jalal/computer_vision/image_retrieval/images/' + datetime.datetime.now().strftime('%y-%m-%d-%s') + modified_url[-4:]) except IOError: pass else: try: urllib.urlretrieve(submission.url, '/home/jalal/computer_vision/image_retrieval/images/' + datetime.datetime.now().strftime('%y-%m-%d-%s') + submission.url[-4:]) except IOError: pass already_done.append(submission.id) print '[LOG] Done Getting ' + submission.url print('{0}: {1}'.format('submission id is', submission.id)) elif 'http://imgur.com/' in submission.url: # This is an Imgur page with a single image. html_source = requests.get(submission.url).text # download the image's page soup = BeautifulSoup(html_source, "lxml") image_url = soup.select('.image a')[0]['href'] if image_url.startswith('//'): # if no schema is supplied in the url, prepend 'http:' to it image_url = 'http:' + image_url image_id = image_url[image_url.rfind('/') + 1:image_url.rfind('.')] urllib.urlretrieve(image_url, '/home/jalal/computer_vision/image_retrieval/images/' + datetime.datetime.now().strftime('%y-%m-%d-%s') + image_url[-4:]) </code></pre> <p>The error is:</p> <pre><code>[LOG] Getting url: http://imgur.com/a/yOLjm Traceback (most recent call last): File "download_images.py", line 43, in &lt;module&gt; image_url = soup.select('.image a')[0]['href'] IndexError: list index out of range </code></pre>
0
2016-10-05T03:24:54Z
39,865,173
<p>You have wrong selection - you need <code>soup.select('img')[0]['src']</code></p> <pre><code>import datetime import urllib import requests from bs4 import BeautifulSoup url = 'http://imgur.com/gyUWtWP' html_source = requests.get(url).text soup = BeautifulSoup(html_source, "lxml") image_url = soup.select('img')[0]['src'] if image_url.startswith('//'): image_url = 'http:' + image_url image_id = image_url[image_url.rfind('/') + 1:image_url.rfind('.')] urllib.urlretrieve(image_url, datetime.datetime.now().strftime('%y-%m-%d-%s') + image_url[-4:]) </code></pre>
1
2016-10-05T03:54:56Z
[ "python", "html", "beautifulsoup", "reddit", "imgur" ]
How to do the modulus calculation without using mod funct in Python
39,865,003
<p>I am coding in Python and using Putty, I couldnt find the right way to do a program that does a modulus calculation without the mod function. </p> <pre><code>def main() Input1 = int(input("Type in first number")) Input2 = int(input("Type in second number")) q = (input1 / Input2) #finding quotient (integer part only) p = (q * Input2) //finding product m = (Input1 - p) //finding modulus print(Input1, "%", Input2, "=", m) main </code></pre>
-2
2016-10-05T03:34:27Z
39,865,713
<pre><code>def main(): Input1 = int(input("Type in first number")) Input2 = int(input("Type in second number")) q = (Input1 / Input2) for i in range(0, Input1, Input2): if Input1 - i &lt; Input2: print(Input1-i) </code></pre> <p>This is a way to find what x mod y is in any given circumstance.</p>
1
2016-10-05T04:56:13Z
[ "python" ]
some misunderstanding about `pandas.series.drop()`
39,865,031
<p>I want to drop some specific rows in a <code>pandas.DataFrame</code>, while it seems that <code>pandas.Series.drop()</code>.What I have tried is as follows:</p> <pre><code>In[1]: a_pd = pd.DataFrame(np.array([[1,2,3], [2,'?','x'],['s','d',4]]), columns=list('abc')) a_pd Out[1]: a b c 0 1 2 3 1 2 ? x 2 s d 4 In[2]: a_pd['b'].drop(a_pd['b'] == '?', inplace=True) a_pd out[2]: a b c 0 1 2 3 1 2 ? x 2 s d 4 </code></pre> <p>Why it is the same <code>a_pd</code>??? Then I tried the <code>pandas.DataFrame.drop</code>, the result is more amazing:</p> <pre><code>In[3]: b_pd = a_pd.drop(a_pd['b'] == '?') out[3]: a b c 1 2 ? x 2 s d 4 </code></pre> <p>What happened? I cannot believe my eyes. Although I can easily choose the what I want by simply using <code>a_pd[a_pd['b'] != '?']</code>, I still want to try <code>drop()</code>.</p>
0
2016-10-05T03:37:40Z
39,865,499
<p>pandas.drop() works on the labels associated with the row you want do delete, which in this case is 0, 1, or 2. So you can delete the middle row by </p> <pre><code>a_pd.drop([1]) </code></pre> <p>returns</p> <pre><code> a b c 0 1 2 3 2 s d 4 </code></pre> <p>Similarly, for the Series version of .drop(), will remove a row from the series. </p> <pre><code>a_pd['b'].drop([1]) </code></pre> <p>returns</p> <pre><code>0 2 2 d </code></pre> <p>When you use the selection </p> <pre><code>a_pd['b'] == '?' </code></pre> <p>you get an array of boolean values</p> <pre><code>0 False 1 True 2 False Name: b, dtype: bool </code></pre> <p>and the result of </p> <pre><code>a_pd.drop(a_pd['b'] == '?') </code></pre> <p>is the same as </p> <pre><code>a_pd.drop([False, True, False]) </code></pre> <p>But now is where things are not as expected, rather than apply a drop where the boolean value is True, this array is treated as an array of integer indices to drop namely</p> <pre><code>a_pd.drop([0, 1, 0]) </code></pre> <p>And thus the result is a removal of the first two rows (the first row is removed twice)</p> <pre><code> a b c 2 s d 4 </code></pre> <p>At least that is how it works on my version of pandas</p> <pre><code>pandas.__version__ $&gt; u'0.17.1' </code></pre>
2
2016-10-05T04:34:32Z
[ "python", "pandas" ]
Python: Calculating exponents of a base
39,865,032
<p>I am new to python and trying to figure out how to get an exponent to times a certain time of the base, ex. 5<sup>4</sup>, without using the exponent operator, **.</p> <p>For this, I am trying to implement the use of the for loop but the thing is I cannot figure out how to achieve this with a loop.</p> <p>This is what I got so far.</p> <pre><code>base = int(input("ENTER NUMBER: ")) exponent = int(input("ENTER EXPONENT: ")) for item_name in things_with_item: if exponent == 0: print("something") elif exponent &gt; 0: print("something") else: print("ERROR. TRY AGAIN") </code></pre> <p>What I am stuck with is what variables I should use to replace "item_name" and "things_with_items" and also how to calculate the answer of 5<sup>4</sup> like 5 * 5 * 5 * 5. Do I need to make a variable for the calculation of 5<sup>4</sup> or would the loop do that for me?</p> <p>I really don't know where to start, if you guys could provide me with some hints, that would be wonderful.</p> <p>Thank you</p>
-1
2016-10-05T03:37:43Z
39,865,075
<p><code>range(x)</code> can be used to run a loop <code>x</code> times (don't even pay attention to the values iterated). If you start with a value of 1, then multiply by <code>base</code> <code>exponent</code> times, that's naive exponentiation right there.</p>
2
2016-10-05T03:42:24Z
[ "python", "python-3.x" ]
Python: Calculating exponents of a base
39,865,032
<p>I am new to python and trying to figure out how to get an exponent to times a certain time of the base, ex. 5<sup>4</sup>, without using the exponent operator, **.</p> <p>For this, I am trying to implement the use of the for loop but the thing is I cannot figure out how to achieve this with a loop.</p> <p>This is what I got so far.</p> <pre><code>base = int(input("ENTER NUMBER: ")) exponent = int(input("ENTER EXPONENT: ")) for item_name in things_with_item: if exponent == 0: print("something") elif exponent &gt; 0: print("something") else: print("ERROR. TRY AGAIN") </code></pre> <p>What I am stuck with is what variables I should use to replace "item_name" and "things_with_items" and also how to calculate the answer of 5<sup>4</sup> like 5 * 5 * 5 * 5. Do I need to make a variable for the calculation of 5<sup>4</sup> or would the loop do that for me?</p> <p>I really don't know where to start, if you guys could provide me with some hints, that would be wonderful.</p> <p>Thank you</p>
-1
2016-10-05T03:37:43Z
39,865,307
<p>Try this code:</p> <pre><code>base = int(input("ENTER NUMBER: ")) exponent = int(input("ENTER EXPONENT: ")) no = base * base for item_name in range(exponent): if exponent == 0: print(1) elif exponent &gt; 0: no += base * exponent * base * item_name if no == base ** exponent: print(no) else: print("ERROR. TRY AGAIN") </code></pre>
0
2016-10-05T04:10:31Z
[ "python", "python-3.x" ]
Python: Calculating exponents of a base
39,865,032
<p>I am new to python and trying to figure out how to get an exponent to times a certain time of the base, ex. 5<sup>4</sup>, without using the exponent operator, **.</p> <p>For this, I am trying to implement the use of the for loop but the thing is I cannot figure out how to achieve this with a loop.</p> <p>This is what I got so far.</p> <pre><code>base = int(input("ENTER NUMBER: ")) exponent = int(input("ENTER EXPONENT: ")) for item_name in things_with_item: if exponent == 0: print("something") elif exponent &gt; 0: print("something") else: print("ERROR. TRY AGAIN") </code></pre> <p>What I am stuck with is what variables I should use to replace "item_name" and "things_with_items" and also how to calculate the answer of 5<sup>4</sup> like 5 * 5 * 5 * 5. Do I need to make a variable for the calculation of 5<sup>4</sup> or would the loop do that for me?</p> <p>I really don't know where to start, if you guys could provide me with some hints, that would be wonderful.</p> <p>Thank you</p>
-1
2016-10-05T03:37:43Z
39,865,631
<p>Try</p> <pre><code> base = float(input('Enter Num:')) exponent = int(input('Enter Exponent:') #what if I want non integer exponent answer = 1 if exponent != 0: #if the exponent is 0 the answer is 1 for in range(abs(exponent)): answer*=base if exponent &lt; 0: answer = 1/answer print('Answer:', answer) </code></pre> <p>5**4 is probably the easiest way. Multiplying as many times as the exponent works only if the exponent is an integer. We can make use of logarithm e.g. a^b is equivalent to exp(b*log a) code is now straight forward.</p> <pre><code> import math base = 5 exponent = 4 print(math.exp(exponent*math.log(base))) </code></pre> <h1>624.9999999999998 is the answer</h1>
0
2016-10-05T04:48:55Z
[ "python", "python-3.x" ]
Selenium Chrome, Python. Couldn't find the button on the website
39,865,034
<p>I am newly learning how to work with Webdriver and while I am playing with it on Eventbrite website it couldn't find the create event button while it is there(I can click it). I try lots of different things to locate button like XPath, link_text, class but they didn't work. Here is the code I am working with :</p> <pre><code> driver = self.driver driver.get("https://www.eventbrite.com/") driver.find_element_by_xpath("(//a[contains(text(),'Log in')])[2]").click() driver.find_element_by_id("login-email").clear() driver.find_element_by_id("login-email").send_keys("email") driver.find_element_by_id("login-password").clear() driver.find_element_by_id("login-password").send_keys("password") driver.find_element_by_id("remember_me").click() driver.find_element_by_xpath("//input[@value='Log in']").click() time.sleep(2) driver.find_element_by_link_text("Create Event").click() </code></pre> <p>Can anyone please help me with this ?</p>
1
2016-10-05T03:37:53Z
39,865,148
<p>If I'm understanding your question right, the last line of your example (<code>"Create Event"</code>) is the one that doesn't work? I can say that if I use a css selector, I can click that button. (I also tend to find css selectors are easier to work with)</p> <pre><code>driver = self.driver driver.get("https://www.eventbrite.com/") driver.find_element_by_xpath("(//a[contains(text(),'Log in')])[2]").click() driver.find_element_by_id("login-email").clear() driver.find_element_by_id("login-email").send_keys("email") driver.find_element_by_id("login-password").clear() driver.find_element_by_id("login-password").send_keys("password") driver.find_element_by_id("remember_me").click() driver.find_element_by_xpath("//input[@value='Log in']").click() time.sleep(2) driver.find_element_by_css_selector("div.l-mar-top-3 a.js-organizer-cta-btn").click() </code></pre>
1
2016-10-05T03:52:07Z
[ "python", "osx", "google-chrome", "selenium" ]
Applying modulo to all elements of a python list and getting some correct some incorrect elements
39,865,185
<p>I am implementing a function that reduces all the elements of a list modulo 3. Here is what I have:</p> <pre><code>def reduceMod3(l): for i in l: l[i] = l[i] % 3 return l </code></pre> <p>when I call this function on L = [1,2,3,4,5,6,7,8,9] I get:</p> <pre><code>L = [1, 2, 0, 4, 2, 6, 1, 8, 0] </code></pre> <p>Why is this? I am trying to figure it out but I'm in a rush. Thanks.</p>
3
2016-10-05T03:56:01Z
39,865,217
<p>You're list assignment is off, <code>l[i]</code> is not saying 'the value that equals <code>i</code>' but 'position <code>i</code> in list <code>l</code>'. You also don't want to modify a list as you iterate over it. </p> <p>I think this is more what you want. Creates a new list of mod3 items of the incoming list. </p> <pre><code>def reduceMod3(l): return [i % 3 for i in l] </code></pre>
1
2016-10-05T04:00:21Z
[ "python", "list", "loops" ]
Applying modulo to all elements of a python list and getting some correct some incorrect elements
39,865,185
<p>I am implementing a function that reduces all the elements of a list modulo 3. Here is what I have:</p> <pre><code>def reduceMod3(l): for i in l: l[i] = l[i] % 3 return l </code></pre> <p>when I call this function on L = [1,2,3,4,5,6,7,8,9] I get:</p> <pre><code>L = [1, 2, 0, 4, 2, 6, 1, 8, 0] </code></pre> <p>Why is this? I am trying to figure it out but I'm in a rush. Thanks.</p>
3
2016-10-05T03:56:01Z
39,865,221
<p>When you write <code>for i in l</code>, you are accessing each element of the list, not the index. Instead, you should write </p> <pre><code>for i in range(len(l)): </code></pre> <p>You can also solve this with a list comprehension:</p> <pre><code>return [item % 3 for item in l] </code></pre>
4
2016-10-05T04:00:46Z
[ "python", "list", "loops" ]
Merging rows in pandas
39,865,192
<p>Say I have a dataframe that looks something like this</p> <pre><code>Line VarA VarB 345 Something abc 346 Something2 def 347 Something ghi 348 Something2 jkl 349 Something mno 350 Something2 pqr 351 Something stu 352 Something2 vwx </code></pre> <p>How can I turn this dataframe into something that looks like this:</p> <pre><code>VarA VarB Something abcghimnostu Something2 defjklpqrvwx </code></pre>
0
2016-10-05T03:56:31Z
39,865,328
<p>You can just <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow">sum</a></p> <pre><code>print(df.groupby('VarA')['VarB'].sum()) VarA something abcghimnostu something2 defjklpqrvwx Name: VarB, dtype: object </code></pre>
2
2016-10-05T04:12:48Z
[ "python", "pandas", "dataframe" ]
Using datetime.now() in Django view
39,865,207
<p><strong>The Code</strong></p> <p>I am using datetime.now() as part of a filter in a Django view as follows:</p> <pre><code>def get_now(): return timezone.now() class BulletinListView(ListView): model = Announcement template_name = 'newswire/home.html' def get_context_data(self, **kwargs): context = super(BulletinListView, self).get_context_data(**kwargs) try: published_announcements = Announcement.objects.filter(publish_start_date__lte=get_now(), publish_end_date__gte=get_now()).filter(hidden=False, under_review=False).extra(order_by=['-publish_start_date', 'publish_end_date']) except Announcement.DoesNotExist: published_announcements = None if published_announcements is not None: context['announcements'] = published_announcements max_print_annoucements = int(config.MAX_PRINT_ANNOUCEMENTS) context['announcements_print'] = published_announcements[ :max_print_annoucements] context['more_annoucements_online_count'] = published_announcements.count() - max_print_annoucements return context </code></pre> <p><strong>Edit:</strong> Managed to update and include more code</p> <p>It works correctly and gets announcements that are supposed to be published and are not hidden or under review according to to the date supplied by <code>datetime.now()</code></p> <p><strong>The Problem</strong></p> <p>I use <code>datetime.datetime.now()</code> to filter out old announcements but I realised after a day in the production environment that <code>datetime.datetime.now()</code> is being evaluated only when the server starts and the value does not update each time the view is called which results in the wrong data being filtered when the next day comes around. This is also affecting another function which retrieves upcoming birthdays in the next 7 days.</p> <p><strong>Things I Read and Tried</strong></p> <p>I have seen a number of questions about using the callable <code>datetime.now</code> instead of <code>datetime.now()</code> but only in the context of setting default values in the model.</p> <p>I have defined a function as follows thinking it would force <code>datetime.now</code> to be evaluated again but it does not seem to work. </p> <pre><code>def get_now(): return timezone.now()) </code></pre> <p>When I pass the date i get to the context to see what I'm getting, I see that the date and time doesn't advance past the time I deploy the server.</p> <p>I have seen a number of examples of using datetime.now() in the view but none run into this issue.</p> <p>I suspect I have never seen this in development because I run the development gunicorn server with the --reload option and <code>datetime.now()</code> is constantly evaluated when I save changes and the server restarts.</p> <p><a href="http://stackoverflow.com/questions/10741201/django-seems-to-be-caching-datetime-now">This problem</a> seems to be similar but I'm not sure how it is similar/different to my situation</p> <p><strong>Context:</strong></p> <p>I am writing a Django application and my development and production environments are implemented using docker and the application run behind an nginx proxy</p> <pre><code>/usr/local/bin/gunicorn app.wsgi:application -w 2 -b :8000 </code></pre>
0
2016-10-05T03:58:28Z
39,888,221
<blockquote> <p>the value does not update each time the view is called which results in the wrong data being filtered when the next day comes around</p> </blockquote> <p>You have to decide which "next day" are you talking about? Is it:</p> <ol> <li>The next day for the user visiting your site.</li> <li>The next day for you, visiting the site.</li> <li>The next day for the timezone that is set on the server.</li> </ol> <p>Each one of these will end up in a "wrong" result, when in fact nothing is actually wrong with the code.</p> <p>This is because your code is naive when it comes to timezones. It basically ignores timezones completely.</p> <p>This is a complicated topic, and django has a <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/" rel="nofollow">complete section of the manual</a> dedicated to dealing with timezones. I suggest reading it once or twice as there are many ways timezones can affect your site.</p> <p>Finally, you can clean up your code a bit, like this:</p> <pre><code>try: max_print_annoucements = int(config.MAX_PRINT_ANNOUCEMENTS) except ValueError: max_print_announcements = 0 published_announcements = Announcement.objects.filter(publish_start_date__lte=get_now(), publish_end_date__gte=get_now()) .filter(hidden=False, under_review=False) .extra(order_by=['-publish_start_date', 'publish_end_date']) context['announcements'] = published_announcements context['announcements_print'] = published_announcements[:max_print_annoucements] context['more_annoucements_online_count'] = abs(published_announcements.count() - max_print_annoucements) </code></pre>
0
2016-10-06T05:33:04Z
[ "python", "django", "datetime", "gunicorn" ]
Grading program having problems with while loop and using different data types
39,865,251
<p>I'm making a program where I need to have the user input a series of homework grades (ranging from 0 to 10) until they type 'done' in which case I must calculate the average of the scores and provide a corresponding letter grade. My trouble is, I don't know how to calculate the average when I don't have the exact number of homeworks to divide the sum of all of the homeworks by, since it's not on a finite loop. And also, when I run my program I keep getting an error message that says TypeError: unorderable types: str() &lt; int()</p> <p>Here's my code so far:</p> <pre><code> print("Enter your homework scores one at a time, must be an integer ranging from 0 to 10. When finished, type done.") number=input("Enter your homework grade: ") while number != 'done': number=input("Enter your homework grade: ") percentage= number*10 #I need to divide by number of homeworks there are, but I'm not sure how to get the variable I need to divide by. if number &lt; 0 or number &gt; 10: print("Score must be between 0 and 10") elif percentage &gt;= 92 and number &lt; 100: letter = 'A' elif percentage &gt;= 87 and number &lt; 92: letter = 'B+' elif percentage &gt;= 80 and number &lt; 87: letter = 'B' elif percentage &gt;=77 and number &lt; 80: letter = 'C+' elif percentage &gt;=70 and number &lt; 77: letter = 'C' elif percentage &gt;= 67 and number &lt; 70: letter = 'D+' elif percentage &gt;= 60 and number &lt; 67: letter = 'D' elif percentage &lt; 60 and number &gt;= 0: letter= 'F' elif number == 'done': print(percentage,"%, you got an ", letter) else: print("Error: please enter an integer ranging from 0 and 10.") </code></pre>
0
2016-10-05T04:03:53Z
39,865,272
<p>The input is a string type so you must explicitly convert it to an integer using something like "number = int(number)".</p> <p>You could create a separate counting variable that is incremented each time through the loop, and then use that final value to divide when you are done.</p>
0
2016-10-05T04:06:28Z
[ "python" ]
Grading program having problems with while loop and using different data types
39,865,251
<p>I'm making a program where I need to have the user input a series of homework grades (ranging from 0 to 10) until they type 'done' in which case I must calculate the average of the scores and provide a corresponding letter grade. My trouble is, I don't know how to calculate the average when I don't have the exact number of homeworks to divide the sum of all of the homeworks by, since it's not on a finite loop. And also, when I run my program I keep getting an error message that says TypeError: unorderable types: str() &lt; int()</p> <p>Here's my code so far:</p> <pre><code> print("Enter your homework scores one at a time, must be an integer ranging from 0 to 10. When finished, type done.") number=input("Enter your homework grade: ") while number != 'done': number=input("Enter your homework grade: ") percentage= number*10 #I need to divide by number of homeworks there are, but I'm not sure how to get the variable I need to divide by. if number &lt; 0 or number &gt; 10: print("Score must be between 0 and 10") elif percentage &gt;= 92 and number &lt; 100: letter = 'A' elif percentage &gt;= 87 and number &lt; 92: letter = 'B+' elif percentage &gt;= 80 and number &lt; 87: letter = 'B' elif percentage &gt;=77 and number &lt; 80: letter = 'C+' elif percentage &gt;=70 and number &lt; 77: letter = 'C' elif percentage &gt;= 67 and number &lt; 70: letter = 'D+' elif percentage &gt;= 60 and number &lt; 67: letter = 'D' elif percentage &lt; 60 and number &gt;= 0: letter= 'F' elif number == 'done': print(percentage,"%, you got an ", letter) else: print("Error: please enter an integer ranging from 0 and 10.") </code></pre>
0
2016-10-05T04:03:53Z
39,865,320
<p>Outside of your <code>while</code> loop, you can keep an array of grades you've seen so far. It will start out empty. </p> <pre><code>arr = [] </code></pre> <p>Every time you see a new grade, you can append it to the array. </p> <pre><code>newGrade = input("Enter your homework grade") arr.append(float(newGrade)*10) </code></pre> <p>Once the user enters done, you can calculate the average using the <code>sum</code> and <code>len</code> functions, which give you the sum of the elements in the array and the number of elements in the array, respectively. </p> <pre><code>average = sum(arr)/len(arr) </code></pre>
0
2016-10-05T04:12:05Z
[ "python" ]
Grading program having problems with while loop and using different data types
39,865,251
<p>I'm making a program where I need to have the user input a series of homework grades (ranging from 0 to 10) until they type 'done' in which case I must calculate the average of the scores and provide a corresponding letter grade. My trouble is, I don't know how to calculate the average when I don't have the exact number of homeworks to divide the sum of all of the homeworks by, since it's not on a finite loop. And also, when I run my program I keep getting an error message that says TypeError: unorderable types: str() &lt; int()</p> <p>Here's my code so far:</p> <pre><code> print("Enter your homework scores one at a time, must be an integer ranging from 0 to 10. When finished, type done.") number=input("Enter your homework grade: ") while number != 'done': number=input("Enter your homework grade: ") percentage= number*10 #I need to divide by number of homeworks there are, but I'm not sure how to get the variable I need to divide by. if number &lt; 0 or number &gt; 10: print("Score must be between 0 and 10") elif percentage &gt;= 92 and number &lt; 100: letter = 'A' elif percentage &gt;= 87 and number &lt; 92: letter = 'B+' elif percentage &gt;= 80 and number &lt; 87: letter = 'B' elif percentage &gt;=77 and number &lt; 80: letter = 'C+' elif percentage &gt;=70 and number &lt; 77: letter = 'C' elif percentage &gt;= 67 and number &lt; 70: letter = 'D+' elif percentage &gt;= 60 and number &lt; 67: letter = 'D' elif percentage &lt; 60 and number &gt;= 0: letter= 'F' elif number == 'done': print(percentage,"%, you got an ", letter) else: print("Error: please enter an integer ranging from 0 and 10.") </code></pre>
0
2016-10-05T04:03:53Z
39,865,322
<p>Kevin's tells you to make an integer, say count = 0, and increment it every time you ask for a grade.</p> <p>In the end, you take the sum / count.</p> <p>Here is a slightly improved way on top of that: start with count = 0</p> <pre><code> Do: Ask for grade AVG = (AVG*count + new grade)/(count+1) count++ </code></pre> <p>The AVG*count gives you the previous sum. </p>
0
2016-10-05T04:12:30Z
[ "python" ]
Adding counter/index to a list of lists in Python
39,865,305
<p>I have a list of lists of strings:</p> <pre><code>listBefore = [['4', '5', '1', '1'], ['4', '6', '1', '1'], ['4', '7', '8', '1'], ['1', '2', '1', '1'], ['2', '3', '1', '1'], ['7', '8', '1', '1'], ['7', '9', '1', '1'], ['2', '4', '3', '1']] </code></pre> <p>and I would like to add a counter/index in the middle of each list so that the list looks like:</p> <pre><code>listAfter = [['4', '5', '1', '1', '1'], ['4', '6', '2', '1', '1'], ['4', '7', '3', '8', '1'], ['1', '2', '4', '1', '1'], ['2', '3', '5', '1', '1'], ['7', '8', '6', '1', '1'], ['7', '9', '7', '1', '1'], ['2', '4', '8', '3', '1']] </code></pre> <p>What would be the easiest way to do so? I could probably loop over the lists and add the index, but is there a cleaner way to do so?</p> <p>Cheers, Kate</p> <p>Edit: The code I wrote works for me:</p> <pre><code>item = 1 for list in listBefore: list.insert(2,str(item)) item = item + 1 print listBefore </code></pre> <p>I was wondering if there is another way to do so more efficiently or in one step.</p>
1
2016-10-05T04:10:15Z
39,865,388
<p>You can perform this with a list comprehension</p> <pre><code>listAfter = [listBefore[i][:len(listBefore[i])/2] + [str(i+1)] + listBefore[i][len(listBefore[i])/2:] for i in range(len(listBefore))] </code></pre>
1
2016-10-05T04:20:15Z
[ "python", "list" ]