text
stringlengths
4
1.08k
How to monkeypatch python's datetime.datetime.now with py.test?,assert datetime.datetime.now() == FAKE_TIME
Python: Lambda function in List Comprehensions,[(lambda x: x * x) for x in range(10)]
Python - Convert dictionary into list with length based on values,"[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]"
How to center a window with PyGObject,window.set_position(Gtk.WindowPosition.CENTER)
Python: How to loop through blocks of lines,"[('X', 'Y', '20'), ('H', 'F', '23'), ('S', 'Y', '13'), ('M', 'Z', '25')]"
How can I speed up transition matrix creation in Numpy?,"m3 = np.zeros((50, 50))"
How to extract a floating number from a string,"re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')"
Calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=0)"
Dot notation string manipulation,"re.sub('\\.[^.]+$', '', s)"
How to group DataFrame by a period of time?,"df.groupby([df['Source'], pd.TimeGrouper(freq='Min')])"
How to convert a Numpy 2D array with object dtype to a regular 2D array of floats,"np.array(arr[:, (1)], dtype=np.float)"
Python: Split string with multiple delimiters,"re.split('; |, ', str)"
Converting JSON date string to python datetime,"datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')"
converting currency with $ to numbers in Python pandas,"df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)"
How to split a string at line breaks in python?,[row.split('\t') for row in s.splitlines()]
How do I coalesce a sequence of identical characters into just one?,"print(re.sub('(\\W)\\1+', '\\1', a))"
How to use regex with optional characters in python?,"print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))"
"How to read a ""C source, ISO-8859 text""","codecs.open('myfile', 'r', 'iso-8859-1').read()"
Default save path for Python IDLE?,os.chdir(os.path.expanduser('~/Documents'))
Remove final characters from string recursively - What's the best way to do this?,""""""""""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]"
How do I transform a multi-level list into a list of strings in Python?,[''.join(x) for x in a]
Get unique values from a list in python,mynewlist = list(myset)
Use sched module to run at a given time,time.sleep(10)
How to dynamically load a Python class,__import__('foo.bar.baz.qux')
How do I run twisted from the console?,reactor.run()
How to convert a Numpy 2D array with object dtype to a regular 2D array of floats,"np.array(arr[:, (1)])"
Getting a list with new line characters,"pattern = re.compile('(.)\\1?', re.IGNORECASE | re.DOTALL)"
"Plotting a list of (x, y) coordinates in python matplotlib",plt.show()
How can I create stacked line graph with matplotlib?,plt.show()
Converting string to tuple and adding to tuple,"ast.literal_eval('(1,2,3,4)')"
Manipulating binary data in Python,print(data.encode('hex'))
python pandas add column in dataframe from list,"df = pd.DataFrame({'A': [0, 4, 5, 6, 7, 7, 6, 5]})"
"Random Python dictionary key, weighted by values",random.choice([k for k in d for x in d[k]])
sqlalchemy add child in one-to-many relationship,session.commit()
Python: transform a list of lists of tuples,zip(*main_list)
how to split a string on the first instance of delimiter in python,"""""""jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,"""""".split('=', 1)"
Find ordered vector in numpy array,"(e == np.array([1, 2])).all(-1)"
Using Colormaps to set color of line in matplotlib,plt.show()
How to configure Logging in Python,logger.setLevel(logging.DEBUG)
How to generate random numbers that are different?,"random.sample(range(1, 50), 6)"
How to copy a file to a remote server in Python using SCP or SSH?,ssh.close()
How do I move the last item in a list to the front in python?,a = a[-1:] + a[:-1]
NumPy Array Indexing,"array([0.63143784, 0.93852927, 0.0026815, 0.66263594, 0.2603184])"
Python Pandas drop columns based on max value of column,df.columns[df.max() > 0]
How to use python_dateutil 1.5 'parse' function to work with unicode?,"['8th', 'of', '\u0418\u044e\u043d\u044c']"
Python equivalent for HashMap,my_dict = {'cheese': 'cake'}
Group By in mongoengine EmbeddedDocumentListField,Cart.objects.filter(user=user).first().distinct('items.item')
Change user agent for selenium driver,driver.execute_script('return navigator.userAgent')
How do I release memory used by a pandas dataframe?,df.info()
Python 3: How do I get a string literal representation of a byte string?,"""""""x = {}"""""".format(x.decode('utf8')).encode('utf8')"
split string on a number of different characters,"re.split('[ .]', 'a b.c')"
Python: Extract variables out of namespace,globals().update(vars(args))
How can I convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85あ"""""".encode('utf-8')"
Sort a numpy array like a table,"array([[2, 1], [5, 1], [0, 3], [4, 5]])"
Can I put a tuple into an array in python?,list_of_tuples[0][0] = 7
Get only certain fields of related object in Django,"Comment.objects.filter(user=user).values_list('user__name', 'user__email')"
"How do I convert all strings (like ""Fault"") and into a unique float?",(s.factorize()[0] + 1).astype('float')
Python turning a list into a list of tuples,"done = [(el, x) for el in [a, b, c, d]]"
get PID from paramiko,"stdin, stdout, stderr = ssh.exec_command('./wrapper.py ./someScript.sh')"
Get data from the meta tags using BeautifulSoup,soup.findAll(attrs={'name': 'description'})
How to properly get url for the login view in template?,"url('^login/$', views.login, name='login'),"
Creating a Browse Button with TKinter,"Tkinter.Button(self, text='Browse', command=self.askopenfile)"
How to set the default color cycle for all subplots with matplotlib?,plt.show()
How to convert this text file into a dictionary?,"{'labelA': 'thereissomethinghere', 'label_Bbb': 'hereaswell'}"
How to remove ^M from a text file and replace it with the next line,"somestring.replace('\\r', '')"
Sorting a dictionary by highest value of nested list,"OrderedDict([('b', 7), ('a', 5), ('c', 3)])"
Two Combination Lists from One List,"print([[l[:i], l[i:]] for i in range(1, len(l))])"
Extract all keys from a list of dictionaries,{k for d in LoD for k in list(d.keys())}
Conditional replacement of row's values in pandas DataFrame,df['SEQ'] = df.sort_values(by='START').groupby('ID').cumcount() + 1
python How do you sort list by occurrence with out removing elements from the list?,"sorted(lst, key=lambda x: (-1 * c[x], lst.index(x)))"
Replace part of a string in Python?,"stuff.replace(' and ', '/')"
Splitting a string by using two substrings in Python,"re.search('Test(.*)print', testStr, re.DOTALL)"
Numpy - group data into sum values,"[(1, 4), (2, 3), (0, 1, 4), (0, 2, 3)]"
Output data from all columns in a dataframe in pandas,"pandas.set_option('display.max_columns', 7)"
Node labels using networkx,"networkx.draw_networkx_labels(G, pos, labels)"
generating a file with django to download with javascript/jQuery,"url('^test/getFile', 'getFile')"
Python list of tuples to list of int,x = [i[0] for i in x]
pandas.read_csv: how to skip comment lines,"pd.read_csv(StringIO(s), sep=',', comment='#')"
How to terminate process from Python using pid?,p.terminate()
How to call a python function with no parameters in a jinja2 template,template_globals.filters['ctest'] = ctest
replace values in an array,"b = np.where(np.isnan(a), 0, a)"
Plotting a polynomial in Python,plt.show()
How to annotate a range of the x axis in matplotlib?,"ax.annotate('important\npart', xy=(5, 1.5), ha='center', va='center')"
how to add border around an image in opencv python,cv2.destroyAllWindows()
How to set environment variables in Python,"os.environ.get('DEBUSSY', 'Not Set')"
What's the best way to generate random strings of a specific length in Python?,print(''.join(choice(ascii_uppercase) for i in range(12)))
how to open a url in python,webbrowser.open_new(url)
"How to slice a 2D Python Array? Fails with: ""TypeError: list indices must be integers, not tuple""","array([[1, 3], [4, 6], [7, 9]])"
Getting two strings in variable from URL in Django,"""""""^/rss/(?P<anynumber>\\d+)/(?P<anystring>.+)/$"""""""
Python load json file with UTF-8 BOM header,"json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))"
Multiindex from array in Pandas with non unique data,"df.set_index(['Z', 'A', 'pos']).unstack('pos')"
Deleting row with Flask-SQLAlchemy,db.session.delete(page)
NumPy - Set values in structured array based on other values in structured array,"a = numpy.zeros((10, 10), dtype=[('x', int), ('y', 'a10')])"
using regular expression to split string in python,[m[0] for m in re.compile('((.+?)\\2+)').findall('44442(2)2(2)44')]
Python: How to Resize Raster Image with PyQt,pixmap = QtGui.QPixmap(path)
How to use the pipe operator as part of a regular expression?,"re.findall('[^ ]*.(?:cnn|espn).[^ ]*', u1)"
Appending to 2D lists in Python,listy = [[] for i in range(3)]
Python: sort an array of dictionaries with custom comparator?,"key = lambda d: (d['rank'] == 0, d['rank'])"
Iterate over the lines of a string,"return map(lambda s: s.strip('\n'), stri)"
How to replace all non-numeric entries with NaN in a pandas dataframe?,df[df.applymap(isnumber)]