text
stringlengths
4
1.08k
how to convert a string representing a binary fraction to a number in python,"return int(s[1:], 2) / 2.0 ** (len(s) - 1)"
how to print a tree in python?,print_tree(shame)
python json dumps,"""""""[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]"""""".replace(""u'"", ""'"")"
how to overplot a line on a scatter plot in python?,"plt.plot(x, y, '.')"
get month name from a datetime object `today`,today.strftime('%B')
how to sort a list of strings with a different order?,"['a\xc3\xa1', 'ab', 'abc']"
zip file `pdffile` using its basename as directory name,"archive.write(pdffile, os.path.basename(pdffile))"
what can i do with a closed file object?,open(f.name).read()
"python regular expressions, find email domain in address","re.search('@.*', test_string).group()"
print python native libraries list,help('collections')
beautifulsoup in python - getting the n-th tag of a type,secondtable = soup.findAll('table')[1]
print multiple arguments in python,"print('Total score for {} is {}'.format(name, score))"
how can i list the contents of a directory in python?,glob.glob('/home/username/www/*')
iteratively writing to hdf5 stores in pandas,"pd.read_hdf('my_store.h5', 'a_table_node', ['index>100'])"
call `dosomething()` in a try-except without handling the exception,"try:
doSomething()
except:
pass"
detecting non-ascii characters in unicode string,"print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))"
get the position of a regex match `is` in a string `string`,"re.search('is', String).start()"
getting the correct timezone offset in python using local timezone,dt = datetime.datetime.utcfromtimestamp(1288483950)
how to extract numbers from filename in python?,regex = re.compile('\\d+')
returning millisecond representation of datetime in python,date_time_secs = time.mktime(datetimeobj.timetuple())
"imshow(img, cmap=cm.gray) shows a white for 128 value","plt.imshow(bg, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)"
how to convert a date string '2013-1-25' in format '%y-%m-%d' to different format '%m/%d/%y',"datetime.datetime.strptime('2013-1-25', '%Y-%m-%d').strftime('%m/%d/%y')"
how to append to the end of an empty list?,list1 = [i for i in range(n)]
add a tuple with value `another_choice` to a tuple `my_choices`,"final_choices = ((another_choice,) + my_choices)"
how to strip all whitespace from string,""""""""""""".join(s.split())"
encode string `data` using hex 'hex' encoding,print(data.encode('hex'))
setting a fixed size for points in legend,plt.show()
regular expression in python 2.7 to identify any non numeric symbol in a column in dataframe,print(df.applymap(lambda x: str(x).isdigit()))
can the python csv module parse files with multi-column delimiters,"reader = csv.reader(open('test.csv'), delimiter='|#|')"
how to round to two decimal places in python 2.7?,"round(1.679, 2)"
how to get the symbolic path instead of real path?,print(os.path.abspath('test/link/file'))
pandas dataframe create new columns and fill with calculated values from same df,df['A_perc'] = df['A'] / df['sum']
creating an empty list `l`,l = []
how can i filter for string values in a mixed datatype object in python pandas dataframe,df.index.values
is it possible to get widget settings in tkinter?,"w = Label(root, text='Hello, world!')"
how to print a dictionary's key?,"print((key, value))"
retrieve an arbitrary value from dictionary `dict`,next(iter(dict.values()))
how do i count unique values inside an array in python?,len(set(new_words))
how to use groupby to avoid loop in python,df.ix[idx]
how to get reproducible results in keras,srng.seed(902340)
unpack numpy array by column,"x = np.arange(15).reshape(5, 3)"
python long integer input,n = int(input())
numpy: how to check if array contains certain numbers?,"numpy.in1d(b, a)"
apply a list of functions named 'functions' over a list of values named 'values',"[x(y) for x, y in zip(functions, values)]"
python tuple to dict,"dict((y, x) for x, y in t)"
check output from calledprocesserror,"output = subprocess.check_output(['ping', '-c', '2', '-W', '2', '1.1.1.1'])"
convert list with str into list with int,"list(map(int, ['1', '2', '3']))"
open web in new tab selenium + python,"browser.execute_script('window.open(""http://bings.com"",""_blank"");')"
close all open files in ipython,fh.close()
what's the best way to search for a python dictionary value in a list of dictionaries?,[x for x in data if x['site'] == 'Superuser']
print backslash,print('\\')
"python, json and string indices must be integers, not str",accesstoken = retdict['access_token']
convert a list of lists `a` into list of tuples of appropriate elements form nested lists,zip(*a)
improved sprintf for php,"printf('Hello %1$s. Your %1$s has just been created!', 'world')"
"is it possible to modify variable in python that is in outer, but not global, scope?",foo()
converting a list in a dict to a series,Series([str(x) for x in htmldata])
split a multidimensional numpy array using a condition,"good_data = [data[(n), :][flag == 1].tolist() for n in range(data.shape[0])]"
average of tuples,sum([v[0] for v in list(d.values())]) / float(len(d))
"parse a yaml file ""example.yaml""","with open('example.yaml', 'r') as stream:
try:
print((yaml.load(stream)))
except yaml.YAMLError as exc:
print(exc)"
python jsonify dictionary in utf-8,"json.dumps(data, ensure_ascii=False).encode('utf8')"
python string splitting,"re.split('(\\d+)', 'a1b2c30d40')"
collapsing whitespace in a string,"re.sub('[_\\W]+', ' ', s).strip().upper()"
select rows in pandas which does not contain a specific character,df['str_name'].str.contains('c')
convert json to pandas dataframe,"pd.concat([pd.Series(json.loads(line)) for line in open('train.json')], axis=1)"
count each element in list without .count,"Counter(['a', 'b', 'a', 'c', 'b', 'a', 'c'])"
how do i sort a python list of time values?,"sorted([tuple(map(int, d.split(':'))) for d in my_time_list])"
spaces inside a list,"""""""{: 3d}"""""".format(x)"
delete final line in file with python,file.close()
"python selenium safari, disable logging",browser = webdriver.Safari(quiet=True)
how to export a table dataframe in pyspark to csv?,df.write.csv('mycsv.csv')
get value of an input box using selenium (python),input.get_attribute('value')
how to convert from infix to postfix/prefix using ast python module?,"['sin', '*', 'w', 'time']"
delete column in pandas based on condition,(df != 0).any(axis=0)
replace all the nan values with 0 in a pandas dataframe `df`,df.fillna(0)
"taking the results of a bash command ""awk '{print $10, $11}' test.txt > test2.txt""","os.system(""awk '{print $10, $11}' test.txt > test2.txt"")"
python - compress ascii string,comptest('test')
regular expression for validating string 'user' containing a sequence of characters ending with '-' followed by any number of digits.,re.compile('{}-\\d*'.format(user))
how to select/reduce a list of dictionaries in flask/jinja,"{{users | selectattr('email', 'equalto', 'foo@bar.invalid')}}"
python/numpy - cross product of matching rows in two arrays,"all((c[i] == np.cross(a[i], b[i])).all() for i in range(len(c)))"
merge dataframes in pandas using the mean,"pd.merge(df1, df2, left_index=True, right_index=True, how='outer').mean(axis=1)"
finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"a[np.argmin(a[:, (1)])]"
sorting a tuple that contains tuples,"MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))"
return list `result` of sum of elements of each list `b` in list of lists `a`,result = [sum(b) for b in a]
get traceback of warnings,warnings.simplefilter('always')
pandas - sorting by column,"pd.concat([df_1, df_2.sort_values('y')])"
sending command parameters to serial port using python,s.write('\x0204;0?:=;\x03')
"get a list of tuples of every three consecutive items in list `[1, 2, 3, 4, 5, 6, 7, 8, 9]`","list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))"
how to construct diagonal array using a 2d array in numpy?,"np.eye(foo.shape[1]) * foo[:, (np.newaxis)]"
use a list of values to select rows from a pandas dataframe,"df[df['A'].isin([3, 6])]"
check at once the boolean values from a set of variables,"x = all((a, b, c, d, e, f))"
sort order of lists in multidimensional array in python,"sorted(test, key=lambda x: isinstance(x, list) and len(x) or 1)"
"using python, how can i access a shared folder on windows network?",open('//HOST/share/path/to/file')
python cant get full path name of file,"os.path.realpath(os.path.join(root, name))"