_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q34400
BlockMatcher.load_settings
train
def load_settings(self, settings): """Load settings from file""" with open(settings) as settings_file: settings_dict = simplejson.load(settings_file) for key, value in settings_dict.items(): self.__setattr__(key, value)
python
{ "resource": "" }
q34401
BlockMatcher.save_settings
train
def save_settings(self, settings_file): """Save block matcher settings to a file object""" settings = {} for parameter in self.parameter_maxima: settings[parameter] = self.__getattribute__(parameter) with open(settings_file, "w") as settings_file: simplejson.dump(...
python
{ "resource": "" }
q34402
StereoBM.search_range
train
def search_range(self, value): """Set private ``_search_range`` and reset ``_block_matcher``.""" if value == 0 or not value % 16: self._search_range = value else: raise InvalidSearchRangeError("Search range must be a multiple of " ...
python
{ "resource": "" }
q34403
StereoBM.window_size
train
def window_size(self, value): """Set private ``_window_size`` and reset ``_block_matcher``.""" if (value > 4 and value < self.parameter_maxima["window_size"] and value % 2): self._window_size = value else: raise InvalidWindowSizeError("Window size ...
python
{ "resource": "" }
q34404
StereoBM.stereo_bm_preset
train
def stereo_bm_preset(self, value): """Set private ``_stereo_bm_preset`` and reset ``_block_matcher``.""" if value in (cv2.STEREO_BM_BASIC_PRESET, cv2.STEREO_BM_FISH_EYE_PRESET, cv2.STEREO_BM_NARROW_PRESET): self._bm_preset = value else: ...
python
{ "resource": "" }
q34405
StereoSGBM.numDisparities
train
def numDisparities(self, value): """Set private ``_num_disp`` and reset ``_block_matcher``.""" if value > 0 and value % 16 == 0: self._num_disp = value else: raise InvalidNumDisparitiesError("numDisparities must be a " "positiv...
python
{ "resource": "" }
q34406
StereoSGBM.SADWindowSize
train
def SADWindowSize(self, value): """Set private ``_sad_window_size`` and reset ``_block_matcher``.""" if value >= 1 and value <= 11 and value % 2: self._sad_window_size = value else: raise InvalidSADWindowSizeError("SADWindowSize must be odd and " ...
python
{ "resource": "" }
q34407
StereoSGBM.uniquenessRatio
train
def uniquenessRatio(self, value): """Set private ``_uniqueness`` and reset ``_block_matcher``.""" if value >= 5 and value <= 15: self._uniqueness = value else: raise InvalidUniquenessRatioError("Uniqueness ratio must be " "bet...
python
{ "resource": "" }
q34408
StereoSGBM.speckleWindowSize
train
def speckleWindowSize(self, value): """Set private ``_speckle_window_size`` and reset ``_block_matcher``.""" if value >= 0 and value <= 200: self._speckle_window_size = value else: raise InvalidSpeckleWindowSizeError("Speckle window size must be 0 " ...
python
{ "resource": "" }
q34409
StereoSGBM.speckleRange
train
def speckleRange(self, value): """Set private ``_speckle_range`` and reset ``_block_matcher``.""" if value >= 0: self._speckle_range = value else: raise InvalidSpeckleRangeError("Speckle range cannot be negative.") self._replace_bm()
python
{ "resource": "" }
q34410
StereoSGBM.P1
train
def P1(self, value): """Set private ``_P1`` and reset ``_block_matcher``.""" if value < self.P2: self._P1 = value else: raise InvalidFirstDisparityChangePenaltyError("P1 must be less " "than P2.") self._rep...
python
{ "resource": "" }
q34411
StereoSGBM.P2
train
def P2(self, value): """Set private ``_P2`` and reset ``_block_matcher``.""" if value > self.P1: self._P2 = value else: raise InvalidSecondDisparityChangePenaltyError("P2 must be greater " "than P1.") self....
python
{ "resource": "" }
q34412
StereoCalibration._copy_calibration
train
def _copy_calibration(self, calibration): """Copy another ``StereoCalibration`` object's values.""" for key, item in calibration.__dict__.items(): self.__dict__[key] = item
python
{ "resource": "" }
q34413
StereoCalibrator._get_corners
train
def _get_corners(self, image): """Find subpixel chessboard corners in image.""" temp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) ret, corners = cv2.findChessboardCorners(temp, (self.rows, self.columns)) if not ret: raise Chessboa...
python
{ "resource": "" }
q34414
StereoCalibrator._show_corners
train
def _show_corners(self, image, corners): """Show chessboard corners found in image.""" temp = image cv2.drawChessboardCorners(temp, (self.rows, self.columns), corners, True) window_name = "Chessboard" cv2.imshow(window_name, temp) if cv2....
python
{ "resource": "" }
q34415
StereoCalibrator.add_corners
train
def add_corners(self, image_pair, show_results=False): """ Record chessboard corners found in an image pair. The image pair should be an iterable composed of two CvMats ordered (left, right). """ side = "left" self.object_points.append(self.corner_coordinates) ...
python
{ "resource": "" }
q34416
StereoCalibrator.calibrate_cameras
train
def calibrate_cameras(self): """Calibrate cameras based on found chessboard corners.""" criteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 100, 1e-5) flags = (cv2.CALIB_FIX_ASPECT_RATIO + cv2.CALIB_ZERO_TANGENT_DIST + cv2.CALIB_SAME_FOCAL_LENGTH)...
python
{ "resource": "" }
q34417
StereoCalibrator.check_calibration
train
def check_calibration(self, calibration): """ Check calibration quality by computing average reprojection error. First, undistort detected points and compute epilines for each side. Then compute the error between the computed epipolar lines and the position of the points detecte...
python
{ "resource": "" }
q34418
find_files
train
def find_files(folder): """Discover stereo photos and return them as a pairwise sorted list.""" files = [i for i in os.listdir(folder) if i.startswith("left")] files.sort() for i in range(len(files)): insert_string = "right{}".format(files[i * 2][4:]) files.insert(i * 2 + 1, insert_strin...
python
{ "resource": "" }
q34419
calibrate_folder
train
def calibrate_folder(args): """ Calibrate camera based on chessboard images, write results to output folder. All images are read from disk. Chessboard points are found and used to calibrate the stereo pair. Finally, the calibration is written to the folder specified in ``args``. ``args`` needs...
python
{ "resource": "" }
q34420
BMTuner._set_value
train
def _set_value(self, parameter, new_value): """Try setting new parameter on ``block_matcher`` and update map.""" try: self.block_matcher.__setattr__(parameter, new_value) except BadBlockMatcherArgumentError: return self.update_disparity_map()
python
{ "resource": "" }
q34421
BMTuner._initialize_trackbars
train
def _initialize_trackbars(self): """ Initialize trackbars by discovering ``block_matcher``'s parameters. """ for parameter in self.block_matcher.parameter_maxima.keys(): maximum = self.block_matcher.parameter_maxima[parameter] if not maximum: maxim...
python
{ "resource": "" }
q34422
BMTuner._save_bm_state
train
def _save_bm_state(self): """Save current state of ``block_matcher``.""" for parameter in self.block_matcher.parameter_maxima.keys(): self.bm_settings[parameter].append( self.block_matcher.__getattribute__(parameter))
python
{ "resource": "" }
q34423
BMTuner.update_disparity_map
train
def update_disparity_map(self): """ Update disparity map in GUI. The disparity image is normalized to the range 0-255 and then divided by 255, because OpenCV multiplies it by 255 when displaying. This is because the pixels are stored as floating points. """ dispa...
python
{ "resource": "" }
q34424
BMTuner.tune_pair
train
def tune_pair(self, pair): """Tune a pair of images.""" self._save_bm_state() self.pair = pair self.update_disparity_map()
python
{ "resource": "" }
q34425
BMTuner.report_settings
train
def report_settings(self, parameter): """ Report chosen settings for ``parameter`` in ``block_matcher``. ``bm_settings`` is updated to include the latest state before work is begun. This state is removed at the end so that the method has no side effects. All settings are reporte...
python
{ "resource": "" }
q34426
PointCloud.write_ply
train
def write_ply(self, output_file): """Export ``PointCloud`` to PLY file for viewing in MeshLab.""" points = np.hstack([self.coordinates, self.colors]) with open(output_file, 'w') as outfile: outfile.write(self.ply_header.format( vertex_count...
python
{ "resource": "" }
q34427
PointCloud.filter_infinity
train
def filter_infinity(self): """Filter infinite distances from ``PointCloud.``""" mask = self.coordinates[:, 2] > self.coordinates[:, 2].min() coords = self.coordinates[mask] colors = self.colors[mask] return PointCloud(coords, colors)
python
{ "resource": "" }
q34428
BlockLoader._get_loader_for_url
train
def _get_loader_for_url(self, url): """ Determine loading method based on uri """ parts = url.split('://', 1) if len(parts) < 2: type_ = 'file' else: type_ = parts[0] if '+' in type_: profile_name, scheme = type_.split('+', 1) ...
python
{ "resource": "" }
q34429
LocalFileLoader.load
train
def load(self, url, offset=0, length=-1): """ Load a file-like reader from the local file system """ # if starting with . or /, can only be a file path.. file_only = url.startswith(('/', '.')) # convert to filename filename = from_file_url(url) if filena...
python
{ "resource": "" }
q34430
HttpLoader.load
train
def load(self, url, offset, length): """ Load a file-like reader over http using range requests and an optional cookie created via a cookie_maker """ headers = {} if offset != 0 or length != -1: headers['Range'] = BlockLoader._make_range_header(offset, length)...
python
{ "resource": "" }
q34431
BaseLoader.raise_on_self_redirect
train
def raise_on_self_redirect(self, params, cdx, status_code, location_url): """ Check if response is a 3xx redirect to the same url If so, reject this capture to avoid causing redirect loop """ if cdx.get('is_live'): return if not status_code.startswith('3') or...
python
{ "resource": "" }
q34432
BlockArcWarcRecordLoader.load
train
def load(self, url, offset, length, no_record_parse=False): """ Load a single record from given url at offset with length and parse as either warc or arc record """ try: length = int(length) except: length = -1 stream = self.loader.load(url, int(o...
python
{ "resource": "" }
q34433
CDXObject.conv_to_json
train
def conv_to_json(obj, fields=None): """ return cdx as json dictionary string if ``fields`` is ``None``, output will include all fields in order stored, otherwise only specified fields will be included :param fields: list of field names to output """ if fi...
python
{ "resource": "" }
q34434
StreamingRewriter.rewrite_text_stream_to_gen
train
def rewrite_text_stream_to_gen(self, stream, rwinfo): """ Convert stream to generator using applying rewriting func to each portion of the stream. Align to line boundaries if needed. """ try: buff = self.first_buff # for html rewriting: ...
python
{ "resource": "" }
q34435
cdx_load
train
def cdx_load(sources, query, process=True): """ merge text CDX lines from sources, return an iterator for filtered and access-checked sequence of CDX objects. :param sources: iterable for text CDX sources. :param process: bool, perform processing sorting/filtering/grouping ops """ cdx_iter ...
python
{ "resource": "" }
q34436
create_merged_cdx_gen
train
def create_merged_cdx_gen(sources, query): """ create a generator which loads and merges cdx streams ensures cdxs are lazy loaded """ # Optimize: no need to merge if just one input if len(sources) == 1: cdx_iter = sources[0].load_cdx(query) else: source_iters = map(lambda src...
python
{ "resource": "" }
q34437
cdx_limit
train
def cdx_limit(cdx_iter, limit): """ limit cdx to at most `limit`. """ # for cdx, _ in itertools.izip(cdx_iter, xrange(limit)): # yield cdx return (cdx for cdx, _ in zip(cdx_iter, range(limit)))
python
{ "resource": "" }
q34438
cdx_reverse
train
def cdx_reverse(cdx_iter, limit): """ return cdx records in reverse order. """ # optimize for single last if limit == 1: last = None for cdx in cdx_iter: last = cdx if not last: return yield last reverse_cdxs = deque(maxlen=limit) f...
python
{ "resource": "" }
q34439
cdx_clamp
train
def cdx_clamp(cdx_iter, from_ts, to_ts): """ Clamp by start and end ts """ if from_ts and len(from_ts) < 14: from_ts = pad_timestamp(from_ts, PAD_14_DOWN) if to_ts and len(to_ts) < 14: to_ts = pad_timestamp(to_ts, PAD_14_UP) for cdx in cdx_iter: if from_ts and cdx[TIMES...
python
{ "resource": "" }
q34440
cdx_collapse_time_status
train
def cdx_collapse_time_status(cdx_iter, timelen=10): """ collapse by timestamp and status code. """ timelen = int(timelen) last_token = None for cdx in cdx_iter: curr_token = (cdx[TIMESTAMP][:timelen], cdx.get(STATUSCODE, '')) # yield if last_dedup_time is diff, otherwise skip ...
python
{ "resource": "" }
q34441
cdx_sort_closest
train
def cdx_sort_closest(closest, cdx_iter, limit=10): """ sort CDXCaptureResult by closest to timestamp. """ closest_cdx = [] closest_keys = [] closest_sec = timestamp_to_sec(closest) for cdx in cdx_iter: sec = timestamp_to_sec(cdx[TIMESTAMP]) key = abs(closest_sec - sec) ...
python
{ "resource": "" }
q34442
cdx_resolve_revisits
train
def cdx_resolve_revisits(cdx_iter): """ resolve revisits. this filter adds three fields to CDX: ``orig.length``, ``orig.offset``, and ``orig.filename``. for revisit records, these fields have corresponding field values in previous non-revisit (original) CDX record. They are all ``"-"`` for non-...
python
{ "resource": "" }
q34443
BaseCli.load
train
def load(self): """This method is called to load the application. Subclasses must return a application that can be used by used by pywb.utils.geventserver.GeventServer.""" if self.r.live: self.extra_config['collections'] = {'live': {'index': '$live'}} if ...
python
{ "resource": "" }
q34444
BaseCli.run_gevent
train
def run_gevent(self): """Created the server that runs the application supplied a subclass""" from pywb.utils.geventserver import GeventServer, RequestURIWSGIHandler logging.info('Starting Gevent Server on ' + str(self.r.port)) ge = GeventServer(self.application, ...
python
{ "resource": "" }
q34445
JinjaEnv._make_loaders
train
def _make_loaders(self, paths, packages): """Initialize the template loaders based on the supplied paths and packages. :param list[str] paths: List of paths to search for templates :param list[str] packages: List of assets package names :return: A list of loaders to be used for loading ...
python
{ "resource": "" }
q34446
JinjaEnv.template_filter
train
def template_filter(self, param=None): """Returns a decorator that adds the wrapped function to dictionary of template filters. The wrapped function is keyed by either the supplied param (if supplied) or by the wrapped functions name. :param param: Optional name to use instead of the n...
python
{ "resource": "" }
q34447
JinjaEnv._init_filters
train
def _init_filters(self): """Initialize the default pywb provided Jninja filters available during template rendering""" self.filters = {} @self.template_filter() def format_ts(value, format_='%a, %b %d %Y %H:%M:%S'): """Formats the supplied timestamp using format_ ...
python
{ "resource": "" }
q34448
BaseInsertView.render_to_string
train
def render_to_string(self, env, **kwargs): """Render this template. :param dict env: The WSGI environment associated with the request causing this template to be rendered :param any kwargs: The keyword arguments to be supplied to the Jninja template render method :return: The rendered t...
python
{ "resource": "" }
q34449
HeadInsertView.create_insert_func
train
def create_insert_func(self, wb_url, wb_prefix, host_prefix, top_url, env, is_framed, coll='', include_ts=True, ...
python
{ "resource": "" }
q34450
PkgResResolver.get_pkg_path
train
def get_pkg_path(self, item): """Get the package path for the :param str item: A resources full package path :return: The netloc and path from the items package path :rtype: tuple[str, str] """ if not isinstance(item, str): return None parts = urlspl...
python
{ "resource": "" }
q34451
WbResponse.text_stream
train
def text_stream(stream, content_type='text/plain; charset=utf-8', status='200 OK'): """Utility method for constructing a streaming text response. :param Any stream: The response body stream :param str content_type: The content-type of the response :param str status: The HTTP status line...
python
{ "resource": "" }
q34452
WbResponse.bin_stream
train
def bin_stream(stream, content_type, status='200 OK', headers=None): """Utility method for constructing a binary response. :param Any stream: The response body stream :param str content_type: The content-type of the response :param str status: The HTTP status line ...
python
{ "resource": "" }
q34453
WbResponse.text_response
train
def text_response(text, status='200 OK', content_type='text/plain; charset=utf-8'): """Utility method for constructing a text response. :param str text: The text response body :param str content_type: The content-type of the response :param str status: The HTTP status line :retu...
python
{ "resource": "" }
q34454
WbResponse.json_response
train
def json_response(obj, status='200 OK', content_type='application/json; charset=utf-8'): """Utility method for constructing a JSON response. :param dict obj: The dictionary to be serialized in JSON format :param str content_type: The content-type of the response :param str status: The H...
python
{ "resource": "" }
q34455
WbResponse.redir_response
train
def redir_response(location, status='302 Redirect', headers=None): """Utility method for constructing redirection response. :param str location: The location of the resource redirecting to :param str status: The HTTP status line :param list[tuple[str, str]] headers: Additional headers f...
python
{ "resource": "" }
q34456
WbResponse.options_response
train
def options_response(env): """Construct WbResponse for OPTIONS based on the WSGI env dictionary :param dict env: The WSGI environment dictionary :return: The WBResponse for the options request :rtype: WbResponse """ status_headers = StatusAndHeaders('200 Ok', [ ...
python
{ "resource": "" }
q34457
canonicalize
train
def canonicalize(url, surt_ordered=True): """ Canonicalize url and convert to surt If not in surt ordered mode, convert back to url form as surt conversion is currently part of canonicalization >>> canonicalize('http://example.com/path/file.html', surt_ordered=True) 'com,example)/path/file.html...
python
{ "resource": "" }
q34458
FuzzyMatcher.parse_fuzzy_rule
train
def parse_fuzzy_rule(self, rule): """ Parse rules using all the different supported forms """ url_prefix = rule.get('url_prefix') config = rule.get('fuzzy_lookup') if not config: return if not isinstance(url_prefix, list): url_prefix = [url_prefix...
python
{ "resource": "" }
q34459
ResolvingLoader.load_headers_and_payload
train
def load_headers_and_payload(self, cdx, failed_files, cdx_loader): """ Resolve headers and payload for a given capture In the simple case, headers and payload are in the same record. In the case of revisit records, the payload and headers may be in different records. If ...
python
{ "resource": "" }
q34460
ResolvingLoader._load_different_url_payload
train
def _load_different_url_payload(self, cdx, headers_record, failed_files, cdx_loader): """ Handle the case where a duplicate of a capture with same digest exists at a different url. If a cdx_server is provided, a query is made for matching url,...
python
{ "resource": "" }
q34461
ResolvingLoader.load_cdx_for_dupe
train
def load_cdx_for_dupe(self, url, timestamp, digest, cdx_loader): """ If a cdx_server is available, return response from server, otherwise empty list """ if not cdx_loader: return iter([]) filters = [] filters.append('!mime:warc/revisit') if ...
python
{ "resource": "" }
q34462
binsearch_offset
train
def binsearch_offset(reader, key, compare_func=cmp, block_size=8192): """ Find offset of the line which matches a given 'key' using binary search If key is not found, the offset is of the line after the key File is subdivided into block_size (default 8192) sized blocks Optional compare_func may be ...
python
{ "resource": "" }
q34463
linearsearch
train
def linearsearch(iter_, key, prev_size=0, compare_func=cmp): """ Perform a linear search over iterator until current_line >= key optionally also tracking upto N previous lines, which are returned before the first matched line. if end of stream is reached before a match is found, nothing is...
python
{ "resource": "" }
q34464
iter_prefix
train
def iter_prefix(reader, key): """ Creates an iterator which iterates over lines that start with prefix 'key' in a sorted text file. """ return itertools.takewhile( lambda line: line.startswith(key), search(reader, key))
python
{ "resource": "" }
q34465
FrontEndApp.get_upstream_paths
train
def get_upstream_paths(self, port): """Retrieve a dictionary containing the full URLs of the upstream apps :param int port: The port used by the replay and cdx servers :return: A dictionary containing the upstream paths (replay, cdx-server, record [if enabled]) :rtype: dict[str, str] ...
python
{ "resource": "" }
q34466
FrontEndApp.init_recorder
train
def init_recorder(self, recorder_config): """Initialize the recording functionality of pywb. If recording_config is None this function is a no op""" if not recorder_config: self.recorder = None self.recorder_path = None return if isinstance(recorder_config, s...
python
{ "resource": "" }
q34467
FrontEndApp.init_autoindex
train
def init_autoindex(self, auto_interval): """Initialize and start the auto-indexing of the collections. If auto_interval is None this is a no op. :param str|int auto_interval: The auto-indexing interval from the configuration file or CLI argument """ if not auto_interval: ret...
python
{ "resource": "" }
q34468
FrontEndApp.serve_static
train
def serve_static(self, environ, coll='', filepath=''): """Serve a static file associated with a specific collection or one of pywb's own static assets :param dict environ: The WSGI environment dictionary for the request :param str coll: The collection the static file is associated with ...
python
{ "resource": "" }
q34469
FrontEndApp.get_metadata
train
def get_metadata(self, coll): """Retrieve the metadata associated with a collection :param str coll: The name of the collection to receive metadata for :return: The collections metadata if it exists :rtype: dict """ #if coll == self.all_coll: # coll = '*' ...
python
{ "resource": "" }
q34470
FrontEndApp.serve_cdx
train
def serve_cdx(self, environ, coll='$root'): """Make the upstream CDX query for a collection and response with the results of the query :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collection this CDX query is for :return: The WbRe...
python
{ "resource": "" }
q34471
FrontEndApp.setup_paths
train
def setup_paths(self, environ, coll, record=False): """Populates the WSGI environment dictionary with the path information necessary to perform a response for content or record. :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collect...
python
{ "resource": "" }
q34472
FrontEndApp.raise_not_found
train
def raise_not_found(self, environ, msg): """Utility function for raising a werkzeug.exceptions.NotFound execption with the supplied WSGI environment and message. :param dict environ: The WSGI environment dictionary for the request :param str msg: The error message """ ra...
python
{ "resource": "" }
q34473
FrontEndApp._check_refer_redirect
train
def _check_refer_redirect(self, environ): """Returns a WbResponse for a HTTP 307 redirection if the HTTP referer header is the same as the HTTP host header :param dict environ: The WSGI environment dictionary for the request :return: WbResponse HTTP 307 redirection :rtype: WbResponse ...
python
{ "resource": "" }
q34474
FrontEndApp.handle_request
train
def handle_request(self, environ, start_response): """Retrieves the route handler and calls the handler returning its the response :param dict environ: The WSGI environment dictionary for the request :param start_response: :return: The WbResponse for the request :rtype: WbRespon...
python
{ "resource": "" }
q34475
FrontEndApp.create_app
train
def create_app(cls, port): """Create a new instance of FrontEndApp that listens on port with a hostname of 0.0.0.0 :param int port: The port FrontEndApp is to listen on :return: A new instance of FrontEndApp wrapped in GeventServer :rtype: GeventServer """ app = FrontEnd...
python
{ "resource": "" }
q34476
FrontEndApp.init_proxy
train
def init_proxy(self, config): """Initialize and start proxy mode. If proxy configuration entry is not contained in the config this is a no op. Causes handler to become an instance of WSGIProxMiddleware. :param dict config: The configuration object used to configure this instance of FrontEndApp ...
python
{ "resource": "" }
q34477
FrontEndApp.proxy_route_request
train
def proxy_route_request(self, url, environ): """ Return the full url that this proxy request will be routed to The 'environ' PATH_INFO and REQUEST_URI will be modified based on the returned url Default is to use the 'proxy_prefix' to point to the proxy collection """ if self.pro...
python
{ "resource": "" }
q34478
FrontEndApp.proxy_fetch
train
def proxy_fetch(self, env, url): """Proxy mode only endpoint that handles OPTIONS requests and COR fetches for Preservation Worker. Due to normal cross-origin browser restrictions in proxy mode, auto fetch worker cannot access the CSS rules of cross-origin style sheets and must re-fetch them in...
python
{ "resource": "" }
q34479
MetadataCache.load
train
def load(self, coll): """Load and receive the metadata associated with a collection. If the metadata for the collection is not cached yet its metadata file is read in and stored. If the cache has seen the collection before the mtime of the metadata file is checked and if it is more recent ...
python
{ "resource": "" }
q34480
MetadataCache.store_new
train
def store_new(self, coll, path, mtime): """Load a collections metadata file and store it :param str coll: The name of the collection the metadata is for :param str path: The path to the collections metadata file :param float mtime: The current mtime of the collections metadata file ...
python
{ "resource": "" }
q34481
ZipNumIndexSource.load_blocks
train
def load_blocks(self, location, blocks, ranges, query): """ Load one or more blocks of compressed cdx lines, return a line iterator which decompresses and returns one line at a time, bounded by query.key and query.end_key """ if (logging.getLogger().getEffectiveLevel() <= logging...
python
{ "resource": "" }
q34482
ArchiveIndexEntryMixin.extract_mime
train
def extract_mime(self, mime, def_mime='unk'): """ Utility function to extract mimetype only from a full content type, removing charset settings """ self['mime'] = def_mime if mime: self['mime'] = self.MIME_RE.split(mime, 1)[0] self['_content_type'] = mime
python
{ "resource": "" }
q34483
ArchiveIndexEntryMixin.extract_status
train
def extract_status(self, status_headers): """ Extract status code only from status line """ self['status'] = status_headers.get_statuscode() if not self['status']: self['status'] = '-' elif self['status'] == '204' and 'Error' in status_headers.statusline: ...
python
{ "resource": "" }
q34484
DefaultRecordParser.parse_warc_record
train
def parse_warc_record(self, record): """ Parse warc record """ entry = self._create_index_entry(record.rec_type) if record.rec_type == 'warcinfo': entry['url'] = record.rec_headers.get_header('WARC-Filename') entry['urlkey'] = entry['url'] entry['_wa...
python
{ "resource": "" }
q34485
DefaultRecordParser.parse_arc_record
train
def parse_arc_record(self, record): """ Parse arc record """ url = record.rec_headers.get_header('uri') url = url.replace('\r', '%0D') url = url.replace('\n', '%0A') # replace formfeed url = url.replace('\x0c', '%0C') # replace nulls url = url.repl...
python
{ "resource": "" }
q34486
render_field
train
def render_field(parser, token): """ Render a form field using given attribute-value pairs Takes form field as first argument and list of attribute-value pairs for all other arguments. Attribute-value pairs should be in the form of attribute=value or attribute="a value" for assignment and attribut...
python
{ "resource": "" }
q34487
TokenIntrospectionEndpoint.response
train
def response(cls, dic, status=200): """ Create and return a response object. """ response = JsonResponse(dic, status=status) response['Cache-Control'] = 'no-store' response['Pragma'] = 'no-cache' return response
python
{ "resource": "" }
q34488
ScopeClaims.create_response_dic
train
def create_response_dic(self): """ Generate the dic that will be jsonify. Checking scopes given vs registered. Returns a dic. """ dic = {} for scope in self.scopes: if scope in self._scopes_registered(): dic.update(getattr(self, 'scop...
python
{ "resource": "" }
q34489
ScopeClaims._scopes_registered
train
def _scopes_registered(self): """ Return a list that contains all the scopes registered in the class. """ scopes = [] for name in dir(self.__class__): if name.startswith('scope_'): scope = name.split('scope_')[1] scopes.append(...
python
{ "resource": "" }
q34490
ScopeClaims._clean_dic
train
def _clean_dic(self, dic): """ Clean recursively all empty or None values inside a dict. """ aux_dic = dic.copy() for key, value in iter(dic.items()): if value is None or value == '': del aux_dic[key] elif type(value) is dict: ...
python
{ "resource": "" }
q34491
AuthorizeEndpoint.set_client_user_consent
train
def set_client_user_consent(self): """ Save the user consent given to a specific client. Return None. """ date_given = timezone.now() expires_at = date_given + timedelta( days=settings.get('OIDC_SKIP_CONSENT_EXPIRE')) uc, created = UserConsent.object...
python
{ "resource": "" }
q34492
AuthorizeEndpoint.client_has_user_consent
train
def client_has_user_consent(self): """ Check if already exists user consent for some client. Return bool. """ value = False try: uc = UserConsent.objects.get(user=self.request.user, client=self.client) if (set(self.params['scope']).issubset(uc.sco...
python
{ "resource": "" }
q34493
AuthorizeEndpoint.get_scopes_information
train
def get_scopes_information(self): """ Return a list with the description of all the scopes requested. """ scopes = StandardScopeClaims.get_scopes_info(self.params['scope']) if settings.get('OIDC_EXTRA_SCOPE_CLAIMS'): scopes_extra = settings.get( 'OIDC_...
python
{ "resource": "" }
q34494
get
train
def get(name, import_str=False): """ Helper function to use inside the package. """ value = None default_value = getattr(default_settings, name) try: value = getattr(settings, name) except AttributeError: if name in default_settings.required_attrs: raise Exceptio...
python
{ "resource": "" }
q34495
DefaultSettings.OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY
train
def OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY(self): """ OPTIONAL. Supply a fixed string to use as browser-state key for unauthenticated clients. """ # Memoize generated value if not self._unauthenticated_session_management_key: self._unauthenticated_session_manage...
python
{ "resource": "" }
q34496
strip_prompt_login
train
def strip_prompt_login(path): """ Strips 'login' from the 'prompt' query parameter. """ uri = urlsplit(path) query_params = parse_qs(uri.query) prompt_list = query_params.get('prompt', '')[0].split() if 'login' in prompt_list: prompt_list.remove('login') query_params['prompt'...
python
{ "resource": "" }
q34497
get_site_url
train
def get_site_url(site_url=None, request=None): """ Construct the site url. Orders to decide site url: 1. valid `site_url` parameter 2. valid `SITE_URL` in settings 3. construct from `request` object """ site_url = site_url or settings.get('SITE_URL') if site_url: ...
python
{ "resource": "" }
q34498
get_issuer
train
def get_issuer(site_url=None, request=None): """ Construct the issuer full url. Basically is the site url with some path appended. """ site_url = get_site_url(site_url=site_url, request=request) path = reverse('oidc_provider:provider-info') \ .split('/.well-known/openid-configuration')[0...
python
{ "resource": "" }
q34499
get_browser_state_or_default
train
def get_browser_state_or_default(request): """ Determine value to use as session state. """ key = (request.session.session_key or settings.get('OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY')) return sha224(key.encode('utf-8')).hexdigest()
python
{ "resource": "" }