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
How to add values to keys in a dictionary for keys found in a file? Python
38,588,876
<p>So I have a csv file, from which I have to find the average price for all products grouped by category. I managed to put all lines from the file into a list. Now I'm trying this:</p> <pre><code>FILE_NAME = 'catalog_sample.csv' full_catalog = [] with open(FILE_NAME, encoding='utf-8') as file: for line in file...
-1
2016-07-26T11:37:54Z
38,593,832
<p>I suggest creating your dictionary while going through the file, instead of adding them to a list and going back through it to construct the dictionary.</p> <pre><code>category_dict = {} full_catalog = [] with open(FILE_NAME, encoding='utf-8') as file: for line in file: item = line.split(',') #...
0
2016-07-26T15:18:19Z
[ "python", "list", "file", "python-3.x", "dictionary" ]
Can't save ManyToManyField
38,588,878
<p>So the problem is that I can't save ManyToManyField from form.</p> <p>forms.py</p> <pre><code>class addGoods(forms.Form): ... permission = form['permission'], ... </code></pre> <p>models.py</p> <pre><code>class Add_good(models.Model): ... permission = models.ManyToManyField(Permission, relate...
-1
2016-07-26T11:37:58Z
38,589,172
<p>The problem is here: <code>newGood = Add_good(permission = form['permission'])</code></p> <p>Permission is ManyToMany field, so your table doesn't directly have <code>permision</code> field, so it can't take that argument. You can create the model entry then add the permission:</p> <pre><code>newGood = Add_good.o...
2
2016-07-26T11:53:08Z
[ "python", "django", "forms" ]
Python netcdf - convert specified values to NaN
38,588,902
<p>I'm plotting pcolourmesh of wind data from satellites and from a weather model. The values are all stored in a netcdf file. Below I try to replace values equal to 70 or 0 with NaN, this doesn't give an error but it doesn't create NaNs either, <code>nozeros</code> is the same size as the original dataset. I have look...
0
2016-07-26T11:39:18Z
38,593,207
<p>There are several issues in your code, setting aside the indentation syntax errors.</p> <p>The code below will do nothing. What is <code>i</code> ? The result is not saved.</p> <pre><code>for i in SARwind_nan: if i.any() == 70: i = np.nan ... </code></pre> <p>Here's an example whi...
1
2016-07-26T14:51:00Z
[ "python", "python-2.7", null, "netcdf" ]
Python, Better way of coding. Using Loop Array?
38,588,946
<p>Im just starting to learn python and was wondering if there was a better way to code the following.</p> <pre><code>user1 = "username" userkey1 = "userkey" user2 = "username" userkey2 = "userkey" user3 = "username" userkey3 = "userkey" user4 = "username" userkey4 = "userkey" user5 = "username" userkey5 = "userkey" u...
0
2016-07-26T11:41:07Z
38,591,189
<p>If your code is working the way you want it good. But the long variable definitions is to much. Look up (google) python list and dictionary. Check out this post: <a href="http://stackoverflow.com/questions/9495950/how-to-implement-associative-array-not-dictionary-in-python">How to implement associative array in Pyth...
0
2016-07-26T13:27:21Z
[ "python" ]
How to count sentences taking into account the occurrence of ellipses
38,588,985
<p>I've written the following script to count the number of sentences in a text file:</p> <pre><code>import re filepath = 'sample_text_with_ellipsis.txt' with open(filepath, 'r') as f: read_data = f.read() sentences = re.split(r'[.{1}!?]+', read_data.replace('\n','')) sentences = sentences[:-1] sentence_count =...
1
2016-07-26T11:43:16Z
38,589,115
<p>Splitting sentences with a regex like this is not enough. See <a href="http://stackoverflow.com/questions/4576077/python-split-text-on-sentences"><em>Python split text on sentences</em></a> to see how NLTK can be leveraged for this.</p> <p>Answering your question, you call 3 dot sequence an ellipsis. Thus, you nee...
4
2016-07-26T11:49:39Z
[ "python", "regex" ]
How to count sentences taking into account the occurrence of ellipses
38,588,985
<p>I've written the following script to count the number of sentences in a text file:</p> <pre><code>import re filepath = 'sample_text_with_ellipsis.txt' with open(filepath, 'r') as f: read_data = f.read() sentences = re.split(r'[.{1}!?]+', read_data.replace('\n','')) sentences = sentences[:-1] sentence_count =...
1
2016-07-26T11:43:16Z
38,593,479
<p>Following Wiktor's suggestion to use NLTK, I also came up with the following alternative solution:</p> <pre><code>import nltk read_data="Wait for it... awesome!" sentence_count = len(nltk.tokenize.sent_tokenize(read_data)) </code></pre> <p>This yields a sentence count of 1 as expected.</p>
0
2016-07-26T15:03:01Z
[ "python", "regex" ]
how to slice a dataframe from the end to the beginning?
38,588,991
<p>I am slicing a dataframe like this:</p> <pre><code>for i in xrange(0,len(df),100000): print("slice %d!!!!" % i) slice= df.iloc[i:(i+100000)] </code></pre> <p>I would like now to get <code>100k</code> slices <strong>from the end to the beginning</strong> of the df (without necessarily sorting my dataframe)....
0
2016-07-26T11:43:24Z
38,589,061
<p>Simply use <code>tail</code>:</p> <pre><code>df.tail(100000) </code></pre>
2
2016-07-26T11:47:21Z
[ "python", "pandas", "indexing", "dataframe", "slice" ]
how to slice a dataframe from the end to the beginning?
38,588,991
<p>I am slicing a dataframe like this:</p> <pre><code>for i in xrange(0,len(df),100000): print("slice %d!!!!" % i) slice= df.iloc[i:(i+100000)] </code></pre> <p>I would like now to get <code>100k</code> slices <strong>from the end to the beginning</strong> of the df (without necessarily sorting my dataframe)....
0
2016-07-26T11:43:24Z
38,590,484
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a>:</p> <pre><code>df.iloc[-100000:] </code></pre>
1
2016-07-26T12:54:41Z
[ "python", "pandas", "indexing", "dataframe", "slice" ]
how to find the black region in near the edge
38,589,119
<p>I have an image like below. It has black border/regions in the top and right side of the image. I want to be able to find these regions like shown in the 2nd images. Note these regions should be always streight (ie rectangle shaped). I want to be able to do this using 'image processing with code not with photoshop' ...
-5
2016-07-26T11:50:03Z
38,589,682
<p>Using Python2.7 + OpenCV3. The idea is to keep only non-zero rows and columns. The code follows.</p> <pre><code>import cv2 import numpy as np #Read in the image arr = np.array(cv2.imread('image.jpg')) #Convert to grayscale gray = np.sum(arr, axis=2) print gray.shape #(496, 1536) filter_row = np.sum(gray,axis=1)!=0 ...
1
2016-07-26T12:16:05Z
[ "python", "matlab", "opencv", "image-processing" ]
how to find the black region in near the edge
38,589,119
<p>I have an image like below. It has black border/regions in the top and right side of the image. I want to be able to find these regions like shown in the 2nd images. Note these regions should be always streight (ie rectangle shaped). I want to be able to do this using 'image processing with code not with photoshop' ...
-5
2016-07-26T11:50:03Z
38,590,485
<pre><code>color_img = imread('0k4Kh.jpg'); img = rgb2gray(color_img); [x, y] = size(img); for i = 1:x if length(find(img(i, :))) ~= 0 lastmarginalrow = i-1; break; end end for ii = y:-1:1 if length(find(img(:, ii))) ~= 0 lastmarginalcol = ii-1; break; end end figure; ...
1
2016-07-26T12:54:41Z
[ "python", "matlab", "opencv", "image-processing" ]
Pythonic way of zeroing numpy array axis
38,589,133
<p>Bit annoyed I haven't been able to get this myself, so here goes. </p> <p>Say I have a 2 dimensional numpy array</p> <pre><code>import numpy as np a = np.array([[1,2,3],[4,5,6],[7,8,9]]) </code></pre> <p>I am in a situation where I want to zero a column in this array, but maintain the original array. I can do thi...
1
2016-07-26T11:50:57Z
38,589,360
<p>To set certain columns as zeros, you can use <code>np.in1d</code> alongwith <code>np.arange</code> to create a mask of invalid elements, which when multiplied with the input array would set the invalid columns as zeros using <code>NumPy broadcasting</code>. Thus, we would have an one-liner implementation, like so -<...
2
2016-07-26T12:02:00Z
[ "python", "numpy" ]
PHP exec command runs python script but not python3
38,589,183
<p>I currently have python 2.7 installed as part of OSX, and recently installed 3.5.2. </p> <p>I'm running a local webserver on my mac using XAMPP, and when I execute the python script from within apache, it loads fine:</p> <pre><code>$executePython = "python " . __DIR__ . "/cycle/cutoff.py $device_id $processPreviou...
2
2016-07-26T11:53:36Z
38,610,901
<p>We don't want to mess up with the system wide path on the latest OSX. What if you add the python3 path in your script like this and then do your normal stuff</p> <pre><code>putenv("PATH=/usr/local/bin/:" . exec('echo $PATH')); $executePython = "python3 " . __DIR__ . "/cycle/cutoff.py $device_id $processPreviousMinu...
2
2016-07-27T10:51:37Z
[ "php", "python", "apache", "python-3.x", "xampp" ]
Scrapy: Images Pipeline, download images
38,589,188
<p>Following: <a href="http://doc.scrapy.org/en/latest/topics/media-pipeline.html" rel="nofollow">scrapy's</a> tutorial i made a simple image crawler (scrapes images of Bugattis). Which is illustrated below in <strong>EXAMPLE</strong>.</p> <p>However, following the guide has left me with a non functioning crawler! It ...
0
2016-07-26T11:53:48Z
38,590,546
<p>The item your spider returns must contains fields <code>"file_urls"</code> for files and/or <code>"image_urls"</code> for images. In your code you specify settings for Image pipeline but your return urls in <code>"file_urls"</code>.</p> <p>Simply change this line: </p> <pre><code>yield ImageItem(file_urls=[img_ur...
1
2016-07-26T12:58:03Z
[ "python", "scrapy", "scrapy-spider", "scraper" ]
Recursively searching an object and editing a string when found
38,589,221
<p>I am new to python and having issues dealing with immutable strings. My problem is as follows:</p> <p>I have a tree where each node is a dictionary and each node has variable number of children. I have multiple operations I wish to perform on this tree and therefore recursively traverse it.</p> <p>The setup is tha...
0
2016-07-26T11:54:51Z
38,589,568
<p>Your <code>enterFunc</code> and <code>leaveFunc</code> should return the modified object instead of attempting to modify it in-place. Then the <code>__recursiveDive</code> function can replace the original object with the returned object.</p> <p>Usually you'd implement <code>__recursiveDive</code> in such a way tha...
1
2016-07-26T12:11:47Z
[ "python", "string", "design-patterns", "recursion", "immutability" ]
Adapting binary stacking example to multiclass
38,589,230
<p>I have been studying <a href="https://github.com/emanuele/kaggle_pbr/blob/master/blend.py" rel="nofollow">this example of stacking</a>. In this case, each set of K-folds produces one column of data, and this is repeated for each classifier. I.e: the matrices for blending are:</p> <pre><code>dataset_blend_train = np...
4
2016-07-26T11:55:19Z
38,796,945
<p>You can adapt the code to the multi-class problem in two ways:</p> <ol> <li>Concatenate horizontally the probabilities, that is you will need to create: <code>dataset_blend_train = np.zeros((X.shape[0], len(clfs)*numOfClasses))</code> <code>dataset_blend_test = np.zeros((X_submission.shape[0], len(clfs)*numOfClasse...
2
2016-08-05T19:58:38Z
[ "python", "matrix", "machine-learning", "ensemble-learning", "ensembles" ]
tensorflow : .eval() never ends
38,589,255
<p>i am loading the cifar-10 data set , the methods adds the data to tensor array , so to access the data i used .eval() with session , on a normal tf constant it return the value , but on the labels and the train set which are tf array it wont</p> <p>1- i am using docker tensorflow-jupyter</p> <p>2- it uses python...
0
2016-07-26T11:56:28Z
38,595,382
<p>You must call <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/train.html#start_queue_runners" rel="nofollow"><code>tf.train.start_queue_runners(sess)</code></a> before you call <code>train_data.eval()</code> or <code>train_labels.eval()</code>.</p> <p>This is a(n unfortunate) consequence of how Te...
1
2016-07-26T16:35:09Z
[ "python", "eval", "tensorflow", "jupyter-notebook" ]
Selenium find button element
38,589,434
<p>I want to find a button element on a website with <code>selenium</code> on <code>python 3</code> . I try some different method but all failed . I use <code>Xpath</code> to find my element but i don't know if it's the better method :</p> <p>This is the <code>HTML</code> code :</p> <pre><code>&lt;div id="review-butt...
0
2016-07-26T12:05:12Z
38,590,490
<p>You can use <code>ActionChains</code> to move to the element before clicking on it</p> <pre><code>from selenium.webdriver.common.action_chains import ActionChains element = br.find_element_by_xpath("//input[@id='place_order']") ActionChains(br).move_to_element(element).perform() # I assume br is your webdriver ele...
1
2016-07-26T12:54:57Z
[ "python", "html", "python-3.x", "selenium", "selenium-webdriver" ]
Selenium find button element
38,589,434
<p>I want to find a button element on a website with <code>selenium</code> on <code>python 3</code> . I try some different method but all failed . I use <code>Xpath</code> to find my element but i don't know if it's the better method :</p> <p>This is the <code>HTML</code> code :</p> <pre><code>&lt;div id="review-butt...
0
2016-07-26T12:05:12Z
38,632,277
<p>Yo can try to scroll to this button before clicking using its location and js</p> <pre><code>element = driver.find_element_by_id("place_order") element_position = element.location["y"] driver.execute_script("window.scroll(0, {})".format(element_position)) time.sleep(1) #may not be required element.click() </code>...
0
2016-07-28T09:26:21Z
[ "python", "html", "python-3.x", "selenium", "selenium-webdriver" ]
Pip Install - "Invalid requirement"
38,589,570
<p>I run the following command in my terminal:</p> <pre><code>pip install -r requirements-dev.txt </code></pre> <p>I get the following error:</p> <pre><code>Invalid requirement: 'nose=1.3.7' = is not a valid operator. Did you mean == ? </code></pre> <p>requirements-dev.txt looks like this:</p> <pre><code>nose=1.3....
-5
2016-07-26T12:11:48Z
38,589,856
<p><code>pip</code> does not specify any behavior for <code>=</code> in its specification, rather <code>==</code> (which you intend) referred to as <a href="https://www.python.org/dev/peps/pep-0440/#version-matching" rel="nofollow">version matching</a>, among others.</p> <p>For your later use, all the currently availa...
1
2016-07-26T12:24:16Z
[ "python", "pip" ]
getting last n items from queue
38,589,668
<p>everything I see is about lists but this is about <code>events = queue.queue()</code> which is a queue with objects that I want to extract, but how would I go about getting the last N elements from that queue?</p>
1
2016-07-26T12:15:35Z
38,589,764
<p>By definition, you can't.</p> <p>What you can do is use a loop or a comprehension to <code>get</code> the <strong>first</strong> (you can't <code>get</code> from the end of a <code>queue</code>) N elements:</p> <pre><code>N = 2 first_N_elements = [my_queue.get() for _ in range(N)] </code></pre>
1
2016-07-26T12:20:35Z
[ "python", "queue" ]
getting last n items from queue
38,589,668
<p>everything I see is about lists but this is about <code>events = queue.queue()</code> which is a queue with objects that I want to extract, but how would I go about getting the last N elements from that queue?</p>
1
2016-07-26T12:15:35Z
38,590,207
<p>If you're multi-threading, "the last N elements from that queue" is undefined and the question doesn't make sense.</p> <p>If there is no multi-threading, it depends on whether you care about the other elements (not the last N).</p> <p>If you don't:</p> <pre><code>for i in range(events.qsize() - N): events.get...
0
2016-07-26T12:41:36Z
[ "python", "queue" ]
Django Developer Server can't be reached from foreign IP
38,589,723
<p>I'm trying to access Django Developer Server from foreign IP but it is not working. </p> <p>I have created a test application in the server. I've created a test virtual environment also.</p> <p>I start the Developer Server using the following command:</p> <pre><code>env/bin/python manage.py runserver 0.0.0.0:8080...
1
2016-07-26T12:18:18Z
38,591,265
<p>First check yourMachineIp address and then following may work for you.</p> <p>Try run server as <code>env/bin/python manage.py runserver YourMachineIp:8080</code> still if you get same error try to change port number for example <code>env/bin/python manage.py runserver YourMachineIp:8134</code>. </p> <p>And you ca...
-1
2016-07-26T13:30:06Z
[ "python", "django" ]
Django testing, mock valid requests to urls
38,589,774
<p>I have a bunch of urls in my urls.py file that have the login_required decorator</p> <pre><code># Index Page url(r'^$', login_required(views.IndexPage.as_view()), name='index'), # Schedule urls url(r'^schedules/$', login_required(views.ScheduleListView.as_view()), name='schedule-list'), url(r'^schedule/(?P&lt;...
1
2016-07-26T12:20:58Z
38,589,858
<p>in the proect_name/project_name/urls.py <code>urlpatterns = [ url(r'', login_required(include('app_name.urls')), ]</code></p> <p>This will apply login_required to all urls in the project_name/app_name/urls.py</p>
1
2016-07-26T12:24:20Z
[ "python", "django", "unit-testing" ]
Django testing, mock valid requests to urls
38,589,774
<p>I have a bunch of urls in my urls.py file that have the login_required decorator</p> <pre><code># Index Page url(r'^$', login_required(views.IndexPage.as_view()), name='index'), # Schedule urls url(r'^schedules/$', login_required(views.ScheduleListView.as_view()), name='schedule-list'), url(r'^schedule/(?P&lt;...
1
2016-07-26T12:20:58Z
38,591,036
<p>You're trying to test something very complicated because you've decided to use <code>login_required</code> to <a href="https://docs.djangoproject.com/en/1.9/topics/class-based-views/intro/#decorating-in-urlconf" rel="nofollow">decorate the urlconf</a>. </p> <p>Why not <a href="https://docs.djangoproject.com/en/1.9/...
2
2016-07-26T13:20:41Z
[ "python", "django", "unit-testing" ]
mongoengine: how to query on a non-ascii StringField in EmbeddedDocumentListField
38,589,820
<p>when I run a query like </p> <pre><code>answerSheet = answerSheet.subAnswerSheets.get( title=subquiz.title) </code></pre> <p>when my title is non-ascii, I get encode error on this method of EmbeddedDocumentList class in datastructures.py of mongoengine:</p> <pre><code>@classmethod def __match_all(cls, i, ...
0
2016-07-26T12:23:06Z
38,591,114
<p>Hope so this will work for you:</p> <pre><code>title = subquiz.title.encode('ascii',errors='ignore') </code></pre>
0
2016-07-26T13:23:58Z
[ "python", "django", "mongoengine" ]
python getattr built_in method executes default arguments
38,589,823
<p>I dont know if this is something an expected behavior of <code>getattr</code> built_in method. <code>getattr</code> executes the default(3rd) argument as well even if the actual argument(2nd) satisfies the condition. Example:</p> <pre><code> def func(): print 'In Function' class A: def __ini...
2
2016-07-26T12:23:11Z
38,590,162
<p>Before <code>getattr</code> gets executed, all the passed parameters have to be evaluated. <code>func()</code> is one of those parameters and an attempt to evaluate it will execute the <code>print</code> statement. Whether the attribute will be found or not, <code>func()</code> must be evaluated apriori.</p> <p>Thi...
4
2016-07-26T12:39:35Z
[ "python", "python-2.7", "getattr" ]
Django crontab not executing test function
38,589,830
<p>I have following:</p> <ol> <li><pre><code> python manage.py crontab show # this command give following Currently active jobs in crontab: 12151a7f59f3f0be816fa30b31e7cc4d -&gt; ('*/1 * * * *', 'media_api_server.cron.cronSendEmail') </code></pre></li> <li><p>My app is in virtual environment (env) active</p></li...
0
2016-07-26T12:23:35Z
38,592,589
<p>Your code actually works. You may be think that <code>print("Hello")</code> should appear in stdout? So it doesn't work that way, because cron doesn't use <code>stdour</code> and <code>stderr</code> for it's output. To see actual results you should point path to some log file in <code>CRONJOBS</code> list: just put ...
0
2016-07-26T14:26:21Z
[ "python", "django" ]
How to understand docs and use the module
38,589,834
<p>I've been struggling for a while understanding the documentation of any module:</p> <p>I want to use the <code>selenium</code> module.</p> <p>Looking at the documentation, I can't really implement anything.</p> <p>Given this part of the Docs API : <a href="http://selenium-python.readthedocs.io/api.html#module-sel...
0
2016-07-26T12:23:39Z
38,590,253
<p>I am not able to explain how to read 'any piece of documentation' (I don't think anyone can). However, I can help you in the good direction by giving you an idea of how <em>I</em> start with new modules.</p> <p>Normally, each module not only has a documentation part but also a 'Getting Started' part: which is <a hr...
0
2016-07-26T12:43:44Z
[ "python", "python-3.x", "selenium", "selenium-webdriver", "documentation" ]
what does " ...:" mean in Ipython console anaconda?
38,589,901
<p>I am trying to print a dataframe into a csv directly from Ipython Console, but I get this symbol and then nothing " ...:". <strong>What does the symbol mean?</strong> </p> <p><strong>Is there anyway I can force my csv to print ?</strong> </p> <p>Code:</p> <pre><code>import ET_Client import pandas as pd Aggrea...
-1
2016-07-26T12:26:59Z
38,591,825
<h1>Display Sizing</h1> <p>When <code>pandas</code> is printing to the console in iPython/Jupyter, it uses <code>...</code> to show that there is data in-between rows of the data displayed on the output. This is useful when the data is to large to print every single value. This is the default behavior unless you ove...
2
2016-07-26T13:52:58Z
[ "python", "pandas", "dataframe", "anaconda", "export-to-csv" ]
Python - pysqlite or sqlite3 must be installed
38,589,963
<p>I have python 2.7.12 installed on my server. I'm using PuTTY to connect to my server. When running my python script I get the following. </p> <blockquote> <p>File "home/myuser/python/lib/python2.7/site-packages/peewee.py", line 3657, in _connect raise ImproperlyConfigured('pysqlite or sqlite3 must be instal...
1
2016-07-26T12:30:00Z
38,715,072
<p>Peewee will use either the standard library <code>sqlite3</code> module or, if you did not compile Python with SQLite, Peewee will look for <code>pysqlite2</code>.</p> <p>The problem is most definitely <strong>not</strong> with Peewee on this one, as Peewee requires a SQLite driver to use the <code>SqliteDatabase</...
0
2016-08-02T08:10:34Z
[ "python", "sqlite" ]
My Python Scrapy cannot scrape out the "keyword" content
38,590,058
<p>I cannot scrapy the "keyword" content. >"&lt; I've tried many methods but still failed.</p> <p>I've successfully retrieved other contents, but still failed to get the "keyword" content.</p> <p>Can anyone help to fix this bug?? The keyword content is located at "#keyword_table a", or XPath "//*[@id="keyword_table"...
0
2016-07-26T12:34:04Z
38,590,335
<p>Is there any particular reason you are using BeautifulSoup over scrapy selectors? Response your method receives already acts as a scrapy selector which can do both xpath and css selections.</p> <p>There seems to be 3 keywords in the table. You can select them with either xpath or css selectors:</p> <pre><code>resp...
0
2016-07-26T12:48:12Z
[ "python", "scrapy", "web-crawler" ]
Assign command to button - Tkinter
38,590,087
<p>I want to find out which command I have to assign to the button in my Tkinter GUI in order to print the results.</p> <p>The setup is to run aaaa.py.</p> <pre><code>def question(): import xxxx return xxxx.hoeveel() if __name__ == '__main__': from bbbb import response def juist(): return re...
1
2016-07-26T12:35:31Z
38,591,349
<p>I think I've found an answer, but I'm not sure it's the most elegant way to do it. If you know a different way and more correct way please let met know.</p> <p>So, you need to run aaaa.py</p> <pre><code>import xxxx def question(): return xxxx.hoeveel() </code></pre> <blockquote> <p>xxxx.py</p> </blockquote>...
0
2016-07-26T13:33:18Z
[ "python", "tkinter" ]
What is the output of np.asarray(scalar)?
38,590,208
<p>For a long time, I always use <code>np.array</code>, <code>np.asarray</code> and <code>np.asanyarray</code> to convert array_like list to array. </p> <p>But when converting a scalar to numpy array, I know <code>np.atleast_1d(123)</code> gives rise to the right thing, <code>array([123])</code>.</p> <p>But I'm confu...
-1
2016-07-26T12:41:37Z
38,596,297
<p>I see this <code>0d</code> case as a natural continuation of <code>nd</code>. MATLAB makes 2d the lower bound. <code>numpy</code> could have used <code>1d</code>, but instead chose <code>0d</code>. </p> <p>An array consists of a data buffer, whether the value bytes are stored, a dtype (how to interpret those byt...
2
2016-07-26T17:25:13Z
[ "python", "arrays", "numpy", "data-type-conversion" ]
Why is the dynamodb performance different between these queries?
38,590,218
<p>I have 3 tables:</p> <pre><code>table 1 ======= Size 458.54 MB Count 2,887,152 table 2 ======= Size 161.05 MB Count 1,060,444 table 3 ======= Size 4.10 GB Count 2,629,162 </code></pre> <p>I've provisioned all 3 tables to 500 read capacity units (RCU), and paginate through 20 pages using python2.7 and a simple...
1
2016-07-26T12:41:59Z
38,595,269
<p>The difference is in the boto3 response parser. Larger, more complicated objects will take longer to parse. I imagine if you look at the objects in each of those tables you'll see a correlation between more complicated objects and query speed. Transfer time also will impact things significantly.</p>
1
2016-07-26T16:29:11Z
[ "python", "amazon-web-services", "amazon-dynamodb", "boto3" ]
Python 3.4: PyQt on Windows: Crash on exit only on some computers
38,590,263
<p>I have a Python program that I packaged with <code>cx_freeze</code> to make executable. The program is strictly a desktop program for data acquisition. It works fine and exits fine on every computer, but on one desktop of one of our collaborators with Windows 7 on it, it crashes only on exit (I emphasize that no pyt...
1
2016-07-26T12:44:18Z
38,590,440
<p>It seems to have trouble freeing memory. You could try to do it manually with some function like this:</p> <pre><code>def clean(item): """Clean up the memory by closing and deleting the item if possible.""" if isinstance(item, list) or isinstance(item, dict): for _ in range(len(item)): c...
1
2016-07-26T12:53:07Z
[ "python", "crash", "pyqt", "exit", "crash-dumps" ]
Python 3.4: PyQt on Windows: Crash on exit only on some computers
38,590,263
<p>I have a Python program that I packaged with <code>cx_freeze</code> to make executable. The program is strictly a desktop program for data acquisition. It works fine and exits fine on every computer, but on one desktop of one of our collaborators with Windows 7 on it, it crashes only on exit (I emphasize that no pyt...
1
2016-07-26T12:44:18Z
40,110,481
<p>It turned out that <strong>ALL</strong> the problems I used to have with this program crashing were because of QThread (on Windows). All the users I know of that used QThread on Windows got similar issues, and for some reason no one is fixing it.</p> <p>Avoid QThread on Python. It's completely useless and more harm...
0
2016-10-18T14:07:40Z
[ "python", "crash", "pyqt", "exit", "crash-dumps" ]
How to kill subprocesses with another command python
38,590,274
<p>I am running two subprocesses in a Python server script. The purpose of the subprocesses is to stream video from my Raspberry Pi.</p> <p>My question is how to kill the subprocesses when another command is sent to the server. I am currently using Popen() to start the subprocesses. </p> <p>This is my code for when t...
0
2016-07-26T12:44:50Z
38,590,906
<p>You're missing some context here, but basically server would do something like:</p> <pre><code>while True: data = wait_for_request() if data == 'startStream': p = subprocess.Popen("raspistill --nopreview -w 640 -h 480 -q 5 -o /tmp/stream/pic.jpg -tl 100 -t 9999999 -th 0:0:0 &amp;", shell=True) ...
1
2016-07-26T13:14:16Z
[ "python", "server", "raspberry-pi", "subprocess", "kill" ]
Django manage.py runserver got AppRegistryNotReady: Models aren't loaded yet
38,590,316
<p>I hit a problem when run django from command line with manage.py runserver.</p> <p>The same code is fine with Django 1.5 several months ago.</p> <p>Today I wanna pickup the code again and run upon Django 1.8.3 and python2.7.10 .</p> <p>Now, got error here:</p> <pre><code>Traceback (most recent call last): File...
0
2016-07-26T12:46:55Z
38,590,704
<p>I think you need to change your wsgi.py file as you go for different version of Django.</p> <pre><code>import os import sys from django.core.handlers.wsgi import WSGIHandler os.environ['DJANGO_SETTINGS_MODULE'] = 'YourAppName.settings' application = WSGIHandler() </code></pre> <p>And try to comment all third par...
0
2016-07-26T13:04:08Z
[ "python", "django" ]
Export from python 3.5 to csv
38,590,391
<p>I scraped six different values with Python 3.5 using beautifulSoup. Now I have the following six variables with values:</p> <ol> <li>project_titles</li> <li>project_href</li> <li>project_desc</li> <li>project_per</li> <li>project_mon</li> <li>project_loc</li> </ol> <p>The data for e.g. "project_titles" looks loke ...
0
2016-07-26T12:50:23Z
38,590,656
<p>Here are a few hints:</p> <p>When you have a string like you want to separate on a given character, use <a class='doc-link' href="http://stackoverflow.com/documentation/python/278/string-methods/1007/split-a-string-based-on-a-delimiter-into-a-list-of-strings#t=201607261257387173865"><code>string.split</code> to get...
0
2016-07-26T13:02:08Z
[ "python", "python-3.x", "csv", "beautifulsoup", "export" ]
Django one-to-one relationships in one form
38,590,568
<p>I'm trying to make a registration form for a extension of django's user model. It has a two relationships, one to <code>User</code> and <code>Address</code>. The form needs to have all the fields from <code>User</code>, <code>UserDetails</code> and <code>Address</code>. But i'm struggling to get the correct view and...
0
2016-07-26T12:58:37Z
38,598,196
<p>You missed the <strong>unicode</strong> or <strong>str</strong> method declaration in model classes. You should always declare it. Remember that str is for python 3.x, and unicode for python 2.x.</p> <p>Here is an example for class Address and python 2:</p> <pre><code>def __unicode__(self): return '%s %s' % (...
0
2016-07-26T19:19:06Z
[ "python", "django" ]
Django one-to-one relationships in one form
38,590,568
<p>I'm trying to make a registration form for a extension of django's user model. It has a two relationships, one to <code>User</code> and <code>Address</code>. The form needs to have all the fields from <code>User</code>, <code>UserDetails</code> and <code>Address</code>. But i'm struggling to get the correct view and...
0
2016-07-26T12:58:37Z
38,633,719
<p>I had to create different forms for each model. Then combine all the instances created from the forms. See <a href="http://stackoverflow.com/a/24011448/2315022">this answer for more details</a></p>
0
2016-07-28T10:27:31Z
[ "python", "django" ]
Why can't I build this code in Sublime text 2?
38,590,600
<p>I need to build a schedule so I found an example (see In [13], Out [13])</p> <p><a href="http://playittodeath.ru/%D0%B0%D0%BD%D0%B0%D0%BB%D0%B8%D0%B7-%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85-%D0%BF%D1%80%D0%B8-%D0%BF%D0%BE%D0%BC%D0%BE%D1%89%D0%B8-python-%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D0%BA%D0%B8-%D0%B2-pandas/" rel="no...
-1
2016-07-26T12:59:29Z
38,593,661
<p>it worked when i modified my Sublime build file. Here is original:</p> <pre><code>{ "cmd": ["python", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python" } </code></pre> <p>And here is modified one:</p> <pre><code>{ "path": "/Library/Frameworks/Python....
-1
2016-07-26T15:10:50Z
[ "python", "python-2.7", "pandas", "matplotlib", "sublimetext2" ]
Can two threads use the same embedded python interpreter simultaneously?
38,590,720
<p>The title has it, but here are some elaborations. Suppose the main thread spawns another thread, where some code is loaded into python interpreter and then another thread is called which executes some more code through the same python interface (through PyImport or PyRun). Is such scenario feasable?</p>
5
2016-07-26T13:04:41Z
38,591,001
<p>If I'm following what you are asking, then yes you can do this, but the Python interpreter itself is not fully thread safe. To get around this, you must make sure each thread obtains the interpreter's <a href="https://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">GIL</a> before calling any Python code a...
2
2016-07-26T13:18:51Z
[ "python", "c++", "multithreading", "interpreter", "python-c-api" ]
Django - ManyToMany table pulling the wrong info
38,590,751
<p>I'm trying to create a linker table for a many to many relationship between these two tables. The third table will have the <code>cand_id</code> from the first table and the <code>p_id</code> from the second table. Here is my code in the candidate and <code>P_user classes</code> in models and the tables from MariaDB...
0
2016-07-26T13:05:42Z
38,591,985
<p>This might be a longshot, since your question doesn't make the context of your incorrect output clear, but if you're just referencing yourmodel.associated_hm, you will see a reference to the associated_hm object. </p> <p>To get the <code>p_id</code>, you would need to explicitly reference it in your query like so <...
0
2016-07-26T14:00:03Z
[ "python", "mysql", "django", "foreign-keys", "mariadb" ]
Binning and then combining bins with minimum number of observations?
38,591,000
<p>Let's say I create some data and then create bins of different sizes:</p> <pre><code>from __future__ import division x = np.random.rand(1,20) new, = np.digitize(x,np.arange(1,x.shape[1]+1)/100) new_series = pd.Series(new) print(new_series.value_counts()) </code></pre> <p>reveals:</p> <pre><code>20 17 16 1 4 1 2 ...
1
2016-07-26T13:18:50Z
38,592,142
<p><strong>EDITED:</strong></p> <pre><code>x = np.random.rand(1,100) bins = np.arange(1,x.shape[1]+1)/100 new = np.digitize(x,bins) n = new.copy()[0] # this will hold the the result threshold = 2 for i in np.unique(n): if sum(n == i) &lt;= threshold: n[n == i] += 1 n.clip(0, bins.size) # avoid adding b...
1
2016-07-26T14:06:51Z
[ "python", "performance", "numpy", "pandas", "binning" ]
Arduino + Raspy3 serial problems
38,591,219
<p>I am new to python, and I'm trying to connect an <code>Arduino</code> Uno with a Raspberry Pi3 using python. Arduino sends data (ID, Temp and Humidity) every 1 second. </p> <p>The problem is that I want <code>raspberry</code> to read serial port every 5 seconds and raspy is losing data... it only gets IDs: 2,4,6,8,...
1
2016-07-26T13:28:13Z
38,685,511
<p>For those having the same problem, I finally solved this issue using Threading....here I paste part of the modified code:</p> <pre><code>class guardarTxt (QtCore.QThread): def __init__(self, texto, nombre): QtCore.QThread.__init__(self) self.nombre = nombre self.texto = texto def _...
0
2016-07-31T15:28:04Z
[ "python", "arduino", "raspberry-pi" ]
Suppress warning Eclipse when developing with Pydev
38,591,420
<p>I want to suppress Eclipse warnings when defining decorators.</p> <p>For example:</p> <pre><code>def tool_wrapper(func): def inner(self): cmd="test" cmd+=func(self) return inner @tool_wrapper def list_peer(self): return "testing " </code></pre> <p>I get warning on a decorator definition: "M...
1
2016-07-26T13:36:07Z
38,591,576
<p>Just define your decorator outside the class and pass the instance as an argument, it will work just as fine.</p> <pre><code>def tool_wrapper(func): def inner(inst): # inst : instance of the object cmd="test" cmd+=func(inst) return cmd return inner class Test(): def __init__(...
1
2016-07-26T13:43:13Z
[ "python", "eclipse", "decorator", "pydev" ]
Passing a value into a python variable via Splinter
38,591,436
<p>I'm looking at a web page and making a yes/no decision. I'm trying to create a prompt that will allow me to pass the "yes" / "no" to a python variable via Splinter.</p> <p>1.) Page loads</p> <p>2.) Execute something like <code>browser.execute_script("window.prompt()")</code> with a yes/ no to a variable</p> <p>3....
0
2016-07-26T13:36:50Z
38,591,550
<blockquote> <p>Is there a good way to go about doing this?</p> </blockquote> <p>No. Use Python's <code>input</code> (or <code>raw_input</code> if using Python 2), or get that value as a command line argument. </p>
1
2016-07-26T13:41:46Z
[ "python" ]
Use both Recursive Feature Eliminiation and Grid Search in SciKit-Learn
38,591,469
<p>I have a machine learning problem and want to optimize my SVC estimators as well as the feature selection.</p> <p>For optimizing SVC estimators I use essentially the code from the <a href="http://scikit-learn.org/stable/auto_examples/model_selection/grid_search_digits.html#example-model-selection-grid-search-digits...
0
2016-07-26T13:38:13Z
38,593,101
<p>I would use a Pipeline, but here you have a more adequate response </p> <p><a href="http://stackoverflow.com/questions/23815938/recursive-feature-elimination-and-grid-search-using-scikit-learn">Recursive feature elimination and grid search using scikit-learn</a></p>
1
2016-07-26T14:46:37Z
[ "python", "machine-learning", "scikit-learn", "feature-selection" ]
Can't open pip in Python version 3.5
38,591,547
<p>Using Python version 3.5 on Windows 10 64bit, I'm unable to run the pip command. When I try running the application, the window will just open for a brief second and then closes. I already tried adding the directory to the <code>PATH</code> environment variable and rebooting the system - didn't work.</p>
0
2016-07-26T13:41:39Z
38,591,837
<blockquote> <p>when i try running the application the window will just open for brief second and then closes</p> </blockquote> <p>Sounds like you are trying to open the <code>pip.exe</code> file and expect an interactive interface of some kind. </p> <p>Unfortunately, that's not how you use <code>pip</code>. Open u...
1
2016-07-26T13:53:36Z
[ "python", "python-3.x", "pip" ]
How to know what are the threads running : python
38,591,551
<p>Is there any way to know what threads are running using python threading module. With the following piece of code, I am able to get the Thread name, current thread, active thread count.</p> <p>But my doubt here is ACTIVE_THREADS are 2 and the CURRENT THREAD is always "MainThread". What could be the other thread whi...
2
2016-07-26T13:41:53Z
38,591,662
<p>You can access all current thread objects using <a href="https://docs.python.org/3/library/threading.html#threading.enumerate" rel="nofollow"><code>threading.enumerate()</code></a>, e.g.</p> <pre><code>for thread in threading.enumerate(): print(thread.name) </code></pre>
2
2016-07-26T13:46:09Z
[ "python", "multithreading" ]
How can i find the minimum value and key in a scipy dictionary of keys?
38,591,595
<p>I'm trying to find the shortest distance between 2 kd trees and am using the scipy function 'sparse_distance_matrix'. The result is returned in a dictionary of keys matrix of the form <code>{(1,2):4.54}</code>.</p> <p>Its possible to retrieve the value using the following code but no method seems to work to get the...
0
2016-07-26T13:43:48Z
38,591,795
<p><code>min(sparsemin.items(), key=lambda item: (item[1], item[0]))</code> will return a tuple with the minimum value and its key.</p> <pre><code>a = {(1,2): 2.54, (1, 0): 4.52} min(a.items(), key=lambda item: (item[1], item[0])) &gt;&gt; ((1, 2), 2.54) </code></pre>
1
2016-07-26T13:51:52Z
[ "python", "scipy", "kdtree" ]
SQLAlchemy, without explicitly stating a rollback call, are the uncommited changes of the session automatically rolledback?
38,591,713
<p>For example this code:</p> <pre><code>db = SQLAlchemy() def myfunction(a): #somechanges in database if a == 2: return db.session.commit() myfunction(2) # there were some changes here that were not committed neither rolled back myfunction(4) # Here the changes were committed. </code></pre> <p>My que...
0
2016-07-26T13:48:49Z
38,591,845
<p>If you read <a href="http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#adding-and-updating-objects" rel="nofollow">the tutorial</a> you'll see that the session has a <code>dirty</code> property:</p> <pre><code>db = SQLAlchemy() def myfunction(a): #somechanges in database if a == 2: return db.ses...
0
2016-07-26T13:53:58Z
[ "python", "sqlalchemy" ]
SQLAlchemy, without explicitly stating a rollback call, are the uncommited changes of the session automatically rolledback?
38,591,713
<p>For example this code:</p> <pre><code>db = SQLAlchemy() def myfunction(a): #somechanges in database if a == 2: return db.session.commit() myfunction(2) # there were some changes here that were not committed neither rolled back myfunction(4) # Here the changes were committed. </code></pre> <p>My que...
0
2016-07-26T13:48:49Z
38,591,854
<p>The changes performed in the call to <code>myFunction(4)</code> will overwrite the changes performed in the call to <code>myFunction(2)</code>. This is the case for updating data, commits or not.</p> <p>For adding rows and columns, there is no over-writing of data. Committing before the function call to <code>myFun...
1
2016-07-26T13:54:11Z
[ "python", "sqlalchemy" ]
Getting survival function estimates group by attribute level in Lifelines
38,591,748
<p>I have a challenge with using Lifelines for KM estimates. I have a variable column called worker type (Full Time, Part Time, etc) that I would like to group the KM estimates for, then output to a <code>CSV</code> file. Here's a snippet:</p> <pre><code>worker_types = df['Emp_Status'].unique() for i, worker_type in...
1
2016-07-26T13:50:05Z
38,592,178
<p>You can open the file in append mode at the top of the loop and then append each row, e.g.:</p> <pre><code>worker_types = df['Emp_Status'].unique() with open('C:/Users/Downloads/test.csv', 'a') as fou: for i, worker_type in enumerate(worker_types): ix = df['Emp_Status'] == worker_type kmf.fit...
0
2016-07-26T14:08:30Z
[ "python", "pandas", "dataframe" ]
rename the categories and add the missing categories to a Series PANDAS
38,591,868
<p>I want to rename the categories and add the missing categories to a Series.</p> <p>My code:</p> <pre><code>codedCol = bdAu['Bordersite'] print 'pre:' print codedCol.head(10) codedCol = codedCol.astype('category') codedCol = codedCol.cat.set_categories(['a','b','c','d','e','f','g','h','i','j']) print 'post:' print ...
1
2016-07-26T13:55:04Z
38,592,028
<p>You've set the categories to the following: <code>['a','b','c','d','e','f','g','h','i','j']</code>. The current values in the column in <code>codedCat</code> do not match any of the categories. Therefore, they get re-set to <code>NaN</code>. For further reading, consider this example <a href="http://pandas.pydata.or...
0
2016-07-26T14:02:25Z
[ "python", "pandas", "dataframe" ]
rename the categories and add the missing categories to a Series PANDAS
38,591,868
<p>I want to rename the categories and add the missing categories to a Series.</p> <p>My code:</p> <pre><code>codedCol = bdAu['Bordersite'] print 'pre:' print codedCol.head(10) codedCol = codedCol.astype('category') codedCol = codedCol.cat.set_categories(['a','b','c','d','e','f','g','h','i','j']) print 'post:' print ...
1
2016-07-26T13:55:04Z
38,592,355
<p>First or creating <code>catagories</code> you can use <code>.astype('category')</code>, but <code>categories</code> are added from your column or <code>Categorical</code> with parameter <code>categories</code> where are defined. </p> <p>You can use:</p> <pre><code>codedCol = bdAu['Bordersite'] codedCol = pd.Serie...
0
2016-07-26T14:16:16Z
[ "python", "pandas", "dataframe" ]
List of dicts: remove duplicates and stack together unique values
38,591,938
<p>I have a list similar to this: </p> <pre><code>[ {'code': 'ABCDEFGH', 'message':'Everything is not OK', 'name': 'Tom Sawyer', 'course': 'Networks'}, {'code': 'ABCDEFGH', 'message':'Alright', 'name': 'Julien Sorel', 'course': 'Networks'}, {'code': 'KQPRADBC', 'message...
-2
2016-07-26T13:58:08Z
38,592,411
<p>To guarantee unicity with rather simple readable code, one could use <a class='doc-link' href="http://stackoverflow.com/documentation/python/497/set#t=201607261412544468519">sets</a>. See comments in the code.</p> <p>I suggest, supposing <code>lst</code> contains your list of dictionaries :</p> <pre><code>res = li...
2
2016-07-26T14:19:06Z
[ "python", "list", "python-3.x", "dictionary" ]
List of dicts: remove duplicates and stack together unique values
38,591,938
<p>I have a list similar to this: </p> <pre><code>[ {'code': 'ABCDEFGH', 'message':'Everything is not OK', 'name': 'Tom Sawyer', 'course': 'Networks'}, {'code': 'ABCDEFGH', 'message':'Alright', 'name': 'Julien Sorel', 'course': 'Networks'}, {'code': 'KQPRADBC', 'message...
-2
2016-07-26T13:58:08Z
38,593,622
<pre><code>a = [ {'code': 'ABCDEFGH', 'message':'Everything is not OK', 'name': 'Tom Sawyer', 'course': 'Networks'}, {'code': 'ABCDEFGH', 'message':'Alright', 'name': 'Julien Sorel', 'course': 'Networks'}, {'code': 'KQPRADBC', 'message':'Hello there', 'name': 'Jacques Paganel', 'course': 'Cooking'}, {'code'...
0
2016-07-26T15:08:52Z
[ "python", "list", "python-3.x", "dictionary" ]
List within a string and print formatting
38,592,007
<p>I am creating something which takes a tuple, converts it into a string and then reorganises the string using print formatting. 'other' can sometimes have 2 names, hence why I have used <code>*</code> and the <code>" ".join(other)</code> in this function:</p> <pre><code>def strFormat(x): #Convert to string ...
0
2016-07-26T14:01:16Z
38,592,077
<p>You're close. Change this line (which does nothing):</p> <pre><code>payR, dep, sal, " ".join(other), surn </code></pre> <p>to</p> <pre><code>other = " ".join(other) </code></pre>
3
2016-07-26T14:03:59Z
[ "python" ]
How to handle clicks on Links in Python with Gtk 3.0 and WebKit2 4.0?
38,592,026
<p>I have created my view (wrapped in a window) and loaded an URL like this:</p> <pre><code>self.web_view = WebKit2.WebView() self.web_view.load_uri("https://en.wikipedia.org") </code></pre> <p>My "Mini-Browser" starts and I can click on local links (links which are bound to JavaScript events or links to other pages ...
6
2016-07-26T14:02:17Z
38,723,324
<p>Did you use a <a href="https://developer.gnome.org/gtk3/stable/GtkLinkButton.html" rel="nofollow">GtkLinkButton</a> ? According to the doc of <a href="https://developer.gnome.org/gtk3/stable/gtk3-Filesystem-utilities.html#gtk-show-uri" rel="nofollow">gtk-show-uri</a> which uses the default-browser to open links, yo...
2
2016-08-02T14:31:31Z
[ "python", "webkit", "gtk", "gtk3", "webkitgtk" ]
Scaling images generated by imshow
38,592,101
<p>The following code snippet</p> <pre><code>import matplotlib.pyplot as plt import numpy as np arr1 = np.arange(100).reshape((10,10)) arr2 = np.arange(25).reshape((5,5)) fig, (ax1, ax2, ) = plt.subplots(nrows=2, figsize=(3,5)) ax1.imshow(arr1, interpolation="none") ax2.imshow(arr2, interpolation="none") plt.tight_...
0
2016-07-26T14:05:13Z
38,598,273
<p>The simplest thing I could think of didn't work, but <code>gridspec</code> does. The origins here aren't aligned explicitly, it just takes advantage of how gridspec fills rows (and there's an unused subplot as a spacer). </p> <pre><code>import matplotlib.pyplot as plt import numpy as np from matplotlib import grids...
1
2016-07-26T19:23:13Z
[ "python", "matplotlib", "imshow" ]
How can i get sum of queryset lists and make jsonresponse?
38,592,103
<p><strong>views.py</strong></p> <pre><code>from itertools import chain def post_list(request): i=1 while i: list_i = Post.objects.filter(title__startswith="i") post_list = list(chain('' + ',' + 'list_i')) if len(post_list) &gt;= 5 : break retu...
-1
2016-07-26T14:05:15Z
38,592,476
<p>You shouldn't be using <code>chain</code>. <code>chain</code> method would chain lists together, but you don't want all of them together, so you should just use plain list methods:</p> <pre><code>def post_list(request): result = [] i = 1 while True: list_i = Post.objects.filter(title__startswith...
0
2016-07-26T14:21:55Z
[ "python", "json", "django" ]
How can i get sum of queryset lists and make jsonresponse?
38,592,103
<p><strong>views.py</strong></p> <pre><code>from itertools import chain def post_list(request): i=1 while i: list_i = Post.objects.filter(title__startswith="i") post_list = list(chain('' + ',' + 'list_i')) if len(post_list) &gt;= 5 : break retu...
-1
2016-07-26T14:05:15Z
38,592,739
<p>It seems like you have a serious disconnect between string values and text values.</p> <pre><code>In [126]: x = 3 In [127]: print("x") x In [128]: print(x) 3 In [129]: print(str(x)) 3 </code></pre> <p>Based on your code, I'm <em>pretty sure</em> you thought that <code>print("x")</code> would print out <code>3</...
1
2016-07-26T14:32:17Z
[ "python", "json", "django" ]
Single Link List in Python Add, Remove, Insert
38,592,218
<p>I'm trying to achieve a singly linked list with add, remove and insert methods. I'm confused with the insertion method.</p> <pre><code>class Node(object): def __init__(self, data, next): self.data = data self.next = next class SingleList(object): head = None tail = None def printList(self): print "L...
0
2016-07-26T14:10:25Z
38,593,253
<p>You have to rewrite your insert as:</p> <pre><code>def insert(self, before, nextdata): #nextdata is to be inserted before 'before' #before is actually a data #but it has dif name in this def to avoid confusion with 'data' current_node = self.head previous_node = None while current_node is no...
0
2016-07-26T14:52:56Z
[ "python", "data-structures", "linked-list" ]
Efficient accessing in sparse matrices
38,592,255
<p>I'm working with recommender systems but I'm struggling with the access times of the scipy sparse matrices.</p> <p>In this case, I'm implementing <em>TrustSVD</em> so I need an efficient structure to operate both in columns and rows (CSR, CSC). I've thought about using both structures, dictionaries,... but either w...
1
2016-07-26T14:12:01Z
38,596,728
<p>When you index a sparse matrix, especially just asking for a row or column, it not only has to select the values, but it also has to construct a new sparse matrix. <code>np.ndarray</code> construction is done in compiled code, but most of the sparse construction is pure Python. The <code>nonzero()[1]</code> constr...
2
2016-07-26T17:52:43Z
[ "python", "numpy", "matrix", "scipy", "sparse-matrix" ]
Python incrementing array index through loop
38,592,307
<p>Im currently using xlwings to display graphs and their corresponding values in microsoft excel. I have 5 graphs and their coordinates(in an array) that i've successfully been able to print through a loop. Unfortunately the columns in which they appeared in had to be hard coded and would be affected if i were to add ...
1
2016-07-26T14:14:00Z
38,592,348
<p>You can use another variable to keep track of the column index. In this case <code>j</code>:</p> <pre><code>Columns = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S"] j = 1 for j,i in enumerate(range(1, 5)): Range(Columns[j] + str(1)).value = list(zip(Xvalues)) Range(Columns...
0
2016-07-26T14:15:55Z
[ "python", "xlwings" ]
One Hot Encoding using numpy
38,592,324
<p>If the input is zero I want to make an array which looks like this-</p> <p><code>[1,0,0,0,0,0,0,0,0,0]</code></p> <p>and if it is 5-</p> <p><code>[0,0,0,0,0,1,0,0,0,0]</code></p> <p>For the above I wrote:</p> <p><code>np.put(np.zeros(10),5,1)</code></p> <p>but it did not work.</p> <p>Is there any way in which...
1
2016-07-26T14:15:01Z
38,592,416
<p>Something like : </p> <pre><code>np.array([int(i == 5) for i in range(10)]) </code></pre> <p>Should do the trick. But I suppose there exist other solutions using numpy.</p> <p>edit : the reason why your formula does not work : np.put does not return anything, it just modifies the element given in first parameter....
1
2016-07-26T14:19:15Z
[ "python", "numpy", "one-hot", "one-hot-encoding" ]
One Hot Encoding using numpy
38,592,324
<p>If the input is zero I want to make an array which looks like this-</p> <p><code>[1,0,0,0,0,0,0,0,0,0]</code></p> <p>and if it is 5-</p> <p><code>[0,0,0,0,0,1,0,0,0,0]</code></p> <p>For the above I wrote:</p> <p><code>np.put(np.zeros(10),5,1)</code></p> <p>but it did not work.</p> <p>Is there any way in which...
1
2016-07-26T14:15:01Z
38,592,615
<p>The problem here is that you save your array nowhere. The <code>put</code> function works in place on the array and returns nothing. Since you never give your array a name you can not address it later. So this</p> <pre><code>one_pos = 5 x = np.zeros(10) np.put(x, one_pos, 1) </code></pre> <p>would work, but then y...
1
2016-07-26T14:27:29Z
[ "python", "numpy", "one-hot", "one-hot-encoding" ]
One Hot Encoding using numpy
38,592,324
<p>If the input is zero I want to make an array which looks like this-</p> <p><code>[1,0,0,0,0,0,0,0,0,0]</code></p> <p>and if it is 5-</p> <p><code>[0,0,0,0,0,1,0,0,0,0]</code></p> <p>For the above I wrote:</p> <p><code>np.put(np.zeros(10),5,1)</code></p> <p>but it did not work.</p> <p>Is there any way in which...
1
2016-07-26T14:15:01Z
38,592,629
<p>Taking a quick look at <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.put.html" rel="nofollow">the manual</a>, you will see that <code>np.put</code> does not return a value. While your technique is fine, you are accessing <code>None</code> instead of your result array.</p> <p>For a 1-D array it ...
1
2016-07-26T14:27:48Z
[ "python", "numpy", "one-hot", "one-hot-encoding" ]
One Hot Encoding using numpy
38,592,324
<p>If the input is zero I want to make an array which looks like this-</p> <p><code>[1,0,0,0,0,0,0,0,0,0]</code></p> <p>and if it is 5-</p> <p><code>[0,0,0,0,0,1,0,0,0,0]</code></p> <p>For the above I wrote:</p> <p><code>np.put(np.zeros(10),5,1)</code></p> <p>but it did not work.</p> <p>Is there any way in which...
1
2016-07-26T14:15:01Z
38,593,112
<p>The <code>np.put</code> mutates its array arg <em>in-place</em>. It's conventional in Python for functions / methods that perform in-place mutation to return <code>None</code>; <code>np.put</code> adheres to that convention. So if <code>a</code> is a 1D array and you do</p> <pre><code>a = np.put(a, 5, 1) </code></p...
0
2016-07-26T14:47:10Z
[ "python", "numpy", "one-hot", "one-hot-encoding" ]
One Hot Encoding using numpy
38,592,324
<p>If the input is zero I want to make an array which looks like this-</p> <p><code>[1,0,0,0,0,0,0,0,0,0]</code></p> <p>and if it is 5-</p> <p><code>[0,0,0,0,0,1,0,0,0,0]</code></p> <p>For the above I wrote:</p> <p><code>np.put(np.zeros(10),5,1)</code></p> <p>but it did not work.</p> <p>Is there any way in which...
1
2016-07-26T14:15:01Z
38,593,472
<pre><code>import time start_time = time.time() z=[] for l in [1,2,3,4,5,6,1,2,3,4,4,6,]: a= np.repeat(0,10) np.put(a,l,1) z.append(a) print("--- %s seconds ---" % (time.time() - start_time)) #--- 0.00174784660339 seconds --- import time start_time = time.time() z=[] for l in [1,2,3,4,5,6,1,2,3,4,4,6,]: ...
0
2016-07-26T15:02:40Z
[ "python", "numpy", "one-hot", "one-hot-encoding" ]
How to install another version of python on Linux?
38,592,329
<p>There already exists a version(2.6) of python on my linux server. I want to install another version(maybe 2.7 or 3) to another directory(maybe "/home/zhangxudong") and then run my python script using this new python. How can I do the above through command line? Very thanks. </p>
-2
2016-07-26T14:15:11Z
38,592,644
<p>First of all, I'm just pointing out your question is awkward, there are many ways to do this. You are probably looking to install python from source (google it) which can be done to a particular director or by using virtual environments (also google it). If you just want say python3 installed, you can do this easily...
0
2016-07-26T14:28:18Z
[ "python", "linux", "install" ]
Python eMail Maibox - Read any "Received" keys
38,592,347
<p>I'm developing a script that allows me to read the "Received" field from the header of a file .mbox.</p> <p>This is a small part of the code:</p> <pre><code>mbox = mailbox.mbox(filename) print message.keys() print message["Received"] </code></pre> <p>The print of the Keys takes me this result:</p> <pre><code>['R...
1
2016-07-26T14:15:54Z
38,593,363
<p>When you call <code>__get__</code> it will linear scan the list of msg headers and return the first one with matching name. To get multiple use <code>items()</code> method ie:</p> <pre><code>print [v for k, v in message.items() if k == "Received"] </code></pre>
0
2016-07-26T14:58:14Z
[ "python" ]
matplotlib - ValueError: weight is invalid
38,592,358
<p>I am running <code>python/3.3.2</code> with <code>matplotlib/1.5.1</code></p> <p>if I run </p> <pre><code> x = linspace(0,1,10) plot(x,x) </code></pre> <p>I get </p> <pre><code>ValueError: weight is invalid </code></pre> <p>but actually it happens with any matplotlib command. It looks like something in the ins...
0
2016-07-26T14:16:35Z
38,592,531
<p>The value of <code>font.weight</code> <code>rcParams</code> should be one of many strings: <code>'normal'</code>, <code>'bold'</code>, <code>'bolder'</code>, etc. </p> <p>Based on that value you have shown, it's somehow the string-representation of a list containing the string <code>bold</code>. </p> <pre><code>s...
2
2016-07-26T14:24:20Z
[ "python", "matplotlib" ]
Why does py.test show my xfail tests as skipped?
38,592,457
<p>I have some python code and a bunch of pytest tests for it.</p> <p>Some of the tests I expect to fail (that is, I am testing error handling, so I pass in inputs that should cause my code to throw exceptions.)</p> <p>In order to do this, I have code like this:</p> <pre><code>CF_TESTDATA =[('data/1_input.csv', 'dat...
0
2016-07-26T14:20:49Z
39,021,921
<p>The answer is that I am using xfail incorrectly. It should not be used to expect test failure. It does not do that. If the test fails or does not fail, it is recorded as passing.</p> <p>What I need to do instead is change the tests to catch the exception I expect, and error out if the exception is not thrown. Then ...
1
2016-08-18T15:19:43Z
[ "python", "unit-testing", "jenkins", "py.test" ]
Beautifulsoup return list for attribute "class" while value for other attribute
38,592,497
<p><a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautifulsoup</a> is handy for html parsing in python, and below code result cofuse me.</p> <pre><code>from bs4 import BeautifulSoup tr =""" &lt;table&gt; &lt;tr class="passed" id="row1"&gt;&lt;td&gt;t1&lt;/td&gt;&lt;/tr&gt; &lt;tr clas...
1
2016-07-26T14:22:48Z
38,592,593
<p><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class" rel="nofollow"><code>class</code></a> is a special <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#multi-valued-attributes" rel="nofollow">multi-valued attribute</a> in <code>BeautifulSoup</code>:</p> <blockquote...
1
2016-07-26T14:26:29Z
[ "python", "beautifulsoup", "html-parsing" ]
Beautifulsoup return list for attribute "class" while value for other attribute
38,592,497
<p><a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautifulsoup</a> is handy for html parsing in python, and below code result cofuse me.</p> <pre><code>from bs4 import BeautifulSoup tr =""" &lt;table&gt; &lt;tr class="passed" id="row1"&gt;&lt;td&gt;t1&lt;/td&gt;&lt;/tr&gt; &lt;tr clas...
1
2016-07-26T14:22:48Z
38,592,596
<p>Because elements may have multiple classes.</p> <p>Consider this example:</p> <p>from bs4 import BeautifulSoup</p> <pre><code>tr =""" &lt;table&gt; &lt;tr class="passed a b c" id="row1"&gt;&lt;td&gt;t1&lt;/td&gt;&lt;/tr&gt; &lt;tr class="failed" id="row2"&gt;&lt;td&gt;t2&lt;/td&gt;&lt;/tr&gt; &lt;/table&g...
1
2016-07-26T14:26:32Z
[ "python", "beautifulsoup", "html-parsing" ]
Convert a list of lists into a nested dictionary
38,592,504
<p>I am trying to convert a list of lists into a nested dictionary:</p> <p>My code:</p> <pre><code>csv_data={} for key, value in csv_files.iteritems(): if key in desired_keys: csv_data[key]=[] for element in value: csv_data[key].append(element[1:]) </code></pre> <...
1
2016-07-26T14:23:17Z
38,592,603
<p>Suppose I demonstrate the use of <code>zip()</code> on one of your keys, <code>Network</code>:</p> <pre><code>&gt;&gt;&gt; network = [ ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'], ['0.3', '0.1', '0.3'] ] </code></pre> <p><code>zip()</code>ing the two lists will yield a set of tuples that can be turn...
4
2016-07-26T14:26:50Z
[ "python", "list", "dictionary" ]
Convert a list of lists into a nested dictionary
38,592,504
<p>I am trying to convert a list of lists into a nested dictionary:</p> <p>My code:</p> <pre><code>csv_data={} for key, value in csv_files.iteritems(): if key in desired_keys: csv_data[key]=[] for element in value: csv_data[key].append(element[1:]) </code></pre> <...
1
2016-07-26T14:23:17Z
38,592,701
<p>Approach without <code>zip</code></p> <pre><code>dct = { 'Network': [ ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'], ['0.3', '0.1', '0.3'] ], 'CPU': [ ['Processor Time', 'User Time', 'Privileged Time'], ['13.8', '6.7', '7.2'] ] } for key, val in dct.items(): p...
0
2016-07-26T14:30:37Z
[ "python", "list", "dictionary" ]
Convert a list of lists into a nested dictionary
38,592,504
<p>I am trying to convert a list of lists into a nested dictionary:</p> <p>My code:</p> <pre><code>csv_data={} for key, value in csv_files.iteritems(): if key in desired_keys: csv_data[key]=[] for element in value: csv_data[key].append(element[1:]) </code></pre> <...
1
2016-07-26T14:23:17Z
38,592,853
<p><code>zip()</code> comes in very handy for iterating the lists at the same time, and converting to a dictionary becomes very easy with <code>dict()</code>.</p> <pre><code>def to_dict(dic): for key, value in dic.iteritems(): dic[key] = dict(zip(* value)) return dic </code></pre> <p><strong>Sample ou...
3
2016-07-26T14:36:38Z
[ "python", "list", "dictionary" ]
Convert a list of lists into a nested dictionary
38,592,504
<p>I am trying to convert a list of lists into a nested dictionary:</p> <p>My code:</p> <pre><code>csv_data={} for key, value in csv_files.iteritems(): if key in desired_keys: csv_data[key]=[] for element in value: csv_data[key].append(element[1:]) </code></pre> <...
1
2016-07-26T14:23:17Z
38,593,067
<p>Try this code :</p> <pre><code>{x:{z:t for z,t in (dict(zip(y[0], y[1]))).items()} for x,y in data.items()} </code></pre> <p>When Input :</p> <pre><code>data={ 'Network': [ ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'], ['0.3', '0.1', '0.3'] ], 'CPU': [ ['Processor Time', 'User Time', 'Privileg...
0
2016-07-26T14:45:01Z
[ "python", "list", "dictionary" ]
Multithreading Issues
38,592,576
<p>This is more of a hypothetical question; I'm having some issues with a program and I'm wondering if it might be because of multithreading.</p> <p>I have a main thread and a worker thread. The worker thread communicates with a machine through a serial port, and when it receives output from the machine, it emits a Py...
0
2016-07-26T14:25:50Z
38,592,947
<p>While your main thread is executing a long task (originated from an event), it will not process any new events. All new events will be queued in a thread-specific queue, and will be processed later when the event loop is executed. If the targeted thread is <em>sleeping</em>, the new event will be queued, and the thr...
1
2016-07-26T14:40:31Z
[ "python", "multithreading", "pyqt4" ]
IndexError: only integers, slices (`:`), ellipsis (`...`) . .
38,592,581
<p>I am using pymc3 to find a best fit for a 3D surface. This is the code that I am using.</p> <pre><code>with Model() as model: # specify glm and pass in data. The resulting linear model, its likelihood and # and all it...
0
2016-07-26T14:26:06Z
38,628,221
<p>I think the problem is related to your definition of <code>flatimage</code>. You need your data labeled for the glm module to work. Something like this:</p> <pre class="lang-py prettyprint-override"><code># synthetic data (just an example) x = np.random.normal(size=100) y = np.random.normal(size=100) z = x**2 + y**...
1
2016-07-28T06:02:18Z
[ "python", "pymc3", "best-fit-curve" ]
Splinter find_by_css() not working as expected
38,592,707
<p>I tried this in the browser and it works fine:</p> <pre><code>('button[data-item-id="1054079703"]')[0].click() </code></pre> <p>When I try it with Splinter:</p> <pre><code>browser.find_by_css('button[data-item-id="1054079703"]') </code></pre> <p>returns a Splinter object:</p> <pre><code>[&lt;splinter.driver.web...
0
2016-07-26T14:30:53Z
38,952,732
<p>Sometimes for whatever reason, selenium will determine that an element is not visible when indeed it is.</p> <p>Best to check your css to make sure nothing is overlaying it just to be sure.</p> <p>If you are sure that it is visible, try using <a href="http://splinter.readthedocs.io/en/latest/api/driver-and-element...
0
2016-08-15T09:41:29Z
[ "python", "splinter" ]
Resize matplotlib object within gridspec cell (matshow and colorbar size mismatched)
38,592,719
<p>The matshow and colorbar objects do not fill the same space inside the gridspec cells and therefore they are different heights.</p> <p>Usually I would use the colorbar 'shrink' argument, but this does not seem to work when nested in a gridspec object</p> <p>How can I shrink the colorbar object without resizing the...
0
2016-07-26T14:31:25Z
38,594,239
<p>You could use matplotlib <a href="http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axesdivider%22AxisDivider%22" rel="nofollow">AxesDivider</a>. Below is an example using the data from your question:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotli...
1
2016-07-26T15:36:01Z
[ "python", "matplotlib", "colorbar", "imshow" ]
How to implement insert for OrderedDict in python 3
38,592,779
<p>I want to insert an item into an OrderedDict at a certain position. Using the <a href="https://gist.github.com/jaredks/6276032" rel="nofollow">gist</a> of <a href="http://stackoverflow.com/a/18326914/1504082">this</a> SO answer i have the problem that it doesn't work on python 3.</p> <p>This is the implementation u...
2
2016-07-26T14:33:59Z
38,599,494
<pre><code>from collections import OrderedDict od1 = OrderedDict([ ('a', 1), ('b', 2), ('d', 4), ]) items = od1.items() items.insert(2, ('c', 3)) od2 = OrderedDict(items) print(od2) # OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) </code></pre>
-2
2016-07-26T20:41:22Z
[ "python", "ordereddictionary" ]
How to implement insert for OrderedDict in python 3
38,592,779
<p>I want to insert an item into an OrderedDict at a certain position. Using the <a href="https://gist.github.com/jaredks/6276032" rel="nofollow">gist</a> of <a href="http://stackoverflow.com/a/18326914/1504082">this</a> SO answer i have the problem that it doesn't work on python 3.</p> <p>This is the implementation u...
2
2016-07-26T14:33:59Z
38,602,395
<p>I'm not sure you wouldn't be better served just keeping up with a separate list and dict in your code, but here is a stab at a pure Python implementation of such an object. This will be an order of magnitude slower than an actual <code>OrderedDict</code> in Python 3.5, which as I pointed out in my comment <a href="h...
1
2016-07-27T01:44:40Z
[ "python", "ordereddictionary" ]
How to implement insert for OrderedDict in python 3
38,592,779
<p>I want to insert an item into an OrderedDict at a certain position. Using the <a href="https://gist.github.com/jaredks/6276032" rel="nofollow">gist</a> of <a href="http://stackoverflow.com/a/18326914/1504082">this</a> SO answer i have the problem that it doesn't work on python 3.</p> <p>This is the implementation u...
2
2016-07-26T14:33:59Z
40,118,488
<p>Since Python 3.2, <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict.move_to_end" rel="nofollow"><code>move_to_end</code></a> can be used to move items around in an <a href="https://docs.python.org/3/library/collections.html#ordereddict-objects" rel="nofollow"><code>OrderedDict</code...
0
2016-10-18T21:35:30Z
[ "python", "ordereddictionary" ]
Multiple quotechars in pandas
38,592,786
<p>I want to parse an nginx access log using pandas python library read_csv function. I'm using the following code:</p> <pre><code>pd.read_csv('lb-access_cache.log', delim_whitespace=True, quotechar='"') </code></pre> <p>It would be possible to specify more than one quotechar, to treat also the elements inside bracke...
1
2016-07-26T14:34:15Z
38,593,025
<p>This will do, you need to use a regex in place of sep: </p> <pre><code>df = pd.read_csv(log_file, sep=r'\s(?=(?:[^"]*"[^"]*")*[^"]*$)(?![^\[]*\])', engine='python', usecols=[0, 3, 4, 5, 6, 7, 8], names=['ip', 'time', 'request', 'status', 'size', 'referer', 'us...
3
2016-07-26T14:43:29Z
[ "python", "csv", "pandas" ]
Precision when converting int32 to other types
38,592,794
<p>The code below</p> <pre><code>import numpy as np i = np.iinfo(np.int32).max # 2147483647 x = np.asanyarray(i) # array([2147483647]) dtypes = (np.int32, np.float16, np.float32, np.float64) for dtp in dtypes: print('%s : %s'%(dtp, x.astype(dtp))) </code></pre> <p>outputs</p> <pre><code>&lt;type 'numpy.int32'&g...
3
2016-07-26T14:34:32Z
38,594,632
<p>Floating point values consist of two parts, an integer and an exponent. To get the value, you take 2 to the power of the exponent and multiply it by the integer part.</p> <p>For an IEEE 32-bit floating point value, the integer part is <a href="https://en.wikipedia.org/wiki/IEEE_floating_point#Basic_and_interchange_...
1
2016-07-26T15:54:44Z
[ "python", "numpy", "floating-point", "precision", "data-type-conversion" ]
XLWings / Excel problems handling "multi-cell array formulas"
38,592,907
<h1>scope</h1> <p>I'm using XLWings for the obvious, to retrieve data from external sources, do a bit of transformation in Python, and then pump it into Excel.</p> <p>I'm using UDFs to do so (Windows 10, Excel 2016 32bit).</p> <p>The only way I'm aware of, is to use "multi-cell array formulas" to add the 2 dimension...
1
2016-07-26T14:39:06Z
39,591,649
<p>xlwings v0.10 introduces dynamic arrays, see the <a href="http://docs.xlwings.org/en/stable/whatsnew.html#dynamic-array-formulas" rel="nofollow">release notes</a>.</p> <p>Now you can do:</p> <pre><code>import xlwings as xw import numpy as np @xw.func @xw.ret(expand='table') def dynamic_array(r, c): return np....
1
2016-09-20T10:23:13Z
[ "python", "excel", "pandas", "xlwings" ]
How do you setup simple timer between two times when the other time is the next day?
38,592,908
<p>Python noob here</p> <pre><code>from datetime import datetime, time now = datetime.now() now_time = now.time() if now_time &gt;= time(10,30) and now_time &lt;= time(13,30): print "yes, within the interval" </code></pre> <p>I would like the timer to work between 10,30 AM today and 10 AM the next day. Changing ...
0
2016-07-26T14:39:06Z
38,593,155
<p>The <code>combine</code> method on the <code>datetime</code> class will help you a lot, as will the <code>timedelta</code> class. Here's how you would use them:</p> <pre><code>from datetime import datetime, timedelta, date, time today = date.today() tomorrow = today + timedelta(days=1) interval_start = datetime.c...
1
2016-07-26T14:49:01Z
[ "python" ]
How do you setup simple timer between two times when the other time is the next day?
38,592,908
<p>Python noob here</p> <pre><code>from datetime import datetime, time now = datetime.now() now_time = now.time() if now_time &gt;= time(10,30) and now_time &lt;= time(13,30): print "yes, within the interval" </code></pre> <p>I would like the timer to work between 10,30 AM today and 10 AM the next day. Changing ...
0
2016-07-26T14:39:06Z
38,593,160
<p>Consider this:</p> <pre><code>from datetime import datetime, timedelta now = datetime.now() today_10 = now.replace(hour=10, minute=30) tomorrow_10 = (now + timedelta(days=1)).replace(hour=10, minute=0) if today_10 &lt;= now &lt;= tomorrow_10: print "yes, within the interval" </code></pre> <p>The logic is to ...
1
2016-07-26T14:49:13Z
[ "python" ]
How do you setup simple timer between two times when the other time is the next day?
38,592,908
<p>Python noob here</p> <pre><code>from datetime import datetime, time now = datetime.now() now_time = now.time() if now_time &gt;= time(10,30) and now_time &lt;= time(13,30): print "yes, within the interval" </code></pre> <p>I would like the timer to work between 10,30 AM today and 10 AM the next day. Changing ...
0
2016-07-26T14:39:06Z
38,593,314
<p>An alternative to creating time objects for the sake of comparison is to simply query the <code>hour</code> and <code>minute</code> attributes:</p> <pre><code>now= datetime.now().time() if now.hour&lt;10 or now.hour&gt;10 or (now.hour==10 and now.minute&gt;30): print('hooray') </code></pre>
0
2016-07-26T14:55:59Z
[ "python" ]
Django get_or_create() is creating multiple rows with the same id
38,592,999
<p>I have a get_or_create() in my django app that's creating duplicate rows and assigning them the same id.</p> <pre><code>stock_search, created = SearchRequest.objects.get_or_create(quote=quote, salesperson=user) </code></pre> <p>count() doesn't count these rows more than once but any queries I run on the data retur...
-3
2016-07-26T14:42:23Z
38,601,454
<p>As mentioned in the <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#get-or-create" rel="nofollow">docs</a>, you need an unique index for get_or_create to work</p> <blockquote> <p>This method is atomic assuming correct usage, correct database configuration, and correct behavior of the underl...
1
2016-07-26T23:28:54Z
[ "python", "django", "postgresql", "python-2.7" ]
alembic db migration concurrently
38,593,034
<p>I have multiple flask apps connect to the same db backend for high availability purpose. There is a problem when app instances try to migrate db concurrently using alembic! What's the best way to prevent it?</p>
1
2016-07-26T14:43:44Z
38,596,490
<p>Alembic <a href="https://groups.google.com/forum/#!msg/sqlalchemy-alembic/I2AAEUdF2dQ/mM2dokcZCAAJ" rel="nofollow">does not</a> support simultaneous migration. Your best bet is to do it manually.</p>
1
2016-07-26T17:37:01Z
[ "python", "flask", "concurrency", "alembic" ]
lxml working with namespaces
38,593,176
<p>I'm working with a pretty complex XML like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!-- ***** Configuration Data exported at 20160623T110335 ***** --&gt; &lt;impex:ExportData xmlns:impex="urn:swift:saa:xsd:impex"&gt; &lt;!-- *** Exported Data for Operator *** --&gt; &lt;OperatorData xm...
1
2016-07-26T14:49:47Z
38,593,480
<p>You may not need namespaces for your use-case, <a href="http://stackoverflow.com/q/18159221/771848">remove them</a> to make parsing easier:</p> <pre><code>from lxml import etree, objectify tree = etree.parse("input.xml") root = tree.getroot() # remove namespaces ---- for elem in root.getiterator(): if not has...
1
2016-07-26T15:03:02Z
[ "python", "python-2.7", "lxml" ]
python error:list.remove(x) x not in list
38,593,206
<p>I was trying to compare integer from a list and remove it from the list and append it on an array with python. Every time I run my code there is an error occured. "list.remove(x) x not in list". I can't figure it out whats happening on such an error. Can anybody give me some advice? Thank you.</p> <pre><code>def ma...
-1
2016-07-26T14:50:57Z
38,593,653
<pre><code>&gt;&gt;&gt; def maxcompare(n): ... return sorted( map(int,n.split(',')) )[-3:] ... &gt;&gt;&gt; maxcompare('2,8,9,7,6,10,5') [8, 9, 10] </code></pre>
1
2016-07-26T15:10:25Z
[ "python", "python-2.7" ]
python error:list.remove(x) x not in list
38,593,206
<p>I was trying to compare integer from a list and remove it from the list and append it on an array with python. Every time I run my code there is an error occured. "list.remove(x) x not in list". I can't figure it out whats happening on such an error. Can anybody give me some advice? Thank you.</p> <pre><code>def ma...
-1
2016-07-26T14:50:57Z
38,593,684
<p>There are a few problems with your code. Try this:</p> <pre><code>def maxcompare(n): lis = map(int, n.split(',')) threeans = [] for i in range(3): maxnum = lis[0] for j in lis[1:]: # iterate lis, not n if int(j) &gt; maxnum: # cast j to int maxnum = j lis.rem...
0
2016-07-26T15:11:41Z
[ "python", "python-2.7" ]