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 subjects_get(self, resource_url): """Get handle for subject resource at given Url. Parameters resource_url : string Url for subject resource at SCO-API Returns ------- scoserv.SubjectHandle Handle for local copy of subject resource """
# Get resource directory, Json representation, active flag, and cache id obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url) # Create subject handle. Will raise an exception if resource is not # in cache and cannot be downloaded. subject = SubjectHandle(obj_json, obj_dir) # Add resource to cache if not exists if not cache_id in self.cache: self.cache_add(resource_url, cache_id) # Return subject handle return subject
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subjects_list(self, api_url=None, offset=0, limit=-1, properties=None): """Get list of subject resources from a SCO-API. Parameters api_url : string, optional Base Url of the SCO-API. Uses default API if argument not present. offset : int, optional Starting offset for returned list items limit : int, optional Limit the number of items in the result properties : List(string) List of additional object properties to be included for items in the result Returns ------- List(scoserv.ResourceHandle) List of resource handles (one per subject in the listing) """
# Get subject listing Url for given SCO-API and return the retrieved # resource listing return sco.get_resource_listing( self.get_api_references(api_url)[sco.REF_SUBJECTS_LIST], offset, limit, properties )
<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_disposable(clientInfo, config = {}): """ Create a new disposable client. """
response = requests.put( _format_url( _extend(DEFAULT_CONFIG, config), OAUTH2_ROOT + 'disposable'), json = clientInfo) if response.status_code != 200: return None else: body = response.json() return Blotre({ 'client_id': body['id'], 'client_secret': body['secret'], 'code': body['code'] }, config = 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_existing_disposable_app(file, clientInfo, conf): """ Attempt to load an existing """
if not os.path.isfile(file): return None else: data = None with open(file, 'r') as f: data = json.load(f) if not 'client' in data or not 'creds' in data: return None return _BlotreDisposableApp(file, data['client'], creds = data['creds'], config = 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 _try_redeem_disposable_app(file, client): """ Attempt to redeem a one time code registred on the client. """
redeemedClient = client.redeem_onetime_code(None) if redeemedClient is None: return None else: return _BlotreDisposableApp(file, redeemedClient.client, creds = redeemedClient.creds, config = redeemedClient.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 _check_app_is_valid(client): """ Check to see if the app has valid creds. """
try: if 'refresh_token' in client.creds: client.exchange_refresh_token() else: existing.get_token_info() return True except TokenEndpointError as e: 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 create_disposable_app(clientInfo, config={}): """ Use an existing disposable app if data exists or create a new one and persist the data. """
file = _get_disposable_app_filename(clientInfo) existing = _get_existing_disposable_app(file, clientInfo, config) if existing: if _check_app_is_valid(existing): return existing else: print("Existing client has expired, must recreate.") return _create_new_disposable_app(file, clientInfo, 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 set_creds(self, newCreds): """Manually update the current creds."""
self.creds = newCreds self.on_creds_changed(newCreds) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_uri(self, uri): """Convert a stream path into it's normalized form."""
return urllib.quote( re.sub(r"\s", '+', uri.strip().lower()), safe = '~@#$&()*!+=:),.?/\'')
<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_authorization_url(self): """Get the authorization Url for the current client."""
return self._format_url( OAUTH2_ROOT + 'authorize', query = { 'response_type': 'code', 'client_id': self.client.get('client_id', ''), 'redirect_uri': self.client.get('redirect_uri', '') })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _access_token_endpoint(self, grantType, extraParams={}): """ Base exchange of data for an access_token. """
response = requests.post( self._format_url(OAUTH2_ROOT + 'access_token'), data = _extend({ 'grant_type': grantType, 'client_id': self.client.get('client_id', ''), 'client_secret': self.client.get('client_secret', ''), 'redirect_uri': self.client.get('redirect_uri', '') }, extraParams)) data = response.json() if 'error' in data or 'error_description' in data: raise _token_error_from_data(data) else: return self.set_creds(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_token_info(self): """ Get information about the current access token. """
response = requests.get( self._format_url(OAUTH2_ROOT + 'token_info', { 'token': self.creds['access_token'] })) data = response.json() if response.status_code != 200: raise _token_error_from_data(data) else: 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 _add_auth_headers(self, base): """Attach the acces_token to a request."""
if 'access_token' in self.creds: return _extend(base, { 'authorization': 'Bearer ' + self.creds['access_token'] }) return base
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_expired_response(self, response): """ Check if the response failed because of an expired access token. """
if response.status_code != 401: return False challenge = response.headers.get('www-authenticate', '') return 'error="invalid_token"' in challenge
<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_request(self, type, path, args, noRetry=False): """ Make a request to Blot're. Attempts to reply the request if it fails due to an expired access token. """
response = getattr(requests, type)(path, headers = self._add_auth_headers(_JSON_HEADERS), **args) if response.status_code == 200 or response.status_code == 201: return response.json() elif not noRetry and self._is_expired_response(response) \ and 'refresh_token' in self.creds: try: self.exchange_refresh_token() except TokenEndpointError: raise _rest_error_from_response(response) return self._make_request(type, path, args, noRetry = True) raise _rest_error_from_response(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 put(self, path, body): """PUT request."""
return self._make_request('put', self._format_url(API_ROOT + path), { 'json': body })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_child(self, streamId, childId, options={}): """Get the child of a stream."""
return self.get('stream/' + streamId + '/children/' + childId, options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _persist(self): """Persist client data."""
with open(self.file, 'w') as f: json.dump({ 'client': self.client, 'creds': self.creds, 'config': self.config }, f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def options(self, parser, env=os.environ): """Handle parsing additional command-line options"""
super(PerfDumpPlugin, self).options(parser, env=env) parser.add_option("", "--perfdump-html", dest="perfdump_html_file", help="Set destination for HTML report output")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def configure(self, options, conf): """Configure this plugin using the given options"""
super(PerfDumpPlugin, self).configure(options, conf) if not self.enabled: return try: self.html_output_file = options.perfdump_html_file except: pass self.db = SqliteConnection.get(self.database_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 report(self, stream): """Displays the slowest tests"""
self.db.commit() stream.writeln() self.draw_header(stream, "10 SLOWEST SETUPS") self.display_slowest_setups(stream) stream.writeln() self.draw_header(stream, "10 SLOWEST TESTS") self.display_slowest_tests(stream) stream.writeln() if self.html_output_file: HtmlReport.write(self.html_output_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 draw_header(self, stream, header): """Draw header with underline"""
stream.writeln('=' * (len(header) + 4)) stream.writeln('| ' + header + ' |') stream.writeln('=' * (len(header) + 4)) stream.writeln()
<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(self, sought, view='lemma'): ''' Returns a word instance for the hit if the "sought" word is found in the text. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option. ''' hits = [] for sentence in self._sentences: hits += sentence.find(sought, view) return hits
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find(self, sought, view='lemma'): ''' Returns a word instance for the hit if the "sought" word is found in the sentence. Per default the "lemma" view of the words is compared. You can specify the desired view with the optional "view" option. ''' for word in self.wordlist: if sought == word.views[view]: yield word
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def word(self, position): ''' Returns the word instance at the given position in the sentence, None if not found. ''' if 0 <= position < len(self.wordlist): return self.wordlist[position] else: log.warn('position "{}" is not in sentence of length "{}"!'.format(position, len(self.wordlist))) raise IndexError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def neighbors(self): ''' Returns the left and right neighbors as Word instance. If the word is the first one in the sentence only the right neighbor is returned and vice versa. ''' if len(self._sentence) == 1: return { 'left': None, 'right': None } else: p = self._position if -1 < p < len(self._sentence): if 0 == self._position: return { 'left': None, 'right': self._sentence.word(p+1) } elif 0 < self._position < len(self._sentence) - 1: return { 'left': self._sentence.word(p-1), 'right': self._sentence.word(p+1) } else: return { 'left': self._sentence.word(p-1), 'right': None } else: raise IndexError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stdrepr_iterable(self, obj, *, cls=None, before=None, after=None): """ Helper function to represent iterables. StdHRepr calls this on lists, tuples, sets and frozensets, but NOT on iterables in general. This method may be called to produce custom representations. Arguments: obj (iterable): The iterable to represent. cls (optional): The class name for the representation. If None, stdrepr will use ``'hrepr-' + obj.__class__.___name__`` before (optional): A string or a Tag to prepend to the elements. after (optional): A string or a Tag to append to the elements. """
if cls is None: cls = f'hrepr-{obj.__class__.__name__}' children = [self(a) for a in obj] return self.titled_box((before, after), children, 'h', 'h')[cls]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stdrepr_object(self, title, elements, *, cls=None, short=False, quote_string_keys=False, delimiter=None): """ Helper function to represent objects. Arguments: title: A title string displayed above the box containing the elements, or a pair of two strings that will be displayed left and right (e.g. a pair of brackets). elements: A list of (key, value) pairs, which will be displayed in a table in the order given. cls: A class to give to the result. short: Whether to use short or long form. Short form displays the elements as ``k=v``, appended horizontally. The alternative is a table, with associations stacked vertically. quote_string_keys: If True, string keys will be displayed with quotes around them. Default is False. delimiter: The character to use to separate key and value. By default '↦' if quote_string_keys is True. """
H = self.H if delimiter is None and quote_string_keys is True: delimiter = ' ↦ ' def wrap(x): if not quote_string_keys and isinstance(x, str): return x else: return self(x) if short: contents = [] for k, v in elements: kv = H.div['hrepr-object-kvpair']( wrap(k), delimiter or '', self(v) ) contents.append(kv) else: t = H.table()['hrepr-object-table'] for k, v in elements: tr = H.tr(H.td(wrap(k))) if delimiter is not None: tr = tr(H.td['hrepr-delimiter'](delimiter)) tr = tr(H.td(self(v))) # t = t(H.tr(H.td(wrap(k)), H.td(self(v)))) t = t(tr) contents = [t] title_brackets = isinstance(title, tuple) and len(title) == 2 horizontal = short or title_brackets rval = self.titled_box(title, contents, 'h' if title_brackets else 'v', 'h' if short else 'v') if cls: rval = rval[cls] return rval
<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_matches(text): r"""Find matching files for text. For this completer to function in Unix systems, the readline module must not treat \ and / as delimiters. """
path = os.path.expanduser(text) if os.path.isdir(path) and not path.endswith('/'): return [ text + '/' ] pattern = path + '*' is_implicit_cwd = not (path.startswith('/') or path.startswith('./')) if is_implicit_cwd: pattern = './' + pattern rawlist = glob.glob(pattern) ret = [] for fname in rawlist: if is_implicit_cwd: fname = fname[2:] if os.path.isdir(fname): ret.append(fname + '/') else: ret.append(fname) 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 cli(ctx, dname, site): """ Launches a MySQL CLI session for the database of the specified IPS installation. """
assert isinstance(ctx, Context) log = logging.getLogger('ipsv.mysql') dname = domain_parse(dname).hostname domain = Session.query(Domain).filter(Domain.name == dname).first() # No such domain if not domain: click.secho('No such domain: {dn}'.format(dn=dname), fg='red', bold=True, err=True) return site_name = site site = Site.get(domain, site_name) # No such site if not site: click.secho('No such site: {site}'.format(site=site_name), fg='red', bold=True, err=True) return # Connect to the MySQL database and exit log.info('Connecting to MySQL database: {db}'.format(db=site.db_name)) log.debug('MySQL host: {host}'.format(host=site.db_host)) log.debug('MySQL username: {user}'.format(user=site.db_user)) log.debug('MySQL password: {pwd}'.format(pwd=site.db_pass)) os.execl( '/usr/bin/mysql', '/usr/bin/mysql', '--database={db}'.format(db=site.db_name), '--user={user}'.format(user=site.db_user), '--password={pwd}'.format(pwd=site.db_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 target_query(plugin, port, location): """ prepared ReQL for target """
return ((r.row[PLUGIN_NAME_KEY] == plugin) & (r.row[PORT_FIELD] == port) & (r.row[LOCATION_FIELD] == location))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enums(*names): """Returns a set of `EnumValue` objects with specified names and optionally orders. Values in an enumeration must have unique names and be either all ordered or all unordered. """
if len(names) != len(list(set(names))): raise TypeError("Names in an enumeration must be unique") item_types = set(True if isinstance(x, tuple) else False for x in names) if len(item_types) == 2: raise TypeError("Mixing of ordered and unordered enumeration items is not allowed") else: is_ordered = item_types.pop() is True if not is_ordered: names = [(None, x) for x in names] return [EnumValue(name, order) for order, name in 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 run(self, args=None): """Applicatin starting point. This will run the associated method/function/module or print a help list if it's an unknown keyword or the syntax is incorrect. Keyword arguments: args -- Custom application arguments (default sys.argv) """
# TODO: Add tests to how command line arguments are passed in raw_args = self.__parser.parse_args(args=args) args = vars(raw_args) cmd = args.pop('cmd') if hasattr(cmd, '__call__'): cmd(**args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_seconds(string): """ Converts a human readable time string into seconds. Accepts: - 's': seconds - 'm': minutes - 'h': hours - 'd': days Examples: 90 300 3600 5400 259200 Traceback (most recent call last): ValueError """
units = { 's': 1, 'm': 60, 'h': 60 * 60, 'd': 60 * 60 * 24 } match = re.search(r'(?:(?P<d>\d+)d)?(?:(?P<h>\d+)h)?(?:(?P<m>\d+)m)?(?:(?P<s>\d+)s)?', string) if not match or not any(match.groups()): raise ValueError total = 0 for unit, seconds in units.iteritems(): if match.group(unit) is not None: total += int(match.group(unit)) * seconds return total
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def slice_reStructuredText(input, output): """ Slices given reStructuredText file. :param input: ReStructuredText file to slice. :type input: unicode :param output: Directory to output sliced reStructuredText files. :type output: unicode :return: Definition success. :rtype: bool """
LOGGER.info("{0} | Slicing '{1}' file!".format(slice_reStructuredText.__name__, input)) file = File(input) file.cache() slices = OrderedDict() for i, line in enumerate(file.content): search = re.search(r"^\.\. \.(\w+)", line) if search: slices[search.groups()[0]] = i + SLICE_ATTRIBUTE_INDENT index = 0 for slice, slice_start in slices.iteritems(): slice_file = File(os.path.join(output, "{0}.{1}".format(slice, OUTPUT_FILES_EXTENSION))) LOGGER.info("{0} | Outputing '{1}' file!".format(slice_reStructuredText.__name__, slice_file.path)) slice_end = index < (len(slices.values()) - 1) and slices.values()[index + 1] - SLICE_ATTRIBUTE_INDENT or \ len(file.content) for i in range(slice_start, slice_end): skip_line = False for item in CONTENT_DELETION: if re.search(item, file.content[i]): LOGGER.info("{0} | Skipping Line '{1}' with '{2}' content!".format(slice_reStructuredText.__name__, i, item)) skip_line = True break if skip_line: continue line = file.content[i] for pattern, value in STATEMENT_SUBSTITUTE.iteritems(): line = re.sub(pattern, value, line) search = re.search(r"- `[\w ]+`_ \(([\w\.]+)\)", line) if search: LOGGER.info("{0} | Updating Line '{1}' link: '{2}'!".format(slice_reStructuredText.__name__, i, search.groups()[0])) line = "- :ref:`{0}`\n".format(search.groups()[0]) slice_file.content.append(line) slice_file.write() index += 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 get(self): """ Fetch all licenses associated with our account @rtype: list of LicenseMeta """
response = requests.get(self.URL, cookies=self.cookiejar) self.log.debug('Response code: %s', response.status_code) if response.status_code != 200: raise HtmlParserError soup = BeautifulSoup(response.text, "html.parser") com_pattern = re.compile('\((.+)\)') package_list = soup.find('ul', {'id': 'package_list'}) package_items = package_list.find_all('li') licenses = [] for item in package_items: div = item.find('div', {'class': 'product_info'}) a = div.find('a') licenses.append( LicenseMeta( div.find('span', {'class': 'desc'}).text, a.get('href'), com_pattern.search(a.text).group(1) ) ) return licenses
<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_app_status(system_key): """ Get Undergraduate application status @return ApplicationStatus object @InvalidSystemKey if system_key is not valid """
if invalid_system_key(system_key): raise InvalidSystemKey( "Invalid system key in get_app_status({})".format(system_key)) url = get_appstatus_url(system_key) response = DAO.getURL(url, {}) response_data = str(response.data) if response.status != 200: raise DataFailureException(url, response.status, response_data) if len(response.data) == 0: is_cached = (type(response) == restclients_core.models.MockHttp) raise Exception( "{} Unexpected Response Data: {}, from cache: {}".format( url, response_data, str(is_cached))) status = parse_statuses(response_data) return status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hint(invertible=True, callable=None, **hints): """ A decorator that can optionally hang datanommer hints on a rule. """
def wrapper(fn): # Hang hints on fn. fn.hints = hints fn.hinting_invertible = invertible fn.hinting_callable = callable return fn 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 gather_hinting(config, rules, valid_paths): """ Construct hint arguments for datanommer from a list of rules. """
hinting = collections.defaultdict(list) for rule in rules: root, name = rule.code_path.split(':', 1) info = valid_paths[root][name] if info['hints-callable']: # Call the callable hint to get its values result = info['hints-callable'](config=config, **rule.arguments) # If the rule is inverted, but the hint is not invertible, then # there is no hinting we can provide. Carry on. if rule.negated and not info['hints-invertible']: continue for key, values in result.items(): # Negate the hint if necessary key = 'not_' + key if rule.negated else key hinting[key].extend(values) # Then, finish off with all the other ordinary, non-callable hints for key, value in info['datanommer-hints'].items(): # If the rule is inverted, but the hint is not invertible, then # there is no hinting we can provide. Carry on. if rule.negated and not info['hints-invertible']: continue # Otherwise, construct the inverse hint if necessary key = 'not_' + key if rule.negated else key # And tack it on. hinting[key] += value log.debug('gathered hinting %r', hinting) return hinting
<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_feed_list(feed, amount=None, list_class=None, li_class=None, list_type='ul'): """Generates a HTML list with items from a feed :param feed: The feed to generate the list from. :type feed: Feed :param amount: The amount of items to show. :type amount: int :param ul_class: The <ul> or <ol> class to use. :type ul_class: str :param li_class: The <li> class to use. :type li_class: str :param list_type: The list type to use. Defaults to 'ul' :type list_type: str :raises: ValueError """
if feed.feed_type == 'twitter': ret = ['<%s class="%s">' % (list_type, list_class or 'tweet-list')] tweets = feed.tweets.all() if amount: if not int(amount): raise ValueError('Amount must be a number') tweets = tweets[:amount] for t in tweets: ret.append( '<li class="%s">' '<div class="tweet-profile-picture">' '<img src="%s" alt="Twitter profile picture of %s" width="48" height="48" /></div>' '<div class="tweet-body">%s</div></li>' % (li_class or 'tweet', t.profile_image_url, t.from_user_name, t.text)) if feed.feed_type == 'rss': ret = ['<%s class="%s">' % (list_type, list_class or 'rss-list')] rss_items = feed.rss_items.all() if amount: if not int(amount): raise ValueError('Amount must be a number') rss_items = rss_items[:amount] for t in rss_items: ret.append( '<li class="%s">' '<div class="rss-item-body">%s</div></li>' % (li_class or 'rss-item', t.description)) ret.append('</%s>' % list_type) return ''.join(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 chunks(f, chunk_size=None): """ Read the file and yield chucks of ``chunk_size`` bytes. """
if not chunk_size: chunk_size = 64 * 2 ** 10 if hasattr(f, "seek"): f.seek(0) while True: data = f.read(chunk_size) if not data: break yield 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(self, name, content): """ Saves new content to the file specified by name. The content should be a proper File object, ready to be read from the beginning. """
# Get the proper name for the file, as it will actually be saved. if name is None: name = content.name name = self.get_available_name(name) name = self._save(name, content) # Store filenames with forward slashes, even on Windows return name.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 print_banner(filename: str, template: str = DEFAULT_BANNER_TEMPLATE) -> None: """ Print text file to output. :param filename: Which file to print. :param template: Format string which specified banner arrangement. :return: Does not return anything """
if not os.path.isfile(filename): logger.warning("Can't find logo banner at %s", filename) return with open(filename, "r") as f: banner = f.read() formatted_banner = template.format(banner) print(formatted_banner)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def repr_feature(feature, max_keys=100, indent=8, lexigraphic=False): ''' generate a pretty-printed string for a feature Currently implemented: * StringCounter @max_keys: truncate long counters @indent: indent multi-line displays by this many spaces @lexigraphic: instead of sorting counters by count (default), sort keys lexigraphically ''' if isinstance(feature, (str, bytes)): try: ustr = feature.decode('utf8') return ustr except: # failure to decode, not actually utf8, other binary data return repr(feature) if isinstance(feature, StringCounter): return repr_stringcounter(feature, max_keys, indent, lexigraphic) elif isinstance(feature, unicode): return feature else: return repr(feature) assert False, 'internal logic failure, no branch taken'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def only_specific_multisets(ent, multisets_to_show): ''' returns a pretty-printed string for specific features in a FeatureCollection ''' out_str = [] for mset_name in multisets_to_show: for key, count in ent[mset_name].items(): out_str.append( '%s - %d: %s' % (mset_name, count, key) ) return '\n'.join(out_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tolerate(substitute=None, exceptions=None, switch=DEFAULT_TOLERATE_SWITCH): """ A function decorator which makes a function fail silently To disable fail silently in a decorated function, specify ``fail_silently=False``. To disable fail silenlty in decorated functions globally, specify ``tolerate.disabled``. Parameters fn : function A function which will be decorated. substitute : function or returning value A function used instead of :attr:`fn` or returning value when :attr:`fn` failed. exceptions : list of exceptions or None A list of exception classes or None. If exceptions is specified, ignore exceptions only listed in this parameter and raise exception if the exception is not listed. switch : string, list/tuple, dict, function or None A switch function which determine whether silent the function failar. The function receive ``*args`` and ``**kwargs`` which will specified to :attr:`fn` and should return status (bool), args, and kwargs. If the function return ``False`` then agggressive decorated function worked as normal function (raise exception when there is exception). Default switch function is generated by :func:`argument_switch_generator` with ``argument_switch_generator('fail_silently')`` so if ``fail_silently=False`` is specified to the function, the function works as noramlly. **From Version 0.1.1**, when switch is specified as non functional value, :func:`argument_switch_generator` will be called with switch as arguments. If string is specified, the switch generator will be called as ``argument_switch_generator(switch)``. If list or tuple is specified, the switch generator will be called as ``argument_switch_generator(*switch)``. If dict is specified, the switch generator will be called as ``argument_switch_generator(**switch)``. Returns ------- function A decorated function Examples -------- 0 0 True 0 0 'zero' 0 True True Traceback (most recent call last): AttributeError Traceback (most recent call last): KeyError Traceback (most recent call last): ValueError True Traceback (most recent call last): Traceback (most recent call last): True True True Traceback (most recent call last): """
def decorator(fn): @wraps(fn) def inner(*args, **kwargs): if getattr(tolerate, 'disabled', False): # the function has disabled so call normally. return fn(*args, **kwargs) if switch is not None: status, args, kwargs = switch(*args, **kwargs) if not status: # the switch function return `False` so call noramlly. return fn(*args, **kwargs) try: return fn(*args, **kwargs) except: e = sys.exc_info()[1] if exceptions is None or e.__class__ in exceptions: if _is_callable(substitute): return substitute(*args, **kwargs) return substitute raise e return inner if switch: # create argument switch if switch is string or list or dict if isinstance(switch, basestring): switch = argument_switch_generator(switch) elif isinstance(switch, (list, tuple)): switch = argument_switch_generator(*switch) elif isinstance(switch, dict): switch = argument_switch_generator(**switch) 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 emit(self, action, payload): """Emit action with payload via `requests.post`."""
url = self.get_emit_api(action) headers = { 'User-Agent': 'rio/%s' % VERSION, 'X-Rio-Protocol': '1', } args = dict( url=url, json=payload, headers=headers, timeout=self.timeout, ) resp = requests.post(**args) data = resp.json() is_success = resp.status_code == 200 result = dict( is_success=is_success, message=data['message'], ) if result['is_success']: result.update( event_uuid=data['event']['uuid'], task_id=data['task']['id'], ) 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 _compile_and_collapse(self): """Actually compile the requested regex"""
self._real_regex = self._real_re_compile(*self._regex_args, **self._regex_kwargs) for attr in self._regex_attributes_to_copy: setattr(self, attr, getattr(self._real_regex, attr))
<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_params(func, *args, **kwargs): """Turn an argument list into a dictionary. :arg function func: A function. :arg list *args: Positional arguments of `func`. :arg dict **kwargs: Keyword arguments of `func`. :returns dict: Dictionary representation of `args` and `kwargs`. """
params = dict(zip(func.func_code.co_varnames[:len(args)], args)) if func.func_defaults: params.update(dict(zip( func.func_code.co_varnames[-len(func.func_defaults):], func.func_defaults))) params.update(kwargs) return 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 _check_type(name, obj, expected_type): """ Raise a TypeError if object is not of expected type """
if not isinstance(obj, expected_type): raise TypeError( '"%s" must be an a %s' % (name, expected_type.__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 _import_module(module_name): """ Imports the module dynamically _import_module('foo.bar') calls: __import__('foo.bar', globals(), locals(), ['bar', ], 0) """
fromlist = [] dot_position = module_name.rfind('.') if dot_position > -1: fromlist.append( module_name[dot_position+1:len(module_name)] ) # Import module module = __import__(module_name, globals(), locals(), fromlist, 0) return module
<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, module_name, class_name, args=None, kwargs=None, factory_method=None, factory_args=None, factory_kwargs=None, static=False, calls=None): """ Initializes an instance of the service """
if args is None: args = [] if kwargs is None: kwargs = {} if factory_args is None: factory_args = [] if factory_kwargs is None: factory_kwargs = {} if static is None: static = False # Verify _verify_create_args(module_name, class_name, static) # Import module = _import_module(module_name) # Instantiate service_obj = self._instantiate(module, class_name, args, kwargs, static) # Factory? if factory_method is not None: service_obj = self._handle_factory_method(service_obj, factory_method, factory_args, factory_kwargs) # Extra Calls if calls is not None and isinstance(calls, list): self._handle_calls(service_obj, calls) # Return return service_obj
<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_from_dict(self, dictionary): """ Initializes an instance from a dictionary blueprint """
# Defaults args = [] kwargs = {} factory_method = None factory_args = [] factory_kwargs = {} static = False calls = None # Check dictionary for arguments if 'args' in dictionary: args = dictionary['args'] if 'kwargs' in dictionary: kwargs = dictionary['kwargs'] if 'factory-method' in dictionary: factory_method = dictionary['factory-method'] if 'factory-args' in dictionary: factory_args = dictionary['factory-args'] if 'factory-kwargs' in dictionary: factory_kwargs = dictionary['factory-kwargs'] if 'static' in dictionary: static = dictionary['static'] if 'calls' in dictionary: calls = dictionary['calls'] return self.create( dictionary['module'], dictionary['class'], args=args, kwargs=kwargs, factory_method=factory_method, factory_args=factory_args, factory_kwargs=factory_kwargs, static=static, calls=calls )
<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_instantiated_service(self, name): """ Get instantiated service by name """
if name not in self.instantiated_services: raise UninstantiatedServiceException return self.instantiated_services[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 _replace_service_arg(self, name, index, args): """ Replace index in list with service """
args[index] = self.get_instantiated_service(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 _replace_scalars_in_args(self, args): """ Replace scalars in arguments list """
_check_type('args', args, list) new_args = [] for arg in args: if isinstance(arg, list): to_append = self._replace_scalars_in_args(arg) elif isinstance(arg, dict): to_append = self._replace_scalars_in_kwargs(arg) elif isinstance(arg, string_types): to_append = self._replace_scalar(arg) else: to_append = arg new_args.append(to_append) return new_args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _replace_scalars_in_kwargs(self, kwargs): """ Replace scalars in keyed arguments dictionary """
_check_type('kwargs', kwargs, dict) new_kwargs = {} for (name, value) in iteritems(kwargs): if isinstance(value, list): new_kwargs[name] = self._replace_scalars_in_args(value) elif isinstance(value, dict): new_kwargs[name] = self._replace_scalars_in_kwargs(value) elif isinstance(value, string_types): new_kwargs[name] = self._replace_scalar(value) else: new_kwargs[name] = value return new_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 _replace_services_in_args(self, args): """ Replace service references in arguments list """
_check_type('args', args, list) new_args = [] for arg in args: if isinstance(arg, list): new_args.append(self._replace_services_in_args(arg)) elif isinstance(arg, dict): new_args.append(self._replace_services_in_kwargs(arg)) elif isinstance(arg, string_types): new_args.append(self._replace_service(arg)) else: new_args.append(arg) return new_args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _replace_services_in_kwargs(self, kwargs): """ Replace service references in keyed arguments dictionary """
_check_type('kwargs', kwargs, dict) new_kwargs = {} for (name, value) in iteritems(kwargs): if isinstance(value, list): new_kwargs[name] = self._replace_services_in_args(value) elif isinstance(value, dict): new_kwargs[name] = self._replace_services_in_kwargs(value) elif isinstance(value, string_types): new_kwargs[name] = self._replace_service(value) else: new_kwargs[name] = value return new_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_scalar_value(self, name): """ Get scalar value by name """
if name not in self.scalars: raise InvalidServiceConfiguration( 'Invalid Service Argument Scalar "%s" (not found)' % name ) new_value = self.scalars.get(name) return new_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 _replace_scalar(self, scalar): """ Replace scalar name with scalar value """
if not is_arg_scalar(scalar): return scalar name = scalar[1:] return self.get_scalar_value(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 _instantiate(self, module, class_name, args=None, kwargs=None, static=None): """ Instantiates a class if provided """
if args is None: args = [] if kwargs is None: kwargs = {} if static is None: static = False _check_type('args', args, list) _check_type('kwargs', kwargs, dict) if static and class_name is None: return module if static and class_name is not None: return getattr(module, class_name) service_obj = getattr(module, class_name) # Replace scalars args = self._replace_scalars_in_args(args) kwargs = self._replace_scalars_in_kwargs(kwargs) # Replace service references args = self._replace_services_in_args(args) kwargs = self._replace_services_in_kwargs(kwargs) # Instantiate object return service_obj(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_factory_method(self, service_obj, method_name, args=None, kwargs=None): """" Returns an object returned from a factory method """
if args is None: args = [] if kwargs is None: kwargs = {} _check_type('args', args, list) _check_type('kwargs', kwargs, dict) # Replace args new_args = self._replace_scalars_in_args(args) new_kwargs = self._replace_scalars_in_kwargs(kwargs) return getattr(service_obj, method_name)(*new_args, **new_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 _handle_calls(self, service_obj, calls): """ Performs method calls on service object """
for call in calls: method = call.get('method') args = call.get('args', []) kwargs = call.get('kwargs', {}) _check_type('args', args, list) _check_type('kwargs', kwargs, dict) if method is None: raise InvalidServiceConfiguration( 'Service call must define a method.' ) new_args = self._replace_scalars_in_args(args) new_kwargs = self._replace_scalars_in_kwargs(kwargs) getattr(service_obj, method)(*new_args, **new_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 _repr_html_(self): """ Jupyter Notebook hook to print this element as HTML. """
nbreset = f'<style>{css_nbreset}</style>' resources = ''.join(map(str, self.resources)) return f'<div>{nbreset}{resources}<div class="hrepr">{self}</div></div>'
<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_client(instance): """Returns an neutron client."""
neutron_client = utils.get_client_class( API_NAME, instance._api_version[API_NAME], API_VERSIONS, ) instance.initialize() url = instance._url url = url.rstrip("/") client = neutron_client(username=instance._username, project_name=instance._project_name, password=instance._password, region_name=instance._region_name, auth_url=instance._auth_url, endpoint_url=url, endpoint_type=instance._endpoint_type, token=instance._token, auth_strategy=instance._auth_strategy, insecure=instance._insecure, ca_cert=instance._ca_cert, retries=instance._retries, raise_errors=instance._raise_errors, session=instance._session, auth=instance._auth) return client
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Client(api_version, *args, **kwargs): """Return an neutron client. @param api_version: only 2.0 is supported now """
neutron_client = utils.get_client_class( API_NAME, api_version, API_VERSIONS, ) return neutron_client(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getSuperFunc(self, s, func): """Return the the super function."""
return getattr(super(self.cls(), s), func.__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 _doc_make(*make_args): """Run make in sphinx' docs directory. :return: exit code """
if sys.platform == 'win32': # Windows make_cmd = ['make.bat'] else: # Linux, Mac OS X, and others make_cmd = ['make'] make_cmd.extend(make_args) # Account for a stupid Python "bug" on Windows: # <http://bugs.python.org/issue15533> with cwd(DOCS_DIRECTORY): retcode = subprocess.call(make_cmd) return retcode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coverage(): """Run tests and show test coverage report."""
try: import pytest_cov # NOQA except ImportError: print_failure_message( 'Install the pytest coverage plugin to use this task, ' "i.e., `pip install pytest-cov'.") raise SystemExit(1) import pytest pytest.main(PYTEST_FLAGS + [ '--cov', CODE_DIRECTORY, '--cov-report', 'term-missing', '--junit-xml', 'test-report.xml', TESTS_DIRECTORY])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doc_watch(): """Watch for changes in the docs and rebuild HTML docs when changed."""
try: from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer except ImportError: print_failure_message('Install the watchdog package to use this task, ' "i.e., `pip install watchdog'.") raise SystemExit(1) class RebuildDocsEventHandler(FileSystemEventHandler): def __init__(self, base_paths): self.base_paths = base_paths def dispatch(self, event): """Dispatches events to the appropriate methods. :param event: The event object representing the file system event. :type event: :class:`watchdog.events.FileSystemEvent` """ for base_path in self.base_paths: if event.src_path.endswith(base_path): super(RebuildDocsEventHandler, self).dispatch(event) # We found one that matches. We're done. return def on_modified(self, event): print_failure_message('Modification detected. Rebuilding docs.') # # Strip off the path prefix. # import os # if event.src_path[len(os.getcwd()) + 1:].startswith( # CODE_DIRECTORY): # # sphinx-build doesn't always pick up changes on code files, # # even though they are used to generate the documentation. As # # a workaround, just clean before building. doc_html() print_success_message('Docs have been rebuilt.') print_success_message( 'Watching for changes in project files, press Ctrl-C to cancel...') handler = RebuildDocsEventHandler(get_project_files()) observer = Observer() observer.schedule(handler, path='.', recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doc_open(): """Build the HTML docs and open them in a web browser."""
doc_index = os.path.join(DOCS_DIRECTORY, 'build', 'html', 'index.html') if sys.platform == 'darwin': # Mac OS X subprocess.check_call(['open', doc_index]) elif sys.platform == 'win32': # Windows subprocess.check_call(['start', doc_index], shell=True) elif sys.platform == 'linux2': # All freedesktop-compatible desktops subprocess.check_call(['xdg-open', doc_index]) else: print_failure_message( "Unsupported platform. Please open `{0}' manually.".format( doc_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 get_tasks(): """Get all paver-defined tasks."""
from paver.tasks import environment for tsk in environment.get_tasks(): print(tsk.shortname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makeService(self, options): """ Construct a Node Server """
return NodeService( port=options['port'], host=options['host'], broker_host=options['broker_host'], broker_port=options['broker_port'], debug=options['debug'] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_triplestore(self, output): """Method attempts to add output to Blazegraph RDF Triplestore"""
if len(output) > 0: result = self.ext_conn.load_data(data=output.serialize(), datatype='rdf')
<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_term(self, **kwargs): """Method generates a rdflib.Term based on kwargs"""
term_map = kwargs.pop('term_map') if hasattr(term_map, "termType") and\ term_map.termType == NS_MGR.rr.BlankNode.rdflib: return rdflib.BNode() if not hasattr(term_map, 'datatype'): term_map.datatype = NS_MGR.xsd.anyURI.rdflib if hasattr(term_map, "template") and term_map.template is not None: template_vars = kwargs template_vars.update(self.constants) # Call any functions to generate values for key, value in template_vars.items(): if hasattr(value, "__call__"): template_vars[key] = value() raw_value = term_map.template.format(**template_vars) if term_map.datatype == NS_MGR.xsd.anyURI.rdflib: return rdflib.URIRef(raw_value) return rdflib.Literal(raw_value, datatype=term_map.datatype) if term_map.reference is not None: # Each child will have different mechanisms for referencing the # source based return self.__generate_reference__(term_map, **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 run(self, **kwargs): """Run method iterates through triple maps and calls the execute method"""
if 'timestamp' not in kwargs: kwargs['timestamp'] = datetime.datetime.utcnow().isoformat() if 'version' not in kwargs: kwargs['version'] = "Not Defined" #bibcat.__version__ # log.debug("kwargs: %s", pprint.pformat({k:v for k, v in kwargs.items() # if k != "dataset"})) # log.debug("parents: %s", self.parents) for map_key, triple_map in self.triple_maps.items(): if map_key not in self.parents: self.execute(triple_map, **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 set_context(self): """ Reads throught the namespaces in the RML and generates a context for json+ld output when compared to the RdfNsManager namespaces """
results = self.rml.query(""" SELECT ?o { { ?s rr:class ?o } UNION { ?s rr:predicate ?o } }""") namespaces = [Uri(row[0]).value[0] for row in results if isinstance(row[0], rdflib.URIRef)] self.context = {ns[0]: ns[1] for ns in namespaces if ns[0]}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json_ld(self, output, **kwargs): """ Returns the json-ld formated result """
raw_json_ld = output.serialize(format='json-ld', context=self.context).decode() # if there are fields that should be returned as arrays convert all # non-array fields to an array if not self.array_fields: return raw_json_ld json_data = json.loads(raw_json_ld) for i, item in enumerate(json_data['@graph']): if item.get("@type") in self.array_fields: test_flds = self.array_fields[item['@type']] for key, val in item.items(): if key in test_flds and not isinstance(val, list): json_data['@graph'][i][key] = [val] # print(json.dumps(json_data, indent=4)) return json.dumps(json_data, indent=4)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, triple_map, output, **kwargs): """Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace): Triple Map """
subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs) start_size = len(output) all_subjects = [] for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.template is not None: object_ = self.generate_term(term_map=pred_obj_map, **kwargs) if len(str(object)) > 0: output.add(( subject, predicate, object_)) if pred_obj_map.parentTriplesMap is not None: self.__handle_parents__( parent_map=pred_obj_map.parentTriplesMap, subject=subject, predicate=predicate, **kwargs) if pred_obj_map.reference is not None: object_ = self.generate_term(term_map=pred_obj_map, **kwargs) if object_ and len(str(object_)) > 0: output.add((subject, predicate, object_)) if pred_obj_map.constant is not None: output.add((subject, predicate, pred_obj_map.constant)) finish_size = len(output) if finish_size > start_size: output.add((subject, NS_MGR.rdf.type.rdflib, triple_map.subjectMap.class_)) all_subjects.append(subject) return all_subjects
<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, row, **kwargs): """Methods takes a row and depending if a dict or list, runs RML rules. Args: ----- row(Dict, List): Row from CSV Reader """
self.source = row kwargs['output'] = self.__graph__() super(CSVRowProcessor, self).run(**kwargs) return kwargs['output']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, triple_map, output, **kwargs): """Method executes mapping between JSON source and output RDF Args: ----- triple_map: SimpleNamespace """
subjects = [] logical_src_iterator = str(triple_map.logicalSource.iterator) json_object = kwargs.get('obj', self.source) # Removes '.' as a generic iterator, replace with '@' if logical_src_iterator == ".": results = [None,] else: json_path_exp = jsonpath_ng.parse(logical_src_iterator) results = [r.value for r in json_path_exp.find(json_object)][0] for row in results: subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs) for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.template is not None: output.add(( subject, predicate, self.generate_term(term_map=pred_obj_map, **kwargs))) if pred_obj_map.parentTriplesMap is not None: self.__handle_parents__( output, parent_map=pred_obj_map.parentTriplesMap, subject=subject, predicate=predicate, obj=row, **kwargs) if pred_obj_map.reference is not None: ref_exp = jsonpath_ng.parse(str(pred_obj_map.reference)) found_objects = [r.value for r in ref_exp.find(row)] for obj in found_objects: if rdflib.term._is_valid_uri(obj): rdf_obj = rdflib.URIRef(str(obj)) else: rdf_obj = rdflib.Literal(str(obj)) output.add((subject, predicate, rdf_obj)) if pred_obj_map.constant is not None: output.add((subject, predicate, pred_obj_map.constant)) subjects.append(subject) return subjects
<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, source, **kwargs): """Method takes a JSON source and any keywords and transforms from JSON to Lean BIBFRAME 2.0 triples Args: ---- source: str, dict """
kwargs['output'] = self.__graph__() if isinstance(source, str): import json source = json.loads(source) self.source = source super(JSONProcessor, self).run(**kwargs) self.output = kwargs['output'] return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, triple_map, output, **kwargs): """Method executes mapping between source Args: ----- triple_map: SimpleNamespace, Triple Map """
subjects = [] found_elements = self.source.xpath( str(triple_map.logicalSource.iterator), namespaces=self.xml_ns) for element in found_elements: subject = self.generate_term(term_map=triple_map.subjectMap, element=element, **kwargs) start = len(output) for row in triple_map.predicateObjectMap: predicate = row.predicate if row.template is not None: obj_ = self.generate_term(term_map=row, **kwargs) output.add((subject, predicate, obj_)) if row.parentTriplesMap is not None: self.__handle_parents__( output, parent_map=row.parentTriplesMap, subject=subject, predicate=predicate, **kwargs) new_subjects = self.__reference_handler__( output, predicate_obj_map=row, element=element, subject=subject) subjects.extend(new_subjects) if row.constant is not None: output.add((subject, predicate, row.constant)) if start < len(output): if triple_map.subjectMap.class_ is not None: output.add((subject, NS_MGR.rdf.type.rdflib, triple_map.subjectMap.class_)) subjects.append(subject) return subjects
<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, xml, **kwargs): """Method takes either an etree.ElementTree or raw XML text as the first argument. Args: xml(etree.ElementTree or text """
kwargs['output'] = self.__graph__() if isinstance(xml, str): try: self.source = etree.XML(xml) except ValueError: try: self.source = etree.XML(xml.encode()) except: raise ValueError("Cannot run error {}".format(sys.exc_info()[0])) else: self.source = xml super(XMLProcessor, self).run(**kwargs) self.output = kwargs['output'] return kwargs['output']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, triple_map, output, **kwargs): """Method iterates through triple map's predicate object maps and processes query. Args: triple_map(SimpleNamespace): Triple Map """
sparql = PREFIX + triple_map.logicalSource.query.format( **kwargs) bindings = self.__get_bindings__(sparql) iterator = str(triple_map.logicalSource.iterator) for binding in bindings: entity_dict = binding.get(iterator) if isinstance(entity_dict, rdflib.term.Node): entity = entity_dict elif isinstance(entity_dict, dict): raw_value = entity_dict.get('value') if entity_dict.get('type').startswith('bnode'): entity = rdflib.BNode(raw_value) else: entity = rdflib.URIRef(raw_value) if triple_map.subjectMap.class_ is not None: output.add( (entity, rdflib.RDF.type, triple_map.subjectMap.class_)) sparql_query = self.__construct_compound_query__( triple_map).format(**kwargs) properties = self.__get_bindings__(sparql_query) for pred_obj_map in triple_map.predicateObjectMap: predicate = pred_obj_map.predicate if pred_obj_map.constant is not None: output.add( (entity, predicate, pred_obj_map.constant)) continue if "#" in str(predicate): key = str(predicate).split("#")[-1] else: key = str(predicate).split("/")[-1] for property_ in properties: if key in property_.keys(): info = {"about": property_.get(key)} object_ = __get_object__(info) output.add((entity, predicate, object_))
<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(self, message, _sender=None): """Sends a message to the actor represented by this `Ref`."""
if not _sender: context = get_context() if context: _sender = context.ref if self._cell: if not self._cell.stopped: self._cell.receive(message, _sender) return else: self._cell = None if not self.is_local: if self.uri.node != self.node.nid: self.node.send_message(message, remote_ref=self, sender=_sender) else: self._cell = self.node.guardian.lookup_cell(self.uri) self.is_local = True self._cell.receive(message, _sender) else: if self.node and self.node.guardian: cell = self.node.guardian.lookup_cell(self.uri) if cell: cell.receive(message, _sender) # do NOT set self._cell--it will never be unset and will cause a memleak return if ('_watched', ANY) == message: message[1].send(('terminated', self), _sender=self) elif (message == ('terminated', ANY) or message == ('_unwatched', ANY) or message == ('_node_down', ANY) or message == '_stop' or message == '_kill' or message == '__done'): pass else: Events.log(DeadLetter(self, message, _sender))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def security_errors(self): """Return just those errors associated with security"""
errors = ErrorDict() for f in ["honeypot", "timestamp", "security_hash"]: if f in self.errors: errors[f] = self.errors[f] return errors
<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_security_hash(self): """Check the security hash."""
security_hash_dict = { 'content_type': self.data.get("content_type", ""), 'object_pk': self.data.get("object_pk", ""), 'timestamp': self.data.get("timestamp", ""), } expected_hash = self.generate_security_hash(**security_hash_dict) actual_hash = self.cleaned_data["security_hash"] if not constant_time_compare(expected_hash, actual_hash): raise forms.ValidationError("Security hash check failed.") return actual_hash
<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_security_data(self): """Generate a dict of security data for "initial" data."""
timestamp = int(time.time()) security_dict = { 'content_type': str(self.target_object._meta), 'object_pk': str(self.target_object._get_pk_val()), 'timestamp': str(timestamp), 'security_hash': self.initial_security_hash(timestamp), } return security_dict
<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_security_hash(self, content_type, object_pk, timestamp): """ Generate a HMAC security hash from the provided info. """
info = (content_type, object_pk, timestamp) key_salt = "django.contrib.forms.CommentSecurityForm" value = "-".join(info) return salted_hmac(key_salt, value).hexdigest()
<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_comment_create_data(self): """ Returns the dict of data to be used to create a comment. Subclasses in custom comment apps that override get_comment_model can override this method to add extra fields onto a custom comment model. """
user_model = get_user_model() return dict( content_type=ContentType.objects.get_for_model(self.target_object), object_pk=force_text(self.target_object._get_pk_val()), text=self.cleaned_data["text"], user=user_model.objects.latest('id'), post_date=timezone.now(), site_id=settings.SITE_ID, is_public=True, is_removed=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 clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """
comment = self.cleaned_data["text"] if settings.COMMENTS_ALLOW_PROFANITIES is False: bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()] if bad_words: raise forms.ValidationError(ungettext( "Watch your mouth! The word %s is not allowed here.", "Watch your mouth! The words %s are not allowed here.", len(bad_words)) % get_text_list( ['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1]) for i in bad_words], ugettext('and'))) return comment
<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_honeypot(self): """Check that nothing's been entered into the honeypot."""
value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) 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 include_original(dec): """Decorate decorators so they include a copy of the original function."""
def meta_decorator(method): """Yo dawg, I heard you like decorators...""" # pylint: disable=protected-access decorator = dec(method) decorator._original = method return decorator return meta_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 sendhello(self): try: # send hello cli_hello_msg = "<hello>\n" +\ " <capabilities>\n" +\ " <capability>urn:ietf:params:netconf:base:1.0</capability>\n" +\ " </capabilities>\n" +\ "</hello>\n" self._cParams.set('cli_hello', cli_hello_msg) self._hConn.sendmsg(cli_hello_msg) # recv hello ser_hello_msg = self._hConn.recvmsg() self._cParams.set('ser_hello', ser_hello_msg) except: print 'BNClient: Call sendhello fail' sys.exit() """ end of function exchgcaps """
null
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sendrpc(self, argv=[]): self._aArgv += argv _operation = '' try: self._cParams.parser(self._aArgv, self._dOptions) # set rpc operation handler while self._cParams.get('operation') not in rpc.operations.keys(): self._cParams.set('operation', raw_input("Enter RPC Operation:\n%s:" % rpc.operations.keys())) _operation = self._cParams.get('operation') self._hRpcOper = rpc.operations[_operation](opts=self._dOptions) # input missing operation parameters self._hRpcOper.fill(params=self._cParams.get()) send_msg = self._hRpcOper.readmsg(self._cParams.get()) self._cParams.set('messageid', self._cParams.get('messageid')+1) self._hConn.sendmsg(send_msg) self._cParams.set('sendmsg', send_msg) recv_msg = self._hConn.recvmsg() self._cParams.set('recvmsg', recv_msg) self._hRpcOper.parsemsg(self._cParams.get()) self._hRpcOper.writemsg(self._cParams.get()) # reset operation params self._cParams.reset() except: if _operation != 'close-session': print 'BNClient: Call sendrpc%s fail' % (' <'+_operation+'>' if len(_operation) else '') sys.exit() """ end of function exchgmsg """
null
<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_templatetags(): """ Register templatetags defined in settings as basic templatetags """
from turboengine.conf import settings from google.appengine.ext.webapp import template for python_file in settings.TEMPLATE_PATH: template.register_template_library(python_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 get_hosts(self, pattern="all"): """ find all host names matching a pattern string, taking into account any inventory restrictions or applied subsets. """
# process patterns if isinstance(pattern, list): pattern = ';'.join(pattern) patterns = pattern.replace(";",":").split(":") hosts = self._get_hosts(patterns) # exclude hosts not in a subset, if defined if self._subset: subset = self._get_hosts(self._subset) hosts.intersection_update(subset) # exclude hosts mentioned in any restriction (ex: failed hosts) if self._restriction is not None: hosts = [ h for h in hosts if h.name in self._restriction ] if self._also_restriction is not None: hosts = [ h for h in hosts if h.name in self._also_restriction ] return sorted(hosts, key=lambda x: x.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_hosts(self, patterns): """ finds hosts that match a list of patterns. Handles negative matches as well as intersection matches. """
hosts = set() for p in patterns: if p.startswith("!"): # Discard excluded hosts hosts.difference_update(self.__get_hosts(p)) elif p.startswith("&"): # Only leave the intersected hosts hosts.intersection_update(self.__get_hosts(p)) else: # Get all hosts from both patterns hosts.update(self.__get_hosts(p)) return hosts