text
stringlengths
4
1.08k
generate a 12-digit random number,"random.randint(100000000000, 999999999999)"
generate a random 12-digit number,"int(''.join(str(random.randint(0, 9)) for _ in range(12)))"
generate a random 12-digit number,""""""""""""".join(str(random.randint(0, 9)) for _ in range(12))"
generate a 12-digit random number,"'%0.12d' % random.randint(0, 999999999999)"
remove specific elements in a numpy array `a`,"numpy.delete(a, index)"
sort list `trial_list` based on values of dictionary `trail_dict`,"sorted(trial_list, key=lambda x: trial_dict[x])"
read a single character from stdin,sys.stdin.read(1)
get a list of characters in string `x` matching regex pattern `pattern`,"print(re.findall(pattern, x))"
get the context of a search by keyword 'My keywords' in beautifulsoup `soup`,k = soup.find(text=re.compile('My keywords')).parent.text
convert rows in pandas data frame `df` into list,"df.apply(lambda x: x.tolist(), axis=1)"
convert a 1d `A` array to a 2d array `B`,"B = np.reshape(A, (-1, 2))"
run app `app` on host '192.168.0.58' and port 9000 in Flask,"app.run(host='192.168.0.58', port=9000, debug=False)"
encode unicode string '\xc5\xc4\xd6' to utf-8 code,print('\xc5\xc4\xd6'.encode('UTF8'))
get the first element of each tuple from a list of tuples `G`,[x[0] for x in G]
regular expression matching all but 'aa' and 'bb' for string `string`,"re.findall('-(?!aa-|bb-)([^-]+)', string)"
regular expression matching all but 'aa' and 'bb',"re.findall('-(?!aa|bb)([^-]+)', string)"
remove false entries from a dictionary `hand`,"{k: v for k, v in list(hand.items()) if v}"
Get a dictionary from a dictionary `hand` where the values are present,"dict((k, v) for k, v in hand.items() if v)"
sort list `L` based on the value of variable 'resultType' for each object in list `L`,"sorted(L, key=operator.itemgetter('resultType'))"
sort a list of objects `s` by a member variable 'resultType',s.sort(key=operator.attrgetter('resultType'))
sort a list of objects 'somelist' where the object has member number variable `resultType`,somelist.sort(key=lambda x: x.resultType)
"join multiple dataframes `d1`, `d2`, and `d3` on column 'name'","df1.merge(df2, on='name').merge(df3, on='name')"
generate random Decimal,decimal.Decimal(random.randrange(10000)) / 100
list all files of a directory `mypath`,"onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]"
list all files of a directory `mypath`,"for (dirpath, dirnames, filenames) in walk(mypath):
f.extend(filenames)"
"list all "".txt"" files of a directory ""/home/adam/""",print(glob.glob('/home/adam/*.txt'))
"list all files of a directory ""somedirectory""",os.listdir('somedirectory')
"execute sql query 'INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)' with all parameters in list `tup`","cur.executemany('INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)', tup)"
get keys with same value in dictionary `d`,print([key for key in d if d[key] == 1])
get keys with same value in dictionary `d`,"print([key for key, value in d.items() if value == 1])"
Get keys from a dictionary 'd' where the value is '1'.,"print([key for key, value in list(d.items()) if value == 1])"
create list of 'size' empty strings,strs = ['' for x in range(size)]
generate pdf file `output_filename` from markdown file `input_filename`,"with open(input_filename, 'r') as f:
html_text = markdown(f.read(), output_format='html4')
pdfkit.from_string(html_text, output_filename)"
remove duplicate dict in list `l`,[dict(t) for t in set([tuple(d.items()) for d in l])]
Set time zone `Europe/Istanbul` in Django,TIME_ZONE = 'Europe/Istanbul'
"append `date` to list value of `key` in dictionary `dates_dict`, or create key `key` with value `date` in a list if it does not exist","dates_dict.setdefault(key, []).append(date)"
Group the values from django model `Article` with group by value `pub_date` and annotate by `title`,Article.objects.values('pub_date').annotate(article_count=Count('title'))
clear Tkinter Canvas `canvas`,canvas.delete('all')
"Initialize a pandas series object `s` with columns `['A', 'B', 'A1R', 'B2', 'AABB4']`","s = pd.Series(['A', 'B', 'A1R', 'B2', 'AABB4'])"
sort list `a` using the first dimension of the element as the key to list `b`,a.sort(key=lambda x: b.index(x[0]))
Save plot `plt` as png file 'filename.png',plt.savefig('filename.png')
Save matplotlib graph to image file `filename.png` at a resolution of `300 dpi`,"plt.savefig('filename.png', dpi=300)"
get output from process `p1`,p1.communicate()[0]
searche in HTML string for elements that have text 'Python',soup.body.findAll(text='Python')
BeautifulSoup find string 'Python Jobs' in HTML body `body`,soup.body.findAll(text='Python Jobs')
Sort items in dictionary `d` using the first part of the key after splitting the key,"sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))"
"create a set that is the exclusive or of [1, 2, 3] and [3, 4, 5]","set([1, 2, 3]) ^ set([3, 4, 5])"
Get a list values of a dictionary item `pass_id` from post requests in django,request.POST.getlist('pass_id')
Filter duplicate entries w.r.t. value in 'id' from a list of dictionaries 'L',"list(dict((x['id'], x) for x in L).values())"
Get pandas GroupBy object with sum over the rows with same column names within dataframe `df`,"df.groupby(df.columns, axis=1).sum()"
"convert the zip of range `(1, 5)` and range `(7, 11)` into a dictionary","dict(zip(list(range(1, 5)), list(range(7, 11))))"
Get all indexes of boolean numpy array where boolean value `mask` is True,numpy.where(mask)
case insensitive string comparison between `string1` and `string2`,"if (string1.lower() == string2.lower()):
pass"
case insensitive string comparison between `string1` and `string2`,(string1.lower() == string2.lower())
case insensitive string comparison between `first` and `second`,(first.lower() == second.lower())
case insensitive comparison between strings `first` and `second`,(first.upper() == second.upper())
"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"")"
remove multiple values from a list `my_list` at the same time with index starting at `2` and ending just before `6`.,del my_list[2:6]
convert a string `s` to its base-10 representation,"int(s.encode('hex'), 16)"
match regex pattern 'TAA(?:[ATGC]{3})+?TAA' on string `seq`,"re.findall('TAA(?:[ATGC]{3})+?TAA', seq)"
sort a set `s` by numerical value,"sorted(s, key=float)"
convert an int 65 to hex string,hex(65)
append a pandas series `b` to the series `a` and get a continuous index,a.append(b).reset_index(drop=True)
simple way to append a pandas series `a` and `b` with same index,"pd.concat([a, b], ignore_index=True)"
Get a list of tuples with multiple iterators using list comprehension,"[(i, j) for i in range(1, 3) for j in range(1, 5)]"
reverse sort items in dictionary `mydict` by value,"sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)"
select the last business day of the month for each month in 2014 in pandas,"pd.date_range('1/1/2014', periods=12, freq='BM')"
disable the certificate check in https requests for url `https://kennethreitz.com`,"requests.get('https://kennethreitz.com', verify=False)"
return dataframe `df` with last row dropped,df.ix[:-1]
"check if ""blah"" is in string `somestring`","if ('blah' not in somestring):
pass"
check if string `needle` is in `haystack`,"if (needle in haystack):
pass"
"check if string ""substring"" is in string",string.find('substring')
"check if string `s` contains ""is""",s.find('is')
extract first and last row of a dataframe `df`,"pd.concat([df.head(1), df.tail(1)])"
filter a Django model `MyModel` to have charfield length of max `255`,MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254'])
Filter queryset for all objects in Django model `MyModel` where texts length are greater than `254`,MyModel.objects.filter(text__regex='^.{254}.*')
count the number of rows with missing values in a pandas dataframe `df`,"sum(df.apply(lambda x: sum(x.isnull().values), axis=1) > 0)"
set the font 'Purisa' of size 12 for a canvas' text item `k`,"canvas.create_text(x, y, font=('Purisa', 12), text=k)"
create a list containing all values associated with key 'baz' in dictionaries of list `foos` using list comprehension,[y['baz'] for x in foos for y in x['bar']]
read pandas data frame csv `comma.csv` with extra commas in column specifying string delimiter `'`,"df = pd.read_csv('comma.csv', quotechar=""'"")"
replace string 'in.' with ' in. ' in dataframe `df` column 'a',"df['a'] = df['a'].str.replace('in.', ' in. ')"
Get all indexes of a list `a` where each value is greater than `2`,[i for i in range(len(a)) if a[i] > 2]
check if a local variable `myVar` exists,('myVar' in locals())
check if a global variable `myVar` exists,('myVar' in globals())
check if object `obj` has attribute 'attr_name',"hasattr(obj, 'attr_name')"
check if a local variable 'myVar' exists,"if ('myVar' in locals()):
pass"
check if a global variable 'myVar' exists,"if ('myVar' in globals()):
pass"
lambda function that adds two operands,"lambda x, y: x + y"
count the number of items in a generator/iterator `it`,sum(1 for i in it)
get tuples of the corresponding elements from lists `lst` and `lst2`,"[(x, lst2[i]) for i, x in enumerate(lst)]"
create tuples containing elements that are at the same index of list `lst` and list `lst2`,"[(i, j) for i, j in zip(lst, lst2)]"
get tuples from lists `lst` and `lst2` using list comprehension in python 2,"[(lst[i], lst2[i]) for i in range(len(lst))]"