text
stringlengths 4
1.08k
|
|---|
convert dynamic python object to json,"json.dumps(c, default=lambda o: o.__dict__)"
|
convert a beautiful soup html `soup` to text,print(soup.get_text())
|
counting array elements in python,len(myArray)
|
extract lists within lists containing a string in python,[l for l in paragraph3]
|
python float to decimal conversion,"format(f, '.15g')"
|
how to convert numpy datetime64 into datetime,"np.array([[x, x], [x, x]], dtype='M8[ms]').astype('O')[0, 1]"
|
how do i convert local time to utc in python?,utc_dt.strftime('%Y-%m-%d %H:%M:%S')
|
python logging - disable logging from imported modules,logger = logging.getLogger('my_module_name')
|
print a string as hex bytes?,""""""":"""""".join(x.encode('hex') for x in 'Hello World!')"
|
how do i get the whole content between two xml tags in python?,"tostring(element).split('>', 1)[1].rsplit('</', 1)"
|
i'm looking for a pythonic way to insert a space before capital letters,"re.sub('([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', '\\1 ', text)"
|
how to avoid line color repetition in matplotlib.pyplot?,"pyplot.plot(x, y, color='#112233')"
|
creating a 2d matrix in python,x = [[None for _ in range(5)] for _ in range(6)]
|
create a regular expression that matches the pattern '^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)' over multiple lines of text,"re.compile('^(.+)(?:\\n|\\r\\n?)((?:(?:\\n|\\r\\n?).+)+)', re.MULTILINE)"
|
multiply high order matrices with numpy,"np.einsum('ijk,ij->ik', ind, dist)"
|
how to remove duplicates in a nested list of objects in python,"sorted(item, key=lambda x: x.id)"
|
get a dictionary in list `dicts` which key 'ratio' is closer to a global value 1.77672955975,"min(dicts, key=lambda x: (abs(1.77672955975 - x['ratio']), -x['pixels']))"
|
python match a string with regex,"re.search('sample', line)"
|
how do i get the application id at runtime,os.environ['APPLICATION_ID']
|
"convert a tensor with list of constants `[1, 2, 3]` into a numpy array in tensorflow","print(type(tf.Session().run(tf.constant([1, 2, 3]))))"
|
possible to retrieve an arbitrary unordered set of named groups in one swoop with python's re module?,"mergedgroupdict('(?P<b>.b.)|(?P<i>.i.)', 'abcdefghijk'[::-1])"
|
deleting items from a dictionary with a for loop,del my_dict[k]
|
python argparse command line flags without arguments,"parser.add_argument('-w', action='store_true')"
|
how to reference to the top-level module in python inside a package?,__init__.py
|
argparse associate zero or more arguments with flag 'file',"parser.add_argument('file', nargs='*')"
|
how to strip comma in python string,"s = s.replace(',', '')"
|
string formatting named parameters?,"print('<a href=""%(url)s"">%(url)s</a>' % {'url': my_url})"
|
how to use cherrypy as a web server for static files?,cherrypy.quickstart()
|
"check if string ""substring"" is in string",string.find('substring')
|
numpy elementwise product of 3d array,"np.einsum('ijk,ikl->ijl', A, B)"
|
get all the values in column `b` from pandas data frame `df`,df['b']
|
how to save and load mllib model in apache spark,"lrm.save(sc, 'lrm_model.model')"
|
edit xml file text based on path,tree.write('filename.xml')
|
find cells in dataframe where value is between x and y,"df.stack().between(2, 10, inclusive=False).unstack()"
|
can't delete row from sqlalchemy due to wrong session,db.session.commit()
|
creating a png file in python,"f.write(makeGrayPNG([[0, 255, 0], [255, 255, 255], [0, 255, 0]]))"
|
python list of tuples to list of int,y = [j for i in x for j in i]
|
how to print more than one value in a list comprehension?,"[[word, len(word), word.upper()] for word in sent]"
|
"remove all non -word, -whitespace, or -apostrophe characters from string `doesn't this mean it -technically- works?`","re.sub(""[^\\w' ]"", '', ""doesn't this mean it -technically- works?"")"
|
sorting a list of dictionary `a` by values in descending order,"sorted(a, key=dict.values, reverse=True)"
|
how to skip the extra newline while printing lines read from a file?,print(line.rstrip('\n'))
|
how to make a pandas crosstab with percentages?,"pd.crosstab(df.A, df.B).apply(lambda r: r / len(df), axis=1)"
|
"read in tuple of lists from text file as tuple, not string - python","ast.literal_eval(""('item 1', [1,2,3,4] , [4,3,2,1])"")"
|
sort a sublist of elements in a list leaving the rest in place,"['X', 'B2', 'B11', 'B22', 'B', 'B1', 'B21', 'C', 'Q1', 'C11', 'C2']"
|
how can i retrieve the current seed of numpy's random number generator?,"print(np.random.randint(0, 100, 10))"
|
matplotlib - fixing x axis scale and autoscale y axis,plt.show()
|
check if string `my_string` is empty,"if (not my_string):
|
pass"
|
can python test the membership of multiple values in a list?,"set(['a', 'b']).issubset(['b', 'a', 'foo', 'bar'])"
|
python accessing data in json object,result['streams']
|
pls-da algorithm in python,"dummy = np.array([[1, 1, 0, 0], [0, 0, 1, 1]]).T"
|
how to write binary data in stdout in python 3?,sys.stdout.write('Your string to Stdout\n')
|
setting matplotlib colorbar range,"quadmesh.set_clim(vmin=0, vmax=15)"
|
finding consecutive consonants in a word,"re.findall('[^aeiou]+', '123concertation')"
|
generate random integers between 0 and 9,"print((random.randint(0, 9)))"
|
how to change font and size of buttons and frame in tkinter using python?,"btn5.grid(row=1, column=2, columnspan=1, sticky='EWNS')"
|
deleting mulitple columns in pandas,"df.drop(df.ix[:, 'Unnamed: 24':'Unnamed: 60'].head(0).columns, axis=1)"
|
best / most pythonic way to get an ordered list of unique items,sorted(set(itertools.chain.from_iterable(sequences)))
|
what is the most pythonic way to avoid specifying the same value in a string,"""""""hello {0}, how are you {0}, welcome {0}"""""".format('john')"
|
i'm looking for a pythonic way to insert a space before capital letters,"re.sub('(\\w)([A-Z])', '\\1 \\2', 'WordWordWWWWWWWord')"
|
element-wise minimum of multiple vectors in numpy,"np.minimum.accumulate([np.arange(3), np.arange(2, -1, -1), np.ones((3,))])"
|
convert the dataframe column 'col' from string types to datetime types,df['col'] = pd.to_datetime(df['col'])
|
"list of tuples (string, float)with nan how to get the min value?","min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])"
|
group by in mongoengine embeddeddocumentlistfield,Cart.objects.filter(user=user).first().distinct('items.item')
|
how to split 1d array into 2d array in numpy by splitting the array at the last element?,"np.split(a, [-1])"
|
open the login site 'http://somesite.com/adminpanel/index.php' in the browser,webbrowser.open('http://somesite.com/adminpanel/index.php')
|
numpy mean with comparison operator in the parameter,"array([True, True, True, False, False, False, False], dtype=bool)"
|
how can i convert a tensor into a numpy array in tensorflow?,"print(type(tf.constant([1, 2, 3]).eval()))"
|
create a list containing a four elements long tuples of permutations of binary values,"itertools.product(list(range(2)), repeat=4)"
|
how to make ordered dictionary from list of lists?,"pprint([OrderedDict(zip(names, subl)) for subl in list_of_lists])"
|
"python selenium safari, disable logging",browser = webdriver.Safari()
|
how can i launch an instance of an application using python?,os.system('start excel.exe <path/to/file>')
|
python: how can i include the delimiter(s) in a string split?,"['(two', 'plus', 'three)', 'plus', 'four']"
|
sum parts of numpy.array,"a[:, ::2] + a[:, 1::2]"
|
multiple pipes in subprocess,p.wait()
|
how do i use a dictionary to update fields in django models?,Book.objects.filter(id=id).update()
|
how can i get the index value of a list comprehension?,"{(p.id, ind): {'id': p.id, 'position': ind} for ind, p in enumerate(p_list)}"
|
how to find elements by class,"soup.find_all('a', class_='sister')"
|
pandas groupby: count the number of occurences within a time range for each group,df['WIN1'] = df['WIN'].map(lambda x: 1 if x == 'Yes' else 0)
|
flipping bits in python,n ^= (1 << upper) - 1 & ~((1 << lower) - 1)
|
python: sorting dictionary of dictionaries,"sorted(list(dic.items()), key=lambda x: x[1]['Fisher'], reverse=True)"
|
scroll backwards and forwards through matplotlib plots,plt.show()
|
python: group list items in a dict,"res.setdefault(item['a'], []).append(item)"
|
insert image in openpyxl,wb.save('out.xlsx')
|
creating a dictionary with list of lists in python,inlinkDict[docid] = adoc[1:]
|
is there a way to subclass a generator in python 3?,"['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']"
|
how to properly determine current script directory in python?,os.path.dirname(os.path.abspath(__file__))
|
how can i color python logging output?,"logging.Formatter.__init__(self, msg)"
|
how to get the index and occurance of each item using itertools.groupby(),"[(key, len(list(it))) for key, it in itertools.groupby(list_one)]"
|
empty a list `lst`,del lst[:]
|
how to get transparent background in window with pygtk and pycairo?,win.show()
|
"subset numpy array `a` by column and row, returning the values from the first row, first column and the second row, second column and the third row, first column.","a[np.arange(3), (0, 1, 0)]"
|
how do i create a python set with only one element?,mySet = set([myString])
|
radar chart with multiple scales on multiple axes,ax.xaxis.set_visible(False)
|
get the maximum 2 values per row in array `a`,"A[:, -2:]"
|
get size of a file before downloading in python,"open(filename, 'rb')"
|
python: sanitize a string for unicode?,s = s.decode('cp1250')
|
add custom method to string object,sayhello('JOHN'.lower())
|
python image library: how to combine 4 images into a 2 x 2 grid?,image64 = Image.open(fluid64 + '%02d.jpg' % pic)
|
how to use re match objects in a list comprehension,[m.group(1) for l in lines for m in [regex.search(l)] if m]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.