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
7,000
55,512,003
How to rotate wxButton label?
<p>I'm creating a Graphical User Interface with wxpython and I would like to insert one button with the label rotated vertically (see example below). I have looked into docs and did some internet search but I can't find information how to do it. Is it possible to do it? If yes any help would be very much appreciated....
<p>The only way that I can think of would be to use a <code>BitmapButton</code> that you have prepared.<br> You could do it programmatically e.g.</p> <pre><code>import wx class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(400, 300)) ...
user-interface|button|wxpython
1
7,001
57,532,761
I need my script to run several lines until task is completed
<p>I need for the questioning part of the code to occur until the player has guessed the number.</p> <p>I'm a bit of a beginner, and I'm writing a simple code for guessing a number. I've gotten to a point where I have everything I need, but I need it so the script runs until they've guessed the number. I'm not sure if...
<h2>Alternative variation:</h2> <ul> <li>Wrapped in a function <ul> <li><code>type hints</code> only work from <code>python 3.5</code></li> </ul></li> <li>Removed separate <code>while loop</code> variable</li> <li>Replaced <code>if-else</code> with a <code>dict</code> <ul> <li><code>output</code> is inside the <code...
python|python-3.x
1
7,002
54,064,982
How do I solve "Failed to load the native TensorFlow runtime"?
<p>Failed to load the native TensorFlow runtime</p> <p>I've downgraded from python version 3.7 to python 3.6.8 using windows 10.0, Tensorflow-gpu, cuda 9.0, cudnn 7.0. Executed the command as shown in code below in order to train my data. The error I got was: "Failed to load the native TensorFlow runtime".</p> <pre>...
<p>Try to match the tensorflow version with the CUDA.</p>
python|tensorflow|anaconda
0
7,003
53,830,073
Python Plotting colours for unknown number of lines
<p>I have a dataframe and want to loop through all columns and add a new line to a chart, with a different colour.</p> <p>This code does the trick.</p> <pre><code>variables=df.columns colours=['b','y','r','c','k','m'] for i, j in zip(variables, colours): plt.plot(df[i],j+'-o',label=i) plt.ylim(ymin=0) plt.gcf()....
<p>From matplotlib <a href="https://matplotlib.org/2.0.2/api/colors_api.html" rel="nofollow noreferrer">documentation</a></p> <blockquote> <p>For a greater range of colors, you have two options. You can specify the color using an html hex string, as in: color = '#eeefff'</p> </blockquote> <p>You can generate an h...
python|matplotlib
1
7,004
58,530,129
How to initialise cost and iteration array within gradient descent class
<p>I'm trying to implement a class for a gradient descent function for multivariate linear regression. I want to plot the cost function against the number of iterations. </p> <p>I'm trying to record each iteration value in an iteration array, and the value of the cost function for each iteration in a cost array. Howev...
<p>Try this <code>plt.plot(gd._iterationArray,gd._costArray)</code> . You have missed the <strong><em>underscore</em></strong> ( _ ) . It should be <code>gd._iterationArray</code> not <code>gd.iterationArray</code>.</p> <p>You don't want a separate list to store your iterations because you already know it. So you ca...
python|class|machine-learning|initialization|gradient-descent
0
7,005
58,420,941
Pandas: TypeError: list indices must be integers or slices, not DataFrame
<p>I am working with a lot of input csv files in a specified folder. I am using pandas data frame to store the input file and intend to do more math.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import csv import os from scipy.interpolate import interp1d import pandas as pd import glob user_info=...
<p>You can concatenate all your csv in one dataframe. It will be easier to manipulate. It is assuming that all csv have the columns at the same position as you don't have any header. I see you are skipping the first rows when selecting you x and y, you could also use the <code>skiprows</code> option of <code>pd.read_cs...
python|python-3.x|pandas|dataframe
0
7,006
45,555,758
A bytes-like object is required, not 'tuple' error when trying to use a Discord bot
<p>I've been writing the following Python 3 Code:</p> <pre><code>import urllib.request import discord import asyncio #Colors black = "\033[0;30m" red = "\033[0;31m" green = "\033[0;32m" yellow = "\033[0;33m" blue = "\033[0;34m" purple = "\033[0;35m" cyan = "\033[0;36m" white = "\033[0;37m" #Bold Colors bblack = "\03...
<p><code>values</code> is a tuple, not a single string:</p> <pre><code>values = """ { "deviceid": """,hg_deviceid,""", "fromnumber": """,sender,""", "body": """,body,""" } """ </code></pre> <p>That's a series of strings, separated by commas.</p> <p>Rather than manually try to construct a JSON string,...
python|python-3.x
3
7,007
14,733,158
Python list in list
<p>I want convert list as follow:</p> <pre><code>list=[['a','b','c','d'],'e','f'] </code></pre> <p>to</p> <pre><code>list['a','b','c','d','e','f'] </code></pre> <p>how could I do this....Helples..</p>
<p>Check out <code>itertools.chain</code>, I think it's exactly what you need: <a href="http://docs.python.org/2/library/itertools.html#itertools.chain" rel="nofollow">http://docs.python.org/2/library/itertools.html#itertools.chain</a></p> <hr> <pre><code>&gt;&gt;&gt; import itertools as it &gt;&gt;&gt; li = [['e', '...
python|list
0
7,008
14,564,622
Two different week numbers evaluated to same date
<p>I'm parsing weekly time series data from a source that shows dates using a year and week number. However, when trying to use Python's <code>datetime.strptime</code> function to turn these into YYYY-MM-DD dates, two different week numbers sometimes evaluate to the same date, when I know that they should not. The week...
<p>1998 did not have 53 weeks; December 31st is week 52:</p> <pre><code>&gt;&gt;&gt; datetime.strptime("1998-4-52", "%Y-%w-%U") datetime.datetime(1998, 12, 31, 0, 0) </code></pre> <p>Note that the documentation for <code>%U</code> states:</p> <blockquote> <p>Week number of the year (Sunday as the first day of the ...
python
1
7,009
57,237,963
How to pass the argument using argparse in xml format?
<p>I'm Trying to pass the argument as CLI,and it have two commands SHOW and CREATE all i want to know is how to pass the command in xml format like my command will be like</p> <pre><code>$ program.py &lt;CREATE ID=12334&gt; # where CREATE is cmd and 'ID=' is fixed constant and integer has to be passed as input. # ma...
<p>Neither the shell (<code>bash</code>) or <code>argparse</code> handles this <code>xml</code> format in any special way. It's just a string or list of strings. </p> <p>A simpler script:</p> <pre><code>import argparse, sys print(sys.argv) parser = argparse.ArgumentParser() parser.add_argument('option') # 'optio...
python|python-3.x|argparse
0
7,010
25,655,275
Bottle: Global Variable 'request' is not defined
<p>I am creating a web based application with python where the user enters a search query and data is returned. I used bottle to provide the web framework for this. Openshift is then used to post online. It is a simple post form and the search criteria is then used in the next section using this:</p> <pre><code>@route...
<p>It seems like you haven't imported the request or route to namespace:</p> <pre><code>from bottle import get, post, request # or route @get('/login') # or @route('/login') def login(): return ''' &lt;form action="/login" method="post"&gt; Username: &lt;input name="username" type="text" /&gt;...
python|python-2.7|openshift|bottle
6
7,011
44,748,022
Python how to print a list of lists backwards?
<p>How can I print a list of lists backwards in Python 3.x? I have created an adjacency list by writing a list of lists as following:</p> <pre><code>adjazenzListe = [[1], #0 [1, 3], #1 [1], #2 [4, 5],#3 [3], #4 [3, 6, 7],#5 [5], #6 ...
<p>You must not have been using the indices correctly.</p> <p>Try the following:</p> <pre><code>adjazenzListe = [[1], #0 [1, 3], #1 [1], #2 [4, 5],#3 [3], #4 [3, 6, 7],#5 [5], #6 [8, 10],#7 [9, 10], #8 ...
list|python-3.x|adjacency-list
0
7,012
44,386,826
Receiving data from sensor via serial port
<p>0x4D – 0x10 – 0x00 – 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF 0x0FFF - 0x0A //ROW 0 INFORMATION</p> <p>I'm supposed to receive data as mentioned above.Actually, I want to extract the 2bytes informations one by one. I'm using python in coding.</p> <pre...
<blockquote> <p>""Question"": , I want to extract the 2bytes informations one by one </p> </blockquote> <pre><code>while True: bytes = [] b = ser.readline() for i in range(3, len(b)-1, 2): bytes.append( int (b[i:i+2], 16 ) ) </code></pre>
python
0
7,013
44,445,051
Creating a 2d numpy array to hold characters
<p>I have the following numpy array and previous set up that has a word queue and a temporary variable 'temp' to store a word. This word needs to be "put", letter by letter, into the numpy 2d array:</p> <pre><code>from collections import deque import numpy as np message=input("Write a message:") wordqueue=message.spl...
<p>First thing is first, if you want a "character" array, you have to be careful with what exactly you expect. In Python 3, strings are now sequences of <em>unicode code points</em>. In Python 2, strings were the classic "sequence of bytes" strings from languages like C. This means, that from a memory pov, unicode type...
python|numpy
5
7,014
61,886,776
Powershell Output as an Array (Python)
<p>Im trying to put the Porwershell Output from <code>Get-Printer | select Name</code> into an Option Menu. How do i put the Output into an Array for example? Currently the Output is only in One Line. Each Printer is suppost to be one Option.</p> <p>Im using tkinter. Here is my OptionMenu</p> <pre><code>variable = St...
<p><code>Select -Expand Name</code> seems to be working fine but as you are taking entire output of process into python variable it is treating it as a single line.</p> <p>You need to split the result into an array like <code>result=process.communicate()[0].splitlines()</code>.</p> <p>sample code looks like this </p>...
python|arrays|powershell|subprocess
3
7,015
61,635,372
Cumulative histogram for 2D data in Python
<p>My data consists of a 2-D array of masses and distances. I want to produce a plot where the x-axis is distance and the y axis is the number of data elements with distance &lt;= x (i.e. a cumulative histogram plot). What is the most efficient way to do this with Python?</p> <p>PS: the masses are irrelevant since I a...
<p>You can combine <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html" rel="nofollow noreferrer">numpy.cumsum()</a> and <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.step.html" rel="nofollow noreferrer">plt.step()</a>:</p> <pre><code>import matplotlib.pyplot as plt import n...
python|matplotlib
2
7,016
23,918,955
Installing Pillow error
<p>I am trying to syncdb a new project I cloned. After installing the requirements, I noticed that I needed to install PIL, or Pillow for that matter in order to get syncdb to work.</p> <p>Here is what happened when I ran <code>pip install pillow</code>:</p> <pre><code>clang: error: unknown argument: '-mno-fused-madd...
<p>I am using OS X El Capitan, and this worked for me.</p> <ol> <li>Close your virtualenv active terminal window.</li> <li>Open new terminal and run <code>sudo xcode-select --install</code>, it will take some time to finish.</li> <li>After finish that open a new terminal and run <code>pip install Pillow</code></li> </...
python|django|clang|pip|osx-mavericks
2
7,017
23,578,819
Method to read data from a file when plot histogram with python?
<p>I ‘ve written a function to plot the histogram for an 1-D array theta . But one thing I do not like in this function is that the data is in the code. Could you know how to keep the data in a <em>file</em> and to make the function <em>read</em> them from the file? Since the data is usually much larger.</p> <p>PS:...
<p>If you have a txt file with the separated-comma theta values in the first line and the number of bins in the second line:</p> <pre><code>77.438110,82.811340,59.701530,124.94859,82.991272,84.300468,24.639610,112.28130 72 </code></pre> <p>You can add this:</p> <pre><code>import numpy as np from StringIO import Stri...
python|matplotlib|plot|histogram
2
7,018
20,724,102
Creating an array of objects in Python for pygame
<p>I create the objects</p> <pre><code>class Disk: def __init__(self,number,colour,position,size): self.size = size self.colour = colour self.number = number self.position = position def Render(self,screen): pygame.draw.rect(screen,self.colour,(self.position,self.size)) </code></pre> <p>I am try...
<p>You haven't defined <code>disk</code>. You are trying to simultaneously create the list and the items in it and iterate over it, but haven't actually told Python what <code>disk</code> is supposed to be. Try:</p> <pre><code>def drawDisk(screen, colours): disk = [Disk(i, colours[i], (0+(i*15), 500-(i*50)), (400 ...
python|arrays|object|pygame
0
7,019
71,929,122
Is there a way to find a specific word multiple times, then find related words near that word?
<p>I have the below and I am looking for a way to find the word &quot;pizza&quot; as many times no matter how many words are in between.</p> <p>Then find related words (e.g. pepperoni, large) only if NEAR the word &quot;pizza&quot;</p> <p>I tried using a larger character count on f1 {0,100} but it seems to carry over a...
<p>To expand on my comment. Consider a direction like so:</p> <pre><code>string = ['I need a pizza with pepperoni word word word word word word word and a small pizza'] for sentence in string: string_list = sentence.split() for i in range(0, len(string_list)): if string_list[i] == 'pizza': ...
python|regex|findall
0
7,020
35,852,301
How do i count a number of occurrences in a string?
<p>I can't seem to find the answer anywhere for this, but I have a program i need to write for computer science 1(beginner friendly answers please). These are the instructions.</p> <blockquote> <p>Write a program that will emulate this car counter.</p> <p>For this program, there will be a continuous string of c...
<p>You need to <code>return</code> variables from inside functions otherwise these will be discarded after the function terminates. For example you could do it like this:</p> <pre><code>def replace(lst): scount = lst.count('xoox') mcount = lst.count('oxo') lcount = lst.count('oxoxxooo') return scount, ...
python|python-2.7
1
7,021
15,331,604
Formatting output in python
<p>This is my code:</p> <pre><code>import commands mount = commands.getoutput('mount -v') lines = mount.splitlines() points = map(lambda line: line.split()[2], lines) permission = map(lambda line: line.split()[5], lines) print points print permission </code></pre> <p>The output I am getting is:</p> <pre><code>['/',...
<p>you can use zip function for this</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3] &gt;&gt;&gt; y = [4, 5, 6] &gt;&gt;&gt; zipped = zip(x, y) &gt;&gt;&gt; zipped [(1, 4), (2, 5), (3, 6)] </code></pre> <p>in your case </p> <pre><code>zipped = zip(points, permission) for i, j in zipped: print i, j </code></pre> <p>f...
python|linux
1
7,022
29,701,242
Aggregate by repeated values in a column in a data frame in pandas
<p>I have a data frame as follows:</p> <pre><code> value identifier 2007-01-01 0.781611 55 2007-01-01 0.766152 56 2007-01-01 0.766152 57 2007-02-01 0.705615 55 2007-02-01 0.032134 56 2007-02-01 0.032134 57 2008-01-01 0.026512 55 2008-01-01 0.993124 56 200...
<p>If your index is a datetime then you can access the <code>.date</code> attribute, if not you can convert it using <code>df.index = pd.to_datetime(df.index)</code> and then perform a groupby on the date and calc the mean:</p> <pre><code>In [214]: df.groupby(df.index.date)['value'].mean() Out[214]: 2007-01-01 0.7...
python|pandas
1
7,023
46,179,481
How to execute a Python 3 program in Tkinter with one button
<p>I am trying to execute a python 3 file from tkinter when I click a button</p> <p><strong>tkinter code</strong> </p> <pre><code>import tkinter as tk import subprocess as sub WINDOW_SIZE = "600x400" root = tk.Tk() root.geometry(WINDOW_SIZE) tk.Button(root, text="Create Motion!", command=lambda: sub.call('home/pi...
<p>You are doing it all wrong. The proper way to do this is to make "motion1.py" with a function in it that does something. Let's say you call that function "main" (very common). Then your code would be: </p> <pre><code>import tkinter as tk import motion1 WINDOW_SIZE = "600x400" root = tk.Tk() root.geometry(WINDOW_S...
python-3.x|tkinter
1
7,024
49,602,439
If-statement with list inside for-loop over same list
<p>I am appending similarity scores of all pairs in a list.</p> <pre><code>data = [] for i1, i2 in list: data.append([i1, i2, cosine_similarity([X[df.index.get_loc(i1)]],[X[df.index.get_loc(i2)]]).ravel()[0]]) </code></pre> <p>However, I need it to only append scores that are non-zero.</p> <p>I put in an if st...
<p>The general pattern for a conditional iteration is <code>(a for a in b if a)</code>. Pulling your calculation into a helper function for readability, this should work:</p> <pre><code>def calc_sim(X, df, i1, i2): return cosine_similarity([X[df.index.get_loc(i1)]], [X[df.index.get_loc(i2)]]) data = [(i1...
python|pandas|for-loop|if-statement|dataframe
0
7,025
53,414,635
reading from a file and checking if word in list
<p>my wife texts me unorganized and long grocery lists. I will paste her list into a text file. I want to write a program that will will erase her unordered list and write to that file an ordered list. e.x. all fruit together, meat together ect. clearly this program is in its infancy. in my text file, I have written:</...
<p>You need to strip the line endings from the file, as they are carrying <code>\n</code> or <code>\r\n</code>(Windows carriage return) at the ends. This means you are comparing <code>banana</code> with <code>banana\n</code>, which are <em>not</em> equal, leading to nothing being appended. </p> <p>You can fix this by ...
python|list|for-loop|conditional
3
7,026
45,979,406
Serve dynamically generated xml file to download in Django with character encoding information
<p>I need to generate a <code>XML</code> file dynamically in <code>Django</code> to download.</p> <p>I can do this with the code below, but without the character encoding information:</p> <pre><code>import xml.etree.ElementTree as ET def get_xml(): my_xml = ET.Element('foo', attrib={'bar': 'bla'}) my_str = ...
<p>I found two ways to solve the question:</p> <p>1) Concatenate the character encoding information as string (duh!):</p> <pre><code>def get_xml(): my_xml = ET.Element('foo', attrib={'bar': 'bla'}) my_str = ET.tostring(my_xml, 'utf-8', short_empty_elements=False) enc = '&lt;?xml version="1.0" encoding="ut...
python|xml|django|python-3.x
0
7,027
45,895,816
Pandas pivot_table multiple aggfunc with margins
<p>I've noticed that I can't set margins=True when having multiple aggfunc such as ("count","mean","sum").</p> <p>It will vomit <code>KeyError: 'Level None not found'</code></p> <p>This is the example code.</p> <pre><code>df.pivot_table(values=A,index=[B,C,D],columns=E,aggfunc=("count","mean","sum"), margins=True,ma...
<p>I see the error you are talking about. I got around it by using the function calls instead of the string names "count","mean", and "sum."</p> <p>First, we start with your dataframe:</p> <pre><code>import pandas as pd df=pd.DataFrame([{'Game_ID': 'no.1', 'Results': 0, 'Team': 'B'}, {'Game_ID': 'no.1', 'Results': ...
python|pandas|pivot-table|multi-index
4
7,028
55,128,462
How to normalize seaborn distplot?
<p>For reproducibility reasons, the dataset and for reproducibility reasons, I am sharing it [here][1]. </p> <p>Here is what I am doing - from column 2, I am reading the current row and compare it with the value of the previous row. If it is greater, I keep comparing. If the current value is smaller than the previous ...
<h2>Foreword</h2> <p>From what I understand, the seaborn distplot by default does a kde estimation. If you want a normalized distplot graph, it could be because you assume that the graph's Ys should be bounded between in [0;1]. If so, a stack overflow question has raised the question of <a href="https://stackoverflow....
python|python-3.x|statistics|seaborn|distribution
10
7,029
33,415,605
Odoo workflows wrong transitions
<p>I have added two new states to the mrp.production workflow. 'new_state' comming right after the 'draft' state and 'new_done_state' which replaces the 'done' state. We I make a transition to 'new_state' (by clicking a button) the workflows goes from draft > new_done_state and then from new_done_state > new_state. I c...
<p>Try adding the "type" attribute to your new buttons and set it as "workflow". Example:</p> <pre><code>&lt;button string="Send to new state" name="signal_new_state" type="workflow" states="draft" class="oe_highlight"/&gt; </code></pre>
python|workflow|transition|state|odoo-8
1
7,030
21,818,193
File object has no attribute encode- BeautifulSoup and Python
<p>I'm trying to figure out the best way to parse a HTML file and make sure I'm dealing with entirely in utf-8 format. Currently I have:</p> <pre><code>fileName = open(givenDir +"/"+ aFile, "r").encode('utf8') soup = BeautifulSoup(fileName) </code></pre> <p>And I continue on my way. These are all local files. But it ...
<p><code>open()</code> returns a file object.</p> <p>If you want to get the contents of the file, use <code>file.read()</code> or <code>file.readline()</code> or <code>file.readlines()</code></p> <p>So that would make your code:</p> <pre><code>fileName = open(givenDir +"/"+ aFile, "r").read().encode('utf8') soup = B...
python|encoding|beautifulsoup
0
7,031
21,767,029
Access the response object in a bottlepy after_request hook
<p>I have the following web app:</p> <pre><code>import bottle app = bottle.Bottle() @app.route('/ping') def ping(): print 'pong' return 'pong' @app.hook('after_request') def after(): print 'foo' print bottle.response.body if __name__ == "__main__": app.run(host='0.0.0.0', port='9999', server='ch...
<blockquote> <p>Is there a way to access the response body before sending the response back?</p> </blockquote> <p>You could write a simple plugin, which (depending on what you're actually trying to do with the response) might be all you need.</p> <p>Here's an example from the <a href="http://bottlepy.org/docs/dev/p...
python|bottle
5
7,032
41,059,001
In Python I want to access a text file while it is being updated by another program
<p><code>if __name__ == "__main__":</code> <code>with open("log.txt", 'r') as f:</code> <code>content = f.readlines()</code> <code>for i, line in enumerate(content):</code></p> <p>I am using above code to read text file. But it only gets current data </p>
<p>Depending on operating system, you have a couple of choices.</p> <ol> <li>Check if the file has changed since last time.</li> <li>In Linux there is this "new" functionality that will inform you of changes made to a file.</li> </ol> <p>It was a while back since I tried to work with something similar and guess what,...
python-3.x
0
7,033
38,277,151
How do I resolve the "TypeError: unorderable types: str() < int()" error?
<p>I'm a newbie to Python (I'm only 14), and I want to create a bubble sorter for a random list of integers. The following is my code:</p> <pre><code>list = input("Please put in a random set of integers, in any order you like (unlimited range), separated by spaces:") list = list.split() indexcounter = 0 def sorter...
<p>That Exception is most likely raised here:</p> <pre><code>int(list[indexcounter2]) &lt;= list[indexcounter2 + 1] </code></pre> <p>If you are certain you will only be working with numbers you can change all elements in the list to <code>int</code>s by using the following after the call to <code>input</code>:</p> <...
python|python-3.x
1
7,034
39,936,480
python multiprocessing, cpu-s and cpu cores
<p>I was trying out <code>python3</code> <code>multiprocessing</code> on a machine that has 8 cpu-s and each cpu has four cores (information is from <code>/proc/cpuinfo</code>). I wrote a little script with a useless function and I use <code>time</code> to see how long it takes for it to finish.</p> <pre><code>from mu...
<p>Simplified and short.. Cpu-s and cores are hardware that your computer have. On this hardware there is a operating system, the middleman between hardware and the programs running on the computer. The programs running on the computer are allotted cpu time. One of these programs is the python interpetar, which runs al...
python|multiprocessing
0
7,035
39,962,949
Reading multiple CSV files with headers in python with numpy?
<p>Currently I am using this code to read one complete csv file to my code:</p> <pre><code>data = np.loadtxt('csv_Complete.csv', delimiter=',', skiprows=1) </code></pre> <p>However, Now I have multiple csv files that are in this format.</p> <p>Log1.csv</p> <pre><code>x1,x2,x3,x4.... 1.5,3,5,7,8 2,5,1.2,5,2 1,3,3,5....
<p>It must be a <code>missing value</code> in file <code>log40a.csv</code>.</p> <p>I have the same error for file like:</p> <pre><code>x1,x2,x3,x4.... 1,3.3,5,7,8 2,5.1,,5.5,2 1,3,3,5,6 </code></pre> <p>Base on <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html" rel="nofollow">documenta...
python
1
7,036
29,133,422
Extract Columns from a Protein Data Bank (PDB) Text File
<p>I want to make a plot with Matplotlib in Python and therefore read some data from a PDB-file (protein data bank). I want to extract every column from the file and store these columns in separate vectors. The PDB-file consists of columns with both text and floats. I'm very new to Matplotlib and I have tried several m...
<p>The Protein Data Bank (pdb) file format is a textual file format describing the three-dimensional structures of molecules held in the Protein Data Bank. The pdb format accordingly provides for description and annotation of protein and nucleic acid structures including atomic coordinates, observed sidechain rotamers ...
python|file|protein-database
1
7,037
8,873,368
How many common English words of 4 letters or more can you make from the letters of a given word (each letter can only be used once)
<p>On the back of a block calendar I found the following riddle:</p> <blockquote> <p>How many common English words of 4 letters or more can you make from the letters of the word 'textbook' (each letter can only be used once).</p> </blockquote> <p>My first solution that I came up with was:</p> <pre><code>from ite...
<p>I thought I'd share this slightly interesting trick although it takes a good bit more code than the rest and isn't really "pythonic". This will take a good bit more code than the other solutions but should be rather quick if I look at the timing the others need. </p> <p>We're doing a bit preprocessing to speed up t...
python|algorithm|permutation|puzzle
3
7,038
51,855,868
Trio execution time without IO operations
<p>I'm doing examples to understand how it works python asynchronously. I read the Trio documentation and I thought that only one task can be executed in the loop every time and in every <code>checkpoint</code> the <code>scheduler</code> decide which task will be executed.</p> <p>I did an example to test it, in the tr...
<p>After a small talk with the Trio author, <a href="https://stackoverflow.com/users/1925449/nathaniel-j-smith">Nathaniel J. Smith</a> he found the problem in my code. The problem is in the synchronous example. I'm using global variables instead of local variables like in the asynchronous example.</p> <p>Nathaniel: "I...
python|python-3.x|python-asyncio|python-trio
9
7,039
51,619,868
"No such file or directory" when using Windows Linux Subsystem bash with VS Code
<p>I am using VS Code on Windows 10 with the Windows Linux Subsystem &amp; Ubuntu 18.04.</p> <p>What I am attempting to do is use VS Code as a python development environment with bash as its terminal and the python3 interpreter installed on the Ubuntu system as its default python executable.</p> <p>In my User configu...
<p>While there does not appear to be official support in Visual Studio Code for Windows, the plugin "Code Runner" with the runInTerminal setting fixes this problem.</p> <p>It adds a "Run Code" (Alt-Ctrl-N) to the right-click window of an open editor.</p> <p>If you set the User setting:</p> <p>"code-runner.runInTermi...
python|windows|visual-studio-code|windows-subsystem-for-linux
3
7,040
51,640,572
parsing two files and make a corresponding string for each id
<p>I have two files like this:</p> <p><strong>p.txt</strong></p> <pre><code>{1=[128, 12, 132], 2=[137, 1, 141, 5, 129, 9], 3=[2, 138, 6, 142]} </code></pre> <p><strong>s.txt</strong></p> <pre><code>{1=[200, 11, 987], 2=[765, 198, 31, 912, 234, 11], 3=[19, 12, 38, 60, 212]} </code></pre> <p>In both the above files,...
<p>You can use <code>ast.literal_eval</code> for converting string to python object. Of course, your input need some modification before that - using <code>re</code> module for example:</p> <pre><code>from ast import literal_eval import re p_str = "{1=[128, 12, 132], 2=[137, 1, 141, 5, 129, 9], 3=[2, 138, 6, 142]}" s...
python|linux|bash
0
7,041
62,292,508
Check if two np arrays have the same tuple inside of them
<p>I have two arrays with multiple np arrays inside of them containing tuples of points in (x, y). </p> <p>A1 = array([array[(x1, y1), (x2, y2)..], [array[(x1, y1), (x2, y2)..]])</p> <p>A2 = array([array[(x1, y1), (x2, y2)..], [array[(x1, y1), (x2, y2)..]])</p> <p>I want to check if a tuple in one array from A1 exis...
<pre><code>In [319]: ar1 Out[319]: array([(1, 2), (2, 2), (3, 6)], dtype=object) In [320]: ar2 Out[320]: array([(1, 2), (3, 2), (5, 4)], dtype=object) </code>...
python|arrays|numpy|numpy-ndarray
2
7,042
63,713,376
Dataframes and looping
<p>I have a list of tickers (186) and for each I need to get prices... I am doing it with loops and for each ticker I want a new df numbered from 0 to 186.</p> <p>for info: len(tickers_list)=186</p> <pre><code>for i in range(len(tickers_list)-180): try: data = pdr.get_data_yahoo(tickers_list[i], start=df['D...
<p>Assuming <code>get_data_yahoo</code> returns a <code>DataFrame</code> and you are selecting only the <code>'Adj Close'</code> column, you could collect all series in a dictionary and later concatenate them into a dataframe.</p> <pre><code>data = dict() for i, (ticker, start_date) in enumerate(zip(tickers_list[:6], ...
python|dataframe|loops|for-loop
0
7,043
16,755,014
Dynamically add rows to GTK List PyGObject
<p>I'm trying to add items dynamically detected into a PyGTK listview.</p> <p>I'm using Python 3 and PyGObject.</p> <p>Here are some example lists:</p> <pre><code>['MomAndKids', 'ddwrt', 'Squirt', 'blurb'] ['WPA1', 'Open', 'WPA2', 'WEP'] ['44/70', '38/70', '66/70', '55/70'] </code></pre> <p>I want it to make a row ...
<p>This did it. I'm not sure if it is the most efficient way, but it worked exactly like I planned.</p> <pre><code> i = 0 for network in output: aps["row" + str(i)] = self.APStore.append([network, "", "", ""]) i = i + 1 i = 0 for encrypt in output2: self.APStore.set(aps["row" + s...
python|python-3.x|gtk3|pygobject|gtktreeview
0
7,044
54,357,729
How to use slicing on queryset for django form?
<p>Let's say I have a django Model Player. Player model has a filed name 'points' a integer field. I need to show top 10 players ordered by points in from.ModelChoiceField.</p> <p>The queryset would be</p> <pre><code>Player.objects.all().order_by('-points')[:10] </code></pre> <p>But if I use slicing on queryset whi...
<p>This seems to be a duplicate of <a href="https://stackoverflow.com/questions/3470111/cannot-filter-a-query-once-a-slice-has-been-taken">this</a></p> <p>But the answers there should clear stuff up for you</p> <p>Taken from: <a href="https://docs.djangoproject.com/en/2.2/ref/models/querysets/" rel="nofollow noreferr...
python|django|django-models|django-forms
0
7,045
38,994,377
Receive push data in R Shiny application
<p>I have a simple python program, which should push its data into an R Shiny application. These lines in Shiny parse the "GET" input:</p> <pre><code> # Parse the GET query string output$queryText &lt;- renderText({ query &lt;- parseQueryString(session$clientData$url_search) eventList[query$eventid] &lt;&lt...
<p>My complete solution using websockets with httpuv: </p> <pre><code>library(httpuv) startWSServer &lt;- function(){ if(exists('server')){ stopDaemonizedServer(server) } app &lt;- list( onWSOpen = function(ws) { ws$onMessage(function(binary, message) { #handle your message, f...
python|r|get|shiny|shiny-server
2
7,046
55,347,336
Django redirect after search using a queryset
<p>When I click search on the homepage, I want it to take that query set e.g (<code>http://127.0.0.1:8000/?q=car</code>) and then use the same url, but in the search view. I have tried searching around but couldn't find anything that was working.</p> <p>Views:</p> <pre><code>class IndexView(ListView): model = Pos...
<p>I think you're mixing up the logic a bit on where to do the actual query. You should't do the actual query search in the <code>IndexView</code> that is meant for the <code>SearchListView</code>.</p> <p>From the information that's available right now (without the <code>SearchListView</code>) I'd say you could do a r...
python|html|django
1
7,047
52,851,184
Get int value from each two bytes
<p>I am trying to read bytes from an image, and get all the int (16 bit) values from that image. After I parsed the image header, I got to the pixel values. The values that I get when the pair of bytes are like b"\xd4\x00" is incorrect. In this case it should be 54272, not 3392.</p> <p>This are parts of the code: I us...
<p>There are much better ways of converting bytes to integters:</p> <ul> <li><p><a href="https://docs.python.org/3/library/stdtypes.html#int.from_bytes" rel="nofollow noreferrer"><code>int.from_bytes()</code></a> takes bytes input, and a byte order argument:</p> <pre><code>&gt;&gt;&gt; int.from_bytes(b"\xd4\x00", 'bi...
python|byte
3
7,048
37,449,199
In Python, how to write a regular expression matching strings starting with string A but NOT ending with B
<p>I have some strings like:</p> <pre><code>tool_abc tool_abc_data tool_xyz tool_xyz_data file_abc file_xyz_data </code></pre> <p>My goal is to have an RegEx to match any strings starting with <code>tool_</code> and NOT ending with <code>_data</code>. How can I write one?</p>
<p>From <a href="https://docs.python.org/2/library/re.html#regular-expression-syntax" rel="nofollow">https://docs.python.org/2/library/re.html#regular-expression-syntax</a>:</p> <pre><code>(?&lt;!...) Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind...
python|regex
2
7,049
66,316,672
My tensorflow neural network accuracy does not change
<p>I wants to build a neural network for <a href="https://stats.idre.ucla.edu/stat/data/binary.csv" rel="nofollow noreferrer">Student Admission dataset</a>(admit, gre, gpa, rank) I made admit and rank one-hot as follows</p> <pre><code> one_hot_data = pd.concat([data, pd.get_dummies(data['rank'], prefix='rank')], axi...
<p>There may be many possible causes here (and we don't have your data), but, according to my experience, a frequent mistake in such cases is initializing the weights with the default argument of <code>stddev=1.0</code> in <code>tf.random_normal()</code> (see the <a href="https://www.tensorflow.org/api_docs/python/tf/r...
python|tensorflow|machine-learning|neural-network
1
7,050
7,553,726
blender: how to export shape keys using python?
<p>I want to export shape keys for some object. How can i get access to a shape key's mesh ? I'm using blender 2.59. Thanks</p>
<p>i did it. Here is the script. maybe it would be helpful for someone:</p> <pre><code>import bpy import xml.dom.minidom path = "/Users/x/Documents/y/game_projects/test.xml" dom = xml.dom.minidom.getDOMImplementation() tree = dom.createDocument(None, "document", None) root = tree.documentElement root.setAttribute("...
python|export|blender
7
7,051
7,577,546
Using pandas, how do I subsample a large DataFrame by group in an efficient manner?
<p>I am trying to subsample rows of a DataFrame according to a grouping. Here is an example. Say I define the following data:</p> <pre><code>from pandas import * df = DataFrame({'group1' : ["a","b","a","a","b","c","c","c","c", "c","a","a","a","b","b","b","b"], 'group2' : [...
<p>I tested with apply, it seems that when there are many sub groups, it's very slow. the groups attribute of grouped is a dict, you can choice index directly from it:</p> <pre><code>subsampled = df.ix[(choice(x) for x in grouped.groups.itervalues())] </code></pre> <p>EDIT: As of pandas version 0.18.1, <code>itervalu...
python|r|numpy|pandas|data.table
9
7,052
16,254,481
Python pygame event loop type error
<p>I am making a simple pygame game. My problem is, when I try to check if the user is clicking the exit button, I get an error. Here's the Code:</p> <pre><code>for event in pygame.event.get(): if event.type == pygame.QUIT(): pygame.quit() sys.exit() </code></pre> <p>Here's the error:</p> <pre><code...
<pre><code>&gt;&gt;&gt; pygame.QUIT 12 </code></pre> <p>So, </p> <pre><code>&gt;&gt;&gt; pygame.QUIT() &gt;&gt; 12() TypeError: 'int' object is not callable </code></pre> <p>IN text, <code>pygame.QUIT = 12</code> so doing <code>pygame.QUIT()</code> is equivalent of doing <code>12()</code>, which is a call, which is ...
python|events|loops|pygame|typeerror
2
7,053
38,660,053
Equivalent of MATLAB's patternsearch in Python/SciPy?
<p>I am looking for a Python equivalent of <a href="http://de.mathworks.com/help/gads/patternsearch.html" rel="nofollow">MATLAB's patternsearch optimization algorithm</a>. I ran through the SCiPy documentation but did not find something similiar. Do you know whether there is some patternsearch algorithm available in Py...
<p>There is one library called &quot;pymoo&quot; which is created for the implementation of optimization algorithms in python.</p> <p>here are a few resources you can check,</p> <ul> <li><a href="https://pypi.org/project/pymoo/" rel="nofollow noreferrer">https://pypi.org/project/pymoo/</a> [pypi.org page with installat...
python|optimization|scipy|minimization
0
7,054
40,352,436
Python Dataframe for loop syntax
<p>I'm having trouble in correctly executing a for loop through my dataframe in python.</p> <p>Basically, for every row in the dataframe (df_weather), the code should select one value each from the column no. 13 and 14 and execute a function which is defined earlier in the code. Eventually, I require the calculated va...
<p>your number one problem is the following line:</p> <p><code>for i in df_weather:</code> This line is actually yielding you the column titles and not the rows themselves. What you're looking for is actually the following: </p> <p><code>for i in df_weather.values():</code>. The <code>values</code> will return a nump...
python|for-loop|dataframe
0
7,055
68,434,126
Print the console results inside a textbox (two file py)
<p>In a Tkinter window of the Test.py file, I would like to display in a textobox what is printed in the Python console.</p> <p>By clicking on button, you start a function in the Test.py file that calls the X.py and Y.py scripts (more precisely their functions). The results of the scripts are printed correctly in the P...
<p>For Python 3.4+, you can use <code>contextlib.redirect_stdout</code> (see <a href="https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout" rel="nofollow noreferrer">official document</a>) to redirect <code>sys.stdout</code> to another file or file-like object temporarily.</p> <pre class="lang-p...
python|python-3.x|tkinter
1
7,056
2,136,371
Dynamic Django model creation based on existing DB table
<p>I'm trying to figure out how I can use the type() module to dynamically create a Django model based on existing DB tables without having to either write it out manually or use the manage.py generator to inspect the DB. Reason is my schema changes frequently -- adding new tables, adding/deleting columns, etc. Anyon...
<p>You can look at <a href="http://code.djangoproject.com/browser/django/trunk/django/core/management/commands/inspectdb.py" rel="nofollow noreferrer">inspectdb code</a>, and instead of outputting code return classes.</p>
python|django|django-models
1
7,057
1,898,310
What is the difference between the __int__ and __index__ methods in Python 3?
<p><a href="http://docs.python.org/release/3.2.1/reference/datamodel.html" rel="noreferrer">The Data Model section of the Python 3.2 documentation</a> provides the following descriptions for the <code>__int__</code> and <code>__index__</code> methods:</p> <blockquote> <h3><code>object.__int__(self)</code></h3> ...
<p>See <a href="http://www.python.org/dev/peps/pep-0357/" rel="noreferrer">PEP 357</a>: Allowing Any Object to be Used for Slicing.</p> <blockquote> <p>The <code>nb_int</code> method is used for coercion and so means something fundamentally different than what is requested here. This PEP proposes a method for s...
python|casting
20
7,058
1,794,161
How do I make set_printoptions(suppress=True) permanent?
<p>In numpy there is a function that makes arrays print prettier.</p> <pre><code>set_printoptions(suppress = True) </code></pre> <p>In other words, instead of this:</p> <pre><code>array([[ 0.00000000e+00, -3.55271368e-16, 0.00000000e+00, 1.74443793e-16, 9.68149172e-17], [ 5.08273978e-17, -4....
<p>I added this to the <code>main()</code> function in <code>~/.ipython/ipy_user_conf.py</code>:</p> <pre><code>from numpy import set_printoptions set_printoptions(suppress = True) </code></pre> <p>and it seems to work.</p> <p>In later IPython versions, run <code>ipython profile create</code>, then open <code>~\.ipy...
numpy|customization|ipython
2
7,059
1,732,452
Django ease of building a RESTful interface
<p>I'm looking for an excuse to learn Django for a new project that has come up. Typically I like to build RESTful server-side interfaces where a URL maps to resources that spits out data in some platform independent context, such as XML or JSON. This is rather straightforward to do without the use of frameworks, but ...
<p>This is probably pretty easy to do.</p> <p>URL mappings are easy to construct, for example:</p> <pre><code>urlpatterns = patterns('books.views', (r'^books/$', 'index'), (r'^books/(\d+)/$', 'get')) </code></pre> <p>Django supports <a href="http://docs.djangoproject.com/en/dev/topics/serialization/" rel="norefe...
python|django|rest
15
7,060
62,956,575
Why isn't my regex working with str.contains?
<p>I have a very simple search string. I am looking for a shop called &quot;Lidl&quot;.</p> <p>My dataframe:</p> <pre><code> term_location amount 0 Lidl 2.28 1 Lidl 16.97 2 Lidl 2.28 3 Lidl 16.97 4 Lidl 16.97 5 Lidl 16.97 6 Lidl 16.97 7 ...
<p>Your regular expression is not working because you are trying to match the word &quot;lidl&quot; exactly as it is (in lowercase).</p> <p>You should either change the first character of the word to uppercase:</p> <pre class="lang-py prettyprint-override"><code>re.compile(r&quot;\bLidl\b&quot;) </code></pre> <p>or use...
python|regex|pandas
2
7,061
32,179,848
Pandas pivot table
<p>When I run my code using Pandas on Windows it works well, however when running on Ubuntu I get the following error:</p> <pre><code>canceled_Table = pd.pivot_table(canceled, index = 'end', columns = 'pcode', values = 'quantity', aggfunc = np.sum) </code></pre> <blockquote> <p>TypeError: pivot_table() got an unexp...
<p>It's highly likely that your pandas versions are different, on windows you're running a version <code>0.16.0</code> or newer and your ubuntu version is older. There was an api change in <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#removal-of-prior-version-deprecations-changes" rel="nofollow"><c...
python|python-2.7|pandas
0
7,062
28,252,585
Functional pipes in python like %>% from R's magrittr
<p>In R (thanks to <a href="https://magrittr.tidyverse.org/" rel="noreferrer">magrittr</a>) you can now perform operations with a more functional piping syntax via <code>%&gt;%</code>. This means that instead of coding this:</p> <pre><code>&gt; as.Date(&quot;2014-01-01&quot;) &gt; as.character((sqrt(12)^2) </code></pre...
<p>Pipes are a new feature in <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#pipe" rel="noreferrer">Pandas 0.16.2</a>.</p> <p>Example:</p> <pre><code>import pandas as pd from sklearn.datasets import load_iris x = load_iris() x = pd.DataFrame(x.data, columns=x.feature_names) def remove_units(df):...
python|functional-programming|pipeline
54
7,063
44,306,109
Calling python script from C#
<p>I have a C# code which helps to run python environment first and then it executes my python process. But the problem is it takes a lot of time to execute. </p> <p>Actually i just want to pass my values and execute single line of code in python script. But need to execute all python code every time. Is there a way ...
<p>I would suggest you to use REST API to call python code from C# application. To achieve that you need to use two libraries: CPickle and flask </p> <ol> <li>Expose line of code as a function and annotate </li> <li>Serialise your model after training and load when predicting</li> </ol> <p>Please refer to this code, ...
c#|python|machine-learning|ipc
3
7,064
54,323,335
cx_Freeze Mac-build stopped at _ctypes for Homebrew-and-Python
<p>We use cx_Freeze to produce standalone binary build of our python application under Mac OS. The build runs well under the build machine (which has Homebrew-and-Python installed), but failed in client machine with following error messages.</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/pyth...
<p>I found the solution by myself.</p> <p>This issue is caused by wrongly linked dylib files. We use "<strong>otool -L</strong>" to find the dependency and re-link them with "<strong>install_name_tool -change</strong>" one by one. Finally the program works.</p>
macos|python-2.7|homebrew|cx-freeze
1
7,065
34,871,637
Parsing unicode csv with unicodecsv module
<p>Parsing csv output of console command with Python 2.7. Standart <code>csv</code> module did not work properly, so I`ve found <code>unicodecsv</code> module. The iteration outputs strange results (empty lists or strings separated to chars), but I expect to see list with values for each row:</p> <pre><code>import un...
<p>According to the documentation <a href="https://pypi.python.org/pypi/unicodecsv/0.14.1" rel="nofollow"><code>unicodecsv</code></a> expects a bytestream. So</p> <pre><code>with open('file.txt', 'rb') as f: data = unicodecsv.reader(f, delimiter=',') </code></pre> <p>should work. Actually if you look at the <a hr...
python|python-2.7|csv
1
7,066
27,349,083
Twisted Web Client HTTP Version
<p>If I am issuing an HTTP request using twisted.web.client.Agent how do I force the request to use HTTP 1.0? By default HTTP 1.1 is used.</p> <p>Edit: The reason why I am interested in using HTTP 1.0 is because I wish to disable Chunked Transfer Encoding, and the most reliable way of doing this is by using HTTP 1.0.<...
<p>If you want to use <code>twisted.web.client.Agent</code>, you can’t without monkeypatching or something. Tracing through <a href="https://twistedmatrix.com/trac/browser/trunk/twisted/web/_newclient.py?rev=42679#L630" rel="nofollow">the source</a>, one of the things you’ll find is:</p> <pre><code># In the future, ha...
python|twisted|twisted.web
1
7,067
26,976,791
Python script for zoning WWN
<p>I am just learning basic python for myself - and hoping to make some simple ..and I mean simple scripts to do a few repetitive tasks</p> <p>One of these is zoning WWN for Cisco switches in a SAN</p> <p>Normally we would need 2 WWNs of 2 ports (ie a host =20:00:00:00:00:00:00:00 + Storgae box =50:06:01:00:00:00:00:...
<p>You Can use regex to achieve the same:</p> <pre><code>import re wwn="5006010000000000" ':'.join(re.findall('..', wwn)) '50:06:01:00:00:00:00:00' </code></pre>
python
0
7,068
8,082,126
Programmatically get the list of versions from appengine
<p>I'd like to get a list of deployed versions from appengine, either from the remote API or via appcfg.py. I can't seem to find any way to do it, certainly not a documented way. Does anyone know of any way to do this (even undocumented)?</p>
<p>I was able to do this by copying some of the RPC code from appcfg.py into my application. I posted up <a href="https://gist.github.com/MattFaus/7275456" rel="nofollow">this gist</a> that goes into detail on how to do this, but I will repeat them here for posterity.</p> <ol> <li><a href="https://developers.google.c...
python|google-app-engine
1
7,069
1,205,343
Debugging Ruby/Python/Groovy
<p>I'm rephrasing this question because it was either too uninteresting or too incomprehensible. :)</p> <p>The original question came about because I'm making the transation from Java to Groovy, but the example could apply equally when transitioning to any of the higher-level languages (Ruby, Python, Groovy).</p> <p>...
<p>If I were to debug your example, the first thing I would do is break it down into multiple steps. I don't care if it's "pythonic" or "the ruby way" or "tclish" or whatever, code like that can be difficult to debug. </p> <p>That's not to say I don't write code like that. Once it's been debugged it is sometimes OK to...
python|ruby|debugging|groovy|dynamic-languages
3
7,070
659,415
Python sequence naming convention
<p>Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous ...
<p>In general, avoid this kind of behaviour. Notice from <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">PEP8</a></p> <blockquote> <p>A Foolish Consistency is the Hobgoblin of Little Minds</p> </blockquote> <p>which is exactly what calling a variable <code>weightss</code> would be doi...
python|naming-conventions|sequence
20
7,071
710,551
Use 'import module' or 'from module import'?
<p>I've tried to find a comprehensive guide on whether it is best to use <code>import module</code> or <code>from module import</code>. I've just started with Python and I'm trying to start off with best practices in mind.</p> <p>Basically, I was hoping if anyone could share their experiences, what preferences other de...
<p>The difference between <code>import module</code> and <code>from module import foo</code> is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.</p> <p><code>import module</code></p> <ul> <li><strong>Pros:</strong> <ul> <li>Less maintenance...
python|python-import
587
7,072
47,393,356
How to use tensorflow's Dataset API Iterator as an input of a (recurrent) neural network?
<p>When using the tensorflow's Dataset API Iterator, my goal is to define an RNN that operates on the iterator's <code>get_next()</code> tensors as its input (see <code>(1)</code> in the code).</p> <p>However, simply defining the <code>dynamic_rnn</code> with <code>get_next()</code> as its input results in an error: <...
<p>Turns out the mysterious error is likely a bug in tensorflow, see <a href="https://github.com/tensorflow/tensorflow/issues/14729" rel="noreferrer">https://github.com/tensorflow/tensorflow/issues/14729</a>. More specifically, the error really comes from feeding a wrong data type (in my example above, the <code>data</...
tensorflow|rnn|tensorflow-datasets
5
7,073
47,208,769
Python: How to merge 1 list of n dicts
<p>I have this list:</p> <p>I want to be able to group these dictionaries according to the department</p> <pre><code>departments = [ { "department": 4, "user": 1, "status": False }, { "department": 2, "user": 1, "status": True }, { "department": 2, "user": 2, "status": True }] </co...
<p>You can try this:</p> <pre><code>import collections new_data = [(a, list(b)) for a, b in itertools.groupby(departments, key=lambda x:x["department"])] final_data = [{"department":a, 'status':list(set([i["status"] for i in b])), 'user':[i["user"] for i in b]} for a, b in new_data] </code></pre> <p>Output:</p> <pre...
python|dictionary
1
7,074
58,429,161
Creating Usable Path Variables
<p>I'm trying to write a piece of software that works on multiple systems. The section of code I have become stuck on is as follows:</p> <pre><code>import shutil from os import environ, getcwd getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"] user = getUser() source = r"C:\Users\ " + str...
<blockquote> <p>No such file or directory: 'C:\Users\Jack\AppData\Roaming\Microsoft\Windows\StartMenu\Programs\Startup'</p> </blockquote> <p>Right; the folder is <code>Start Menu</code>, not <code>StartMenu</code>. Removing spaces from the string was a mistake, presumably trying to fix this:</p> <pre><code>source =...
python
0
7,075
33,970,278
python3 : Cannot Import cv2 : DLL load failed after installing opencv_contrib modules
<p>I had been using cv2 in python on Windows 7 for basic image processing , but wanted xfeatured2d from the opencv_contrib package. I followed the instructions given in <a href="https://www.youtube.com/watch?v=vp0AbhXXTrw" rel="nofollow">https://www.youtube.com/watch?v=vp0AbhXXTrw</a> up till the point of building t...
<p>I installed latest OpenCV from Git master on Ubuntu 12.10 with Python 3.2 and 3.3 bindings. </p> <p>But if you want at Window check below given Link</p> <p><a href="http://sourceforge.net/projects/opencvlibrary/files/opencv-win/" rel="nofollow">Open CV Package Installation</a></p> <p>if Ubuntu before I did for Li...
python|opencv|python-3.x|python-3.4
1
7,076
67,873,889
Python subprocess.Popen method not executing "start chrome" command
<p>I tried executing <code>start chrome</code> in the command line and it worked. However when I tried the same using subprocess.Popen(), throws a file not found error.</p> <p>Please find blow the code and let me know the reason for the same.</p> <pre><code>import subprocess as sp sp.Popen(['start','chrome']) </code></...
<p>I can not tell you why it does not work with subprocess, but if you do not rely on it, try os:</p> <pre><code>import os os.system(&quot;start chrome&quot;) </code></pre>
python
1
7,077
37,085,203
How to pass a variable from pyqt to .py file and execute it on button click?
<p>I want to pass a filename from this pyqt4 app to another .py file and execute the respective .py file when button is clicked.</p> <p><strong>GUI.py</strong> </p> <pre><code>from PyQt4 import QtCore, QtGui import subprocess class QDataViewer(QtGui.QMainWindow): def __init__(self): QtGui.QWidget.__ini...
<p>You're looking for <a href="https://docs.python.org/2/library/sys.html#sys.argv" rel="nofollow">command line arguments</a>. Change the <code>run</code> function to this:</p> <pre><code>def run(self, path): subprocess.call(['python',path,self.filename]) </code></pre> <p>to pass the file name as a command line a...
python|pyqt|pyqt4
2
7,078
48,692,500
fit-transform on training data and transform on test data
<p>I am having trouble understanding how exactly <code>transform()</code> and <code>fit_transform()</code> are working together.</p> <p>I call <code>fit_transform()</code> on my training data set and <code>transform()</code> on my test set afterwards.</p> <p>However if I call <code>fit_transform()</code> on the test ...
<p>Let's take an example of a transform, <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" rel="noreferrer">sklearn.preprocessing.StandardScaler</a>.</p> <p>From the docs, this will:</p> <blockquote> <p>Standardize features by removing the mean and scaling to unit ...
python|scikit-learn
29
7,079
20,168,900
How would I get my game over screen stay on the screen
<pre><code>import pygame, random, time from time import sleep from pygame import* pygame.init() myname=input('What is your name') #set the window size window= pygame.display.set_mode((800,600) ,0,24) pygame.display.set_caption("Fruit Catch") gameover=pygame.image.load('fifa.jpg') #game variables myscore=0 mylives=3 mou...
<p>If line is 0 then you run some blits and update twice</p> <p>First inside <code>if mylives==0:</code> (and it stay for awhile becaus you use delay(10) )</p> <p>Second time at the end of loop.</p> <p>Use:</p> <pre><code>if mylives==0: #blit and update game over else: #blit and update normal game </code></pr...
python|pygame
0
7,080
66,923,808
Why can I find this text box element in selenium?
<p>Hi I cant get my selenium code to find this element in a page, it appears after ive used code to click a button on a page which opens up a form under the button.</p> <p>Im looking to try get it to click on this input text box</p> <pre><code>&lt;input id=&quot;number&quot; class=&quot;iField&quot; type=&quot;text&quo...
<pre><code>from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By num = WebDriverWait(driver1, 10).until( EC.visibility_of_element_located((By.XPATH,&quot;//*[@id='number']&quot;))) </code></pre> <p>your w...
python|selenium
0
7,081
66,869,968
handling large timestamps when converting from pyarrow.Table to pandas
<p>I have a timestamp of <code>9999-12-31 23:59:59</code> stored in a parquet file as an int96. I read this parquet file using pyarrow.dataset and convert the resulting table into a pandas dataframe (using pyarrow.Table.to_pandas()). The conversion to pandas dataframe turns my timestamp into <code>1816-03-30 05:56:07.0...
<p>My understanding is that your data has been saved using <code>use_deprecated_int96_timestamps=True</code>.</p> <pre><code>import pyarrow as pa import pyarrow.parquet as pq my_table = pa.Table.from_arrays([pa.array(['9999-12-31', '9999-12-31', '9999-12-31']).cast('timestamp[us]')], names = ['my_timestamps']) pq.wri...
python|pandas|timestamp|parquet|pyarrow
1
7,082
4,474,430
How can I get unicode characters from a URL parameter?
<p>I need to use a GET request to send JSON to my server via a JavaScript client, so I started echoing responses back to make sure nothing is lost in translation. There doesn't seem to be a problem with normal text, but as soon as I include a Unicode character of any sort (e.g. &quot;ç&quot;) the character is encoded s...
<p>Everything looks fine to me.</p> <pre><code>&gt;&gt;&gt; hex(ord(u'°')) '0xb0' &gt;&gt;&gt; hex(ord(u'ç')) '0xe7' </code></pre> <p>Perhaps you should decode the JSON before attempting to use it.</p>
python|unicode|encoding|character-encoding|special-characters
3
7,083
4,070,082
Fetching nested child records in django framework
<p>This project is being developed in python and django.</p> <p>As per my requirement I want to querying all the products from the categories upto two to three level up...</p> <p>My entity structure is as follows.</p> <pre><code>Category: - Name - ParentCategory Product: - ID - Name - Category </code></pre> <p>Her...
<p>What about thinking an implementation of <a href="http://translate.google.fr/translate?js=n&amp;prev=_t&amp;hl=fr&amp;ie=UTF-8&amp;layout=2&amp;eotf=1&amp;sl=fr&amp;tl=en&amp;u=http://sqlpro.developpez.com/cours/arborescence/&amp;act=url" rel="nofollow">2-interval graphs</a> ?</p>
python|django|django-models
1
7,084
69,313,439
Python - Proper way to add attributes to functions
<p>I have a list of functions that do the same tasks in different ways. Let's call them scrapper_german, scrapper_english, scrapper_spanish. I want to make my program know things about this functions, like how effective they are in some tasks. I can use a dictionary.</p> <pre><code>function_info = { 'scrapper_english':...
<p>Propably the best way is to use class <code>__call__</code> function to imitate your function with class possibilities</p> <p>something like this:</p> <pre><code>class EnglishScraper: info_1=None info_2=None info_3=None info_4=None performance=None def __init__(self): &quot;&quot;&qu...
python
1
7,085
48,354,675
How to print comparison matrix in python?
<p>Do you probably know how I can print a comparison matrix in python, I have 5 variables, I apply T test(defined a function as ttest to apply the T test between 2 data samples) on them one by one and get 10 comparison results, now I want to visualize the results just like correlation matrix or a table, to visualize th...
<p>Your question is incredibly unclear but I think I can see vaguely what you want...</p> <p>So you have a <code>list</code> (or some other data type) which contains <code>5</code> elements and want to apply some <code>function</code> to every combination of <code>2</code> elements.</p> <p>We can achieve this with <c...
python
0
7,086
51,185,638
Text qualifiers getting misplaced while trying to remove extra delimiters in csv file using python
<p>I am trying to remove extra delimiters in between the data using a python script. I usually work with large data sets. For example:</p> <pre><code>"abc","def","ghi","jkl","mno","pqr" "","","fds","dfs","adfadf","AAAA111" "","","fds","df,s","adfadf","AAAA111" </code></pre> <p>If I run the script, the script will re...
<pre><code>writer = DictWriter( corrected_people_file, fieldnames=[ "abc", "def", "ghi", "jkl", "mno", "pqr" ],delimiter=',',quoting=csv.QUOTE_ALL) </code></pre> <p><code>QUOTE_ALL</code> will force all fields to be quoted, and existing double quotes will be escaped with another double quote.</p> ...
python|csv
0
7,087
51,544,775
How to groupby two fields and set index as one of the two fields. Pandas, Python-3
<p>I'm new to Stack Overflow so any community best practices are welcome too.</p> <pre><code>#aggregate rides and average of fares combo_grouped_df =combo_df.groupby(['city','type']) #combo_grouped_df.set_index('city') does not work! combo_grouped_df.head() avg_fare =combo_grouped_df['fare'].mean() total_rides =com...
<p>All you need is:</p> <pre><code>import pandas as pd # Group it group_df = combo_df.groupby(['city','type']) # Aggregate it aggregated_df = group_df.agg({'fare': 'mean', 'ride_id': 'count'}) # Reset index (only type) summary_df = aggregated_df.reset_index(level=1) </code></pre>
python|python-3.x|pandas|group-by
3
7,088
17,558,551
Write UDP data to CSV in Python?
<p>DISCLAIMER: I am a total Python n00b and have never ever written anything in Python, I haven't programmed anything in years, and the last language I learned was Visual Basic 6. So bear with me!</p> <p>So I have an Android app that transmits my phone's sensor (accelerometer, magnet, light etc) data to my Windows PC...
<p><code>writerow</code> expects a sequence or iterable of values. But you just have one value.</p> <p>The reason it sort of works, but does the wrong thing, is that your one value—a <code>bytes</code> string—is actually itself a sequence. But it's not a sequence of the comma-separated values, it's a sequence of bytes...
python|csv|encoding|udp|ascii
0
7,089
17,651,031
Does Django have exception for an immediate http response?
<p>Django-Tastypie has <code>ImmediateHttpResponse</code> exception which allow to return to the client an immediate response:</p> <pre><code>raise ImmediateHttpResponse(response='a message') </code></pre> <p>Django has <a href="https://docs.djangoproject.com/en/dev/topics/http/views/#the-http404-exception" rel="nofo...
<p>I think what you want is a <a href="https://docs.djangoproject.com/en/dev/topics/http/middleware/" rel="nofollow">middleware</a> which implements a <a href="https://docs.djangoproject.com/en/dev/topics/http/middleware/#process_exception" rel="nofollow">process_exception</a>.</p> <p>It works like this: you raise an ...
python|django
5
7,090
64,313,164
I don't know what is happening when is tried to upgrade pip fro 20.2.2 to 20.2.3 is showing errors
<pre><code>C:\Users\sulav&gt;python get-pip.py python: can't open file 'get-pip.py': [Errno 2] No such file or directory C:\Users\sulav&gt;python -m pip install -U pip Collecting pip Using cached pip-20.2.3-py2.py3-none-any.whl (1.5 MB) Installing collected packages: pip Attempting uninstall: pip Found existin...
<p>You need to download <code>get-pip.py</code> and make sure that you are in that directory when you are trying to install it. For instance i see that the dirctory you are in is <code>C:\Users\sulav&gt;</code> make sure that it is downloaded to this directory.</p>
python
0
7,091
69,828,793
How to specify a type hint for a Pandas series expression
<p>I define Boolean expressions with type hints to match rows in a pandas DataFrame. The PyCharm code inspection tool flags these expressions.</p> <p>For example, consider the code snippet below given a DataFrame <code>holdings</code> with fields <code>IsCash</code> and <code>Weight</code>:</p> <pre><code>predicate_isc...
<p>The following works and passes code inspection:</p> <pre><code>predicate_iscash: pandas.Series = holdings.IsCash == True predicate_short: pandas.Series = predicate_is_cash &amp; holdings.Weight.le(0) </code></pre>
python|pandas|pycharm
0
7,092
73,003,839
Square root of a number with python bisect?
<p>We can get square root of complete square with bisect as follows:</p> <pre><code>import bisect def squareRootUsingBisect(num): return bisect.bisect_left(list(range(0,num)), num, lo=0, hi=num, key=lambda v: v*v) print(squareRootUsingBisect(169)) </code></pre> <p>appropriately prints square root of 169:</p> <pre>...
<p>bisect_left only gives you the nearest root. If you want to check whether <code>num</code> actually is a real square, you have to check afterwards (<code>bisect</code> doesn't come with an option to do that)</p> <pre><code>import bisect def squareRootUsingBisect(num): n = bisect.bisect_left(list(range(0,num)), ...
python
2
7,093
72,849,027
how do I make a code that help to find a match pair based on age and height?
<p>I was looking for the same thing <a href="https://stackoverflow.com/a/72842963/18334455">https://stackoverflow.com/a/72842963/18334455</a> but my problem is how to make a condition so that the matched pair should be within 10 years of age-old and within 10 height difference, I need my code to find the matched rando...
<p>Pretty straight forward with an if condition, it all depends on your data types, but it could in theory look like this:</p> <pre><code>if abs(age1 - age2) &lt; 10 and abs(height1 - height2) &lt; 10: print('Yay you are almost same height and age, so it must be a match!') else: print('No match, you are way too di...
python|pandas|data-collection
0
7,094
55,989,795
How to return True if two-dimensional array in python has at least one True
<p>I'm trying to write a code which checks if 2D-array (consists of only boolean) has at least one True and return True if there is at least one True.</p> <p>I tried using <code>all()</code> function but couldn't come up with a solution. I assume what I need is opposite of what <code>all()</code> function does.</p> <...
<pre><code>def has_true(arr): return any(any(row) for row in arr) In [7]: array1 = [[True, False], [False, False]] In [8]: array2 = [[False, False], [False, False]] In [9]: has_true(array1) Out[9]: True In [10]: has_true(array2) Out[10]: False </code></pre> <p>this answer is using generators so it will return ...
python|python-3.x|multidimensional-array|boolean
2
7,095
49,926,746
Telegram, what is Geolocation method used?
<p>I am developing a Telegram bot. During the conversation bot asks the location_request in this way:</p> <pre><code>reply_keyboard = [[KeyboardButton("Send Location", request_location=True)], [KeyboardButton("/cancel")] ] update.message.reply_text('Share your location:', ...
<p>Unfortunately, you can't know about it :(</p> <p>Even Telegram itself, it didn't verify this data from phone, so there might have someone use <em>Fake GPS</em>.</p>
python|geolocation|telegram-bot
1
7,096
66,372,522
Python script to encrypt a message fails
<p>Trying to encrypt to HMAC-SHA256 by giving my script a key and message.</p> <p>A popular example that I saw online fails to run on my machine:</p> <pre><code>import hmac import hashlib import binascii def create_sha256_signature(key, message): byte_key = binascii.unhexlify(key) message = message.encode() ...
<p>When you call <code>unhexlify</code> it implies that your <code>key</code> is a hexadecimal representation of bytes. E.g. <code>A73FB0FF...</code>. In this kind of encoding, every character represents just 4 bits and therefore you need two characters for a byte and an even number of characters for the whole input st...
python|python-3.x|encryption|hmac
3
7,097
65,077,530
Openedx - Adding Mongo Definition Field while creating course
<p>I am using Ironwood version and trying to add field &quot;program&quot;. Call goes to function create_course and I find following error.</p> <pre><code>File &quot;/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/modulestore/split_mongo/split.py&quot;, line 2007, in create_course search_targets, root_categ...
<p>I have faced the same error, the issue got resolved when I added the field <strong>'program'</strong> to <strong>common/lib/xmodule/xmodule/course_module.py</strong>.</p> <pre><code>class CourseFields(object): ... program = String( display_name=_(&quot;Program&quot;), help=_(&quot;Specify the pro...
python|openedx
1
7,098
5,326,295
Excluding words in Conditions in Python
<p>I'm currently trying to write a program where I have several conditions. I wanted to exclude a list of words (det) from a list of tokens. Up to <code>if len(W) &lt;=8:</code>, it worked just as I wanted it to. However, I could not get the program to find any of words in det in my list of tokens, and exclude them fr...
<p>Your <code>det</code> seems to be invalid (check the quotes).</p> <p>If you want to check often whether an element is in a list, you can use a <code>set()</code>, which is much faster to check for content.</p> <p>The whole could look like this:</p> <pre><code>det = set(["the", "a", "an", "'s"]) for w in tkV: ...
python
3
7,099
61,920,555
Do logical operations in 2 column simmultaneously in Pandas
<p>I have one Dataframe name df - </p> <pre><code> id year month target1 0 324 2019.0 1.0 100.0 1 325 2019.0 3.0 100.0 2 326 2019.0 10.0 100.0 3 327 2019.0 11.0 100.0 4 328 2019.0 12.0 100.0 </code></pre> <p>Now I want to compare 2 columns...
<p>As far as I understand you want to print everything before the specified month of the specified year. This could be done in several ways </p> <ol> <li>Simply add </li> </ol> <pre><code>data.query('(year == 2020 and month &lt;= 1) or (year &lt;= 2020)') </code></pre> <ol start="2"> <li>You can try to create a new ...
python|python-3.x|pandas|python-2.7|sklearn-pandas
1