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 expand_groups(config_ids, maps): """ Iterates over a list of container configuration ids, expanding groups of container configurations. :param config_ids: Li...
for config_id in config_ids: if config_id.map_name == '__all__': c_maps = six.iteritems(maps) else: c_maps = (config_id.map_name, maps[config_id.map_name]), if isinstance(config_id, InputConfigId): instance_name = config_id.instance_names elif isi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand_instances(config_ids, ext_maps): """ Iterates over a list of input configuration ids, expanding configured instances if ``None`` is specified. Otherwi...
for type_map_config, items in itertools.groupby(sorted(config_ids, key=get_map_config), get_map_config): config_type, map_name, config_name = type_map_config instances = _get_nested_instances(items) c_map = ext_maps[map_name] try: c_instances = _get_config_instances(conf...
<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_network(self, action, n_name, **kwargs): """ Creates a configured network. :param action: Action configuration. :type action: dockermap.map.runner.Act...
c_kwargs = self.get_network_create_kwargs(action, n_name, **kwargs) res = action.client.create_network(**c_kwargs) self._policy.network_names[action.client_name][n_name] = res['Id'] 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 remove_network(self, action, n_name, **kwargs): """ Removes a network. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :...
c_kwargs = self.get_network_remove_kwargs(action, n_name, **kwargs) res = action.client.remove_network(**c_kwargs) del self._policy.network_names[action.client_name][n_name] 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 get_container_create_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to create a container. :param a...
policy = self._policy client_config = action.client_config container_map = action.container_map container_config = action.config image_tag = container_map.get_image(container_config.image or action.config_id.config_name) default_paths = policy.default_volume_paths[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 get_attached_container_create_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to create an attached ...
client_config = action.client_config policy = self._policy config_id = action.config_id path = resolve_value(policy.default_volume_paths[config_id.map_name][config_id.instance_name]) user = extract_user(action.config.user) c_kwargs = dict( name=container_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 get_attached_container_host_config_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to set up the Hos...
if container_name: c_kwargs = {'container': container_name} else: c_kwargs = {} update_kwargs(c_kwargs, kwargs) return c_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 get_container_update_kwargs(self, action, container_name, update_values, kwargs=None): """ Generates keyword arguments for the Docker client to update the Ho...
c_kwargs = dict(container=container_name) update_kwargs(c_kwargs, update_values, kwargs) return c_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 get_container_wait_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to wait for a container. :param a...
c_kwargs = dict(container=container_name) timeout = action.client_config.get('wait_timeout') if timeout is not None: c_kwargs['timeout'] = timeout update_kwargs(c_kwargs, kwargs) return c_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 get_container_stop_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to stop a container. :param actio...
c_kwargs = dict( container=container_name, ) stop_timeout = action.config.stop_timeout if stop_timeout is NotSet: timeout = action.client_config.get('stop_timeout') if timeout is not None: c_kwargs['timeout'] = timeout elif sto...
<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_remove_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to remove a container. :param a...
c_kwargs = dict(container=container_name) update_kwargs(c_kwargs, kwargs) return c_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 get_network_create_kwargs(self, action, network_name, kwargs=None): """ Generates keyword arguments for the Docker client to create a network. :param action:...
config = action.config c_kwargs = dict( name=network_name, driver=config.driver, options=config.driver_options, ) if config.internal: c_kwargs['internal'] = True driver_opts = init_options(config.driver_options) if driver_o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_network_remove_kwargs(self, action, network_name, kwargs=None): """ Generates keyword arguments for the Docker client to remove a network. :param action:...
c_kwargs = dict(net_id=network_name) update_kwargs(c_kwargs, kwargs) return c_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 get_network_connect_kwargs(self, action, network_name, container_name, endpoint_config=None, kwargs=None): """ Generates keyword arguments for the Docker cli...
c_kwargs = dict( container=container_name, net_id=network_name, ) if endpoint_config: c_kwargs.update(self.get_network_create_endpoint_kwargs(action, endpoint_config)) update_kwargs(c_kwargs, kwargs) return c_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 get_network_disconnect_kwargs(self, action, network_name, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to remove a con...
c_kwargs = dict( container=container_name, net_id=network_name, ) update_kwargs(c_kwargs, kwargs) return c_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 get_volume_create_kwargs(self, action, volume_name, kwargs=None): """ Generates keyword arguments for the Docker client to create a volume. :param action: Ac...
config = action.config c_kwargs = dict(name=volume_name) if config: c_kwargs['driver'] = config.driver driver_opts = init_options(config.driver_options) if driver_opts: c_kwargs['driver_opts'] = {option_name: resolve_value(option_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 get_volume_remove_kwargs(self, action, volume_name, kwargs=None): """ Generates keyword arguments for the Docker client to remove a volume. :param action: Ac...
c_kwargs = dict(name=volume_name) update_kwargs(c_kwargs, kwargs) return c_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 cname(cls, map_name, container, instance=None): """ Generates a container name that should be used for creating new containers and checking the status of exi...
if instance: return '{0}.{1}.{2}'.format(map_name, container, instance) return '{0}.{1}'.format(map_name, container)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aname(cls, map_name, attached_name, parent_name=None): """ Generates a container name that should be used for creating new attached volume containers and che...
if parent_name: return '{0}.{1}.{2}'.format(map_name, parent_name, attached_name) return '{0}.{1}'.format(map_name, attached_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 nname(cls, map_name, network_name): """ Generates a network name that should be used for creating new networks and checking the status of existing networks o...
if network_name in DEFAULT_PRESET_NETWORKS: return network_name return '{0}.{1}'.format(map_name, network_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 get_hostname(cls, container_name, client_name=None): """ Determines the host name of a container. In this implementation, replaces all dots and underscores o...
base_name = container_name for old, new in cls.hostname_replace: base_name = base_name.replace(old, new) if not client_name or client_name == cls.default_client_name: return base_name client_suffix = client_name for old, new in cls.hostname_replace: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adduser(username, uid=None, system=False, no_login=True, no_password=False, group=False, gecos=None, **kwargs): """ Formats an ``adduser`` command. :param us...
return _format_cmd('adduser', username, __system=bool(system), __uid=uid, __group=bool(group), __gid=uid, no_login=(no_login, _NO_CREATE_HOME, _NO_LOGIN), __disabled_password=no_login or bool(no_password), __gecos=gecos, **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 mkdir(path, create_parent=True, check_if_exists=False): """ Generates a unix command line for creating a directory. :param path: Directory path. :type path: ...
cmd = _format_cmd('mkdir', path, _p=create_parent) if check_if_exists: return 'if [[ ! -d {0} ]]; then {1}; fi'.format(path, cmd) return cmd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, field_name, parent): """ Create translation serializer dynamically. Takes translatable model class (shared_model) from parent serializer and it ma...
super(TranslatedFieldsField, self).bind(field_name, parent) # Expect 1-on-1 for now. Allow using source as alias, # but it should not be a dotted path for now related_name = self.source or field_name # This could all be done in __init__(), but by moving the code here, ...
<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_representation(self, value): """ Serialize translated fields. Simply iterate over available translations and, for each language, delegate serialization lo...
if value is None: return # Only need one serializer to create the native objects serializer = self.serializer_class( instance=self.parent.instance, # Typically None context=self.context, partial=self.parent.partial ) # Don't nee...
<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_internal_value(self, data): """ Deserialize data from translations fields. For each received language, delegate validation logic to the translation model ...
if data is None: return if not isinstance(data, dict): self.fail('invalid') if not self.allow_empty and len(data) == 0: self.fail('empty') result, errors = {}, {} for lang_code, model_fields in data.items(): serializer = self.ser...
<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, text, layers=None): """Parsing passed text to json. Args: text: Text to parse. layers (optional): Special fields. Only one string or iterable ob...
params = { "text": text, "key": self.key, } if layers is not None: # if it's string if isinstance(layers, six.string_types): params["layers"] = layers # if it's another iterable object elif isinstance(laye...
<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(self, text): """Try to get the generated file. Args: text: The text that you want to generate. """
if not text: raise Exception("No text to speak") if len(text) >= self.MAX_CHARS: raise Exception("Number of characters must be less than 2000") params = self.__params.copy() params["text"] = text self._data = requests.get(self.TTS_URL, params=params, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, path="speech"): """Save data in file. Args: path (optional): A path to save file. Defaults to "speech". File extension is optional. Absolute path...
if self._data is None: raise Exception("There's nothing to save") extension = "." + self.__params["format"] if os.path.splitext(path)[1] != extension: path += extension with open(path, "wb") as f: for d in self._data: f.write(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 create_translated_fields_serializer(shared_model, meta=None, related_name=None, **fields): """ Create a Rest Framework serializer class for a translated fiel...
if not related_name: translated_model = shared_model._parler_meta.root_model else: translated_model = shared_model._parler_meta[related_name].model # Define inner Meta class if not meta: meta = {} meta['model'] = translated_model meta.setdefault('fields', ['language_cod...
<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, **kwargs): """ Extract the translations and save them after main object save. By default all translations will be saved no matter if creating or u...
translated_data = self._pop_translated_data() instance = super(TranslatableModelSerializer, self).save(**kwargs) self.save_translations(instance, translated_data) return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pop_translated_data(self): """ Separate data of translated fields from other data. """
translated_data = {} for meta in self.Meta.model._parler_meta: translations = self.validated_data.pop(meta.rel_name, {}) if translations: translated_data[meta.rel_name] = translations return translated_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 save_translations(self, instance, translated_data): """ Save translation data into translation objects. """
for meta in self.Meta.model._parler_meta: translations = translated_data.get(meta.rel_name, {}) for lang_code, model_fields in translations.items(): translation = instance._get_translated_model(lang_code, auto_create=True, meta=meta) for field, value in m...
<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_conf(cfg_path): """ Try to load the given conf file. """
global config try: cfg = open(cfg_path, 'r') except Exception as ex: if verbose: print("Unable to open {0}".format(cfg_path)) print(str(ex)) return False # Read the entire contents of the conf file cfg_json = cfg.read() cfg.close() # print(cf...
<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_message_tokens(message_tokens): """ Translates alias references to their defined values. The first token is a channel alias. The remaining tokens a...
trans_tokens = [] if message_tokens[0] in cv_dict[channels_key]: trans_tokens.append(cv_dict[channels_key][message_tokens[0]]) else: trans_tokens.append(int(message_tokens[0])) for token in message_tokens[1:]: if token in cv_dict[values_key]: trans_tokens.extend(cv_...
<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_headers(cls, msg): """ Parse HTTP headers. Args: msg (str): HTTP message. Returns: (List[Tuple[str, str]): List of header tuples. """
return list(email.parser.Parser().parsestr(msg).items())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse(cls, msg): """Parse message string to response object."""
lines = msg.splitlines() version, status_code, reason = lines[0].split() headers = cls.parse_headers('\r\n'.join(lines[1:])) return cls(version=version, status_code=status_code, reason=reason, headers=headers)
<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(cls, msg): """Parse message string to request object."""
lines = msg.splitlines() method, uri, version = lines[0].split() headers = cls.parse_headers('\r\n'.join(lines[1:])) return cls(version=version, uri=uri, method=method, headers=headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendto(self, transport, addr): """ Send request to a given address via given transport. Args: transport (asyncio.DatagramTransport): Write transport to send...
msg = bytes(self) + b'\r\n' logger.debug("%s:%s < %s", *(addr + (self,))) transport.sendto(msg, addr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_rgb(dev, red, green, blue, dimmer): """ Send a set of RGB values to the light """
cv = [0 for v in range(0, 512)] cv[0] = red cv[1] = green cv[2] = blue cv[6] = dimmer sent = dev.send_multi_value(1, cv) return sent
<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(): """ How to control a DMX light through an Anyma USB controller """
# Channel value list for channels 1-512 cv = [0 for v in range(0, 512)] # Create an instance of the DMX controller and open it print("Opening DMX controller...") dev = pyudmx.uDMXDevice() # This will automagically find a single Anyma-type USB DMX controller dev.open() # For inform...
<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): """Connect to vCenter server"""
try: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) if self.config['no_ssl_verify']: requests.packages.urllib3.disable_warnings() context.verify_mode = ssl.CERT_NONE self.si = SmartConnectNoSSL( host=self.config['server...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self): """Check power status"""
vm = self.get_vm_failfast(self.config['name']) extra = self.config['extra'] parserFriendly = self.config['parserFriendly'] status_to_print = [] if extra: status_to_print = \ [["vmname", "powerstate", "ipaddress", "hostname", "memory", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shutdown(self): """ Shutdown guest fallback to power off if guest tools aren't installed """
vm = self.get_vm_failfast(self.config['name']) if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOff: print("%s already poweredOff" % vm.name) else: if self.guestToolsRunning(vm): timeout_minutes = 10 print("waiting for %s 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_resource_pool(self, cluster, pool_name): """ Find a resource pool given a pool name for desired cluster """
pool_obj = None # get a list of all resource pools in this cluster cluster_pools_list = cluster.resourcePool.resourcePool # get list of all resource pools with a given text name pool_selections = self.get_obj( [vim.ResourcePool], pool_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 get_obj(self, vimtype, name, return_all=False, path=""): """Get the vsphere object associated with a given text name or MOID"""
obj = list() if path: obj_folder = self.content.searchIndex.FindByInventoryPath(path) container = self.content.viewManager.CreateContainerView( obj_folder, vimtype, True ) else: container = self.content.viewManager.CreateContainerV...
<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_host_system_failfast( self, name, verbose=False, host_system_term='HS' ): """ Get a HostSystem object fail fast if the object isn't a valid reference """
if verbose: print("Finding HostSystem named %s..." % name) hs = self.get_host_system(name) if hs is None: print("Error: %s '%s' does not exist" % (host_system_term, name)) sys.exit(1) if verbose: print("Found HostSystem: {0} Name: {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 get_vm(self, name, path=""): """Get a VirtualMachine object"""
if path: return self.get_obj([vim.VirtualMachine], name, path=path) else: return self.get_obj([vim.VirtualMachine], 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 get_vm_failfast(self, name, verbose=False, vm_term='VM', path=""): """ Get a VirtualMachine object fail fast if the object isn't a valid reference """
if verbose: print("Finding VirtualMachine named %s..." % name) if path: vm = self.get_vm(name, path=path) else: vm = self.get_vm(name) if vm is None: print("Error: %s '%s' does not exist" % (vm_term, name)) sys.exit(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 WaitForVirtualMachineShutdown( self, vm_to_poll, timeout_seconds, sleep_period=5 ): """ Guest shutdown requests do not run a task we can wait for. So, we mus...
seconds_waited = 0 # wait counter while seconds_waited < timeout_seconds: # sleep first, since nothing shuts down instantly seconds_waited += sleep_period time.sleep(sleep_period) vm = self.get_vm(vm_to_poll.name) if vm.runtime.powerState ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def location(ip=None, key=None, field=None): ''' Get geolocation data for a given IP address If field is specified, get specific field as text Else get complete location data as JSON ''' if field and (field not in field_list): return 'Invalid field' if field: if ip: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Main example."""
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) parser = argparse.ArgumentParser( description='Test the SMA webconnect library.') parser.add_argument( 'ip', type=str, help='IP address of the Webconnect module') parser.add_argument( 'user', help='installer/user') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self): """ Get a cached post-processed result of a GitHub API call. Uses Trac cache to avoid constant querying of the remote API. If a previous API call...
if self._next_update and datetime.now() > self._next_update: self.update() return self._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 teams(self): """ Return a sequence of `GitHubTeam` objects, one for each team in this org. """
teams = self._teamlist.teams() # find out which teams have been added or removed since the last sync current_teams = set(self._teamobjects.keys()) new_teams = set(teams.keys()) # pylint: disable=no-member added = new_teams - current_teams removed = current_teams - new_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 members(self): """ Return a list of all users in this organization. Users are identified by their login name. Note that this is computed from the teams in th...
allmembers = set() for team in self.teams(): allmembers.update(team.members()) return sorted(allmembers)
<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_team(self, slug): """ Trigger an update and cache invalidation for the team identified by the given `slug`. Returns `True` on success, `False` otherwi...
if slug not in self._teamobjects: # This case is checked and handled further up, but better be safe # than sorry. return False # pragma: no cover return self._teamobjects[slug].update()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def github_api(self, url, *args): """ Connect to the given GitHub API URL template by replacing all placeholders with the given parameters and return the decoded...
import requests import urllib github_api_url = os.environ.get("TRAC_GITHUB_API_URL", "https://api.github.com/") formatted_url = github_api_url + url.format(*(urllib.quote(str(x)) for x in args)) access_token = _config_secret(self.access_token) self.log.debug("Hitting Gi...
<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_team(self, slug): """ Trigger update and cache invalidation for the team identified by the given `slug`, if any. Returns `True` if the update was succ...
if self._org: if not self._org.has_team(slug): return self._org.update() return self._org.update_team(slug) # self._org is created during Trac startup, so there should never # be a case where we try to update an org before it's created; this # 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 get_permission_groups(self, username): """ Return a list of names of the groups that the user with the specified name is a member of. Implements an `IPermiss...
if not self.organization or not self.username or not self.access_token: return [] elif (self.username_prefix and not username.startswith(self.username_prefix)): return [] data = self._fetch_groups() if not data: self.log.error("No cac...
<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_request(self, req): """ Return whether the handler wants to process the given request. Implements an `IRequestHandler` API. """
match = self._request_re.match(req.path_info) if match: return True if os.environ.get('TRAC_GITHUB_ENABLE_DEBUGGING', None) is not None: debug_match = self._debug_request_re.match(req.path_info) if debug_match: 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 process_debug_request(self, req): """ Debgging helper used for testing, processes the given request and dumps the internal state of cached user to group mapp...
req.send(json.dumps(self._fetch_groups()).encode('utf-8'), 'application/json', 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 process_request(self, req): """ Process the given request `req`, implements an `IRequestHandler` API. Normally, `process_request` would return a tuple, but s...
if os.environ.get('TRAC_GITHUB_ENABLE_DEBUGGING', None) is not None: debug_match = self._debug_request_re.match(req.path_info) if debug_match: self.process_debug_request(req) if req.method != 'POST': msg = u'Endpoint is ready to accept GitHub Organiz...
<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_content_children(self, content_id, expand=None, parent_version=None, callback=None): """ Returns a map of the direct children of a piece of Content. Cont...
params = {} if expand: params["expand"] = expand if parent_version: params["parentVersion"] = parent_version return self._service_get_request("rest/api/content/{id}/child".format(id=content_id), params=params, callback=cal...
<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_content_descendants(self, content_id, expand=None, callback=None): """ Returns a map of the descendants of a piece of Content. Content can have multiple ...
params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/content/{id}/descendant".format(id=content_id), params=params, callback=callback)
<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_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None, callback=None): """ Returns the direct descendants of a pi...
params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return self._service_get_request("rest/api/content/{id}/descendant/{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_content_properties(self, content_id, expand=None, start=None, limit=None, callback=None): """ Returns a paginated list of content properties. Content pro...
params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return self._service_get_request("rest/api/content/{id}/property".format(id=content_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 create_new_attachment_by_content_id(self, content_id, attachments, callback=None): """ Add one or more attachments to a Confluence Content entity, with optio...
if isinstance(attachments, list): assert all(isinstance(at, dict) and "file" in list(at.keys()) for at in attachments) elif isinstance(attachments, dict): assert "file" in list(attachments.keys()) else: assert False return self._service_post_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 create_new_space(self, space_definition, callback=None): """ Creates a new Space. The incoming Space does not include an id, but must include a Key and Name,...
assert isinstance(space_definition, dict) and {"key", "name", "description"} <= set(space_definition.keys()) return self._service_post_request("rest/api/space", data=json.dumps(space_definition), headers={"Content-Type": "application/json"}, callback=callback)
<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_content_by_id(self, content_data, content_id, callback=None): """ Updates a piece of Content, or restores if it is trashed. The body contains the repr...
assert isinstance(content_data, dict) and set(content_data.keys()) >= self.UPDATE_CONTENT_REQUIRED_KEYS return self._service_put_request("rest/api/content/{id}".format(id=content_id), data=json.dumps(content_data), headers={"Content-Type": "application/json"}, c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_attachment_metadata(self, content_id, attachment_id, new_metadata, callback=None): """ Update the non-binary data of an Attachment. This resource can ...
assert isinstance(new_metadata, dict) and set(new_metadata.keys()) >= self.ATTACHMENT_METADATA_KEYS return self._service_put_request("rest/api/content/{id}/child/attachment/{attachment_id}" "".format(id=content_id, attachment_id=attachment_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 update_attachment(self, content_id, attachment_id, attachment, callback=None): """ Update the binary data of an Attachment, and optionally the comment and th...
if isinstance(attachment, dict): assert "file" in list(attachment.keys()) else: assert False return self._service_post_request("rest/api/content/{content_id}/child/attachment/{attachment_id}/data" "".format(content_id=content_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 update_property(self, content_id, property_key, new_property_data, callback=None): """ Updates a content property. The body contains the representation of th...
assert isinstance(new_property_data, dict) and {"key", "value", "version"} <= set(new_property_data.keys()) return self._service_put_request("rest/api/content/{id}/property/{key}".format(id=content_id, key=property_key), data=json.dumps(new_property_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 update_space(self, space_key, space_definition, callback=None): """ Updates a Space. Currently only the Space name, description and homepage can be updated. ...
assert isinstance(space_definition, dict) and {"key", "name", "description"} <= set(space_definition.keys()) return self._service_put_request("rest/api/space/{key}".format(key=space_key), data=json.dumps(space_definition), ...
<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_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None): """ Converts between content body representations...
assert {old_representation, new_representation} < {"storage", "editor", "view", "export_view"} # TODO: Enforce conversion rules better here. request_data = {"value": str(content_data), "representation": old_representation} return self._service_post_request("rest/api/contentbody/convert/...
<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_label_by_id(self, content_id, label_name, callback=None): """ Deletes a labels to the specified content. There is an alternative form of this delete m...
params = {"name": label_name} return self._service_delete_request("rest/api/content/{id}/label".format(id=content_id), params=params, callback=callback)
<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_space(self, space_key, callback=None): """ Deletes a Space. The space is deleted in a long running task, so the space cannot be considered deleted whe...
return self._service_delete_request("rest/api/space/{key}".format(key=space_key), callback=callback)
<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(self, sensor): """Add a sensor, warning if it exists."""
if isinstance(sensor, (list, tuple)): for sss in sensor: self.add(sss) return if not isinstance(sensor, Sensor): raise TypeError("pysma.Sensor expected") if sensor.name in self: old = self[sensor.name] self.__s.remove...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetch_json(self, url, payload): """Fetch json data for requests."""
params = { 'data': json.dumps(payload), 'headers': {'content-type': 'application/json'}, 'params': {'sid': self.sma_sid} if self.sma_sid else None, } for _ in range(3): try: with async_timeout.timeout(3): 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 new_session(self): """Establish a new session."""
body = yield from self._fetch_json(URL_LOGIN, self._new_session_data) self.sma_sid = jmespath.search('result.sid', body) if self.sma_sid: return True msg = 'Could not start session, %s, got {}'.format(body) if body.get('err'): if body.get('err') == 503:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, sensors): """Read a set of keys."""
payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))} if self.sma_sid is None: yield from self.new_session() if self.sma_sid is None: return False body = yield from self._fetch_json(URL_VALUES, payload=payload) # On the first 401...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def media(self, uri): """Play a media file."""
try: local_path, _ = urllib.request.urlretrieve(uri) metadata = mutagen.File(local_path, easy=True) if metadata.tags: self._tags = metadata.tags title = self._tags.get(TAG_TITLE, []) self._manager[ATTR_TITLE] = title[0] if len(title) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def play(self): """Change state to playing."""
if self.state == STATE_PAUSED: self._player.set_state(Gst.State.PLAYING) self.state = STATE_PLAYING
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(self): """Change state to paused."""
if self.state == STATE_PLAYING: self._player.set_state(Gst.State.PAUSED) self.state = STATE_PAUSED
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop(self): """Stop pipeline."""
urllib.request.urlcleanup() self._player.set_state(Gst.State.NULL) self.state = STATE_IDLE self._tags = {}
<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_position(self, position): """Set media position."""
if position > self._duration(): return position_ns = position * _NANOSEC_MULT self._manager[ATTR_POSITION] = position self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def state(self, state): """Set state."""
self._state = state self._manager[ATTR_STATE] = state _LOGGER.info('state changed to %s', state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _duration(self): """Get media duration."""
duration = 0 if self.state != STATE_IDLE: resp = self._player.query_duration(_FORMAT_TIME) duration = resp[1] // _NANOSEC_MULT return duration
<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): """Get media position."""
position = 0 if self.state != STATE_IDLE: resp = self._player.query_position(_FORMAT_TIME) position = resp[1] // _NANOSEC_MULT return position
<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_message(self, bus, message): # pylint: disable=unused-argument """When a message is received from Gstreamer."""
if message.type == Gst.MessageType.EOS: self.stop() elif message.type == Gst.MessageType.ERROR: self.stop() err, _ = message.parse_error() _LOGGER.error('%s', err)
<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_previous_node(node): """ Return the node before this node. """
if node.prev_sibling: return node.prev_sibling if node.parent: return get_previous_node(node.parent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def casperjs_command_kwargs(): """ will construct kwargs for cmd """
kwargs = { 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'universal_newlines': True } phantom_js_cmd = app_settings['PHANTOMJS_CMD'] if phantom_js_cmd: path = '{0}:{1}'.format( os.getenv('PATH', ''), os.path.dirname(phantom_js_cmd) ) k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def casperjs_capture(stream, url, method=None, width=None, height=None, selector=None, data=None, waitfor=None, size=None, crop=None, render='png', wait=None): "...
if isinstance(stream, six.string_types): output = stream else: with NamedTemporaryFile('wb+', suffix='.%s' % render, delete=False) as f: output = f.name try: cmd = CASPERJS_CMD + [url, output] # Extra command-line options cmd += ['--format=%s' % render] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_casperjs_stdout(stdout): """Parse and digest capture script output. """
for line in stdout.splitlines(): bits = line.split(':', 1) if len(bits) < 2: bits = ('INFO', bits) level, msg = bits if level == 'FATAL': logger.fatal(msg) raise CaptureError(msg) elif level == 'ERROR': logger.error(msg) ...
<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_url(request, url): """Parse url URL parameter."""
try: validate = URLValidator() validate(url) except ValidationError: if url.startswith('/'): host = request.get_host() scheme = 'https' if request.is_secure() else 'http' url = '{scheme}://{host}{uri}'.format(scheme=scheme, ...
<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_render(render): """Parse render URL parameter. 'png' 'png' 'png' 'jpeg' 'gif' """
formats = { 'jpeg': guess_all_extensions('image/jpeg'), 'png': guess_all_extensions('image/png'), 'gif': guess_all_extensions('image/gif'), 'bmp': guess_all_extensions('image/x-ms-bmp'), 'tiff': guess_all_extensions('image/tiff'), 'xbm': guess_all_extensions('image/x...
<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_size(size_raw): """ Parse size URL parameter. None (300, 100) None None None """
try: width_str, height_str = size_raw.lower().split('x') except AttributeError: size = None except ValueError: size = None else: try: width = int(width_str) assert width > 0 except (ValueError, AssertionError): width = 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 build_absolute_uri(request, url): """ Allow to override printing url, not necessarily on the same server instance. """
if app_settings.get('CAPTURE_ROOT_URL'): return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url) return request.build_absolute_uri(url)
<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_template(template_name, context, format='png', output=None, using=None, **options): """ Render a template from django project, and return the file obj...
# output stream, as required by casperjs_capture stream = BytesIO() out_f = None # the suffix=.html is a hack for phantomjs which *will* # complain about not being able to open source file # unless it has a 'html' extension. with NamedTemporaryFile(suffix='.html') as render_file: te...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def go(fn, *args, **kwargs): """Launch an operation on a thread and get a handle to its future result. hello from background thread main thread goodbye from back...
if not callable(fn): raise TypeError('go() requires a function, not %r' % (fn,)) result = [None] error = [] def target(): try: result[0] = fn(*args, **kwargs) except Exception: # Are we in interpreter shutdown? if sys: error.e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def going(fn, *args, **kwargs): """Launch a thread and wait for its result before exiting the code block. 'return value' Or discard the result: If an exception i...
future = go(fn, *args, **kwargs) try: yield future except: # We are raising an exception, just try to clean up the future. exc_info = sys.exc_info() try: # Shorter than normal timeout. future(timeout=1) except: log_message = ('\ner...