text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fill_in_table(self, table, worksheet, flags):
'''
Fills in any rows with missing right hand side data with empty cells.
'''
max_row = 0
min_row = sys.maxint
for row in table:
if len(row) > max_row:
max_row = len(row)
if len(row)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _find_valid_block(self, table, worksheet, flags, units, used_cells, start_pos, end_pos):
'''
Searches for the next location where a valid block could reside and constructs the block
object representing that location.
'''
for row_index in range(len(table)):
if row_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _find_block_bounds(self, table, used_cells, possible_block_start, start_pos, end_pos):
'''
First walk the rows, checking for the farthest left column belonging to the block and the
bottom most row belonging to the block. If a blank cell is hit and the column started with a
blank cell... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _single_length_title(self, table, row_index, current_col):
'''
Returns true if the row is a single length title element with no other row titles. Useful
for tracking pre-data titles that belong in their own block.
'''
if len(table[row_index]) - current_col <= 0:
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _find_block_start(self, table, used_cells, possible_block_start, start_pos, end_pos):
'''
Finds the start of a block from a suggested start location. This location can be at a lower
column but not a lower row. The function traverses columns until it finds a stopping
condition or a re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_dict(self, join='.'):
""" Returns the error as a path to message dictionary. Paths are joined with the ``join`` string. """ |
if self.path:
path = [str(node) for node in self.path]
else:
path = ''
return { join.join(path): self.message } |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_dict(self, join='.'):
""" Returns all the errors in this collection as a path to message dictionary. Paths are joined with the ``join`` string. """ |
result = {}
for e in self.errors:
result.update(e.as_dict(join))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_gffutils_db(f):
""" Load database for gffutils. Parameters f : str Path to database. Returns ------- db : gffutils.FeatureDB gffutils feature database. ... |
import gffutils
db = gffutils.FeatureDB(f, keep_order=True)
return db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_gffutils_db(gtf, db):
""" Make database for gffutils. Parameters gtf : str Path to Gencode gtf file. db : str Path to save database to. Returns ------- ... |
import gffutils
out_db = gffutils.create_db(gtf,
db,
keep_order=True,
infer_gene_extent=False)
return out_db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_bed_by_name(bt):
""" Merge intervals in a bed file when the intervals have the same name. Intervals with the same name must be adjacent in the bed file... |
name_lines = dict()
for r in bt:
name = r.name
name_lines[name] = name_lines.get(name, []) + [[r.chrom, r.start,
r.end, r.name,
r.strand]]
new_lines = []
for name in name_l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_feature_bed(gtf, feature, out=None):
""" Make a bed file with the start and stop coordinates for all of a particular feature in Gencode. Valid features ... |
bed_lines = []
with open(gtf) as f:
line = f.readline().strip()
while line != '':
if line[0] != '#':
line = line.split('\t')
if line[2] == feature:
chrom = line[0]
start = str(int(line[3]) - 1)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_transcript_gene_se(fn):
""" Make a Pandas Series with transcript ID's as the index and values as the gene ID containing that transcript. Parameters fn :... |
import itertools as it
import HTSeq
gtf = it.islice(HTSeq.GFF_Reader(fn), None)
transcripts = []
genes = []
line = gtf.next()
while line != '':
if line.type == 'transcript':
transcripts.append(line.attr['transcript_id'])
genes.append(line.attr['gene_id'])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_gene_info_df(fn):
""" Make a Pandas dataframe with gene information Parameters fn : str of filename Filename of the Gencode gtf file Returns ------- df ... |
import itertools as it
import HTSeq
gff_iter = it.islice(HTSeq.GFF_Reader(fn), None)
convD = dict()
eof = False
while not eof:
try:
entry = gff_iter.next()
if entry.type == 'gene':
convD[entry.attr['gene_id']] = [entry.attr['gene_name'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_splice_junction_df(fn, type='gene'):
"""Read the Gencode gtf file and make a pandas dataframe describing the splice junctions Parameters filename : str ... |
import itertools as it
import HTSeq
import numpy as np
# GFF_Reader has an option for end_included. However, I think it is
# backwards. So if your gtf is end-inclusive, you want the default
# (end_included=False). With this, one will NOT be subtracted from the end
# coordinate.
gffI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login_required(function=None, required=False, redirect_field_name=REDIRECT_FIELD_NAME):
""" Decorator for views that, if required, checks that the user is lo... |
if required:
if django.VERSION < (1, 11):
actual_decorator = user_passes_test(
lambda u: u.is_authenticated(),
redirect_field_name=redirect_field_name
)
else:
actual_decorator = user_passes_test(
lambda u: u.is_auth... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_table_existed(self, tablename):
""" Check whether the given table name exists in this database. Return boolean. """ |
all_tablenames = self.list_tables()
tablename = tablename.lower()
if tablename in all_tablenames:
return True
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_table(self, tablename, silent=False):
""" Drop a table :Parameters: - tablename: string - slient: boolean. If false and the table doesn't exists an exce... |
if not silent and not self.is_table_existed(tablename):
raise MonSQLException('TABLE %s DOES NOT EXIST' %tablename)
self.__cursor.execute('DROP TABLE IF EXISTS %s' %(tablename))
self.__db.commit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calendar(ctx, date, agenda, year):
"""Show a 3-month calendar of meetups. \b date: The date around which the calendar is centered. May be: - YYYY-MM-DD, YY-M... |
do_full_year = year
today = ctx.obj['now'].date()
db = ctx.obj['db']
term = ctx.obj['term']
date_info = cliutil.parse_date(date)
if 'relative' in date_info:
year = today.year
month = today.month + date_info['relative']
elif 'date_based' in date_info:
year = date_inf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register(self, obj):
'''
register all methods for of an object as json rpc methods
obj - object with methods
'''
for method in dir(obj):
#ignore private methods
if not method.startswith('_'):
fct = getattr(obj, method)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _validate_format(req):
'''
Validate jsonrpc compliance of a jsonrpc-dict.
req - the request as a jsonrpc-dict
raises SLOJSONRPCError on validation error
'''
#check for all required keys
for key in SLOJSONRPC._min_keys:
if not key in req:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _validate_params(self, req):
'''
Validate parameters of a jsonrpc-request.
req - request as a jsonrpc-dict
raises SLOJSONRPCError on validation error
'''
#does the method exist?
method = req['method']
if not method in self._methods:
rais... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def handle_request(self, req, validate=True):
'''
handle a jsonrpc request
req - request as jsonrpc-dict
validate - validate the request? (default: True)
returns jsonrpc-dict with result or error
'''
#result that will be filled and returned
res = {'json... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def handle_string(self, strreq):
'''
Handle a string representing a jsonrpc-request
strreq - jsonrpc-request as a string
returns jsonrpc-response as a string
'''
#convert to jsonrpc-dict
req = None
try:
req = json.loads(strreq)
excep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def report_calls(request):
'''
POST endpoint for APIs to report their statistics
requires parameters: api, key, calls, date, endpoint & signature
if 'api' or 'key' parameter is invalid returns a 404
if signature is bad returns a 400
returns a 200 with content 'OK' if call s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_key(request):
'''
POST endpoint determining whether or not a key exists and is valid
'''
api_objs = list(Api.objects.filter(name=request.POST['api']))
if not api_objs:
return HttpResponseBadRequest('Must specify valid API')
# check the signature
if get_signature(reques... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register(request,
email_template='locksmith/registration_email.txt',
registration_template=getattr(settings, 'LOCKSMITH_REGISTER_TEMPLATE', 'locksmith/register.html'),
registered_template=getattr(settings, 'LOCKSMITH_REGISTERED_TEMPLATE', 'locksmith/registered.html'),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def confirm_registration(request, key, template="locksmith/confirmed.html"):
'''
API key confirmation
visiting this URL marks a Key as ready for use
'''
context = {'LOCKSMITH_BASE_TEMPLATE': settings.LOCKSMITH_BASE_TEMPLATE}
try:
context['key'] = key_obj = Key.objects.get(key=ke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def profile(request):
'''
Viewing of signup details and editing of password
'''
context = {}
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
form.save()
messages.info(request, 'Password Changed.')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _dictlist_to_lists(dl, *keys):
''' convert a list of dictionaries to a dictionary of lists
>>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444},
{'a': 'wow', 'b': 300}]
>>> _dictlist_to_lists(dl)
(['test', 'zaz', 'wow'], [3, 444, 300])
'''
lists = []
for k in keys:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _cumulative_by_date(model, datefield):
'''
Given a model and date field, generate monthly cumulative totals.
'''
monthly_counts = defaultdict(int)
for obj in model.objects.all().order_by(datefield):
datevalue = getattr(obj, datefield)
monthkey = (datevalue.year, datevalue.mon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def factory(codes, base=_Exception):
""" Creates a custom exception class with arbitrary error codes and arguments. """ |
if not issubclass(base, _Exception):
raise FactoryException("Invalid class passed as parent: Must be a subclass of an Exception class created with this function",
FactoryException.INVALID_EXCEPTION_CLASS, intended_parent=base)
class Error(base):
pass
if isi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Save the current instance to the DB """ |
with rconnect() as conn:
try:
self.validate()
except ValidationError as e:
log.warn(e.messages)
raise
except ModelValidationError as e:
log.warn(e.messages)
raise
except ModelConversi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Delete the current instance from the DB. """ |
with rconnect() as conn:
# Can't delete an object without an ID.
if self.id is None:
raise FrinkError("You can't delete an object with no ID")
else:
if isinstance(self.id, uuid.UUID):
self.id = str(self.id)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, id):
""" Get a single instance by pk id. :param id: The UUID of the instance you want to retrieve. """ |
with rconnect() as conn:
if id is None:
raise ValueError
if isinstance(id, uuid.UUID):
id = str(id)
if type(id) != str and type(id) != unicode:
raise ValueError
try:
query = self._base().get(id)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(self, order_by=None, limit=0, **kwargs):
""" Fetch a list of instances. :param order_by: column on which to order the results. \ To change the sort, p... |
with rconnect() as conn:
if len(kwargs) == 0:
raise ValueError
try:
query = self._base()
query = query.filter(kwargs)
if order_by is not None:
query = self._order_by(query, order_by)
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, order_by=None, limit=0):
""" Fetch all items. :param limit: How many rows to fetch. :param order_by: column on which to order the results. \ To cha... |
with rconnect() as conn:
try:
query = self._base()
if order_by is not None:
query = self._order_by(query, order_by)
if limit > 0:
query = self._limit(query, limit)
log.debug(query)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def opterate(func):
'''A decorator for a main function entry point to a script. It
automatically generates the options for the main entry point based on the
arguments, keyword arguments, and docstring.
All keyword arguments in the function definition are options. Positional
arguments are mandatory ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_setup(self):
""" Provide a helper script for the user to setup completion. """ |
shell = os.getenv('SHELL')
if not shell:
raise SystemError("No $SHELL env var found")
shell = os.path.basename(shell)
if shell not in self.script_body:
raise SystemError("Unsupported shell: %s" % shell)
tplvars = {
"prog": '-'.join(self.prog.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trim(self, text):
""" Trim whitespace indentation from text. """ |
lines = text.splitlines()
firstline = lines[0] or lines[1]
indent = len(firstline) - len(firstline.lstrip())
return '\n'.join(x[indent:] for x in lines if x.strip()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_client(self):
"""Synchronous OAuth 2.0 Bearer client""" |
if not self._sync_client:
self._sync_client = AlfSyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secret=self.config.get('OAUTH_CLIENT_SECRET')
)
return self._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def async_client(self):
"""Asynchronous OAuth 2.0 Bearer client""" |
if not self._async_client:
self._async_client = AlfAsyncClient(
token_endpoint=self.config.get('OAUTH_TOKEN_ENDPOINT'),
client_id=self.config.get('OAUTH_CLIENT_ID'),
client_secret=self.config.get('OAUTH_CLIENT_SECRET')
)
return sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_package_version():
"""returns package version without importing it""" |
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, "firepit/__init__.py")) as pkg:
for line in pkg:
m = version.match(line.strip())
if not m:
continue
return ".".join(m.groups()[0].split(", ")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recognise(self, string, line_num):
""" Splits the string into chars and distributes these into the buckets of IPA and non-IPA symbols. Expects that the... |
symbols = []
unknown = []
for char in string:
if char == SPACE:
continue
try:
name = unicodedata.name(char)
except ValueError:
name = 'UNNAMED CHARACTER {}'.format(ord(char))
if char in self.ipa:
symbol = Symbol(char, name, self.ipa[char])
symbols.append(symbol)
self.ipa_sy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def report(self, reporter):
""" Adds the problems that have been found so far to the given Reporter instance. """ |
for symbol in sorted(self.unk_symbols.keys()):
err = '{} ({}) is not part of IPA'.format(symbol.char, symbol.name)
if symbol.char in self.common_err:
repl = self.common_err[symbol.char]
err += ', suggested replacement is {}'.format(repl)
if len(repl) == 1:
err += ' ({})'.format(unicodedata.na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parsing(self):
"""Parameters for parsing directory trees""" |
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Directory Paths utility', size=(30, 1), font=("Helvetica", 25), text_color='blue')],
# Source
[gui.Text('Source Folder', size=(15, 1), auto... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def source(self):
"""Parameters for saving zip backups""" |
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Zip Backup utility', size=(30, 1), font=("Helvetica", 30), text_color='blue')],
[gui.Text('Create a zip backup of a file or directory.', size=(50, 1), font... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def contains(self, desired):
'''Return the filter closure fully constructed.'''
field = self.__field
def aFilter(testDictionary):
return (desired in testDictionary[field])
return aFilter |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_valid_file(path):
''' Returns True if provided file exists and is a file, or False otherwise. '''
return os.path.exists(path) and os.path.isfile(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_valid_dir(path):
''' Returns True if provided directory exists and is a directory, or False otherwise. '''
return os.path.exists(path) and os.path.isdir(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_readable(path):
'''
Returns True if provided file or directory exists and can be read with the current user.
Returns False otherwise.
'''
return os.access(os.path.abspath(path), os.R_OK) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(command, get_output=False, cwd=None):
"""By default, run all commands at GITPATH directory. If command fails, stop program execution. """ |
if cwd is None:
cwd = GITPATH
cprint('===')
cprint('=== Command: ', command)
cprint('=== CWD: ', cwd)
cprint('===')
if get_output:
proc = capture_stdout(command, cwd=cwd)
out = proc.stdout.read().decode()
print(out, end='')
check_exit_code(proc.re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_argument_parser(executable):
"""creates an argument parser from the given `executable` model. An argument '__xml__' for "--xml" is added independently.... |
a = ArgumentParser()
a.add_argument("--xml", action="store_true", dest="__xml__", help="show cli xml")
for p in executable:
o = []
if p.flag: o.append("-%s" % p.flag)
if p.longflag: o.append("--%s" % p.longflag)
a.add_argument(
*o,
metavar=p.type.up... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(self, d):
""" Set this person from dict :param d: Dictionary representing a person ('sitting'[, 'id']) :type d: dict :rtype: Person :raises KeyErro... |
self.sitting = d['sitting']
self.id = d.get('id', None)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_tuple(self, t):
""" Set this person from tuple :param t: Tuple representing a person (sitting[, id]) :type t: (bool) | (bool, None | str | unicode | int... |
if len(t) > 1:
self.id = t[0]
self.sitting = t[1]
else:
self.sitting = t[0]
self.id = None
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def meta_bar_chart(series=None, N=20):
"Each column in the series is a dict of dicts"
if not series or isinstance(series, basestring):
series = json.load(load_app_meta)
if isinstance(series, Mapping) and isinstance(series.values()[0], Mapping):
rows_received = series['# Received'].items()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1):
'''Create dict from values_list with first N values as a compound key.
Default N (number of columns assumbed to be "unique_together") is 2.
>>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def index_model_field_batches(model_or_queryset, key_fields=['model_number', 'serial_number'], value_fields=['pk'],
key_formatter=lambda x: str.lstrip(str.strip(str(x or '')), '0'),
value_formatter=lambda x: str.strip(str(x)), batch_len=10000,
limit=100000000, verbosity=1):
'''Like index_model_field e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_index(model_meta, weights=None, verbosity=0):
"""Return a tuple of index metadata for the model metadata dict provided return value format is: ( field_n... |
weights = weights or find_index.default_weights
N = model_meta['Meta'].get('count', 0)
for field_name, field_meta in model_meta.iteritems():
if field_name == 'Meta':
continue
pkfield = field_meta.get('primary_key')
if pkfield:
if verbosity > 1:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_unique(table, field=-1):
"""Use the Django ORM or collections.Counter to count unique values of a field in a table `table` is one of: 1. An iterable of... |
from collections import Counter
# try/except only happens once, and fastest route (straight to db) tried first
try:
ans = {}
for row in table.distinct().values(field).annotate(field_value_count=models.Count(field)):
ans[row[field]] = row['field_value_count']
return ans
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startGraph(self):
"""Starts RDF graph and bing namespaces""" |
g = r.Graph()
g.namespace_manager.bind("rdf", r.namespace.RDF)
g.namespace_manager.bind("foaf", r.namespace.FOAF)
g.namespace_manager.bind("xsd", r.namespace.XSD)
g.namespace_manager.bind("opa", "http://purl.org/socialparticipation/opa/")
g.namespace_mana... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triplifyPortalInfo(self):
"""Make triples with information about the portal. """ |
uri=self.P.opa.ParticipationPortal+self.separator+"participabr"
self.X.G(uri,self.P.rdf.type,self.P.opa.ParticipationPortal)
self.X.G(uri,self.P.opa.description,self.X.L(DATA.portal_description,self.P.xsd.string))
self.X.G(uri,self.P.opa.url,self.X.L("http://participa.br/",self.P.xsd.st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triplifyOverallStructures(self):
"""Insert into RDF graph the textual and network structures. Ideally, one should be able to make bag of words related to eac... |
if self.compute_networks:
self.computeNetworks()
if self.compute_bows:
self.computeBows() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def db_create():
"""Create the database""" |
try:
migrate_api.version_control(url=db_url, repository=db_repo)
db_upgrade()
except DatabaseAlreadyControlledError:
print 'ERROR: Database is already version controlled.' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def db_downgrade(version):
"""Downgrade the database""" |
v1 = get_db_version()
migrate_api.downgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'No changes made.'
else:
print 'Downgraded: %s ... %s' % (v1, v2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def db_upgrade(version=None):
"""Upgrade the database""" |
v1 = get_db_version()
migrate_api.upgrade(url=db_url, repository=db_repo, version=version)
v2 = get_db_version()
if v1 == v2:
print 'Database already up-to-date.'
else:
print 'Upgraded: %s ... %s' % (v1, v2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_npm_modules():
"""Uses npm to dependencies in node.json""" |
# This is a little weird, but we do it this way because if you
# have package.json, then heroku thinks this might be a node.js
# app.
call_command('cp node.json package.json', verbose=True)
call_command('npm install', verbose=True)
call_command('rm package.json', verbose=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def defer( self, func: typing.Callable[[], typing.Any], until: typing.Union[int, float]=-1, ) -> typing.Any: """Defer the execution of a function until some clock... |
raise NotImplementedError() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delay( self, identifier: typing.Any, until: typing.Union[int, float]=-1, ) -> bool: """Delay a deferred function until the given time. Args: identifier (typin... |
raise NotImplementedError() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_email(self, to):
""" Do work. """ |
body = self.body()
subject = self.subject()
import letter
class Message(letter.Letter):
Postie = letter.DjangoPostman()
From = getattr(settings, 'DEFAULT_FROM_EMAIL', 'contact@example.com')
To = to
Subject = subject
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def form_valid(self, form):
""" Praise be, someone has spammed us. """ |
form.send_email(to=self.to_addr)
return super(EmailView, self).form_valid(form) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_model(self, model_cls):
"""Decorator for registering model.""" |
if not getattr(model_cls, '_database_'):
raise ModelAttributeError('_database_ missing '
'on %s!' % model_cls.__name__)
if not getattr(model_cls, '_collection_'):
raise ModelAttributeError('_collection_ missing '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable_counter(self, base=None, database='counter', collection='counters'):
"""Register the builtin counter model, return the registered Counter class and th... |
Counter._database_ = database
Counter._collection_ = collection
bases = (base, Counter) if base else (Counter,)
counter = self.register_model(type('Counter', bases, {}))
class CounterMixin(object):
"""Mixin class for model"""
@classmethod
def... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_id(cls, oid):
"""Find a model object by its ``ObjectId``, ``oid`` can be string or ObjectId""" |
if oid:
d = cls.collection.find_one(ObjectId(oid))
if d:
return cls(**d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(cls, d):
"""Build model object from a dict. Will be removed in v1.0""" |
warnings.warn(
'from_dict is deprecated and will be removed in v1.0!',
stacklevel=2)
d = d or {}
return cls(**d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(cls, *args, **kwargs):
"""Same as ``collection.find``, returns model object instead of dict.""" |
return cls.from_cursor(cls.collection.find(*args, **kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_one(cls, *args, **kwargs):
"""Same as ``collection.find_one``, returns model object instead of dict.""" |
d = cls.collection.find_one(*args, **kwargs)
if d:
return cls(**d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload(self, d=None):
"""Reload model from given dict or database.""" |
if d:
self.clear()
self.update(d)
elif self.id:
new_dict = self.by_id(self._id)
self.clear()
self.update(new_dict)
else:
# should I raise an exception here?
# Like "Model must be saved first."
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
"""Save model object to database.""" |
d = dict(self)
old_dict = d.copy()
_id = self.collection.save(d)
self._id = _id
self.on_save(old_dict)
return self._id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Remove from database.""" |
if not self.id:
return
self.collection.remove({'_id': self._id})
self.on_delete(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_to(cls, name, num):
"""Set counter of ``name`` to ``num``.""" |
if num < 0:
raise CounterValueError('Counter[%s] can not be set to %s' % (
name, num))
else:
counter = cls.collection.find_and_modify(
{'name': name},
{'$set': {'seq': num}},
new=True,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(cls, name):
"""Return the count of ``name``""" |
counter = cls.collection.find_one({'name': name}) or {}
return counter.get('seq', 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def geo_filter(d):
"""Inspects the given Wikipedia article dict for geo-coordinates. If no coordinates are found, returns None. Otherwise, returns a new dict wit... |
page = d["page"]
if not "revision" in page:
return None
title = page["title"]
if skip_article(title):
LOG.info("Skipping low-value article %s", title)
return None
text = page["revision"]["text"]
if not utils.is_str_type(text):
if "#text" in text:
text... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def depipe(s):
"""Convert a string of the form DD or DD|MM or DD|MM|SS to decimal degrees""" |
n = 0
for i in reversed(s.split('|')):
n = n / 60.0 + float(i)
return n |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def skip_coords(c):
"""Skip coordinate strings that are not valid""" |
if c == "{{coord|LAT|LONG|display=inline,title}}": # Unpopulated coord template
return True
if c.find("globe:") >= 0 and c.find("globe:earth") == -1: # Moon, venus, etc.
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iter_output(self, pause=0.05):
""" Returns iterator of chunked output. :param cmd: command that would be passed to ``subprocess.Popen`` :param shell: Tells i... |
with self.stream as temp:
for chunk in self.iter_output_for_stream(temp, pause=pause):
yield chunk |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def terminate(self):
""" Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some messages of progresses that ha... |
self.queue.put(dill.dumps(ExitCommand()))
if self.process:
self.process.join() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_mail(self):
"""Generate the email as MIMEText """ |
# Script info
msg = "Script info : \r\n"
msg = msg + "%-9s: %s" % ('Script', SOURCEDIR) + "\r\n"
msg = msg + "%-9s: %s" % ('User', USER) + "\r\n"
msg = msg + "%-9s: %s" % ('Host', HOST) + "\r\n"
msg = msg + "%-9s: %s" % ('PID', PID) + "\r\n"
# Current trace
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subject(self):
"""Generate the subject.""" |
level = logging.getLevelName(self.flush_level)
message = self.current_buffer[0].split("\n")[0]
message = message.split(']')[-1]
return '{0} : {1}{2}'.format(level, SOURCE, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_query_result(self, query_result, query_path, return_type=list, preceding_depth=None):
""" Formats the query result based on the return type requested.... |
if type(query_result) != return_type:
converted_result = self.format_with_handler(query_result, return_type)
else:
converted_result = query_result
converted_result = self.add_preceding_dict(converted_result, query_path, preceding_depth)
return converted_result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_with_handler(self, query_result, return_type):
""" Uses the callable handler to format the query result to the desired return type :param query_result... |
handler = self.get_handler(type(query_result), return_type)
return handler.format_result(query_result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_handler(query_result_type, return_type):
""" Find the appropriate return type handler to convert the query result to the desired return type :param query... |
try:
return FormatterRegistry.get_by_take_and_return_type(query_result_type, return_type)
except (IndexError, AttributeError, KeyError):
raise IndexError(
'Could not find function in conversion list for input type %s and return type %s' % (
query_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_preceding_dict(config_entry, query_path, preceding_depth):
""" Adds the preceeding config keys to the config_entry to simulate the original full path to ... |
if preceding_depth is None:
return config_entry
preceding_dict = {query_path[-1]: config_entry}
path_length_minus_query_pos = len(query_path) - 1
preceding_depth = path_length_minus_query_pos - preceding_depth if preceding_depth != -1 else 0
for index in reversed(r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rebuild_config_cache(self, config_filepath):
""" Loads from file and caches all data from the config file in the form of an OrderedDict to self.data :param c... |
self.validate_config_file(config_filepath)
config_data = None
try:
with open(config_filepath, 'r') as f:
config_data = yaml.load(f)
items = list(iteritems(config_data))
except AttributeError:
items = list(config_data)
self.co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, query_path=None, return_type=list, preceding_depth=None, throw_null_return_error=False):
""" Traverses the list of query paths to find the data req... |
function_type_lookup = {str: self._get_path_entry_from_string,
list: self._get_path_entry_from_list}
if query_path is None:
return self._default_config(return_type)
try:
config_entry = function_type_lookup.get(type(query_path), str)(quer... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_path_entry_from_string(self, query_string, first_found=True, full_path=False):
""" Parses a string to form a list of strings that represents a possible ... |
iter_matches = gen_dict_key_matches(query_string, self.config_file_contents, full_path=full_path)
try:
return next(iter_matches) if first_found else iter_matches
except (StopIteration, TypeError):
raise errors.ResourceNotFoundError('Could not find search string %s in the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_path_entry_from_list(self, query_path):
""" Returns the config entry at query path :param query_path: list(str), config header path to follow for entry ... |
cur_data = self.config_file_contents
try:
for child in query_path:
cur_data = cur_data[child]
return cur_data
except (AttributeError, KeyError):
raise errors.ResourceNotFoundError('Could not find query path %s in the config file contents' %
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_config_file(cls, config_filepath):
""" Validates the filepath to the config. Detects whether it is a true YAML file + existance :param config_filepa... |
is_file = os.path.isfile(config_filepath)
if not is_file and os.path.isabs(config_filepath):
raise IOError('File path %s is not a valid yml, ini or cfg file or does not exist' % config_filepath)
elif is_file:
if os.path.getsize(config_filepath) == 0:
rai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_it(cls):
""" Performs the import only once. """ |
if not cls in cls._FEATURES:
try:
cls._FEATURES[cls] = cls._import_it()
except ImportError:
raise cls.Error(cls._import_error_message(), cls.Error.UNSATISFIED_IMPORT_REQ)
return cls._FEATURES[cls] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(author, kind):
""" Attempts to read the cache to fetch missing arguments. This method will attempt to find a '.license' file in the 'CACHE_DIRECTORY', t... |
if not os.path.exists(CACHE_PATH):
raise LicenseError('No cache found. You must '
'supply at least -a and -k.')
cache = read_cache()
if author is None:
author = read_author(cache)
if kind is None:
kind = read_kind(cache)
return author, kind |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_ticket_signature(self, data, sig):
"""Verify ticket signature. """ |
try:
signature = base64.b64decode(sig)
except TypeError as e:
if hasattr(self, "debug"):
print("Exception in function base64.b64decode. File %s" % (__file__))
print("%s" % e)
return False
if six.PY3:
# To av... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.