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 |
|---|---|---|---|---|---|---|
6,800 | 5,994,297 | Could not load library "/usr/lib/pgsql/plpgsql.so" & undefined symbol: PinPortal | <p>I have been running Davical on a CentOS 5 box for a while now with no problems.</p>
<p>Yesterday however, I installed Trac bug-tracker which eventually forced me to run a full update via Yum which updated a whole heap of packages.</p>
<p>I cant seem to work out exactly what the issue is and time spent googling did... | <p>I have had this problem before, although with 8.4 instead of 8.1, but the issue is the same, I believe.</p>
<p>A recent minor upgrade of all supported maintenance branches of PostgreSQL introduced the function <code>PinPortal</code> in the server, and made PL/pgSQL use it. So if you use a <code>plpgsql.so</code> f... | python|postgresql|centos|trac | 8 |
6,801 | 6,180,272 | Emacs for Python programming: module/class outline/browser | <p>I am currently using <a href="https://github.com/fgallina/python.el" rel="noreferrer">https://github.com/fgallina/python.el</a> + ropemacs, but I am missing module browser: separate buffer that outlines names defined in the current module (list of classes with their methods). Google says that there are OO-browser an... | <p>I think <a href="http://ecb.sourceforge.net/" rel="noreferrer">ECB</a> (Emacs Code Browser) is worth a try. I don't use it all the time but it can be very handy. Especially useful is the "ECB Methods" window which displays an outline of all members of a module. </p>
<p>Here is a screenshot with the ECB Methods wind... | python|emacs|navigation | 8 |
6,802 | 67,932,403 | Python tkinter - How to reload label's image every second? | <p>I have an image (QR image) that i have to display it, and keep refreshing it every time. I tried many solutions but none worked, this is my code:</p>
<pre><code>def QRDisplayer():
global displayQR #I tried a tutorial wrote like this line, with it or without nothing changes
path = getcwd() + r"\temp\qr.... | <p>You have to keep a reference to the <code>PhotoImage</code> instance first, which you are not:</p>
<pre><code>def QRDisplayer():
global img
img = None
path = getcwd() + r"\temp\qr.png"
try:
img = PhotoImage(file=path)
except TclError: # Error that gets invoked with invalid fil... | python|tkinter | 1 |
6,803 | 30,446,649 | Problems while compiling Qt 5.4.1 using Visual Studio 2013 | <p>I am trying to build Qt, but can't solve an error coming up when I run 'nmake'.
I used this configuration:</p>
<pre><code>configure -prefix %CD%\qtbase -debug-and-release -qt-sql-sqlite -no-audio-backend -no-declarative -mp -nomake examples
</code></pre>
<p>These options are compatible with MITK.
My Python version... | <p>I had a similar issue - I resolved after finding a clue somewhere (can't find the link) about this. </p>
<p>IF you go into </p>
<pre><code>Qt\X.x\Src\qtwebengine\3rdparty\ninja
</code></pre>
<p>you will find a 'bootstrap.py'</p>
<p>I had to manually run boostrap.py. Then, you should be able to re-run 'nmake' a... | c++|visual-studio|qt|python-2.7|ninja | 1 |
6,804 | 66,723,875 | How to remove '/' from the string? | <p>I have a problem with the backslash. When the code executes numbers from the text file it looks like this 00744/,00474/ ...</p>
<p>And when I tried to float string into integer I got TypeErro: unsupported operand type(s) for +=: 'int' and 'str'.</p>
<p>How I can remove '/' from the numbers?
Thank you</p> | <p>If you have a string and want to remove chars at the end from it, you can use <code>str.rstrip()</code> with custom characters</p>
<pre><code>content = "123/"
print(content.rstrip("/")) # 123
content = "123=/"
print(content.rstrip("/")) # 123=
print(content.rstrip("... | python | 0 |
6,805 | 50,568,647 | How to join elements inside a tuple, in list of tuples? | <p>I have a list like</p>
<pre><code>A = [(1, 2, 3), (3, 4, 5), (3, 5, 7)]
</code></pre>
<p>and I want to turn it into</p>
<pre><code>A = [[123], [345], [357]]
</code></pre>
<p>Is there any way to do this?</p>
<p>My upper list with tuple comes from permutation function so maybe you can reccomend me to change some... | <p>You can swizzle that up like so:</p>
<h3>Code:</h3>
<pre><code>[[int(''.join(str(i) for i in x))] for x in a]
</code></pre>
<p>this converts the integer digits to a str, and then joins them before converting back to an integer.</p>
<h3>Test Code:</h3>
<pre><code>a = [(1, 2, 3), (3, 4, 5), (3, 5, 7)]
print([[int... | python|list-comprehension | 4 |
6,806 | 64,669,788 | How to sort a text file numerically while having the number imbedded into other strings | <p>Hi I'm looking for help with sorting my text file in numerical order, I have found <a href="https://stackoverflow.com/questions/62284908/how-to-sort-a-text-file-numerically">How to sort a text file numerically?</a> which shows me how to sort the numbers but in my text file I have the numbers in with other non numeri... | <p>The following should work, with the gived structure of your lines:</p>
<pre><code>with open('so.txt') as f:
l=f.readlines()
l[-1]=l[-1]+'\n'
with open('so.txt', 'w') as f:
for i in sorted(l, key=lambda x: x[x.find(' ')+1:x.find('pts')]):
f.write(i)
</code></pre>
<p>Output:</p>
<pre><code>Username5,... | python|sorting | 1 |
6,807 | 61,580,004 | i stuck with these error in django there all command work but if i want start server these error occur | <p>Unable to create process using 'C:\Users\Bunty Waghmare\Desktop\env_site\Scripts\python.exe manage.py runserver<a href="https://i.stack.imgur.com/Sfw9W.jpg" rel="nofollow noreferrer">enter image description here</a></p> | <p>there must be something wrong with the virtual environment you have made, like a directory is missing or things like that, please <a href="https://stackoverflow.com/questions/37220055/pip-fatal-error-in-launcher-unable-to-create-process-using">try these solutions</a>. i'm trying to give you a better clue by saying i... | python|django|networking|terminal | 0 |
6,808 | 58,077,672 | Python3 Relink issue while importing opencv | <h2>Question:</h2>
<p>I have a segmentation fault after trying to import a freshly compiled version of the latest available <a href="https://opencv.org/" rel="nofollow noreferrer">OpenCV</a> from <a href="https://github.com/opencv" rel="nofollow noreferrer">github</a> on Ubuntu 18.04.</p>
<p>Here is the error message I... | <p>This seems to be caused by version dependency issues.
I faced the same problem, Run the below command
<code>apt install python3-opencv</code></p>
<p>This will solve the problem.</p> | python-3.x|opencv|segmentation-fault | 12 |
6,809 | 56,347,686 | Pandas parse json column and and keep existing column into a new dataframe | <p>I have the following dataframe:</p>
<pre><code>name stats
smith {"eye_color": "brown", "height": 160, "weight": 76}
jones {"eye_color": "blue", "height": 170, "weight": 85}
will {"eye_color": "green", "height": 180, "weight": 94}
</code></pre>
<p>I use the following code to parse the json field into a new datafr... | <p>Use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html" rel="nofollow noreferrer"><code>df.join()</code></a>:</p>
<pre><code>new_df=df[['name']].join(df["stats"].apply(json.loads).apply(pd.Series))
</code></pre> | python|python-3.x|pandas | 2 |
6,810 | 56,099,492 | Pandas: How to avoid nested for loop | <p>I have some code that compares actual data to target data, where the actual data lives in one DataFrame and the target in another. I need to look up the target, bring it into the df with the actual data, and then compare the two. In the simplified example below, I have a set of products and a set of locations all wi... | <p>If the target dataframe is guaranteed to have unique locations, you can use a join to make this process really quick.</p>
<pre><code>import pandas as pd
import numpy as np
import time
employee_list = ['Joe', 'Bernie', 'Elizabeth', 'Kamala', 'Cory', 'Pete',
'Amy', 'Andrew', 'Beto', 'Jay', 'Kristen'... | python|pandas | 1 |
6,811 | 71,498,154 | Select item from a list like random.choice() does, but not randomly | <p>I know this might be a silly question. But on this <a href="https://github.com/Esri/workforce-scripts/blob/master/notebooks/examples/4%20-%20Optimally%20Creating%20and%20Assigning%20Work%20Orders%20Based%20on%20Routes.ipynb" rel="nofollow noreferrer">notebook</a> there is the following piece of code:</p>
<pre><code>... | <p>You have a few options for this.</p>
<p>List indexing:</p>
<pre><code>worker = workers[0]
del workers[0]
</code></pre>
<p><code>.pop()</code>:</p>
<pre><code>worker = workers.pop(0)
# pop removes item from list and assigns to worker
</code></pre>
<p><code>next()</code>:</p>
<pre><code>#convert list to iterator
w_ite... | python | 1 |
6,812 | 71,674,648 | Python Tkinter should use default directory, if I don't specify the directory | <p>I have the following program: <a href="https://i.stack.imgur.com/TgzXz.png" rel="nofollow noreferrer">https://i.stack.imgur.com/TgzXz.png</a>. Now if I press the Download Location Button, then it should download the song to the chosen directory, this works perfectly. But if I don't press the button, then it should u... | <p>you can assign destination as below and if destination doesn't changes it will take default destination.</p>
<pre><code>destination_source_new = ''
filename_url = "y2meta.com"
format = ".mp3"
space = filename_url + " "
hyphen = "- "
quality_file_320 = " (320 kbps)"
b... | python|file|tkinter|move|shutil | 0 |
6,813 | 69,480,350 | TypeError: Selector object is not iterable | <p>I am trying to run this practice scrapy code but it's continuously giving this error.
It is giving me error of AttributeError: Selector object is not iterable error</p>
<p>Here is code:</p>
<pre><code>from scrapy import Spider
class WikiSpider(Spider):
name = 'wiki'
allowed_domains = ['wikipedia.com']
... | <p>when you doing <code>Tabel=response.xpath('//table[contains(@class,"wikitable sortable")]')</code> it give you list of Selector but you selected first element with <code>[0]</code> at end of line<br>
that gives you a Selector because of that you get that exception</p>
<p>change<br><code>Tabel=response.xpat... | python-3.x|web-scraping|scrapy | 1 |
6,814 | 55,444,558 | implementing conv2d in fourier domain using einsum --> ValueError: einstein sum subscripts string contains too many subscripts for operand 0 | <p>According to the convolution theorem, convolution operation changes to pointwise multiplication in fourier domain -
here I have 'fft_x' of shape (batchsize, height, width, in_channels) which is the fft of input data
and similarly 'fft_kernel' of shape (height, width, in_channels, out_channels) which is fft of the ... | <p>I used tf.einsum instead of np.einsum, and it worked.</p> | python|numpy|tensorflow | 1 |
6,815 | 42,171,816 | How do template languages/engines like DTL and Jinja express and manage the relationships between various template files? | <p>I'm specifically using Django and Jinja2. This is my first foray into using templates without the help of a CMS to pick which ones and put them all together.</p>
<p>For some reason, I can't seem to comprehend how a bunch of pieces fit together.</p>
<p>I feel comfortable with these concepts:</p>
<ul>
<li>A templat... | <p>But these are not supported workflows. The only case that makes sense is a child extending a parent, and the child being sent to the template engine. </p>
<p>Any template can also include other templates directly, but that is not part of the inheritance chain.</p> | python|django|jinja2|templating|templating-engine | 0 |
6,816 | 42,353,153 | Django Creating A Team Function | <p>I want to design a simple app using Django. The design is as follows:</p>
<p>Each user has their own unique ID in the database called <code>id</code> which exists in the <code>auth_user</code> table already equipped with Django. Then I have a <code>Team_ID</code> which is another unique id that represents a team in... | <p>There are multiple way to engineer your problem, I'm gonna suggest one, but eventually you may adapt it to your need ( i don't know your project in dept )</p>
<pre><code>TeamMembership:
user1: user that send the request
user2: user that receive the request
status: here you can create a choice field where 1... | python|django|database|psql|invite | 0 |
6,817 | 42,267,128 | Extract multiple patterns from a text file and save it to a panda dataframe [python] | <p>my Text file looks like this</p>
<pre><code>Description: Text 1 follows <br/> blah blah blah Cause: Cause Text 1
follows here <br/>Description: Text 2 follows <br/> blah blah
blah Cause: Cause Text 2 follows here<br/>Description: Text 3 follows <br/>
blah blah blah Description: Text... | <p>Here's what I came up with.</p>
<pre><code>r"Description:(.*?)<br/>(?:(?!Cause)(?!Description).)*(?:Cause:(.*?)<br/>)?"
</code></pre>
<p>If you use this regex, which matches both a <code>Description</code> <em>and</em> an optional <code>Cause</code>, it will ensure the pairings of descriptions and caus... | python|regex|pandas | 0 |
6,818 | 53,980,189 | Printing dict Showing keyerror | <p>I'm new to PY.</p>
<p>I was reading a code and tried it locally.</p>
<pre><code>ta = 'aa'print('{{"test":"{}"}}'.format(ta))
</code></pre>
<p>While if I remove one pair of curly braces it throws me key error.</p>
<pre><code>ta = 'aa'print('{"test":"{}"}'.format(ta))
</code></pre>
<p>Resulting in</p>
<pre><code... | <p>When you using .format method it looks for a curly braces, which it replace with any values. If you want to print braces, but not replace it with any value you need to write double-braces. You can read about Python3 format methods more detailed in <a href="https://realpython.com/python-f-strings/" rel="nofollow nore... | python-3.x | 0 |
6,819 | 58,466,562 | Given a batch of n images, how to scalar multiply each image by a different scalar in tensorflow? | <p>Assume we have two TensorFlow tensors:
<code>input</code> and <code>weights</code>.</p>
<p><code>input</code> is a tensor of n images, say. So its shape is [n, H, W, C].
<code>weights</code> is a simple list of n scalar weights: <code>[w1 w2 ... wn]</code></p>
<p>The aim is to scalar-multiply each image by its c... | <p>Thanks to user zihaozhihao:</p>
<p>The answer is to change the shape of <code>weights</code> to (-1, 1, 1, 1) and then multiply it with <code>input</code>.</p>
<pre><code>weights = tf.reshape(weights, (-1, 1, 1, 1))
weighted_input = input * weights
</code></pre> | tensorflow | 1 |
6,820 | 58,402,219 | How to shift some values from one column to another in python / pandas? | <p>Some values are placed under wrong column in the dataset, which needs to be copied to some other column, so how to shift the values from one column to another. Images of the defected dataset and the expected output is given in the link below
Link to the images are given as
Dataset problem
<a href="https://imgur.co... | <p>The problem comes from the fact that pandas considers ; as a column separator. You should modify your data set.</p>
<p>If you can't do this here an example of what you're trying to do :</p>
<pre><code>df = pd.DataFrame({'Genres' : ['Art & Design', 'Art & Design'],'Last updated' : ['January 16', 'Pretend Pl... | python|pandas|dataframe | 0 |
6,821 | 45,434,781 | TensorFlow, when can Python-like negative indexing be used if ever? | <p>I'm new to TensorFlow (version 1.2), but not to Python or Numpy. I am building a model to predict the shape of a protein molecule. I need to wrap TensorFlow's standard tf.losses.cosine_distance function in some extra code, because I need to stop the propagation of some NaN values into the loss calculation.</p>
<p... | <p>It can be used with tensorflow's bindings to python slicing operators. So for example, <code>loss[-1]</code> is a valid slicing of <code>loss</code>.</p>
<p>In your case, if you have only three slices, you could assign them individually:</p>
<pre><code>update_op0 = indices[0,0,0].assign(updates[0])
update_op1 = in... | python|numpy|tensorflow | 0 |
6,822 | 28,503,419 | 'Unknown extension' in save function of PIL due to empty EXTENSION array | <p>I am rather new to python and have a problem with the <code>save</code> function of the Pillow fork of PIL.</p>
<p>With this minimal example</p>
<pre><code>import Image
im = Image.new("RGB", (200, 30), "#ddd")
im.save("image.png")
</code></pre>
<p>I get the following error:</p>
<pre><code>File "/usr/lib64/pytho... | <p>You need to write this instead:</p>
<pre class="lang-py prettyprint-override"><code>from PIL import Image # Notice the 'from PIL' at the start of the line
im = Image.new("RGB", (200, 30), "#ddd")
im.save("image.png")
</code></pre> | python|python-imaging-library|pillow | 14 |
6,823 | 68,652,597 | Sort words based on first letter in text file, python | <p>This is the function to read words from text file, sort these and then store in another text file.</p>
<pre><code>#file contains words
file=open('/content/gdrive/MyDrive/Post_OCR_Classifictaion/Dict_try.txt').read().split()
#sorting order based on letters
letters="abcçdefgğhıijklmnoöprsştuüvyz"
d={i:lette... | <p>Here</p>
<p><code>sorted_list=sorted(file,key=d.get)</code></p>
<p><code>file</code> is <code>list</code> of <em>words</em> whilst <code>d</code> is <code>dict</code> with keys being <em>letters</em>. You need first retrieve first letter of word then search for it in <code>dict</code>, for example using <code>lambda... | python | 3 |
6,824 | 57,031,208 | How to extract text from xml error message python | <p>I want to determine if the return from a beautifulsoup request looks like this.</p>
<pre><code>Out[32]:
<?xml version="1.0" encoding="utf-8"?>
<boardgames termsofuse="https://boardgamegeek.com/xmlapi/termsofuse">
<boardgame>
<error message="Item not found"/>
</boardgame>
</boardgam... | <p>Use the attribute <code>message</code> to get the value.If you to find the <code>error</code> tag first and then use the attribute <code>message</code></p>
<pre><code>from bs4 import BeautifulSoup
data='''<?xml version="1.0" encoding="utf-8"?>
<boardgames termsofuse="https://boardgamegeek.com/xmlapi/terms... | python|xml|beautifulsoup | 2 |
6,825 | 44,816,903 | Recursively find child items and list in jinja | <p>I'm trying to display "notes" in a nested list. Each note has a property called <code>parentID</code> that indicates a note that it is nested under.</p>
<p>Currently I am achieving a single level nest by doing this:</p>
<p><strong>models.py</strong></p>
<pre><code>class Note(Model):
title = CharField()
ta... | <p>In the example from the docs, I think that <code>item.children</code> is just an iterable of items of the same type. Then <code>{{ loop(item.children) }}</code> causes the current loop to be executed over the iterable <code>item.children</code> creating a nested list.</p>
<p>You can verify this:</p>
<pre><code>imp... | python|python-3.x|recursion|flask|jinja2 | 1 |
6,826 | 44,508,254 | Increasing memory limit in Python? | <p>I am currently using a function making extremely long dictionaries (used to compare DNA strings) and sometimes I'm getting MemoryError.
Is there a way to allot more memory to Python so it can deal with more data at once?</p> | <p>Python doesn’t limit memory usage on your program. It will allocate as much memory as your program needs until your computer is out of memory. The most you can do is reduce the limit to a fixed upper cap. That can be done with the <code>resource</code> module, but it isn't what you're looking for.</p>
<p>You'd need... | python|memory-management | 26 |
6,827 | 44,733,261 | Translating Pseudocode steps into Python algorithm | <p>I'm entirely new to programming and I'm supposed to turn pseudocode into a Python algorithm for a class assignment. I've tested mine algorithm (if you can even call it that) a few too many times and keep coming up with error messages. Any suggestions or resources that might be able to help would be greatly appreciat... | <p><code>input()</code> returns a string, thus your TypeError. You tried to multiply a string by a float.</p>
<p>Updated Code here:</p>
<pre><code>radius = 1.0
print("Enter value for radius : ")
radius = input()
print(type(radius))
Area = 3.14 * (float(radius) * float(radius))
print(Area)
</code></pre>
<p>Output... | python-3.x|input|pseudocode|area | 1 |
6,828 | 62,020,568 | Conditional return Query | <p>Why is the below program right? It checks if the list has <code>1,2,3</code> sequence present.
Now, should the <code>else</code> statement be not in indentation with <code>if</code> line, rather than <code>for</code> line. As soon as I put it under <code>if</code>, other tests of this program go wrong. Please help e... | <p>From here: <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops</a></p>
<h1>4.4. break and continue Statements, and e... | python|python-3.x | 0 |
6,829 | 24,255,035 | How to generate dictionary from two lists, keys with multiple values | <p>I have a series of jpgs that are photos of sites. For some sites I have more than one photo. I have unique IDs for each site. Each photo has a name like 'IDPhoto1', 'IDPhoto2', etc. I would like to isolate the unique IDs in one list and the full paths of the file in another, then generate a dictionary from the two l... | <pre><code>>>> list_of_unique_ids = ['IDPhoto1', 'IDPhoto2', 'IDPhoto3']
>>> list_of_corresponding_paths = [r'Path/To/Photo1', r'Path/To/Photo2', r'Path/To/Photo3']
>>> dictionary = dict(zip(list_of_unique_ids, list_of_corresponding_paths))
>>> print dictionary
{'IDPhoto3': 'Path/To/... | python|list|dictionary | 0 |
6,830 | 15,072,003 | Ubuntu - python2 and python3 coexist - installing library | <p>I have a silly problem. I wrote a simple application in Python3. I was testing it on my local machine with Windows and Python3 only so when I installed psutil everything worked just fine. However when I've sent it to the target system with Ubuntu problems started. There two instances of python on this machine: 2.7 a... | <p>Ok, I found the solution. So to install psutil for python3 you should:</p>
<ol>
<li>Download psutil sources from <a href="http://code.google.com/p/psutil/downloads/list" rel="nofollow">http://code.google.com/p/psutil/downloads/list</a></li>
<li>Extract tar file in some tmp directory</li>
<li>Open terminal and go to... | ubuntu|python-3.x|python-2.x|coexistence | 0 |
6,831 | 29,501,741 | WTForms not validating type | <p>I'm trying to use <code>wtforms</code> to check if the data in a dictionary is of the desired type. In the example below, I want to ensure that <code>some_field</code> in a dictionary is an integer. The documentation leads me to believe that if I use <code>IntegerField</code>, the data will be coerced to an integer,... | <p>Data needs to be passed to the form's <code>formdata</code> argument in order to force type coercion. In order to pass data to <code>formdata</code>, use a <code>MultiDict</code>.</p>
<pre><code>In [2]: from wtforms import Form, IntegerField, validators
In [3]: class Foo(Form):
...: some_field = IntegerFiel... | python|wtforms | 0 |
6,832 | 46,608,465 | What is inside SO file of Python library distribution? | <p>I <a href="http://usa.autodesk.com/adsk/servlet/pc/item?siteID=123112&id=10775847" rel="nofollow noreferrer">have a library</a>, which consists of 3 files which are intended to be put in site python directory.</p>
<pre><code>FbxCommon.py
fbxsip.so
fbx.so
</code></pre>
<p>Once these files are in place, Python can... | <p>.PYD files on Windows are .DLLs with a Python interface.</p>
<p>On Linux, both of these use .SO as the extension. So your files are probably Linux binaries with the Python interface (init function etc.), which is why they can be simply imported by Python, without using ctypes or something similar.</p>
<p>When comp... | linux|python-3.x|binaryfiles|dynamic-linking | 6 |
6,833 | 46,245,957 | How to assign ordinal numbers of unique values to a list in Python? | <p>Suppose I have a list</p>
<pre><code>A = ['A', 'A', 'A', 'B', 'B', 'C']
</code></pre>
<p>How to turn it to </p>
<pre><code>B = [0, 0, 0, 1, 1, 2]
</code></pre>
<p>?</p>
<p>I wrote this way</p>
<pre><code>C = {t[1]:t[0] for t in enumerate(list(set(A)))}
B = [C[e] for e in A]
</code></pre>
<p>and it gave</p>
<... | <p>I will assume that: 1. you don't rely on elements being letters; 2. you want to index them on the base on the first appearence in the list <code>A</code>.</p>
<pre><code>>>> A = ['A', 'A', 'A', 'B', 'B', 'C']
>>> seen=set()
>>> C={x:len(seen)-1 for x in A if not (x in seen or seen.add(x))... | python|list|unique | 2 |
6,834 | 21,272,480 | Does nitrous.io support the endpoint library? | <p>Developing a python project on the platform and attempting <a href="https://developers.google.com/appengine/docs/python/endpoints/getstarted/backend/write_api" rel="nofollow">appengine endpoints</a>.</p>
<p><code>import endpoints</code> throws <code>google.appengine.api.yaml_errors.EventError: the library "endpoint... | <ol>
<li><p>Start with a non-python project.</p></li>
<li><p>Download appengine for Linux python:</p>
<p><code>
curl -O http://googleappengine.googlecode.com/files/google_appengine_1.8.9.zip
</code></p></li>
<li><p>Unzip and export directory in <code>~/.bash_profile</code>:</p>
<p><code>
export PATH="$HOME/google_app... | python|google-app-engine|nitrousio | 0 |
6,835 | 62,820,601 | flask_login always returning 401 unauthorized | <p>I'm having issues with flask_login. But while testing I realized that I was getting 401 unauthorized error when I request a login_required route. I made sure I logged in.</p>
<p>Any help appreciated. thanks!</p>
<p>Here is my login function:</p>
<pre class="lang-py prettyprint-override"><code>@app.route('/login', me... | <p>My issue was that I wasn't storing a cookie in request.
By making request.Session, I was able to make it work.</p>
<pre><code>s = request.Session()
>>> print(s.post(url+"login", data={"id":"test", "password":"1"}).content)
>>> print(requests.get(url... | python|authentication|flask|flask-login | 1 |
6,836 | 70,161,635 | PCA to select features for Linear regression in Pipeline | <p>I have a dataset with some numeric and categorical variables. I tried to preprocess categorical variables with pandas dummies in order to scale the data with StandardScaler. However, some columns also have missing values (mostly categorical) so I used imputer in the pipeline though it still generates the error:</p>
... | <p>you can access the pca by pipeline.named_steps['PCA']</p>
<p>I fixed the errors in the pipeline for imputer</p>
<p>Only get dummies the category columns
df_cat=pd.get_dummies(df[cat_columns]) X=pd.concat(Df_numeric, df_cat, axis=1)</p>
<pre><code> df=pd.read_csv('https://raw.githubusercontent.com/eric-b... | python|pandas|scikit-learn | -1 |
6,837 | 53,451,241 | program checking for password strength (and/or operators aren't working/checking for symbols in a string?) | <p>I am making a password program that checks for the strength of a password according to its length and how many uppercase /lowercase letters, numbers, and symbols there are. </p>
<p>The following is the program that I have so far, however whenever I enter a password that should be returned as 'medium', it doesn't wo... | <p>Welcome to Stack Overflow Aidyn. There are a few problems that I see with your code.</p>
<hr>
<p>The condition</p>
<pre><code>password.lower()== password and password.upper()==password or password.isalnum()==password
</code></pre>
<p>won't ever happen. The first part <code>password.lower()== password</code> chec... | python|python-3.x|passwords | 0 |
6,838 | 53,487,246 | Python- Print Specific Object List Attribute | <p>How do I print a specific object attribute from a list of objects. I was thinking I could provide the specific list index but I get the following error when I try that: <code>AttributeError: 'list' object has no attribute 'grade'</code></p>
<pre><code>class tests():
def __init__(self,grade):
self.grad... | <p>You have some bugs here.</p>
<pre><code>class tests():
def __init__(self,grade):
self.grade = grade
test_list = []
for x in range(1,6):
test_object = tests(x)
test_list.append(test_object)
list_a = [5,3,2,1,4]
# THIS LINE BELOW IS THE PROBLEM
for x in [test_list]:
# in this line b... | python|oop | 0 |
6,839 | 53,610,035 | Slicing a python list over step | <p>I have a list that I acquired parsing a text file(delimeted by \t and \n) which I eventually have to import into a database:</p>
<pre><code>list = ['1', '1', 'Thurs', '1', 'Snow', '1', 'Rockville', 'Basic', 'Medium',
'1', 'Smith, J.', 'Junior', '5', '1', 'Chicken Noodle', 'Progresso',
'Canned', 'Basic', '1', 'Rad... | <p>I am not sure what you mean with <code>slice 4-5 items with a step of 23</code>, but maybe this solves your problem</p>
<p>code:</p>
<pre><code>import numpy as np
list=np.arange(100).tolist()
print('input list')
print(list)
print('\nyour slices, if this is what you want')
for ii in range(len(list)//23):
prin... | python|parsing|slice | 0 |
6,840 | 54,793,539 | pybind11 modify numpy array from C++ | <p>EDIT: It works now, I do not know why. Don't think I changed anything</p>
<p>I want to pass in and modify a large numpy array with pybind11. Because it's large I want to avoid copying it and returning a new one. </p>
<p>Here's the code:</p>
<pre><code>#include <pybind11/pybind11.h>
#include <pybind11/stl... | <p>I just had the same problem. If, from Python, you pass a numpy array of the type matching the C++ argument then no conversion happens, and you can modify the data in-place i.e. for <code>py::array_t<float></code> argument pass in a numpy <code>np.float32</code> array. If you happen to pass in a <code>np.float6... | python|pybind11 | 11 |
6,841 | 55,071,264 | `requests.post` not connecting correctly | <p>I have a model I am trying to connect to in R. I open the model by running;</p>
<pre><code>> library(plumber)
> r <- plumb("deploy_ml_credit_model.R")
Warning message:
In readLines(file) :
incomplete final line found on 'deploy_ml_credit_model.R'
> r$run(swagger = FALSE)
Starting server to listen on p... | <p>You have very weird quotes in the string</p>
<pre><code>“http://127.0.0.1:3582”
</code></pre>
<p>– they should just be straight quotes:</p>
<pre><code>"http://127.0.0.1:3582"
</code></pre> | python|curl | 2 |
6,842 | 21,807,660 | Failed to load OpenCL runtime in OpenCV for Python | <p>I am trying to run the first example <a href="http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="nofollow">here</a>, but I am getting this error. I am using Ubuntu 13.10. </p>
<pre><code>Failed to load OpenCL runtime
OpenCV Error: Unknown error ... | <p>As for the OpenCL failure, try installing required packages:</p>
<p><code>sudo apt-get install ocl-icd-opencl-dev</code></p>
<p>Worked for me. My guess is that OCL is a part of the <code>opencv_core</code> module, and if it failed to initialise, then many other components might behave strange.</p> | python|opencv|ubuntu|opencl | 14 |
6,843 | 21,516,027 | Running code in PyCharm's console | <p>Are there any smooth way to run Python scripts in the PyCharm's console?</p>
<p>My previous IDE - PyScripter - provides me with that nice little feature. As far as I know PyCharm has 2 ways of running script in console:
1) Select a bunch of code and press <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>E</kbd>.
2) Save the cod... | <p>In the Run/Debug Configuration, add -i to the interpreter options. This will stop it from closing a python session even after a successful run. I.e. you will be able to see all the variable contents</p> | python|pycharm|pyscripter | 28 |
6,844 | 24,813,139 | Python: How to write to a file and continuously monitor it's file size changes? | <p>I have a python script, which has a method called <code>produce_output(input)</code> to generate an output file after running a long running process that's hard to predict how long it will take. Sometimes the process will hang (due to memory or bad input).</p>
<p>In the same script, I want to create a method <code>... | <p>Assuming only the script is writing to the file, you can simply monitor the time since you last wrote something to the file:</p>
<pre><code>import signal, time
# Set time limit to 5 minutes.
time_limit = 300
class TimeoutException(Exception):
pass
# Create signal countdown.
def signal_handler(signum, frame)... | python|celery | 1 |
6,845 | 41,214,390 | On creating new dictionaries in python: Using for_loops vs using deepcopy() | <p>I just learnt how to build a dictionary out of another dictionary by using a for-loop.</p>
<p>But i can achieve the same using a deep-copy function. And <code>deep-copy()</code> seems to save time and is shorter.</p>
<p>Is there any disadvantage in using deep-copy.</p> | <p>Deep copy is functionally different from using a for loop, which gives a shallow copy. If a dictionary contains any mutable objects, for example, lists, as values, then changing an element in a list changes the corresponding element in a shallow copy, but not in deep:</p>
<pre><code>dic = {'1': [0, 1]}
shallow_copy... | python|python-3.x | 1 |
6,846 | 30,830,156 | Specific Android Bluetooth Server issue | <p>I have a very particular Android Bluetooth issue:</p>
<p>I have a device (with almost no documentation) that acts as a Bluetooth Client and tries to connect (after pairing) to a Bluetooth Server that listens using the UUID "1234". I have tested in advance using a python script, that the device works and that it con... | <p>By the off chance that someone else runs into this type of issue, it turns out the Bluetooth Client device was only connecting to the server if it had a certain <a href="http://developer.android.com/reference/android/bluetooth/BluetoothClass.Device.html" rel="nofollow">bluetooth device class</a>, which was evidently... | android|python|bluetooth | 0 |
6,847 | 40,021,384 | How to access the next iteration of a for loop | <p>I have dictionary which I'm looping through. I want to say that if a value == a certain number (0 in this case) then the value of the next iteration of the for loop will be 2x that value. </p>
<p>I have a dictionary like the following:</p>
<pre><code>d = {'a' : 1, 'b' : 0, 'c' : 4}
</code></pre>
<p>When I loop th... | <p>You can use <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow">orderedDict</a> to have a dictionary and keep your order. </p>
<p>Looking at your algorithm, you are adding 1 to all values if it is not zero and if it is zero, you multiply the next item first, then add... | python-3.x|for-loop|dictionary | 2 |
6,848 | 40,140,892 | Java like function getLeastSignificantBits() & getMostSignificantBits in Python? | <p>Can someone please help me out in forming an easy function to extract the leastSignificant & mostSignificant bits in Python?</p>
<p>Ex code in Java:</p>
<pre><code>UUID u = UUID.fromString('a316b044-0157-1000-efe6-40fc5d2f0036');
long leastSignificantBits = u.getLeastSignificantBits();
private UUID(byte[] dat... | <p>Old post but still... Just thought I'd add this:</p>
<pre><code>import struct
import uuid
u = uuid.UUID('c88524da-d88f-11e9-9185-f85971a9ba7d')
msb, lsb = struct.unpack(">qq", u.bytes)
</code></pre>
<p>This give the values:<br>
(-3997748571866721815, -7960683703264757123)
... and if I input those into the ... | python|bitmap|bit | 4 |
6,849 | 40,011,373 | Installing python 3 for a specific environment | <p>I have <code>python 2.7.10</code> installed on my <code>mac</code>.</p>
<p>but I happen to need <code>Python 3</code> to use a <code>python wrapper</code> for a given <code>API</code>.</p>
<p>this is my folder structure:</p>
<pre><code>apps/
myapp/
app.py
gracenote/
pygn.py
</... | <p>You'll need to install both versions of python at the same time</p>
<pre><code>$ which python3 # copy the output of this command
$ mkvirtualenv --python=/path/to/python3 ~/.virtualenvs/{your env name}
$ workon {your env name}
</code></pre> | python|python-2.7|python-3.x|development-environment | 0 |
6,850 | 29,159,218 | Find the mode of a list of numbers in python | <pre><code>dictionary={}
list=[1,1,2,3,3,4,5]
maximum=0
for values in list:
if values in dictionary:
dictionary[values]+=1
else:
dictionary[values]=1
if not maximum or dictionary[values]>maximum[0]:
maximum=(values,dictionary[values])
mode=maximum[0]
print("Mode:",mode)
</code></pre>
<p>Output:3</... | <p>You are basically reinventing the built-in <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>.</p>
<pre><code>In [3]: my_list = [1, 1, 2, 3, 3, 4, 5]
In [4]: from collections import Counter
In [5]: counter = Counter(my_list)
In [6]... | python|python-3.x | 3 |
6,851 | 52,190,821 | Aligning objects to bottom of sizers in wxPython | <p>I've been trying to add a button to the bottom of a sizer for a while and cant seem to get it to work right. Ive provided the code from my design along with a badly designed ascii layout. I want the back button to be in the bottom left corner of my frame. </p>
<pre><code> ---------------------------------
| ... | <p>Aligning items in box sizers only works in the direction transversal to the sizer primary direction. So using <code>ALIGN_BOTTOM</code> in a <code>VERTICAL</code> sizer <code>SplitSizer</code> doesn't make sense (and in wxWidgets 3.1+ you will get an assertion failure explaining this to you).</p>
<p>Instead, you ne... | python|wxwidgets|wxpython | 2 |
6,852 | 51,730,802 | How to add a text inside rectangle? | <p>I defined the class of the objects <code>fences</code> as follows:</p>
<pre><code>class GeoFence(pygame.sprite.Sprite):
def __init__(self, rect, risk_level, *groups):
self._layer = 1
pygame.sprite.Sprite.__init__(self, groups)
self.image = pygame.surface.Surface((rect.width, rect.height)... | <p>The problem is that you're blitting the text at the coordinates <code>(200, 100)</code> of the <code>screen</code> surface when the sprites are created, so the text will disappear when the screen gets cleared in the next frame. </p>
<p>In order to blit the text on the <code>GeoFence</code> objects, you need to blit... | python|pygame | 1 |
6,853 | 18,937,338 | Python sys.stdin.read(max) blocks until max is read (if max>=0), blocks until EOF else, but select indicates there is data to be read | <p>My problem is:</p>
<p><code>select</code> indicates that there is data to be read, I want to read whatever is there, I do not want to wait for a <code>max</code> amount to be present. if <code>max</code> <= 0 then read waits until EOF is encountered, if <code>max</code>>0 read blocks until <code>max</code> bytes... | <p>In <code>os</code> module there is <a href="http://docs.python.org/2/library/os.html#os.read" rel="noreferrer"><code>os.read</code></a> function that allows lower level control over reading from file descriptor. It is nonblocking as long as there is at least a byte ready to read.</p>
<blockquote>
<pre><code>os.read... | python|file|file-io | 5 |
6,854 | 63,610,935 | Python KeyError: 'destinationAccount' | <p>i've code with the following structure from a website i'm <strong>scraping</strong> data:</p>
<pre><code>destinationAccount:
ownerBuilding: ( collapse to destinationAccount)
label: ( collapse to ownerBuilding )
_id: ( collapse to ownerBuilding )
vban: ( collapse to destinationAccount)
_id: ( collapse to... | <p>Difficult without seeing the full list but I suspect some of the items are missing the key. Have you tried a check on the key existing. Using your example:</p>
<pre><code>transaction = {
"_id":"CENSORED",
"uuid":"CENSORED",
"amount":11.8421,
"taxAm... | python|web-scraping|python-requests | 1 |
6,855 | 36,439,063 | python 3.5 scikit-learn developer version error: Unable to find vcvarsall.bat VS 2015 | <p>I need to install the latest version of scikit-learn, so i use version from GitHub with command </p>
<pre><code>python setup.py install --user
</code></pre>
<p>instead of compiled version from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn" rel="nofollow noreferrer">http://www.lfd.uci.edu/~gohlke... | <p>The answer is connected with this <a href="https://stackoverflow.com/a/35243904/3618344">issue</a>, my fault was that I downloaded <a href="https://www.microsoft.com/ru-ru/download/details.aspx?id=48145" rel="nofollow noreferrer">C++ Common Tools </a> as a separate package, but you need to reinstall VS and select "C... | python|scikit-learn|python-3.5 | 1 |
6,856 | 19,360,323 | In web.py, How to 301 redirect to another domain? | <p>Function seeother() and redirect() in web.py is no use. I try to use<br>
<code>web.header('Location', 'www.google.com')</code><br>
<code>web.header('status', '301')</code><br>
or<br>
<code>web.HTTPError('301', {'Location': 'www.google.com'})</code><br>
but still redirect to:<br>
<code>http://127.0.0.... | <p>Use:</p>
<pre><code>web.HTTPError('301', {'Location': 'http://www.google.com'})
</code></pre>
<p>Note that you must put <code>http://</code> to denote an absolute URL.</p> | python|http|web|web.py | 1 |
6,857 | 19,435,223 | XPath not working in Scrapy | <p>I have the following XPath that I am trying to extract data from:</p>
<pre><code>/html/body/div[2]/div[2]/div/div/div[4]/ul[2]/li/div
</code></pre>
<p>I am trying to simply test this through Scrapy Shell, so I do the following:</p>
<pre><code>scrapy shell "https://www.rentler.com/listing/520583"
</code></pre>
<p... | <p>I solved this. To access the individual items above, you simply add li[1],li[2], etc.</p> | python|xpath|web-scraping|scrapy | 1 |
6,858 | 13,664,129 | Plotting Pearson Correlation Coefficient with matplotlib | <p>I've been able to use the pearsonr function in sciPy to get the correlation coefficient and now want to plot the result onto a scatter plot using matplotlib.</p>
<p>I looked through the doc's but can't see anything to help with this.</p>
<p>What would be the best way to achieve this.</p>
<p>I'm not a mathematici... | <p>matplotlib.org has several examples. Here's how you'd get started with your data: </p>
<pre><code>import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
x = [50,500,1500,2500];
y = [72,414,1,13]
ax1.plot(x, y, 'bo')
plt.show()
</code></pre>
<p>And here's a link to the most basic example available:
<a href="ht... | python|matplotlib|statistics|scipy | -2 |
6,859 | 13,484,740 | What are exceptions in Python? | <p>I've read three beginner-level Python books, however, I still don't understand exceptions.</p>
<p>Could someone give me a high level explanation?</p>
<p>I guess I understand that exceptions are errors in code or process that cause the code to stop working.</p> | <p>In the old days, when people wrote in assembly language or C, every time you called a function that might fail, you had to check whether it succeeded. So you'd have code like this:</p>
<pre><code>def countlines(path):
f = open(path, 'r')
if not f:
print("Couldn't open", path)
return None
... | python | 3 |
6,860 | 16,849,996 | memory leak in matplotlib histogram | <p>Running the following code will result in memory usage rapidly creeping up. </p>
<pre><code>import numpy as np
import pylab as p
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(100000)
for i in range(100):
n, bins, patches = p.hist(x, 5000)
</code></pre>
<p>However, when substituting the call to pylab with ... | <p>Matplotlib generates a diagram. NumPy does not. Add <code>p.show()</code> to your first code to see where the work goes.</p>
<pre><code>import numpy as np
import pylab as p
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(100000)
n, bins, patches = p.hist(x, 5000)
p.show()
</code></pre>
<p>You may want to try wi... | python|memory-leaks|numpy|matplotlib|histogram | 2 |
6,861 | 43,855,580 | Pyplot hist sum of bin counts is not equal to number of elements | <p>I'm using pyplot to plot histogram, and found that the sum of bin counts is not equal to the total sum of elements. Where could be possible errors here?</p>
<pre><code>data = [1.272499, 1.3480160000000001, 1.42106, 1.431921, 0.95531699999999997, 1.167071, 1.2155849999999999, 0.716526, 1.356554]
n, bins, patches = ... | <p>The highest histogram bin ends at 1.4, so the two values higher than 1.4 are not included. You should use <code>np.arange(-0.2, 1.8, 0.2)</code> instead. This produces the array <code>[-0.2 0. 0.2 0.4 0.6 0.8 1. 1.2 1.4 1.6]</code>, and your assertion will be <code>True</code>.</p> | python|matplotlib | 2 |
6,862 | 54,658,044 | PyQt5 context menu for QTableWidget column head | <p>is there a way to get a context menu on a tables column head.</p>
<p>Find nothing about that in PyQt5's tuts.</p>
<p>the table's context menu is simple but the column heads don't affect.</p>
<pre><code># dlg is a QDialog object
self.tbl = QtWidgets.QTableWidget(dlg)
self.tbl.setContextMenuPolicy( Qt.CustomContext... | <p>You need to set the context menu policy on the header itself (if I've understood correctly), so...</p>
<pre><code>self.tbl = QtWidgets.QTableWidget(dlg)
self.tbl.horizontalHeader().setContextMenuPolicy(Qt.CustomContextMenu)
</code></pre>
<p>and connect to the <a href="https://doc.qt.io/qt-5/qwidget.html#customCont... | python|pyqt|pyqt5|qtablewidget|qmenu | 2 |
6,863 | 54,517,556 | Need to remove all the character after ":" and "-" | <p>I have two string with the following structure.</p>
<pre><code>1 ABCD: PQRS XYZ
2 qwerty-asd zxc
</code></pre>
<p>I need to remove all the character after ":" and "-"
I have tried the following code.
I want one combined solution for this please help me with this.</p>
<pre><code>m = re.sub(r'^-(.*?)', "" ,tags)
pr... | <p>Don't bother replacing everything after <code>:</code> or <code>-</code>, just take whatever is before.</p>
<pre><code>import re
li = ['1 ABCD: PQRS XYZ', '2 qwerty-asd zxc']
regex = re.compile(r'(.*)[:|-]')
for string in li:
print(regex.search(string).group(1))
</code></pre>
<p>Outputs</p>
<pre><code>1 AB... | python|python-3.x | 2 |
6,864 | 39,087,614 | How to trigger a variable/method in python from a html file with javascript | <p>I want to have a hyperlink on a html page run a variable that is defined in my python file. The variable is going to clear my database. Here is the code I am trying to use. </p>
<p><strong>Python</strong></p>
<pre><code>@app.route('/log')
def log():
cleardb = db.session.delete()
return render_template('log.html', ... | <p>You need to make an ajax request with javascript to /log, it would look something like this:</p>
<pre><code>function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
... | javascript|python|html|flask-sqlalchemy | 1 |
6,865 | 52,887,034 | No module named pymysql - aws serverless framework | <p>I deployed a python lambda function through server less framework. Installed <code>pymysql</code> through <code>pip</code>. My handler info is : <code>dynamodbtoauroradb/aurora-data-management/aurora-data-management.handler</code></p>
<p><a href="https://i.stack.imgur.com/uLRM1.png" rel="nofollow noreferrer"><img s... | <p>Use the plugin <a href="https://www.npmjs.com/package/serverless-python-requirements" rel="nofollow noreferrer">serverless-python-requirements</a> with docker.</p>
<p>This will package all your python virtual env dependencies into your serverless package.</p>
<p>See this <a href="https://stackoverflow.com/a/500270... | python|amazon-web-services|serverless-framework|pymysql | 1 |
6,866 | 47,707,030 | Python Extract values from string and move onto next | <p>I'm trying to extract strings that fit between the patterns '{"comments_disabled":' and '}},'
and then append whatever fits between these two patterns. (There could be 100+ occurances that match between these patterns.</p>
<p>The problem is that the code below just keeps extracting the first occurrence, how do I ma... | <p>Try <a href="https://docs.python.org/3/library/re.html#re.findall" rel="nofollow noreferrer"><code>re.findall()</code></a>:</p>
<pre><code>userpost = re.findall(r'{"comments disabled":(.*?)}},', script)
</code></pre>
<p>Tested script:</p>
<pre><code>import re
script = '''
{"comments disabled": one two }},
alpha ... | python|regex|python-3.x | 1 |
6,867 | 37,506,493 | how to make a raw_input call a function | <p>I'm tinkering with a game by my own creation and I came across this problem. I am making the game in a very interactive fiction style but I can't make raw_input call a function like <code>take sword</code> to <code>take(sword, room)</code> to remove it from <code>room</code> and into <code>inventory</code>.
First h... | <p>It looks like you're doing pretty well. I'm not sure if I'm understanding completely, but I think you want to be keeping track of the current room that the user is in (I'm not sure if you're doing that already, it hasn't been specified). Once you do that, you already have the user's input stored in <code>a</code>.</... | python|list|function|raw-input | 1 |
6,868 | 34,208,741 | Is it possible to assign multiple variables to individual hosts in ansible? | <p>Example. </p>
<p>[main]
192.168.1.1 users="test1, test2"</p>
<p>This example does not work since this type of var requires a key value. But is it possible to do this in anyway? And if so what is the correct syntax to use? </p>
<p>For a better look at what I want to do. I have hundreds of users that I need to remo... | <p>In python you can use dictionaries, which are essentially key-value pairs. They are optimized to fetch values based on keys, but not the other way around. So in your case, if you have a list of user data, and want to efficiently assign it to a user, you can set the key to the username, and the value to the list. It ... | python|ansible | 2 |
6,869 | 34,340,326 | How to add five rows of invaders in space invader game | <p>i currently have 1 row of 11 invaders in my space invader game and wish to add 5 more rows, what code would i need to add on to my current code below?</p>
<pre><code>import sys
import pygame
import Invader
import Missile
from pygame.locals import *
class SpaceInvaders:
# Constructor of the basic game class.
... | <p>From what it seems, you would just need to make a nested loop</p>
<pre><code>for b in range(5):
XPos = #insert original starting value
for i in range(11):
invader = Invader.Invader()
invader.setPosX(xPos)
invader.setPosY(20 * b) #adjust y values to your preference
self.invaders.app... | python|pygame | 0 |
6,870 | 66,291,970 | How to plot 2D density clouds so that multiple clouds can be combined? | <p>I'd like to make some similar plots like my first figure. I already used the code below to get the second figure. How can I obtain the same effect as the first figure?</p>
<pre><code>from scipy import stats
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#read data
df=pd.read_excel('plot.xlsx... | <p>You can use seaborn's <a href="https://seaborn.pydata.org/generated/seaborn.kdeplot.html#seaborn.kdeplot" rel="nofollow noreferrer"><code>kdeplot()</code></a> with <code>fill=True</code> and setting a threshold (<code>thresh=</code> between 0 and 1) which cuts off the lowest densities. You may need to experiment to ... | python|pandas|numpy|matplotlib | 1 |
6,871 | 7,170,171 | Python and Unicode | <p>I'm learning Django through the tutorials on their website and I'm running into a weird problem. At this <a href="https://docs.djangoproject.com/en/1.3/intro/tutorial01/#playing-with-the-api" rel="nofollow">step</a> when I get to the part where I enter the unicode snippets so that</p>
<pre><code>>>> Poll.... | <p>Must be caused by mixed tab/space indentation...</p>
<p>Your code pasted in the comment was messed up but I had a look at the HTML source code and found that the lines you typed in (around the <code>__unicode__</code> methods, specifically) were indented using mixed tabs/spaces. Maybe you're using an editor where y... | python|django|unicode | 1 |
6,872 | 7,327,689 | How to generate a sequence of future datetimes in Python and determine nearest datetime from set | <p>I need to generate four datetime objects in Python:</p>
<pre><code>"The next instance of 5:30AM EST"
"The next instance of 8:30AM EST"
"The next instance of 1:00PM EST"
"The next instance of 5:30PM EST"
</code></pre>
<p>Then I need to find which of those is closest to the current date/time.</p>
<p>I wish I could ... | <p>This should get you started. I have the current time being passed into the function as a datetime, so if the argument is in EST, this should just work.</p>
<pre><code>def find_next(cur_dt):
import datetime as dt
t = [dt.time(5,30), dt.time(8,30), dt.time(13,0), dt.time(17,30)]
cur_t = cur_dt.time()
... | python|datetime|sequence | 1 |
6,873 | 31,758,302 | Testing a loop that repeats itself every 10 seconds | <p>I have a code that repeats itself every 10 seconds, but I can't test it for a long time because my powershell keeps on hanging and the code just stops for no particular reason (the code is running but it doesn't give out results). Is there a way to test the code, or safely running it without it being interrupted? I ... | <p>So after testing and experimenting. It seems like a resource miss-management by windows when I use PowerShell, cmd.exe or the default Python IDE. Thus in case someone wants to test their code for a prolonged period of time, it is recommended to use PyCharm as it has been running for more than a day for me. This shou... | python|powershell|testing|python-requests | 0 |
6,874 | 68,037,749 | Upload new version of python library | <p>I recently made a python library (most recent version: v1.0.0). I have made a few changes to it and want to release the next version (that is v1.0.1). I tried searching google to find the command to do so but found nothing. So I decided to run the initial commands (The ones used to publish the library) which are:</p... | <p>Okay so the way is to clear all the files like <code>build/</code>, <code>dist/</code> and <code>src/<LIBRARY-NAME>.egg-info</code> and then run the commands:</p>
<pre><code>$ python setup.py bdist_wheel
$ py -m build
$ twine upload --skip-existing dist/*
</code></pre>
<p>Running the commands in this order sha... | python|pypi | 2 |
6,875 | 26,092,748 | How to Run two django projects in one server | <p>I am using python 2.7,django 1.4,and Apache2.2.21, I am able to run one project on Apache server, I want to use the same Apache and same server to run my second project.</p>
<p>I am using the following <code>wsgi.py</code> for my first project</p>
<pre><code>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE"... | <p>You should not write your application configuration(the code you added) on module configuration(<code>mod_wsgi.so</code>)</p>
<p>You should create application configuration file (usually at <code>/var/www/apache2/sites-available/</code>) and then enable it. In order to create multiple application, you should use <a... | python|django|apache|python-2.7 | 3 |
6,876 | 2,069,362 | '%s' % 'somestring' | <p>Here are a couple of examples taken from <a href="http://github.com/nathanborror/django-basic-apps/" rel="nofollow noreferrer">django-basic-apps</a>:</p>
<pre><code># self.title is a unicode string already
def __unicode__(self):
return u'%s' % self.title
# 'q' is a string
search_term = '%s' % request.GET['... | <p>It's just a habit of mine. In these cases it's not necessary.</p> | python|django | 3 |
6,877 | 28,257,482 | PyQt4 QPalette not working | <pre><code> {btn = QtGui.QPushButton('Button', self)
palettes = btn.palette()
palettes.setColor(btn.backgroundRole(),QtCore.Qt.green)
btn.setPalette(palettes)
btn.setAutoFillBackground(True)}
</code></pre>
<p>Using <code>btn.backgroundRole()</code> only provides green border to the button.<br/>
Us... | <p>You can read in Qt documentation about <code>QPalette</code> :</p>
<blockquote>
<p>Warning: Some styles do not use the palette for all drawing, for
instance, if they make use of native theme engines. This is the case
for both the Windows XP, Windows Vista, and the Mac OS X styles.</p>
</blockquote>
<p>Window... | python|qt|pyqt|qpalette | 2 |
6,878 | 44,291,518 | Remove smilies (not emojis!) from tweets string | <p>I want to remove emoticons in my data that contains only text containing tweets. Each line corresponds to one tweet.
I get a bad character error for the ":)". </p>
<pre><code>error: bad character range :-) at position 4
</code></pre>
<p>What is wrong?</p>
<pre><code>#remove emoticons
import re
emoji_pattern = re.... | <p>The bad character is actually on the previous line, the non-ASCII character. If you want to use those, you need to declare a compatible encoding. Search "Python character encoding" for the variety of choices you have.</p> | python|regex|twitter | 0 |
6,879 | 33,046,184 | How to pass sub-arguments to default function of sub parser? | <p>If I have an Argparse setup like the following:</p>
<pre><code>parser = argparse.ArgumentParser(description='test.')
subparsers = parser.add_subparsers(help='sub-command help')
parser_somethingX = subparsers.add_parser('somethingX', help='generate X')
parser_somethingY = subparsers.add_parser('somethingY', help="g... | <p>I thought the <code>argparse</code> example using <code>setdefaults</code> explained how to use the function?</p>
<p>Look at <code>args</code>. It probably looks something like</p>
<pre><code>Namespace(func=execute_z, N=1000)
</code></pre>
<p>So you should be able to use:</p>
<pre><code>args.func(args.N)
</code... | python|python-3.x|parameter-passing|argparse | 0 |
6,880 | 14,348,857 | Requests library not properly directing HTTP requests through proxies | <p>I know how to use <code>requests</code> very well, yet for some reason I am not succeeding in getting the proxies working. I am making the following request:</p>
<pre class="lang-py prettyprint-override"><code>r = requests.get('http://whatismyip.com', proxies={'http': 'http://148.236.5.92:8080'})
</code></pre>
<p... | <p>It's a known issue: <a href="https://github.com/kennethreitz/requests/issues/1074" rel="nofollow">https://github.com/kennethreitz/requests/issues/1074</a></p>
<p>I'm not sure exactly why it's taking so long to fix though. To answer your question though, you're doing nothing wrong.</p> | python|node.js|proxy|python-requests | 2 |
6,881 | 8,039,422 | Want to store last paragraph to any variable | <p>I have <a href="http://dpaste.com/648868/" rel="nofollow">long text</a>. And I'm converting this string to dict.</p>
<p>Here is code</p>
<pre><code>data_dict = {}
filter_dict = {}
for each in text.split("\n"):
temp = each.split('=')
if len(temp) == 2:
data_dict[temp[0]] = temp[1]
data = dic... | <p>You are not storing the text at the bottom. The only place where you assign values to the dictionary entries is under the if len(temp) == 2. Since that text paragraph doesn't have an equal sign, this part will simply fall through and nothing will be done. You need an 'else' somewhere there</p> | python|regex|dictionary | 1 |
6,882 | 8,230,969 | How to get two values from two seperate lists to print (python) | <p>Here’s my problem, I have two different lists, list <code>a</code> which contains the name of people and list <code>b</code> which contains their phone numbers: </p>
<pre><code>a = ["peter", "bob", "john", "jack"]
b = ["8954 3434", "8999 4432", "8976 5443", "8990 3331"]
</code></pre>
<p>What I need to do is prompt... | <p>Put your data in a dictionary:</p>
<pre><code>>>> a = ["peter", "bob", "john", "jack"]
>>> b = ["8954 3434", "8999 4432", "8976 5443", "8990 3331"]
>>> phone_numbers = dict(zip(a,b))
</code></pre>
<p>Then you can get someone's phone number from their name:</p>
<pre><code>>>> ph... | python|list|zip | 4 |
6,883 | 890,461 | Explain to me what the big deal with tail call optimization is and why Python needs it | <p>So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone <a href="http://drj11.wordpress.com/2009/04/30/python-tail-call-optimisation/" rel="noreferrer">shipped Guido a copy of SICP</a> because he didn't "get it." I'm in the same boat as G... | <p>Personally, I put great value on tail call optimization; but mainly because it makes recursion as efficient as iteration (or makes iteration a subset of recursion). In minimalistic languages you get huge expressive power without sacrificing performance.</p>
<p>In a 'practical' language (like Python), OTOH, you usua... | python|tail-recursion|tail-call-optimization | 16 |
6,884 | 41,831,870 | Python, Tkinter: Making a grid of Checkboxes using Lists | <p>I'm trying to make a tkinter program that has a 3x3 grid of checkboxes, the code I have created to do this is:</p>
<pre><code>import tkinter as tk
class App(tk.Frame):
def __init__(self,* args,** qwargs):
tk.Frame.__init__(self)
self.strCategories=("Q","W","E","R","T","Y","U","I","O")
s... | <p>The first reason that the widgets don't appear on screen is because they are in a frame, and you never added the frame to the main window. You need to call <code>pack</code>, <code>place</code> or <code>grid</code> on the instance of <code>App</code>. </p>
<p>Unrelated to the problem but related to good coding prac... | python|python-3.x|loops|checkbox|tkinter | 2 |
6,885 | 47,211,563 | Python Dictionary recursive searching | <p>The way it works is that the keys can turn into any value from the lists they're associated with. So the question I'm trying to answer is can maximus turn into bumble. The function should return True because maximus -> bee -> bumble.</p>
<p>My function so far works with the following logic:</p>
<pre><code>for i in... | <p>We can do this using recursion. Recursion always has base cases and inductive cases.</p>
<p>The base case is:</p>
<blockquote>
<p>"An object can transform into itself." (1)</p>
</blockquote>
<p>The inductive case is:</p>
<blockquote>
<p>"An object can transform into the requested object <code>req</code> give... | python|python-3.x|recursion | 4 |
6,886 | 11,615,664 | Multivariate normal density in Python? | <p>Is there any python package that allows the efficient computation of the PDF (probability density function) of a <a href="https://en.wikipedia.org/wiki/Multivariate_normal_distribution" rel="noreferrer">multivariate normal distribution</a>?</p>
<p>It doesn't seem to be included in Numpy/Scipy, and surprisingly a Goo... | <p>The multivariate normal is now available on <code>SciPy 0.14.0.dev-16fc0af</code>:</p>
<pre><code>from scipy.stats import multivariate_normal
var = multivariate_normal(mean=[0,0], cov=[[1,0],[0,1]])
var.pdf([1,0])
</code></pre> | python|numpy|scipy|probability | 91 |
6,887 | 33,592,778 | Lasagne dropoutlayer does not utilize GPU efficiently | <p>I am using theano and lasagne for a DNN speech enhancement project. I use a feed-forward network very similar to the mnist example in the lasagne documentation (/github.com/Lasagne/Lasagne/blob/master/examples/mnist.py). This network uses several dropout layers. I train my network on an Nvidia Titan X GPU. However, ... | <p>As pointed out by talonmies the problem was that lasagne was using the CPU version of the RNG (mrg_uniform) and not the GPU version (GPU_mrg_uniform).
I have not yet found an elegant solution but the following two hacks solves the problem. </p>
<p>Either change line 93 <code>cuda_enabled = False</code> to <code>cu... | python|gpgpu|theano|deep-learning|lasagne | 1 |
6,888 | 46,650,518 | how to implement search and sorting function in Django table | <p>I know that there are Django-datatable, django_tables2, and even django_filter to perform search and sorting to the table. I have tried using Django-datatable, django_tables2 and even django_filter, but none of them work. I have attached my code for the template. I am rendering two different tables using the code b... | <p>After the table displays some data correctly, you must also make sure the filter formset is displayed. I usually use something like this (in this case using <code>{% load bootstrap3 %}</code></p>
<pre><code>{% if filter %}
<div class="col-sm-10">
<form action="" method="get" class="form form-in... | python|django|search|django-tables2|django-filters | 1 |
6,889 | 67,772,647 | else if clause not executing in for loop python | <pre><code>num_input = open('final_activity_io_text.txt')
new_var = num_input.read()
num_list = (int(i) for i in new_var)
catch = (i for i in num_list if i > 3)
if (i for i in num_list if i > 3):
print(*catch, sep='\n')
elif (i for i in num_list if i <= 3):
print('None!')
</code></pre>
<p>hi, I've te... | <p>You can't use generator expressions as the condition of if-statements. Generators are lazily evaluated & are inherently "truth-y".</p>
<p>Check this example:</p>
<pre><code>nums = list(range(100))
gen_full = (i for i in nums if i < 3)
gen_empty = (i for i in nums if i > 100)
print(bool(gen_ful... | python | 1 |
6,890 | 29,877,876 | Find max values in a dict containing lists | <p>The dict got the keys <code>years</code> and for each year it's a list of all the temperatures in all 12 months of that year. My goal is to print out a table starting with what year it is and then a new line for each month and the temp that month.</p>
<p><strong>The main thing is to mark the highest temp of all yea... | <p>Python has built-in function <a href="https://docs.python.org/3.4/library/functions.html#max" rel="nofollow noreferrer">max</a>, it's considered a good practice to use it.</p>
<p>Max in year:</p>
<pre><code>max(temp_dict["2010"])
</code></pre>
<p>Max all time:</p>
<pre><code>max(sum(temp_dict.values(), []))
</co... | python|list|python-3.x|for-loop|dictionary | 4 |
6,891 | 56,906,376 | unsupported operand type(s) for /: 'list' and 'int' in pyhton | <p>I have some problems with the code, which he can't process data lists and int.
but at first he was able to produce csv data on line 27 ... but then it can't ...
what's wrong with hasil=total/kata</p>
<pre><code>import gensim
#import pandas as pd
import re
import csv
import numpy as np
def processing(kata):
wo... | <pre><code> for word in processed.split():
#for line in fp:
try:
vector=model[""+word+""]
print(vector)
total=total+vector
print(word)
except:
pass
if kata is not 0 :
hasil = [x/kata for x in total]
#hasil=total/kata
... | python|list|int|word2vec | 0 |
6,892 | 27,613,111 | How do you use compiled programming languages and scripting languages together? | <p>Such a simple question, but I have not found a reasonable answer to this. I currently program in Python, an interpretive language. I always hear of people using multiple languages in a program? Then I hear them using scripting languages. Can someone on here please, in plain English, explain to me the difference betw... | <p><code>How do you use programming languages and scripting languages together?</code></p>
<p>Scripting languages ARE programming languages. You are likely thinking of the typical alternative to scripting/interpreted languages: Compiled languages.</p>
<p><code>I always hear of people using multiple languages in a pr... | python|c++|scripting|programming-languages | 3 |
6,893 | 65,745,215 | Can you make this function more efficient? Thank you | <p>I have a list of profane words that I compare against user input:
(using Django)</p>
<pre><code>def check_profanity(string):
if string is not None:
import os
import gzip
profanity_list = staticfiles_storage.path('users/files/list.txt')
try:
with gzip.open(profanity_lis... | <p>You can move loading from file into a separate function and perform it once:</p>
<pre class="lang-py prettyprint-override"><code>def _read_file_lines(fn):
with open(fn, "rb") as f:
if f.read(2) == b"\x1f\x8b": # magic
from gzip import GzipFile
_f = GzipFile(fi... | python | 2 |
6,894 | 43,270,827 | Shifting values in datetimeindex of pandas dataframe | <p>I have a df with a DateTimeIndex of 30 minute intervals over a long period (> 1 year), so >17520 rows. For reasons related to daylight savings, two of the index values are repeated in the index and two values are missing. So the duplicated values are:</p>
<pre><code>In[1]: df[df.index.duplicated('first')]
Out[2]: ... | <p>I think you need map <code>duplicated index</code> with <code>rename</code> by <code>dict</code>:</p>
<pre><code>print (df)
a b c
timestamp
2013-10-06 01:00:00 1 NaN NaN
2013-10-06 01:30:00 2 NaN NaN
2013-10-06 01:00:00 3 NaN NaN
2013-10-06 01:30:00 4 NaN NaN
2012-1... | pandas|dataframe|datetimeindex | 0 |
6,895 | 43,086,920 | Anaconda on Windows 10: iPython and Spyder fail to start in Python3 environment | <p>I'm using Windows 10 and I have Anaconda with Python 2 installed, so my root environment is Python 2. I created an additional Python 3 environment and among other packages installed iPython and Spyder into it. I used the Anaconda Navigator to install the packages.</p>
<p>I can activate and deactivate the environmen... | <p>I found the problem.</p>
<p>As it turns out the module <code>menuinst</code> wasn't automatically installed into the new environment so I had to manually install it. Now everything works.</p> | python|windows|python-3.x|windows-10|anaconda | 0 |
6,896 | 43,211,185 | flask-login repeatedly asks for username | <p>I have the following code:</p>
<p><strong>user.py</strong></p>
<pre><code>class User(Base, UserMixin):
username = StringField(max_length=10, required=True, unique=True)
first_name = StringField(max_length=32, required=True)
last_name = StringField(max_length=32, required=True)
def get_id(self):
... | <p><code>def get_id(self)</code> must be return id, not username. Try this:</p>
<pre><code>def get_id(self):
return self.id
</code></pre>
<p>The following is written in the <a href="https://flask-login.readthedocs.io/en/latest/" rel="nofollow noreferrer">documentation</a>:</p>
<blockquote>
<p>get_id()
Th... | python|flask|flask-login | 1 |
6,897 | 37,050,336 | No module error when running python script from command prompt | <p>I have a python script which is running successfully when i run it from spyder. But the same script gives "ImportError: No module named pandas" when run from windows command prompt.</p> | <p>This Q&A mentioned similar problem <a href="https://stackoverflow.com/a/10741803/5088142">https://stackoverflow.com/a/10741803/5088142</a></p>
<p>Can you please check which folders are mentioned in Spyder Tools/PYTHONPATH manager?</p>
<p>Also you can execute the following two lines in Spyder, and identify the ... | python | 2 |
6,898 | 48,561,247 | TfidfVectorizer vs. definition of tf-idf | <p>For a tutorial, I want to implement manually what the <code>TfidfVectorizer</code> is doing, just to show what's going on in the background. In this <a href="https://stackoverflow.com/questions/36966019/how-aretf-idf-calculated-by-the-scikit-learn-tfidfvectorizer">Stack Overflow article</a> I found how the <code>Tfi... | <p>Usually, TfidfVectorizer using as next construction:</p>
<pre><code>from sklearn.feature_extraction.text import TfidfVectorizer
features = ['1', '2', '3', '4', '5']
data = ['string1', 'string2', 'string3', 'string4', 'string5']
tfidfve = TfidfVectorizer()
tfidfve.fit_transform(data, features)
</code></pre> | python|scikit-learn|tf-idf | 0 |
6,899 | 48,451,943 | python ipdb.set_trace() one frame "up" (frame=?) | <p>Sometimes when I invoke ipdb, I <em>know</em> I want to be a frame above where the trace is set. I presume that's why the API exposes the <code>frame</code> parameter (as discussed in <a href="https://github.com/gotcha/ipdb/blob/master/ipdb/__main__.py" rel="nofollow noreferrer">the documentation</a>).</p>
<p>So he... | <pre><code>import inspect
import ipdb
def dbg_up():
ipdb.set_trace(inspect.currentframe().f_back.f_back)
def foo():
var = 'in foo'
bar()
def bar():
var = 'in bar'
dbg_up()
foo()
</code></pre>
<p>Users of vanilla <code>pdb</code>: your interface is slightly different, like this:</p>
<pre><code>... | python|ipdb | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.