Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
0
20,581,479
Can python or JS hide video embedded source?
<p>I'm doing a video website right now and I would like to hide the embedded source of the video from being seen by beginner programmer. (I know they are no 100% way to hide the video embeded source).</p> <p>Any experience programmer knows how python or JS can help to do this? or it can't?</p>
<p>For Javascript, hiding code (almost) cannot be done!</p> <p>However, if your code is sensetive in any manner, try using obfuscators so that the code will not be readable by human eye.</p> <p>Here are few obfuscation services:</p> <ol> <li><p>Free Javascript Obfuscator: <a href="http://javascriptobfuscator.com/" rel="nofollow">Javascript Obfuscator</a></p></li> <li><p>Uglify JS: <a href="https://github.com/mishoo/UglifyJS" rel="nofollow">Uglify JS</a></p></li> <li><p><a href="http://www.jsobfuscate.com/" rel="nofollow">JSObfuscate to Obfuscate JS/jQuery</a></p></li> <li><p>JScrambler 3: <a href="https://jscrambler.com/" rel="nofollow">JScrambler 3</a></p></li> </ol> <p><strong>UPDATE</strong>: Use this tutorial to get a heads-up: <a href="http://techcrunch.com/2013/04/17/improved-jscramber-3-helps-javascript-and-html5-developers-obfuscate-their-code/" rel="nofollow">Improved JScrambler 3 Helps JavaScript And HTML5 Developers Obfuscate Their Code</a></p>
javascript|jquery|python|video|video-streaming
3
1
71,894,592
How to concatenate database elements to a string
<p>I'm currently trying to take elements from a database to be displayed in a string by iterating through each row and adding it to an empty string.</p> <pre><code> def PrintOverdueBooks(): printed_message = &quot;&quot; for row in db_actions.GetAllOverdue(): printed_message += row printed_message += &quot; \n&quot; print(printed_message) </code></pre> <p>Whenever the function is called I receive an error stating that &quot;row&quot; is a tuple and cannot be concatenated to a string. Using <strong>.join</strong> also creates an error.</p>
<p>You can try this:</p> <pre><code>def PrintOverdueBooks(): printed_message = '' for row in db_actions.GetAllOverdue(): stup = ''.join(row) printed_message += stup print(printed_message) </code></pre>
python|database|concatenation
0
2
36,150,410
'DataFrame' object has no attribute 'value_counts'
<p>My dataset is a DataFrame of dimension (840,84). When I write the code: <code>ds[ds.columns[1]].value_counts()</code><br> I get a correct output:</p> <pre><code>Out[82]: 0 847 1 5 Name: o_East, dtype: int64 </code></pre> <p>But when I write a loop to store values, I get <em>'DataFrame' object has no attribute 'value_counts'</em>. I can't explain why ... </p> <pre><code>wind_vec = [] wind_vec = [(ds[x].value_counts()) for x in ds.columns] </code></pre> <p><strong>UPDATE FOR THE CODE</strong></p> <pre><code>import pandas as pd import numpy as np import numpy.ma as ma import statsmodels.api as sm import matplotlib import matplotlib.pyplot as plt from sklearn.preprocessing import OneHotEncoder dataset = pd.read_csv('data/dataset.csv') ds = dataset o_wdire = pd.get_dummies(ds['o_wdire']) s_wdire = pd.get_dummies(ds['s_wdire']) t_wdire = pd.get_dummies(ds['t_wdire']) k_wdire = pd.get_dummies(ds['k_wdire']) b_wdire = pd.get_dummies(ds['b_wdire']) o_wdire.rename(columns={'ENE': 'o_ENE','ESE': 'o_ESE', 'East': 'o_East', 'NE': 'o_NE', 'NNE': 'o_NNE', 'NNW': 'o_NNW', \ 'NW': 'o_NW', 'North': 'o_North', 'SE': 'o_SE', 'SSE': 'o_SSE', 'SSW': 'o_SSW', 'SW': 'o_SW', \ 'South': 'o_South', 'Variable': 'o_Variable', 'WSW': 'o_WSW','West':'o_West'}, inplace=True) s_wdire.rename(columns={'ENE': 's_ENE','ESE': 's_ESE', 'East': 's_East', 'NE': 's_NE', 'NNE': 's_NNE', 'NNW': 's_NNW', \ 'NW': 's_NW', 'North': 's_North', 'SE': 's_SE', 'SSE': 's_SSE', 'SSW': 's_SSW', 'SW': 's_SW', \ 'South': 's_South', 'Variable': 's_Variable', 'West': 's_West','WSW': 's_WSW'}, inplace=True) k_wdire.rename(columns={'ENE': 'k_ENE','ESE': 'k_ESE', 'East': 'k_East', 'NE': 'k_NE', 'NNE': 'k_NNE', 'NNW': 'k_NNW', \ 'NW': 'k_NW', 'North': 'k_North', 'SE': 'k_SE', 'SSE': 'k_SSE', 'SSW': 'k_SSW', 'SW': 'k_SW', \ 'South': 'k_South', 'Variable': 'k_Variable', 'WNW': 'k_WNW', 'West': 'k_West','WSW': 'k_WSW'}, inplace=True) b_wdire.rename(columns={'ENE': 'b_ENE','ESE': 'b_ESE', 'East': 'b_East', 'NE': 'b_NE', 'NNE': 'b_NNE', 'NNW': 'b_NNW', \ 'NW': 'b_NW', 'North': 'b_North', 'SE': 'b_SE', 'SSE': 'b_SSE', 'SSW': 'b_SSW', 'SW': 'b_SW', \ 'South': 'b_South', 'Variable': 'b_Variable', 'WSW': 'b_WSW', 'WNW': 'b_WNW', 'West': 'b_West'}, inplace=True) t_wdire.rename(columns={'ENE': 't_ENE','ESE': 't_ESE', 'East': 't_East', 'NE': 't_NE', 'NNE': 't_NNE', 'NNW': 't_NNW', \ 'NW': 't_NW', 'North': 't_North', 'SE': 't_SE', 'SSE': 't_SSE', 'SSW': 't_SSW', 'SW': 't_SW', \ 'South': 't_South', 'Variable': 't_Variable', 'WSW': 't_WSW', 'WNW': 't_WNW', 'West':'t_West'}, inplace=True) #WIND ds_wdire = pd.DataFrame(pd.concat([o_wdire,s_wdire,t_wdire,k_wdire,b_wdire],axis=1)) ds_wdire = ds_wdire.astype('float64') In [93]: ds_wdire.shape Out[93]: (852, 84) In[101]: ds_wdire[ds_wdire.columns[0]].head() Out[101]: 0 0 1 0 2 0 3 0 4 0 Name: o_ENE, dtype: float64 In[103]: ds_wdire[ds_wdire.columns[0]].value_counts() Out[103]: 0 838 1 14 Name: o_ENE, dtype: int64 In[104]: [ds_wdire[x].value_counts() for x in ds_wdire.columns] --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-104-d9756c468818&gt; in &lt;module&gt;() 1 #Filtering for the wind direction based on the most frequent ones. ----&gt; 2 [ds_wdire[x].value_counts() for x in ds_wdire.columns] &lt;ipython-input-104-d9756c468818&gt; in &lt;listcomp&gt;(.0) 1 #Filtering for the wind direction based on the most frequent ones. ----&gt; 2 [ds_wdire[x].value_counts() for x in ds_wdire.columns] /home/florian/anaconda3/lib/python3.5/site-packages/pandas/core/generic.py in __getattr__(self, name) 2358 return self[name] 2359 raise AttributeError("'%s' object has no attribute '%s'" % -&gt; 2360 (type(self).__name__, name)) 2361 2362 def __setattr__(self, name, value): AttributeError: 'DataFrame' object has no attribute 'value_counts' </code></pre>
<p>Thanks to @EdChum adviced, I checked :</p> <pre><code>len(ds_wdire.columns),len(ds_wdire.columns.unique()) Out[100]: (83,84) </code></pre> <p>Actually, there was a missing name value in the dict that should have been modified from 'WNW' to 'o_WNW'.:</p> <pre><code>o_wdire.rename(columns={'ENE': 'o_ENE','ESE': 'o_ESE', 'East': 'o_East', 'NE': 'o_NE', 'NNE': 'o_NNE', 'NNW': 'o_NNW', \ 'NW': 'o_NW', 'North': 'o_North', 'SE': 'o_SE', 'SSE': 'o_SSE', 'SSW': 'o_SSW', 'SW': 'o_SW', \ 'South': 'o_South', 'Variable': 'o_Variable', 'WSW': 'o_WSW','West':'o_West', **[MISSING VALUE WNW]**}, inplace=True) </code></pre> <p>Maybe it would be better to write a loop that inserts a prefix to the wind direction variables, this way, I would avoid that kind of problem.</p>
python|python-2.7|pandas|dataframe
1
3
46,529,659
How to find ellipses in text string Python?
<p>Fairly new to Python (And Stack Overflow!) here. I have a data set with subject line data (text strings) that I am working on building a bag of words model with. I'm creating new variables that flags a 0 or 1 for various possible scenarios, but I'm stuck trying to identify where there is an ellipsis ("...") in the text. Here's where I'm starting from:</p> <pre><code>Data_Frame['Elipses'] = Data_Frame.Subject_Line.str.match('(\w+)\.{2,}(.+)') </code></pre> <p>Inputting ('...') doesn't work for obvious reasons, but the above RegEx code was suggested--still not working. Also tried this:</p> <pre><code>Data_Frame['Elipses'] = Data_Frame.Subject_Line.str.match('.\.\.\') </code></pre> <p>No dice.</p> <p>The above code shell works for other variables I've created, but I'm also having trouble creating a 0-1 output instead of True/False (would be an 'as.numeric' argument in R.) Any help here would also be appreciated.</p> <p>Thanks!</p>
<p>Using <code>search()</code> instead of <code>match()</code> would spot an ellipses at any point in the text. If you need <code>0</code> or <code>1</code> to be returned, convert to bool and then int.</p> <pre><code>import re for test in ["hello..", "again... this", "is......a test", "...def"]: print int(bool(re.search(r'(\w+)\.{3,}', test))) </code></pre> <p>This matches on the middle two tests:</p> <pre class="lang-none prettyprint-override"><code>0 1 1 0 </code></pre> <p>Take a look at <a href="https://docs.python.org/2/library/re.html#search-vs-match" rel="nofollow noreferrer">search-vs-match</a> for a good explanation in the Python docs.</p> <hr> <p>To display the matching words:</p> <pre><code>import re for test in ["hello..", "again... this", "is......a test", "...def"]: ellipses = re.search(r'(\w+)\.{3,}', test) if ellipses: print ellipses.group(1) </code></pre> <p>Giving you:</p> <pre class="lang-none prettyprint-override"><code>again is </code></pre>
python|regex
2
4
60,791,304
google.cloud namespace import error in __init__.py
<p>I have read through at least a dozen different stackoverflow questions that all present the same basic problem and have the same basic answer: either the module isn't installed correctly or the OP is doing the import wrong.</p> <p>In this case, I am trying to do <code>from google.cloud import secretmanager_v1beta1</code>. </p> <p>It works in my airflow container when I run <code>airflow dags</code> or if I run <code>pytest tests/dags/test_my_dag.py</code>. However, if I run <code>cd dags; python -m my_dag</code> or <code>cd dags; python my_dag.py</code> I get this error:</p> <pre><code>from google.cloud import secretmanager as secretmanager ImportError: cannot import name 'secretmanager' from 'google.cloud' (unknown location) </code></pre> <p>I can add <code>from google.cloud import bigquery</code> in the line right above this line and that works OK. It appears to literally just be a problem with this particular package. </p> <p>Why does it matter if pytest and airflow commands succeed? Because, I have another environment where I am trying to run dataflow jobs from the command-line and I get this same error. And unfortunately I don't think I can bypass this error in that environment for several reasons.</p> <p><strong>UPDATE 6</strong></p> <p>I have narrowed down the error to an issue with the <code>google.cloud</code> namespace and the <code>secretmanager</code> package within that namespace in the <code>__init__.py</code> file.</p> <p>If I add <code>from google.cloud import secretmanager</code> to <code>airflow/dags/__init__.py</code> and then try to run <code>python -m dags.my_dag.py</code>, I receive this error but with a slightly different stacktrace:</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python3.7/runpy.py", line 183, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "/usr/local/lib/python3.7/runpy.py", line 109, in _get_module_details __import__(pkg_name) File "/workspace/airflow/dags/__init__.py", line 3, in &lt;module&gt; from google.cloud import secretmanager ImportError: cannot import name 'secretmanager' from 'google.cloud' (unknown location) </code></pre> <p><strong>OLD INFORMATION</strong></p> <p><s>I am 95% sure that it's still a path problem and that pytest and airflow are fixing something I'm not aware of that isn't handled when I try to manually run the python script.</s></p> <p>Things I have tried:</p> <pre><code>cd /airflow; python setup.py develop --user cd /airflow; pip install -e . --user cd /airflow/dags; pip install -r requirements.txt --user </code></pre> <p><strong>UPDATE</strong></p> <p>As per requests in the comments, here are the contents of <code>requirements.txt</code>:</p> <pre><code>boto3&gt;=1.7.84 google-auth==1.11.2 google-cloud-bigtable==1.2.1 google-cloud-bigquery==1.24.0 google-cloud-spanner==1.14.0 google-cloud-storage==1.26.0 google-cloud-logging==1.14.0 google-cloud-secret-manager&gt;=0.2.0 pycloudsqlproxy&gt;=0.0.15 pyconfighelper&gt;=0.0.7 pymysql==0.9.3 setuptools==45.2.0 six==1.14.0 </code></pre> <p>And I accidentally omitted the <code>--user</code> flags from the pip and python installation command examples above. In my container environment everything is installed into the user's home directory using <code>--user</code> and <strong>NOT</strong> in the global <code>site-packages</code> directory.</p> <p><strong>UPDATE 2</strong></p> <p>I've added the following code to the file that is generating the error:</p> <pre><code>print('***********************************************************************************') import sys print(sys.path) from google.cloud import secretmanager_v1beta1 as secretmanager print('secretmanager.__file__: {}'.format(secretmanager.__file__)) </code></pre> <p>From <code>airflow list_dags</code>:</p> <pre><code>['/home/app/.local/bin', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/home/app/.local/lib/python3.7/site-packages', '/home/app/.local/lib/python3.7/site-packages/Jeeves-0.0.1-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/google_cloud_secret_manager-0.2.0-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/pyconfighelper-0.0.7-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/click-7.1.1-py3.7.egg', '/workspace/airflow', '/usr/local/lib/python3.7/site-packages', '/workspace/airflow/dags', '/workspace/airflow/config', '/workspace/airflow/plugins'] secretmanager.__file__: /home/app/.local/lib/python3.7/site-packages/google_cloud_secret_manager-0.2.0-py3.7.egg/google/cloud/secretmanager_v1beta1/__init__.py </code></pre> <p>From <code>python my_dag.py</code>:</p> <pre><code>['/workspace/airflow/dags', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/home/app/.local/lib/python3.7/site-packages', '/home/app/.local/lib/python3.7/site-packages/Jeeves-0.0.1-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/google_cloud_secret_manager-0.2.0-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/pyconfighelper-0.0.7-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/click-7.1.1-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/icentris_ml_airflow-0.0.0-py3.7.egg', '/usr/local/lib/python3.7/site-packages'] </code></pre> <p><strong>UPDATE 3</strong> <code>tree airflow/dags</code></p> <pre><code>airflow/dags ├── __init__.py ├── __pycache__ │   ├── __init__.cpython-37.pyc │   ├── bq_to_cs.cpython-37.pyc │   ├── bq_to_wrench.cpython-37.pyc │   ├── fetch_cloudsql_tables-bluesun.cpython-37.pyc │   ├── fetch_cloudsql_tables.cpython-37.pyc │   ├── fetch_app_tables-bluesun.cpython-37.pyc │   ├── fetch_app_tables.cpython-37.pyc │   ├── gcs_to_cloudsql.cpython-37.pyc │   ├── gcs_to_s3.cpython-37.pyc │   ├── lake_to_staging.cpython-37.pyc │   ├── schedule_dfs_sql_to_bq-bluesun.cpython-37.pyc │   ├── schedule_dfs_sql_to_bq.cpython-37.pyc │   ├── app_to_bq_initial_load-bluesun.cpython-37.pyc │   ├── app_to_lake-bluesun.cpython-37.pyc │   └── app_to_lake.cpython-37.pyc ├── bq_to_wrench.py ├── composer_variables.json ├── my_ml_airflow.egg-info │   ├── PKG-INFO │   ├── SOURCES.txt │   ├── dependency_links.txt │   └── top_level.txt ├── lake_to_staging.py ├── libs │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-37.pyc │   │   ├── checkpoint.cpython-37.pyc │   │   └── utils.cpython-37.pyc │   ├── checkpoint.py │   ├── io │   │   ├── __init__.py │   │   ├── __pycache__ │   │   │   └── __init__.cpython-37.pyc │   │   └── gcp │   │   ├── __init__.py │   │   ├── __pycache__ │   │   │   ├── __init__.cpython-37.pyc │   │   │   └── storage.cpython-37.pyc │   │   └── storage.py │   ├── shared -&gt; /workspace/shared/ │   └── utils.py ├── requirements.txt ├── table_lists │   └── table-list.json └── templates └── sql ├── lake_to_staging.contacts.sql ├── lake_to_staging.orders.sql └── lake_to_staging.users.sql 11 directories, 41 files </code></pre> <p><strong>UPDATE 4</strong></p> <p>I tried fixing it so that <code>sys.path</code> looked the same when running <code>python dags/my_dag.py</code> as it does when running <code>airflow list_dags</code> or <code>pytest test_my_dag.py</code>.</p> <p>Still get the same error. </p> <p>Looking at a more recent version of documentation, I noticed that you <em>should</em> be able to just do <code>from google.cloud import secretmanager</code>. Which gave me the same result (works with airflow and pytest, not when trying to run directly). </p> <p>At this point, my best guess is that it has something to do with namespace magic, but I'm not sure?</p>
<p>It have to be installed via terminal: <code>pip install google-cloud-secret-manager</code> Because package name is not secretmanager but google-cloud-secret-manager</p>
python-3.x|google-cloud-platform|python-import|google-secret-manager
8
5
49,532,854
Python - Multiple 'split' Error
<p>I posted here 4-5 days ago, about one problem to sort some numbers from file. Now, is the same of the other problem but, I want to sort numbers from one file (x) to another file (y). For example: In x i have: (5,6,3,11,7), and I want to sort this numbers to y (3,5,6,7,11). But I have some errors and can't resolve on my own, I do not understand them, can you help me?</p> <pre><code>from sys import argv try: with open(argv[1],"r") as desti: cad = desti.readlines() k= list(cad) for n in range(len(cad)): k = n.split(',') k = (int, cad) k = sorted(cad) with open("nums_ordenats.txt","w") as prl: prl.write(k) except Exception as err: print(err, "Error") </code></pre> <p>Actually, the error message is " 'int' object has no attribute 'split' Error ". I think the code is correct. Also, the program says me other errors, but how im changintg code everytime, they also change. </p> <p>Tanks a lot! </p>
<p>There are too many problems with your code for me to address. Try this:</p> <pre><code>from sys import argv with open(argv[1], "r") as infile: with open("nums_ordenats.txt", "w") as outfile: for line in infile: nums = [int(n) for n in line.split(',')] nums.sort() outfile.write(','.join([str(n) for n in nums])) outfile.write('\n') </code></pre>
python|python-3.x|list|sorting|tuples
0
6
62,587,462
PyQT - QlistWidget with infinite scroll
<p>I have a QlistWidget and I need to implement on this an Infinite Scroll, something like this HTML example:</p> <p><a href="https://scrollmagic.io/examples/advanced/infinite_scrolling.html" rel="nofollow noreferrer">https://scrollmagic.io/examples/advanced/infinite_scrolling.html</a></p> <p>Basically, when the user scrolls to the last item of the list, I need to load more items and dynamically append it in the QlistWidget.</p> <p>Is it possible? I didn't find any example yet.</p>
<p>There are likely many ways to achieve this task, but the easiest I found is to watch for changes in the scroll bar, and detect if we're at the bottom before adding more items to the list widget.</p> <pre><code>import sys, random from PyQt5.QtWidgets import QApplication, QListWidget class infinite_scroll_area(QListWidget): #https://doc.qt.io/qt-5/qlistwidget.html def __init__(self): super().__init__() #call the parent constructor if you're overriding it. #connect our own function the valueChanged event self.verticalScrollBar().valueChanged.connect(self.valueChanged) self.add_lines(15) self.show() def valueChanged(self, value): #https://doc.qt.io/qt-5/qabstractslider.html#valueChanged if value == self.verticalScrollBar().maximum(): #if we're at the end self.add_lines(5) def add_lines(self, n): for _ in range(n): #add random lines line_text = str(random.randint(0,100)) + ' some data' self.addItem(line_text) if __name__ == &quot;__main__&quot;: app = QApplication(sys.argv) widget = infinite_scroll_area() sys.exit(app.exec_()) </code></pre> <p>You can directly grab scroll wheel events by overriding the <a href="https://doc.qt.io/qt-5/qlistview.html#wheelEvent" rel="nofollow noreferrer"><code>wheelEvent</code></a> method of <code>QListWidget</code>, then do the logic there which solves the potential problem of not starting out with enough list items for the scrollbar to appear. If it's not there, it can't change value, and the event can't fire. It introduces a new problem however as scrolling with the mouse wheel is not the only way to scroll the view (arrow keys, page up/down keys, etc). With the number of classes and subclasses in any gui library, it becomes imperative to get really familiar with the documentation. It's a little inconvenient that it isn't as comprehensive for python specifically, but I think the c++ docs are second to none as far as gui library documentation goes.</p>
python|pyqt|pyqt5|qlistwidget
1
7
53,736,868
How to correctly import custom widgets in kivy
<p>I have a widget(W2), made of other widgets (W1). Each has a corresponding .kv file as below. Running main.py, I expect to see a black background with two labels, vertically stacked. Instead, I get both labels on top of each other, so something has gone wrong.</p> <pre><code>kivy.factory.FactoryException: Unknown class &lt;W1&gt; </code></pre> <p>So I thought, "Maybe I should import w1.py in w2.py even though it's not explicitly used in the py file? That ... sort of worked. I get both labels on top of each other, as in the following image.</p> <p><a href="https://i.stack.imgur.com/Nn8yy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nn8yy.png" alt="enter image description here"></a></p> <p>What am I doing wrong? What is the correct way to write a widget that is expected to be imported/included by another widget? And the correct way to import it?</p> <p>I tried using <code>Builder.load_file()</code> in the .py file and just importing the .py file but that had similar results.</p> <p><strong>w1.py:</strong></p> <pre><code>import kivy from kivy.properties import StringProperty from kivy.uix.widget import Widget kivy.require('1.10.0') class W1(Widget): text = StringProperty('default') def __init__(self, **kwargs): super(W1, self).__init__(**kwargs) </code></pre> <p><strong>w1.kv:</strong></p> <pre><code>#:kivy 1.10.0 &lt;W1&gt;: text: Label: text: root.text </code></pre> <p><strong>w2.py:</strong></p> <pre><code>import kivy from kivy.uix.boxlayout import BoxLayout # from w1 import W1 # added this to get a working, but the incorrect layout kivy.require('1.10.0') class W2(BoxLayout): def __init__(self, **kwargs): super(W2, self).__init__(**kwargs) </code></pre> <p><strong>w2.kv:</strong></p> <pre><code>#:kivy 1.10.0 #:include w1.kv &lt;W2&gt;: orientation: 'vertical' W1: text: 'w1.1' W1: text: 'w1.2' </code></pre> <p><strong>main.py:</strong></p> <pre><code>import kivy from w2 import W2 from kivy.app import App kivy.require('1.10.0') class mainApp(App): def build(self): pass if __name__ == '__main__': mainApp().run() </code></pre> <p><strong>main.kv:</strong></p> <pre><code>#:kivy 1.10.0 #:include w2.kv W2: </code></pre> <p><strong>EDIT</strong> The overlapping has been resolved, though maybe not correctly. I had W1 inherit from BoxLayout rather than Widget, with the thought that maybe there was a minimum height/width property missing in the base Widget class.</p> <p>I'm still not certain what the "correct" way to handle importing a widget which has a paired .kv file is, or exactly why I'm getting overlapping widgets when I inherit from Widget; only speculation. <a href="https://i.stack.imgur.com/lxaPe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lxaPe.png" alt="enter image description here"></a></p>
<p>why are you using two different kv files for this? I would say the proper way would be similar to what i have with my kv file. because you are spliting up things that can be done on a single page and if you need different pages you use the <code>ScreenManager</code> import stuff</p> <p><strong>main.py</strong>:</p> <pre><code>` import kivy from kivy.app import App from kivy.uix.widgets import Widget from kivy.uix.label import Label from kivy.uix.gridlayut import GridLayout class MyGrid(Widget): pass class MyApp(App): def build(self): # this calls what we want to show in the kv file return MyGrid() if __name__ == &quot;__main__&quot;: MyApp().run() ` </code></pre> <h1>file is written like this because the App falls off and in order to link the 2 it must have the same name</h1> <p><strong>my.kv</strong>: # &quot;&lt;&gt;&quot; Basically links <code>MyGrid</code> from the .py file and then displays the # gridlayout and such GridLayout: rows: 2</p> <pre><code> Label: text: &quot;whatever&quot; Label: text: &quot;whatever 2&quot; </code></pre>
python-3.x|kivy|kivy-language
0
8
53,456,874
ImportError: cannot import name 'convert_kernel'
<p>When i try to use tensorflow to train model, i get this error message. </p> <p>File "/Users/ABC/anaconda3/lib/python3.6/site-packages/keras/utils/layer_utils.py", line 7, in from .conv_utils import convert_kernel</p> <p>ImportError: cannot import name 'convert_kernel'</p> <p>i have already install Keras</p>
<p>I got the same issue. The filename of my python code was "tensorflow.py". After I changed the name to "test.py". The issue was resolved.</p> <p>I guess there is already a "tensorflow.py" in the tensorflow package. If anyone uses the same name, it may lead to the conflict.</p> <p>If your python code is also called "tensorflow.py", you can try to use other names and see if it helps.</p>
python|tensorflow
1
9
53,467,807
Python function that identifies if the numbers in a list or array are closer to 0 or 1
<p>I have a <code>numpy</code> array of numbers. Below is an example:</p> <pre><code>[[-2.10044520e-04 1.72314372e-04 1.77235336e-04 -1.06613465e-04 6.76617611e-07 2.71623057e-03 -3.32789944e-05 1.44899758e-05 5.79249863e-05 4.06502549e-04 -1.35823707e-05 -4.13955189e-04 5.29862793e-05 -1.98286005e-04 -2.22829175e-04 -8.88758230e-04 5.62228710e-05 1.36249752e-05 -2.00474996e-05 -2.10090068e-05 1.00007518e+00 1.00007569e+00 -4.44597417e-05 -2.93724453e-04 1.00007513e+00 1.00007496e+00 1.00007532e+00 -1.22357142e-03 3.27903892e-06 1.00007592e+00 1.00007468e+00 1.00007558e+00 2.09869172e-05 -1.97610235e-05 1.00007529e+00 1.00007530e+00 1.00007503e+00 -2.68725642e-05 -3.00372853e-03 1.00007386e+00 1.00007443e+00 1.00007388e+00 5.86993822e-05 -8.69989983e-06 1.00007590e+00 1.00007488e+00 1.00007515e+00 8.81850779e-04 2.03875532e-05 1.00007480e+00 1.00007425e+00 1.00007517e+00 -2.44678912e-05 -4.36556267e-08 1.00007436e+00 1.00007558e+00 1.00007571e+00 -5.42990711e-04 1.45517859e-04 1.00007522e+00 1.00007469e+00 1.00007575e+00 -2.52271817e-05 -7.46339417e-05 1.00007427e+00]] </code></pre> <p>I want to know if each of the numbers is closer to 0 or 1. Is there a function in Python that could do it or do I have to do it manually?</p>
<p>A straightforward way:</p> <pre><code>lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] closerTo1 = [x &gt;= 0.5 for x in lst] </code></pre> <p>Or you can use np:</p> <pre><code>import numpy as np lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] arr = np.array(lst) closerTo1 = arr &gt;= 0.5 </code></pre> <p>Note that <code>&gt;= 0.5</code> can be changed to <code>&gt; 0.5</code>, however you choose to treat it.</p>
python|arrays|list|function|numpy
22
10
53,424,798
Python pandas: map and return Nan
<p>I have two data frame, the first one is:</p> <pre><code>id code 1 2 2 3 3 3 4 1 </code></pre> <p>and the second one is:</p> <pre><code>id code name 1 1 Mary 2 2 Ben 3 3 John </code></pre> <p>I would like to map the data frame 1 so that it looks like:</p> <pre><code>id code name 1 2 Ben 2 3 John 3 3 John 4 1 Mary </code></pre> <p>I try to use this code:</p> <pre><code>mapping = dict(df2[['code','name']].values) df1['name'] = df1['code'].map(mapping) </code></pre> <p>My mapping is correct, but the mapping value are all NAN:</p> <pre><code>mapping = {1:"Mary", 2:"Ben", 3:"John"} id code name 1 2 NaN 2 3 NaN 3 3 NaN 4 1 NaN </code></pre> <p>Can anyone know why an how to solve? </p>
<p>Problem is different type of values in column <code>code</code> so necessary converting to integers or strings by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="noreferrer"><code>astype</code></a> for same types in both:</p> <pre><code>print (df1['code'].dtype) object print (df2['code'].dtype) int64 </code></pre> <pre><code>print (type(df1.loc[0, 'code'])) &lt;class 'str'&gt; print (type(df2.loc[0, 'code'])) &lt;class 'numpy.int64'&gt; </code></pre> <hr> <pre><code>mapping = dict(df2[['code','name']].values) #same dtypes - integers df1['name'] = df1['code'].astype(int).map(mapping) </code></pre> <pre><code>#same dtypes - object (obviously strings) df2['code'] = df2['code'].astype(str) mapping = dict(df2[['code','name']].values) df1['name'] = df1['code'].map(mapping) </code></pre> <hr> <pre><code>print (df1) id code name 0 1 2 Ben 1 2 3 John 2 3 3 John 3 4 1 Mary </code></pre>
python|pandas|dataframe
6
11
54,843,657
How to select a specific range of cells in an Excel worksheet with Python library tools
<p>I would like to select a specific range of cells in a workbook worksheet. I am currently able to set a variable to a workbook worksheet with the line below.</p> <pre><code> import pandas as pd sheet1 = pd.read_excel('workbookname1.xlsx', sheet_name = ['sheet1']) </code></pre> <p>I would like to go one step further and have the ability to select a range of cells in the worksheet so that I can practice dataframe functionality with the defined range. Some of my ranges are with row values greater than 1000. How am I able to select a variable length row value for the desired excel range?</p>
<p>You can utilize <code>OpenPyXl</code> module.</p> <pre><code>from openpyxl import Workbook, load_workbook wb = load_workbook("workbookname1.xlsx") ws = wb.active cell_range = ws['A1':'C2'] </code></pre> <p>You can also use <code>iter_rows()</code> or <code>iter_columns()</code> methods.</p> <p>For additional information, you can refer to <a href="https://media.readthedocs.org/pdf/openpyxl/latest/openpyxl.pdf" rel="nofollow noreferrer">OpenPyXL documentation</a>.</p>
python|pandas|series
2
12
33,204,160
Listing all class members with Python `inspect` module
<p>What is the "optimal" way to list all class methods of a given class using <code>inspect</code>? It works if I use the <code>inspect.isfunction</code> as predicate in <code>getmembers</code> like so</p> <pre><code>class MyClass(object): def __init(self, a=1): pass def somemethod(self, b=1): pass inspect.getmembers(MyClass, predicate=inspect.isfunction) </code></pre> <p>returns</p> <pre><code>[('_MyClass__init', &lt;function __main__.MyClass.__init&gt;), ('somemethod', &lt;function __main__.MyClass.somemethod&gt;)] </code></pre> <p>But isn't it supposed to work via <code>ismethod</code>?</p> <pre><code> inspect.getmembers(MyClass, predicate=inspect.ismethod) </code></pre> <p>which returns an empty list in this case. Would be nice if someone could clarify what's going on. I was running this in Python 3.5.</p>
<p>As described in the documentation, <a href="https://docs.python.org/3/library/inspect.html#inspect.ismethod" rel="noreferrer"><code>inspect.ismethod</code></a> will show bound methods. This means you have to create an instance of the class if you want to inspect its methods. Since you are trying to inspect methods on the un-instantiated class you are getting an empty list.</p> <p>If you do:</p> <pre><code>x = MyClass() inspect.getmembers(x, predicate=inspect.ismethod) </code></pre> <p>you would get the methods.</p>
python|class|inspect
10
13
33,425,495
Groupby in pandas multiplication
<p>I have a data frame called <code>bf</code>. The commas are mine, it was imported from a csv file.</p> <pre><code>val,ben a,123 b,234 c,123 </code></pre> <p>I have another larger data frame <code>df</code></p> <pre><code> bla,val, blablab, blablaa 1,a,123,333 2,b,333,222 3,c,12,33 1,a,123,333 ..... </code></pre> <p>I would like to create a new data frame which multiplies all rows of <code>df</code> with the specific value corresponding to <code>ben</code> for it, taken from <code>bf</code>. For exaple the first row of this new data frame will be <code>1,a,123*123,333*123</code> How do we do that using pandas and groupby?</p> <p>EDIT: Note that <code>bf</code> and <code>df</code> have different lengths.</p>
<p>Probably you want to use a merge to bring in the column <code>ben</code> into your dataframe:</p> <pre><code>df_merged = pd.merge(df, bf, on='val') </code></pre> <p>Then you can calculate your product however you like, for example:</p> <pre><code>df_prod = df_merged * df_merged.ben </code></pre>
python|pandas|group-by
1
14
13,055,309
Why doesn't this python function with a dictionary named parameter and a default value apply the default value each time it's called?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">“Least Astonishment” in Python: The Mutable Default Argument</a> </p> </blockquote> <p>The following code illustrates the issue:</p> <pre><code>def fn(param, named_param={}, another_named_param=1): named_param[param] = str(another_named_param) another_named_param += param return named_param for i in range(0, 2): result = {} result = fn(i) print result print for i in range(0, 2): result = fn(i, named_param={}) print result print result = fn(0) print result result = fn(1) print result </code></pre> <p>Output:</p> <pre><code>{0: '1'} {0: '1', 1: '1'} {0: '1'} {1: '1'} {0: '1', 1: '1'} {0: '1', 1: '1'} </code></pre> <p>I expected the output of the 1st, 2nd loop and subsequent 2 single calls with param matching the values of the for loop would have the same textual output, but <code>fn</code> holds onto the value of <code>named_param</code> if not explicitly defaulted to an empty dictionary. Is functionality defined in the documentation?</p>
<p>The default value of <code>named_param</code> is evaluated once, when the function definition is executed. It is the same dictionary each time and its value is retained between calls to the function.</p> <p>Do not use mutable objects as default values in functions unless you do not mutate them. Instead, use <code>None</code> or another sentinel value, and check for that value and replace it with a fresh object (e.g. empty dictionary). This way you get a fresh one each time your function is called.</p>
python
1
15
12,921,260
Importing a class to another class in python
<p>I am trying to learn python i tried to import a class in another class but it is not working</p> <p><code>Application.py</code>:</p> <pre><code>class Application: def example(self): return "i am from Application class" </code></pre> <p><code>Main.py</code></p> <pre><code>class Main: def main(): application = Application() application.example() if __name__ == "__main__": Main.main() </code></pre> <p>This gives me :</p> <pre><code>File "Main.py", line 11, in &lt;module&gt; Main.main() TypeError: unbound method main() must be called with Main instance as first argument (got nothing instead) </code></pre>
<p>You should instantiate your Main class first. </p> <pre><code>if __name__ == '__main__': myMain = Main() myMain.main() </code></pre> <p>But this will give you another error:</p> <blockquote> <p>TypeError: main() takes no arguments (1 given)</p> </blockquote> <p>There are two ways to fix this. Either make Main.main take one argument:</p> <pre><code>class Main: def main(self): application = Application() application.example() </code></pre> <p>or make Main.main a static method. In which case you don't have to instantiate your Main class:</p> <pre><code>class Main: @staticmethod def main(): application = Application() application.example() if __name__ == "__main__": Main.main() </code></pre>
python
0
16
21,924,444
Jinja2 extensions - get the value of variable passed to extension
<p>So I have a Jinja2 extension. Basically follows the parser logic, except that I need to get a value from the parsed args being passed in.</p> <p>For instance, if I have an extension called loadfile, and pass it a variable:</p> <p><code>{% loadfile "file.txt" %}</code></p> <p>when I grab the argument through <code>parser.parse_expression()</code> I get a <code>node.Const</code> variable that has a <code>.value</code> argument - and I can get the name <code>file.txt</code> no problem.</p> <p>However...</p> <pre><code>{% set filename = "file.txt" %} {% loadfile filename %} </code></pre> <p>causes me issues. The parser gives me a <code>node.Name</code> expr node, which neither responds to <code>.value</code> or the <code>as_const(...)</code> call that all other nodes respond to.</p> <p>I can't figure out how to evaluate the value of the <code>node.Name</code> node I'm getting from parsing the arguments, and thus cannot get the name <code>file.txt</code>.</p> <p>Is there a good way to parse argument variables/values in an extension so that I can use them to execute the extention?</p> <p>Thanks!</p>
<p>This works for me</p> <pre><code>def parse(self, parser): lineno = parser.stream.next().lineno # args will contains filename args = [parser.parse_expression()] return nodes.Output([ nodes.MarkSafeIfAutoescape(self.call_method('handle', args)) ]).set_lineno(lineno) def handle(self, filename): # bla-bla-bla </code></pre>
python|jinja2
1
17
24,472,957
Get relative links from html page
<p>I want to extract only relative urls from html page; somebody has suggest this :</p> <pre><code>find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'&lt;&gt;=\s]+)', re.IGNORECASE) </code></pre> <p>but it return :</p> <p>1/all absolute and relative urls from the page.</p> <p>2/the url may be quated by <code>""</code> or <code>''</code> randomly .</p>
<p>Use <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">the tool for the job</a>: an <code>HTML parser</code>, like <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer"><code>BeautifulSoup</code></a>.</p> <p>You can <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow noreferrer">pass a function</a> as an attribute value to <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow noreferrer"><code>find_all()</code></a> and check whether <code>href</code> starts with <code>http</code>:</p> <pre><code>from bs4 import BeautifulSoup data = """ &lt;div&gt; &lt;a href="http://google.com"&gt;test1&lt;/a&gt; &lt;a href="test2"&gt;test2&lt;/a&gt; &lt;a href="http://amazon.com"&gt;test3&lt;/a&gt; &lt;a href="here/we/go"&gt;test4&lt;/a&gt; &lt;/div&gt; """ soup = BeautifulSoup(data) print soup.find_all('a', href=lambda x: not x.startswith('http')) </code></pre> <p>Or, using <a href="https://docs.python.org/2/library/urlparse.html" rel="nofollow noreferrer"><code>urlparse</code></a> and <a href="https://stackoverflow.com/a/8357518/771848">checking for network location part</a>:</p> <pre><code>def is_relative(url): return not bool(urlparse.urlparse(url).netloc) print soup.find_all('a', href=is_relative) </code></pre> <p>Both solutions print:</p> <pre><code>[&lt;a href="test2"&gt;test2&lt;/a&gt;, &lt;a href="here/we/go"&gt;test4&lt;/a&gt;] </code></pre>
python|html|regex|html-parsing
4
18
24,665,403
replace information in Json string based on a condition
<p>I have a very large json file with several nested keys. From whaat I've read so far, if you do:</p> <pre><code>x = json.loads(data) </code></pre> <p>Python will interpret it as a dictionary (correct me if I'm wrong). The fourth level of nesting in the json file contains several elements named by an ID number and all of them contain an element called children, something like this:</p> <pre><code>{"level1": {"level2": {"level3": {"ID1": {"children": [1,2,3,4,5]} } {"ID2": {"children": []} } {"ID3": {"children": [6,7,8,9,10]} } } } } </code></pre> <p>What I need to do is to replace all items in all the <code>"children"</code> elements with nothing, meaning <code>"children": []</code> if the ID number is in a list called <code>new_ids</code> and then convert it back to json. I've been reading on the subject for a few hours now but I haven't found anything similar to this to try to help myself.</p> <p>I'm running Python 3.3.3. Any ideas are greatly appreciated!!</p> <p>Thanks!!</p> <p><strong>EDIT</strong></p> <p>List:</p> <pre><code>new_ids=["ID1","ID3"] </code></pre> <p>Expected result:</p> <pre><code>{"level1": {"level2": {"level3": {"ID1": {"children": []} } {"ID2": {"children": []} } {"ID3": {"children": []} } } } } </code></pre>
<p>First of all, your JSON is invalid. I assume you want this:</p> <pre><code>{"level1": {"level2": {"level3": { "ID1":{"children": [1,2,3,4,5]}, "ID2":{"children": []}, "ID3":{"children": [6,7,8,9,10]} } } } } </code></pre> <p>Now, load your data as a dictionary:</p> <pre><code>&gt;&gt;&gt; with open('file', 'r') as f: ... x = json.load(f) ... &gt;&gt;&gt; x {u'level1': {u'level2': {u'level3': {u'ID2': {u'children': []}, u'ID3': {u'children': [6, 7, 8, 9, 10]}, u'ID1': {u'children': [1, 2, 3, 4, 5]}}}}} </code></pre> <p>Now you can loop over the keys in <code>x['level1']['level2']['level3']</code> and check whether they are in your <code>new_ids</code>.</p> <pre><code>&gt;&gt;&gt; new_ids=["ID1","ID3"] &gt;&gt;&gt; for key in x['level1']['level2']['level3']: ... if key in new_ids: ... x['level1']['level2']['level3'][key]['children'] = [] ... &gt;&gt;&gt; x {u'level1': {u'level2': {u'level3': {u'ID2': {u'children': []}, u'ID3': {u'children': []}, u'ID1': {u'children': []}}}}} </code></pre> <p>You can now write <code>x</code> back to a file like this:</p> <pre><code>with open('myfile', 'w') as f: f.write(json.dumps(x)) </code></pre> <p>If your <code>new_ids</code> list is large, consider making it a <code>set</code>.</p>
python|json|python-3.x
1
19
38,326,387
How to get percentiles on groupby column in python?
<p>I have a dataframe as below:</p> <pre><code>df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3, 'office_id': list(range(1, 7)) * 2, 'sales': [np.random.randint(100000, 999999) for _ in range(12)]}) </code></pre> <p>To get percentiles of sales,state wise,I have written below code:</p> <pre><code>pct_list1 = [] pct_list2 = [] for i in df['state'].unique().tolist(): pct_list1.append(i) for j in range(0,101,10): pct_list1.append(np.percentile(df[df['state'] == i]['sales'],j)) pct_list2.append(pct_list1) pct_list1 = [] colnm_list1 = [] for k in range(0,101,10): colnm_list1.append('perct_'+str(k)) colnm_list2 = ['state'] + colnm_list1 df1 = pd.DataFrame(pct_list2) df1.columns = colnm_list2 df1 </code></pre> <p>Can we optimize this code?</p> <p>I feel that,we can also use</p> <pre><code>df1 = df[['state','sales']].groupby('state').quantile(0.1).reset_index(level=0) df1.columns = ['state','perct_0'] for i in range(10,101,10): df1.loc[:,('perct_'+str(i))] = df[['state','sales']].groupby('state').quantile(float(i/100.0)).reset_index(level=0)['sales'] </code></pre> <p>If there are any other alternatives,please help.</p> <p>Thanks.</p>
<p>How about this?</p> <pre><code>quants = np.arange(.1,1,.1) pd.concat([df.groupby('state')['sales'].quantile(x) for x in quants],axis=1,keys=[str(x) for x in quants]) </code></pre>
python|pandas
1
20
38,490,748
Isolating subquery from its parent
<p>I have a <code>column_property</code> on my model that is a count of the relationships on a secondary model.</p> <pre><code>membership_total = column_property( select([func.count(MembershipModel.id)]).where( MembershipModel.account_id == id).correlate_except(None)) </code></pre> <p>This works fine until I try to join the membership model.</p> <pre><code>query = AccountModel.query.join(MembershipModel) # ProgrammingError: subquery uses ungrouped column "membership.account_id" from outer query </code></pre> <p>I can fix this issue by appending:</p> <pre><code>query = query.group_by(MembershipModel.account_id, AccountModel.id) # resolves the issue </code></pre> <p>But I don't really want to do that. I want it to be its own island that ignores whatever the query is doing and just focuses on returning a count of memberships for that particular row's account ID.</p> <p>What can I do to the column_property to make it more robust and less reliant on what the parent query is doing?</p>
<p>Pass <code>MembershipModel</code> to <code>correlate_except()</code> instead of <code>None</code>, as described <a href="http://docs.sqlalchemy.org/en/latest/orm/mapped_sql_expr.html#using-column-property" rel="nofollow">here</a> in the documentation. Your current method allows omitting everything from the subquery's FROM-clause, if it can be correlated to the enclosing query. When you join <code>MembershipModel</code> it becomes available in the enclosing query.</p> <p>Here's a simplified example. Given 2 models <code>A</code> and <code>B</code>:</p> <pre><code>In [2]: class A(Base): ...: __tablename__ = 'a' ...: id = Column(Integer, primary_key=True, autoincrement=True) ...: In [3]: class B(Base): ...: __tablename__ = 'b' ...: id = Column(Integer, primary_key=True, autoincrement=True) ...: a_id = Column(Integer, ForeignKey('a.id')) ...: a = relationship('A', backref='bs') </code></pre> <p>and 2 <code>column_property</code> definitions on <code>A</code>:</p> <pre><code>In [10]: A.b_count = column_property( select([func.count(B.id)]).where(B.a_id == A.id).correlate_except(B)) In [11]: A.b_count_wrong = column_property( select([func.count(B.id)]).where(B.a_id == A.id).correlate_except(None)) </code></pre> <p>If we query just <code>A</code>, everything's fine:</p> <pre><code>In [12]: print(session.query(A)) SELECT a.id AS a_id, (SELECT count(b.id) AS count_1 FROM b WHERE b.a_id = a.id) AS anon_1, (SELECT count(b.id) AS count_2 FROM b WHERE b.a_id = a.id) AS anon_2 FROM a </code></pre> <p>But if we join <code>B</code>, the second property incorrectly correlates <code>B</code> from the enclosing query and completely omits the FROM-clause:</p> <pre><code>In [13]: print(session.query(A).join(B)) SELECT a.id AS a_id, (SELECT count(b.id) AS count_1 FROM b WHERE b.a_id = a.id) AS anon_1, (SELECT count(b.id) AS count_2 WHERE b.a_id = a.id) AS anon_2 FROM a JOIN b ON a.id = b.a_id </code></pre>
python|sqlalchemy
2
21
31,154,238
Clustering latitude longitude points in Python with fixed number of clusters
<p>kmeans does not work properly for geospatial coordinates - even when changing the distance function to haversine as stated <a href="https://datascience.stackexchange.com/a/848/10436">here</a>.</p> <p>I had a look at <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html" rel="nofollow noreferrer">DBSCAN</a> which doesn t let me set a fixed number of clusters.</p> <ol> <li>Is there any algorithm (in python if possible) that has the same input values as kmeans? or</li> <li>Can I easily convert latitude, longitude to euclidean coordinates (x,y,z) as done <a href="https://stackoverflow.com/a/1185413/1252307">here</a> and do the calculation on my data?</li> </ol> <p>It does not have to perfectly accurate, but it would nice if it would.</p>
<p>Using just lat and longitude leads to problems when your geo data spans a large area. Especially since the distance between longitudes is less near the poles. To account for this it is good practice to first convert lon and lat to cartesian coordinates.</p> <p>If your geo data spans the united states for example you could define an origin from which to calculate distance from as the center of the contiguous united states. I believe this is located at Latitude 39 degrees 50 minutes and Longitude 98 degrees 35 minute.</p> <p>TO CONVERT lat lon to CARTESIAN coordinates- calculate the distance using haversine, from every location in your dataset to the defined origin. Again, I suggest Latitude 39 degrees 50 minutes and Longitude 98 degrees 35 minute. </p> <p>You can use haversine in python to calculate these distances:</p> <pre><code>from haversine import haversine origin = (39.50, 98.35) paris = (48.8567, 2.3508) haversine(origin, paris, miles=True) </code></pre> <p>Now you can use k-means on this data to cluster, assuming the haversin model of the earth is adequate for your needs. If you are doing data analysis and not planning on launching a satellite I think this should be okay.</p>
python|gis|geospatial|latitude-longitude|k-means
4
22
39,930,022
How to make exceptions during the iteration of a for loop in python
<p>Sorry in advance for the certainly simple answer to this but I can't seem to figure out how to nest an <code>if ______ in ____:</code> block into an existing <code>for</code> block.</p> <p>For example, how would I change this block to iterate through each instance of <code>i</code>, omitting odd numbers. </p> <pre><code>odds = '1 3 5 7 9'.split() for i in range(x): if i in odds: continue print(i) </code></pre> <p>this code works for <code>if i == y</code> but I cannot get it to work with a specific set of "y"s</p>
<p>This has nothing to do with nesting. You are comparing apples to pears, or in this case, trying to find an <code>int</code> in a list of <code>str</code> objects.</p> <p>So the <code>if</code> test never matches, because there is no <code>1</code> in the list <code>['1', '3', '5', '7', '9']</code>; there is no <code>3</code> or <code>5</code> or <code>7</code> or <code>9</code> either, because an integer is a different type of object from a string, even if that string contains digits that look, to you as a human, like digits.</p> <p>Either convert your int to a string first, or convert your strings to integers:</p> <pre><code>if str(i) in odds: </code></pre> <p>or</p> <pre><code>odds = [int(i) for i in '1 3 5 7 9'.split()] </code></pre> <p>If you want to test for odd numbers, there is a much better test; check if the remainder of division by 2 is 1:</p> <pre><code>if i % 2 == 1: # i is an odd number </code></pre>
python|python-3.x|if-statement|for-loop|nested
4
23
8,482,007
Python 2.6.2: writing lines to file hard wrap at 192 characters
<p>I implemented a function to make a wrapper to write to files. This is the code:</p> <pre><code>def writeStringToFile(thestring, thefile, mode='w'): """Write a string to filename `thefile' to the directory specified in `dir_out'.""" with open(os.path.join(dir_out, thefile), mode) as fh: fh.write("{0}\n".format(thestring)) </code></pre> <p>I found out that when I write any string over 192 characters, a newline is inserted at character 192, resulting in a hard wrap in my output file, which I don't want.</p> <p>I looked at the docs for the <code>open</code> and <code>write</code> function/method, and I don't see anything that would specify a hard wrap at any line length.</p> <p>Any insight into fixing this is appreciated.</p>
<p>My own stupidity -- I was writing strings that had the character sequence <code>\n</code> in them, and python was rightly interpreting them as newlines. I need to escape them in my string. I'd take this post down if it hadn't already been responded to.</p>
python
1
24
59,013,654
list of indices in 3D array
<p>I have an array that looks like this:</p> <pre><code> [[[ -1., 1., -1., 1., -1., 1., 1., 1., 1., -1., 1., 1., 1., 1.]], [[ 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0.]], [[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]] </code></pre> <p>I have a list of 3 indices</p> <pre><code>[2,3,4] </code></pre> <p>I would like to get only the "rows" where those indices are zero. So the mask would look like this:</p> <pre><code>[False, True, True] </code></pre> <p>And the result I am looking for would just be the two "rows" which satisfy the condition:</p> <pre><code> [[ 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0.]], [[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]] </code></pre> <p>I put "rows" in quotes because I understand that there is an extra dimension in there - but it needs to stay.</p> <p>======================EXTENDED EXAMPLE==================</p> <pre><code>a = [[[0,1,0]], [[0,0,0]], [[1,1,1]], [[1,0,1]], [[0,0,1]], [[1,0,0]]] b = [0, 1, 2, 2, 1, 0] c = f(a,b) For f(a,b) the first element, [[0,1,0]] is skipped because it has a 0 in the 0th position the second element, [[0,0,0]] is likewise omitted because because there is a 0 in the 1st position The third element, [[1,1,1]] is included because it does not have a 0 in the 2nd index position ... and so on... until the final result is... c = [[[1, 1, 1]], [[1, 0, 1]], [[1, 0, 0]] </code></pre> <p>So I am looking for f()</p>
<p><strong>Solution 1:</strong></p> <p><strong>The most pythonic way (my way to go).</strong></p> <pre><code>c = [a[i] for i,j in enumerate(b) if a[i][0][j] == 1] print(c) [[[1, 1, 1]], [[1, 0, 1]], [[1, 0, 0]]] </code></pre> <hr> <p><strong>Solution 2:</strong></p> <pre><code>a = [[[0,1,0]], [[0,0,0]], [[1,1,1]], [[1,0,1]], [[0,0,1]], [[1,0,0]]] b = [0, 1, 2, 2, 1, 0] c=[] for i,j in enumerate(b): if a[i][0][j] == 1: c.append(a[i]) print(c) [[[1, 1, 1]], [[1, 0, 1]], [[1, 0, 0]]] </code></pre>
python|numpy|numpy-ndarray
1
25
51,953,821
Close cmd while Tk object remains
<p>So I made a simple calculator in Python 3.7 and made a batch file to get it to run from the CMD. The thing is, after I run the batch file, I get a CMD window and then the Tk window, but the CMD window remains there and shuts my program down if I close it. Is there a way to hide the CMD window or just omit its apperance at all?</p> <p>Here is how it looks, in case my description is bad:<br> <a href="https://i.stack.imgur.com/CXAsp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXAsp.png" alt="Cmd window visible and active"></a></p> <p>The BATCH FILE reads:</p> <pre><code>Start "" "C:\Users\Username\AppData\Local\Programs\Python\Python37\draft.py" </code></pre>
<p>You can use the <code>pythonw</code> executable, or rename your script to something<code>.pyw</code>.</p> <p><code>.pyw</code> is a special extension for Python files on Windows which are associated with <code>pythonw</code>, the Python interpreter that does not pop up the console window at all.</p>
python|tkinter|cmd|visible
4
26
62,205,131
PyQt app won't run properly unless I open the whole folder
<p>So I'm trying to share my PyQt project. When I download the zip file and extract it, it looks like</p> <p><a href="https://i.stack.imgur.com/ApGY4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ApGY4.png" alt="enter image description here"></a></p> <p>If I run <code>app.py</code> from CMD, it will run the app, but without the icon file which is inside of that folder. Inside of the code I do need that file and point to it, so I'm not sure why it doesn't find it automatically. It seems that without it the app doesn't work properly. I was wondering if there's a work around for this issue.</p> <p>Here is how the app looks when I "open folder" in my IDE:</p> <p><a href="https://i.stack.imgur.com/Nrip3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nrip3.png" alt="enter image description here"></a></p> <p>Here is how it looks when I simply open the <code>.py</code> file, in that same folder:</p> <p><a href="https://i.stack.imgur.com/G7aGb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G7aGb.png" alt="enter image description here"></a></p> <p>Anything related to the icons (basically all notifications) are not working when I run it like that.</p> <p>I'm not sure what why it behaves like this, but I'd like to be able to share the code for anyone to use without them opening the whole folder.</p>
<p>Eventually, I ended up changing how I'm using the paths.</p> <p>I added this</p> <pre class="lang-py prettyprint-override"><code>dirname = os.path.dirname(__file__) iconFile = os.path.join(dirname, 'icon/icon.png') </code></pre> <p>So now I'm using <code>iconFile</code> as my path. Seems to fix the issue</p>
python
2
27
63,529,436
Cannot connect VPS Server to MS SQL Server
<p>I'm trying to connect to MS SQL database using my VPS server IP, and login info. But I kept getting login failed error</p> <blockquote> <p>pyodbc.InterfaceError: ('28000', &quot;[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'root'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'root'. (18456)&quot;)</p> </blockquote> <p>[enter image description here][1] Products: Vultr VPS Server Version: Ubuntu 18.04 I already installed SQL Server 2017 In my python program, I got this</p> <pre><code>server = '66.42.92.32' username = 'root' password = 'abc' conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};' + f'Server={server};' + 'Database=KyInventory;' + 'UID=root;' + 'PWD=abc;'+ 'Trusted_Connection=no;') cursor = conn.cursor() </code></pre> <p>Please help me!</p>
<p>When you use IP address to connect to your server, you have to set SQL-Server port even it was default. like this:</p> <pre><code>server = '66.42.92.32,1433' </code></pre> <p>for more information look at this Microsoft link: <a href="https://docs.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver15" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver15</a></p>
python|sql-server|ubuntu|vps
-1
28
36,676,594
Spark Sql: TypeError("StructType can not accept object in type %s" % type(obj))
<p>I am currently pulling data from SQL Server using PyODBC and trying to insert into a table in Hive in a Near Real Time (NRT) manner. </p> <p>I got a single row from source and converted into List[Strings] and creating schema programatically but while creating a DataFrame, Spark is throwing StructType error.</p> <pre><code>&gt;&gt;&gt; cnxn = pyodbc.connect(con_string) &gt;&gt;&gt; aj = cnxn.cursor() &gt;&gt;&gt; &gt;&gt;&gt; aj.execute("select * from tjob") &lt;pyodbc.Cursor object at 0x257b2d0&gt; &gt;&gt;&gt; row = aj.fetchone() &gt;&gt;&gt; row (1127, u'', u'8196660', u'', u'', 0, u'', u'', None, 35, None, 0, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, u'', 0, None, None) &gt;&gt;&gt; rowstr = map(str,row) &gt;&gt;&gt; rowstr ['1127', '', '8196660', '', '', '0', '', '', 'None', '35', 'None', '0', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', '', '0', 'None', 'None'] &gt;&gt;&gt; schemaString = " ".join([row.column_name for row in aj.columns(table='tjob')]) &gt;&gt;&gt; schemaString u'ID ExternalID Name Description Notes Type Lot SubLot ParentJobID ProductID PlannedStartDateTime PlannedDurationSeconds Capture01 Capture02 Capture03 Capture04 Capture05 Capture06 Capture07 Capture08 Capture09 Capture10 Capture11 Capture12 Capture13 Capture14 Capture15 Capture16 Capture17 Capture18 Capture19 Capture20 User UserState ModifiedDateTime UploadedDateTime' &gt;&gt;&gt; fields = [StructField(field_name, StringType(), True) for field_name in schemaString.split()] &gt;&gt;&gt; schema = StructType(fields) &gt;&gt;&gt; [f.dataType for f in schema.fields] [StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType] &gt;&gt;&gt; myrdd = sc.parallelize(rowstr) &gt;&gt;&gt; myrdd.collect() ['1127', '', '8196660', '', '', '0', '', '', 'None', '35', 'None', '0', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', '', '0', 'None', 'None'] &gt;&gt;&gt; schemaPeople = sqlContext.createDataFrame(myrdd, schema) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/apps/opt/cloudera/parcels/CDH-5.5.2-1.cdh5.5.2.p0.4/lib/spark/python/pyspark/sql/context.py", line 404, in createDataFrame rdd, schema = self._createFromRDD(data, schema, samplingRatio) File "/apps/opt/cloudera/parcels/CDH-5.5.2-1.cdh5.5.2.p0.4/lib/spark/python/pyspark/sql/context.py", line 298, in _createFromRDD _verify_type(row, schema) File "/apps/opt/cloudera/parcels/CDH-5.5.2-1.cdh5.5.2.p0.4/lib/spark/python/pyspark/sql/types.py", line 1132, in _verify_type raise TypeError("StructType can not accept object in type %s" % type(obj)) TypeError: StructType can not accept object in type &lt;type 'str'&gt; </code></pre>
<p>here is the reason for error message:</p> <pre><code>&gt;&gt;&gt; rowstr ['1127', '', '8196660', '', '', '0', '', '', 'None' ... ] #rowstr is a list of str &gt;&gt;&gt; myrdd = sc.parallelize(rowstr) #myrdd is a rdd of str &gt;&gt;&gt; schema = StructType(fields) #schema is StructType([StringType, StringType, ....]) &gt;&gt;&gt; schemaPeople = sqlContext.createDataFrame(myrdd, schema) #myrdd should have been RDD([StringType, StringType,...]) but is RDD(str) </code></pre> <p>to fix that, make the RDD of proper type:</p> <pre><code>&gt;&gt;&gt; myrdd = sc.parallelize([rowstr]) </code></pre>
python|apache-spark|apache-spark-sql
27
29
36,393,643
Encoder for a string - Python
<p>I've been playing around with encoding random sets of strings using a dictionary. I've gotten my code to replace the letters I want, but in some cases it will replace a character more than once, when I truly only want it to replace the letter in the string once. This is what I have:</p> <pre><code>def encode(msg,code): for i in msg: for i in code: msg = msg.replace(i, code[i]) return msg </code></pre> <p>for testing purposes I used the function calls: initial:</p> <pre><code>encode("blagh", {"a":"e","h":"r"}) </code></pre> <p>and a more complex string:</p> <pre><code>encode("once upon a time",{'a':'ae','e':'ei','i':'io','o':'ou','u':'ua'}) </code></pre> <p>for the second one right above, I'm looking for the output of : 'ouncei uapoun ae tiomei'</p> <p>but instead am finding myself with :</p> <p>"ounceio uapoun aeio tiomeio"</p> <p>How can I limit my loop to only replacing each character once?</p>
<p>Python 3's <a href="https://docs.python.org/3.3/library/stdtypes.html?highlight=translate#str.translate" rel="nofollow"><code>str.translate</code></a> function does what you want. Note that the translation dictionary must use Unicode ordinals for keys, so the function uses a dictionary comprehension to convert it to the right format:</p> <pre><code>def encode(msg,code): code = {ord(k):v for k,v in code.items()} return msg.translate(code) print(encode("blagh", {"a":"e","h":"r"})) print(encode("once upon a time",{'a':'ae','e':'ei','i':'io','o':'ou','u':'ua'})) </code></pre> <p>Output:</p> <pre><code>blegr ouncei uapoun ae tiomei </code></pre> <p>It works in Python 2 as well if you use Unicode strings or add the following to the top of the file to make strings Unicode by default:</p> <pre><code>from __future__ import unicode_literals </code></pre>
python|string|loops|dictionary|encoding
2
30
13,593,514
assigning values in a numpy array
<p>I have a numpy array of zeros. For concreteness, suppose it's 2x3x4:</p> <pre><code>x = np.zeros((2,3,4)) </code></pre> <p>and suppose I have a 2x3 array of random integers from 0 to 3 (the index of the 3rd dimension of x).</p> <pre><code>&gt;&gt;&gt; y = sp.stats.distributions.randint.rvs(0, 4, size=(2,3)) &gt;&gt;&gt; y [[2 1 0] [3 2 0]] </code></pre> <p>How do I do the following assignments efficiently (edit: something that doesn't use for loops and works for x with any number of dimensions and any number of elements in each dimension)? </p> <pre><code>&gt;&gt;&gt; x[0,0,y[0,0]]=1 &gt;&gt;&gt; x[0,1,y[0,1]]=1 &gt;&gt;&gt; x[0,2,y[0,2]]=1 &gt;&gt;&gt; x[1,0,y[1,0]]=1 &gt;&gt;&gt; x[1,1,y[1,1]]=1 &gt;&gt;&gt; x[1,2,y[1,2]]=1 &gt;&gt;&gt; x array([[[ 0., 0., 1., 0.], [ 0., 1., 0., 0.], [ 1., 0., 0., 0.]], [[ 0., 0., 0., 1.], [ 0., 0., 1., 0.], [ 1., 0., 0., 0.]]]) </code></pre> <p>Thanks, James</p>
<p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow">numpy.meshgrid</a>() to make arrays of indexes that you can use to index into both your original array and the array of values for the third dimension.</p> <pre><code>import numpy as np import scipy as sp import scipy.stats.distributions a = np.zeros((2,3,4)) z = sp.stats.distributions.randint.rvs(0, 4, size=(2,3)) xx, yy = np.meshgrid( np.arange(2), np.arange(3) ) a[ xx, yy, z[xx, yy] ] = 1 print a </code></pre> <p>I've renamed your array from x to a, and the array of indexes from y to z, for clarity.</p> <p><strong>EDIT:</strong> 4D example:</p> <pre><code>a = np.zeros((2,3,4,5)) z = sp.stats.distributions.randint.rvs(0, 4, size=(2,3)) w = sp.stats.distributions.randint.rvs(0, 5, size=(2,3)) xx, yy = np.meshgrid( np.arange(2), np.arange(3) ) a[ xx, yy, z[xx, yy], w[xx, yy] ] = 1 </code></pre>
python|arrays|numpy|variable-assignment
1
31
13,558,653
How can I create a new folder with Google Drive API in Python?
<p>From <a href="https://developers.google.com/drive/v2/reference/files/insert" rel="noreferrer">this example</a>. Can I use MediafileUpload with creating folder? How can I get the parent_id from?</p> <p>From <a href="https://developers.google.com/drive/folder" rel="noreferrer">https://developers.google.com/drive/folder</a></p> <p>I just know that i should use mime = "application/vnd.google-apps.folder" but how do I implement this tutorial to programming in Python?</p> <p>Thank you for your suggestions.</p>
<p>To create a folder on Drive, try:</p> <pre><code> def createRemoteFolder(self, folderName, parentID = None): # Create a folder on Drive, returns the newely created folders ID body = { 'title': folderName, 'mimeType': "application/vnd.google-apps.folder" } if parentID: body['parents'] = [{'id': parentID}] root_folder = drive_service.files().insert(body = body).execute() return root_folder['id'] </code></pre> <p>You only need a parent ID here if you want to create folder within another folder, otherwise just don't pass any value for that. </p> <p>If you want the parent ID, you'll need to write a method to search Drive for folders with that parent name in that location (do a list() call) and then get the ID of that folder.</p> <hr> <p><strong>Edit:</strong> Note that v3 of the API uses a list for the 'parents' field, instead of a dictionary. Also, the <code>'title'</code> field changed to <code>'name'</code>, and the <code>insert()</code> method changed to <code>create()</code>. The code from above would change to the following for v3:</p> <pre><code> def createRemoteFolder(self, folderName, parentID = None): # Create a folder on Drive, returns the newely created folders ID body = { 'name': folderName, 'mimeType': "application/vnd.google-apps.folder" } if parentID: body['parents'] = [parentID] root_folder = drive_service.files().create(body = body).execute() return root_folder['id'] </code></pre>
python|google-drive-api
22
32
22,296,150
Deadlock when creating index
<p>I try to create an index with a Cypher query using py2neo 1.6.2 and neo4j 2.0.1:</p> <pre><code>graph_db = neo4j.GraphDatabaseService() query = "CREATE INDEX ON :Label(prop)" neo4j.CypherQuery(graph_db, query).run() </code></pre> <p>The query works fine in the neo4j web interface but throws a deadlock error in py2neo: <hr> py2neo.neo4j.DeadlockDetectedException: Don't panic.</p> <p>A deadlock scenario has been detected and avoided. This means that two or more transactions, which were holding locks, were wanting to await locks held by one another, which would have resulted in a deadlock between these transactions. This exception was thrown instead of ending up in that deadlock.</p> <p>See the deadlock section in the Neo4j manual for how to avoid this: <a href="http://docs.neo4j.org/chunked/stable/transactions-deadlocks.html" rel="nofollow">http://docs.neo4j.org/chunked/stable/transactions-deadlocks.html</a></p> <p>Details: 'Transaction(15438, owner:"qtp1927594840-9525")[STATUS_ACTIVE,Resources=1] can't wait on resource RWLock[SchemaLock]since => Transaction(15438, owner:"qtp1927594840-9525")[STATUS_ACTIVE,Resources=1] &lt;-[:HELD_BY]- RWLock[SchemaLock] &lt;-[:WAITING_FOR]- Transaction(15233, owner:"qtp1927594840-9503")[STATUS_ACTIVE,Resources=1] &lt;-[:HELD_BY]- RWLock[SchemaLock]'.</p> <hr> <p>It doesn't make a difference if the label exists or not, the request usually fails.</p>
<p>Judging from the deadlock graph in the details section, this looks like a bug in 2.0.1. Are you doing anything else to the database other than running this specific query, or is this just starting up a fresh database and running the code you provided?</p> <p>In any case, since it works in the Neo4j Browser, I'd suggest swapping to use the transactional APIs, as that is what the browser uses. Py2neo supports this using the "Cypher Transactions" feature, documented here:</p> <p><a href="http://book.py2neo.org/en/latest/cypher/#id2" rel="nofollow">http://book.py2neo.org/en/latest/cypher/#id2</a></p>
python|neo4j|cypher|py2neo
1
33
43,838,895
Data comes out misaligned when printing list
<p>I have a code that reads an inventory txt file that is suppose to display a menu for the user when it is run. However, when it runs the quantity and pice columns are misaligned:</p> <pre><code>Select an item ID to purchase or return: ID Item Quantity Price 244 Large Cake Pan 7.00 19.99 576 Assorted Sprinkles 3.00 12.89 212 Deluxe Icing Set 6.00 37.97 827 Yellow Cake Mix 3.00 1.99 194 Cupcake Display Board 2.00 27.99 285 Bakery Boxes 7.00 8.59 736 Mixer 5.00 136.94 Enter another item ID or 0 to stop </code></pre> <p>Here is my code:</p> <pre><code>import InventoryFile def readFile (): #open the file and read the lines inventoryFile = open ('Inventory.txt', 'r') raw_data = inventoryFile.readlines () #remove the new line characters clean_data = [] for item in raw_data: clean_item = item.rstrip ('\n') clean_data.append (clean_item) #read lists into objects all_objects = [] for i in range (0, len(clean_data), 4): ID = clean_data [i] item = clean_data [i+1] qty = float (clean_data [i+2]) price = float (clean_data [i+3]) inventory_object = InventoryFile.Inventory (ID, item, qty, price) all_objects.append (inventory_object) return all_objects def printMenu (all_data): print () print ('Select an item ID to purchase or return: ') print () print ('ID\tItem\t\t Quantity\t Price') for item in all_data: print (item) print () print ('Enter another item ID or 0 to stop') def main (): all_items = readFile () printMenu (all_items) main () </code></pre> <p>How can I format the output so that the quantity and price columns are correctly aligned?</p> <p>Here is the inventory class:</p> <pre><code>class Inventory: def __init__ (self, new_id, new_name, new_stock, new_price): self.__id = new_id self.__name = new_name self.__stock = new_stock self.__price = new_price def get_id (self): return self.__id def get_name (self): return self.__name def get_stock (self): return self.__stock def get_price (self): return self.__price def restock (self, new_stock): if new_stock &lt; 0: print ('ERROR') return False else: self.__stock = self.__stock + new_stock return True def purchase (self, purch_qty): if (new_stock - purch_qty &lt; 0): print ('ERROR') return False else: self.__stock = self.__stock + purch_qty return True def __str__ (self): return self.__id + '\t' + self.__name + '\t' + \ format (self.__stock, '7.2f') + format (self.__price, '7.2f') </code></pre>
<p>Using your class <code>Inventory</code>'s getters you can make a list and just join the output.</p> <pre><code>def printMenu (all_data): print () print ('Select an item ID to purchase or return: ') print () print ('ID\tItem\t\t Quantity\t Price') for item in all_data: product_id = item.get_id() product_name = item.get_name() product_stock = item.get_stock() product_price = item.get_price() output = [product_id, product_name, product_stock, product_price] output = [str(item) for item in output] print('{:&lt;5}\t{:&lt;5}\t{:&lt;5}\t{:&lt;5}'.format(output)) print () print ('Enter another item ID or 0 to stop') </code></pre>
python|list
0
34
71,384,054
How to save a dictionary having multiple lists of values for each key in a csv file
<p>I have a dictionary in the format:</p> <pre><code>cu = {'m':[['a1','a2'],['a3','a4'],['a5','a6']], 'n':[['b1','b2'], ['b3','b4']]} </code></pre> <p>#the code I used to save the dictionary in csv file was:</p> <pre><code>#using numpy to make the csv file import numpy as np # using the savetxt np.savetxt(&quot;cu_ck.csv&quot;, cu , delimiter =&quot;,&quot; , fmt ='% s') </code></pre> <p>and it raised an error stating that: <em>ValueError: Expected 1D or 2D array, got 0D array instead</em></p> <p>Please help me write a code which can be used to save a dictionary of such type. And it is to be noted that, this dictionary is only for example basis...the original dictionary has keys more than 12, wherein the length of values for each key may vary but are in the same format as stated in the cu dictionary.</p> <p>The csv file should at least look like this:</p> <pre><code>m a1 a2 m a3 a4 m a5 a6 n b1 b2 n b3 b4 </code></pre>
<p>The error is caused by <code>cu</code> being a dictionary type, which is not an array type.</p> <p>However, simply converting to an array isn't going to work either, since what you want is fairly complicated. One way to perform this data transformation is to append the key to each subarray:</p> <pre><code>([['m', a1, a2], ['m', a3, a4], ['m', a5, a6]], [['n', b1, b2], ['n', b3, b4]]) </code></pre> <p>and then concatenate the outer lists:</p> <pre><code>[['m', a1, a2], ['m', a3, a4], ['m', a5, a6], ['n', b1, b2], ['n', b3, b4]] </code></pre> <p>Admittedly, I don't know whether this is very Pythonic, but it does the trick:</p> <pre class="lang-py prettyprint-override"><code>cu_arr2d = sum(([[key, *row] for row in cu[key]] for key in cu), []) </code></pre> <p>Here the</p> <pre class="lang-py prettyprint-override"><code>([[key, *row] for row in cu[key]] for key in cu) </code></pre> <p>is iterating over all the keys and then iterating over all the rows of that key, and appending the key to the row. Its output is that tuple of 2d lists from the top of this post. Then the <code>sum</code> is concatenating everything.</p>
python|numpy|csv|dictionary
0
35
39,063,571
Binding command line arguments to the object methods calls in Python
<p>I am working on a command line utility with a few possible arguments. The argument parsing is done with argparse module. In the end, with some additional customization, I get a dictionary with one and only one element:</p> <pre><code>{'add_account': ['example.com', 'example']} </code></pre> <p>Where the key is an option that should translate to a method call and the value is the arguments list. I have all the planned objects method implemented. I wonder what would be the best, most pythonic way to create method calls based on received dictionary. I could obviously go through a predefined mapping like:</p> <pre><code>if option == 'add_account': object.add_account( dictionary['add_account'][0], dictionary['add_account'][1] ) </code></pre> <p>I feel that there's a much better way to do it, though. </p>
<p>You can use <code>getattr</code> to fetch a method object (<code>argparse.py</code> uses this approach several times).</p> <p>You didn't give us a concrete example, but I'm guessing you have a class like this:</p> <pre><code>In [387]: class MyClass(object): ...: def add_account(self,*args): ...: print(args) ...: In [388]: obj=MyClass() In [389]: obj.add_account(*['one','two']) ('one', 'two') </code></pre> <p>To do the same thing, starting with a string, I can use <code>getattr</code> to fetch the method object:</p> <pre><code>In [390]: getattr(obj,'add_account') Out[390]: &lt;bound method MyClass.add_account of &lt;__main__.MyClass object at 0x98ddaf2c&gt;&gt; In [391]: getattr(obj,'add_account')('one') ('one',) </code></pre> <p>Now with your dictionary:</p> <pre><code>In [392]: dd={'add_account': ['example.com', 'example']} In [393]: key='add_account' In [394]: getattr(obj, key)(*dd[key]) ('example.com', 'example') </code></pre>
python-3.x|argparse
0
36
39,258,038
The most efficient way to iterate over a list of elements. Python 2.7
<p>I am trying to iterate over a list of elements, however the list can be massive and takes too long to execute. I am using newspaper api. The for loop I constructed is:</p> <pre><code>for article in list_articles: </code></pre> <p>Each article in the list_articles are an object in the format of:</p> <pre><code>&lt;newspaper.article.Article object at 0x1103e1250&gt; </code></pre> <p>I checked that some recommended using xrange or range, however that did not work in my case, giving a type error:</p> <pre><code>TypeError: 'int' object is not iterable </code></pre> <p>It would be awesome if anyone can point me to the right direction or give me some idea that can efficietly increase iterating over this list.</p>
<p>The best way is to use built in functions, when possible, such as functions to split strings, join strings, group things, etc...</p> <p>The there is the list comprehension or <code>map</code> when possible. If you need to construct one list from another by manipulating each element, then this is it.</p> <p>The thirst best way is the <code>for item in items</code> loop.</p> <p><strong>ADDED</strong></p> <p>One of the things that makes you a Python programmer, a better programmer, takes you to the next level of programming is the second thing I mentioned - list comprehension and map. Many times you iterate a list only to construct something that could be easily done with list comprehension. For example:</p> <pre><code>new_items = [] for item in items: if item &gt; 3: print(item * 10) new_items.append(item * 10) </code></pre> <p>You could do this much better (shorter and faster and more robust) like this:</p> <pre><code>new_items = [item * 10 for item in items if item &gt; 3] print(items) </code></pre> <p>Now, the printing is a bit different from the first example, but more often than not, it doesn't matter, and even better, and also can be transformed with one line of code to what you need.</p>
python|list|python-2.7|loops|cpython
2
37
52,505,943
SyntaxError: invalid syntax in URLpattern
<p>hi am getting a syntax error</p> <p>url:</p> <pre><code>url(r'^reset-password/$', PasswordResetView.as_view(template_name='accounts/reset_password.html', 'post_reset_redirect': 'accounts:password_reset_done'), name='reset_password'), </code></pre> <p>What is the problem?</p> <p>thanks</p>
<p>The problem is that you mix dictionary syntax with parameter syntax:</p> <pre><code>url( r'^reset-password/$', PasswordResetView.as_view( template_name='accounts/reset_password.html', <s><b>'post_reset_redirect': 'accounts:password_reset_done'</b></s> ), name='reset_password' )</code></pre> <p>This syntax with a colon, is used for dictionaries. For parameters, it is <code>identifier=expression</code>, so:</p> <pre><code>from django.urls import <b>reverse_lazy</b> url( r'^reset-password/$', PasswordResetView.as_view( template_name='accounts/reset_password.html', <b>success_url=reverse_lazy('accounts:password_reset_done')</b> ), name='reset_password' )</code></pre> <p>The <code>post_reset_redirect</code> has been removed as parameter, but the <code>success_url</code> performs the same functionality: it is the URL to which a redirect is done, after the POST request has been handled successfully.</p> <p>The wrong syntax probably originates from the fact that when you used a <em>function-based view</em>, you passed parameters through the <code>kwargs</code> paramter, which accepted a dictionary.</p> <p>The class-based view however, obtains these parameter through the <code>.as_view(..)</code> call. Furthermore class-based views typically aim to generalize the process, and there the <code>success_url</code>, is used for <code>FormView</code>s.</p>
python|django|syntax
3
38
52,831,640
Converting hex to binary in array
<p>I'm working on Visual Studio about python Project and The user input like that <code>010203</code> and I use this code for saparating the input:</p> <pre><code>dynamic_array = [ ] hexdec = input("Enter the hex number to binary "); strArray = [hexdec[idx:idx+2] for idx in range(len(hexdec)) if idx%2 == 0] dynamic_array = strArray print(dynamic_array[0] + " IAM" ) print(dynamic_array[1] + " NOA" ) print(dynamic_array[2] + " FCI" ) </code></pre> <p>So, the output is:</p> <pre><code>01 IAM 02 NOA 03 FCI </code></pre> <p>However my expected output converting this hex numbers to binary numbers look like this:</p> <pre><code>00000001 IAM 00000010 NOA 00000011 FCI </code></pre> <p>Is there any way to do this?</p>
<p>It's a lot easier if you thnk of hex as a integer (number).<br> There's a lot of tips on how to convert integers to different outcomes, but one useful string representation tool is <code>.format()</code> which can format a integer (and others) to various outputs.</p> <p>This is a combination of:</p> <ul> <li><a href="https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">Convert hex string to int in Python</a></li> <li><a href="https://stackoverflow.com/questions/699866/python-int-to-binary">Python int to binary?</a></li> </ul> <p>The solutions would be:</p> <pre><code>binary = '{:08b}'.format(int(hex_val, 16)) </code></pre> <p>And the end result code would look something like this:</p> <pre><code>def toBin(hex_val): return '{:08b}'.format(int(hex_val, 16)).zfill(8) hexdec = input("Enter the hex number to binary "); dynamic_array = [toBin(hexdec[idx:idx+2]) for idx in range(len(hexdec)) if idx%2 == 0] print(dynamic_array[0] + " IAM" ) print(dynamic_array[1] + " NOA" ) print(dynamic_array[2] + " FCI" ) </code></pre> <p>Rohit also proposed a pretty good solution, but I'd suggest you swap the contents of <code>toBin()</code> with <code>bin(int())</code> rather than doing it per print statement.</p> <p>I also restructured the code a bit, because I saw no point in initializing <code>dynamic_array</code> with a empty list. Python doesn't need you to set up variables before assigning values to them. There was also no point in creating <code>strArray</code> just to replace the empty <code>dynamic_array</code> with it, so concatenated three lines into one.</p> <p>machnic also points out a good programming tip, the use of <code>format()</code> on your entire string. Makes for a very readable code :) </p> <p>Hope this helps and that my tips makes sense. </p>
python|python-3.x
3
39
52,626,708
Why is my program shifting s and c by the wrong amount if I enter 5 into my program but not with any other letters or number?
<p>This program is meant to ask you for a sentence and a number then it shifts the letters down the alphabet all by the inputted number and then lets you undo it by shift it by minus what you enter. For some reason when you enter <code>5</code> as your shift the letter s shift to different random letters and does not give you the correct word when you try and shift back and I have no idea why.</p> <pre><code>import sys import time letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26) def program(): def encryption(): def encryption1(): global message global shift message = list ((input ("Please enter the sentence you would like to be %s\n&gt;" % (EnDe1))).lower()) print ("To %s your message please %s your private key number (from 1 - 10)" % (EnDe2, EnDe3)) shift = int (input ("&gt;")) if EnDe == "b": shift = - (shift) if shift &lt; 11 or shift &gt; 0: for x in range(len(message)): if message[x] != " ": if eval(message[x]) &gt; 26 - shift: message[x] = letters[eval(message[x]) + shift - 27] else: message[x] = letters[eval(message[x]) + shift - 1] else: shift = int (input ("only numbers from 1 to 10 are accepted, try again\n&gt;")) encryption1() def choice(): global EnDe global EnDe1 global EnDe2 global EnDe3 EnDe = (input ("would you like to A)encrypt or B)decrypt\n&gt;")).lower() if EnDe == "a": EnDe1 = "encrypted" EnDe2 = "encrypt" EnDe3 = "pick" encryption1() elif EnDe == "b": EnDe1 = "decrypted" EnDe2 = "decrypt" EnDe3 = "enter" encryption1() else: print ("please pick either 'A' or 'B' , ONLY!") time.sleep(2) choice() choice() output = ''.join(message) print (output) retry = input ("would you like to Decrypt/Encrypt another message? (Y/N)\n&gt;") retry = retry.lower() while retry != ("y" or "n"): retry = input ("please select either y or n\n&gt;") retry = retry.lower() while retry == "y": program() else: sys.exit() encryption() </code></pre>
<p>The problem is that you define a global <code>x</code> variable, and also a local one. The local one shadows the global one and so the result of <code>eval("x")</code> is not anymore what you expected to have. </p> <p>Solution: use a different variable for the <code>for</code> loop.</p> <p>There is much that can be improved in your code. You can take advantage of the modulo operator and the <code>ord</code> function, avoiding the need for all those 26 letter names.</p> <p>Here is how that <code>for</code> loop could look without all that:</p> <pre><code>if 0 &lt; shift &lt; 11: for i, ch in enumerate(message): if ch != " ": message[i] = chr((ord(ch)-ord('a')+shift)%26+ord('a')) </code></pre> <p>Unrelated: note that <code>retry != ("y" or "n")</code> does not work like that. You should do <code>retry not in "yn"</code> </p>
python|arrays|loops|eval
0
40
47,735,224
Receiving service messages in a group chat using Telegram Bot
<p>I am trying to create a bot in my group to help me track the group users who have invited other users into the group.</p> <p>I have disabled the privacy mode so the bot can receive all messages in a group chat. However, it seems to be that <code>update.message</code> only gets messages supplied by other users but not service messages like <code>Alice has added Bob into the group</code></p> <p>Is there any way that I can get these service messages as well?</p> <p>Thanks for helping!</p>
<p>I suppose you are using <code>python-telegram-bot</code> library.</p> <p>You can add a handler with a specific filter to listen to service messages:</p> <pre><code>from telegram.ext import MessageHandler, Filters def callback_func(bot, update): # here you receive a list of new members (User Objects) in a single service message new_members = update.message.new_chat_members # do your stuff here: for member in new_members: print(member.username) def main(): ... dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, callback_func) </code></pre> <p>There are several more service message types your bot may receive using the <code>Filters</code> module, check them out <a href="http://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.filters.html#telegram.ext.filters.Filters.status_update" rel="nofollow noreferrer">here</a>.</p>
python|python-3.x|telegram-bot|python-telegram-bot
1
41
47,930,647
Pandas division with 2 dfs
<p>I want to divide 2 dfs by matching their names. For example,</p> <p><code>df1 = pd.DataFrame({'Name':['xy-yz','xa-ab','yz-ijk','zb-ijk'],1:[1,2,3,4],2:[1,2,1,2],3:[2,2,2,2]} )</code></p> <p><code>df2 = pd.DataFrame({'Name2':['x','y','z','a'],1:[0,1,2,3],2:[1,2,3,4],3:[5,5,5,6]})</code></p> <p>df1:</p> <pre><code>Name1 1 2 3 xy-yz 1 1 2 xa-ab 2 2 2 yz-ijk 3 1 2 zb-ijk 4 2 2 </code></pre> <p>df2:</p> <pre><code>Name2 1 2 3 x 0 1 5 y 1 2 5 z 2 3 5 a 3 4 6 </code></pre> <p>The result would be df3: </p> <pre><code>Name1 1 2 3 xy-yz 1 1 2 x 0 1 5 xy-yz 1 .4 &lt;---(xy-yz)/x xa-ab 2 2 2 x 0 1 5 xa-ab 2 .4 &lt;---(xa-ab)/x yz-ijk 3 1 2 y 1 2 5 yz-ijk 3 .5 .4 &lt;---(yz-ijk)/y zb-ijk 4 2 2 z 2 3 5 zb-ijk 2 .67 .4 &lt;---(zb-ijk)/z </code></pre> <p>I would use concat but I'm not not sure how to do the division by mapping the Name2 to the first letter in Name1 here. </p> <p>Thank you!</p>
<p>I do not know why you need it , but this give back what you need </p> <pre><code>df2=df2.set_index('Name2') dfNew=df2.reindex(df1.Name1.str.split('-',expand=True)[0]) df1=df1.set_index('Name1') pd.concat([df1.reset_index(),dfNew.reset_index().rename(columns={0:'Name1'}),pd.DataFrame(df1.values/dfNew.values,columns=df1.columns).assign(Name1=df1.index)]).sort_index() Out[897]: 1 2 3 Name1 0 1.000000 1.000000 2.0 x-yz 0 0.000000 1.000000 5.0 x 0 inf 1.000000 0.4 x-yz 1 2.000000 2.000000 2.0 x-ab 1 0.000000 1.000000 5.0 x 1 inf 2.000000 0.4 x-ab 2 3.000000 1.000000 2.0 y-ijk 2 1.000000 2.000000 5.0 y 2 3.000000 0.500000 0.4 y-ijk 3 4.000000 2.000000 2.0 z-ijk 3 2.000000 3.000000 5.0 z 3 2.000000 0.666667 0.4 z-ijk </code></pre>
python|pandas|dataframe|division
3
42
34,316,747
Django logout() returns none
<p>Morning everyone</p> <p>Im using django logout() to end my sessions just like django docs says :</p> <p><strong>views.py</strong></p> <pre><code>class Logout(View): def logout_view(request): logout(request) return HttpResponseRedirect(reverse('cost_control_app:login')) </code></pre> <p>and im calling it from this url :</p> <p>urls.py</p> <pre><code>url(r'^logout/$', views.Logout.as_view(), name = "logout"), </code></pre> <p>Buttttttt it's not working, when i do a trace i find that the function :</p> <pre><code> def logout_view(request): </code></pre> <p>it's returning "none" and it's nos entering to execute the code inside...</p> <p>Please help me !</p>
<p>I'm curious, why do you have the method named <code>logout_view()</code>? By default, nothing is going to call that method. You need to change the name to match the HTTP verb which will be used to call the page. For instance, if it's going to be a <code>GET</code> request, you would change it to:</p> <pre><code>def get(self, request): </code></pre> <p>If you want it to be a POST request, you would change it to:</p> <pre><code>def post(self, request): </code></pre> <p>This is the standard way that class-based views work in Django. Also, you may want to look at the <a href="https://docs.djangoproject.com/en/1.9/topics/class-based-views/" rel="nofollow">documentation for class-based views</a>, as this may give you a better idea of their workings and what they can provide to you. (Hint: There is a built-in <a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/base/#redirectview" rel="nofollow">RedirectView</a>)</p>
python|django|logout
2
43
72,769,527
Def and Return Function in python
<p>I'm having some problems with the def and return function in Python. On the top of my program I've defined:</p> <pre><code>from subprogram import subprogram </code></pre> <p>then I've defined the def in which I've included the values I wanted to be returned:</p> <pre><code>def subprogram(ssh, x_off, y_off, data_array, i, j): if j==1: print('shutdonw X') # Run command. ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(x_off) var_colonna_1 = data_array[i][j] return var_colonna_1 print(var_colonna_1) if j==2: print('shutdown Y') # Run command. ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(y_off) var_colonna_2 = data_array[i][j] return var_colonna_2 </code></pre> <p>this is then called in the main program as:</p> <pre><code>for j in range(5, lunghezza_colonna): if data_array[i][j] == 'V': subprogram(ssh, x_off, y_off, data_array, i, j) print(var_colonna_1) </code></pre> <p>I was expecting that every time the <code>subprogram</code> is called, it returns the <code>var_colonna_1</code> or <code>var_colonna_2</code>, but the values I see when I print <code>var_colonna_1</code> is always 0 even if, internally the other commands are execute (so X and Y are set in shut down). Can you help me? I don't see my coding mistake.</p>
<p>The function doesn't return the variable, only the value on it.</p> <p>If you want to get the returned value on var_colonna_1, you should asign it, as Sayse said, you should do:</p> <pre><code>var_colonna_1 = subprogram(ssh, x_off, y_off, data_array, i, j) </code></pre>
python
1
44
16,380,528
Faster alternatives to Popen for CAN bus access?
<p>I'm currently using Popen to send instructions to a utility (<code>canutils</code>... the <code>cansend</code> function in particular) via the command line.</p> <p>The entire function looks like this.</p> <pre><code>def _CANSend(self, register, value, readWrite = 'write'): """send a CAN frame""" queue=self.CANbus.queue cobID = hex(0x600 + self.nodeID) #assign nodeID indexByteLow,indexByteHigh,indexByteHigher,indexByteHighest = _bytes(register['index'], register['objectDataType']) subIndex = hex(register['subindex']) valueByteLow,valueByteHigh,valueByteHigher,valueByteHighest = _bytes(value, register['objectDataType']) io = hex(COMMAND_SPECIFIER[readWrite]) frame = ["cansend", self.formattedCANBus, "-i", cobID, io, indexByteLow, indexByteHigh, subIndex, valueByteLow, valueByteHigh, valueByteHigher, valueByteHighest, "0x00"] Popen(frame,stdout=PIPE) a=queue.get() queue.task_done() return a </code></pre> <p>I was running into some issues as I was trying to send frames (the <code>Popen</code> frame actually executes the command that sends the frame) in rapid succession, but found that the Popen line was taking somewhere on the order of 35 ms to execute... every other line was less than 2 us.</p> <p>So... what might be a better way to invoke the <code>cansend</code> function (which, again, is part of the <code>canutils</code> utility...<code>_CANSend</code> is the python function above that calls ) more rapidly?</p>
<p>I suspect that most of that time is due to the overhead of forking every time you run cansend. To get rid of it, you'll want an approach that doesn't have to create a new process for each send.</p> <p>According to <a href="http://libbits.wordpress.com/2012/05/22/socketcan-support-in-python/" rel="nofollow">this blog post</a>, <a href="https://en.wikipedia.org/wiki/SocketCAN" rel="nofollow">SocketCAN</a> is supported by python 3.3. It should let your program create and use CAN sockets directly. That's probably the direction you'll want to go.</p>
python|linux|popen|can-bus|socketcan
4
45
38,892,509
how to install wordcloud package in python?
<pre><code>pip install wordcloud File "&lt;ipython-input-130-12ee30540bab&gt;", line 1 pip install wordcloud ^ SyntaxError: invalid syntax </code></pre> <p>This is the problem I am facing while using <code>pip install wordcloud</code>.</p>
<p><code>pip</code> is a tool used for installing python packages. You should not use this command inside the python interactive shell. </p> <p>Instead, exit out of it and write <code>pip install wordcloud</code> on the main shell.</p>
python|word-cloud
5
46
38,810,696
Python -- sizing frames with weights
<p>In the minimum example code below, you can change the last range(), currently at 3, to 6 and notice that the frames with buttons all get smaller than if you run it with 3. I have configured 6 columns of "lower_frame" to all be weight 1. The expected result is that there are 6 empty columns of the same width no matter how many buttons I put in there. If I put 3 buttons in there, as the example below has by default, the buttons are quite large and leave only room for about 1 more button. If I put 6 buttons in, they fill the space and each gets smaller.</p> <p>How do I achieve the expected result of having equal width columns no matter how many widgets I actually put in the cells? The goal here is a standard size to these buttons that is based on proportion of the screen, not a pixel size, and have it always be the same no matter the number of buttons. I realize I could do a bunch of math with bounding boxes and programatically set the sizes at runtime, but that seems like overkill and lacking elegance.</p> <p>Minimum example:</p> <pre><code>import Tkinter as tk import ttk mods = {} modBtns = {} root = tk.Tk() upper_frame = ttk.Frame(master=root) lower_frame = ttk.Frame(master=root) right_frame = ttk.Frame(master=root) root.columnconfigure(0, weight=3) root.columnconfigure(1, weight=1) root.rowconfigure(0, weight=1) root.rowconfigure(1, weight=5) for i in range(6): lower_frame.columnconfigure(i, weight=1) for i in range(5): lower_frame.rowconfigure(i, weight=1) upper_frame.grid(column=0, row=0, sticky=tk.N + tk.S + tk.E + tk.W) lower_frame.grid(column=0, row=1, sticky=tk.N + tk.S + tk.E + tk.W) right_frame.grid(column=1, row=0, sticky=tk.N + tk.S + tk.E + tk.W) for i in range(3): mods[i] = ttk.Frame(master=lower_frame) mods[i].columnconfigure(0, weight=1) mods[i].rowconfigure(0, weight=1) modBtns[i] = ttk.Button(master=mods[i], text="mod{0}".format(i)) modBtns[i].grid(column=0, row=0, sticky=tk.N + tk.S + tk.E + tk.W) mods[i].grid(column=i, row=0, sticky=tk.N + tk.S + tk.E + tk.W) root.geometry("700x700+0+0") root.mainloop() </code></pre>
<p>If you want all of the rows and all of the columns to have the same width/height, you can set the <code>uniform</code> attribute of each row and column. All columns with the same <code>uniform</code> value will be the same width, and all rows with the same <code>uniform</code> value will be the same height.</p> <p>Note: the actual value to the <code>uniform</code> attribute is irrelevant, as long as it is consistent.</p> <pre><code>for i in range(6): lower_frame.columnconfigure(i, weight=1, uniform='whatever') for i in range(5): lower_frame.rowconfigure(i, weight=1, uniform='whatever') </code></pre>
python|python-2.7|user-interface|tkinter|tk
1
47
40,621,144
Can't get stored python integer back in java in habase google cloud
<p>I'm using hbase over google cloud bigtable to store my bigdata. I have 2 programs. first, store data using python into hbase and the second, read those info back from java by connecting to the same endpoint.</p> <p>so from python interactive shell I can read byte arrays back into an integer (command 15)</p> <pre><code>In [13]: row.cells['stat']['viewability'][0].value Out[13]: '\x00\x00\x00\x00\x00\x00\x00A' In [14]: len(row.cells['stat']['viewability'][0].value) Out[14]: 8 In [15]: struct.unpack('&gt;Q', row.cells['stat']['viewability'][0].value) Out[15]: (65,) </code></pre> <p>but I can't read back the same byte array into java Integer data type<br/> I'm using the following in java</p> <pre><code>byte[] columnFamilyBytes = Bytes.toBytes("stat"); byte[] viewabilityColumnBytes = Bytes.toBytes("viewability"); Integer viewability = Bytes.toInt(c1.getValue(columnFamilyBytes, viewabilityColumnBytes)); </code></pre> <p>and I'm getting NULL in response.</p>
<p>I found the problem<br/> the column stored as long value so I had to first read it as long in java and then convert it to int</p>
java|python|hbase|google-cloud-dataproc
0
48
1,504,804
Using IronPython to learn the .NET framework, is this bad?
<p>Because I'm a Python fan, I'd like to learn the .NET framework using IronPython. Would I be missing out on something? Is this in some way not recommended?</p> <p>EDIT: I'm pretty knowledgeable of Java ( so learning/using a new language is not a problem for me ). If needed, will I be able to use everything I learned in IronPython ( excluding language featurs ) to write C# code?</p>
<p>No, sounds like a good way to learn to me. You get to stick with a language and syntax that you are familiar with, and learn about the huge range of classes available in the framework, and how the CLR supports your code.</p> <p>Once you've got to grips with some of the framework and the CLR services you could always pick up C# in the future. By that point it will just be a minor syntax change from what you already know.</p> <p>Bare in mind that if you are thinking with respect to a career, you won't find many iron python jobs, but like I say, this could be a good way to learn about the framework first, then build on that with C# in a month or twos time.</p>
c#|.net|ironpython
11
49
32,230,578
Django: handle migrations for an imported database?
<p>I'm working in Django 1.8 and trying to set up an existing project. I've inherited a database dump, plus a codebase. </p> <p>I've imported the database dump successfully. </p> <p>The problem is that if I try to run <code>migrate</code> against the imported database I then get errors about columns already existing, because the database is already at the end state of all the migrations:</p> <pre><code> django.db.utils.ProgrammingError: column "managing_group_id" of relation "frontend_pct" already exists </code></pre> <p>How can I resolve this? </p> <p>I would like to be able to add new migrations from this point, and I would also prefer not to delete all the existing migrations. </p> <p>Basically I need a way to say "skip straight to migration 36, and continue from there". </p>
<p>I think your migrations problem solved by the previous Answer. Therefore I'm adding a link below...</p> <p>If you just started django 1.7 and above then</p> <p>Here I'ld like to add a link <a href="https://markusholtermann.eu/2014/09/django-17-database-migrations-done-right/" rel="nofollow">Django Migration How works </a></p> <p>That will useful where I think.</p>
python|django|django-migrations|django-database
1
50
32,399,565
convert python integer to its signed binary representation
<p>Given a positive integer such as 171 and a "register" size, e.g. 8.</p> <p>I want the integer which is represented by the binary representation of 171, i.e. '0b10101011' interpreted as twos complement.</p> <p>In the present case, the 171 should become -85. It is negative because given the "register" size 8, the MSB is 1.</p> <p>I hope I managed to explain my problem. How can I do this conversion?</p> <p>What I tried:</p> <pre><code>size = 8 value = 171 b = bin(value) if b[len(b)-size] == '1': print "signed" # What to do next? </code></pre>
<p>You don't need binary conversion to achieve that:</p> <pre><code>&gt;&gt;&gt; size = 8 &gt;&gt;&gt; value = 171 &gt;&gt;&gt; unsigned = value % 2**size &gt;&gt;&gt; signed = unsigned - 2**size if unsigned &gt;= 2**(size-1) else unsigned &gt;&gt;&gt; signed -85 </code></pre>
python|binary|integer|twos-complement
3
51
43,992,609
Unable to uninstall anaconda from Ubuntu 16.04
<p>I am trying to uninstall Ananconda from my Ubuntu 16.04 LTS machine.</p> <p>I ran the following commands</p> <pre><code>conda install anaconda-clean anaconda-clean rm -rf ~/anaconda </code></pre> <p>Everything is getting exceuted without any error/warning. If fact, when I run <code>anaconda-clean</code> it is saying so and so packages have been uninstalled. However, I can still open up anaconda navigator and everything seems to be working just fine. What am I missing?</p>
<pre><code>conda install anaconda-clean anaconda-clean --yes rm -rf ~/anaconda3 </code></pre> <p>Replace <em>anaconda3</em> with your version of anaconda</p> <p>This will uninstall anaconda</p>
python|ubuntu|anaconda|ubuntu-16.04|uninstallation
4
52
34,612,214
if loop repeating first if statement
<p>I'm trying to create a continuous question loop to process all my calculations for my nmea sentences in my project. For some reason only the first <code>if</code> statement is executed. What am I doing wrong? I'm still fairly new to python</p> <pre><code> if command_type == "$GPGGA" or "GPGGA" or "GGA": #define the classes gps = GPS() createworkbook = CreateWorkbook() convertfile = ConvertFile() print_gps = PrintGPS() #do the deeds createworkbook.openworkbook(data) print_gps.process_gpgga_data(data) createworkbook.closeworkbook_gpgga(data) convertfile.convert2csv(data) convertfile.convert2kml(data) if command_type == "$GPRMC" or "GPRMC" or "RMC": #define the classes gps = GPS() createworkbook = CreateWorkbook() convertfile = ConvertFile() print_gps = PrintGPS() #do the deeds createworkbook.openworkbook(data) print_gps.process_gprmc_data(data) createworkbook.closeworkbook_gprmc(data) convertfile.convert2csv(data) convertfile.convert2kml(data) if command_type == "$GPGLL" or "GPGLL" or "GLL": #define the classes gps = GPS() createworkbook = CreateWorkbook() convertfile = ConvertFile() print_gps = PrintGPS() #do the deeds createworkbook.openworkbook(data) print_gps.process_gpgll_data(data) createworkbook.closeworkbook_gpgll(data) convertfile.convert2csv(data) convertfile.convert2kml(data) if command_type == "$GPGSA" or "GPGSA" or "GSA": #define the classes gps = GPS() createworkbook = CreateWorkbook() convertfile = ConvertFile() print_gps = PrintGPS() #do the deeds createworkbook.openworkbook(data) print_gps.process_gpgsa_data(data) createworkbook.closeworkbook_gpgsa(data) convertfile.convert2csv(data) if command_type == "$GPVTG" or "GPVTG" or "VTG": print('Better check $GPRMC') else: print("Invalid type:", command_type) list_gps_commands(data) wannalook = input('Want to look at another message or no?') if not wannalook.startswith('y'): keep_asking = False print('********************') print('**mischief managed**') print('********************') </code></pre>
<pre><code>if command_type == "$GPGGA" or "GPGGA" or "GGA": </code></pre> <p>As you can see, here you are not trying to check if <em>command_type</em> is valued "$GPGGA" or "GPGGA" or "GGA". But if <em>command_type == "$GPGGA"</em> is true <strong>or</strong> <em>"GPGGA"</em> is true <strong>or</strong> <em>"GGA"</em> is true.</p> <p>And a non-empty string in python is always true : your first condition will be evaluated true.</p> <p>So you have to do : </p> <pre><code>if command_type == "$GPGGA" or command_type == "GPGGA" or command_type == "GGA" </code></pre>
python|loops|python-3.x|if-statement
2
53
789,598
What is the easiest way to build Python26.zip for embedded distribution?
<p>I am using Python as a plug-in scripting language for an existing C++ application. I am able to embed the python interpreter as stated in the Python documentation. Everything works successfully with the initialization and de-initialization of the interpreter. I am, however, having trouble loading modules because I have not been able to zip up the standard library in to a zip file (normally PythonXX.zip, corresponding to the version number of the python dll). </p> <p>What is the simplest way to zip up all of the standard library after optimized bytecode compiling? I'm looking for a simple script or command to do so for me, as I really don't want to do this by hand. </p> <p>Any ideas? </p> <p>Thanks!</p>
<p>I would probably use <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow noreferrer">setuptools</a> to create an egg (basically a java jar for python). The setup.py would probably look something like this:</p> <pre><code>from setuptools import setup, find_packages setup( name='python26_stdlib', package_dir = {'' : '/path/to/python/lib/directory'}, packages = find_packages(), #any other metadata ) </code></pre> <p>You could run this using <code>python setup.py bdist_egg</code>. Once you have the egg, you can either add it to the python path or you can install it using setuptools. I believe this should also handle the generation of pycs for you as well.</p> <p><strong>NOTE</strong>: I wouldn't use this on my system python directory. You might want to set up a <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow noreferrer">virtualenv</a> for this.</p>
c++|python|distribution|embedded-language
2
54
1,053,344
Modeling a complex relationship in Django
<p>I'm working on a Web service in Django, and I need to model a very specific, complex relationship which I just can't be able to solve.</p> <p>Imagine three general models, let's call them Site, Category and Item. Each Site contains one or several Categories, but it can relate to them in one of two possible ways: one are "common" categories, which are in a many-to-many relationship: they are predefined, and each Site can relate to zero or more of the Categories, and vice versa. The other type of categories are individually defined for each site, and one such category "belongs" only to that site and none other; i.e. they are in a many-to-one relationship, as each Site may have a number of those Categories.</p> <p>Internally, those two type of Categories are completely identical, they only differ in the way they are related to the Sites. It could, however, separate them in two different models (with a common parent model probably), but that solves only half of my problem: the Item model is in a many-to-one relationship with the Categories, i.e. each Item belongs to only one Category, and ideally it shouldn't care how it is related to a Site.</p> <p>Another solution would be to allow the two separate types of Site-Category relations to coexist (i.e. to have both a ForeignKey and a ManyToMany field on the same Category model), but this solution feels like opening a whole other can of worms.</p> <p>Does anyone have an idea if there is a third, better solution to this dead end?</p>
<p>Why not just have both types of category in one model, so you just have 3 models?</p> <pre><code>Site Category Sites = models.ManyToManyField(Site) IsCommon = models.BooleanField() Item Category = models.ForeignKey(Category) </code></pre> <p>You say "Internally, those two type of Categories are completely identical". So in sounds like this is possible. Note it is perfectly valid for a ManyToManyField to have only one value, so you don't need "ForeignKey and a ManyToMany field on the same Category model" which just sounds like a hassle. Just put only one value in the ManyToMany field</p>
python|django|django-models|entity-relationship
4
55
815,530
How to use subversion Ctypes Python Bindings?
<p>Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly i need to download/install/compile in order to do something like</p> <pre><code>import svn from almighty_ctype_subversion_bindings svn.get( "\\rep\\project" ) </code></pre> <p>And how is this connected to pysvn project? Is this a same technology, or different technologies?</p>
<p>You need the Subversion source distribution, Python (>= 2.5), and <a href="http://code.google.com/p/ctypesgen/" rel="nofollow noreferrer">ctypesgen</a>.</p> <p>Instructions for building the ctypes bindings are <a href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/README" rel="nofollow noreferrer">here</a>.</p> <p>You will end up with a package called <code>csvn</code>, examples of it's use are <a href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/examples/" rel="nofollow noreferrer">here</a>.</p>
python|svn
1
56
47,413,755
Installing Python's Cryptography on Windows
<p>I've created a script on windows to connect to Remote SSH server. I have successfully installed <code>cryptography</code>, <code>pynacl</code> and finally <code>paramiko</code>(Took me an entire day to figure out how to successfully install them on windows).</p> <p>Now that I run the script, it pops an error saying that the DLL loading has failed. The error seems to be related to <code>libsodium</code> but I cannot figure out exactly which DLL is to trying to load and from where. Just to be on the safer side I also installed <code>pysodium</code>.</p> <p>Here's the script:</p> <blockquote> <p>automate.py</p> </blockquote> <pre><code>import SSH connection = ssh("10.10.65.100", "gerrit2", "gerrit@123") print("Calling OpenShell") connection.openShell() print("Calling sendShell") connection.sendShell("ls -l") print("Calling process") connection.process() print("Calling closeConnection") connection.closeConnection() </code></pre> <blockquote> <p>SSH.py</p> </blockquote> <pre><code>import threading, paramiko class ssh: shell = None client = None transport = None def __init__(self, address, username, password): print("Connecting to server on ip", str(address) + ".") self.client = paramiko.client.SSHClient() self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy()) self.client.connect(address, username=username, password=password, look_for_keys=False) self.transport = paramiko.Transport((address, 22)) self.transport.connect(username=username, password=password) thread = threading.Thread(target=self.process) thread.daemon = True thread.start() def closeConnection(self): if(self.client != None): self.client.close() self.transport.close() def openShell(self): self.shell = self.client.invoke_shell() def sendShell(self, command): if(self.shell): self.shell.send(command + "\n") else: print("Shell not opened.") def process(self): global connection while True: # Print data when available if self.shell != None and self.shell.recv_ready(): alldata = self.shell.recv(1024) while self.shell.recv_ready(): alldata += self.shell.recv(1024) strdata = str(alldata, "utf8") strdata.replace('\r', '') print(strdata, end = "") if(strdata.endswith("$ ")): print("\n$ ", end = "") </code></pre> <p>And here's the error:</p> <pre><code>&gt; python automate.py Traceback (most recent call last): File "automate.py", line 1, in &lt;module&gt; import SSH File "D:\Automate\SSH_Paramiko\SSH.py", line 1, in &lt;module&gt; import threading, paramiko File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\paramiko-2.4.0-py3.7.egg\paramiko\__init__.py", line 22, in &lt;module&gt; File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\paramiko-2.4.0-py3.7.egg\paramiko\transport.py", line 57, in &lt;module&gt; File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\paramiko-2.4.0-py3.7.egg\paramiko\ed25519key.py", line 22, in &lt;module&gt; File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\nacl\signing.py", line 19, in &lt;module&gt; import nacl.bindings File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\nacl\bindings\__init__.py", line 17, in &lt;module&gt; from nacl.bindings.crypto_box import ( File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\nacl\bindings\crypto_box.py", line 18, in &lt;module&gt; from nacl._sodium import ffi, lib ImportError: DLL load failed: The specified module could not be found. </code></pre>
<p>After a lot of googling, I finally stumbled upon <a href="https://github.com/pyca/pynacl/issues/281" rel="nofollow noreferrer">this</a>. As mentioned in the conversation I uninstalled my previous pynacl installation, downloaded the zipped source from <a href="https://github.com/lmctv/pynacl/archive/v1.2.a0.reorder.zip" rel="nofollow noreferrer">https://github.com/lmctv/pynacl/archive/v1.2.a0.reorder.zip</a>, downloaded libsodium from <a href="https://github.com/jedisct1/libsodium/releases/download/1.0.15/libsodium-1.0.15.tar.gz" rel="nofollow noreferrer">https://github.com/jedisct1/libsodium/releases/download/1.0.15/libsodium-1.0.15.tar.gz</a>, set <code>LIB</code> environment variable to <code>D:\Users\prashant-gu\Downloads\libsodium-1.0.15\bin\x64\Release\v140\dynamic</code>, and finally installed pynacl form this downloaded source using </p> <p><code>pip install .</code></p> <p>Now it works fine.</p> <p>During the installation of <code>paramiko</code>, I also happen to download OpenSSL from <a href="https://ci.cryptography.io/job/cryptography-support-jobs/job/openssl-release-1.1/" rel="nofollow noreferrer">https://ci.cryptography.io/job/cryptography-support-jobs/job/openssl-release-1.1/</a>, and set INCLUDE environment variable to <code>D:\Users\prashant-gu\Downloads\openssl-1.1.0g-2015-x86_64\openssl-win64-2015\include</code> in order to successfully install the <code>cryptography</code> package which happens to be a dependency for <code>paramiko</code>.</p>
python|windows|ssh
0
57
47,206,902
OpenCV Python Assertion Failed
<p>I am trying to run opencv-python==3.3.0.10 on a macOS 10.12.6 to read from a file and show the video in a window. I have exactly copied the code from here <a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="nofollow noreferrer">http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html</a>, section 'Playing' video from file.</p> <p>The code runs correctly and shows the video, however after termination of the video it breaks the program, giving the following error:</p> <blockquote> <p>Assertion failed: (ec == 0), function unlock, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/libcxx/libcxx-307.5/src/mutex.cpp, line 48.</p> </blockquote> <p>Does anyone have any idea of what might cause this?</p> <hr> <p>Code snippet for your convenience (edited to include some suggestions in the comment)</p> <pre><code>cap = cv2.VideoCapture('vtest.avi') while(True): ret, frame = cap.read() if not ret: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cv2.destroyAllWindows() </code></pre>
<p>It's not clear from your question, but it looks like you're specifically running into a situation where the video completes playing without being interrupted. I <em>think</em> the issue is that the VideoCapture object is already closed by the time you get to <code>cap.release()</code>. I'd recommend putting the call to <code>release</code> inside of the <code>if</code> statement by the break.</p> <p>I've not had time to experiment, but I normally follow this pattern:</p> <pre><code>reader = cv2.VideoCapture(&lt;stuff&gt;) while True: success, frame = reader.read() if not success: break </code></pre> <p>I'd not had to call <code>release</code> explicitly in those contexts.</p>
python|opencv|opencv3.0|opencv-python
1
58
57,332,622
reference to invalid character number: (Python ElementTree parse)
<p>I have xml file which has following content:</p> <pre><code> &lt;word&gt;vegetation&lt;/word&gt; &lt;word&gt;cover&lt;/word&gt; &lt;word&gt;(&amp;#x2;31%&lt;/word&gt; &lt;word&gt;split_identifier ;&lt;/word&gt; &lt;word&gt;Still&lt;/word&gt; &lt;word&gt;and&lt;/word&gt; </code></pre> <p>When I read the file using ElmentTree parse, it gives me error : </p> <blockquote> <p>xml.etree.ElementTree.ParseError: reference to invalid character number </p> </blockquote> <p>Its becuase of (&amp;#x2 which is "~").</p> <p>How can I take care of such issues. I am not sure how many other symbols i would get in future.</p>
<p>If you want to get rid of those special characters, you can by scrubbing the input XML as a string:</p> <pre><code>respXML = response.content.decode("utf-16") scrubbedXML = re.sub('&amp;.+[0-9]+;', '', respXML) respRoot = ET.fromstring(scrubbedXML) </code></pre> <p>If you prefer to keep the special characters you may parse them beforehand. In your case it looks like html, therefore you may use the python html module:</p> <pre><code>import html respRoot = ET.fromstring(html.unescape(response.content.decode("utf-16")) </code></pre>
python|elementtree
1
59
57,447,687
Can I save results anyway even when Keyboardinterrupt?
<p>I have a very long code which is taking forever to run. I was wondering if there is a way to save the results even if I use the keyboard to interrupt the code from running? All the examples I found were using except with Keyboardinterrupt, so I don't know if this is the right code to use.</p> <p>More concretely: I have a code which ends with saving results in a list, and returning the list. In this case, is there a way to return the list despite keyboardinterrupt? Can I use <code>if keyboardinterrupt</code> statement?</p> <p>My code:</p> <pre><code># removed is a very long list for a, b in itertools.combinations(removed, 2): temp = [a,b] Token_Set_Ratio = fuzz.token_set_ratio(temp[0],temp[1]) if Token_Set_Ratio &gt; k: c = random.choice(temp) if c in removed: removed.remove(c) else: pass else: pass return removed </code></pre> <p>Where can I add the part for python to retain removed even if keyboard interrupt occurs?</p>
<p>You could use a <code>try</code>-<code>except</code> with <code>KeyboardInterrupt</code>:</p> <pre><code>def your_function(): removed = [...] try: # Code that takes long time for a, b in itertools.combinations(removed, 2): ... return removed except KeyboardInterrupt: return removed </code></pre> <p>A small example:</p> <pre><code>import time def foo(): result = [] try: # Long running code for i in range(10000): result.append(i) time.sleep(0.1) return result except KeyboardInterrupt: # Code to "save" return result print(foo()) </code></pre> <p>When you Ctrl-C before the end of execution, a partial list is printed.</p>
python|python-3.x|keyboardinterrupt
2
60
71,057,396
How can i replace a value in a specific row and column in a csv file
<p>I need to replace a value in correspondence of an ID in a .csv file:</p> <pre><code>ChatId,Color 805525230,black </code></pre> <p>So if the ID in input is equal to the one in the file my program will replace the Color &quot;black&quot; with the new one. I tried this:</p> <pre class="lang-py prettyprint-override"><code>for idx, row in enumerate(df.ChatId): if str(row) == str(CHAT_ID): df.loc[1,idx] = BGc df.to_csv(&quot;path&quot;) </code></pre>
<p>Assuming you loaded the csv on a dataframe, you could you use some of its functions.</p> <p>For example: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html</a></p> <p>Alternatively, you could use the loc function:</p> <pre><code>df.loc[df['ChatId'=='SomeId'], 'Color'] = 'ValueToReplace' </code></pre> <p>If you need to apply it to a different column, you can 'Color' with the appropriate name. <br> I think you could even include a list of column names, though I haven't tested it</p>
python|pandas|csv
0
61
11,737,817
What is the simplest language which support template&context mechanism?
<p>I need to find the easiest way to automatically build ebooks from downloaded articles.</p> <p>I want to automatically generate TOC, which will be based on HTML template.</p> <p>I know that python django has template &amp; context mechanism, however django is a little to complicated for people to which I am preparing this whole mechanism. I don't need all web-related features.</p>
<p>IMHO, if you are familiar with Django:</p> <ul> <li>if you want to build a command line application or a abstract library, look at <a href="http://jinja.pocoo.org/docs/" rel="nofollow">Jinja2</a> template engine.</li> <li>if you are looking for a web framework simpler than Django, look at <a href="http://flask.pocoo.org/docs/" rel="nofollow">Flask</a> (Flask uses Jinja2 as the default template engine).</li> </ul>
python|django|templates|programming-languages|django-context
3
62
46,815,043
python managing tasks in threads when using priority queue
<p>I'm trying to write a program which starts new tasks in new threads. Data is passed from task threads to a single worker/processing thread via a priority queue (so more important jobs are processes first). The worker/processing thread gets higher priority data from the queue and limits calls to a REST API </p> <p>How can I passed the data back to it's origionating task thread, while tracking that all that particular task threads data has been processed?</p> <p>Thanks</p>
<p>In your request queue entry include a response queue. When finished place a response on the response queue.</p> <p>The requesting thread waits on the response queue.</p> <p>A callback method could alternately be used.</p>
python|queue
0
63
46,730,360
Wrong datetimes picked up by pandas
<p>Data Scraped</p> <p><a href="https://i.stack.imgur.com/lULod.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lULod.png" alt="enter image description here"></a></p> <p>So I've scraped data from a website with a timestamp of when it was scraped. As you can see I have no date between 2017-09-14 13:56:28 and 2017-09-16 14:43:05, however when I scrape it using the following code:</p> <pre><code>path ='law_scraped' files = glob.glob(path + "/*.csv") frame = pd.DataFrame() for f in files: df = pd.read_csv(f) df['dtScraped'] = df['dtScraped'].str.replace("|", " ") try: df['dtScraped'] = pd.to_datetime(df['dtScraped'], format = "%Y/%m/%d %H:%M:%S") except Exception as e: df['dtScraped'] = pd.to_datetime(df['dtScraped']) frame = pd.concat([frame, df], ignore_index=True) </code></pre> <p>I get datetimes that don't match the data as you can see below:</p> <pre><code>+-----------+---------------------+-------+-------------------+ | | dtScraped | odds | team | +-----------+---------------------+-------+-------------------+ | 15117 | 2017-09-14 14:00:00 | 7.75 | Feyenoord | | 15118 | 2017-09-14 14:00:00 | 1.446 | Manchester City | | 15119 | 2017-09-14 14:00:00 | 5.01 | Draw | | 15120 | 2017-09-14 14:00:00 | 4.73 | NK Maribor | | 15121 | 2017-09-14 14:00:00 | 1.869 | Spartak Moscow | | 15122 | 2017-09-14 14:00:00 | 3.65 | Draw | | 15123 | 2017-09-14 14:00:00 | 1.694 | Liverpool | | 15124 | 2017-09-14 14:00:00 | 5.16 | Sevilla | | 15125 | 2017-09-14 14:00:00 | 4.25 | Draw | | 15126 | 2017-09-14 14:00:00 | 3.53 | Shakhtar Donetsk | | 15127 | 2017-09-14 14:00:00 | 2.19 | Napoli | | 15128 | 2017-09-14 14:00:00 | 3.58 | Draw | | 15129 | 2017-09-14 14:00:00 | 2.15 | RB Leipzig | | 15130 | 2017-09-14 14:00:00 | 3.5 | AS Monaco | | 15131 | 2017-09-14 14:00:00 | 3.73 | Draw | | 15132 | 2017-09-14 14:00:00 | 1.044 | Real Madrid | | 15133 | 2017-09-14 14:00:00 | 34.68 | APOEL Nicosia | | 15134 | 2017-09-14 14:00:00 | 23.04 | Draw | | 15135 | 2017-09-14 14:00:00 | 2.33 | Tottenham Hotspur | | 15136 | 2017-09-14 14:00:00 | 3.12 | Borussia Dortmund | | 15137 | 2017-09-14 14:00:00 | 3.69 | Draw | | 15138 | 2017-09-14 14:00:00 | 1.52 | FC Porto | | 15139 | 2017-09-14 14:00:00 | 7.63 | Besiktas JK | | 15140 | 2017-09-14 14:00:00 | 4.32 | Draw | | 144009 | 2017-09-14 14:00:00 | 7.75 | Feyenoord | | 144010 | 2017-09-14 14:00:00 | 1.446 | Manchester City | | 144011 | 2017-09-14 14:00:00 | 5.01 | Draw | | 144012 | 2017-09-14 14:00:00 | 4.609 | NK Maribor | | 144013 | 2017-09-14 14:00:00 | 1.892 | Spartak Moscow | | 144014 | 2017-09-14 14:00:00 | 3.64 | Draw | | 144015 | 2017-09-14 14:00:00 | 1.694 | Liverpool | | 144016 | 2017-09-14 14:00:00 | 5.16 | Sevilla | | 144017 | 2017-09-14 14:00:00 | 4.25 | Draw | | 144018 | 2017-09-14 14:00:00 | 3.53 | Shakhtar Donetsk | | 144019 | 2017-09-14 14:00:00 | 2.19 | Napoli | | 144020 | 2017-09-14 14:00:00 | 3.58 | Draw | | 144021 | 2017-09-14 14:00:00 | 2.15 | RB Leipzig | | 144022 | 2017-09-14 14:00:00 | 3.5 | AS Monaco | | 144023 | 2017-09-14 14:00:00 | 3.73 | Draw | | 144024 | 2017-09-14 14:00:00 | 1.044 | Real Madrid | | 144025 | 2017-09-14 14:00:00 | 34.68 | APOEL Nicosia | | 144026 | 2017-09-14 14:00:00 | 23.04 | Draw | | 144027 | 2017-09-14 14:00:00 | 2.33 | Tottenham Hotspur | | 144028 | 2017-09-14 14:00:00 | 3.12 | Borussia Dortmund | | 144029 | 2017-09-14 14:00:00 | 3.69 | Draw | | 144030 | 2017-09-14 14:00:00 | 1.52 | FC Porto | | 144031 | 2017-09-14 14:00:00 | 7.63 | Besiktas JK | | 144032 | 2017-09-14 14:00:00 | 4.32 | Draw | +-----------+---------------------+-------+-------------------+ </code></pre>
<p>Assuming your timestamps have the same format as the filenames in your screenshot, this should work (after the replacement of <code>"|"</code> by <code>" "</code>):</p> <pre><code>df['dtScraped'] = pd.to_datetime(df['dtScraped'], format="%Y-%m-%d %H-%M-%S") </code></pre>
python-3.x|pandas
0
64
37,619,363
Plot wind speed and direction from u, v components
<p>I'm trying to plot the wind speed and direction, but there is an error code that keeps telling me that "sequence too large; cannot be greater than 32." Here is the code that I am using:</p> <pre><code>N = 500 ws = np.array(u) wd = np.array(v) df = pd.DataFrame({'direction': [ws], 'speed': [wd]}) df direction speed 0 [[-7.87291, -8.19969, -8.41213, -8.42775, -8.4... [[-3.68055, -4.07912, -4.07992, -3.55594, -3.2... from windrose import plot_windrose N = 500 ws = np.random.random(u) * 6 wd = np.random.random(v) * 360 df = pd.DataFrame({'speed': ws, 'direction': wd}) plot_windrose(df, kind='contour', bins=np.arange(0.01,8,1), cmap=cm.hot, lw=3) ValueError Traceback (most recent call last) &lt;ipython-input-78-dfb188ec377a&gt; in &lt;module&gt;() 1 from windrose import plot_windrose 2 N = 500 3 ws = np.random.random(u) * 6 4 wd = np.random.random(v) * 360 5 df = pd.DataFrame({'speed': ws, 'direction': wd}) mtrand.pyx in mtrand.RandomState.random_sample (numpy\random\mtrand\mtrand.c:10396)() mtrand.pyx in mtrand.cont0_array (numpy\random\mtrand\mtrand.c:1865)() ValueError: sequence too large; cannot be greater than 32 </code></pre> <p>How do I fix this and plot the U and V? Thank you.</p>
<p>To plot wind U, V use <code>barbs</code> and <code>quiver</code>. Look at the code below:</p> <pre><code>import matplotlib.pylab as plt import numpy as np x = np.linspace(-5, 5, 5) X, Y = np.meshgrid(x, x) d = np.arctan(Y ** 2. - .25 * Y - X) U, V = 5 * np.cos(d), np.sin(d) # barbs plot ax1 = plt.subplot(1, 2, 1) ax1.barbs(X, Y, U, V) #quiver plot ax2 = plt.subplot(1, 2, 2) qui = ax2.quiver(X, Y, U, V) plt.quiverkey(qui, 0.9, 1.05, 1, '1 m/s',labelpos='E',fontproperties={'weight': 'bold'}) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/WhRt0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WhRt0.png" alt="enter image description here"></a></p>
python|pandas|matplotlib|jupyter-notebook
1
65
37,934,099
Python 2.7.3 urllib2 Error
<p>When I try to run my python script this error happens. How can I solve this problem ?</p> <pre><code>['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'urllib2'] Traceback (most recent call last): File "m.py", line 3, in &lt;module&gt; import requests File "/usr/local/lib/python2.7/dist-packages/requests-2.9.1-py2.7.egg/requests/__init__.py", line 58, in &lt;module&gt; from . import utils File "/usr/local/lib/python2.7/dist-packages/requests-2.9.1-py2.7.egg/requests/utils.py", line 26, in &lt;module&gt; from .compat import parse_http_list as _parse_list_header File "/usr/local/lib/python2.7/dist-packages/requests-2.9.1-py2.7.egg/requests/compat.py", line 38, in &lt;module&gt; from urllib2 import parse_http_list ImportError: cannot import name parse_http_list </code></pre>
<p>you need to upgrade <a href="https://pypi.python.org/pypi/requests/" rel="nofollow">requests</a> </p> <pre><code>pip install --upgrade requests </code></pre>
python
2
66
67,669,925
"The request's session was deleted before the request completed. The user may have logged out in a concurrent request"
<p>&quot;The request's session was deleted before the request completed. The user may have logged out in a concurrent request&quot; I am facing this error when trying to use 2 request.session().</p> <p>In my code my using two request.session() to store variables.After one request successfully completed,its going to another request and throwing this error.</p> <pre><code>request.session['dataset1'] = dataset1.to_json() request.session['total_cols'] = total_cols // getting error here </code></pre> <p>Please help to resolve the same.</p>
<p>Since my dataset has 8000 rows, It was not a good idea to store in session variables. I have written some rest calls and that solved my problem.</p>
python|django
0
67
30,036,305
Shelves an multiple items
<p>I've been trying to make a quote input that puts multiple quotes inside a file (coupled with the authors name). I have tried with pickle, but I could not get more than 2 pickled items inside a file and finally I decided to use shelf.</p> <p>However, I am having some trouble with shelves as well.</p> <p>I dont really know how to put multiple items inside a file, even if I can shelf one.</p> <pre><code>import pickle import shelve quote = [] author = [] def givequote(): f = shelve.open('quotation') ## open the shelve so that i can write stuff in it f["quote"] = raw_input("What quote has its place in the quote book? \n to quit press Q\n\n") ## ask for input so that i can put stuff into quote, ##quote is a random value so its a problem, i might have to make a key/value first. if quote != "Q": f['author'] = raw_input("what author said that? \n to quit press Q \n\n") if author == "Q": print "goodbye" elif quote == "Q": print "goodbye" f.close() def readquote(): f = shelve.open('quotation') print "%3s\n - %s" % (f["quote"], f['author']) </code></pre> <p>thank you.</p> <p>After finding out how it works I plan to try to make the same program using classes ( was thinking of nested ones) and methods, just to practice figuring out my inner programmer.</p>
<p>You can do this with pickle. As this <a href="https://stackoverflow.com/questions/12761991/how-to-use-append-with-pickle-in-python">answer</a> describes, you can append a pickled object to a binary file using open with append in binary mode. </p> <p>To read the multiple pickled objects out of the file, just call <code>pickle.load</code> on the file handle until you get an EOF error.</p> <blockquote> <p>so your unpickle code might look like</p> <pre><code>import pickle objs = [] while 1: try: objs.append(pickle.load(f)) except EOFError: break </code></pre> </blockquote>
python
0
68
57,028,126
"chalice deploy" call ends up with "Unknown parameter in input: "Layers""
<p>I create the most basic chalice app </p> <pre><code>from chalice import Chalice app = Chalice(app_name='testApp') @app.route('/') def index(): return {'hello': 'world'} </code></pre> <p>with empty requirements.txt and config that looks like this:</p> <pre><code>{ "version": "2.0", "app_name": "testApp", "stages": { "dev": { "api_gateway_stage": "api" } } } </code></pre> <p>Error fires right after the first deploy</p> <p>This is the error i receive:</p> <p>Creating deployment package. Updating policy for IAM role: testApp-dev Updating lambda function: testApp-dev Traceback (most recent call last): File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\cli__init__.py", line 466, in main return cli(obj={}) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 722, in <strong>call</strong> return self.main(*args, **kwargs) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 697, in main rv = self.invoke(ctx) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 1066, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 535, in invoke return callback(*args, **kwargs) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\cli__init__.py", line 202, in deploy deployed_values = d.deploy(config, chalice_stage_name=stage) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\deploy\deployer.py", line 342, in deploy return self._deploy(config, chalice_stage_name) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\deploy\deployer.py", line 355, in _deploy self._executor.execute(plan) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\deploy\executor.py", line 31, in execute self._default_handler)(instruction) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\deploy\executor.py", line 43, in _do_apicall result = method(**final_kwargs) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\awsclient.py", line 283, in update_function layers=layers File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\awsclient.py", line 352, in _update_function_config max_attempts=self.LAMBDA_CREATE_ATTEMPTS File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\awsclient.py", line 1009, in _call_client_method_with_retries response = method(**kwargs) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\botocore\client.py", line 314, in _api_call return self._make_api_call(operation_name, kwargs) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\botocore\client.py", line 586, in _make_api_call api_params, operation_model, context=request_context) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\botocore\client.py", line 621, in _convert_to_request_dict api_params, operation_model) File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\botocore\validate.py", line 291, in serialize_to_request raise ParamValidationError(report=report.generate_report()) botocore.exceptions.ParamValidationError: Parameter validation failed:</p> <p>Unknown parameter in input: "Layers", must be one of: FunctionName, Role, Handler, Description, Timeout, MemorySize, VpcConfig, Environment, Runtime, DeadLetterConfig, KMSKeyArn, TracingConfig, RevisionId</p>
<p>After troubleshooting found some issues with my local configurations. What helped was running the chalice in virtualenv (<a href="https://virtualenv.pypa.io/en/latest/" rel="nofollow noreferrer">https://virtualenv.pypa.io/en/latest/</a>)</p>
python|amazon-web-services|deployment|aws-lambda|chalice
0
69
65,540,231
Import and insert word in sequence in Python
<p>I want to <strong>import</strong> and <strong>insert</strong> word in <strong>sequence</strong> and <strong>NOT RANDOMLY</strong>, each registration attempt uses a <strong>single</strong> username and <strong>stop</strong> until the registration is <strong>completed</strong>. Then logout and begin a <strong>new</strong> registration with the <strong>next</strong> username in the list if the <strong>REGISTRATION is FAILED</strong>, and <strong>skip</strong> if the <strong>REGISTRATION is SUCCEDED</strong>.</p> <p>I'm really confused because I have no clue. I've tried this <strong>code</strong> but it chooses randomly and I have <strong>no</strong> idea how to use the &quot;<strong>for loop</strong>&quot;</p> <pre><code>import random Copy = driver.find_element_by_xpath('XPATH') Copy.click() names = [ &quot;Noah&quot; ,&quot;Liam&quot; ,&quot;William&quot; ,&quot;Anthony&quot; ] idx = random.randint(0, len(names) - 1) print(f&quot;Picked name: {names[idx]}&quot;) Copy.send_keys(names[idx]) </code></pre> <p>How can I make it choose the next word in sequence and <strong>NOT RANDOMLY</strong> Any Help Please</p>
<p>I am going to assume that you are happy with what the code does, with exception that the names it picks are random. This narrows everything down to one line, and namely the one that picks names randomly:</p> <pre><code>idx = random.randint(0, len(names) - 1) </code></pre> <p>Simple enough, you want &quot;the next word in sequence and NOT RANDOMLY&quot;: <a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/datastructures.html#more-on-lists</a></p> <p>If you take a look at the link I've provided, you can see that lists have a <em><strong>pop()</strong></em> method, returning and removing some element from the list. We want the first one so we will provide 0 as the argument for the pop method.</p> <p>We modify the line to look something like this</p> <pre><code>name = names.pop(0) </code></pre> <p>Now you still want to have the for-loop that will loop over all of the actions including name picking so you encapsulate all of the code in a for-loop:</p> <pre><code>names = [ &quot;Noah&quot; ,&quot;Liam&quot; ,&quot;William&quot; ,&quot;Anthony&quot; ] for i in range(len(names)): # ... Copy = driver.find_element_by_xpath('XPATH') Copy.click() name = names.pop(0) print(f&quot;Picked name: {name}&quot;) Copy.send_keys(name) # ... </code></pre> <p>You might notice that the names list is <strong>not</strong> inside the for-loop. That is because we don't want to reassign the list every time we try to use a new name.</p> <p>If you're completely unsure how for-loops work or how to implement one yourself, you should probably start by reading about how they work.</p> <p><a href="https://docs.python.org/3/tutorial/controlflow.html?highlight=loop#for-statements" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/controlflow.html?highlight=loop#for-statements</a></p> <p>Last but not least you can see some <code># ...</code> comments in my example indicating where the logic will probably go for the other part of your question: <em>&quot;Then logout and begin a new registration with the next username in the list if the REGISTRATION is FAILED, and skip if the REGISTRATION is SUCCEDED.&quot;</em> I don't think we I can help you with that since there is simply not enough context or examples in your question.</p> <p>Refer to <a href="https://stackoverflow.com/help/how-to-ask">this guide</a> explaining how to ask a well formulated question so we can help you more next time.</p>
python|import|webforms
0
70
65,903,633
Load a text file paragraph into a string without libraries
<p>sorry if this question may look a bit dumb for some of you but i'm totally a beginner at programming in Python so i'm quite bad and got a still got a lot to learn. So basically I have this long text file separated by paragraphs, sometimes the newline can be double or triple to make the task more hard for us so i added a little check and looks like it's working fine so i have a variable called &quot;paragraph&quot; that tells me in which paragraph i am currently. Now basically i need to scan this text file and search for some sequences of words in it but the newline character is the worst enemy here, for example if i have the string = &quot;dummy text&quot; and i'm looking into this:</p> <pre><code>&quot;random questions about files with a dummy text and strings hey look a new paragraph here&quot; </code></pre> <p>As you can see there is a newline between dummy and text so reading the file line by line doesn't work. So i was wondering to load directly the entire paragraph to a string so this way i can even remove punctuation and stuff more easly and check directly if those sequences of words are contained in it. All this must be done without libraries. However my piece of code of paragraph counter works while the file is being read, so if uploading a whole paragraph in a string is possible i should basically use something like &quot;&quot;.join until the paragraph increases by 1 because we're on the next paragraph? Any idea?</p>
<p>This should do the trick. It is very short and elegant:</p> <pre><code>with open('dummy text.txt') as file: data = file.read().replace('\n', '') print(data)#prints out the file </code></pre> <p>The output is:</p> <pre><code>&quot;random questions about files with a dummy text and strings hey look a new paragraph here&quot; </code></pre>
python|string|file|txt
1
71
43,439,172
Python/Kivy Assertion Error
<p>I obtained an Assertion error while attempting to learn BoxLayout in kivy. I cannot figure out what has went wrong.</p> <pre><code> from kivy.app import App from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout class BoxLayoutApp(App): def build(self): return BoxLayout() if __name__=="__main__": BoxLayoutApp().run() </code></pre> <p>And for the kv code:</p> <pre><code>&lt;BoxLayout&gt;: BoxLayout: Button: text: "test" Button: text: "test" Button: text: "test" BoxLayout: Button: text: "test" Button: text: "test" Button: text: "test" </code></pre> <p>Edit: I tried to subclass BoxLayout as suggested however, I still face an AssertionError. The full (original) error message I reproduce here:</p> <pre><code> Traceback (most recent call last): File "boxlayout.py", line 12, in &lt;module&gt; BoxLayoutApp().run() File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\app.py", line 802, in run root = self.build() File "boxlayout.py", line 8, in build return BoxLayout() File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\boxlayout.py", line 131, in __init__ super(BoxLayout, self).__init__(**kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\layout.py", line 76, in __in it__ super(Layout, self).__init__(**kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\widget.py", line 345, in __i nit__ Builder.apply(self, ignored_consts=self._kwargs_applied_init) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 451, in a pply self._apply_rule(widget, rule, rule, ignored_consts=ignored_consts) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 566, in _ apply_rule self.apply(child) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 451, in a pply self._apply_rule(widget, rule, rule, ignored_consts=ignored_consts) File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 464, in _ apply_rule assert(rule not in self.rulectx) AssertionError </code></pre>
<p>Try subclassing boxlayout instead:</p> <pre><code>from kivy.app import App from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder class MyBoxLayout(BoxLayout): pass Builder.load_string(''' &lt;MyBoxLayout&gt;: BoxLayout: Button: text: "test" Button: text: "test" Button: text: "test" BoxLayout: Button: text: "test" Button: text: "test" Button: text: "test" ''') class BoxLayoutApp(App): def build(self): return MyBoxLayout() if __name__=="__main__": BoxLayoutApp().run() </code></pre> <p>The <code>AssertionError</code> is being thrown because you try to apply rules to the same class you are nesting.<br> In other words you apply a rule to a class, that it shall contain itself.<br> That causes issues.<br> Following will throw the same error.</p> <pre><code>&lt;MyBoxLayout&gt;: MyBoxLayout: </code></pre>
python|kivy
5
72
36,966,316
How to get the dimensions of a tensor (in TensorFlow) at graph construction time?
<p>I am trying an Op that is not behaving as expected.</p> <pre><code>graph = tf.Graph() with graph.as_default(): train_dataset = tf.placeholder(tf.int32, shape=[128, 2]) embeddings = tf.Variable( tf.random_uniform([50000, 64], -1.0, 1.0)) embed = tf.nn.embedding_lookup(embeddings, train_dataset) embed = tf.reduce_sum(embed, reduction_indices=0) </code></pre> <p>So I need to know the dimensions of the Tensor <code>embed</code>. I know that it can be done at the run time but it's too much work for such a simple operation. What's the easier way to do it?</p>
<p>I see most people confused about <code>tf.shape(tensor)</code> and <code>tensor.get_shape()</code> Let's make it clear:</p> <ol> <li><code>tf.shape</code></li> </ol> <p><code>tf.shape</code> is used for dynamic shape. If your tensor's shape is <strong>changable</strong>, use it. An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:<br> <code>new_height = tf.shape(image)[0] / 2</code></p> <ol start="2"> <li><code>tensor.get_shape</code></li> </ol> <p><code>tensor.get_shape</code> is used for fixed shapes, which means the tensor's <strong>shape can be deduced</strong> in the graph. </p> <p>Conclusion: <code>tf.shape</code> can be used almost anywhere, but <code>t.get_shape</code> only for shapes can be deduced from graph. </p>
python|tensorflow|deep-learning|tensor
62
73
36,993,569
/usr/bin/python: No module named pip
<p>I am having a bit of trouble getting everything to work on my Mac running El Capitan. I am running 3.5.1. I am under the impression that Pip is included with an install of the above, however when I try to use it to install sympy using the syntax in terminal: <code>python -m pip install SomePackage</code>, I get the error mentioned in the title. I tried running <code>import pip</code> in IDLE, and got no error, so I am quite confused. If I type pip into IDLE, I get:</p> <pre><code>&lt;module 'pip' from '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/__init__.py'&gt; </code></pre> <p>Does anybody know what the problem is? Do I need to navigate to a certain directory in Terminal when I run the command?</p>
<p>I believe that you can run it by calling <code>pip</code> in the terminal. If you have it already installed.</p> <p><code>pip install sympy</code></p>
python|python-3.x|pip
2
74
36,897,802
Get params validation on viewsets.ModelViewSet
<p>I am new to django and building a REST API using <code>django-rest-framework</code>. I have written some code to check whether the user has supplied some parameters or not.But that is very ugly with lot of <code>if conditions</code>, so i want to refactor it.Below is the code that i have written please suggest how to refactor it.</p> <p>I am looking for some django based validations.</p> <pre><code>class AssetsViewSet(viewsets.ModelViewSet): queryset = Assets.objects.using("gpr").all() def create(self, request): assets = [] farming_details = {} bluenumberid = request.data.get('bluenumberid', None) if not bluenumberid: return Response({'error': 'BlueNumber is required.'}) actorid = request.data.get('actorid', None) if not actorid: return Response({'error': 'Actorid is required.'}) asset_details = request.data.get('asset_details', None) if not asset_details: return Response({'error': 'AssetDetails is required.'}) for asset_detail in asset_details: location = asset_detail.get('location', None) if not location: return Response({'error': 'location details is required.'}) assettype = asset_detail.get('type', None) if not assettype: return Response({'error': 'assettype is required.'}) asset_relationship = asset_detail.get('asset_relationship', None) if not asset_relationship: return Response({'error': 'asset_relationship is required.'}) subdivision_code = location.get('subdivision_code', None) if not subdivision_code: return Response({'error': 'subdivision_code is required.'}) country_code = location.get('country_code', None) if not country_code: return Response({'error': 'country_code is required.'}) locationtype = location.get('locationtype', None) if not locationtype: return Response({'error': 'locationtype is required.'}) latitude = location.get('latitude', None) if not latitude: return Response({'error': 'latitude is required.'}) longitude = location.get('longitude', None) if not longitude: return Response({'error': 'longitude is required.'}) try: country_instance = Countries.objects.using('gpr').get(countrycode=country_code) except: return Response({'error': 'Unable to find country with countrycode ' + str(country_code)}) try: subdivision_instance = NationalSubdivisions.objects.using('gpr').get(subdivisioncode=subdivision_code, countrycode=country_code) except: return Response({'error': 'Unable to find subdivision with countrycode ' + str(country_code) + ' and' + ' subdivisioncode ' + str(subdivision_code)}) kwargs = {} kwargs['pobox'] = location.get('pobox', '') kwargs['sublocation'] = location.get('sublocation', '') kwargs['streetaddressone'] = location.get('streetaddressone', '') kwargs['streetaddresstwo'] = location.get('streetaddresstwo', '') kwargs['streetaddressthree'] = location.get('streetaddressthree', '') kwargs['city'] = location.get('city', '') kwargs['postalcode'] = location.get('postalcode', '') cursor = connections['gpr'].cursor() cursor.execute("Select uuid() as uuid") u = cursor.fetchall() uuid = u[0][0].replace("-", "") kwargs['locationid'] = uuid # l.refresh_from_db() try: Locations.objects.using('gpr').create_location(locationtype=locationtype, latitude=latitude, longitude=longitude, countrycode=country_instance, subdivisioncode = subdivision_instance, **kwargs) except (TypeError, ValueError): return Response({'error': 'Error while saving location'}) try: location_entry = Locations.objects.using('gpr').get(locationid=uuid) except: return Response({'error': 'Unable to find location with locationid ' + str(uuid)}) asset_entry = Assets.objects.using('gpr').create(locationid=location_entry, assettype=assettype) asset_entry = Assets.objects.using('gpr').filter(locationid=location_entry, assettype=assettype).latest('assetinserted') farming_details[asset_entry.assetid] = [] try: actor = Actors.objects.using('gpr').get(actorid = actorid) except: return Response({'error': 'Unable to find actor with actorid ' + str(actorid)}) assetrelationship = AssetRelationships.objects.using('gpr').create(assetid= asset_entry, actorid= actor,assetrelationship=asset_relationship) assets.append(asset_entry) if assettype=="Farm or pasture land": hectares = asset_detail.get('hectares', None) if hectares is None: return Response({'error': 'hectares must be a decimal number'}) try: farmingasset = FarmingAssets.objects.using('gpr').create(assetid=asset_entry, hectares=hectares) except ValidationError: return Response({'error': 'hectares must be decimal value.'}) farmingasset = FarmingAssets.objects.using('gpr').filter(assetid=asset_entry, hectares=hectares).last() for type_detail in asset_detail.get('type_details', []): crop = type_detail.get('crop', '') hectare = type_detail.get('hectare', '') if crop != '' and hectare != '': try: h3code = ProductCodes.objects.using('gpr').get(h3code=crop) except: return Response({'error': 'Unable to find ProductCode with h3code' + str(crop)}) try: farming = Farming.objects.using('gpr').create(assetid=farmingasset, h3code=h3code, annualyield=hectare) farming_details[asset_entry.assetid].append(farming.farmingid) except Exception as e: return Response({'error': e}) else: return Response({'error': 'crop with hectare is required.'}) i = 0 data = {} for asset in assets: if farming_details[asset.assetid]: data[i] = {"assetid": asset.assetid, "assetbluenumber": asset.assetuniversalid, "farming_ids": farming_details[asset.assetid]} else: data[i] = {"assetid": asset.assetid, "assetbluenumber": asset.assetuniversalid} i+=1 return Response(data) </code></pre> <p>Asset Model</p> <pre><code>class Assets(models.Model): assetid = models.CharField(db_column='AssetID', primary_key=True, max_length=255) # Field name made lowercase. assetname = models.CharField(db_column='AssetName', max_length=255, blank=True, null=True) # Field name made lowercase. locationid = models.ForeignKey('Locations', models.DO_NOTHING, db_column='LocationID') # Field name made lowercase. assetuniversalid = models.CharField(db_column='AssetBluenumber', unique=True, blank=True, null=True, max_length=255) # Field name made lowercase. assettype = models.CharField(db_column='AssetType', max_length=45, blank=True, null=True) # Field name made lowercase. assetinserted = models.DateTimeField(db_column='AssetInserted', blank=True, null=True, auto_now_add=True) # Field name made lowercase. assetupdated = models.DateTimeField(db_column='AssetUpdated', blank=True, null=True, auto_now=True) # Field name made lowercase. </code></pre>
<p>You can make <a href="http://www.django-rest-framework.org/api-guide/serializers/#modelserializer" rel="noreferrer">serializers</a>, they have a very easy way to validate your data. As in your case all the fields seem to be required it becomes even easier.</p> <p>Create a file on you api app like:</p> <h3>serializers.py</h3> <pre><code>#Import Serializers lib from rest_framework import serializers #Import your models here (You can put more than one serializer in one file) from assets.model import Assets #Now make you serializer class class AssetsSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' #This last line will put all the fields on you serializer #but you can also especify only some fields like: #fields = ('assetid', 'assetname') </code></pre> <p>On you view you can use your serializer(s) class to validate you data.</p> <h3>views.py</h3> <pre><code>#Serializers from assets.serializers import AssetsSerializer #Libraries you can use from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class AssetsViewSet(viewsets.ModelViewSet): queryset = Assets.objects.using(&quot;gpr&quot;).all() def create(self, request): assets = [] farming_details = {} #Set your serializer serializer = AssetsSerializer(data=request.data) if serializer.is_valid(): #MAGIC HAPPENS HERE #... Here you do the routine you do when the data is valid #You can use the serializer as an object of you Assets Model #Save it serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre> <p>i took this all from the documentation. You can learn a lot doing the <a href="http://www.django-rest-framework.org/tutorial/1-serialization/" rel="noreferrer">tutorial</a> from the official site. I hope it helps.</p>
python|django|django-views|django-rest-framework
8
75
48,687,009
Python - Error in two-layer neural network
<p>I am trying to implement a 2-layer neural network from scratch. But there is something wrong. After some iterations, my loss becomes <code>nan</code>.</p> <pre><code>''' We are implementing a two layer neural network. ''' import numpy as np x,y = np.random.rand(64,1000),np.random.randn(64,10) w1,w2 = np.random.rand(1000,100),np.random.rand(100,10) learning_rate = 1e-4 x -= np.mean(x,axis=0) #Normalizing the Training Data Set for t in range(2000): h = np.maximum(0,x.dot(w1)) # Applying Relu Non linearity ypred = h.dot(w2) #Output of Hidden layer loss = np.square(ypred - y).sum() print('Step',t,'\tLoss:- ',loss) #Gradient Descent grad_ypred = 2.0 * (ypred - y) gradw2 = (h.transpose()).dot(grad_ypred) grad_h = grad_ypred.dot(w2.transpose()) gradw1 = (x.transpose()).dot(grad_h*h*(1-h)) w1 -= learning_rate*gradw1 w2 -= learning_rate*gradw2 </code></pre> <p>I also implemented Linear Regression using a Softmax classifier and multi-class SVM loss. Same problem happens. Please tell me how to resolve this.</p> <p>Output:</p> <pre><code>D:\Study Material\Python 3 Tutorial\PythonScripts\Machine Learning&gt;python TwoLayerNeuralNet.py Step 0 Loss:- 19436393.79233052 Step 1 Loss:- 236820315509427.38 Step 2 Loss:- 1.3887002186558748e+47 Step 3 Loss:- 1.868219503527502e+189 Step 4 Loss:- inf TwoLayerNeuralNet.py:23: RuntimeWarning: invalid value encountered in multiply gradw1 = (x.transpose()).dot(grad_h*h*(1-h)) TwoLayerNeuralNet.py:12: RuntimeWarning: invalid value encountered in maximum h = np.maximum(0,x.dot(w1)) # Applying Relu Non linearity Step 5 Loss:- nan Step 6 Loss:- nan Step 7 Loss:- nan Step 8 Loss:- nan Step 9 Loss:- nan Step 10 Loss:- nan Step 11 Loss:- nan Step 12 Loss:- nan Step 13 Loss:- nan Step 14 Loss:- nan Step 15 Loss:- nan Step 16 Loss:- nan Step 17 Loss:- nan Step 18 Loss:- nan Step 19 Loss:- nan Step 20 Loss:- nan </code></pre>
<p>Its because your loss is becoming too high<br> try this </p> <pre><code>loss = np.square(ypred - y).mean() </code></pre> <p>and if still doesn't work try reducing the learning rate to something like <code>1e-8</code>.<br> and observe if the loss is going up or down, if loss is reducing thats good, if the loss is increasing thats a bad sign, you might want to consider using a better dataset and check the weights updation.</p>
python|neural-network
0
76
19,919,498
How to implement n times nested loops in python?
<p>I want to do nested loops with n times, this n is an variable and can be provided by function or input methods. In order to do this, I have to write lots of if..elif blocks depend on size of n, does anybody have good strategies to handle this task? The codes (for combination of 4 letters problem) I used are as follows:</p> <pre><code>def charCombination(n): patList = [] s = 'ATCG' if n == 1: for i in s: patList.append(i) elif n == 2: for i in s: for j in s: patList.append(i+j) elif n == 3: for i in s: for j in s: for k in s: patList.append(i+j+k) ... return patList </code></pre>
<p>You can use <a href="http://docs.python.org/2/library/itertools.html#itertools.product" rel="noreferrer">itertools.product</a> with <code>repeat</code> parameter</p> <pre><code>import itertools def charCombination(n): return ["".join(item) for item in itertools.product("ATCG", repeat=n)] print charCombination(1) print charCombination(2) print charCombination(3) </code></pre> <p><strong>Output</strong></p> <pre><code>['A', 'T', 'C', 'G'] ['AA', 'AT', 'AC', 'AG', 'TA', 'TT', 'TC', 'TG', 'CA', 'CT', 'CC', 'CG', 'GA', 'GT', 'GC', 'GG'] ['AAA', 'AAT', 'AAC', 'AAG', 'ATA', 'ATT', 'ATC', 'ATG', 'ACA', 'ACT', 'ACC', 'ACG', 'AGA', 'AGT', 'AGC', 'AGG', 'TAA', 'TAT', 'TAC', 'TAG', 'TTA', 'TTT', 'TTC', 'TTG', 'TCA', 'TCT', 'TCC', 'TCG', 'TGA', 'TGT', 'TGC', 'TGG', 'CAA', 'CAT', 'CAC', 'CAG', 'CTA', 'CTT', 'CTC', 'CTG', 'CCA', 'CCT', 'CCC', 'CCG', 'CGA', 'CGT', 'CGC', 'CGG', 'GAA', 'GAT', 'GAC', 'GAG', 'GTA', 'GTT', 'GTC', 'GTG', 'GCA', 'GCT', 'GCC', 'GCG', 'GGA', 'GGT', 'GGC', 'GGG'] </code></pre>
python
5
77
66,959,167
Timer for variable time delay
<p>I would like a timer (Using Python 3.8 currently) that first checks the system time or Naval Observatory clock, so it can be started at any time and synch with the 00 seconds.</p> <p>I'm only interested in the number of seconds on the system clock or Naval Observatory. At the top of every minute, i.e when the seconds = 00 I need to write data to a DataFrame or database, then sleep again for another 60 seconds.</p> <p>I first checked the system time, determined how long it is from the 00 seconds, and placed the first delay for that amount. After that it should delay or sleep for 60 seconds, then run again. Data is constantly changing but at this point I only need to write the data every 60 seconds, would like to also have it have the capability of using other time frames like 5 minutes, 15 minutes etc, but once the first is done the other time frames will be easy.</p> <p>Here is my lame attempt, it runs a few iterations then quits, and I'm sure it's not very efficient</p> <pre class="lang-py prettyprint-override"><code>def time_delay(): sec = int(time.strftime('%S')) if sec != 0: wait_time = 60 - sec time.sleep(wait_time) sec = int(time.strftime('%S')) wait_time = 60 - sec elif time.sleep(60): time_delay() </code></pre>
<p>This will call a function when the seconds are 0:</p> <pre><code>def time_loop(job): while True: if int(time.time()) % 60 == 0: job() time.sleep( 1 ) </code></pre>
python|variables|time|timer|delay
1
78
48,054,298
Finding nearest timeindex for many categories
<p>I am trying to obtain the data points nearest to the query timestamp for multiple independent categories like this (<a href="https://gist.github.com/talesa/babe9955b891c8f75611eaf8e4f48974" rel="nofollow noreferrer">example in more detail in the gist</a>):</p> <pre><code>dt = pd.to_datetime(dt) df_output = list() for category in df.category.unique(): df_temp = df[df.category == category] i = df_temp.index.get_loc(dt, method='nearest') latest = df_temp.iloc[i] df_output.append(latest) pd.DataFrame(df_output) </code></pre> <p>The issue with this approach is that it is very slow (and obviously feels very blunt). Profiling suggests the bottleneck is <code>iloc</code>, which seems odd.</p> <p>What is a faster/more correct way to go about it? Is there a way to obtain the result for all of the categories at once? (I'm thinking of some <code>groupby</code> magic) </p> <p>Is <code>pandas</code> capable of doing it or should I switch to some other timeseries storage method?</p>
<p>Pandas was made for time-series data so this is it's bread and butter. Try this for performance:</p> <pre><code>dt = '2017-12-23 01:49:13' df["timedelta"] = abs(df.index - pd.Timestamp(dt)) df.loc[df.groupby(by="category")["timedelta"].idxmin()].drop("timedelta", axis=1) </code></pre> <p>This is creating a new column called timedelta, named after <code>pandas.Timedelta</code> class, and then using <code>groupby</code> to combine all the categories, find the smallest timedelta in each and return their index into <code>.loc</code>. Lastly I dropped the column.</p>
python|pandas|time-series
1
79
48,082,038
Cassandra Pagination CPU Utilization Issue
<p>I had developed a python script for pulling the data but it is using only single cpu core and when I do top cassandra is using more than 200% cpu. Going into Idle state since in between GC coming into picture Unable understand how can I convert the code to utilize multiple cores and parallel processing.</p> <pre><code>class PagedResultHandler(object): def __init__(self, future): self.error = None self.finished_event = multiprocessing.Event() self.future = future self.future.add_callbacks( callback=self.handle_page, errback=self.handle_error) self.rows = [] def handle_page(self, rows): self.rows += rows if self.future.has_more_pages: self.future.start_fetching_next_page() else: self.finished_event.set() def handle_error(self, exc): self.error = exc self.finished_event.set() start_time = time.time() cluster = Cluster(contact_points=['127.0.0.1'],protocol_version=4) session = cluster.connect('unit_test') query = "select * from "+table_name+" where runseq=0" print("--Fired Query---&gt;&gt; ", query) future = session.execute_async(query) handler = PagedResultHandler(future) handler.finished_event.wait() data = pd.DataFrame(handler.rows) print("--- %s seconds ---" % (time.time() - start_time)) if handler.error: raise handler.error cluster.shutdown() </code></pre> <p>Each table I pull contains more than 3million rows and has lot performance issue. Can I help me how I can Make cpu cores and improve performance </p>
<p>You wont get blazing performance out of python driver, but you can look at cqlsh's copy functions (<a href="https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py#L229" rel="nofollow noreferrer">https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py#L229</a>) if you really want to see a fast implementation that can use multiple cores.</p> <p>On C* side make sure you have enough nodes with adequate hardware (ssds, multiple cores, >16gb of ram). If using sub 8gb heaps etc don't expect much out of it. Cassandra/JVM (with default settings) are designed to fully utilize the server as much as it can, not share resources so expect high CPU.</p>
python-3.x|cassandra
1
80
48,376,460
finding just full words in a python string
<p>Basically it all comes down to finding just the fullword, not matching also a substring thereof.</p> <p>I have phrases like: </p> <p>texto = "hello today is the first day of working week" and what I wanted to do is to split that phrase into words to see if any matched fullwords that I have obtained from a sql query, like this:</p> <pre><code>sql = "select keyword from keywords" try: cursor.execute(sql) # Fetch all the rows in a list of lists. results = cursor.fetchall() for result in results: keywords.append(result) </code></pre> <p>so there I have a tuple of keywords.</p> <p>So, yes, of course, you would split the phrase like this:</p> <pre><code>for word in texto.split(): if word in keywords.__str__(): print ("keyword %s detected in texto" % (word)) </code></pre> <p>but while that does indeed find me words, it also "finds" me things that I would have not wanted or expected (a substring of a word):</p> <p>I know that in PHP you would do something like this:</p> <pre><code>if (preg_match("/\b$search\b/", texto)): {print "word found"} </code></pre> <p>and I ve read quite a few discussions on this at SO. Some people say that you just do split, (but that is what I have done), others say use this:</p> <p>in isn't how it's done.</p> <pre><code>&gt;&gt;&gt; re.search(r'\babc\b', 'abc123') &gt;&gt;&gt; re.search(r'\babc\b', 'abc 123') &lt;_sre.SRE_Match object at 0x1146780&gt; </code></pre> <p>is this latest example the way to do it? according to the shell interpreter it would match the second row.</p>
<p>I dont't see why split() should not work. The issue is the <code>.__str__()</code> (which I don't see any need for). It creates one single string in which the keywords are searched - and then it will find substrings as well. </p> <p>The following is working for me:</p> <pre><code>texto = "hello today is the first day of working week" keywords = ["is", "day", "week", "work", "sun"] for keyword in keywords: print("keyword", keyword, end=" ") if keyword in texto.split(): print("found.") else: print("not found") </code></pre> <p><code>work</code> and <code>sun</code> should not match, <code>work</code> is a substring in the text, <code>sun</code> is not in the text.</p> <p>Output is </p> <pre><code>keyword is found. keyword day found. keyword week found. keyword work not found keyword sun not found </code></pre>
python
0
81
73,682,019
How to solve a Dataset problem in python?
<p>i have a dataset with different programming language in a column titled and i want to get the 10 most used programming language in my dataset python</p> <p>Dataset: <a href="https://drive.google.com/file/d/1nJLDFSdIbkNxcqY7NBtJZfcgLW1wpsUZ/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1nJLDFSdIbkNxcqY7NBtJZfcgLW1wpsUZ/view?usp=sharing</a></p>
<p>On StackOverflow, you should not link to outside sources, but include relevant data in your question. You should also pare down the data - if it is long, make it as short as possible and still illustrate your question.</p> <p>Finally, on StackOverflow, we don't ask bare questions like &quot;how to do x&quot;. You must first make an effort yourself to solve your problem, and then, if you don't understand why your code does not work, then you post the smallest possible example, and we will tell you where the bug is. You must show the effort first and then we help you fix it. The purpose of it is so that you learn to code yourself, and not just copy a ready solution.</p> <p>Since you did not show any effort, I will not give you a complete solution, but I will give you some start to point you in the right direction. You should first analyze my code so that you understand how it works and then you can finish it.</p> <p>When you run this code, it will print for you the relevant words. You should probably further process them, to remove irrelevant characters that people put in, and also to use proper case of letters, and then you can count the occurrences of words.</p> <pre><code>#!/usr/bin/python3 LANGUAGE_COLUMN_INDEX = 8 with open('Salary.csv') as fp: #skip over first line fp.readline() for line in fp: for word in line.split(',')[LANGUAGE_COLUMN_INDEX].split('/'): print(word.strip()) </code></pre>
python
0
82
17,505,091
Python/Django - Having trouble giving an object a foreignkey that was just created
<p>I am expanding on the basic django Poll site tutorial, and I have made a view that allows users to add their own polls. Adding a poll works, adding choices does not. Apparently this is because the poll does not "exist" yet, and the p.id cannot be used. However, the p.id works when redirecting the browser at the bottom. Anyy ideas? </p> <pre><code>def save(request): p = Poll(question=request.POST['question'], pub_date=timezone.now()) p.save() c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0) c2 = Choice(poll=p.id, choice_text=request.POST['c2'], votes=0) c3 = Choice(poll=p.id, choice_text=request.POST['c3'], votes=0) c4 = Choice(poll=p.id, choice_text=request.POST['c4'], votes=0) c1.save() c2.save() c3.save() c4.save() return HttpResponseRedirect(reverse('detail', args=(p.id,))) </code></pre>
<p>Nevermind, I figured it out. The choice doent need an id, rather, it needs the object. FIxed by changing:</p> <pre><code>c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0) </code></pre> <p>to</p> <pre><code>c1 = Choice(poll=p, choice_text=request.POST['c1'], votes=0) </code></pre>
python|django
1

Dataset Details

Dataset Description

TP4 is a comprehensive dataset containing a curated collection of questions and answers from Stack Overflow. Focused on the realms of Python programming, NumPy, Pandas, TensorFlow, and PyTorch, TP4 includes essential attributes such as question ID, title, question body, answer body, associated tags, and score. This dataset is designed to facilitate research, analysis, and exploration of inquiries and solutions within the Python and machine learning communities on Stack Overflow.

Dataset Structure

-Question ID: Unique identifiers for each question, facilitating easy referencing and linkage. -Title: Concise titles summarizing the essence of each question. -Question and Answer Bodies: Rich textual content providing detailed context and solutions. -Tags: Categorization labels such as 'python', 'numpy', 'pandas', 'tensorflow', and 'pytorch' for efficient filtering. -Score: Numerical representation of the community's evaluation of the question or answer.

Dataset Card Authors

SYED HASAN ABBAS

Downloads last month
38
Edit dataset card