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 __get_hosts(self, pattern): """ finds hosts that postively match a particular pattern. Does not take into account negative matches. """
(name, enumeration_details) = self._enumeration_info(pattern) hpat = self._hosts_in_unenumerated_pattern(name) hpat = sorted(hpat, key=lambda x: x.name) return set(self._apply_ranges(pattern, hpat))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hosts_in_unenumerated_pattern(self, pattern): """ Get all host names matching the pattern """
hosts = {} # ignore any negative checks here, this is handled elsewhere pattern = pattern.replace("!","").replace("&", "") groups = self.get_groups() for group in groups: for host in group.get_hosts(): if pattern == 'all' or self._match(group.name, pattern) or self._match(host.name, pattern): hosts[host.name] = host return sorted(hosts.values(), key=lambda x: x.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 restrict_to(self, restriction): """ Restrict list operations to the hosts given in restriction. This is used to exclude failed hosts in main playbook code, don't use this for other reasons. """
if type(restriction) != list: restriction = [ restriction ] self._restriction = restriction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def also_restrict_to(self, restriction): """ Works like restict_to but offers an additional restriction. Playbooks use this to implement serial behavior. """
if type(restriction) != list: restriction = [ restriction ] self._also_restriction = restriction
<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_file(self): """ did inventory come from a file? """
if not isinstance(self.host_list, basestring): return False return os.path.exists(self.host_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 register(tag, end_tag=None): """ Decorator for registering shortcode functions. """
def register_function(function): tagmap[tag] = {'func': function, 'endtag': end_tag} if end_tag: tagmap['endtags'].append(end_tag) return function return register_function
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_time_param(t): """Check whether a string sent in matches the ISO8601 format. If a Datetime object is passed instead, it will be converted into an ISO8601 compliant string. :param t: the datetime to check :type t: string or Datetime :rtype: string"""
if type(t) is str: if not ISO.match(t): raise ValueError('Date string "%s" does not match ISO8601 format' % (t)) return t else: return t.isoformat()
<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_iso_stamp(t, tz=None): """Convert a string in ISO8601 form into a Datetime object. This is mainly used for converting timestamps sent from the TempoDB API, which are assumed to be correct. :param string t: the timestamp to convert :rtype: Datetime object"""
if t is None: return None dt = dateutil.parser.parse(t) if tz is not None: timezone = pytz.timezone(tz) if dt.tzinfo is None: dt = timezone.localize(dt) return dt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next_weekday(weekday): """Returns the name of the weekday after the given weekday name."""
ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: return WEEKDAYS[0] return WEEKDAYS[ix+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 prev_weekday(weekday): """Returns the name of the weekday before the given weekday name."""
ix = WEEKDAYS.index(weekday) if ix == 0: return WEEKDAYS[len(WEEKDAYS)-1] return WEEKDAYS[ix-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 workdays(first_day=None): """Returns a list of workday names. Arguments --------- first_day : str, default None The first day of the five-day work week. If not given, 'Monday' is used. Returns ------- list A list of workday names. """
if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+5]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def weekdays(first_day=None): """Returns a list of weekday names. Arguments --------- first_day : str, default None The first day of the week. If not given, 'Monday' is used. Returns ------- list A list of weekday names. """
if first_day is None: first_day = 'Monday' ix = _lower_weekdays().index(first_day.lower()) return _double_weekdays()[ix:ix+7]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buyQuestItems(self): """ Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False """
for item in self.items: us = UserShopFront(self.usr, item.owner, item.id, str(item.price)) us.loadInventory() if not item.name in us.inventory: return False if not us.inventory[item.name].buy(): 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 submitQuest(self): """ Submits the active quest, returns result Returns bool - True if successful, otherwise False """
form = pg.form(action="kitchen2.phtml") pg = form.submit() if "Woohoo" in pg.content: try: self.prize = pg.find(text = "The Chef waves his hands, and you may collect your prize...").parent.parent.find_all("b")[-1].text except Exception: logging.getLogger("neolib.quest").exception("Failed to parse kitchen quest prize", {'pg': pg}) raise parseException return True else: logging.getLogger("neolib.quest").info("Failed to complete kitchen quest", {'pg': pg}) 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 youtube(no_controls, no_autoplay, store, store_name, youtube_url): """Convert a Youtube URL so that works correctly with Helium. This command is used for converting the URL for a Youtube video that is part of a playlist so that Helium recognises it as a playlist and when the video ends it correctly moves onto the next video in the playlist. :param youtube_url: the URL of the playlist youtube video. :type youtube_url: str """
old_url_colour = 'blue' new_url_colour = 'green' echo('Format --> {0}: {1}'.format( style('Original URL/Stored Title', fg=old_url_colour), style('New URL', fg=new_url_colour) )) for url in youtube_url: new_url = convert_youtube_url(url, no_controls, no_autoplay) if store: if store_name is not None: url = store_name store_data({url: new_url}) echo('{}: {}'.format( style(url, fg=old_url_colour), style(new_url, fg=new_url_colour) ))
<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(): """Use this function to display all of the stored URLs. This command is used for displaying all of the URLs and their names from the stored list. """
for name, url in get_all_data().items(): echo('{}: {}'.format( style(name, fg='blue'), style(url, fg='green') ))
<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_class_by_path(class_path: str, is_module: Optional[bool] = False) -> type: """ Get class by its name within a package structure. :param class_path: E.g. brandt.some.module.ClassName :param is_module: Whether last item is module rather than class name :return: Class ready to be instantiated. """
if is_module: try: backend_module = importlib.import_module(class_path) except ImportError: logger.warning("Can't import backend with name `%s`", class_path) raise else: return backend_module module_name, class_name = class_path.rsplit('.', 1) try: backend_module = importlib.import_module(module_name) except ImportError: logger.error("Can't import backend with name `%s`", module_name) raise try: backend_class = getattr(backend_module, class_name) except AttributeError: logger.error("Can't get backend class `%s` from `%s`", class_name, module_name) raise return backend_class
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """Get list of submodules for some package by its path. E.g ``pkg.subpackage``"""
pkg = importlib.import_module(package_path) subs = ( ModuleDescription( name=modname, path="{}.{}".format(package_path, modname), is_package=ispkg ) for importer, modname, ispkg in pkgutil.iter_modules(pkg.__path__) ) result = tuple(subs) 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: """ Makes tuple to use in Django's Fields ``choices`` attribute. Enum members names will be titles for the choices. :param source: Enum to process. :return: Tuple to put into ``choices`` """
result = tuple((s.value, s.name.title()) for s in source) 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 is_contradictory(self, other): """ Returns True if the two DictCells are unmergeable. """
if not isinstance(other, DictCell): raise Exception("Incomparable") for key, val in self: if key in other.__dict__['p'] \ and val.is_contradictory(other.__dict__['p'][key]): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ This method converts the DictCell into a python `dict`. This is useful for JSON serialization. """
output = {} for key, value in self.__dict__['p'].iteritems(): if value is None or isinstance(value, SIMPLE_TYPES): output[key] = value elif hasattr(value, 'to_dot'): output[key] = value.to_dot() elif hasattr(value, 'to_dict'): output[key] = value.to_dict() elif isinstance(value, datetime.date): # Convert date/datetime to ms-since-epoch ("new Date()"). ms = time.mktime(value.utctimetuple()) * 1000 ms += getattr(value, 'microseconds', 0) / 1000 output[key] = int(ms) elif isinstance(value, dict): output[key] = [] else: raise ValueError('cannot encode ' + repr(key)) return 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 to_latex(self): """ Returns a LaTeX representation of an attribute-value matrix """
latex = r"[{} " for attribute, value in self: if attribute in ['speaker_model', 'is_in_commonground']: continue value_l = value.to_latex() if value_l == "": continue latex += "{attribute:<15} & {value:<20} \\\\ \n".format(attribute=attribute, value=value_l) latex += "]\n" return latex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def business_days(start, stop): """ Return business days between two inclusive dates - ignoring public holidays. Note that start must be less than stop or else 0 is returned. @param start: Start date @param stop: Stop date @return int """
dates=rrule.rruleset() # Get dates between start/stop (which are inclusive) dates.rrule(rrule.rrule(rrule.DAILY, dtstart=start, until=stop)) # Exclude Sat/Sun dates.exrule(rrule.rrule(rrule.DAILY, byweekday=(rrule.SA, rrule.SU), dtstart=start)) return dates.count()
<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_anniversary_periods(start, finish, anniversary=1): """ Return a list of anniversaries periods between start and finish. """
import sys current = start periods = [] while current <= finish: (period_start, period_finish) = date_period(DATE_FREQUENCY_MONTHLY, anniversary, current) current = period_start + relativedelta(months=+1) period_start = period_start if period_start > start else start period_finish = period_finish if period_finish < finish else finish periods.append((period_start, period_finish)) return periods
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def previous_quarter(d): """ Retrieve the previous quarter for dt """
from django_toolkit.datetime_util import quarter as datetime_quarter return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_field_changed(instance, old_instance, field_name, update_fields=None): """ Examines update_fields and an attribute of an instance to determine if that attribute has changed prior to the instance being saved. Parameters field_name : str instance : object old_instance : object update_fields : list of str, optional """
if update_fields is not None and field_name not in update_fields: return False return getattr(instance, field_name) != getattr(old_instance, field_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 play(self): """Play the match. This match simulator iterates through two lists of random numbers 25 times, one for each team, comparing the numbers and awarding a point to the team with the higher number. The team with more points at the end of the lists wins and is recorded in the winner field. If the result is a draw, the winner field is set to None. @return: The winner (or None if the result is a draw) @rtype: An object that can be converted to a string or NoneType """
score1 = 0 score2 = 0 for __ in range(25): num1 = random.randint(0, 100) num2 = random.randint(0, 100) if num1 > num2: score1 += 1 elif num2 > num1: score2 += 1 if score1 > score2: self.winner = self.team1 self.loser = self.team2 self.drawn = False elif score2 > score1: self.winner = self.team2 self.loser = self.team1 self.drawn = False else: self.winner = None self.loser = None self.drawn = True self.score1 = score1 self.score2 = score2 return self.winner
<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_logger(name, formatter=None, handler=None, level=None): """ Returns a new logger for the specified name. """
logger = logging.getLogger(name) #: remove existing handlers logger.handlers = [] #: use a standard out handler if handler is None: handler = logging.StreamHandler(sys.stdout) #: set the formatter when a formatter is given if formatter is not None: handler.setFormatter(formatter) #: set DEBUG level if no level is specified if level is None: level = logging.DEBUG handler.setLevel(level) logger.setLevel(level) logger.addHandler(handler) return logger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def splitstatus(a,statusfn): 'split sequence into subsequences based on binary condition statusfn. a is a list, returns list of lists' groups=[]; mode=None for elt,status in zip(a,map(statusfn,a)): assert isinstance(status,bool) if status!=mode: mode=status; group=[mode]; groups.append(group) group.append(elt) return groups
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def ungroupslice(groups,gslice): 'this is a helper for contigsub.' 'coordinate transform: takes a match from seqingroups() and transforms to ungrouped coordinates' eltsbefore=0 for i in range(gslice[0]): eltsbefore+=len(groups[i])-1 x=eltsbefore+gslice[1]; return [x-1,x+gslice[2]-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 translate_diff(origtext,deltas): 'take diff run on separated words and convert the deltas to character offsets' lens=[0]+cumsum(map(len,splitpreserve(origtext))) # [0] at the head for like 'length before' return [Delta(lens[a],lens[b],''.join(replace)) for a,b,replace in deltas]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def word_diff(a,b): 'do diff on words but return character offsets' return translate_diff(a,rediff(splitpreserve(a),splitpreserve(b)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def checkdiff(a,b,sp=True): 'take diff of a to b, apply to a, return the applied diff so external code can check it against b' if sp: a=splitpreserve(a); b=splitpreserve(b) res=applydiff(a,rediff(a,b)) if sp: res=''.join(res) return res
<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(cls, source, *, transform_args=None): """Create an instance of the class from the source. By default cls.transform_args is used, but can be overridden by passing in transform_args. """
if transform_args is None: transform_args = cls.transform_args return cls(get_obj(source, *transform_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 map(cls, sources, *, transform_args=None): """Generates instances from the sources using either cls.transform_args or transform_args argument if present. """
for idx, source in enumerate(sources): try: yield cls.create(source, transform_args=transform_args) except Exception as ex: raise Exception("An error occurred with item {0}".format(idx)) from 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 save(self, *args, **kwargs): """ Set the current site ID, and ``is_public`` based on the setting ``COMMENTS_DEFAULT_APPROVED``. """
if not self.id: self.is_public = settings.COMMENTS_DEFAULT_APPROVED self.site_id = current_site_id() super(ThreadedComment, self).save(*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 save(self, *args, **kwargs): """ Validate that the rating falls between the min and max values. """
valid = map(str, settings.RATINGS_RANGE) if str(self.value) not in valid: raise ValueError("Invalid rating. %s is not in %s" % (self.value, ", ".join(valid))) super(Rating, self).save(*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 add_mutex_switch(parser, dest, arguments=set(), default=None, single_arg=False, required=False): """Adds mutually exclusive switch arguments. Args: arguments: a dictionary that maps switch name to helper text. Use sets to skip help texts. """
if default is not None: assert default in arguments if isinstance(arguments, set): arguments = {k: None for k in arguments} if not single_arg: mg = parser.add_mutually_exclusive_group(required=required) for name, help_text in arguments.items(): kwargs = { "action": "store_const", "dest": dest, "const": name, "help": help_text } if default == name: kwargs["default"] = name mg.add_argument("--{}".format(name), **kwargs) return mg else: kwargs = { "dest": dest, "type": str, "default": default, "help": "\n".join("{}: {}".format(k, v) for k, v in arguments.items()), "choices": list(arguments.keys()) } return parser.add_argument("--{}".format(dest), **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 _save_action(extra_context=None): ''' Save list of revisions revisions for active Conda environment. .. versionchanged:: 0.18 Compress action revision files using ``bz2`` to save disk space. Parameters ---------- extra_context : dict, optional Extra content to store in stored action revision. Returns ------- path_helpers.path, dict Path to which action was written and action object, including list of revisions for active Conda environment. ''' # Get list of revisions to Conda environment since creation. revisions_js = ch.conda_exec('list', '--revisions', '--json', verbose=False) revisions = json.loads(revisions_js) # Save list of revisions to `/etc/microdrop/plugins/actions/rev<rev>.json` # See [wheeler-microfluidics/microdrop#200][i200]. # # [i200]: https://github.com/wheeler-microfluidics/microdrop/issues/200 action = extra_context.copy() if extra_context else {} action['revisions'] = revisions action_path = (MICRODROP_CONDA_ACTIONS .joinpath('rev{}.json.bz2'.format(revisions[-1]['rev']))) action_path.parent.makedirs_p() # Compress action file using bz2 to save disk space. with bz2.BZ2File(action_path, mode='w') as output: json.dump(action, output, indent=2) return action_path, action
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def available_packages(*args, **kwargs): ''' Query available plugin packages based on specified Conda channels. Parameters ---------- *args Extra arguments to pass to Conda ``search`` command. Returns ------- dict .. versionchanged:: 0.24 All Conda packages beginning with ``microdrop.`` prefix from all configured channels. Each *key* corresponds to a package name. Each *value* corresponds to a ``list`` of dictionaries, each corresponding to an available version of the respective package. For example: { "microdrop.dmf-device-ui-plugin": [ ... { ... "build_number": 0, "channel": "microdrop-plugins", "installed": true, "license": "BSD", "name": "microdrop.dmf-device-ui-plugin", "size": 62973, "version": "2.1.post2", ... }, ...], ... } ''' # Get list of available MicroDrop plugins, i.e., Conda packages that start # with the prefix `microdrop.`. try: plugin_packages_info_json = ch.conda_exec('search', '--json', '^microdrop\.', verbose=False) return json.loads(plugin_packages_info_json) except RuntimeError, exception: if 'CondaHTTPError' in str(exception): logger.warning('Could not connect to Conda server.') else: logger.warning('Error querying available MicroDrop plugins.', exc_info=True) except Exception, exception: logger.warning('Error querying available MicroDrop plugins.', exc_info=True) 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 install(plugin_name, *args, **kwargs): ''' Install plugin packages based on specified Conda channels. .. versionchanged:: 0.19.1 Do not save rollback info on dry-run. .. versionchanged:: 0.24 Remove channels argument. Use Conda channels as configured in Conda environment. Note that channels can still be explicitly set through :data:`*args`. Parameters ---------- plugin_name : str or list Plugin package(s) to install. Version specifiers are also supported, e.g., ``package >=1.0.5``. *args Extra arguments to pass to Conda ``install`` command. Returns ------- dict Conda installation log object (from JSON Conda install output). ''' if isinstance(plugin_name, types.StringTypes): plugin_name = [plugin_name] # Perform installation conda_args = (['install', '-y', '--json'] + list(args) + plugin_name) install_log_js = ch.conda_exec(*conda_args, verbose=False) install_log = json.loads(install_log_js.split('\x00')[-1]) if 'actions' in install_log and not install_log.get('dry_run'): # Install command modified Conda environment. _save_action({'conda_args': conda_args, 'install_log': install_log}) logger.debug('Installed plugin(s): ```%s```', install_log['actions']) return install_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 uninstall(plugin_name, *args): ''' Uninstall plugin packages. Plugin packages must have a directory with the same name as the package in the following directory: <conda prefix>/share/microdrop/plugins/available/ Parameters ---------- plugin_name : str or list Plugin package(s) to uninstall. *args Extra arguments to pass to Conda ``uninstall`` command. Returns ------- dict Conda uninstallation log object (from JSON Conda uninstall output). ''' if isinstance(plugin_name, types.StringTypes): plugin_name = [plugin_name] available_path = MICRODROP_CONDA_SHARE.joinpath('plugins', 'available') for name_i in plugin_name: plugin_module_i = name_i.split('.')[-1].replace('-', '_') plugin_path_i = available_path.joinpath(plugin_module_i) if not _islinklike(plugin_path_i) and not plugin_path_i.isdir(): raise IOError('Plugin `{}` not found in `{}`' .format(name_i, available_path)) else: logging.debug('[uninstall] Found plugin `%s`', plugin_path_i) # Perform uninstall operation. conda_args = ['uninstall', '--json', '-y'] + list(args) + plugin_name uninstall_log_js = ch.conda_exec(*conda_args, verbose=False) # Remove broken links in `<conda prefix>/etc/microdrop/plugins/enabled/`, # since uninstall may have made one or more packages unavailable. _remove_broken_links() logger.debug('Uninstalled plugins: ```%s```', plugin_name) return json.loads(uninstall_log_js.split('\x00')[-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 import_plugin(package_name, include_available=False): ''' Import MicroDrop plugin. Parameters ---------- package_name : str Name of MicroDrop plugin Conda package. include_available : bool, optional If ``True``, import from all available plugins (not just **enabled** ones). By default, only the ``<conda>/etc/microdrop/plugins/enabled`` directory is added to the Python import paths (if necessary). If ``True``, also add the ``<conda>/share/microdrop/plugins/available`` directory to the Python import paths. Returns ------- module Imported plugin module. ''' available_plugins_dir = MICRODROP_CONDA_SHARE.joinpath('plugins', 'available') enabled_plugins_dir = MICRODROP_CONDA_ETC.joinpath('plugins', 'enabled') search_paths = [enabled_plugins_dir] if include_available: search_paths += [available_plugins_dir] for dir_i in search_paths: if dir_i not in sys.path: sys.path.insert(0, dir_i) module_name = package_name.split('.')[-1].replace('-', '_') return importlib.import_module(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 attach_related(self, filename=None, content=None, mimetype=None): """ Attaches a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass it is inserted directly into the resulting message attachments. """
if isinstance(filename, MIMEBase): assert content == mimetype == None self.related_attachments.append(filename) else: assert content is not None self.related_attachments.append((filename, content, mimetype))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_related_file(self, path, mimetype=None): """Attaches a file from the filesystem."""
filename = os.path.basename(path) content = open(path, 'rb').read() self.attach_related(filename, content, mimetype)
<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_dat_file(self): """ Create and write empty data file in the data directory """
output = "## {}\n".format(self.name) try: kwargs_items = self.kwargs.iteritems() except AttributeError: kwargs_items = self.kwargs.items() for key, val in kwargs_items: if val is "l": output += "#l {}=\n".format(str(key)) elif val is "f" or True: output += "#f {}=\n".format(str(key)) comment = "## " + "\t".join(["col{" + str(i) + ":d}" for i in range(self.argnum)]) comment += "\n" rangeargnum = range(self.argnum) output += comment.format(*rangeargnum) if os.path.isfile(self.location_dat): files = glob.glob(self.location_dat + "*") count = 2 while ( (self.location_dat + str(count) in files) ) and (count <= 10): count += 1 os.rename(self.location_dat, self.location_dat + str(count)) dat_file = open(self.location_dat, "wb") dat_file.write(output) dat_file.close()
<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_to_internal(self, data=None): """parse to internal """
if data is None: f = open(self.location_dat, "rb") data = { "PMCA SPECTRUM": {}, "DATA": [], "DP5 CONFIGURATION": {}, "DPP STATUS": {} } delimiter = { "PMCA SPECTRUM": " - ", "DP5 CONFIGURATION": "=", "DPP STATUS": ":" } comments = { "PMCA SPECTRUM": None, "DP5 CONFIGURATION": ";", "DPP STATUS": None } for e in f: if "<<" in e: if "<<END>>" in e: current = None elif "<<PMCA SPECTRUM>>" in e: current = "PMCA SPECTRUM" elif "<<DATA>>" in e: current = "DATA" elif "<<DP5 CONFIGURATION>>" in e: current = "DP5 CONFIGURATION" elif "<<DPP STATUS>>" in e: current = "DPP STATUS" elif "<<ROI>>" in e: current = "ROI" else: if current == "DATA": data["DATA"].append(float(e)) elif current == "ROI": continue elif current is not None: e = e.split("\r\n")[0] if comments[current] is not None: e = e.split(comments[current], 1)[0] e_list = e.split(delimiter[current], 1) data[current][e_list[0]] = e_list[1] f.close() self.save_to_internal(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 parse_data_to_internal(self, data=None): """Use numpy loadtxt """
if data is None: kwargs = self.kwargs data = np.loadtxt( open(self.location_dat, "rb"), **kwargs ) if self.filetype is "pickle": pickle.dump(data, open(self.location_internal, "wb")) elif self.filetype is "hickle": import hickle hickle.dump(data, open(self.location_internal, "wb")) else: raise ValueError( "Invalid filetype {} (must be {} or {})".format( self.filetype, "pickle", "hickle" ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ctx_provider(self, func): """ Decorator for adding a context provider. :: @jade.ctx_provider def my_context(): """
func = to_coroutine(func) self.providers.append(func) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, func): """ Register function to templates. """
if callable(func): self.functions[func.__name__] = func return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, path, **context): """ Render a template with context. """
funcs = self.functions ctx = dict(self.functions, jdebug=lambda: dict( (k, v) for k, v in ctx.items() if k not in funcs and k != 'jdebug')) for provider in self.providers: _ctx = yield from provider() ctx.update(_ctx) ctx.update(context) template = self.env.get_template(path) return self.env.render(template, **ctx)
<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_template(self, path): """ Load and compile a template. """
if not path.startswith('/'): for folder in self.options['template_folders']: fullpath = op.join(folder, path) if op.exists(fullpath): path = fullpath break else: raise JadeException('Template doesnt exist: %s' % path) with open(path, 'rb') as f: source = f.read().decode(self.options['encoding']) return ExtendCompiler( pyjade.parser.Parser(source).parse(), pretty=self.options['pretty'], env=self, compileDebug=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 set_size(self, data_size): """ Set the data slice size. """
if len(str(data_size)) > self.first: raise ValueError( 'Send size is too large for message size-field width!') self.data_size = data_size
<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_related(parent_entry, child_entry): '''This function checks if a child entry is related to the parent entry. This is done by comparing the reference and sequence numbers.''' if parent_entry.header.mft_record == child_entry.header.base_record_ref and \ parent_entry.header.seq_number == child_entry.header.base_record_seq: return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_mp(cls, file_pointer, _mft_config=None): '''The initialization process takes a file like object "file_pointer" and loads it in the internal structures. "use_cores" can be definied if multiple cores are to be used. The "size" argument is the size of the MFT entries. If not provided, the class will try to auto detect it. ''' import multiprocessing import queue mft_config = _mft_config if _mft_config is not None else MFT.mft_config mft_entry_size = mft_config["entry_size"] #self.entries = {} if not mft_entry_size: mft_entry_size = MFT._find_mft_size(file_pointer) file_size = _get_file_size(file_pointer) if (file_size % mft_entry_size): #TODO error handling (file size not multiple of mft size) MOD_LOGGER.error("Unexpected file size. It is not multiple of the MFT entry size.") end = int(file_size / mft_entry_size) #setup the multiprocessing stuff queue_size = 10 n_processes = 3 manager = multiprocessing.Manager() buffer_queue_in = manager.Queue(queue_size) buffer_queue_out = manager.Queue(queue_size) entries = manager.dict() temp_entries = manager.list() processes = [multiprocessing.Process(target=MFT._load_entry, args=(mft_config, buffer_queue_in, buffer_queue_out, entries, temp_entries)) for i in range(n_processes)] for p in processes: p.start() for i in range(queue_size): buffer_queue_out.put(bytearray(mft_entry_size)) #start the game for i in range(0, end): try: data_buffer = buffer_queue_out.get(timeout=1) file_pointer.readinto(data_buffer) buffer_queue_in.put((i, data_buffer)) #print("adding", i) except queue.Empty as e: print("DAMN") raise for i in range(queue_size): buffer_queue_in.put((-1, None)) for p in processes: p.join() print("LOADING DONE") #process the temporary list and add it to the "model" for entry in temp_entries: base_record_ref = entry.header.base_record_ref if base_record_ref in entries: #if the parent entry has been loaded if MFT._is_related(entries[base_record_ref], entry): entries[base_record_ref].copy_attributes(entry) else: #can happen when you have an orphan entry entries[i] = entry
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def finddives2(depths, min_dive_thresh=10): '''Find dives in depth data below a minimum dive threshold Args ---- depths: ndarray Datalogger depth measurements min_dive_thresh: float Minimum depth threshold for which to classify a dive Returns ------- dives: ndarray Dive summary information in a numpy record array *Columns*: * dive_id * start_idx * stop_idx * dive_dur * depth_max * depth_max_i * depth_min * depth_min_i * depth_mean * comp_mean dive_mask: ndarray Boolean mask array over depth data. Cells with `True` are dives and cells with `False` are not. ''' import numpy import pandas from . import utils # Get start and stop indices for each dive above `min_dive_thresh` condition = depths > min_dive_thresh ind_start, ind_end = utils.contiguous_regions(condition) n_dives = len(ind_start) dive_mask = numpy.zeros(len(depths), dtype=bool) dtypes = numpy.dtype([('dive_id', int), ('start_idx', int), ('stop_idx', int), ('dive_dur', int), ('depth_max', float), ('depth_max_idx', float), ('depth_min', float), ('depth_min_idx', float), ('depth_mean', float), ('comp_mean', float),]) dive_data = numpy.zeros(n_dives, dtype=dtypes) for i in range(n_dives): dive_mask[ind_start[i]:ind_end[i]] = True dive_depths = depths[ind_start[i]:ind_end[i]] dive_data['dive_id'][i] = i dive_data['start_idx'][i] = ind_start[i] dive_data['stop_idx'][i] = ind_end[i] dive_data['dive_dur'][i] = ind_end[i] - ind_start[i] dive_data['depth_max'][i] = dive_depths.max() dive_data['depth_max_idx'][i] = numpy.argmax(dive_depths) dive_data['depth_min'][i] = dive_depths.min() dive_data['depth_min_idx'][i] = numpy.argmin(dive_depths) dive_data['depth_mean'][i] = numpy.mean(dive_depths) # TODO Supposedly time of deepest dive... doesn't appear to be that dive_data['comp_mean'][i] = numpy.mean(1 + (1/(0.1*dive_depths))) # Filter any dives with an endpoint with an index beyond bounds of array dive_data = dive_data[dive_data['stop_idx'] < len(depths)] # Create pandas data frame with following columns, init'd with nans dives = pandas.DataFrame(dive_data) return dives, dive_mask
<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_des_asc2(depths, dive_mask, pitch, cutoff, fs, order=5): '''Get boolean masks of descents and ascents in the depth data Args ---- dive_mask: ndarray Boolean mask array over depth data. Cells with `True` are dives and cells with `False` are not. pitch: ndarray Pitch angle in radians cutoff: float Cutoff frequency at which signal will be filtered fs: float Sampling frequency order: int Order of butter filter to apply Returns ------- des_mask: ndarray Boolean mask of descents in the depth data asc_mask: ndarray Boolean mask of ascents in the depth data ''' import numpy from . import dsp asc_mask = numpy.zeros(len(depths), dtype=bool) des_mask = numpy.zeros(len(depths), dtype=bool) b, a = dsp.butter_filter(cutoff, fs, order, 'low') dfilt = dsp.butter_apply(b, a, depths) dp = numpy.hstack([numpy.diff(dfilt), 0]) asc_mask[dive_mask] = dp[dive_mask] < 0 des_mask[dive_mask] = dp[dive_mask] > 0 # Remove descents/ascents withough a corresponding ascent/descent des_mask, asc_mask = rm_incomplete_des_asc(des_mask, asc_mask) return des_mask, asc_mask
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rm_incomplete_des_asc(des_mask, asc_mask): '''Remove descents-ascents that have no corresponding ascent-descent Args ---- des_mask: ndarray Boolean mask of descents in the depth data asc_mask: ndarray Boolean mask of ascents in the depth data Returns ------- des_mask: ndarray Boolean mask of descents with erroneous regions removed asc_mask: ndarray Boolean mask of ascents with erroneous regions removed ''' from . import utils # Get start/stop indices for descents and ascents des_start, des_stop = utils.contiguous_regions(des_mask) asc_start, asc_stop = utils.contiguous_regions(asc_mask) des_mask = utils.rm_regions(des_mask, asc_mask, des_start, des_stop) asc_mask = utils.rm_regions(asc_mask, des_mask, asc_start, asc_stop) return des_mask, asc_mask
<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_bottom(depths, des_mask, asc_mask): '''Get boolean mask of regions in depths the animal is at the bottom Args ---- des_mask: ndarray Boolean mask of descents in the depth data asc_mask: ndarray Boolean mask of ascents in the depth data Returns ------- BOTTOM: ndarray (n,4) Indices and depths for when the animal is at the bottom *Index positions*: 0. start ind 1. depth at start 2. stop ind 3. depth at stop ''' import numpy from . import utils # Get start/stop indices for descents and ascents des_start, des_stop = utils.contiguous_regions(des_mask) asc_start, asc_stop = utils.contiguous_regions(asc_mask) # Bottom time is at stop of descent until start of ascent bottom_len = min(len(des_stop), len(asc_start)) bottom_start = des_stop[:bottom_len] bottom_stop = asc_start[:bottom_len] BOTTOM = numpy.zeros((len(bottom_start),4), dtype=float) # Time (seconds) at start of bottom phase/end of descent BOTTOM[:,0] = bottom_start # Depth (m) at start of bottom phase/end of descent BOTTOM[:,1] = depths[bottom_start] # Time (seconds) at end of bottom phase/start of asscent BOTTOM[:,2] = bottom_stop # Depth (m) at end of bottom phase/start of descent BOTTOM[:,3] = depths[bottom_stop] return BOTTOM
<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_phase(n_samples, des_mask, asc_mask): '''Get the directional phase sign for each sample in depths Args ---- n_samples: int Length of output phase array des_mask: numpy.ndarray, shape (n,) Boolean mask of values where animal is descending asc_mask: numpy.ndarray, shape(n,) Boolean mask of values where animal is ascending Returns ------- phase: numpy.ndarray, shape (n,) Signed integer array values representing animal's dive phase *Phases*: * 0: neither ascending/descending * 1: ascending * -1: descending. ''' import numpy phase = numpy.zeros(n_samples, dtype=int) phase[asc_mask] = 1 phase[des_mask] = -1 return phase
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tempfilename(**kwargs): """ Reserve a temporary file for future use. This is useful if you want to get a temporary file name, write to it in the future and ensure that if an exception is thrown the temporary file is removed. """
kwargs.update(delete=False) try: f = NamedTemporaryFile(**kwargs) f.close() yield f.name except Exception: if os.path.exists(f.name): # Ensure we clean up after ourself os.unlink(f.name) raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makedirs(p): """ A makedirs that avoids a race conditions for multiple processes attempting to create the same directory. """
try: os.makedirs(p, settings.FILE_UPLOAD_PERMISSIONS) except OSError: # Perhaps someone beat us to the punch? if not os.path.isdir(p): # Nope, must be something else... raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def control_high_limit(self) -> Optional[Union[int, float]]: """ Control high limit setting for a special sensor. For LS-10/LS-20 base units only. """
return self._get_field_value(SpecialDevice.PROP_CONTROL_HIGH_LIMIT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def control_low_limit(self) -> Optional[Union[int, float]]: """ Control low limit setting for a special sensor. For LS-10/LS-20 base units only. """
return self._get_field_value(SpecialDevice.PROP_CONTROL_LOW_LIMIT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_reading(self) -> Optional[Union[int, float]]: """Current reading for a special sensor."""
return self._get_field_value(SpecialDevice.PROP_CURRENT_READING)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def high_limit(self) -> Optional[Union[int, float]]: """ High limit setting for a special sensor. For LS-10/LS-20 base units this is the alarm high limit. For LS-30 base units, this is either alarm OR control high limit, as indicated by special_status ControlAlarm bit flag. """
return self._get_field_value(SpecialDevice.PROP_HIGH_LIMIT)
<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_limit(self) -> Optional[Union[int, float]]: """ Low limit setting for a special sensor. For LS-10/LS-20 base units this is the alarm low limit. For LS-30 base units, this is either alarm OR control low limit, as indicated by special_status ControlAlarm bit flag. """
return self._get_field_value(SpecialDevice.PROP_LOW_LIMIT)
<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, device_id: int) -> Optional[Device]: """Get device using the specified ID, or None if not found."""
return self._devices.get(device_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_ttv_yaml(corpora, path_to_ttv_file, ttv_ratio=DEFAULT_TTV_RATIO, deterministic=False): """ Create a test, train, validation from the corpora given and saves it as a YAML filename. Each set will be subject independent, meaning that no one subject can have data in more than one set # Arguments; corpora: a list of the paths to corpora used (these have to be formatted accoring to notes.md) path_to_ttv_file: the path to where the YAML file be be saved ttv_ratio: a tuple (e.g. (1,4,4) of the relative sizoe of each set) deterministic: whether or not to shuffle the resources around when making the set. """
dataset = get_dataset(corpora) data_sets = make_ttv(dataset, ttv_ratio=ttv_ratio, deterministic=deterministic) def get_for_ttv(key): return ( data_sets['test'][key], data_sets['train'][key], data_sets['validation'][key] ) test, train, validation = get_for_ttv('paths') number_of_files_for_each_set = list(get_for_ttv('number_of_files')) number_of_subjects_for_each_set = [len(x) for x in get_for_ttv('subjects')] dict_for_yaml = { 'split': number_of_files_for_each_set, 'subject_split': number_of_subjects_for_each_set, "test": test, "train": train, "validation": validation } with open(path_to_ttv_file, 'w') as f: yaml.dump(dict_for_yaml, f, 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 load_user_config(vcs): """Load the user config Args: vcs (easyci.vcs.base.Vcs) - the vcs object for the current project Returns: dict - the config Raises: ConfigFormatError ConfigNotFoundError """
config_path = os.path.join(vcs.path, 'eci.yaml') if not os.path.exists(config_path): raise ConfigNotFoundError with open(config_path, 'r') as f: try: config = yaml.safe_load(f) except yaml.YAMLError: raise ConfigFormatError if not isinstance(config, dict): raise ConfigFormatError for k, v in _default_config.iteritems(): config.setdefault(k, v) for k, v in _config_types.iteritems(): if not isinstance(config[k], v): raise ConfigFormatError return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expose_request(func): """ A decorator that adds an expose_request flag to the underlying callable. @raise TypeError: C{func} must be callable. """
if not python.callable(func): raise TypeError("func must be callable") if isinstance(func, types.UnboundMethodType): setattr(func.im_func, '_pyamf_expose_request', True) else: setattr(func, '_pyamf_expose_request', True) return func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addService(self, service, name=None, description=None, authenticator=None, expose_request=None, preprocessor=None): """ Adds a service to the gateway. @param service: The service to add to the gateway. @type service: C{callable}, class instance, or a module @param name: The name of the service. @type name: C{str} @raise pyamf.remoting.RemotingError: Service already exists. @raise TypeError: C{service} cannot be a scalar value. @raise TypeError: C{service} must be C{callable} or a module. """
if isinstance(service, (int, long, float, basestring)): raise TypeError("Service cannot be a scalar value") allowed_types = (types.ModuleType, types.FunctionType, types.DictType, types.MethodType, types.InstanceType, types.ObjectType) if not python.callable(service) and not isinstance(service, allowed_types): raise TypeError("Service must be a callable, module, or an object") if name is None: # TODO: include the module in the name if isinstance(service, (type, types.ClassType)): name = service.__name__ elif isinstance(service, types.FunctionType): name = service.func_name elif isinstance(service, types.ModuleType): name = service.__name__ else: name = str(service) if name in self.services: raise remoting.RemotingError("Service %s already exists" % name) self.services[name] = ServiceWrapper(service, description, authenticator, expose_request, preprocessor)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeService(self, service): """ Removes a service from the gateway. @param service: Either the name or t of the service to remove from the gateway, or . @type service: C{callable} or a class instance @raise NameError: Service not found. """
for name, wrapper in self.services.iteritems(): if service in (name, wrapper.service): del self.services[name] return raise NameError("Service %r not found" % (service,))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getServiceRequest(self, request, target): """ Returns a service based on the message. @raise UnknownServiceError: Unknown service. @param request: The AMF request. @type request: L{Request<pyamf.remoting.Request>} @rtype: L{ServiceRequest} """
try: return self._request_class( request.envelope, self.services[target], None) except KeyError: pass try: sp = target.split('.') name, meth = '.'.join(sp[:-1]), sp[-1] return self._request_class( request.envelope, self.services[name], meth) except (ValueError, KeyError): pass raise UnknownServiceError("Unknown service %s" % target)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getProcessor(self, request): """ Returns request processor. @param request: The AMF message. @type request: L{Request<remoting.Request>} """
if request.target == 'null' or not request.target: from pyamf.remoting import amf3 return amf3.RequestProcessor(self) else: from pyamf.remoting import amf0 return amf0.RequestProcessor(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 mustExposeRequest(self, service_request): """ Decides whether the underlying http request should be exposed as the first argument to the method call. This is granular, looking at the service method first, then at the service level and finally checking the gateway. @rtype: C{bool} """
expose_request = service_request.service.mustExposeRequest(service_request) if expose_request is None: if self.expose_request is None: return False return self.expose_request return expose_request
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def callServiceRequest(self, service_request, *args, **kwargs): """ Executes the service_request call """
if self.mustExposeRequest(service_request): http_request = kwargs.get('http_request', None) args = (http_request,) + args return service_request(*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 node_input(): """ Get a valid node id from the user. Return -1 if invalid """
try: node = int(raw_input("Node id: ")) except ValueError: node = INVALID_NODE print 'invalid node id: %s' % node return node
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def existing_node_input(): """ Get an existing node id by name or id. Return -1 if invalid """
input_from_user = raw_input("Existing node name or id: ") node_id = INVALID_NODE if not input_from_user: return node_id # int or str? try: parsed_input = int(input_from_user) except ValueError: parsed_input = input_from_user if isinstance(parsed_input, int): result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=parsed_input).fetchall() if result: node_id = int(result[0]['node_id']) else: result = db.execute(text(fetch_query_string('select_node_from_name.sql')), node_name=parsed_input).fetchall() if result: if len(result) == 1: print 'Node id: {node_id}\nNode name: {name}'.format(**result[0]) print '-------------' node_id = result[0]['node_id'] else: print 'Multiple nodes found with the name: {0}'.format(parsed_input) for item in result: print '{node_id}: {name} = {value}'.format(**item) node_selection = raw_input('Enter a node id from this list or enter "?" to render all or "?<node>" for a specific one.') if node_selection: node_selection_match = re.match(r"\?(\d)*", node_selection) if node_selection_match: if node_selection_match.groups()[0]: value = render_node(int(node_selection_match.groups()[0]), noderequest={'_no_template':True}, **result[0]) print safe_dump(value, default_flow_style=False) else: for item in result: value = render_node(item['node_id'], noderequest={'_no_template':True}, **item) print 'Node id: {0}'.format(item['node_id']) print safe_dump(value, default_flow_style=False) print '---' node_id = node_input() else: try: node_id = int(node_selection) except ValueError: node_id = INVALID_NODE print 'invalid node id: %s' % node return 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 render_value_for_node(node_id): """ Wrap render_node for usage in operate scripts. Returns without template rendered. """
value = None result = [] try: result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=node_id).fetchall() except DatabaseError as err: current_app.logger.error("DatabaseError: %s", err) if result: kw = dict(zip(result[0].keys(), result[0].values())) value = render_node(node_id, noderequest={'_no_template':True}, **kw) return 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 purge_collection(keys): "Recursive purge of nodes with name and id" for key in keys: m = re.match(r'(.*) \((\d+)\)', key) name = m.group(1) node_id = m.group(2) value = render_value_for_node(node_id) print 'remove node with name:{0} and id:{1}'.format(name, node_id) delete_node(node_id=node_id) if isinstance(value, dict): purge_collection(value.keys())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mode_new_collection(): """ Create a new collection of items with common attributes. """
print globals()['mode_new_collection'].__doc__ collection_name = raw_input("Collection name: ") item_attr_list = [] collection_node_id = None if collection_name: collection_node_id = insert_node(name=collection_name, value=None) insert_query(name='select_link_node_from_node.sql', node_id=collection_node_id) item_attr = True while item_attr: item_attr = raw_input("Add a collection item attribute name: ") if item_attr: item_attr_list.append(item_attr) # if no collection name then exit selection = collection_name while selection: selection = select([ 'Add item', ]) if selection == 'Add item': # create item add_item_with_attributes_to_collection( collection_name=collection_name, collection_node_id=collection_node_id, item_attr_list=item_attr_list) if collection_node_id: print "Added collection name '{0}' with node id: {1}".format(collection_name, collection_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 mode_database_functions(): "Select a function to perform from chill.database" print globals()['mode_database_functions'].__doc__ selection = True database_functions = [ 'init_db', 'insert_node', 'insert_node_node', 'delete_node', 'select_node', 'insert_route', 'insert_query', 'add_template_for_node', 'fetch_query_string', ] while selection: choices = database_functions + [ 'help', ] selection = select(choices) if selection: print globals().get(selection).__doc__ if selection == 'init_db': confirm = raw_input("Initialize new database y/n? [n] ") if confirm == 'y': init_db() elif selection == 'insert_node': name = raw_input("Node name: ") value = raw_input("Node value: ") node = insert_node(name=name, value=value or None) print "name: %s \nid: %s" % (name, node) elif selection == 'insert_query': sqlfile = choose_query_file() if sqlfile: node = existing_node_input() if node >= 0: insert_query(name=sqlfile, node_id=node) print "adding %s to node id: %s" % (sqlfile, node) elif selection == 'insert_node_node': print "Add parent node id" node = existing_node_input() print "Add target node id" target_node = existing_node_input() if node >= 0 and target_node >= 0: insert_node_node(node_id=node, target_node_id=target_node) elif selection == 'delete_node': node = existing_node_input() if node >= 0: delete_node(node_id=node) elif selection == 'select_node': node = existing_node_input() if node >= 0: result = select_node(node_id=node) print safe_dump(dict(zip(result[0].keys(), result[0].values())), default_flow_style=False) elif selection == 'insert_route': path = raw_input('path: ') weight = raw_input('weight: ') or None method = raw_input('method: ') or 'GET' node = existing_node_input() if node >= 0: insert_route(path=path, node_id=node, weight=weight, method=method) elif selection == 'add_template_for_node': folder = current_app.config.get('THEME_TEMPLATE_FOLDER') choices = map(os.path.basename, glob(os.path.join(folder, '*')) ) choices.sort() templatefile = select(choices) if templatefile: node = existing_node_input() if node >= 0: add_template_for_node(name=templatefile, node_id=node) print "adding %s to node id: %s" % (templatefile, node) elif selection == 'fetch_query_string': sqlfile = choose_query_file() if sqlfile: sql = fetch_query_string(sqlfile) print sql elif selection == 'help': print "------" for f in database_functions: print "\n** %s **" % f print globals().get(f).__doc__ print "------" else: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def operate_menu(): "Select between these operations on the database" selection = True while selection: print globals()['operate_menu'].__doc__ selection = select([ 'chill.database functions', 'execute sql file', 'render_node', 'New collection', 'Manage collection', 'Add document for node', 'help', ]) if selection == 'chill.database functions': mode_database_functions() elif selection == 'execute sql file': print "View the sql file and show a fill in the blanks interface with raw_input" sqlfile = choose_query_file() if not sqlfile: # return to the menu choices if not file picked selection = True else: sql_named_placeholders_re = re.compile(r":(\w+)") sql = fetch_query_string(sqlfile) placeholders = set(sql_named_placeholders_re.findall(sql)) print sql data = {} for placeholder in placeholders: value = raw_input(placeholder + ': ') data[placeholder] = value result = [] try: result = db.execute(text(sql), data) except DatabaseError as err: current_app.logger.error("DatabaseError: %s", err) if result and result.returns_rows: result = result.fetchall() print result if not result: print 'No results.' else: kw = result[0] if 'node_id' in kw: print 'render node %s' % kw['node_id'] value = render_node(kw['node_id'], **kw) print safe_dump(value, default_flow_style=False) else: #print safe_dump(rowify(result, [(x, None) for x in result[0].keys()]), default_flow_style=False) print safe_dump([dict(zip(x.keys(), x.values())) for x in result], default_flow_style=False) elif selection == 'render_node': print globals()['render_node'].__doc__ node_id = existing_node_input() value = render_value_for_node(node_id) print safe_dump(value, default_flow_style=False) elif selection == 'New collection': mode_new_collection() elif selection == 'Manage collection': mode_collection() elif selection == 'Add document for node': folder = current_app.config.get('DOCUMENT_FOLDER') if not folder: print "No DOCUMENT_FOLDER configured for the application." else: choices = map(os.path.basename, glob(os.path.join(folder, '*')) ) choices.sort() if len(choices) == 0: print "No files found in DOCUMENT_FOLDER." else: filename = select(choices) if filename: defaultname = os.path.splitext(filename)[0] nodename = raw_input("Enter name for node [{0}]: ".format(defaultname)) or defaultname node = insert_node(name=nodename, value=filename) print "Added document '%s' to node '%s' with id: %s" % (filename, nodename, node) elif selection == 'help': print "------" print __doc__ print "------" else: print 'Done'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def thread_local_property(name): '''Creates a thread local ``property``.''' name = '_thread_local_' + name def fget(self): try: return getattr(self, name).value except AttributeError: return None def fset(self, value): getattr(self, name).value = value return property(fget=fget, fset=fset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def kvlclient(self): '''Return a thread local ``kvlayer`` client.''' if self._kvlclient is None: self._kvlclient = kvlayer.client() return self._kvlclient
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def divide(self, data_source_factory): """Divides the task according to the number of workers."""
data_length = data_source_factory.length() data_interval_length = data_length / self.workers_number() + 1 current_index = 0 self.responses = [] while current_index < data_length: self.responses.append(0) offset = current_index limit = min((data_length - current_index, data_interval_length)) yield data_source_factory.part(limit, offset) current_index += limit
<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, data_source_factory, timeout=0, on_timeout="local_mode"): """Sends tasks to workers and awaits the responses. When all the responses are received, reduces them and returns the result. If timeout is set greater than 0, producer will quit waiting for workers when time has passed. If on_timeout is set to "local_mode", after the time limit producer will run tasks locally. If on_timeout is set to "fail", after the time limit producer raise TimeOutException. """
def local_launch(): print "Local launch" return self.reduce_fn( self.map_fn(data_source_factory.build_data_source()) ) if self.local_mode: return local_launch() for index, factory in enumerate(self.divide(data_source_factory)): self.unprocessed_request_num += 1 self.logging.info("Sending %d-th message with %d elements" % (index + 1, factory.length())) self.logging.info("len(data) = %d" % len(pickle.dumps(factory))) self.channel.basic_publish(exchange='', routing_key=self.routing_key(), properties=pika.BasicProperties( reply_to=self.callback_queue, correlation_id="_".join((self.correlation_id, str(index))), ), body=pickle.dumps(factory)) self.logging.info("Waiting...") time_limit_exceeded = [False] def on_timeout_func(): print "Timeout!!" self.logging.warning("Timeout!") time_limit_exceeded[0] = True if timeout > 0: self.timer = Timer(timeout, on_timeout_func) self.timer.start() while self.unprocessed_request_num: if time_limit_exceeded[0]: if on_timeout == "local_mode": return local_launch() assert on_timeout == "fail", "Invalid value for on_timeout: %s" % on_timeout raise TimeOutException() self.connection.process_data_events() self.logging.info("Responses: %s" % str(self.responses)) return self.reduce_fn(self.responses)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _orderedCleanDict(attrsObj): """ -> dict with false-values removed Also evaluates attr-instances for false-ness by looking at the values of their properties """
def _filt(k, v): if attr.has(v): return not not any(attr.astuple(v)) return not not v return attr.asdict(attrsObj, dict_factory=OrderedDict, recurse=False, filter=_filt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def representCleanOpenAPIOperation(dumper, data): """ Unpack nonstandard attributes while representing an OpenAPIOperation """
dct = _orderedCleanDict(data) if '_extended' in dct: for k, ext in list(data._extended.items()): dct[k] = ext del dct['_extended'] return dumper.yaml_representers[type(dct)](dumper, dct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def representCleanOpenAPIParameter(dumper, data): """ Rename python reserved keyword fields before representing an OpenAPIParameter """
dct = _orderedCleanDict(data) # We are using "in_" as a key for the "in" parameter, since in is a Python keyword. # To represent it correctly, we then have to swap "in_" for "in". # So we do an item-by-item copy of the dct so we don't change the order when # making this swap. d2 = OrderedDict() for k, v in dct.copy().items(): if k == 'in_': d2['in'] = v else: d2[k] = v return dumper.yaml_representers[type(d2)](dumper, d2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def representCleanOpenAPIObjects(dumper, data): """ Produce a representation of an OpenAPI object, removing empty attributes """
dct = _orderedCleanDict(data) return dumper.yaml_representers[type(dct)](dumper, dct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mediaTypeHelper(mediaType): """ Return a function that creates a Responses object; """
def _innerHelper(data=None): """ Create a Responses object that contains a MediaType entry of the specified mediaType Convenience function for the most common cases where you need an instance of Responses """ ret = OpenAPIResponses() if data is None: data = {} ret.default.content[mediaType] = data return ret return _innerHelper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_config_file_exists(): """ Makes sure the config file exists. :raises: :class:`epab.core.new_config.exc.ConfigFileNotFoundError` """
config_file = Path(ELIBConfig.config_file_path).absolute() if not config_file.exists(): raise ConfigFileNotFoundError(ELIBConfig.config_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 _relevant_checkers(self, path): """ Get set of checkers for the given path. TODO: currently this is based off the file extension. We would like to honor magic bits as well, so that python binaries, shell scripts, etc but we're not guaranteed that `path` currently exists on the filesystem -- e.g. when version control for historical revs is used. """
_, ext = os.path.splitext(path) ext = ext.lstrip('.') return checkers.checkers.get(ext, [])
<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_checkers(self): """ Print information about checkers and their external tools. Currently only works properly on systems with the `which` tool available. """
classes = set() for checker_group in checkers.checkers.itervalues(): for checker in checker_group: classes.add(checker) max_width = 0 for clazz in classes: max_width = max(max_width, len(clazz.tool), len(clazz.__name__)) for clazz in sorted(classes): status, _ = commands.getstatusoutput('which %s' % clazz.tool) result = 'missing' if status else 'installed' version = '' if status else clazz.get_version() print '%s%s%s%s' % ( clazz.__name__.ljust(max_width + 1), clazz.tool.ljust(max_width + 1), result.ljust(max_width + 1), version, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _should_ignore(self, path): """ Return True iff path should be ignored. """
for ignore in self.options.ignores: if fnmatch.fnmatch(path, ignore): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def legacy_notes_view(request): """ View to see legacy notes. """
notes = TeacherNote.objects.all() note_count = notes.count() paginator = Paginator(notes, 100) page = request.GET.get('page') try: notes = paginator.page(page) except PageNotAnInteger: notes = paginator.page(1) except EmptyPage: notes = paginator.page(paginator.num_pages) return render_to_response( 'teacher_notes.html', {'page_name': "Legacy Notes", 'notes': notes, 'note_count': note_count,}, context_instance=RequestContext(request) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def legacy_events_view(request): """ View to see legacy events. """
events = TeacherEvent.objects.all() event_count = events.count() paginator = Paginator(events, 100) page = request.GET.get('page') try: events = paginator.page(page) except PageNotAnInteger: events = paginator.page(1) except EmptyPage: events = paginator.page(paginator.num_pages) return render_to_response( 'teacher_events.html', {'page_name': "Legacy Events", 'events': events, 'event_count': event_count,}, context_instance=RequestContext(request) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def legacy_requests_view(request, rtype): """ View to see legacy requests of rtype request type, which should be either 'food' or 'maintenance'. """
if not rtype in ['food', 'maintenance']: raise Http404 requests_dict = [] # [(req, [req_responses]), (req2, [req2_responses]), ...] requests = TeacherRequest.objects.filter(request_type=rtype) request_count = requests.count() paginator = Paginator(requests, 50) page = request.GET.get('page') try: requests = paginator.page(page) except PageNotAnInteger: requests = paginator.page(1) except EmptyPage: requests = paginator.page(paginator.num_pages) for req in requests: requests_dict.append( (req, TeacherResponse.objects.filter(request=req),) ) return render_to_response( 'teacher_requests.html', {'page_name': "Legacy {rtype} Requests".format(rtype=rtype.title()), 'requests_dict': requests_dict, 'requests': requests, 'request_type': rtype.title(), 'request_count': request_count,}, context_instance=RequestContext(request) )