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 RemoveEmptyDirectoryTree(path, silent = False, recursion = 0):
""" Delete tree of empty directories. Parameters path : string Path to root of directory tree.... |
if not silent and recursion is 0:
goodlogging.Log.Info("UTIL", "Starting removal of empty directory tree at: {0}".format(path))
try:
os.rmdir(path)
except OSError:
if not silent:
goodlogging.Log.Info("UTIL", "Removal of empty directory tree terminated at: {0}".format(path))
return
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ValidUserResponse(response, validList):
""" Check if user response is in a list of valid entires. If an invalid response is given re-prompt user to enter one... |
if response in validList:
return response
else:
prompt = "Unknown response given - please reenter one of [{0}]: ".format('/'.join(validList))
response = goodlogging.Log.Input("DM", prompt)
return ValidUserResponse(response, validList) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UserAcceptance( matchList, recursiveLookup = True, promptComment = None, promptOnly = False, xStrOverride = "to skip this selection" ):
""" Prompt user to se... |
matchString = ', '.join(matchList)
if len(matchList) == 1:
goodlogging.Log.Info("UTIL", "Match found: {0}".format(matchString))
prompt = "Enter 'y' to accept this match or e"
elif len(matchList) > 1:
goodlogging.Log.Info("UTIL", "Multiple possible matches found: {0}".format(matchString))
prompt ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetBestMatch(target, matchList):
""" Finds the elements of matchList which best match the target string. Note that this searches substrings so "abc" will hav... |
bestMatchList = []
if len(matchList) > 0:
ratioMatch = []
for item in matchList:
ratioMatch.append(GetBestStringMatchValue(target, item))
maxRatio = max(ratioMatch)
if maxRatio > 0.8:
matchIndexList = [i for i, j in enumerate(ratioMatch) if j == maxRatio]
for index in matchInde... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetBestStringMatchValue(string1, string2):
""" Return the value of the highest matching substrings between two strings. Parameters string1 : string First str... |
# Ignore case
string1 = string1.lower()
string2 = string2.lower()
# Ignore non-alphanumeric characters
string1 = ''.join(i for i in string1 if i.isalnum())
string2 = ''.join(i for i in string2 if i.isalnum())
# Finding best match value between string1 and string2
if len(string1) == 0 or len(string2) ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def WebLookup(url, urlQuery=None, utf8=True):
""" Look up webpage at given url with optional query string Parameters url : string Web url. urlQuery : dictionary ... |
goodlogging.Log.Info("UTIL", "Looking up info from URL:{0} with QUERY:{1})".format(url, urlQuery), verbosity=goodlogging.Verbosity.MINIMAL)
response = requests.get(url, params=urlQuery)
goodlogging.Log.Info("UTIL", "Full url: {0}".format(response.url), verbosity=goodlogging.Verbosity.MINIMAL)
if utf8 is 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 ArchiveProcessedFile(filePath, archiveDir):
""" Move file from given file path to archive directory. Note the archive directory is relative to the file path ... |
targetDir = os.path.join(os.path.dirname(filePath), archiveDir)
goodlogging.Log.Info("UTIL", "Moving file to archive directory:")
goodlogging.Log.IncreaseIndent()
goodlogging.Log.Info("UTIL", "FROM: {0}".format(filePath))
goodlogging.Log.Info("UTIL", "TO: {0}".format(os.path.join(targetDir, os.path.basenam... |
<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_wait(self,text):
"""Send a string to the PiLite, sleep until the message has been displayed (based on an estimate of the speed of the display. Due to... |
self.send(text)
time.sleep(len(text)*PiLite.COLS_PER_CHAR*self.speed/1000.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 set_speed(self,speed):
"""Set the display speed. The parameters is the number of milliseconds between each column scrolling off the display""" |
self.speed=speed
self.send_cmd("SPEED"+str(speed)) |
<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_fb_random(self):
"""Set the "frame buffer" to a random pattern""" |
pattern=''.join([random.choice(['0','1']) for i in xrange(14*9)])
self.set_fb(pattern) |
<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_pixel(self,x,y,state):
"""Set pixel at "x,y" to "state" where state can be one of "ON", "OFF" or "TOGGLE" """ |
self.send_cmd("P"+str(x+1)+","+str(y+1)+","+state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display_char(self,x,y,char):
"""Display character "char" with its top left at "x,y" """ |
self.send_cmd("T"+str(x+1)+","+str(y+1)+","+char) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def the_magic_mapping_function(peptides, fastaPath, importAttributes=None, ignoreUnmapped=True):
"""Returns a dictionary mapping peptides to protein group leadin... |
missedCleavage = max([p.count('K') + p.count('R') for p in peptides]) - 1
minLength = min([len(p) for p in peptides])
maxLength = max([len(p) for p in peptides])
defaultAttributes = {
'cleavageRule': '[KR]', 'minLength': minLength, 'maxLength': maxLength,
'removeNtermM': True, 'ignore... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
""" Returns a truncated version of the inputted text. :param text | <str> length | <int> ellipsis | <str> :return <str> """ |
text = nativestring(text)
return text[:length] + (text[length:] and ellipsis) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(data):
"""Return data as a JSON string.""" |
return json.dumps(data, default=lambda x: x.__dict__, sort_keys=True, indent=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_string(string, chars=None):
"""Remove certain characters from a string.""" |
if chars is None:
chars = [',', '.', '-', '/', ':', ' ']
for ch in chars:
if ch in string:
string = string.replace(ch, ' ')
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_time(time):
"""Convert a time string into 24-hour time.""" |
split_time = time.split()
try:
# Get rid of period in a.m./p.m.
am_pm = split_time[1].replace('.', '')
time_str = '{0} {1}'.format(split_time[0], am_pm)
except IndexError:
return time
try:
time_obj = datetime.strptime(time_str, '%I:%M %p')
except ValueError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_month(date, shorten=True, cable=True):
"""Replace month by shortening or lengthening it. :param shorten: Set to True to shorten month name. :param ca... |
month = date.split()[0].lower()
if 'sept' in month:
shorten = False if cable else True
try:
if shorten:
month = SHORT_MONTHS[MONTHS.index(month)]
else:
month = MONTHS[SHORT_MONTHS.index(month)]
except ValueError:
month = month.title()
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_date(date):
"""Convert string to datetime object.""" |
date = convert_month(date, shorten=False)
clean_string = convert_string(date)
return datetime.strptime(clean_string, DATE_FMT.replace('-','')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def date_in_range(date1, date2, range):
"""Check if two date objects are within a specific range""" |
date_obj1 = convert_date(date1)
date_obj2 = convert_date(date2)
return (date_obj2 - date_obj1).days <= range |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inc_date(date_obj, num, date_fmt):
"""Increment the date by a certain number and return date object. as the specific string format. """ |
return (date_obj + timedelta(days=num)).strftime(date_fmt) |
<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_soup(url):
"""Request the page and return the soup.""" |
html = requests.get(url, stream=True, headers=HEADERS)
if html.status_code != 404:
return BeautifulSoup(html.content, 'html.parser')
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_list(query_list, string):
"""Return True if all words in a word list are in the string. :param query_list: list of words to match :param string: the wo... |
# Get rid of 'the' word to ease string matching
match = False
index = 0
string = ' '.join(filter_stopwords(string))
if not isinstance(query_list, list):
query_list = [query_list]
while index < len(query_list):
query = query_list[index]
words_query = filter_stopwords(qu... |
<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_stopwords(phrase):
"""Filter out stop words and return as a list of words""" |
if not isinstance(phrase, list):
phrase = phrase.split()
stopwords = ['the', 'a', 'in', 'to']
return [word.lower() for word in phrase if word.lower() not in stopwords] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_unicode(string):
"""If Python 2, replace non-ascii characters and return encoded string.""" |
if not PY3:
uni = string.replace(u'\u2019', "'")
return uni.encode('utf-8')
return string |
<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_strings(soup, tag):
"""Get all the string children from an html tag.""" |
tags = soup.find_all(tag)
strings = [s.string for s in tags if s.string]
return strings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, given_name, demo):
"""Initializes a bubble.""" |
path = None
if path is None:
path = ctx.home
bubble_file_name = path + '/.bubble'
config_file = path + '/config/config.yaml'
if os.path.exists(bubble_file_name) and os.path.isfile(bubble_file_name):
ctx.say_yellow(
'There is already a bubble present,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bld_op(self, op, num, **kwargs):
"""implements pandas an operator""" |
kwargs['other'] = num
setattr(self, op, {'mtype': pab, 'kwargs': 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 _bld_pab_generic(self, funcname, **kwargs):
"""
implements a generic version of an attribute based pandas function
""" |
margs = {'mtype': pab, 'kwargs': kwargs}
setattr(self, funcname, margs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bld_pnab_generic(self, funcname, **kwargs):
"""
implement's a generic version of a non-attribute based pandas function
""" |
margs = {'mtype': pnab, 'kwargs': kwargs}
setattr(self, funcname, margs) |
<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, request, *args, **kwargs):
""" List all products in the shopping cart """ |
cart = ShoppingCartProxy(request)
return JsonResponse(cart.get_products(onlypublic=request.GET.get('onlypublic', 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 post(self, request, *args, **kwargs):
""" Adds new product to the current shopping cart """ |
POST = json.loads(request.body.decode('utf-8'))
if 'product_pk' in POST and 'quantity' in POST:
cart = ShoppingCartProxy(request)
cart.add(
product_pk=int(POST['product_pk']),
quantity=int(POST['quantity'])
)
return JsonRe... |
<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_signal(alias: str, signal: pyqtSignal):
""" Used to register signal at the dispatcher. Note that you can not use alias that already exists. :param a... |
if SignalDispatcher.signal_alias_exists(alias):
raise SignalDispatcherError('Alias "' + alias + '" for signal already exists!')
SignalDispatcher.signals[alias] = signal |
<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_handler(alias: str, handler: callable):
""" Used to register handler at the dispatcher. :param alias: Signal alias to match handler to. :param handl... |
if SignalDispatcher.handlers.get(alias) is None:
SignalDispatcher.handlers[alias] = [handler]
else:
SignalDispatcher.handlers.get(alias).append(handler) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dispatch():
""" This methods runs the wheel. It is used to connect signal with their handlers, based on the aliases. :return: """ |
aliases = SignalDispatcher.signals.keys()
for alias in aliases:
handlers = SignalDispatcher.handlers.get(alias)
signal = SignalDispatcher.signals.get(alias)
if signal is None or handlers.__len__() == 0:
continue
for handler in handlers:... |
<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_rev(self, fpath):
""" Get an SCM version number. Try svn and git. """ |
rev = None
try:
cmd = ["git", "log", "-n1", "--pretty=format:\"%h\"", fpath]
rev = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()[0]
except:
pass
if not rev:
try:
cmd = ["svn", "info", fpath]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_migrations(self, show_traceback=True):
""" Executes all pending migrations across all capable databases """ |
all_migrations = get_pending_migrations(self.path, self.databases)
if not len(all_migrations):
sys.stdout.write("There are no migrations to apply.\n")
for db, migrations in all_migrations.iteritems():
connection = connections[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 handle(self, *args, **options):
""" Upgrades the database. Executes SQL scripts that haven't already been applied to the database. """ |
self.do_list = options.get("do_list")
self.do_execute = options.get("do_execute")
self.do_create = options.get("do_create")
self.do_create_all = options.get("do_create_all")
self.do_seed = options.get("do_seed")
self.load_initial_data = options.get("load_initial_data", T... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plantuml(desc):
"""Generate plantuml class diagram :param desc: result of sadisplay.describe function Return plantuml class diagram string """ |
classes, relations, inherits = desc
result = [
'@startuml',
'skinparam defaultFontName Courier',
]
for cls in classes:
# issue #11 - tabular output of class members (attrs)
# http://stackoverflow.com/a/8356620/258194
# build table
class_desc = []
... |
<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_reference_target(resource, rtype, label):
""" Return true if the resource has this rtype with this label """ |
prop = resource.props.references.get(rtype, False)
if prop:
return label in prop |
<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_sources(self, resources):
""" Filter resources based on which have this reference """ |
rtype = self.rtype # E.g. category
label = self.props.label # E.g. category1
result = [
resource
for resource in resources.values()
if is_reference_target(resource, rtype, label)
]
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 setup(app: Sphinx):
""" Initialize Kaybee as a Sphinx extension """ |
# Scan for directives, first in the system, second in the docs project
importscan.scan(plugins)
dectate.commit(kb)
app.add_config_value('kaybee_settings', KaybeeSettings(), 'html')
bridge = 'kaybee.plugins.postrenderer.config.KaybeeBridge'
app.config.template_bridge = bridge
app.connect(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadInstance(self):
""" Loads the plugin from the proxy information that was created from the registry file. """ |
if self._loaded:
return
self._loaded = True
module_path = self.modulePath()
package = projex.packageFromPath(module_path)
path = os.path.normpath(projex.packageRootPath(module_path))
if path in sys.path:
sys.path.remove(path)
sys.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 clean_resource_json(resource_json):
""" The catalog wants to be smaller, let's drop some stuff """ |
for a in ('parent_docname', 'parent', 'template', 'repr', 'series'):
if a in resource_json:
del resource_json[a]
props = resource_json['props']
for prop in (
'acquireds', 'style', 'in_nav', 'nav_title', 'weight',
'auto_excerpt'):
if prop in props:
... |
<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, url, params=None, cache_cb=None, **kwargs):
""" Make http get request. :param url: :param params: :param cache_cb: (optional) a function that takin... |
if self.use_random_user_agent:
headers = kwargs.get("headers", dict())
headers.update({Headers.UserAgent.KEY: Headers.UserAgent.random()})
kwargs["headers"] = headers
url = add_params(url, params)
cache_consumed, value = self.try_read_cache(url)
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, url, dst, params=None, cache_cb=None, overwrite=False, stream=False, minimal_size=-1, maximum_size=1024 ** 6, **kwargs):
""" Download binary c... |
response = self.get(
url,
params=params,
cache_cb=cache_cb,
stream=stream,
**kwargs
)
if not overwrite: # pragma: no cover
if os.path.exists(dst):
raise OSError("'%s' exists!" % dst)
if stream:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def option(*args, **kwargs):
"""Decorator to add an option to the optparser argument of a Cmdln subcommand To add a toplevel option, apply the decorator on the c... |
def decorate_sub_command(method):
"""create and add sub-command options"""
if not hasattr(method, "optparser"):
method.optparser = SubCmdOptionParser()
method.optparser.add_option(*args, **kwargs)
return method
def decorate_class(klass):
"""store toplevel opt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _inherit_attr(klass, attr, default, cp):
"""Inherit the attribute from the base class Copy `attr` from base class (otherwise use `default`). Copying is done ... |
if attr not in klass.__dict__:
if hasattr(klass, attr):
value = cp(getattr(klass, attr))
else:
value = default
setattr(klass, attr, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _forgiving_issubclass(derived_class, base_class):
"""Forgiving version of ``issubclass`` Does not throw any exception when arguments are not of class type ""... |
return (type(derived_class) is ClassType and \
type(base_class) is ClassType and \
issubclass(derived_class, base_class)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timecalMs1DataMedian(msrunContainer, specfile, calibrationData, minDataPoints=50, deviationKey='relDev'):
"""Generates a calibration value for each MS1 scan ... |
corrData = dict()
_posDict = dict()
pos = 0
for si in msrunContainer.getItems(specfiles=specfile, sort='rt',
selector=lambda si: si.msLevel==1
):
corrData[si.id] = {'calibValue': float(), 'n': int(), 'data': list()}
... |
<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_genericpage(cls, kb_app):
""" Return the one class if configured, otherwise default """ |
# Presumes the registry has been committed
q = dectate.Query('genericpage')
klasses = sorted(q(kb_app), key=lambda args: args[0].order)
if not klasses:
# The site doesn't configure a genericpage,
return Genericpage
else:
return klasses[0][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 cli(ctx):
"""Shows the man page packed inside the bubble tool this is mainly too overcome limitations on installing manual pages in a distribution agnostic a... |
manfile = bubble_lib_dir+os.sep+'extras'+os.sep+'Bubble.1.gz'
mancmd = ["/usr/bin/man", manfile]
try:
return subprocess.call(mancmd)
except Exception as e:
print('cannot run man with bubble man page')
print('you can always have a look at: '+manfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _fetch_dimensions(self, dataset):
""" We override this method just to set the correct datatype and dialect for regions. """ |
for dimension in super(SCB, self)._fetch_dimensions(dataset):
if dimension.id == "Region":
yield Dimension(dimension.id,
datatype="region",
dialect="skatteverket",
label=dimension.label)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def call(self, func, key, timeout=None):
'''Wraps a function call with cache.
Args:
func (function): the function to call.
key (str): the cache key for this call.
timeout (int): the cache timeout for the key (the
unit of this parameter depe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def map(self, key_pattern, func, all_args, timeout=None):
'''Cache return value of multiple calls.
Args:
key_pattern (str): the key pattern to use for generating
keys for caches of the decorated function.
func (function): the function to call.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def _window_open(self, stream_id: int):
"""Wait until the identified stream's flow control window is open. """ |
stream = self._get_stream(stream_id)
return await stream.window_open.wait() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_data( self, stream_id: int, data: bytes, end_stream: bool = False, ):
"""Send data, respecting the receiver's flow control instructions. If the pr... |
if self.closed:
raise ConnectionClosedError
stream = self._get_stream(stream_id)
if stream.closed:
raise StreamClosedError(stream_id)
remaining = data
while len(remaining) > 0:
await asyncio.gather(
self._writable.wait(),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def read_data(self, stream_id: int) -> bytes: """Read data from the specified stream until it is closed by the remote peer. If the stream is never ended, th... |
frames = [f async for f in self.stream_frames(stream_id)]
return b''.join(frames) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def read_frame(self, stream_id: int) -> bytes: """Read a single frame of data from the specified stream, waiting until frames are available if none are pres... |
stream = self._get_stream(stream_id)
frame = await stream.read_frame()
if frame.flow_controlled_length > 0:
self._acknowledge_data(frame.flow_controlled_length, stream_id)
return frame.data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_pushed_stream_ids(self, parent_stream_id: int) -> List[int]: """Return a list of all streams pushed by the remote peer that are children of the spec... |
if parent_stream_id not in self._streams:
logger.error(
f'Parent stream {parent_stream_id} unknown to this connection'
)
raise NoSuchStreamError(parent_stream_id)
parent = self._get_stream(parent_stream_id)
await parent.pushed_streams_availab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convertMzml(mzmlPath, outputDirectory=None):
"""Imports an mzml file and converts it to a MsrunContainer file :param mzmlPath: path of the mzml file :param o... |
outputDirectory = outputDirectory if outputDirectory is not None else os.path.dirname(mzmlPath)
msrunContainer = importMzml(mzmlPath)
msrunContainer.setPath(outputDirectory)
msrunContainer.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepareSiiImport(siiContainer, specfile, path, qcAttr, qcLargerBetter, qcCutoff, rankAttr, rankLargerBetter):
"""Prepares the ``siiContainer`` for the import... |
if specfile not in siiContainer.info:
siiContainer.addSpecfile(specfile, path)
else:
raise Exception('...')
siiContainer.info[specfile]['qcAttr'] = qcAttr
siiContainer.info[specfile]['qcLargerBetter'] = qcLargerBetter
siiContainer.info[specfile]['qcCutoff'] = qcCutoff
siiContai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def importPeptideFeatures(fiContainer, filelocation, specfile):
""" Import peptide features from a featureXml file, as generated for example by the OpenMS node f... |
if not os.path.isfile(filelocation):
warnings.warn('The specified file does not exist %s' %(filelocation, ))
return None
elif (not filelocation.lower().endswith('.featurexml') and
not filelocation.lower().endswith('.features.tsv')
):
#TODO: this is depricated as impo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _importDinosaurTsv(filelocation):
"""Reads a Dinosaur tsv file. See also :func:`importPeptideFeatures` """ |
with io.open(filelocation, 'r', encoding='utf-8') as openFile:
#NOTE: this is pretty similar to importing percolator results, maybe unify in a common function
lines = openFile.readlines()
headerDict = dict([[y,x] for (x,y) in enumerate(lines[0].strip().split('\t'))])
featureDict = 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 rst_to_html(input_string: str) -> str: """ Given a string of RST, use docutils to generate html """ |
overrides = dict(input_encoding='unicode', doctitle_xform=True,
initial_header_level=1)
parts = publish_parts(
writer_name='html',
source=input_string,
settings_overrides=overrides
)
return parts['html_body'] |
<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_rst_title(rst_doc: Node) -> Optional[Any]: """ Given some RST, extract what docutils thinks is the title """ |
for title in rst_doc.traverse(nodes.title):
return title.astext()
return None |
<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_rst_excerpt(rst_doc: document, paragraphs: int = 1) -> str: """ Given rst, parse and return a portion """ |
texts = []
for count, p in enumerate(rst_doc.traverse(paragraph)):
texts.append(p.astext())
if count + 1 == paragraphs:
break
return ' '.join(texts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requires_password_auth(fn):
"""Decorator for HAPI methods that requires the instance to be authenticated with a password""" |
def wrapper(self, *args, **kwargs):
self.auth_context = HAPI.auth_context_password
return fn(self, *args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requires_api_auth(fn):
"""Decorator for HAPI methods that requires the instance to be authenticated with a HAPI token""" |
def wrapper(self, *args, **kwargs):
self.auth_context = HAPI.auth_context_hapi
return fn(self, *args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(response):
"""Parse a postdata-style response format from the API into usable data""" |
"""Split a a=1b=2c=3 string into a dictionary of pairs"""
tokens = {r[0]: r[1] for r in [r.split('=') for r in response.split("&")]}
# The odd dummy parameter is of no use to us
if 'dummy' in tokens:
del tokens['dummy']
"""
If we have key names that end in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_chain(self):
"""Autodetect the devices attached to the Controller, and initialize a JTAGDevice for each. This is a required call before device specific ... |
if not self._hasinit:
self._hasinit = True
self._devices = []
self.jtag_enable()
while True:
# pylint: disable=no-member
idcode = self.rw_dr(bitcount=32, read=True,
lastbit=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 _UserUpdateConfigValue(self, configKey, strDescriptor, isDir = True, dbConfigValue = None):
""" Allow user to set or update config values in the database tab... |
newConfigValue = None
if dbConfigValue is None:
prompt = "Enter new {0} or 'x' to exit: ".format(strDescriptor)
else:
prompt = "Enter 'y' to use existing {0}, enter a new {0} or 'x' to exit: ".format(strDescriptor)
while newConfigValue is None:
response = goodlogging.Log.Input("CLEA... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetConfigValue(self, configKey, strDescriptor, isDir = True):
""" Get configuration value from database table. If no value found user will be prompted to en... |
goodlogging.Log.Info("CLEAR", "Loading {0} from database:".format(strDescriptor))
goodlogging.Log.IncreaseIndent()
configValue = self._db.GetConfigValue(configKey)
if configValue is None:
goodlogging.Log.Info("CLEAR", "No {0} exists in database".format(strDescriptor))
configValue = self._U... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _UserUpdateSupportedFormats(self, origFormatList = []):
""" Add supported formats to database table. Always called if the database table is empty. User can b... |
formatList = list(origFormatList)
inputDone = None
while inputDone is None:
prompt = "Enter new format (e.g. .mp4, .avi), " \
"'r' to reset format list, " \
"'f' to finish or " \
"'x' to exit: "
response = g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetSupportedFormats(self):
""" Get supported format values from database table. If no values found user will be prompted to enter values for this table. Ret... |
goodlogging.Log.Info("CLEAR", "Loading supported formats from database:")
goodlogging.Log.IncreaseIndent()
formatList = self._db.GetSupportedFormats()
if formatList is None:
goodlogging.Log.Info("CLEAR", "No supported formats exist in database")
formatList = self._UserUpdateSupportedFormat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _UserUpdateIgnoredDirs(self, origIgnoredDirs = []):
""" Add ignored directories to database table. Always called if the database table is empty. User can bui... |
ignoredDirs = list(origIgnoredDirs)
inputDone = None
while inputDone is None:
prompt = "Enter new directory to ignore (e.g. DONE), " \
"'r' to reset directory list, " \
"'f' to finish or " \
"'x' to exit: "
respon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetIgnoredDirs(self):
""" Get ignored directories values from database table. If no values found user will be prompted to enter values for this table. Retur... |
goodlogging.Log.Info("CLEAR", "Loading ignored directories from database:")
goodlogging.Log.IncreaseIndent()
ignoredDirs = self._db.GetIgnoredDirs()
if ignoredDirs is None:
goodlogging.Log.Info("CLEAR", "No ignored directories exist in database")
ignoredDirs = self._UserUpdateIgnoredDirs()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetDatabaseConfig(self):
""" Get all configuration from database. This includes values from the Config table as well as populating lists for supported forma... |
goodlogging.Log.Seperator()
goodlogging.Log.Info("CLEAR", "Getting configuration variables...")
goodlogging.Log.IncreaseIndent()
# SOURCE DIRECTORY
if self._sourceDir is None:
self._sourceDir = self._GetConfigValue('SourceDir', 'source directory')
# TV DIRECTORY
if self._inPlaceRena... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetSupportedFilesInDir(self, fileDir, fileList, supportedFormatList, ignoreDirList):
""" Recursively get all supported files given a root search directory. ... |
goodlogging.Log.Info("CLEAR", "Parsing file directory: {0}".format(fileDir))
if os.path.isdir(fileDir) is True:
for globPath in glob.glob(os.path.join(fileDir, '*')):
if util.FileExtensionMatch(globPath, supportedFormatList):
newFile = tvfile.TVFile(globPath)
if newFile.GetSho... |
<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(self):
""" Main entry point for ClearManager class. Does the following steps: - Parse script arguments. - Optionally print or update database tables. - G... |
self._GetArgs()
goodlogging.Log.Info("CLEAR", "Using database: {0}".format(self._databasePath))
self._db = database.RenamerDB(self._databasePath)
if self._dbPrint or self._dbUpdate:
goodlogging.Log.Seperator()
self._db.PrintAllTables()
if self._dbUpdate:
goodlogging.Log.Sep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush(self):
"""Force the queue of Primitives to compile, execute on the Controller, and fulfill promises with the data returned.""" |
self.stages = []
self.stagenames = []
if not self.queue:
return
if self.print_statistics:#pragma: no cover
print("LEN OF QUENE", len(self))
t = time()
if self._chain._collect_compiler_artifacts:
self._compile(debug=True, stages=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step_impl(context):
"""Compares text as written to the log output""" |
expected_lines = context.text.split('\n')
assert len(expected_lines) == len(context.output)
for expected, actual in zip(expected_lines, context.output):
print('--\n\texpected: {}\n\tactual: {}'.format(expected, actual))
assert expected == actual |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ParseShowList(self, checkOnly=False):
""" Read self._allShowList as csv file and make list of titles and IDs. Parameters checkOnly : boolean [optional : def... |
showTitleList = []
showIDList = []
csvReader = csv.reader(self._allShowList.splitlines())
for rowCnt, row in enumerate(csvReader):
if rowCnt == 0:
# Get header column index
for colCnt, column in enumerate(row):
if column == 'title':
titleIndex = colCnt
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetAllShowList(self):
""" Populates self._allShowList with the epguides all show info. On the first lookup for a day the information will be loaded from the... |
today = datetime.date.today().strftime("%Y%m%d")
saveFile = '_epguides_' + today + '.csv'
saveFilePath = os.path.join(self._saveDir, saveFile)
if os.path.exists(saveFilePath):
# Load data previous saved to file
with open(saveFilePath, 'r') as allShowsFile:
self._allShowList = allSho... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetShowID(self, showName):
""" Get epguides show id for a given show name. Attempts to match the given show name against a show title in self._showTitleList... |
self._GetTitleList()
self._GetIDList()
for index, showTitle in enumerate(self._showTitleList):
if showName == showTitle:
return self._showIDList[index]
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetEpisodeName(self, showID, season, episode):
""" Get episode name from epguides show info. Parameters showID : string Identifier matching show in epguides... |
# Load data for showID from dictionary
showInfo = csv.reader(self._showInfoDict[showID].splitlines())
for rowCnt, row in enumerate(showInfo):
if rowCnt == 0:
# Get header column index
for colCnt, column in enumerate(row):
if column == 'season':
seasonIndex = colC... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ShowNameLookUp(self, string):
""" Attempts to find the best match for the given string in the list of epguides show titles. If this list has not previous bee... |
goodlogging.Log.Info("EPGUIDES", "Looking up show name match for string '{0}' in guide".format(string), verbosity=self.logVerbosity)
self._GetTitleList()
showName = util.GetBestMatch(string, self._showTitleList)
return(showName) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def EpisodeNameLookUp(self, showName, season, episode):
""" Get the episode name correspondng to the given show name, season number and episode number. Parameter... |
goodlogging.Log.Info("EPGUIDE", "Looking up episode name for {0} S{1}E{2}".format(showName, season, episode), verbosity=self.logVerbosity)
goodlogging.Log.IncreaseIndent()
showID = self._GetShowID(showName)
if showID is not None:
try:
self._showInfoDict[showID]
except KeyError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def private_path(self):
"""Get the path to a directory which can be used to store arbitrary data This directory should not conflict with any of the repository in... |
path = os.path.join(self.path, '.hg', '.private')
try:
os.mkdir(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
return 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 bookmarks(self):
"""Get list of bookmarks""" |
cmd = [HG, 'bookmarks']
output = self._command(cmd).decode(self.encoding, 'replace')
if output.startswith('no bookmarks set'):
return []
results = []
for line in output.splitlines():
m = bookmarks_rx.match(line)
assert m, 'unexpected output: '... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def content(self):
"""Get the file contents. This property is cached. The file is only read once. """ |
if not self._content:
self._content = self._read()
return self._content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def config(self):
"""Get a Configuration object from the file contents.""" |
conf = config.Configuration()
for namespace in self.namespaces:
if not hasattr(conf, namespace):
if not self._strict:
continue
raise exc.NamespaceNotRegistered(
"The namespace {0} is not registered.".format(namespac... |
<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(self):
"""Open the file and return its contents.""" |
with open(self.path, 'r') as file_handle:
content = file_handle.read()
# Py27 INI config parser chokes if the content provided is not unicode.
# All other versions seems to work appropriately. Forcing the value to
# unicode here in order to resolve this issue.
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def ask(self, body, quick_replies=None, options=None, user=None):
""" simple ask with predefined quick replies :param body: :param quick_replies: (optional... |
await self.send_text_message_to_all_interfaces(
recipient=user,
text=body,
quick_replies=quick_replies,
options=options,
)
return any.Any() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def say(self, body, user, options):
""" say something to user :param body: :param user: :return: """ |
return await self.send_text_message_to_all_interfaces(
recipient=user, text=body, options=options) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self, protocolFactory):
"""Starts a process and connect a protocol to it. """ |
deferred = self._startProcess()
deferred.addCallback(self._connectRelay, protocolFactory)
deferred.addCallback(self._startRelay)
return deferred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _startProcess(self):
"""Use the inductor to start the process we want to relay data from. """ |
connectedDeferred = defer.Deferred()
processProtocol = RelayProcessProtocol(connectedDeferred)
self.inductor.execute(processProtocol, *self.inductorArgs)
return connectedDeferred |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connectRelay(self, process, protocolFactory):
"""Set up and connect the protocol we want to relay to the process. This method is automatically called when t... |
try:
wf = _WrappingFactory(protocolFactory)
connector = RelayConnector(process, wf, self.timeout,
self.inductor.reactor)
connector.connect()
except:
return defer.fail()
# Return a deferred that is called back... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _startRelay(self, client):
"""Start relaying data between the process and the protocol. This method is called when the protocol is connected. """ |
process = client.transport.connector.process
# Relay any buffered data that was received from the process before
# we got connected and started relaying.
for _, data in process.data:
client.dataReceived(data)
process.protocol = client
@process._endedDeferred... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connectRelay(self):
"""Builds the target protocol and connects it to the relay transport. """ |
self.protocol = self.connector.buildProtocol(None)
self.connected = True
self.protocol.makeConnection(self) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.