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 full_width_svg(url, width, height, alt_text=None): ''' Helper to render an SVG that will size to fill its element while keeping its dimentions. ''' return { 'ratio': str((float(height)/float(width))*100)[:2], 'url': url, 'alt_text': alt_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 open(self): """Opens a SSH connection with a Pluribus machine."""
self._connection = paramiko.SSHClient() self._connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self._connection.connect(hostname=self._hostname, username=self._username, password=self._pas...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Closes the SSH connection if the connection is UP."""
if not self.connected: return None if self.config is not None: if self.config.changed() and not self.config.committed(): try: self.config.discard() # if configuration changed and not committed, will rollback except pyPluribus....
<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(self, command): """ Executes a command and returns raw output from the CLI. :param command: Command to be executed on the CLI. :raise pyPluribus.exceptio...
if not self.connected: raise pyPluribus.exceptions.ConnectionError("Not connected to the deivce.") cli_output = '' ssh_session = self._connection.get_transport().open_session() # opens a new SSH session ssh_session.settimeout(self._timeout) ssh_session.exec_comma...
<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_data_xlsx(file_name, file_contents=None, on_demand=False): ''' Loads the new excel format files. Old format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. ...
<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_data_xls(file_name, file_contents=None, on_demand=False): ''' Loads the old excel format files. New format files will automatically get loaded as well. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. ...
<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_data_excel_xml(file_name, file_contents=None, on_demand=False): ''' Loads xml excel format files. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. file_contents: The file-like object holding contents o...
<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_data_csv(file_name, encoding='utf-8', file_contents=None, on_demand=False): ''' Gets good old csv data from a file. Args: file_name: The name of the local file, or the holder for the extension type when the file_contents are supplied. encoding: Loads the file with the sp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write(data, file_name, worksheet_names=None): ''' Writes 2D tables to file. Args: data: 2D list of tables/worksheets. file_name: Name of the output file (determines type). worksheet_names: A list of worksheet names (optional). ''' if re.search(XML_EXT_REGEX, file_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 write_xls(data, file_name, worksheet_names=None): ''' Writes out to old excel format. Args: data: 2D list of tables/worksheets. file_name: Name of the output file. worksheet_names: A list of worksheet names (optional). ''' workbook = xlwt.Workbook() for sheet_index, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write_csv(data, file_name, encoding='utf-8'): ''' Writes out to csv format. Args: data: 2D list of tables/worksheets. file_name: Name of the output file. ''' name_extension = len(data) > 1 root, ext = os.path.splitext(file_name) for i, sheet in enumerate(data): ...
<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_group(name): """ Return group with given name, if it exists. Check cache first. """
group = cache.get('bits.general.group_%s' % name) if not group: group = Group.objects.get(name=name) cache.set('bits.general.group_%s' % name, group, 365 * 24 * 60 * 60) return group
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def uniqify(list_): "inefficient on long lists; short lists only. preserves order." a=[] for x in list_: if x not in a: a.append(x) return a
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def eliminate_sequential_children(paths): "helper for infer_columns. removes paths that are direct children of the n-1 or n-2 path" return [p for i,p in enumerate(paths) if not ((i>0 and paths[i-1]==p[:-1]) or (i>1 and paths[i-2]==p[:-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 collapse_group_expr(groupx,cols,ret_row): "collapses columns matching the group expression. I'm sure this is buggy; look at a real DB's imp of this." for i,col in enumerate(cols.children): if col==groupx: ret_row[i]=ret_row[i][0] return ret_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 update_aliases(aliases,aonly,x): "helper for ctor. takes AliasX or string as second arg" if isinstance(x,basestring): aliases[x]=x elif isinstance(x,sqparse2.AliasX): if not isinstance(x.alias,basestring): raise TypeError('alias not string',type(x.alias)) if isinstance(x.name,sqparse2.NameX)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resolve_aonly(self,tables_dict,table_ctor): "circular depends on pgmock.Table. refactor." for alias,selectx in self.aonly.items(): table = table_ctor(alias,infer_columns(selectx,tables_dict),None) table.rows = run_select(selectx,tables_dict,table_ctor) self.aonly[alias] = table self.ao...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rowget(self,tables_dict,row_list,index): "row_list in self.row_order" tmp=row_list for i in self.index_tuple(tables_dict,index,False): tmp=tmp[i] return tmp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def eval_agg_call(self, exp): "helper for eval_callx; evaluator for CallX that consume multiple rows" if not isinstance(self.c_row,list): raise TypeError('aggregate function expected a list of rows') if len(exp.args.children)!=1: raise ValueError('aggregate function expected a single value',exp.args) ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def eval_nonagg_call(self, exp): "helper for eval_callx; evaluator for CallX that consume a single value" # todo: get more concrete about argument counts args=self.eval(exp.args) if exp.f=='coalesce': a,b=args # todo: does coalesce take more than 2 args? return b if a is None else a elif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def eval_callx(self, exp): "dispatch for CallX" # below: this isn't contains(exp,consumes_row) -- it's just checking the current expression return (self.eval_agg_call if consumes_rows(exp) else self.eval_nonagg_call)(exp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def redirect_to_handler(error, location): """ Cause a requset with an error to internally redirect to a URI path. This is generally for internal use, but can be ...
if callable(location): location = location() request.environ['REQUEST_METHOD'] = 'GET' redirect(location, internal=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 _transfer_str(self, conn, tmp, name, data): ''' transfer string to remote file ''' if type(data) == dict: data = utils.jsonify(data) afd, afile = tempfile.mkstemp() afo = os.fdopen(afd, 'w') try: afo.write(data.encode('utf8')) except: ...
<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_module(self, conn, tmp, module_name, args, async_jid=None, async_module=None, async_limit=None, inject=None): ''' runs a module that has already been transferred ''' # hack to support fireball mode if module_name == 'fireball': args = "%s password=%s" % (args, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _executor(self, host): ''' handler for multiprocessing library ''' try: exec_rc = self._executor_internal(host) #if type(exec_rc) != ReturnData and type(exec_rc) != ansible.runner.return_data.ReturnData: # raise Exception("unexpected return type: %s" % type(ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _executor_internal(self, host): ''' executes any module one or more times ''' host_variables = self.inventory.get_variables(host) if self.transport in [ 'paramiko', 'ssh' ]: port = host_variables.get('ansible_ssh_port', self.remote_port) if port is 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 _low_level_exec_command(self, conn, cmd, tmp, sudoable=False, executable=None): ''' execute a command string over SSH, return the output ''' if executable is None: executable = '/bin/sh' sudo_user = self.sudo_user rc, stdin, stdout, stderr = conn.exec_command(cmd, tmp, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _remote_md5(self, conn, tmp, path): ''' takes a remote md5sum without requiring python, and returns 0 if no file ''' test = "rc=0; [ -r \"%s\" ] || rc=2; [ -f \"%s\" ] || rc=1" % (path,path) md5s = [ "(/usr/bin/md5sum %s 2>/dev/null)" % path, # Linux "(/sbin/md5sum ...
<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_tmp_path(self, conn): ''' make and return a temporary path on a remote box ''' basefile = 'ansible-%s-%s' % (time.time(), random.randint(0, 2**48)) basetmp = os.path.join(C.DEFAULT_REMOTE_TMP, basefile) if self.sudo and self.sudo_user != 'root': basetmp = os.path.j...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _copy_module(self, conn, tmp, module_name, module_args, inject): ''' transfer a module over SFTP, does not run it ''' if module_name.startswith("/"): raise errors.AnsibleFileNotFound("%s is not a module" % module_name) # Search module path(s) for named module. in_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 _parallel_exec(self, hosts): ''' handles mulitprocessing when more than 1 fork is required ''' if not hosts: return p = multiprocessing.Pool(self.forks) results = [] #results = p.map(multiprocessing_runner, hosts) # can't handle keyboard interrupt results ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _partition_results(self, results): ''' seperate results by ones we contacted & ones we didn't ''' if results is None: return None results2 = dict(contacted={}, dark={}) for result in results: host = result.host if host is None: ra...
<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): ''' xfer & run module on all matched hosts ''' # find hosts that match the pattern hosts = self.inventory.list_hosts(self.pattern) if len(hosts) == 0: self.callbacks.on_no_hosts() return dict(contacted={}, dark={}) global multiprocessing_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 run_async(self, time_limit): ''' Run this module asynchronously and return a poller. ''' self.background = time_limit results = self.run() return results, poller.AsyncPoller(results, 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 image_by_id(self, id): """ Return image with given Id """
if not id: return None return next((image for image in self.images() if image['Id'] == id), 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 image_by_tag(self, tag): """ Return image with given tag """
if not tag: return None return next((image for image in self.images() if tag in image['RepoTags']), 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 image_exists(self, id=None, tag=None): """ Check if specified image exists """
exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag(tag): exists = True return exists
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def container_by_id(self, id): """ Returns container with given id """
if not id: return None return next((container for container in self.containers(all=True) if container['Id'] == id), 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 container_by_name(self, name): """ Returns container with given name """
if not name: return None # docker prepends a '/' to container names in the container dict name = '/'+name return next((container for container in self.containers(all=True) if name in container['Names']), 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 container_exists(self, id=None, name=None): """ Checks if container exists already """
exists = False if id and self.container_by_id(id): exists = True elif name and self.container_by_name(name): exists = True return exists
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def container_running(self, id=None, name=None): """ Checks if container is running """
running = False if id: running = self.inspect_container(id)['State']['Running'] elif name: running = self.inspect_container(name)['State']['Running'] return running
<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_container_ip(self, container): """ Returns the internal ip of the container if available """
info = self.inspect_container(container) if not info: return None netInfo = info['NetworkSettings'] if not netInfo: return None ip = netInfo['IPAddress'] if not ip: return None return ip
<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(fileobj): """Parse fileobj for a shebang."""
fileobj.seek(0) try: part = fileobj.read(2) except UnicodeDecodeError: part = "" if part == "#!": shebang = shlex.split(fileobj.readline().strip()) if (platform.system() == "Windows" and len(shebang) and os.path.basename(shebang[0]) == "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 run(self, port=5000, background=False): """ Runs this application with builtin server for testing. This is only for test usage, do not use in production stag...
target = os.path.dirname(os.path.abspath(sys.argv[0])) driver = Driver(self, port, target, 1) if background: driver.run_background() else: driver.run()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unbind(self, handler, argspec): """ handler will no longer be called if args match argspec :param argspec: instance of ArgSpec - args to be matched """
self.handlers[argspec.key].remove((handler, argspec)) if not len(self.handlers[argspec.key]): del self.handlers[argspec.key]
<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(self, *args, **kwargs): """ Call handlers that match args or kwargs :return: set of handlers called """
called_handlers = set() for handler_list in self.handlers.values(): for handler, argspec in handler_list: accept_args, accept_kwargs = argspec.accepts if handler in called_handlers and False: continue 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 iterencode(self, o, _one_shot=False): """Encode the given object and yield each string representation as available. For example:: for chunk in JSONEncoder()....
if self.check_circular: markers = {} else: markers = None if self.ensure_ascii: _encoder = encode_basestring_ascii else: _encoder = encode_basestring if self.encoding != 'utf-8': def _encoder(o, _orig_encoder=_encoder, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """ Updates intension and then adds or includes extension """
# updates intension self.update_intension() self._size_known_intension = len(self.members) self._update_members = 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 is_entailed_by(self, other): """ Means merging other with self does not produce any new information. """
if not set(self.include.keys()).issubset(set(other.include.keys())): return False if not self.exclude.isuperset(other.exclude): return False if not self.prototype.is_entailed_by(other.prototype): return False return 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 get_instances(self): """ Returns the members of the LazyDict """
if self._update_members: self.update() return iter(sorted(self.members.iteritems()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bots_list(self): """ List all user's bots :rtype: list of Bot :return: user's bots """
data = self.client.bots() return [Bot(item) for item in data]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bots_create(self, bot): """ Save new bot :param bot: bot object to save :type bot: Bot """
self.client.bots(_method="POST", _json=bot.to_json(), _params=dict(userToken=self.token))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bots_get(self, bot): """ Fetch and fill Bot object :param bot: empty bot object with name to search :type bot: Bot :rtype: Bot :return: filled bot object """
data = self.client.bots.__getattr__(bot.name).__call__() return Bot(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bots_delete(self, bot): """ Delete existing bot :param bot: bot to delete :type bot: Bot """
self.client.bots.__getattr__(bot.name).__call__(_method="DELETE", _params=dict(botName=bot.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 talk(self, bot, message): """ Talk to bot and get response based You can use this method to integrate the platform with your own channels :param bot: bot to ...
data = self.client.talk(_method="POST", _params=dict(botName=bot.name), _json=message.to_json()) return ActionResponse(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, bot, channel_type, ar, user_id): """ Use this method to push message to user of bot. The message should be packed into ActionResponse object. This...
self.client.push.__getattr__(bot.name).__call__(_method="POST", _params=dict(id=user_id, channel=channel_type), _json=ar.to_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 broadcast(self, bot, channel_type, text): """ Use this method to broadcast text message to all users of bot. :param bot: bot that will push user :type bot: B...
self.client.broadcast.__getattr__(bot.name).__call__(_method="POST", _params=dict(channel=channel_type), _json=dict(message=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 __parse(self, lines): """ Parse a list of lines and create an internal property dictionary """
# Every line in the file must consist of either a comment # or a key-value pair. A key-value pair is a line consisting # of a key which is a combination of non-white space characters # The separator character between key-value pairs is a '=', # ':' or a whitespace character not...
<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(self, stream): """ Load properties from an open file stream """
# For the time being only accept file input streams if not _is_file(stream): raise TypeError('Argument should be a file object!') # Check for the opened mode if stream.mode != 'r': raise ValueError('Stream should be opened in read-only mode!') try: ...
<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_property(self, key, value): """ Set the property for the given key """
if type(key) is str and type(value) is str: self.process_pair(key, value) else: raise TypeError('Both key and value should be 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 list(self, out=sys.stdout): """ Prints a listing of the properties to the stream 'out' which defaults to the standard output """
out.write('-- listing properties --\n') for key,value in self._properties.items(): out.write(''.join((key,'=',value,'\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 store(self, out, header=""): """ Write the properties list to the stream 'out' along with the optional 'header' """
if out.mode[0] != 'w': raise ValueError('Steam should be opened in write mode!') try: out.write(''.join(('#',header,'\n'))) # Write timestamp tstamp = time.strftime('%a %b %d %H:%M:%S %Z %Y', time.localtime()) out.write(''.join(('#',tstamp,'...
<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_random(self): """Get a kitten, either from the db, or a new one. """
num_kittens = self.count() new_cutoff = (num_kittens / (num_kittens + constants.KITTEN_FRESHNESS)) if random.random() < new_cutoff: return self._rand_inst() else: return self.create_new()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boot(): """Read configuration files, initialize glin and run main loop"""
argparser = argparse.ArgumentParser( description="Controller for LED stripes (WS2801, WS2811 an similar)") argparser.add_argument("-c", "--config", metavar="CONFIGFILE", dest="configfiles", action='append', help='Configuration File. May be repeated multiple times. Later confi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _play_sound(self, filename): """ Shells player with the provided filename. `filename` Filename for sound file. """
command = self._get_external_player() if not command: return # no player found if common.IS_MACOSX: command += ' "{0}"'.format(filename) else: # append quiet flag and filename is_play = (command == 'play') command += ' -q "{...
<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_option(self, option, block_name, *values): """ Parse options for play, end_play, and timer_play. """
if len(values) != 1: raise TypeError value = os.path.realpath(os.path.expanduser(values[0])) if not os.path.isfile(value) and not os.path.islink(value): raise ValueError(u'Sound file "{0}" does not exist' .format(value)) # special ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_taskend(self, task): """ Play sounds at task end. """
key = 'timer' if task.elapsed else 'end' filename = self.files.get(key) if filename: self._play_sound(filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fixpath(root, base): """Return absolute, normalized, joined paths"""
return os.path.abspath(os.path.normpath(os.path.join(root, base)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sorter(generated): """Return a list of paths sorted by dirname & basename."""
pairs = [(os.path.dirname(f), os.path.basename(f)) for f in set(list(generated))] pairs.sort() return [os.path.join(pair[0], pair[1]) for pair in pairs]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _walk(recursion): """Returns a recursive or non-recursive directory walker"""
try: from scandir import walk as walk_function except ImportError: from os import walk as walk_function if recursion: walk = partial(walk_function) else: def walk(path): # pylint: disable=C0111 try: yield next(walk_function(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 isvalid(path, access=None, extensions=None, filetype=None, minsize=None): """Check whether file meets access, extension, size, and type criteria."""
return ((access is None or os.access(path, access)) and (extensions is None or checkext(path, extensions)) and (((filetype == 'all' and os.path.exists(path)) or (filetype == 'dir' and os.path.isdir(path)) or (filetype == 'file' and os.path.isfile(path))) or ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generator_file(self): """Generator for `self.filetype` of 'file'"""
for path in self.paths: if os.path.isfile(path): if isvalid(path, self.access, self.extensions, minsize=self.minsize): yield os.path.abspath(path) elif os.path.isdir(path): for root, _, fnames in self._walker...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generator_other(self): """Generator for `self.filetype` other than file"""
for path in self.paths: for root, dnames, fnames in self._walker(path): yield from self._generator_rebase(dnames, root) yield from self._generator_rebase(fnames, root)
<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, paths, access=None): """Verify list of paths"""
self.failures = [path for path in paths if not isvalid(path, access, filetype='all')] return not self.failures
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirs(self, paths, access=None): """Verify list of directories"""
self.failures = [path for path in paths if not isvalid(path, access, filetype='dir')] return not self.failures
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files(self, paths, access=None, extensions=None, minsize=None): """Verify list of files"""
self.failures = [path for path in paths if not isvalid(path, access, extensions, 'file', minsize)] return not self.failures
<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_manhole_factory(namespace, **passwords): """Get a Manhole Factory """
realm = manhole_ssh.TerminalRealm() realm.chainedProtocolFactory.protocolFactory = ( lambda _: EnhancedColoredManhole(namespace) ) p = portal.Portal(realm) p.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords) ) return manhole_ssh.ConchFactory(p)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_entity(self): """Create a new entity. The entity will have a higher UID than any previously associated with this world. :return: the new entity :rtype...
self._highest_id_seen += 1 entity = Entity(self._highest_id_seen, self) self._entities.append(entity) return entity
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy_entitiy(self, entity): """Remove the entity and all connected components from the world. Long-hand for :func:`essence.Entity.destroy`. """
for relation in self._database.values(): relation.pop(entity, None) for l in self._entities_by_component.values(): l.discard(entity) self._entities.remove(entity)
<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_component(self, entity, component): """Add component to entity. Long-hand for :func:`essence.Entity.add`. :param entity: entity to associate :type entity...
component_type = type(component) relation = self._get_relation(component_type) if entity in relation: # PYTHON2.6: Numbers required in format string. msg = "Component {0} can't be added to entity {1} since it already has a component of type {2}.".format(component, entity...
<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_component(self, entity, component_type, missing=MISSING): """Get the component of type component_type associated with entity. Long-hand for :func:`essenc...
relation = self._get_relation(component_type) if entity not in relation: if missing is MISSING: raise NoSuchComponentError() else: return missing return relation[entity]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_component(self, entity, component_type): """Remove the component of component_type from entity. Long-hand for :func:`essence.Entity.remove`. :param en...
relation = self._get_relation(component_type) del relation[entity] self._entities_with(component_type).remove(entity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, *args, **kwargs): """Calls update on each of the systems self.systems."""
for system in self.systems: system.update(self, *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 auto_discover(): """ Auto-map urls from controllers directory. Ignored only files and classes that start from underscore. """
urls = [ url(r'^admin/', admin.site.urls), ] # TODO: we can create python package to have a lot of controllers # in separate files def get_controllers(module_name): """Return list of controllers in a module.""" module = import_module('app.controllers.{}'.format(module_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 download_file(url, suffix=''): """Download attached file as temporary file. Parameters url : string SCO-API download Url suffix : string, optional If suffix ...
r = urllib2.urlopen(url) # Save attached file in temp file and return path to temp file fd, f_path = tempfile.mkstemp(suffix=suffix) os.write(fd, r.read()) os.close(fd) return f_path, suffix
<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_resource_listing(url, offset, limit, properties): """Gneric method to retrieve a resource listing from a SCO-API. Takes the resource-specific API listing...
# Create listing query based on given arguments query = [ QPARA_OFFSET + '=' + str(offset), QPARA_LIMIT + '=' + str(limit) ] # Add properties argument if property list is not None and not empty if not properties is None: if len(properties) > 0: query.append(QPARA...
<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_local_time(timestamp): """Convert a datatime object from UTC time to local time. Adopted from: http://stackoverflow.com/questions/4770297/python-convert-u...
utc = dt.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f') # Get UTC and local time zone from_zone = tz.gettz('UTC') to_zone = tz.tzlocal() # Tell the utc object that it is in UTC time zone utc = utc.replace(tzinfo=from_zone) # Convert time zone return utc.astimezone(to_zone)
<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_secret(self, creds_file): '''read the oauth secrets and account ID from a credentials configuration file''' try: with open(creds_file) as fp: creds = j...
) sys.stderr.write("\n") raise 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 get_video_count(self, search_q=None): '''Return the number of videos in the account''' if search_q is not None: params = {'q': search_q} else: params = None url = "/counts/videos" result = self._make_request(self.CMS_Server, 'GET', url, params=params)...
<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_video(self, videoUrl, name=None, ingestMedia=True): '''Post and optionally ingest media from the specified URL''' if name is None: name = os.path.basename(videoUrl) url = '/videos' data = {'name': name} new_video = self._make_request(self.CMS_Server, 'POST',...
<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): """ Connects the client to the server and returns it. """
key = paramiko.RSAKey(data=base64.b64decode( app.config['SSH_HOST_KEY'] )) client = paramiko.SSHClient() client.get_host_keys().add( app.config['SSH_HOST'], 'ssh-rsa', key ) client.connect( app.config['SSH_HOST'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def server_rules(self): """ Reads the server rules from the client and returns it. """
sftp = self.client.open_sftp() try: rule_path = self.rule_location try: stat_entry = sftp.stat(rule_path) if stat.S_ISDIR(stat_entry.st_mode): sftp.rmdir(rule_path) return [] except IOError: ...
<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(data: str) -> list: """ Parses the given data string and returns a list of rule objects. """
if isinstance(data, bytes): data = data.decode('utf-8') lines = ( item for item in (item.strip() for item in data.split('\n')) if len(item) and not item.startswith('#') ) rules = [] for line in lines: rules.append( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jaccardIndex(s1, s2, stranded=False): """ Compute the Jaccard index for two collections of genomic intervals :param s1: the first set of genomic intervals :p...
def count(s): """ sum the size of regions in s. """ tot = 0 for r in s: tot += len(r) return tot if stranded: raise GenomicIntervalError("Sorry, stranded mode for computing Jaccard " + "index hasn't been implemented yet.") s1 = collapseRegions(s1) s2 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intervalTreesFromList(inElements, verbose=False, openEnded=False): """ build a dictionary, indexed by chrom name, of interval trees for each chrom. :param in...
elements = {} if verbose: totalLines = len(inElements) pind = ProgressIndicator(totalToDo=totalLines, messagePrefix="completed", messageSuffix="of parsing") for element in inElements: if element.chrom not in elements: elements[element.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regionsIntersection(s1, s2, collapse=True): """ given two lists of genomic regions with chromosome, start and end coordinates, return a new list of regions w...
debug = False # we don't need to explicitly check for sorting because sorted order is # a post-condition of the collapsing function s1_c = collapseRegions(s1) s2_c = collapseRegions(s2) if len(s1_c) == 0 or len(s2_c) == 0: return [] res = [] j = 0 for i in range(0, len(s1_c)): if debug: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bucketIterator(elements, buckets): """ For each bucket in buckets, yield it and any elements that overlap it. :param elements: the genomic intervals to place...
def check_sorted(current, previous): if (previous is not None) and \ ((previous.chrom > current.chrom) or ((previous.chrom == current.chrom) and (previous.start > current.start))): raise GenomicIntervalError("elements not sorted. Saw " + str(previous...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseWigString(line, scoreType=int): """ Parse a string in simple Wig format and return a GenomicInterval. :param line: the string to be parsed :param scoreT...
parts = line.split("\t") if (len(parts) < 4): raise GenomicIntervalError("failed to parse " + line + " as wig format, too few fields") return GenomicInterval(parts[0].strip(), int(parts[1]), int(parts[2]), None, scoreType(parts[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 parseBEDString(line, scoreType=int, dropAfter=None): """ Parse a string in BED format and return a GenomicInterval object. :param line: the string to be pars...
peices = line.split("\t") if dropAfter is not None: peices = peices[0:dropAfter] if len(peices) < 3: raise GenomicIntervalError("BED elements must have at least chrom, " + "start and end; found only " + str(len(peices)) + " in " + line) chro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sameRegion(self, e): """ Check whether self represents the same DNA region as e. :param e: genomic region to compare against :return: True if self and e are ...
if e is None: return False return (self.chrom == e.chrom and self.start == e.start and self.end == e.end and self.name == e.name and self.strand == e.strand)