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 sync_and_deploy_gateway(collector): """Do a sync followed by deploying the gateway"""
configuration = collector.configuration aws_syncr = configuration['aws_syncr'] find_gateway(aws_syncr, configuration) artifact = aws_syncr.artifact aws_syncr.artifact = "" sync(collector) aws_syncr.artifact = artifact deploy_gateway(collector)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_result(self, f=sys.stdout, verbose=False): """Print result to f :param f: stream to print output :param verbose: print all data or only the most important parts? """
var_count = len(self.betas)/2 if verbose: results = [str(x) for x in [ self.chr, self.pos, self.rsid, self.ph_label, self.non_miss, self.maj_allele, self.min_allele, "%.4e" % self.eff_alcount, "%.4e" % self.p_mvtest, "%.4e" % self.lmpv ]] for i in range(var_count): results.append("%.3e" % self.betas[i]) results.append(self.stringify(self.beta_stderr[i])) results.append(self.stringify(self.beta_pvalues[i])) results.append(self.stringify(self.betas[i+var_count])) results.append(self.stringify(self.beta_stderr[i+var_count])) results.append(self.stringify(self.beta_pvalues[i+var_count])) print >> f, "\t".join([str(x) for x in results]) else: print >> f, "\t".join(str(x) for x in [ self.chr, self.pos, self.rsid, self.ph_label, self.non_miss, self.maj_allele, self.min_allele, "%.3e" % self.eff_alcount, "%.3e" % self.p_mvtest, "%.3e" % self.betas[1], self.stringify(self.beta_stderr[1]), "%.3e" % self.beta_pvalues[1], "%.3e" % self.betas[1+var_count], self.stringify(self.beta_stderr[1+var_count]), "%.3e" % self.beta_pvalues[1+var_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 generate_synonym(self, input_word): """ Generate Synonym using a WordNet synset. """
results = [] results.append(input_word) synset = wordnet.synsets(input_word) for i in synset: index = 0 syn = i.name.split('.') if syn[index]!= input_word: name = syn[0] results.append(PataLib().strip_underscore(name)) else: index = index + 1 results = {'input' : input_word, 'results' : results, 'category' : 'synonym'} return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_canonical(version, loosedev=False): # type: (str, bool) -> bool """ Return whether or not the version string is canonical according to Pep 440 """
if loosedev: return loose440re.match(version) is not None return pep440re.match(version) is not None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(data): """ Handles decoding of the JSON `data`. Args: data (str): Data which will be decoded. Returns: dict: Dictionary with decoded data. """
decoded = None try: decoded = json.loads(data) except Exception, e: raise MetaParsingException("Can't parse your JSON data: %s" % e.message) decoded = validator.check_structure(decoded) return decoded
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(host='0.0.0.0', port=1338): """ Initialize PyMLGame. This creates a controller thread that listens for game controllers and events. :param host: Bind to this address :param port: Bind to this port :type host: str :type port: int """
CONTROLLER.host = host CONTROLLER.port = port CONTROLLER.setDaemon(True) # because it's a deamon it will exit together with the main thread CONTROLLER.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_events(maximum=10): """ Get all events since the last time you asked for them. You can define a maximum which is 10 by default. :param maximum: Maximum number of events :type maximum: int :return: List of events :rtype: list """
events = [] for ev in range(0, maximum): try: if CONTROLLER.queue.empty(): break else: events.append(CONTROLLER.queue.get_nowait()) except NameError: print('PyMLGame is not initialized correctly. Use pymlgame.init() first.') events = False break return events
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_entry(entry): """Consolidate some entry attributes and rename a few others. Consolidate address attributes into a single field and replace some field names with others as described in FIELD_TRANSFORM_INDEX. @param entry: The entry attributes to update. @type entry: dict @return: Entry copy after running clean operations @rtype: dict """
newEntry = {} if 'Address1' in entry: address = str(entry['Address1']) if entry['Address2'] != '': address = address + ' ' + str(entry['Address2']) newEntry['address'] = address del entry['Address1'] del entry['Address2'] for key in entry.keys(): if key != None: if key in FIELD_TRANSFORM_INDEX: newKey = FIELD_TRANSFORM_INDEX[key] else: newKey = key newKey = newKey[:1].lower() + newKey[1:] newEntry[newKey] = entry[key] return newEntry
<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_expenditure_entry(database, entry): """Update a record of a expenditure report in the provided database. @param db: The MongoDB database to operate on. The expenditures collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, updating the entry with the same recordID if one exists. @type entry: dict """
entry = clean_entry(entry) database.expenditures.update( {'recordID': entry['recordID']}, {'$set': entry}, upsert=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 update_loan_entry(database, entry): """Update a record of a loan report in the provided database. @param db: The MongoDB database to operate on. The loans collection will be used from this database. @type db: pymongo.database.Database @param entry: The entry to insert into the database, updating the entry with the same recordID if one exists. @type entry: dict """
entry = clean_entry(entry) database.loans.update( {'recordID': entry['recordID']}, {'$set': entry}, upsert=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 insert_contribution_entries(database, entries): """Insert a set of records of a contribution report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param database: The MongoDB database to operate on. The contributions collection will be used from this database. @type db: pymongo.database.Database @param entries: The entries to insert into the database. @type entries: dict """
entries = map(clean_entry, entries) database.contributions.insert(entries, continue_on_error=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 insert_expenditure_entries(database, entries): """Insert a set of records of a expenditure report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param db: The MongoDB database to operate on. The expenditures collection will be used from this database. @type db: pymongo.database.Database @param entries: The entries to insert into the database. @type entries: dict """
entries = map(clean_entry, entries) database.expenditures.insert(entries, continue_on_error=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 insert_loan_entries(database, entries): """Insert a set of records of a loan report in the provided database. Insert a set of new records into the provided database without checking for conflicting entries. @param db: The MongoDB database to operate on. The loans collection will be used from this database. @type db: pymongo.database.Database @param entries: The entries to insert into the database. @type entries: dict """
entries = map(clean_entry, entries) database.loans.insert(entries, continue_on_error=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 pagination_links(paginator_page, show_pages, url_params=None, first_page_label=None, last_page_label=None, page_url=''): '''Django template tag to display pagination links for a paginated list of items. Expects the following variables: * the current :class:`~django.core.paginator.Page` of a :class:`~django.core.paginator.Paginator` object * a dictionary of the pages to be displayed, in the format generated by :meth:`eulcommon.searchutil.pages_to_show` * optional url params to include in pagination link (e.g., search terms when paginating search results) * optional first page label (only used when first page is not in list of pages to be shown) * optional last page label (only used when last page is not in list of pages to be shown) * optional url to use for page links (only needed when the url is different from the current one) Example use:: {% load search_utils %} {% pagination_links paged_items show_pages %} ''' return { 'items': paginator_page, 'show_pages': show_pages, 'url_params': url_params, 'first_page_label': first_page_label, 'last_page_label': last_page_label, 'page_url': page_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 modify_classes(): """ Auto-discover INSTALLED_APPS class_modifiers.py modules and fail silently when not present. This forces an import on them to modify any classes they may want. """
import copy from django.conf import settings from django.contrib.admin.sites import site from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule for app in settings.INSTALLED_APPS: mod = import_module(app) # Attempt to import the app's class_modifier module. try: before_import_registry = copy.copy(site._registry) import_module('%s.class_modifiers' % app) except: site._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have an class_modifier module, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(mod, 'class_modifiers'): 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 wrap(self, text): '''Wraps the text object to width, breaking at whitespaces. Runs of whitespace characters are preserved, provided they do not fall at a line boundary. The implementation is based on that of textwrap from the standard library, but we can cope with StringWithFormatting objects. :returns: a list of string-like objects. ''' result = [] chunks = self._chunk(text) while chunks: self._lstrip(chunks) current_line = [] current_line_length = 0 current_chunk_length = 0 while chunks: current_chunk_length = len(chunks[0]) if current_line_length + current_chunk_length <= self.width: current_line.append(chunks.pop(0)) current_line_length += current_chunk_length else: # Line is full break # Handle case where chunk is bigger than an entire line if current_chunk_length > self.width: space_left = self.width - current_line_length current_line.append(chunks[0][:space_left]) chunks[0] = chunks[0][space_left:] self._rstrip(current_line) if current_line: result.append(reduce( lambda x, y: x + y, current_line[1:], current_line[0])) else: # FIXME: should this line go? Removing it makes at least simple # cases like wrap(' ', 10) actually behave like # textwrap.wrap... result.append('') 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 chainable(fn): """ Make function a chainable validator The returned function is a chainable validator factory which takes the next function in the chain and returns a chained version of the original validator: ``fn(next(value))``. The chainable validators are used with the ``make_chain()`` function. """
@functools.wraps(fn) def wrapper(nxt=lambda x: x): if hasattr(nxt, '__call__'): return lambda x: nxt(fn(x)) # Value has been passsed directly, so we don't chain return fn(nxt) return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_chain(fns): """ Take a list of chainable validators and return a chained validator The functions should be decorated with ``chainable`` decorator. Any exceptions raised by any of the validators are propagated except for ``ReturnEarly`` exception which is trapped. When ``ReturnEarly`` exception is trapped, the original value passed to the chained validator is returned as is. """
chain = lambda x: x for fn in reversed(fns): chain = fn(chain) def validator(v): try: return chain(v) except ReturnEarly: return v return validator
<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, locator, factory): """ Registers a component using a factory method. :param locator: a locator to identify component to be created. :param factory: a factory function that receives a locator and returns a created component. """
if locator == None: raise Exception("Locator cannot be null") if factory == None: raise Exception("Factory cannot be null") self._registrations.append(Registration(locator, factory))
<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(self, locator): """ Creates a component identified by given locator. :param locator: a locator to identify component to be created. :return: the created component. """
for registration in self._registrations: this_locator = registration.locator if this_locator == locator: try: return registration.factory(locator) except Exception as ex: if isinstance(ex, CreateException): raise ex raise CreateException( None, "Failed to create object for " + str(locator) ).with_cause(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 update(self, catalog=None, dependencies=None, allow_overwrite=False): ''' Convenience method to update this Di instance with the specified contents. :param catalog: ICatalog supporting class or mapping :type catalog: ICatalog or collections.Mapping :param dependencies: Mapping of dependencies :type dependencies: collections.Mapping :param allow_overwrite: If True, allow overwriting existing keys. Only applies to providers. :type allow_overwrite: bool ''' if catalog: self._providers.update(catalog, allow_overwrite=allow_overwrite) if dependencies: self._dependencies.update(dependencies)
<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_missing_deps(self, obj): ''' Returns missing dependencies for provider key. Missing meaning no instance can be provided at this time. :param key: Provider key :type key: object :return: Missing dependencies :rtype: list ''' deps = self.get_deps(obj) ret = [] for key in deps: provider = self._providers.get(key) if provider and provider.providable: continue ret.append(key) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def iresolve(self, *keys): ''' Iterates over resolved instances for given provider keys. :param keys: Provider keys :type keys: tuple :return: Iterator of resolved instances :rtype: generator ''' for key in keys: missing = self.get_missing_deps(key) if missing: raise UnresolvableError("Missing dependencies for %s: %s" % (key, missing)) provider = self._providers.get(key) if not provider: raise UnresolvableError("Provider does not exist for %s" % key) yield provider()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resolve(self, *keys): ''' Returns resolved instances for given provider keys. If only one positional argument is given, only one is returned. :param keys: Provider keys :type keys: tuple :return: Resolved instance(s); if only one key given, otherwise list of them. :rtype: object or list ''' instances = list(self.iresolve(*keys)) if len(keys) == 1: return instances[0] return instances
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resolve_deps(self, obj): ''' Returns list of resolved dependencies for given obj. :param obj: Object to lookup dependencies for :type obj: object :return: Resolved dependencies :rtype: list ''' deps = self.get_deps(obj) return list(self.iresolve(*deps))
<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_factory(self, key, factory=_sentinel, scope=NoneScope, allow_overwrite=False): ''' Creates and registers a provider using the given key, factory, and scope. Can also be used as a decorator. :param key: Provider key :type key: object :param factory: Factory callable :type factory: callable :param scope: Scope key, factory, or instance :type scope: object or callable :return: Factory (or None if we're creating a provider without a factory) :rtype: callable or None ''' if factory is _sentinel: return functools.partial(self.register_factory, key, scope=scope, allow_overwrite=allow_overwrite) if not allow_overwrite and key in self._providers: raise KeyError("Key %s already exists" % key) provider = self.provider(factory, scope) self._providers[key] = provider return factory
<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_instance(self, key, instance, default_scope=GlobalScope): ''' Sets instance under specified provider key. If a provider for specified key does not exist, one is created without a factory using the given scope. :param key: Provider key :type key: object :param instance: Instance :type instance: object :param default_scope: Scope key, factory, or instance :type default_scope: object or callable ''' if key not in self._providers: # We don't know how to create this kind of instance at this time, so add it without a factory. factory = None self.register_factory(key, factory, default_scope) self._providers[key].set_instance(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 depends_on(self, *keys): ''' Decorator that marks the wrapped as depending on specified provider keys. :param keys: Provider keys to mark as dependencies for wrapped :type keys: tuple :return: decorator :rtype: decorator ''' def decorator(wrapped): if keys: if wrapped not in self._dependencies: self._dependencies[wrapped] = set() self._dependencies[wrapped].update(keys) return wrapped return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def inject_classproperty(self, key, name=None, replace_on_access=False): ''' Decorator that injects the specified key as a classproperty. If replace_on_access is True, then it replaces itself with the instance on first lookup. :param key: Provider key :type key: object :param name: Name of classproperty, defaults to key :type name: str :param replace_on_access: If True, replace the classproperty with the actual value on first lookup :type replace_on_access: bool ''' return ClassPropertyInjector(self, key, name=name, replace_on_access=replace_on_access)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getTarget(iid): ''' A static method which returns a Target object identified by iid. Returns None if a Target object was not found ''' db = getDataCommunicator() verbose('Loading target with id {}'.format(iid)) data = db.getTarget(iid) if data: verbose('Found target') return Target(data['name'], data['path'], _id=iid) verbose('Could not find target belonging to id {}'.format(iid)) return 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 delete(self): ''' Deletes link from vault and removes database information ''' if not self._id: verbose('This target does not have an id') return False # Removes link from vault directory verbose('Removing link from vault directory') os.remove(self.vault_path) verbose('Removing information from database') # Removing information from database self.db.removeTarget(self._id) self._id = -1 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 secure(self): ''' Creates a hard link to the target file in the vault directory and saves information about the target file in the database ''' verbose('Saving information about target into conman database') self._id = self.db.insertTarget(self.name, self.path) verbose('Creating a hard link from {} to {} directory'.format( str(self), config.CONMAN_PATH )) link(self.real_path, self.vault_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 deploy(self): ''' Creates a link at the original path of this target ''' if not os.path.exists(self.path): makedirs(self.path) link(self.vault_path, self.real_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 parse_cstring(stream, offset): """ parse_cstring will parse a null-terminated string in a bytestream. The string will be decoded with UTF-8 decoder, of course since we are doing this byte-a-byte, it won't really work for all Unicode strings. TODO: add proper Unicode support """
stream.seek(offset) string = "" while True: char = struct.unpack('c', stream.read(1))[0] if char == b'\x00': return string else: string += char.decode()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unite_dataset(dataset, basecolumn, fn=None): """ Unite dataset via fn Parameters dataset : list A list of data basecolumn : int A number of column which will be respected in uniting dataset fn : function A function which recieve :attr:`data` and return classification string. It if is None, a function which return the first item of the :attr:`data` will be used (See ``with_filename`` parameter of :func:`maidenhair.load` function). Returns ------- list A united dataset """
# create default unite_fn if fn is None: fn = default_unite_function # classify dataset via unite_fn united_dataset = OrderedDict() for data in dataset: unite_name = fn(data) if unite_name not in united_dataset: united_dataset[unite_name] = [] united_dataset[unite_name].append(data[1:]) # unite dataset via maidenhair.loaders.base.unite_dataset for name, dataset in united_dataset.items(): united_dataset[name] = _unite_dataset(dataset, basecolumn)[0] # create new dataset (respect the order of the dataset) dataset = [] for name, _dataset in united_dataset.items(): dataset.append([name] + _dataset) return dataset
<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_folder(self): ''' a helper method for creating a temporary audio clip folder ''' # import dependencies import os from labpack.platforms.localhost import localhostClient from labpack.records.id import labID # create folder in user app data record_id = labID() collection_name = 'Watson Speech2Text' localhost_client = localhostClient() app_folder = localhost_client.app_data(org_name=__team__, prod_name=__module__) if localhost_client.os in ('Linux', 'FreeBSD', 'Solaris'): collection_name = collection_name.replace(' ', '-').lower() collection_folder = os.path.join(app_folder, collection_name) clip_folder = os.path.join(collection_folder, record_id.id24) if not os.path.exists(clip_folder): os.makedirs(clip_folder) return clip_folder
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _transcribe_files(self, file_list, file_mimetype): ''' a helper method for multi-processing file transcription ''' # import dependencies import queue from threading import Thread # define multithreading function def _recognize_file(file_path, file_mimetype, queue): details = { 'error': '', 'results': [] } file_data = open(file_path, 'rb') try: transcript = self.client.recognize(file_data, file_mimetype, continuous=True) if transcript['results']: for result in transcript['results']: details['results'].append(result['alternatives'][0]) except Exception as err: details['error'] = err queue.put(details) # construct queue q = queue.Queue() # send clips to watson for transcription in separate threads threads = [] for file in file_list: watson_job = Thread(target=_recognize_file, args=(file, file_mimetype, q)) watson_job.start() threads.append(watson_job) # wait for threads to end for t in threads: t.join() # construct result transcript_details = { 'error': '', 'segments': [] } for i in range(len(file_list)): job_details = q.get() if job_details['error']: transcript_details['error'] = job_details['error'] transcript_details['segments'].extend(job_details['results']) return transcript_details
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lazy_enumerate(self, **kwargs): '''Enumerate without evaluating any sets. ''' kwargs['lazy'] = True for item in self.enumerate(**kwargs): yield item
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_selection(request): """Allow user to select a TenantGroup if they have more than one."""
groups = get_user_groups(request.user) count = len(groups) if count == 1: # Redirect to the detail page for this group return redirect(groups[0]) context = { 'groups': groups, 'count': count, } return render(request, 'multitenancy/group-landing.html', context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_dashboard(request, group_slug): """Dashboard for managing a TenantGroup."""
groups = get_user_groups(request.user) group = get_object_or_404(groups, slug=group_slug) tenants = get_user_tenants(request.user, group) can_edit_group = request.user.has_perm('multitenancy.change_tenantgroup', group) count = len(tenants) if count == 1: # Redirect to the detail page for this tenant return redirect(tenants[0]) context = { 'group': group, 'tenants': tenants, 'count': count, 'can_edit_group': can_edit_group, } return render(request, 'multitenancy/group-detail.html', context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tenant_dashboard(request, group_slug, tenant_slug): """Dashboard for managing a tenant."""
groups = get_user_groups(request.user) group = get_object_or_404(groups, slug=group_slug) tenants = get_user_tenants(request.user, group) tenant = get_object_or_404(tenants, slug=tenant_slug) can_edit_tenant = request.user.has_perm('multitenancy.change_tenant', tenant) context = { 'group': group, 'tenant': tenant, 'can_edit_tenant': can_edit_tenant, } return render(request, 'multitenancy/tenant-detail.html', context)
<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_connections(self, connections): """ Reads connections from configuration parameters. Each section represents an individual Connectionparams :param connections: configuration parameters to be read """
del self._items[:] for key in connections.get_key_names(): item = DiscoveryItem() item.key = key value = connections.get_as_nullable_string(key) item.connection = ConnectionParams.from_string(value) self._items.append(item)
<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, correlation_id, key, connection): """ Registers connection parameters into the discovery service. :param correlation_id: (optional) transaction id to trace execution through call chain. :param key: a key to uniquely identify the connection parameters. :param connection: a connection to be registered. """
item = DiscoveryItem() item.key = key item.connection = connection self._items.append(item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_one(self, correlation_id, key): """ Resolves a single connection parameters by its key. :param correlation_id: (optional) transaction id to trace execution through call chain. :param key: a key to uniquely identify the connection. :return: a resolved connection. """
connection = None for item in self._items: if item.key == key and item.connection != None: connection = item.connection break return connection
<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_chunks(string, num_chars): """Yield num_chars-character chunks from string."""
for start in range(0, len(string), num_chars): yield string[start:start+num_chars]
<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_package_config(reload_=False): """Loads the package configurations from the global `acorn.cfg` file. """
global _packages from acorn.config import settings packset = settings("acorn", reload_) if packset.has_section("acorn.packages"): for package, value in packset.items("acorn.packages"): _packages[package] = value.strip() == "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 load_decorate(package): """Imports and decorates the package with the specified name. """
# We import the decoration logic from acorn and then overwrite the sys.module # for this package with the decorated, original pandas package. from acorn.logging.decoration import set_decorating, decorating #Before we do any imports, we need to set that we are decorating so that #everything works as if `acorn` wasn't even here. origdecor = decorating set_decorating(True) #If we try and import the module directly, we will get stuck in a loop; at #some point we must invoke the built-in module loader from python. We do #this by removing our sys.path hook. import sys from importlib import import_module apack = import_module(package) from acorn.logging.decoration import decorate decorate(apack) sys.modules["acorn.{}".format(package)] = apack #Set the decoration back to what it was. from acorn.logging.decoration import set_decorating set_decorating(origdecor) return apack
<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_file(self, path, dryrun): """ Remove files and return filename. """
# if dryrun just return file path if dryrun: return path # remove and return file if self.__force or raw_input("Remove file '%s'? [y/N]" % path).lower() == "y": os.remove(path) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_module(self, fullname, path=None): """ Find the appropriate loader for module ``name`` :param fullname: ``__name__`` of the module to import :type fullname: str :param path: ``__path__`` of the *parent* package already imported :type path: str or None """
# path points to the top-level package path if any # and we can only import sub-modules/-packages if path is None: return if fullname.startswith(self.module_prefix): return self else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Evaluate the command line arguments, performing the appropriate actions so the application can be started. """
# The list command prevents any other processing of args if self._args.list: self._print_installed_apps(self._args.controller) sys.exit(0) # If app is not specified at this point, raise an error if not self._args.application: sys.stderr.write('\nerror: application not specified\n\n') self._arg_parser.print_help() sys.exit(-1) # If it's a registered app reference by name, get the module name app_module = self._get_application_module(self._args.controller, self._args.application) # Configure logging based upon the flags self._configure_logging(app_module, self._args.verbose, self._args.syslog) # Try and run the controller try: self._controllers[self._args.controller].main(app_module, self._args) except TypeError as error: sys.stderr.write('error: could not start the %s controller for %s' ': %s\n\n' % (self._args.controller, app_module, str(error))) 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 _add_cli_args(self): """Add the cli arguments to the argument parser."""
# Optional cli arguments self._arg_parser.add_argument('-l', '--list', action='store_true', help='List installed sprockets apps') self._arg_parser.add_argument('-s', '--syslog', action='store_true', help='Log to syslog') self._arg_parser.add_argument('-v', '--verbose', action='count', help=('Verbose logging output, use -vv ' 'for DEBUG level logging')) self._arg_parser.add_argument('--version', action='version', version='sprockets v%s ' % __version__) # Controller sub-parser subparsers = self._arg_parser.add_subparsers(dest='controller', help=DESCRIPTION) # Iterate through the controllers and add their cli arguments for key in self._controllers: help_text = self._get_controller_help(key) sub_parser = subparsers.add_parser(key, help=help_text) try: self._controllers[key].add_cli_arguments(sub_parser) except AttributeError: LOGGER.debug('%s missing add_cli_arguments()', key) # The application argument self._arg_parser.add_argument('application', action="store", help='The sprockets app to run')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure_logging(application, verbosity=0, syslog=False): """Configure logging for the application, setting the appropriate verbosity and adding syslog if it's enabled. :param str application: The application module/package name :param int verbosity: 1 == INFO, 2 == DEBUG :param bool syslog: Enable the syslog handler """
# Create a new copy of the logging config that will be modified config = dict(LOGGING) # Increase the logging verbosity if verbosity == 1: config['loggers']['sprockets']['level'] = logging.INFO elif verbosity == 2: config['loggers']['sprockets']['level'] = logging.DEBUG # Add syslog if it's enabled if syslog: config['loggers']['sprockets']['handlers'].append('syslog') # Copy the sprockets logger to the application config['loggers'][application] = dict(config['loggers']['sprockets']) # Configure logging logging_config.dictConfig(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 _get_application_module(self, controller, application): """Return the module for an application. If it's a entry-point registered application name, return the module name from the entry points data. If not, the passed in application name is returned. :param str controller: The controller type :param str application: The application name or module :rtype: str """
for pkg in self._get_applications(controller): if pkg.name == application: return pkg.module_name return application
<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_controllers(self): """Iterate through the installed controller entry points and import the module and assign the handle to the CLI._controllers dict. :return: dict """
controllers = dict() for pkg in pkg_resources.iter_entry_points(group=self.CONTROLLERS): LOGGER.debug('Loading %s controller', pkg.name) controllers[pkg.name] = importlib.import_module(pkg.module_name) return controllers
<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_controller_help(self, controller): """Return the value of the HELP attribute for a controller that should describe the functionality of the controller. :rtype: str|None """
if hasattr(self._controllers[controller], 'HELP'): return self._controllers[controller].HELP return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_installed_apps(self, controller): """Print out a list of installed sprockets applications :param str controller: The name of the controller to get apps for """
print('\nInstalled Sprockets %s Apps\n' % controller.upper()) print("{0:<25} {1:>25}".format('Name', 'Module')) print(string.ljust('', 51, '-')) for app in self._get_applications(controller): print('{0:<25} {1:>25}'.format(app.name, '(%s)' % app.module_name)) print('')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rslv(self, interface: str, name: str=None) -> Tuple[str, int, Optional[str]]: """Return the IP address, port and optionally host IP for one of this Nodes interfaces."""
if name is None: name = self.name key = '{}-{}'.format(name, interface) host = None if 'host' in self.interfaces[key]: host = self.interfaces[key]['host'] return self.interfaces[key]['ip'], self.interfaces[key]['port'], host
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trigger(self, target: str, trigger: str, parameters: Dict[str, Any]={}): """Calls the specified Trigger of another Area with the optionally given parameters. Args: target: The name of the target Area. trigger: The name of the Trigger. parameters: The parameters of the function call. """
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 benchmark(f, n_repeats=3, warmup=True, name=""): """ Run the given function f repeatedly, return the average elapsed time. """
if warmup: f() total_time = 0 for i in range(n_repeats): iter_name = "%s (iter #%d)" % (name, i + 1,) with Timer(iter_name) as t: f() total_time += t.elapsed return total_time / n_repeats
<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_to_dict(item): '''Examine an item of any type and return a true dictionary. If the item is already a dictionary, then the item is returned as-is. Easy. Otherwise, it attempts to interpret it. So far, this routine can handle: * a class, function, or anything with a .__dict__ entry * a legacy mongoEngine document (a class for MongoDb handling) * a list (index positions are used as keys) * a generic object that is iterable * a generic object with members .. versionadded:: 0.0.4 :param item: Any object such as a variable, instance, or function. :returns: A true dictionary. If unable to get convert 'item', then an empty dictionary '{}' is returned. ''' # get type actual_type = detect_type(item) # given the type, do conversion if actual_type=="dict": return item elif actual_type=="list": temp = {} ctr = 0 for entry in item: temp[ctr]=entry ctr += 1 return temp elif actual_type=="mongoengine": return item.__dict__['_data'] elif actual_type=="class": return item.__dict__ elif actual_type=="iterable_dict": # for a 'iterable_dict' create a real dictionary for a ALMOST-dict object. d = {} for key in item: # NO, you can't use iteritems(). The method might not exist. d[key] = item[key] return d elif actual_type=="object": tuples = getmembers(item) d = {} for (key, value) in tuples: d[key] = value return d 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 do_op(field, op, value): ''' used for comparisons ''' if op==NOOP: return True if field==None: if value==None: return True else: return False if value==None: return False if op==LESS: return (field < value) if op==LESSorEQUAL: return (field <= value) if op==GREATERorEQUAL: return (field >= value) if op==GREATER: return (field > value) # for the EQUAL and NOT_EQUAL conditions, additional factors are considered. # for EQUAL, # if they don't match AND the types don't match, # then the STR of the field and value is also tried if op==EQUAL: if (field == value): return True if type(field)==type(value): return False try: field = str(field) value = str(value) return (field == value) except: return False # for NOT_EQUAL, # if they match, then report False # if they don't match AND the types don't match, # then the STR equivalents are also tried. if op==NOT_EQUAL: if (field == value): return False if type(field)==type(value): return True try: field = str(field) value = str(value) return (field != value) except: 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 get_value(row, field_name): ''' Returns the value found in the field_name attribute of the row dictionary. ''' result = None dict_row = convert_to_dict(row) if detect_list(field_name): temp = row for field in field_name: dict_temp = convert_to_dict(temp) temp = dict_temp.get(field, None) result = temp else: result = dict_row.get(field_name, None) 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 select(table, index_track, field_name, op, value, includeMissing): '''Modifies the table and index_track lists based on the comparison. ''' result = [] result_index = [] counter = 0 for row in table: if detect_fields(field_name, convert_to_dict(row)): final_value = get_value(row, field_name) if do_op(final_value, op, value): result.append(row) result_index.append(index_track[counter]) else: if includeMissing: result.append(row) result_index.append(index_track[counter]) counter += 1 #table = result #index_track = result_index return (result, result_index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def capture(package, prefix, modules=[], level=logging.DEBUG): """ Capture log messages for the given modules and archive them to a ``LogFile`` resource. """
handler = LogFileHandler(package, prefix) formatter = logging.Formatter(FORMAT) handler.setFormatter(formatter) modules = set(modules + ['loadkit']) for logger in modules: if not hasattr(logger, 'addHandler'): logger = logging.getLogger(logger) logger.setLevel(level=level) logger.addHandler(handler) return handler
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(package, prefix, offset=0, limit=1000): """ Load lines from the log file with pagination support. """
logs = package.all(LogFile, unicode(prefix)) logs = sorted(logs, key=lambda l: l.name, reverse=True) seen = 0 record = None tmp = tempfile.NamedTemporaryFile(suffix='.log') for log in logs: shutil.copyfileobj(log.fh(), tmp) tmp.seek(0) for line in reversed(list(tmp)): seen += 1 if seen < offset: continue if seen > limit: tmp.close() return try: d, mo, l, m = line.split(' %s ' % SEP, 4) if record is not None: yield record record = {'time': d, 'module': mo, 'level': l, 'message': m} except ValueError: if record is not None: record['message'] += '\n' + line tmp.seek(0) tmp.close() if record is not None: yield record
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(): """ Clean data created by this script """
for queue in MyQueue.collection().instances(): queue.delete() for job in MyJob.collection().instances(): job.delete() for person in Person.collection().instances(): person.delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, queue): """ Create the fullname, and store a a message serving as result in the job """
# add some random time to simulate a long job time.sleep(random.random()) # compute the fullname obj = self.get_object() obj.fullname.hset('%s %s' % tuple(obj.hmget('firstname', 'lastname'))) # this will the "result" of the job result = 'Created fullname for Person %s: %s' % (obj.pk.get(), obj.fullname.hget()) # save the result of the callback in the job itself self.result.set(result) # return the result for future use in the worker 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 job_success(self, job, queue, job_result): """ Update the queue's dates and number of jobs managed, and save into the job the result received by the callback. """
# display what was done obj = job.get_object() message = '[%s|%s] %s [%s]' % (queue.name.hget(), obj.pk.get(), job_result, threading.current_thread().name) self.log(message) # default stuff: update job and queue statuses, and do logging super(FullNameWorker, self).job_success(job, queue, job_result) # update the queue's dates queue_fields_to_update = { 'last_job_date': str(datetime.utcnow()) } if not queue.first_job_date.hget(): queue_fields_to_update['first_job_date'] = queue_fields_to_update['last_job_date'] queue.hmset(**queue_fields_to_update) # update the jobs counter on the queue queue.jobs_counter.hincrby(1) # save a ref to the job to display at the end of this example script self.jobs.append(int(job.pk.get()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resource_listing(cls, request) -> [(200, 'Ok', ResourceListingModel)]: '''Return the list of all available resources on the system. Resources are filtered according to the permission system, so querying this resource as different users may bare different results.''' apis = [api.get_swagger_fragment() for api in Api if not api.private] Respond(200, { 'apiVersion': cls.api.version, 'swaggerVersion': cls.api.swagger_version, 'apis': apis })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _extract_models(cls, apis): '''An helper function to extract all used models from the apis.''' # TODO: This would probably be much better if the info would be # extracted from the classes, rather than from the swagger # representation... models = set() for api in apis: for op in api.get('operations', []): models.add(op['type']) for param in op.get('parameters', []): models.add(param.get('type', 'void')) for msg in op['responseMessages']: models.add(msg.get('responseModel', 'void')) # Convert from swagger name representation to classes models = map(lambda m: Model.name_to_cls[m], models) ret = {} for model in models: if model.native_type: continue obj = model.schema.copy() obj['id'] = model.name ret[model.name] = obj return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def api_declaration( cls, request, api_path: (Ptypes.path, String('The path for the info on the resource.'))) -> [ (200, 'Ok', ApiDeclarationModel), (404, 'Not a valid resource.')]: '''Return the complete specification of a single API. Resources are filtered according to the permission system, so querying this resource as different users may bare different results. ''' if api_path in cls.__cache: Respond(200, cls.__cache[api_path]) # Select the resources belonging to this API resources = tuple(filter(lambda ep: ep.api.path == api_path, Resource)) if not resources: Respond(404) apis = [r.get_swagger_fragment() for r in resources if not r.private] cls.__cache[api_path] = { 'apiVersion': cls.api.version, 'swaggerVersion': cls.api.swagger_version, 'basePath': request.url_root[:-1], # Remove trailing slash 'resourcePath': '/{}'.format(api_path), 'apis': apis, 'models': cls._extract_models(apis), 'consumes': ['application/json'], 'produces': ['application/json'] } Respond(200, cls.__cache[api_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 _get_route_info(self, request): """Return information about the current URL."""
resolve_match = resolve(request.path) app_name = resolve_match.app_name # The application namespace for the URL pattern that matches the URL. namespace = resolve_match.namespace # The instance namespace for the URL pattern that matches the URL. url_name = resolve_match.url_name # The name of the URL pattern that matches the URL. view_name = resolve_match.view_name # Name of the view that matches the URL, incl. namespace if there's one. return { "app_name": app_name or None, "namespace": namespace or None, "url_name": url_name or None, "view_name": view_name or 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 validate_account(self): """Make sure we are able to connect to the right account"""
self._validating = True with self.catch_invalid_credentials(): log.info("Finding a role to check the account id") a_role = list(self.iam.resource.roles.limit(1)) if not a_role: raise AwsSyncrError("Couldn't find an iam role, can't validate the account....") account_id = a_role[0].meta.data['Arn'].split(":", 5)[4] chosen_account = self.accounts[self.environment] if chosen_account != account_id: raise BadCredentials("Don't have credentials for the correct account!", wanted=chosen_account, got=account_id) self._validating = False self._validated = 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 do_GET(self): '''The GET command. ''' if self.path.lower().endswith("?wsdl"): service_path = self.path[:-5] service = self.server.getNode(service_path) if hasattr(service, "_wsdl"): wsdl = service._wsdl # update the soap:location tag in the wsdl to the actual server # location # - default to 'http' as protocol, or use server-specified protocol proto = 'http' if hasattr(self.server,'proto'): proto = self.server.proto serviceUrl = '%s://%s:%d%s' % (proto, self.server.server_name, self.server.server_port, service_path) soapAddress = '<soap:address location="%s"/>' % serviceUrl wsdlre = re.compile('\<soap:address[^\>]*>',re.IGNORECASE) wsdl = re.sub(wsdlre,soapAddress,wsdl) self.send_xml(wsdl) else: self.send_error(404, "WSDL not available for that service [%s]." % self.path) else: self.send_error(404, "Service not found [%s]." % self.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 get_notebook_names(self, path=''): """List all notebook names in the notebook dir and path."""
path = path.strip('/') spec = {'path': path, 'type': 'notebook'} fields = {'name': 1} notebooks = list(self._connect_collection(self.notebook_collection).find(spec,fields)) names = [n['name'] for n in notebooks] return names
<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_notebook(self, model=None, path=''): """Create a new notebook and return its model with no content."""
path = path.strip('/') if model is None: model = {} if 'content' not in model: metadata = current.new_metadata(name=u'') model['content'] = current.new_notebook(metadata=metadata) if 'name' not in model: model['name'] = self.increment_filename('Untitled', path) model['path'] = path model['type'] = 'notebook' model = self.save_notebook(model, model['name'], model['path']) return model
<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_type(stype): ''' Get the python type for a given string describtion for a type. @param stype: The string representing the type to return @return: The python type if available ''' stype = stype.lower() if stype == 'str': return str if stype == 'unicode': if PY2: return unicode else: return str if stype == 'int': return int if stype == 'float': return float if stype == 'bool': return bool raise AppConfigValueException('Unsuported type given: {0}'.format(stype))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _format_message(value, line_length, indent="", first_indent=None): ''' Return a string with newlines so that the given string fits into this line length. At the start of the line the indent is added. This can be used for commenting the message out within a file or to indent your text. All \\t will be replaced with 4 spaces. @param value: The string to get as a commented multiline comment. @param line_length: The length of the line to fill. @param indent: The indent to use for printing or charcter to put in front @param first_indent: The first indent might be shorter. If None then the first line uses the normal indent as the rest of the string. @return: The string with newlines ''' if indent.find('\t'): indent = indent.replace('\t', ' ') result = [] if first_indent is None: first_indent = indent cindent = first_indent tmp = "*" * line_length for ele in value.split(' '): if ele.find('\t') >= 0: ele = ele.replace('\t', ' ') if (len(ele) + len(tmp)) >= line_length: result.append(tmp) tmp = '{0}{1}'.format(cindent, ele) cindent = indent else: tmp = "{0} {1}".format(tmp, ele) result.append(tmp) result = result[1:] return "\n".join(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 init_default_config(self, path): ''' Initialize the config object and load the default configuration. The path to the config file must be provided. The name of the application is read from the config file. The config file stores the description and the default values for all configurations including the application name. @param path: The path to the config config file. ''' if not (os.path.exists(path) and os.path.isfile(path)): raise AppConfigValueException('The given config config file does ' 'not exist. ({0})'.format(path)) cfl = open(path, 'r') data = json.load(cfl) cfl.close() for key in data.keys(): if 'application_name' == key: self.application_name = data[key].lower() continue if 'application_author' == key: self.application_author = data[key].lower() continue if 'application_version' == key: self.application_version = data[key].lower() continue self._add_section_default(key, data[key])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_description(self, section, key): ''' Get the description of a config key. If it does not exist an Exception will be thrown. @param section: the section where the key is stored. @param key: the key to get the description for. @return: A tuple with three elements (description, type, default) ''' if section in self.config_description: if key in self.config_description[section]: desc, value_type, default = \ self.config_description[section][key] return (desc, value_type, default) else: if self.has_option(section, key): # return an empty string since it is possible that a # section is not initialized, this happens if a plugin # that has some config values but is not initialized. return "", str, "" else: raise AppConfigValueException('Key ({0}) does not exist ' 'in section: {1}'.format(key, section)) else: if self.has_section(section): # return an empty string since it is possible that a section # is not initialized, this happens if a plugin that has some # config values but is not initialized. return "", str, "" else: raise AppConfigValueException('Section does not exist ' '[{0}]'.format(section))
<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_default(self): ''' Load the default config files. First the global config file then the user config file. ''' appdir = AppDirs(self.application_name, self.application_author, version=self.application_version) file_name = os.path.join(appdir.site_data_dir, "{0}.conf".format( self.application_name.lower())) if os.path.exists(file_name): self.load(file_name) if os.name is not 'posix' or os.getuid() > 0: config_file = os.path.join(appdir.user_data_dir, '{0}.conf'.format( self.application_name.lower())) if os.path.exists(config_file): self.load(config_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load(self, filename): ''' Load the given config file. @param filename: the filename including the path to load. ''' if not os.path.exists(filename): #print 'Could not load config file [%s]' % (filename) raise AppConfigValueException('Could not load config file {0}'. format(filename)) cfl = open(filename, 'r') if PY2: self.readfp(cfl) else: self.read_file(cfl) cfl.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 get(self, section, key): ''' Get the value of a key in the given section. It will automatically translate the paramter type if the parameter has a type specified with the description. @param section: the section where the key can be found. @param key: the key the value is stored under. @return the value as a string or the specified type. @exception: if the type is specified and the value could not be translated to the given type. ''' section = section.lower() key = key.lower() descr, value_type, default = self.get_description(section, key) value = ConfigParser.get(self, section, key) if value_type == bool: if PY2: if value.lower() not in self._boolean_states: raise AppConfigValueException('Not a boolean: {0}'. format(value)) return self._boolean_states[value.lower()] else: try: return self._convert_to_boolean(value) except ValueError: raise AppConfigValueException('Not a boolean: {0}'. format(value)) return value_type(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 set(self, section, key, value): ''' Set the value for a key in the given section. It will check the type of the value if it is available. If the value is not from the given type it will be transformed to the type. An exception will be thrown if there is a problem with the conversion. @param section: the section of the key @param key: the key where to store the valu @param value: the value to store @exception: If there is a problem with the conversation of the value type. ''' value_type = str if self.has_option(section, key): descr, value_type, default = self.get_description(section, key) if value_type != type(value): if value_type == bool: if ((type(value) in string_types and value.lower() in ('true', 't')) or (type(value) == int and value > 0)): value = True elif ((type(value) in string_types and value.lower() in ('false', 'f')) or (type(value) == int and value == 0)): value = False else: raise AppConfigValueException('Could not convert ' 'boolean type: {0}'.format(value)) else: value = value_type(value) if not self.has_section(section): self.add_section(section) ConfigParser.set(self, section, key, str(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 save(self, filename=None, verbose=False): ''' Save the config to the given file or to given default location. @param filename: the file to write the config @param verbose: If set to true the config file will have all values and all descriptions ''' if filename is None: if (not self.has_section(self.application_name) or not self.has_option(self.application_name, 'config_file')): if not self.has_section(self.application_name): self.add_section(self.application_name) if not self.application_name in self.config_description: self.config_description[self.application_name] = {} appdir = AppDirs(self.application_name, self.application_author, version=self.application_version) value = os.path.join(appdir.user_data_dir, '{0}.conf'.format( self.application_name.lower())) if not self.has_option(self.application_name, 'config_file'): self.set(self.application_name, 'config_file', value) if not ('config_file' in self.config_description[self.application_name]): self.config_description[self.application_name]\ ['config_file'] = ('The config file to ' 'overwrite on change of the config values. ' '[$HOME/.{0}/{0}.conf]'.format( self.application_name), str, value) filename = self.get(self.application_name, 'config_file') if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) hidden = None if self.has_section('hidden'): hidden = self.items('hidden') self.remove_section('hidden') cfp = open(filename, 'w') self._write_config(cfp, verbose) cfp.close() if hidden is not None: for key, value in hidden: self.set('hidden', key, 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 _write_config(self, filedesc, verbose=False): ''' Write the current config to the given filedescriptor which has must be opened for writing. Only the config values different from the default value are written If the verbose switch is turned on the config file generated will have all values including the default values shown but they will be commented out. In addition the description of each paramters is stored before the value. @param filedesc: The file to write the config into @param verbose: The switch between the minimalistic and the more verbose config file. ''' desc = [] for section in self.sections(): if section.lower() in ('', 'hidden'): continue desc.append("") desc.append('[{0}]'.format(section)) for key in self.options(section): descr, value_type, default = self.get_description(section, key) if verbose: desc.append(_format_message(descr, 78, "# ")) desc.append("# Type: [{0}]".format(str(value_type))) desc.append("# {0}={1}".format(key, default)) if not self.get(section, key) == default: desc.append('{0}={1}'.format(key, self.get(section, key))) if verbose: desc.append("") filedesc.write("{0}\n".format("\n".join(desc[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 serialize(self, data): """ Call json.dumps & let it rip """
super(Serializer, self).serialize(data) self.resp.body = json.dumps(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 surround_previous_word(input_str): ''' Surround last word in string with parentheses. If last non-whitespace character is delimiter, do nothing ''' start = None end = None for i, char in enumerate(reversed(input_str)): if start is None: if char in '{}()[]<>?|': return input_str elif char != ' ': start = i else: if char in '{}()[]<>?| ': end = i break if start is None: return input_str if end is None: end = len(input_str) new_str = '' for i, char in enumerate(reversed(input_str)): if char == ' ' and i + 1 == start: continue if i == start: new_str += ') ' elif i == end: new_str += '(' new_str += char if end == len(input_str): new_str += '(' return new_str[::-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 _limit_call_handler(self): """ Ensure we don't exceed the N requests a minute limit by leveraging a thread lock """
# acquire a lock on our threading.Lock() object with self.limit_lock: # if we have no configured limit, exit. the lock releases based on scope if self.limit_per_min <= 0: return now = time.time() # self.limits is a list of query times + 60 seconds. In essence it is a list of times # that queries time out of the 60 second query window. # this check expires any limits that have passed self.limits = [l for l in self.limits if l > now] # and we tack on the current query self.limits.append(now + 60) # if we have more than our limit of queries (and remember, we call this before we actually # execute a query) we sleep until the oldest query on the list (element 0 because we append # new queries) times out. We don't worry about cleanup because next time this routine runs # it will clean itself up. if len(self.limits) >= self.limit_per_min: time.sleep(self.limits[0] - now)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roughpage(request, url): """ Public interface to the rough page view. """
if settings.APPEND_SLASH and not url.endswith('/'): # redirect to the url which have end slash return redirect(url + '/', permanent=True) # get base filename from url filename = url_to_filename(url) # try to find the template_filename with backends template_filenames = get_backend().prepare_filenames(filename, request=request) # add extra prefix path root = settings.ROUGHPAGES_TEMPLATE_DIR template_filenames = [os.path.join(root, x) for x in template_filenames] try: t = loader.select_template(template_filenames) return render_roughpage(request, t) except TemplateDoesNotExist: if settings.ROUGHPAGES_RAISE_TEMPLATE_DOES_NOT_EXISTS: raise raise Http404
<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_roughpage(request, t): """ Internal interface to the rough page view. """
import django if django.VERSION >= (1, 8): c = {} response = HttpResponse(t.render(c, request)) else: c = RequestContext(request) response = HttpResponse(t.render(c)) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_form_media_type(media_type): """ Return True if the media type is a valid form media type. """
base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING)) return (base_media_type == 'application/x-www-form-urlencoded' or base_media_type == 'multipart/form-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 clone_request(request, method): """ Internal helper method to clone a request, replacing with a different HTTP method. Used for checking permissions against other methods. """
ret = Request(request=request._request, parsers=request.parsers, authenticators=request.authenticators, negotiator=request.negotiator, parser_context=request.parser_context) ret._data = request._data ret._files = request._files ret._full_data = request._full_data ret._content_type = request._content_type ret._stream = request._stream ret.method = method if hasattr(request, '_user'): ret._user = request._user if hasattr(request, '_auth'): ret._auth = request._auth if hasattr(request, '_authenticator'): ret._authenticator = request._authenticator if hasattr(request, 'accepted_renderer'): ret.accepted_renderer = request.accepted_renderer if hasattr(request, 'accepted_media_type'): ret.accepted_media_type = request.accepted_media_type if hasattr(request, 'version'): ret.version = request.version if hasattr(request, 'versioning_scheme'): ret.versioning_scheme = request.versioning_scheme return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user(self, value): """ Sets the user on the current request. This is necessary to maintain compatibility with django.contrib.auth where the user property is set in the login and logout functions. Note that we also set the user on Django's underlying `HttpRequest` instance, ensuring that it is available to any middleware in the stack. """
self._user = value self._request.user = 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 auth(self, value): """ Sets any non-user authentication information associated with the request, such as an authentication token. """
self._auth = value self._request.auth = 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 _load_data_and_files(self): """ Parses the request content into `self.data`. """
if not _hasattr(self, '_data'): self._data, self._files = self._parse() if self._files: self._full_data = self._data.copy() self._full_data.update(self._files) else: self._full_data = 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 _load_stream(self): """ Return the content body of the request, as a stream. """
meta = self._request.META try: content_length = int( meta.get('CONTENT_LENGTH', meta.get('HTTP_CONTENT_LENGTH', 0)) ) except (ValueError, TypeError): content_length = 0 if content_length == 0: self._stream = None elif hasattr(self._request, 'read'): self._stream = self._request else: self._stream = six.BytesIO(self.raw_post_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 generate_antonym(self, input_word): """ Generate an antonym using a Synset and its lemmas. """
results = [] synset = wordnet.synsets(input_word) for i in synset: if i.pos in ['n','v']: for j in i.lemmas: if j.antonyms(): name = j.antonyms()[0].name results.append(PataLib().strip_underscore(name)) results = {'input' : input_word, 'results' : results, 'category' : 'antonym'} return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, name, default=None): """ Returns an extension instance with a given name. In case there are few extensions with a given name, the first one will be returned. If no extensions with a given name are exist, the `default` value will be returned. :param name: (str) an extension name :param default: (object) a fallback value :returns: (object) an extension instance """
try: value = self[name] except KeyError: value = default 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 sort(line): """ change point position if x1,y0 < x0,y0 """
x0, y0, x1, y1 = line # if (x0**2+y0**2)**0.5 < (x1**2+y1**2)**0.5: # return (x1,y1,x0,y0) # return line # # if x1 < x0: # return (x1,y1,x0,y0) # return line turn = False if abs(x1 - x0) > abs(y1 - y0): if x1 < x0: turn = True elif y1 < y0: turn = True if turn: return (x1, y1, x0, y0) # return line[(2,3,0,1)] return line