text
stringlengths
4
1.08k
how to get the length of words in a sentence?,[len(x) for x in s.split()]
how to mute all sounds in chrome webdriver with selenium,driver.get('https://www.youtube.com/watch?v=hdw1uKiTI5c')
how do i use django groups and permissions?,obj.has_perm('drivers.read_car')
using colormaps to set color of line in matplotlib,plt.show()
how to add a constant column in a spark dataframe?,"df.withColumn('new_column', lit(10))"
how to get a list of variables in specific python module?,print([item for item in dir(adfix) if not item.startswith('__')])
how do you check the presence of many keys in a python dictinary?,"set(['stackoverflow', 'google']).issubset(sites)"
python: efficient counting number of unique values of a key in a list of dictionaries,print(len(set(p['Nationality'] for p in people)))
python: extract variables out of namespace,globals().update(vars(args))
how do you remove the column name row from a pandas dataframe?,"df.to_csv('filename.tsv', sep='\t', index=False)"
remove newline in string 'unix eol\n' on the right side,'Unix EOL\n'.rstrip('\r\n')
how to sort pandas data frame using values from several columns?,"df = df.sort_values(by=['c1', 'c2'], ascending=[False, True])"
"delete an item with key ""key"" from `mydict`","mydict.pop('key', None)"
how to use 'user' as foreign key in django 1.5,"user = models.ForeignKey(User, unique=True)"
split dictionary/list inside a pandas column 'b' into separate columns in dataframe `df`,"pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)"
"python sort a dict by values, producing a list, how to sort this from largest to smallest?","results = sorted(list(results.items()), key=lambda x: x[1], reverse=True)"
"pandas dataframe, how do i split a column into two","df['AB'].str.split('-', 1, expand=True)"
convert pandas group by object to multi-indexed dataframe,"df.set_index(['Name', 'Destination'])"
python: converting from binary to string,"struct.pack('<I', 1633837924)"
what is a pythonic way to alter a dict with a key and multiple values to get the desired output?,"[(10, 'India'), (12, 'USA'), (12, 'UK'), (11, 'Other')]"
check if 7 is in `a`,(7 in a)
"difference between using commas, concatenation, and string formatters in python","print('I am printing {0} and {1}'.format(x, y))"
python list of tuples to list of int,y = [i[0] for i in x]
simple/efficient way to expand a pandas dataframe,"y = pd.DataFrame(y, columns=list('y'))"
move the cursor of file pointer `fh1` at the end of the file.,fh1.seek(2)
embed a web browser in a python program,browser.close()
run multiple tornado processess,"application = tornado.web.Application([('/', hello)], debug=False)"
unzip a list of tuples `l` into a list of lists,zip(*l)
convert hex string `s` to decimal,"i = int(s, 16)"
how to rename a column of a pandas.core.series.timeseries object?,s.reset_index(name='New_Name')
check for a valid domain name in a string?,"""""""^(?=.{4,255}$)([a-zA-Z0-9][a-zA-Z0-9-]{,61}[a-zA-Z0-9]\\.)+[a-zA-Z0-9]{2,5}$"""""""
python split string on regex,"p = re.compile('((?:Friday|Saturday)\\s*\\d{1,2})')"
download file from http url `file_url`,file_name = wget.download(file_url)
i want to plot perpendicular vectors in python,ax.set_aspect('equal')
how to use regexp function in sqlite with sqlalchemy?,"cursor.execute('CREATE TABLE t1 (id INTEGER PRIMARY KEY, c1 TEXT)')"
remove and insert lines in a text file,outfile.write(line)
python insert numpy array into sqlite3 database,cur.execute('create table test (arr array)')
getting column values from multi index data frame pandas,"df.stack(0).query('Panning == ""Panning""').stack().unstack([-2, -1])"
argparse: get undefined number of arguments,"parser.add_argument('FILE', help='File to store as Gist', nargs='+')"
is there a binary or operator in python that works on arrays?,"c = [(x | y) for x, y in zip(a, b)]"
"sort a nested list by the inverse of element 2, then by element 1","sorted(l, key=lambda x: (-int(x[1]), x[0]))"
python pandas - using to_sql to write large data frames in chunks,"df.to_sql('table', engine, chunksize=20000)"
"dropping a row in pandas with dates indexes, python",df.ix[:-1]
how to change the window title in pyside?,self.setWindowTitle('Checkbox')
retrieve an element from a set `s` without removing it,e = next(iter(s))
"handle tinymce window with python, selenium and phantomjs","driver.execute_script(""tinyMCE.activeEditor.setContent('%s')"" % payload)"
get the platform os name,platform.system()
what is the best way to convert a sympy matrix to a numpy array/matrix,np.array(g).astype(np.float64)
check if any item in string list a is a substring of an item in string list b,results = [s for s in strings if any(m in s for m in matchers)]
execute a command `command ` in the terminal from a python script,os.system(command)
python: sanitize a string for unicode?,uni.encode('utf-8')
python library to beep motherboard speaker,"call(['echo', '\x07'])"
python : reverse order of list,reverse_lst = lst[::-1]
writing a python list into a single csv column,writer.writerow([val])
"how to create datetime object from ""16sep2012"" in python","datetime.datetime.strptime('16Sep2012', '%d%b%Y')"
how to get desktop item count in python?,len(os.listdir('path/desktop'))
how do i insert a list at the front of another list?,"a.insert(0, k)"
python split string by pattern,repeat = re.compile('(?P<start>[a-z])(?P=start)*-?')
how to implement a watchdog timer in python?,sys.exit()
build dictionary with keys of dictionary `_container` as keys and values of returned value of function `_value` with correlating key as parameter,{_key: _value(_key) for _key in _container}
print variable in python without space or newline,sys.stdout.write(str(x))
get os version,"import platform
platform.release()"
how to get all sub-elements of an element tree with python elementtree?,all_descendants = list(elem.iter())
pandas: joining items with same index,pd.DataFrame(s.groupby(level=0).apply(list).to_dict())
typeerror when creating a date object,"datetime.datetime.date(2011, 1, 1)"
pads string '5' on the left with 1 zero,print('{0}'.format('5'.zfill(2)))
listing files from a directory using glob python,glob.glob('*')
what is the fool proof way to convert some string (utf-8 or else) to a simple ascii string in python,"ascii_garbage = text.encode('ascii', 'replace')"
difference between every pair of columns of two numpy arrays (how to do it more efficiently)?,"((a[:, (np.newaxis), :] - v) ** 2).sum(axis=-1).shape"
"check if the third element of all the lists in a list ""items"" is equal to zero.",any(item[2] == 0 for item in items)
best way to plot an angle between two lines in matplotlib,plt.show()
calcuate mean for selected rows for selected columns in pandas data frame,"df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)"
how to correctly parse utf-8 encoded html to unicode strings with beautifulsoup?,"soup = BeautifulSoup(response.read().decode('utf-8', 'ignore'))"
how to set bokeh legend font?,legend().orientation = 'top_left'
get key by value in dictionary with same value in python?,print([key for key in d if d[key] == 1])
plotting stochastic processes in python,plt.show()
creating a simple xml file using python,tree.write('filename.xml')
check if list item contains items from another list,[item for item in my_list if any(x in item for x in bad)]
writing string to a file on a new line everytime?,file.write('My String\n')
how to concatenate element-wise two lists in python?,"[(m + str(n)) for m, n in zip(b, a)]"
imoverlay in python,plt.show()
how to check if a template exists in django?,"django.template.loader.select_template(['custom_template', 'default_template'])"
how can i split this comma-delimited string in python?,"print(s.split(','))"
how to tell if python script is being run in a terminal or via gui?,sys.stdin.isatty()
get the first element of each tuple in a list in python,res_list = [i[0] for i in rows]
is it possible to use 'else' in a python list comprehension?,obj = [('Even' if i % 2 == 0 else 'Odd') for i in range(10)]
"calling an external command ""echo hello world""",print(os.popen('echo Hello World').read())
how to remove specific elements in a numpy array,"numpy.delete(a, index)"
getting the opposite diagonal of a numpy array,np.diag(np.fliplr(array))
multiindex from array in pandas with non unique data,"df.set_index(['Z', 'A', 'pos']).unstack('pos')"
disable the certificate check in https requests for url `https://kennethreitz.com`,"requests.get('https://kennethreitz.com', verify=False)"
how to open html file?,print(f.read())
pyqt dialog - how to make it quit after pressing a button?,self.ui.closeButton.clicked.connect(self.closeIt)
how to obtain values of parameters of get request in flask?,app.run(debug=True)
"check if all the items in a list `['a', 'b']` exists in another list `l`","set(['a', 'b']).issubset(set(l))"
replacing one character of a string in python,""""""""""""".join(l)"
convert python 2 dictionary `a` to a list of tuples where the value is the first tuple element and the key is the second tuple element,"[(v, k) for k, v in a.items()]"
"changing the color of the axis, ticks and labels for a plot in matplotlib",ax.spines['top'].set_color('red')
how do you get a decimal in python?,print('the number is {:.2}'.format(1.0 / 3.0))