divide the values with same keys of two dictionary `d1` and `d2`

{k: (float(VAR_STR[k]) / VAR_STR[k]) for k in VAR_STR}


divide values associated with each key in dictionary `d1` from values associated with the same key in dictionary `d2`

dict((k, float(d2[k]) / d1[k]) for k in d2)

dict((k, float(VAR_STR[k]) / VAR_STR[k]) for k in VAR_STR)


download "http://randomsite.com/file.gz" from http and save as "file.gz"

testfile = urllib.request.URLopener()
testfile.retrieve('http://randomsite.com/file.gz', 'file.gz')

testfile = urllib.request.URLopener()
testfile.retrieve('VAR_STR', 'VAR_STR')


download file from http url "http://randomsite.com/file.gz" and save as "file.gz"


filter a Django model `MyModel` to have charfield length of max `255`


VAR_STR and not VAR_STR or not VAR_STR and VAR_STR


(date(2010, 12, 31) + relativedelta(months=(+ 1)))

date(2010, 12, 31) + relativedelta(months=+1)


(date(2010, 12, 31) + relativedelta(months=(+ 2)))

date(2010, 12, 31) + relativedelta(months=+2)


check if object `obj` has attribute 'attr_name'


slice list `[1, 2, 3, 4, 5, 6, 7]` into lists of two elements each


[input[i:i + n] for i in range(0, len(input), n)]


fetch smilies matching regex pattern '(?::|;|=)(?:-)?(?:\\)|\\(|D|P)' in string `s`


Get data of dataframe `df` where the sum of column 'X' grouped by column 'User' is equal to 0


Get data from dataframe `df` where column 'X' is equal to 0


webbrowser open url 'http://example.com'


get value of environment variable "HOME"


get value of the environment variable 'KEY_THAT_MIGHT_EXIST' with default value `default_value`


sort dictionary `dictionary` in ascending order by its values


iterate over a python dictionary, ordered by values

sorted(list(dictionary.items()), key=lambda x: x[1])


pandas split strings in column 'stats' by ',' into columns in dataframe `df`


split string in column 'stats' by ',' into separate columns in dataframe `df`


Remove characters "!@#$" from a string `line`


Remove characters in '!@#$' from a string `line`

line = line.translate(string.maketrans('', ''), '!@#$')

VAR_STR = VAR_STR.translate(string.maketrans('', ''), 'VAR_STR')


subtract 1 hour and 10 minutes from time object `t`

(t - datetime.timedelta(hours=1, minutes=10))

VAR_STR - datetime.timedelta(hours=1, minutes=10)


subtract 5 hours from the time object `dt`


Parsing webpage 'http://www.google.com/' using BeautifulSoup

page = urllib.request.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)

page = urllib.request.urlopen('VAR_STR')
soup = BeautifulSoup(page)


print number `value` as thousands separators


move an x-axis label to the top of a plot `ax` in matplotlib


check if array `b` contains all elements of array `a`


convert decimal 8 to a list of its binary values


convert decimal integer 8 to a list of its binary values as elements

[int(x) for x in list('{0:0b}'.format(8))]


print current date and time in a regular format


Calling an external command "some_command with args"


Calling an external command "some_command < input_file | another_command > output_file"

os.system('some_command < input_file | another_command > output_file')


stream = os.popen('some_command with args')


Calling an external command "echo Hello World"

return_code = subprocess.call('echo Hello World', shell=True)

return_code = subprocess.call('VAR_STR', shell=True)


unpack hexadecimal string `s` to a list of integer values


convert column of date objects 'DateObj' in pandas dataframe `df` to strings in new column 'DateStr'


generate all permutations of list `[1, 2, 3]` and list `[4, 5, 6]`

print(list(itertools.product([1, 2, 3], [4, 5, 6])))


generate all permutations of a list `[1, 2, 3]`


Exclude column names when writing dataframe `df` to a csv file `filename.csv`


How do I get rid of Python Tkinter root window?


create a list `files` containing all files in directory '.' that starts with numbers between 0 and 9 and ends with the extension '.jpg'

files = [f for f in os.listdir('.') if re.match('[0-9]+.*\\.jpg', f)]

VAR_STR = [f for f in os.listdir('VAR_STR') if re.match('[0-9]+.*\\.jpg', f)]


convert dataframe `df` into a pivot table using column 'order' as index and values of column 'sample' as columns


python pickle/unpickle a list to/from a file 'afile'


Extract first two substrings in string `phrase` that end in `.`, `?` or `!`


how to write a unicode csv in Python 2.7

self.writer.writerow([str(s).encode('utf-8') for s in row])


calculat the difference between each row and the row previous to it in dataframe `data`


get index of elements in array `A` that occur in another array `B`


query all data from table `Task` where the value of column `time_spent` is bigger than 3 hours


np.zeros((6, 9, 20)) + np.array([VAR_STR])[(None), :, (None)]


np.zeros((VAR_STR)) + np.array([VAR_STR]).reshape((1, 9, 1))


extract first and last row of a dataframe `df`


convert date string '24052010' to date object in format '%d%m%Y'


calculate the mean of the nonzero values' indices of dataframe `df`


Get index of numpy array `a` with another numpy array `b`


tuple(int(x.strip()) for x in input().split(','))


rotate x-axis text labels of plot `ax` 45 degrees


sum the 3 largest integers in groupby by 'STNAME' and 'COUNTY_POP'


transform time series `df` into a pivot table aggregated by column 'Close' using column `df.index.date` as index and values of column `df.index.time` as columns

pd.pivot_table(df, index=df.index.date, columns=df.index.time, values='Close')

pd.pivot_table(VAR_STR, index=VAR_STR.index.date, columns=VAR_STR.index.time,
    values='VAR_STR')


Create array `a` containing integers from stdin

a.fromlist([int(val) for val in stdin.read().split()])

VAR_STR.fromlist([int(val) for val in stdin.read().split()])


sort list of nested dictionaries `yourdata` in reverse based on values associated with each dictionary's key 'subkey'

sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)

sorted(VAR_STR, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)


sort list of nested dictionaries `yourdata` in reverse order of 'key' and 'subkey'

yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)

VAR_STR.sort(VAR_STR=lambda e: e['VAR_STR']['VAR_STR'], reverse=True)


Draw node labels `labels` on networkx graph `G ` at position `pos`


get the common prefix from comparing two absolute paths '/usr/var' and '/usr/var2/log'


get relative path of path '/usr/var' regarding path '/usr/var/log/'


Evaluate a nested dictionary `myobject.id.number` to get `number` if `myobject` is present with getattr

getattr(getattr(myobject, 'id', None), 'number', None)

getattr(getattr(VAR_STR, 'id', None), 'VAR_STR', None)


outer product of each column of a 2d `X` array to form a 3d array `X`


create a list containing a four elements long tuples of permutations of binary values


match regex pattern '\\$[0-9]+[^\\$]*$' on string '$1 off delicious $5 ham.'


generate 6 random numbers between 1 and 50


generate six unique random numbers in the range of 1 to 49.


Change the current directory one level up


set the font 'Purisa' of size 12 for a canvas' text item `k`

canvas.create_text(x, y, font=('Purisa', 12), text=k)

canvas.create_text(x, y, font=('VAR_STR', 12), text=VAR_STR)


create a pandas data frame from list of nested dictionaries `my_list`

pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T

pd.concat([pd.DataFrame(l) for l in VAR_STR], axis=1).T


check if string `one` exists in the values of dictionary `d`


Check if value 'one' is among the values of dictionary `d`


change legend size to 'x-small' in upper-left location


change legend font size with matplotlib.pyplot to 6


remove all whitespace in a string `sentence`


pattern = re.compile('\\s+')
sentence = re.sub(pattern, '', sentence)

pattern = re.compile('\\s+')
VAR_STR = re.sub(pattern, '', VAR_STR)


remove whitespace in string `sentence` from beginning and end


remove all whitespaces in string `sentence`

sentence = re.sub('\\s+', '', sentence, flags=re.UNICODE)

VAR_STR = re.sub('\\s+', '', VAR_STR, flags=re.UNICODE)


remove all whitespaces in a string `sentence`


create dataframe `df` with content of hdf store file '/home/.../data.h5' with key of 'firstSet'

df1 = pd.read_hdf('/home/.../data.h5', 'firstSet')


read a text file 'very_Important.txt' into a string variable `str`

str = open('very_Important.txt', 'r').read()


handle the `urlfetch_errors ` exception for imaplib request to url `url`

urlfetch.fetch(VAR_STR, deadline=10 * 60)


remove the fragment identifier `#something` from a url `http://www.address.com/something#something`


reverse sort items in dictionary `mydict` by value


Flask get value of request variable 'firstname'


read the contents of the file 'file.txt' into `txt`


using python's datetime module, get the year that utc-11 is currently in


Filter model 'Entry' where 'id' is not equal to 3 in Django


using beautifulsoup to select div blocks within html `soup`


convert hex triplet string `rgbstr` to rgb tuple


reverse a string `a` by 2 characters at a time

"""""".join(reversed([a[i:i + 2] for i in range(0, len(a), 2)]))

"""""".join(reversed([VAR_STR[i:i + 2] for i in range(0, len(VAR_STR), 2)]))


Terminating a Python script with error message "some error message"


hide output of subprocess `['espeak', text]`


convert a string `s` containing a decimal to an integer


Convert a string to integer with decimal in Python


elementwise product of 3d arrays `A` and `B`


run shell command 'rm -r some.file' in the background


round off entries in dataframe `df` column `Alabama_exp` to two decimal places, and entries in column `Credit_exp` to three decimal places

df.round({'Alabama_exp': 2, 'Credit_exp': 3})

VAR_STR.round({'VAR_STR': 2, 'VAR_STR': 3})


retrieve an element from a set `s` without removing it


Parse string `datestr` into a datetime object using format pattern '%Y-%m-%d'

dateobj = datetime.datetime.strptime(datestr, '%Y-%m-%d').date()

dateobj = datetime.datetime.strptime(VAR_STR, 'VAR_STR').date()


encode a pdf file `pdf_reference.pdf` with `base64` encoding

a = open('pdf_reference.pdf', 'rb').read().encode('base64')

a = open('VAR_STR', 'rb').read().encode('VAR_STR')


change current working directory to directory 'chapter3'


Match regex '[a-zA-Z][\\w-]*\\Z' on string 'A\n'


match regex '[a-zA-Z][\\w-]*$' on string '!A_B'


Find all `div` tags whose classes has the value `comment-` in a beautiful soup object `soup`


Open file 'sample.json' in read mode with encoding of 'utf-8-sig'


load json file 'sample.json' with utf-8 bom header


convert string representation `s2` of binary string rep of integer to floating point number

struct.unpack('d', struct.pack('Q', int(s2, 0)))[0]

struct.unpack('d', struct.pack('Q', int(VAR_STR, 0)))[0]


convert a binary '-0b1110' to a float number


in django, check if a user is in a group 'Member'


check if a user `user` is in a group from list of groups `['group1', 'group2']`


find rows matching `(0,1)` in a 2 dimensional numpy array `vals`

np.where((VAR_STR == (0, 1)).all(axis=1))


change directory to the directory of a python script


export a table dataframe `df` in pyspark to csv 'mycsv.csv'


Write DataFrame `df` to csv file 'mycsv.csv'


zip a list of tuples `[(1, 4), (2, 5), (3, 6)]` into a list of tuples according to original tuple index


split a list of tuples `data` into sub-lists of the same tuple field using itertools

[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]

[list(group) for key, group in itertools.groupby(VAR_STR, operator.itemgetter(1))
    ]


pandas dataframe `df` column 'a' to list


Get a list of all values in column `a` in pandas data frame `df`


parse UTF-8 encoded HTML response `response` to BeautifulSoup object


get all the values from a numpy array `a` excluding index 3


get the output of a subprocess command `echo "foo"` in command line


extract unique dates from time series 'Date' in dataframe `df`


check if file `filename` is descendant of directory '/the/dir/'

os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == '/the/dir/'

os.path.commonprefix(['VAR_STR', os.path.realpath(VAR_STR)]) == 'VAR_STR'


create a dictionary of pairs from a list of tuples `myListOfTuples`

dict(x[1:] for x in reversed(myListOfTuples))


sort a list of dictionary values by 'date' in reverse order

list.sort(key=lambda item: item['date'], reverse=True)

list.sort(key=lambda item: item['VAR_STR'], reverse=True)


export a pandas data frame `df` to a file `mydf.tsv` and retain the indices


Get the difference between two lists `[1, 2, 2, 2, 3]` and `[1, 2]` that may have duplicate values


compare contents  at filehandles `file1` and `file2` using difflib


Get a minimum value from a list of tuples `list` with values of type `string` and `float` with nan

min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])

min(VAR_STR, key=lambda x: VAR_STR('inf') if math.isnan(x[1]) else x[1])


convert list `lst` of tuples of floats to list `str_list` of tuples of strings of floats in scientific notation with eight decimal point precision

str_list = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in lst]

VAR_STR = [tuple('{0:.8e}'.format(flt) for flt in sublist) for sublist in VAR_STR]


convert list of sublists `lst` of floats to a list of sublists `str_list` of strings of integers in scientific notation with 8 decimal points

str_list = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in lst]

VAR_STR = [['{0:.8e}'.format(flt) for flt in sublist] for sublist in VAR_STR]


get element at index 0 of first row and element at index 1 of second row in array `A`


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.


Find all the tags `a` and `div` from Beautiful Soup object `soup`


def reversed_string(a_string):
    return a_string[::(-1)]

def reversed_string(VAR_STR):
    return VAR_STR[::-1]


set the stdin of the process 'grep f' to be b'one\ntwo\nthree\nfour\nfive\nsix\n'

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n')[0]

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input='VAR_STR')[0]


set the stdin of the process 'grep f' to be 'one\ntwo\nthree\nfour\nfive\nsix\n'

p = subprocess.Popen(['grep', 'f'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
p.stdin.write('one\ntwo\nthree\nfour\nfive\nsix\n')
p.communicate()[0]
p.stdin.close()

p = subprocess.Popen(['grep', 'f'], stdout=subprocess.PIPE, stdin=
    subprocess.PIPE)
p.stdin.write('VAR_STR')
p.communicate()[0]
p.stdin.close()


normalize a pandas dataframe `df` by row


read a file from redirected stdin and save to variable `result`


remove elements from an array `A` that are in array `B`

A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]

VAR_STR[np.all(np.any(VAR_STR - VAR_STR[:, (None)], axis=2), axis=0)]


drop rows of dataframe `df` whose index is smaller than the value of `start_remove` or bigger than the value of`end_remove`

df.query('index < @start_remove or index > @end_remove')

VAR_STR.query('index < @start_remove or index > @end_remove')


Drop the rows in pandas timeseries `df` from the row containing index `start_remove` to the row containing index `end_remove`

df.loc[(df.index < start_remove) | (df.index > end_remove)]

VAR_STR.loc[(VAR_STR.index < VAR_STR) | (VAR_STR.index > VAR_STR)]


Get all indexes of boolean numpy array where boolean value `mask` is True


Convert CSV file `Result.csv` to Pandas dataframe using separator ' '

df.to_csv('Result.csv', index=False, sep=' ')

df.to_csv('VAR_STR', index=False, sep=' ')


convert a list of dictionaries `d` to pandas data frame


Open gzip-compressed file encoded as utf-8 'file.gz' in text mode


navigate to webpage given by url `http://www.python.org` using Selenium


check if "blah" is in string `somestring`


check if string `needle` is in `haystack`


check if string "substring" is in string


if (s.find('is') == (-1)):
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")

if VAR_STR.find('VAR_STR') == -1:
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")


calling a function named 'myfunction' in the module


convert double 0.00582811585976 to float


[dict(y) for y in set(tuple(x.items()) for x in d)]


get a list of words `words` of a file 'myfile'


create a django query for a list of values `1, 4, 7`


case insensitive comparison of strings `string1` and `string2`

if (string1.lower() == string2.lower()):
    print('The strings are the same (case insensitive)')
else:
    print('The strings are not the same (case insensitive)')

if VAR_STR.lower() == VAR_STR.lower():
    print('The strings are the same (case insensitive)')
else:
    print('The strings are not the same (case insensitive)')


case insensitive string comparison between `string1` and `string2`

if (string1.lower() == string2.lower()):
    pass

if VAR_STR.lower() == VAR_STR.lower():
    pass


case insensitive string comparison between `first` and `second`


case insensitive comparison between strings `first` and `second`


Create a pandas dataframe of values from a dictionary `d` which contains dictionaries of dictionaries

pd.concat(map(pd.DataFrame, iter(VAR_STR.values())), keys=list(VAR_STR.keys())
    ).stack().unstack(0)


get count of rows in each series grouped by column 'col5' and column 'col2' of dataframe `df`


get the attribute `x` from object `your_obj`


convert datetime object to date object in python


How do I convert datetime to date (in Python)?


sort numpy float array `A` column by column

VAR_STR = np.array(sorted(VAR_STR, key=tuple))


Update a user's name as `Bob Marley` having id `123` in SQLAlchemy


define global variable `something` with value `bob`


Check whether a numpy array `a` contains a given row `[1, 2]`


convert dict `result` to numpy structured array

numpy.array([(key, val) for key, val in result.items()], dtype)

numpy.array([(key, val) for key, val in VAR_STR.items()], dtype)


sort list `mylist` in alphabetical order


load a file `file.py` into the python console


check if string `test.mp3` ends with one of the strings from a tuple `('.mp3', '.avi')`


unpack first and second bytes of byte string `pS` into integer


check if all string elements in list `words` are upper-cased

print(all(word[0].isupper() for word in words))

print(all(word[0].isupper() for word in VAR_STR))


convert dataframe `df` to integer-type sparse object


check if object `a` has property 'property'

if hasattr(VAR_STR, 'VAR_STR'):
    pass


get the value of attribute 'property' of object `a` with default value 'default value'


create a list of all unique characters in string 'aaabcabccd'


get list of all unique characters in a string 'aaabcabccd'


List of all unique characters in a string?


find the index of sub string 'World' in `x`


find the index of sub string 'Aloha' in `x`


find the index of sub string 'cc' in string 'sdfasdf'


find the index of sub string 'df' in string 'sdfasdf'


find the index of sub string 'a' in string `str`


find the index of sub string 'g' in string `str`


find the index of sub string 's' in string `str` starting from index 11


find the index of sub string 's' in string `str` starting from index 15


find the index of sub string 's' in string `str` starting from index 16


find the index of sub string 's' in string `str` starting from index 11 and ending at index 14


reverse sort items in default dictionary `cityPopulation` by the third item in each key's list of values

sorted(iter(cityPopulation.items()), key=lambda k_v: k_v[1][2], reverse=True)

sorted(iter(VAR_STR.items()), key=lambda k_v: k_v[1][2], reverse=True)


Sort dictionary `u` in ascending order based on second elements of its values

sorted(list(u.items()), key=lambda v: v[1])

sorted(list(VAR_STR.items()), key=lambda v: v[1])


reverse sort dictionary `d` based on its values

sorted(list(d.items()), key=lambda k_v: k_v[1], reverse=True)

sorted(list(VAR_STR.items()), key=lambda k_v: k_v[1], reverse=True)


sorted(list(d.items()), key=lambda k_v: k_v[1])

sorted(list(VAR_STR.items()), key=lambda k_v: k_v[1])


terminate the script using status value 0


abort the execution of the script using message 'aa! errors!'


create a pandas dataframe `df` from elements of a dictionary `nvalues`

df = pd.DataFrame.from_dict({k: v for k, v in list(nvalues.items()) if k != 'y3'})

VAR_STR = pd.DataFrame.from_dict({k: v for k, v in list(VAR_STR.items()) if k !=
    'y3'})


find href value that has string 'follow?page' inside it


Get the average values from two numpy arrays `old_set` and `new_set`


create a set containing all keys' names from dictionary `LoD`

{k for d in LoD for k in list(d.keys())}

{k for d in VAR_STR for k in list(d.keys())}


create a set containing all keys names from list of dictionaries `LoD`

set([i for s in [list(d.keys()) for d in LoD] for i in s])

set([i for s in [list(d.keys()) for d in VAR_STR] for i in s])


extract all keys from a list of dictionaries `LoD`

[i for s in [list(d.keys()) for d in LoD] for i in s]

[i for s in [list(d.keys()) for d in VAR_STR] for i in s]


create a list containing the digits values from binary string `x` as elements


group dataframe `df` by columns 'Month' and 'Fruit'


request page 'https://www.mysite.com/' with credentials of username 'username' and password 'pwd'


list folders in zip file 'file' that ends with '/'

[x for x in file.namelist() if x.endswith('/')]

[x for x in VAR_STR.namelist() if x.endswith('VAR_STR')]


remove all spaces from a string converted from dictionary `{'a': 1, 'b': 'as df'}`


convert dictionary `dict` into a string formatted object


load a json data `json_string` into variable `json_data`


Retrieve parameter 'var_name' from a GET request.


convert keys in dictionary `thedict` into case insensitive

theset = set(k.lower() for k in thedict)

theset = set(k.lower() for k in VAR_STR)


merge 2 dataframes `df1` and `df2` with same values in a column 'revenue' with and index 'date'


permanently set the current directory to the 'C:/Users/Name/Desktop'


get the  size of file 'C:\\Python27\\Lib\\genericpath.py'


urlencode a querystring 'string_of_characters_like_these:$#@=?%^Q^$' in python 2


How to get only the last part of a path in Python?


create a list of values from the dictionary `programs` that have a key with a case insensitive match to 'new york'

[value for key, value in list(programs.items()) if 'new york' in key.lower()]

[value for key, value in list(VAR_STR.items()) if 'VAR_STR' in key.lower()]


Replace special characters in utf-8 encoded string `s` using the %xx escape


Get sum of values of columns  'Y1961', 'Y1962', 'Y1963' after group by on columns "Country" and "Item_code" in dataframe `df`.

VAR_STR.groupby(['VAR_STR', 'Item_Code'])[['VAR_STR', 'VAR_STR', 'VAR_STR']].sum()


get the number of values in list `j` that is greater than 5


get the number of values in list `j` that is greater than `i`

VAR_STR = np.array(VAR_STR)
sum(VAR_STR > VAR_STR)


check if a numpy array `a1` contains any element of another array `a2`


clamping floating number `my_value` to be between `min_value` and `max_value`


lst = list(itertools.product([0, 1], repeat=n))


lst = map(list, itertools.product([0, 1], repeat=n))


bin = [0, 1]
[(x, y, z) for x in bin for y in bin for z in bin]


lst = list(itertools.product([0, 1], repeat=3))


add one day and three hours to the present time from datetime.now()

datetime.datetime.now() + datetime.timedelta(days=1, hours=3)


unpack the binary data represented by the hexadecimal string '4081637ef7d0424a' to a float


add a colorbar to plot `plt` using image `im` on axes `ax`


remove first and last lines of string `s`


From multiIndexed dataframe `data` select columns `a` and `c` within each higher order column `one` and `two`

data.loc[:, (list(itertools.product(['one', 'two'], ['a', 'c'])))]

VAR_STR.loc[:, (list(itertools.product(['VAR_STR', 'VAR_STR'], ['VAR_STR', 'VAR_STR'])))]


select only specific columns 'a' and 'c' from a dataframe 'data' with multiindex columns

VAR_STR.loc[:, ([('one', 'VAR_STR'), ('one', 'VAR_STR'), ('two', 'VAR_STR'), ('two',
    'VAR_STR')])]


filter `Users` by field `userprofile` with level greater than or equal to `0`


make a list of lists in which each list `g` are the elements from list `test` which have the same characters up to the first `_` character

[list(g) for _, g in itertools.groupby(test, lambda x: x.split('_')[0])]

[list(VAR_STR) for VAR_STR, VAR_STR in itertools.groupby(VAR_STR, lambda x: x.split
    ('VAR_STR')[0])]


[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]


django get the value of key 'title' from POST request `request` if exists, else return empty string ''


List comprehension with an accumulator in range of 10


Create a default empty json object if no json is available in request parameter `mydata`


get the largest index of the last occurrence of characters '([{' in string `test_string`

max(test_string.rfind(i) for i in '([{')

max(VAR_STR.rfind(i) for i in 'VAR_STR')


get all characters in string 'foobar' up to the fourth index


count unique index values in column 'A' in pandas dataframe `ex`

VAR_STR.groupby(level='VAR_STR').agg(lambda x: x.index.get_level_values(1).
    nunique())


Create a tuple `t` containing first element of each tuple in tuple `s`


BeautifulSoup get value associated with attribute 'content' where attribute 'name' is equal to 'City' in tag 'meta' in HTML parsed string `soup`


pivot dataframe `df` so that values for `upc` become column headings and values for `saleid` become the index

df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0)

VAR_STR.pivot_table(index='VAR_STR', columns='VAR_STR', aggfunc='size', fill_value=0)


changing permission of file `path` to `stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH`

os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

os.chmod(VAR_STR, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)


write dataframe `df` to csv file `filename` with dates formatted as yearmonthday  `%Y%m%d`


replace NaN values in array `a` with zeros

b = np.where(np.isnan(VAR_STR), 0, VAR_STR)


get a numpy array that contains the element wise minimum of three 3x1 arrays

np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)


obtain the current day of the week in a 3 letter format from a datetime object


"""<br/>""".join([('%s:: %s' % (key, value)) for key, value in list(d.items())])

"""<br/>""".join([('%s:: %s' % (key, value)) for key, value in list(VAR_STR.
    items())])


select rows of dataframe `df` whose value for column `A` is `foo`


select rows whose column value in column `column_name` does not equal `some_value` in pandas data frame


select rows from a dataframe `df` whose value for column `column_name` is not in `some_values`


select all rows whose values in a column `column_name` equals a scalar `some_value` in pandas data frame object `df`


Select rows whose value of the "B" column is "one" or "three" in the DataFrame `df`


get a list of locally installed Python modules


Enable the SO_REUSEADDR socket option in socket object `s` to fix the error `only one usage of each socket address is normally permitted`


import all classes from module `some.package`


Find indices of elements equal to zero from numpy array `x`


Convert a string `s` containing hex bytes to a hex string


convert a string `s` containing hex bytes to a hex string


zip list `a`, `b`, `c` into a list of tuples

[(x + tuple(y)) for x, y in zip(zip(a, b), c)]

[(x + tuple(y)) for x, y in zip(zip(VAR_STR, VAR_STR), VAR_STR)]


"""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))

"""""".join('{}{}'.format(key, val) for key, val in sorted(VAR_STR.items()))


"""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))

"""""".join('{}{}'.format(key, val) for key, val in list(VAR_STR.items()))


convert matlab engine array `x` to a numpy ndarray


Convert list of booleans `walls` into a hex string

hex(int(''.join([str(int(b)) for b in walls]), 2))

hex(int(''.join([str(int(b)) for b in VAR_STR]), 2))


convert the sum of list `walls` into a hex presentation

hex(sum(b << i for i, b in enumerate(reversed(walls))))

hex(sum(b << i for i, b in enumerate(reversed(VAR_STR))))


set the current working directory to 'c:\\Users\\uname\\desktop\\python'


set the current working directory to path `path`


Check the status code of url "http://www.stackoverflow.com"


Check the status code of url "www.python.org"

conn = httplib.HTTPConnection('www.python.org')
conn.request('HEAD', '/')
r1 = conn.getresponse()
print(r1.status, r1.reason)

conn = httplib.HTTPConnection('VAR_STR')
conn.request('HEAD', '/')
r1 = conn.getresponse()
print(r1.status, r1.reason)


r = requests.head(url)
return (r.status_code == 200)

r = requests.head(VAR_STR)
return r.status_code == 200


Checking if website "http://www.stackoverflow.com" is up


rename column 'gdp' in dataframe `data` to 'log(gdp)'


commit all the changes after executing a query.


best way to extract subset of key-value pairs with keys matching 'l', 'm', or 'n' from python dictionary object

{k: bigdict[k] for k in list(bigdict.keys()) & {'l', 'm', 'n'}}

{k: bigdict[k] for k in list(bigdict.keys()) & {'VAR_STR', 'VAR_STR', 'VAR_STR'}}


extract subset of key-value pairs with keys as `('l', 'm', 'n')` from dictionary object `bigdict`

dict((k, bigdict[k]) for k in ('l', 'm', 'n'))

dict((k, VAR_STR[k]) for k in (VAR_STR))


Get items from a dictionary `bigdict` where the keys are present in `('l', 'm', 'n')`

{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}

{k: VAR_STR.get(k, None) for k in (VAR_STR)}


Extract subset of key value pair for keys 'l', 'm', 'n' from `bigdict` in python 3

{k: bigdict[k] for k in ('l', 'm', 'n')}

{k: VAR_STR[k] for k in ('VAR_STR', 'VAR_STR', 'VAR_STR')}


Search for string 'blabla' in txt file 'example.txt'

if ('blabla' in open('example.txt').read()):
    pass

if 'VAR_STR' in open('VAR_STR').read():
    pass


f = open('example.txt')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if (s.find('blabla') != (-1)):
    pass

f = open('VAR_STR')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('VAR_STR') != -1:
    pass


Search for string `blabla` in txt file 'example.txt'

datafile = file('example.txt')
found = False
for line in datafile:
    if (blabla in line):
        return True
return False

datafile = file('VAR_STR')
found = False
for line in datafile:
    if VAR_STR in line:
        return True
return False


request http url `url` with parameters `payload`

r = requests.get(VAR_STR, params=VAR_STR)


post request url `url` with parameters `payload`

r = requests.post(VAR_STR, data=VAR_STR)


make an HTTP post request with data `post_data`

post_response = requests.post(url='http://httpbin.org/post', json=post_data)

post_response = requests.post(url='http://httpbin.org/post', json=VAR_STR)


convert binary string '01010101111' to integer


convert binary string '010101' to integer


convert binary string '0b0010101010' to integer


convert binary string '11111111' to integer


get proportion of rows in dataframe `trace_df` whose values for column `ratio` are greater than 0


get all possible combination of items from 2-dimensional list `a`


iterate over a dictionary `d` in sorted order


for (key, value) in sorted(d.items()):
    pass

for key, value in sorted(VAR_STR.items()):
    pass


iterate over a dictionary `dict` in sorted order


iterate over a dictionary `foo` in sorted order

for (k, v) in sorted(foo.items()):
    pass

for k, v in sorted(VAR_STR.items()):
    pass


iterate over a dictionary `foo` sorted by the key

for k in sorted(VAR_STR.keys()):
    pass


lower-case the string obtained by replacing the occurrences of regex pattern '(?<=[a-z])([A-Z])' in string `s` with eplacement '-\\1'


convert a tensor with list of constants `[1, 2, 3]` into a numpy array in tensorflow


Initialize a pandas series object `s` with columns `['A', 'B', 'A1R', 'B2', 'AABB4']`


get set intersection between dictionaries `d1` and `d2`

dict((x, set(y) & set(d1.get(x, ()))) for x, y in d2.items())

dict((x, set(y) & set(VAR_STR.get(x, ()))) for x, y in VAR_STR.items())


construct pandas dataframe from a list of tuples

df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])


converting dictionary `d` into a dataframe `pd` with keys as data for column 'Date' and the corresponding values as data for column 'DateValue'


generate a random number in 1 to 7 with a given distribution [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]


Convert dataframe `df` to a pivot table using column 'year', 'month', and 'item' as indexes


run a pivot with a multi-index `year` and `month` in a pandas data frame

df.pivot_table(values='value', index=['year', 'month'], columns='item')

df.pivot_table(values='value', index=['VAR_STR', 'VAR_STR'], columns='item')


How to get output of exe in python script?

output = subprocess.Popen(['mycmd', 'myarg'], stdout=PIPE).communicate()[0]


get all sub-elements of an element `a` in an elementtree


get all sub-elements of an element tree `a` excluding the root element

[elem.tag for elem in a.iter() if elem is not a]

[elem.tag for elem in VAR_STR.iter() if elem is not VAR_STR]


get the next value greatest to `2` from a list of numbers `num_list`


if VAR_STR in VAR_STR:
    VAR_STR.remove(VAR_STR)


try:
    a.remove(c)
except ValueError:
    pass

try:
    VAR_STR.remove(VAR_STR)
except ValueError:
    pass


call a function `otherfunc` inside a bash script `test.sh` using subprocess


Can a python script execute a function inside a bash script?

subprocess.Popen(['bash', '-c', '. foo.sh; go'])


write pandas dataframe `df` to the file 'c:\\data\\t.csv' without row names


match regex pattern '(\\d+(\\.\\d+)?)' with string '3434.35353'


filter the objects in django model 'Sample' between date range `2011-01-01` and `2011-01-31`


filter objects month wise in django model `Sample` for year `2011`


img = Image.open('picture.jpg')
img.show()


img = Image.open('picture.jpg')
Img.show


write the content of file `xxx.mp4` to file `f`


Sort the values of the dataframe `df` and align the columns accordingly based on the obtained indices after np.argsort.

pd.DataFrame(VAR_STR.columns[np.argsort(VAR_STR.values)], VAR_STR.index, np.
    unique(VAR_STR.values))


remove duplicate rows from dataframe `df1` and calculate their frequency


Get average for every three columns in `df` dataframe

df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()

VAR_STR.groupby(np.arange(len(VAR_STR.columns)) // 3, axis=1).mean()


django redirect to view 'Home.views.index'


get a list of keys of dictionary `things` sorted by the value of nested dictionary key 'weight'

sorted(list(things.keys()), key=lambda x: things[x]['weight'], reverse=True)

sorted(list(VAR_STR.keys()), key=lambda x: VAR_STR[x]['VAR_STR'], reverse=True)


get the path of the current python module


get the path of the python module `amodule`


sum the values in each row of every two adjacent columns in dataframe `df`

df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')

VAR_STR.groupby(np.arange(len(VAR_STR.columns)) // 2 + 1, axis=1).sum().add_prefix(
    's')


capture final output of a chain of system commands `ps -ef | grep something | wc -l`

subprocess.check_output('ps -ef | grep something | wc -l', shell=True)


find intersection data between series `s1` and series `s2`


Format a datetime string `when` to extract date only

then = datetime.datetime.strptime(when, '%Y-%m-%d').date()

then = datetime.datetime.strptime(VAR_STR, '%Y-%m-%d').date()


get the first object from a queryset in django model `Entry`


download a file "http://www.example.com/songs/mp3.mp3" over HTTP and save to "mp3.mp3"


download a file `url` over HTTP and save to `file_name`

u = urllib.request.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders('Content-Length')[0])
print(('Downloading: %s Bytes: %s' % (file_name, file_size)))
file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if (not buffer):
        break
    file_size_dl += len(buffer)
    f.write(buffer)
    status = ('%10d  [%3.2f%%]' % (file_size_dl, ((file_size_dl * 100.0) / file_size)))
    status = (status + (chr(8) * (len(status) + 1)))
    print(status, end=' ')
f.close()

u = urllib.request.urlopen(VAR_STR)
f = open(VAR_STR, 'wb')
meta = u.info()
file_size = int(meta.getheaders('Content-Length')[0])
print('Downloading: %s Bytes: %s' % (VAR_STR, file_size))
file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
        break
    file_size_dl += len(buffer)
    f.write(buffer)
    status = '%10d  [%3.2f%%]' % (file_size_dl, file_size_dl * 100.0 /
        file_size)
    status = status + chr(8) * (len(status) + 1)
    print(status, end=' ')
f.close()


download a file 'http://www.example.com/' over HTTP

response = urllib.request.urlopen('http://www.example.com/')
html = response.read()

response = urllib.request.urlopen('VAR_STR')
html = response.read()


download a file `url` over HTTP and save to "10MB"

response = requests.get(url, stream=True)
with open('10MB', 'wb') as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)

response = requests.get(VAR_STR, stream=True)
with open('VAR_STR', 'wb') as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)


Multiply a matrix `P` with a 3d tensor `T` in scipy

scipy.tensordot(P, T, axes=[1, 1]).swapaxes(0, 1)

scipy.tensordot(VAR_STR, VAR_STR, axes=[1, 1]).swapaxes(0, 1)


convert hex string '470FC614' to a float number


get the date 7 days before the current date


encode binary string 'your string' to base64 code


identify duplicate values in list `mylist`

[k for k, v in list(Counter(mylist).items()) if v > 1]

[k for k, v in list(Counter(VAR_STR).items()) if v > 1]


write the data of dataframe `df` into text file `np.txt`


write content of DataFrame `df` into text file 'c:\\data\\pandas.txt'

df.to_csv('c:\\data\\pandas.txt', header=None, index=None, sep=' ', mode='a')

VAR_STR.to_csv('VAR_STR', header=None, index=None, sep=' ', mode='a')


Split a string `x` by last occurrence of character `-`


get the last part of a string before the character '-'


[int(1000 * random.random()) for i in range(10000)]


Using %f with strftime() in Python to get microseconds


print a 2 dimensional list `tab` as a table with delimiters

print('\n'.join('\t'.join(str(col) for col in row) for row in tab))

print('\n'.join('\t'.join(str(col) for col in row) for row in VAR_STR))


count non zero values in each column in pandas data frame


lower a string `text` and remove non-alphanumeric characters aside from space


remove all non-alphanumeric characters except space from a string `text` and lower it


access a tag called "name" in beautifulsoup `soup`


Get the characters count in a file `filepath`


count the occurrences of item "a" in list `l`


count the occurrences of items in list `l`


[[x, VAR_STR.count(x)] for x in set(VAR_STR)]


dict((x, VAR_STR.count(x)) for x in set(VAR_STR))


count the occurrences of item "b" in list `l`


copy file `srcfile` to directory `dstdir`


combine values from column 'b' and column 'a' of dataframe `df`  into column 'c' of datafram `df`

df['c'] = np.where(df['a'].isnull, df['b'], df['a'])

VAR_STR['VAR_STR'] = np.where(VAR_STR['VAR_STR'].isnull, VAR_STR['VAR_STR'], VAR_STR['VAR_STR']
    )


send the output of pprint object `dataobject` to file `logFile`


Create a list containing the indexes of rows where the value of column 'BoolCol' in dataframe `df` are equal to True


get list of indexes of rows where column 'BoolCol' values match True


get index of rows in dataframe `df` which column 'BoolCol' matches value True


change working directory to the directory `owd`


remove a div with a id `main-content` using beautifulsoup


join each element in array `a` with element at the same index in array `b` as a tuple

np.array([zip(x, y) for x, y in zip(a, b)])

np.array([zip(x, y) for x, y in zip(VAR_STR, VAR_STR)])


Find last occurrence of character '}' in string "abcd}def}"


determine number of files on a drive with python


how to get a single result from a SQLite query in python?


prepend the line '#test firstline\n' to the contents of file 'infile' and save as the file 'outfile'

open('outfile', 'w').write('#test firstline\n' + open('infile').read())

open('VAR_STR', 'w').write('VAR_STR' + open('VAR_STR').read())


return `True` if string `foobarrrr` contains regex `ba[rzd]`


Removing duplicates in list `source_list`


Removing duplicates in list `abracadabra`


Convert the first row of numpy matrix `a` to a list


In `soup`, get the content of the sibling of the `td`  tag with text content `Address:`


encoded = base64.b64encode('data to be encoded')


encode a string `data to be encoded` to `ascii` encoding

encoded = 'data to be encoded'.encode('ascii')


Get attribute `my_str` of object `my_object`


replace all elements in array `A` that are not present in array `[1, 3, 4]` with zeros

np.where(np.in1d(A, [1, 3, 4]).reshape(A.shape), A, 0)

np.where(np.in1d(VAR_STR, [VAR_STR]).reshape(VAR_STR.shape), VAR_STR, 0)


calculate mean across dimension in a 2d array `a`


selecting rows in Numpy ndarray 'a', where the value in the first column is 0 and value in the second column is 1


convert a pandas series `sf` into a pandas dataframe `df` with columns `email` and `list`

pd.DataFrame({'email': sf.index, 'list': sf.values})

pd.DataFrame({'VAR_STR': VAR_STR.index, 'VAR_STR': VAR_STR.values})


resized image `image` to width, height of `(x, y)` with filter of `ANTIALIAS`

image = image.resize((x, y), Image.ANTIALIAS)

VAR_STR = VAR_STR.resize((VAR_STR), Image.VAR_STR)


find 10 largest differences between each respective elements of list `l1` and list `l2`

heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))

heapq.nlargest(10, range(len(VAR_STR)), key=lambda i: abs(VAR_STR[i] - VAR_STR[i]))


BeautifulSoup find all 'span' elements in HTML string `soup` with class of 'starGryB sp'

soup.find_all('span', {'class': 'starGryB sp'})


Sort lis `list5` in ascending order based on the degrees value of its elements

sorted(VAR_STR, lambda x: (degree(x), x))


How do I perform secondary sorting in python?

sorted(list5, key=lambda vertex: (degree(vertex), vertex))


encode `Decimal('3.9')` to a JSON string


filter dataframe `df` by values in column `A` that appear more than once

df.groupby('A').filter(lambda x: len(x) > 1)

VAR_STR.groupby('VAR_STR').filter(lambda x: len(x) > 1)


add color bar with image `mappable` to plot `plt`


count most frequent 100 words in column 'text' of dataframe `df`


get a value of datetime.today() in the UTC time zone


Open a background process 'background-process' with arguments 'arguments'


finding the index of elements containing substring 'how' and 'what' in a list of strings 'myList'.

[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]

[i for i, j in enumerate(VAR_STR) if 'VAR_STR' in j.lower() or 'VAR_STR' in j.lower()
    ]


unpack a series of tuples in pandas into a DataFrame with column names 'out-1' and 'out-2'

pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)

pd.DataFrame(out.tolist(), columns=['VAR_STR', 'VAR_STR'], index=out.index)


rotate the xtick labels of matplotlib plot `ax` by `45` degrees to make long labels readable


get number of keys in dictionary `yourdict`


count the number of keys in dictionary `yourdictfile`


split a list in first column  into multiple columns keeping other columns as well in pandas data frame


Call a subprocess with arguments `c:\\Program Files\\VMware\\VMware Server\\vmware-cmd.bat` that may contain spaces


reverse a priority queue `q` in python without using classes


numpy concatenate two arrays `a` and `b` along the first axis


numpy concatenate two arrays `a` and `b` along the second axis


c = np.r_[VAR_STR[(None), :], VAR_STR[(None), :]]


Get the integer location of a key `bob` in a pandas data frame


converting two lists `[1, 2, 3]` and `[4, 5, 6]` into a matrix


delete all occurrences of character 'i' in string 'it is icy'

"""""".join([char for char in 'it is icy' if char != 'i'])

"""""".join([char for char in 'VAR_STR' if char != 'VAR_STR'])


delete all instances of a character 'i' in a string 'it is icy'


delete all characters "i" in string "it is icy"


How to delete all instances of a character in a string in python?

"""""".join([char for char in 'it is icy' if char != 'i'])


converting list of strings `intstringlist` to list of integer `nums`


convert list of string numbers into list of integers

map(int, eval(input('Enter the unfriendly numbers: ')))


Find all files in directory "/mydir" with extension ".txt"

os.chdir('/mydir')
for file in glob.glob('*.txt'):
    pass

os.chdir('VAR_STR')
for file in glob.glob('*.txt'):
    pass


for file in os.listdir('/mydir'):
    if file.endswith('.txt'):
        pass

for file in os.listdir('VAR_STR'):
    if file.endswith('VAR_STR'):
        pass


for (root, dirs, files) in os.walk('/mydir'):
    for file in files:
        if file.endswith('.txt'):
            pass

for root, dirs, files in os.walk('VAR_STR'):
    for file in files:
        if file.endswith('VAR_STR'):
            pass


decode json string `request.body` to python dict


How to sort a Dataframe by the ocurrences in a column in Python (pandas)


get json data from restful service 'url'


sort a list of dictionary `list` first by key `points` and then by `time`

list.sort(key=lambda item: (item['points'], item['time']))

VAR_STR.sort(key=lambda item: (item['VAR_STR'], item['VAR_STR']))


Convert integer `number` into an unassigned integer


write dataframe `df`, excluding index, to a csv file


convert a urllib unquoted string `unescaped` to a json data `json_data`


write `newFileBytes` to a binary file `newFile`


Django get maximum value associated with field 'added' in model `AuthorizedEmail`


create a datetime with the current date & time


get the highest element in absolute value in a numpy matrix `x`