text
stringlengths
4
1.08k
How to sort a list of strings with a different order?,lst.sort()
Best way to format integer as string with leading zeros?,print('{0:05d}'.format(i))
Changing the application and taskbar icon - Python/Tkinter,root.iconbitmap(default='ardulan.ico')
Email datetime parsing with python,"print(dt.strftime('%a, %b %d, %Y at %I:%M %p'))"
Joining pairs of elements of a list - Python,"[(x[i] + x[i + 1]) for i in range(0, len(x), 2)]"
Shading an area between two points in a matplotlib plot,plt.show()
Python Tkinter - resize widgets evenly in a window,"self.grid_rowconfigure(1, weight=1)"
how to use concatenate a fixed string and a variable in Python,msg['Subject'] = 'Auto Hella Restart Report ' + sys.argv[1]
changing file extension in Python,os.path.splitext('name.fasta')[0]
Matplotlib subplot y-axis scale overlaps with plot above,plt.show()
redirect prints to log file,logging.info('hello')
Use pyqt4 to create GUI that runs python script,sys.exit(app.exec_())
Decode complex JSON in Python,json.loads(s)
How to generate all permutations of a list in Python,"print(list(itertools.product([1, 2], repeat=3)))"
Using Selenium in the background,driver.quit()
Convert a list to a dictionary in Python,"{'bi': 2, 'double': 2, 'duo': 2, 'two': 2}"
creating a color coded time chart using colorbar and colormaps in python,plt.show()
Python logging across multiple modules,logging.info('Doing something')
Sorting a dictionary by value then key,"[v[0] for v in sorted(iter(d.items()), key=lambda k_v: (-k_v[1], k_v[0]))]"
How can I create a list from two dictionaries?,"fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in fus_d.keys() | fus_s]"
Numpy `logical_or` for more than two arguments,"functools.reduce(np.logical_or, (x, y, z))"
How to serialize to JSON a list of model objects in django/python,"return HttpResponse(json.dumps(results), content_type='application/json')"
Convert a string key to int in a Dictionary,"d = {int(k): [int(i) for i in v] for k, v in list(d.items())}"
How to convert upper case letters to lower case,"w.strip(',.').lower()"
Strip random characters from url,"re.sub('Term|Term1|Term2', '', file_name)"
How do I modify a text file in Python?,f.write('new line\n')
Regex Python adding characters after a certain word,"re.sub('(get)', '\\1@', text)"
How to get cookies from web-browser with Python?,"r = requests.get('http://stackoverflow.com', cookies=cj)"
How can I insert data into a MySQL database?,cursor.execute(sql)
Basic authentication using urllib2 with python with JIRA REST api,"r = requests.get('https://api.github.com', auth=('user', 'pass'))"
Joining rows based on value conditions,"df.groupby(['year', 'bread'])['amount'].sum().reset_index()"
Getting only element from a single-element list in Python?,singleitem = next(iter(mylist))
How do I capture SIGINT in Python?,sys.exit()
How to delete everything after a certain character in a string?,s = s[:s.index('.zip') + 4]
List of integers into string (byte array) - python,"str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))"
Parse values in text file,"df = pd.read_csv('file_path', sep='\t', error_bad_lines=False)"
How to use Flask-Script and Gunicorn,"manager.add_command('gunicorn', GunicornServer())"
Comparing 2 lists consisting of dictionaries with unique keys in python,"[[(k, x[k], y[k]) for k in x if x[k] != y[k]] for x, y in pairs if x != y]"
Python - NumPy - tuples as elements of an array,"linalg.svd(a[:, :, (1)])"
Sorting numpy array on multiple columns in Python,df.sort(['date'])
Deciding and implementing a trending algorithm in Django,Book.objects.annotate(reader_count=Count('readers')).order_by('-reader_count')
How can I convert a python urandom to a string?,a.decode('latin1')
Python: Converting from Tuple to String?,"s += '(' + ', '.join(map(str, tup)) + ')'"
Get the immediate minimum among a list of numbers in python,max([x for x in num_list if x < 3])
how to call a function from another file?,print(function())
Django model field default based on another model field,"super(ModelB, self).save(*args, **kwargs)"
How to read integers from a file that are 24bit and little endian using Python?,"struct.unpack('<i', bytes + ('\x00' if bytes[2] < '\x80' else '\xff'))"
How can I split a string and form a multi-level nested dictionary?,"from functools import reduce
reduce(lambda res, cur: {cur: res}, reversed('foo/bar/baz'.split('/')), 1)"
Flask server cannot read file uploaded by POST request,data = request.files['file'].read()
How to add multiple values to a key in a Python dictionary,print(dict(new_dict))
How to loop backwards in python?,"[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]"
Django: Detecting changes of a set of fields when a model is saved,"super(MyModel, self).save(*args, **kwargs)"
Python: Extract numbers from a string,[int(s) for s in str.split() if s.isdigit()]
Create an array where each element stores its indices,"np.moveaxis(np.indices((4, 5)), 0, -1)"
How to store a naive datetime in Django 1.4,pytz.timezone('Europe/Helsinki').localize(naive)
How to get unique list using a key word :Python,list({e.id: e for e in somelist}.values())
How do you perform basic joins of two RDD tables in Spark using Python?,"rdd2 = sc.parallelize([('foo', 4), ('bar', 5), ('bar', 6)])"
String formatting for hex colors in Python,print('{0:06x}'.format(123))
python: flatten to a list of lists but no more,"[[1, 2, 3], ['a', 'b', 'c']]"
Matplotlib show multiple images with for loop,plt.show()
Terminate a multi-thread python program,time.sleep(0.1)
5 maximum values in a python dictionary,"max(A, key=A.get)"
Python: Setting an element of a Numpy matrix,"a[i, j] = x"
Print raw HTTP request in Flask or WSGI,app.run()
"python, regex split and special character",l = re.compile('(\\s)').split(s)
"python, regex split and special character",l = re.compile('\\s').split(s)
Convert snmp octet string to human readable date format,"datetime.datetime(*struct.unpack('>HBBBBBB', s))"
Scikit Learn HMM training with set of observation sequences,model.fit([X])
Plotting a 3d surface from a list of tuples in matplotlib,plt.show()
Map two lists into one single list of dictionaries,"[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]"
How do I plot multiple X or Y axes in matplotlib?,plt.title('Experimental Data')
Pandas: select the first couple of rows in each group,"df.groupby('id', as_index=False).head(2)"
Inserting an element before each element of a list,[item for sublist in l for item in sublist]
understanding list comprehension for flattening list of lists in python,[item for sublist in list_of_lists for item in sublist if valid(item)]
How to override template in django-allauth?,"TEMPLATE_DIRS = os.path.join(BASE_DIR, 'cms', 'templates', 'allauth'),"
Control Charts in Python,plt.show()
Change a string of integers separated by spaces to a list of int,"map(int, x.split(' '))"
Square root scale using matplotlib/python,plt.show()
Store different datatypes in one NumPy array?,"array([('a', 0), ('b', 1)], dtype=[('keys', '|S1'), ('data', '<i8')])"
autofmt_xdate deletes x-axis labels of all subplots,"plt.setp(plt.xticks()[1], rotation=30, ha='right')"
Spaces inside a list,"""""""{: 3d}"""""".format(x)"
Can I use a class attribute as a default value for an instance method?,my_instance = MyClass(name='new name')
How to fix unicode issue when using a web service with Python Suds,thestring = thestring.decode('utf8')
How to filter by sub-level index in Pandas,df.index
Turning a string into list of positive and negative numbers,"tuple(map(int, inputstring.split(',')))"
"matplotlib: two y-axis scales, how to align gridlines?",plt.show()
Creating HTML in python,f.write(doc.render())
Python Seaborn Matplotlib setting line style as legend,plt.show()
Programmatically sync the db in Django,"management.call_command('syncdb', interactive=False)"
Authenticate with private key using Paramiko Transport (channel),session.exec_command('cd /home/harperville/my_scripts/')
Creating a python dictionary from a line of text,"fields = tuple(field.strip() for field in line.split(','))"
Extracting date from a string in Python,"date = datetime.strptime(match.group(), '%Y-%m-%d').date()"
change first line of a file in python,"shutil.copyfileobj(from_file, to_file)"
Sort N-D numpy array by column with a smaller N-D array,"a[(np.arange(a.shape[0])[:, (None)]), :, (b2)].transpose(0, 2, 1)"
How to iterate over a range of keys in a dictionary?,"[x for x in d if x not in ('Domain Source', 'Recommend Suppress')]"
What would be the most pythonic way to make an attribute that can be used in a lambda?,"lambda : setattr(self, 'spam', 'Ouch')"
python - crontab to run a script,main()
Python dictionary replace values,my_dict.get('corse') and my_dict.update({'corse': 'my definition'})
converting a list of integers into range in python,"print(list(ranges([0, 1, 2, 3, 4, 7, 8, 9, 11])))"