intent
stringlengths
4
183
snippet
stringlengths
2
1k
access item in a list of lists
list1[0][2]
load csv into 2d matrix with numpy for plotting
numpy.loadtxt(open('test.csv', 'rb'), delimiter=',', skiprows=1)
how to delete an object using django rest framework
url('^delete/(?P<pk>\\d+)', views.EventDetail.as_view(), name='delete_event'),
get data from the meta tags using beautifulsoup
soup.findAll(attrs={'name': 'description'})
numpy array assignment using slicing
values = np.array([i for i in range(100)], dtype=np.float64)
how to add a second x-axis in matplotlib
plt.show()
how do i remove identical items from a list and sort it in python?
sorted(set(my_list))
insert string `string1` after each character of `string2`
string2.replace('', string1)[len(string1):-len(string1)]
find indices of large array if it contains values in smaller array
np.where(np.in1d(a, b))
how do i slice a numpy array to get both the first and last two rows
x[[0, 1, -2, -1]]
sort a list of tuples `my_list` by second parameter in the tuple
my_list.sort(key=lambda x: x[1])
sorting list in python
l.sort(key=alphanum_key)
convert rows in pandas data frame `df` into list
df.apply(lambda x: x.tolist(), axis=1)
best way to delete a django model instance after a certain date
print(Event.objects.filter(date__lt=datetime.datetime.now()).delete())
apply logical operator 'and' to all elements in list `a_list`
all(a_list)
apply multiple functions to multiple groupby columns
df.groupby('GRP').agg(f)
reverse sort items in dictionary `mydict` by value
sorted(iter(mydict.items()), key=itemgetter(1), reverse=True)
django database query: how to filter objects by date range?
Sample.objects.filter(date__year='2011', date__month='01')
python regular expression matching a multiline block of text
re.compile('^(.+)\\n((?:\\n.+)+)', re.MULTILINE)
access index of last element in data frame
df['date'][df.index[-1]]
how to convert triangle matrix to square in numpy?
np.where(np.eye(A.shape[0], dtype=bool), A, A.T + A)
get a list `c` by subtracting values in one list `b` from corresponding values in another list `a`
C = [(a - b) for a, b in zip(A, B)]
lowercase keys and values in dictionary `{'my key': 'my value'}`
{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}
how to "scale" a numpy array?
np.kron(a, np.ones((n, n)))
beautiful soup [python] and the extracting of text in a table
table = soup.find('table', attrs={'class': 'bp_ergebnis_tab_info'})
regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc
re.sub('g+', 'g', 'omgggg')
in python how can i declare a dynamic array
lst = [1, 2, 3]
sort a list in python based on another sorted list
sorted(unsorted_list, key=presorted_list.index)
mmap file inquiry for a blank file in python
sys.stdout.flush()
python list of dictionaries[int : tuple] sum
sum(v[1] for d in myList for v in d.values())
find the mean of elements in list `l`
sum(l) / float(len(l))
convert strings to int or float in python 3?
print('2 + ' + str(integer) + ' = ' + str(rslt))
interleaving lists in python
[x for t in zip(list_a, list_b) for x in t]
is it possible to run pygame as a cronjob?
pygame.display.set_mode((1, 1))
using regular expression to split string in python
[i[0] for i in re.findall('((\\d)(?:[()]*\\2*[()]*)*)', s)]
read a single character from stdin
sys.stdin.read(1)
trimming a string " hello"
' Hello'.strip()
array in python with arbitrary index
[100, None, None, None, None, None, None, None, None, None, 200]
rendering text with multiple lines in pygame
pygame.display.update()
execute a file with arguments in python shell
subprocess.call(['./abc.py', arg1, arg2])
add single element to array in numpy
numpy.append(a, a[0])
how to generate all permutations of a list in python
print(list(itertools.permutations([1, 2, 3, 4], 2)))
get a unique computer id in python on windows and linux
subprocess.Popen('dmidecode.exe -s system-uuid'.split())
efficiently construct pandas dataframe from large list of tuples/rows
pandas.DataFrame(initialload, columns=list_of_column_names)
how to use jenkins environment variables in python script
qualifier = os.environ['QUALIFIER']
what is the best way to convert a printed list in python back into an actual list
ast.literal_eval(a)
getting today's date in yyyy-mm-dd in python?
datetime.datetime.today().strftime('%Y-%m-%d')
drawing a rectangle or bar between two points in a 3d scatter plot in python and matplotlib
matplotlib.pyplot.show()
best way to extract subset of key-value pairs from python dictionary object
{k: bigdict[k] for k in ('l', 'm', 'n')}
how to split a string into integers in python?
l = [int(x) for x in s.split()]
what's the usage to add a comma after self argument in a class method?
{'top': ['foo', 'bar', 'baz'], 'bottom': ['qux']}
plotting dates on the x-axis with python's matplotlib
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
get all combination of n binary values
lst = map(list, itertools.product([0, 1], repeat=n))
how to check if all elements of a list matches a condition?
[x for x in items if x[2] == 0]
how to check if all values in the columns of a numpy matrix are the same?
a == a[(0), :]
is there a way to know if a list of elements is on a larger list without using 'in' keyword?
print(in_list([1, 2, 3], [1, 2, 4]))
converting timezone-aware datetime to local time in python
datetime.datetime.fromtimestamp(calendar.timegm(d.timetuple()))
equivalent of objects.latest() in app engine
MyObject.all().order('-time')[0]
pandas: selection with multiindex
df[pd.Series(df.index.get_level_values('A')).isin(vals[vals['values']].index)]
read a file from redirected stdin with python
result = sys.stdin.read()
how to change [1,2,3,4] to '1234' using python
"""""".join(map(str, [1, 2, 3, 4]))
add a new filter into sld
fts.Rules[1].create_filter('name_1', '>=', '0')
how to filter files (with known type) from os.walk?
files = [fi for fi in files if not fi.endswith('.dat')]
replace nan values in a pandas data frame with the average of columns
df.apply(lambda x: x.fillna(x.mean()), axis=0)
why does a python bytearray work with value >= 256
bytearray('\xff')
utf-16 codepoint counting in python
len(text.encode('utf-16-le')) // 2
delete character "m" from a string `s` using python
s = s.replace('M', '')
how to insert current_timestamp into postgres via python
cur.execute('INSERT INTO some_table (somecol) VALUES (%s)', (dt,))
python max function using 'key' and lambda expression
max(lis, key=lambda x: int(x))
how to get the number of <p> tags inside div in scrapy?
len(response.xpath('//div[@class="entry-content"]/p'))
confusing with the usage of regex in python
re.search('[a-z]*', '1234')
python finding index of maximum in list
max(enumerate(a), key=lambda x: x[1])[0]
regex match even number of letters
re.compile('(.)\\1')
store return value of a python script in a bash script
sys.exit(1)
convert `a` to string
str(a)
mysql execute query 'select * from foo where bar = %s and baz = %s' with parameters `param1` and `param2`
c.execute('SELECT * FROM foo WHERE bar = %s AND baz = %s', (param1, param2))
how to check is a string is a valid regex - python?
re.compile('[')
how can i plot a mathematical expression of two variables in python?
plt.show()
how to urlencode a querystring in python?
urllib.parse.quote_plus('string_of_characters_like_these:$#@=?%^Q^$')
how to generate all permutations of a list in python
print(list(itertools.product([1, 2], repeat=3)))
in python, how to join a list of tuples into one list?
list(itertools.chain(*a))
how do i check if an insert was successful with mysqldb in python?
conn.commit()
django-rest-swagger: how to group endpoints?
url('^api/', include('api.tasks.urls'), name='my-api-root'),
flattening a list of numpy arrays?
out = np.concatenate(input_list).ravel().tolist()
subtract 1 hour and 10 minutes from time object `t`
(t - datetime.timedelta(hours=1, minutes=10))
reverse all x-axis points in pyplot
plt.gca().invert_xaxis()
reverse list `yourdata`
sorted(yourdata, reverse=True)
how to show pil image in ipython notebook
pil_im.show()
moving x-axis to the top of a plot in matplotlib
ax.xaxis.set_label_position('top')
find out how many times a regex matches in a string in python
len(re.findall(pattern, string_to_search))
python: lambda function in list comprehensions
[(lambda x: x * i) for i in range(4)]
remove dollar sign '$' from second to last column data in dataframe 'df' and convert the data into floats
df[df.columns[1:]].replace('[\\$,]', '', regex=True).astype(float)
how to generate random numbers that are different?
random.sample(range(1, 50), 6)
removing vowel characters 'aeiouaeiou' from string `text`
"""""".join(c for c in text if c not in 'aeiouAEIOU')
how to group dataframe by a period of time?
df.groupby(df.index.map(lambda t: t.minute))
how to convert the following string in python?
print('/'.join(new))
swap each pair of characters in string `s`
"""""".join([s[x:x + 2][::-1] for x in range(0, len(s), 2)])
how to get a max string length in nested lists
len(max(i, key=len))
how to append rows in a pandas dataframe in a for loop?
print('{}\n'.format(df))
print a emoji from a string `\\ud83d\\ude4f` having surrogate pairs
"""\\ud83d\\ude4f""".encode('utf-16', 'surrogatepass').decode('utf-16')