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 main(argv=None): """ Execute the application CLI. Arguments are taken from sys.argv by default. """
args = _cmdline(argv) config.load(args.config) results = get_package_list(args.search_term) results = sorted(results, key=lambda a: sort_function(a[1]), reverse=True) results_normalized = list() last_result = None for result in results: if result[0] == last_result: conti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_permissions(urlpatterns, permissions={}): """Generate names for permissions."""
for pattern in urlpatterns: if isinstance(pattern, urlresolvers.RegexURLPattern): perm = generate_perm_name(pattern.callback) if is_allowed_view(perm) and perm not in permissions: permissions[ACL_CODE_PREFIX + perm] = ACL_NAME_PREFIX + perm elif isinstance(pa...
<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_allowed_view(perm): """Check if permission is in acl list."""
# Check if permission is in excluded list for view in ACL_EXCLUDED_VIEWS: module, separator, view_name = view.partition('*') if view and perm.startswith(module): return False # Check if permission is in acl list for view in ACL_ALLOWED_VIEWS: module, separator, vie...
<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_location(query, format, api_key): """Get geographic data of a lab in a coherent way for all labs."""
# Play nice with the API... sleep(1) geolocator = OpenCage(api_key=api_key, timeout=10) # Variables for storing the data data = {"city": None, "address_1": None, "postal_code": None, "country": None, "county": None, "state": 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 interp(self, *args): """ This method takes a list of SQL snippets and returns a SQL statement and a list of bind variables to be passed to the DB API's execu...
sql = "" bind = () def _append_sql(sql, part): "Handle whitespace when appending properly." if len(sql) == 0: return part elif sql[-1] == ' ': return sql + part else: return sql + ' ' + part ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def esc(self, val): """ Returns the given object in the appropriate wrapper class from esc_types.py. In most cases, you will not need to call this directly. Howe...
if type(val) in self.type_map: return self.type_map[type(val)](val) else: return Esc(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def api_request(api_base_url='http://localhost:8080/', path='', method='get', data=None, params={}, verify=True, cert=list()): """ Wrapper function for requests ...
method = method.lower() headers = { 'Accept': 'application/json', 'Content-type': 'application/json', } methods = { 'get': requests.get, 'post': requests.post, } if path[0] != '/': path = '/{0}'.format(path) if params: path += '?{0}'.format(ur...
<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_ssh_creds(config, args): """ Set ssh credentials into config. Note that these values might also be set in ~/.bangrc. If they are specified both in ~/.ban...
creds = config.get(A.DEPLOYER_CREDS, {}) creds[A.creds.SSH_USER] = args.user if args.user else creds.get( A.creds.SSH_USER, DEFAULT_SSH_USER, ) if args.ask_pass: creds[A.creds.SSH_PASS] = getpass.getpass('SSH Password: ') config[A.DEPLOYER_CREDS] = creds
<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_bang(alt_args=None): """ Runs bang with optional list of strings as command line options. If ``alt_args`` is not specified, defaults to parsing ``sys.arg...
parser = get_parser() args = parser.parse_args(alt_args) source = args.config_specs or get_env_configs() if not source: return config = Config.from_config_specs(source) if args.playbooks: config[A.PLAYBOOKS] = args.playbooks if args.dump_config: if args.dump_con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def monitor(self, timeout): """ Monitor the process, check whether it runs out of time. """
def check(self, timeout): time.sleep(timeout) self.stop() wather = threading.Thread(target=check) wather.setDaemon(True) wather.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def hdf5_storable(type_or_storable, *args, **kwargs): '''Registers a `Storable` instance in the global service.''' if not isinstance(type_or_storable, Storable): type_or_storable = default_storable(type_or_storable) hdf5_service.registerStorable(type_or_storable, *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 hdf5_not_storable(_type, *args, **kwargs): '''Tags a type as not serializable.''' hdf5_service.registerStorable(not_storable(_type), *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 compile_and_process(self, in_path): """compile a file, save it to the ouput file if the inline flag true"""
out_path = self.path_mapping[in_path] if not self.embed: pdebug("[%s::%s] %s -> %s" % ( self.compiler_name, self.name, os.path.relpath(in_path), os.path.relpath(out_path)), groups=["build_task"], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_output(self): """ helper function to gather the results of `compile_and_process` on all target files """
if self.embed: if self.concat: concat_scripts = [self.compiled_scripts[path] for path in self.build_order] return [self.embed_template_string % '\n'.join(concat_scripts)] else: return [self.embed_template...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self): """build the scripts and return a string"""
if not self.embed: mkdir_recursive(self.output_directory) # get list of script files in build order self.build_order = remove_dups( reduce(lambda a, b: a + glob.glob(b), self.build_targets, [])) self.build_order_output = [s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_experiments(experiment_ids=None, user_id=None, client_id=None, bucket_if_necessary=True, user_data=None): """ Retrieve the experiments the user is a part...
if not client_id: client_id = os.environ.get('BERNOULLI_CLIENT_ID') if not client_id: raise Exception("client_id is required") if type(experiment_ids) is dict: experiment_ids = ','.join(experiment_ids) params = { 'clientId': client_id, 'experimentIds': experi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def record_goal_attained(experiment_id, user_id, client_id = None): """ Record that a variant was successful for a user @param experiment_id : A single experimen...
if not client_id: client_id = os.environ.get('BERNOULLI_CLIENT_ID') if not client_id: raise Exception("client_id is required") try: response = requests.post(BASE_URL, data={ 'clientId': client_id, 'userId': user_id, 'experimentId': experiment_i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yaml_dump_hook(cfg, text: bool=False): """ Dumps all the data into a YAML file. """
data = cfg.config.dump() if not text: yaml.dump(data, cfg.fd, Dumper=cfg.dumper, default_flow_style=False) else: return yaml.dump(data, Dumper=cfg.dumper, default_flow_style=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 _create_djset(args, cls): """ Return a DjSecret object """
name = args.get('--name') settings = args.get('--settings') if name: return cls(name=name) elif settings: return cls(name=settings) else: return cls()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_args(args, cls): """ Parse a docopt dictionary of arguments """
d = _create_djset(args, cls) key_value_pair = args.get('<key>=<value>') key = args.get('<key>') func = None if args.get('add') and key_value_pair: fargs = tuple(args.get('<key>=<value>').split('=')) if fargs[1]: func = d.set elif args.get('remove') and 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 prompt_update_all(config: 'Config'): """Prompt each field of the configuration to the user."""
click.echo() click.echo('Welcome !') click.echo('Press enter to keep the defaults or enter a new value to update the configuration.') click.echo('Press Ctrl+C at any time to quit and save') click.echo() for field in config: type_ = config.__type__(field) hint = config.__hint_...
<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_config(configclass: type(Config)): """Command line function to update and the a config."""
# we build the real click command inside the function, because it needs to be done # dynamically, depending on the config. # we ignore the type errors, keeping the the defaults if needed # everything will be updated anyway config = configclass() # type: Config def print_list(ctx, param, val...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def configureLogger(logFolder, logFile): ''' Start the logger instance and configure it ''' # Set debug level logLevel = 'DEBUG' logger = logging.getLogger() logger.setLevel(logLevel) # Format formatter = logging.Formatter('%(asctime)s - %(levelname)s | %(name)s -> %(message)s', '%Y-%m-%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 printWelcomeMessage(msg, place=10): ''' Print any welcome message ''' logging.debug('*' * 30) welcome = ' ' * place welcome+= msg logging.debug(welcome) logging.debug('*' * 30 + '\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 on_chat(self, data): ''' Transfert a message to everybody ''' # XXX: we cannot use on_message as it's 'official' one already used # by sockjsroom to create multiple on_* elements (like on_chat), # so we use on_chat instead of on_message # data => message if self.room...
<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_leave(self): ''' Quit chat room ''' # Only if user has time to call self.initialize # (sometimes it's not the case) if self.roomId != '-1': # Debug logging.debug('chat: leave room (roomId: %s)' % self.roomId) # Say to other users the current us...
<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, target, acceptor): """ Initiate a connection from the tendril manager's endpoint. Once the connection is completed, a UDPTendril object will be...
# Call some common sanity-checks super(UDPTendrilManager, self).connect(target, acceptor, None) # Construct the Tendril tend = UDPTendril(self, self.local_addr, target) try: # Set up the application tend.application = acceptor(tend) except appl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listener(self, acceptor, wrapper): """ Listens for new connections to the manager's endpoint. Once a new connection is received, a UDPTendril object is gener...
# OK, set up the socket sock = socket.socket(self.addr_family, socket.SOCK_DGRAM) with utils.SocketCloser(sock): # Bind to our endpoint sock.bind(self.endpoint) # Get the assigned port number self.local_addr = sock.getsockname() # ...
<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_lb_nodes(self, lb_id, nodes): """ Adds nodes to an existing LBaaS instance :param string lb_id: Balancer id :param list nodes: Nodes to add. {address, po...
log.info("Adding load balancer nodes %s" % nodes) resp, body = self._request( 'post', '/loadbalancers/%s/nodes' % lb_id, data={'nodes': nodes}) return 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 match_lb_nodes(self, lb_id, existing_nodes, host_addresses, host_port): """ Add and remove nodes to match the host addresses and port given, based on existin...
delete_filter = lambda n: \ n['address'] not in host_addresses or \ str(n['port']) != str(host_port) delete_nodes = filter(delete_filter, existing_nodes) delete_node_ids = [n['id'] for n in delete_nodes] delete_node_hosts = [n['address'] for n in delete_...
<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_lb_nodes(self, lb_id, node_ids): """ Remove one or more nodes :param string lb_id: Balancer id :param list node_ids: List of node ids """
log.info("Removing load balancer nodes %s" % node_ids) for node_id in node_ids: self._request('delete', '/loadbalancers/%s/nodes/%s' % (lb_id, node_id))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def soup(self, *args, **kwargs): """Parse the currently loaded website. Optionally, SoupStrainer can be used to only parse relevant parts of the page. This can b...
if self._url is None: raise NoWebsiteLoadedError('website parsing requires a loaded website') content_type = self._response.headers.get('Content-Type', '') if not any(markup in content_type for markup in ('html', 'xml')): raise ParsingError('unsupported content type \'{...
<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, **kwargs): """Send a GET request to the specified URL. Method directly wraps around `Session.get` and updates browser attributes. <http://docs...
response = self.session.get(url, **kwargs) self._url = response.url self._response = response return response
<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, **kwargs): """Send a POST request to the currently loaded website's URL. The browser will automatically fill out the form. If `data` dict has been...
if self._url is None: raise NoWebsiteLoadedError('request submission requires a loaded website') data = kwargs.get('data', {}) for i in self.soup('form').select('input[name]'): if i.get('name') not in data: data[i.get('name')] = i.get('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 build_howto(request=None): """ Searches for "how_to.md" files in app directories. Creates user-friendly admin how-to section from apps that have them. """
how_tos = {} for app in settings.INSTALLED_APPS: mod = import_module(app) app_dir = os.path.dirname(mod.__file__) how_to_file = os.path.join(app_dir, 'how_to.md') if os.path.exists(how_to_file): contents = open(how_to_file).read() how_tos[app] = markdow...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formfield_for_foreignkey_helper(inline, *args, **kwargs): """ The implementation for ``RelatedContentInline.formfield_for_foreignkey`` This takes the takes a...
db_field = args[0] if db_field.name != "related_type": return args, kwargs initial_filter = getattr(settings, RELATED_TYPE_INITIAL_FILTER, False) if "initial" not in kwargs and initial_filter: # TODO: handle gracefully if unable to load and in non-debug initial = Re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def usage(self): """ A usage string that describes the signature. """
return u' '.join(u'<%s>' % pattern.usage for pattern in self.patterns)
<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, argv): """ Parses the given `argv` and returns a dictionary mapping argument names to the values found in `argv`. """
rv = {} for pattern in self.patterns: pattern.apply(rv, argv) return rv
<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_record(self, name, record_id): """Retrieve a record with a given type name and record id. Args: name (string): The name which the record is stored under...
if name in self._cache: if record_id in self._cache[name]: return self._cache[name][record_id]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_records(self, name): """Return all the records for the given name in the cache. Args: name (string): The name which the required models are stored under...
if name in self._cache: return self._cache[name].values() else: 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 set_record(self, name, record_id, record): """Save a record into the cache. Args: name (string): The name to save the model under. record_id (int): The rec...
if name not in self._cache: self._cache[name] = {} self._cache[name][record_id] = record
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hone_cache(maxsize=128, maxage=None, refineby='startswith', store_partials=False): """ A caching decorator that follows after the style of lru_cache. Calls t...
if not callable(refineby): finder = hone_cache_finders[refineby] else: finder = refineby def decorator(inner_func): wrapper = make_hone_cache_wrapper(inner_func, maxsize, maxage, finder, store_partials) return functools.update_wrapp...
<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_hone_cache_wrapper(inner_func, maxsize, maxage, finder, store_partials): """ Keeps a cache of requests we've already made and use that for generating re...
hits = misses = partials = 0 cache = TTLMapping(maxsize, maxage) def wrapper(*args): nonlocal hits, misses, partials radix = args[-1] # Attempt fast cache hit first. try: r = cache[radix] except KeyError: pass else: hits ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ttl_cache(maxage, maxsize=128): """ A time-to-live caching decorator that follows after the style of lru_cache. The `maxage` argument is time-to-live in seco...
def decorator(inner_func): wrapper = make_ttl_cache_wrapper(inner_func, maxage, maxsize) return functools.update_wrapper(wrapper, inner_func) return decorator
<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_ttl_cache_wrapper(inner_func, maxage, maxsize, typed=False): """ Use the function signature as a key for a ttl mapping. Any misses will defer to the wra...
hits = misses = 0 cache = TTLMapping(maxsize, maxage) def wrapper(*args, **kwargs): nonlocal hits, misses key = functools._make_key(args, kwargs, typed) try: result = cache[key] except KeyError: misses += 1 result = cache[key] = inner_fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(command, options, args): """Run the requested command. args is either a list of descriptions or a list of strings to filter by"""
if command == "backend": subprocess.call(("sqlite3", db_path)) if command == "add": dp = pdt.Calendar() due = mktime(dp.parse(options.due)[0]) if options.due else None print "added tasks..." [Task(desc, due).add() for desc in args] return filters = args 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 mark_read(self): """ Mark notifications as read. CURRENT UNSUPPORTED: https://github.com/kippt/api-documentation/blob/master/endpoints/notifications/POST_not...
# Obviously remove the exception when Kippt says the support it. raise NotImplementedError( "The Kippt API does not yet support marking notifications as read." ) data = json.dumps({"action": "mark_seen"}) r = requests.post( "https://kippt.com/api/notific...
<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_programs(): """Returns a generator that yields the available executable programs :returns: a generator that yields the programs available after a refresh...
programs = [] os.environ['PATH'] += os.pathsep + os.getcwd() for p in os.environ['PATH'].split(os.pathsep): if path.isdir(p): for f in os.listdir(p): if _is_executable(path.join(p, f)): yield f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _underscore_run_program(name, *args, **kwargs): """Runs the 'name' program, use this if there are illegal python method characters in the program name 'Hello...
if name in get_programs() or kwargs.get("shell", False): return _run_program(name, *args, **kwargs) else: raise ProgramNotFoundException()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_listing(): """Refreshes the list of programs attached to the perform module from the path"""
for program in get_programs(): if re.match(r'^[a-zA-Z_][a-zA-Z_0-9]*$', program) is not None: globals()[program] = partial(_run_program, program) globals()["_"] = _underscore_run_program
<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(path=None): """ Compile le lemmatiseur localement """
if path is None: path = os.path.join(os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")) path = os.path.join(path, "compiled.pickle") with open(path, "rb") as file: return load(file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lemmatise_assims(self, f, *args, **kwargs): """ Lemmatise un mot f avec son assimilation :param f: Mot à lemmatiser :param pos: Récupère la POS :param get_l...
forme_assimilee = self.assims(f) if forme_assimilee != f: for proposal in self._lemmatise(forme_assimilee, *args, **kwargs): yield proposal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lemmatise_roman_numerals(self, form, pos=False, get_lemma_object=False): """ Lemmatise un mot f si c'est un nombre romain :param form: Mot à lemmatiser :par...
if estRomain(form): _lemma = Lemme( cle=form, graphie_accentuee=form, graphie=form, parent=self, origin=0, pos="a", modele=self.modele("inv") ) yield Lemmatiseur.format_result( form=form, lemma=_lemma, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lemmatise_contractions(self, f, *args, **kwargs): """ Lemmatise un mot f avec sa contraction :param f: Mot à lemmatiser :yield: Match formated like in _lemm...
fd = f for contraction, decontraction in self._contractions.items(): if fd.endswith(contraction): fd = f[:-len(contraction)] if "v" in fd or "V" in fd: fd += decontraction else: fd += deramise(decontract...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _lemmatise_suffixe(self, f, *args, **kwargs): """ Lemmatise un mot f si il finit par un suffixe :param f: Mot à lemmatiser :yield: Match formated like in _le...
for suffixe in self._suffixes: if f.endswith(suffixe) and suffixe != f: yield from self._lemmatise(f[:-len(suffixe)], *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 connect(host, port, username, password): """Connect and login to an FTP server and return ftplib.FTP object."""
# Instantiate ftplib client session = ftplib.FTP() # Connect to host without auth session.connect(host, port) # Authenticate connection session.login(username, password) return session
<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, remote, local=None, keep_dir_structure=False): """ Download a remote file on the fto sever to a local directory. :param remote: File path of remote...
if local and os.path.isdir(local): os.chdir(local) elif keep_dir_structure: # Replicate the remote files folder structure for directory in remote.split(os.sep)[:-1]: if not os.path.isdir(directory): os.mkdir(directory) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chdir(self, directory_path, make=False): """Change directories and optionally make the directory if it doesn't exist."""
if os.sep in directory_path: for directory in directory_path.split(os.sep): if make and not self.directory_exists(directory): try: self.session.mkd(directory) except ftplib.error_perm: # Director...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listdir(self, directory_path=None, hidden_files=False): """ Return a list of files and directories in a given directory. :param directory_path: Optional str ...
# Change current directory if a directory path is specified, otherwise use current if directory_path: self.chdir(directory_path) # Exclude hidden files if not hidden_files: return [path for path in self.session.nlst() if not path.startswith('.')] # Incl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, file_path): """Remove the file named filename from the server."""
if os.sep in file_path: directory, file_name = file_path.rsplit(os.sep, 1) self.chdir(directory) return self.session.delete(file_name) else: return self.session.delete(file_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 _retrieve_binary(self, file_name): """Retrieve a file in binary transfer mode."""
with open(file_name, 'wb') as f: return self.session.retrbinary('RETR ' + file_name, f.write)
<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_binary(self, local_path, remote): """Store a file in binary via ftp."""
# Destination directory dst_dir = os.path.dirname(remote) # Destination file name dst_file = os.path.basename(remote) # File upload command dst_cmd = 'STOR {0}'.format(dst_file) with open(local_path, 'rb') as local_file: # Change directory if neede...
<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_new_password2(self): """Validate password when set"""
password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password1 or password2: if password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _run_command(self, arguments: List[str], input_data: Any=None, output_encoding: str="utf-8") -> str: """ Run a command as a subprocess. Ignores errors given o...
process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) if isinstance(input_data, List): for to_write in input_data: to_write_as_json = json.dumps(to_write) process.stdin.write(str.encode(to_write_as_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 collection_choices(): """Return collection choices."""
from invenio_collections.models import Collection return [(0, _('-None-'))] + [ (c.id, c.name) for c in Collection.query.all() ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _query_api(self, endpoint, **kwargs): """ Query the API. """
try: response = requests.get( '{api}/{endpoint}?{args}'.format( api=self.url, endpoint=endpoint, args=urllib.urlencode(kwargs)), headers={ 'Authorization': 'Token {token}'.format(token=se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_random_string(template_dict, key='start'): """Generates a random excuse from a simple template dict. Based off of drow's generator.js (public domain...
data = template_dict.get(key) #if isinstance(data, list): result = random.choice(data) #else: #result = random.choice(data.values()) for match in token_regex.findall(result): word = generate_random_string(template_dict, match) or match result = result.replace('{{{0}}}'.fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bofh_excuse(how_many=1): """Generate random BOFH themed technical excuses! Args: how_many: Number of excuses to generate. (Default: 1) Returns: A list of BOF...
excuse_path = os.path.join(os.path.dirname(__file__), 'bofh_excuses.json') with open(excuse_path, 'r') as _f: excuse_dict = json.load(_f) return [generate_random_string(excuse_dict) for _ in range(int(how_many))]
<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_current_waypoints(boatd=None): ''' Get the current set of waypoints active from boatd. :returns: The current waypoints :rtype: List of Points ''' if boatd is None: boatd = Boatd() content = boatd.get('/waypoints') return [Point(*coords) for coords in content.get('waypo...
<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_home_position(boatd=None): ''' Get the current home position from boatd. :returns: The configured home position :rtype: Points ''' if boatd is None: boatd = Boatd() content = boatd.get('/waypoints') home = content.get('home', None) if home is not None: lat,...
<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, endpoint): '''Return the result of a GET request to `endpoint` on boatd''' json_body = urlopen(self.url(endpoint)).read().decode('utf-8') return json.loads(json_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 post(self, content, endpoint=''): ''' Issue a POST request with `content` as the body to `endpoint` and return the result. ''' url = self.url(endpoint) post_content = json.dumps(content).encode('utf-8') headers = {'Content-Type': 'application/json'} re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def wind(self): ''' Return the direction of the wind in degrees. :returns: wind object containing direction bearing and speed :rtype: Wind ''' content = self._cached_boat.get('wind') return Wind( Bearing(content.get('absolute')), content.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 position(self): ''' Return the current position of the boat. :returns: current position :rtype: Point ''' content = self._cached_boat lat, lon = content.get('position') return Point(lat, lon)
<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_rudder(self, angle): ''' Set the angle of the rudder to be `angle` degrees. :param angle: rudder angle :type angle: float between -90 and 90 ''' angle = float(angle) request = self.boatd.post({'value': float(angle)}, '/rudder') return request.get(...
<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_sail(self, angle): ''' Set the angle of the sail to `angle` degrees :param angle: sail angle :type angle: float between -90 and 90 ''' angle = float(angle) request = self.boatd.post({'value': float(angle)}, '/sail') return request.get('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 start(self, name): ''' End the current behaviour and run a named behaviour. :param name: the name of the behaviour to run :type name: str ''' d = self.boatd.post({'active': name}, endpoint='/behaviours') current = d.get('active') if current is not Non...
<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_types(name, *types): """ Register a short name for one or more content types. """
type_names.setdefault(name, set()) for t in types: # Redirecting the type if t in media_types: type_names[media_types[t]].discard(t) # Save the mapping media_types[t] = name type_names[name].add(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 get_types(self): """ Retrieve a set of all recognized content types for this translator object. """
# Convert translators into a set of content types content_types = set() for name in self.translators: content_types |= type_names[name] return content_types
<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_search_page(self, term: str): """Get search page. This function will get the first link from the search term we do on term and then it will return ...
# Uses the BASEURL and also builds link for the page we want using the term given params = {'s': term, 'post_type': 'seriesplan'} async with self.session.get(self.BASEURL, params=params) as response: # If the response is 200 OK if response.status == 200: ...
<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_aliases(parse_info): """get aliases from parse info. :param parse_info: Parsed info from html soup. """
return [ div.string.strip() for div in parse_info.find('div', id='editassociated') if div.string is not 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_related_series(parse_info): """get related_series from parse info. :param parse_info: Parsed info from html soup. """
seriesother_tags = [x for x in parse_info.select('h5.seriesother')] sibling_tag = [x for x in seriesother_tags if x.text == 'Related Series'][0] siblings_tag = list(sibling_tag.next_siblings) # filter valid tag # valid tag is all tag before following tag # <h5 class="se...
<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_fm_ext(self, freq, amplitude, peak_freq_dev=None, output_state=True): """Sets the func generator to frequency modulation with external modulation. freq i...
if peak_freq_dev is None: peak_freq_dev = freq commands = ['FUNC SIN', # set to output sine functions 'FM:STAT ON', 'FREQ {0}'.format(freq), 'FM:SOUR EXT', # 'FM:FREQ {0}'.format(freq), 'FM...
<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_burst(self, freq, amplitude, period, output_state=True): """Sets the func generator to burst mode with external trigerring."""
ncyc = int(period*freq) commands = ['FUNC SIN', 'BURS:STAT ON', 'BURS:MODE TRIG', # external trigger 'TRIG:SOUR EXT', 'TRIG:SLOP POS', 'FREQ {0}'.format(freq), 'VOLT {0}'.format(amp...
<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_arbitrary(self, freq, low_volt, high_volt, output_state=True): """Programs the function generator to output the arbitrary waveform."""
commands = ['FUNC USER', 'BURS:STAT OFF', 'SWE:STAT OFF', 'FM:STAT OFF', 'FREQ {0}'.format(freq), 'VOLT:HIGH {0}'.format(high_volt), 'VOLT:LOW {0}'.format(low_volt), ] ...
<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_continuous(self, freq, amplitude, offset, output_state=True): """Programs the Stanford MW function generator to output a continuous sine wave. External '...
commands = ['MODL 0', #disable any modulation 'FREQ {0}'.format(freq) ] if freq > 4.05e9: commands.append('AMPH {0}'.format(amplitude)) #set rear RF doubler amplitude if offset > 0.0: print('HIGH FREQUENCY OUTPUT IS ...
<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_freqsweep_ext(self, amplitude, sweep_low_end, sweep_high_end, offset=0.0, output_state=True): """Sets the Stanford MW function generator to freq modulati...
sweep_deviation = round(abs(sweep_low_end - sweep_high_end)/2.0,6) freq = sweep_low_end + sweep_deviation commands = ['TYPE 3', #set to sweep 'SFNC 5', #external modulation 'FREQ {0}'.format(freq), 'SDEV {0}'.format(sweep_deviation),...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disable_all(self, disable): """Disables all modulation and outputs of the Standford MW func. generator"""
commands = ['ENBH 0', #disable high freq. rear output 'ENBL 0', #disable low freq. front bnc 'MODL 0' #disable modulation ] command_string = '\n'.join(commands) print_string = '\n\t' + command_string.replace('\n', '\n\t') log...
<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_continuous(self, freq, amplitude, offset, phase, channel=2): """Programs the function generator to output a continuous sine wave."""
commands = [':SOUR{0}:APPL:SIN '.format(channel), '{0},'.format(freq), '{0},'.format(amplitude), '{0},'.format(offset), '{0}'.format(phase), ] command_string = ''.join(commands) logging.info(com...
<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_requires(__fname: str) -> List[str]: """Parse ``pip``-style requirements files. This is a *very* naïve parser, but very few packages make use of the mor...
deps = [] with open(__fname) as req_file: entries = [s.split('#')[0].strip() for s in req_file.readlines()] for dep in entries: if not dep: continue elif dep.startswith('-r '): include = dep.split()[1] if '/' not in include...
<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_email(filepaths, collection_name): """Create an email message object which implements the email.message.Message interface and which has the files to b...
outer = MIMEMultipart() outer.preamble = 'Here are some files for you' def add_file_to_outer(path): if not os.path.isfile(path): return # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def enter_config_value(self, key, default=""): ''' Prompts user for a value ''' value = input('Please enter a value for ' + key + ': ') if value: return value else: return default
<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_introspection(self, runtime='', whitelist=[], verbose=False): """ Figure out which objects are opened by a test binary and are matched by the white list...
found_objects = set() try: # Retrieve list of successfully opened objects strace = subprocess.Popen(['strace', runtime], stderr=subprocess.PIPE, stdout=subprocess.PIPE) (_, stderr) = strace.communicate() opened_objects = set() for line in stderr.split('\n'): if 'open' in l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __get_container_path(self, host_path): """ A simple helper function to determine the path of a host library inside the container :param host_path: The path o...
libname = os.path.split(host_path)[1] return os.path.join(_container_lib_location, libname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inside_softimage(): """Returns a boolean indicating if the code is executed inside softimage."""
try: import maya return False except ImportError: pass try: from win32com.client import Dispatch as disp disp('XSI.Application') return True except: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_item(self, path, name, icon=None, url=None, order=None, permission=None, active_regex=None): """ Add new menu item to menu :param path: Path of menu :par...
if self.root_item is None: self.root_item = MenuItem('ROOT', 'ROOT') root_item = self.root_item current_path = '' for node in path.split('/')[:-1]: if not node: continue current_path = '/' + '{}/{}'.format(current_path, node).strip('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(self, item): """Merge Menu item data"""
self.name = item.name if item.icon: self.icon = item.icon if item.url: self.url = item.url if item.order: self.order = item.order if item.permission: self.permission = item.permission
<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_child(self, item): """Add child to menu item"""
item.depth = self.depth + 1 self.childs.append(item) self.childs = sorted(self.childs, key=lambda item: item.order if item.order else 999)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def child_by_code(self, code): """ Get child MenuItem by its last path code :param code: :return: MenuItem or None """
for child in self.childs: if child.path.split('/')[-1] == code: return child 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 is_active(self, path): """Check if given path is active for current item"""
if self.url == '/' and self.url == path: return True elif self.url == '/': return False if self.url and path.startswith(self.url): return True if self.active_regex and re.compile(self.active_regex).match(path): return True for c...