Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
700
51,373,953
Reading and Processing Large CSVs with Python
<p>I have a question that is similar in spirit to this <a href="https://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3">previously asked question</a>. Nonetheless, I can't seem to figure out a suitable solution. </p> <p><strong>Input</strong>: I have CSV data that looks like </p> <pre><code>id,prescriber_last_name,prescriber_first_name,drug_name,drug_cost 1000000001,Smith,James,AMBIEN,100 1000000002,Garcia,Maria,AMBIEN,200 1000000003,Johnson,James,CHLORPROMAZINE,1000 1000000004,Rodriguez,Maria,CHLORPROMAZINE,2000 1000000005,Smith,David,BENZTROPINE MESYLATE,1500 </code></pre> <p><strong>Output</strong>: from this I simply need to output each drug, the total cost which is summed over all prescriptions and I need to get a count of the unique number of prescribers. </p> <pre><code>drug_name,num_prescriber,total_cost AMBIEN,2,300.0 CHLORPROMAZINE,2,3000.0 BENZTROPINE MESYLATE,1,1500.0 </code></pre> <p>I was able to accomplish this pretty easily with Python. However, when I try to run my code with a much larger (1gb) input, my code does not terminate in a reasonable amount of time.</p> <pre><code>import sys, csv def duplicate_id(id, id_list): if id in id_list: return True else: return False def write_file(d, output): path = output # path = './output/top_cost_drug.txt' with open(path, 'w', newline='') as csvfile: fieldnames = ['drug_name', 'num_prescriber', 'total_cost'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for key, value in d.items(): print(key, value) writer.writerow({'drug_name': key, 'num_prescriber': len(value[0]), 'total_cost': sum(value[1])}) def read_file(data): # TODO: https://codereview.stackexchange.com/questions/88885/efficiently-filter-a-large-100gb-csv-file-v3 drug_info = {} with open(data) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) for row in readCSV: prescriber_id = row[0] prescribed_drug = row[3] prescribed_drug_cost = float(row[4]) if prescribed_drug not in drug_info: drug_info[prescribed_drug] = ([prescriber_id], [prescribed_drug_cost]) else: if not duplicate_id(prescriber_id, drug_info[prescribed_drug][0]): drug_info[prescribed_drug][0].append(prescriber_id) drug_info[prescribed_drug][1].append(prescribed_drug_cost) else: drug_info[prescribed_drug][1].append(prescribed_drug_cost) return(drug_info) def main(): data = sys.argv[1] output = sys.argv[2] drug_info = read_file(data) write_file(drug_info, output) if __name__ == "__main__": main() </code></pre> <p>I am having trouble figuring out how to refactor this to handle the larger input and was hoping someone could take a look and provide me some suggestions for how to solve this problem. </p>
<p>IF you can use pandas, Please try the following. Pandas reads your file and store them in dataframe. It is much faster than our manual file processing using iterator.</p> <pre><code>import pandas as pd df = pd.read_csv('sample_data.txt') columns = ['id','drug_name','drug_cost'] df1 = df[columns] gd = df1.groupby('drug_name') cnt= gd.count() s=gd.sum() out = s.join(cnt,lsuffix='x') out['total_cost']=out['drug_costx'] out['num_prescriber']=out['drug_cost'] fout = out[['num_prescriber','total_cost']] fout.to_csv('out_data.csv') </code></pre> <p>I am getting the following output.</p> <pre><code>drug_name,num_prescriber,total_cost AMBIEN,2,300 BENZTROPINE MESYLATE,1,1500 CHLORPROMAZINE,2,3000 </code></pre> <p>Hope this helps.</p>
python|python-3.x
1
701
51,407,746
Installing pyOpt on python in ubuntu
<p>I have downloaded pyOpt from its website and installed it on python in ubuntu, using the instructions on the website. </p> <p>Still, I cannot import and use it in my pycharm projects.</p>
<p>I had the same problem, but I did not dare to try Akin's solution for my research project (I think it is a good solution if anyone wants to stick to PyOpt package with python3). </p> <p>I used Pyomo instead.</p> <p>By the way, Laurent's answer actually points to another package. PyOpt and pyopt are two different packages.</p>
python|pycharm
1
702
17,495,999
convert dataframe from wide layout to SQL-style slim layout
<p>How can I convert a dataframe like this:</p> <pre><code> a b c 0 1.067683 -1.110463 0.208670 1 -1.321405 0.368915 -1.055342 2 -0.807333 0.082980 -0.873361 </code></pre> <p>into</p> <pre><code> det value 0 a 1.067683 1 a -1.321405 2 a -0.807333 3 b -1.110463 4 b 0.368915 5 b 0.082980 6 b 0.082980 7 c 0.208670 8 c -1.055342 9 c -0.873361 </code></pre>
<p>You can do this with <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-by-melt" rel="nofollow"><code>melt</code></a>:</p> <pre><code>In [11]: from pandas.core.reshape import melt In [12]: melt(df) Out[12]: variable value 0 a 1.067683 1 a -1.321405 2 a -0.807333 3 b -1.110463 4 b 0.368915 5 b 0.082980 6 c 0.208670 7 c -1.055342 8 c -0.873361 </code></pre>
python|pandas
3
703
64,423,245
dataframe Sort_values giving improper results
<p><a href="https://i.stack.imgur.com/cwzhx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cwzhx.png" alt="enter image description here" /></a></p> <p>Hi I am trying to get the top 10 values. I would like to get the top 10 attendance and punctuality by staff. here's my code for sorting: newData =data.sort_values(&quot;Attendance&quot;, ascending=False).head(10) I'm not sure why am I getting 8.82 and 8.57. Please advise. I tried Nth largest but it didn't work for me.</p>
<p>Because values in column <code>Attendance</code> are strings, so sorted in lexicographic order.</p> <p>So need convert them to numeric:</p> <pre><code>data['Attendance'] = data['Attendance'].astype(float) #if possible some non numeric values convert them to NaNs #data['Attendance'] = pd.to_numeric(data['Attendance'], errors='coerce') newData = data.sort_values(&quot;Attendance&quot;, ascending=False).head(10) </code></pre>
pandas|sorting|plotly
0
704
64,607,956
PyGears How to make counter
<p>I want to make a counter which can start counting at posedge of a specific signal (enable signal). And once it counts to 256, stop counting, set the counter to 0 and output something.</p>
<p>When designing with PyGears, you should try to think more in terms of functions (although asynchronous) that are being invoked by receiving commands via input interfaces. Instead of thinking of the <code>enable</code> signal that triggers the counter, try to think of a counter you described as a function that receives a number to count to as an input command and outputs something once it's done counting. There are two ways we could go about implementing this:</p> <ol> <li><p>An async gear, in which we write procedural code to describe the logic</p> <pre><code> from pygears import gear, sim from pygears.typing import Uint from pygears.sim import log from pygears.lib import once, qrange @gear async def counter(cmd: Uint, *, something) -&gt; b'type(something)': async with cmd as c: async for i in qrange(c): pass yield something @gear async def collect(data): async with data as d: log.info(f'Got something: {d}') once(val=256) \ | counter(something=Uint[8](2)) \ | collect sim() </code></pre> <p>Here, the <code>counter</code> has an interface called <code>cmd</code>, where a number of cycles to count is received, and a compile time parameter called <code>something</code>, which will be sent through the output interface once the counting is done. In the body of the function, we first wait for the input command to arrive: <code>async with cmd as c:</code>, next we wait for the counter to finish and finally we output <code>something</code>. <code>qrange</code> is a builtin gear and you are welcome to inspect its implementation here: <a href="https://github.com/bogdanvuk/pygears/blob/master/pygears/lib/rng.py" rel="nofollow noreferrer">rng.py</a></p> <p>Then there's the <code>collect</code> gear which simply prints out whatever it receives. Finally, we generate the command for the <code>counter</code> using <code>once</code>, and feed the output of the <code>counter</code> to the <code>collect</code> module. When <code>sim()</code> is invoked, we get the following output showing that <code>collect</code> got <code>something</code> in the cycle 255:</p> <pre><code> 0 [INFO]: -------------- Simulation start -------------- 255 /collect [INFO]: Got something: u8(2) 256 [INFO]: ----------- Simulation done --------------- 256 [INFO]: Elapsed: 0.03 </code></pre> </li> <li><p>We could use a hierarchical gear to connect existing builtin modules to achieve the same thing:</p> <pre><code> from pygears import gear, sim from pygears.typing import Uint from pygears.sim import log from pygears.lib import once, qrange, when @gear def counter(cmd: Uint, *, something): last = qrange(cmd)['eot'] return when(last, something) @gear async def collect(data): async with data as d: log.info(f'Got something: {d}') once(val=256) \ | counter(something=Uint[8](2)) \ | collect sim() </code></pre> <p>Everything is pretty much the same, except that the <code>counter</code> isn't defined with the <code>async</code> keyword, meaning that it is a hierarchical gear and only describes interconnection between its submodules. The <code>qrange</code> gear outputs both the iterator and a flag, called <code>eot</code> (for end-of-transaction), which marks the last count. We feed <code>eot</code> (via <code>eot</code> variable) to the <code>when</code> gear that will only output <code>something</code> when it sees value <code>True</code> on <code>eot</code> interface.</p> </li> </ol>
python|pygears
1
705
64,420,446
How to open a file in binary mode in google storage bucket from cloud function?
<p>In my cloud function, I need to get a file in cloud storage and send the file to an API through HTTP POST request. I tried the following code:</p> <pre><code>storage_client = storage.Client() bucket = storage_client.bucket(BUCKET_NAME) source_blob_name = &quot;/compressed_data/file_to_send.7z&quot; blob = bucket.blob(source_blob_name) url = UPLOADER_BACKEND_URL files = {'upload_file': blob} values = {'id': '1', 'ouid': OUID} r = requests.post(url, files=files, data=values) </code></pre> <p>It gave an error saying:</p> <pre><code>Traceback (most recent call last): File &quot;/env/local/lib/python3.7/site-packages/google/cloud/functions/worker_v2.py&quot;, ... \ line 90, in encode_multipart_formdata body.write(data) TypeError: a bytes-like object is required, not 'Blob' </code></pre> <p>If this code was to run on an actual VM, the following would work:</p> <pre><code>url = UPLOADER_BACKEND_URL files = {'upload_file': open('/tmp/file_to_send.7z','rb')} values = {'id': '1', 'name': 'John'} r = requests.post(url, files=files, data=values) </code></pre> <p>So the question is: In cloud functions, how can I load a file from cloud storage such that it has the same output as the python <code>open(filename, 'rb')</code> function?</p> <p>I know that I can do <code>blob.download_to_file()</code> and then <code>open()</code> the file, but I'm wondering if there is a quicker way.</p>
<p>In your Cloud Functions reference, you don't provide the Blob content to the API call but only the Blob reference (file path + Bucket name).</p> <p>You can, indeed download the file locally in the in memory file system <code>/tmp</code> directory. and then handle this tmp file as any file. <em>Don't forget to delete it after the upload!!</em></p> <p>You can also have a try to <a href="https://gcsfs.readthedocs.io/en/latest/" rel="nofollow noreferrer">the <code>gcsfs</code> library</a> where you can handle files in a python idiomatic way. I never tried to do this when I call an API, but it should work.</p>
python|file-io|google-cloud-functions|google-cloud-storage
2
706
70,515,842
Tkinter image application keeps freezing system after it runs
<p>I'm testing an app with the following code:</p> <pre><code>#!/usr/bin/env python3 import os from tkinter import * from tkinter import filedialog from PIL import Image, ImageTk root = Tk() root.title(&quot;Image Viewer App&quot;) root.withdraw() location_path = filedialog.askdirectory() root.resizable(0, 0) #Load files in directory path im=[] def load_images(loc_path): for path,dirs,filenames in os.walk(loc_path): for filename in filenames: im.append(ImageTk.PhotoImage(Image.open(os.path.join(path, filename)))) load_images(location_path) root.geometry(&quot;700x700&quot;) #Display test image with Label label=Label(root, image=im[0]) label.pack() root.mainloop() </code></pre> <p>The problem is that when I run it, my system will freeze and Linux distro will crash. I'm not able to tell what I'm doing wrong except I'm not sure if it's a good idea to store an entire image within a list variable vs just storing the location itself. Right now, it's just testing the ability to open one image with img=[0].</p>
<p>The loading of images may take time and cause the freeze. Better to run <code>load_images()</code> in a child thread instead:</p> <pre class="lang-py prettyprint-override"><code>import os import threading import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk root = tk.Tk() root.geometry(&quot;700x700&quot;) root.title(&quot;Image Viewer App&quot;) root.resizable(0, 0) root.withdraw() #Display test image with Label label = tk.Label(root) label.pack() location_path = filedialog.askdirectory() root.deiconify() # show the root window #Load files in directory path im = [] def load_images(loc_path): for path, dirs, filenames in os.walk(loc_path): for filename in filenames: im.append(ImageTk.PhotoImage(file=os.path.join(path, filename))) print(f'Total {len(im)} images loaded') if location_path: # run load_images() in a child thread threading.Thread(target=load_images, args=[location_path]).start() # show first image def show_first_image(): label.config(image=im[0]) if len(im) &gt; 0 else label.after(50, show_first_image) show_first_image() root.mainloop() </code></pre> <p>Note that I have changed <code>from tkinter import *</code> to <code>import tkinter as tk</code> as wildcard import is not recommended.</p>
python-3.x|ubuntu|tkinter|python-imaging-library
1
707
55,778,312
Input Transformation for Keras LSTM
<p>I am working on a project to try to enhance my understanding of LSTM networks. I am following the steps outlined in this blog post <a href="https://towardsdatascience.com/predicting-stock-price-with-lstm-13af86a74944" rel="nofollow noreferrer">here</a>. My dataset looks like the following:</p> <pre><code> Open High Low Close Volume Date 2014-04-21 197.080002 206.199997 194.000000 204.380005 5258200 2014-04-22 206.360001 219.330002 205.009995 218.639999 9804700 2014-04-23 216.330002 216.740005 207.000000 207.990005 7295600 2014-04-24 210.809998 212.800003 203.199997 207.860001 5495200 2014-04-25 202.000000 206.699997 197.649994 199.850006 6996700 </code></pre> <p>As you can see this is a small snapshot of TSLA Stock movement.</p> <p>I understand that with LSTM, this data needs to be reshaped into three dimensions:</p> <ol> <li><p>Batch Size</p></li> <li><p>Time Steps</p></li> <li><p>Features</p></li> </ol> <p>My initial idea was to use some sort of medium batch size (to allow for the best generalization). Also, to look back at 10 days of history as the Time Step. Features as Open, High, Low, Volume, Close.</p> <p>Here is where I am a bit stuck. I have two questions specifically:</p> <ol> <li><p>What is the approach for breaking the data into the new representation (transforming it)?</p></li> <li><p>How do we take this and split it into the train, test, and validation sets? I am having trouble conceptualizing exactly what is being broken down. My initial thought was to use sklearn:</p> <p>train_test_split()</p></li> </ol> <p>But this does not seem like it will work in this case.</p> <p>Obviously, once the data has been transformed and then split it is easy building the Keras model. It is just a matter of calling fit.(data).</p> <p>Any suggestions or resources (pointing in the right direction) would be greatly appreciated.</p> <p>My current code is:</p> <pre><code>from sklearn.model_selection import train_test_split # Split the Data into Training and Testing Data tsla_train, tsla_test = train_test_split(tsla) tsla_train.shape tsla_test.shape from sklearn.preprocessing import MinMaxScaler # Scale the Data scaler = MinMaxScaler() scaler.fit(tsla_train) tsla_train_scaled = scaler.transform(tsla_train) tsla_test_scaled = scaler.transform(tsla_test) # Define the parameters of the model batch_size = 20 # Set the model to look back on four days of historical data and try to predict the fifth time_steps = 10 from keras.models import Sequential from keras.layers import LSTM, Dense lstm_model = Sequential() </code></pre> <p>There is some explanation found in this post <a href="https://stackoverflow.com/questions/38714959/understanding-keras-lstms?rq=1">here</a>.</p>
<p>The <code>train_test_split</code> function would indeed not give the desired results here. It assumes that each row is an independent data point, which is not the case since you're using a single time series.</p> <p>The most common option would be to use earlier data points for training and later data points for testing (and a range of points in the middle for validation if applicable), which would give you the same results as if you had used all the available data for training on the last day in the training set and actually used it for predictions on the following days.</p> <p>Once you have the data sets split, then the idea is that each training batch will need to have the inputs and corresponding outputs for a randomly selected set of date ranges, where each input is the chosen number of days of historical data (i.e. <code>days × features</code>, with the full batch being <code>batch size × days × features</code>) and the output is just the data for the next day,</p> <p>Hopefully that helps with some of the intuition behind the procedure. The article you linked has examples of most of the code you would need--it's going to be pretty dense, but I would recommend trying to go line by line and understand everything it's doing, possibly even just typing it out verbatim.</p>
python|keras|lstm|recurrent-neural-network
0
708
55,981,316
Showing step by step solving of sudoku
<p>Is there any way to show the steps of solving a sudoku? My code just solve it within 0.5 second and I wish to modify it to show the changes on the sudoku grid step by step on processing. (I am using python)</p>
<p>You can store all steps of solving sudoku (e.g. Grid data) into a list. For each step you modify the sudoku state, you clone a copy and append it to the global list. After solved it, you can loop through this list and render each state with some seconds delay.</p>
python|processing|sudoku
0
709
49,820,305
How to put extras_require in setup.cfg
<p><a href="https://setuptools.readthedocs.io/en/latest/history.html#v30-3-0" rel="noreferrer">setuptools 30.3.0</a> introduced declarative package config, allowing us to put most of the options we used to pass directly to <code>setuptools.setup</code> in <code>setup.cfg</code> files. For example, given following setup.cfg:</p> <pre><code>[metadata] name = hello-world description = Example of hello world [options] zip_safe = False packages = hello_world install_requires = examples example1 </code></pre> <p>A setup.py containing only</p> <pre><code>import setuptools setuptools.setup() </code></pre> <p>will do all the right things.</p> <p>However, I haven't been able to figure out the correct syntax for <code>extras_require</code>. In <code>setup</code> args, it is a dictionary, like</p> <pre><code>setup(extras_require={'test': ['faker', 'pytest']}) </code></pre> <p>But I can't figure out the right syntax to use in setup.cfg. I tried reading the docs, but I can't find the correct syntax that setuptools expects for a dictionary there. I tried a few guesses, too</p> <pre><code>[options] extras_require = test=faker,pytest </code></pre> <p>it fails.</p> <pre><code>Traceback (most recent call last): File "./setup.py", line 15, in &lt;module&gt; 'pylint', File "/lib/site-packages/setuptools/__init__.py", line 128, in setup _install_setup_requires(attrs) File "/lib/site-packages/setuptools/__init__.py", line 121, in _install_setup_requires dist.parse_config_files(ignore_option_errors=True) File "/lib/python3.6/site-packages/setuptools/dist.py", line 495, in parse_config_files self._finalize_requires() File "/lib/python3.6/site-packages/setuptools/dist.py", line 419, in _finalize_requires for extra in self.extras_require.keys(): AttributeError: 'str' object has no attribute 'keys' </code></pre> <p>Reading the code, I'm not 100% sure this is supported, but based on <a href="https://www.python.org/dev/peps/pep-0508" rel="noreferrer">PEP 508</a> it seems this should be a supported use case. What am I missing?</p>
<p>It is supported. You need a config <em>section</em>:</p> <pre><code>[options.extras_require] test = faker; pytest </code></pre> <p>Syntax is documented <a href="https://setuptools.readthedocs.io/en/latest/userguide/declarative_config.html?highlight=options.extras_require#configuring-setup-using-setup-cfg-files" rel="noreferrer">here</a>.</p>
python|setuptools|declarative
38
710
66,531,778
Change bar order and legend order in plot (matplotlib/pandas)
<p>I would like to have the order of the legend and of the bars as the one defined in label_order</p> <pre><code>for feat in df.columns: label_order = ['Very Low', 'Low', 'Average', 'High', 'Very High'] df.groupby('class')[feat].value_counts().unstack(0).plot.bar() plt.ylabel('Count') plt.xlabel('Score') plt.legend() plt.title('Answers to ' + str(feat) + ' divided for each risk class') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/2vqF2.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>The order of columns is determined by the column order in the dataframe you are plotting, therefore simply reordering the columns between unstacking and plotting will do the trick:</p> <pre class="lang-py prettyprint-override"><code>df.groupby('class')[feat].value_counts().unstack(0)[label_order].plot.bar() </code></pre> <p>Here's a sample plot with and without the <code>[label_order]</code> addition</p> <p><a href="https://i.stack.imgur.com/LMSPg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LMSPg.png" alt="enter image description here" /></a></p>
python|pandas
1
711
64,830,528
rearranging 2*2 pixel images, each given by 1 by 4 numpy vectors, into a single 8 by 8 matrix without using a for loop
<p>in an assignment for a uni class i am given multiple images in vectors, and i need to display multiple of them by rearranging them into a single matrix.</p> <p>assume the given vectors:</p> <pre><code>[[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13,14,15,16]] </code></pre> <p>where each pair of 4 values within a vector describes a 2x2 pixel image my task is to rearrange this into a 4x4 matrix:</p> <pre><code>[[1,2,5,6],[3,4,7,8],[8,9,12,13],[10,11,15,16]] </code></pre> <p>without using a single for loop. i have tried multiple variants of reshapes, but have no idea how to actually solve this problem.</p>
<p>Let's use <code>reshape</code>, and <code>swapaxes</code>:</p> <pre><code>arrs = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13,14,15,16]] np.array(arrs).reshape(2,2,2,2).swapaxes(1,2).reshape(4,4) </code></pre> <p>Output:</p> <pre><code>array([[ 1, 2, 5, 6], [ 3, 4, 7, 8], [ 9, 10, 13, 14], [11, 12, 15, 16]]) </code></pre>
python|numpy|matrix|reshape|imshow
1
712
64,897,011
python - json keep returning JSONDecodeError when reading from file
<p>I want to write data to a json file. If it does not exists, I want to create that file, and write data to it. I wrote code for it, but I'm getting <code>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)</code>.</p> <p>Here's part of my code:</p> <pre><code>data = {&quot;foo&quot;: &quot;1&quot;} with open(&quot;file.json&quot;, &quot;w+&quot;) as f: try: file_data = json.load(f) json.dump(data, f) print(&quot;got data from file:&quot;, file_data) except json.decoder.JSONDecodeError: json.dump(data, f) print(&quot;wrote&quot;) </code></pre> <p>I put print statements so that I can &quot;track&quot; what's going on, but If I try to run this code multiple times, I keep getting <code>wrote</code> message.</p> <p>Thanks in advance for help!</p>
<p>The problem is that you open the file for write/read therefore once you open the file it will be emptied.</p> <p>Then you want to load the content with <code>json.load</code> and it obviously fails because the file is not a valid JSON anymore.</p> <p>So I'd suggest to open the file for reading and writing separately:</p> <pre class="lang-py prettyprint-override"><code>import json with open(&quot;file.json&quot;) as json_file: file_data = json.load(json_file) print(&quot;got data from file:&quot;, file_data) data = {&quot;foo&quot;: &quot;1&quot;} with open(&quot;file.json&quot;, &quot;w&quot;) as json_file: json.dump(data, json_file) </code></pre> <p>Hope it helps!</p>
python|json|python-3.x
0
713
63,741,027
Regression statistics for subsets of Pandas dataframe
<p>I have a dataframe consisting of multiple years of data with multiple environmental parameters as columns. The dataframe looks like this:</p> <pre><code>import pandas as pd import numpy as np from scipy import stats Parameters= ['Temperature','Rain', 'Pressure', 'Humidity'] nrows = 365 daterange = pd.date_range('1/1/2019', periods=nrows, freq='D') Vals = pd.DataFrame(np.random.randint(10, 150, size=(nrows, len(Parameters))), columns=Parameters) Vals = Vals.set_index(daterange) print(Vals) </code></pre> <p>I have created a column with month names as <code>Vals['Month'] = Vals.index.month_name().str.slice(stop=3)</code> and I want to calculate the slope from the regression between two variables, <code>Rain and Temperature</code> and extract them in a dataframe. I have tried a solution as below:</p> <pre><code>pd.DataFrame.from_dict({y:stats.linregress(Vals['Temperature'], Vals['Rain'])[:2] for y, x in Vals.groupby('Month')},'index').\ rename(columns={0:'Slope',1:'Intercept'}) </code></pre> <p>But the output is not what I expected. I want the monthly regression statistics but the result is like this</p> <pre><code> Slope Intercept Apr -0.016868 81.723291 Aug -0.016868 81.723291 Dec -0.016868 81.723291 Feb -0.016868 81.723291 Jan -0.016868 81.723291 Jul -0.016868 81.723291 Jun -0.016868 81.723291 Mar -0.016868 81.723291 May -0.016868 81.723291 Nov -0.016868 81.723291 Oct -0.016868 81.723291 Sep -0.016868 81.723291 </code></pre> <p>It seems the regression is calculated from the total dataset and stored in each month index. How can I calculate the monthly statistics from the similar process?</p>
<p>Here is a bit of code that I have used in the past. I used <code>sklearn.LinearModel</code> because I think its a bit easier to use, but you can change to scipy.stats if you like.</p> <p>This code uses <code>apply</code> and does the linear regression in the function <code>linear_model</code>.</p> <pre><code>import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression def linear_model(group): x,y = group.Temperature.values.reshape(-1,1), group.Rain.values.reshape(-1,1) model = LinearRegression().fit(x,y) m = model.coef_ i = model.intercept_ r_sqd = model.score(x,y) return (pd.Series({ 'slope':np.squeeze(m), 'intercept':np.squeeze(i), 'r_sqd':np.squeeze(r_sqd)})) Parameters= ['Temperature','Rain', 'Pressure', 'Humidity'] nrows = 365 daterange = pd.date_range('1/1/2019', periods=nrows, freq='D') Vals = pd.DataFrame(np.random.randint(10, 150, size=(nrows, len(Parameters))), columns=Parameters) Vals = Vals.set_index(daterange) Vals.groupby(Vals.index.month).apply(linear_model) </code></pre> <p>Result:</p> <pre><code>Vals.groupby(Vals.index.month).apply(linear_model) Out[15]: slope intercept r_sqd 1 -0.06334408633973578 80.98723450432585 0.003480 2 -0.1393001910724248 85.40023995141723 0.020435 3 -0.0535505295232336 69.09958112535743 0.003481 4 0.23187299827488306 57.866651248302546 0.048741 5 -0.04813654915436082 74.31295680099751 0.001867 6 0.31976921541526526 48.496345031992746 0.089027 7 -0.1979417421554613 94.84215558468942 0.052023 8 0.22239030327077666 68.62700822940076 0.061849 9 0.054607306452220644 72.0988798639258 0.002877 10 -0.07841007716276265 91.9211204014171 0.006085 11 -0.13517307855088803 100.44769438307809 0.016045 12 -0.1967407738498068 101.7393002049148 0.042255 </code></pre> <p>Your attempt was close. When you use a for loop with groupby object, you group's name and data in return. The typical convention is:</p> <pre><code>for name, group in Vals.groupby('Month'): #do stuff with group </code></pre> <p>Since you called <code>x</code> for <code>name</code> and <code>y</code> for <code>group</code>, you could change <code>Vals</code> to <code>y</code>, the code will produce the same result as above.</p> <pre><code>pd.DataFrame.from_dict({y:stats.linregress(x['Temperature'], x['Rain'])[:2] for y, x in Vals.groupby('Month')},'index').\ rename(columns={0:'Slope',1:'Intercept'}) Slope Intercept Apr 0.231873 57.866651 Aug 0.222390 68.627008 Dec -0.196741 101.739300 Feb -0.139300 85.400240 Jan -0.063344 80.987235 Jul -0.197942 94.842156 Jun 0.319769 48.496345 Mar -0.053551 69.099581 May -0.048137 74.312957 Nov -0.135173 100.447694 Oct -0.078410 91.921120 Sep 0.054607 72.098880 </code></pre>
python|pandas|dataframe|regression
1
714
53,290,260
How do I import a python file using Ansible Playbook?
<p>This is on a Linux machine. I have a run.yml like this</p> <pre><code>--- - name: Appspec hosts: localhost become: true tasks: - name: test 1 script: test.py </code></pre> <p>test.py uses a python file (helper.py) by 'import helper' which is in the same path as the ansible-playbook and while running the playbook.yml it still gives me a 'Import Error: cannot import name helper'. How should I do this?</p>
<p>Copy both <code>test.py</code> and <code>helper.py</code> over to same directory on the remote machine (possibly to a temporary directory) and run <code>python test.py</code> as a <code>command</code> task. Something like this:</p> <pre><code>- name: Create temporary directory tempfile: state: directory register: tmpdir - name: Copy test.py copy: src: /wherever/test.py dest: "{{tmpdir.path}}/test.py" - name: Copy helper.py copy: src: /wherever/helper.py dest: "{{tmpdir.path}}/helper.py" - name: Run test.py command: python test.py args: chdir: "{{tmpdir.path}}" </code></pre>
python|linux|ansible
1
715
61,819,812
How to only create relevant model fields during a django test?
<p>I am testing a method that requires me to create a fake record in my model. The model has over 40 fields. Is it possible to create a record with only the relevant model fields for the test so I don't have to populate the other fields? If so how would I apply it to this test case example. </p> <p>models.py</p> <pre><code>class Contract(): company = models.CharField(max_length=255), commission_rate = models.DecimalField(max_digits=100, decimal_places=2) type = models.CharField(max_length=255) offer = models.ForeignKey('Offer', on_delete=models.PROTECT) notary = models.ForeignKey('Notary', on_delete=models.PROTECT) jurisdiction = models.ForeignKey('Jurisdiction', on_delete=models.PROTECT) active = models.BooleanField() ... </code></pre> <p>test.py</p> <pre><code>import pytest from app.models import Contract def calculate_commission(company, value): contract = Contract.objects.get(company='Apple') return value * contract.commission_rate @pytest.mark.django_db def test_calculate_commission(): #The only two model fields I need for the test Contract.objects.create(company='Apple', commission_rate=0.2) assert calculate_commission('Apple', 100) == 20 </code></pre>
<p>Try to use <code>model_bakery</code> to make an object record. Just populate fields you want and leave another blank, <code>model_bakery</code> will handle it. For the Detail, you can check this out <a href="https://github.com/model-bakers/model_bakery" rel="nofollow noreferrer">model_bakery</a> </p>
django|python-3.x|unit-testing|django-models
0
716
67,600,810
Find local duplicates (which follow each other) in pandas
<p>I want to find local duplicates and give them a unique id, directly in pandas.</p> <p><strong>Reallife example:</strong></p> <p>Time-ordered purchase data where a customer id occures multiple times (because he visits a shop multiple times a week), but I want to identify occasions where the customer purches multiple items at the same time.</p> <p><strong>My current approach would look like this:</strong></p> <pre><code>def follow_ups(lst): lst2 = [None] + lst[:-1] i = 0 l = [] for e1, e2 in zip(lst, lst2): if e1 != e2: i += 1 l.append(i) return l follow_ups(['A', 'B', 'B', 'C', 'B', 'D', 'D', 'D', 'E', 'A', 'B', 'C']) # [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9] # for pandas df['out'] = follow_ups(df['test']) </code></pre> <p>But I have the feeling there might be a much simpler and cleaner approach in pandas which I am unable to find.</p> <p><strong>Pandas Sample data</strong></p> <pre><code>import pandas as pd df = pd.DataFrame({'test':['A', 'B', 'B', 'C', 'B', 'D', 'D', 'D', 'E', 'A', 'B', 'C']}) # test # 0 A # 1 B # 2 B # 3 C # 4 B # 5 D # 6 D # 7 D # 8 E # 9 A # 10 B # 11 C df_out = pd.DataFrame({'test':['A', 'B', 'B', 'C', 'B', 'D', 'D', 'D', 'E', 'A', 'B', 'C'], 'out':[1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9]}) # test out # 0 A 1 # 1 B 2 # 2 B 2 # 3 C 3 # 4 B 4 # 5 D 5 # 6 D 5 # 7 D 5 # 8 E 6 # 9 A 7 # 10 B 8 # 11 C 9 </code></pre>
<p>You can compare whether your column test is not equal to it's shifted version, using <code>shift()</code> with <code>ne()</code>, and use <code>cumsum()</code> on that:</p> <pre><code>df['out'] = df['test'].ne(df['test'].shift()).cumsum() </code></pre> <p>Which prints:</p> <pre><code>df test out 0 A 1 1 B 2 2 B 2 3 C 3 4 B 4 5 D 5 6 D 5 7 D 5 8 E 6 9 A 7 10 B 8 11 C 9 </code></pre>
python|pandas
2
717
60,575,408
Can not connect to smtp.gmail.com in Django
<p>I'm trying to send email using smtp.gmail.com in Django project. This is my email settings.</p> <p>settings.py</p> <pre><code># Email Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '[email protected]' EMAIL_HOST_PASSWORD = 'mygooglepassword' </code></pre> <p>views.py</p> <pre><code>... send_mail( &quot;message title&quot;, &quot;message content&quot;, &quot;[email protected]&quot;, [&quot;[email protected]&quot;], fail_silently=False) </code></pre> <p>Whenever I try to send email, I get this error</p> <h3>gaierror at /contact-us/</h3> <p>[Errno-2] Name or service not known</p> <p>I tried the followings.</p> <ol> <li>I set my google account's less secure app access on.</li> <li>I unchecked avast antivirus setting 'Setting-&gt;Protection-&gt;Core Shields-&gt;Mail Shield-&gt;Scan outbound emails(SMTP)'</li> <li>Tried different ports in email settings. 587 and 25</li> <li>Switched the ssl and tls in email settings.</li> </ol> <p>But it's not sending yet. When I use 'django.core.mail.backends.console.EmailBackend' instead of 'django.core.mail.backends.smtp.EmailBackend', it prints email on console.</p> <p>I double checked my gmail username and password on settings. Please help me.</p> <p>Thank you.</p>
<p>You may need to do some configuration on Google side.</p> <p><a href="https://stackoverflow.com/a/31333304/11607969">Reference answer:</a>:</p> <p>Go to your Google Account settings, find Security -> Account permissions -> Access for less secure apps, enable this option.</p> <p><a href="https://accounts.google.com/DisplayUnlockCaptcha" rel="nofollow noreferrer">https://accounts.google.com/DisplayUnlockCaptcha</a></p>
python|php|django|smtp|gmail
0
718
71,370,969
displaying flask input() to a html template
<p>how can i display an input to my web application? Ive tried many ways but not succesfully...</p> <pre><code>import random import re from flask import Flask, render_template app = Flask(__name__) app.debug = True @app.route(&quot;/&quot;) def index(): return render_template(&quot;play.html&quot;) @app.route(&quot;/hangman&quot;) def hangman(): answer = input(&quot;Hi, wanna play? Y/N: &quot;) return render_template(&quot;game.html&quot;, answer=answer) </code></pre>
<p>In game.html template you should put an <code>input</code> tag:</p> <pre><code>&lt;form method=&quot;post&quot; action=&quot;/want-to-play&quot;&gt; &lt;input type=&quot;text&quot; placeholder=&quot;Do you want to play?&quot; /&gt; &lt;input type=&quot;submit&quot; value=&quot;OK&quot;/&gt; &lt;/form&gt; </code></pre> <p>Then just put an endpoint /want-to-play in your flask app with what you want to do.</p>
python|html|flask
0
719
71,157,722
Scraping multiple anchor tags which are under the same header/class
<p>I am trying to scrape the top episode data from IMDB and extract the name of the show and the name of the episode. However I am facing an issue where the show name and episode name are both anchor tags which are under the same header. <a href="https://i.stack.imgur.com/MobsQ.png" rel="nofollow noreferrer">Screenshot of element</a></p> <p>Here is the code:</p> <pre><code>url = &quot;https://www.imdb.com/search/title/?title_type=tv_episode&amp;num_votes=1000,&amp;sort=user_rating,desc&amp;ref_=adv_prv&quot; response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') series_name = [] episode_name = [] episode_data = soup.findAll('div', attrs={'class': 'lister-item mode-advanced'}) for store in episode_data: sName = store.h3.a.text series_name.append(sName) # eName = store.h3.a.text # episode_name.append(eName) </code></pre> <p>Anyone know how to get through this problem?</p>
<p>in the last part you should specify more</p> <pre><code>for store in episode_data: h3=store.find('h3', attrs={'class': 'lister-item-header'}) sName =h3.findAll('a')[0].text series_name.append(sName) eName = h3.findAll('a')[1].text episode_name.append(eName) </code></pre> <p>note that the name of 'attack of titan' has been changed to it's Japanese name!!, which is different than the html that has been shown in the browser and I don't know why!?!</p>
python|web-scraping|beautifulsoup
1
720
10,909,316
How do I map values to values with a common key in Python
<p>In the dictionaries below I want to check whether the value in aa matches the value in bb and produce a mapping of the keys of aa to the keys of bb. Do I need to rearrange the dictionaries? I import the data from a tab separated file, so I am not attached to dictionaries. Note that aa is about 100 times bigger than bb (100k lines for aa), but this is to be run infrequently and offline. </p> <p>Input:</p> <pre><code>aa = {1: 'a', 3: 'c', 2 : 'b', 4 : 'd'} bb = {'apple': 'a', 'pear': 'b', 'mango' : 'g'} </code></pre> <p>Desired output (or any similar data structure):</p> <pre><code>dd = {1 : 'apple', 2 : 'pear'} </code></pre>
<pre><code>aa = {1:'a', 3:'c', 2:'b', 4:'d'} bb = {'apple':'a', 'pear':'b', 'mango': 'g'} bb_rev = dict((value, key) for key, value in bb.iteritems()) # bb.items() in python3 dd = dict((key, bb_rev[value]) for key, value in aa.iteritems() # aa.items() in python3 if value in bb_rev) print dd </code></pre>
python
3
721
72,562,173
Find most recent date from different dataframe
<p>I have a data frame (df1) and want to get a previous most recent survey_date for the ID and associated score from another data frame (df2)</p> <pre><code> df1 = pd.DataFrame({'ID' : [1,2], 'start_date':['2018-08-04','2018-08-09']}) df1 df2 = pd.DataFrame({'ID' : [1,1,2,2], 'survey_date':['2018-08-01','2018-08-05','2018-08-08','2018-08-10'], 'score':[200,100, 400, 800]}) df2 </code></pre> <p>desired output</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">ID</th> <th style="text-align: center;">start date</th> <th style="text-align: right;">prev_survey_date</th> <th style="text-align: right;">score</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">1</td> <td style="text-align: center;">2018-08-04</td> <td style="text-align: right;">2018-08-01</td> <td style="text-align: right;">200</td> </tr> <tr> <td style="text-align: left;">2</td> <td style="text-align: center;">2018-08-09</td> <td style="text-align: right;">2018-08-08</td> <td style="text-align: right;">400</td> </tr> </tbody> </table> </div> <p>How can I do this in python?</p>
<p>You can try <code>merge_asof</code></p> <pre><code>#df1.start_date = pd.to_datetime(df1.start_date) #df2.survey_date = pd.to_datetime(df2.survey_date) out = pd.merge_asof(df1, df2, by = 'ID', left_on = 'start_date', right_on = 'survey_date') Out[366]: ID start_date survey_date score 0 1 2018-08-04 2018-08-01 200 1 2 2018-08-09 2018-08-08 400 </code></pre>
pandas|date
2
722
58,653,528
Return list of all cell addresses within a Range
<p>I have a list of Ranges (loaded from an Excel workbook via openpyxl) in a list (e.g., <code>rng_list = ['$A$1:$A$3', '$B$1:$B$3', '$C$1:$C$3']</code>) and I would like to "unpack" each of those ranges into separate lists within a list of lists (i.e., <code>unpacked_list = [['$A$1','$A$2','$A$3'], ['$B$1','$B$2','$B$3'], ['$C$1','$C$2','$C$3']]</code>).</p> <p>Please see the code below on what I have tried so far in a Jupyter Notebook. Any thoughts on why I am getting the error below? or if you have ideas on how I might want to approach this from a different angle, that would be much appreciated! Thanks! </p> <pre><code> import os from openpyxl import Workbook from openpyxl.utils import get_column_letter # create temp worksheet wb_A = Workbook() sheet_A = wb_A.create_sheet('sheetA') # list with Excel ranges as str items in list rng_list = ['$A$1:$B$10', '$C$1:$D$10', '$E$1:$F$10'] temp_list = [] unpacked_list = [] for item in rng_list: for row in sheet_A(item): # use range from item in rng_list to iterate through range in temp worksheet for cell in row: x = cell.row y = cell.column addr = get_column_letter(y) + str(x) temp_list.append(addr) unpacked_list.append(addr) # delete temp worksheet wb_A.remove(sheet_A) unpacked_list </code></pre> <p>I was hoping to use the range str from the list to iterate through a "dummy worksheet" created just to iterate through the cell range and capture the corresponding cell addresses within the range. I get the following error:</p> <pre><code>--------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-85-13b28d369550&gt; in &lt;module&gt; 14 15 for item in rng_list: ---&gt; 16 for row in sheet_A(item): # use range from item in rng_list to iterate through range in temp worksheet 17 for cell in row: 18 x = cell.row TypeError: 'Worksheet' object is not callable </code></pre>
<p>After correcting syntax error in my original code (thanks, Rahasya Prabhakar!), I modified my original code to work as needed.</p> <p>Specifically, I needed to redefine the '''temp_list''' as an empty list at the start of the initial For loop, and append to the '''unpacked_list''' at the end of the initial For loop to obtain the list of list of unpacked ranges as desired.</p> <p>''' import os from openpyxl import Workbook from openpyxl.utils import get_column_letter</p> <pre><code># create temp worksheet wb_A = Workbook() sheet_A = wb_A.create_sheet('sheetA') # list with Excel ranges as str items in list rng_list = ['$A$1:$B$10', '$C$1:$D$10', '$E$1:$F$10'] temp_list = [] unpacked_list = [] for item in rng_list: temp_list=[] for row in sheet_A[item]: # use range from item in rng_list to iterate through range in temp worksheet for cell in row: x = cell.row y = cell.column addr = get_column_letter(y) + str(x) temp_list.append(addr) unpacked_list.append(temp_list) # delete temp worksheet wb_A.remove(sheet_A) print(unpacked_list) </code></pre> <p>'''</p>
python|excel|range|openpyxl
0
723
59,699,616
Pandas Date Time subraction - assigning nan values
<p>If I have code as below, </p> <pre><code>df['variance'] = (pd.to_datetime(df.last_date) - pd.to_datetime(df.first_date)) / np.timedelta64(1, 'M') </code></pre> <p>This gives me number of months, but if one of the columns does not have a date and the result for this code for that value is NaN, is there a way where I can assign the value of the NaN to a certain value like 'Void'?</p> <p>So instead of the number of months, I would see void as the value? Thanks Thanks</p>
<p>This should do it:</p> <pre><code>df = df.fillna(value='Void') </code></pre>
python|python-3.x|pandas
2
724
48,949,022
Django Filewrapper memory error serving big files, how to stream
<p>I have code like this:</p> <pre><code>@login_required def download_file(request): content_type = "application/octet-stream" download_name = os.path.join(DATA_ROOT, "video.avi") with open(download_name, "rb") as f: wrapper = FileWrapper(f, 8192) response = HttpResponse(wrapper, content_type=content_type) response['Content-Disposition'] = 'attachment; filename=blabla.avi' response['Content-Length'] = os.path.getsize(download_name) # response['Content-Length'] = _file.size return response </code></pre> <p>It seems that it works. However, If I download bigger file (~600MB for example) my memory consumption increase by this 600MB. After few such a downloads my server throws:</p> <blockquote> <p>Internal Server Error: /download/ Traceback (most recent call last):<br> File "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/matous/.local/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/media/matous/89104d3d-fa52-4b14-9c5d-9ec54ceebebb/home/matous/phd/emoapp/emoapp/mainapp/views.py", line 118, in download_file response = HttpResponse(wrapper, content_type=content_type) File "/home/matous/.local/lib/python3.5/site-packages/django/http/response.py", line 285, in <strong>init</strong> self.content = content File "/home/matous/.local/lib/python3.5/site-packages/django/http/response.py", line 308, in content content = b''.join(self.make_bytes(chunk) for chunk in value) MemoryError</p> </blockquote> <p>What I am doing wrong? Is it possible to configure it somehow to stream it the piece by piece from hard-drive without this insane memory storage?</p> <p>Note: I know that big files should not be served by Django, but I am looking for simple approach that allows to verify user access rights for any served file.</p>
<p>Try to use <code>StreamingHttpResponse</code> instead, that will help, it is exactly what you are looking for.</p> <p><em>Is it possible to configure it somehow to stream it the piece by piece from hard-drive without this insane memory storage?</em></p> <pre><code>import os from django.http import StreamingHttpResponse from django.core.servers.basehttp import FileWrapper #django &lt;=1.8 from wsgiref.util import FileWrapper #django &gt;1.8 @login_required def download_file(request): file_path = os.path.join(DATA_ROOT, "video.avi") filename = os.path.basename(file_path) chunk_size = 8192 response = StreamingHttpResponse( FileWrapper(open(file_path, 'rb'), chunk_size), content_type="application/octet-stream" ) response['Content-Length'] = os.path.getsize(file_path) response['Content-Disposition'] = "attachment; filename=%s" % filename return response </code></pre> <p>This will stream your file in chunks without loading it in memory; alternatively, you can use <a href="https://docs.djangoproject.com/en/2.0/ref/request-response/#fileresponse-objects" rel="noreferrer">FileResponse</a>, </p> <blockquote> <p>which is a subclass of <code>StreamingHttpResponse</code> optimized for binary files.</p> </blockquote>
python|django|file|download|streaming
8
725
60,191,880
How to use Python to get all cookies from web?
<p>Input </p> <pre><code>import requests from http import cookiejar headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64;rv:57.0) Gecko/20100101 Firefox/57.0'} url = "http://www.baidu.com/" session = requests.Session() req = session.put(url = url,headers=headers) cookie = requests.utils.dict_from_cookiejar(req.cookies) print(session.cookies.get_dict()) print(cookie) </code></pre> <p>Gives output: {'BAIDUID': '323CFCB910A545D7FCCDA005A9E070BC:FG=1', 'BDSVRTM': '0'} {'BAIDUID': '323CFCB910A545D7FCCDA005A9E070BC:FG=1'}</p> <p><a href="https://i.stack.imgur.com/j44LN.png" rel="nofollow noreferrer">as here.</a></p> <p>I try to use this code to get all cookies from the Baidu website but only return the first cookie. I compare it with the original web cookies(in the picture), it has 9 cookies. How can I get all the cookies?</p>
<p>You didn't maintain your session, so it terminated after the second cookie.</p> <pre><code>import requests from http import cookiejar headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64;rv:57.0) Gecko/20100101 Firefox/57.0'} url = "http://www.baidu.com/" with requests.Session() as s: req = s.get(url, headers=headers) print(req.cookies.get_dict()) </code></pre> <pre><code>&gt;&gt; print(req.cookies.get_dict().keys()) &gt;&gt;&gt; ['BDSVRTM', 'BAIDUID', 'H_PS_PSSID', 'BIDUPSID', 'PSTM', 'BD_HOME'] </code></pre>
python|python-requests
0
726
67,049,558
How to show only a few Many-to-many relations in DRF?
<p>If for an example I have 2 models and a simple View:</p> <pre class="lang-py prettyprint-override"><code>class Recipe(model.Model): created_at = model.DateField(auto_add_now=True) class RecipeBook(model.Model): recipes = model.ManyToManyField(Recipe) ... class RecipeBookList(ListAPIView): queryset = RecipeBook.objects.all() serializer_class = RecipeBookSerializer ... class RecipeBookSerializer(serializers.ModelSerializer): recipe = RecipeSerializer(many=True, read_ony=True) class Meta: model = RecipeBook fields = &quot;__all__&quot; </code></pre> <p>What would be the best way, when showing all Restaurants with a simple <code>GET</code> method, to show only the first 5 recipes created and not all of them?</p>
<p>QuerySet way:</p> <p>You can specify custom <code>Prefetch</code> operation in your queryset to limit the prefetched related objects:</p> <pre><code>queryset.prefetch_related(Prefetch('recipes', queryset=Recipe.objects.all()[:5])) </code></pre> <p>Docs: <a href="https://docs.djangoproject.com/en/3.2/ref/models/querysets/#prefetch-objects" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.2/ref/models/querysets/#prefetch-objects</a></p> <p>Serializer way:</p> <p>You can use <code>source</code> to provide a custom method to return a custom queryset</p> <pre><code>class RecipeBookSerializer(serializers.ModelSerializer): recipes = RecipeSerializer(many=True, read_only=Treue, source='get_recipes') class Meta: model = RecipeBook fields = &quot;__all__&quot; def get_recipes(self, obj): return obj.recipes.all()[:5] </code></pre> <p>Then use <code>prefetch_related(&quot;recipes&quot;)</code> to minimize related queries.</p> <p>Source: <a href="https://stackoverflow.com/questions/25312987/django-rest-framework-limited-queryset-for-nested-modelserializer">django REST framework - limited queryset for nested ModelSerializer?</a></p> <p>The problem with the serializer way is that either a related query for recipes is performed per recipe book object or all related recipes are pre-fetched from the beginning.</p>
python|django|django-models|django-rest-framework|many-to-many
2
727
72,239,073
Panda dataframe replace() method for row numbers
<p>I need to replace some values in a column with a specific value using the row numbers list of the required values as an array like following array.Can I use <code>dataframe.replace()</code> for that?</p> <pre><code>row_numbers = [ 4, 7, 15, 18, 49, 60, 78, 80] </code></pre>
<p>You can use <code>loc</code></p> <pre class="lang-py prettyprint-override"><code>df.loc[row_numbers, 'col'] = 3 </code></pre> <p>in case your index is not number</p> <pre class="lang-py prettyprint-override"><code>df['col'].iloc[row_numbers] = 3 </code></pre>
python|pandas
0
728
50,462,322
How is this Python function read?
<p>Wikipedia has the following example code for <a href="https://en.wikipedia.org/wiki/Softmax_function" rel="nofollow noreferrer">softmax</a>.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; z = [1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0] &gt;&gt;&gt; softmax = lambda x : np.exp(x)/np.sum(np.exp(x)) &gt;&gt;&gt; softmax(z) array([0.02364054, 0.06426166, 0.1746813 , 0.474833 , 0.02364054 , 0.06426166, 0.1746813 ]) </code></pre> <p>When I run it, it runs successfully. I don't understand how to read the <code>lambda</code> function. In particular, how can the parameter <code>x</code> refer to an array element in the numerator and span all the elements in the denominator?</p> <p>[Note: <a href="https://stackoverflow.com/questions/890128/why-are-python-lambdas-useful">The question</a> this question presumably duplicates is about <code>lambdas</code> in general. This question is not necessarily about <code>lambda</code>. It is about how to read the <code>np</code> conventions. The answers by @Paul Panzer and @Mihai Alexandru-Ionut both answer my question. Too bad I can't check both simultaneously as answering the question.</p> <p>To confirm that I understand their answers (and to clarify what my question was about):</p> <ul> <li><code>x</code> is the entire array (as it should be since the array is passed as the argument). </li> <li><code>np.exp(x)</code> returns the array with each element <code>x[i]</code> replaced by <code>np.exp(x[i])</code>. Call that new array <code>x_new</code>.</li> <li><code>x_new/np.sum(x_new)</code> divides each element of <code>x_new</code> by the sum of <code>x_new</code>.</li> </ul> <p>]</p>
<p>Three remarks.</p> <p>The use of <code>lambda</code> in the example is actually bad style, cf. this paragraph from the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">Python style guide</a>:</p> <blockquote> <p>Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.</p> <p>Yes:</p> <p>def f(x): return 2*x</p> <p>No:</p> <p>f = lambda x: 2*x</p> <p>The first form means that the name of the resulting function object is specifically 'f' instead of the generic ''. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)</p> </blockquote> <p>Re the content. What you are seeing is array arithmetic. <code>np.exp</code> is a numpy <code>ufunc</code> it operates element-wise, so it will return an array of the same shape as its argument. <code>np.sum</code> is a reducing function, when called with an array as its sole argument it will return a scalar. The <code>/</code> operator is overloaded with a binary <code>ufunc</code>; like <code>np.exp</code> it operates element-wise. In addition, it does broadcasting: In this case the scalar denominator will be paired with every element of the array numerator resulting in an array.</p> <p>And finally: <a href="https://stackoverflow.com/a/50425683/7207392">Here</a> is how to implement the softmax <a href="https://stackoverflow.com/a/42606665/7207392">properly</a>.</p>
python|numpy
1
729
44,891,294
Problems with converting a Python script into a Windows service
<p>I already have a python script that runs continuously. It's very similar to this: <a href="https://github.com/walchko/Black-Hat-Python/blob/master/BHP-Code/Chapter10/file_monitor.py" rel="nofollow noreferrer">https://github.com/walchko/Black-Hat-Python/blob/master/BHP-Code/Chapter10/file_monitor.py</a></p> <p>Similar as in, when running it as a script, it opens a CMD which shows some data when stuff happens - it's not user-interactible so it's not mandatory that it shows (just in case someone wishes to point out that windows services can't have interfaces)</p> <p>I've tried to convert it to a service. It starts for a fraction of a second and then automatically stops. When trying to start it via services.msc (instead of python script.py start) it doesn't start at all, Windows error says something like: "The service on local computer started and then stopped" which sounds just about what's happening if I try to start it with the argument. </p> <p>I've tried modifying the script to allow it to run as a service - adding the skeleton I found here: <a href="https://stackoverflow.com/questions/32404/is-it-possible-to-run-a-python-script-as-a-service-in-windows-if-possible-how">Is it possible to run a Python script as a service in Windows? If possible, how?</a></p> <p>I've also tried just getting the skeleton script above and just trying to make it run the other script with examples from here: <a href="https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-python-script-from-another-python-script">What is the best way to call a Python script from another Python script?</a> </p> <p>Does anyone have any idea what the best course of action would be to run that script above as a service?</p> <p>Thanks!</p>
<p><strong><em>Edited</em></strong></p> <blockquote> <p><em>"...services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface."</em> ~<a href="https://docs.microsoft.com/en-us/dotnet/framework/windows-services/introduction-to-windows-service-applications" rel="nofollow noreferrer"><strong><em>Introduction to Windows Service Applications</em></strong></a></p> </blockquote> <p><strong>Windows services require the implementation to make a specific interface available:</strong></p> <ul> <li><p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms685967(v=vs.85).aspx" rel="nofollow noreferrer"><strong>Service Programs</strong></a></p></li> <li><p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms685141(v=vs.85).aspx" rel="nofollow noreferrer"><strong>Services</strong></a></p></li> </ul> <p><strong>So you will need to access the Windows API through Python:</strong></p> <p>You can see the <a href="http://examples.oreilly.com/9781565926219/ppw32_samples.zip" rel="nofollow noreferrer"><strong>example code</strong></a>, from <a href="http://www.oreilly.com/catalog/pythonwin32/" rel="nofollow noreferrer"><strong>Python Programming On Win32</strong></a>, within which Chapter 18 Services (ch18_services folder) contains a sample (SmallestService.py) demonstrating the smallest possible service written in Python:</p> <pre><code># SmallestService.py # # A sample demonstrating the smallest possible service written in Python. import win32serviceutil import win32service import win32event class SmallestPythonService(win32serviceutil.ServiceFramework): _svc_name_ = "SmallestPythonService" _svc_display_name_ = "The smallest possible Python Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. # The "service stop" request will set this event. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): # Before we do anything, tell the SCM we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # And set my event. win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # We do nothing other than wait to be stopped! win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) if __name__=='__main__': win32serviceutil.HandleCommandLine(SmallestPythonService) </code></pre> <hr> <p>You may need to download the appropriate <strong>pywin32</strong> wheel for your particular python environment here: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32" rel="nofollow noreferrer">http://www.lfd.uci.edu/~gohlke/pythonlibs/#pywin32</a></p> <p>And <a href="https://pip.pypa.io/en/stable/reference/pip_install/" rel="nofollow noreferrer">install</a> it (system wide, from admin cmd prompt):</p> <pre><code>&gt; cd \program files\python&lt;ver&gt;\scripts &gt; pip install \path\to\pywin32‑221‑cp&lt;ver&gt;‑cp&lt;ver&gt;m‑win_&lt;arch&gt;.whl </code></pre> <p>Or install it (per user, from regular cmd prompt):</p> <pre><code>&gt; cd \program files\python&lt;ver&gt;\scripts &gt; pip install --user \path\to\pywin32‑221‑cp&lt;ver&gt;‑cp&lt;ver&gt;m‑win_&lt;arch&gt;.whl </code></pre> <p><em>Be sure to replace the occurences of <code>&lt;ver&gt;</code> and <code>&lt;arch&gt;</code> appropriately.</em></p>
python|windows-services
2
730
61,555,726
I need a HTML front end to test and use a Django API
<p>newbie here. I followed a guide online and successfully deploy a Keras model with Django API. I wanted to create a HTML file which connected to the Django API, where I can load image into the model for processing, and then send back the prediction.</p> <p>Below are the codes for the API. I need someone to guide me. </p> <pre><code>import datetime import pickle import json from django.shortcuts import render from django.http import HttpResponse from rest_framework.decorators import api_view from api.settings import BASE_DIR from custom_code import image_converter @api_view(['GET']) def __index__function(request): start_time = datetime.datetime.now() elapsed_time = datetime.datetime.now() - start_time elapsed_time_ms = (elapsed_time.days * 86400000) + (elapsed_time.seconds * 1000) + (elapsed_time.microseconds / 1000) return_data = { "error" : "0", "message" : "Successful", "restime" : elapsed_time_ms } return HttpResponse(json.dumps(return_data), content_type='application/json; charset=utf-8') @api_view(['POST','GET']) def predict_plant_disease(request): try: if request.method == "GET" : return_data = { "error" : "0", "message" : "Plant Assessment System" } else: if request.body: request_data = request.data["plant_image"] header, image_data = request_data.split(';base64,') image_array, err_msg = image_converter.convert_image(image_data) if err_msg == None : model_file = f"{BASE_DIR}/ml_files/cnn_model.pkl" saved_classifier_model = pickle.load(open(model_file,'rb')) prediction = saved_classifier_model.predict(image_array) label_binarizer = pickle.load(open(f"{BASE_DIR}/ml_files/label_transform.pkl",'rb')) return_data = { "error" : "0", "data" : f"{label_binarizer.inverse_transform(prediction)[0]}" } else : return_data = { "error" : "4", "message" : f"Error : {err_msg}" } else : return_data = { "error" : "1", "message" : "Request Body is empty", } except Exception as e: return_data = { "error" : "3", "message" : f"Error : {str(e)}", } return HttpResponse(json.dumps(return_data), content_type='application/json; charset=utf-8') </code></pre>
<p>If you just need to test your API, download Postman and make requests from the application. It is much easier than actually making a whole HTML script to test your API. However, if you absolutely need to test your API through a frontend app, try the steps below.</p> <ol> <li>You need an image upload function in your HTML code.</li> </ol> <pre><code> &lt;body&gt; &lt;input type="file accept="image/png, image/jpeg"/&gt; &lt;/body&gt; </code></pre> <ol start="2"> <li>Make sure you have a valid API request URL</li> </ol> <pre><code>// For example POST &lt;site&gt;/v1/plant-image </code></pre> <ol start="3"> <li>Make the request from JS Script</li> </ol> <pre><code>&lt;script type="text/javascript"&gt; var HTTP = new XMLHttpRequest(); HTTP.onreadystatechange = function () { if (HTTP.readyState === 4 &amp;&amp; HTTP.status === 200) { console.log(HTTP.responseText); } } HTTP.open('POST', 'https://&lt;site&gt;/v1/plant-image', true); HTTP.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); HTTP.send(); &lt;/script&gt; </code></pre> <p>Since you are using DRF, make sure to handle errors by raising errors instead of returning them as responses. This can make error handling much easier. </p> <pre><code>from rest_framework.exceptions import ValidationError // some code... raise ValidationError() </code></pre>
python|html|django|api|keras
0
731
57,894,373
flask_sqlalchemy create model from different file
<p>I am trying to define and create my models with <code>flask_sqlalchemy</code>.</p> <p>If I do it all in one script, it works:</p> <p><strong>all_in_one.py</strong></p> <pre><code>from config import DevConfig from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object(DevConfig) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = app.config.get("DB_URI") db = SQLAlchemy(app) class Members(db.Model): id = db.Column(db.String, primary_key=True, nullable=False) def main(): db.drop_all() db.create_all() if __name__ == "__main__": main() </code></pre> <p>The <code>Members</code> table is created.</p> <p>If I split this process into files, I can't seem to get the <code>db</code> object to register my <code>Members</code> model and do anything.</p> <pre><code>root │-- config.py │-- create.py │-- database.py │-- members.py </code></pre> <p><strong>database.py</strong></p> <pre><code>from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() </code></pre> <p><strong>members.py</strong></p> <pre><code>from database import db class Members(db.Model): id = db.Column(db.String, primary_key=True, nullable=False) </code></pre> <p><strong>create.py</strong></p> <pre><code>from database import db from config import DevConfig from flask import Flask app = Flask(__name__) app.config.from_object(DevConfig) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = app.config.get("DB_URI") def main(): db.init_app(app) with app.app_context(): db.drop_all() db.create_all() if __name__ == "__main__": main() </code></pre> <p>The <code>Members</code> table does not get created.</p>
<p>add <code>import members</code> below <code>db.init_app(app)</code></p> <pre class="lang-py prettyprint-override"><code>from database import db from config import DevConfig from flask import Flask app = Flask(__name__) app.config.from_object(DevConfig) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = app.config.get("DB_URI") def main(): db.init_app(app) import members with app.app_context(): db.drop_all() db.create_all() if __name__ == "__main__": main() </code></pre>
python|flask|sqlalchemy|flask-sqlalchemy
2
732
53,836,433
Turning on Jinja2 extensions in Salt
<p>I'm writing a lot of Salt states and I want to use the <a href="http://jinja.pocoo.org/docs/2.10/extensions/#expression-statement" rel="nofollow noreferrer">do tag extension</a> as suggested in <a href="https://stackoverflow.com/a/43265291/1694">this StackOverflow answer</a>.</p> <p>According to the <a href="https://www.linode.com/docs/applications/configuration-management/introduction-to-jinja-templates-for-salt/#jinja-basics" rel="nofollow noreferrer">Salt docs</a>, I should be able to edit <code>/etc/salt/master</code> to add these lines:</p> <pre><code>jinja_env: extensions: ['jinja2.ext.do'] jinja_sls_env: extensions: ['jinja2.ext.do'] </code></pre> <p>and then restart the <code>salt-master</code> service and have access to the <code>do</code> tag. However, I tried that and I get the same error as before, so it's not recognizing the tag.</p> <p>I've confirmed that the extension is available on the server by testing it at the command line:</p> <pre><code>&gt;&gt;&gt; import jinja2 &gt;&gt;&gt; jinja2.Environment(extensions=['jinja2.ext.do']).parse(open('/path/to/mytemplate.jinja').read()) Template(body=[...]) </code></pre> <p>What am I missing? How do I configure Salt to use the <code>{% do %}</code> Jinja tag?</p>
<p>From reviewing the <a href="https://github.com/MadeiraCloud/salt/blame/master/sources/salt/utils/templates.py#L226" rel="nofollow noreferrer">Salt source code</a>, it appears that it applies these extensions automatically if they're available. The error I was getting about the template failing to render appears to be from an unrelated syntax error.</p> <p>So the true answer all along is that you don't have to do anything to make use of the <code>{% do %}</code> template tag.</p>
python|jinja2|salt-stack
0
733
23,985,316
Auto set field in Django Model, depending on another user submitted field
<p>Say I have this code:</p> <pre><code>from django.db import models class Restaurant(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) </code></pre> <p>then I'm able to create a 'Place':</p> <pre><code>&gt;&gt;&gt; p1 = Restaurant(name='Demon Dogs', address='944 W. Fullerton') &gt;&gt;&gt; p1.save() </code></pre> <p>Here's the point. I'd like to have a preset dictionary like:</p> <pre><code>autoadress = {'Demon Dogs':'944 W. Fullerton', 'Eat attack':'100 Green Meadows', 'Pizza Fast':'50 E. High Hill'} </code></pre> <p>so that when a user creates a 'Restaurant' by only specifying it's name:</p> <pre><code>&gt;&gt;&gt; p1 = Restaurant(name='Demon Dogs') &gt;&gt;&gt; p1.save() </code></pre> <p>A new Restaurant with name='Demon Dogs' and address='944 W. Fullerton' was created</p> <p>How should I do this?</p> <p>thanks. </p>
<pre><code>AUTOADDRESS = {'Demon Dogs':'944 W. Fullerton', 'Eat attack':'100 Green Meadows', 'Pizza Fast':'50 E. High Hill'} class Restaurant(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def clean(self): if not self.address: self.address = AUTOADDRESS.get(self.name, '') </code></pre>
python|django
1
734
20,875,529
Realtime list of viewers in a Google Drive document
<p>I'm working on an app which wraps Google Docs (using GAE/Python), and I want to keep track of who is viewing these docs in real-time. I can't find any APIs for this in the Google Drive SDK.</p> <p>What's a good way to do this? Naively, I might imagine repeatedly polling each document individually and parsing the returned HTML. I expect there to be ~150 docs total in the system; would this be too inefficient?</p>
<p>Realtime api is not for using with gdocs, only for your own custom formats. Instead see the changes api in drive but you wont be able to detect viewers only modifications <a href="https://developers.google.com/drive/manage-changes" rel="nofollow">https://developers.google.com/drive/manage-changes</a></p>
python|google-app-engine|google-drive-api
2
735
21,083,772
How to tell if boto.sqs.Queue.write() succeeded?
<p>All documentation of this method that I can find says that Queue.write returns True or False, depending on whether the write succeeded, but this doesn't square with reality. </p> <p>The docs say:</p> <blockquote> <p>The write method returns a True if everything went well. If the write didn't succeed it will either return a False (meaning SQS simply chose not to write the message for some reason) or an exception if there was some sort of problem with the request.</p> </blockquote> <p>But in fact the method simply returns the message that gets passed in. Here is the relevant source code from <a href="https://github.com/boto/boto/blob/develop/boto/sqs/queue.py" rel="nofollow">https://github.com/boto/boto/blob/develop/boto/sqs/queue.py</a>:</p> <pre><code>def write(self, message, delay_seconds=None): """ Add a single message to the queue. :type message: Message :param message: The message to be written to the queue :rtype: :class:`boto.sqs.message.Message` :return: The :class:`boto.sqs.message.Message` object that was written. """ new_msg = self.connection.send_message(self, message.get_body_encoded(), delay_seconds) message.id = new_msg.id message.md5 = new_msg.md5 return message </code></pre> <p>My question then is: How do I really tell if the write was successful?</p>
<p>The documentation quote you provide comes from the SQS tutorial. The <a href="http://docs.pythonboto.org/en/latest/ref/sqs.html#boto.sqs.queue.Queue.write_batch" rel="noreferrer">SQS API docs</a> correctly describe the current return value. The SQS tutorial is simply out of date and needs to be corrected. I have created an <a href="https://github.com/boto/boto/issues/1985" rel="noreferrer">issue</a> to track this.</p> <p>If the write fails for any reason, the service will return an HTTP error code which, in turn, will cause boto to raise an SQSError exception. If no exception is raised, the write was successful.</p>
python|amazon-web-services|boto|amazon-sqs
6
736
53,592,140
What is the difference between timesteps and features in LSTM?
<p>I have a dataframe representing numerical values in many time periods, and I have formatted that dataframe in the way there are represented as a concatenation of previous values. For example:</p> <pre><code>+------+------+------+ | t1 | t2 | t3 | +------+------+------+ | 4 | 7 | 10 | +------+------+------+ | 7 | 10 | 8 | +------+------+------+ | 10 | 8 | 11 | +------+------+------+ ... </code></pre> <p>When I format the dataset to work with a LSTM, I reshape it to a 3 dimensional vector [samples, time steps, features].</p> <p>But, which value do I have to put for time steps and features? Should features be 3 because I learn with the last 3 elements?</p> <p>By the moment I have this one:</p> <pre><code>trainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) </code></pre>
<p>I try to explain on example. So assume we have some measurement with temperature and pressure and we want to predict temperature at some point of future. We have two features right(temperature &amp; pressure). So we can use them for feeding LSTM and try to predict. Now I'm not sure how you stand with LSTM theory, but there are two variables at game, cell state C and previous output h(t-1). We concentrate to h(t-1). So you gave LSTM cell(assume now only one neuron) input(temperature and pressure). LSTM produce output and cell state and now, if you have time steps at 1, when you give LSTM new input, output will be dependent only at cell state and input. But if your timesteps is set to five. Second input will be dependent on cell state, input and previous output. Third output will be dependent on second output, cell state, current input. This sequence continues at the moment of sixth input, when you again depend on input and cell state. These h(t-1) stuff is refereed as short time memory. So if you set time steps to 1, you loose your short memory.</p> <p><strong>Edit</strong> My bad I don't look at your data at right way. You have one feature, t and three steps. But you don't frame it right way, you treat three t values as separate features and feed LSTM with them. But you can instead reshape your data to samples x 3 x 1. So you feed LSTM with t1 of first sample, next t2 of first sample but LSTM output will be affected by output from previous time step.</p>
python|neural-network|lstm|timestep
0
737
51,808,871
Python relations between run_until_complete and ensure_future
<p>This is a follow up question to this question:</p> <p><a href="https://stackoverflow.com/questions/40143289/why-do-most-asyncio-examples-use-loop-run-until-complete">Why do most asyncio examples use loop.run_until_complete()?</a></p> <p>I'm trying to figure out how asynchronous programming work in python. There's something very basic which I'm still not sure about..</p> <p>when having this line code: <code>asyncio.ensure_future(someTask)</code> , will this line ALONE actually enqueue the <code>Future</code> returned in the default event loop and start the task? Or do I ALSO need to call <code>loop.run_until_complete(someTask)</code> (or some other kind of run) before that in order to get the event loop up and running? </p>
<blockquote> <p><code>asyncio.ensure_future(someTask)</code> will this line ALONE actually enqueue the Future returned in the default event loop and start the task?</p> </blockquote> <p>It will schedule the coroutine, but it won’t run it. You still need to run the loop to do that. You can do that with </p> <pre><code>loop.run_forever() </code></pre> <p>If you want the loop to run until <code>someTask</code> is done rather than forever, use</p> <pre><code>future = asyncio.ensure_future(someTask) loop.run_until_complete(future) </code></pre> <p>Don’t call both <code>asyncio.ensure_future(someTask)</code> and <code>loop.run_until_complete(someTask)</code> or you’ll end up with a <code>RuntimeError</code> since <code>someTask</code> will have already been scheduled. </p>
python|python-asyncio
4
738
43,623,117
Cleaner pandas/numpy code to find equivalency matrix?
<p>I have pandas DataFrame and would like to generate an equivalency matrix (or whatever it's called) where each cell has one value if the the df.Col[i] == df.Col[j] and another value when !=.</p> <p>The following code works:</p> <pre><code>df = pd.DataFrame({"Col":[1, 2, 3, 1, 2]}, index=["A","B","C","D","E"]) df Col A 1 B 2 C 3 D 1 E 2 sm = pd.DataFrame(columns=df.index, index=df.index) for i in df.index: for j in df.index: if df.Col[i] == df.Col[j]: sm.loc[i, j] = 3 else: sm.loc[i, j] = -1 sm A B C D E A 3 -1 -1 3 -1 B -1 3 -1 -1 3 C -1 -1 3 -1 -1 D 3 -1 -1 3 -1 E -1 3 -1 -1 3 </code></pre> <p>But there must be a better way. Perhaps using numpy? Any thoughts?</p> <p>[Edit]</p> <p>Using what piRsquared wrote, perhaps something like?</p> <pre><code>m = df.values == df.values[:, 0] sm = pd.DataFrame(None, df.index, df.index).where(m, 3).where(~m, -1) </code></pre> <p>Can this be improved?</p>
<pre><code>v = df.values m = v == v[:, 0] pd.DataFrame(np.where(m, 1, -1), df.index, df.index) A B C D E A 1 -1 -1 1 -1 B -1 1 -1 -1 1 C -1 -1 1 -1 -1 D 1 -1 -1 1 -1 E -1 1 -1 -1 1 </code></pre>
python|pandas|numpy
3
739
39,204,113
Send XML to activeMQ using Django
<p>I am trying to send a XML file generated using 'ElementTree' to activeMQ server using python django 'requests' library .My views.py code is :</p> <pre><code>from django.shortcuts import render import requests import xml.etree.cElementTree as ET # Create your views here. def index(request): return render(request,"indexer.html") def xml(request): root = ET.Element("root") doc = ET.SubElement(root, "doc") field1 = ET.SubElement(doc,"field1") ET.SubElement(doc, "field2", fame="yeah", name="asdfasd").text = "some vlaue2" ET.SubElement(field1,"fielder", name="ksd").text = "valer" tree = ET.ElementTree(root) headers = {} tree.write("filename.xml", encoding = "us-ascii", xml_declaration = 'utf-8', default_namespace = xml, method = "xml") url = 'http://localhost:8082/testurl/' headers = {'Content-Type': 'application/xml'} files = {'file': open('filename.xml', 'rb')} requests.post(url, files=files, headers = headers) return render(request,"indexer.html") </code></pre> <p>and there is a simple submit button on indexer.html page.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" action="/xml/"&gt;{% csrf_token %} &lt;input type="submit" value="submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When I click submit button it's generating filename.xml file and then sending it successfully to activeMQ server, but at activeMQ i am getting XML message which contains header information also . So ,is it possible to send only body part without header or how to omit header at activeMQ side and keep only body/data part ? At activeMQ I'm getting following message:</p> <pre><code>--6dc760762ba245eb8e4c3d72aa38062b Content-Disposition: form-data; name="file"; filename="filename.xml" &lt;root&gt;&lt;doc&gt;&lt;field1&gt;&lt;fielder name="ksd"&gt;valer&lt;/fielder&gt;&lt;/field1&gt;&lt;field2 fame="yeah" name="asdfasd"&gt;some vlaue2&lt;/field2&gt;&lt;/doc&gt;&lt;/root&gt; --6dc760762ba245eb8e4c3d72aa38062b-- </code></pre>
<p>I suggest looking at using the available STOMP protocol instead of HTTP. You'll have more control over message payloads and message headers.</p> <p>Python library: <a href="https://pypi.python.org/pypi/stomp.py" rel="nofollow">https://pypi.python.org/pypi/stomp.py</a> ActiveMQ Support: <a href="http://activemq.apache.org/stomp.html" rel="nofollow">http://activemq.apache.org/stomp.html</a></p>
python|xml|django|jms|activemq
1
740
39,322,967
Django's runscript: No (valid) module for script 'filename' found
<p>I'm trying to run a script from the Django shell using the Django-extension <a href="http://django-extensions.readthedocs.io/en/latest/runscript.html" rel="noreferrer">RunScript</a>. I have done this before and but it refuses to recognize my new script:</p> <pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript fill_in_random_variants No (valid) module for script 'fill_in_random_variants' found Try running with a higher verbosity level like: -v2 or -v3 </code></pre> <p>While running any other script works fine:</p> <pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript fill_in_variants Success! At least, there were no errors. </code></pre> <p>I have double checked that the file exists, including renaming it to something else. I have also tried running the command with non-existent script names:</p> <pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript thisfiledoesntexist No (valid) module for script 'thisfiledoesntexist' found Try running with a higher verbosity level like: -v2 or -v3 </code></pre> <p>and the error is the same.</p> <p>Why can't RunScript find my file?</p>
<p>RunScript has confusing error messages. It gives the same error for when it can't find a script at all and when there's an import error in the script.</p> <p>Here's an example script to produce the error:</p> <pre><code>import nonexistrentpackage def run(): print("Test") </code></pre> <p>The example has the only stated requirement for scripts, namely a <code>run</code> function.</p> <p>Save this as <code>test_script.py</code> in a scripts folder (such as <code>project root/your app/scripts/test_script.py</code>). Then try to run it:</p> <pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript test_script No (valid) module for script 'test_script' found Try running with a higher verbosity level like: -v2 or -v3 </code></pre> <p>Which is the same error as the file not found one. Now outcomment the import line and try again:</p> <pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript test_script Test </code></pre> <p>As far as I know, the only way to tell the errors apart is to use the verbose (-v2) command line option and then look at the <em>first</em> (scroll up) error returned:</p> <pre><code>(env) mint@mint-VirtualBox ~/GP/GP $ python manage.py runscript test_script -v2 Check for www.scripts.test_script Cannot import module 'www.scripts.test_script': No module named 'nonexistrentpackage'. Check for django.contrib.admin.scripts.test_script Cannot import module 'django.contrib.admin.scripts.test_script': No module named 'django.contrib.admin.scripts'. Check for django.contrib.auth.scripts.test_script Cannot import module 'django.contrib.auth.scripts.test_script': No module named 'django.contrib.auth.scripts'. Check for django.contrib.contenttypes.scripts.test_script Cannot import module 'django.contrib.contenttypes.scripts.test_script': No module named 'django.contrib.contenttypes.scripts'. Check for django.contrib.sessions.scripts.test_script Cannot import module 'django.contrib.sessions.scripts.test_script': No module named 'django.contrib.sessions.scripts'. Check for django.contrib.messages.scripts.test_script Cannot import module 'django.contrib.messages.scripts.test_script': No module named 'django.contrib.messages.scripts'. Check for django.contrib.staticfiles.scripts.test_script Cannot import module 'django.contrib.staticfiles.scripts.test_script': No module named 'django.contrib.staticfiles.scripts'. Check for django_extensions.scripts.test_script Cannot import module 'django_extensions.scripts.test_script': No module named 'django_extensions.scripts'. Check for scripts.test_script Cannot import module 'scripts.test_script': No module named 'scripts'. No (valid) module for script 'test_script' found </code></pre> <p>where we can see the crucial line:</p> <pre><code>No module named 'nonexistrentpackage'. </code></pre> <p>The commonality of the errors seems to be because the extension runs the script using <code>import</code>. It would be more sensible if it first checked for the existence of the file using <a href="https://docs.python.org/3/library/os.path.html" rel="noreferrer"><code>os.path.isfile</code></a> and if not found, the threw a more sensible error message.</p>
python|django
13
741
47,957,499
Multiple filters on exists
<p>I'm trying to filter my <em>exists</em> query set into looking through 3 fields to check if a release date of this game, platform and region already exists. </p> <p>What I seek to accomplish: </p> <pre><code>if ReleaseDate.objects.filter(game=game.id).filter(platform=release_date_object['platform']).filter(region=release_date_object['region']).exists(): </code></pre>
<p>Very simple - just put them all together in one filter() with commas:</p> <pre><code>if ReleaseDate.objects.filter(game=game.id, platform=release_date_object['platform'], region=release_date_object['region']).exists(): </code></pre> <p>Sometimes more complicated queries require Q objects but for a simple multiple-field query just put them all in one filter().</p>
python|django|rest
1
742
38,517,124
How to minimize two loss using TensorFlow?
<p>I am working on a project which is to localize object in a image. The method I am going to adopt is based on the localization algorithm in <a href="https://cs231n.stanford.edu/slides/winter1516_lecture8.pdf" rel="nofollow">CS231n-8</a>.</p> <p>The network structure has two optimization heads, classification head and regression head. How can I minimize both of them when training the network?</p> <p>I have one idea that summarizing both of them into one loss. But the problem is classification loss is softmax loss and regression loss is l2 loss, which means they have different range. I don't think this is the best way.</p>
<p>It depends on your network status.</p> <p>If your network is just able to extract features [you're using weights kept from some other net], you can set this weights to be constants and then train separately the two classification heads, since the gradient will not flow trough the constants.</p> <p>If you're not using weights from a pre-trained model, you</p> <ol> <li>Have to train the network to extract features: thus train the network using the classification head and let the gradient flow from the classification head to the first convolutional filter. In this way your network now can classify objects combining the extracted features.</li> <li>Convert to constant tensors the learned weights of the convolutional filters and the classification head and train the regression head.</li> </ol> <p>The regression head will learn to combine the features extracted from the convolutional layer adapting its parameters in order to minimize the L2 loss.</p> <p><strong>Tl;dr:</strong></p> <ol> <li>Train the network for classification first.</li> <li>Convert every learned parameter to a constant tensor, using <code>graph_util.convert_variables_to_constants</code> as showed in the '<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py" rel="nofollow">freeze_graph`</a> script.</li> <li>Train the regression head.</li> </ol>
tensorflow
2
743
26,428,773
Django - Save a new table1.PK and table2.PK and table2.FK
<p>I created 2 forms based on django-crispy forms. </p> <ol> <li>Form1 shows the OrderHeader</li> <li>Form2 shows the OrderLines in a formset</li> </ol> <p>When i open an existing OrderHeader, i see the Header and the Lines, i can adjust and save the open forms just fine. </p> <p>When i open the form empty, i select a customer in the OrderHeader and then Add some order lines, but here i can not save as the OrderLine has no FK value for the OrderLine.orderheader. </p> <p><strong>Q: How can i save the OrderHeader.pk in the OrderLine.orderheader when i hit submit?</strong></p> <p>My views.py</p> <pre><code>def orderline_formset(request, id=None): if id: orderid = OrderHeader.objects.get(pk=id) else: orderid = OrderHeader() OrderLineFormSet = inlineformset_factory(OrderHeader, OrderLine, OrderLineForm, extra = 1, can_delete=True) form = OrderHeaderForm(instance=orderid) formset = OrderLineFormSet(instance=orderid) helper = OrderLineFormSetHelper() if request.method == 'POST': OrderLine.orderheader = orderid formset = OrderLineFormSet(request.POST,instance=orderid) if formset.is_valid(): formset.save() messages.success(request, 'Order saved succesfully!') else: messages.error(request, 'Order save error, please check fields below') else: formset = OrderLineFormSet(instance=orderid) return render_to_response("order.html", {'orderform' : form,'formset': formset, 'helper': helper}, context_instance=RequestContext(request)) </code></pre> <p>My forms.py</p> <pre><code>class OrderHeaderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderHeaderForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False class Meta: model = OrderHeader class OrderLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderLineForm, self).__init__(*args, **kwargs) class Meta: model = OrderLine class OrderLineFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(OrderLineFormSetHelper, self).__init__(*args, **kwargs) self.form_method = 'post' self.template = 'bootstrap3/table_inline_formset.html' self.render_required_fields = True self.form_tag = False </code></pre>
<p>The error was that i was only saving the formset and not the form. So i changed my views.py to the following; </p> <pre><code>if request.method == 'POST': form = OrderHeaderForm(request.POST,instance=orderid) formset = OrderLineFormSet(request.POST,instance=orderid) if form.is_valid() and formset.is_valid(): form.save() formset.save() messages.success(request, 'Order saved succesfully!') </code></pre>
python|django|django-crispy-forms
0
744
28,252,337
Use AJAX to display dictionary data returned by Django view in a table on the template
<p>I saw some posts on this topic but none quite similar. I am getting back a dictionary in JSON format from a Django view as shown below:</p> <pre><code># display game statistics on the developer homepage def gamestats(request): countlist = [] datedict = {} if request.method=='POST' and request.is_ajax: id = request.POST.get('id',None) gameobj = Games.objects.filter(pk=id) # get queryset of Scores objects with the selected game ID scores = Scores.objects.filter(game=gameobj) # get list of distinct registration dates from "scores" queryset datelist = scores.values_list('registration_date',flat=True).distinct() for dateobj in datelist: scoredate = scores.filter(registration_date=dateobj) c = scoredate.count() countlist.append(c) n = len(countlist) for i in range(n): t = datelist[i].strftime('%d/%m/%Y') datedict[t] = countlist[i] print(t) print(datedict[t]) json_stats = json.dumps(datedict) return HttpResponse(json_stats,content_type='application/json') </code></pre> <p>This dictionary holds data in the form:</p> <pre><code>{ "29/01/2015" : 2, "21/12/2014" : 1, "23/01/2015": 3 } </code></pre> <p>Now, on the client side, the AJAX code is given below:</p> <pre><code>$(".stats").click(function(){ var game = $(this); var id = game.attr('id'); var csrftoken = getCookie('csrftoken'); $.ajax({ type : "POST", url : "/gamestats/", data : {'id': id, 'csrfmiddlewaretoken': csrftoken}, dataType : "json", success : function(data){ alert(data); //var obj = $.parseJSON(response); //for (var key in obj){ // alert("inside for loop"); // var value = obj[key]; // alert(value); // $("#gamestats").html(value); //} } }); event.preventDefault(); }); </code></pre> <p>The relevant HTML code: ...</p> <pre><code>&lt;tr&gt; &lt;td width="10%" align="center"&gt;&lt;button class="stats" id="{{game.id}}"&gt; View game statistics&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; ... &lt;b&gt;Game statistics: &lt;/b&gt; &lt;p id="gamestats"&gt;&lt;/p&gt; </code></pre> <p>Due to my very limited knowledge of AJAX, I do not know how to handle the response inside the "success" parameter of the request. I want to display the JSON data in a table, with 2 columns, one for the dates (keys) and other for the corresponding numbers (values). I want to do this inside the "gamestats" section of the page. I tried some things but they don't display anything. Any help is appreciated, thank you!!</p>
<p>If you want to take a JSON object and put it into a table you can loop over it like so:</p> <pre><code>var tableData = '&lt;table&gt;' $.each(data, function(key, value){ tableData += '&lt;tr&gt;'; tableData += '&lt;td&gt;' + key + '&lt;/td&gt;'; tableData += '&lt;td&gt;' + value + '&lt;/td&gt;'; tableData += '&lt;/tr&gt;'; }); tableData += '&lt;/table&gt;'; $('#table').html(tableData); </code></pre>
jquery|python|ajax|json|django
2
745
42,069,025
Pandas timeseries indexing fails when the index is hierarchical
<p>I tried the following code snippet.</p> <pre><code>In [84]: from datetime import datetime from dateutil.parser import parse ​ rng = [datetime(2017,1,13), datetime(2017,1,14), datetime(2017,2,15), datetime(2017,2,16)] ​ s = Series([1,2,3,4], index=rng) ​s['2017/1'] Out[84]: 2017-01-13 1 2017-01-14 2 dtype: int64 </code></pre> <p>As I expected, I could successfully retrieve only those items belonging to JAN by only specifying up to JAN like s['2017/1'].</p> <p>Next time, I tried a bit extended version of the above code, where a hierarchical index was used instead:</p> <pre><code>from datetime import datetime from dateutil.parser import parse rng1 = [datetime(2017,1,1), datetime(2017,1,1), datetime(2017,2,1), datetime(2017,2,1)] rng2 = [datetime(2017,1,13), datetime(2017,1,14), datetime(2017,2,15), datetime(2017,2,16)] midx = pd.MultiIndex.from_arrays([rng1, rng2]) s = Series([1,2,3,4], index=midx) s['2017/1'] </code></pre> <p>The above code snippet, however, generates an error: TypeError: unorderable types: int() > slice()</p> <p>Would you give me some help?</p>
<p>It seems it is more complicated.</p> <p><a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#partial-string-indexing-on-datetimeindex-when-part-of-a-multiindex" rel="nofollow noreferrer"><code>Partial string indexing on datetimeindex when part of a multiindex</code></a> is implemented in <code>DataFrame</code> in <code>pandas 0.18.</code></p> <p>So if use:</p> <pre><code>rng1 = [pd.Timestamp(2017,5,1), pd.Timestamp(2017,5,1), pd.Timestamp(2017,6,1), pd.Timestamp(2017,6,1)] rng2 = pd.date_range('2017-01-13', periods=2).tolist() + pd.date_range('2017-02-15', periods=2).tolist() s = pd.Series([1,2,3,4], index=[rng1, rng2]) print (s) 2017-05-01 2017-01-13 1 2017-01-14 2 2017-06-01 2017-02-15 3 2017-02-16 4 </code></pre> <p>Then for me works:</p> <pre><code>print (s.to_frame().loc[pd.IndexSlice[:, '2017/1'],:].squeeze()) 2017-05-01 2017-01-13 1 2017-01-14 2 Name: 0, dtype: int64 print (s.loc['2017/6']) 2017-06-01 2017-02-15 3 2017-02-16 4 dtype: int64 </code></pre> <p>But this return empty <code>Series</code>:</p> <pre><code>print (s.loc[pd.IndexSlice[:, '2017/2']]) Series([], dtype: int64 </code></pre>
pandas|time-series
1
746
47,086,990
High Scores! From ACM 2017
<pre><code> testcases = int(input()) for i in range(testcases): n = int(input()) names = [] for a in range(n): names.append(input()) prefix = '' for b in range(len(names[0])): for c in names: if c.startswith(prefix) == True: common = True else: common = False if common == False: break prefix += names[0][b] print(prefix) </code></pre> <p>I am given a list of names and I need to find the common prefix that applies to every name. My program works, but always returns one more letter than is supposed to be there. Why is this, and how do I fix it?</p>
<p>If the current prefix matches all the entered names, you add one more character to it. When it fails to match, you break out of the loop - but the character that caused the failure is still attached to the end of <code>prefix</code>.</p> <p>There are various ways to fix this, but one possibility is to just remove the last character by adding this statement outside the loop:</p> <pre><code>prefix = prefix[:-1] # python slice notation - remove the last element </code></pre> <p>There are some style issues with your code. Those would be best addressed on CodeReview rather than Stackoverflow.</p> <p>I would have done it this way (after replacing your input statements with a hard-coded test case):</p> <pre><code>x = ["Joseph", "Jose", "Josie", "Joselyn"] n = 0 try: while all(a[n] == x[0][n] for a in x[1:]): n += 1 except IndexError: pass print(x[0][:n]) </code></pre> <p>This script prints "Jos".</p>
python|python-3.x
0
747
62,158,878
Adding a dimension to an array
<p>If I have an array that I loaded from a nifti file with shape <code>(112, 176, 112)</code> and I want to add a fourth dimension but not be limited to shape <code>(112, 176, 112, 3)</code></p> <p>Why does this code allow me to add however many layers in the 4th dimension I want:</p> <pre><code>data = np.ones((112, 176, 112, 20), dtype=np.int16) print(data.shape) &gt;&gt;&gt;(112, 176, 112, 20) </code></pre> <p>But when I try to add a higher layer number to the fourth dimension of my file I get an error. The code only works correctly if <code>axis = 3</code>. If <code>axis = 2</code> the shape is <code>(112, 176, 336, 1)</code></p> <pre><code>filepath = '3channel.nii' img = nib.load(filepath) img = img.get_fdata() print(img.shape) &gt;&gt;&gt;(112, 176, 112) img2 = img.reshape((112, 176, 112, -1)) img2 = np.concatenate([img2, img2, img2], axis = 20) </code></pre> <p>Error:</p> <pre><code>AxisError: axis 20 is out of bounds for array of dimension 4 </code></pre>
<p>@hpaulj got it, I was looking this up, and this shows the issue; note the shape of the arrays. I modified the original array so you can see what is being added...</p> <pre><code>import numpy as np data = np.ones((112, 176, 115, 20), dtype=np.int16) data2=np.ones((112, 176, 115), dtype=np.int16) data2a = data2.reshape((112, 176, 115, -1)) print(data2a.shape) print("concatenate...") img2 = np.concatenate([data2a, data2a, data2a],axis=0) print(img2.shape) img2 = np.concatenate([data2a, data2a, data2a],axis=1) print(img2.shape) img2 = np.concatenate([data2a, data2a, data2a],axis=2) print(img2.shape) img2 = np.concatenate([data2a, data2a, data2a],axis=3) print(img2.shape) # This throws the error img2 = np.concatenate([data2a, data2a, data2a],axis=4) print(img2.shape) </code></pre>
python|numpy|concatenation|reshape|nifti
0
748
67,324,818
How can I get the last 10 records of each day?
<p>I have a DataFrame with 96 records each day, for 5 consecutive days.</p> <p><strong>Data:</strong> {'value': {Timestamp ('2018-05-03 00:07:30'): 13.02657778, Timestamp ('2018-05-03 00:22:30'): 10.89890556, Timestamp ('2018-05-03 00:37:30'): 11.04877222,... (more days and times)</p> <p><strong>Datatypes:</strong> DatetimeIndex (index column) and float64 ('flow' column).</p> <p>I want to save 10 records before an indicated hour (H), of each day.</p> <p>I only managed to do that for one day:</p> <pre><code>df.loc[df['time'] &lt; '09:07:30'].tail(10) </code></pre>
<p>I would suggest filter the record by an hour and then group by date.</p> <p><strong>Data setup:</strong></p> <pre><code>import pandas as pd start, end = '2020-10-01 01:00:00', '2021-04-30 23:30:00' rng = pd.date_range(start, end, freq='5min') df=pd.DataFrame(rng,columns=['DateTS']) </code></pre> <p>set the hour</p> <pre><code>noon_hour=12 # fill the hour , for filteration </code></pre> <p>Result, if head or tail does not work on your data, you would need to sort it.</p> <pre><code>df_before_noon=df.loc[df['DateTS'].dt.hour &lt; noon_hour] # records before noon df_result=df_before_noon.groupby([df_before_noon['DateTS'].dt.date]).tail(10) # group by date </code></pre>
python|time-series|timestamp
0
749
63,627,858
get error when using sum and case in sqlalchemy
<p>I'm using <code>sqlalchemy</code> <code>func.sum</code> with <code>case</code> in a <code>having</code> condition but get below error. code:</p> <pre><code>query = query.having( func.sum(case([(e.c.escalation_type.in_(escalation_types), 1)], else_=0)) &gt; 0 ) </code></pre> <p><code>escalation_types</code> above is Python list get this error:</p> <pre><code>asyncpg.exceptions.UndefinedFunctionError: function sum(text) does not exist HINT: No function matches the given name and argument types. You might need to add explicit type casts. </code></pre> <p>Here is the <code>SQL</code> printed by above:</p> <pre><code>HAVING sum(CASE WHEN (escalation_1.escalation_type IN (:escalation_type_1)) THEN :param_1 ELSE :param_2 END) &gt; :sum_1 </code></pre> <p>what am I missing here? Thanks!</p>
<p>Looks like there is a bug in one of the libraries of <code>sqlalchemy</code>, <code>asyncpg</code>. I have to cast 1 and 0 to integer to make it work. here is working code:</p> <pre><code>query = query.having( func.sum( case( [(e.c.escalation_type.in_(escalation_types), cast(1, Integer))], else_=cast(0, Integer), ) ) &gt; 0 ) </code></pre>
python|sqlalchemy
1
750
36,596,457
iterate, Nonetype converting to String
<p>I am Scraping Financial Data from "<a href="http://profit.ndtv.com/stock/hindustan-unilever-ltd_hindunilvr/financials-historical" rel="nofollow">http://profit.ndtv.com/stock/hindustan-unilever-ltd_hindunilvr/financials-historical</a>"</p> <p>Code : </p> <pre><code>import requests from bs4 import BeautifulSoup import re url = "http://profit.ndtv.com/stock/hindustan-unilever-ltd_hindunilvr/financials-historical" page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') table = soup.find("table", {"id": "finsummaryTab"}) tr = table.findAll("tr") def periodEnding(index): td = BeautifulSoup(str(tr[2]), 'html.parser') td_list = td.find_all("td") return td_list[index].getText() b = print(periodEnding(1)) a = str(b) print(type(a)) for i in a: print(i) </code></pre> <p>Output :</p> <pre><code>216.35 &lt;class 'str'&gt; N o n e </code></pre> <p>I dont know why this happens, can anybody help me with this. thannkyou I want to iterate this numbers</p>
<p>You are using the return value of <code>print()</code>:</p> <pre><code>b = print(periodEnding(1)) </code></pre> <p><code>print()</code> <strong>always</strong> returns <code>None</code>. You then tried to print each individual character of the string <code>"None"</code> (produced by <code>a = str(b)</code>), so you indeed get the letters <code>N</code>, <code>o</code>, <code>n</code> and <code>e</code> printed.</p> <p>Store the return value of <code>periodEnding()</code> instead:</p> <pre><code>b = periodEnding(1) print(b) </code></pre> <p>You are also needlessly reparsing the <code>tr[2]</code> object here:</p> <pre><code>td = BeautifulSoup(str(tr[2]), 'html.parser') td_list = td.find_all("td") </code></pre> <p>There is <strong>no point</strong> in doing this. <code>tr[2]</code> is a <code>Tag</code> object and supports <code>find_all</code> directly:</p> <pre><code>def periodEnding(index): td_list = tr[2].find_all("td") return td_list[index].getText() </code></pre> <p>This gives you the exact same result without converting a whole subtree to a string then back again into virtually the same BeautifulSoup object tree.</p>
python|beautifulsoup|python-3.4
3
751
16,937,584
Could not import django.contrib.syndication.views.feed. View does not exist in module django.contrib.syndication.views. using django and rss
<p>I'm trying to get RSS to work with django</p> <p>I have a social bookmarking app.</p> <p>when I try to access the rss page at localhost:8000/feeds/recent/</p> <p>I get the following error:</p> <pre><code>Could not import django.contrib.syndication.views.feed. View does not exist in module django.contrib.syndication.views. </code></pre> <p>I am using python 2.7.3 and django 1.5.1</p> <p>I am only going to show the code that I think is relevant.</p> <p>I have the following code in feeds.py</p> <pre><code>from django.contrib.syndication.views import Feed from bookmarks.models import Bookmark class RecentBookmarks(Feed): title = 'Django Bookmarks | Recent Bookmarks' link = '/feeds/recent/' description = 'Recent bookmarks posted to Django Bookmarks' def items(self): return Bookmark.objects.order_by('id')[:10] </code></pre> <p>The urls.py has the following code I have left out the urls that are not relevant.</p> <pre><code>import os.path from django.conf.urls.defaults import * from bookmarks.views import * from bookmarks.feeds import * from django.views.generic import TemplateView from bookmarks.models import Link, Bookmark, Tag, SharedBookmark site_media = os.path.join( os.path.dirname(__file__), 'site_media' ) # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() admin.site.register(Link) class BookmarkAdmin(admin.ModelAdmin): list_display = ('title', 'link', 'user') list_filter = ('user',) ordering = ('title',) search_fields = ('title',) admin.site.register(Bookmark, BookmarkAdmin) admin.site.register(Tag) admin.site.register(SharedBookmark) feeds = { 'recent': RecentBookmarks } urlpatterns = patterns('', # Feeds (r'^feeds/(?P&lt;url&gt;.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds }), ) </code></pre> <p>The models.py looks like the following:</p> <pre><code>from django.db import models from django.contrib.auth.models import User class Link(models.Model): url = models.URLField(unique=True) def __str__(self): return self.url class Bookmark(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User) link = models.ForeignKey(Link) def __str__(self): return '%s %s' % (self.user.username, self.link.url) def get_absolute_url(self): return self.link.url </code></pre>
<p>The book I have been learning Django from is quite old.</p> <p>I discovered from looking at the Django Documentation that the url pattern that's required can now go straight to RecentBookmarks.</p> <p>I first looked <a href="https://docs.djangoproject.com/en/1.0/ref/contrib/syndication/" rel="nofollow">here</a></p> <p>and compared it with <a href="https://docs.djangoproject.com/en/1.2/ref/contrib/syndication/" rel="nofollow">this</a></p> <p>From this comparison I discovered that what I need to do is change the url pattern to the following.</p> <pre><code>(r'^feeds/(?P&lt;url&gt;.*)/$', RecentBookmarks()), </code></pre> <p>I also found that in RSS does not work with google chrome browser unless I installed the <a href="https://chrome.google.com/webstore/detail/rss-subscription-extensio/nlbjncdgjeocebhnmkbbbdekmmmcbfjd?hl=en" rel="nofollow">RSS Subscription extension</a></p> <p>After making these changes it now works correctly.</p>
django|python-2.7|rss
0
752
71,259,713
PyQt5 Application Window Not Showing
<p>I am trying to code an application that will allow the user to view a list of Tag IDs, as well as its description, and allow the user to check off each Tag ID that they would like to import data from. At this point I am working on developing the UI only.</p> <p>The code below worked and would show the application window until I added the <em>itemChanged</em> function &amp; connection. Now, when I run this code, only the print statement from the new function will show. The window never shows and the entire application promptly exits (see image for outcome of running script).</p> <p>Additionally, you'll notice that we get the checkState of each type of item - I only want the checkState of the Tag ID.</p> <p><a href="https://i.stack.imgur.com/e8CCC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e8CCC.jpg" alt="output" /></a></p> <pre><code>import sys from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QTableView, QHeaderView, QVBoxLayout, QAbstractItemView from PyQt5.QtCore import Qt, QSortFilterProxyModel from PyQt5.QtGui import QStandardItemModel, QStandardItem class myApp(QWidget): def __init__(self): super().__init__() self.resize(1000, 500) mainLayout = QVBoxLayout() tagIDs = ('Tag_1', 'Tag_2', 'Tag_3', 'Tag_4', 'Tag_5') descriptions = ('Description_1', 'Description_2', 'Description_3', 'Description_4', 'Description_5') model = QStandardItemModel(len(tagIDs), 2) model.itemChanged.connect(self.itemChanged) model.setHorizontalHeaderLabels(['Tag IDs', 'Description']) for i in range(len(tagIDs)): item1 = QStandardItem(tagIDs[i]) item1.setCheckable(True) item2 = QStandardItem(descriptions[i]) model.setItem(i, 0, item1) model.setItem(i, 1, item2) filterProxyModel = QSortFilterProxyModel() filterProxyModel.setSourceModel(model) filterProxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) filterProxyModel.setFilterKeyColumn(1) searchField = QLineEdit() searchField.setStyleSheet('font-size: 20px; height: 30px') searchField.textChanged.connect(filterProxyModel.setFilterRegExp) mainLayout.addWidget(searchField) table = QTableView() table.setStyleSheet('font-size: 20px;') table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch) table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch) table.setModel(filterProxyModel) table.setEditTriggers(QAbstractItemView.NoEditTriggers) mainLayout.addWidget(table) self.setLayout(mainLayout) def itemChanged(self, item): print(&quot;Item {!r} checkState: {}&quot;.format(item.text(), item.checkState())) def main(): app = QApplication(sys.argv) myAppControl = myApp() myAppControl.show() sys.exit(app.exec_()) if __name__ == &quot;__main__&quot;: main() </code></pre>
<p>Header settings that depend on the model <strong>must</strong> always be set when a model is set.</p> <p>Move <code>table.setModel(filterProxyModel)</code> right after the creation of the table or, at least, before <code>table.horizontalHeader().setSectionResizeMode</code> (the vertical <code>setSectionResizeMode()</code> is generic for the whole header and doesn't cause problems).</p>
python|pyqt5
1
753
9,139,287
Python - store chinese characters read from excel
<p>I am trying to read in an excel sheet using xlrd, but I'm having some problems storing Chinese characters.</p> <p>I am not sure why values get translated when I store it in a list:</p> <p>Code:</p> <pre><code>for rownum in range(sh.nrows): Temp.append(sh.row_values(rownum)) print Temp </code></pre> <p><strong>Output:</strong> </p> <blockquote> <p>u'\u8bbe\u5168\u96c6\u662f\u5b9e\u6570\u96c6R\uff0c<code>M= {x|-2&amp;lt;=x&amp;lt;=2}</code>\uff0c<code>N{x|x&amp;lt;1}</code>\uff0c\u5219<code>bar(M) nn N</code>\u7b49\u4e8e <p>\n[A]\uff1a<code>{x|x&amp;lt;-2}</code> <p>[B]\uff1a<code> {x|-2&amp;lt;1}</code> <p>[C]\uff1a<code>{x|x&amp;lt;1}</code> <p>[D]\uff1a<code>{x|-2&amp;lt;=x&amp;lt;1}</code>'</p> </blockquote> <p>However when I print out a single cell value, they are printed out correctly as per excel sheet:</p> <p>Code:</p> <pre><code> cell_test = sh.cell(1,3).value print cell_test </code></pre> <p><strong>Output:</strong> </p> <blockquote> <p>设全集是实数集R,<code>M={x|-2&amp;lt;=x&amp;lt;=2}</code>,<code>N={x|x&amp;lt;1}</code>,则<code>bar(M) nn N</code>等于 <p> [A]:<code>{x|x&amp;lt;-2}</code> <p>[B]:<code>{x|-2&amp;lt;1}</code> <p>[C]:<code>{x|x&amp;lt;1}</code> <p>[D]:<code>{x|-2&amp;lt;=x&amp;lt;1}</code></p> </blockquote> <p>What should I do to get Python to store the above data at its original value?</p> <p>Thanks!</p>
<p>First. You XSL parser seem to return <code>unicode</code> values.</p> <p>Second. When you do <code>print some_complex_object</code> (as you do <code>print Temp</code>), Python usually outputs the result of <code>repr</code> function on the elements of that object. And when you do <code>print repr(some_unicode_string)</code>, the usual output is something like <code>u'\u8bbe\u5168\u96c6\u662f'</code>.</p> <p>Third. There is nothing wrong with storing of the values - they are correctly stored, you just have problems with printing. Try something like:</p> <pre><code>for i in Temp: print i </code></pre>
python|cjk|xlrd
2
754
9,134,553
Web.py todo list with login
<p>I try to add a login functionality to the <code>web.py</code> <a href="http://webpy.org/src/todo-list/0.3" rel="nofollow">todo example</a>.</p> <p>This is my code:</p> <pre><code>""" Basic todo list using webpy 0.3 """ import web import model ### Url mappings urls = ( '/', 'Index', '/login', 'Login', '/logout', 'Logout', '/del/(\d+)', 'Delete', ) ### Templates render = web.template.render('templates', base='base') app = web.application(urls, locals()) session = web.session.Session(app, web.session.DiskStore('sessions')) allowed = ( ('user','pass'), ('tom','pass2') ) class Login: login_form = web.form.Form( web.form.Textbox('username'), web.form.Password('password'), web.form.Button('Login'), ) def GET(self): f = self.login_form() return render.login(f) def POST(self): # Validation if not self.login_form.validates(): print "it didn't validate!" session.logged_in = True raise web.seeother('/') class Logout: def GET(self): session.logged_in = False raise web.seeother('/') class Index: form = web.form.Form( web.form.Textbox('title', web.form.notnull, description="I need to:"), web.form.Button('Add todo'), ) def GET(self): print "logged_in " + str(session.get('logged_in', False)) if session.get('logged_in', False): """ Show page """ todos = model.get_todos() form = self.form() return render.index(todos, form) else: raise web.seeother('/login') def POST(self): """ Add new entry """ form = self.form() if not form.validates(): todos = model.get_todos() return render.index(todos, form) model.new_todo(form.d.title) raise web.seeother('/') class Delete: def POST(self, id): """ Delete based on ID """ id = int(id) model.del_todo(id) raise web.seeother('/') app = web.application(urls, globals()) if __name__ == '__main__': app.run() </code></pre> <p>When the user does a <code>POST</code> in <code>/login</code>, <code>logged_in</code> is always <code>False</code>.</p> <p>Any ideas why?</p>
<p>I just fixed it. I was missing some session initialization code. Here's the working code:</p> <pre><code>""" Basic todo list using webpy 0.3 """ import web import model ### Url mappings urls = ( '/', 'Index', '/login', 'Login', '/logout', 'Logout', '/del/(\d+)', 'Delete', ) web.config.debug = False render = web.template.render('templates', base='base') app = web.application(urls, locals()) session = web.session.Session(app, web.session.DiskStore('sessions')) allowed = ( ('user','pass'), ) class Login: login_form = web.form.Form( web.form.Textbox('username', web.form.notnull), web.form.Password('password', web.form.notnull), web.form.Button('Login'), ) def GET(self): f = self.login_form() return render.login(f) def POST(self): if not self.login_form.validates(): return render.login(self.login_form) username = self.login_form['username'].value password = self.login_form['password'].value if (username,password) in allowed: session.logged_in = True raise web.seeother('/') return render.login(self.login_form) class Logout: def GET(self): session.logged_in = False raise web.seeother('/') class Index: form = web.form.Form( web.form.Textbox('title', web.form.notnull, description="I need to:"), web.form.Button('Add todo'), ) def GET(self): if session.get('logged_in', False): """ Show page """ todos = model.get_todos() form = self.form() return render.index(todos, form) else: raise web.seeother('/login') def POST(self): """ Add new entry """ form = self.form() if not form.validates(): todos = model.get_todos() return render.index(todos, form) model.new_todo(form.d.title) raise web.seeother('/') class Delete: def POST(self, id): """ Delete based on ID """ id = int(id) model.del_todo(id) raise web.seeother('/') app = web.application(urls, globals()) if web.config.get('_session') is None: session = web.session.Session(app, web.session.DiskStore('sessions'), {'count': 0}) web.config._session = session else: session = web.config._session if __name__ == '__main__': app.run() </code></pre>
python|session|web.py
1
755
52,470,662
TypeError at /add_team/ 'dict' object is not callable
<p>views.py:</p> <pre><code>class AddTeamView(View): template_name = 'add_team.html' def get (self, request): form = TeamForm() context = {'form': form} return render(request, 'add_team.html', context) def post(self, request): form = TeamForm(request.POST) if form.is_valid(): team = Team() team.name = form.cleaned_data('name') team.details = form.cleaned_data('detials') context = {'form': form, 'team.name':team.name,'team.details':team.details} return render(request, self.template_name, context) </code></pre> <p>add_team.html :</p> <pre><code> {% extends 'base.html' %} {% block title %} add team {% endblock %} {% block content %} &lt;form action="/add_team/" method="post"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>forms.py :</p> <pre><code>from django import forms class TeamForm(forms.Form): name = forms.CharField(label='name of team') details = forms.CharField(label='details of team') </code></pre> <p>when I went to the browser it appeared this:</p> <blockquote> <p>TypeError at /add_team/ 'dict' object is not callable Request Method: POST Request URL: <a href="http://127.0.0.1:8000/add_team/" rel="nofollow noreferrer">http://127.0.0.1:8000/add_team/</a> Django Version: 2.1.1 Exception Type: TypeError Exception Value: 'dict' object is not callable Exception Location: C:\Users\Acer\Desktop\teammanager\teams\views.py in post, line 52 Python Executable: C:\Users\Acer\Desktop\teammanager_env\Scripts\python.exe Python Version: 3.7.0</p> </blockquote>
<p>The <code>form.cleaned_data</code> is a dictionary, so you obtain elements by subscripting, or by using the <code>.get(..)</code> method (to return <code>None</code> or a default value in case the key is missing), so you should rewrite:</p> <pre><code>team.name = form.cleaned_data('name') team.details = form.cleaned_data('detials')</code></pre> <p>to:</p> <pre><code>team.name = form.cleaned_data<b>['name']</b> team.details = form.cleaned_data<b>['details']</b> # typo: detials -&gt; details</code></pre> <p>That being said, it is probably better to make a <code>ModelForm</code>:</p> <pre><code>class TeamForm(<b>forms.ModelForm</b>): name = forms.CharField(label='name of team') details = forms.CharField(label='details of team')</code></pre> <p>then the view looks like:</p> <pre><code>class AddTeamView(View): template_name = 'add_team.html' def get (self, request): form = TeamForm() context = {'form': form} return render(request, 'add_team.html', context) def post(self, request): form = TeamForm(request.POST) if form.is_valid(): team = <b>form.save()</b> context = {'form': form, 'name':team.name,'details':team.details} return render(request, self.template_name, context)</code></pre> <p>You should also consider using a <code>CreateView</code>, instead of a simple view, and redirect when a <code>post(..)</code> is done successful, since rendering in case of a POST, can result in errors when the user refreshes the page (see <a href="https://en.wikipedia.org/wiki/Post/Redirect/Get" rel="nofollow noreferrer">this Wikipedia article</a> for the POST-REDIRECT-GET pattern).</p>
python|django
2
756
37,144,260
after4 - Simple python task (index and list issues)
<p>this is my first time asking a question on stack overflow. It has been really valuable to me while I have been learning python 2.7</p> <p>The question is as follows: <p>"Given a non-empty list numlist of ints, write a function after4(numlist) that returns a new list containing the elements from the original numlist that come after the last 4 in the original numlist. The numlist will contain at least one 4. </p> <pre><code>after4([2, 4, 1, 2]) → [1, 2] after4([4, 1, 4, 2]) → [2] after4([4, 4, 1, 2, 3]) → [1, 2, 3]" </code></pre> <p>I believed the question to be rather simple but I just can seem to get the code right for what I had planned in my head.</p> <pre><code> def after4(numlist): """ Given a list of numbers, will print all numbers after the last 4 :param x: list - list of numbers including the 4 :return: list - New list of all numbers after the last 4 """ indices = [i for i, x in enumerate(numlist) if x == 4] index = max(indices) print x[index:] </code></pre> <p>But I keep getting this error and I'm not sure how to work around it. 'int' object has no attribute 'getitem'" (the error is on the final line of the code "print x[index:]")</p> <p>Thank you in advance.</p>
<p>You use the name <code>x</code> for two different purposes: as the list parameter for the function <code>after4()</code> and as an integer in the list comprehension for the variable <code>indices</code>.</p> <p>The interpreter thinks you mean the integer one in the last line, but you mean the list parameter one. Change one of those names to a different name and see what happens.</p> <p>You should use more descriptive variable names from now on. For example, instead of using <code>x</code> for the list parameter, use something like number_list, which makes it clear just what it is. Keep short names like <code>x</code> for mathematical parameters (such as math.sin(x)) and for list comprehensions.</p>
python
1
757
37,169,602
(1) Running a .py in cmd and (2) with variable in same line
<p><strong>I figured out the zip code in same line out. It's sys.argv[1], I had other code I neglected to comment out when trying out [1] that gave me the error. All I need help with now is getting weather.py to run without having to call the whole file path.</strong></p> <p>I will preface with I'm not very experienced with python and may get certain names wrong or think something might work that obviously doesn't, bear with me I tried to word this to make as much sense as possible.</p> <p>So I need to run a program using the command line. The program is complete and 100% functioning when ran in PyDev. The program is called weather.py, and what needs to trigger it in cmd is </p> <blockquote> <p>python weather.py (5 digit zip)</p> </blockquote> <p>I cannot get the program to run using just 'python weather.py' first off. I have added C:\python27 to PATH as well as C:\python27\python.exe (not sure if that does anything). Getting the .py to run via those two keywords doesn't seem to work with what I've tried. I also need to be able to add a zip code to the same line to trigger the program. I was told about </p> <blockquote> <p>zipcode = sys.argv[0]</p> </blockquote> <p>to allow the zip code to be automatically initialized as a variable, but I get </p> <blockquote> <p>IndexError: list index out of range</p> </blockquote> <p>when I run the program using </p> <blockquote> <p>python C:\python27\weather.py</p> </blockquote> <p>I tried replacing 0 with 1 or 2 because I'm unfamiliar with .argv but neither of those worked either. Any help getting the program to run using just python weather.py OR getting the zip code input to function on the same line is greatly appreciated.</p>
<p>Make sure you <code>import sys</code> in your code.</p> <pre><code>import sys zipCode = sys.argv[1] </code></pre> <p>and actually provide an argument</p> <p>EDIT:</p> <p>For clarity, if sys was not imported, you would get <code>NameError</code> and not an <code>IndexError</code>. Additionally, when passing args in from the command line, the indexing actually begins at 0 where <code>sys.argv[0]</code> is always the program name and the provided args begin at 1. So, in this case, the zip code would be at <code>sys.argv[1]</code></p> <p>EDIT2:</p> <p>variable name to avoid using reserve words :)</p>
python|python-2.7
4
758
66,093,871
Python, range(), double loops,
<p>Codes and result are shown below.</p> <p>I'm curious about the prints beginning wiht 1 instead of 0 as start. Where does the program get 1 from?</p> <p>Can someone please help me here? Thanks!</p> <pre><code>for i in range(5) : for j in range(i) : print(i, end=&quot; &quot;) print() </code></pre> <p>1 <br> 2 2 <br> 3 3 3 <br> 4 4 4 4</p> <p>The same result with codes below:</p> <pre><code>for i in range(5) : for j in range(0, i) : print(i, end=&quot; &quot;) print() </code></pre> <p>By altering (0, i) to (1, i), it's also logically omitted 1, but how does it come to a single 2 as the result shown below?</p> <pre><code>for i in range(5) : for j in range(1, i) : print(i, end=&quot; &quot;) print() </code></pre> <p>2 <br> 3 3 <br> 4 4 4 <br></p>
<p>Because <code>for j in range(0):</code> loops 0 times, so it never prints <code>i</code> when its 0. If you look closely at your output, you'll see that the first line is actually blank.</p>
python|range
2
759
39,687,484
python error in decoding base64 string
<p>I'm trying to unzip a base64 string,</p> <p>this is the code I'm using</p> <pre><code>def unzip_string(s) : s1 = base64.decodestring(urllib.unquote(s)) sio = StringIO.StringIO(s1) gzf = gzip.GzipFile(fileobj=sio) guff = gzf.read() return json.loads(guff) </code></pre> <p>i'm getting error Error: Incorrect padding</p> <p>where I try to unzip the same string using node.js code it works without a problem.</p> <p>where:</p> <pre><code>s == H4sIAAAAAAAAA22PW0/CQBCF/8s81wQosdA3TESJhhhb9cHwMN1O6Ybtbt0LhDT97+5yU4yPc+bMnO90YCyyDaSfHRimieQSG4IUaldABC1qbAykHbQsrzWZWokSUumEiMCQ3nJGCy9ADH0EFvWarJ+eHv11v4qgEIptqHyTlovzWes0q9HQ3X87Lh80Msp5gDhqzGlN0or9B1pWU5ldxV72c2/ODg0C7lUXu/U2p8XLpY35+6Mmtsn4WqLILFrnTRUKQxFwk7+fSL23+zX215VD/jE16CeojIzhSi5kpQ6xzVkIz76wuSmHRVINRuVtheMxDuLJJB5Nk5hRMkriaTGJh8MDn5LWv8v3bejzvFjez15/5EsNbuZo7FzpHepyJoTaBWqrHfX9N0/UAJ7qAQAA.bi0I1YDZ3V6AXu6aYTGO1JWi5tE5CoZli7aa6bFtqM4 </code></pre> <p>I've seen some suggestions to add '=' and other magic but it just results in the gzip module failing to open the file.</p> <p>any ideas?</p>
<p>This worked for me (Python 3). The padding is indeed important, as you've seen in other answers:</p> <pre><code>import base64 import zlib import json s = b'H4sIAAAAAAAAA22PW0/CQBCF/8s81wQosdA3TESJhhhb9cHwMN1O6Ybtbt0LhDT97+5yU4yPc+bMnO90YCyyDaSfHRimieQSG4IUaldABC1qbAykHbQsrzWZWokSUumEiMCQ3nJGCy9ADH0EFvWarJ+eHv11v4qgEIptqHyTlovzWes0q9HQ3X87Lh80Msp5gDhqzGlN0or9B1pWU5ldxV72c2/ODg0C7lUXu/U2p8XLpY35+6Mmtsn4WqLILFrnTRUKQxFwk7+fSL23+zX215VD/jE16CeojIzhSi5kpQ6xzVkIz76wuSmHRVINRuVtheMxDuLJJB5Nk5hRMkriaTGJh8MDn5LWv8v3bejzvFjez15/5EsNbuZo7FzpHepyJoTaBWqrHfX9N0/UAJ7qAQAA.bi0I1YDZ3V6AXu6aYTGO1JWi5tE5CoZli7aa6bFtqM4' decoded = base64.urlsafe_b64decode(s + b'=') uncompressed = zlib.decompress(decoded, 16 + zlib.MAX_WBITS) unjsoned = json.loads(uncompressed.decode('utf-8')) print(unjsoned) </code></pre> <p>The <code>zlib.decompress(decoded, 16 + zlib.MAX_WBITS)</code> is a slightly more compact way to un-gzip a byte string.</p>
python|base64|gzip
0
760
39,649,551
Python 3 Sockets - Receiving more then 1 character
<p>So when I open up the CMD and create a telnet connection with:</p> <p>telnet localhost 5555</p> <p>It will apear a "Welcome", as you can see on the screen below. After that every single character I type into the CMD will be printed out/send immediately. My Question is: Is it, and if yes, how is it possible to type in messages and then send them so I receive them as 1 sentence and not char by char. <a href="https://i.stack.imgur.com/kexib.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kexib.png" alt="enter image description here"></a></p> <pre><code>import socket import sys from _thread import * host = "" port = 5555 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.bind((host,port)) except socket.error as e: print(str(e)) s.listen(5) #Enable a server to accept connections. print("Waiting for a connection...") def threaded_client(conn): conn.send(str.encode("Welcome\n")) while True: # for m in range (0,20): #Disconnects after x chars data = conn.recv(2048) #Receive data from the socket. reply = "Server output: "+ data.decode("utf-8") print(data) if not data: break conn.sendall(str.encode(reply)) conn.close() while True: conn, addr = s.accept() print("connected to: "+addr[0]+":"+str(addr[1])) start_new_thread(threaded_client,(conn,)) </code></pre>
<p>You need to keep reading until the stream ends:</p> <pre><code>string = "" while True: # for m in range (0,20): #Disconnects after x chars data = conn.recv(1) #Receive data from the socket. if not data: reply = "Server output: "+ string conn.sendall(str.encode(reply)) break else: string += data.decode("utf-8") conn.close() </code></pre> <p>By the way, using that method you'll read one char at a time. You may adapt it to the way your server is sending the data.</p>
python|sockets|python-3.x
2
761
39,444,591
Set handler for GPIO state change using python signal module
<p>I want to detect change in <code>gpio</code> input of raspberry pi and set handler using signal module of python. I am new to signal module and I can't understand how to use it. I am using this code now:</p> <pre><code>import RPi.GPIO as GPIO import time from datetime import datetime import picamera i=0 j=0 camera= picamera.PiCamera() camera.resolution = (640, 480) # handle the button event def buttonEventHandler (pin): global j j+=1 #camera.close() print "handling button event" print("pressed",str(datetime.now())) time.sleep(4) camera.capture( 'clicked%02d.jpg' %j ) #camera.close() def main(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(2,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(2,GPIO.FALLING) GPIO.add_event_callback(2,buttonEventHandler) # RPIO.add_interrupt_callback(2,buttonEventHandler,falling,RPIO.PUD_UP,False,None) while True: global i print "Hello world! {0}".format(i) i=i+1 time.sleep(5) # if(GPIO.input(2)==GPIO.LOW): # GPIO.cleanup() if __name__=="__main__": main() </code></pre>
<p>I just changed code in a different manner tough you are free to implement same using SIGNAL module.You can start new thread and poll or register call back event their, by using following code and write whatever your functional logic in it's run() method.</p> <pre><code>import threading import RPi.GPIO as GPIO import time import time from datetime import datetime import picamera i=0 j=0 camera= picamera.PiCamera() camera.resolution = (640, 480) PIN = 2 class GPIOThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): while True: if GPIO.input(PIN) == False: # adjust this statement as per your pin status i.e HIGH/LOW global j j+=1 #camera.close() print "handling button event" print("pressed",str(datetime.now())) time.sleep(4) camera.capture( 'clicked%02d.jpg' %j ) def main(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(PIN,GPIO.IN,pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(PIN,GPIO.FALLING) gpio_thread = GPIOThread() gpio_thread.start() while True: global i print "Hello world! {0}".format(i) i=i+1 time.sleep(5) if __name__=="__main__": main() </code></pre> <p>The above code will iterate until PIN input goes high, so once PIN goes high the condition in while loop inside run method breaks and picture is captured.</p> <p>So, in order to call above thread do this.</p> <pre><code>gpio_thread = GPIOThread() gpio_thread.start() </code></pre> <p>this will call the thread constructor <strong>init</strong> and will initialize the variable inside constructor if any, and execute the run method.</p> <p>You can also call join() method , to wait until thread completes it's execution.</p> <pre><code>gpio_thread.join() </code></pre> <p>This always works for me, so Cheers!!</p>
python|raspberry-pi|interrupt|gpio|django-signals
0
762
10,030,042
rpy + matplotlib + arcpy
<p>I am trying to use ryp with my arcpy scripts but I have the following error:</p> <pre><code>import rpy2.robjects as robjects Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import rpy2.robjects as robjects File "C:\Python26\ArcGIS10.0\lib\site-packages\rpy2\robjects\__init__.py", line 12, in &lt;module&gt; import rpy2.rinterface as rinterface File "C:\Python26\ArcGIS10.0\lib\site-packages\rpy2\rinterface\__init__.py", line 39, in &lt;module&gt; import win32api ImportError: No module named win32api </code></pre> <p>This error comes even after the installation of the pywin32 for my version of python. I've noticed that this seems to be a common error that is usually solved with the installation of pywin32.</p> <p>I also have a problem with the matplotlib installation, every time i try to use it (<strong>import matplotlib.pyplot as plt</strong>), python crashes...</p> <p><strong>Versions:</strong></p> <p>Python 2.6.6</p> <p>matplotlib installation: matplotlib-1.1.0.win32-py2.6.exe</p>
<p>You will need to run these scripts with PROPER Python. It seems to me that the ArcPy distribution does not include the win32api module (It also does not exist from example in Python on Mac or Linux). </p> <p>I would install <a href="http://code.google.com/p/pythonxy/" rel="nofollow">PythonXY</a> which includes R bindings, and see if your scripts run there. If they run there, then I (guess) I am correct, and ArcPy does not include these modules. </p> <p>A nice BONUS of PythonXY is it's an excellent Python IDE (Spyder), but the real bonus is what the commenter above me said: </p> <blockquote> <p>different compiler versions can cause hell of a lot of Problems.</p> </blockquote> <p>So, in PythonXY you get a whole bundle compiled with the same compiler.<br> Let us know if these made your RPy script run. </p>
python|matplotlib|rpy2|arcpy
2
763
1,380,860
Add Variables to Tuple
<p>I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB. </p> <p><strong>What I am Doing</strong>: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?</p> <p>Also if there is an efficient way of doing this, please share...</p> <p><strong>EDIT</strong> Let me edit this question a bit...I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don't need the tuple anymore.</p>
<p>Tuples are immutable; you can't change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:</p> <pre><code>a = (1, 2, 3) b = a + (4, 5, 6) # (1, 2, 3, 4, 5, 6) c = b[1:] # (2, 3, 4, 5, 6) </code></pre> <p>And, of course, build them from existing values:</p> <pre><code>name = "Joe" age = 40 location = "New York" joe = (name, age, location) </code></pre>
python|tuples
483
764
63,169,446
How to increment a string in python
<p>I was trying this code:</p> <pre><code>str = input(&quot;Enter the string:&quot;) num = input(&quot;By how much you want to increment:&quot;) x = int(str) + num print(char(num)) </code></pre> <p>but this throws a traceback, What will be the correct code and what if the person enters (z + 1) i.e. how will the code be fixed around only the 26 alphabets. Thank you</p>
<p>You can use <code>ord</code> to get ascii of them and <code>chr</code> to get back the value using ascii value</p> <pre><code>def inc_letter(char, inc): start_char = ord('a') if char.islower() else ord('A') start = ord(char) - start_char offset = ((start + inc) % 26) + start_char result = chr(offset) return result </code></pre> <hr /> <pre><code>str_ = input(&quot;Enter the string:&quot;) num = int(input(&quot;By how much you want to increment:&quot;)) inc_letter(str_, num) </code></pre> <hr /> <p><strong>Result:</strong></p> <pre><code>Enter the string:Z By how much you want to increment:12 'L' </code></pre>
python|string
0
765
28,371,990
IO error in savetxt while using numpy
<p>Im trying to read a dataset and collect meta features from it. I get the following error after executing the python file.</p> <pre><code>Traceback (most recent call last): File "runmeta.py", line 79, in &lt;module&gt; np.savetxt('datasets/'+str(i)+'/metafeatures',meta[i],delimiter=',') File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 940, in savetxt fh = open(fname, 'w') IOError: [Errno 2] No such file or directory: 'datasets/2/metafeatures' </code></pre>
<p>the error you're getting is simply telling you it didn't find the file. i would suggest looking into absolute and relative file paths. </p> <p>advice in error handling: the error is triggered on this line</p> <pre><code>fh = open(fname, 'w') </code></pre> <p>so as you debug your program, look at the line python shows you. maybe change the variable fname. that is where i would start. currently</p> <pre><code>fname = 'datasets/2/metafeatures' </code></pre>
python|numpy
1
766
14,333,098
Why this SQL does not work in python
<pre><code>cur.execute("SELECT * FROM `productinfo` WHERE CreateDate &gt; '%s'",kakko) </code></pre> <p>where <code>kakko</code> is user input string, for example, 2012-01-15</p> <p>'%s' is not correct?</p>
<p>So, elaborating from the comments:</p> <p><code>cursor.execute</code> requires a parameter tuple, and you don't need to quote the <code>%s</code>:</p> <pre><code>cur.execute("SELECT * FROM `productinfo` WHERE CreateDate &gt; %s", (kakko, )) </code></pre>
python|mysql|mysql-python
1
767
34,766,044
how to verify connection is reused with python requests.session?
<p>I'd like to use requests 's session to reuse connections in django. </p> <p><a href="https://stackoverflow.com/questions/30748200/reusing-connections-in-django-with-python-requests">Reusing connections in Django with Python Requests</a> </p> <p>says I only need to declare it in global and access it.<br> However I doubt it is working as expected because it didn't get any faster in my test.</p> <p>Is there a way to see if connection is actually reused as described here?</p> <p><a href="http://docs.python-requests.org/en/latest/user/advanced/" rel="nofollow noreferrer">http://docs.python-requests.org/en/latest/user/advanced/</a></p> <p>Django spawns separate thread for each requests and I think it defeats the mechanism to share the connection. (because session won't be shared across multiple threads) .. this is my hypothesis..</p>
<p>You can try increasing your logging verbosity, then look out for logs that look like:</p> <p><em><code>&quot;Starting new HTTPS connection (1): some.url:port&quot;</code></em></p> <p>This is how to make global logging more verbose:</p> <pre><code>import logging logging.basicConfig(level=logging.DEBUG, format=&quot;%(message)s&quot;) </code></pre> <p>If the connection is being reused, you will only see one of those messages for any given url. If it is not being reused, you will see a different one each time a connection is established to the same url.</p>
python|django|python-requests|connection-pooling
0
768
23,142,251
Is there a way to remove all characters except letters in a string in Python?
<p>I call a function that returns code with all kinds of characters ranging from ( to ", and , and numbers.</p> <p>Is there an elegant way to remove all of these so I end up with nothing but letters?</p>
<p>Given</p> <pre><code>s = '@#24A-09=wes()&amp;8973o**_##me' # contains letters 'Awesome' </code></pre> <p>You can filter out non-alpha characters with a generator expression:</p> <pre><code>result = ''.join(c for c in s if c.isalpha()) </code></pre> <p>Or filter with <code>filter</code>:</p> <pre><code>result = ''.join(filter(str.isalpha, s)) </code></pre> <p>Or you can substitute non-alpha with blanks using <code>re.sub</code>:</p> <pre><code>import re result = re.sub(r'[^A-Za-z]', '', s) </code></pre>
python|regex|string|parsing
27
769
7,878,064
how to check if two strings have intersection in python?
<p>For example, a = "abcdefg", b = "krtol", they have no intersection, c = "hflsfjg", then a and c have intersaction.<br> What's the easiest way to check this? just need a True or False result</p>
<pre><code>def hasIntersection(a, b): return not set(a).isdisjoint(b) </code></pre>
python
11
770
7,852,249
Why am i getting error
<p>The error:</p> <pre><code>Error Traceback (most recent call last): File "/home/enrique/Dropbox/Public/pygametut3.py", line 41, in &lt;module&gt; pix = MovingPixel(width/2, height/2) TypeError: this constructor takes no arguments </code></pre> <p>The Code:</p> <pre><code>#Creat a moving pixel pix = MovingPixel(width/2, height/2) while running: pix.move() if pix.x &lt;= 0 or pix.x &gt;= width or pix.y &lt;= 0 or pix.y &gt;= height: print "Crash" running = False </code></pre>
<p>Because <code>MovingPixel</code> needs to be instantiated with no arguments:</p> <pre><code>pix = MovingPixel() </code></pre>
python|pygame
1
771
1,173,767
using pyunit on a network thread
<p>I am tasked with writing unit tests for a suite of networked software written in python. Writing units for message builders and other static methods is very simple, but I've hit a wall when it comes to writing a tests for network looped threads.</p> <p>For example: The server it connects to could be on any port, and I want to be able to test the ability to connect to numerous ports (in sequence, not parallel) without actually having to run numerous servers. What is a good way to approach this? Perhaps make server construction and destruction part of the test? Something tells me there must a simpler answer that evades me.</p> <p>I have to imagine there are methods for unit testing networked threads, but I can't seem to find any.</p>
<p>I would try to introduce a factory into your existing code that purports to create socket objects. Then in a test pass in a mock factory which creates mock sockets which just pretend they've connected to a server (or not for error cases, which you also want to test, don't you?) and log the message traffic to prove that your code has used the right ports to connect to the right types of servers.</p> <p>Try not to use threads just yet, to simplify testing.</p>
python|unit-testing|networking|python-unittest
1
772
564,469
What is a good & free game engine?
<p>For C++, Java, or Python, what are some good game + free game engines that are easy to pick up?</p> <p>Any type of game engine is okay. I just want to get started somewhere by looking into different game engines and their capabilities.</p>
<p>For my Computer Graphics course in College we used the open source <a href="http://www.ogre3d.org/" rel="noreferrer">OGRE 3D</a> engine. Not only is this an extremely robust 3D engine but it was a blast! </p> <p>Develop a medium sized game using it and you will get a good taste of many of the different <a href="http://en.wikipedia.org/wiki/Game_programmer" rel="noreferrer">game programming specialties</a>. You'll find yourself doing 3d modeling, sound effects, physics programming, AI, the works. </p> <p><a href="http://www.mactabilisarts.com/Images/multiplayer%20games.jpg" rel="noreferrer">alt text http://www.mactabilisarts.com/Images/multiplayer%20games.jpg</a><br> <em>Screenshot of a recent OGRE 3D Game</em></p>
java|c++|python
17
773
41,965,202
Tensorflow: how to assign variables properly
<p>It's not duplicate of <a href="https://stackoverflow.com/questions/34220532/how-to-assign-value-to-a-tensorflow-variable">How to assign value to a tensorflow variable?</a></p> <p>I was trying to do simpliest thing: just swap variables <a href="https://stackoverflow.com/questions/41949633/tensorflow-how-to-swap-variables-between-scopes-and-set-variables-in-scope-from">Tensorflow: how to swap variables between scopes and set variables in scope from another</a>, and I still can't do it.</p> <p>BUT now I know that <code>assign</code> changes even copy of tensor which I get with <code>tf.identity</code>. I don't want this. I need copy of variable for swapping. </p> <pre><code>In [10]: a = tf.Variable(1) In [11]: b = tf.identity(a) In [12]: a += 1 In [14]: sess.run(a) Out[14]: 2 In [15]: sess.run(b) Out[15]: 1 In [16]: a = tf.Variable(1) In [17]: b = tf.identity(a) In [18]: assign_t = a.assign(2) In [20]: sess.run(tf.initialize_all_variables()) In [21]: sess.run(a) Out[21]: 1 In [22]: sess.run(assign_t) Out[22]: 2 In [23]: sess.run(a) Out[23]: 2 In [24]: sess.run(b) Out[24]: 2 </code></pre> <p>How can I assign value to <code>a</code> without changing <code>b</code>?</p>
<p>The <a href="https://www.tensorflow.org/api_docs/python/control_flow_ops/control_flow_operations#identity" rel="nofollow noreferrer"><code>tf.identity()</code></a> operation is stateless. When you have a <code>tf.Variable</code> called <code>a</code>, the value of <code>tf.identity(a)</code> will always be the same as the value of <code>a</code>. If you want <code>b</code> to remember a previous value of <code>a</code>, you should create <code>b</code> as a <code>tf.Variable</code> as well:</p> <pre><code>a = tf.Variable(1) b = tf.Variable(a.initialized_value()) sess.run(tf.global_variables_initializer()) # Initially, variables `a` and `b` have the same value. print(sess.run([a, b])) ==&gt; [1, 1] # Update the value of `a` to 2. assign_op = a.assign(2) sess.run(assign_op) # Now, `a` and `b` have different values. print(sess.run([a, b])) ==&gt; [2, 1] </code></pre>
variables|tensorflow
1
774
11,627,362
How to straighten a rotated rectangle area of an image using OpenCV in Python?
<p>The following picture will tell you what I want.</p> <p>I have the information of the rectangles in the image (width, height, center point and rotation degree). Now, I want to write a script to cut them out and save them as an image, but straighten them as well. As in, I want to go from the rectangle shown inside the image to the rectangle that is shown outside.</p> <p>I am using OpenCV Python. <strong>Please</strong> tell me a way to accomplish this.</p> <p><strong>Kindly</strong> show some code as examples of OpenCV Python are hard to find.</p> <p><img src="https://i.stack.imgur.com/6Xinc.jpg" alt="Example Image"></p>
<p>You can use the <a href="https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.html#rotation" rel="noreferrer"><code>warpAffine</code></a> function to rotate the image around a defined center point. The suitable rotation matrix can be generated using <a href="https://docs.opencv.org/3.4.0/da/d54/group__imgproc__transform.html#gafbbc470ce83812914a70abfb604f4326" rel="noreferrer"><code>getRotationMatrix2D</code></a> (where <code>theta</code> is in <em>degrees</em>).</p> <p><img src="https://i.stack.imgur.com/Zu4Y2.jpg" alt="Start Image"> <img src="https://i.stack.imgur.com/xw4jh.jpg" alt="After finding the desired rectangle"></p> <p>You then can use <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="noreferrer">Numpy slicing</a> to cut the image.</p> <p><a href="https://i.stack.imgur.com/6oB6V.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6oB6V.jpg" alt="Rotated Image"></a> <img src="https://i.stack.imgur.com/fs9T5.jpg" alt="Result"></p> <pre><code>import cv2 import numpy as np def subimage(image, center, theta, width, height): ''' Rotates OpenCV image around center with angle theta (in deg) then crops the image according to width and height. ''' # Uncomment for theta in radians #theta *= 180/np.pi shape = ( image.shape[1], image.shape[0] ) # cv2.warpAffine expects shape in (length, height) matrix = cv2.getRotationMatrix2D( center=center, angle=theta, scale=1 ) image = cv2.warpAffine( src=image, M=matrix, dsize=shape ) x = int( center[0] - width/2 ) y = int( center[1] - height/2 ) image = image[ y:y+height, x:x+width ] return image </code></pre> <p>Keep in mind that <code>dsize</code> is the shape of the <em>output</em> image. If the patch/angle is sufficiently large, edges get cut off (compare image above) if using the original shape as--for means of simplicity--done above. In this case, you could introduce a scaling factor to <code>shape</code> (to enlarge the output image) and the reference point for slicing (here <code>center</code>).</p> <p>The above function can be used as follows:</p> <pre><code>image = cv2.imread('owl.jpg') image = subimage(image, center=(110, 125), theta=30, width=100, height=200) cv2.imwrite('patch.jpg', image) </code></pre>
python|image-processing|opencv
64
775
33,946,338
Python + selenium: extract variable quantity of paragraphs between titles
<p>Fellows, assuming the html below how can extract the paragraphs <code>&lt;p&gt;</code> who belongs to the tile <code>&lt;h3&gt;</code>.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; ... &lt;div class=&quot;main-div&quot;&gt; &lt;h3&gt;Title 1&lt;/h3&gt; &lt;p&gt;&lt;/p&gt; &lt;h3&gt;Title 2&lt;/h3&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;h3&gt;Title 3&lt;/h3&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; ... &lt;/div&gt; &lt;/body&gt; </code></pre> <p>As you can see both <code>&lt;h3&gt;</code> and <code>&lt;p&gt;</code> tags are children of the <code>&lt;div&gt;</code> tag <strong>but they have no class or id</strong> that makes possible to identify them and say that &quot;Title 1&quot; has 1 paragraph, title 2 has 3 paragraphs, title 3 has two paragraphs and so on. I can't see a way to tie the paragraph to the title...</p> <p><strong>I'm trying to do it using Python 2.7 + selenium</strong>. But I'm not sure that I'm working with the right tools, maybe you can suggest the solution or any different combinations like Beautifulsoup, urllib2...</p> <p>Any suggestion/direction will be very appreciated!</p> <hr /> <h1>UPDATE</h1> <p>After the brilliant solution pointed by @JustMe I came up with the solution below, hope it helps someone else or if someone can improve it to pythonic. I coming from c/c++/java/perl world so always I hit the wall :)</p> <pre><code>import bs4 page = &quot;&quot;&quot; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; ... &lt;div class=&quot;maincontent-block&quot;&gt; &lt;h3&gt;Title 1&lt;/h3&gt; &lt;p&gt;1&lt;/p&gt; &lt;p&gt;2&lt;/p&gt; &lt;p&gt;3&lt;/p&gt; &lt;h3&gt;Title 2&lt;/h3&gt; &lt;p&gt;2&lt;/p&gt; &lt;p&gt;3&lt;/p&gt; &lt;p&gt;4&lt;/p&gt; &lt;h3&gt;Title 3&lt;/h3&gt; &lt;p&gt;7&lt;/p&gt; &lt;p&gt;9&lt;/p&gt; ... &lt;/div&gt; &lt;/body&gt; &quot;&quot;&quot; page = bs4.BeautifulSoup(page, &quot;html.parser&quot;) div = page.find('div', {'class':&quot;maincontent-block&quot;}) mydict = {} # write to the dictionary for tag in div.findChildren(): if (tag.name == &quot;h3&quot;): #print(tag.string) mydict[tag.string] = None nextTags = tag.findAllNext() arr = []; for nt in nextTags: if (nt.name == &quot;p&quot;): arr.append(nt.string) mydict[tag.string] = arr elif (nt.name == &quot;h3&quot;): arr = [] break # read from dictionary arrKeys = [] for k in mydict: arrKeys.append(k) arrKeys.sort() for k in arrKeys: print k for v in mydict[k]: print v </code></pre>
<p>It's easy to be done using BeautifulSoup</p> <pre><code>import bs4 page = """ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; ... &lt;div class="main-div"&gt; &lt;h3&gt;Title 1&lt;/h3&gt; &lt;p&gt;&lt;/p&gt; &lt;h3&gt;Title 2&lt;/h3&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;h3&gt;Title 3&lt;/h3&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; ... &lt;/div&gt; &lt;/body&gt; """ page = bs4.BeautifulSoup(page) h3_tag = page.div.find("h3").string print(h3_tag) &gt;&gt;&gt; u'Title 1' h3_tag.find_next_siblings("p") &gt;&gt;&gt; [&lt;p&gt;&lt;/p&gt;, &lt;p&gt;&lt;/p&gt;, &lt;p&gt;&lt;/p&gt;, &lt;p&gt;&lt;/p&gt;, &lt;p&gt;&lt;/p&gt;, &lt;p&gt;&lt;/p&gt;] len(h3_tag.find_next_siblings("p"))/2 &gt;&gt;&gt; 3 </code></pre> <p>Ok, since You want separated count of paragraphs i came up with this, crude thing.</p> <pre><code> h_counters = [] count = -1 for child in page.div.findChildren(): if "&lt;h3&gt;" in str(child): h_counters.append(count) count = 0 else: count += 1 h_counters.append(count) h_counters = h_counters[1:] print (h_counters) &gt;&gt; [1, 3, 2] </code></pre>
python|html|selenium|beautifulsoup|urllib2
0
776
46,842,321
How to print the sum value of gradient in tensorflow?
<pre><code>self.logits = nn_layers.full_connect_(self.wide_deep_embed, config.num_classes, activation='None', use_bn = True, \ keep_prob=self.keep_prob, name='output_layer') # predict prob ## loss and optim #self.loss = nn_layers.cross_entropy_loss_with_reg(self.labels, self.logits) self.loss = tf.losses.mean_squared_error(self.labels, self.logits) tf.summary.scalar('loss', self.loss) if not opt: optim = nn_layers.get_optimizer(config.optimizer, learning_rate=self.learning_rate) else: optim = opt self.train_op = optim.minimize(self.loss, global_step=self.global_step) ## score &amp; infers self.infers = self.logits # predict label </code></pre> <p>Here is a part of my model which is a DNN to do a regression task. But I find that the model's loss did not change to much after several batches (batch size is 1000 and the whole data is 11 million). So I want to print the value of sum gradient in every step, which is the sum of gradients in every batches. How can I modify my code to do it? </p>
<p>Here's how you can add the gradients to <a href="https://www.tensorflow.org/get_started/summaries_and_tensorboard" rel="nofollow noreferrer">tensorboard summary</a> on each step:</p> <pre><code># All gradients of loss function wrt trainable variables grads = tf.gradients(self.loss, tf.trainable_variables()) # Summarize all gradients for grad, var in list(zip(grads, tf.trainable_variables())): tf.summary.histogram(var.name + '/gradient', grad) </code></pre> <p>If the gradients are too big, you can report the sum as well:</p> <pre><code>for grad, var in list(zip(grads, tf.trainable_variables())): tf.summary.histogram(var.name + '/gradient_sum', tf.reduce_sum(grad)) </code></pre> <p>But usually you can detect vanishing gradients without taking a sum: just take a look at the gradients at the early layers of your network.</p>
python|machine-learning|tensorflow|neural-network|deep-learning
0
777
46,821,548
tensorflow object detection eval error
<p>When I use a model to check the mAP on test datasets, I got the following error:</p> <pre><code>INFO:tensorflow:Restoring parameters from /home/aurora/workspaces/PycharmProjects/tensorflow/tensorflow_object_detection/outputs/model.ckpt-278075 INFO:tensorflow:Restoring parameters from /home/aurora/workspaces/PycharmProjects/tensorflow/tensorflow_object_detection/outputs/model.ckpt-278075 WARNING:root:The following classes have no ground truth examples: 0 /home/aurora/workspaces/PycharmProjects/tensorflow/tensorflow_object_detection/object_detection/utils/metrics.py:145: RuntimeWarning: invalid value encountered in true_divide num_images_correctly_detected_per_class / num_gt_imgs_per_class) </code></pre> <p>I examined test.tfrecords, and every image have ground-truth bounding-boxes. How could I solve this problem? Thanks.</p>
<p>I got a similar error and I was stuck for many days on that error. I could resolve that error by editing my label.pbtxt file. Could you show your label(.pbtxt) file? My label file was :(containing 3 labels)</p> <pre><code>item { id: 1 name: 'tree' id: 2 name: 'water body' id: 3 name: 'building' } </code></pre> <p>Then I changed that to :</p> <pre><code>item { id: 1 name: 'tree' } item { id: 2 name: 'water body' } item { id: 3 name: 'building' } </code></pre> <p>This worked in my case. Have a look at your .pbtxt file which you reference to in the config file of your model.</p>
tensorflow|object-detection|object-detection-api
0
778
37,946,663
Incrementing IntegerField counter in a database
<p>As beginner at Django, i tried to make a simple application that would give Http response of how many times content was viewed. I have created a new <code>Counter</code> model, and inside, added IntegerField model <code>count</code>.</p> <pre><code>class Counter(models.Model): count = models.IntegerField(default=0) def __int__(self): return count </code></pre> <p>In views, i made a variable <code>counter</code> out of <code>Counter()</code> class, and tried adding +1 to <code>counter.count</code> integer, but when i tried to save, it would give me an error that integer couldn't be saved.</p> <p>so i tried saving class instead:</p> <pre><code>def IndexView(response): counter = Counter() counter.count = counter.count + 1 counter.save() return HttpResponse(counter.count) </code></pre> <p>This method, would keep showing <code>1</code> and could not change after reload.</p> <hr> <p>How would i change <code>IntegerField</code> model properly, so it could be updated after every view, and would be saved even if server was reloaded?</p>
<h2>The problem</h2> <p>Yes but you are creating a new <code>Counter</code> object on each request, which starts again at 0, that's your problem</p> <pre><code>def IndexView(response): counter = Counter() # This creates a new counter each time counter.count = counter.count + 1 counter.save() return HttpResponse(counter.count) </code></pre> <p>What you were doing above would result in a bunch of Counter objects with <code>count = 1</code> in the database.</p> <h2>The Solution</h2> <p>My example below shows you how to get an existing Counter object, and increment it, or create it if it doesn't already exist, with <code>get_or_create()</code></p> <p>First we need to associate a Counter to e.g. a page (or anything, but we need someway to identify it and grab it from the DB)</p> <pre><code>class Counter(models.Model): count = models.IntegerField(default=0) page = models.IntegerField() # or any other way to identify # what this counter belongs to </code></pre> <p>then:</p> <pre><code>def IndexView(response): # Get an existing page counter, or create one if not found (first page hit) # Example below is for page 1 counter, created = Counter.objects.get_or_create(page=1) counter.count = counter.count + 1 counter.save() return HttpResponse(counter.count) </code></pre> <h2>Avoid race conditions that can happen with <code>count = count + 1</code></h2> <p>And to avoid race conditions use an <a href="https://docs.djangoproject.com/en/1.9/ref/models/expressions/#django.db.models.F" rel="nofollow">F expression</a></p> <pre><code># When you have many requests coming in, # this may have outdated value of counter.count: # counter.count = counter.count + 1 # Using an F expression makes the +1 happen on the database from django.db.models import F counter.count = F('count') + 1 </code></pre>
python|django|django-models|models
2
779
30,103,029
Django Celery Directory Structure and Layout
<p>I have a django project using the following directory structure.</p> <pre><code>project/ account/ models.py views.py blog/ models.py views.py mediakit/ models.py views.py reports/ celery.py &lt;-- new models.py tasks.py &lt;-- new views.py settings/ __init__.py &lt;-- project settings file system/ cron/ mongodb/ redis/ manage.py </code></pre> <p>Here's the contents of celery.py derived from the celery tutorial (<a href="http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html" rel="nofollow">http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html</a>).</p> <pre><code>from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') from django.conf import settings # app = Celery('reports') app = Celery('reports', backend='djcelery.backends.database:DatabaseBackend', broker='amqp://guest:guest@localhost:5672//') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) </code></pre> <p>Some of my apps are shared across projects. reports, for example might be used in 4 different projects, so I can see how tasks.py should live in the reports app so when it's added to a new project the tasks come along. What I don't quite understand is why celery.py needs to live within the reports app too. When I go to add some tasks to the account app, I'm basically building the same celery.py file replacing 'reports' with 'account'. Shouldn't I have one celery file that lives at the same level as manage.py? Any help or suggestions would be greatly appreciated. </p>
<p>The celery app file should live in the core directory of your project, along the settings and all the other things as shown in the documentation that you posted.</p> <p>To define portable tasks it makes sense to put them in the app that is using them, as you pointed out, in your case the reports app.</p> <p>The idea is that your task file is registered by whatever celery app is defined in the project, and your django app need no knowledge of which celery app is registering the tasks. You do this by using the <a href="http://celery.readthedocs.org/en/latest/django/first-steps-with-django.html#using-the-shared-task-decorator" rel="nofollow"><code>shared_task</code></a> decorator instead of <code>app.task</code>.</p> <p>To summarize:</p> <pre><code>project/ project/ settings.py celery.py &lt;- new, shown in the docs, also add __init__.py urls.py account/ models.py views.py blog/ models.py views.py mediakit/ models.py tasks.py &lt;-- tasks for the me views.py reports/ models.py tasks.py &lt;-- tasks for the reports app views.py manage.py </code></pre> <p>In tasks.py you have something like this:</p> <pre><code>from celery import shared_task @shared_task def my_add_task(a, b): return a + b </code></pre> <p>Hope this helps.</p>
python|django|rabbitmq|celery|django-celery
4
780
30,174,841
How to escape spaces in Bash command line arguments
<p>Does Bash support escaping spaces in command line arguments?</p> <p>I have a simple Python script using argparse to get arguments passed from Bash, but when I call it like:</p> <pre><code>myscript.py --name="Some Text With Spaces" </code></pre> <p>I get a result like:</p> <pre><code>args = ['Text', 'With' Spaces'] kwargs = {'name': 'Some'} </code></pre> <p>I though Bash support spaces with "\" but trying</p> <pre><code>myscript.py --name="Some\ Text\ With\ Spaces" </code></pre> <p>results in the same thing.</p> <p>Am I misusing Bash, or is this a problem I have to deal with on Python's side?</p>
<p>Coming from the bash end, the most likely cause is that you're not telling us the truth about your bash code. What you're hitting looks a great deal like <A HREF="http://mywiki.wooledge.org/BashFAQ/050" rel="noreferrer">BashFAQ #50</A>.</p> <p>Running</p> <pre><code>myscript.py --name="Some Text With Spaces" </code></pre> <p>...directly from a command line works perfectly, resulting in a <code>sys.argv</code> array of <code>['myscript.py', '--name=Some Text With Spaces']</code>. The behavior you describe is consistent with this:</p> <pre><code>cmd='myscript.py --name="Some Text With Spaces"' $cmd </code></pre> <p>...which will result in a <code>sys.argv</code> array of <code>['myscript.py', '--name="Some', 'Text', 'With', 'Spaces"']</code>.</p> <hr> <p>Don't do that, ever. Either use an array (typically appropriate if you need to build up an argument line conditionally):</p> <pre><code>cmd=( myscript.py --name="Some Text With Spaces" ) "${cmd[@]}" </code></pre> <p>...or a function (typically the appropriate choice in all other cases):</p> <pre><code>myscript() { myscript.py --name="Some Text With Spaces" "$@"; } myscript </code></pre>
python|bash
6
781
56,939,740
How do I convert a str list that has phrases to a int list?
<p>I have a script that allows me to extract the info obtained from excel to a list, this list contains str values that contain phrases such as: "I like cooking", "My dog´s name is Doug", etc.</p> <p>So I've tried this code that I found on the Internet, knowing that the int function has a way to transform an actual phrase into numbers.</p> <p>The code I used is:</p> <pre><code>lista=["I like cooking", "My dog´s name is Doug", "Hi, there"] test_list = [int(i, 36) for i in lista] </code></pre> <p>Running the code I get the following error:</p> <blockquote> <p>builtins.ValueError: invalid literal for int() with base 36: "I like cooking"</p> </blockquote> <p>But I´ve tried the code without the spaces or punctuation, and i get an actual value, but I do need to take those characters into consideration.</p>
<p>To expand on the <code>bytearray</code> approach you could use <code>int.to_bytes</code> and <code>int.from_bytes</code> to actually get an int back, although the integers will be much longer than you show in your example.</p> <pre><code>def to_int(s): return int.from_bytes(bytearray(s, 'utf-8'), 'big', signed=False) def to_str(s): return s.to_bytes((s.bit_length() +7 ) // 8, 'big').decode() lista = ["I like cooking", "My dog´s name is Doug", "Hi, there"] encoded = [to_int(s) for s in lista] decoded = [to_str(s) for s in encoded] </code></pre> <p>encoded:</p> <pre><code>[1483184754092458833204681315544679, 28986146900667755422058678317652141643897566145770855, 1335744041264385192549] </code></pre> <p>decoded:</p> <pre><code>['I like cooking', 'My dog´s name is Doug', 'Hi, there'] </code></pre>
python|python-3.x
2
782
27,680,866
Wrong symbol when using escape sequences learn python the hard way ex10
<p>When i try to print \v or \f i get gender symbols instead:</p> <p><img src="https://i.imgur.com/NlPLx92.png" alt="screenshot"></p> <p>Note also that I'm a complete beginner at programming.</p> <p>edit: Seems like i didnt write clear enough, i <strong>dont</strong> want to write \v or \f but the escape sequence created by them, i dont know what they exactly do but i dont think this is their meant function-</p>
<p>You are trying to print special characters, e.g., <code>"\n" == new line</code>. You can learn more here: <a href="https://docs.python.org/2/reference/lexical_analysis.html#string-literals" rel="nofollow">Python String Literals</a>.</p> <p>Excerpt: </p> <blockquote> <p>In plain English: String literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). <strong>The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.</strong> String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.</p> </blockquote> <p>The r tells it to print a "raw string."</p> <p>Python 2.7ish:</p> <pre><code>print r"\v" </code></pre> <p>Or, you can escape the escape character:</p> <pre><code>print "\\v" </code></pre> <p>Or, for dynamic prints:</p> <pre><code>print "%r" % ("\v",) </code></pre>
python|windows|python-2.7|console|control-characters
2
783
27,609,247
Can tuples implement external data from .txt files?
<p># Defines the variable 'load_words()'.</p> <pre><code>def load_words(): </code></pre> <p># Opens and assigns a 'word' file from an external "txt" file.</p> <pre><code> words_file = open("words.txt", "r") </code></pre> <p># Assigns 'words' as the condensed function for lines of coded words in the external "txt" file.</p> <pre><code> words = [line.strip() for line in words_file] </code></pre> <p>can you do the same with tuples, without accessing data directly within the program?</p> <p>Thanks</p>
<p>If I understood you correctly, yes.</p> <p>From your question, it sounds like you want to read a file with <code>N</code> lines, and from that file produce an N-tuple of strings, in which each element of the tuple is a line from the file.</p> <p>So, what you're doing now is reading a file that looks like this:</p> <pre><code>Hello World ! </code></pre> <p>and producing the list of strings, <code>["Hello", "World", "!"]</code></p> <p>What I think you want is the 3-tuple: <code>("Hello", "World", "!")</code></p> <p>You can do the following:</p> <pre><code>with open("words.txt") as file: t = tuple(line.strip() for line in file) </code></pre> <p>which will result in <code>t</code> containing the N-tuple of "words.txt"'s contents. What's happening here is that the expression <code>line.strip() for line in file</code> is a generator, being passed to the tuple constructor. Generators are iterable, and the tuple constructor, when given an iterable, iterates over all elements of the iterable and stuffs them into a tuple.</p> <p>A quick note: you should not want to or need to do this. File inputs are beyond your direct control as a programmer, and therefore should be treated as variable length. Tuples are useful to represent fixed-length constructs, not so much for variable things like files. Why do you want to do this? What purpose do tuples serve for you which lists do not?</p>
python
1
784
43,274,901
How to change timezone in http response (django server)?
<p>I'm running django server without any proxy:</p> <pre><code>python manage.py runserver 0.0.0.0:80 </code></pre> <p>I set my local timezone on linux server, it's correct:</p> <pre><code>root@83b3bf90b5c5:/app# date Fri Apr 7 12:38:42 MSK 2017 </code></pre> <p>Also I set local timezone on settings.py of my django project:</p> <pre><code>TIME_ZONE = 'Europe/Moscow' </code></pre> <p>And checked it:</p> <pre><code>&gt;&gt;&gt; from django.utils.timezone import localtime, now &gt;&gt;&gt; localtime(now()) datetime.datetime(2017, 4, 7, 12, 38, 42, 196476, tzinfo=&lt;DstTzInfo 'Europe/Moscow' MSK+3:00:00 STD&gt;) </code></pre> <p>But when I open any webpage from client (Google Chrome browser) - in http response headers timezone isn't local:</p> <pre><code>Date:Fri, 07 Apr 2017 09:38:42 GMT </code></pre> <p>How can I change timezone in http headers for all project globally?</p>
<p>Using <a href="http://pytz.sourceforge.net/" rel="nofollow noreferrer">pytz</a>, as <code>astimezone</code> method</p> <pre><code>from pytz import timezone time_zone = timezone(settings.TIME_ZONE) currentTime = currentTime.astimezone(time_zone) </code></pre> <blockquote> <p>In your Middleware:</p> </blockquote> <pre><code>import pytz from django.utils import timezone from django.utils.deprecation import MiddlewareMixin class TimezoneMiddleware(MiddlewareMixin): def process_request(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() </code></pre> <blockquote> <p>In Your view.py</p> </blockquote> <pre><code>from django.shortcuts import redirect, render def set_timezone(request): if request.method == 'POST': request.session['django_timezone'] = request.POST['timezone'] return redirect('/') else: return render(request, 'template.html', {'timezones': pytz.common_timezones}) </code></pre> <blockquote> <p>In your templete.html</p> </blockquote> <pre><code>{% load tz %} {% get_current_timezone as TIME_ZONE %} &lt;form action="{% url 'set_timezone' %}" method="POST"&gt; {% csrf_token %} &lt;label for="timezone"&gt;Time zone:&lt;/label&gt; &lt;select name="timezone"&gt; {% for tz in timezones %} &lt;option value="{{ tz }}"{% if tz == TIME_ZONE %} selected="selected"{% endif %}&gt;{{ tz }}&lt;/option&gt; {% endfor %} &lt;/select&gt; &lt;input type="submit" value="Set" /&gt; &lt;/form&gt; </code></pre>
python|django|http|datetime|timezone
1
785
43,160,597
Heroku error : Compiled slug size: 624.7M is too large (max is 300M) - using miniconda for scipy and numpy
<p>I am working with Python 2.7.11, Django 1.9 and Heroku.</p> <p>I need to use scipy and numpy. Everything works well locally but Heroku returns an error when I push the application : "Compiled slug size: 624.7M is too large (max is 300M)"</p> <p>I therefore deleted the buildpack Heroku/Python and added this one: <a href="https://github.com/kennethreitz/conda-buildpack" rel="nofollow noreferrer">https://github.com/kennethreitz/conda-buildpack</a></p> <p>I kept the file requirements.txt:</p> <pre><code>django==1.9.2 boto==2.41.0 dj-database-url==0.4.1 Django==1.9.2 django-allauth==0.28.0 django-appconf==1.0.2 django-autocomplete-light==3.1.6 django-toolbelt==0.0.1 gunicorn==19.6.0 pep8==1.7.0 Pillow==4.0.0 psycopg2==2.6.1 pytz==2016.10 sorl-thumbnail==12.3 virtualenv==15.1.0 sendgrid==3.2.10 python_http_client==2.2.1 django-s3-folder-storage==0.3 django-debug-toolbar==1.5 celery==3.1.25 redis==2.10.5 tweepy==3.5.0 geopy==1.11.0 django-mptt==0.8.7 mistune==0.7.3 django-widget-tweaks==1.4.1 django-cleanup == 0.4.2 django-unused-media == 0.1.6 python-memcached == 1.58 python-binary-memcached == 0.26.0 django-bmemcached == 0.2.3 whitenoise==3.2 coverage == 4.3.4 raven == 6.0.0 newrelic == 2.82.0.62 ajaxuploader==0.3.8 awscli==1.10.47 botocore==1.4.37 colorama==0.3.7 dj-static==0.0.6 django-libs==1.67.4 django-user-media==1.2.3 docutils==0.12 ecdsa==0.13 flake8==2.5.4 jmespath==0.9.0 mccabe==0.5.0 oauthlib==1.1.2 paramiko==2.0.1 pyasn1==0.1.9 pycrypto==2.6.1 pyflakes==1.2.3 python-openid==2.2.5 requests==2.9.1 requests-oauthlib==0.6.1 rsa==3.4.2 s3transfer==0.0.1 simplejson==3.8.2 six==1.10.0 static3==0.7.0 futures==3.0.5 </code></pre> <p>and added a conda-requirements.txt with:</p> <pre><code>nomkl python=2.7.11 numpy=1.11.1 scipy=0.19.0 scikit-learn==0.18.1 </code></pre> <p>Here is the complete Heroku build log (too many lines to fit here):</p> <p><a href="https://gist.github.com/jpuaux/74cb50a6cfb2dcab80d25d1809ae01c2" rel="nofollow noreferrer">https://gist.github.com/jpuaux/74cb50a6cfb2dcab80d25d1809ae01c2</a></p> <p>Please note that I purged Heroku cache with:</p> <p>heroku repo:purge_cache -a myapp</p> <p>Thanks for any help you can provide!</p>
<p>Did you use Anaconda? I had the same problem the slug file was 505M, then I created a virtual env with pip and got one only 237M My requirements.txt: I created a new virtual env using pip instead of conda. </p> <pre><code>pip install virtualenv cd my_project_folder virtualenv my_project </code></pre> <p>Then I installed the packages I needed, this is my list in requirements.txt:</p> <pre><code>certifi==2018.10.15 chardet==3.0.4 Click==7.0 cycler==0.10.0 decorator==4.3.0 Flask==1.0.2 gunicorn==19.9.0 idna==2.7 ipython-genutils==0.2.0 itsdangerous==1.1.0 Jinja2==2.10 jsonschema==2.6.0 jupyter-core==4.4.0 kiwisolver==1.0.1 MarkupSafe==1.0 matplotlib==3.0.1 nbformat==4.4.0 nltk==3.3 numpy==1.15.3 pandas==0.23.4 Pillow==5.3.0 plotly==3.3.0 pyparsing==2.2.2 python-dateutil==2.7.4 pytz==2018.6 requests==2.20.0 retrying==1.3.3 scikit-learn==0.20.0 scipy==1.1.0 six==1.11.0 sklearn==0.0 SQLAlchemy==1.2.12 traitlets==4.3.2 urllib3==1.24 Werkzeug==0.14.1 wordcloud==1.5.0 </code></pre> <p>Then I uploaded to heroku and it went through.</p>
python|django|numpy|heroku|scipy
0
786
48,465,648
How to save training model at each training step instead of periodic save based on time interval.? - in TensorFlow-Slim
<p>slim.learning.train(...) accepts two arguments pertaining to saving the model(<em>save_interval_secs</em>) or saving the summaries(<em>save_summaries_secs</em>). The problem with this API is, it only allows to save the model/summary based on some "time interval" but I need to do this based on "each step" of the training.</p> <p>how to achieve this using TF-slim api.?</p> <p>Here is the slim.learning train api -</p> <pre><code>def train(train_op, logdir, train_step_fn=train_step, train_step_kwargs=_USE_DEFAULT, log_every_n_steps=1, graph=None, master='', is_chief=True, global_step=None, number_of_steps=None, init_op=_USE_DEFAULT, init_feed_dict=None, local_init_op=_USE_DEFAULT, init_fn=None, ready_op=_USE_DEFAULT, summary_op=_USE_DEFAULT, **save_summaries_secs=600,** summary_writer=_USE_DEFAULT, startup_delay_steps=0, saver=None, **save_interval_secs=600,** sync_optimizer=None, session_config=None, session_wrapper=None, trace_every_n_steps=None, ignore_live_threads=False): </code></pre>
<p>Slim is deprecated, and using Estimator you get full control over saving / summary frequency.</p> <p>You can also set the seconds to a very small number so it always saves.</p>
tensorflow|tensorflow-slim
0
787
48,631,907
Running CrossValidationCV in parallel
<p>When I run a <strong><code>GridsearchCV()</code></strong> and a <strong><code>RandomizedsearchCV()</code></strong> methods in parallel ( having <strong><code>n_jobs&gt;1</code></strong> or <strong><code>n_jobs=-1</code></strong> options set )<br> it shows this message:</p> <blockquote> <p>ImportError: [joblib] Attempting to do parallel computing without protecting your import on a system that does not support forking. To use parallel-computing in a script, you must protect your main loop using "if name == 'main'". Please see the joblib documentation on Parallel for more information" I put the code in a class in .py file and call it using if_name_=='main in other .py file but it still shows this message</p> </blockquote> <p>It works good when <strong><code>n_jobs=1</code></strong></p> <pre><code>import platform; print(platform.platform()) </code></pre> <blockquote> <pre><code>Windows-10-10.0.10586-SP0 </code></pre> </blockquote> <pre><code>import numpy; print("NumPy", numpy.__version__) </code></pre> <blockquote> <p>NumPy 1.13.1</p> </blockquote> <pre><code>import scipy; print("SciPy", scipy.__version__) </code></pre> <blockquote> <p>SciPy 0.19.1</p> </blockquote> <pre><code> import sklearn; print("Scikit-Learn", sklearn.__version__) </code></pre> <blockquote> <p>Scikit-Learn 0.19.0</p> </blockquote> <hr> <p>UPDATE</p> <p>I tried this code but it still gives me the same error </p> <pre><code>import numpy as np from sklearn.model_selection import RandomizedSearchCV from sklearn.tree import DecisionTreeClassifier class Test(): def __init__(self): attributes = [..] dataset = pd.read_csv("..") X=dataset[[..]] Y=dataset[...] model=DecisionTreeClassifier() model = RandomizedSearchCV(....) model.fit(X, Y) if __name__ == '__main__': Test() </code></pre>
<h2><strong><code>joblib</code></strong> is know for this behaviour and rather explicit in documenting:</h2> <blockquote> <p><strong>Warning</strong></p> <p>Under Windows, it is important to protect the main loop of code to avoid recursive spawning of <code>subprocesses</code> when using <strong><code>joblib.Parallel</code></strong>. In other words, you should be writing code like this:</p> </blockquote> <pre><code>import .... def function1(...): ... def function2(...): ... ... if __name__ == '__main__': # do stuff with imports and functions defined about ... </code></pre> <blockquote> <p>No code should run outside of the <strong><code>“if __name__ == ‘__main__’”</code></strong> blocks, only imports and definitions.</p> </blockquote> <p>So, refactor your code so as to meet this well-defined requirement and your code will start to benefit from the <strong><code>joblib</code></strong>-tools powers.</p>
python|parallel-processing|scikit-learn|cross-validation
0
788
48,519,440
Validation Error while creating partial invoice from sales order in Odoo 10
<p>When am creating partial invoice (down payment), I got the below error</p> <blockquote> <p>The operation cannot be completed, probably due to the following:- deletion: you may be trying to delete a record while other records still reference it- creation/update: a mandatory field is not correctly set</p> <p>[object with reference: categ_id - categ.id]</p> </blockquote>
<p>As far as my understanding, I think you have done some customizations in the DB, that's why this error. The error says that there is a mandatory field, but you are not supplied the value into it. The field is shown in the error message, categ_id.</p> <p>Thanks</p>
python|python-2.7|odoo|odoo-10
0
789
19,960,166
What are the workaround options for python out of memory error?
<p>I am reading a x,y,z point file (LAS) into python and have run into memory errors. I am interpolating unknown points between known points for a project I am working on. I began working with small files (&lt; 5,000,000 points) and was able to read/write to a numpy array and python lists with no problem. I have received more data to work with (> 50,000,000 points) and now my code fails with a MemoryError.</p> <p>What are some options for handling such large amounts of data? I do not have to load all data into memory at once, but I will need to look at neighboring points using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html" rel="nofollow">scipy kd-tree</a> I am using Python 2.7 32 bit on a 64 bit Windows XP OS.</p> <p>Thanks in advance.</p> <p>EDIT: Code is posted below. I took out code for long calculations and variable definitions.</p> <pre><code>from liblas import file import numpy as np f = file.File(las_file, mode='r') num_points = int(f.__len__()) dt = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('i', 'u2'), ('c', 'u1'), ('t', 'datetime64[us]')] xyzict = np.empty(shape=(num_points,), dtype = dt) counter = 0 for p in f: newrow = (p.x, p.y, p.z, p.intensity, p.classification, p.time) xyzict[counter] = newrow counter += 1 dropoutList = [] counter = 0 for i in np.nditer(xyzict): # code to define P1x, P1y, P1z, P1t if counter != 0: # code to calculate n, tDiff, and seconds if n &gt; 1 and n &lt; scanN: # code to find v and vD for d in range(1, int(n-1)): # Code to interpolate x, y, z for points between P0 and P1 # Append tuple of x, y, and z to dropoutList dropoutList.append(vD) # code to set x, y, z, t for next iteration counter += 1 </code></pre>
<p>Regardless of the amount of RAM in your system, if you are running 32-bit python, you will have a practical limit of about 2 GB of RAM for your application. There are a number of other questions on SO that address this (e.g., see <a href="https://stackoverflow.com/questions/18282867/python-32-bit-memory-limits-on-64bit-windows">here</a>). Since the structure you are using in your ndarray is 23 bytes and you are reading over 50,000,000 points, that already puts you at about 1 GB. You haven't included the rest of your code so it isn't clear how much additional memory is being consumed by other parts of your program.</p> <p>If you have well over 2 GB of RAM in your system and you will continue to work on large data sets, you should install 64-bit python to get around this ~ 2 GB limit.</p>
python|numpy|scipy|out-of-memory
5
790
66,941,321
Why isn't my label configuring correctly?
<p>I want this label to configure into the text entry after the user enters the text and hits go but the label isn't configuring.</p> <p>I want the label that says &quot;Hello!&quot; to change into whatever is put in the main entry. I'm looking for an answer written in full code instead of one fixed line.</p> <p>Here's my code:</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk root = tk.Tk() root.attributes('-fullscreen', True) exit_button = tk.Button(root, text=&quot;Exit&quot;, command = root.destroy) exit_button.place(x=1506, y=0) def answer(): answer_label.config(text=main_entry.get()) entry_frame = tk.Frame(root) main_entry = tk.Entry(entry_frame, width=100) main_entry.grid(row=0, column=0) go_button = tk.Button(entry_frame, text= 'Go!', width=85, command= answer) go_button.grid(row=1, column=0) answer_label = tk.Label(text = &quot;Hello!&quot;).pack() entry_frame.place(relx=.5, rely=.5, anchor='center') root.mainloop() </code></pre>
<p>1.Split <code>tk.Label</code> and <code>pack()</code>.</p> <p>2.Pass the lable.</p> <pre><code> import tkinter as tk root = tk.Tk() root.attributes('-fullscreen', True) exit_button = tk.Button(root, text=&quot;Exit&quot;, command = root.destroy) exit_button.place(x=1506, y=0) def answer(answer_label): answer_label.config(text=main_entry.get()) entry_frame = tk.Frame(root) main_entry = tk.Entry(entry_frame, width=100) main_entry.grid(row=0, column=0) answer_label = tk.Label(text = &quot;Hello!&quot;) answer_label.pack() go_button = tk.Button(entry_frame, text= 'Go!', width=85, command=lambda: answer(answer_label)) go_button.grid(row=1, column=0) entry_frame.place(relx=.5, rely=.5, anchor='center') root.mainloop() </code></pre>
python|python-3.x|tkinter|pycharm
0
791
48,255,267
How do I print a local tensor in tensorflow?
<p>I want to print a tensor in my program to see its internal values once it gets evaluated. The problem, however, is that the tensor being declared inside a function. To understand my problem better, here is some example code to better explain what it is I want to do:</p> <pre><code>a = tf.Variable([[2,3,4], [5,6,7]]) b = tf.Variable([[1,2,2], [3,3,3]]) def divide(a,b): with tf.variable_scope('tfdiv', reuse=True): c = tf.divide(a,b, name='c') # Cannot print(c) here, as this will only yield tf info on c return c d = divide(a,b) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(d) sess.run(tf.get_variable('tfdiv/c:0').eval(session=sess)) </code></pre> <p>Previously, I have been able to do a print(c.eval(session=sess)), but as c is a local variable inside a function now, that does not work. As can be seen in the code above, I have tried to use tensorflow's variable scope in order to access the variable and then evaluate it. Unfortunately, this results in the error message:</p> <pre><code>ValueError: Shape of a new variable (tfdiv/c:0) must be fully defined, but instead was &lt;unknown&gt;. </code></pre> <p>I tried to use the reuse=True flag, but I still get the same error. Any thoughts on how I can solve this problem? Best would be if there is a print(c) equivalent that can be put into the divide function, as written in the code above. </p>
<p>This will achieve what you want to do:</p> <pre><code>with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(d)) </code></pre> <p>Alternatively, you could replace the last line with:</p> <pre><code>print(sess.run(tf.get_default_graph().get_tensor_by_name('tfdiv/c:0'))) </code></pre>
python|debugging|variables|tensorflow|local
2
792
48,245,809
How to build a content-based recommender system that uses multiple attributes?
<p>I want to build a content-based recommender system in Python that uses multiple attributes to decide whether two items are similar. In my case, the "items" are packages hosted by the C# package manager (<a href="https://www.nuget.org/packages/EntityFramework" rel="nofollow noreferrer">example</a>) that have various attributes such as name, description, tags that could help to identify similar packages.</p> <p>I have a prototype recommender system <a href="https://github.com/jamesqo/nuget_stuff" rel="nofollow noreferrer">here</a> that currently uses only a single attribute, the description, to decide whether packages are similar. It computes TF-IDF rankings for the descriptions and prints out the top 10 recommendations based on that:</p> <pre><code># Code mostly stolen from http://blog.untrod.com/2016/06/simple-similar-products-recommendation-engine-in-python.html </code></pre> <pre class="lang-py prettyprint-override"><code>def train(dataframe): tfidf = TfidfVectorizer(analyzer='word', ngram_range=(1, 3), min_df=0, stop_words='english') tfidf_matrix = tfidf.fit_transform(dataframe['description']) cosine_similarities = linear_kernel(tfidf_matrix, tfidf_matrix) for idx, row in dataframe.iterrows(): similar_indices = cosine_similarities[idx].argsort()[:-10:-1] similar_items = [(dataframe['id'][i], cosine_similarities[idx][i]) for i in similar_indices] id = row['id'] similar_items = [it for it in similar_items if it[0] != id] # This 'sum' is turns a list of tuples into a single tuple: # [(1,2), (3,4)] -&gt; (1,2,3,4) flattened = sum(similar_items, ()) try_print("Top 10 recommendations for %s: %s" % (id, flattened)) </code></pre> <p>How can I combine <code>cosine_similarities</code> with other similarity measures (based on same author, similar names, shared tags, etc.) to give more context to my recommendations?</p>
<p>For some context, my work with content-based recommenders has revolved primarily around raw text and categorical data/features. Here's a high-level approach I've taken that has worked out nicely and is pretty simple to implement.</p> <p>Suppose I have three feature columns that I can potentially use to make recommendations: <code>description</code>, <code>name</code>, and <code>tags</code>. To me, the path of least resistance entails combining these three feature sets in a useful way.</p> <p>You're off to a good start, using TF-IDF to encode <code>description</code>. So why not treat <code>name</code> and <code>tags</code> in a similar way by creating a feature "corpus" consisting of <code>description</code>, <code>name</code>, and <code>tags</code>? Literally, this would mean concatenating the contents of each of the three columns into one long text column.</p> <p>Be wise about the concatenation, though, as it's probably to your advantage to preserve <em>from which column a given word comes from</em>, in the case of features like <code>name</code> and <code>tag</code>, which are assumed to have much lower cardinality than <code>description</code>. To put it more explicitly: instead of just creating your corpus column like this:</p> <pre><code>df['corpus'] = (pd.Series(df[['description', 'name', 'tags']] .fillna('') .values.tolist() ).str.join(' ') </code></pre> <p>You might try preserving information about where particular data points in <code>name</code> and <code>tags</code> come from. Something like this:</p> <pre><code>df['name_feature'] = ['name_{}'.format(x) for x in df['name']] df['tags_feature'] = ['tags_{}'.format(x) for x in df['tags']] </code></pre> <p>And after you do that, I would take things a step further by considering how the default tokenizer (which you're using above) works in <code>TfidfVectorizer</code>. Suppose you have the name of a given package's author: "Johnny 'Lightning' Thundersmith". If you just concatenate that literal string, the tokenizer will split it up and roll each of "Johnny", "Lightning", and "Thundersmith" into <em>separate features</em>, which could potentially diminish the information added by that row's value for <code>name</code>. I think it's best to try to preserve that information. So I would do something like this to each of your lower-cardinality text columns (e.g. <code>name</code> or <code>tags</code>):</p> <pre><code>def raw_text_to_feature(s, sep=' ', join_sep='x', to_include=string.ascii_lowercase): def filter_word(word): return ''.join([c for c in word if c in to_include]) return join_sep.join([filter_word(word) for word in text.split(sep)]) def['name_feature'] = df['name'].apply(raw_text_to_feature) </code></pre> <p>The same sort of critical thinking should be applied to <code>tags</code>. If you've got a comma-separated "list" of tags, you'll probably have to parse those individually and figure out the right way to use them.</p> <p>Ultimately, once you've got all of your <code>&lt;x&gt;_feature</code> columns created, then you can create your final "corpus" and plug that into your recommender system as inputs.</p> <p>This whole system takes some engineering, to be sure, but I've found it's the easiest way to introduce new information from other columns that have different cardinalities.</p>
python|pandas|machine-learning|scikit-learn|recommendation-system
6
793
73,548,977
How to convert voltage (or frequency) floating number read backs to mV (or kHz)?
<p>I am successfully able to read back data from an instrument:</p> <ul> <li><p>When the read back is a voltage, I typically read back values such as <code>5.34e-02</code> Volts.</p> </li> <li><p>When the read back is frequency, I typically read values like <code>2.95e+04</code>or <code>1.49e+05</code> with units Hz.</p> </li> </ul> <p>I would like to convert the voltage read back of <code>5.34e-02</code> to exponent e-3 (aka millivolts), ie.. <code>53.4e-3</code>. next, I would like to extract the mantissa <code>53.4</code> out of this because I want all my data needs to be in milliVolts.</p> <p>Similarly, I would like to convert all the frequency such as <code>2.95e+04</code> (or <code>1.49e+05</code>) to kiloHz, ie... <code>29.5e+03</code> or <code>149e+03</code>. Next would like to extract the mantissa <code>29.5</code> and <code>149</code> from this since all my data needs to be kHz.</p> <p>Can someone suggest how to do this?</p>
<p>Well, to convert volts to millivolts, you multiply by 1000. To convert Hz to kHz, you divide by 1000.</p> <pre><code>&gt;&gt;&gt; reading = 5.34e-02 &gt;&gt;&gt; millivolts = reading * 1000 &gt;&gt;&gt; print(millivolts) 53.400000000000006 &gt;&gt;&gt; hz = 2.95e+04 &gt;&gt;&gt; khz = hz /1000 &gt;&gt;&gt; khz 29.5 &gt;&gt;&gt; </code></pre> <h2>FOLLOW-UP</h2> <p>OK, assuming your real goal is to keep the units the same but adjust the exponent to a multiple of 3, see if this meets your needs.</p> <pre><code> def convert(val): if isinstance(val,int): return str(val) cvt = f&quot;{val:3.2e}&quot; if 'e' not in cvt: return cvt # a will be #.## # b will be -## a,b = cvt.split('e') exp = int(b) if exp % 3 == 0: return cvt if exp % 3 == 1: a = a[0]+a[2]+a[1]+a[3] exp = abs(exp-1) return f&quot;{a}e{b[0]}{exp:02d}&quot; a = a[0]+a[2]+a[3]+a[1] exp = abs(exp-2) return f&quot;{a}e{b[0]}{exp:02d}&quot; for val in (5.34e-01, 2.95e+03, 5.34e-02, 2.95e+04, 5.34e-03, 2.95e+06): print( f&quot;{val:3.2e} -&gt;&quot;, convert(val) ) </code></pre> <p>Output:</p> <pre><code>5.34e-01 -&gt; 534.e-03 2.95e+03 -&gt; 2.95e+03 5.34e-02 -&gt; 53.4e-03 2.95e+04 -&gt; 29.5e+03 5.34e-03 -&gt; 5.34e-03 2.95e+06 -&gt; 2.95e+06 </code></pre>
python|floating-point|number-formatting|pyvisa
2
794
69,924,897
How to get the div before a specific div with css selector
<p>There is probably a better way to do this, but I just need this to work for now before I can come up with a better solution. Im working on a webscraping application with Python and BeautifulSoup. I need to grab a specific div, but the placement of that div changes slightly on different pages (sometimes its the 3rd, sometimes the 4th, ect). There are no class tags or id tags on the div I want, but I did notice how there was always a div directly after the one I want, and that one has a id tag. It looks something like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;main-container&quot;&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;The div I want&lt;/div&gt; &lt;div id=&quot;point&quot;&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>So im looking for something like this:</p> <pre class="lang-css prettyprint-override"><code>div#main-container &gt; div:item-before(#point) </code></pre> <p>Is there any easy way to do this in CSS, or do I have to come up with a better solution?</p>
<p>Find specific <code>div</code> using <code>id</code> or <code>class</code> and call <code>find_previous()</code> to get appropriate tag</p> <pre><code>html=&quot;&quot;&quot;&lt;div id=&quot;main-container&quot;&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;The div I want&lt;/div&gt; &lt;div id=&quot;point&quot;&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt;&quot;&quot;&quot; soup=BeautifulSoup(html,&quot;html.parser&quot;) soup.find(&quot;div&quot;,attrs={&quot;id&quot;:&quot;main-container&quot;}).find(&quot;div&quot;,attrs={&quot;id&quot;:&quot;point&quot;}).find_previous() </code></pre> <p>Output:</p> <pre><code>&lt;div&gt;The div I want&lt;/div&gt; </code></pre>
python|html|css|web-scraping|beautifulsoup
0
795
73,451,375
scrape sports reference table
<p>I have tried the following script to make to grab the table on the webpage.</p> <pre><code>from bs4 import BeautifulSoup import pandas as pd url = 'https://www.sports-reference.com/cfb/play-index/rivals.cgi?request=1&amp;school_id=penn-state&amp;opp_id=purdue' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'} pageTree = requests.get(url, headers=headers) soup = BeautifulSoup(pageTree.content, 'html.parser') soup.find('tbody') </code></pre> <p>However, the table is not able to be pulled. Not even a &quot;pd.read_html&quot; line works. Is there a reason for that?</p>
<p>The desired table data is under html comment. By removing the comment,you can extract the table data using pandas only.</p> <pre><code>import pandas as pd import requests from bs4 import BeautifulSoup url= 'https://www.sports-reference.com/cfb/play-index/rivals.cgi?request=1&amp;school_id=penn-state&amp;opp_id=purdue' res = requests.get(url).text.replace('&lt;!--', '').replace('--&gt;', '') soup =BeautifulSoup(res,'lxml') table = soup.select_one('#div_results') df = pd.read_html(str(table))[0] d = df.droplevel(0, axis=1) print(d) </code></pre> <p><strong>Output:</strong></p> <pre><code> G Date Day School Unnamed: 4_level_1 Opponent ... Diff W L T Streak Notes 0 19 2019-10-05 Sat Penn State (12) NaN Purdue ... 28 15 3 1 W 9 NaN 1 18 2016-10-29 Sat Penn State (24) @ Purdue ... 38 14 3 1 W 8 NaN 2 17 2013-11-16 Sat Penn State NaN Purdue ... 24 13 3 1 W 7 NaN 3 16 2012-11-03 Sat Penn State @ Purdue ... 25 12 3 1 W 6 NaN 4 15 2011-10-15 Sat Penn State NaN Purdue ... 5 11 3 1 W 5 NaN 5 14 2008-10-04 Sat Penn State (6) @ Purdue ... 14 10 3 1 W 4 NaN 6 13 2007-11-03 Sat Penn State NaN Purdue ... 7 9 3 1 W 3 NaN 7 12 2006-10-28 Sat Penn State @ Purdue ... 12 8 3 1 W 2 NaN 8 11 2005-10-29 Sat Penn State (11) NaN Purdue ... 18 7 3 1 W 1 NaN 9 10 2004-10-09 Sat Penn State NaN Purdue (9) ... -7 6 3 1 L 2 NaN 10 9 2003-10-11 Sat Penn State @ Purdue (18) ... -14 6 2 1 L 1 NaN 11 8 2000-09-30 Sat Penn State NaN Purdue (22) ... 2 6 1 1 W 6 NaN 12 7 1999-10-23 Sat Penn State (2) @ Purdue (16) ... 6 5 1 1 W 5 NaN 13 6 1998-10-17 Sat Penn State (12) NaN Purdue ... 18 4 1 1 W 4 NaN 14 5 1997-11-15 Sat Penn State (6) @ Purdue (19) ... 25 3 1 1 W 3 NaN 15 4 1996-10-12 Sat Penn State (10) NaN Purdue ... 17 2 1 1 W 2 NaN 16 3 1995-10-14 Sat Penn State (20) @ Purdue ... 3 1 1 1 W 1 NaN 17 2 1952-09-27 Sat Penn State NaN Purdue ... 0 0 1 1 T 1 NaN 18 1 1951-11-03 Sat Penn State @ Purdue ... -28 0 1 0 L 1 NaN [19 rows x 16 columns] </code></pre>
python-3.x|pandas|beautifulsoup
3
796
73,267,048
Can't import a class from a python package
<p>I created a private python package with this structure:</p> <pre><code> python_package utils __init__.py module1.py module2.py </code></pre> <p>And inside the module1.py file there is a class <code>Class1</code></p> <p>Now when I download this package in another project using pip, I can't import <code>Class1</code> using</p> <p><code>from utils import Class1</code></p> <p>Am I missing something ?</p> <p>Also the <code>__init__.py</code> file contains the following lines :</p> <pre><code>from .module1 import * from .module2 import * </code></pre>
<p>try this if you are not able to access the class directly</p> <pre><code>import filename object=filename.class1() </code></pre>
python|class|package
1
797
64,830,998
Adding an increment to duplicates within a python dataframe
<p>I'm looking to concatenate two columns in data frame and, where there are duplicates, append an integer number at the end. The wrinkle here is that I will keep receiving feeds of data and the increment needs to be aware of historical values that were generated and not reuse them.</p> <p>I've been trying to do this with an apply function but I'm having issues when there are duplicates within a single received data set and I just can't wrap my head around a way to do this without iterating through the data frame (which is generally frowned upon).</p> <p><strong>I've gotten this far:</strong></p> <pre><code>import pandas as pd def gen_summary(color, car, blacklist): exists = True increment = 0 summary = color + car while exists: if summary in blacklist: increment += 1 summary = color + car + str(increment) # Append increment if in burn list else: exists = False # Exit this loop return summary def main(): blacklist = ['RedToyota', 'BlueVolkswagon', 'BlueVolkswagon1', 'BlueVolkswagon2'] df = pd.DataFrame( {'color': ['Red', 'Blue', 'Blue', 'Green'], 'car': ['Toyota', 'Volkswagon', 'Volkswagon', 'Hyundai'], 'summary': ['', '', '', '']} ) #print(df) df[&quot;summary&quot;] = df.apply(lambda x: gen_summary(x['color'], x['car'], blacklist), axis=1) print(df) if __name__ == &quot;__main__&quot;: main() </code></pre> <p><strong>Output:</strong></p> <pre><code> color car summary 0 Red Toyota RedToyota1 1 Blue Volkswagon BlueVolkswagon3 2 Blue Volkswagon BlueVolkswagon3 3 Green Hyundai GreenHyundai </code></pre> <p>Note that BlueVolkswagon1 and BlueVolkswagon2 were used in previous data feeds so it has to start from 3 here. The real issue is that there are duplicate BlueVolkswagon values in just this data set so it doesn't increment properly and duplicates BlueVolkswagon3 because I can't update the history in the middle of applying a function to the entire data set.</p> <p>Is there some elegant pythonic way to do this that I can't wrap my head around or is this a scenario where iterating through the data frame actually does make sense?</p>
<p>I'm not completely sure what you want to achieve, but you can update <code>blacklist</code> in the process. <code>blacklist</code> is just a pointer to the actual list data. If you slightly modify <code>gen_summary</code> by adding <code>blacklist.append(summary)</code> before the <code>return</code> statement</p> <pre><code>def gen_summary(color, car, blacklist): ... exists = False # Exit this loop blacklist.append(summary) return summary </code></pre> <p>you will get following result</p> <pre><code> color car summary 0 Red Toyota RedToyota1 1 Blue Volkswagon BlueVolkswagon3 2 Blue Volkswagon BlueVolkswagon4 3 Green Hyundai GreenHyundai </code></pre> <p>Grouping would be a bit more efficient. This should produce the same result:</p> <pre><code>def gen_summary(ser, blacklist): color_car = ser.iat[0] summary = color_car increment = 0 exists = True while exists: if summary in blacklist: increment += 1 summary = color_car + str(increment) # Append increment if in burn list else: exists = False # Exit this loop return ([color_car + ('' if increment == 0 else str(increment))] + [color_car + str(i + increment) for i in range(1, len(ser))]) df['summary'] = df['color'] + df['car'] df['summary'] = df.groupby(['color', 'car']).transform(gen_summary, blacklist) </code></pre> <p>Is that the result you are looking for? If yes, I'd like to add a suggestion for optimising your approach: Use a dictionary instead of a list for <code>blacklist</code>:</p> <pre><code>def gen_summary(color, car, blacklist): key = color + car num = blacklist.get(key, -1) + 1 blacklist[key] = num return key if num == 0 else f'{key}{num}' blacklist = {'RedToyota': 0, 'BlueVolkswagon': 2} </code></pre> <p>or with grouping</p> <pre><code>def gen_summary(ser, blacklist): key = ser.iat[0] num = blacklist.get(key, -1) + 1 return ([f'{key}{&quot;&quot; if num == 0 else num}'] + [f'{key}{i + num}' for i in range(1, len(ser))]) blacklist = {'RedToyota': 0, 'BlueVolkswagon': 2} df['summary'] = df['color'] + df['car'] df['summary'] = df.groupby(['color', 'car']).transform(gen_summary, blacklist) </code></pre> <p>should produce the same result without the <code>while</code>-loop and a much faster lookup.</p>
python|python-3.x|pandas|dataframe
0
798
63,820,615
Can I optimize this code with an array for it to work on 100 pages in a single loop?
<p>I'm fairly new in writing code in Python. I'm trying website parser with Beautiful Soup and it works fine. I need guidance in making my code more optimized because I need to parse 100 pages of a single website one by one, and wanted to do it with a single loop + array of pages. Pages change just by numbers like: <a href="https://www.example.com/cat?page1" rel="nofollow noreferrer">https://www.example.com/cat?page1</a> /cat?page2 /cat?page3 and etc. Please see the code below and please give advice if you can regarding my subject. Thanks a lot in advance &lt;3</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>from __future__ import print_function from re import sub from bs4 import BeautifulSoup from urllib.request import urlopen urlpage= urlopen("https://www.example.com/cat?page1").read() bswebpage=BeautifulSoup(urlpage) results=bswebpage.findAll("div",{'class':"someDiv"}) for result in results: print(sub("&amp;ldquo;|.&amp;rdquo;","","".join(result.contents[0:1]).strip()))</code></pre> </div> </div> </p>
<p>You can make a loop there like this:</p> <pre><code>for i in range(1, 101): #goes from 1-100 url = f&quot;https://www.example.com/cat?page{i}&quot; #page1 etc. urlpage= urlopen(url).read() bswebpage=BeautifulSoup(urlpage) results=bswebpage.findAll(&quot;div&quot;,{'class':&quot;someDiv&quot;}) for result in results: print(sub(&quot;&amp;ldquo;|.&amp;rdquo;&quot;,&quot;&quot;,&quot;&quot;.join(result.contents[0:1]).strip())) </code></pre> <p>The results part you can make an array:</p> <pre><code>all_results = [] (... then inside the for) all_results.append(results) </code></pre>
python|arrays
0
799
52,995,053
Python 3 inheritance multiple classes with __str__
<p>How do I use multiple <code>__str__</code> from other classes? For example:</p> <pre class="lang-py prettyprint-override"><code>class A: def __str__(self): return "this" class B: def __str__(self): return "that" class C(A,B): def __str__(self): return super(C, self).__str__() + " those" # return something(A) + " " something(B) + " those" cc = C() print(cc) </code></pre> <p>Output: <strong>this those</strong></p> <p>I would like the output to be: <strong>this that those</strong></p> <p>This <a href="https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance" title="How does Python&#39;s super() work with multiple inheritance?">post</a> is almost a solution (with <code>super()</code>)</p>
<p>With multiple inheritance, <code>super()</code> searches for the <em>first</em> class that has the attribute, as they appear, from left to right. So, it will stop at <code>A</code>. You can access all the parent classes with the special <code>__bases__</code> attribute, and loop over them, calling <code>str</code> on each one.</p>
python|string|python-3.x|class|inheritance
7