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 is_valid_image(self, raw_data): ''' Wand library makes sure when opening any image that is fine, when the image is corrupted raises an exception. ''' try: Image(blob=raw_data) return True except (exceptions.CorruptImageError, exceptions.MissingDelegateError): 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 parse_cropbox(cropbox): """ Returns x, y, x2, y2 tuple for cropping. """
if isinstance(cropbox, six.text_type): return tuple([int(x.strip()) for x in cropbox.split(',')]) else: return tuple(cropbox)
<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_image(self, source): """ Returns the backend image objects from a ImageFile instance """
with NamedTemporaryFile(mode='wb', delete=False) as fp: fp.write(source.read()) return {'source': fp.name, 'options': OrderedDict(), 'size': None}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid_image(self, raw_data): """ This is not very good for imagemagick because it will say anything is valid that it can use as input. """
with NamedTemporaryFile(mode='wb') as fp: fp.write(raw_data) fp.flush() args = settings.THUMBNAIL_IDENTIFY.split(' ') args.append(fp.name + '[0]') p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) retcode = p.wait() return retcode == 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 _crop(self, image, width, height, x_offset, y_offset): """ Crops the image """
image['options']['crop'] = '%sx%s+%s+%s' % (width, height, x_offset, y_offset) image['size'] = (width, height) # update image size return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scale(self, image, width, height): """ Does the resizing of the image """
image['options']['scale'] = '%sx%s!' % (width, height) image['size'] = (width, height) # update image size return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _padding(self, image, geometry, options): """ Pads the image """
# The order is important. The gravity option should come before extent. image['options']['background'] = options.get('padding_color') image['options']['gravity'] = 'center' image['options']['extent'] = '%sx%s' % (geometry[0], geometry[1]) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokey(*args): """ Computes a unique key from arguments given. """
salt = '||'.join([force_text(arg) for arg in args]) hash_ = hashlib.md5(encode(salt)) return hash_.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_module_class(class_path): """ imports and returns module class from ``path.to.module.Class`` argument """
mod_name, cls_name = class_path.rsplit('.', 1) try: mod = import_module(mod_name) except ImportError as e: raise ImproperlyConfigured(('Error importing module %s: "%s"' % (mod_name, e))) return getattr(mod, cls_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_thumbnail(file_, geometry_string, **options): """ A shortcut for the Backend ``get_thumbnail`` method """
return default.backend.get_thumbnail(file_, geometry_string, **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 safe_filter(error_output=''): """ A safe filter decorator only raising errors when ``THUMBNAIL_DEBUG`` is ``True`` otherwise returning ``error_output``. """
def inner(f): @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except Exception as err: if sorl_settings.THUMBNAIL_DEBUG: raise logger.error('Thumbnail filter failed: %s' % str(err), exc_info=sys.exc_info()) return error_output return wrapper return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolution(file_, resolution_string): """ A filter to return the URL for the provided resolution of the thumbnail. """
if sorl_settings.THUMBNAIL_DUMMY: dummy_source = sorl_settings.THUMBNAIL_DUMMY_SOURCE source = dummy_source.replace('%(width)s', '(?P<width>[0-9]+)') source = source.replace('%(height)s', '(?P<height>[0-9]+)') source = re.compile(source) try: resolution = decimal.Decimal(resolution_string.strip('x')) info = source.match(file_).groupdict() info = {dimension: int(int(size) * resolution) for (dimension, size) in info.items()} return dummy_source % info except (AttributeError, TypeError, KeyError): # If we can't manipulate the dummy we shouldn't change it at all return file_ filename, extension = os.path.splitext(file_) return '%s@%s%s' % (filename, resolution_string, extension)
<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_portrait(file_): """ A very handy filter to determine if an image is portrait or landscape. """
if sorl_settings.THUMBNAIL_DUMMY: return sorl_settings.THUMBNAIL_DUMMY_RATIO < 1 if not file_: return False image_file = default.kvstore.get_or_set(ImageFile(file_)) return image_file.is_portrait()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def margin(file_, geometry_string): """ Returns the calculated margin for an image and geometry """
if not file_ or (sorl_settings.THUMBNAIL_DUMMY or isinstance(file_, DummyImageFile)): return 'auto' margin = [0, 0, 0, 0] image_file = default.kvstore.get_or_set(ImageFile(file_)) x, y = parse_geometry(geometry_string, image_file.ratio) ex = x - image_file.x margin[3] = ex / 2 margin[1] = ex / 2 if ex % 2: margin[1] += 1 ey = y - image_file.y margin[0] = ey / 2 margin[2] = ey / 2 if ey % 2: margin[2] += 1 return ' '.join(['%dpx' % n for n in margin])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text_filter(regex_base, value): """ Helper method to regex replace images with captions in different markups """
regex = regex_base % { 're_cap': r'[a-zA-Z0-9\.\,:;/_ \(\)\-\!\?"]+', 're_img': r'[a-zA-Z0-9\.:/_\-\% ]+' } images = re.findall(regex, value) for i in images: image = i[1] if image.startswith(settings.MEDIA_URL): image = image[len(settings.MEDIA_URL):] im = get_thumbnail(image, str(sorl_settings.THUMBNAIL_FILTER_WIDTH)) value = value.replace(i[1], im.url) 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 delete_file(self, instance, sender, **kwargs): """ Adds deletion of thumbnails and key value store references to the parent class implementation. Only called in Django < 1.2.5 """
file_ = getattr(instance, self.attname) # If no other object of this type references the file, and it's not the # default value for future objects, delete it from the backend. query = Q(**{self.name: file_.name}) & ~Q(pk=instance.pk) qs = sender._default_manager.filter(query) if (file_ and file_.name != self.default and not qs): default.backend.delete(file_) elif file_: # Otherwise, just close the file, so it doesn't tie up resources. file_.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_image_size(self, image): """ Returns the image width and height as a tuple """
if image['size'] is None: args = settings.THUMBNAIL_VIPSHEADER.split(' ') args.append(image['source']) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() m = size_re.match(str(p.stdout.read())) image['size'] = int(m.group('x')), int(m.group('y')) return image['size']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_thumbnail(self, file_, geometry_string, **options): """ Returns thumbnail as an ImageFile instance for file with geometry and options given. First it will try to get it from the key value store, secondly it will create it. """
logger.debug('Getting thumbnail for file [%s] at [%s]', file_, geometry_string) if file_: source = ImageFile(file_) else: raise ValueError('falsey file_ argument in get_thumbnail()') # preserve image filetype if settings.THUMBNAIL_PRESERVE_FORMAT: options.setdefault('format', self._get_format(source)) for key, value in self.default_options.items(): options.setdefault(key, value) # For the future I think it is better to add options only if they # differ from the default settings as below. This will ensure the same # filenames being generated for new options at default. for key, attr in self.extra_options: value = getattr(settings, attr) if value != getattr(default_settings, attr): options.setdefault(key, value) name = self._get_thumbnail_filename(source, geometry_string, options) thumbnail = ImageFile(name, default.storage) cached = default.kvstore.get(thumbnail) if cached: return cached # We have to check exists() because the Storage backend does not # overwrite in some implementations. if settings.THUMBNAIL_FORCE_OVERWRITE or not thumbnail.exists(): try: source_image = default.engine.get_image(source) except IOError as e: logger.exception(e) if settings.THUMBNAIL_DUMMY: return DummyImageFile(geometry_string) else: # if S3Storage says file doesn't exist remotely, don't try to # create it and exit early. # Will return working empty image type; 404'd image logger.warning( 'Remote file [%s] at [%s] does not exist', file_, geometry_string, ) return thumbnail # We might as well set the size since we have the image in memory image_info = default.engine.get_image_info(source_image) options['image_info'] = image_info size = default.engine.get_image_size(source_image) source.set_size(size) try: self._create_thumbnail(source_image, geometry_string, options, thumbnail) self._create_alternative_resolutions(source_image, geometry_string, options, thumbnail.name) finally: default.engine.cleanup(source_image) # If the thumbnail exists we don't create it, the other option is # to delete and write but this could lead to race conditions so I # will just leave that out for now. default.kvstore.get_or_set(source) default.kvstore.set(thumbnail, source) return thumbnail
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, file_, delete_file=True): """ Deletes file_ references in Key Value store and optionally the file_ it self. """
image_file = ImageFile(file_) if delete_file: image_file.delete() default.kvstore.delete(image_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 _create_thumbnail(self, source_image, geometry_string, options, thumbnail): """ Creates the thumbnail by using default.engine """
logger.debug('Creating thumbnail file [%s] at [%s] with [%s]', thumbnail.name, geometry_string, options) ratio = default.engine.get_image_ratio(source_image, options) geometry = parse_geometry(geometry_string, ratio) image = default.engine.create(source_image, geometry, options) default.engine.write(image, options, thumbnail) # It's much cheaper to set the size here size = default.engine.get_image_size(image) thumbnail.set_size(size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_alternative_resolutions(self, source_image, geometry_string, options, name): """ Creates the thumbnail by using default.engine with multiple output sizes. Appends @<ratio>x to the file name. """
ratio = default.engine.get_image_ratio(source_image, options) geometry = parse_geometry(geometry_string, ratio) file_name, dot_file_ext = os.path.splitext(name) for resolution in settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS: resolution_geometry = (int(geometry[0] * resolution), int(geometry[1] * resolution)) resolution_options = options.copy() if 'crop' in options and isinstance(options['crop'], string_types): crop = options['crop'].split(" ") for i in range(len(crop)): s = re.match(r"(\d+)px", crop[i]) if s: crop[i] = "%spx" % int(int(s.group(1)) * resolution) resolution_options['crop'] = " ".join(crop) image = default.engine.create(source_image, resolution_geometry, options) thumbnail_name = '%(file_name)s%(suffix)s%(file_ext)s' % { 'file_name': file_name, 'suffix': '@%sx' % resolution, 'file_ext': dot_file_ext } thumbnail = ImageFile(thumbnail_name, default.storage) default.engine.write(image, resolution_options, thumbnail) size = default.engine.get_image_size(image) thumbnail.set_size(size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_thumbnail_filename(self, source, geometry_string, options): """ Computes the destination filename. """
key = tokey(source.key, geometry_string, serialize(options)) # make some subdirs path = '%s/%s/%s' % (key[:2], key[2:4], key) return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def round_corner(radius, fill): """Draw a round corner"""
corner = Image.new('L', (radius, radius), 0) # (0, 0, 0, 0)) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill) return corner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def round_rectangle(size, radius, fill): """Draw a rounded rectangle"""
width, height = size rectangle = Image.new('L', size, 255) # fill corner = round_corner(radius, 255) # fill rectangle.paste(corner, (0, 0)) rectangle.paste(corner.rotate(90), (0, height - radius)) # Rotate the corner and paste it rectangle.paste(corner.rotate(180), (width - radius, height - radius)) rectangle.paste(corner.rotate(270), (width - radius, 0)) return rectangle
<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_image_entropy(self, image): """calculate the entropy of an image"""
hist = image.histogram() hist_size = sum(hist) hist = [float(h) / hist_size for h in hist] return -sum([p * math.log(p, 2) for p in hist if p != 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 create(self, image, geometry, options): """ Processing conductor, returns the thumbnail as an image engine instance """
image = self.cropbox(image, geometry, options) image = self.orientation(image, geometry, options) image = self.colorspace(image, geometry, options) image = self.remove_border(image, options) image = self.scale(image, geometry, options) image = self.crop(image, geometry, options) image = self.rounded(image, geometry, options) image = self.blur(image, geometry, options) image = self.padding(image, geometry, options) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cropbox(self, image, geometry, options): """ Wrapper for ``_cropbox`` """
cropbox = options['cropbox'] if not cropbox: return image x, y, x2, y2 = parse_cropbox(cropbox) return self._cropbox(image, x, y, x2, y2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def orientation(self, image, geometry, options): """ Wrapper for ``_orientation`` """
if options.get('orientation', settings.THUMBNAIL_ORIENTATION): return self._orientation(image) self.reoriented = True return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colorspace(self, image, geometry, options): """ Wrapper for ``_colorspace`` """
colorspace = options['colorspace'] return self._colorspace(image, colorspace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scale(self, image, geometry, options): """ Wrapper for ``_scale`` """
upscale = options['upscale'] x_image, y_image = map(float, self.get_image_size(image)) factor = self._calculate_scaling_factor(x_image, y_image, geometry, options) if factor < 1 or upscale: width = toint(x_image * factor) height = toint(y_image * factor) image = self._scale(image, width, height) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crop(self, image, geometry, options): """ Wrapper for ``_crop`` """
crop = options['crop'] x_image, y_image = self.get_image_size(image) if not crop or crop == 'noop': return image elif crop == 'smart': # Smart cropping is suitably different from regular cropping # to warrent it's own function return self._entropy_crop(image, geometry[0], geometry[1], x_image, y_image) # Handle any other crop option with the backend crop function. geometry = (min(x_image, geometry[0]), min(y_image, geometry[1])) x_offset, y_offset = parse_crop(crop, (x_image, y_image), geometry) return self._crop(image, geometry[0], geometry[1], x_offset, y_offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rounded(self, image, geometry, options): """ Wrapper for ``_rounded`` """
r = options['rounded'] if not r: return image return self._rounded(image, int(r))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blur(self, image, geometry, options): """ Wrapper for ``_blur`` """
if options.get('blur'): return self._blur(image, int(options.get('blur'))) return image
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def padding(self, image, geometry, options): """ Wrapper for ``_padding`` """
if options.get('padding') and self.get_image_size(image) != geometry: return self._padding(image, geometry, options) return image
<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_image_ratio(self, image, options): """ Calculates the image ratio. If cropbox option is used, the ratio may have changed. """
cropbox = options['cropbox'] if cropbox: x, y, x2, y2 = parse_cropbox(cropbox) x = x2 - x y = y2 - y else: x, y = self.get_image_size(image) return float(x) / y
<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, image_file, source=None): """ Updates store for the `image_file`. Makes sure the `image_file` has a size set. """
image_file.set_size() # make sure its got a size self._set(image_file.key, image_file) if source is not None: if not self.get(source): # make sure the source is in kvstore raise ThumbnailError('Cannot add thumbnails for source: `%s` ' 'that is not in kvstore.' % source.name) # Update the list of thumbnails for source. thumbnails = self._get(source.key, identity='thumbnails') or [] thumbnails = set(thumbnails) thumbnails.add(image_file.key) self._set(source.key, list(thumbnails), identity='thumbnails')
<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, image_file, delete_thumbnails=True): """ Deletes the reference to the ``image_file`` and deletes the references to thumbnails as well as thumbnail files if ``delete_thumbnails`` is `True``. Does not delete the ``image_file`` is self. """
if delete_thumbnails: self.delete_thumbnails(image_file) self._delete(image_file.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 delete_thumbnails(self, image_file): """ Deletes references to thumbnails as well as thumbnail ``image_files``. """
thumbnail_keys = self._get(image_file.key, identity='thumbnails') if thumbnail_keys: # Delete all thumbnail keys from store and delete the # thumbnail ImageFiles. for key in thumbnail_keys: thumbnail = self._get(key) if thumbnail: self.delete(thumbnail, False) thumbnail.delete() # delete the actual file # Delete the thumbnails key from store self._delete(image_file.key, identity='thumbnails')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """ Brutely clears the key value store for keys with THUMBNAIL_KEY_PREFIX prefix. Use this in emergency situations. Normally you would probably want to use the ``cleanup`` method instead. """
all_keys = self._find_keys_raw(settings.THUMBNAIL_KEY_PREFIX) if all_keys: self._delete_raw(*all_keys)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get(self, key, identity='image'): """ Deserializing, prefix wrapper for _get_raw """
value = self._get_raw(add_prefix(key, identity)) if not value: return None if identity == 'image': return deserialize_image_file(value) return deserialize(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, key, value, identity='image'): """ Serializing, prefix wrapper for _set_raw """
if identity == 'image': s = serialize_image_file(value) else: s = serialize(value) self._set_raw(add_prefix(key, identity), s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_keys(self, identity='image'): """ Finds and returns all keys for identity, """
prefix = add_prefix('', identity) raw_keys = self._find_keys_raw(prefix) or [] for raw_key in raw_keys: yield del_prefix(raw_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 dtw(x, y, dist=None): ''' return the distance between 2 time series without approximation Parameters ---------- x : array_like input array 1 y : array_like input array 2 dist : function or int The method for calculating the distance between x[i] and y[j]. If dist is an int of value p > 0, then the p-norm will be used. If dist is a function then dist(x[i], y[j]) will be used. If dist is None then abs(x[i] - y[j]) will be used. Returns ------- distance : float the approximate distance between the 2 time series path : list list of indexes for the inputs x and y Examples -------- >>> import numpy as np >>> import fastdtw >>> x = np.array([1, 2, 3, 4, 5], dtype='float') >>> y = np.array([2, 3, 4], dtype='float') >>> fastdtw.dtw(x, y) (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)]) ''' x, y, dist = __prep_inputs(x, y, dist) return __dtw(x, y, None, dist)
<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_next_url(request, redirect_field_name): """Retrieves next url from request Note: This verifies that the url is safe before returning it. If the url is not safe, this returns None. :arg HttpRequest request: the http request :arg str redirect_field_name: the name of the field holding the next url :returns: safe url or None """
next_url = request.GET.get(redirect_field_name) if next_url: kwargs = { 'url': next_url, 'require_https': import_from_settings( 'OIDC_REDIRECT_REQUIRE_HTTPS', request.is_secure()) } hosts = list(import_from_settings('OIDC_REDIRECT_ALLOWED_HOSTS', [])) hosts.append(request.get_host()) kwargs['allowed_hosts'] = hosts is_safe = is_safe_url(**kwargs) if is_safe: return next_url 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 get(self, request): """Callback handler for OIDC authorization code flow"""
nonce = request.session.get('oidc_nonce') if nonce: # Make sure that nonce is not used twice del request.session['oidc_nonce'] if request.GET.get('error'): # Ouch! Something important failed. # Make sure the user doesn't get to continue to be logged in # otherwise the refresh middleware will force the user to # redirect to authorize again if the session refresh has # expired. if is_authenticated(request.user): auth.logout(request) assert not is_authenticated(request.user) elif 'code' in request.GET and 'state' in request.GET: kwargs = { 'request': request, 'nonce': nonce, } if 'oidc_state' not in request.session: return self.login_failure() if request.GET['state'] != request.session['oidc_state']: msg = 'Session `oidc_state` does not match the OIDC callback state' raise SuspiciousOperation(msg) self.user = auth.authenticate(**kwargs) if self.user and self.user.is_active: return self.login_success() return self.login_failure()
<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, request): """OIDC client authentication initialization HTTP endpoint"""
state = get_random_string(self.get_settings('OIDC_STATE_SIZE', 32)) redirect_field_name = self.get_settings('OIDC_REDIRECT_FIELD_NAME', 'next') reverse_url = self.get_settings('OIDC_AUTHENTICATION_CALLBACK_URL', 'oidc_authentication_callback') params = { 'response_type': 'code', 'scope': self.get_settings('OIDC_RP_SCOPES', 'openid email'), 'client_id': self.OIDC_RP_CLIENT_ID, 'redirect_uri': absolutify( request, reverse(reverse_url) ), 'state': state, } params.update(self.get_extra_params(request)) if self.get_settings('OIDC_USE_NONCE', True): nonce = get_random_string(self.get_settings('OIDC_NONCE_SIZE', 32)) params.update({ 'nonce': nonce }) request.session['oidc_nonce'] = nonce request.session['oidc_state'] = state request.session['oidc_login_next'] = get_next_url(request, redirect_field_name) query = urlencode(params) redirect_url = '{url}?{query}'.format(url=self.OIDC_OP_AUTH_ENDPOINT, query=query) return HttpResponseRedirect(redirect_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 get_oidc_backend(): """ Get the Django auth backend that uses OIDC. """
# allow the user to force which back backend to use. this is mostly # convenient if you want to use OIDC with DRF but don't want to configure # OIDC for the "normal" Django auth. backend_setting = import_from_settings('OIDC_DRF_AUTH_BACKEND', None) if backend_setting: backend = import_string(backend_setting)() if not isinstance(backend, OIDCAuthenticationBackend): msg = 'Class configured in OIDC_DRF_AUTH_BACKEND ' \ 'does not extend OIDCAuthenticationBackend!' raise ImproperlyConfigured(msg) return backend # if the backend setting is not set, look through the list of configured # backends for one that is an OIDCAuthenticationBackend. backends = [b for b in get_backends() if isinstance(b, OIDCAuthenticationBackend)] if not backends: msg = 'No backends extending OIDCAuthenticationBackend found - ' \ 'add one to AUTHENTICATION_BACKENDS or set OIDC_DRF_AUTH_BACKEND!' raise ImproperlyConfigured(msg) if len(backends) > 1: raise ImproperlyConfigured('More than one OIDCAuthenticationBackend found!') return backends[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 get_access_token(self, request): """ Get the access token based on a request. Returns None if no authentication details were provided. Raises AuthenticationFailed if the token is incorrect. """
header = authentication.get_authorization_header(request) if not header: return None header = header.decode(authentication.HTTP_HEADER_ENCODING) auth = header.split() if auth[0].lower() != 'bearer': return None if len(auth) == 1: msg = 'Invalid "bearer" header: No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid "bearer" header: Credentials string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) return auth[1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def import_from_settings(attr, *args): """ Load an attribute from the django settings. :raises: ImproperlyConfigured """
try: if args: return getattr(settings, attr, args[0]) return getattr(settings, attr) except AttributeError: raise ImproperlyConfigured('Setting {0} not found'.format(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 default_username_algo(email): """Generate username for the Django user. :arg str/unicode email: the email address to use to generate a username :returns: str/unicode """
# bluntly stolen from django-browserid # store the username as a base64 encoded sha224 of the email address # this protects against data leakage because usernames are often # treated as public identifiers (so we can't use the email address). username = base64.urlsafe_b64encode( hashlib.sha1(force_bytes(email)).digest() ).rstrip(b'=') return smart_text(username)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_users_by_claims(self, claims): """Return all users matching the specified email."""
email = claims.get('email') if not email: return self.UserModel.objects.none() return self.UserModel.objects.filter(email__iexact=email)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_claims(self, claims): """Verify the provided claims to decide if authentication should be allowed."""
# Verify claims required by default configuration scopes = self.get_settings('OIDC_RP_SCOPES', 'openid email') if 'email' in scopes.split(): return 'email' in claims LOGGER.warning('Custom OIDC_RP_SCOPES defined. ' 'You need to override `verify_claims` for custom claims verification.') 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 create_user(self, claims): """Return object for a newly created user account."""
email = claims.get('email') username = self.get_username(claims) return self.UserModel.objects.create_user(username, email)
<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_username(self, claims): """Generate username based on claims."""
# bluntly stolen from django-browserid # https://github.com/mozilla/django-browserid/blob/master/django_browserid/auth.py username_algo = self.get_settings('OIDC_USERNAME_ALGO', None) if username_algo: if isinstance(username_algo, six.string_types): username_algo = import_string(username_algo) return username_algo(claims.get('email')) return default_username_algo(claims.get('email'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _verify_jws(self, payload, key): """Verify the given JWS payload with the given key and return the payload"""
jws = JWS.from_compact(payload) try: alg = jws.signature.combined.alg.name except KeyError: msg = 'No alg value found in header' raise SuspiciousOperation(msg) if alg != self.OIDC_RP_SIGN_ALGO: msg = "The provider algorithm {!r} does not match the client's " \ "OIDC_RP_SIGN_ALGO.".format(alg) raise SuspiciousOperation(msg) if isinstance(key, six.string_types): # Use smart_bytes here since the key string comes from settings. jwk = JWK.load(smart_bytes(key)) else: # The key is a json returned from the IDP JWKS endpoint. jwk = JWK.from_json(key) if not jws.verify(jwk): msg = 'JWS token verification failed.' raise SuspiciousOperation(msg) return jws.payload
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve_matching_jwk(self, token): """Get the signing key by exploring the JWKS endpoint of the OP."""
response_jwks = requests.get( self.OIDC_OP_JWKS_ENDPOINT, verify=self.get_settings('OIDC_VERIFY_SSL', True) ) response_jwks.raise_for_status() jwks = response_jwks.json() # Compute the current header from the given token to find a match jws = JWS.from_compact(token) json_header = jws.signature.protected header = Header.json_loads(json_header) key = None for jwk in jwks['keys']: if jwk['kid'] != smart_text(header.kid): continue if 'alg' in jwk and jwk['alg'] != smart_text(header.alg): raise SuspiciousOperation('alg values do not match.') key = jwk if key is None: raise SuspiciousOperation('Could not find a valid JWKS.') return 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_payload_data(self, token, key): """Helper method to get the payload of the JWT token."""
if self.get_settings('OIDC_ALLOW_UNSECURED_JWT', False): header, payload_data, signature = token.split(b'.') header = json.loads(smart_text(b64decode(header))) # If config allows unsecured JWTs check the header and return the decoded payload if 'alg' in header and header['alg'] == 'none': return b64decode(payload_data) # By default fallback to verify JWT signatures return self._verify_jws(token, 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 verify_token(self, token, **kwargs): """Validate the token signature."""
nonce = kwargs.get('nonce') token = force_bytes(token) if self.OIDC_RP_SIGN_ALGO.startswith('RS'): if self.OIDC_RP_IDP_SIGN_KEY is not None: key = self.OIDC_RP_IDP_SIGN_KEY else: key = self.retrieve_matching_jwk(token) else: key = self.OIDC_RP_CLIENT_SECRET payload_data = self.get_payload_data(token, key) # The 'token' will always be a byte string since it's # the result of base64.urlsafe_b64decode(). # The payload is always the result of base64.urlsafe_b64decode(). # In Python 3 and 2, that's always a byte string. # In Python3.6, the json.loads() function can accept a byte string # as it will automagically decode it to a unicode string before # deserializing https://bugs.python.org/issue17909 payload = json.loads(payload_data.decode('utf-8')) token_nonce = payload.get('nonce') if self.get_settings('OIDC_USE_NONCE', True) and nonce != token_nonce: msg = 'JWT Nonce verification failed.' raise SuspiciousOperation(msg) return payload
<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(self, payload): """Return token object as a dictionary."""
auth = None if self.get_settings('OIDC_TOKEN_USE_BASIC_AUTH', False): # When Basic auth is defined, create the Auth Header and remove secret from payload. user = payload.get('client_id') pw = payload.get('client_secret') auth = HTTPBasicAuth(user, pw) del payload['client_secret'] response = requests.post( self.OIDC_OP_TOKEN_ENDPOINT, data=payload, auth=auth, verify=self.get_settings('OIDC_VERIFY_SSL', True)) response.raise_for_status() return response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_userinfo(self, access_token, id_token, payload): """Return user details dictionary. The id_token and payload are not used in the default implementation, but may be used when overriding this method"""
user_response = requests.get( self.OIDC_OP_USER_ENDPOINT, headers={ 'Authorization': 'Bearer {0}'.format(access_token) }, verify=self.get_settings('OIDC_VERIFY_SSL', True)) user_response.raise_for_status() return user_response.json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, request, **kwargs): """Authenticates a user based on the OIDC code flow."""
self.request = request if not self.request: return None state = self.request.GET.get('state') code = self.request.GET.get('code') nonce = kwargs.pop('nonce', None) if not code or not state: return None reverse_url = self.get_settings('OIDC_AUTHENTICATION_CALLBACK_URL', 'oidc_authentication_callback') token_payload = { 'client_id': self.OIDC_RP_CLIENT_ID, 'client_secret': self.OIDC_RP_CLIENT_SECRET, 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': absolutify( self.request, reverse(reverse_url) ), } # Get the token token_info = self.get_token(token_payload) id_token = token_info.get('id_token') access_token = token_info.get('access_token') # Validate the token payload = self.verify_token(id_token, nonce=nonce) if payload: self.store_tokens(access_token, id_token) try: return self.get_or_create_user(access_token, id_token, payload) except SuspiciousOperation as exc: LOGGER.warning('failed to get or create user: %s', exc) return None 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 store_tokens(self, access_token, id_token): """Store OIDC tokens."""
session = self.request.session if self.get_settings('OIDC_STORE_ACCESS_TOKEN', False): session['oidc_access_token'] = access_token if self.get_settings('OIDC_STORE_ID_TOKEN', False): session['oidc_id_token'] = id_token
<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_or_create_user(self, access_token, id_token, payload): """Returns a User instance if 1 user is found. Creates a user if not found and configured to do so. Returns nothing if multiple users are matched."""
user_info = self.get_userinfo(access_token, id_token, payload) email = user_info.get('email') claims_verified = self.verify_claims(user_info) if not claims_verified: msg = 'Claims verification failed' raise SuspiciousOperation(msg) # email based filtering users = self.filter_users_by_claims(user_info) if len(users) == 1: return self.update_user(users[0], user_info) elif len(users) > 1: # In the rare case that two user accounts have the same email address, # bail. Randomly selecting one seems really wrong. msg = 'Multiple users returned' raise SuspiciousOperation(msg) elif self.get_settings('OIDC_CREATE_USER', True): user = self.create_user(user_info) return user else: LOGGER.debug('Login failed: No user with email %s found, and ' 'OIDC_CREATE_USER is False', email) 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 exempt_urls(self): """Generate and return a set of url paths to exempt from SessionRefresh This takes the value of ``settings.OIDC_EXEMPT_URLS`` and appends three urls that mozilla-django-oidc uses. These values can be view names or absolute url paths. :returns: list of url paths (for example "/oidc/callback/") """
exempt_urls = list(self.get_settings('OIDC_EXEMPT_URLS', [])) exempt_urls.extend([ 'oidc_authentication_init', 'oidc_authentication_callback', 'oidc_logout', ]) return set([ url if url.startswith('/') else reverse(url) for url in exempt_urls ])
<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_refreshable_url(self, request): """Takes a request and returns whether it triggers a refresh examination :arg HttpRequest request: :returns: boolean """
# Do not attempt to refresh the session if the OIDC backend is not used backend_session = request.session.get(BACKEND_SESSION_KEY) is_oidc_enabled = True if backend_session: auth_backend = import_string(backend_session) is_oidc_enabled = issubclass(auth_backend, OIDCAuthenticationBackend) return ( request.method == 'GET' and is_authenticated(request.user) and is_oidc_enabled and request.path not in self.exempt_urls )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read(self): """ Reads and returns a buffer reversely from current file-pointer position. :rtype : str """
filepos = self._fp.tell() if filepos < 1: return "" destpos = max(filepos - self._chunk_size, 0) self._fp.seek(destpos) buf = self._fp.read(filepos - destpos) self._fp.seek(destpos) return buf
<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): """ Returns the position of the first occurence of needle. If the needle was not found, -1 is returned. :rtype : int """
lastbuf = "" while 0 < self._fp.tell(): buf = self._read() bufpos = (buf + lastbuf).rfind(self._needle) if bufpos > -1: filepos = self._fp.tell() + bufpos self._fp.seek(filepos) return filepos # for it to work when the needle is split between chunks. lastbuf = buf[:len(self._needle)] return -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 search(self, text): """ Find text in log file from current position returns a tuple containing: absolute position, position in result buffer, result buffer (the actual file contents) """
key = hash(text) searcher = self._searchers.get(key) if not searcher: searcher = ReverseFileSearcher(self.filename, text) self._searchers[key] = searcher position = searcher.find() if position < 0: # reset the searcher to start from the tail again. searcher.reset() return -1, -1, '' # try to get some content from before and after the result's position read_before = self.buffer_size / 2 offset = max(position - read_before, 0) bufferpos = position if offset == 0 else read_before self.fp.seek(offset) return position, bufferpos, self.read()
<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_interface_addresses(): """ Get addresses of available network interfaces. See netifaces on pypi for details. Returns a list of dicts """
addresses = [] ifaces = netifaces.interfaces() for iface in ifaces: addrs = netifaces.ifaddresses(iface) families = addrs.keys() # put IPv4 to the end so it lists as the main iface address if netifaces.AF_INET in families: families.remove(netifaces.AF_INET) families.append(netifaces.AF_INET) for family in families: for addr in addrs[family]: address = { 'name': iface, 'family': family, 'ip': addr['addr'], } addresses.append(address) return addresses
<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_net_io_counters(self): """ Fetch io counters from psutil and transform it to dicts with the additional attributes defaulted """
counters = psutil.net_io_counters(pernic=self.pernic) res = {} for name, io in counters.iteritems(): res[name] = io._asdict() res[name].update({'tx_per_sec': 0, 'rx_per_sec': 0}) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build( cls, *, scheme="", user="", password=None, host="", port=None, path="", query=None, query_string="", fragment="", encoded=False ): """Creates and returns a new URL"""
if not host and scheme: raise ValueError('Can\'t build URL with "scheme" but without "host".') if port and not host: raise ValueError('Can\'t build URL with "port" but without "host".') if query and query_string: raise ValueError('Only one of "query" or "query_string" should be passed') if path is None or query_string is None or fragment is None: raise TypeError('NoneType is illegal for "path", "query_string" and ' '"fragment" args, use string values instead.') if not user and not password and not host and not port: netloc = "" else: netloc = cls._make_netloc(user, password, host, port, encode=not encoded) if not encoded: path = cls._PATH_QUOTER(path) if netloc: path = cls._normalize_path(path) cls._validate_authority_uri_abs_path(host=host, path=path) query_string = cls._QUERY_QUOTER(query_string) fragment = cls._FRAGMENT_QUOTER(fragment) url = cls( SplitResult(scheme, netloc, path, query_string, fragment), encoded=True ) if query: return url.with_query(query) else: return 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 is_default_port(self): """A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise. """
if self.port is None: return False default = DEFAULT_PORTS.get(self.scheme) if default is None: return False return self.port == default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def origin(self): """Return an URL with scheme, host and port parts only. user, password, path, query and fragment are removed. """
# TODO: add a keyword-only option for keeping user/pass maybe? if not self.is_absolute(): raise ValueError("URL should be absolute") if not self._val.scheme: raise ValueError("URL should have scheme") v = self._val netloc = self._make_netloc(None, None, v.hostname, v.port, encode=False) val = v._replace(netloc=netloc, path="", query="", fragment="") return URL(val, encoded=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 relative(self): """Return a relative part of the URL. scheme, user, password, host and port are removed. """
if not self.is_absolute(): raise ValueError("URL should be absolute") val = self._val._replace(scheme="", netloc="") return URL(val, encoded=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 host(self): """Decoded host part of URL. None for relative URLs. """
raw = self.raw_host if raw is None: return None if "%" in raw: # Hack for scoped IPv6 addresses like # fe80::2%Проверка # presence of '%' sign means only IPv6 address, so idna is useless. return raw try: return idna.decode(raw.encode("ascii")) except UnicodeError: # e.g. '::1' return raw.encode("ascii").decode("idna")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def port(self): """Port part of URL, with scheme-based fallback. None for relative URLs or URLs without explicit port and scheme without default port substitution. """
return self._val.port or DEFAULT_PORTS.get(self._val.scheme)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_path(self): """Encoded path of URL. / for absolute URLs without path part. """
ret = self._val.path if not ret and self.is_absolute(): ret = "/" 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 query(self): """A MultiDictProxy representing parsed query parameters in decoded representation. Empty value if URL has no query part. """
ret = MultiDict(parse_qsl(self.raw_query_string, keep_blank_values=True)) return MultiDictProxy(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 path_qs(self): """Decoded path of URL with query."""
if not self.query_string: return self.path return "{}?{}".format(self.path, self.query_string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raw_path_qs(self): """Encoded path of URL with query."""
if not self.raw_query_string: return self.raw_path return "{}?{}".format(self.raw_path, self.raw_query_string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent(self): """A new URL with last part of path removed and cleaned up query and fragment. """
path = self.raw_path if not path or path == "/": if self.raw_fragment or self.raw_query_string: return URL(self._val._replace(query="", fragment=""), encoded=True) return self parts = path.split("/") val = self._val._replace(path="/".join(parts[:-1]), query="", fragment="") return URL(val, encoded=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 raw_name(self): """The last part of raw_parts."""
parts = self.raw_parts if self.is_absolute(): parts = parts[1:] if not parts: return "" else: return parts[-1] else: return parts[-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 _validate_authority_uri_abs_path(host, path): """Ensure that path in URL with authority starts with a leading slash. Raise ValueError if not. """
if len(host) > 0 and len(path) > 0 and not path.startswith("/"): raise ValueError( "Path in a URL with authority " "should start with a slash ('/') if set" )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_scheme(self, scheme): """Return a new URL with scheme replaced."""
# N.B. doesn't cleanup query/fragment if not isinstance(scheme, str): raise TypeError("Invalid scheme type") if not self.is_absolute(): raise ValueError("scheme replacement is not allowed " "for relative URLs") return URL(self._val._replace(scheme=scheme.lower()), encoded=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 with_user(self, user): """Return a new URL with user replaced. Autoencode user if needed. Clear user/password if user is None. """
# N.B. doesn't cleanup query/fragment val = self._val if user is None: password = None elif isinstance(user, str): user = self._QUOTER(user) password = val.password else: raise TypeError("Invalid user type") if not self.is_absolute(): raise ValueError("user replacement is not allowed " "for relative URLs") return URL( self._val._replace( netloc=self._make_netloc( user, password, val.hostname, val.port, encode=False ) ), encoded=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 with_host(self, host): """Return a new URL with host replaced. Autoencode host if needed. Changing host for relative URLs is not allowed, use .join() instead. """
# N.B. doesn't cleanup query/fragment if not isinstance(host, str): raise TypeError("Invalid host type") if not self.is_absolute(): raise ValueError("host replacement is not allowed " "for relative URLs") if not host: raise ValueError("host removing is not allowed") host = self._encode_host(host) val = self._val return URL( self._val._replace( netloc=self._make_netloc( val.username, val.password, host, val.port, encode=False ) ), encoded=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 with_port(self, port): """Return a new URL with port replaced. Clear port to default if None is passed. """
# N.B. doesn't cleanup query/fragment if port is not None and not isinstance(port, int): raise TypeError("port should be int or None, got {}".format(type(port))) if not self.is_absolute(): raise ValueError("port replacement is not allowed " "for relative URLs") val = self._val return URL( self._val._replace( netloc=self._make_netloc( val.username, val.password, val.hostname, port, encode=False ) ), encoded=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 with_path(self, path, *, encoded=False): """Return a new URL with path replaced."""
if not encoded: path = self._PATH_QUOTER(path) if self.is_absolute(): path = self._normalize_path(path) if len(path) > 0 and path[0] != "/": path = "/" + path return URL(self._val._replace(path=path, query="", fragment=""), encoded=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 with_query(self, *args, **kwargs): """Return a new URL with query part replaced. Accepts any Mapping (e.g. dict, multidict.MultiDict instances) or str, autoencode the argument if needed. A sequence of (key, value) pairs is supported as well. It also can take an arbitrary number of keyword arguments. Clear query if None is passed. """
# N.B. doesn't cleanup query/fragment new_query = self._get_str_query(*args, **kwargs) return URL( self._val._replace(path=self._val.path, query=new_query), encoded=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_query(self, *args, **kwargs): """Return a new URL with query part updated."""
s = self._get_str_query(*args, **kwargs) new_query = MultiDict(parse_qsl(s, keep_blank_values=True)) query = MultiDict(self.query) query.update(new_query) return URL(self._val._replace(query=self._get_str_query(query)), encoded=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 with_fragment(self, fragment): """Return a new URL with fragment replaced. Autoencode fragment if needed. Clear fragment to default if None is passed. """
# N.B. doesn't cleanup query/fragment if fragment is None: fragment = "" elif not isinstance(fragment, str): raise TypeError("Invalid fragment type") return URL( self._val._replace(fragment=self._FRAGMENT_QUOTER(fragment)), encoded=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 human_repr(self): """Return decoded human readable string for URL representation."""
return urlunsplit( SplitResult( self.scheme, self._make_netloc( self.user, self.password, self.host, self._val.port, encode=False ), self.path, self.query_string, self.fragment, ) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_arch_srcarch_kconfigs(): """ Generates Kconfig instances for all the architectures in the kernel """
os.environ["srctree"] = "." os.environ["HOSTCC"] = "gcc" os.environ["HOSTCXX"] = "g++" os.environ["CC"] = "gcc" os.environ["LD"] = "ld" for arch, srcarch in all_arch_srcarch_pairs(): print(" Processing " + arch) os.environ["ARCH"] = arch os.environ["SRCARCH"] = srcarch # um (User Mode Linux) uses a different base Kconfig file yield Kconfig("Kconfig" if arch != "um" else "arch/x86/um/Kconfig", warn=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 menuconfig(kconf): """ Launches the configuration interface, returning after the user exits. kconf: Kconfig instance to be configured """
global _kconf global _conf_filename global _conf_changed global _minconf_filename global _show_all _kconf = kconf # Load existing configuration and set _conf_changed True if it is outdated _conf_changed = _load_config() # Filename to save configuration to _conf_filename = standard_config_filename() # Filename to save minimal configuration to _minconf_filename = "defconfig" # Any visible items in the top menu? _show_all = False if not _shown_nodes(kconf.top_node): # Nothing visible. Start in show-all mode and try again. _show_all = True if not _shown_nodes(kconf.top_node): # Give up. The implementation relies on always having a selected # node. print("Empty configuration -- nothing to configure.\n" "Check that environment variables are set properly.") return # Disable warnings. They get mangled in curses mode, and we deal with # errors ourselves. kconf.disable_warnings() # Make curses use the locale settings specified in the environment locale.setlocale(locale.LC_ALL, "") # Try to fix Unicode issues on systems with bad defaults if _CONVERT_C_LC_CTYPE_TO_UTF8: _convert_c_lc_ctype_to_utf8() # Get rid of the delay between pressing ESC and jumping to the parent menu, # unless the user has set ESCDELAY (see ncurses(3)). This makes the UI much # smoother to work with. # # Note: This is strictly pretty iffy, since escape codes for e.g. cursor # keys start with ESC, but I've never seen it cause problems in practice # (probably because it's unlikely that the escape code for a key would get # split up across read()s, at least with a terminal emulator). Please # report if you run into issues. Some suitable small default value could be # used here instead in that case. Maybe it's silly to not put in the # smallest imperceptible delay here already, though I don't like guessing. # # (From a quick glance at the ncurses source code, ESCDELAY might only be # relevant for mouse events there, so maybe escapes are assumed to arrive # in one piece already...) os.environ.setdefault("ESCDELAY", "0") # Enter curses mode. _menuconfig() returns a string to print on exit, after # curses has been de-initialized. print(curses.wrapper(_menuconfig))
<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_menuconfig_nodes(node, indent): """ Prints a tree with all the menu entries rooted at 'node'. Child menu entries are indented. """
while node: string = node_str(node) if string: indent_print(string, indent) if node.list: print_menuconfig_nodes(node.list, indent + 8) node = node.next
<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_menuconfig(kconf): """ Prints all menu entries for the configuration. """
# Print the expanded mainmenu text at the top. This is the same as # kconf.top_node.prompt[0], but with variable references expanded. print("\n======== {} ========\n".format(kconf.mainmenu_text)) print_menuconfig_nodes(kconf.top_node.list, 0) 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 expr_str(expr, sc_expr_str_fn=standard_sc_expr_str): """ Returns the string representation of the expression 'expr', as in a Kconfig file. Passing subexpressions of expressions to this function works as expected. sc_expr_str_fn (default: standard_sc_expr_str): This function is called for every symbol/choice (hence "sc") appearing in the expression, with the symbol/choice as the argument. It is expected to return a string to be used for the symbol/choice. This can be used e.g. to turn symbols/choices into links when generating documentation, or for printing the value of each symbol/choice after it. Note that quoted values are represented as constants symbols (Symbol.is_constant == True). """
if expr.__class__ is not tuple: return sc_expr_str_fn(expr) if expr[0] is AND: return "{} && {}".format(_parenthesize(expr[1], OR, sc_expr_str_fn), _parenthesize(expr[2], OR, sc_expr_str_fn)) if expr[0] is OR: # This turns A && B || C && D into "(A && B) || (C && D)", which is # redundant, but more readable return "{} || {}".format(_parenthesize(expr[1], AND, sc_expr_str_fn), _parenthesize(expr[2], AND, sc_expr_str_fn)) if expr[0] is NOT: if expr[1].__class__ is tuple: return "!({})".format(expr_str(expr[1], sc_expr_str_fn)) return "!" + sc_expr_str_fn(expr[1]) # Symbol # Relation # # Relation operands are always symbols (quoted strings are constant # symbols) return "{} {} {}".format(sc_expr_str_fn(expr[1]), _REL_TO_STR[expr[0]], sc_expr_str_fn(expr[2]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def standard_kconfig(): """ Helper for tools. Loads the top-level Kconfig specified as the first command-line argument, or "Kconfig" if there are no command-line arguments. Returns the Kconfig instance. Exits with sys.exit() (which raises a SystemExit exception) and prints a usage note to stderr if more than one command-line argument is passed. """
if len(sys.argv) > 2: sys.exit("usage: {} [Kconfig]".format(sys.argv[0])) # Only show backtraces for unexpected exceptions try: return Kconfig("Kconfig" if len(sys.argv) < 2 else sys.argv[1]) except (IOError, KconfigError) as e: # Some long exception messages have extra newlines for better # formatting when reported as an unhandled exception. Strip them here. sys.exit(str(e).strip())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_config(self, filename=None, header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n", save_old=True, verbose=True): r""" Writes out symbol values in the .config format. The format matches the C implementation, including ordering. Symbols appear in the same order in generated .config files as they do in the Kconfig files. For symbols defined in multiple locations, a single assignment is written out corresponding to the first location where the symbol is defined. See the 'Intro to symbol values' section in the module docstring to understand which symbols get written out. filename (default: None): Filename to save configuration to (a string). If None (the default), the filename in the the environment variable KCONFIG_CONFIG is used if set, and ".config" otherwise. See standard_config_filename(). header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"): Text that will be inserted verbatim at the beginning of the file. You would usually want each line to start with '#' to make it a comment, and include a final terminating newline. save_old (default: True): If True and <filename> already exists, a copy of it will be saved to .<filename>.old in the same directory before the new configuration is written. The leading dot is added only if the filename doesn't already start with a dot. Errors are silently ignored if .<filename>.old cannot be written (e.g. due to being a directory). verbose (default: True): If True and filename is None (automatically infer configuration file), a message will be printed to stdout telling which file got written. This is meant to reduce boilerplate in tools. """
if filename is None: filename = standard_config_filename() else: verbose = False if save_old: _save_old(filename) with self._open(filename, "w") as f: f.write(header) for node in self.node_iter(unique_syms=True): item = node.item if item.__class__ is Symbol: f.write(item.config_string) elif expr_value(node.dep) and \ ((item is MENU and expr_value(node.visibility)) or item is COMMENT): f.write("\n#\n# {}\n#\n".format(node.prompt[0])) if verbose: print("Configuration written to '{}'".format(filename))
<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_min_config(self, filename, header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"): """ Writes out a "minimal" configuration file, omitting symbols whose value matches their default value. The format matches the one produced by 'make savedefconfig'. The resulting configuration file is incomplete, but a complete configuration can be derived from it by loading it. Minimal configuration files can serve as a more manageable configuration format compared to a "full" .config file, especially when configurations files are merged or edited by hand. filename: Self-explanatory. header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"): Text that will be inserted verbatim at the beginning of the file. You would usually want each line to start with '#' to make it a comment, and include a final terminating newline. """
with self._open(filename, "w") as f: f.write(header) for sym in self.unique_defined_syms: # Skip symbols that cannot be changed. Only check # non-choice symbols, as selects don't affect choice # symbols. if not sym.choice and \ sym.visibility <= expr_value(sym.rev_dep): continue # Skip symbols whose value matches their default if sym.str_value == sym._str_default(): continue # Skip symbols that would be selected by default in a # choice, unless the choice is optional or the symbol type # isn't bool (it might be possible to set the choice mode # to n or the symbol to m in those cases). if sym.choice and \ not sym.choice.is_optional and \ sym.choice._get_selection_from_defaults() is sym and \ sym.orig_type is BOOL and \ sym.tri_value == 2: continue f.write(sym.config_string)