title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Coloring given words in a text with Python
39,452,744
<p>I have already read the questions about how coloring text with Python and the Colorama package but I didn't find what I was looking for.</p> <p>I have some raw text:</p> <blockquote> <p>Impossible considered invitation him men instrument saw celebrated unpleasant. Put rest and must set kind next many near nay. He exquisite continued explained middleton am. Voice hours young woody has she think equal.</p> </blockquote> <p>And two lists of words:</p> <pre><code>good = ["instrument", "kind", "exquisite", "young"] bad = ["impossible", "unpleasant", "woody"] </code></pre> <p>I would like to print that text in a terminal so that words in <code>good</code> are displayed in green and words in <code>bad</code> are displayed in red.</p> <p>I know I could use colorama, check each word sequentially and make a print statement for this word but it doesn't sound like a good solution. Is there an effective way to do that?</p>
0
2016-09-12T14:28:53Z
39,453,030
<p>Here is a solution using map. It's definitely no faster than conventional looping :/ </p> <pre><code>from colorama import Fore, Style def colourise(s, good, bad): if s in good: return Fore.RED + s elif s in bad: return Fore.GREEN + s else: return Style.RESET_ALL + s text = "Impossible considered invitation him men instrument saw celebrated unpleasant. Put rest and must set kind next many near nay. He exquisite continued explained middleton am. Voice hours young woody has she think equal." good = ["instrument", "kind", "exquisite", "young"] bad = ["impossible", "unpleasant", "woody"] print(' '.join(map(lambda s: colourise(s, good, bad),text.split()))) </code></pre> <p>Or alternatively:</p> <pre><code>print(' '.join(colourise(s, good, bad) for s in text.split())) </code></pre> <p>The second version is probably better.</p>
1
2016-09-12T14:45:27Z
[ "python" ]
Cannot cast array data from dtype('O') to dtype('float64')
39,452,792
<p>I am using scipy's curve_fit to fit a function to some data, and receive the following error;</p> <pre><code>Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe' </code></pre> <p>which points me to this line in my code;</p> <pre><code>popt_r, pcov = curve_fit( self.rightFunc, np.array(wavelength)[beg:end][edgeIndex+30:], np.dstack(transmitted[:,:,c][edgeIndex+30:])[0][0], p0=[self.m_right, self.a_right]) </code></pre> <p>rightFunc is defined as follows;</p> <pre><code>def rightFunc(self, x, m, const): return np.exp(-(m*x + const)) </code></pre> <p>As I understand it, the 'O' type refers to a python object, but I can't see what is causing this error.</p> <p>Complete Error:</p> <p><a href="http://i.stack.imgur.com/2HwF3.png" rel="nofollow"><img src="http://i.stack.imgur.com/2HwF3.png" alt="Image detailing the error received"></a></p> <p>Any ideas for what I should investigate to get to the bottom of this?</p>
0
2016-09-12T14:31:40Z
39,453,034
<p>From <a href="https://github.com/numpy/numpy/issues/4384" rel="nofollow">here</a>, apparently numpy struggles with index type. The proposed solution is:</p> <blockquote> <p>One thing you can do is use np.intp as dtype whenever things have to do with indexing or are logically related to indexing/array sizes. This is the natural dtype for it and it will normally also be the fastest one.</p> </blockquote> <p>Does this help?</p>
0
2016-09-12T14:45:44Z
[ "python", "python-2.7", "scipy" ]
Cannot cast array data from dtype('O') to dtype('float64')
39,452,792
<p>I am using scipy's curve_fit to fit a function to some data, and receive the following error;</p> <pre><code>Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe' </code></pre> <p>which points me to this line in my code;</p> <pre><code>popt_r, pcov = curve_fit( self.rightFunc, np.array(wavelength)[beg:end][edgeIndex+30:], np.dstack(transmitted[:,:,c][edgeIndex+30:])[0][0], p0=[self.m_right, self.a_right]) </code></pre> <p>rightFunc is defined as follows;</p> <pre><code>def rightFunc(self, x, m, const): return np.exp(-(m*x + const)) </code></pre> <p>As I understand it, the 'O' type refers to a python object, but I can't see what is causing this error.</p> <p>Complete Error:</p> <p><a href="http://i.stack.imgur.com/2HwF3.png" rel="nofollow"><img src="http://i.stack.imgur.com/2HwF3.png" alt="Image detailing the error received"></a></p> <p>Any ideas for what I should investigate to get to the bottom of this?</p>
0
2016-09-12T14:31:40Z
39,454,698
<p>Typically these <code>scipy</code> functions require parameters like:</p> <pre><code>curvefit( function, initial_values, (aux_values,), ...) </code></pre> <p>where the tuple of <code>aux_values</code> is passed through to your <code>function</code> along with the current value of the main variable.</p> <p>Is the <code>dstack</code> expression this <code>aux_values</code>? Or a concatenation of several. It may need to be wrapped in a <code>tuple</code>.</p> <pre><code>(np.dstack(transmitted[:,:,c][edgeIndex+30:])[0][0],) </code></pre> <p>We may need to know exactly where this error arises, not just which line of your code does it. We need to know what value is being converted. Where is there an array with dtype object?</p>
1
2016-09-12T16:20:32Z
[ "python", "python-2.7", "scipy" ]
Python: Qt-Gui and several tasks
39,452,804
<p>I'm trying to use a Qt-Gui and to implement there several task to do work in the background and to update the content in the gui. Here is the code I'm working on (simplified to the minimum). Without gui, ie printing to the terminal, this code works fine:</p> <pre><code> #!/usr/bin/env python3 import sys import asyncio from PyQt4 import QtCore, QtGui, uic qtCreatorFile = "gui_mini_task.ui" # Enter file here. Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class MyApp(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) @asyncio.coroutine def task_1(futue_1): for i in range(50): window.results_window.setText("task_1") yield from asyncio.sleep(.1) @asyncio.coroutine def task_2(future_2): for i in range(1, 10): window.results_window.setText("task_2") yield from asyncio.sleep(0.5) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = MyApp() future_1 = asyncio.Future() future_2 = asyncio.Future() tasks = [ asyncio.async(task_1(future_1)), asyncio.async(task_2(future_2))] loop = asyncio.get_event_loop() window.show() loop.run_until_complete(asyncio.wait(tasks)) loop.close() sys.exit(app.exec_()) </code></pre> <p>At the end, ie after 5 seconds, the main window opens and it seems, both task has been executed meanwhile. But my intent is to see the messages in (more or less) real-time, ie the alternance of task_1 and task_2.</p> <p>Thank you for your precious help!</p> <p>The folowing is the Code of the "gui_mini_task.ui" in case you want to ...</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ui version="4.0"&gt; &lt;class&gt;MainWindow&lt;/class&gt; &lt;widget class="QMainWindow" name="MainWindow"&gt; &lt;property name="enabled"&gt; &lt;bool&gt;true&lt;/bool&gt; &lt;/property&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;800&lt;/width&gt; &lt;height&gt;600&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="windowTitle"&gt; &lt;string&gt;MainWindow&lt;/string&gt; &lt;/property&gt; &lt;widget class="QWidget" name="centralwidget"&gt; &lt;widget class="QTextEdit" name="results_window"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;40&lt;/x&gt; &lt;y&gt;410&lt;/y&gt; &lt;width&gt;731&lt;/width&gt; &lt;height&gt;71&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QLabel" name="label_3"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;170&lt;/x&gt; &lt;y&gt;20&lt;/y&gt; &lt;width&gt;161&lt;/width&gt; &lt;height&gt;41&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="font"&gt; &lt;font&gt; &lt;pointsize&gt;20&lt;/pointsize&gt; &lt;weight&gt;75&lt;/weight&gt; &lt;bold&gt;true&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;nellcor_gui&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/widget&gt; &lt;widget class="QMenuBar" name="menubar"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;800&lt;/width&gt; &lt;height&gt;27&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QStatusBar" name="statusbar"/&gt; &lt;/widget&gt; &lt;tabstops&gt; &lt;tabstop&gt;results_window&lt;/tabstop&gt; &lt;/tabstops&gt; &lt;resources/&gt; &lt;connections/&gt; &lt;/ui&gt; </code></pre>
2
2016-09-12T14:32:15Z
39,455,500
<p><code>PyQt4</code> is not aware about <code>asyncio</code> existence. But <a href="https://github.com/harvimt/quamash" rel="nofollow">quamash</a> does, please use it as bridge between Qt and asyncio.</p>
0
2016-09-12T17:16:40Z
[ "python", "qt", "pyqt", "multitasking", "python-asyncio" ]
Python: Qt-Gui and several tasks
39,452,804
<p>I'm trying to use a Qt-Gui and to implement there several task to do work in the background and to update the content in the gui. Here is the code I'm working on (simplified to the minimum). Without gui, ie printing to the terminal, this code works fine:</p> <pre><code> #!/usr/bin/env python3 import sys import asyncio from PyQt4 import QtCore, QtGui, uic qtCreatorFile = "gui_mini_task.ui" # Enter file here. Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class MyApp(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) @asyncio.coroutine def task_1(futue_1): for i in range(50): window.results_window.setText("task_1") yield from asyncio.sleep(.1) @asyncio.coroutine def task_2(future_2): for i in range(1, 10): window.results_window.setText("task_2") yield from asyncio.sleep(0.5) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = MyApp() future_1 = asyncio.Future() future_2 = asyncio.Future() tasks = [ asyncio.async(task_1(future_1)), asyncio.async(task_2(future_2))] loop = asyncio.get_event_loop() window.show() loop.run_until_complete(asyncio.wait(tasks)) loop.close() sys.exit(app.exec_()) </code></pre> <p>At the end, ie after 5 seconds, the main window opens and it seems, both task has been executed meanwhile. But my intent is to see the messages in (more or less) real-time, ie the alternance of task_1 and task_2.</p> <p>Thank you for your precious help!</p> <p>The folowing is the Code of the "gui_mini_task.ui" in case you want to ...</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ui version="4.0"&gt; &lt;class&gt;MainWindow&lt;/class&gt; &lt;widget class="QMainWindow" name="MainWindow"&gt; &lt;property name="enabled"&gt; &lt;bool&gt;true&lt;/bool&gt; &lt;/property&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;800&lt;/width&gt; &lt;height&gt;600&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="windowTitle"&gt; &lt;string&gt;MainWindow&lt;/string&gt; &lt;/property&gt; &lt;widget class="QWidget" name="centralwidget"&gt; &lt;widget class="QTextEdit" name="results_window"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;40&lt;/x&gt; &lt;y&gt;410&lt;/y&gt; &lt;width&gt;731&lt;/width&gt; &lt;height&gt;71&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QLabel" name="label_3"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;170&lt;/x&gt; &lt;y&gt;20&lt;/y&gt; &lt;width&gt;161&lt;/width&gt; &lt;height&gt;41&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="font"&gt; &lt;font&gt; &lt;pointsize&gt;20&lt;/pointsize&gt; &lt;weight&gt;75&lt;/weight&gt; &lt;bold&gt;true&lt;/bold&gt; &lt;/font&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;nellcor_gui&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/widget&gt; &lt;widget class="QMenuBar" name="menubar"&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;800&lt;/width&gt; &lt;height&gt;27&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class="QStatusBar" name="statusbar"/&gt; &lt;/widget&gt; &lt;tabstops&gt; &lt;tabstop&gt;results_window&lt;/tabstop&gt; &lt;/tabstops&gt; &lt;resources/&gt; &lt;connections/&gt; &lt;/ui&gt; </code></pre>
2
2016-09-12T14:32:15Z
39,464,406
<p>Using quamash like proposed by Andrew Svetlov, the working code looks now like this:</p> <pre><code>#!/usr/bin/env python3 import sys import asyncio from PyQt4 import QtCore, QtGui, uic from quamash import QEventLoop qtCreatorFile = "gui_mini_task.ui" # Enter file here. Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class MyApp(QtGui.QMainWindow, Ui_MainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) @asyncio.coroutine def task_1(futue_1): for i in range(50): window.results_window.setText("task_1") yield from asyncio.sleep(.1) @asyncio.coroutine def task_2(future_2): for i in range(1, 12): window.results_window.setText("task_2") yield from asyncio.sleep(0.5) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = MyApp() loop = QEventLoop(app) asyncio.set_event_loop(loop) future_1 = asyncio.Future() future_2 = asyncio.Future() tasks = [ asyncio.async(task_1(future_1)), asyncio.async(task_2(future_2))] window.show() # erst jetzt werden die Widgets instanziert! loop.run_until_complete(asyncio.wait(tasks)) loop.close() sys.exit(app.exec_()) </code></pre> <p>Thank you!</p>
2
2016-09-13T07:27:43Z
[ "python", "qt", "pyqt", "multitasking", "python-asyncio" ]
Text Pre-processing with NLTK
39,452,842
<p>I am practicing on using NLTK to remove certain features from raw tweets and subsequently hoping to remove tweets that are (to me) irelevant (e.g. empty tweet or single word tweets). However, it seems that some of the single word tweets are not removed. I am also facing an issue with not able to remove any stopword that are either at the beginning or end of sentence.</p> <p>Any advice? At the moment, I hope to pass back a sentence as an output rather than a list of tokenized words.</p> <p>Any other comment on improving the code (processing time, elegance) are welcome.</p> <pre><code>import string import numpy as np import nltk from nltk.corpus import stopwords cache_english_stopwords=stopwords.words('english') cache_en_tweet_stopwords=stopwords.words('english_tweet') # For clarity, df is a pandas dataframe with a column['text'] together with other headers. def tweet_clean(df): temp_df = df.copy() # Remove hyperlinks temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('https?:\/\/.*\/\w*', '', regex=True) # Remove hashtags # temp_df.loc[:,"text"]=temp_df.loc[:,"text"].replace('#\w*', '', regex=True) temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('#', ' ', regex=True) # Remove citations temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\@\w*', '', regex=True) # Remove tickers temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\$\w*', '', regex=True) # Remove punctuation temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[' + string.punctuation + ']+', '', regex=True) # Remove stopwords for tweet in temp_df.loc[:,"text"]: tweet_tokenized=nltk.word_tokenize(tweet) for w in tweet_tokenized: if (w.lower() in cache_english_stopwords) | (w.lower() in cache_en_tweet_stopwords): temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[\W*\s?\n?]'+w+'[\W*\s?]', ' ', regex=True) #print("w in stopword") # Remove quotes temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\&amp;*[amp]*\;|gt+', '', regex=True) # Remove RT temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\s+rt\s+', '', regex=True) # Remove linebreak, tab, return temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[\n\t\r]+', ' ', regex=True) # Remove via with blank temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('via+\s', '', regex=True) # Remove multiple whitespace temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\s+\s+', ' ', regex=True) # Remove single word sentence for tweet_sw in temp_df.loc[:, "text"]: tweet_sw_tokenized = nltk.word_tokenize(tweet_sw) if len(tweet_sw_tokenized) &lt;= 1: temp_df.loc["text"] = np.nan # Remove empty rows temp_df.loc[(temp_df["text"] == '') | (temp_df['text'] == ' ')] = np.nan temp_df = temp_df.dropna() return temp_df </code></pre>
0
2016-09-12T14:35:10Z
39,454,322
<p>What is df? a list of tweets? You maybe should consider cleaning the tweet one after the other and not as a list of tweets. It would be easier to have a function <code>tweet_cleaner(single_tweet)</code>.</p> <p>nltk provides a <a href="http://www.nltk.org/api/nltk.tokenize.html" rel="nofollow">TweetTokenizer</a> to clean the tweets.</p> <p>the <a href="https://docs.python.org/3.5/library/re.html" rel="nofollow">"re" package</a> provides good solutions to use regex.</p> <p>I advice you to create a variable for an easier use of <code>temp_df.loc[:, "text"]</code></p> <p>Deleting stopwords in a sentence is described [here] (<a href="http://stackoverflow.com/questions/19130512/stopword-removal-with-nltk#19133088">Stopword removal with NLTK</a>): <code>clean_wordlist = [i for i in sentence.lower().split() if i not in stopwords]</code></p> <p>If you want to use regex (with the re package), you can</p> <ol> <li><p>create a regex pattern composed of all the stopwords (out of the tweet_clean function): <code>stop_pattern = re.compile('|'.join(stoplist)(?siu))</code><br> (?siu) for multiline, ignorecase, unicode</p></li> <li><p>and use this pattern to clean any string <code>clean_string = stop_pattern.sub('', input_string)</code></p></li> </ol> <p>(you can concatenate the 2 stoplists if having separate ones is not needed)</p> <p>To remove 1 words tweet you could only keep the one longest than 1 word:<br> <code>if len(tweet_sw_tokenized) &gt;= 1: kept_ones.append(tweet_sw)</code></p>
2
2016-09-12T15:54:44Z
[ "python", "twitter", "nltk" ]
Text Pre-processing with NLTK
39,452,842
<p>I am practicing on using NLTK to remove certain features from raw tweets and subsequently hoping to remove tweets that are (to me) irelevant (e.g. empty tweet or single word tweets). However, it seems that some of the single word tweets are not removed. I am also facing an issue with not able to remove any stopword that are either at the beginning or end of sentence.</p> <p>Any advice? At the moment, I hope to pass back a sentence as an output rather than a list of tokenized words.</p> <p>Any other comment on improving the code (processing time, elegance) are welcome.</p> <pre><code>import string import numpy as np import nltk from nltk.corpus import stopwords cache_english_stopwords=stopwords.words('english') cache_en_tweet_stopwords=stopwords.words('english_tweet') # For clarity, df is a pandas dataframe with a column['text'] together with other headers. def tweet_clean(df): temp_df = df.copy() # Remove hyperlinks temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('https?:\/\/.*\/\w*', '', regex=True) # Remove hashtags # temp_df.loc[:,"text"]=temp_df.loc[:,"text"].replace('#\w*', '', regex=True) temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('#', ' ', regex=True) # Remove citations temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\@\w*', '', regex=True) # Remove tickers temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\$\w*', '', regex=True) # Remove punctuation temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[' + string.punctuation + ']+', '', regex=True) # Remove stopwords for tweet in temp_df.loc[:,"text"]: tweet_tokenized=nltk.word_tokenize(tweet) for w in tweet_tokenized: if (w.lower() in cache_english_stopwords) | (w.lower() in cache_en_tweet_stopwords): temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[\W*\s?\n?]'+w+'[\W*\s?]', ' ', regex=True) #print("w in stopword") # Remove quotes temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\&amp;*[amp]*\;|gt+', '', regex=True) # Remove RT temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\s+rt\s+', '', regex=True) # Remove linebreak, tab, return temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('[\n\t\r]+', ' ', regex=True) # Remove via with blank temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('via+\s', '', regex=True) # Remove multiple whitespace temp_df.loc[:, "text"] = temp_df.loc[:, "text"].replace('\s+\s+', ' ', regex=True) # Remove single word sentence for tweet_sw in temp_df.loc[:, "text"]: tweet_sw_tokenized = nltk.word_tokenize(tweet_sw) if len(tweet_sw_tokenized) &lt;= 1: temp_df.loc["text"] = np.nan # Remove empty rows temp_df.loc[(temp_df["text"] == '') | (temp_df['text'] == ' ')] = np.nan temp_df = temp_df.dropna() return temp_df </code></pre>
0
2016-09-12T14:35:10Z
39,457,094
<p>With advice from mquantin, I have modified my code to clean tweets individually as a sentence. Here is my amateur attempt with a sample tweet that I believe covers most scenarios (Let me know if you encounter any other cases that deserve a clean up):</p> <pre><code>import string import re from nltk.corpus import stopwords from nltk.tokenize import TweetTokenizer cache_english_stopwords=stopwords.words('english') def tweet_clean(tweet): # Remove tickers sent_no_tickers=re.sub(r'\$\w*','',tweet) print('No tickers:') print(sent_no_tickers) tw_tknzr=TweetTokenizer(strip_handles=True, reduce_len=True) temp_tw_list = tw_tknzr.tokenize(sent_no_tickers) print('Temp_list:') print(temp_tw_list) # Remove stopwords list_no_stopwords=[i for i in temp_tw_list if i.lower() not in cache_english_stopwords] print('No Stopwords:') print(list_no_stopwords) # Remove hyperlinks list_no_hyperlinks=[re.sub(r'https?:\/\/.*\/\w*','',i) for i in list_no_stopwords] print('No hyperlinks:') print(list_no_hyperlinks) # Remove hashtags list_no_hashtags=[re.sub(r'#', '', i) for i in list_no_hyperlinks] print('No hashtags:') print(list_no_hashtags) # Remove Punctuation and split 's, 't, 've with a space for filter list_no_punctuation=[re.sub(r'['+string.punctuation+']+', ' ', i) for i in list_no_hashtags] print('No punctuation:') print(list_no_punctuation) # Remove multiple whitespace new_sent = ' '.join(list_no_punctuation) # Remove any words with 2 or fewer letters filtered_list = tw_tknzr.tokenize(new_sent) list_filtered = [re.sub(r'^\w\w?$', '', i) for i in filtered_list] print('Clean list of words:') print(list_filtered) filtered_sent =' '.join(list_filtered) clean_sent=re.sub(r'\s\s+', ' ', filtered_sent) #Remove any whitespace at the front of the sentence clean_sent=clean_sent.lstrip(' ') print('Clean sentence:') print(clean_sent) s0=' RT @Amila #Test\nTom\'s newly listed Co. &amp;amp; Mary\'s unlisted Group to supply tech for nlTK.\nh.. $TSLA $AAPL https:// t.co/x34afsfQsh' tweet_clean(s0) </code></pre>
0
2016-09-12T19:06:41Z
[ "python", "twitter", "nltk" ]
"In" operator for numpy arrays?
39,452,843
<p>How can I do the "in" operation on a numpy array? (Return True if an element is present in the given numpy array)</p> <p>For strings, lists and dictionaries, the functionality is intuitive to understand.</p> <p>Here's what I got when I applied that on a numpy array</p> <pre><code>a array([[[2, 3, 0], [1, 0, 1]], [[3, 2, 0], [0, 1, 1]], [[2, 2, 0], [1, 1, 1]], [[1, 3, 0], [2, 0, 1]], [[3, 1, 0], [0, 2, 1]]]) b = [[3, 2, 0], [0, 1, 1]] b in a True #Aligned with the expectation c = [[300, 200, 0], [0, 100, 100]] c in a True #Not quite what I expected </code></pre>
2
2016-09-12T14:35:12Z
39,452,929
<p>You could compare the input arrays for <code>equality</code>, which will perform <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasted</code></a> comparisons across all elements in <code>a</code> at each position in the last two axes against elements at corresponding positions in the second array. This will result in a boolean array of matches, in which we check for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html" rel="nofollow"><code>ALL</code></a> matches across the last two axes and finally check for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.any.html" rel="nofollow"><code>ANY</code></a> match, like so -</p> <pre><code>((a==b).all(axis=(1,2))).any() </code></pre> <p><strong>Sample run</strong></p> <p>1) Inputs :</p> <pre><code>In [68]: a Out[68]: array([[[2, 3, 0], [1, 0, 1]], [[3, 2, 0], [0, 1, 1]], [[2, 2, 0], [1, 1, 1]], [[1, 3, 0], [2, 0, 1]], [[3, 1, 0], [0, 2, 1]]]) In [69]: b Out[69]: array([[3, 2, 0], [0, 1, 1]]) </code></pre> <p>2) Broadcasted elementwise comparisons :</p> <pre><code>In [70]: a==b Out[70]: array([[[False, False, True], [False, False, True]], [[ True, True, True], [ True, True, True]], [[False, True, True], [False, True, True]], [[False, False, True], [False, False, True]], [[ True, False, True], [ True, False, True]]], dtype=bool) </code></pre> <p>3) <code>ALL</code> match across last two axes and finally <code>ANY</code> match :</p> <pre><code>In [71]: (a==b).all(axis=(1,2)) Out[71]: array([False, True, False, False, False], dtype=bool) In [72]: ((a==b).all(axis=(1,2))).any() Out[72]: True </code></pre> <p>Following similar steps for <code>c</code> in <code>a</code> -</p> <pre><code>In [73]: c Out[73]: array([[300, 200, 0], [ 0, 100, 100]]) In [74]: ((a==c).all(axis=(1,2))).any() Out[74]: False </code></pre>
4
2016-09-12T14:40:01Z
[ "python", "arrays", "numpy", "operators" ]
Enforce precision in decimal python
39,452,845
<p>In some environments, exact decimals (numerics, numbers...) are defined with <code>scale</code> and <code>precision</code>, with scale being all significant numbers, and precision being those right of the decimal point. I want to use python's decimal implementation to raise an error, if the precision of the casted string is higher than the one defined by the implementation.</p> <p>So for example, I have an environment, where <code>scale = 4</code> and <code>precision = 2</code>. How can I achieve these commands to raise an error, because their precision exceeds that of the implementation?</p> <pre><code>decimals.Decimal('1234.1') decimals.Decimal('0.123') </code></pre>
1
2016-09-12T14:35:13Z
39,453,334
<p>The closest I could find in the <code>decimal</code> <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow">module</a> is in the <code>context.create_decimal_from_float</code> example, using the <code>Inexact</code> <a href="https://docs.python.org/2/library/decimal.html#decimal.Inexact" rel="nofollow">context trap</a> :</p> <pre><code>&gt;&gt;&gt; context = Context(prec=5, rounding=ROUND_DOWN) &gt;&gt;&gt; context.create_decimal_from_float(math.pi) Decimal('3.1415') &gt;&gt;&gt; context = Context(prec=5, traps=[Inexact]) &gt;&gt;&gt; context.create_decimal_from_float(math.pi) Traceback (most recent call last): ... Inexact: None </code></pre> <p>The decimal module doesn't seem to have the concept of scale. It's precision is basically your scale + your precision. </p>
2
2016-09-12T15:01:17Z
[ "python", "decimal", "precision" ]
Enforce precision in decimal python
39,452,845
<p>In some environments, exact decimals (numerics, numbers...) are defined with <code>scale</code> and <code>precision</code>, with scale being all significant numbers, and precision being those right of the decimal point. I want to use python's decimal implementation to raise an error, if the precision of the casted string is higher than the one defined by the implementation.</p> <p>So for example, I have an environment, where <code>scale = 4</code> and <code>precision = 2</code>. How can I achieve these commands to raise an error, because their precision exceeds that of the implementation?</p> <pre><code>decimals.Decimal('1234.1') decimals.Decimal('0.123') </code></pre>
1
2016-09-12T14:35:13Z
39,453,389
<p>You could always define a stricter class of Decimal and check the number of decimals in the setter and constructor functions. This should act exactly like the Decimal object, except that it'll raise a ValueError when its created or set with more than two decimals.</p> <pre><code>class StrictDecimal: def __init__(self, x): x = Decimal(x) if format(x, '.2f') != str(x): raise ValueError('Precision must by limited to 2 digits') self._x = x @property def x(self): return self._x @x.setter def x(self, x): x = Decimal(x) if format(x, '.2f') != str(x): raise ValueError('Precision must by limited to 2 digits') self._x = x </code></pre>
0
2016-09-12T15:03:37Z
[ "python", "decimal", "precision" ]
Print Node Id from Igraph in Python
39,452,862
<p>I have text file with the following sample data representing nodes and edges. </p> <pre><code>a b b c d a b d </code></pre> <p>I want to print the node ID in python but I realize that there is no way to achieve this,for example in R once I generate my graph, I get the node attribute name printed along with the pagerank score. In the case of python, I am trying to generate the pagerank score which I achieve with python code:</p> <pre><code>Fin = Graph.Read_Ncol('test.txt',directed = True) #print(Fin) PRankH = Graph.pagerank( Fin, directed =True,damping = 0.85) print(PRankH) print(PRankH.index) for item in PRankH: print(PRankH.index(item),PRankH[item]) </code></pre> <p>The output printed is just the pagerank scores for example the Node id and the scores:</p> <pre><code>0.0001, 000.2, 0.0003 </code></pre> <p>How ever I would want to print for example</p> <pre><code>A 0.0001 , B 0.0002 , C 0.0003 </code></pre> <p>Is there any way I can achieve this from the python I graph library?</p>
0
2016-09-12T14:36:04Z
39,459,137
<p>If anyone is interested, I ended solving my own problem. The values generated by the graph in python are linked by the vertex id. You will need to access the vertex name attribute for your graph and linked that with eh scores produced from the page rank output. </p> <pre><code>Fin = Graph.Read_Ncol('Node_edge.txt',directed = True) PRankH = Graph.pagerank( Fin, directed =True,damping = 0.85) x = 0 for item in PRankH: print([Fin.vs[x]['name'],PRankH[x]])) x+=1 myfile.close() </code></pre> <p>This is an example of how I solved the the issue. </p>
0
2016-09-12T21:34:14Z
[ "python", "igraph" ]
Breaking out of one for loop and continuing the other code
39,452,881
<p>I currently have an excel sheet checking another excel sheet for certain numbers. Once it finds the matching cell, I want it to move on back to the very first for loop. if it doesn't find the matching cell, but finds the first 6 digits of it, I want it to mark it as checked and then move back to the first for loop again. </p> <p>How is this done? </p> <p>Below is my code. I commented where I wanted it to go back to the first <code>for</code> loop I made.</p> <pre><code>for row in range(sheet.nrows): cell = str(sheet.cell_value(row, 0)) if fd.match(cell): for rows in range(sheet.nrows): windcell = str(windc_sheet.cell_value(rows, 0)) if fd.match(windcell): if cell == windcell: outputsheet.write(row, 1, ' ') #GO BACK TO FIRST FOR LOOP else: sixdig = cell[0:6] sixdigwind = windcell[0:6] if sixdig == sixdigwind: outputsheet.write(row, 1, 'Check') #GO BACK TO FIRST FOR LOOP else: sixdig = cell[0:6] for rows in range(sheet.nrows): windcell = str(windc_sheet.cell_value(rows,0)) sixdigwind = windcell[0:6] if sixdig == sixdigwind: outputsheet.write(row, 1, 'Check') </code></pre>
-2
2016-09-12T14:37:17Z
39,452,915
<p>Just use the <code>break</code> statement. It breaks you out of a <code>for</code> loop or <code>while</code> loop. </p> <p>From the Python docs:</p> <blockquote> <p>break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. <strong>It terminates the nearest enclosing loop</strong>, skipping the optional else clause if the loop has one. If a for loop is terminated by break, the loop control target keeps its current value. When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.</p> </blockquote> <p>(Emphasis mine)</p> <pre><code>for row in range(sheet.nrows): cell = str(sheet.cell_value(row, 0)) if fd.match(cell): for rows in range(sheet.nrows): windcell = str(windc_sheet.cell_value(rows, 0)) if fd.match(windcell): if cell == windcell: outputsheet.write(row, 1, ' ') break # TERMINATE ENCLOSING FOR LOOP else: sixdig = cell[0:6] sixdigwind = windcell[0:6] if sixdig == sixdigwind: outputsheet.write(row, 1, 'Check') break # TERMINATE ENCLOSING FOR LOOP else: sixdig = cell[0:6] for rows in range(sheet.nrows): windcell = str(windc_sheet.cell_value(rows,0)) sixdigwind = windcell[0:6] if sixdig == sixdigwind: outputsheet.write(row, 1, 'Check') </code></pre>
1
2016-09-12T14:39:26Z
[ "python", "for-loop", "break" ]
How to expose a templated class as one class to python with boost::python
39,453,015
<p>In many examples about boost::python you see something like:</p> <pre><code>using namespace boost::python; typedef class_&lt;std::vector&lt;float&gt;&gt; VectorFloat; </code></pre> <p>And then of course if you need a <code>double</code> vector you will have a second class called <code>DoubleVector</code> or so. In my opinion this is not very "pythonic". It would be more intuitive (I think), if one (templated) class in C++ is actually one class in python which takes an argument like <code>, ..., type='float', ... ,</code>. This way the class also appears only once in the pydocs and has to be added only once to the <code>boost::python module</code>.</p> <p>So let's say we have a simple templated class for our C++ code:</p> <pre><code>template &lt;typename T&gt; MyClass { T val; public: MyClass(const T&amp; tVal) : val(tVal) {} T getVal() { return val; } void setVal(const T&amp; tVal) { val = tVal; } }; </code></pre> <p>Now we want to write an interface for Python. My idea so far:</p> <p><strong>Using boost::variant</strong></p> <pre><code>typedef boost::variant&lt;MyClass&lt;float&gt;, MyClass&lt;double&gt;&gt; VariantClass; class MyPythonClass { VariantClass vClass; public: MyPythonClass( const PyObject&amp; tVal, const boost::python::str&amp; type) { using namespace boost::python; std::string type_string = extract&lt;std::string&gt;(type); if( type_string == "float" ) { float f = extract&lt;float&gt;(tVal); vClass = MyClass(f); } else if( type_string == "double" ) { double d = extract&lt;double&gt;(tVal); vClass = MyClass(d); } } boost::python::PyObject* getVal() { // What to put here? } void setVal(const boost::python::PyObject&amp; tVal) { //What to put here? } }; BOOST_PYTHON_MODULE(my_module) { class_&lt;MyPythonClass&gt;("MyClass", init&lt;boost::python::PyObject, int, boost::python::str&gt;).def("getVal", &amp;MyClass::getVal()); } </code></pre> <p>A clear drawback of this solution is I guess that boost::variant can work with types that are quite different wheras my classes are almost identitcal, except for the type of data they store. So probably more information is abstracted away than necessary.</p> <p>So the question I guess boils down to the two empty functions in the example. However, cleaner and shorter or less "if"-chain like answers will of course also be accepted. As the title says, it is about templated classes and boost::python and not necessarily about boost::variant.</p>
0
2016-09-12T14:44:41Z
39,453,655
<p>There's a couple sources of confusion here. First, in Python, <code>object</code> is already basically a variant - everything is an <code>object</code>. And in C++, a class template isn't a type - it's a recipe for creating a type. So if you want to expose <code>MyClass&lt;T&gt;</code> from C++ to Python, you should just expose all the <code>MyClass&lt;T&gt;s</code></p> <p>I would write a function template that does the bindings:</p> <pre><code>template &lt;class T&gt; void bind_MyClass(const char* name) { class_&lt;MyClass&lt;T&gt;&gt;(name, init&lt;T const&amp;&gt;()) .add_property("val", &amp;MyClass&lt;T&gt;::getVal, &amp;MyClass&lt;T&gt;::setVal); ; } </code></pre> <p>And then just call it:</p> <pre><code>bind_MyClass&lt;float&gt;("MyClassFloat"); bind_MyClass&lt;double&gt;("MyClassDouble"); </code></pre>
1
2016-09-12T15:17:45Z
[ "python", "c++", "templates", "boost", "boost-python" ]
Label for input field isn't rendered when ends with non ASCII character
39,453,137
<p>I encountered a strange behavior while using Django forms. In my <code>forms.py</code> I have a user register form, and for each field I have set a label. Then in view I am passing the form into the context. In html file I'm using the form as follows:</p> <pre><code>{% for field in UserForm %} &lt;div class="form-group"&gt; {{field.label_tag}} {{field}} &lt;/div&gt; {% endfor %} </code></pre> <p>my form looks like this:</p> <pre><code>class UserForm(UserCreationForm): first_name = forms.CharField( label = 'Imię', max_length=255, widget=forms.TextInput( attrs={ 'class': 'form-control', 'name': 'Name', 'placeholder': 'Imię', 'required' : '', } ) ) last_name = forms.CharField( label = 'Nazwisko', max_length=255, widget=forms.TextInput( attrs={ 'class': 'form-control', 'name': 'Surname', 'placeholder': 'Nazwisko', 'required' : '', } ) ) </code></pre> <p>The problem is that for one field a label is not shown, the <code>&lt;label&gt;</code> tag is not even generated in output html file.</p> <p>The problematic label is: <code>label = 'Imię',</code>. I noticed that when a label ends with non ASCII character, the label is not generated. I tested that for other field labels.</p> <p>I have included <code># -*- coding: utf-8 -*-</code> at the beginning of the <code>forms.py</code> (otherwise python throws an error about non ASCII characters in file), so that's not the source of this problem. Also I checked in Notepad++ that this file really uses UTF-8 encoding.</p> <p>I'm using Django 1.9 and python version is 2.7.6.</p> <p>Any help is appreciated.</p>
0
2016-09-12T14:50:39Z
39,454,257
<p>Python 2.7 have 2 types of string, normal and unicode. Normal string (used by default) can't store any unicode characters. In your form you are using normal strings for label. That is causing issues.</p> <p>You can either use unicode in that string:</p> <pre><code> first_name = forms.CharField( label = u'Imię', max_length=255, widget=forms.TextInput( attrs={ 'class': 'form-control', 'name': 'Name', 'placeholder': u'Imię', 'required' : '', } ) ) </code></pre> <p>Or set all strings in this file to be treated as unicode by default, by adding:</p> <pre><code>from __future__ import unicode_literals </code></pre> <p>At the very top of the file (right after setting encoding for file).</p> <p>In python 3 that was changed, so by default all strings are treated as unicode.</p>
0
2016-09-12T15:51:40Z
[ "python", "html", "django" ]
Skimage: group labels with distance condition on outline
39,453,168
<p>I have used <em>skimage.measure.label</em> to get labels of my image but i was wondering if there was a function or a best way to group the labels with a distance condition on their outline.</p> <p>Currently i use <em>skimage.measure.regionprops</em> to analyse each label then <em>skimage.segmentation.find_boundaries</em> to get the outline of each label then i get the coordinates, i check the distance between each points, i update the label if the distance match the condition and then i reuse <em>regionprops</em> to get right labels after grouping (i will post my code soon).</p> <p>Currently work with this code:</p> <pre><code>import math import matplotlib.pyplot as plt import numpy as np from skimage.draw import ellipse from skimage.measure import label, regionprops from skimage.transform import rotate image = np.zeros((600, 600)) rr, cc = ellipse(300, 350, 100, 220) rr2, cc2 = ellipse(100, 100, 20, 50) image[rr, cc] = 1 image[rr2, cc2] = 1 image = rotate(image, angle=15, order=0) label_img = label(image) regions = regionprops(label_img) fig, ax = plt.subplots() ax.imshow(image, cmap=plt.cm.gray) for props in regions: y0, x0 = props.centroid orientation = props.orientation x1 = x0 + math.cos(orientation) * 0.5 * props.major_axis_length y1 = y0 - math.sin(orientation) * 0.5 * props.major_axis_length x2 = x0 - math.sin(orientation) * 0.5 * props.minor_axis_length y2 = y0 - math.cos(orientation) * 0.5 * props.minor_axis_length ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5) ax.plot((x0, x2), (y0, y2), '-r', linewidth=2.5) ax.plot(x0, y0, '.g', markersize=15) minr, minc, maxr, maxc = props.bbox bx = (minc, maxc, maxc, minc, minc) by = (minr, minr, maxr, maxr, minr) ax.plot(bx, by, '-b', linewidth=2.5) ax.axis((0, 600, 600, 0)) plt.show() </code></pre>
0
2016-09-12T14:52:37Z
39,454,882
<p>This code work for grouping and display the result (blue is before, cyan is after):</p> <p><a href="http://i.stack.imgur.com/j32Bp.png" rel="nofollow"><img src="http://i.stack.imgur.com/j32Bp.png" alt="label grouping"></a></p> <pre><code>import math import matplotlib.pyplot as plt import numpy as np from skimage.draw import ellipse from skimage.measure import label, regionprops from skimage.transform import rotate from skimage.segmentation import find_boundaries image = np.zeros((600, 600)) rr, cc = ellipse(300, 350, 100, 220) rr2, cc2 = ellipse(100, 100, 20, 50) rr3, cc3 = ellipse(200, 50, 20, 50) image[rr, cc] = 1 image[rr2, cc2] = 1 image[rr3, cc3] = 1 image = rotate(image, angle=15, order=0) pixel_distance = 100 # Labeling image label_img = label(image) # Applying regionprops regions = regionprops(label_img) # First draw before regroup with blue rectangles fig, ax = plt.subplots() ax.imshow(image, interpolation="none") for props in regions: y0, x0 = props.centroid orientation = props.orientation x1 = x0 + math.cos(orientation) * 0.5 * props.major_axis_length y1 = y0 - math.sin(orientation) * 0.5 * props.major_axis_length x2 = x0 - math.sin(orientation) * 0.5 * props.minor_axis_length y2 = y0 - math.cos(orientation) * 0.5 * props.minor_axis_length ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5) ax.plot((x0, x2), (y0, y2), '-r', linewidth=2.5) ax.plot(x0, y0, '.g', markersize=15) minr, minc, maxr, maxc = props.bbox bx = (minc, maxc, maxc, minc, minc) by = (minr, minr, maxr, maxr, minr) ax.plot(bx, by, '-b', linewidth=2.5) # Check distances for each label for props in regions: # Get boundaries coordinates for that label label_boundaries = find_boundaries(label_img == props.label) bound_cord = np.column_stack(np.where(label_boundaries)) # DEBUG: Draw boundaries # for cord in bound_cord: # ax.plot(cord[1], cord[0], '.b', markersize=5) # We will compare each boundaries coordinates with the coordinates of all other label boundaries for j_props in regions: if j_props.label &gt; props.label: regrouped = False print "LABEL :", props.label, "VS :", j_props.label # Get boundaries coordinates for that label j_label_boundaries = find_boundaries(label_img == j_props.label) j_bound_cord = np.column_stack(np.where(j_label_boundaries)) # Coordinates comparisons i = 0 while not regrouped and i &lt; len(bound_cord): j = 0 while not regrouped and j &lt; len(j_bound_cord): # Apply distance condition if math.hypot(j_bound_cord[j][1] - bound_cord[i][1], j_bound_cord[j][0] - bound_cord[i][0]) &lt;= pixel_distance: # Assign the less label value label_img[label_img == j_props.label] = min(props.label, j_props.label) j_props.label = min(props.label, j_props.label) regrouped = True j += 1 i += 1 # Second time we use regionprobs to get new labels informations regions_2 = regionprops(label_img) # Redraw after grouping with cyan rectangles for props in regions_2: y0, x0 = props.centroid orientation = props.orientation x1 = x0 + math.cos(orientation) * 0.5 * props.major_axis_length y1 = y0 - math.sin(orientation) * 0.5 * props.major_axis_length x2 = x0 - math.sin(orientation) * 0.5 * props.minor_axis_length y2 = y0 - math.cos(orientation) * 0.5 * props.minor_axis_length ax.plot((x0, x1), (y0, y1), '-y', linewidth=2.5) ax.plot((x0, x2), (y0, y2), '-y', linewidth=2.5) ax.plot(x0, y0, '.c', markersize=15) minr, minc, maxr, maxc = props.bbox bx = (minc, maxc, maxc, minc, minc) by = (minr, minr, maxr, maxr, minr) ax.plot(bx, by, '-c', linewidth=2.5) ax.axis((0, 600, 600, 0)) plt.show() </code></pre>
0
2016-09-12T16:32:16Z
[ "python", "image-processing", "scikit-image", "skimage" ]
Unrecognized file type in selenium python
39,453,184
<p>So I am testing a web client which communicates with an engine that does something to a text file that I upload. So basically, I choose a file to upload, once this file is uploaded i can press start and the engine does its thing and returns a result. I am trying to test the front end using selenium in python. This web client accepts zip or txt files. The developer of this web client made it such that when a file type other than a zip or text is uploaded it will give an error like so</p> <pre><code>File type "audio/wav" is not supported: Must be one of "text/plain", "application/zip", "application/zip-compressed", "application/x-zip-compressed". </code></pre> <p>In this case, I tried to upload a wav audio file. When I try to manually upload a zip file, it works as expected. However, when I try this same process using the same file in selenium, it no longer recognize the file type and gives me this error</p> <pre><code>File type "" is not supported: Must be one of "text/plain", "application/zip", "application/zip-compressed", "application/x-zip-compressed". </code></pre> <p>So the file type is unrecognized. Here is what I am using to upload the file:</p> <pre><code>choose = self.driver.find_element_by_id("chooseButton") time.sleep(1) #clicks to open upload window choose.click() time.sleep(1) #ZIp file with other zips pyautogui.typewrite("C:\\Transcriber\\Framework\\test\\audio\\Nested.zip") time.sleep(1) pyautogui.press('enter') </code></pre> <p>I am using pyautogui to manipulate the upload window that pops up when I click the upload button, so it's as though I am automating my keyboard. The time.sleep is just to ensure that enough time is provided between actions such that an action ends before the next one starts.</p> <p>My zip is just an ordinary zip file. When I run it in selenium it gave me the above error. Does anyone know what the problem could be? Is this a python issue? Thanks in advance.</p> <p>Edit: This issue only occurs when I try to upload a zip file, if I replace the zip file in my test case with a txt file, then it works fine.</p> <p>Edit2: After my test case finishes, if I leave the browser opened, the error would still occur even I I try to upload manually. So this seems to happen only in the browser instance spawned by selenium. Otherwise, if I open a fresh browser on my own, uploading a zip works fine.</p>
1
2016-09-12T14:53:11Z
39,467,073
<p>Python + selenium also gives you the option of uploading the file directly.</p> <p>I am not sure whether this is true in your case, because I don't have the complete html for the "choose" element.</p> <p>In my case I had an element of input[type=file] and this worked:</p> <p>driver.find_element_by_css_selector('input[type="file"]').send_keys(path+filename) </p> <p>Maybe you have to click an ok/submit button after that, depending on your situation. </p> <p>Hope this helps!</p> <p>More info about this for instance here: <a href="http://stackoverflow.com/questions/8665072/how-to-upload-file-picture-with-selenium-python">How to upload file ( picture ) with selenium, python</a></p>
0
2016-09-13T09:52:13Z
[ "python", "unit-testing", "selenium", "file-upload" ]
Can I run pdflatex on an in-memory file?
39,453,227
<p>I am to generate a series of pdf files whose contents is to be generated in Python (2.7). A regular solution is to save the .tex contents at some directory, call pdflatex on the file, read in the pdf-file afterwards in order to finally place the file somewhere relevant. This is shown below:</p> <pre><code>import os texFile = \ """\\documentclass[11pt,a4paper,final]{article} \\begin{document} Hello, world! \\end{document} """ # Clearly will a more awesome file be generated here! with open('hello.tex', 'w') as f: f.write(texFile) os.system('pdflatex hello.tex') pdfFile = open('hello.pdf', 'rb').read() # Now place the file somewhere relevant ... </code></pre> <p>I desire the same procedures but comitted on an in-memory basis, for increasing speed and avoiding file leakage into some folder. So my question is, how to run pdflatex on an in-memory basis and extracting the resulting pdf back into Python?</p>
1
2016-09-12T14:55:24Z
39,453,345
<p>Have a look at <a href="https://pypi.python.org/pypi/tex" rel="nofollow">tex</a>. It provides an in-memory API to the TeX command line tools. For example:</p> <pre><code>&gt;&gt;&gt; from tex import latex2pdf &gt;&gt;&gt; document = ur""" ... \documentclass{article} ... \begin{document} ... Hello, World! ... \end{document} ... """ &gt;&gt;&gt; pdf = latex2pdf(document) &gt;&gt;&gt; type(pdf) &lt;type 'str'&gt; &gt;&gt;&gt; print "PDF size: %.1f KB" % (len(pdf) / 1024.0) PDF size: 5.6 KB &gt;&gt;&gt; pdf[:5] '%PDF-' &gt;&gt;&gt; pdf[-6:] '%%EOF\n' </code></pre> <p>You can install it by simply running <code>pip install tex</code>. Also note that for the string blocks you can simply prepend <code>r</code> to make it a raw string. That way you don't have to escape all the backslashes.</p>
0
2016-09-12T15:01:37Z
[ "python", "pdflatex" ]
How to submit a form to get URL of next webpage using mechanize?
39,453,333
<p>I am trying to scrape some data, decided to employ mechanize in conjunction with beautifulsoup. I have to enter the field that I want to search in a form on this webpage, then click the search button to get to the next relevant page whose URL I want to get to scrape data off.</p> <p>The developer mode shows the following code for the form-</p> <pre><code>&lt;form name="topsearch" id="topsearch" method="get" onsubmit="javascript:return search_post();" action=""&gt; &lt;input type="hidden" name="search_data" id="search_data" value=""&gt; &lt;input type="hidden" name="cid" id="cid" value=""&gt; &lt;input type="hidden" name="mbsearch_str" id="mbsearch_str"&gt; &lt;input type="hidden" name="topsearch_type" id="topsearch_type" value="1"&gt; &lt;input name="search_str" id="search_str" autocomplete="off" onkeyup="getAutosuggesion();" type="text" value="Search Quotes, News, NAVs..." onblur="if(this.value=='')this.value='Search Quotes, News, NAVs...';" onfocus="if(this.value=='Search Quotes, News, NAVs...')this.value='';if(this.value=='Search Quotes, News, NAVs...')this.value='';" class="txtsrchbox"&gt; &lt;div id="autosugg_mc" class="sugbx"&gt;&lt;/div&gt; &lt;div class="PR srch_qote"&gt; &lt;div class="srchdrp" id="srchR"&gt;Quotes&lt;/div&gt; &lt;div id="srch" class="qubx"&gt; &lt;ul class="qlist"&gt; &lt;li&gt;&lt;a onclick="tab_topser('1');getAutosuggesion();" id="tab1" href="javascript:void(0)" class=""&gt;Quotes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="tab_topser('2');getAutosuggesion();" id="tab2" href="javascript:void(0)" class=""&gt;NAVs&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="tab_topser('5');" id="tab5" href="javascript:void(0)" class=""&gt;Commodities&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="tab_topser('9');" id="tab9" href="javascript:void(0)" class="active"&gt;Futures&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="tab_topser('3');getAutosuggesion();" id="tab3" href="javascript:void(0)" class=""&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="tab_topser('4');" id="tab4" href="javascript:void(0)" class=""&gt;Messages&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="tab_topser('6');getAutosuggesion();" id="tab6" href="javascript:void(0)" class=""&gt;Notices&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a onclick="tab_topser('7');" id="tab7" href="javascript:void(0)" class=""&gt;Videos&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="" onclick="tab_topser('8');" id="tab8" href="javascript:void(0)"&gt;All&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;a href="javascript:;" onclick="$('#topsearch').submit()" style="float:left;" class="btn_search"&gt;&lt;/a&gt; &lt;div class="CL"&gt;&lt;/div&gt; &lt;/form&gt; </code></pre> <p>I fill up the form with my relevant search item using-</p> <pre><code>import pandas as pd import urllib2 import BeautifulSoup as bs import mechanize baseURL = "someBaseURL" br = mechanize.Browser() br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) #Open the Website r = br.open(baseURL) #Selecting the first form of the page br.select_form(nr=0) print br.geturl() br.form['search_str'] = "Some Search" br.submit() print br.geturl() </code></pre> <p>After submitting the form, the url does NOT change to the url it goes to if I search the same string on the website manually. </p> <p>I am getting the url after submitting as -</p> <pre><code>'baseURL?search_data=&amp;cid=&amp;mbsearch_str=&amp;topsearch_type=1&amp;search_str=Kiri+Industries' </code></pre> <p>whereas if I submit manually I get to the next page with the URL -</p> <pre><code>'baseURL/stockpricequote/dyes-pigments/kiriindustries/KDC01' </code></pre> <p>This is the URL I need to be able to scrape the data.</p> <p>Is the submit button using javascript that cannot be called using mechanize, if that is the issue how can I make it to work?</p> <p>Any help is appreciated, thank you.</p>
0
2016-09-12T15:01:15Z
39,585,862
<p>It seems , at least from my similar problem that mechanize does not handle Javascript at all. Try using selenium it handles javascript well. I am building my script on this I'll update if it solves my issue.</p>
0
2016-09-20T04:46:18Z
[ "javascript", "python", "mechanize" ]
google search by google api in r or python
39,453,352
<p>I want to search some thing (ex:"python language") in google by python or R and it will give me the list of links for that google search like:</p> <pre><code>https://en.wikipedia.org/wiki/Python_(programming_language) https://www.python.org/ https://www.python.org/about/gettingstarted/ </code></pre> <p>Is there any api for that I went through this question <a href="http://stackoverflow.com/questions/32889136/how-to-get-google-search-results">How to get google search results</a></p> <p>but problem is sometime it is working and most of the time it is not working and giving only empty list() as an output. thanks.</p>
0
2016-09-12T15:02:09Z
39,453,679
<p>I have used this <a href="https://github.com/rohithpr/py-web-search" rel="nofollow">python web search api</a> to perform google search in python. Fairly straightforward to use and easy to install.</p>
0
2016-09-12T15:18:51Z
[ "python", "web-scraping", "google-api", "google-api-python-client" ]
When to use association, aggregation, composition and inheritance?
39,453,493
<p>I've seen plenty of posts on Stackoverflow explaining the difference between the relationships: associations, aggregation, composition and inheritance, with examples. However, I'm more specifically confused more about the pros and cons of each of these approaches, and when one approach is most effective for the task in hand. This is something I've not been able to really find a good answer on.</p> <p>Keeping inline with the forum's guidelines, I'm <strong>not</strong> asking for why people might personally prefer using inheritance over composition, for example. I'm specifically interested in any objective benefits/weaknesses in each approach, as strong as that may sound. I.e. does one approach create more readable code than another, or does it have a better run time efficiency etc.</p> <p>Ideally, if someone could give me some real world examples where these approaches may have succeeded or failed and why, that would be <strong>extremely</strong> useful for developing my and, I hope, others knowledge. </p> <p>In the interest of ensuring a solid base to work off, I've included examples of each relationship in Python 2. Hopefully this should allow confusion to be avoided, if my understanding of these relationships is not in-fact correct.</p> <p><strong>Association</strong></p> <p>Class B has a week association relationship with Class A, as it uses specific attributes from A in the addAllNums method. However, that is the extent of the relationship. </p> <pre><code>class A(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def addNums(): self.b + self.c class B(object): def __init__(self, d, e): self.d = d self.e = e def addAllNums(self, Ab, Ac): x = self.d + self.e + Ab + Ac return x ting = A("yo", 2, 6) ling = B(5, 9) print ling.addAllNums(ting.b, ting.c) </code></pre> <p><strong>Aggregation</strong></p> <p>Class B forms an aggregation relationship with Class A, as it references an independent A object when initialized, as one of its attributes. Whilst a B object is dependent on A, in the event of B's destruction, A will continue to exist as it is independent of B. </p> <pre><code>class A(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def addNums(): self.b + self.c class B(object): def __init__(self, d, e, A): self.d = d self.e = e self.A = A def addAllNums(self): x = self.d + self.e + self.A.b + self.A.c return x ting = A("yo", 2, 6) ling = B(5, 9, ting) print ling.addAllNums() </code></pre> <p><strong>Composition</strong></p> <p>Much like aggregation, however rather than referencing an independent object, B actually initializes an instance of A in it's own constructor as an attribute. If the B object is destroyed then so too is the A object. This is why composition is such a strong relationship. </p> <pre><code>class A(object): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def addNums(): self.b + self.c class B(object): def __init__(self, d, e): self.d = d self.e = e self.A = A("yo", 2, 6) def addAllNums(self): x = self.d + self.e + self.A.b + self.A.c return x ling = B(5, 9) print ling.addAllNums() </code></pre> <p>I've decided not to include an example of inheritance as I'm completely happy with it, and I feel that its inclusion may throw the point of the question off at a bit of a tangent. </p> <p>Regardless, again, what are the pros and cons of the above examples and inheritance (compared to one another).</p> <p>Thanks. </p>
2
2016-09-12T15:09:14Z
39,453,900
<p>My personal opinion is you should first think about how you would model real world data in ways that help you solve specific real world problems. Assigning things to classes, describing relationships between classes and/or instances, describing properties of things, etc, is the hard part: get this right, and the pattern in code (be it inheritance, aggregation, subclassing, etc) becomes easy. For example:</p> <p>What is the relationship between squares and rectangles? Are invertible matrices a subclass of square matrices? Is a dead cow a mammal? Is student a subclass of person? Is teacher a subclass? What about TAs?</p>
0
2016-09-12T15:30:02Z
[ "python", "inheritance", "associations", "aggregation", "composition" ]
Dot product between 2D and 3D arrays
39,453,770
<p>Assume that I have two arrays <code>V</code> and <code>Q</code>, where <code>V</code> is <code>(i, j, j)</code> and <code>Q</code> is <code>(j, j)</code>. I now wish to compute the dot product of <code>Q</code> with each "row" of <code>V</code> and save the result as an <code>(i, j, j)</code> sized matrix. This is easily done using for-loops by simply iterating over <code>i</code> like</p> <pre><code>import numpy as np v = np.random.normal(size=(100, 5, 5)) q = np.random.normal(size=(5, 5)) output = np.zeros_like(v) for i in range(v.shape[0]): output[i] = q.dot(v[i]) </code></pre> <p>However, this is way too slow for my needs, and I'm guessing there is a way to vectorize this operation using either <code>einsum</code> or <code>tensordot</code>, but I haven't managed to figure it out. Could someone please point me in the right direction? Thanks</p>
1
2016-09-12T15:23:39Z
39,454,139
<p>You can certainly use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow"><code>np.tensordot</code></a>, but need to swap axes afterwards, like so -</p> <pre><code>out = np.tensordot(v,q,axes=(1,1)).swapaxes(1,2) </code></pre> <p>With <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>, it's a bit more straight-forward, like so -</p> <pre><code>out = np.einsum('ijk,lj-&gt;ilk',v,q) </code></pre>
1
2016-09-12T15:44:26Z
[ "python", "numpy", "vectorization" ]
Numpy: how to apply vectorized functions to array with dtype
39,453,771
<p>I'm following <a href="http://www.scipy-lectures.org/advanced/image_processing/" rel="nofollow">this tutorial</a> on how to use numpy to manipulate images. When I load the sample image using scipy, I get a 2D array of RGB tuples, with a dtype value appended on the end.</p> <pre><code>array([[7, 8, 5], [3, 5, 7]], dtype=uint8) </code></pre> <p>I wrote a function and vectorized it</p> <pre><code>def myfunc(a, b): return a + 2 vfunc = np.vectorize(myfunc) </code></pre> <p>but when I apply it to my array, the result doesn't have the dtype</p> <pre><code>array([[9, 10, 7], [5, 7, 9]]) </code></pre> <p>My guess is that because "dtype + 2" isn't defined, it's just losing that element of the array.</p> <p>How can I write a function that will not strip the dtype when I vectorize it and apply it to a numpy array?</p>
0
2016-09-12T15:23:49Z
39,453,937
<p><code>dtype=uint8</code> is not an element of the array. It is just a thing that gets printed to let you know that the array is of type <code>np.uint8</code>.</p> <p>The default types <code>np.float_</code> and <code>np.int_</code> do not get a printout like that, which is what you are seeing in the second case. The way you can tell float and int arrays apart is that float arrays will always have decimal points in the numbers.</p> <p>The reason that this is happening is that you are adding <code>2</code> to each element of your array. Since <code>2</code> is an integer, the output array gets promoted to <code>np.int_</code> type and you do not get an explicit <code>dtype</code> printout.</p> <p>You can try the following experiment: redefine <code>myfunc</code> to add a <code>np.uint8</code> instead of an integer to the array elements and try to print the result:</p> <pre><code>def myfunc(a, b): return a + np.uint8(2) </code></pre> <p>Finally, keep in mind that vectorizing Python code is usually not the best way to get things done. The function itself will be a Python function, and therefore slow. It is generally better to find a way of performing whatever operations you want with numpy functions.</p>
0
2016-09-12T15:32:16Z
[ "python", "numpy" ]
Numpy: how to apply vectorized functions to array with dtype
39,453,771
<p>I'm following <a href="http://www.scipy-lectures.org/advanced/image_processing/" rel="nofollow">this tutorial</a> on how to use numpy to manipulate images. When I load the sample image using scipy, I get a 2D array of RGB tuples, with a dtype value appended on the end.</p> <pre><code>array([[7, 8, 5], [3, 5, 7]], dtype=uint8) </code></pre> <p>I wrote a function and vectorized it</p> <pre><code>def myfunc(a, b): return a + 2 vfunc = np.vectorize(myfunc) </code></pre> <p>but when I apply it to my array, the result doesn't have the dtype</p> <pre><code>array([[9, 10, 7], [5, 7, 9]]) </code></pre> <p>My guess is that because "dtype + 2" isn't defined, it's just losing that element of the array.</p> <p>How can I write a function that will not strip the dtype when I vectorize it and apply it to a numpy array?</p>
0
2016-09-12T15:23:49Z
39,454,515
<p><code>np.vectorize</code> takes an <code>otypes</code> parameter. You can use that to specify the dtype of the return. Without that <code>vectorize</code> does a trial calculation on the 1st element of your array, and uses that return dtype to determine the dtype of the whole reply.</p> <p>Look at the 3rd example in its docs.</p> <p>Usually users encounter this when the first value produces an integer value (e.g. <code>0</code>) and they expect the whole thing to be float.</p> <p>So try:</p> <pre><code> vfunc = np.vectorize(myfunc, otypes=[np.uint8]) </code></pre>
1
2016-09-12T16:07:01Z
[ "python", "numpy" ]
Extracting Pylint Score
39,453,828
<p>Does anyone know how to extract <em>only</em> the pylint score for a repository?</p> <p>So, assuming pylint produces the following output:</p> <pre><code>Global evaluation ----------------- Your code has been rated at 6.67/10 (previous run: 6.67/10, +0.00) </code></pre> <p>I would like it to return a value of 6.67.</p> <p>Thanks,</p> <p>Seán</p>
1
2016-09-12T15:26:03Z
39,454,034
<p>You can run <code>pylint</code> <em>programmatically</em> and get to the <code>stats</code> dictionary of the underlying "linter":</p> <pre><code>from pylint.lint import Run results = Run(['test.py'], exit=False) print(results.linter.stats['global_note']) </code></pre>
2
2016-09-12T15:38:20Z
[ "python", "pylint" ]
Not concatenating in same line
39,453,829
<p>This is my code:</p> <pre><code>with open('test1.txt') as f: print "printing f" print f print '**********************' for line in f: print "printing line each" print line print '********' line2=line.upper()+"abc" print "printing line 2" print line2 print '********' open('testout.txt','a').write(line2) </code></pre> <p>And for this I am getting this output:</p> <pre class="lang-none prettyprint-override"><code>printing line 2 ROMA abc </code></pre> <p>instead of:</p> <pre class="lang-none prettyprint-override"><code>printing line 2 ROMAabc </code></pre> <p>I can't understand what is wrong, can someone help me understand?</p> <p>P.S: I tried using <code>join</code> method as well, and still got the same result.</p> <p>I am using python 2.7</p>
0
2016-09-12T15:26:04Z
39,453,882
<p>line contains '\n' at the end, you can use this for your goal:</p> <pre><code>line.strip().upper() </code></pre>
3
2016-09-12T15:28:55Z
[ "python", "python-2.7", "concatenation" ]
Not concatenating in same line
39,453,829
<p>This is my code:</p> <pre><code>with open('test1.txt') as f: print "printing f" print f print '**********************' for line in f: print "printing line each" print line print '********' line2=line.upper()+"abc" print "printing line 2" print line2 print '********' open('testout.txt','a').write(line2) </code></pre> <p>And for this I am getting this output:</p> <pre class="lang-none prettyprint-override"><code>printing line 2 ROMA abc </code></pre> <p>instead of:</p> <pre class="lang-none prettyprint-override"><code>printing line 2 ROMAabc </code></pre> <p>I can't understand what is wrong, can someone help me understand?</p> <p>P.S: I tried using <code>join</code> method as well, and still got the same result.</p> <p>I am using python 2.7</p>
0
2016-09-12T15:26:04Z
39,453,897
<p>Just use a <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow">.strip()</a>, so</p> <pre><code>print line.strip().upper() </code></pre> <p>You're reading a new line separated document. It's got special "\n"s inside.</p>
1
2016-09-12T15:29:48Z
[ "python", "python-2.7", "concatenation" ]
How to get an element having its relative XPath?
39,453,891
<p>I have xml file. After parsing it with <code>lxml</code> as an <code>etree</code>, I can get all of its tags as follows:</p> <pre><code>root = tree.getroot() for e in root.iter(): print e.tag </code></pre> <p>and the output is something like this:</p> <pre class="lang-none prettyprint-override"><code>'{http://www.w3.org/1999/xhtml}html' '{http://www.w3.org/1999/xhtml}head' '{http://www.w3.org/1999/xhtml}meta' '{http://www.w3.org/1999/xhtml}link' '{http://www.w3.org/1999/xhtml}meta' '{http://www.w3.org/1999/xhtml}meta' '{http://www.w3.org/1999/xhtml}meta' '{http://www.w3.org/1999/xhtml}script' '{http://www.w3.org/1999/xhtml}body' '{http://www.w3.org/1999/xhtml}section' '{http://www.w3.org/1999/xhtml}h1' '{http://www.w3.org/1999/xhtml}p' '{http://www.w3.org/1999/xhtml}em' '{http://www.w3.org/1999/xhtml}section' '{http://www.w3.org/1999/xhtml}h1' '{http://www.w3.org/1999/xhtml}p' '{http://www.w3.org/1999/xhtml}a' '{http://www.w3.org/1999/xhtml}p' '{http://www.w3.org/1999/xhtml}p' </code></pre> <p><strong>I want to get some elements with relative path using python/lxml/bs4.</strong> For example I want first <code>p</code> element in second <code>section</code> and I have following relative path: <code>/section[2]/p[1]</code> .</p> <p>But I can not even get all sections with following code, which returns <code>None</code>:</p> <pre><code>xhtml = {http://www.w3.org/1999/xhtml} section = xhtml + "section" root.find(section) </code></pre> <p>EDIT: Here's part of original file:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;?xml-model href="grammar/rash.rng" type="application/xml" schematypens="http://relaxng.org/ns/structure/1.0"?&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" prefix="schema: http://schema.org/ prism: http://prismstandard.org/namespaces/basic/2.0/"&gt; &lt;head&gt; &lt;meta charset="UTF-8"/&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"/&gt; &lt;link rel="stylesheet" href="css/bootstrap.min.css"/&gt; &lt;link rel="stylesheet" href="css/rash.css"/&gt; &lt;script src="js/jquery.min.js"&gt;&lt;![CDATA[ ]]&gt;&lt;/script&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;![CDATA[ ]]&gt;&lt;/script&gt; &lt;script src="js/rash.js"&gt;&lt;![CDATA[ ]]&gt;&lt;/script&gt; &lt;title&gt;It ROCS! -- The RASH Online Conversion Service&lt;/title&gt; &lt;meta about="#affiliation-1" property="schema:name" content="Department of Computer Science and Engineering, University of Bologna, Italy"/&gt; &lt;meta about="#affiliation-2" property="schema:name" content="Oxford e-Research Centre, University of Oxford, UK"/&gt; &lt;meta about="#affiliation-3" property="schema:name" content="Knowledge Media Institute, Open University, UK"/&gt; &lt;meta property="prism:keyword" content="HTML-based format"/&gt; &lt;meta property="prism:keyword" content="Scholarly HTML"/&gt; &lt;meta property="prism:keyword" content="RASH"/&gt; &lt;script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"&gt;&lt;![CDATA[ ]]&gt;&lt;/script&gt;&lt;/head&gt; &lt;body&gt; &lt;section role="doc-abstract"&gt; &lt;h1&gt;Abstract&lt;/h1&gt; &lt;p&gt;In this poster paper we introduce the &lt;em&gt;RASH Online Conversion Service&lt;/em&gt;, i.e., a Web application that allows the conversion of ODT documents into RASH, a HTML-based markup language for writing scholarly articles, and from RASH into LaTeX. This tool allows authors with no experience in HTML to easily produce HTML-based papers and supports the publishing process by generating also a LaTeX version according to the Springer LNCS and ACM ICPS layouts.&lt;/p&gt; &lt;/section&gt; &lt;section&gt; &lt;h1&gt;Introduction&lt;/h1&gt; &lt;p&gt;The use of HTML as format for writing scholarly papers and submitting them to scholarly venues is a very popular, discussed and trendy topic within the scholarly domain. This is demonstrated by the existence of several posts within technical mailing lists of the Web community&lt;a href="#ftn0"&gt; &lt;/a&gt;, by the birth of W3C community groups on such topic&lt;a href="#ftn3"&gt; &lt;/a&gt;, by the development of HTML-based formats for scholarly articles&lt;a href="#ftn4"&gt; &lt;/a&gt;, and by the increasing number of events that are experimenting with HTML-based formats for submissions, such as the SAVE-SD&lt;a href="#ftn5"&gt; &lt;/a&gt; and LDOW&lt;a href="#ftn6"&gt; &lt;/a&gt; workshops at WWW 2016, and the Extended Semantic Web Conference&lt;a href="#ftn7"&gt; &lt;/a&gt;.&lt;/p&gt; &lt;p&gt;In order to foster a wider adoption of these formats, frameworks for HTML-based papers should support the needs of all the actors involved in the production, delivery and fruition of scholarly articles, with particular regards to authors and publishers. Hence, this solution calls for a number of requirements that go well beyond those used on the Web. &lt;/p&gt; &lt;p&gt;First of all, it is vital to support authors with a variety of tools to provide for an easy transition to the new format. To this end, authors should be allowed to keep using well-known current word processors rather than adopting HTML and/or pure text editors. We thus need to support the conversion from the main word processor formats (e.g., ODT and OOXML) to HTML formats, in particular when authors use only basic features, such as standard styles for paragraphs and tables. In addition, authors should be given the option to focus on the content and let appropriate tools handle the presentation layer after the conversion into the HTML-based format.&lt;/p&gt; </code></pre> <p>In this example I want to get <code>&lt;p&gt;</code> element which starts with this sentence: "The use of HTML as format for writing scholarly..."</p>
-1
2016-09-12T15:29:29Z
39,454,096
<p>BeautifulSoup, does not support XPath expressions, but <strong>lxml</strong> you've mentioned, does. </p> <p>You can search for elements with XPath like following:</p> <pre><code>from lxml import etree htmlparser = etree.HTMLParser() tree = etree.parse(html_content, htmlparser) tree.xpath(xpathselector) </code></pre>
0
2016-09-12T15:41:56Z
[ "python", "xml", "xpath", "lxml", "bs4" ]
How to overload __str__ operation so str("test") returns "test"
39,454,069
<p>I'm trying to overload the <strong>str</strong> operation so that when I do str(string) it keeps the quotations.</p> <p>ex: str("test") returns test</p> <p>I want it to return "test"</p> <p>Heres what I have written, any help would be very much appreciated!</p> <pre><code>class Action(MalmoAgent): def __init__(self, command = '', value = 0): self.__command = command self.__value = value def __str__(self): return ' " ' + self + ' " ' </code></pre>
0
2016-09-12T15:40:18Z
39,454,138
<p>Use <code>repr()</code>, this is obviously not an actual string.</p> <pre><code>repr('Test') </code></pre>
0
2016-09-12T15:44:23Z
[ "python", "string", "operator-overloading" ]
How to overload __str__ operation so str("test") returns "test"
39,454,069
<p>I'm trying to overload the <strong>str</strong> operation so that when I do str(string) it keeps the quotations.</p> <p>ex: str("test") returns test</p> <p>I want it to return "test"</p> <p>Heres what I have written, any help would be very much appreciated!</p> <pre><code>class Action(MalmoAgent): def __init__(self, command = '', value = 0): self.__command = command self.__value = value def __str__(self): return ' " ' + self + ' " ' </code></pre>
0
2016-09-12T15:40:18Z
39,454,165
<p>Just format your string</p> <pre><code>... def __str__(self): ... return '"%s"' % self.whatever </code></pre>
0
2016-09-12T15:45:58Z
[ "python", "string", "operator-overloading" ]
How to overload __str__ operation so str("test") returns "test"
39,454,069
<p>I'm trying to overload the <strong>str</strong> operation so that when I do str(string) it keeps the quotations.</p> <p>ex: str("test") returns test</p> <p>I want it to return "test"</p> <p>Heres what I have written, any help would be very much appreciated!</p> <pre><code>class Action(MalmoAgent): def __init__(self, command = '', value = 0): self.__command = command self.__value = value def __str__(self): return ' " ' + self + ' " ' </code></pre>
0
2016-09-12T15:40:18Z
39,463,367
<pre><code>class MalmoAgent(): pass class Action(MalmoAgent): def __init__(self, command='', value=0): self.__command = command self.__value = value def __str__(self): return '"' + super(Action, self).__str__() + '"' thing = Action() print("I have a", thing, "called thing.") </code></pre> <p><strong>OUTPUT</strong></p> <pre><code>I have a "&lt;__main__.Action object at 0x101ae9a90&gt;" called thing. </code></pre>
0
2016-09-13T06:19:01Z
[ "python", "string", "operator-overloading" ]
How to use leveldb and What kind of dataLayer I can use in pycaffe interface?
39,454,111
<p>I tried to make train/val.prototxt using leveldb by caffe python interface:</p> <pre><code>layer { name: "cifar" type: "Data" top: "data" top: "label" data_param { source: "/home/youngwan/data/cifar10/cifar10-gcn-leveldb-splits/cifar10_full_train_leveldb_padded" batch_size: 100 backend: LEVELDB } transform_param { mean_file: "/home/youngwan/data/cifar10/cifar10-gcn-leveldb-splits/paddedmean.binaryproto" mirror: 1 crop_size: 32 } include: { phase: TRAIN } } </code></pre> <p>But in caffe python interface, I can't find a proper datalayer python wrapper(e.g., <code>L.MemoryData</code>) even though I tried to find examples and tutorials in BLVC/caffe page.</p> <p>Could you notice which <code>'L.xxx'</code> layer I can use it?</p>
1
2016-09-12T15:42:44Z
39,464,010
<p>Using <code>caffe.NetSpec()</code> interface, you can have all the layers you want:</p> <pre><code>from caffe import layers as L, params as P cifar = L.Data(data_param={'source': '/home/youngwan/data/cifar10/cifar10-gcn-leveldb-splits/cifar10_full_train_leveldb_padded', 'batch_size': 100, 'backend': P.Data.LEVELDB}, transform_param={'mean_file': '/home/youngwan/data/cifar10/cifar10-gcn-leveldb-splits/paddedmean.binaryproto', 'mirror': 1, 'crop_size': 32}, include={'phase':caffe.TRAIN}) </code></pre> <p>Basically, <code>L.&lt;layer type&gt;</code> defines a layer of type <code>&lt;layer type&gt;</code>.</p>
1
2016-09-13T07:03:20Z
[ "python", "neural-network", "deep-learning", "caffe", "pycaffe" ]
"FailedParse: [...] Expecting end of text" when trying to parse parenthesized expressions in grako
39,454,140
<p>In <code>search_query.ebnf</code>, I have the following grammar definition for <code>grako</code> 3.14.0:</p> <pre class="lang-none prettyprint-override"><code>@@grammar :: SearchQuery start = search_query $; search_query = parenthesized_query | combined_query | search_term; parenthesized_query = '(' search_query ')'; combined_query = search_query binary_operator search_query; binary_operator = '&amp;' | '|'; search_term = /\w+/; </code></pre> <p>I generate the parser with </p> <pre><code>grako search_query.ebnf --outfile search_query_parser.py </code></pre> <p>The result works as I expected for these inputs:</p> <pre><code>import search_query_parser parser = search_query_parser.SearchQueryParser() parser.parse('a') # -&gt; 'a' parser.parse('(a)') # -&gt; ['(', 'a', ')'] parser.parse('a &amp; b') # -&gt; ['a', '&amp;', 'b'] parser.parse('a | b') # -&gt; ['a', '|', 'b'] parser.parse('(a|b)&amp;c') # -&gt; ['(', ['a', '|', 'b'], ')', '&amp;', 'c'] </code></pre> <p>but if I have a parenthesized expression at the right hand side of an operator, the parser gives me an error message:</p> <pre><code>parser.parse('c&amp;(a|b)') </code></pre> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/search_query_parser.py", line 82, in parse return super(SearchQueryParser, self).parse(text, *args, **kwargs) File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 227, in parse result = rule() File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 86, in wrapper return self._call(rule, name, params, kwparams) File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 475, in _call node, newpos, newstate = self._invoke_rule(rule, name, params, kwparams) File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 511, in _invoke_rule rule(self) File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/search_query_parser.py", line 87, in _start_ self._check_eof() File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 650, in _check_eof self._error('Expecting end of text.') File "/home/das-g/.virtualenvs/tmp-d0fd5a9428f7612a/lib/python3.5/site-packages/grako/contexts.py", line 450, in _error item grako.exceptions.FailedParse: (1:2) Expecting end of text. : c&amp;(a|b) ^ start </code></pre> <p>Am I doing something wrong?</p>
1
2016-09-12T15:44:43Z
39,454,141
<blockquote> <p>Am I doing something wrong?</p> </blockquote> <p>I don't think so.</p> <p>This looks like a <a href="https://bitbucket.org/apalala/grako/issues/81/left-recursion" rel="nofollow">known bug</a> in <code>grako</code> concerning "left recursion".</p> <p>The workaround mentioned in the bug seems to work for your case, too:</p> <pre class="lang-none prettyprint-override"><code>@@grammar :: SearchQuery start = search_query $; search_query = parenthesized_query | combined_query | search_term; parenthesized_query = '(' search_query | search_term ')'; ## Workaround combined_query = search_query binary_operator search_query; binary_operator = '&amp;' | '|'; search_term = /\w+/; </code></pre> <p>i.e. mention <code>search_term</code> explicitly inside the parentheses, even though the <code>search_query</code> rule should be able to produce it, too.</p>
1
2016-09-12T15:44:43Z
[ "python", "ebnf", "grako" ]
Scipy.optimize COBYLA constraint violation
39,454,203
<p>I have an optimization problem with constraints, but the COBYLA solver doesn't seem to respect the constraints I specify.</p> <p>My optimization problem:</p> <pre><code>cons = ({'type':'ineq', 'fun':lambda t: t},) # all variables must be positive minimize(lambda t: -stateEst(dict(zip(self.edgeEvents.keys(),t)), (0.1,)*len(self.edgeEvents), constraints=cons, method='COBYLA') </code></pre> <p>and <code>stateEst</code> is defined as:</p> <pre><code>def stateEst(t): val = 0 for edge,nextState in self.edgeEvents.iteritems(): val += edge_probability(self,edge,ts) * estimates[nextState] val += node_probability(self, edge.head, ts, edge_list=[edge])* cost for node,nextState in self.nodeEvents.iteritems(): val += node_probability(self, node, ts) * \ (estimates[nextState] + cost*len([e for e in node.incoming if e in self.compEdges]) return val </code></pre> <p>The probability functions are only defined for positive <code>t</code> values. The dictionary is necessary because the probabilities are calculated with respect to the 'named' t-values.</p> <p>When I run this, I notice that COBYLA tries a value of -0.025 for one of the t-values. Why is the optimization not respecting the constraints?</p>
0
2016-09-12T15:48:47Z
39,455,568
<p><strong>COBYLA</strong> is technically speaking an <strong>infeasible method</strong>, which means, that the <strong>iterates might not be always feasible in regards to your constraints!</strong> (it's only about the final convergence, where feasibility matters for these algorithms).</p> <p>Using an objective-function which is not defined everywhere will be problematic. Maybe you are forced to switch to some <strong>feasible method</strong>.</p> <p>Alternatively you could think about generalizing your objective, so that there are penalties introduced for negative t's. But this is problem-dependent and could introduce other problems as well (convergence; numeric-stability).</p> <p>Try using <a href="http://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html#optimize-minimize-lbfgsb" rel="nofollow">L-BFGS-B</a>, which is limited to bound-constraints, which is not a problem here (for your current problem!).</p>
3
2016-09-12T17:22:10Z
[ "python", "optimization", "scipy", "constraints" ]
xarray.Dataset.where() method force-changes dtype of DataArrays to float
39,454,205
<h1>Problem description</h1> <p>I have a dataset with <code>int</code>s in them, and I'd like to select a subdataset by some criteria but I would like to preserve the integer datatype. It seems to me that Xarray force-changes the integer data to float datatype.</p> <h1>Example setup</h1> <h3>Code</h3> <pre><code>import numpy import xarray nums = numpy.random.randint(0, 100, 13) names = numpy.random.choice(["babadook", "samara", "jason"], 13) data_vars = {"num": xarray.DataArray(nums), "name": xarray.DataArray(names)} dataset = xarray.Dataset(data_vars) print(dataset) </code></pre> <h3>Output</h3> <pre class="lang-none prettyprint-override"><code>&lt;xarray.Dataset&gt; Dimensions: (dim_0: 13) Coordinates: * dim_0 (dim_0) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 Data variables: num (dim_0) int64 93 99 49 35 92 14 41 57 28 59 74 1 15 name (dim_0) &lt;U8 'babadook' 'samara' 'samara' 'samara' 'jason' ... In [16]: </code></pre> <h1>Example problem</h1> <h3>Code</h3> <pre><code>subdataset = dataset.where(dataset.num &lt; 50, drop=True) print(subdataset) </code></pre> <h3>Output</h3> <pre class="lang-none prettyprint-override"><code>&lt;xarray.Dataset&gt; Dimensions: (dim_0: 7) Coordinates: * dim_0 (dim_0) int64 2 3 5 6 8 11 12 Data variables: num (dim_0) float64 49.0 35.0 14.0 41.0 28.0 1.0 15.0 name (dim_0) &lt;U32 'samara' 'samara' 'jason' 'babadook' 'jason' ... </code></pre>
2
2016-09-12T15:48:51Z
39,454,954
<p>That's because with numpy (which xarray uses under-the-hood) ints don't have a way of representing <code>NaN</code>s. So with most <code>where</code> results, the type needs to be coerced to floats.</p> <p>If <code>drop=True</code> and every value that is masked is dropped, that's not actually a constraint - you could have the new array retain its dtype, because there's no need for <code>NaN</code> values. That's not in xarray at the moment, but could be an additional feature.</p>
3
2016-09-12T16:38:17Z
[ "python", "python-xarray" ]
How to convert an angle vector to Euclidean coordinates given a fixed amplitude, in n dimension
39,454,240
<p>so to convert a polar coordinate (amplitude, angle) to euclidean coordinates in 2D is straight forward. </p> <p>But in n (say n = 5) dimension, I have a fixed amplitude, and a randomised angle vector. How can I convert it into an euclidean vector of the coordinates?</p> <pre><code>amp = 0.5 n = 5 ang = np.random.rand(n) * 2* pi </code></pre> <p>Many thanks</p>
0
2016-09-12T15:50:41Z
39,454,853
<p>In 2D, the conversion is:</p> <pre><code>x = amp * cos(angle) y = amp * sin(angle) </code></pre> <p>In 3D, one option is:</p> <pre><code>x = amp * cos(angle1) * cos(angle2) y = amp * sin(angle1) * cos(angle2) z = amp * sin(angle2) </code></pre> <p>You should see a pattern. The dimensions that already exist get a factor of <code>cos(newAngle)</code>. The new dimension gets <code>sin(newAngle)</code>. So, in 4D, this would be:</p> <pre><code>x = amp * cos(angle1) * cos(angle2) * cos(angle3) y = amp * sin(angle1) * cos(angle2) * cos(angle3) z = amp * sin(angle2) * cos(angle3) w = amp * sin(angle3) </code></pre> <p>In general, the <code>i</code>-th dimension is (1-based):</p> <pre><code>dim_i = sin(angle_(i-1)) * Product {j from i to n} cos(angle_j) </code></pre> <p>(Only if <code>angle_(i-1)</code> exists, otherwise set the term to <code>1</code>).</p>
5
2016-09-12T16:30:43Z
[ "python", "math", "wolfram-mathematica" ]
How can I plot my groupby() result?
39,454,260
<p>I'm running a <code>groupby()</code> on my data like this:</p> <pre><code>user.groupby(["DOC_ACC_DT", "DOC_ACTV_CD"]).agg("sum")["SUM_DOC_CNT"] </code></pre> <p>which results in this grouped data:</p> <pre><code>DOC_ACC_DT DOC_ACTV_CD 2015-07-01 BR 1 PT 1 2015-07-02 BR 1 PT 1 2015-07-06 BR 1 PT 1 2015-07-08 BR 1 2015-07-09 AD 2 PT 1 2015-07-13 AD 50 BR 52 PT 1 2015-07-14 AD 6 BR 5 PT 1 2015-07-16 BR 1 PT 1 2015-07-23 AD 13 BR 14 PT 3 2015-07-27 BR 1 PT 1 </code></pre> <p>What I want to do now is simply plot by <code>DOC_ACTV_CD</code>. Please not that there are gaps between days so I'd have to fill in zero-values between days where nothing happened e.g.</p> <pre><code>2015-07-23 AD 13 BR 14 PT 3 2015-07-25 BR 1 PT 1 </code></pre> <p>would have to become</p> <pre><code>2015-07-23 AD 13 BR 14 PT 3 2015-07-24 AD 0 BR 0 PT 0 2015-07-25 AD 0 BR 1 PT 1 </code></pre> <p>before I plot a time series for <code>AD</code>, <code>BR</code> and <code>PT</code> in one plot. What's the quickest way to do this?</p>
1
2016-09-12T15:51:46Z
39,454,561
<p>You can use:</p> <pre><code>df = user.groupby(["DOC_ACC_DT", "DOC_ACTV_CD"]).agg("sum")["SUM_DOC_CNT"] df.unstack().resample('D').replace(np.nan,0).plot() </code></pre>
2
2016-09-12T16:09:37Z
[ "python", "pandas", "plot", null, "resampling" ]
Is there a way to play song from the middle in gstreamer?
39,454,407
<p>I've looking for method to play songs not from the begining in python gstreamer, consider this:</p> <pre><code>import threading import gst import gobject class GobInit(threading.Thread): ... class BasicPlayer(threading.Thread): def __init__(self, musiclist): threading.Thread.__init__(self) self.musiclist = musiclist self.song_num = 0 self.construct_pipeline() self.set_property_file() def construct_pipeline(self): self.player = gst.element_factory_make("playbin") self.is_playing = False self.connect_signals() def connect_signals(self): ... def play(self): self.is_playing = True self.player.set_state(gst.STATE_PLAYING) def set_property_file(self): self.player.set_property( "uri", "file://"+"/home/user/work/mp3/"+self.musiclist[ self.song_num]) def main(): gob = GobInit() gob.start() print('start') player = BasicPlayer(['test1.mp3', 'test2.mp3', 'test3.mp3']) print('player created') player.play() print('start play') main() </code></pre> <p>So I have only this function to start:</p> <pre><code>self.player.set_state(gst.STATE_PLAYING) </code></pre> <p>But I bet there is a way to start playing from the middle of the song, something like this:</p> <pre><code>self.player.play_from_middle(gst.STATE_PLAYING, &lt;sec_after_begin&gt;) </code></pre> <p>Or maybe can I rewind the song somehow to make it be played from the middle?</p>
1
2016-09-12T15:59:54Z
39,456,299
<p>Yes, I guess there should be a few ways, but the one (for non-live streams) that immediately comes to my mind is:</p> <ul> <li>Set the pipeline to PAUSED instead of PLAYING</li> <li>Wait for the GST_MESSSAGE_ASYNC_DONE message to appear in the bus handler.</li> <li>Query pipeline (gst_element_query()) for the duration, and then seek the pipeline (gst_element_seek()) to the duration/2 time </li> <li>Set the pipeline to PLAYING.</li> </ul>
3
2016-09-12T18:12:34Z
[ "python", "gstreamer" ]
Django having issues with django-registration-redux
39,454,433
<p>I've been following an online tutorial on django registration. They are using <code>django-registration-redux==1.1</code>, and I have to use <code>django-registration-redux==1.4</code>. I start my local server and go to this: <a href="http://127.0.0.1:8000/accounts/register/" rel="nofollow">http://127.0.0.1:8000/accounts/register/</a></p> <p>I then see this error: <code>TemplateDoesNotExist at /accounts/register/</code></p> <pre><code>Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register/ Django Version: 1.9 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'store'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/django/contrib/admin/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/django/contrib/auth/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/registration/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Users/xx/Desktop/stoneriverelearning/bookstore/store/templates/base.html (Source does not exist) Template error: In template /Library/Python/2.7/site-packages/registration/templates/registration/registration_form.html, error at line 1 base.html 1 : {% extends "registration/ registration_base.html" %} 2 : {% load i18n %} 3 : 4 : {% block title %}{% trans "Register for an account" %}{% endblock %} 5 : 6 : {% block content %} 7 : &lt;form method="post" action=""&gt; 8 : {% csrf_token %} 9 : {{ form.as_p }} 10 : &lt;input type="submit" value="{% trans 'Submit' %}" /&gt; 11 : &lt;/form&gt; Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 174. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 172. response = response.render() File "/Library/Python/2.7/site-packages/django/template/response.py" in render 160. self.content = self.rendered_content File "/Library/Python/2.7/site-packages/django/template/response.py" in rendered_content 137. content = template.render(context, self._request) File "/Library/Python/2.7/site-packages/django/template/backends/django.py" in render 97. reraise(exc, self.backend) File "/Library/Python/2.7/site-packages/django/template/backends/django.py" in reraise 107. six.reraise(exc.__class__, new, sys.exc_info()[2]) File "/Library/Python/2.7/site-packages/django/template/backends/django.py" in render 95. return self.template.render(context) File "/Library/Python/2.7/site-packages/django/template/base.py" in render 206. return self._render(context) File "/Library/Python/2.7/site-packages/django/template/base.py" in _render 197. return self.nodelist.render(context) File "/Library/Python/2.7/site-packages/django/template/base.py" in render 988. bit = node.render_annotated(context) File "/Library/Python/2.7/site-packages/django/template/base.py" in render_annotated 955. return self.render(context) File "/Library/Python/2.7/site-packages/django/template/loader_tags.py" in render 173. return compiled_parent._render(context) File "/Library/Python/2.7/site-packages/django/template/base.py" in _render 197. return self.nodelist.render(context) File "/Library/Python/2.7/site-packages/django/template/base.py" in render 988. bit = node.render_annotated(context) File "/Library/Python/2.7/site-packages/django/template/base.py" in render_annotated 955. return self.render(context) File "/Library/Python/2.7/site-packages/django/template/loader_tags.py" in render 151. compiled_parent = self.get_parent(context) File "/Library/Python/2.7/site-packages/django/template/loader_tags.py" in get_parent 148. return self.find_template(parent, context) File "/Library/Python/2.7/site-packages/django/template/loader_tags.py" in find_template 128. template_name, skip=history, File "/Library/Python/2.7/site-packages/django/template/engine.py" in find_template 169. raise TemplateDoesNotExist(name, tried=tried) Exception Type: TemplateDoesNotExist at /accounts/register/ Exception Value: base.html </code></pre> <p>I'm getting that the difference would be that I have to do something different in this newer version to get it to find all the new registration html files and txt files (for email), but how do I do this?</p> <p>EDIT:</p> <p>So thanks for pointing out the space here:</p> <pre><code>{% extends "registration/ registration_base.html" %} </code></pre> <p>How can this be removed? I don't have this in my code that I know of.</p> <p>Here is my urls file:</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^store/', include('store.urls'), name='store'), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^admin/', include(admin.site.urls)), </code></pre> <p>]</p> <p>Thanks :)</p>
0
2016-09-12T16:01:50Z
39,454,475
<p>It looks like you have a space in line 1 of your template when referencing the file name. If that's not it, you may have another folder locally named registration that django is looking in instead of the registration package.</p>
0
2016-09-12T16:04:22Z
[ "python", "django", "django-registration" ]
Read (decode) and process an aac stream with python
39,454,468
<p>I have an Axis camera that provides an audio stream that is aac encoded. I would like to find a possibility to decode that stream in Python to further process the raw audio data. Does anybody have suggestions how that could be done?</p> <p>Thanks!</p>
0
2016-09-12T16:03:53Z
39,647,478
<p>You can use <a href="https://github.com/jiaaro/pydub" rel="nofollow">pydub</a> to convert an <code>aac</code> audio to datasegment and then process it further.</p> <pre><code>from pydub import AudioSegment from pydub.playback import play #convert audio to datasegment sound = AudioSegment.from_file("your/path/to/audio.aiff", "aac") play(sound) #play sound </code></pre> <p>Lots of other data manipulation using <code>pydub</code> is available <a href="https://github.com/jiaaro/pydub" rel="nofollow">here</a> </p>
0
2016-09-22T19:33:20Z
[ "python", "audio", "decode", "aac" ]
different ways to access pandas.DataFrame columns
39,454,471
<p>What is the difference between <code>df[columns]</code> and <code>df.loc[:,columns]</code>, both as lvalue and rvalue?</p> <p>They seem to be interchangeable from the behavioral POV:</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'x':[1,2,3],'y':['a','b','c']}) &gt;&gt;&gt; df[['x']].equals(df.loc[:,['x']]) True &gt;&gt;&gt; df.loc[:,'z'] = df.x.apply(str) + df.y &gt;&gt;&gt; df['a'] = df.x.apply(str) + df.y &gt;&gt;&gt; df x y z a 0 1 a 1a 1a 1 2 b 2b 2b 2 3 c 3c 3c </code></pre> <p>I know there is a document somewhere answering this in excruciating details (and I am sure I even saw it once, but a link would be nice), but I am looking at an "executive summary", so to speak.</p> <p><strong>Specifically</strong>: is one a shortcut for the other, or there is some semantic difference?</p> <p>PS. This is prompted by the message</p> <blockquote> <p>~/.virtualenvs/wilbur/lib/python2.7/site-packages/pandas/core/indexing.py:465: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead</p> </blockquote>
1
2016-09-12T16:04:07Z
39,456,621
<p>what about timing comparison for a 300K rows DF?</p> <pre><code>In [22]: big = pd.concat([df] * 10**5, ignore_index=True) In [23]: %timeit -n 1 -r 1 big['n1'] = big.x.apply(str) + big.y 1 loop, best of 1: 266 ms per loop In [24]: %timeit -n1 -r 1 big.ix[:, 'n2'] = big.x.apply(str) + big.y 1 loop, best of 1: 317 ms per loop In [25]: %timeit -n 1 -r 1 big.loc[:, 'n3'] = big.x.apply(str) + big.y 1 loop, best of 1: 333 ms per loop In [26]: %timeit -n 1 -r 1 big.insert(len(big.columns), 'n4', big.x.apply(str) + big.y) 1 loop, best of 1: 266 ms per loop In [27]: big.shape Out[27]: (300000, 6) In [28]: big.head() Out[28]: x y n1 n2 n3 n4 0 1 a 1a 1a 1a 1a 1 2 b 2b 2b 2b 2b 2 3 c 3c 3c 3c 3c 3 1 a 1a 1a 1a 1a 4 2 b 2b 2b 2b 2b </code></pre>
0
2016-09-12T18:34:30Z
[ "python", "pandas", "dataframe" ]
Add Name and Value in PDF Document Properties \ Custom with Reportlab
39,454,484
<p>I am wondering if is possible to add new Names &amp; Values (new attributes) to the PDF Document Properties \ Custom (AKA Metadata).</p> <p>I've been looking to the documentation but it seems they don't speak about it. Only the metadata Author, Keywords, etc inside Document Properties \ Description.</p> <p>Thanks in advance.</p>
0
2016-09-12T16:04:38Z
39,505,562
<p>It seems that this is not possible, I checked the source code which actually specifies the reason why:</p> <blockquote> <p>PDF documents can have basic information embedded, viewable from File | Document Info in Acrobat Reader. If this is wrong, you get Postscript errors while printing, even though it does not print.</p> </blockquote> <p><a href="https://bitbucket.org/rptlab/reportlab/src/d73ddcc5dba569ecc41770001c06d5ca9f447b7b/src/reportlab/pdfbase/pdfdoc.py?at=default&amp;fileviewer=file-view-default#pdfdoc.py-1525" rel="nofollow">Sourcecode</a></p> <p>As printing is one of the main goals of a PDF document (and not being able to print them sucks) it therefor makes sense to protect these properties.</p> <p>The only options that are available in the <code>PDFDocument</code> class are: <code>setTitle</code>, <code>setAuthor</code>, <code>setSubject</code>, <code>setCreator</code>, <code>setKeywords</code>, <code>setDateFormatter</code>. Most likely because these are the only one that are hard to get wrong.</p>
1
2016-09-15T07:43:49Z
[ "python", "reportlab" ]
How can I run a Jython script with Python
39,454,526
<p>I am programming in Python(2.7), processing a bunch of data. And I've got a software, what I have to use, and I want to start it automatically, and fill it up with data.</p> <p>The problem is, that I cant open it with Python, because it has API only for Jython. </p> <p>My question is, that how could I run a Jython script from a Python code(actually I am working on a standalone software)? Is it even possible?</p> <p>If it is, could you please give me a short example? How to install Jython and how to run a file from python?</p>
0
2016-09-12T16:07:51Z
39,489,547
<p>You can simply use Jython to run everything.</p> <p>Having <code>my_script.py</code> and <code>jython_script.py</code> edit <code>my_script.py</code> by adding <code>import jython_script</code> and adding call <code>jython_script.some_function()</code>.</p> <pre><code># my_script.py import jython_script def my_function_using_some_function_from_jython_script(): ... jython_script.some_function() ... </code></pre> <p>Then simply call:</p> <pre><code>jython my_script.py </code></pre> <p>I assume you do not use modules that work only with CPython.</p>
2
2016-09-14T11:41:12Z
[ "python", "python-2.7", "jython" ]
Divide two dataframes with python
39,454,542
<p>I have two dataframes : df1 and df2</p> <p>df1 : </p> <pre><code>TIMESTAMP eq1 eq2 eq3 2016-05-10 13:20:00 40 30 10 2016-05-10 13:40:00 40 10 20 </code></pre> <p>df2 : </p> <pre><code>TIMESTAMP eq1 eq2 eq3 2016-05-10 13:20:00 10 20 30 2016-05-10 13:40:00 10 20 20 </code></pre> <p>I would like to divide df1 by df2 : each column of df1 by all column of df2 to get this result df3 : </p> <pre><code>TIMESTAMP eq1 eq2 eq3 2016-05-10 13:20:00 40/(10+10) 30/(20+20) 10/(30+20) 2016-05-10 13:40:00 40/(10+10) 10/(20+20) 20/(30+20) </code></pre> <p>Any idea please ?</p>
2
2016-09-12T16:08:44Z
39,454,665
<p>This should work if <code>TIMESTAMP</code> is not the index:</p> <pre><code>&gt;&gt;&gt; df1.set_index('TIMESTAMP').div(df2.set_index('TIMESTAMP').sum()) eq1 eq2 eq3 TIMESTAMP 2016-05-10 13:20:00 2 0.75 0.2 2016-05-10 13:40:00 2 0.25 0.4 </code></pre> <p>If <code>TIMESTAMP</code> is the index, then simply this:</p> <pre><code>df1.div(df2.sum()) </code></pre>
1
2016-09-12T16:17:41Z
[ "python", "pandas", "dataframe", "multiple-columns", "division" ]
Divide two dataframes with python
39,454,542
<p>I have two dataframes : df1 and df2</p> <p>df1 : </p> <pre><code>TIMESTAMP eq1 eq2 eq3 2016-05-10 13:20:00 40 30 10 2016-05-10 13:40:00 40 10 20 </code></pre> <p>df2 : </p> <pre><code>TIMESTAMP eq1 eq2 eq3 2016-05-10 13:20:00 10 20 30 2016-05-10 13:40:00 10 20 20 </code></pre> <p>I would like to divide df1 by df2 : each column of df1 by all column of df2 to get this result df3 : </p> <pre><code>TIMESTAMP eq1 eq2 eq3 2016-05-10 13:20:00 40/(10+10) 30/(20+20) 10/(30+20) 2016-05-10 13:40:00 40/(10+10) 10/(20+20) 20/(30+20) </code></pre> <p>Any idea please ?</p>
2
2016-09-12T16:08:44Z
39,454,901
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a>, but before <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> from both columns <code>TIMESTAMP</code>:</p> <pre><code>df1.set_index('TIMESTAMP', inplace=True) df2.set_index('TIMESTAMP', inplace=True) print (df1.div(df2).reset_index()) TIMESTAMP eq1 eq2 eq3 0 2016-05-10 13:20:00 4.0 1.5 0.333333 1 2016-05-10 13:40:00 4.0 0.5 1.000000 </code></pre> <p>EDIT by comment:</p> <pre><code>df1.set_index('TIMESTAMP', inplace=True) df2.set_index('TIMESTAMP', inplace=True) print (df2.sum()) eq1 20 eq2 40 eq3 50 dtype: int64 print (df1.div(df2.sum()).reset_index()) TIMESTAMP eq1 eq2 eq3 0 2016-05-10 13:20:00 2.0 0.75 0.2 1 2016-05-10 13:40:00 2.0 0.25 0.4 </code></pre>
3
2016-09-12T16:34:17Z
[ "python", "pandas", "dataframe", "multiple-columns", "division" ]
Decorators in class methods: compatibility with 'getattr'
39,454,560
<p>I need to make wrappers for class methods, to be executed before and/or after the call of a specific method.</p> <p>Here is a minimal example:</p> <pre><code>class MyClass: def call(self, name): print "Executing function:", name getattr(self, name)() def my_decorator(some_function): def wrapper(): print("Before we call the function.") some_function() print("After we call the function.") return wrapper @my_decorator def my_function(self): print "My function is called here." engine = MyClass() engine.call('my_function') </code></pre> <p>This gives me an error at the line <code>getattr(self, name)()</code>: </p> <blockquote> <p>TypeError: 'NoneType' object is not callable</p> </blockquote> <p>If I comment out the decorator before the class method, it works perfectly:</p> <pre><code>class MyClass: def call(self, name): print "Executing function:", name getattr(self, name)() def my_decorator(some_function): def wrapper(): print("Before we call the function.") some_function() print("After we call the function.") return wrapper # @my_decorator def my_function(self): print "My function is called here." engine = MyClass() engine.call('my_function') </code></pre> <p>The output is:</p> <blockquote> <p>Executing function: my_function</p> <p>My function is called here.</p> </blockquote> <p>The decorator itself is identical to textbook examples. It looks like something goes wrong at a low level when calling a decorated method in Python with <code>getattr</code>.</p> <p>Do you have any ideas on how to fix this code?</p>
0
2016-09-12T16:09:31Z
39,454,612
<p>This has nothing to do with <code>getattr()</code>. You get the exact same error when you try to call <code>my_function()</code> directly:</p> <pre><code>&gt;&gt;&gt; engine.my_function() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'NoneType' object is not callable </code></pre> <p>You have 2 problems:</p> <ul> <li><p>Your decorator never returns the <code>wrapper</code>, so <code>None</code> is returned instead. This return value replaces <code>my_function</code> and is the direct cause of your error; <code>MyClass.my_function</code> is set to <code>None</code>:</p> <pre><code>&gt;&gt;&gt; MyClass.my_function is None True </code></pre></li> <li><p>Your wrapper takes no arguments, including <code>self</code>. You'll need this for it to work once you do return it properly.</p></li> </ul> <p>The first problem is fixed by un-indenting the <code>return wrapper</code> line; it is currently part of the <code>wrapper</code> function <em>itself</em>, and should be part of <code>my_decorator</code> instead:</p> <pre><code>def my_decorator(some_function): def wrapper(self): print("Before we call the function.") # some_function is no longer bound, so pass in `self` explicitly some_function(self) print("After we call the function.") # return the replacement function return wrapper </code></pre>
2
2016-09-12T16:14:03Z
[ "python", "oop", "metaprogramming", "decorator", "python-decorators" ]
Single origin value for python matplotlib plot
39,454,672
<p>I have a simple plot executed using matplotlib. My x and y axes start at 0,0 respectively. A matplotlib plot shows 2 zeros corresponding to the 2 axes. I want only one zero (somewhere in the middle of the start point, if possible). How can this be done?</p> <p>Here's what I used:</p> <pre><code>import matplotlib.pyplot as plt plt.plot([1,2,3], [4,5,6]) plt.xlim([0,5]) plt.ylim([0,10]) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/6gzPl.png" rel="nofollow"><img src="http://i.stack.imgur.com/6gzPl.png" alt="Matplotlib Plot"></a></p> <p>UPDATE: </p> <p>I used @nostradamus' solution and it got rid of one of the zeros. I want the zero a little centred if possible. </p> <p>I used: </p> <pre><code>plt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower')) plt.gca().yaxis.get_majorticklabels()[0].set_x(-0.05) </code></pre> <p><a href="http://i.stack.imgur.com/HIdBy.png" rel="nofollow"><img src="http://i.stack.imgur.com/HIdBy.png" alt="enter image description here"></a></p> <p>I want the reverse of this. I want the zero on the y axis to move down or the one from x axis left. So tried:</p> <pre><code>plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower')) plt.gca().xaxis.get_majorticklabels()[0].set_x(-0.05) </code></pre> <p>It doesn't work. I think the bottom and left boundaries for the zeros are set to ensure they don't go beyond the area.</p>
0
2016-09-12T16:18:31Z
39,464,894
<p>The keyword is <code>prune</code>, which allows you to kill the <code>upper</code>, <code>lower</code> or <code>both</code> tick labels. Here is a working examples that gets rid of the 0 of the x-axis:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator plt.plot([1,2,3], [4,5,6]) plt.xlim([0,5]) plt.ylim([0,10]) plt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower')) plt.show() </code></pre> <p>The second part (to move the remaining zero to the corner) seems to be much more difficult. It seems that you can move single tick labels using</p> <pre><code>plt.gca().yaxis.get_majorticklabels()[0].set_x(-0.05) </code></pre> <p>However, I was unable to figure out how to move it below the lower limit of the corresponding axis (i.e. <code>plt.gca().yaxis.get_majorticklabels()[0].set_y(-0.05)</code> is doing nothing).</p>
1
2016-09-13T07:56:07Z
[ "python", "matplotlib", "plot" ]
How to fetch json response from another url in django?
39,454,771
<p>I have created 2 views in django namely</p> <pre><code> def next_qn_url(request): test_result1 = 'questionansewrchoice' return JsonResponse({'test_result':test_result1}) def last_qn_url(request): test_result2 = 'questionansewrchoice' return JsonResponse({'test_result':test_result2}) def test(request): test = 'testchoice' return render(request, 'ap/test.html', {}) </code></pre> <p>i have also registered these views in urls.py</p> <pre><code>urlpatterns = [ url(r'^test/$', views.test, name='test'), url(r'^next_qn_url/$', views.test, name='next_qn_url'), url(r'^last_qn_url/$', views.test, name='last_qn_url'), url(r'.*', views.home, name='home'), ] </code></pre> <p>I send data from my test page to the other 2 views and try to fetch their json response and update my test page with the help of jquery getJSON function.</p> <pre><code> $.getJSON('/next_qn_url/', selected_qn_ans, function(data) { console.log(data); }); $.getJSON('/last_qn_url/', selected_qn_ans, function(data) { console.log(data); }); </code></pre> <p>I am just giving a rough draft here. But in the jsonresponse, i get the whole test page again and again with all html but not json. Is it not correct way to do it or guide me through this process. Thanks</p>
0
2016-09-12T16:25:01Z
39,465,350
<p>I'm not sure your urls are correct. The first 3 point to the same views.test Django view, which could explain why you get the test html continuously. In my understanding, calling the name of the url in the getJSON function is not the same as calling a view that happen to have a 'similar name'. The first argument in getJSON is an url name, not a view name. </p> <p>I would try the following modification, see the difference in the second &amp; third urls : </p> <pre><code>urlpatterns = [ url(r'^test/$', views.test, name='test'), url(r'^next_qn_url/$', views.next_qn_url, name='next_qn_url'), url(r'^last_qn_url/$', views.last_qn_url, name='last_qn_url'), url(r'.*', views.home, name='home'), ] </code></pre> <p>Hope it works. </p>
1
2016-09-13T08:22:01Z
[ "jquery", "python", "json", "ajax", "django" ]
How to divide a list into a given time step
39,454,811
<p>I have a list, e.g.</p> <pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5] </code></pre> <p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p> <p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed about splitting the list into equal parts, but in this case if we have delta t = 1, I want a list where 0.1 and 0.6 is together, and another for 1.5 etc.</p>
0
2016-09-12T16:28:01Z
39,455,042
<p>Here is a version that iterates through the list only once: </p> <pre><code>start = 0 delta = 1 stop = delta grouped = [] group = [] event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5] for val in event: if start &lt; val &lt; stop: group.append(val) else: while val &gt; stop: start += delta stop += delta grouped.append(group) group = [val] print(grouped) # [[0.1, 0.6], [1.5], [3.4, 3.8], [4.1], [6.2], [8.5]] </code></pre>
0
2016-09-12T16:44:10Z
[ "python", "list" ]
How to divide a list into a given time step
39,454,811
<p>I have a list, e.g.</p> <pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5] </code></pre> <p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p> <p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed about splitting the list into equal parts, but in this case if we have delta t = 1, I want a list where 0.1 and 0.6 is together, and another for 1.5 etc.</p>
0
2016-09-12T16:28:01Z
39,455,128
<p>First, make sure you list is sorted. Once you've done this, iterate through the list. Starting from the first value, create a new list containing all values from the first value to the final value that rests within the desired range. Then, jump to the index of that value and repeat. Given a delta t of 1, the list </p> <pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5] </code></pre> <p>will concatenate [0.1, 0.6] into a smaller list on the first step and begin the second step at [1.5], because 1.5 is the first value out of the range 1. Repeat this procedure until you have all of the smaller lists you need.</p>
0
2016-09-12T16:50:22Z
[ "python", "list" ]
How to divide a list into a given time step
39,454,811
<p>I have a list, e.g.</p> <pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5] </code></pre> <p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p> <p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed about splitting the list into equal parts, but in this case if we have delta t = 1, I want a list where 0.1 and 0.6 is together, and another for 1.5 etc.</p>
0
2016-09-12T16:28:01Z
39,455,213
<p>It look like you just want a list lists separated by the integers they are above/below. If that is the case then just use your "delta" in an conditional...loop through the list comparing each value to your delta, and keep a record of the index of your "current/active" list that you are inserting into. If the current value if less than the delta insert it. assuming that the initial list is sorted...</p> <pre><code> import math list_of_lists=[[]] active_index=0 for entry in event: if entry&lt;delta #use current delta and an outer loop if they are preset or increment delta by your step-size on each loop list_of_lists[active_index].append(entry) else: list_of_lists.append([]) active_index+=1 list_of_lists[active_index].append(entry) #seems like you want to go to the next highest int here: delta=math.ceil[entry] </code></pre>
0
2016-09-12T16:56:17Z
[ "python", "list" ]
How to divide a list into a given time step
39,454,811
<p>I have a list, e.g.</p> <pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5] </code></pre> <p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p> <p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed about splitting the list into equal parts, but in this case if we have delta t = 1, I want a list where 0.1 and 0.6 is together, and another for 1.5 etc.</p>
0
2016-09-12T16:28:01Z
39,455,236
<p>you can do this with <code>itertools.groupby</code> pretty easily:</p> <pre><code>from itertools import groupby event.sort() delta_t = 1 r = [list(v) for (k, v) in groupby(event, lambda v: v // delta_t)] </code></pre>
1
2016-09-12T16:58:10Z
[ "python", "list" ]
How to divide a list into a given time step
39,454,811
<p>I have a list, e.g.</p> <pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5] </code></pre> <p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p> <p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed about splitting the list into equal parts, but in this case if we have delta t = 1, I want a list where 0.1 and 0.6 is together, and another for 1.5 etc.</p>
0
2016-09-12T16:28:01Z
39,455,247
<p>Another possible solution:</p> <pre><code>from collections import defaultdict def split_list(lst, delta=1): start, end = 0, max(event) result = [] while start &lt; end: start += delta group = filter(lambda x: x &gt; (start - delta) and x &lt; start, event) if group: result.append(group) return result event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5] print split_list(event) # [[0.1, 0.6], [1.5], [3.4, 3.8], [4.1], [6.2], [8.5], [9.1, 9.5]] </code></pre>
1
2016-09-12T16:58:38Z
[ "python", "list" ]
Openerp workflow doesn't show last transition button
39,454,832
<p>I tried to edit my holiday work-flow and up do '<strong>validate</strong>' state it is working fine. But then I have added new node with transition , then the transition button does not appear to validate the work-flow. Please help me with this and relevant codes are bellow.</p> <p><strong><em>The last two nodes</em></strong> - hr_holidays_workflow.xml</p> <pre><code> &lt;record model="workflow.activity" id="act_validate"&gt; &lt;!-- accepted --&gt; &lt;field name="wkf_id" ref="wkf_holidays" /&gt; &lt;field name="name"&gt;validate&lt;/field&gt; &lt;field name="kind"&gt;function&lt;/field&gt; &lt;field name="action"&gt;holidays_validate()&lt;/field&gt; &lt;/record&gt; &lt;record model="workflow.activity" id="act_new_validate"&gt; &lt;!-- last --&gt; &lt;field name="wkf_id" ref="wkf_holidays" /&gt; &lt;field name="name"&gt;new_validate&lt;/field&gt; &lt;field name="kind"&gt;function&lt;/field&gt; &lt;field name="action"&gt;action_new_function()&lt;/field&gt; &lt;/record&gt; </code></pre> <p><strong><em>The last transition</em></strong> </p> <pre><code>&lt;record model="workflow.transition" id="holiday_new_validate"&gt; &lt;field name="act_from" ref="act_validate" /&gt; &lt;field name="act_to" ref="act_new_validate" /&gt; &lt;field name="signal"&gt;signal_last_validate&lt;/field&gt; &lt;field name="group_id" ref="base.group_hr_user"/&gt; &lt;/record&gt; </code></pre> <p><strong><em>Transition Button</em></strong> - hr_holidyas_view.xml</p> <pre><code> &lt;button string="Approved" type="workflow" name="last_validate" states="new_validate" class="oe_highlight"/&gt; &lt;field name="state" widget="statusbar" statusbar_visible="draft,confirm,validate,new_validate" statusbar_colors='{"confirm":"blue","validate1":"blue","new_validate":"blue","refuse":"red"}'/&gt; </code></pre> <p><strong>State declaration</strong> - hr_holidays.py</p> <pre><code> 'state': fields.selection([('draft', 'To Submit'), ('cancel', 'Cancelled'),('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate2', 'First Approval'),('validate1', 'Second Approval'), ('validate', 'Approval'),('new_validate','Appl')], 'Status', readonly=True, #track_visibility='onchange', </code></pre> <p><strong><em>The function</em></strong> - hr_holidays.py</p> <pre><code>def action_new_function(self, cr, uid, ids, context=None): res = self.write(cr, uid, ids, {'state': 'last_validate'}, context=context) return res </code></pre> <p><strong><em>UI</em></strong> Only refuse button is there not the "signal_last_validate" button <a href="http://i.stack.imgur.com/DFwXH.png" rel="nofollow"><img src="http://i.stack.imgur.com/DFwXH.png" alt="enter image description here"></a></p>
0
2016-09-12T16:29:36Z
39,469,251
<p>It was just I have used a wrong state in the button. </p> <pre><code>&lt;button string="Approved" type="workflow" name="last_validate" states="**new_validate**" class="oe_highlight"/&gt; </code></pre> <p>changed in to:</p> <pre><code>&lt;button string="Approved" type="workflow" name="last_validate" states="**validate**" class="oe_highlight"/&gt; </code></pre>
0
2016-09-13T11:46:20Z
[ "python", "xml", "openerp" ]
Python - accessing single database wrapper object from multiple objects
39,454,993
<p>I have a simple Python wrapper around a MySQL database, and I need to be able to access it from inside other custom class objects within Python. The wrapper class lives in a separate file to each of the other custom classes. So far I've only been able to find the following ways of doing things:</p> <ol> <li>Make the database object global (bad)</li> <li>Pass the database object into every other object's constructor (inelegant)</li> <li>Stop using the database wrapper class entirely (annoying)</li> </ol> <p>There must surely be a better way of doing this in Python (yes, I have searched the web and Stack Overflow, but apparently I'm searching for the wrong keywords). Can anyone explain what it is? I only need one database connection, and most of my other classes need to use it. Dummy Python code explaining the sort of thing I'm trying to do follows.</p> <p>(Partial) Database wrapper class:</p> <pre><code>import mysql.connector class Database: def __init__( self, username, password, database, host = 'localhost' ): self.connection = mysql.connector.connect( user = username, password = password, database = database, host = host ) self.connection.set_autocommit( True ) self.cursor = self.connection.cursor( dictionary = True ) def __del__( self ): self.cursor.close() self.connection.close() def fetchAll( self, query, constraints = None ): self.cursor.execute( query, constraints ) return self.cursor.fetchall() def delete( self, id, table, key = 'id' ): self.cursor.execute( 'DELETE FROM `' + table + '` WHERE `' + key + '` = %s', ( id, ) ) </code></pre> <p>Another class requiring access to the database (N.B. undeclared object <code>db</code> in class methods):</p> <pre><code>class Queue: def __init__( self ): self.jobs = [] def refreshJobs( self ): self.jobs = db.fetchAll( 'SELECT * FROM `jobs`' ) def deleteJob( self, id ): db.delete( id, 'jobs' ) self.refreshJobs() </code></pre> <p>A third class that accesses the database (N.B. undeclared object <code>db</code> in class methods):</p> <pre><code>class User: def __init__( self, email ): self.email = email details = db.fetchAll( 'SELECT * FROM `users` WHERE `email` = %s', [email] ) if( len( details ) == 1 ): self.password = details[0]['password'] </code></pre> <p>Any suggestions much appreciated, except framework recommendations. I'd really like to deepen my understanding of how best to handle this sort of situation in Python. Thanks in advance!</p>
0
2016-09-12T16:40:57Z
39,571,848
<p>Answering my own question since no one responded, and this might be useful to other people in future. I was recommended to use a "half-way" global, by writing an intermediary module that looks something like this:</p> <pre><code>from my_db_class import Database db = Database( 'user', 'password', 'database' ) </code></pre> <p>Then in <code>Queue</code> and <code>User</code> classes, do something like this:</p> <pre><code>from my_db_instantiation import db </code></pre> <p>You can then access the same <code>db</code> database object in each of the classes that requires it. Note that only <code>my_db_intermediary</code> imports <code>my_db_class</code> directly. All other modules import <code>my_db_intermediary</code>. It might seem a bit convoluted but it allows you to keep your class implementations separate from the parameters required to instantiate them, in this case the database class and its associated credentials.</p>
0
2016-09-19T11:15:00Z
[ "python", "mysql", "database", "mysql-connector-python" ]
Python 3 Print Update on multiple lines
39,455,022
<p>Is it possible to print and update more than one line? This works for one line:</p> <pre><code>print ("Orders: " + str(OrderCount) + " Operations: " + str(OperationCount), end="\r") </code></pre> <p>and get this: (Of course the numbers update because its in a loop)</p> <pre><code>Orders: 25 Operations: 300 </code></pre> <p>I have tried this:</p> <pre><code>print ("Orders: " + str(OrderCount) + "\rOperations: " + str(OperationCount), end="\r\r") </code></pre> <p>and get this: (The number does update correctly)</p> <pre><code>Operations: 300 </code></pre> <p>Looking for two lines that are updated like:</p> <pre><code>Orders: 25 Operations: 300 </code></pre> <p>and not:</p> <pre><code>Orders: 23 Operations: 298 Orders: 24 Operations: 299 Orders: 25 Operations: 300 </code></pre>
0
2016-09-12T16:42:38Z
39,455,032
<p><code>\r</code> is a <em>carriage return</em>, where the cursor moves to the start of the line (column 0). From there, writing more text will overwrite what was written before, so you end up only with the last line (which is long enough to overwrite everything you've written before).</p> <p>You want <code>\n</code>, a newline, which moves to the next line (and starts at column 0 again):</p> <pre><code>print ("Orders: " + str(OrderCount) + "\nOperations: " + str(OperationCount), end="\n\n") </code></pre> <p>Rather than use <code>str()</code> and <code>+</code> concatenation, consider using string templating with <a href="https://docs.python.org/3/library/stdtypes.html#str.format" rel="nofollow"><code>str.format()</code></a>:</p> <pre><code>print("Orders: {}\nOperations: {}\n".format(OrderCount, OperationCount)) </code></pre> <p>Note that you <em>can't</em> go back up a line; if you wanted to use <code>\r</code> carriage returns to update two lines, then you are out of luck with straight-up printing. You'll need to switch to a full-terminal control with <a href="https://docs.python.org/3/howto/curses.html" rel="nofollow">Curses</a> or stick to putting everything on one line.</p> <p>If you are going to go the Curses route, take into account that Windows compatibility is sketchy at best.</p>
3
2016-09-12T16:43:35Z
[ "python" ]
Python 3 Print Update on multiple lines
39,455,022
<p>Is it possible to print and update more than one line? This works for one line:</p> <pre><code>print ("Orders: " + str(OrderCount) + " Operations: " + str(OperationCount), end="\r") </code></pre> <p>and get this: (Of course the numbers update because its in a loop)</p> <pre><code>Orders: 25 Operations: 300 </code></pre> <p>I have tried this:</p> <pre><code>print ("Orders: " + str(OrderCount) + "\rOperations: " + str(OperationCount), end="\r\r") </code></pre> <p>and get this: (The number does update correctly)</p> <pre><code>Operations: 300 </code></pre> <p>Looking for two lines that are updated like:</p> <pre><code>Orders: 25 Operations: 300 </code></pre> <p>and not:</p> <pre><code>Orders: 23 Operations: 298 Orders: 24 Operations: 299 Orders: 25 Operations: 300 </code></pre>
0
2016-09-12T16:42:38Z
39,455,043
<p>You probably want <code>\n</code> instead of <code>\r</code>. <code>\r</code> is "carriage return", a.k.a. "go back to the beginning of the line" -- so you're print "Operations" over "Orders".</p>
0
2016-09-12T16:44:25Z
[ "python" ]
sqlalchemy empty schema and no tables
39,455,048
<p>I am trying to use sqlalchemy via a Database first approach and generate the models for the existing database structure. The db is a standard SQLServer(express).</p> <p>I can connect to my database and query it via the following</p> <pre><code>from sqlalchemy import create_engine, MetaData, Table from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base __connectionString = "DSN=databaseDSN;Trusted_Connection=yes" db_engine = create_engine('mssql+pyodbc:///?odbc_connect=%s' % __connectionString, echo=True) db_session = scoped_session(sessionmaker(bind=db_engine)) result = db_session.execute("SELECT * FROM debug.BasicTable") for row in result.fetchmany(10): print(row) </code></pre> <p>When I try to reflect the database structure below I am unable to see any of the actual tables and the following raises a NoSuchTableError </p> <pre><code>myTable= Table('debug.BasicTable', meta, autoload=True, autoload_with=db_engine) </code></pre> <p>from a common tutorial <a href="http://pythoncentral.io/sqlalchemy-faqs/" rel="nofollow">http://pythoncentral.io/sqlalchemy-faqs/</a></p> <p>I should be able to reflect the table objects </p> <pre><code>Base = declarative_base() Base.metadata.reflect(db_engine) meta = MetaData() meta.reflect(bind=db_engine) </code></pre> <p>However there are no table objects in meta.tables at all.</p>
0
2016-09-12T16:44:35Z
39,455,113
<p>This is because <code>debug.BasicTable</code> is most likley not the name of your table. The name of your table is <code>BasicTable</code> and <code>debug</code> is its schema. So:</p> <pre><code>Table('BasicTable', meta, schema="debug", autoload=True, autoload_with=db_engine) </code></pre>
1
2016-09-12T16:49:36Z
[ "python", "sql-server", "sqlalchemy" ]
.py config file with fallback data?
39,455,068
<p>I have a <code>settings.py</code> file in my project:</p> <pre><code>"Nickname of the user to check the games for" USERNAME = "user" </code></pre> <p>Unfortunately, it will be overwritten by each upgrade. So, I'd like to allow the user to override the default settings by creating a <code>.py</code> file <code>$XDG_CONFIG_HOME/myapp/config.py</code>, containing for example</p> <pre><code>USERNAME = "real-user" </code></pre> <p>Is it possible to modify <code>settings.py</code> so that it sucks any variables from the <code>.../config.py</code> file in a generic way, something like including this file at the end of <code>config.py</code>?</p> <p>I'm using Python 3</p>
0
2016-09-12T16:46:02Z
39,455,595
<p>I assume the way you get the values from the <code>settings.py</code> file is by <code>import</code>ing it:</p> <pre><code>import settings print(settings.USERNAME) </code></pre> <p>Then you could change it by adding something like this to the end which will do what you want.</p> <p><strong><code>settings.py</code></strong> </p> <pre><code>"Nickname of the user to check the games for" USERNAME = "user" def _read_overrides(filename): localdict = {} # populated by exec try: with open(filename) as file: exec(compile(file.read(), filename, 'exec'), {'__builtins__': None}, localdict) except FileNotFoundError: pass return localdict for key, value in _read_overrides('config.py').items(): globals()[key] = value </code></pre> <p>Then after it's <code>import</code>ed, the <code>print(settings.USERNAME)</code> will display:</p> <pre><code>real-user </code></pre> <p>Also note the <code>config.py</code> overrides file can be named anything (it's doesn't need a <code>.py</code> extension).</p>
1
2016-09-12T17:23:56Z
[ "python", "python-3.x", "settings" ]
Python zip - Why do we need to unpack the argument?
39,455,100
<p>I'm trying to understand the need to unpack the arguments using <code>*</code> when the input to <code>zip</code> is a 2D list. The <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow">docs</a> state,</p> <blockquote> <p>[zip] Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.</p> </blockquote> <p>So, regarding the second <code>print</code> statement below, I expected it to be just like the ones before and after it. I am having trouble connecting the description of <code>zip</code> to this result.</p> <p>MWE: </p> <pre><code>x = [1, 2, 3] y = [4, 5, 6] print zip(x, y) print zip([x, y]) # don't understand this result print zip(*[x, y]) </code></pre> <p>Result:</p> <pre><code>[(1, 4), (2, 5), (3, 6)] [([1, 2, 3],), ([4, 5, 6],)] [(1, 4), (2, 5), (3, 6)] </code></pre>
0
2016-09-12T16:47:54Z
39,455,396
<p>Consider this example:</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3] &gt;&gt;&gt; y = [4, 5, 6] &gt;&gt;&gt; z = [7, 8, 9] &gt;&gt;&gt; zip(x,y,z) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] &gt;&gt;&gt; zip(x,y) [(1, 4), (2, 5), (3, 6)] &gt;&gt;&gt; zip(x) [(1,), (2,), (3,)] &gt;&gt;&gt; zip() [] </code></pre> <p>Observe that <code>zip</code> with a single argument (and even with no arguments!) follows the same pattern. It always returns a sequence of tuples, where the tuples (if there are any) have the same number of members as the arguments to <code>zip</code>. Even when there's only one argument to <code>zip</code>.</p> <p>Now consider the case you're asking about:</p> <pre><code>zip([x, y]) </code></pre> <p>This is just <code>zip</code> with one argument! <code>Zip</code> isn't going to try to be clever and poke about inside the elements of the sequence you give it. It doesn't know or care that the elements of the sequence you gave it are themselves sequences. <code>Zip</code> is (thankfully!) simple and predictable. If you give it one argument it returns you a sequence of 1-tuples. In this case those 1-tuples contain a list each, but again, <code>zip</code> doesn't care! They could be strings or numbers or <code>None</code> or anything!</p> <pre><code>&gt;&gt;&gt; zip([x, y]) [([1, 2, 3],), ([4, 5, 6],)] &gt;&gt;&gt; zip([x, 'marmalade']) [([1, 2, 3],), ('marmalade',)] &gt;&gt;&gt; zip([None, y]) [(None,), ([4, 5, 6],)] </code></pre>
5
2016-09-12T17:08:27Z
[ "python" ]
Increase the number of columns in a list of dictionaries
39,455,106
<p>I don't know the exact words to phrase this in a more scientific way, so please feel free to help me out with my poor grammar.</p> <p>My problem is the following: I have constructed a table out of a list of dictionaries like so:</p> <pre><code>for d in listDictionary: print d {'key1':'value11', 'key2':'value12', ..., 'keyM':'value1M'} {'key1':'value21', 'key2':'value22', ..., 'keyM':'value2M'} ... {'key1':'valueN1', 'key2':'valueN2', ..., 'keyM':'valueNM'} </code></pre> <p>For simplicity, you can picture this as an <code>N*M</code> matrix. Like so:</p> <pre><code>key1 key2 ... keyM value11 value12 ... value1M value21 value22 ... value2M ... valueN1 valueN2 ... valueNM </code></pre> <p><strong>Now</strong>, here's the real problem. Some of the values need further processing but it's not always clear how much more. For example, let's pick the <code>Ith</code> value from keyK. <code>0&lt;K&lt;M, 0&lt;I&lt;N</code> therefore we have <code>valueIK</code>.</p> <p><code>valueIK</code> will be either <code>n/a</code> or represent a tree with <code>siblings</code> and <code>children</code>.</p> <p>The tree representation is something like this:</p> <pre><code>root1 -&gt; somevalue1 root2 -&gt; somevalue2 root3 -&gt; somevalue3 </code></pre> <p>So in plain text, <code>valueIK</code> will be: <code>root1&gt;somevalue1;root2&gt;somevalue2;root3&gt;somevalue3;</code> I want to be able to expand the matrix/listDictionary because valueIK has more items than the initial assumption. But in order to maintain a constant size in the dictionary the other entries in the list have to be updated as well.</p> <p>ex. If we have this as our initial matrix</p> <pre><code>key1 key2 ... keyK ... keyM value11 value12 ... ... value1M value21 value22 ... ... value2M ... valueIK valueN1 valueN2 ... ... valueNM </code></pre> <p>I want to accomplish something like this:</p> <pre><code>key1 key2 ... keyK root1 root2 ... keyM value11 value12 ... n/a whatevervalue ... value1M value21 value22 ... someothervalue n/a ... value2M ... valueIK somevalue1 n/a valueN1 valueN2 ... n/a helloWorld ... valueNM </code></pre> <p>In other words, the rest of the entries <strong>might</strong> have some values under the key <code>root_</code> and we <strong>don't</strong> want to alter them but if they have nothing we have to fill the matrix cell with <code>'n/a'</code></p> <p>Sorry for the very long and technical post. I tried to be as analytical as I could be. I can't figure out a way to do this on my own, that's why I'm asking for help. </p> <p>Thanks :)</p>
0
2016-09-12T16:48:54Z
39,455,816
<p>Firstly, the simple answer:</p> <p>If you want to set only unset values, there's a <code>dict.setdefault</code> method. For example, given <code>dict5</code> as the fifth row (containing <code>value51</code>, <code>value52</code>, etc.), and that you want to update the column <code>root1</code>:</p> <pre><code># returns the value of dict5['root1'], setting it to 'n/a' if it didn't exist at all dict5.setdefault('root1', 'n/a') </code></pre> <p>However, a note: Since you're building your table out of dictionaries for each row, you shouldn't actually need to set unused things to <code>'n/a'</code> in most cases - you can safely leave elements of one dictionary unset and set things in another, because none of the dictionaries are actually checking each other. This will save memory, and you won't need to spend time setting all the empties. Just make sure that when you're getting things out, you use <code>get</code> instead of <code>[]</code>, e.g.:</p> <pre><code># Returns dict5['root1'], but returns 'n/a' if that doesn't exist. dict5.get('root1', 'n/a') </code></pre> <p>If you do that, though, you will have to keep a separate list of all the columns somewhere and loop through that, if you were previously looping through each dict somehow, e.g.:</p> <pre><code># Prints each cell of the table on a new line, including 'n/a' for empty cells columns = ['key1', 'key2', 'key3'] for d in listDictionary: for c in columns: print d.get(c, 'n/a') # Instead of: for d in listDictionary: for c in d: # Only gets the keys that exist in that particular dict, so no 'n/a's print d.get[c] </code></pre>
0
2016-09-12T17:40:01Z
[ "python", "dictionary" ]
Increase the number of columns in a list of dictionaries
39,455,106
<p>I don't know the exact words to phrase this in a more scientific way, so please feel free to help me out with my poor grammar.</p> <p>My problem is the following: I have constructed a table out of a list of dictionaries like so:</p> <pre><code>for d in listDictionary: print d {'key1':'value11', 'key2':'value12', ..., 'keyM':'value1M'} {'key1':'value21', 'key2':'value22', ..., 'keyM':'value2M'} ... {'key1':'valueN1', 'key2':'valueN2', ..., 'keyM':'valueNM'} </code></pre> <p>For simplicity, you can picture this as an <code>N*M</code> matrix. Like so:</p> <pre><code>key1 key2 ... keyM value11 value12 ... value1M value21 value22 ... value2M ... valueN1 valueN2 ... valueNM </code></pre> <p><strong>Now</strong>, here's the real problem. Some of the values need further processing but it's not always clear how much more. For example, let's pick the <code>Ith</code> value from keyK. <code>0&lt;K&lt;M, 0&lt;I&lt;N</code> therefore we have <code>valueIK</code>.</p> <p><code>valueIK</code> will be either <code>n/a</code> or represent a tree with <code>siblings</code> and <code>children</code>.</p> <p>The tree representation is something like this:</p> <pre><code>root1 -&gt; somevalue1 root2 -&gt; somevalue2 root3 -&gt; somevalue3 </code></pre> <p>So in plain text, <code>valueIK</code> will be: <code>root1&gt;somevalue1;root2&gt;somevalue2;root3&gt;somevalue3;</code> I want to be able to expand the matrix/listDictionary because valueIK has more items than the initial assumption. But in order to maintain a constant size in the dictionary the other entries in the list have to be updated as well.</p> <p>ex. If we have this as our initial matrix</p> <pre><code>key1 key2 ... keyK ... keyM value11 value12 ... ... value1M value21 value22 ... ... value2M ... valueIK valueN1 valueN2 ... ... valueNM </code></pre> <p>I want to accomplish something like this:</p> <pre><code>key1 key2 ... keyK root1 root2 ... keyM value11 value12 ... n/a whatevervalue ... value1M value21 value22 ... someothervalue n/a ... value2M ... valueIK somevalue1 n/a valueN1 valueN2 ... n/a helloWorld ... valueNM </code></pre> <p>In other words, the rest of the entries <strong>might</strong> have some values under the key <code>root_</code> and we <strong>don't</strong> want to alter them but if they have nothing we have to fill the matrix cell with <code>'n/a'</code></p> <p>Sorry for the very long and technical post. I tried to be as analytical as I could be. I can't figure out a way to do this on my own, that's why I'm asking for help. </p> <p>Thanks :)</p>
0
2016-09-12T16:48:54Z
39,456,148
<p>If I've understood the question correctly, perhaps this might work:</p> <pre><code>data = [ { 'k1': 'root3&gt;rv11;root1&gt;rv12', 'k2': 'v12', 'k3': 'v13'}, { 'k1': 'v21', 'k2': 'root1&gt;rv21;root2&gt;rv22;', 'k3': 'v23'}, { 'k1': 'v31', 'k2': 'v32', 'k3': 'root2&gt;rv32;'} ] newkeys = set() for item in data: add = {} for k, v in item.items(): if '&gt;' in v: fields = v.strip(';').split(';') add.update(dict(f.split('&gt;') for f in fields)) newkeys |= set(add.keys()) item.update(add) for nk in newkeys: for item in data: if nk not in item: item[nk] = None print(data) </code></pre>
0
2016-09-12T18:01:47Z
[ "python", "dictionary" ]
Kivy non-GUI events
39,455,119
<p>i am trying to start an animation when the app is first loaded. I.E. immediately after the loading screen has closed. I have tired the "on_enter" event but it doesn't seem to work, any help would be much appreciated.</p> <pre><code>from kivy.base import runTouchApp from kivy.lang import Builder from kivy.uix.widget import Widget from kivy.animation import Animation from kivy.properties import ListProperty from kivy.core.window import Window from random import random from kivy.graphics import Color, Rectangle Builder.load_string(''' &lt;Root&gt;: AnimRect: pos: 500, 300 &lt;AnimRect&gt;: on_enter: self.start_animation canvas: Color: rgba: 0, 1, 0, 1 Rectangle: pos: self.pos size: self.size ''') class Root(Widget): pass class AnimRect(Widget): def anim_to_random_pos(self): Animation.cancel_all(self) random_x = random() * (Window.width - self.width) random_y = random() * (Window.height - self.height) anim = Animation(x=random_x, y=random_y, duration=4, t='out_elastic') anim.start(self) def on_touch_down(self, touch): if self.collide_point(*touch.pos): self.anim_to_random_pos() def start_animation(self, touch): if self.collide_point(*touch.pos): self.anim_to_random_pos() runTouchApp(Root()) </code></pre> <p><a href="http://i.stack.imgur.com/8vPEC.png" rel="nofollow"><img src="http://i.stack.imgur.com/8vPEC.png" alt="print screen of error"></a></p>
0
2016-09-12T16:49:49Z
39,455,849
<p>The <code>on_enter</code> method is defined in the <code>Screen</code>, not in the <code>Widget</code>. You should put that rectangle on a screen (the <code>Root</code> widget should be a screen here), and once the screen's <code>on_enter</code> event fires, start the rectangle animation.</p> <p>Also, you are calling it incorrectly; function call should contain brackets, i.e. <code>on_enter: self.start_animation()</code></p>
0
2016-09-12T17:42:41Z
[ "python", "events", "event-handling", "kivy", "kivy-language" ]
How to make a pdb set_trace the first breakpoint
39,455,167
<p>I have pdb.set_trace() in two spots of my code. The problem is that I get multiple stops in the second area when I want it to start somewhere specific. Here is an example:</p> <pre><code>def function(): #some code in here pdb.set_trace() #some more code def main(): #some code function() #come more code function() #the code I care about pdb.set_trace() function() </code></pre> <p>The problem here is that it will stop in function twice before actually getting to the actual set_trace I want to which first stops inside main and then to function. </p> <p>This isn't a big deal but in a real setting I get 100s of calls to inside of 'function' before getting to the 'main' set_trace(). Is there a way to specify the first set_trace() or ignore all calls to set_trace until I get to the one I want?</p>
0
2016-09-12T16:53:11Z
39,459,884
<p>You need not modify your code (by adding calls to <code>pdb.set_trace()</code>) in order to debug it with <code>pdb</code> (the advice to do that has always seemed misguided to me). <a href="http://stackoverflow.com/q/34914704/5384908">This question</a> is another example of a problem this approach can cause.</p> <p>If you invoke <code>pdb</code> on a version of your code with no calls to <code>pdb.set_trace()</code> and use <code>pdb</code>'s <code>break</code> command to set breakpoints wherever you might otherwise have added calls to <code>pdb.set_trace()</code>, you can use <code>pdb</code>'s <code>disable</code> command when you no longer want a breakpoint to take effect.</p>
0
2016-09-12T22:51:42Z
[ "python", "pdb" ]
Odoo - Change domain on inherited view
39,455,189
<p>I am currently working on building a custom module, and I extended the unit of measure class (product.uom). I want some uom entries to be removed from the list/tree views, based on a specific value for one of my new variables.</p> <p>I am not entirely sure how to modify this view. I seem to be reading that I need to specify a domain, like domain = [("myvariable","=",True)], but I'm not entirely sure how to apply this. I tried inheriting the tree view, and adding a domain, but this doesn't work.</p> <p>Any help would be greatly appreciated.</p> <p>Solution:</p> <pre class="lang-xml prettyprint-override"><code>&lt;record model="ir.actions.act_window" id="uom_list_action"&gt; &lt;field name="name"&gt;Units Of Measurement&lt;/field&gt; &lt;field name="res_model"&gt;product.uom&lt;/field&gt; &lt;field name="domain"&gt;[("myvariable","!=",True)]&lt;/field&gt; &lt;field name="view_mode"&gt;tree,form&lt;/field&gt; &lt;/record&gt; &lt;record model="ir.ui.menu" id="product.menu_product_uom_form_action"&gt; &lt;field name="action" ref="uom_list_action"/&gt; &lt;/record&gt; &lt;record model="ir.ui.menu" id="stock.menu_stock_uom_form_action"&gt; &lt;field name="action" ref="uom_list_action"/&gt; &lt;/record&gt; </code></pre>
1
2016-09-12T16:54:59Z
39,459,866
<p>In order to do what Nross2781 is looking for you have to override the ir.actions.act_window for the record. </p> <pre><code>&lt;record model="ir.actions.act_window" id="uom_list_action"&gt; &lt;field name="name"&gt;Units Of Measurement&lt;/field&gt; &lt;field name="res_model"&gt;product.uom&lt;/field&gt; &lt;field name="domain"&gt;[("myvariable","!=",True)]&lt;/field&gt; &lt;field name="view_mode"&gt;tree,form&lt;/field&gt; &lt;/record&gt; </code></pre> <p>However you may want to consider adding filters to a search view which would be more flexible. You would also be able to see the records which do not show up by default.</p> <pre><code>&lt;record model="ir.ui.view" id="uom_search_view"&gt; &lt;field name="name"&gt;uom.search&lt;/field&gt; &lt;field name="model"&gt;product.uom&lt;/field&gt; &lt;field name="arch" type="xml"&gt; &lt;search string="Units Of Measurement"&gt; &lt;filter name="my_var_is_true" string="My Variable" domain="[('myvariable','=',True)]"/&gt; &lt;filter name="my_var_is_false" string="Not My Variable" domain="[('myvariable','!=',True)]"/&gt; &lt;/search&gt; &lt;/field&gt; &lt;/record&gt; </code></pre>
1
2016-09-12T22:48:19Z
[ "python", "filter", "openerp" ]
Difficulties in installation of pysparse and superlu
39,455,263
<p>I want to run a python2.7 program (<a href="https://github.com/williamhunter/topy" rel="nofollow">this one</a>). I'm having a lot of trouble (I spend my whole aftenoon on this), because of the installation of the python 2.7 dependencies.</p> <p><strong>Config</strong></p> <p>I am running an Ubuntu 16.04 64bits ([Mint XFCE 18), based on Debian. My computer is a Dell Inspiron N5110 from 2011, with dual boot W7/U16. The keyboard-to-screen interface is really new in this world and perhaps need to learn a lot more about it to solve this alone.</p> <p><strong>Proceeds</strong></p> <p>I started by installing various programs with apt:</p> <p><code>sudo apt-get install -y git python-dev libpython-dev libevent-dev libsuperlu-dev libblas-dev liblapack-dev</code></p> <p>After <em>git cloning</em> the program I wanted, I installed the dependencies. I don't know why, but <code>sudo pip install pysparse</code> didn't worked. Instead, <code>sudo pip install csc-pysparse</code> worked fine.</p> <p><strong>Issue</strong></p> <p>When I run my program, it tells me <code>from pysparse import superlu, itsolvers, precon</code> and then <code>ImportError: cannot import name superlu</code>.</p> <p>Why ? Isn't the pip resolving the dependencies problems it could have and install superlu ? Do I need to install superlu manually or to install the pysparse instead of csc-pysparse ?</p> <p>(and please be indulgent, It's my really first post on stackoverflow, as <a href="https://github.com/williamhunter/topy/issues/9" rel="nofollow" title="github issue">thoses</a> were my really firsts posts on github)</p>
0
2016-09-12T17:00:02Z
39,471,269
<p>I did get an <a href="https://github.com/williamhunter/topy/issues/9" rel="nofollow">answer</a>, thanks to <a href="https://github.com/williamhunter" rel="nofollow" title="William Hunter&#39;s profile on Github">William Hunter</a>.</p> <p>The procedure to install it is the following :</p> <pre><code>sudo apt-get install -y python-dev python-tk libpython-dev libevent-dev libsuperlu-dev libblas-dev liblapack-dev libatlas3-base libatlas-dev sudo pip install matplotlib setuptools SymPy pysparse pyvtk </code></pre>
0
2016-09-13T13:24:46Z
[ "python", "python-2.7", "pip", "python-module", "finite-element-analysis" ]
Normalisation of data
39,455,299
<p>I am trying to plot the data below in a pie chart. I split the pie chart based on the group first and then based on the Id. But since for some rows, the count is very small, I am not able to see it in the pie chart. </p> <p>I am trying to normalise the data. I am not sure on how to do that. Any help would be sincerely appreciated. </p> <pre><code> Group Id Count G1 12 276938 G1 13 102 G2 12 27 G3 12 4683 G3 13 7 G4 12 301 </code></pre>
1
2016-09-12T17:02:16Z
39,455,469
<p>Don't pie chart what doesn't fit a visual representation in a pie chart</p> <pre><code>( df.groupby(['Group', 'Id']) .sum().Count.sort_values(ascending=False) .plot.bar(logy=True, subplots=True) ) </code></pre>
3
2016-09-12T17:14:13Z
[ "python", "pandas", "normalization" ]
Error in reading and writing files in Python
39,455,343
<p>I am trying to convert files from one format to other in Python. The current format is DAQ (data acquisition format), which is read in first. Then I use <code>undaq Tools</code> module to write the files to hdf5 format. </p> <pre><code>import glob ctnames = glob.glob('*.daq') </code></pre> <p>Following are the few filenames (there are 100 in total):</p> <pre><code>ctnames ['Cars_20160601_01.daq', 'Cars_20160601_02.daq', 'Cars_20160601_03.daq', 'Cars_20160601_04.daq', 'Cars_20160601_05.daq', 'Cars_20160601_06.daq', 'Cars_20160601_07.daq', . . . ## Importing undaq tools: from undaqTools import Daq </code></pre> <h2>Reading the DAQ files and writing to hdf5:</h2> <pre><code>for n in ctnames: x = daq.read(n) daq.write_hd5(x) </code></pre> <p>Following is the error I got: </p> <pre><code>C:\Anaconda3\envs\py27\lib\site-packages\undaqtools-0.2.3-py2.7.egg\undaqTools\daq.py:405: RuntimeWarning: Failed loading file on frame 46970. (stopped reading file) --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) &lt;ipython-input-17-6fe7a8c9496d&gt; in &lt;module&gt;() 1 for n in ctnames: ----&gt; 2 x = daq.read(n) 3 daq.write_hd5(x) C:\Anaconda3\envs\py27\lib\site-packages\undaqtools-0.2.3-py2.7.egg\undaqTools\daq.pyc in read_daq(self, filename, elemlist, loaddata, process_dynobjs, interpolate_missing_frames) 272 273 if loaddata: --&gt; 274 self._loaddata() 275 self._unwrap_lane_deviation() 276 C:\Anaconda3\envs\py27\lib\site-packages\undaqtools-0.2.3-py2.7.egg\undaqTools\daq.pyc in _loaddata(self) 449 assert tmpdata[name].shape[0] == frame.frame.shape[0] 450 else: --&gt; 451 assert tmpdata[name].shape[1] == frame.frame.shape[0] 452 453 # cast as Element objects AssertionError: </code></pre> <h1>Questions</h1> <p>I have 2 questions:<br> 1. How do I know which of the 100 files is throwing the error?<br> 2. How do I skip the files if they throw the error?</p>
0
2016-09-12T17:04:42Z
39,455,492
<p>Wrap the <code>read()</code> call in a try/except block. If you get an exception, print the current filename and skip to the next one.</p> <pre><code>for n in ctnames: try: x = daq.read(n) except AssertionError: print 'Could not process file %s. Skipping.' % n continue daq.write_hd5(x) </code></pre>
1
2016-09-12T17:15:56Z
[ "python" ]
wxPython: pause main script and wait for button press
39,455,361
<p>I am working on a GUI using wxPython. This GUI should dynamically ask to the user several sets of inputs in the same window, updating the window with the new set of inputs after a button "ok" is pressed.</p> <p>To do this I have a for loop which calls a function that prompts the input controls on the window. I have tried to use the <code>threading.Event</code> class, letting the script wait for the button to be pressed, but python crashes.</p> <p>Here below is the interested part of the code.</p> <pre><code> # Iterate through parameters self.cv = threading.Event() for key in parameters: self.input_sizer = [None]*len(parameters[key]) self.cv.clear() self.make_widgets(key, parameters[key]) self.cv.wait() # Panel final settings self.panel.SetSizer(self.main_sizer) self.main_sizer.SetSizeHints(self) def make_widgets(self, request, parameters): # Function for widget prompting on the panel self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.controls = {"request": wx.StaticText(self.panel, label="Please type the new alias' " + request), "txt": [None]*len(parameters), "tc": [None]*len(parameters)} self.main_sizer.Add(self.controls["request"], 1, wx.ALL, 10) for i in range(len(parameters)): self.input_sizer[i] = wx.BoxSizer(wx.HORIZONTAL) self.main_sizer.Add(self.input_sizer[i], 1, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) # Text self.controls['txt'][i] = wx.StaticText(self.panel, label=parameters[i]) self.input_sizer[i].Add(self.controls["txt"][i], 0, wx.ALIGN_CENTER | wx.LEFT, 10) # Input self.controls['tc'][i] = wx.TextCtrl(self.panel) self.input_sizer[i].Add(self.controls["tc"][i], 0, wx.ALIGN_CENTER) # Ok button self.button_ok = wx.Button(self.panel, label="Ok") self.main_sizer.Add(self.button_ok, 1, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) self.button_ok.Bind(wx.EVT_BUTTON, self.carry_on) def carry_on(self, event): self.cv.set() </code></pre> <p>Does anyone has any idea?</p> <p>Thanks, here below there's the complete code.</p> <pre><code>import wx from collections import OrderedDict import threading ############################################################################ class AddMainName(wx.Frame): # Class definition for main Name addition def __init__(self, parent, title): # Constructor super().__init__(parent, title=title) # Run the name addition self.set_alias_name() self.Centre() self.Show() def set_alias_name(self): # Function for definition of alias name # Panel self.panel = wx.Panel(self) # Lists of parameters to be typed parameters = OrderedDict([("name parts", [ "Prefix", "Measurement", "Direction", "Item", "Location", "Descriptor", "Frame", "RTorigin" ]), ("SI units", [ "A", "cd", "K", "kg", "m", "mol", "Offset", "rad", "s", "ScaleFactor" ]), ("normal display unit", [ "A", "cd", "K", "kg", "m", "mol", "Offset", "rad", "s", "ScaleFactor" ]), ("other parameters", [ "Meaning", "Orientation Convention", "Contact Person", "Note", ])]) # Iterate through parameters self.cv = threading.Event() for key in parameters: self.input_sizer = [None]*len(parameters[key]) self.cv.clear() self.make_widgets(key, parameters[key]) self.cv.wait() # Panel final settings self.panel.SetSizer(self.main_sizer) self.main_sizer.SetSizeHints(self) def make_widgets(self, request, parameters): # Function for widget prompting on the panel self.main_sizer = wx.BoxSizer(wx.VERTICAL) self.controls = {"request": wx.StaticText(self.panel, label="Please type the new alias' " + request), "txt": [None]*len(parameters), "tc": [None]*len(parameters)} self.main_sizer.Add(self.controls["request"], 1, wx.ALL, 10) for i in range(len(parameters)): self.input_sizer[i] = wx.BoxSizer(wx.HORIZONTAL) self.main_sizer.Add(self.input_sizer[i], 1, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) # Text self.controls['txt'][i] = wx.StaticText(self.panel, label=parameters[i]) self.input_sizer[i].Add(self.controls["txt"][i], 0, wx.ALIGN_CENTER | wx.LEFT, 10) # Input self.controls['tc'][i] = wx.TextCtrl(self.panel) self.input_sizer[i].Add(self.controls["tc"][i], 0, wx.ALIGN_CENTER) # Ok button self.button_ok = wx.Button(self.panel, label="Ok") self.main_sizer.Add(self.button_ok, 1, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) self.button_ok.Bind(wx.EVT_BUTTON, self.carry_on) def carry_on(self, event): self.cv.set() ############################################################################ class AddCommonName(wx.Frame): # Class definition for common name addition def __init__(self, parent, title): # Constructor super().__init__(parent, title=title, size=(400, 150)) # Run the name addition self.set_alias() self.Centre() self.Show() def set_alias(self): panel = wx.Panel(self) sizer = wx.GridBagSizer(5, 5) text1 = wx.StaticText(panel, label="Please type the new alias name.") sizer.Add(text1, pos=(0, 0), flag=wx.TOP | wx.LEFT | wx.BOTTOM, border=15) panel.SetSizer(sizer) ############################################################################ class AliasGUI(wx.Frame): def __init__(self, parent, title): # Constructor super().__init__(parent, title=title) # Run first dialog of the GUI self.begin() self.Centre() self.Show() def begin(self): # Panel initial settings panel_start = wx.Panel(self) main_sizer = wx.BoxSizer(wx.VERTICAL) # Alias type selection text_start = wx.StaticText(panel_start, label="Please select the type of the new alias.") main_sizer.Add(text_start, 1, wx.ALL, 10) # Buttons buttons_sizer = wx.BoxSizer(wx.HORIZONTAL) main_sizer.Add(buttons_sizer, 1, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) # Main name button button_main_name = wx.Button(panel_start, label="Main Name") buttons_sizer.Add(button_main_name, 0, wx.ALIGN_CENTER | wx.RIGHT, 10) button_main_name.Bind(wx.EVT_BUTTON, self.main_name) # Common name button button_common_name = wx.Button(panel_start, label="Common Name") buttons_sizer.Add(button_common_name, 0, wx.ALIGN_CENTER) button_common_name.Bind(wx.EVT_BUTTON, self.common_name) # Panel final settings panel_start.SetSizer(main_sizer) main_sizer.SetSizeHints(self) @staticmethod def main_name(event): # Function for main name addition frame = AddMainName(None, title="New Main Name") frame.Centre() frame.Show() @staticmethod def common_name(event): # Function for common name addition frame = AddCommonName(None, title="New Common Name") frame.Centre() frame.Show() # GUI execution if __name__ == '__main__': app = wx.App() AliasGUI(None, title="Aliases Management GUI") app.MainLoop() </code></pre>
0
2016-09-12T17:05:45Z
39,466,326
<p>It's not really clear what you intend to do here. Your Script doesnt crash, it just waits indefinatly on the event at line 40. You did not start any additional thread which could set the event, so the other script would continue.</p> <p>Also be aware that wxPython is not thread safe - so if you start adding widgets from inside another thread, you will (really) crash there.</p> <p>The setup of the actual frame is not started until your __ init __ function is done. Inside this call you wait for a button press which cannot happen, as the window is yet to be created. So your script waits.</p> <p>I would have posted an actual solution to your problem, but as stated above, I do not see what you intend to do here.</p> <p>Edit:</p> <p>As stated in the comment, I would use a dialog to ask the user for the items.</p> <p>Create a Dialog Subclass:</p> <pre><code>class getDataDlg(wx.Dialog): def __init__(self, *args, **kwargs): self.parameters = parameters = kwargs.pop('parameters', None) request = kwargs.pop('request', None) assert parameters is not None assert request is not None wx.Dialog.__init__(self, *args, **kwargs) self.data = {} vsizer = wx.BoxSizer(wx.VERTICAL) reqLbl = wx.StaticText(self, label="Please type new alias {}".format(request)) vsizer.Add(reqLbl, 1, wx.ALL, 10) self.controls = controls = {} for item in parameters: hsizer = wx.BoxSizer(wx.HORIZONTAL) parLbl = wx.StaticText(self, label=item) hsizer.Add(parLbl, 0, wx.ALIGN_CENTER | wx.LEFT, 10) ctrl = controls[item] = wx.TextCtrl(self) hsizer.Add(ctrl, 0, wx.ALIGN_CENTER) vsizer.Add(hsizer, 1, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) okBtn = wx.Button(self, id=wx.ID_OK) vsizer.Add(okBtn, 1, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) self.SetSizer(vsizer) self.Fit() self.Layout() okBtn.Bind(wx.EVT_BUTTON, self.saveData) def saveData(self, event): for item in self.parameters: self.data[item] = self.controls[item].GetValue() event.Skip() </code></pre> <p>Change main_name function to the following:</p> <pre><code>def main_name(self, event): parameters = OrderedDict([("name parts", ["Prefix", "Measurement", "Direction", "Item", "Location", "Descriptor", "Frame", "RTorigin"]), ("SI units", ["A", "cd", "K", "kg", "m", "mol", "Offset", "rad", "s", "ScaleFactor"]), ("normal display unit", ["A", "cd", "K", "kg", "m", "mol", "Offset", "rad", "s", "ScaleFactor"]), ("other parameters", ["Meaning", "Orientation Convention", "Contact Person", "Note",])]) # Iterate through parameters self.cv = threading.Event() for itemKey in parameters: item = parameters[itemKey] dlg = getDataDlg(self, parameters=item, request=itemKey) result = dlg.ShowModal() if result == wx.ID_OK: print("Got Result from Dialog:") print(dlg.data) dlg.Destroy() </code></pre> <p>Michael</p>
1
2016-09-13T09:14:40Z
[ "python", "user-interface", "dynamic", "wxpython" ]
extract a sentence that contains a list of keywords or phrase using python
39,455,363
<p>I have used the following code to extract a sentence from file(the sentence should contain some or all of the search keywords)</p> <pre><code>search_keywords=['mother','sing','song'] with open('text.txt', 'r') as in_file: text = in_file.read() sentences = text.split(".") for sentence in sentences: if (all(map(lambda word: word in sentence, search_keywords))): print sentence </code></pre> <p>The problem with the above code is that it does not print the required sentence if one of the search keywords do not match with the sentence words. I want a code that prints the sentence containing some or all of the search keywords. It would be great if the code can also search for a phrase and extract the corresponding sentence.</p>
0
2016-09-12T17:05:49Z
39,455,515
<p>So you want to find sentences that contain at least one keyword. You can use <a href="https://docs.python.org/3/library/functions.html?highlight=any#any" rel="nofollow">any()</a> instead of <a href="https://docs.python.org/3/library/functions.html?highlight=all#all" rel="nofollow">all()</a>.</p> <p>EDIT: If you want to find the sentence which contains the most keywords:</p> <pre><code>sent_words = [] for sentence in sentences: sent_words.append(set(sentence.split())) num_keywords = [len(sent &amp; set(search_keywords)) for sent in sent_words] # Find only one sentence ind = num_keywords.index(max(num_keywords)) # Find all sentences with that number of keywords ind = [i for i, x in enumerate(num_keywords) if x == max(num_keywords)] </code></pre>
0
2016-09-12T17:17:55Z
[ "python", "file", "search", "text" ]
extract a sentence that contains a list of keywords or phrase using python
39,455,363
<p>I have used the following code to extract a sentence from file(the sentence should contain some or all of the search keywords)</p> <pre><code>search_keywords=['mother','sing','song'] with open('text.txt', 'r') as in_file: text = in_file.read() sentences = text.split(".") for sentence in sentences: if (all(map(lambda word: word in sentence, search_keywords))): print sentence </code></pre> <p>The problem with the above code is that it does not print the required sentence if one of the search keywords do not match with the sentence words. I want a code that prints the sentence containing some or all of the search keywords. It would be great if the code can also search for a phrase and extract the corresponding sentence.</p>
0
2016-09-12T17:05:49Z
39,455,516
<p>If I understand correctly, you should be using <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any()</code></a> instead of <code>all()</code>.</p> <pre><code>if (any(map(lambda word: word in sentence, search_keywords))): print sentence </code></pre>
0
2016-09-12T17:17:59Z
[ "python", "file", "search", "text" ]
extract a sentence that contains a list of keywords or phrase using python
39,455,363
<p>I have used the following code to extract a sentence from file(the sentence should contain some or all of the search keywords)</p> <pre><code>search_keywords=['mother','sing','song'] with open('text.txt', 'r') as in_file: text = in_file.read() sentences = text.split(".") for sentence in sentences: if (all(map(lambda word: word in sentence, search_keywords))): print sentence </code></pre> <p>The problem with the above code is that it does not print the required sentence if one of the search keywords do not match with the sentence words. I want a code that prints the sentence containing some or all of the search keywords. It would be great if the code can also search for a phrase and extract the corresponding sentence.</p>
0
2016-09-12T17:05:49Z
39,455,804
<p>It seems like you want to count the number of <code>search_keyboards</code> in each sentence. You can do this as follows:</p> <pre><code>sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".") search_keywords=['mother','sing','song'] for sentence in sentences: print("{} key words in sentence:".format(sum(1 for word in search_keywords if word in sentence))) print(sentence + "\n") # Outputs: #2 key words in sentence: #My name is sing song # #1 key words in sentence: # I am a mother # #0 key words in sentence: # I am happy # #2 key words in sentence: # You sing like my mother </code></pre> <p>Or if you only want the sentence(s) that have the most matching <code>search_keywords</code>, you can make a dictionary and find the maximum values:</p> <pre><code>dct = {} for sentence in sentences: dct[sentence] = sum(1 for word in search_keywords if word in sentence) best_sentences = [key for key,value in dct.items() if value == max(dct.values())] print("\n".join(best_sentences)) # Outputs: #My name is sing song # You sing like my mother </code></pre>
2
2016-09-12T17:39:11Z
[ "python", "file", "search", "text" ]
Python: read regexps from JSON
39,455,366
<p>I have a JSON file where I store a mapping, which contains regexes, like the ones below:</p> <pre><code>"F(\\d)": "field-\\\\1", "FLR[ ]*(\\w)": "floor-\\\\1", </code></pre> <p>To comply with the standard I escape the backslashes, the actually regexps should contain <code>\d</code>, <code>\w</code>, and <code>\\1</code>.</p> <p>Once I read this JSON with json.load() I still need to post-process the resulting dictionary to get correct regexps. I need to substitute a <code>\\</code> with <code>\</code>. What's the best way to this?</p> <p>So far I tried both <code>re.sub()</code> and <code>str.replace()</code> and in both cases it's not clear how to represent a single backslash in substation.</p> <p>For example, I don't understand why the following doesn't produce a single backslash:</p> <pre><code>In [76]: "\\\\d".replace("\\\\", "\\") Out[76]: '\\d' </code></pre>
1
2016-09-12T17:05:55Z
39,455,454
<p>It does produce a single backslash - that backslash is escaped when displayed. This is done so that characters without a non-escaped way to display them can still be unambiguously printed - otherwise, you wouldn't know whether a backslash was meant to be escaping the following character or not.</p> <p>This can be demonstrated by checking the individual characters:</p> <pre><code># In a terminal/REPL: &gt;&gt;&gt;&gt; "\\\\d".replace("\\\\", "\\")[0] '\\' &gt;&gt;&gt;&gt; "\\\\d".replace("\\\\", "\\")[1] 'd' &gt;&gt;&gt;&gt; "\\\\d".replace("\\\\", "\\")[2] 'd' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: string index out of range </code></pre> <p>One tip for doing regexes in python: Use raw strings. If you put an <code>r</code> before the first quote of a string literal, backslashes won't escape anything (except for an ending quote). <code>r"\n"</code> is a string containing two characters, a <code>\</code> and an <code>n</code>, equivalent to <code>"\\n"</code>. When working with regexes and other things where you need to send escape sequences, they're very helpful. See also: <a href="http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l">What exactly do “u” and “r” string flags do in Python, and what are raw string literals?</a></p>
1
2016-09-12T17:13:16Z
[ "python", "json", "regex", "python-2.7" ]
Python relative imports using setuptools with scripts
39,455,388
<p>I am transitioning to a package-based workflow for a project I've been working on. I want to be able to separate development and production environments and I think setuptools offers this possibility with some degree of ease.</p> <p>I have a project structured as follows:</p> <pre><code>modulename/ setup.py modulename/ file_a.py script.py </code></pre> <p>In script.py, I want to import file_a.py. Currently I do this by doing <code>import file_a</code>. </p> <p>My setup.py looks like:</p> <pre><code>from setuptools import setup, find_packages setup(name='modulename', packages = find_packages(), package_dir = {'': '../modulename'}, scripts = ['modulename/script.py']) </code></pre> <p>Currently, when I run <code>script.py</code> after doing <code>python setup.py install</code>, I get an error message:</p> <p><code>SystemError: Parent module '' not loaded, cannot perform relative import</code></p> <p>I have tried a variety of permutations of <code>package_dir = ...</code>, most notably <code>package_dir = {'': 'modulename'}</code>, but this throws another error on install, <code>error: package directory 'modulename/modulename' does not exist</code></p> <p>I am not sure what I am doing wrong. The documentation online for setuptools is relatively poor in dealing with situations involving relative imports. Can someone point me in the right direction?</p>
0
2016-09-12T17:07:27Z
39,483,698
<p>The problem is not related with <code>setuptools</code>. Using relative imports inside the module being executed as <code>__main__</code> does not work out of the box. There are workarounds / hacks, but the most common solutions seems to be moving the script out of the package or using absolute imports in the script file.</p> <p>Take a look at <a href="http://stackoverflow.com/questions/16981921/relative-imports-in-python-3">Relative imports in Python 3</a> for the full story.</p>
1
2016-09-14T06:20:54Z
[ "python", "python-3.x", "import", "package" ]
shell shift in exel using python
39,455,474
<p>i wrote the following python script that reads the contents of "prom output.csv" file" and after does some processing it writes the output to the file "sorted output."</p> <pre><code>import collections import csv import sys with open("prom output.csv","r") as f: cr = csv.reader(f,delimiter=",") d=collections.defaultdict(lambda : list()) header=next(cr) for r in cr: d[r[0]].append(r[1]) with open("sorted output.csv","w") as f: cr = csv.writer(f,sys.stdout, lineterminator='\n') cr.writerow(header) od = collections.OrderedDict(sorted(d.items())) for k,v in od.items(): cr.writerow([k,";".join(v)]) </code></pre> <p>The output "sorted output.csv" looks like:</p> <p><a href="http://i.stack.imgur.com/x3X63.png" rel="nofollow"><img src="http://i.stack.imgur.com/x3X63.png" alt="enter image description here"></a></p> <p>My input file: "prom output.csv" looks like:</p> <p><a href="http://i.stack.imgur.com/gRq3a.png" rel="nofollow"><img src="http://i.stack.imgur.com/gRq3a.png" alt="enter image description here"></a></p> <p>I want to slightly modify the current output so that it will have the following form:</p> <p><a href="http://i.stack.imgur.com/D26C4.png" rel="nofollow"><img src="http://i.stack.imgur.com/D26C4.png" alt="enter image description here"></a></p> <p>Any ideas?</p>
2
2016-09-12T17:14:23Z
39,455,538
<p>Don't use <code>join</code> for your row content; just combine the header w/ the data into a single list:</p> <pre><code>cr.writerow([k]+v) </code></pre>
3
2016-09-12T17:19:36Z
[ "python", "excel" ]
Python 2.7 MySQLdb to save last row read from database into text file
39,455,484
<p>So bare with me, I have been doing python for a little over a week now. I have been tasked with getting a MySQL database to send data into Salesforce and create a ticket. I currently have python downloading the required tables from the database and saving that information into a .xlsx sheet. Then I have another python script uploading that data to a Google Doc sheet and then a Javascript trigger that will submit the data into salesforce and all works as I expected. </p> <p>Issue I am having is that when it pulls the data from MySQL, it pulls the same info again and again, I need it to remember the last row or customer ID that it grabbed the last time around, save that ID or Row into a .txt file then pull that same data the next time the script runs so it starts from that row or ID instead of starting from the top again.</p> <p>Any help would be greatly appreciated.</p> <pre><code>#!/usr/bin/python import smtplib import base64 import os import sys import csv from xlsxwriter.workbook import Workbook import xlwt import MySQLdb def sql_run(): ur = 'user' # your username pd = 'password' # your password ht = '192.168.1.10' # your host pt = 3306 db = 'database' # database where your table is stored #table = 'rma_customer' # table you want to save con = MySQLdb.connect(user=ur, passwd=pd, host=ht, port=pt, db=db) cursor = con.cursor() query = "SELECT cus_id, cus_username FROM database.rma_customer" query0 = "SELECT cus_firstname, cus_lastname, cus_cell_phone FROM database.rma_customer_details" query1 = "SELECT cus_address_1 FROM database.rma_customer_address" query2 = "SELECT cus_city, cus_postcode FROM database.rma_customer_address" query3 = "SELECT regpro_model_type, regpro_buy_location, regpro_sn FROM database.rma_reg_product" cursor.execute(query) workbook = Workbook('outfile.xlsx') sheet = workbook.add_worksheet("Warranty Info") headers = ['ID', 'Email', 'FirstName', 'LastName', 'Phone', 'Street', 'City', 'Postal', 'Product', 'Store', 'SN'] for i, header in enumerate(headers): sheet.write(0, i, header) for r, row in enumerate(cursor.fetchall()): r = r + 1 for c, col in enumerate(row): sheet.write(r, c, col) cursor.execute(query0) for r, row in enumerate(cursor.fetchall()): r = r + 1 for c, col in enumerate(row): sheet.write(r, c+2, col) cursor.execute(query1) for r, row in enumerate(cursor.fetchall()): r = r + 1 for c, col in enumerate(row): sheet.write(r, c+5, col) cursor.execute(query2) for r, row in enumerate(cursor.fetchall()): r = r + 1 for c, col in enumerate(row): sheet.write(r, c+6, col) cursor.execute(query3) for r, row in enumerate(cursor.fetchall()): r = r + 1 for c, col in enumerate(row): sheet.write(r, c+8, col) cursor.close () workbook.close() con.close () sys.exit() # exit the program sql_run() </code></pre>
0
2016-09-12T17:15:38Z
39,489,791
<ol> <li>Add a <code>row</code> in the <code>table</code>you pull your information from. </li> <li>Pull the <code>id</code> (0th's row) as unique identifier</li> <li>Update <code>row</code> which has <code>id</code> with something like <code>True</code> or <code>False</code>.</li> <li>Give your query a <code>condition</code> that said row must be <code>True</code>/ <code>False</code></li> </ol> <p>This way you make sure it stops iterating over the same info.</p> <p>Programatically:</p> <pre><code>query = "SELECT cus_id, cus_username FROM database.rma_customer WHERE row = 'True'" ... data = cursor.execute(query) for col in data: id = col[0] ... cursor.execute(""" UPDATE table SET row= %s WHERE id= %s """, (row, id)) </code></pre> <p>The <code>...</code> stand for your code. I cannot guess where you want to place the code snippets.</p>
0
2016-09-14T11:53:14Z
[ "python", "mysql", "excel", "python-2.7" ]
SQLAlchemy Core bulk insert slow
39,455,518
<p>I'm trying to truncate a table and insert only ~3000 rows of data using SQLAlchemy, and it's very slow (~10 minutes). </p> <p>I followed the recommendations on this <a href="http://docs.sqlalchemy.org/en/latest/faq/performance.html" rel="nofollow">doc</a> and leveraged sqlalchemy core to do my inserts, but it's still running very very slow. What are possible culprits for me to look at? Database is a postgres RDS instance. Thanks!</p> <pre><code>engine = sa.create_engine(db_string, **kwargs, pool_recycle=3600) with engine.begin() as conn: conn.execute("TRUNCATE my_table") conn.execute( MyTable.__table__.insert(), data #where data is a list of dicts ) </code></pre>
0
2016-09-12T17:18:02Z
39,755,105
<p>I was bummed when I saw this didn't have an answer... I ran into the exact same problem the other day: Trying to bulk-insert about millions of rows to a Postgres RDS Instance using CORE. It was taking <em>hours</em>.</p> <p>As a workaround, I ended up writing my own bulk-insert script that generated the raw sql itself:</p> <pre><code>bulk_insert_str = [] for entry in entry_list: val_str = "('{}', '{}', ...)".format(entry["column1"], entry["column2"], ...) bulk_insert_str.append(val_str) engine.execute( """ INSERT INTO my_table (column1, column2 ...) VALUES {} """.format(",".join(bulk_insert_str)) ) </code></pre> <p>While ugly, this gave me the performance we needed (~500,000 rows/minute)</p> <p>Did you find a CORE-based solution? If not, hope this helps!</p> <p>UPDATE: Ended up moving my old script into a spare EC2 instance that we weren't using which actually fixed the slow performance issue. Not sure what your setup is, but apparently there's a network overhead in communicating with RDS from an external (non-AWS) connection.</p>
0
2016-09-28T18:30:12Z
[ "python", "postgresql", "orm", "sqlalchemy" ]
Custom user model and custom authentication not working in django. Authentication form is not passing validation tests
39,455,546
<p>I am trying to implement the custom User model and custom authentication for my application.<br> I am able to create models and make migrations. But when I created a form and implemented the login template, I am getting this error - </p> <pre><code>login User model with this Login already exists. </code></pre> <p><strong>View where I am authenticating user -</strong> </p> <pre><code>from django.shortcuts import render_to_response, redirect, render from django.template import RequestContext from django.contrib.auth import login, logout , authenticate from accounts.forms import AuthenticationForm from django.contrib.auth.decorators import login_required def accounts_login(request): context = {} if request.method == "POST": form = AuthenticationForm(request.POST) #getting error here print(form) if form.is_valid(): user = authenticate(login = request.POST["login"], password = request.POST["password"]) if user is not None: print(user) login(request,user) next_url = request.POST["next"] return redirect(next_url, args=(), kwargs={}) #more code - not required here. Let me know if needed. </code></pre> <p><strong>Authentication form:</strong></p> <pre><code>from django import forms from accounts.models import UserModel class AuthenticationForm(forms.Form): login = forms.CharField(max_length=128, required=True) password = forms.CharField(max_length=128, required=True) </code></pre> <p><strong>My custom user model and user manager -</strong></p> <pre><code>from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.utils import timezone from django.db.models import Max class MyUserManager(BaseUserManager): use_in_migrations = True def create_user(self,login, parent_type, last_name, first_name, password): return create_superuser(self,login, parent_type, last_name, first_name, password) def create_superuser(self,login, parent_type, last_name, first_name, password): maxx = self.model.objects.all().aggregate(Max('sys_id')) print(maxx) user = self.model( sys_id = maxx["sys_id__max"] + 1, login = login, password = password, parent_type = parent_type, last_name = last_name, first_name = first_name, display_name = last_name + " " + first_name, created_when = timezone.now() ) user.save(using=self._db) # no difference here...actually can set is_admin = True or something like that. return user class UserModel(AbstractBaseUser): # custom user class SYSTEM = 0 TENANT = 1 parent_type_choices = ( (SYSTEM, 'System'), (TENANT, 'Tenant') ) sys_id = models.BigIntegerField(primary_key=True, blank=True) parent_type = models.PositiveIntegerField(choices=parent_type_choices, null=False, blank=False) parent_sys_id = models.ForeignKey('tenant.TenantModel', on_delete = models.SET_NULL, null=True, blank=True) last_name = models.CharField(null=False, blank=False, max_length=40) first_name = models.CharField(max_length=40, null=False, blank=False) display_name = models.CharField(max_length=80, unique=True, null=False, blank=True) login = models.CharField(max_length=40, unique=True, null=False, blank=False) authentication_method = models.CharField(max_length=80, null=True, blank=True) access_valid_start = models.DateTimeField(null=True, blank=True) access_valid_end = models.DateTimeField(null=True, blank=True) created_when = models.DateTimeField(null=True, blank=True, ) created_by = models.BigIntegerField(null=True, blank=True) last_updated_when = models.DateTimeField(null=True, blank=True) last_updated_by = models.BigIntegerField(null=True, blank=True) notes = models.CharField(max_length=2048, null=True, blank=True) is_active = models.BooleanField(default=True) objects = MyUserManager() USERNAME_FIELD = "login" # REQUIRED_FIELDS must contain all required fields on your User model, # but should not contain the USERNAME_FIELD or password as these fields will always be prompted for. REQUIRED_FIELDS = ['parent_type', 'last_name', 'first_name'] class Meta: app_label = "accounts" db_table = "Users" def __str__(self): return self.display_name def get_full_name(self): return self.display_name def get_short_name(self): return self.last_name def check_password(self,password): return True if self.password ==password: return true </code></pre> <p><strong>Custom backend</strong></p> <pre><code>from django.conf import settings from accounts.models import UserModel class MyAuthBackend(object): def authenticate(self, login, password): try: user = UserModel.objects.get(login=login) if user.check_password(password): return user else: print("wrong password") return None except User.DoesNotExist: return None except Exception as e: print(repr(e)) return None def get_user(self, user_id): try: user = User.objects.get(pk=user_id) if user.is_active: return user return None except User.DoesNotExist: return None </code></pre> <p><strong>Added these two variables in setting.py</strong></p> <pre><code>AUTH_USER_MODEL = 'accounts.UserModel' AUTHENTICATION_BACKENDS = ('accounts.backends.MyAuthBackend',) </code></pre> <p><strong>Getting backend from command line</strong></p> <pre><code>&gt;&gt;&gt; get_backends() [&lt;accounts.backends.MyAuthBackend object at 0x7f2c438afe80&gt;] </code></pre> <p>A user with username lets say xyz and password 'ABC' exists in db.<br> 1. When I am trying to login with existing username and password it throws me error <code>User model with this Login already exists.</code><br> 2. When I try to login with non-existing username and password (lets say xyz123) it throws me error <code>authenticate() takes 0 positional arguments but 2 were given</code></p> <p>I followed multiple articles but mainly django official documentation for this. Read multiple articles to solve the issue but failed.<br> Please suggest what I am doing wrong.</p> <p>Update 1: chnged the AuthenticationForm from ModelForm to normal Form class. Error 1 is solved.<br> Update 2: Not using my custom backend as pointed by Daniel, it is useless because I am not doing anything new in it. Hence error 2 is also solved.<br> Update 3: Now hashing password before saving user to db in create super user function. <code>user.set_password(password)</code></p>
0
2016-09-12T17:20:38Z
39,456,300
<p>Firstly, you are storing passwords in plain text in your overwritten <code>create_superuser</code> method. You <strong>must absolutely not do this</strong>. Quite apart from the security issues, it won't actually work, as the authentication backend will hash a submitted password before comparing it with the saved version, so it will never match.</p> <p>Secondly, your actual problem is that your AuthenticationForm is a ModelForm; as such it will attempt to see if it can <em>create</em> a user with that email and password. There is no reason to make it a modelform, you should just have a plain form with CharFields for email and password.</p> <p>Note though that you won't actually be able to log in, until you have fixed the plain text password issue. Note also that your custom auth backend - as well as breaking the authenticate method by not conforming to the interface described <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#writing-an-authentication-backend" rel="nofollow">in the docs</a> - does not do anything that the built-in one does not do; it is pointless and you should remove it.</p>
1
2016-09-12T18:12:39Z
[ "python", "django", "authentication" ]
map items from list using list comprehension?
39,455,561
<p>I have a problem with a list comprehension inside a loop. I want to add items from one list to an other.</p> <p>I'm using <code>map class</code> and <code>zip</code> inside the list comprehension.</p> <pre><code>from pandas import Series, DataFrame import pandas x = ['a', 'b', 'c', 'd', 'e'] y = [2, 3, 6, 7, 4] ser = {'A': Series(x), 'B': Series(y)} df = DataFrame(ser) targets = df['A'].tolist() df['A1999'] = [i + 1 for i in df['B']] df['A2000'] = [i + 2 for i in df['B']] df['A2001'] = [i + 3 for i in df['B']] df['A2002'] = [i + 1.7 for i in df['B']] df['A2003'] = [i + 1.1 for i in df['B']] y = range(1999, 2004) gaps = [] for t in targets: temp = [] years = [] for ele in y: target = 'A' + str(ele) new = df[target][df['A'] == t].tolist() temp.append(new) years.append(ele) gap = [list(map(list, zip(years, item))) for item in temp] gaps.append(gap) </code></pre> <p>And the output:</p> <pre><code>[[[[1999, 3]], [[1999, 4]], [[1999, 5]], [[1999, 3.7000000000000002]], [[1999, 3.1000000000000001]]]... </code></pre> <p>What I'm looking for is:</p> <pre><code>[[[[1999, 3]], [[2000, 4]], [[2001, 5]], [[2002, 3.7000000000000002]], [[2003, 3.1000000000000001]]]... </code></pre> <p>How can I fix the list comprehension in order to add all years from <code>years list</code> and not only the first (i.e. 1999)</p> <p><strong>I tried</strong> with this example, but I think I'm doing the same thing:</p> <pre><code>gap = [[[years[i], x] for i, x in enumerate(y)] for y in temp] </code></pre> <p>or</p> <pre><code>gap = [list(map(list, zip([[y] for y in years], item))) for item in temp] </code></pre>
2
2016-09-12T17:21:13Z
39,456,594
<p>Replace gap = with this</p> <pre><code>[list((x,y[0])) for x,y in zip(years,temp)] </code></pre>
2
2016-09-12T18:32:39Z
[ "python", "list", "python-3.x", "loops" ]
django login_required defaults request.LANGUAGE_CODE to default language in settings
39,455,603
<p><strong>login_required</strong> decorator sets <strong>request.LANGUAGE_CODE</strong> to default language that has been set in <strong>settings.py</strong>. How can I bypass this behavior ?</p> <p>thanks! </p>
1
2016-09-12T17:24:27Z
39,457,089
<p>I had this issue in the past and found that setting your LOGIN_URL in the settings file to use reverse_lazy works:</p> <pre><code>LOGIN_URL = reverse_lazy('log_in') </code></pre>
0
2016-09-12T19:06:29Z
[ "python", "django" ]
My labels aren't moving to the column and rows I want them to
39,455,718
<p>I want my labels and entry widgets and different rows but they automatically move to the top. What do I do to do that? Is there a simple function I could use?</p> <pre><code>from tkinter import * root = Tk() root.resizable(width = False, height = False) label_1 = Label(root, text="Text") label_2 = Label(root, text="Text2") entry1 = Entry(root) entry2 = Entry(root) label_1.grid(row=4, column=2, sticky=E) label_2.grid(row=5, column=2, sticky=E) entry1.grid(row=4, column=3, sticky=E) entry2.grid(row=5, column=3, sticky=E) checkbox = Checkbutton(root, text="Check me") checkbox.grid(columnspan=2) </code></pre> <p>Also do you know how to add sub frames? I searched but the examples were all with classes and I was left confused. I of course also want it to be in a specific column and row without automatically getting moved somewhere else.</p>
-1
2016-09-12T17:32:55Z
39,458,554
<p>Empty rows and columns have size 0. Blank labels can be used to create blank space.</p> <pre><code>from tkinter import * root = Tk() dummy = Label(root, text='\n') label_1 = Label(root, text="Text") label_2 = Label(root, text="Text2") entry1 = Entry(root) entry2 = Entry(root) dummy.grid() label_1.grid(row=4, column=2, sticky=E) label_2.grid(row=5, column=2, sticky=E) entry1.grid(row=4, column=3, sticky=E) entry2.grid(row=5, column=3, sticky=E) checkbox = Checkbutton(root, text="Check me") checkbox.grid(columnspan=2) </code></pre>
0
2016-09-12T20:47:18Z
[ "python", "tkinter" ]
gcc: error trying to exec 'cc1plus': execvp: No such file or directory
39,455,741
<p>I'm trying to install this python module, which requires compilation (on Ubuntu 16.04). I'm struggling to understand exactly what's causing it stall; what am I missing?</p> <pre><code>(xenial)chris@localhost:~$ pip install swigibpy Collecting swigibpy Using cached swigibpy-0.4.1.tar.gz Building wheels for collected packages: swigibpy Running setup.py bdist_wheel for swigibpy ... error Complete output from command /home/chris/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-162vhh_i/swigibpy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmptqb6ctskpip-wheel- --python-tag cp35: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.5 copying swigibpy.py -&gt; build/lib.linux-x86_64-3.5 running build_ext building '_swigibpy' extension creating build/temp.linux-x86_64-3.5 creating build/temp.linux-x86_64-3.5/IB creating build/temp.linux-x86_64-3.5/IB/PosixSocketClient gcc -pthread -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DIB_USE_STD_STRING=1 -IIB -IIB/PosixSocketClient -IIB/Shared -I/home/chris/anaconda3/include/python3.5m -c IB/PosixSocketClient/EClientSocketBase.cpp -o build/temp.linux-x86_64-3.5/IB/PosixSocketClient/EClientSocketBase.o -Wno-switch gcc: error trying to exec 'cc1plus': execvp: No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Failed building wheel for swigibpy Running setup.py clean for swigibpy Failed to build swigibpy Installing collected packages: swigibpy Running setup.py install for swigibpy ... error Complete output from command /home/chris/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-162vhh_i/swigibpy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-yv9u0wok-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-3.5 copying swigibpy.py -&gt; build/lib.linux-x86_64-3.5 running build_ext building '_swigibpy' extension creating build/temp.linux-x86_64-3.5 creating build/temp.linux-x86_64-3.5/IB creating build/temp.linux-x86_64-3.5/IB/PosixSocketClient gcc -pthread -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DIB_USE_STD_STRING=1 -IIB -IIB/PosixSocketClient -IIB/Shared -I/home/chris/anaconda3/include/python3.5m -c IB/PosixSocketClient/EClientSocketBase.cpp -o build/temp.linux-x86_64-3.5/IB/PosixSocketClient/EClientSocketBase.o -Wno-switch gcc: error trying to exec 'cc1plus': execvp: No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/home/chris/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-162vhh_i/swigibpy/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-yv9u0wok-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-162vhh_i/swigibpy/ </code></pre>
0
2016-09-12T17:34:37Z
39,458,229
<p>The routine commands that saved me time after time for such errors:</p> <pre><code>sudo apt install upgrade sudo apt install update sudo apt install gcc python3-dev python3-pip libxml2-dev libxslt1-dev zlib1g-dev </code></pre> <p>Hope it works.</p>
0
2016-09-12T20:22:30Z
[ "python", "gcc" ]
How to store mySQL query as python dictionary and call later in script?
39,455,758
<p>I have a table called "<strong>uid</strong>" which has two fields, <strong>rfid</strong> and <strong>empid</strong>:</p> <ul> <li><strong>EXAMPLE RECORD 1</strong> rfid = 88 999 33 555 empid = 1 </li> <li><strong>EXAMPLE RECORD 2</strong> rfid = 64 344 77 222 empid = 2</li> </ul> <p>I would like to run a query which stores all of these values in a python dictionary, and allows me to set the rfid number as a variable (MyRFID) to be called later in the script:</p> <pre><code>db = MySQLdb.connect("MyIp", "MyUser", "MyPass", "MyDB", cursorclass=MySQLdb.cursors.DictCursor) curs=db.cursor() curs.execute("""SELECT number, empid FROM rfid """) </code></pre> <p>So that later in the code I can check to see if I get a match from an existing variable:</p> <pre><code>if MyVariable == MyRFID: #Create new record for that empid </code></pre>
1
2016-09-12T17:35:44Z
39,456,216
<p>I think you're looking for the fetchall method. After you call </p> <p><code>cur.execute("""SELECT number, empid FROM rfid """)</code></p> <p>you would do:</p> <p><code>rows = cur.fetchall()</code></p> <p>and then rows would contain a list of tuples. If you specifically need it to be a dictionary, you could just do <code>dict(rows)</code> in this example but that only works because your query happens to return two columns. If it was more than two columns you would need something like:</p> <p><code>rows_dict = dict([ k[0], k[1:]) for k in rows])</code></p> <p>(see: <a href="http://stackoverflow.com/questions/14263494/converting-list-of-3-element-tuple-to-dictionary">Converting List of 3 Element Tuple to Dictionary</a>)</p> <p>If the dictionary you were imagining had column names as keys you need to look at DictCursor (<a href="http://stackoverflow.com/questions/2180226/python-use-mysqldb-to-import-a-mysql-table-as-a-dictionary">Python: use mysqldb to import a MySQL table as a dictionary?</a>).</p>
0
2016-09-12T18:06:31Z
[ "python", "mysql", "dictionary" ]
Find a character from a string without using find method?
39,455,784
<p>As I am a newbie ... not understanding why it's not working properly ? expecting the cause and solution and also tips thanks</p> <pre><code>str = "gram chara oi ranga matir poth" find ='p' l = len(str) for x in range(0,l): if str[x]==find: flag = x #break if flag == x: print "found in index no",flag else: print "not found in there" </code></pre>
1
2016-09-12T17:37:55Z
39,455,839
<p><code>if flag == x</code> looks strange. What value of <code>x</code> are you expecting there?</p> <p>I'd suggest instead initializing <code>flag</code> to <code>None</code> and then checking for it not being <code>None</code> at the end of the loop.</p> <pre><code>flag = None # assign a "sentinel" value here str = "gram chara oi ranga matir poth" find = 'p' for x in range(len(str)): if str[x] == find: flag = x # Leaving out the break is also fine. It means you'll print the # index of the last occurrence of the character rather than the first. break if flag is not None: print "found in index no", flag else: print "not found in there" </code></pre>
1
2016-09-12T17:41:48Z
[ "python", "string" ]
Find a character from a string without using find method?
39,455,784
<p>As I am a newbie ... not understanding why it's not working properly ? expecting the cause and solution and also tips thanks</p> <pre><code>str = "gram chara oi ranga matir poth" find ='p' l = len(str) for x in range(0,l): if str[x]==find: flag = x #break if flag == x: print "found in index no",flag else: print "not found in there" </code></pre>
1
2016-09-12T17:37:55Z
39,455,879
<p>You're trying to have flag be the location of the index of the (first) matching character. Good!</p> <pre><code>if str[x]==find: flag = x break </code></pre> <p>But how to tell if nothing was found? Testing against x won't help! Try initializing flag to a testable value:</p> <pre><code>flag = -1 for x in range(0,l): if str[x]==find: flag = x break </code></pre> <p>Now everything is easy:</p> <pre><code>if flag != -1: print "found in index no",flag else: print "not found in there" </code></pre>
0
2016-09-12T17:44:45Z
[ "python", "string" ]
Find a character from a string without using find method?
39,455,784
<p>As I am a newbie ... not understanding why it's not working properly ? expecting the cause and solution and also tips thanks</p> <pre><code>str = "gram chara oi ranga matir poth" find ='p' l = len(str) for x in range(0,l): if str[x]==find: flag = x #break if flag == x: print "found in index no",flag else: print "not found in there" </code></pre>
1
2016-09-12T17:37:55Z
39,456,005
<p>Your method of searching is valid (iterating through the characters in the string). However, your problem is at the end when you're evaluating whether or not you've found the character. You're comparing <code>flag</code> to <code>x</code>, but when you do the comparison, <code>x</code> is <a href="http://stackoverflow.com/a/292502/1368616">out of scope</a>. Because <code>x</code> is declared in a for loop statement, it's only defined <em>inside</em> that for loop. So, to fix your code set an initial value for <code>flag</code> that you can check against, then change the check at the end:</p> <pre><code>flag = None for x in range(len(str)): if str[x] == find: flag = x break # Using break here means you'll find the FIRST occurrence of find if flag: print "found in index no",flag else: print "not found in there" </code></pre>
0
2016-09-12T17:52:36Z
[ "python", "string" ]
Issue with Flask-Marshmallow exposing DB contents via API
39,455,814
<p>I am developing a API which will return entries from a Database. I am using Flask-SQLAlchemy, Flask-Marshmallow, Flask-Admin and Docker to package it all up. </p> <p>In one file Packages.py I have the following code regarding the database. The class PckagesSchema is the class I've added when trying to get Flash-Marshmallow working.</p> <pre><code>class Packages(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) trackingnumber = db.Column(db.String(15)) email = db.Column(db.String(80)) localid = db.Column(db.String(80)) class PackagesSchema(ma.ModelSchema): class Meta: model = Packages </code></pre> <p>The in the main file I have the following snippets of code</p> <pre><code>from app.models import Packages, PackagesSchema packages_schema = PackagesSchema() db.create_all() </code></pre> <p>and then further down the part which will deal with API GET Requests. </p> <pre><code>@app.route('/packages', methods=['GET']) def get_packages(): result = packages_schema.dump(Packages).data return jsonify(result) </code></pre> <p>at the moment this returns:</p> <pre><code>{ "email": "Packages.email", "localid": "Packages.localid", "trackingnumber": "Packages.trackingnumber" } </code></pre> <p>However, there is definitely something in the database as the Flask-Admin app displays its.</p> <p>This is my first day working with Flask-Marshmallow so I am not that experienced at all and would appreciate any help. I have read <a href="https://flask-marshmallow.readthedocs.io/en/latest/" rel="nofollow">https://flask-marshmallow.readthedocs.io/en/latest/</a> but still stuck. </p>
1
2016-09-12T17:39:57Z
39,458,289
<p>I just brushed up a little on marshmallow:</p> <pre><code>@app.route('/packages', methods=['GET']) def get_packages(): packages = Packages.query.all() result = packages_schema.dump(packages).data return jsonify(result) </code></pre> <p>Should give you everything in there. If you are returning many records, you need to add <code>packages_schema = PackagesSchema(many=True)</code>.</p> <p>Also, not sure what version of flask you are running... but pre the latest release, I dont think jsonify would work here since you could not call it on a list. Juts a heads up.</p>
0
2016-09-12T20:25:27Z
[ "python", "flask", "flask-sqlalchemy", "marshmallow" ]
pyspark: convert a bytearray field to string in data frame
39,455,836
<p>I am reading a parquet file to a dataframe:</p> <pre><code>my_df = sqlContext.read.parquet('hdfs://my_server/user/hive/warehouse/my_db.db/my_table') </code></pre> <p>if I do:</p> <pre><code>my_df.head() </code></pre> <p>I got:</p> <pre><code>Row(id=bytearray(b'00000000000000000000000000000000'), numcores=8, ...) </code></pre> <p>and when I do </p> <pre><code>my_df.show() </code></pre> <p>the first field id looks like:</p> <pre><code>[30 30 30 30 30 3...] </code></pre> <p>How do I change the bytearray field and make it show as a string output? Thanks!</p>
0
2016-09-12T17:41:41Z
39,455,876
<p>If you mean to change what <code>head()</code> returns to you, that's not gonna happen, since the <a href="https://spark.apache.org/docs/1.6.2/api/python/pyspark.sql.html#pyspark.sql.DataFrame.head" rel="nofollow">prototype</a> doesn't provide any such functionality:</p> <blockquote> <p>head(n=None)</p> </blockquote>
1
2016-09-12T17:44:27Z
[ "python", "apache-spark", "pyspark", "spark-dataframe" ]
What is the benefit of a dataframe view or copy
39,455,863
<p>I've seen many questions about the infamous <code>SettingWithCopy</code> warning. I've even ventured to answer a few of them. Recently, I was putting together an answer that involved this topic and I wanted to present the benefit of a dataframe view. I failed to produce a tangible demonstration of why it is a good idea to create a dataframe view or whatever the thing is that generates <code>SettingWithCopy</code></p> <p>Consider <code>df</code></p> <pre><code>df = pd.DataFrame([[1, 2], [3, 4]], list('ab'), list('AB')) df A B x 1 2 y 3 4 </code></pre> <p>and <code>dfv</code> which is a copy of <code>df</code></p> <pre><code>dfv = df[['A']] </code></pre> <hr> <pre><code>print(dfv.is_copy) &lt;weakref at 0000000010916E08; to 'DataFrame' at 000000000EBF95C0&gt; </code></pre> <hr> <pre><code>print(bool(dfv.is_copy)) True </code></pre> <hr> <p>I can generate the <code>SettingWithCopy</code></p> <pre><code>dfv.iloc[0, 0] = 0 </code></pre> <p><a href="http://i.stack.imgur.com/eazEe.png" rel="nofollow"><img src="http://i.stack.imgur.com/eazEe.png" alt="enter image description here"></a></p> <hr> <p>However, <code>dfv</code> has changed</p> <pre><code>print(dfv) A a 0 b 3 </code></pre> <p><code>df</code> has not</p> <pre><code>print(df) A B x 1 2 y 3 4 </code></pre> <hr> <p>and <code>dfv</code> is still a copy</p> <pre><code>print(bool(dfv.is_copy)) True </code></pre> <hr> <p>If I change <code>df</code></p> <pre><code>df.iloc[0, 0] = 7 print(df) A B x 7 2 y 3 4 </code></pre> <hr> <p>But <code>dfv</code> has not changed. However, I can reference <code>df</code> from <code>dfv</code></p> <pre><code>print(dfv.is_copy()) A B x 7 2 y 3 4 </code></pre> <hr> <h3>Question</h3> <p>If <code>dfv</code> maintains it's own data (meaning, it doesn't actually save memory) and it assigns values via assignment operations despite warnings, then why do we bother saving references in the first place and generate <code>SettingWithCopyWarning</code> at all?</p> <p>What is the tangible benefit?</p>
2
2016-09-12T17:43:28Z
39,456,035
<p>There is a lot of existing discussion on this, see <a href="https://github.com/pydata/pandas/issues/10954" rel="nofollow">here</a> for instance, including the attempted PRs. It's also worth noting that true copy-on-write for views is being considered as part of the "pandas 2.0" refactor, see <a href="https://github.com/pydata/pandas-design/issues/10" rel="nofollow">here</a>.</p> <p>The reason the reference is being maintained in your example is specifically because it's <em>not</em> a view, so that if someone tries this, they'll get a warning.</p> <pre><code>df[['A']].iloc[0, 0] = 1 </code></pre> <p>Edit:</p> <p>In terms of "why use views at all," it's for performance / memory reasons. Consider, basic indexing (selecting a column), because this operation takes a view, it is almost instantaneous.</p> <pre><code>df = pd.DataFrame(np.random.randn(1000000, 2), columns=['a','b']) %timeit df['a'] 100000 loops, best of 3: 2.13 µs per loop </code></pre> <p>Whereas taking a copy has a non-trivial cost.</p> <pre><code>%timeit df['a'].copy() 100 loops, best of 3: 4.28 ms per loop </code></pre> <p>This performance cost would show up in many operations, for instance adding two <code>Series</code> together.</p> <pre><code>%timeit df['a'] + df['b'] 100 loops, best of 3: 4.31 ms per loop %timeit df['a'].copy() + df['b'].copy() 100 loops, best of 3: 13.3 ms per loop </code></pre>
3
2016-09-12T17:54:17Z
[ "python", "pandas" ]
How to merge lists of tuples?
39,455,901
<p>I use python 3</p> <p>I have a list L, which contains another lists, which contains turples of point (x,y):</p> <pre><code>L=[A, B, C, D ...] A = [(1,1),(3,3),(4,5)...] B=[(1,2),..(6,7)] </code></pre> <p>I want to merge all lists from L, which have a adjacent points. As above: we must to union A,B because they have a adjacent points: (1,1) from A, and (1,2) from B. And obtain: L =[A+B, C, ...]</p> <p>I tried code something like this:</p> <pre><code>if (x-1,y-1) in L[i] or (x-1,y) in L[i] or (x-1,y+1) in L[i] or (x,y-1) in L[i] or (x,y+1) in L[i] or (x+1,y-1) in L[i] or (x+1,y) in L[i] or (x+1,y+1) in L[i]: </code></pre> <p>But I can't union all of the list from L. Help</p> <p>* adjacent points are point , distance between them = 1, for example (1,1) and (1,2). (5,6) and (6,7). (8,7) and (7,7)</p>
-2
2016-09-12T17:46:17Z
39,456,990
<p>This is my crack at your algorithm:</p> <pre><code>def adjacent(list_1, list_2): for elem_1 in list_1: for elem_2 in list_2: if abs(elem_1[0] - elem_2[0]) == 1 or\ abs(elem_1[1] - elem_2[1]) == 1: return True return False def join_adjacent_points(L): result = [] while len(L) &gt; 0: result.append(L[0]) L = L[1:] i = 0 while i &lt; len(L): if adjacent(L[i], result[-1]): result[-1] += L[i] del L[i] i = 0 i += 1 return result </code></pre>
0
2016-09-12T18:59:48Z
[ "python", "python-3.x" ]
A simple case of struct, but getting a "bad char" error
39,455,984
<p>I'm attempting to read a section of a binary file, and decode it as a string of characters using the struct. module. </p> <p>It's a simple enough case. Here is the bytes argument:</p> <pre><code>b'11:10:00\x00ng ' </code></pre> <p>and here is the function I am attempting to use: </p> <pre><code>struct.unpack('utf-8', b'11:10:00\x00ng ') </code></pre> <p>The output should be twelve characters, no?:</p> <pre><code>'11:10:00 ng ' </code></pre> <p>It returns <code>"struct.error bad char in struct format"</code> for some reason. What's going on? I tried a lot of resources but nobody had an example of this happening. I've tried other formats besides <code>'utf-8'</code>, such as <code>'ascii'</code>.</p> <p>edit - there seems to be confusion; maybe i should have given my problem in less general terms: </p> <p>I am attempting to write a command that will decode a bytes object created using f.read, in a variable format, and I tried to do it this way: </p> <p>Value = struct.unpack(Format, Bytes)[0]</p> <p>where Bytes = f.read(Length) and Format = 'i' or 'd' or whatever it needs to be. </p> <p>What I tried worked great for the case of an integer ('i') but did not work for the case of a string of characters - I got the error instead, and I'm trying to figure out why. Thanks for any help!</p> <p>edit2 - for anyone coming after me, it looks like this is simply not possible to handle in python with a single function, because the struct.unpack function doesn't handle unicode strings and the decode. function doesn't handle encoded numbers. The only way to do what I need to do appears to be to use an if: to apply the proper function for the format</p>
-3
2016-09-12T17:51:18Z
39,456,314
<h1>EDIT</h1> <ol> <li>no <code>"i"</code> is not a valid encoding to use <code>str.decode</code> <ul> <li>see <a href="https://docs.python.org/2/library/codecs.html#standard-encodings" rel="nofollow">https://docs.python.org/2/library/codecs.html#standard-encodings</a></li> </ul></li> <li>no <code>"utf-8"</code> is not a valid format string to pass to <code>struct.unpack</code> <ul> <li>see <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="nofollow">https://docs.python.org/3/library/struct.html#format-characters</a></li> </ul></li> </ol> <h1>old anser ...</h1> <p><code>struct.unpack</code> is not the right tool to use here</p> <pre><code>b'11:10:00\x00ng '.decode("utf8") b'+\r\x00\x00'.decode("utf8") </code></pre> <p>you simply want to decode the bytes to a unicode string I believe</p> <p>if you want to <code>struct.unpack</code> a string you can ... but its just unpacking a bytestring</p> <pre><code>fmt = "bb5s" #2 bytes and a string of length 5 struct.unpack(fmt,b"\x00\x12\x33\x43\x55\x77\x65") #result: (0, 18, b'3CUwe') </code></pre>
1
2016-09-12T18:13:17Z
[ "python", "struct" ]
A simple case of struct, but getting a "bad char" error
39,455,984
<p>I'm attempting to read a section of a binary file, and decode it as a string of characters using the struct. module. </p> <p>It's a simple enough case. Here is the bytes argument:</p> <pre><code>b'11:10:00\x00ng ' </code></pre> <p>and here is the function I am attempting to use: </p> <pre><code>struct.unpack('utf-8', b'11:10:00\x00ng ') </code></pre> <p>The output should be twelve characters, no?:</p> <pre><code>'11:10:00 ng ' </code></pre> <p>It returns <code>"struct.error bad char in struct format"</code> for some reason. What's going on? I tried a lot of resources but nobody had an example of this happening. I've tried other formats besides <code>'utf-8'</code>, such as <code>'ascii'</code>.</p> <p>edit - there seems to be confusion; maybe i should have given my problem in less general terms: </p> <p>I am attempting to write a command that will decode a bytes object created using f.read, in a variable format, and I tried to do it this way: </p> <p>Value = struct.unpack(Format, Bytes)[0]</p> <p>where Bytes = f.read(Length) and Format = 'i' or 'd' or whatever it needs to be. </p> <p>What I tried worked great for the case of an integer ('i') but did not work for the case of a string of characters - I got the error instead, and I'm trying to figure out why. Thanks for any help!</p> <p>edit2 - for anyone coming after me, it looks like this is simply not possible to handle in python with a single function, because the struct.unpack function doesn't handle unicode strings and the decode. function doesn't handle encoded numbers. The only way to do what I need to do appears to be to use an if: to apply the proper function for the format</p>
-3
2016-09-12T17:51:18Z
39,456,358
<p>The struct module does a completely different job from what you're trying to do. It's for deserializing data that looks like serialized C structs (hence the name). <code>int</code>s, <code>double</code>s, fixed-size <code>char</code> arrays, things like that, packed together in a rigid layout with fixed alignment and padding. If you look at the <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">docs</a>, you'll see nothing related to Unicode codecs, and the format string argument format looks nothing like a codec name.</p> <p>You want the built-in bytestring <code>decode</code> method, which does Unicode decoding:</p> <pre><code>b'11:10:00\x00ng '.decode('utf-8') </code></pre> <p>though that <code>\x00</code> will still be a Unicode NUL, not a space, because Unicode doesn't work like that.</p>
1
2016-09-12T18:16:27Z
[ "python", "struct" ]
Data from socket.recv() printing as a mixture of \x and printable ASCII, how to force raw hex?
39,455,997
<p>I have some simple code which is listening to data on a TCP socket:</p> <pre><code> data = client_socket.recv(4096) print("RECEIVED:",data) </code></pre> <p>It works great, but the output looks like this:</p> <pre><code>RECEIVED: b'\xd8\xff\xfe\x00$\xe3J\xda*\x00 </code></pre> <p>and so on.</p> <p>What I want is just the raw hex, like </p> <pre><code>D8 FF FE 00 24 E3 4A DA 2A 00 </code></pre> <p>My end goal is to put the raw bytes straight into a file, but I do want to print them first. How do I print them as I desire, and how do I put them into a file? Maybe I do not even need to manipulate 'data' to put it in a file?</p> <p>Thanks very much!</p>
0
2016-09-12T17:52:27Z
39,456,059
<pre><code>import binascii binascii.hexlify('\xd8\xff\xfe\x00$\xe3J\xda*\x00').upper() </code></pre> <p>gets you most of the way ...</p>
0
2016-09-12T17:55:41Z
[ "python", "tcp" ]
Python Recursion vs Iteration
39,456,149
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p> <blockquote> <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p> </blockquote> <p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p> <p>Now here is my code:</p> <pre><code>my_list1 = [] my_list2 = [] def replicate_iter(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &gt; 0: x = 0 while x &lt; times: my_list2.append(data) x = x+1 return my_list2 else: return [] except (ValueError,AttributeError,TypeError): raise ValueError('Invalid Argument') def replicate_recur(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &lt;= 0: return my_list1 else: my_list1.append(data) return replicate_recur(times-1,data) except(AttributeError,TypeError): raise ValueError('Invalid Argument') </code></pre>
-1
2016-09-12T18:01:52Z
39,456,272
<pre><code>def replicate(c,times): return [c]*times def replicate2(c,times): return [c for i in range(times)] def replicate3(c,times): result = [] for i in range(times): result.append(c) return result def replicate4(c,times): return [c] + (replicate4(c,times-1) if times &gt; 0 else []) </code></pre>
1
2016-09-12T18:10:51Z
[ "python", "recursion", "iteration" ]
Python Recursion vs Iteration
39,456,149
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p> <blockquote> <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p> </blockquote> <p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p> <p>Now here is my code:</p> <pre><code>my_list1 = [] my_list2 = [] def replicate_iter(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &gt; 0: x = 0 while x &lt; times: my_list2.append(data) x = x+1 return my_list2 else: return [] except (ValueError,AttributeError,TypeError): raise ValueError('Invalid Argument') def replicate_recur(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &lt;= 0: return my_list1 else: my_list1.append(data) return replicate_recur(times-1,data) except(AttributeError,TypeError): raise ValueError('Invalid Argument') </code></pre>
-1
2016-09-12T18:01:52Z
39,456,289
<pre><code>def replicate_iter(times, data): if not isinstance(data, int) and not isinstance(data, str): raise ValueError('Must be int or str') if times &lt;= 0: return [] return [data for _ in range(times)] def replicate_recur(times, data): if not isinstance(data, int) and not isinstance(data, str): raise ValueError('Must be int or str') if times &lt;= 0: return [] return [data] + replicate_recur(times-1, data) </code></pre> <p>Output</p> <pre><code>&gt;&gt;&gt; replicate_iter(3, 5) [5, 5, 5] &gt;&gt;&gt; replicate_recur(3, 5) [5, 5, 5] </code></pre> <p>Edge cases</p> <pre><code>&gt;&gt;&gt; replicate_iter(0, 5) [] &gt;&gt;&gt; replicate_iter(3, list()) Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; replicate_iter(3, list()) File "C:/temp/temp.py", line 3, in replicate_iter raise ValueError('Must be int or str') ValueError: Must be int or str </code></pre>
0
2016-09-12T18:12:01Z
[ "python", "recursion", "iteration" ]
Python Recursion vs Iteration
39,456,149
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p> <blockquote> <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p> </blockquote> <p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p> <p>Now here is my code:</p> <pre><code>my_list1 = [] my_list2 = [] def replicate_iter(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &gt; 0: x = 0 while x &lt; times: my_list2.append(data) x = x+1 return my_list2 else: return [] except (ValueError,AttributeError,TypeError): raise ValueError('Invalid Argument') def replicate_recur(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &lt;= 0: return my_list1 else: my_list1.append(data) return replicate_recur(times-1,data) except(AttributeError,TypeError): raise ValueError('Invalid Argument') </code></pre>
-1
2016-09-12T18:01:52Z
39,456,450
<p>Basic implementation for both (although they are not good Python to be honest) would be:</p> <pre><code>def replicate_iter(times, data): result = [] for _ in range(times): # xrange in Python2 result.append(data) return result def replicate_recur(times, data): if times &lt;= 0: return [] return [data] + replicate_recur(times - 1, data) assert replicate_iter(3, 5) == [5, 5, 5] assert replicate_recur(3, 5) == [5, 5, 5] assert replicate_iter(4, "abc") == ["abc", "abc", "abc", "abc"] assert replicate_recur(4, "abc") == ["abc", "abc", "abc", "abc"] </code></pre> <p>They are simple, straightforward and shows basic differences between both approaches.</p> <p>Pythonic code would either use multiplying a sequence or list comprehension:</p> <pre><code>result = [data for _ in range(times)] result = [data] * times </code></pre> <p>Recursion wouldn't really be used for this task in any production code.</p>
1
2016-09-12T18:22:21Z
[ "python", "recursion", "iteration" ]
Python Recursion vs Iteration
39,456,149
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p> <blockquote> <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p> </blockquote> <p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p> <p>Now here is my code:</p> <pre><code>my_list1 = [] my_list2 = [] def replicate_iter(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &gt; 0: x = 0 while x &lt; times: my_list2.append(data) x = x+1 return my_list2 else: return [] except (ValueError,AttributeError,TypeError): raise ValueError('Invalid Argument') def replicate_recur(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &lt;= 0: return my_list1 else: my_list1.append(data) return replicate_recur(times-1,data) except(AttributeError,TypeError): raise ValueError('Invalid Argument') </code></pre>
-1
2016-09-12T18:01:52Z
39,456,972
<p>I think your code is closer to being correct than other folks are saying -- you just need to rearrange some elements:</p> <pre><code>def replicate_iter(times, data): if type(data) != int and type(data) != str: raise TypeError('Invalid Argument') try: my_list = [] if times &gt; 0: for _ in range(times): my_list.append(data) return my_list except (ValueError, TypeError): raise ValueError('Invalid Argument') from None def replicate_recur(times, data): if type(data) != int and type(data) != str: raise TypeError('Invalid Argument') try: my_list = [] if times &gt; 0: my_list.append(data) my_list.extend(replicate_recur(times - 1, data)) return my_list except (ValueError, TypeError): raise ValueError('Invalid Argument') from None </code></pre> <p>I agree the error handling is a bit complicated but that's what the specification called for. Though specific about the <code>times</code> argument, the specification was ambiguous about which error to generate if the <code>data</code> isn't one of the accepted types, but TypeError seems to make sense.</p>
1
2016-09-12T18:58:45Z
[ "python", "recursion", "iteration" ]
Python Recursion vs Iteration
39,456,149
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p> <blockquote> <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p> </blockquote> <p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p> <p>Now here is my code:</p> <pre><code>my_list1 = [] my_list2 = [] def replicate_iter(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &gt; 0: x = 0 while x &lt; times: my_list2.append(data) x = x+1 return my_list2 else: return [] except (ValueError,AttributeError,TypeError): raise ValueError('Invalid Argument') def replicate_recur(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &lt;= 0: return my_list1 else: my_list1.append(data) return replicate_recur(times-1,data) except(AttributeError,TypeError): raise ValueError('Invalid Argument') </code></pre>
-1
2016-09-12T18:01:52Z
39,457,423
<p>for the recursive version I recommend <a href="https://en.wikipedia.org/wiki/Tail_call" rel="nofollow">tail recursion</a> as you are already doing, the other examples even if simplest use list concatenation (<code>+</code>) which produce a new list with a copy of the elements of each, that is too much waste of time and space when you can pass around a single list where you add elements to it as you do with a iterative version</p> <p>here is a example </p> <pre><code>def replicate_recur(times, data, result=None): if result is None: result = [] if times &lt;= 0 : return result else: result.append(data) return replicate_recur(times-1,data,result) </code></pre> <p>Additionally, you can avoid repeat the same check over and over again by using an auxiliary function</p> <pre><code>def replicate_recur_aux(times, data, result): if times &lt;= 0 : return result else: result.append(data) return replicate_recur_aux(times-1,data,result) def replicate_recur(times, data): if not isinstance(data, int) and not isinstance(data, str): raise ValueError('Invalid Argument') return replicate_recur_aux(times,data,[]) </code></pre> <p>this way the main function do all the check that needs to be done and all the necessary setup just once so the auxiliary function do its job without any worry or unnecessary checks of the same thing.</p> <p>For the iterative version, any of the other examples are good, but maybe your teacher want something like this</p> <pre><code>def replicate_iter(times, data): if not isinstance(data, int) and not isinstance(data, str): raise ValueError('Invalid Argument') result = [] if times &lt;=0: return result for i in range(times): result.append(data) return result </code></pre> <p>now notice the similarity between both version, you can easy transform one into the other </p>
1
2016-09-12T19:28:02Z
[ "python", "recursion", "iteration" ]
Python Recursion vs Iteration
39,456,149
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p> <blockquote> <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p> </blockquote> <p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p> <p>Now here is my code:</p> <pre><code>my_list1 = [] my_list2 = [] def replicate_iter(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &gt; 0: x = 0 while x &lt; times: my_list2.append(data) x = x+1 return my_list2 else: return [] except (ValueError,AttributeError,TypeError): raise ValueError('Invalid Argument') def replicate_recur(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &lt;= 0: return my_list1 else: my_list1.append(data) return replicate_recur(times-1,data) except(AttributeError,TypeError): raise ValueError('Invalid Argument') </code></pre>
-1
2016-09-12T18:01:52Z
39,459,754
<p>This works!</p> <pre><code>def replicate_iter(times, data): if((not isinstance(times, int)) or (not isinstance(data, (int, float, long, complex, str)))): raise ValueError("Invalid arguments") elif(times &lt;= 0): return [] else: array = [] for x in range(times): array.append(data) return array def replicate_recur(times, data): if((not isinstance(times, int)) or (not isinstance(data, (int, float, long, complex, str)))): raise ValueError("Invalid arguments") elif(times &lt;= 0): return [] else: return ([data] + replicate_recur((times - 1), data)) </code></pre>
2
2016-09-12T22:34:30Z
[ "python", "recursion", "iteration" ]
Python Recursion vs Iteration
39,456,149
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p> <blockquote> <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p> </blockquote> <p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p> <p>Now here is my code:</p> <pre><code>my_list1 = [] my_list2 = [] def replicate_iter(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &gt; 0: x = 0 while x &lt; times: my_list2.append(data) x = x+1 return my_list2 else: return [] except (ValueError,AttributeError,TypeError): raise ValueError('Invalid Argument') def replicate_recur(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &lt;= 0: return my_list1 else: my_list1.append(data) return replicate_recur(times-1,data) except(AttributeError,TypeError): raise ValueError('Invalid Argument') </code></pre>
-1
2016-09-12T18:01:52Z
39,462,465
<p>I think the iterative version is straightforward, and others have provided good answers. As for the recursion, I always like to see if I can come up with a divide and conquer strategy rather than whittle the problem down one step at a time, to avoid blowing out the stack. The following does that:</p> <pre><code>def replicate_recur(times, data): def f(n, value): if n &lt; 1: return [] result = f(n // 2, value) * 2 if n % 2 &gt; 0: result += [value] return result if not isinstance(data, int) and not isinstance(data, str): raise ValueError('Must be int or str') return f(times, data) </code></pre> <p>This uses an internal recursive function <code>f()</code> to avoid repeating the type checking for <code>data</code>. The recursion constructs a list of half the size, and either doubles it (if the current <code>n</code> is even) or doubles it and adds one more occurrence of <code>data</code> (if the current <code>n</code> is odd).</p> <p>Try it, you'll like it!</p>
1
2016-09-13T04:59:37Z
[ "python", "recursion", "iteration" ]
Python Recursion vs Iteration
39,456,149
<p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p> <blockquote> <p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the number of times to repeat and data which is the number or string to be repeated.</p> </blockquote> <p>The function should return an array containing repetitions of the data argument. For instance, <code>replicate_recur(3, 5)</code> or <code>replicate_iter(3,5)</code> should return <code>[5,5,5]</code>. If the times argument is negative or zero, return an empty array. If the argument is invalid, raise a <code>ValueError</code>."</p> <p>Now here is my code:</p> <pre><code>my_list1 = [] my_list2 = [] def replicate_iter(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &gt; 0: x = 0 while x &lt; times: my_list2.append(data) x = x+1 return my_list2 else: return [] except (ValueError,AttributeError,TypeError): raise ValueError('Invalid Argument') def replicate_recur(times,data): try: if type(data) != int and type(data) != str: raise ValueError('Invalid Argument') times += 0 if times &lt;= 0: return my_list1 else: my_list1.append(data) return replicate_recur(times-1,data) except(AttributeError,TypeError): raise ValueError('Invalid Argument') </code></pre>
-1
2016-09-12T18:01:52Z
39,563,723
<p>def replicate_recur(times, data): list = [] if (times &lt;= 0): return [] elif(type(times) != int and type(data) != str): raise ValueError ("invalid")</p> <pre><code>elif(times &gt; 0): list.append(data) return list + replicate_recur(times -1, data) </code></pre> <p>def replicate_iter(times, data): list = [] if (times &lt;= 0): return list elif(type(times) != int and type(data) != str): raise ValueError elif (times > 0): for i in range(times): list.append(data) return list </p>
0
2016-09-18T23:57:43Z
[ "python", "recursion", "iteration" ]