text
stringlengths
4
1.08k
How do I pass arguments to AWS Lambda functions using GET requests?,"{'va1': ""$input.params('val1')"", 'val2': ""$input.params('val2')""}"
hexadecimal string to byte array in python,hex_string = 'deadbeef'
Dictionary within dictionary in Python 3,result = copy.deepcopy(old_dict) if old_dict is not None else {}
Plot specific rows of a pandas dataframe,df.iloc[2:6].plot(y='b')
"Simple, Cross Platform MIDI Library for Python","MyMIDI.addNote(track, channel, pitch, time, duration, volume)"
How to plot cdf in matplotlib in Python?,"plt.plot(X, Y, color=c, marker='o', label='xyz')"
How to clear the Entry widget after a button is pressed in Tkinter?,root.mainloop()
Convert a string to integer with decimal in Python,int(float(s))
kill process with python,os.system('path/to/my_script.sh')
kill process with python,os.system('your_command_here; second_command; third; etc')
finding index of an item closest to the value in a list that's not entirely sorted,"min(list(range(len(a))), key=lambda i: abs(a[i] - 11.5))"
How to send email attachments with Python,msg.attach(MIMEText(text))
How to check if given variable exist in jinja2 template?,"""""""{{ x.foo }}"""""""
Check to ensure a string does not contain multiple values,"""""""test.png"""""".endswith(('jpg', 'png', 'gif'))"
Token pattern for n-gram in TfidfVectorizer in python,"re.findall('(?u)\\b\\w\\w+\\b', 'this is a sentence! this is another one.')"
pandas: slice a MultiIndex by range of secondary index,"s.loc[slice('a', 'b'), slice(2, 10)]"
How to combine callLater and addCallback?,reactor.run()
Is there any API for formatting Sphinx text?,print(doctree.toprettyxml())
Python list comprehension to join list of lists,combined = list(itertools.chain.from_iterable(lists))
How do I print the content of a .txt file in Python?,file_contents = f.read()
Python: How to ignore #comment lines when reading in a file,print(line.rstrip())
How should I take the max of 2 columns in a dataframe and make it another column?,"df[['A', 'B']].max(axis=1)"
How to generate 2D gaussian with Python?,"np.random.multivariate_normal(mean, cov, 10000)"
Data munging in pandas,"df.groupby('ID')['<colname>'].agg(['std', 'mean'])"
How to get http headers in flask?,request.headers.get('your-header-name')
How to make a related field mandatory in Django?,raise ValidationError('At least one address is required.')
How to plot confusion matrix with string axis rather than integer in python,"plt.savefig('confusion_matrix.png', format='png')"
Check if a key exists in a Python list,mylist[1:] == ['comment']
Check if all values of iterable are zero,list(l) == [0] * len(l)
matplotlib diagrams with 2 y-axis,"ax2.set_ylabel('name2', fontsize=14, color='blue')"
"Is it possible to add <key, value> pair at the end of the dictionary in python",dict(mylist)
Python print on same line,print('[DONE]')
Matrix Mirroring in python,"np.concatenate((A[::-1, :], A), axis=0)"
Python: Get the first character of a the first string in a list?,mylist[0][:1]
finding elements by attribute with lxml,"print(root.xpath(""//article[@type='news']/content/text()""))"
How do I change the range of the x-axis with datetimes in MatPlotLib?,fig.autofmt_xdate()
how to create a range of random decimal numbers between 0 and 1,"[random.random() for _ in range(0, 10)]"
"Is it possible to take an ordered ""slice"" of a dictionary in Python based on a list of keys?","map(my_dictionary.get, my_list)"
How do I use the 'json' module to read in one JSON object at a time?,list(json_parse(open('data')))
"Matplotlib plots: removing axis, legends and white spaces","plt.savefig('test.png', bbox_inches='tight')"
Numpy object arrays,"print(numpy.array([X()], dtype=object))"
How to plot a wav file,plt.show()
How to find all terms in an expression in Sympy,"sympify('1/(x+1)+4*x/(x-1)+3-4*x**2+10*x**2', evaluate=False).args"
How to smooth matplotlib contour plot?,plt.show()
How can I vectorize the averaging of 2x2 sub-arrays of numpy array?,"y.mean(axis=(1, 3))"
replace all characters in a string with asterisks,word = ['*'] * len(word)
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']
How can I generate more colors on pie chart matplotlib,plt.show()
Python List Comprehensions Splitting loop variable,"[(x[1], x[2]) for x in (x.split(';') for x in a.split('\n')) if x[1] != 5]"
Show Explorer's properties dialog for a file in Windows,time.sleep(5)
Divide two lists in python,"map(truediv, a, b)"
How to convert pointer to c array to python array,a = np.frombuffer(Data)
get http response codes with python,urllib.request.urlopen('http://google.com').getcode()
Python/Matplotlib - Is there a way to make a discontinuous axis?,ax.set_xscale('custom')
How to copy a dict and modify it in one line of code,"setup2 = dict(list(setup1.items()) + list({'param1': val10, 'param2': val20}.items()))"
How to select cells greater than a value in a multi-index Pandas dataframe?,df[(df <= 2).all(axis=1)]
selecting from multi-index pandas,"df.xs(1, level='A', drop_level=False)"
performance loss after vectorization in numpy,"np.allclose(ans1, ans2)"
Python write (iPhone) Emoji to a file,f.write(e8)
Finding index of the same elements in a list,[i for i in range(len(word)) if word[i] == letter]
How to remove square brackets from list in Python?,"print(', '.join(LIST))"
Python/Matplotlib - Is there a way to make a discontinuous axis?,ax.spines['right'].set_visible(False)
How to parse malformed HTML in python,print(soup.prettify())
Formatting numbers consistently in Python,print('%.1e' % x)
How to Filter from CSV file using Python Script,"csv.writer(open('abx.csv', 'w'), delimiter=' ').writerows(filtered)"
Python 2.7: test if characters in a string are all Chinese characters,all('\u4e00' <= c <= '\u9fff' for c in name.decode('utf-8'))
Can python dictionary comprehension be used to create a dictionary of substrings and their locations?,"d = collections.defaultdict(lambda : [0, []])"
How to update an object or bail if it has been deleted in Django,thing.save()
Python -Intersection of multiple lists?,"from functools import reduce
reduce(set.intersection, [[1, 2, 3, 4], [2, 3, 4], [3, 4, 5, 6, 7]])"
method overloading in python,"func2(1, 2, 3, 4, 5)"
Stacked bar chart with differently ordered colors using matplotlib,plt.show()
Removing white space from txt with python,"subbed = re.sub('\\s{2,}', '|', line.strip())"
How to get an arbitrary element from a frozenset?,"[random.sample(s, 1)[0] for _ in range(10)]"
How do you serialize a model instance in Django?,"serialized_obj = serializers.serialize('json', [obj])"
Send Data from a textbox into Flask?,app.run()
Pandas DataFrame: remove unwanted parts from strings in a column,data['result'] = data['result'].map(lambda x: x.lstrip('+-').rstrip('aAbBcC'))
Rotating a two-dimensional array in Python,"[[7, 8, 9], [4, 5, 6], [1, 2, 3]]"
"Finding minimum, maximum and average values for nested lists?","max(PlayerList, key=lambda p: max(p[1:]))[0]"
How to import .py file from another directory?,"sys.path.insert(0, 'path/to/your/py_file')"
How can I compare two lists in python and return matches,set(a) & set(b)
Is there a way to specify the build directory for py2exe,"setup(console=['myscript.py'], options=options)"
Can I run a Python script as a service?,sys.exit(0)
Imoverlay in python,plt.show()
Python string to unicode,print(repr(a.decode('unicode-escape')))
How to append in a json file in Python?,"{'new_key': 'new_value', '67790': {'1': {'kwh': 319.4}}}"
What alterations do I need to make for my Flask python application to use a MySQL database?,db.session.commit()
Logging in and using cookies in pycurl,"C.setopt(pycurl.COOKIEFILE, 'cookie.txt')"
Numpy: find the euclidean distance between two 3-D arrays,"np.linalg.norm(A - B, axis=-1)"
how to get the value of multiple maximas in an array in python,"[0, 16, 17, 18]"
Filtering a Pandas DataFrame Without Removing Rows,"df.where((df > df.shift(1)).values & (df.D == 1)[:, (None)], np.nan)"
Regex - substitute specific chars exept specific string,"""""""\\1"""""""
"Shuffle an array with python, randomize array item order with python",random.shuffle(array)
"Saving dictionary whose keys are tuples with json, python","json.dumps({str(k): v for k, v in list(data.items())})"
How can I convert JSON to CSV?,"f.writerow(['pk', 'model', 'codename', 'name', 'content_type'])"
How to unpack a dictionary of list (of dictionaries!) and return as grouped tuples?,"[('A', 1, 2), ('B', 3, 4)]"
How to sort a Python dict by value,"sorted(d, key=d.get, reverse=True)"
Is there a way to set all values of a dictionary to zero?,"c = [(i, 0) for i in a]"
How do I sort a key:list dictionary by values in list?,"{'name': [p['name'] for p in persons], 'age': [p['age'] for p in persons]}"
How do I sort a key:list dictionary by values in list?,"persons = sorted(persons, key=lambda person: person['name'])"