_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q233700
WorkflowThread.join
train
def join(self): """Joins the coordinator thread and all worker threads.""" for thread in self.worker_threads: thread.join() WorkerThread.join(self)
python
{ "resource": "" }
q233701
WorkflowThread.wait_one
train
def wait_one(self): """Waits until this worker has finished one work item or died.""" while True: try: item = self.output_queue.get(True, self.polltime) except Queue.Empty: continue except KeyboardInterrupt: LOGGER.debug...
python
{ "resource": "" }
q233702
superuser_required
train
def superuser_required(f): """Requires the requestor to be a super user.""" @functools.wraps(f) @login_required def wrapped(*args, **kwargs): if not (current_user.is_authenticated() and current_user.superuser): abort(403) return f(*args, **kwargs) return wrapped
python
{ "resource": "" }
q233703
can_user_access_build
train
def can_user_access_build(param_name): """Determines if the current user can access the build ID in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: The build the user has access to. ...
python
{ "resource": "" }
q233704
build_access_required
train
def build_access_required(function_or_param_name): """Decorator ensures user has access to the build ID in the request. May be used in two ways: @build_access_required def my_func(build): ... @build_access_required('custom_build_id_param') def my_func(build): ...
python
{ "resource": "" }
q233705
_get_api_key_ops
train
def _get_api_key_ops(): """Gets the operations.ApiKeyOps instance for the current request.""" auth_header = request.authorization if not auth_header: logging.debug('API request lacks authorization header') abort(flask.Response( 'API key required', 401, {'WWW-Authentic...
python
{ "resource": "" }
q233706
current_api_key
train
def current_api_key(): """Determines the API key for the current request. Returns: The ApiKey instance. """ if app.config.get('IGNORE_AUTH'): return models.ApiKey( id='anonymous_superuser', secret='', superuser=True) ops = _get_api_key_ops() ...
python
{ "resource": "" }
q233707
can_api_key_access_build
train
def can_api_key_access_build(param_name): """Determines if the current API key can access the build in the request. Args: param_name: Parameter name to use for getting the build ID from the request. Will fetch from GET or POST requests. Returns: (api_key, build) The API Key and...
python
{ "resource": "" }
q233708
build_api_access_required
train
def build_api_access_required(f): """Decorator ensures API key has access to the build ID in the request. Always calls the given function with the models.Build entity as the first positional argument. """ @functools.wraps(f) def wrapped(*args, **kwargs): g.api_key, g.build = can_api_key...
python
{ "resource": "" }
q233709
superuser_api_key_required
train
def superuser_api_key_required(f): """Decorator ensures only superuser API keys can request this function.""" @functools.wraps(f) def wrapped(*args, **kwargs): api_key = current_api_key() g.api_key = api_key utils.jsonify_assert( api_key.superuser, 'API key=%...
python
{ "resource": "" }
q233710
manage_api_keys
train
def manage_api_keys(): """Page for viewing and creating API keys.""" build = g.build create_form = forms.CreateApiKeyForm() if create_form.validate_on_submit(): api_key = models.ApiKey() create_form.populate_obj(api_key) api_key.id = utils.human_uuid() api_key.secret = ut...
python
{ "resource": "" }
q233711
revoke_api_key
train
def revoke_api_key(): """Form submission handler for revoking API keys.""" build = g.build form = forms.RevokeApiKeyForm() if form.validate_on_submit(): api_key = models.ApiKey.query.get(form.id.data) if api_key.build_id != build.id: logging.debug('User does not have access t...
python
{ "resource": "" }
q233712
claim_invitations
train
def claim_invitations(user): """Claims any pending invitations for the given user's email address.""" # See if there are any build invitations present for the user with this # email address. If so, replace all those invitations with the real user. invitation_user_id = '%s:%s' % ( models.User.EMA...
python
{ "resource": "" }
q233713
manage_admins
train
def manage_admins(): """Page for viewing and managing build admins.""" build = g.build # Do not show cached data db.session.add(build) db.session.refresh(build) add_form = forms.AddAdminForm() if add_form.validate_on_submit(): invitation_user_id = '%s:%s' % ( models.Us...
python
{ "resource": "" }
q233714
revoke_admin
train
def revoke_admin(): """Form submission handler for revoking admin access to a build.""" build = g.build form = forms.RemoveAdminForm() if form.validate_on_submit(): user = models.User.query.get(form.user_id.data) if not user: logging.debug('User being revoked admin access doe...
python
{ "resource": "" }
q233715
save_admin_log
train
def save_admin_log(build, **kwargs): """Saves an action to the admin log.""" message = kwargs.pop('message', None) release = kwargs.pop('release', None) run = kwargs.pop('run', None) if not len(kwargs) == 1: raise TypeError('Must specify a LOG_TYPE argument') log_enum = kwargs.keys()[0...
python
{ "resource": "" }
q233716
view_admin_log
train
def view_admin_log(): """Page for viewing the log of admin activity.""" build = g.build # TODO: Add paging log_list = ( models.AdminLog.query .filter_by(build_id=build.id) .order_by(models.AdminLog.created.desc()) .all()) return render_template( 'view_admin...
python
{ "resource": "" }
q233717
verify_binary
train
def verify_binary(flag_name, process_args=None): """Exits the program if the binary from the given flag doesn't run. Args: flag_name: Name of the flag that should be the path to the binary. process_args: Args to pass to the binary to do nothing but verify that it's working correctly...
python
{ "resource": "" }
q233718
create_release
train
def create_release(): """Creates a new release candidate for a build.""" build = g.build release_name = request.form.get('release_name') utils.jsonify_assert(release_name, 'release_name required') url = request.form.get('url') utils.jsonify_assert(release_name, 'url required') release = mod...
python
{ "resource": "" }
q233719
_check_release_done_processing
train
def _check_release_done_processing(release): """Moves a release candidate to reviewing if all runs are done.""" if release.status != models.Release.PROCESSING: # NOTE: This statement also guards for situations where the user has # prematurely specified that the release is good or bad. Once the u...
python
{ "resource": "" }
q233720
_get_release_params
train
def _get_release_params(): """Gets the release params from the current request.""" release_name = request.form.get('release_name') utils.jsonify_assert(release_name, 'release_name required') release_number = request.form.get('release_number', type=int) utils.jsonify_assert(release_number is not None...
python
{ "resource": "" }
q233721
_find_last_good_run
train
def _find_last_good_run(build): """Finds the last good release and run for a build.""" run_name = request.form.get('run_name', type=str) utils.jsonify_assert(run_name, 'run_name required') last_good_release = ( models.Release.query .filter_by( build_id=build.id, ...
python
{ "resource": "" }
q233722
find_run
train
def find_run(): """Finds the last good run of the given name for a release.""" build = g.build last_good_release, last_good_run = _find_last_good_run(build) if last_good_run: return flask.jsonify( success=True, build_id=build.id, release_name=last_good_releas...
python
{ "resource": "" }
q233723
_get_or_create_run
train
def _get_or_create_run(build): """Gets a run for a build or creates it if it does not exist.""" release_name, release_number = _get_release_params() run_name = request.form.get('run_name', type=str) utils.jsonify_assert(run_name, 'run_name required') release = ( models.Release.query ...
python
{ "resource": "" }
q233724
_enqueue_capture
train
def _enqueue_capture(build, release, run, url, config_data, baseline=False): """Enqueues a task to run a capture process.""" # Validate the JSON config parses. try: config_dict = json.loads(config_data) except Exception, e: abort(utils.jsonify_error(e)) # Rewrite the config JSON to ...
python
{ "resource": "" }
q233725
request_run
train
def request_run(): """Requests a new run for a release candidate.""" build = g.build current_release, current_run = _get_or_create_run(build) current_url = request.form.get('url', type=str) config_data = request.form.get('config', default='{}', type=str) utils.jsonify_assert(current_url, 'url t...
python
{ "resource": "" }
q233726
runs_done
train
def runs_done(): """Marks a release candidate as having all runs reported.""" build = g.build release_name, release_number = _get_release_params() release = ( models.Release.query .filter_by(build_id=build.id, name=release_name, number=release_number) .with_lockmode('update') ...
python
{ "resource": "" }
q233727
_save_artifact
train
def _save_artifact(build, data, content_type): """Saves an artifact to the DB and returns it.""" sha1sum = hashlib.sha1(data).hexdigest() artifact = models.Artifact.query.filter_by(id=sha1sum).first() if artifact: logging.debug('Upload already exists: artifact_id=%r', sha1sum) else: log...
python
{ "resource": "" }
q233728
upload
train
def upload(): """Uploads an artifact referenced by a run.""" build = g.build utils.jsonify_assert(len(request.files) == 1, 'Need exactly one uploaded file') file_storage = request.files.values()[0] data = file_storage.read() content_type, _ = mimetypes.guess_type(file_s...
python
{ "resource": "" }
q233729
_get_artifact_response
train
def _get_artifact_response(artifact): """Gets the response object for the given artifact. This method may be overridden in environments that have a different way of storing artifact files, such as on-disk or S3. """ response = flask.Response( artifact.data, mimetype=artifact.content...
python
{ "resource": "" }
q233730
download
train
def download(): """Downloads an artifact by it's content hash.""" # Allow users with access to the build to download the file. Falls back # to API keys with access to the build. Prefer user first for speed. try: build = auth.can_user_access_build('build_id') except HTTPException: log...
python
{ "resource": "" }
q233731
BaseOps.evict
train
def evict(self): """Evict all caches related to these operations.""" logging.debug('Evicting cache for %r', self.cache_key) _clear_version_cache(self.cache_key) # Cause the cache key to be refreshed next time any operation is # run to make sure we don't act on old cached data. ...
python
{ "resource": "" }
q233732
BuildOps.sort_run
train
def sort_run(run): """Sort function for runs within a release.""" # Sort errors first, then by name. Also show errors that were manually # approved, so the paging sort order stays the same even after users # approve a diff on the run page. if run.status in models.Run.DIFF_NEEDED_...
python
{ "resource": "" }
q233733
parse
train
def parse(obj, required_properties=None, additional_properties=None, ignore_optional_property_errors=None): """Try to parse the given ``obj`` as a validator instance. :param obj: The object to be parsed. If it is a...: - :py:class:`Validator` instance, return it. - :py:class:`Validat...
python
{ "resource": "" }
q233734
parsing
train
def parsing(**kwargs): """ Context manager for overriding the default validator parsing rules for the following code block. """ from .validators import Object with _VALIDATOR_FACTORIES_LOCK: old_values = {} for key, value in iteritems(kwargs): if value is not None: ...
python
{ "resource": "" }
q233735
register
train
def register(name, validator): """Register a validator instance under the given ``name``.""" if not isinstance(validator, Validator): raise TypeError("Validator instance expected, %s given" % validator.__class__) _NAMED_VALIDATORS[name] = validator
python
{ "resource": "" }
q233736
accepts
train
def accepts(**schemas): """Create a decorator for validating function parameters. Example:: @accepts(a="number", body={"+field_ids": [int], "is_ok": bool}) def f(a, body): print (a, body["field_ids"], body.get("is_ok")) :param schemas: The schema for validating a given paramet...
python
{ "resource": "" }
q233737
returns
train
def returns(schema): """Create a decorator for validating function return value. Example:: @accepts(a=int, b=int) @returns(int) def f(a, b): return a + b :param schema: The schema for adapting a given parameter. """ validate = parse(schema).validate @decora...
python
{ "resource": "" }
q233738
adapts
train
def adapts(**schemas): """Create a decorator for validating and adapting function parameters. Example:: @adapts(a="number", body={"+field_ids": [V.AdaptTo(int)], "is_ok": bool}) def f(a, body): print (a, body.field_ids, body.is_ok) :param schemas: The schema for adapting a giv...
python
{ "resource": "" }
q233739
ClientSideChecksumHandler.get_checksum_metadata_tag
train
def get_checksum_metadata_tag(self): """ Returns a map of checksum values by the name of the hashing function that produced it.""" if not self._checksums: print("Warning: No checksums have been computed for this file.") return {str(_hash_name): str(_hash_value) for _hash_name, _hash_...
python
{ "resource": "" }
q233740
ClientSideChecksumHandler.compute_checksum
train
def compute_checksum(self): """ Calculates checksums for a given file. """ if self._filename.startswith("s3://"): print("Warning: Did not perform client-side checksumming for file in S3. To be implemented.") pass else: checksumCalculator = self.ChecksumCalcula...
python
{ "resource": "" }
q233741
UploadArea.upload_files
train
def upload_files(self, file_paths, file_size_sum=0, dcp_type="data", target_filename=None, use_transfer_acceleration=True, report_progress=False, sync=True): """ A function that takes in a list of file paths and other optional args for parallel file upload """ self._...
python
{ "resource": "" }
q233742
UploadArea.validation_status
train
def validation_status(self, filename): """ Get status and results of latest validation job for a file. :param str filename: The name of the file within the Upload Area :return: a dict with validation information :rtype: dict :raises UploadApiException: if information cou...
python
{ "resource": "" }
q233743
S3Agent._item_exists_in_bucket
train
def _item_exists_in_bucket(self, bucket, key, checksums): """ Returns true if the key already exists in the current bucket and the clientside checksum matches the file's checksums, and false otherwise.""" try: obj = self.target_s3.meta.client.head_object(Bucket=bucket, Key=key) ...
python
{ "resource": "" }
q233744
upload_to_cloud
train
def upload_to_cloud(file_handles, staging_bucket, replica, from_cloud=False): """ Upload files to cloud. :param file_handles: If from_cloud, file_handles is a aws s3 directory path to files with appropriate metadata uploaded. Else, a list of binary file_handles to upload. :para...
python
{ "resource": "" }
q233745
DSSClient.download
train
def download(self, bundle_uuid, replica, version="", download_dir="", metadata_files=('*',), data_files=('*',), num_retries=10, min_delay_seconds=0.25): """ Download a bundle and save it to the local filesystem as a directory. :param str bundle_uuid: The uuid o...
python
{ "resource": "" }
q233746
DSSClient._download_file
train
def _download_file(self, dss_file, dest_path, num_retries=10, min_delay_seconds=0.25): """ Attempt to download the data. If a retryable exception occurs, we wait a bit and retry again. The delay increases each time we fail and decreases each time we successfully read a block. We set a quota f...
python
{ "resource": "" }
q233747
DSSClient._do_download_file
train
def _do_download_file(self, dss_file, fh, num_retries, min_delay_seconds): """ Abstracts away complications for downloading a file, handles retries and delays, and computes its hash """ hasher = hashlib.sha256() delay = min_delay_seconds retries_left = num_retries ...
python
{ "resource": "" }
q233748
DSSClient._write_output_manifest
train
def _write_output_manifest(self, manifest, filestore_root): """ Adds the file path column to the manifest and writes the copy to the current directory. If the original manifest is in the current directory it is overwritten with a warning. """ output = os.path.basename(manifest) ...
python
{ "resource": "" }
q233749
hardlink
train
def hardlink(source, link_name): """ Create a hardlink in a portable way The code for Windows support is adapted from: https://github.com/sunshowers/ntfs/blob/master/ntfsutils/hardlink.py """ if sys.version_info < (3,) and platform.system() == 'Windows': # pragma: no cover import ctype...
python
{ "resource": "" }
q233750
_ClientMethodFactory.request_with_retries_on_post_search
train
def request_with_retries_on_post_search(self, session, url, query, json_input, stream, headers): """ Submit a request and retry POST search requests specifically. We don't currently retry on POST requests, and this is intended as a temporary fix until the swagger is updated and changes ...
python
{ "resource": "" }
q233751
SwaggerClient.refresh_swagger
train
def refresh_swagger(self): """ Manually refresh the swagger document. This can help resolve errors communicate with the API. """ try: os.remove(self._get_swagger_filename(self.swagger_url)) except EnvironmentError as e: logger.warn(os.strerror(e.errno)) ...
python
{ "resource": "" }
q233752
UploadConfig.add_area
train
def add_area(self, uri): """ Record information about a new Upload Area :param UploadAreaURI uri: An Upload Area URI. """ if uri.area_uuid not in self._config.upload.areas: self._config.upload.areas[uri.area_uuid] = {'uri': uri.uri} self.save()
python
{ "resource": "" }
q233753
UploadConfig.select_area
train
def select_area(self, area_uuid): """ Update the "current area" to be the area with this UUID. :param str area_uuid: The RFC4122-compliant UUID of the Upload Area. """ self._config.upload.current_area = area_uuid self.save()
python
{ "resource": "" }
q233754
ApiClient.create_area
train
def create_area(self, area_uuid): """ Create an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :return: a dict of the form { "uri": "s3://<bucket_name>/<upload-area-id>/" } :rtype: dict :raises UploadApiException: if the an Upload Area was n...
python
{ "resource": "" }
q233755
ApiClient.area_exists
train
def area_exists(self, area_uuid): """ Check if an Upload Area exists :param str area_uuid: A RFC4122-compliant ID for the upload area :return: True or False :rtype: bool """ response = requests.head(self._url(path="/area/{id}".format(id=area_uuid))) retur...
python
{ "resource": "" }
q233756
ApiClient.delete_area
train
def delete_area(self, area_uuid): """ Delete an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :return: True :rtype: bool :raises UploadApiException: if the an Upload Area was not deleted """ self._make_request('delete', path...
python
{ "resource": "" }
q233757
ApiClient.credentials
train
def credentials(self, area_uuid): """ Get AWS credentials required to directly upload files to Upload Area in S3 :param str area_uuid: A RFC4122-compliant ID for the upload area :return: a dict containing an AWS AccessKey, SecretKey and SessionToken :rtype: dict :raises ...
python
{ "resource": "" }
q233758
ApiClient.file_upload_notification
train
def file_upload_notification(self, area_uuid, filename): """ Notify Upload Service that a file has been placed in an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name the file in the Upload Area :return: True :rtyp...
python
{ "resource": "" }
q233759
ApiClient.files_info
train
def files_info(self, area_uuid, file_list): """ Get information about files :param str area_uuid: A RFC4122-compliant ID for the upload area :param list file_list: The names the files in the Upload Area about which we want information :return: an array of file information dicts ...
python
{ "resource": "" }
q233760
ApiClient.validation_statuses
train
def validation_statuses(self, area_uuid): """ Get count of validation statuses for all files in upload_area :param str area_uuid: A RFC4122-compliant ID for the upload area :return: a dict with key for each state and value being the count of files in that state :rtype: dict ...
python
{ "resource": "" }
q233761
Guess.language_name
train
def language_name(self, text: str) -> str: """Predict the programming language name of the given source code. :param text: source code. :return: language name """ values = extract(text) input_fn = _to_func(([values], [])) pos: int = next(self._classifier.predict_...
python
{ "resource": "" }
q233762
Guess.scores
train
def scores(self, text: str) -> Dict[str, float]: """A score for each language corresponding to the probability that the text is written in the given language. The score is a `float` value between 0.0 and 1.0 :param text: source code. :return: language to score dictionary ...
python
{ "resource": "" }
q233763
Guess.probable_languages
train
def probable_languages( self, text: str, max_languages: int = 3) -> Tuple[str, ...]: """List of most probable programming languages, the list is ordered from the most probable to the least probable one. :param text: source code. :param max_languages: ...
python
{ "resource": "" }
q233764
Guess.learn
train
def learn(self, input_dir: str) -> float: """Learn languages features from source files. :raise GuesslangError: when the default model is used for learning :param input_dir: source code files directory. :return: learning accuracy """ if self.is_default: LOGGE...
python
{ "resource": "" }
q233765
main
train
def main(): """Report graph creator command line""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( 'reportfile', type=argparse.FileType('r'), help="test report file generated by `guesslang --test TESTDIR`") parser.add_argument( '-d', '--debug', defaul...
python
{ "resource": "" }
q233766
search_files
train
def search_files(source: str, extensions: List[str]) -> List[Path]: """Retrieve files located the source directory and its subdirectories, whose extension match one of the listed extensions. :raise GuesslangError: when there is not enough files in the directory :param source: directory name :param ...
python
{ "resource": "" }
q233767
extract_from_files
train
def extract_from_files( files: List[Path], languages: Dict[str, List[str]]) -> DataSet: """Extract arrays of features from the given files. :param files: list of paths :param languages: language name => associated file extension list :return: features """ enumerator = en...
python
{ "resource": "" }
q233768
safe_read_file
train
def safe_read_file(file_path: Path) -> str: """Read a text file. Several text encodings are tried until the file content is correctly decoded. :raise GuesslangError: when the file encoding is not supported :param file_path: path to the input file :return: text file content """ for encoding ...
python
{ "resource": "" }
q233769
config_logging
train
def config_logging(debug: bool = False) -> None: """Set-up application and `tensorflow` logging. :param debug: show or hide debug messages """ if debug: level = 'DEBUG' tf_level = tf.logging.INFO else: level = 'INFO' tf_level = tf.logging.ERROR logging_config = ...
python
{ "resource": "" }
q233770
config_dict
train
def config_dict(name: str) -> Dict[str, Any]: """Load a JSON configuration dict from Guesslang config directory. :param name: the JSON file name. :return: configuration """ try: content = resource_string(PACKAGE, DATADIR.format(name)).decode() except DistributionNotFound as error: ...
python
{ "resource": "" }
q233771
model_info
train
def model_info(model_dir: Optional[str] = None) -> Tuple[str, bool]: """Retrieve Guesslang model directory name, and tells if it is the default model. :param model_dir: model location, if `None` default model is selected :return: selected model directory with an indication that the model is the...
python
{ "resource": "" }
q233772
ColorLogFormatter.format
train
def format(self, record: logging.LogRecord) -> str: """Format log records to produce colored messages. :param record: log record :return: log message """ if platform.system() != 'Linux': # Avoid funny logs on Windows & MacOS return super().format(record) re...
python
{ "resource": "" }
q233773
main
train
def main(): """Github repositories downloaded command line""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( 'githubtoken', help="Github OAuth token, see https://developer.github.com/v3/oauth/") parser.add_argument('destination', help="location of the downloa...
python
{ "resource": "" }
q233774
retry
train
def retry(default=None): """Retry functions after failures""" def decorator(func): """Retry decorator""" @functools.wraps(func) def _wrapper(*args, **kw): for pos in range(1, MAX_RETRIES): try: return func(*args, **kw) exc...
python
{ "resource": "" }
q233775
main
train
def main(): """Keywords generator command line""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('learn', help="learning source codes directory") parser.add_argument('keywords', help="output keywords file, JSON") parser.add_argument( '-n', '--nbkeywords', type=int...
python
{ "resource": "" }
q233776
main
train
def main() -> None: """Run command line""" try: _real_main() except GuesslangError as error: LOGGER.critical("Failed: %s", error) sys.exit(-1) except KeyboardInterrupt: LOGGER.critical("Cancelled!") sys.exit(-2)
python
{ "resource": "" }
q233777
split
train
def split(text: str) -> List[str]: """Split a text into a list of tokens. :param text: the text to split :return: tokens """ return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
python
{ "resource": "" }
q233778
main
train
def main(): """Files extractor command line""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('source', help="location of the downloaded repos") parser.add_argument('destination', help="location of the ext...
python
{ "resource": "" }
q233779
combine_slices
train
def combine_slices(slice_datasets, rescale=None): ''' Given a list of pydicom datasets for an image series, stitch them together into a three-dimensional numpy array. Also calculate a 4x4 affine transformation matrix that converts the ijk-pixel-indices into the xyz-coordinates in the DICOM patient'...
python
{ "resource": "" }
q233780
_validate_slices_form_uniform_grid
train
def _validate_slices_form_uniform_grid(slice_datasets): ''' Perform various data checks to ensure that the list of slices form a evenly-spaced grid of data. Some of these checks are probably not required if the data follows the DICOM specification, however it seems pertinent to check anyway. '''...
python
{ "resource": "" }
q233781
BlockLocatorBase.parse_url
train
def parse_url(cls, string): # pylint: disable=redefined-outer-name """ If it can be parsed as a version_guid with no preceding org + offering, returns a dict with key 'version_guid' and the value, If it can be parsed as a org + offering, returns a dict with key 'id' and optiona...
python
{ "resource": "" }
q233782
CourseLocator.offering
train
def offering(self): """ Deprecated. Use course and run independently. """ warnings.warn( "Offering is no longer a supported property of Locator. Please use the course and run properties.", DeprecationWarning, stacklevel=2 ) if not self....
python
{ "resource": "" }
q233783
CourseLocator.make_usage_key_from_deprecated_string
train
def make_usage_key_from_deprecated_string(self, location_url): """ Deprecated mechanism for creating a UsageKey given a CourseKey and a serialized Location. NOTE: this prejudicially takes the tag, org, and course from the url not self. Raises: InvalidKeyError: if the url do...
python
{ "resource": "" }
q233784
BlockUsageLocator._from_string
train
def _from_string(cls, serialized): """ Requests CourseLocator to deserialize its part and then adds the local deserialization of block """ # Allow access to _from_string protected method course_key = CourseLocator._from_string(serialized) # pylint: disable=protected-access ...
python
{ "resource": "" }
q233785
BlockUsageLocator._parse_block_ref
train
def _parse_block_ref(cls, block_ref, deprecated=False): """ Given `block_ref`, tries to parse it into a valid block reference. Returns `block_ref` if it is valid. Raises: InvalidKeyError: if `block_ref` is invalid. """ if deprecated and block_ref is None: ...
python
{ "resource": "" }
q233786
BlockUsageLocator.html_id
train
def html_id(self): """ Return an id which can be used on an html page as an id attr of an html element. It is currently also persisted by some clients to identify blocks. To make compatible with old Location object functionality. I don't believe this behavior fits at this place...
python
{ "resource": "" }
q233787
BlockUsageLocator.to_deprecated_son
train
def to_deprecated_son(self, prefix='', tag='i4x'): """ Returns a SON object that represents this location """ # This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'), # because that format was used to store data historically in mongo # ...
python
{ "resource": "" }
q233788
BlockUsageLocator._from_deprecated_son
train
def _from_deprecated_son(cls, id_dict, run): """ Return the Location decoding this id_dict and run """ course_key = CourseLocator( id_dict['org'], id_dict['course'], run, id_dict['revision'], deprecated=True, ) r...
python
{ "resource": "" }
q233789
LibraryUsageLocator._from_string
train
def _from_string(cls, serialized): """ Requests LibraryLocator to deserialize its part and then adds the local deserialization of block """ # Allow access to _from_string protected method library_key = LibraryLocator._from_string(serialized) # pylint: disable=protected-access ...
python
{ "resource": "" }
q233790
LibraryUsageLocator.for_branch
train
def for_branch(self, branch): """ Return a UsageLocator for the same block in a different branch of the library. """ return self.replace(library_key=self.library_key.for_branch(branch))
python
{ "resource": "" }
q233791
LibraryUsageLocator.for_version
train
def for_version(self, version_guid): """ Return a UsageLocator for the same block in a different version of the library. """ return self.replace(library_key=self.library_key.for_version(version_guid))
python
{ "resource": "" }
q233792
_strip_object
train
def _strip_object(key): """ Strips branch and version info if the given key supports those attributes. """ if hasattr(key, 'version_agnostic') and hasattr(key, 'for_branch'): return key.for_branch(None).version_agnostic() else: return key
python
{ "resource": "" }
q233793
_strip_value
train
def _strip_value(value, lookup='exact'): """ Helper function to remove the branch and version information from the given value, which could be a single object or a list. """ if lookup == 'in': stripped_value = [_strip_object(el) for el in value] else: stripped_value = _strip_obje...
python
{ "resource": "" }
q233794
LocationBase._deprecation_warning
train
def _deprecation_warning(cls): """Display a deprecation warning for the given cls""" if issubclass(cls, Location): warnings.warn( "Location is deprecated! Please use locator.BlockUsageLocator", DeprecationWarning, stacklevel=3 ) ...
python
{ "resource": "" }
q233795
LocationBase._check_location_part
train
def _check_location_part(cls, val, regexp): """Deprecated. See CourseLocator._check_location_part""" cls._deprecation_warning() return CourseLocator._check_location_part(val, regexp)
python
{ "resource": "" }
q233796
LocationBase._clean
train
def _clean(cls, value, invalid): """Deprecated. See BlockUsageLocator._clean""" cls._deprecation_warning() return BlockUsageLocator._clean(value, invalid)
python
{ "resource": "" }
q233797
_join_keys_v1
train
def _join_keys_v1(left, right): """ Join two keys into a format separable by using _split_keys_v1. """ if left.endswith(':') or '::' in left: raise ValueError("Can't join a left string ending in ':' or containing '::'") return u"{}::{}".format(_encode_v1(left), _encode_v1(right))
python
{ "resource": "" }
q233798
_split_keys_v1
train
def _split_keys_v1(joined): """ Split two keys out a string created by _join_keys_v1. """ left, _, right = joined.partition('::') return _decode_v1(left), _decode_v1(right)
python
{ "resource": "" }
q233799
_split_keys_v2
train
def _split_keys_v2(joined): """ Split two keys out a string created by _join_keys_v2. """ left, _, right = joined.rpartition('::') return _decode_v2(left), _decode_v2(right)
python
{ "resource": "" }