text
stringlengths
4
1.08k
How can I get the output of a matplotlib plot as an SVG?,"plt.gca().set_position([0, 0, 1, 1])"
Key to maxima of dictionary in python,"['e', 'f']"
How to handle Unicode (non-ASCII) characters in Python?,outbytes = yourstring.encode('utf-8')
Convert a IP to Hex by Python,"hex(8).replace('0x', '')"
Display a float with two decimal places in Python,"""""""{0:.2f}"""""".format(5)"
How to extend a fixed-length Python list by variable number of characters?,list2 = list1 + [''] * (5 - len(list1))
Appending to dict of lists adds value to every key,d = {k: [] for k in keys}
Replace first occurrence only of a string?,"text = text.replace('very', 'not very', 1)"
Python: How to download a zip file,f.close()
Parsing HTML page using beautifulsoup,print(''.join(x.stripped_strings))
Django: Faking a field in the admin interface?,"forms.ModelForm.__init__(self, *args, **kwargs)"
Elegant way to take basename of directory in Python?,"os.path.dirname(os.path.join(output_dir, ''))"
How sending and receiving works in Python sockets?,"socket.socket(socket.AF_INET, socket.SOCK_DGRAM)"
How to read a file byte by byte in Python and how to print a bytelist as a binary?,file.read(1)
How do I use Django groups and permissions?,obj.has_perm('drivers.read_car')
Iterating on a file using Python,f.seek(0)
Python: Read hex from file into list?,hex_list = ('{:02x}'.format(ord(c)) for c in fp.read())
Django equivalent for count and group by,Item.objects.values('category').annotate(Count('category')).order_by()
Find and Replace Values in XML using Python,tree.find('.//enddate').text = '1/1/2011'
How can i recreate this graphic with python//Matplotlib?,plt.show()
Adding calculated column(s) to a dataframe in pandas,d['A'][:-1] < d['C'][1:]
Convert enum to int in python,print(nat.index(nat.Germany))
How to discontinue a line graph in the plot pandas or matplotlib python,plt.show()
Plotting dates on the x-axis with Python's matplotlib,plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
Python numpy: cannot convert datetime64[ns] to datetime64[D] (to use with Numba),df['month_15'].astype('datetime64[D]').dtype
How do I plot multiple X or Y axes in matplotlib?,plt.subplots_adjust(bottom=0.2)
How can I select random characters in a pythonic way?,random.choice(string.ascii_letters + string.digits)
How to capture the entire string while using 'lookaround' with chars in regex?,"re.findall('(b+ab+)+', mystring)"
Extract text from webpage using Selenium in Python,driver.get('https://www.sunnah.com/bukhari/5')
how to edit model data using django forms,"form = MyModelForm(request.POST, instance=my_record)"
How to read stdin to a 2d python array of integers?,"a = [map(int, row.split()) for row in stdin]"
python convert a list of float to string,['{:.2f}'.format(x) for x in nums]
How to compute the accumulative sum of a list of tuples,"list(itertools.accumulate(lst, lambda a, b: tuple(map(sum, zip(a, b)))))"
matplotlib problems plotting logged data and setting its x/y bounds,plt.axis('tight')
How to plot 2d math vectors with matplotlib?,plt.show()
What is the easiest way to detect key presses in python 3 on a linux machine?,main()
"Fix first element, shuffle the rest of a list/array",numpy.random.shuffle(a[1:])
Creating a list of objects in Python,simplelist.append(x)
Reading a text file and splitting it into single words in python,[word for line in f for word in line.split()]
How to get the values from a NumPy array using multiple indices,"print(arr[[1, 4, 5]])"
Google App Engine (Python) - Uploading a file (image),imagedata.image = str(self.request.get('image'))
List of strings to integers while keeping a format in python,integers = [(int(i) - 1) for i in line.split()]
Transparency for Poly3DCollection plot in matplotlib,plt.show()
python get last 5 elements in list of lists,print(list(itertools.chain(*[l for l in lst if l is not None]))[-5:])
Slick way to reverse the (binary) digits of a number in Python?,"int('{0:b}'.format(n)[::-1], 2)"
Python library to generate regular expressions,"""""""(desired)+|(input)+|(strings)+"""""""
Matplotlib 3D Scatter Plot with Colorbar,"p = ax.scatter(xs, ys, zs, c=cs, marker=m)"
Python: splitting string by all space characters,"re.split('(?u)\\s', 'a\u200bc d')"
python one line save values of lists in dict to list,list(itertools.chain.from_iterable(list(d.values())))
convert dictionaries into string python,""""""", """""".join('{} {}'.format(k, v) for k, v in list(d.items()))"
How to count the occurrence of certain item in an ndarray in Python?,collections.Counter(a)
How to change the window title in pyside?,self.show()
Creating a dictionary with list of lists in Python,{d[0]: (' '.join(d[1:]) if d[1:] else 0) for d in data}
"Iterate through each value of list in order, starting at random value","[numbers[i % len(numbers)] for i in range(start, start + len(numbers))]"
How can I insert a new tag into a BeautifulSoup object?,"new_tag = self.new_soup.new_tag('div', id='file_history')"
Google App Engine/Python - Change logging formatting,logging.getLogger().handlers[0].setFormatter(fr)
Color states with Python's matplotlib/basemap,plt.show()
How to create broken vertical bar graphs in matpltolib?,plt.show()
Python: Convert a list of python dictionaries to an array of JSON objects,json.dumps([dict(mpn=pn) for pn in lst])
Breaking a string in python if a number is 5 digit long or longer,"s = re.split('[0-9]{5,}', string)[0].strip()"
Why would I ever use anything else than %r in Python string formatting?,"'Repr:%r Str:%s' % ('foo', 'foo')"
"imshow(img, cmap=cm.gray) shows a white for 128 value","plt.imshow(bg, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)"
From tuples to multiple columns in pandas,"df = df.drop('location', axis=1)"
How do I run Selenium in Xvfb?,browser.get('http://www.google.com')
Invert colors when plotting a PNG file using matplotlib,"plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))"
Python: How do I make a subclass from a superclass?,"super(MySubClassBetter, self).__init__()"
How to create bi-directional messaging using AMP in Twisted/Python,reactor.run()
Pandas: How to make apply on dataframe faster?,"df['C'] = numpy.where(df['B'] > 5, df['A'], 0.1 * df['A'] * df['B'])"
How to count occurences at the end of the list,"print(list_end_counter([1, 2, 1, 1, 1, 1, 1, 1]))"
How to extract the n-th elements from a list of tuples in python?,"map(itemgetter(1), elements)"
How do I get rid of Python Tkinter root window?,root.deiconify()
Index the first and the last n elements of a list,l[:3] + l[-3:]
"Numpy index, get bands of width 2","test.reshape((4, 4))[:, :2].reshape((2, 4))"
Python Remove last 3 characters of a string,foo = ''.join(foo.split())[:-3].upper()
How to add timezone into a naive datetime instance in python,"dt = tz.localize(naive, is_dst=True)"
Hacking JavaScript Array Into JSON With Python,print(json.dumps(result))
How can I get dict from sqlite query?,cur.execute('select 1 as a')
How to print the function name as a string in Python from inside that function,print(applejuice.__name__)
import local function from a module housed in another directory with relative imports in jupyter notebook using python3,sys.path.append(module_path)
How to calculate next Friday in Python?,d += datetime.timedelta(1)
Run shell command with input redirections from python 2.4?,"subprocess.call(cmd, stdin=f)"
Average over parts in list of lists,"map(lambda y: [np.mean(y[i:i + length]) for i in range(0, len(y), length)], a)"
convert a string to an array,testarray = ast.literal_eval(teststr)
Set max number of threads at runtime on numpy/openblas,"np.dot(x, y)"
Finding index of maximum element from Python list,"from functools import reduce
reduce(lambda a, b: [a, b], [1, 2, 3, 4], 'seed')"
Adaptable descriptor in Python,"self.variable_evidence.arrays.append((self, 'basic_in'))"
Get a random boolean in python?,bool(random.getrandbits(1))
Terminate a python script from another python script,"os.kill(5383, signal.SIGKILL)"
How to test if all rows are equal in a numpy,(arr == arr[0]).all()
Combine or join numpy arrays,"[(0, 0, 1, 1), (0, 1, 0, 1)]"
"Find where f(x) changes in a list, with bisection (in Python)","binary_f(lambda v: v >= '4.2', ['1.0', '1.14', '2.3', '3.1', '4'])"
Logging across multiple co-routines / greenlets / microthreads with Gevent?,gevent.joinall(jobs)
Accessing the default argument values in Python,test.__defaults__
Fastest way to split a concatenated string into a tuple and ignore empty strings,tuple(a[:-1].split(';'))
How to save a list as numpy array in python?,"myArray = np.load(open('array.npy', 'rb'))"
Calcuate mean for selected rows for selected columns in pandas data frame,"df[['b', 'c']].iloc[[2, 4]]"
how to execute a python script file with an argument from inside another python script file,"sys.exit(main(sys.argv[1], sys.argv[2]))"
How to select specific columns in numpy array?,"A = np.delete(A, 50, 1)"
Post JSON to Python CGI,print(json.dumps(result))