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
2,100
64,814,007
Loading Comments to page without Refreshing
<p>I am new to JS and I am trying to learn steps to add comments to posts without refreshing the page. So, far I was successful in using JS in loading Like button without refreshing by following tutorials but I need some help with the comments.</p> <p>Here is the comments view.py</p> <pre><code>class PostDetailView(Det...
<p>I have a complete CRUD example here in this repository. Take a look, I think it might be useful.</p> <p><a href="https://github.com/felipevisu/django_cbv_ajax_crud" rel="nofollow noreferrer">https://github.com/felipevisu/django_cbv_ajax_crud</a></p>
javascript|python|django|ajax
0
2,101
65,283,046
Problem with matrix product definition inside class
<p>I'm trying to make a basic matrix class without numpy. Every operation works just fine, except for the matrix multiplication. I can't see what exactly is wrong with it. Any ideas?</p> <pre><code>import cmath i = cmath.sqrt(-1) class Matrix: def __init__(self, Data): self.Data = Data def __add_...
<p>You have a couple of problems. I will point out where and you take it from there</p> <pre><code>def MatrixMul(self, OpMat): Data = [] for i in range(len(self.Data)): Data.append([]) for j in range(len(OpMat.Data[0])): Sum = 0 Data[i].append([]) for k in ran...
python|arrays|class|matrix
1
2,102
62,609,961
How to properly dynamically import modules in packages for developing / testing
<p>I have made an app with lots of packages and modules. I'm developing these packages (within their directories) and since I'm executing files within the package directory the import paths for modules/packages change.</p> <p>For instance, the project looks a little bit like this...</p> <pre><code>├── app.py └── utils ...
<p>Set the <code>$PYTHONPATH</code> environment variable to the directory containing <code>utils</code>, then your imports will work.</p> <p>Never run a module contained within a package directly. It's problematic if the same is run directly and can also be imported from the package, because then there will be two cop...
python|python-3.x
1
2,103
61,683,626
warning in building webcrawler in python using beautifulsoup
<p>I am trying to build a simple web crawler that gives the URLs of every legion product displayed on amazon.in if the key searched is 'legion'. I am using the following code:</p> <pre><code>import requests from bs4 import BeautifulSoup def legion_spider(max_pages): page = 1 while page &lt;= max_pages: ...
<p>You are missing the parser! Follow this <em>part</em> of the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow noreferrer">BS documentation</a>!</p> <pre><code> BeautifulSoup(markup, &lt;parser&gt;) </code></pre>
python|beautifulsoup|web-crawler|pyspider
0
2,104
61,897,822
Iterating a list VS using pandas
<p>I have a large list called reassembly organized like this:</p> <pre><code>['HYDR', 30472.0, 'B'], ['HYDR', 30470.0, 'S'], ['HYDR', 30474.0, 'B']..... </code></pre> <p>A piece of my code:</p> <pre><code>sum_buys = 0 sum_sells = 0 for deal in reassembly: ticker, vol, oper = deal[0], deal[1], deal[2] if oper...
<p>Yes, you can and should convert the list into a pandas dataframe and use <code>groupby()</code>:</p> <pre><code>df = pd.DataFrame(reassembly, columns=['tickers','vol','operation']) df.groupby('operation')['vol'].sum() </code></pre> <p>Output for the sample data:</p> <pre><code>operation B 60946.0 S 30470.0...
python|pandas
5
2,105
66,301,106
Pandas DataFrame Groupby How to get the group as a list and get average of particular column
<p>I have a dataframe df</p> <pre><code>p m r p1 m1 120 p1 m2 34 p1 m3 56 p2 m4 54 p2 m5 58 </code></pre> <p>I need to group data on p and get the average of r and output should be like this:</p> <pre><code>p m r p1 [m1,m2,m3] 70 p2 [m4,m5] 56 </code></pre>
<p>You can use <code>groupby</code> and <code>agg</code>:</p> <pre><code>&gt;&gt;&gt; df.groupby('p').agg({'m': [list], 'r': ['mean']}).droplevel(1, axis=1) m r p p1 [m1, m2, m3] 70 p2 [m4, m5] 56 </code></pre> <p>Or,</p> <pre><code>&gt;&gt;&gt; df.groupby('p').agg({'m': [li...
python|pandas|dataframe
1
2,106
62,943,125
Overlaying straight lines over a Mollweide Projection
<p>I am trying to overlay straight lines connecting points on a Mollweide Projection, instead of curves.</p> <p>What I am currently getting (top) and the desired plot (bottom):</p> <p><img src="https://i.stack.imgur.com/RwZIX.jpg" alt="Mollweide Projection with curved and straight lines" /></p> <p>Here is the code that...
<p>You want to transform from data coordinates to axes coordinates (say <code>x</code> and <code>y</code>) and plot the lines telling explicitly to Matplotlib to use the system of coordinates associated with your <code>ax</code> — all this stuff is nicely explained in the <a href="https://matplotlib.org/tutorials/advan...
python|matplotlib|map-projections
0
2,107
49,268,558
matplotlib: unreadable scatter plots and histograms on shared axis with logscale
<p>I'm plotting a couple of scatter plots with a lot of data points. At some point half the plot is just solid color and you cannot see the density very well. So I want to "project" the data onto the axis and display a histogram.</p> <p>I wrote a little function that does that. To a plot on axis <code>ax</code> it plo...
<p>I do not exactly know the reason why this fails, I could imagine that the problem is related to the data ranging to below 0 for which a log scale is not defined.</p> <p>In any case you would need to set the limits of the plot manually, </p> <pre><code>ax.set_yscale('log') ax.set_ylim(1,None) </code></pre> <p><a h...
python|matplotlib
2
2,108
67,878,311
Image isn't loading to webpage
<p>I want a logo on my webpage but it isn't loading for some reason. Here's my code to include it in my html file:</p> <pre><code>&lt;img src=&quot;IMG_4772.jpg&quot; alt=&quot;Logo&quot;&gt; </code></pre> <p>Here's what my file organization looks like: <a href="https://i.stack.imgur.com/IskmD.png" rel="nofollow norefe...
<p>Put the image in the <code>static</code> folder and use <code>url_for</code>.</p> <pre><code>&lt;img src=&quot;{{url_for(&quot;static&quot;,filename=&quot;IMG_4772.jpg&quot;)}}&quot; alt=&quot;Logo&quot;&gt; </code></pre>
python|html|flask
0
2,109
35,031,918
How to delete ndb ComputedProperty
<p>I can't del on ComputedProperty.</p> <p>If i remove the property in the model, then, when i get a result i can see the last value.</p> <pre><code>dbExamCorrection(key=Key('dbExamCorrection', 4519216128458752), aid=6744627663077376, c=0, ca=0, correct=5, created=datetime.datetime(2016, 1, 26, 11, 40, 10, 35968), dm...
<p>One approach is outlined here - <a href="https://stackoverflow.com/questions/19842671/migrating-data-when-changing-an-ndb-fields-property-type/19848970#19848970">Migrating data when changing an NDB field&#39;s property type</a></p> <p>Basically fetch the underlying entity (without using ndb) - you get a dictionary ...
python|google-app-engine|google-cloud-datastore|app-engine-ndb
0
2,110
44,933,395
Extracting only required details from the website using Selenium Python
<p>I am trying to search a product 'Printer' in search bar automatically and retrieve only the MFR number of the products of company named EPSON. But the output which I am getting is more than what I want! It is the complete content of that class.</p> <p>Here is my code</p> <pre><code>from selenium import webdriver d...
<p>Try to replace line</p> <pre><code>print(i, item.text) </code></pre> <p>with </p> <pre><code>print(i, item.find_element_by_xpath('.//div[@class="productCodes"]/div[2]/span').text) </code></pre> <p>to get required output</p>
python|selenium-webdriver
1
2,111
61,481,884
How do I introduce values on a dict based on a condition met in nested dicts?
<p>I am trying to export some data from the following json: <a href="http://app.parlamento.pt/webutils/docs/doc.txt?path=6148523063446f764c324679626d56304c3239775a57356b595852684c3052685a47397a51574a6c636e52766379394a626d6c6a6157463061585a686379394a53556b6c4d6a424d5a57647063327868644856795953394a626d6c6a6157463061585a6...
<p>Not sure if I really got the problem but here we go:</p> <p>First of all I would recommend you to avoid using variable names like <code>j</code> and <code>i</code>; it's easier to understand what the code is doing if variable names are descriptive of what they hold.</p> <p>Indeed you are using <code>any()</code> t...
python|json|dictionary
0
2,112
44,688,178
R's replicate and do.call functions equivalent in Python
<p>Suppose that you want construct a pd.DataFrame and you want to get different numbers every-time you increase replicate number in it. (Please Scroll down for Reproducible example in R)</p> <p>I would like to get same output with Python but I dont know how to get there!</p> <p>If you consider this simple pd.Datafram...
<p>Not sure if this is what you wanted, but you could use a <code>for</code> loop and generate the second set of random numbers as shown below.</p> <pre><code>df = pd.DataFrame.from_items([('a' , np.append([np.random.normal(0.10,0.01,5) for _ in xrange(2)], [np.random.norm...
python|pandas|numpy
1
2,113
44,814,848
save() doesn't update datetime fields in monoengine
<p>I am new to mongoengine, but this doesn't make any sense to me, that when I call my my_update() function, the user's updated_at field doesnt get updated but other fields do. here is my model:</p> <pre><code>class User(db.Document): username = db.StringField(required=True, unique=True, max_length=20) created...
<p>To anyone who has same problem, I figured out I had to use Atomic Update() instead of Save() because the save() wouldn't block till it is done and my view function will ask for the object before it was saved.</p> <p>so bottom line is, Save is Evil (mostly). just use atomic update ! </p> <p>like this</p> <p><code>...
python|mongoengine
0
2,114
46,226,490
Remove \r\n\r\n from csv File
<p>My LogFile looks like this because I accidentally added a string that consists of <code>\r\n\r\n</code> to the log script (Arduino Upload to ThingSpeak):</p> <pre><code>created_at,entry_id,field1,field2 "2017-09-10 09:21:43 UTC,18,23.10,""48.70" " 2017-09-10 10:20:35 UTC,19,23.10,48.30" " </code></pre> <p>it sho...
<p>Notice that the csv module's <code>DictReader</code> accepts any object that supports the iterator protocol (more or less). This means that we can read your log file in a function that returns lines from it, suitably modified as necessary, using <code>yield</code> statements.</p> <p>In this function I return the fi...
python-3.x|replace|logfile
1
2,115
49,586,639
why cant i update tensorflow 1.7.0 by conda
<p>I am currently using tensorflow 1.2.1 and I am trying to update to version 1.7.0 using conda, but it is downgraded to 1.1.0. Why is this happening?</p>
<p>The default <code>tensorflow</code> version under <code>conda</code> package manager is 1.1.0.</p> <ol> <li><p>Try creating a new environment within Anaconda with <code>conda</code> virtual environment manager (refer to this <a href="https://conda.io/docs/user-guide/tasks/manage-environments.html#creating-an-enviro...
tensorflow|conda
2
2,116
52,130,720
python 3 get specific value from json dictionary
<p>I have a dictionary I'm getting from an API call. I am trying to grab a specific value from the results.</p> <pre><code>names = requests.get("http://some.api") </code></pre> <p>The result of that call when printed looks like this</p> <pre><code>{'mynames': [{'id': 38, 'name': 'Betsy'}, {'id': 93, 'name': 'Pitbull...
<p><code>requests.get</code> gives a <code>'Response'</code> object rather than a <code>dict</code>. Only the latter has an <code>items</code> method for iteration.</p> <p>You can use the <code>json</code> library to retrieve a regular Python dictionary:</p> <pre><code>import json import requests names = requests.ge...
python|python-3.x|dictionary|python-requests
5
2,117
36,228,363
Dealing with masked coordinate arrays in pcolormesh
<p>I'm working on visualizing some climate model output. The computation is done on a projected latitude/longitude grid. Since the model is simulating sea ice, all land grid cells are masked. The standard tools for plotting geographical information in Python are Basemap and Cartopy, both of which use matplotlib routine...
<p>I see two issues with your &quot;naive&quot; approaches.</p> <p>Firstly, you generally shouldn't set the coordinate arrays <code>X</code> and <code>Y</code> to <code>nan</code>, only the value of the function to plot. Most plotting functions (both <code>matplotlib</code> and others) automatically treat these as miss...
python|numpy|matplotlib|plot
3
2,118
36,184,645
Datetime in python - speed of calculations - big data
<p>I want to find the difference (in days) between two columns in a dataframe (more specifically in the graphlab SFrame datastructure). </p> <p>I have tried to write a couple of functions to do this but I cannot seem to create a function that is fast enough. Speed is my issue right now as I have ~80 million rows to pr...
<p>I'm glad you found a workable way for you, however SArrays allow vector operations, so you don't need to loop through every element of the column. SArrays will iterate, but they're REALLY slow at that.</p> <p>Unfortunately, SArrays don't support vector operations on datetime types because they don't support a "time...
python-2.7|datetime|timedelta|graphlab|bigdata
0
2,119
35,946,215
when to use makemigrations in Django
<p>I am new to Django. I am following tutorials on Django <a href="https://docs.djangoproject.com/en/1.9/intro/tutorial02/" rel="nofollow">Docs</a>. The Docs have mentioned: </p> <blockquote> <p>By running makemigrations, you’re telling Django that you’ve made some changes to your models (in this case, you’ve made...
<p>Migrations describe changes that must be made to the definitions in the underlying database, but not everything in a Django model corresponds directly to the database. Overwriting the <code>__str__</code> method and adding the <code>was_published_recently</code> method don't require any database changes.</p> <p>Add...
python|django
2
2,120
15,457,267
which way of importing is better in python and some clarifications on the class objects
<p>I have a python file named Point2.py, which has the following code</p> <pre><code>class Point(): def __init__(self,x=0,y=0): self.x = x self.y = y def __str__(self): return "%d,%d" %(self.x,self.y) </code></pre> <p>Now in the interpreter, I did this:</p> <pre><code>&gt;&gt;&gt; ...
<p>To answer why:</p> <pre><code>&gt;&gt;&gt; import Point2 &gt;&gt;&gt; p1 = Point() </code></pre> <p>doesn't work, is because you did not directly import the class Point(). To access the <code>Point()</code> class, you'll want to do:</p> <pre><code>&gt;&gt;&gt; import Point2 &gt;&gt;&gt; p1 = Point2.Point() </code...
python|class|object|import
4
2,121
29,651,576
python flickr api for group search and get image data set
<p>Is there any python flickr api where i can hit the group url and get the all the latest image data ?</p> <p>I have an url like : </p> <pre><code>https://www.flickr.com/groups/caterpillarequipment/ </code></pre> <p>I want to get all the latest images data set. I try to do it with flickrapi lib but able to figure o...
<p>If you want to get all of the info for a group's pool use the <code>flickr.groups.pools.getPhotos</code> API call, like this:</p> <pre><code>import flickrapi from pprint import pprint api_key = 'your api key' secret = 'your secret key' flickr = flickrapi.FlickrAPI(api_key, secret, format='parsed-json') group_id =...
python|flickr
4
2,122
29,417,212
Merge Sort Function in Python
<p>I am having trouble with some code in Python: </p> <pre><code>def sort(number_list): if len(number_list &lt;= 1): return number_list front_list = [] back_list = [] counter = 0 half = len(number_list)//2 for x in number_list: if counter &lt; half: front_list.append...
<p>The if statement in the <code>sort()</code> function should be as follows:</p> <pre><code>if len(number_list) &lt;= 1: return number_list </code></pre> <p>Additionally, in <code>merge()</code></p> <pre><code>elif i &lt; front_list: </code></pre> <p>should be</p> <pre><code>elif i &lt; lenght1: </code></pre>
python|sorting|merge
0
2,123
46,423,956
Load checkpoint and finetuning using tf.estimator.Estimator
<p>We're trying to translate old training code based into a more tf.estimator.Estimator compliant code. In the initial code we fine tune an original model for a target dataset. Only some layers are loaded from the checkpoint before the training takes place using a combination of <strong>variables_to_restore</strong> a...
<pre><code>import tensorflow as tf def model_fn(): # your model defintion here # ... # specify your saved checkpoint path checkpoint_path = "model.ckpt" ws = tf.estimator.WarmStartSettings(ckpt_to_initialize_from=checkpoint_path) est = tf.estimator.Estimator(model_fn=model_fn, warm_start_from=ws) </code></pr...
tensorflow
4
2,124
60,962,704
How do I check if a variable exists, inside a Function?
<p>I'm trying so check if a variable exists, but inside a function. I was taught that, to do this, the only thing you needed to do was:</p> <pre><code>'a' in locals() </code></pre> <p>Unfortunately, things turned out to be a little bit more difficult than I expected.</p> <p>I tried to define a function that include...
<p>You may test for the existence of your list <code>q</code> in the <code>globals()</code> dictionary, since it exists in global scope, not the local scope of your function <code>f</code>, i.e.:</p> <pre><code>def f(): print('q' in globals()) </code></pre> <p>As pointed out in the comments, testing the existence...
python|function|variables
0
2,125
49,494,889
Python WordNet Pandas
<p>I am trying to remove any word from a dataframe that is not in the nltk corpus, wordnet</p> <pre><code>dFrame['newtext'] = [' '.join([(i) for i in x.split()]) for x in dFrame['newtext'] if wn.synsets(i) == True] </code></pre> <p>I am checking each word to see if it exists in the corpus, and if it does then I want ...
<p>Try it like this:</p> <pre><code>dFrame['newtext'] = dFrame['newtext'].apply(lambda x: ' '.join([i for i in x.split(' ') if wn.synsets(i)])) </code></pre> <p>If you prefer your approach, then change it into this:</p> <pre><code>dFrame['newtext'] = [' '.join([(i) for i in x.split() if wn.synsets(i)]) for x in dFra...
python-3.x|pandas
1
2,126
49,524,395
How to use html GET request with bootstrap to get input values?
<p>I wrote an HTML code with the bootstrap library. Mainly, i want someone to go to this website, type in their info, and I store their inputs to do some internal analysis. After user enters his input, the url gets redirected to a 'search' url. My code is as follows:</p> <p>html</p> <pre><code>{% block content %} ...
<p>Actually, the correct answer is we need to include a name attribute:</p> <pre><code> &lt;input class="form-control" type="text" id="fname",name='fname'&gt; </code></pre> <p>and then it works!!</p>
html|django|python-3.x|django-views|bootstrap-4
1
2,127
49,468,929
Python/Pygame crash: attribute error
<p>This is code for a program I am writing that is supposed to be a card game. I have come across a crash, and running it through the debugger gives me an error I'm not sure I understand. I looked it up but don't really know what it means in the context of this code, thanks for your time!</p> <p>I am running this c...
<p>One reason why your game crashes is that you don't handle the events each frame and the operating system assumes the game has become unresponsive. You have to call one of the <a href="http://www.pygame.org/docs/ref/event.html" rel="nofollow noreferrer"><code>pygame.event</code></a> functions , for example <code>pyga...
python|debugging|attributes|pygame
0
2,128
62,726,164
List index out of range in loop
<p>Im getting an error for list index being out of range. Sorry if this is a stupid question.</p> <pre><code>def filter_list(l): for x in range(0, len(l)): if type(l[x]) is str: del l[x] return l </code></pre>
<p>You should not definitely change a <code>list</code> while iterating over it. It is very bad practise... it can lead to a whole lot of errors for you. Either you should create a <code>copy</code> of use something else, as list comprehension:</p> <pre><code>def filter_list(l): return [x for x in l if type(x) is n...
python|list|loops|indexing
0
2,129
70,193,404
How to get Beyond Compare exe full path using python?
<p>I am trying to find full path of Beyond Compare exe with following code. But both giving output as <code>None.</code></p> <pre><code>from shutil import which print(which('BCompare')) from distutils import spawn print(spawn.find_executable('BCompare')) </code></pre> <p>Expected ouput:</p> <pre><code>C:\Program Files...
<p>Since your Beyond Compare is installed in <code>C:\Program Files\Beyond Compare 4</code>, try this:</p> <pre><code>from os import environ from pathlib import Path location = r'C:\Program Files\Beyond Compare 4' dirs_on_path = [dir.strip('\\') for dir in environ['path'].split(';')] if location in dirs_on_path: ...
python|exe
0
2,130
53,580,544
Why do I get error while trying to build an architecture with multiple inputs in Keras?
<p>I am trying to build an architecture with multiple inputs in Keras. As mentioned in <a href="https://keras.io/getting-started/functional-api-guide/" rel="noreferrer">1</a>, I used similar code as followed:</p> <pre><code>model_merged = Model(inputs=[model_parts1, model_parts2, model_par...
<p>Keras functional api Model expects two positional arguments namely <code>inputs</code>, and <code>outputs</code>. The error</p> <blockquote> <p>TypeError: _init_subclassed_network() got an unexpected keyword argument 'inputs'</p> </blockquote> <p>is thrown when the output of the model is not specified.</p> <p...
python|tensorflow|keras
11
2,131
45,725,440
How can i obtain Camera Matrix in 3Dreconstruction?
<p>I want to achieve a 3D-reconstruction algorithm with sfm,</p> <p>But how should i set the parameters of the Camera Matrix?</p> <p>I have double cameras,both know their focal length.</p> <p>And how about Rotation Matrix and Translation Matrix from world view?</p> <p>i use python</p>
<p>You already have a code for camera calibration and printing a camera matrix in your OpenCV installation. Go to this path if you are on windows -</p> <p>C:\opencv\sources\samples\python</p> <p>There you have a file called calibrate</p>
python|opencv|matrix|camera|3d-reconstruction
1
2,132
54,831,907
Recursion in python not reaching correct result
<p>I have the a problem of wanting to find the number of ways a subset of a list will sum to specific value. However if i run the recursive formula by hand i get a different (correct) value, than with the python code. Am i missing something, or why am i getting different results?</p> <p>Assume i have a list <code>b = ...
<p>Here is your code with extra instrumentation to help track the output, indenting for recursive calls.</p> <p>You'll notice a critical problem with your counting: when you get the desired total and reach the end of the list, you return <code>0</code> instead of <code>1</code>. This prevents you from properly accumu...
python|python-3.x|recursion
3
2,133
55,012,558
How to read a specific paragraph from from multiple folders and files
<p>I have a list that contains directories and filenames that I want to open, read a paragraph from and save that paragraph to a list.</p> <p>The problem is that I don't know how to "filter" the paragraph out from the files and insert into my list.</p> <p>My code so far.</p> <pre><code>rr = [] file_list = [f for f i...
<p>You need to learn how your imported text is structured. How are the paragraphs segregated? does it look like '\n\n', could you split your text file on '\n\n' and return the index of the paragraph you want?</p> <pre><code>text = 'paragraph one text\n\nparagraph two text\n\nparagraph three text'.split('\n\n')[1] prin...
python
2
2,134
73,625,534
transfer custom plotfunction to plotly
<p>I am using the package <a href="https://riskfolio-lib.readthedocs.io/en/latest/plot.html" rel="nofollow noreferrer"><code>riskfolio-lib</code></a>. It allows you to do portfolio optimizations and plot all sorts of statistics for a portfolio of assets. As well as customized charts that I want to use in my <code>plotl...
<ul> <li>if you look at <strong>riskfolio-lib</strong> code on GitHub you can find the implementation of <code>plot_network()</code>. With only a little refactoring you can remove <strong>matplotlib</strong> code and return <code>pos</code> (positions of nodes) and <code>G</code> <strong>networkx</strong> graph</li> <...
python|graph|plotly|plotly-dash|portfolio
1
2,135
73,527,657
Separating element type with list from input
<p>Trying to separate int, string, float from the list and put them in their variable. It's easy to do with predefined list. I am trying to do with input list.</p> <pre><code>NumList = input(&quot;Enter string, int, float with the list : &quot;) #NumList = [1, 4.9, 4, &quot;Five&quot;, 6, 7, &quot;Eight&quot;, &quot;#...
<p>All input from</p> <pre><code>x = input(&quot;Enter input: &quot;) </code></pre> <p>is taken as a string unless otherwise specified. if you are wanting extract strings integers and floats from the list shown above you should use.</p> <pre><code>parsed_list = [i.strip(&quot;'&quot;) for i in input_list.split(&quot;,&...
python|list|input
0
2,136
12,711,211
Receiving 'error multiple values for index' in a simple DataFrame
<p>I have several lists that I'm trying to enter into a data frame:</p> <pre><code> mydates = [0, 6, 15, 21, 30, 37, 45, 53] prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8] mylist = [6.907894736842111, -2.461538461538464, -1.5772870662460567,4.807692307692319, 4.2813455657492305, 4.98533724340...
<pre><code>In [604]: d = {'dates' : mydates, 'prices': prices, 'mylist': mylist} In [605]: df= DataFrame(d) In [606]: print df dates mylist prices 0 0 6.907895 30.4 1 6 -2.461538 32.5 2 15 -1.577287 31.7 3 21 4.807692 31.2 4 30 4.281346 32.7 5 37 4.985337 34.1 6 ...
python|pandas|dataframe
1
2,137
13,032,220
How to validate a form all fields without knowing field names in html
<p>I want to validate a form where any field should not be blank. I don't know the name of the fields. The code is:</p> <pre><code> &lt;form action="/addproductgroupinsert_fun/" method="post" name="SForm" onsubmit="return validateForm()"&gt; {% for id in ProductTypefeatureentryList %} &lt;label for="{{id.Na...
<p>You can consider HTML-5 <code>data-val-*</code> attributes and have a look at jquery unobtrusive validation plugin. your inputs would look something like</p> <pre><code> &lt;form action="/addproductgroupinsert_fun/" method="post" name="SForm" onsubmit="return validateForm()"&gt; {% for id in ProductTypefeaturee...
python|django
0
2,138
24,932,931
PyLint 1.2.1 - AttributeError: 'Module' object has no attribute 'future_imports'
<p>I am using PyLint for years now and have just installed PyLint 1.2.1 on Python 2.7.6</p> <p>When I am running PyLint 1.2.1 (within PyScripter 2.5.3) on any Python script, I get error log:</p> <pre><code>Command line: D:\PROGRA~1\Python27\python.exe D:\PROGRA~1\Python27\Lib\site-packages\pylint-1.2.1-py2.7.egg\pyli...
<p>Upgrading astroid fixed this after a pylint upgrade</p> <pre><code>pip install --upgrade astroid </code></pre>
python|pylint
3
2,139
38,130,466
find random number using divide and conquer
<p>This is my first post to the community and I am still very new to coding. I was hoping to get some help on finding x in the following code using divide and conquer, it doesn't seem to work for me.</p> <pre><code>import random x= random.randint(1,1000) ##set range high = (1000) low = (1) while x != high: mid =...
<pre><code>mid = round(high//2, 0) </code></pre> <p>This doesn't look right to me. Shouldn't mid be the average of high and low?</p> <pre><code>mid = (high+low)//2 </code></pre>
python
1
2,140
31,160,282
ImportError: No module named comments.models
<p>I'm getting errors when using the new <code>django_comments</code> which <a href="http://django-contrib-comments.readthedocs.org/en/latest/porting.html" rel="nofollow">replaced</a> <code>django.contrib.comments</code>. Any ideas on how to get around this error?</p> <p>I'm installing the comment app <a href="https:/...
<p>Try this, I think you missed this: </p> <pre><code>pip install django-contrib-comments </code></pre> <p>and use latest code</p> <pre><code>from django.contrib.comments.models import Comment # old from django_comments.models import Comment # new </code></pre>
python|django
3
2,141
40,178,859
Nginx can't find some static files
<p>I can't figure out why nginx can't find some static files after deploying on a Digital Ocean. I think that I've set everything correctly. The collectstatic worked ok, it created <code>/project/static</code> directory with all static files.</p> <p>Maybe there is something wrong with <code>settings.py</code>:</p> <p...
<p>You should not use <code>alias</code> there. In nginx it works absolutle different from apache.</p> <p><a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#alias" rel="nofollow">http://nginx.org/en/docs/http/ngx_http_core_module.html#alias</a></p> <p>You should just use <code>root</code> instead.</p> ...
python|django|nginx
1
2,142
52,049,667
how to reindex panel data with MultiIndex
<p>i got a panel data,how can i get the dataframe without Multiindex,i try to do this</p> <pre><code>print k_data &lt;class 'pandas.core.panel.Panel'&gt; Dimensions: 6 (items) x 480 (major_axis) x 100 (minor_axis) Items axis: close to volume Major_axis axis: 2018-08-13 09:35:00 to 2018-08-24 15:00:00 Minor_axis axis: ...
<p>ok,i figure out the question</p> <p>use k_data.to_frame().reset_index() to reset like this:</p> <pre><code>df = k_data.to_frame().reset_index() print df major minor close high low money \ 0 2018-08-13 09:35:00 603105.XSHG 25.20 26.00 23.65 367025532.0 1 ...
pandas|dataframe|panel
-1
2,143
69,101,318
How to check if an argument is equal to the name of a class attribute and return it?
<p>Let's say we have the following function model_type:</p> <pre><code>import numpy as np import pandas as pd import sklearn as sk from sklearn.model_selection import train_test_split from sklearn.linear_model import * def model_type(linreg_model): for linreg_model in inspect.getmembers(sk.linear_model) re...
<p><strong>EDIT:</strong> Please note 'Bayesian' does not exist in sklearn.linear_model</p> <p>Example: (should work as is)</p> <pre class="lang-py prettyprint-override"><code>import inspect import sys from sklearn import linear_model def get_model(key): for x in inspect.getmembers(sys.modules['sklearn.linear_mod...
python|scikit-learn
0
2,144
68,920,845
How to multiply two rows in a 2d array?
<pre><code>table=[] rows=int(input(&quot;Enter number of rows: &quot;)) col=int(input(&quot;Enter number of columns: &quot;)) for i in range(rows): array=[] for i in range(col): array.append(int(input(&quot;Enter element row wise&quot;))) table.append(array) print(table) c=[] for a in range(rows): ...
<p>You can do the following, <code>zip</code>ping the first and last row:</p> <pre><code>table = [[2,4,7,8], [3,5,0,0], [1,2,3,0]] mult = [a*b for a, b in zip(table[0], table[-1])] table.append(mult) table # [[2, 4, 7, 8], [3, 5, 0, 0], [1, 2, 3, 0], [2, 8, 21, 0]] </code></pre>
python
1
2,145
63,326,857
Find common alphabets in multiple dictionaries - python
<p>I'm making the code returning character with given strings. I know it is easier to use when using the counter function but I'm trying not to use it.</p> <p>here is my code</p> <pre><code>class Solution: def commonChars(self, A): dic = {} for i in range(len(A)): A[i] = list(A[i]) ...
<p>Possible solution with <code>reduce</code>.only add one line:</p> <pre><code>from functools import reduce class Solution: def commonChars(self, A): dic = {} for i in range(len(A)): A[i] = list(A[i]) dic[i] = self.checkLetter(A[i]) print([char for char, count in r...
python|dictionary
7
2,146
63,393,996
Calculate the address of the subnet
<p>Calculate the address of the subnet:</p> <p>COMMAND: If you represent the host address and netmask as lists of 4 numbers each, you may take the bitwise AND of the first number from one list and the first number from the other list, followed by the bitwise AND of the second number from the one list and the bitwise AN...
<p>You can do this in one go by reading the <code>network</code> property of an <a href="https://docs.python.org/3/library/ipaddress.html#ipaddress.ip_interface" rel="nofollow noreferrer"><code>ipaddress.ip_interface</code></a></p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import ipaddress &gt;&gt;&g...
python
0
2,147
19,351,262
Read file with "variable=value" (Windows INI) format?
<p>I'm learning Python and as a starter developer I have few questions.</p> <p>I need read a file that have this format:</p> <pre><code># This is the text file [label1] method=auto [label2] variable1=value1 variable2=ae56d491-3847-4185-97a0-36063d53ff2c variable3=value3 </code></pre> <p>Now I have the following cod...
<p>Use the <a href="http://docs.python.org/2/library/configparser.html" rel="nofollow"><code>configparser</code> module</a> to handle this instead. That module parses this file format ( called the Windows INI format ) directly.</p> <pre><code>try: # Python 3 from configparser import ConfigParser except ImportE...
python|file
10
2,148
13,662,667
Sending GET requests for a Google reverse image search
<p>I'm trying to do a reverse image search and collect the the descriptions of the results. I've quickly run into a dead end:</p> <pre><code>import requests r = requests.get('http://www.google.com/searchbyimage?image_url=http://i.imgur.com/j3shP.jpg') r.text </code></pre> <p>Ideally I should be able to find Wikipedi...
<p>Interesting question. For some reason, this feature needs a User-Agent header and at least in my Firefox browser, it doesn't work. However, if you do this:</p> <pre><code>headers = {} headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17" r ...
python|image|search|reverse
3
2,149
43,561,717
How to install libraries for a program?
<p>I am making a game that use some 3rd party libraries and I want to know how can I make a setup to automatly install this requeriments or something like that (I don't know how this is called). <br/> My program needs this libraries: Tabulate 0.7.7 and Progress 1.2. <br/> How can I auto-install them and how can I auto-...
<p>To manage Python packages you can simply use <code>pip</code>. To install Tabulate for example you can open the Command Prompt or Terminal and type in <code>pip install tabulate</code>. For Progress 1.3 you can download the sources files <a href="https://pypi.python.org/pypi/progress" rel="nofollow noreferrer">here<...
python
1
2,150
43,631,344
What is the best way in Python to call the same function in separate threads?
<p>What is the best way to call same <em>function</em> in separate threads and have a separate list with returned values for each instance, without duplicating <em>function</em>?</p> <p>Example:</p> <pre><code>import threading def function(a): returned_values = [] ct = threading.currentThread() whil...
<p>Use ThreadPool</p> <p>Something like this </p> <pre><code>from multiprocessing.pool import ThreadPool pool = ThreadPool() pool.map(function, list_containing_args) </code></pre> <p>P.S <code>it works similar to multiprocess map.Each argument is given a new thread .You can specify the number of threads you want to...
python|python-2.7|python-multithreading
7
2,151
54,571,111
Sum Product using Django ORM
<p>I need to calculate the sumproduct of two fields from Django queryset.</p> <p>I have checked the answer in <a href="https://stackoverflow.com/questions/12165636/django-aggregation-summation-of-multiplication-of-two-fields">Django Aggregation: Summation of Multiplication of two fields</a> but it doesnt work. They s...
<p>Try something like this</p> <pre><code>from django.db.models import Sum, F MyModel.objects.filter(&lt;filters&gt;).aggregate(sum=Sum(F('field1')*F('field2')))["sum"] </code></pre>
python|django-models|django-queryset
3
2,152
9,448,631
What is wrong with my merge sort in python?
<p>I am trying to write merge sort and stuck here. </p> <p>What is the problem here with my code? I am trying to implement it without referring any resources and unnecessarily writing this line since some dumb rule in Stackoverflow forces to me explain my code.</p> <pre><code>def merge_sort(A): if len(A) &lt;= 1:...
<p>You merge_sort() function needs to </p> <pre><code>return result </code></pre> <p>at the end but it does not. Functions return None by default and this is why you get the error.</p>
python|mergesort
8
2,153
39,401,603
I don't understand this sentence
<p>I'm new to learning Python and I'm making a lot of questions these days. I tried to make a Bulls and Cows game, but I failed and then I searched on the internet for the code. I found this sentence and I don't know what it does:</p> <pre><code>while True: guess = raw_input('\nNext guess [%i]: ' % guesses).st...
<p>Typically, code in python needs complete itself on one line. If you would, instead, like to have line breaks to continue an expression to the next line (the most obvious reason being to increase readability) then you can insert a <code>\</code> at the end of the line. </p> <p>This tells python to treat the next lin...
python
1
2,154
39,152,675
retrieve expected key name when formatting a string with .format
<p>How can I retrieve the expected format key name from a string?</p> <p>Lets say I have:</p> <pre><code>"This string expects {expected}" </code></pre> <p>If I input the wrong key name python throws a KeyError showing the expected name.</p> <pre><code>"This string expects {expected}".format(whoops="wrong key") KeyE...
<p>You can use <a href="https://docs.python.org/3/library/string.html#string.Formatter.parse" rel="nofollow"><code>Formatter.parse</code></a> like that:</p> <pre><code>&gt;&gt;&gt; s="{a} {b} {c}" &gt;&gt;&gt; list(string.Formatter.parse("",s)) [('', 'a', '', None), (' ', 'b', '', None), (' ', 'c', '', None)] &gt;&gt;...
python|python-3.x|string-formatting
4
2,155
52,704,327
How to insert a 3d GLViewWidget into a window containing 2d PyQtGraph plots
<p>I am trying to port some plotting code from matplotlib to pyqtgraph for performance improvement. The pyqtgraph examples give separate examples of 2d plots and 3d plots, but I have not been able to find a sample of a 3d plot embedded as a subplot in a 2d plot window. I have tried embedding a GLViewWidget into a Graph...
<p>"the PlotWidget has more aggressive default settings because it inherits from QGraphicsView" - <a href="https://groups.google.com/forum/#!msg/pyqtgraph/mTlUfT0ozT8/OOMMK-D0HO4J" rel="nofollow noreferrer">source</a> I have yet to understand PyQT(Graph) and OpenGL, so I'm sorry I can't say much more, but these 3 lines...
python|matplotlib|opengl|pyqtgraph
2
2,156
65,991,011
Remove Background image opencv
<p>Please hold before downgrading the Question. I am not looking for a segmentation or detection algorithm/library.</p> <p>I have also seen this Post</p> <p><a href="https://stackoverflow.com/questions/42294109/remove-background-of-the-image-using-opencv-python">Remove background of the image using opencv Python</a></p...
<p>OpenCV background Subtractor models <a href="https://docs.opencv.org/3.4.0/db/d5c/tutorial_py_bg_subtraction.html" rel="nofollow noreferrer">Documentation</a></p> <p>After a lot of testing, Videos based MOG/MOG2 works better than single Image based background subtraction with KNN.</p> <p>This <a href="https://medium...
python|opencv
0
2,157
72,498,069
How to find the solution list with python string list manipulation
<p>I am looking for a way to find the expected output: Here we have both list contains strings. Please take a look at below input lists:</p> <pre><code>lst1 =[&quot;a: &quot;,&quot;b: &quot;,&quot;c:&quot;,&quot;d :&quot;] lst2 =[&quot; b:&quot;,&quot; a:&quot;,&quot;f:&quot;,&quot;g:&quot;,&quot;c: &quot;,&quot;d:&quo...
<p>Normally, I would recommend using <code>outputlst = list(set(lst1 + lst2))</code> but since there's a slight variation by whitespaces in two ends, you can probably create a list or set (<code>already_contained</code> in below code) to check if a string with trailing whitespaces removed and use it as a check to see i...
python|string|list
0
2,158
39,845,028
Pandas groupby - grouping users and counting the type of subscription
<p>I'm attempting to use pandas to group members, to count the number of subscription types that a member has purchased and get a total spent per member. Once loaded the data resembles:</p> <pre><code>df = Member Nbr Member Name-First Member Name-Last Date-Joined Member Type Amount Add...
<p>You can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html" rel="nofollow"><code>map</code></a> values of column <code>Member Type</code> by dict <code>d</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><...
python|pandas|group-by|pivot-table|reshape
2
2,159
16,062,804
numpy cov (covariance) function, what exactly does it compute?
<p>I assume <code>numpy.cov(X)</code> computes the sample covariance matrix as:</p> <pre><code>1/(N-1) * Sum (x_i - m)(x_i - m)^T (where m is the mean) </code></pre> <p>I.e sum of outer products. But nowhere in the documentation does it actually say this, it just says "Estimate a covariance matrix".</p> <p>Can anyo...
<p>As you can see looking at the <a href="https://github.com/numpy/numpy/blob/v1.7.0/numpy/lib/function_base.py#L1947" rel="nofollow">source</a>, in the simplest case with no masks, and <code>N</code> variables with <code>M</code> samples each, it returns the <code>(N, N)</code> covariance matrix calculated as:</p> <p...
python|numpy|statistics|scipy
3
2,160
31,823,822
Am I using "warnings" module right?
<p>I am using this to issue warnings while parsing a configuration file. All sorts of errors could happen while doing this - some fatal, some not. All those non-fatal errors should not interrupt the parsing, but they must not escape user's attention either. This is where the warnings module comes in.</p> <p>I am curre...
<p>When you are using <code>warnings</code> module, the second print is actually the stack, you can control what level you want to print using the <code>stacklevel</code> argument. Example -</p> <pre><code>import warnings def warn(): warnings.warn("Blah",stacklevel=2) warn() </code></pre> <p>This results -</p> ...
python|warnings
2
2,161
31,683,607
Can't find directory on Mac terminal
<p>I have an wordtangler document saved as <code>ex1.py</code> under a folder I named <code>lpthw</code>, but I can't open it using a terminal.</p> <p>I open the terminal and <code>cd</code> to the folder <code>lpthw</code>. Then, I write python <code>ex1.py</code>, but I get an error saying:</p> <pre><code>python: c...
<p>Try using <code>ls -a</code> to list the contents of the folder including hidden files.</p> <p>If there is still no results, the file is probably elsewhere and you can try to find it running <code>find . -name "ex1.py"</code> at your root folder.</p>
python|macos|terminal|notepad
1
2,162
31,961,312
Error while checking if a string contains an element from a list in Python?
<p>So I'm trying to use the any() function to search through a user inputted string and see if it contains any elements from a list:</p> <pre><code># takes the user input i = raw_input("&gt;&gt;&gt; ") e = i.lower() af.inp.append(e) # greeting section if any(x in e for x in af.x): af.greeting() </code></pre> <p>...
<p>If you wan to check for existence of your words in list <code>x</code> so you need to <strong>split</strong> your input then use <code>any</code> :</p> <pre><code>i = raw_input("&gt;&gt;&gt; ") e = i.lower().split() af.inp.append(e) # greeting section if any(x in e for x in af.x): af.greeting() </code></pre> ...
python|list|any
2
2,163
38,601,730
Programming on PySpark (local) vs. Python on Jupyter Notebook
<p>Recently I've been working a lot with pySpark, so I've been getting used to it's syntax, the different APIs and the HiveContext functions. Many times when I start working on a project I'm not fully aware of what its scope will be, or the size of the input data, so sometimes I end up requiring the full power of distr...
<p>I'm in a similar situation. We've done most of our development in Python (primarily Pandas) and now we're moving into Spark as our environment has matured to the point that we can use it. </p> <p>The biggest disadvantage I see to PySpark is when we have to perform operations across an entire DataFrame but PySpark d...
python|apache-spark|pyspark
0
2,164
38,922,632
Select pandas columns by several strings
<p>I have tried to select several rows of dataframe by specific partial string. </p> <p>The dataframe below is the original example data: </p> <pre><code>CODE DATA AA2016 47518 BB2016 47518 CC2014 47518 AA2014 47518 EE2015 47518 BB2015 47518 FF2016 47518 ...
<p>As @ayhan notes in the comment, you can use <code>df[df.CODE.str[0:2].isin(Select_list)]</code>.</p> <p>Alternatively, note that you can use regular expressions via <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>pd.Series.str.contains</code></a>:...
python|python-2.7|pandas|dataframe
1
2,165
32,408,355
Which format of scipy.sparse is best for this type of matrix generation and use?
<p>I have a data file that encodes information about nonzero elements of a large sparse boolean matrix. This matrix does not have any particular structure, i.e. it's not diagonal or block etc. Each row of the file determines one element. Right now I use the following loop to populate the matrix:</p> <pre><code>from sc...
<p>For incremental additions like this <code>dok</code> is as good as it gets. It is really a dictionary that stores the value at a tuple: <code>(iRow,iCol)</code>. So storing and fetching depends on the basic Python dictinary efficiency.</p> <p>The only one that is good for incremental additions is <code>lil</code>...
python|scipy|vectorization|sparse-matrix
2
2,166
32,425,811
Python understanding list comprehension from Java background
<p>I come from a Java background and <strong>just started to work on Python</strong>. Most of the things are fairly easy to pick up but I am having hard time to understand one thing in the language which I just found out that is called list comprehension. What is this <strong>list comprehension in Python</strong>? How ...
<blockquote> <p>What is this list comprehension in Python?</p> </blockquote> <p>First let’s start with the basic definition taken from the official Python documentation.</p> <p>A list comprehension consists of brackets containing an expression followed by a <code>for</code> clause, then zero or more <code>for</code...
python
6
2,167
54,931,167
Finding the column names of a pandas DataFrame where row values are minimum
<p>I have a DataFrame as below:</p> <pre><code>X = np.array([[1.0, -20, 200, 50], [2.0, 19, 100, 52], [3.0, 17, -150, 55], [4.0, 20, -120, 60], [5.0, 21, 119, 70], [6.0, -15, 134, -75], [7.0, 9, 178, -80], [8.0, 10, -190,...
<p>Use <code>DataFrame.idxmin</code> (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmin.html" rel="nofollow noreferrer">docs</a>):</p> <pre><code>df.idxmin(axis=1) </code></pre> <p>Equivalently you can use <code>np.argmin</code> in <code>df.apply(np.argmin, axis=1)</code>. Bu...
python|pandas|numpy
2
2,168
28,269,391
Scraping with Mechanize
<p>I'm having an issue where mechanize isn't producing the same response as a browser. I'm trying to scrape the price from this webpage which allows the addition of items to a basket using a prefilled url.</p> <p><a href="http://store.nike.com/us/services/jcartService?callback=nike_Cart_hanleJCartResponse&amp;action=a...
<p>Navigate to the main store page first so that you can be issued with the correct cookies. Then navigate to the required URL:</p> <pre><code>import mechanize store_url = 'http://store.nike.com' cart_url = 'http://store.nike.com/us/services/jcartService?callback=nike_Cart_hanleJCartResponse&amp;action=addItem&amp;la...
python|html|web-scraping|mechanize
1
2,169
44,186,626
Heroku error code H10n cant run app
<p>I'm using flask and python (2.7). I built an app that run no problem on localhost, but now it will not run on heroku.</p> <p>the error that im getting when i run heroku log --tail is: with running heroku restart:</p> <pre><code> 17-05-25T17:22:27.879428+00:00 heroku[web.1]: Starting process with command `pytho...
<p>In <code>project.py</code> I was missing the <code>import os</code> statement </p> <p>Issue resolved.</p>
python|heroku|flask
2
2,170
43,940,569
Return a pandas dataframe and invoke from main (Python)
<p>I have the following code for readVision.py:</p> <pre><code>import pandas as pd #Read csv files vision = pd.read_csv('path/vision.csv') vision = vision[vision['gaze_x'].notnull()] vision = vision[vision['gaze_y'].notnull()] vision = vision[vision['pupil_axis1'].notnull()] vision = vision[vision['pupil_axis1'].notnu...
<p>Try putting your code in readVision.py into a function, and then importing that function iside of main.py:</p> <pre><code># readVision.py def vision(path): vision = pd.read_csv(path) vision = vision[vision['gaze_x'].notnull()] vision = vision[vision['gaze_y'].notnull()] vision = vision[vision['pupil_axis1']...
python-2.7|pandas|program-entry-point
1
2,171
44,046,665
Python Watchdog Issue Not triggering Events for files saved by external software
<p>Does watchdog's "trigger event on file creation" depend on anything specific to how the files are created? I'm finding a discrepancy between when files are saved into a directory by an external program and when they are copied into the directory. </p> <p>I'm using watchdog to monitor a directory, trigger off new...
<p>Yes it does. Check how is the external program creating the file. In my case, the external program was creating a file with filename initiated with a '.' and ending with '.tmp' and when it is done writing to the temporary file it was moving it to actual filename which is ending with '.json'(for which I have set up t...
python|filesystems|inotify|watchdog|python-watchdog
1
2,172
43,928,229
pygame.mouse.get_pos() into two separate strings
<p>I'm using pygame and am using the code <em>pygame.mouse.get_pos()</em>, but need to turn this into two seperate strings: one where x = the x coordinate, and one where y = the y coordinate. Thanks for the help. </p>
<p>You can use map:</p> <p><code>x, y = map(str, pygame.mouse.get_pos())</code></p>
python|pygame|cursor|coordinates|python-3.2
1
2,173
13,959,470
for loops on text files
<p>I'm writing a huge code and one of the little things I need it to do is go over a text file that is divided to different lines. i need it to create a new list of lines every time the line is empty. for example if the text is: (each number is a new line)</p> <p>1 2 3 4</p> <p>5 6 3</p> <p>1 2</p> <p>it should bui...
<p>Ok, This should work now:</p> <pre><code>initial_list, temp_list = [], [] for line in open(filename): if line.strip() == '': initial_list.append(temp_list) temp_list = [] else: temp_list.append(line.strip()) if len(temp_list) &gt; 0: initial_list.append(temp_list) final_list = [item for item...
python|list|filenames
3
2,174
14,003,281
How can I convert a hex ASCII string to a signed integer
<p>Input = 'FFFF' # 4 ASCII F's</p> <p>desired result ... -1 as an integer</p> <p>code tried:</p> <pre><code>hexstring = 'FFFF' result = (int(hexstring,16)) print result #65535 </code></pre> <p>Result: 65535</p> <p>Nothing that I have tried seems to recognized that a 'FFFF' is a representation of ...
<p>Python converts FFFF at 'face value', to decimal 65535 </p> <pre><code>input = 'FFFF' val = int(input,16) # is 65535 </code></pre> <p>You want it interpreted as a 16-bit signed number. The code below will take the lower 16 bits of any number, and 'sign-extend', i.e. interpret as a 16-bit signed value and deliver t...
python|binary
10
2,175
27,186,182
Send a message to a current thread or end it in ZeroMQ with Publish/Subscribe pattern
<p>I am using ZeroMQ and a publish/subscribe pattern, in Python.</p> <p>The server sends a message, as follows:</p> <pre><code>ZMQsocket_Publisher.send(subscription_string) </code></pre> <p>which is received by a client, that, as consequence, starts a loop, like this:</p> <pre><code>loop_condition = True while loop...
<p>As I understood, you have something like this:</p> <pre><code>subscription_string = your_client_receiver_socket.recv() strings, data = some_processing(subscription_string) loop_condition = True while loop_condition: ZMQsocket_Pusher.send(strings, zmq.SNDMORE) ZMQsocket_Pusher.send(data) </code></pre> <p>If...
python|message-queue|infinite-loop|zeromq
1
2,176
8,261,535
Decrypt a a middle chunk of data using pycrypto AES or other algorithm
<p>I was looking for a way to use an encryption algorithm from pycrypto package that allows me to encrypt an original LARGE piece of data, and then decrypt only a MIDDLE chunk of this data. In other words, start decrypting the data at a certain offset, instead of starting to decrypt it at offset 0.</p> <p>I've tried A...
<p>You are using <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29" rel="nofollow">CBC (ciphertext block chaining)</a> mode, in which the message is split up into blocks and the output of one block used to encrypt the next. This is fundamentally a sequential operation...
python|pycrypto
2
2,177
185,378
Regular expression to match start of filename and filename extension
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py Ru...
<p>For a regular expression, you would use:</p> <pre><code>re.match(r'Run.*\.py$') </code></pre> <p>A quick explanation:</p> <ul> <li>. means match any character.</li> <li>* means match any repetition of the previous character (hence .* means any sequence of chars)</li> <li>\ is an escape to escape the explicit dot<...
python|sql|regex|sql-like
56
2,178
47,328,822
How can i get my program to remove from end of list instead of start in python
<pre><code>class Node: def __init__(self): self.data = None self.next = None class Stack: def __init__(self): self.size = 0 self.head = None self.tail = None def append(self, data): node = Node() node.data = data if not self.head: ...
<p>This seems to work, but i had to make some additional changes to your code</p> <pre><code>class Node: def __init__(self): self.data = None self.next = None class Stack: def __init__(self): self.size = 0 self.head = None self.tail = None def append(self, data): ...
python|stack
1
2,179
47,044,866
How to convert Python object to C++ type in Cython
<p>How can I convert a Python object argument in a Cython method defined using <code>def</code> to a C++ type? I am attempting to provide a Cython wrapper class for a C++ library, as described in the <a href="https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#create-cython-wrapper-class" rel=...
<p>I am afraid I have to say, the <code>foo and bar</code> is really a foolish example, have no idea what the C++ codes want to complete, no logic and no implementation. But I also made up such a foolish example based on yours, and made it work. It's tricky and buggy, hope that will help you a little.</p> <p>I use jup...
python|c++|cython
0
2,180
47,043,508
Set a date variable to SQL query in Python
<p>I want to do sql query in python. I could use cx_oracle to connection database in python:</p> <pre><code># Build connection conn_str = u'username/password@host:1521/sid' conn = cx_Oracle.connect(conn_str) </code></pre> <p>Now I'm trying to retrieve data from the database by using SQL query in Python:</p> <pre><co...
<p>Consider <a href="http://docs.sqlalchemy.org/en/latest/dialects/oracle.html" rel="nofollow noreferrer">SQLAlchemy</a> to connect pandas and use the <em>params</em> argument of <a href="http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_sql.html" rel="nofollow noreferrer"><code>pandas.read_sql</...
python|sql|datetime|cx-oracle|data-retrieval
0
2,181
38,017,022
Run your own python script in background
<p>I have my own python library which gets installed wide when I do this</p> <pre><code>python setup.py install </code></pre> <p>inside python project directory, it copies the executable file in bin also, but basically I am doing all this so, that it can be run as a service and I should be able to include it in upsta...
<p><code>&amp;</code> is used to run a process in the background. It's still very much attached to the terminal (<code>tty</code>) you run it from.</p> <p>These are the basic steps to making a process a daemon:</p> <ol> <li>Fork your process and kill its parent so that it becomes an orphan (handled directly by <code>...
linux|unix|python|monit
1
2,182
29,931,860
How do I make it so it goes to a new scene on keypress? (Pygame)
<p>I am very new and I cant seem to find any tutorials on how to do this. I would imagine it would be pretty simple. I am creating an Oregon Trail type game and I need it to go to the next picture when you press E, or quit the program when you press Q. </p> <p>Here is my code:</p> <pre><code># 1 - Import library imp...
<p>I think you are looking for something like this:</p> <pre><code># 1 - Import library import pygame from pygame.locals import * # 2 - Initialize the game pygame.init() width, height = 1000, 800 screen=pygame.display.set_mode((width, height)) # 3 - Load images background = pygame.image.load("start.png") # 4 - keep...
python|python-2.7|pygame|scene
0
2,183
29,852,007
Freezing with no error codes using non-standard library
<p>I'm doing some work with a MIDI controller called the Novation Launchpad that has a python module available to import and use.</p> <p>My code keeps getting stuck on the line <code>LP = launchpad.Launchpad()</code>. So here is how I've attempted to de-bug:</p> <pre><code>import launchpad print "I've started" LP = ...
<p>So, after finding a programme that would run with those commands, it became clear quickly that I hadn't initiated <code>pygame</code> and <code>pygame.midi</code>. </p> <pre><code>import pygame, pygame.midi, launchpad pygame.init() pygame.midi.init() print "I've started" LP = launchpad.Launchpad() LP.Open() print ...
python|midi|launchpad|pyportmidi
0
2,184
29,996,994
Improve String Comparison Time For Numpy Array
<p>Is there a faster way to get a Boolean array from string comparison than the following, all the strings in the array are unique:</p> <pre><code>myArray = np.random.rand(500000).astype('S18') toCompare = '0.166618892171' %timeit np.in1d(myArray, toCompare) 100 loops, best of 3: 6.62 ms per loop %timeit myArray == ...
<p>Just to clarify my comments.</p> <ol> <li>String comparison is never going to be faster than string comparison.</li> <li>If you are looking up many different strings, (and using pandas) then it may make sense to use these strings as an Index*.</li> </ol> <p><em>*An index uses klib hashtables under the hood so look...
python|performance|numpy
1
2,185
56,912,533
Decompression using gzip -d is ok, but wrong when using zlib in Python
<p>I had downloaded a .gz file and decompressed it successfully using 'gzip -d'. But it went wrong when I tried to decompress it using python zlib by chunk.</p> <pre><code>CHUNK = 1024 * 1024 infile = open('2019-07-06-13.log.gz') d = zlib.decompressobj(32 + zlib.MAX_WBITS) while True: chunk = infile.read(CHUNK) ...
<p><strong>Thanks for the hint from DavisHerring!</strong> The key problem is that the origin gz file is concatenated from multiple gz sub-files, making its decompression a little more complex.</p> <p><strong>Here's the solution:</strong></p> <pre><code> CHUNK = 1024 * 1024 infile = open('2019-07-06-13.log.gz') d =...
python|compression|gzip|zlib
2
2,186
65,521,610
Python - Obtain a full list of product combinations that satisfy a function to be > 0
<p>I have the following two number lists, one an amount and other a probability:</p> <pre><code>stake=[0,2,5,10,20,50,100] odds=[1,2,5,10,20,50,100] </code></pre> <p>I have created a class 'bet' which takes a certain number of variables and a '.payoff' method which is simply the product of each draw of stake and odds f...
<p>A naive solution just computes <em>all</em> the sums, then filters them.</p> <pre><code>from itertools import product def bet(s, o): return (bet1.payout(s,o) +1*bet2.payout(s,o) -2*bet3.payout(s,o) +3*bet4.payout(s,o) -1*bet5.payout(s,o) +1*bet6.payout(s,o)) def function...
python|function|object|product
2
2,187
37,035,013
Python Pandas to_csv method formatting
<p>I create a 2D matrix using PANDAS with the following code:</p> <pre><code>def constructTransition(originalList): st = np.ones((26, 26)) s1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] s2 = ['a', 'b', 'c', 'd', 'e', 'f', '...
<p>you can use:</p> <pre><code>pd.set_option('display.expand_frame_repr', False) pd.set_option('display.max_columns', 99) pd.set_option('display.float_format', '%.12f') </code></pre> <p>then just print your DF:</p> <pre><code>print(df) n [34]: stateProbability ut[34]: a b c ...
python|csv|pandas|dataframe|export-to-csv
1
2,188
20,223,456
Using Django markup in CSS
<p>So let us say I have loads of stylesheets on a Django site. CSS and JS files are under <code>static/</code> in either an app's directory or the global site directory (if it's a common file). I have different color themes going along with different pages, only changing some color values across stylesheets.</p> <p>In...
<p>You can use the <a href="http://www.w3schools.com/css/css_howto.asp" rel="nofollow">CSS property of cascading</a> to your advantage! Don't store colours in your stylesheet, you can specify them in your <code>&lt;head&gt;</code> style. For example:</p> <pre><code>&lt;head&gt; &lt;link rel="stylesheet" type="text/css...
python|django|css
3
2,189
20,202,757
Tried to guess R's HOME but no R command in the PATH. OsX 10.6
<p>I am trying to install rpy2 and I am facing a common issue. Unfortunately all the solution I have found are for win7</p> <p>I have installed a Python 2.7 and R 2.15. then I write on the terminal</p> <pre><code>easy_install rpy2 </code></pre> <p>or, alternatively </p> <pre><code>pip install rpy2 </code></pre> <p...
<p>Make sure you have R installed</p> <pre><code>brew install r </code></pre> <p>Then install rpy</p> <pre><code>pip install rpy2 </code></pre>
python|r|macos|rpy2
4
2,190
69,415,692
How to check if an online Excel file is in use by another user?
<p>I have a Microsoft Excel file on OneDrive. When my Python script saves anything to the file and the file is already open, OneDrive raises an error, telling me there is a sync issue.</p> <p>If the file is closed(not in use by another user), everything works great.</p> <p>Is there was a way to check if the file is cur...
<p>In case you have <code>sheet.xlsx</code> and someone has opened it, you should see <code>~$sheet.xlsx</code> file in the same directory.</p> <pre><code>-rw-r--r--@ 1 szymon szymon 9431 Oct 2 11:41 sheet.xlsx -rw-r--r--@ 1 szymon szymon 165 Oct 2 11:45 ~$sheet.xlsx </code></pre>
python|openxls
0
2,191
48,337,964
Django Beginner Forms, not able to get loop forms
<p>I have a model name Fightmma and a model named Fightmmacard. Commentform works for Fightcard but not for Fightmma. </p> <p>Each fightcard is made of fights. When I comment on any fight, the last fight on the card gets the comment.</p> <p>My Commentform looks for the content type and the id. I am not able to pass t...
<p>Added this to the views.py</p> <pre><code>fightform = [] for fight in fightcard initial_data = { "content_type": fight.get_content_type, "object_id": fight.id } Form[fight] = CommentForm(request.POST or None, initial=initial_data,) if form.is_valid(): ### same as before fight...
python|django|forms|django-templates|django-contenttypes
0
2,192
73,667,629
Iterative ffill with median values in a dataframe
<p>Appreciate any help on this. Let's say I have the following df with two columns:</p> <pre><code>col1 col2 NaN NaN 11 100 12 110 15 115 NaN NaN NaN NaN NaN NaN 9 142 12 144 NaN NaN NaN NaN NaN NaN 6 155 9 156 7 161 NaN NaN NaN NaN </code></pre> <p>I'd like to forward fill and replace t...
<p>Try:</p> <pre class="lang-py prettyprint-override"><code>m1 = (df.col1.isna() != df.col1.isna().shift(1)).cumsum() m2 = (df.col2.isna() != df.col2.isna().shift(1)).cumsum() df[&quot;col1&quot;] = df[&quot;col1&quot;].fillna( df.groupby(m1)[&quot;col1&quot;].transform(&quot;median&quot;).ffill() ) df[&quot;col2...
python|pandas|for-loop
1
2,193
64,461,493
I was using 'beeware'. While using briefcase create android i got the following permission error
<p>I used <code>briefcase create android</code> but it shows pemission error. I am using windows command prompt for all this. Can someone tell what can I do to resolve this error</p> <pre><code>Downloading OpenJDK8U-jdk_x64_windows_hotspot_8u242b08.zip... ################################################## 100% Installi...
<p>Hey dear try copying the file/folder From here: 'C:\Users\Alok\.briefcase\tools\jdk8u242-b08' To Here: 'C:\Users\Alok\.briefcase\tools\java' This might help you Thanks</p>
python|android|beeware
1
2,194
66,564,912
Execute an action based on how many times an element appears in a list
<p>I have a list :</p> <pre><code>CASE 1 : group_member = ['MEU1', 'MEU1','MEU2', 'MEU1','MEU1','MEU2','MEU1','MEU2','MEU1','MEU3'] CASE 2 : group_member = ['MEU1','MEU2','MEU3','None','None'] CASE 3 : group_member = ['MEU1','MEU2','MEU3','MEU1','CEU1'] </code></pre> <p>What I'm trying to do is insert a value in a t...
<p>I believe you should check if there's at least one item with a value greater or equal than 70, then send mail if there's no such value. This means you should check if you should send a mail after you go through the list.</p> <pre><code>from collections import Counter freqDict = Counter(group_member) size = len(gr...
python
1
2,195
64,152,428
Combining two different types of graphs in Holoviews using addition in Python
<p>I am trying to combine 2 different type of graph. Both the graphs have different x and y axis and that's how it should be. I have to send the plot in an combined way only. Below is what I tried and failed. Any workarounds?</p> <pre><code>import holoviews as hv import pandas as pd height_sub = 500 width_sub = 400 l...
<p><code>size</code> is not a style option for <code>hv.Curve</code> use <code>line_width</code> instead if you want thicker lines.</p> <pre><code>import holoviews as hv hv.extension(&quot;bokeh&quot;) height_sub = 500 width_sub = 400 linechart1 = hv.Curve([(1,2,'crust'), (3,4,'moon'), (4,9, 'mars')]) bubbled1 = hv.C...
python|pandas|holoviews
2
2,196
63,793,180
TensorFlow Checkpoint variables not saved
<p>I am trying to use <code>Checkpoint</code> for my model. Before that tried this with a toy example. This runs with no errors. But every time I run, looks like the training parameter starts from the initial value. Not sure if I am missing something here? Following is the code im using:</p> <pre><code>import numpy as...
<p><strong>What's the issue :</strong></p> <p>The main issue is that your <code>beta</code> variable is not trackable: it means that the checkpoint object will not save it. We can see that by inspecting the content of the checkpoint with the following function :</p> <pre class="lang-py prettyprint-override"><code>&gt;&...
python|tensorflow|tensorflow2.0|checkpoint
1
2,197
53,141,223
Problems with connection database
<p>when I run this program, it doesn't change the value in my database. Is it because something is wrong with the options section or is there the other problem? I don"t know what it is, I hope someone can help me with this.</p> <pre><code>import sqlite3 def product_kopen(crsr): print ("Which product would you lik...
<p>After you make changes to the database, you must <code>commit</code> them. <code>sqlite3</code> does not <code>commit</code> changes by default. Every time you do <code>cursor.execute(...)</code>, follow it up with a <code>cursor.commit()</code></p> <pre><code>crsr.execute(kopen) crsr.commit() </code></pre> <p>See...
python
0
2,198
71,847,079
Pandas "ValueError: columns overlap but no suffix specified" with .xlsx files but not with .txt files
<p>I get &quot;ValueError: columns overlap but no suffix specified&quot; when I run my code for .xlsx files but not for .txt files. The data in these two different filetypes are identical. The following works fine:</p> <pre><code>import os import pandas as pd path = r'C:\Users\Me\1Test' filelist = [] for root, dirs, f...
<p>I do not understand what you are trying to do, so i only can give some general tips.</p> <p>The given error raises, if you <code>join</code> dataframes which have one or more equal column names, so pandas can not distinguish them. And if i read your code correct you join <code>df</code> with itself, so there will be...
python|pandas|dataframe
1
2,199
71,891,938
Producing mean, mode. median for columns in python
<p>I'm trying to calculate mean median and mode for WEIGHT (column name) only for rows that have value of PET_AGE (column name) = 5</p> <p>I have the following line, but don't know how to extract the values from PET_AGE column that are exactly 5. Could you please help?</p> <p><code>output1 = weights.groupby(&quot;PET_A...
<p>You can try the following: (pet_age_5 is a DataFrame which contains the rows whose PET_AGE is 5)</p> <pre class="lang-py prettyprint-override"><code>pet_age_5 = weights[weights[&quot;PET_AGE&quot;] == 5][&quot;WEIGHT&quot;] mean = pet_age_5.mean() median = pet_age_5.median() mode = pet_age_5.mode() </code></pre>
python|pandas|dataframe|tkinter
0