repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
bslatkin/dpxdt
dpxdt/server/api.py
runs_done
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
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') ...
Marks a release candidate as having all runs reported.
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L531-L562
bslatkin/dpxdt
dpxdt/server/api.py
_save_artifact
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
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...
Saves an artifact to the DB and returns it.
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L575-L592
bslatkin/dpxdt
dpxdt/server/api.py
upload
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
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...
Uploads an artifact referenced by a run.
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L598-L617
bslatkin/dpxdt
dpxdt/server/api.py
_get_artifact_response
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
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...
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.
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L620-L632
bslatkin/dpxdt
dpxdt/server/api.py
download
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
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...
Downloads an artifact by it's content hash.
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L636-L682
bslatkin/dpxdt
dpxdt/client/pdiff_worker.py
register
def register(coordinator): """Registers this module as a worker with the given coordinator.""" utils.verify_binary('pdiff_compare_binary', ['-version']) utils.verify_binary('pdiff_composite_binary', ['-version']) assert FLAGS.pdiff_threads > 0 assert FLAGS.queue_server_prefix item = queue_work...
python
def register(coordinator): """Registers this module as a worker with the given coordinator.""" utils.verify_binary('pdiff_compare_binary', ['-version']) utils.verify_binary('pdiff_composite_binary', ['-version']) assert FLAGS.pdiff_threads > 0 assert FLAGS.queue_server_prefix item = queue_work...
Registers this module as a worker with the given coordinator.
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/pdiff_worker.py#L226-L240
bslatkin/dpxdt
dpxdt/server/operations.py
BaseOps.evict
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
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. ...
Evict all caches related to these operations.
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/operations.py#L72-L78
bslatkin/dpxdt
dpxdt/server/operations.py
BuildOps.sort_run
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
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_...
Sort function for runs within a release.
https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/operations.py#L170-L177
podio/valideer
valideer/base.py
parse
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
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...
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:`Validator` subclass, instantiate it without arguments and return it. - :py:attr:`~Validator.name` of a known :py:c...
https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L60-L165
podio/valideer
valideer/base.py
parsing
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
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: ...
Context manager for overriding the default validator parsing rules for the following code block.
https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L169-L188
podio/valideer
valideer/base.py
register
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
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
Register a validator instance under the given ``name``.
https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L191-L195
podio/valideer
valideer/base.py
accepts
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
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...
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 parameter.
https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L272-L289
podio/valideer
valideer/base.py
returns
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
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...
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.
https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L292-L310
podio/valideer
valideer/base.py
adapts
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
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...
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 given parameter.
https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L313-L346
podio/valideer
valideer/validators.py
_ObjectFactory
def _ObjectFactory(obj): """Parse a python ``{name: schema}`` dict as an :py:class:`Object` instance. - A property name prepended by "+" is required - A property name prepended by "?" is optional - Any other property is required if :py:attr:`Object.REQUIRED_PROPERTIES` is True else it's optional ...
python
def _ObjectFactory(obj): """Parse a python ``{name: schema}`` dict as an :py:class:`Object` instance. - A property name prepended by "+" is required - A property name prepended by "?" is optional - Any other property is required if :py:attr:`Object.REQUIRED_PROPERTIES` is True else it's optional ...
Parse a python ``{name: schema}`` dict as an :py:class:`Object` instance. - A property name prepended by "+" is required - A property name prepended by "?" is optional - Any other property is required if :py:attr:`Object.REQUIRED_PROPERTIES` is True else it's optional
https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/validators.py#L713-L732
HumanCellAtlas/dcp-cli
hca/upload/lib/client_side_checksum_handler.py
ClientSideChecksumHandler.get_checksum_metadata_tag
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
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_...
Returns a map of checksum values by the name of the hashing function that produced it.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/client_side_checksum_handler.py#L20-L24
HumanCellAtlas/dcp-cli
hca/upload/lib/client_side_checksum_handler.py
ClientSideChecksumHandler.compute_checksum
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
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...
Calculates checksums for a given file.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/client_side_checksum_handler.py#L26-L33
HumanCellAtlas/dcp-cli
hca/upload/upload_area.py
UploadArea.get_credentials
def get_credentials(self): """ Return a set of credentials that may be used to access the Upload Area folder in the S3 bucket :return: a dict containing AWS credentials in a format suitable for passing to Boto3 or if capitalized, used as environment variables """ cred...
python
def get_credentials(self): """ Return a set of credentials that may be used to access the Upload Area folder in the S3 bucket :return: a dict containing AWS credentials in a format suitable for passing to Boto3 or if capitalized, used as environment variables """ cred...
Return a set of credentials that may be used to access the Upload Area folder in the S3 bucket :return: a dict containing AWS credentials in a format suitable for passing to Boto3 or if capitalized, used as environment variables
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L57-L70
HumanCellAtlas/dcp-cli
hca/upload/upload_area.py
UploadArea.list
def list(self, detail=False): """ A generator that yields information about each file in the upload area :param detail: return detailed file information (slower) :return: a list of dicts containing at least 'name', or more of detail was requested """ creds_provider = Cred...
python
def list(self, detail=False): """ A generator that yields information about each file in the upload area :param detail: return detailed file information (slower) :return: a list of dicts containing at least 'name', or more of detail was requested """ creds_provider = Cred...
A generator that yields information about each file in the upload area :param detail: return detailed file information (slower) :return: a list of dicts containing at least 'name', or more of detail was requested
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L72-L89
HumanCellAtlas/dcp-cli
hca/upload/upload_area.py
UploadArea.store_file
def store_file(self, filename, file_content, content_type): """ Store a small file in an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name the file will have in the Upload Area :param str file_content: The contents of the ...
python
def store_file(self, filename, file_content, content_type): """ Store a small file in an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name the file will have in the Upload Area :param str file_content: The contents of the ...
Store a small file in an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name the file will have in the Upload Area :param str file_content: The contents of the file :param str content_type: The MIME-type for the file :return...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L91-L107
HumanCellAtlas/dcp-cli
hca/upload/upload_area.py
UploadArea.upload_files
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
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._...
A function that takes in a list of file paths and other optional args for parallel file upload
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L109-L138
HumanCellAtlas/dcp-cli
hca/upload/upload_area.py
UploadArea.validate_files
def validate_files(self, file_list, validator_image, original_validation_id="", environment={}): """ Invoke supplied validator Docker image and give it access to the file/s. The validator must be based off the base validator Docker image. :param list file_list: A list of files within th...
python
def validate_files(self, file_list, validator_image, original_validation_id="", environment={}): """ Invoke supplied validator Docker image and give it access to the file/s. The validator must be based off the base validator Docker image. :param list file_list: A list of files within th...
Invoke supplied validator Docker image and give it access to the file/s. The validator must be based off the base validator Docker image. :param list file_list: A list of files within the Upload Area to be validated :param str validator_image: the location of a docker image to use for validatio...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L140-L157
HumanCellAtlas/dcp-cli
hca/upload/upload_area.py
UploadArea.checksum_status
def checksum_status(self, filename): """ Retrieve checksum status and values for a file :param str filename: The name of the file within the Upload Area :return: a dict with checksum information :rtype: dict :raises UploadApiException: if information could not be obtaine...
python
def checksum_status(self, filename): """ Retrieve checksum status and values for a file :param str filename: The name of the file within the Upload Area :return: a dict with checksum information :rtype: dict :raises UploadApiException: if information could not be obtaine...
Retrieve checksum status and values for a file :param str filename: The name of the file within the Upload Area :return: a dict with checksum information :rtype: dict :raises UploadApiException: if information could not be obtained
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L159-L168
HumanCellAtlas/dcp-cli
hca/upload/upload_area.py
UploadArea.validation_status
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
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...
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 could not be obtained
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L181-L190
HumanCellAtlas/dcp-cli
hca/cli.py
check_if_release_is_current
def check_if_release_is_current(log): """Warns the user if their release is behind the latest PyPi __version__.""" if __version__ == '0.0.0': return client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') latest_pypi_version = client.package_releases('hca') latest_version_nums = [int...
python
def check_if_release_is_current(log): """Warns the user if their release is behind the latest PyPi __version__.""" if __version__ == '0.0.0': return client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi') latest_pypi_version = client.package_releases('hca') latest_version_nums = [int...
Warns the user if their release is behind the latest PyPi __version__.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/cli.py#L61-L81
HumanCellAtlas/dcp-cli
hca/util/_docs.py
_parse_docstring
def _parse_docstring(docstring): """ Using the sphinx RSTParse to parse __doc__ for argparse `parameters`, `help`, and `description`. The first rst paragraph encountered it treated as the argparse help text. Any param fields are treated as argparse arguments. Any other text is combined and added to the ...
python
def _parse_docstring(docstring): """ Using the sphinx RSTParse to parse __doc__ for argparse `parameters`, `help`, and `description`. The first rst paragraph encountered it treated as the argparse help text. Any param fields are treated as argparse arguments. Any other text is combined and added to the ...
Using the sphinx RSTParse to parse __doc__ for argparse `parameters`, `help`, and `description`. The first rst paragraph encountered it treated as the argparse help text. Any param fields are treated as argparse arguments. Any other text is combined and added to the argparse description. example: \...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/_docs.py#L51-L98
HumanCellAtlas/dcp-cli
hca/upload/lib/s3_agent.py
sizeof_fmt
def sizeof_fmt(num, suffix='B'): """ Adapted from https://stackoverflow.com/a/1094933 Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection """ precision = {'': 0, 'Ki': 0, 'Mi': 0, 'Gi': 3, 'Ti': 6, 'Pi': 9, 'Ei': 12, 'Zi': 15} for unit in ['', 'Ki', ...
python
def sizeof_fmt(num, suffix='B'): """ Adapted from https://stackoverflow.com/a/1094933 Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection """ precision = {'': 0, 'Ki': 0, 'Mi': 0, 'Gi': 3, 'Ti': 6, 'Pi': 9, 'Ei': 12, 'Zi': 15} for unit in ['', 'Ki', ...
Adapted from https://stackoverflow.com/a/1094933 Re: precision - display enough decimals to show progress on a slow (<5 MB/s) Internet connection
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/s3_agent.py#L16-L28
HumanCellAtlas/dcp-cli
hca/upload/lib/s3_agent.py
S3Agent._item_exists_in_bucket
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
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) ...
Returns true if the key already exists in the current bucket and the clientside checksum matches the file's checksums, and false otherwise.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/s3_agent.py#L130-L141
HumanCellAtlas/dcp-cli
hca/dss/upload_to_cloud.py
upload_to_cloud
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
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...
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. :param staging_bucket: The aws bucket to upload the files to. :param replica: The cloud rep...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/upload_to_cloud.py#L53-L102
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient.download
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
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...
Download a bundle and save it to the local filesystem as a directory. :param str bundle_uuid: The uuid of the bundle to download :param str replica: the replica to download from. The supported replicas are: `aws` for Amazon Web Services, and `gcp` for Google Cloud Platform. [aws, gcp] ...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L87-L140
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient._download_to_filestore
def _download_to_filestore(self, download_dir, dss_file, num_retries=10, min_delay_seconds=0.25): """ Attempt to download the data and save it in the 'filestore' location dictated by self._file_path() """ dest_path = self._file_path(dss_file.sha256, download_dir) if os.path.exist...
python
def _download_to_filestore(self, download_dir, dss_file, num_retries=10, min_delay_seconds=0.25): """ Attempt to download the data and save it in the 'filestore' location dictated by self._file_path() """ dest_path = self._file_path(dss_file.sha256, download_dir) if os.path.exist...
Attempt to download the data and save it in the 'filestore' location dictated by self._file_path()
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L198-L209
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient._download_file
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
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...
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 for the number of failures that goes up with every successful block read and down with each failure....
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L211-L237
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient._do_download_file
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
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 ...
Abstracts away complications for downloading a file, handles retries and delays, and computes its hash
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L239-L303
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient._file_path
def _file_path(cls, checksum, download_dir): """ returns a file's relative local path based on the nesting parameters and the files hash :param checksum: a string checksum :param download_dir: root directory for filestore :return: relative Path object """ checksum...
python
def _file_path(cls, checksum, download_dir): """ returns a file's relative local path based on the nesting parameters and the files hash :param checksum: a string checksum :param download_dir: root directory for filestore :return: relative Path object """ checksum...
returns a file's relative local path based on the nesting parameters and the files hash :param checksum: a string checksum :param download_dir: root directory for filestore :return: relative Path object
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L306-L322
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient._write_output_manifest
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
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) ...
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.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L332-L350
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient.download_manifest_v2
def download_manifest_v2(self, manifest, replica, num_retries=10, min_delay_seconds=0.25, download_dir='.'): """ Process the given manifest file in TSV (tab-separated values) format and download the files referenced b...
python
def download_manifest_v2(self, manifest, replica, num_retries=10, min_delay_seconds=0.25, download_dir='.'): """ Process the given manifest file in TSV (tab-separated values) format and download the files referenced b...
Process the given manifest file in TSV (tab-separated values) format and download the files referenced by it. The files are downloaded in the version 2 format. This download format will serve as the main storage format for downloaded files. If a user specifies a different format for download (c...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L352-L405
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient.download_manifest
def download_manifest(self, manifest, replica, num_retries=10, min_delay_seconds=0.25, download_dir=''): """ Process the given manifest file in TSV (tab-separated values) format and download the files referenced by it. :param str manifest: path to a TSV (tab-separated values) file listing files...
python
def download_manifest(self, manifest, replica, num_retries=10, min_delay_seconds=0.25, download_dir=''): """ Process the given manifest file in TSV (tab-separated values) format and download the files referenced by it. :param str manifest: path to a TSV (tab-separated values) file listing files...
Process the given manifest file in TSV (tab-separated values) format and download the files referenced by it. :param str manifest: path to a TSV (tab-separated values) file listing files to download :param str replica: the replica to download from. The supported replicas are: `aws` for Amazon Web Servi...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L407-L457
HumanCellAtlas/dcp-cli
hca/dss/__init__.py
DSSClient.upload
def upload(self, src_dir, replica, staging_bucket, timeout_seconds=1200): """ Upload a directory of files from the local filesystem and create a bundle containing the uploaded files. :param str src_dir: file path to a directory of files to upload to the replica. :param str replica: the ...
python
def upload(self, src_dir, replica, staging_bucket, timeout_seconds=1200): """ Upload a directory of files from the local filesystem and create a bundle containing the uploaded files. :param str src_dir: file path to a directory of files to upload to the replica. :param str replica: the ...
Upload a directory of files from the local filesystem and create a bundle containing the uploaded files. :param str src_dir: file path to a directory of files to upload to the replica. :param str replica: the replica to upload to. The supported replicas are: `aws` for Amazon Web Services, and ...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L486-L580
HumanCellAtlas/dcp-cli
hca/dss/util/__init__.py
iter_paths
def iter_paths(src_dir): """ Function that recursively locates files within folder Note: scandir does not guarantee ordering :param src_dir: string for directory to be parsed through :return an iterable of DirEntry objects all files within the src_dir """ for x in scandir(os.path.join(src_d...
python
def iter_paths(src_dir): """ Function that recursively locates files within folder Note: scandir does not guarantee ordering :param src_dir: string for directory to be parsed through :return an iterable of DirEntry objects all files within the src_dir """ for x in scandir(os.path.join(src_d...
Function that recursively locates files within folder Note: scandir does not guarantee ordering :param src_dir: string for directory to be parsed through :return an iterable of DirEntry objects all files within the src_dir
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/util/__init__.py#L15-L27
HumanCellAtlas/dcp-cli
hca/dss/util/__init__.py
hardlink
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
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...
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
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/util/__init__.py#L40-L69
HumanCellAtlas/dcp-cli
hca/util/__init__.py
_ClientMethodFactory.request_with_retries_on_post_search
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
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 ...
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 applied to prod. In the meantime, this function will add retries specifically for POST search (and any other...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/__init__.py#L143-L174
HumanCellAtlas/dcp-cli
hca/util/__init__.py
SwaggerClient.load_swagger_json
def load_swagger_json(swagger_json, ptr_str="$ref"): """ Load the Swagger JSON and resolve {"$ref": "#/..."} internal JSON Pointer references. """ refs = [] def store_refs(d): if len(d) == 1 and ptr_str in d: refs.append(d) return d ...
python
def load_swagger_json(swagger_json, ptr_str="$ref"): """ Load the Swagger JSON and resolve {"$ref": "#/..."} internal JSON Pointer references. """ refs = [] def store_refs(d): if len(d) == 1 and ptr_str in d: refs.append(d) return d ...
Load the Swagger JSON and resolve {"$ref": "#/..."} internal JSON Pointer references.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/__init__.py#L286-L302
HumanCellAtlas/dcp-cli
hca/util/__init__.py
SwaggerClient.refresh_swagger
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
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)) ...
Manually refresh the swagger document. This can help resolve errors communicate with the API.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/__init__.py#L335-L344
HumanCellAtlas/dcp-cli
hca/util/__init__.py
SwaggerClient.login
def login(self, access_token=""): """ Configure and save {prog} authentication credentials. This command may open a browser window to ask for your consent to use web service authentication credentials. """ if access_token: credentials = argparse.Namespace(tok...
python
def login(self, access_token=""): """ Configure and save {prog} authentication credentials. This command may open a browser window to ask for your consent to use web service authentication credentials. """ if access_token: credentials = argparse.Namespace(tok...
Configure and save {prog} authentication credentials. This command may open a browser window to ask for your consent to use web service authentication credentials.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/__init__.py#L370-L393
HumanCellAtlas/dcp-cli
hca/upload/upload_config.py
UploadConfig.area_uri
def area_uri(self, area_uuid): """ Return the URI for an Upload Area :param area_uuid: UUID of area for which we want URI :return: Upload Area URI object :rtype: UploadAreaURI :raises UploadException: if area does not exist """ if area_uuid not in self.are...
python
def area_uri(self, area_uuid): """ Return the URI for an Upload Area :param area_uuid: UUID of area for which we want URI :return: Upload Area URI object :rtype: UploadAreaURI :raises UploadException: if area does not exist """ if area_uuid not in self.are...
Return the URI for an Upload Area :param area_uuid: UUID of area for which we want URI :return: Upload Area URI object :rtype: UploadAreaURI :raises UploadException: if area does not exist
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L85-L95
HumanCellAtlas/dcp-cli
hca/upload/upload_config.py
UploadConfig.add_area
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
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()
Record information about a new Upload Area :param UploadAreaURI uri: An Upload Area URI.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L97-L105
HumanCellAtlas/dcp-cli
hca/upload/upload_config.py
UploadConfig.select_area
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
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()
Update the "current area" to be the area with this UUID. :param str area_uuid: The RFC4122-compliant UUID of the Upload Area.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L107-L115
HumanCellAtlas/dcp-cli
hca/upload/upload_config.py
UploadConfig.forget_area
def forget_area(self, area_uuid): """ Remove an Upload Area from out cache of known areas. :param str area_uuid: The RFC4122-compliant UUID of the Upload Area. """ if self._config.upload.current_area == area_uuid: self._config.upload.current_area = None if are...
python
def forget_area(self, area_uuid): """ Remove an Upload Area from out cache of known areas. :param str area_uuid: The RFC4122-compliant UUID of the Upload Area. """ if self._config.upload.current_area == area_uuid: self._config.upload.current_area = None if are...
Remove an Upload Area from out cache of known areas. :param str area_uuid: The RFC4122-compliant UUID of the Upload Area.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L117-L126
HumanCellAtlas/dcp-cli
hca/upload/upload_config.py
UploadConfig.area_uuid_from_partial_uuid
def area_uuid_from_partial_uuid(self, partial_uuid): """ Given a partial UUID (a prefix), see if we have know about an Upload Area matching it. :param (str) partial_uuid: UUID prefix :return: a matching UUID :rtype: str :raises UploadException: if no or more than one UUID...
python
def area_uuid_from_partial_uuid(self, partial_uuid): """ Given a partial UUID (a prefix), see if we have know about an Upload Area matching it. :param (str) partial_uuid: UUID prefix :return: a matching UUID :rtype: str :raises UploadException: if no or more than one UUID...
Given a partial UUID (a prefix), see if we have know about an Upload Area matching it. :param (str) partial_uuid: UUID prefix :return: a matching UUID :rtype: str :raises UploadException: if no or more than one UUIDs match.
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L128-L143
HumanCellAtlas/dcp-cli
hca/upload/upload_config.py
UploadConfig.unique_prefix
def unique_prefix(self, area_uuid): """ Find the minimum prefix required to address this Upload Area UUID uniquely. :param (str) area_uuid: UUID of Upload Area :return: a string with the minimum prefix required to be unique :rtype: str """ for prefix_len in range(...
python
def unique_prefix(self, area_uuid): """ Find the minimum prefix required to address this Upload Area UUID uniquely. :param (str) area_uuid: UUID of Upload Area :return: a string with the minimum prefix required to be unique :rtype: str """ for prefix_len in range(...
Find the minimum prefix required to address this Upload Area UUID uniquely. :param (str) area_uuid: UUID of Upload Area :return: a string with the minimum prefix required to be unique :rtype: str
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L145-L156
HumanCellAtlas/dcp-cli
hca/util/fs_helper.py
FSHelper.get_days_since_last_modified
def get_days_since_last_modified(filename): """ :param filename: Absolute file path :return: Number of days since filename's last modified time """ now = datetime.now() last_modified = datetime.fromtimestamp(os.path.getmtime(filename)) return (now - last_modified)...
python
def get_days_since_last_modified(filename): """ :param filename: Absolute file path :return: Number of days since filename's last modified time """ now = datetime.now() last_modified = datetime.fromtimestamp(os.path.getmtime(filename)) return (now - last_modified)...
:param filename: Absolute file path :return: Number of days since filename's last modified time
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/fs_helper.py#L17-L24
HumanCellAtlas/dcp-cli
hca/upload/upload_service.py
UploadService.create_area
def create_area(self, area_uuid): """ Create an Upload Area :param area_uuid: UUID of Upload Area to be created :return: an Upload Area object :rtype: UploadArea """ result = self.api_client.create_area(area_uuid=area_uuid) area_uri = UploadAreaURI(uri=res...
python
def create_area(self, area_uuid): """ Create an Upload Area :param area_uuid: UUID of Upload Area to be created :return: an Upload Area object :rtype: UploadArea """ result = self.api_client.create_area(area_uuid=area_uuid) area_uri = UploadAreaURI(uri=res...
Create an Upload Area :param area_uuid: UUID of Upload Area to be created :return: an Upload Area object :rtype: UploadArea
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_service.py#L29-L38
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.create_area
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
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...
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 not created
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L35-L47
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.area_exists
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
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...
Check if an Upload Area exists :param str area_uuid: A RFC4122-compliant ID for the upload area :return: True or False :rtype: bool
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L49-L58
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.delete_area
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
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...
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
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L60-L71
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.credentials
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
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 ...
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 UploadApiException: if credentials could not be obtain...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L73-L83
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.store_file
def store_file(self, area_uuid, filename, file_content, content_type): """ Store a small file in an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name the file will have in the Upload Area :param str file_content: The conte...
python
def store_file(self, area_uuid, filename, file_content, content_type): """ Store a small file in an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name the file will have in the Upload Area :param str file_content: The conte...
Store a small file in an Upload Area :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name the file will have in the Upload Area :param str file_content: The contents of the file :param str content_type: The MIME-type for the file :return...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L87-L108
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.file_upload_notification
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
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...
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 :rtype: bool :raises UploadApiException: if file could not be stored
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L111-L124
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.files_info
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
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 ...
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 :rtype: list of dicts :raises UploadApiException...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L126-L139
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.checksum_status
def checksum_status(self, area_uuid, filename): """ Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information ...
python
def checksum_status(self, area_uuid, filename): """ Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information ...
Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information :rtype: dict :raises UploadApiException: if information coul...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L143-L156
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.validate_files
def validate_files(self, area_uuid, file_list, validator_image, original_validation_id="", environment={}): """ Invoke supplied validator Docker image and give it access to the file/s. The validator must be based off the base validator Docker image. :param str area_uuid: A RFC4122-compl...
python
def validate_files(self, area_uuid, file_list, validator_image, original_validation_id="", environment={}): """ Invoke supplied validator Docker image and give it access to the file/s. The validator must be based off the base validator Docker image. :param str area_uuid: A RFC4122-compl...
Invoke supplied validator Docker image and give it access to the file/s. The validator must be based off the base validator Docker image. :param str area_uuid: A RFC4122-compliant ID for the upload area :param list file_list: A list of files within the Upload Area to be validated :param...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L174-L197
HumanCellAtlas/dcp-cli
hca/upload/lib/api_client.py
ApiClient.validation_statuses
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
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 ...
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 :raises UploadApiException: if information could not be ob...
https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L214-L225
yoeo/guesslang
guesslang/guesser.py
Guess.language_name
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
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_...
Predict the programming language name of the given source code. :param text: source code. :return: language name
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L61-L72
yoeo/guesslang
guesslang/guesser.py
Guess.scores
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
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 ...
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
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L74-L87
yoeo/guesslang
guesslang/guesser.py
Guess.probable_languages
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
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: ...
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: maximum number of listed languages. :return: languages list
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L89-L116
yoeo/guesslang
guesslang/guesser.py
Guess.learn
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
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...
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
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L118-L164
yoeo/guesslang
tools/report_graph.py
main
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
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...
Report graph creator command line
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/report_graph.py#L25-L42
yoeo/guesslang
guesslang/utils.py
search_files
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
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 ...
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 extensions: list of file extensions :return: filenames
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L30-L52
yoeo/guesslang
guesslang/utils.py
extract_from_files
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
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...
Extract arrays of features from the given files. :param files: list of paths :param languages: language name => associated file extension list :return: features
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L55-L73
yoeo/guesslang
guesslang/utils.py
safe_read_file
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
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 ...
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
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L106-L120
yoeo/guesslang
guesslang/config.py
config_logging
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
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 = ...
Set-up application and `tensorflow` logging. :param debug: show or hide debug messages
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L53-L70
yoeo/guesslang
guesslang/config.py
config_dict
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
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: ...
Load a JSON configuration dict from Guesslang config directory. :param name: the JSON file name. :return: configuration
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L73-L85
yoeo/guesslang
guesslang/config.py
model_info
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
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...
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 default or not
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L88-L110
yoeo/guesslang
guesslang/config.py
ColorLogFormatter.format
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
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...
Format log records to produce colored messages. :param record: log record :return: log message
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L37-L50
yoeo/guesslang
tools/download_github_repo.py
main
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
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...
Github repositories downloaded command line
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/download_github_repo.py#L54-L87
yoeo/guesslang
tools/download_github_repo.py
retry
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
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...
Retry functions after failures
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/download_github_repo.py#L117-L140
yoeo/guesslang
tools/make_keywords.py
main
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
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...
Keywords generator command line
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/make_keywords.py#L29-L87
yoeo/guesslang
guesslang/__main__.py
main
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
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)
Run command line
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/__main__.py#L19-L28
yoeo/guesslang
guesslang/extractor.py
split
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
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')]
Split a text into a list of tokens. :param text: the text to split :return: tokens
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/extractor.py#L34-L40
yoeo/guesslang
tools/unzip_repos.py
main
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
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...
Files extractor command line
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/unzip_repos.py#L30-L65
innolitics/dicom-numpy
dicom_numpy/combine_slices.py
combine_slices
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
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'...
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's coordinate system. Returns a two-tuple containing the 3...
https://github.com/innolitics/dicom-numpy/blob/c870f0302276e7eaa0b66e641bacee19fe090296/dicom_numpy/combine_slices.py#L12-L74
innolitics/dicom-numpy
dicom_numpy/combine_slices.py
_validate_slices_form_uniform_grid
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
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. '''...
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.
https://github.com/innolitics/dicom-numpy/blob/c870f0302276e7eaa0b66e641bacee19fe090296/dicom_numpy/combine_slices.py#L126-L153
innolitics/dicom-numpy
dicom_numpy/combine_slices.py
_validate_image_orientation
def _validate_image_orientation(image_orientation): ''' Ensure that the image orientation is supported - The direction cosines have magnitudes of 1 (just in case) - The direction cosines are perpendicular ''' row_cosine, column_cosine, slice_cosine = _extract_cosines(image_orientation) if n...
python
def _validate_image_orientation(image_orientation): ''' Ensure that the image orientation is supported - The direction cosines have magnitudes of 1 (just in case) - The direction cosines are perpendicular ''' row_cosine, column_cosine, slice_cosine = _extract_cosines(image_orientation) if n...
Ensure that the image orientation is supported - The direction cosines have magnitudes of 1 (just in case) - The direction cosines are perpendicular
https://github.com/innolitics/dicom-numpy/blob/c870f0302276e7eaa0b66e641bacee19fe090296/dicom_numpy/combine_slices.py#L156-L177
edx/opaque-keys
opaque_keys/edx/locator.py
BlockLocatorBase.parse_url
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
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...
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 optional keys 'branch' and 'version_guid'. Raises: InvalidKeyError: if str...
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L110-L124
edx/opaque-keys
opaque_keys/edx/locator.py
CourseLocator.offering
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
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....
Deprecated. Use course and run independently.
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L234-L247
edx/opaque-keys
opaque_keys/edx/locator.py
CourseLocator._from_string
def _from_string(cls, serialized): """ Return a CourseLocator parsing the given serialized string :param serialized: matches the string to a CourseLocator """ parse = cls.parse_url(serialized) if parse['version_guid']: parse['version_guid'] = cls.as_object_id...
python
def _from_string(cls, serialized): """ Return a CourseLocator parsing the given serialized string :param serialized: matches the string to a CourseLocator """ parse = cls.parse_url(serialized) if parse['version_guid']: parse['version_guid'] = cls.as_object_id...
Return a CourseLocator parsing the given serialized string :param serialized: matches the string to a CourseLocator
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L250-L260
edx/opaque-keys
opaque_keys/edx/locator.py
CourseLocator.make_usage_key_from_deprecated_string
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
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...
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 does not parse
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L283-L297
edx/opaque-keys
opaque_keys/edx/locator.py
CourseLocator._to_deprecated_string
def _to_deprecated_string(self): """Returns an 'old-style' course id, represented as 'org/course/run'""" return u'/'.join([self.org, self.course, self.run])
python
def _to_deprecated_string(self): """Returns an 'old-style' course id, represented as 'org/course/run'""" return u'/'.join([self.org, self.course, self.run])
Returns an 'old-style' course id, represented as 'org/course/run
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L348-L350
edx/opaque-keys
opaque_keys/edx/locator.py
CourseLocator._from_deprecated_string
def _from_deprecated_string(cls, serialized): """ Return an instance of `cls` parsed from its deprecated `serialized` form. This will be called only if :meth:`OpaqueKey.from_string` is unable to parse a key out of `serialized`, and only if `set_deprecated_fallback` has been call...
python
def _from_deprecated_string(cls, serialized): """ Return an instance of `cls` parsed from its deprecated `serialized` form. This will be called only if :meth:`OpaqueKey.from_string` is unable to parse a key out of `serialized`, and only if `set_deprecated_fallback` has been call...
Return an instance of `cls` parsed from its deprecated `serialized` form. This will be called only if :meth:`OpaqueKey.from_string` is unable to parse a key out of `serialized`, and only if `set_deprecated_fallback` has been called to register a fallback class. Args: cls: T...
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L362-L381
edx/opaque-keys
opaque_keys/edx/locator.py
LibraryLocator.for_branch
def for_branch(self, branch): """ Return a new CourseLocator for another branch of the same library (also version agnostic) """ if self.org is None and branch is not None: raise InvalidKeyError(self.__class__, "Branches must have full library ids not just versions") r...
python
def for_branch(self, branch): """ Return a new CourseLocator for another branch of the same library (also version agnostic) """ if self.org is None and branch is not None: raise InvalidKeyError(self.__class__, "Branches must have full library ids not just versions") r...
Return a new CourseLocator for another branch of the same library (also version agnostic)
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L545-L551
edx/opaque-keys
opaque_keys/edx/locator.py
LibraryLocator._to_string
def _to_string(self): """ Return a string representing this location. """ parts = [] if self.library: # pylint: disable=no-member parts.extend([self.org, self.library]) # pylint: disable=no-member if self.branch: # pylint: disable=no-member ...
python
def _to_string(self): """ Return a string representing this location. """ parts = [] if self.library: # pylint: disable=no-member parts.extend([self.org, self.library]) # pylint: disable=no-member if self.branch: # pylint: disable=no-member ...
Return a string representing this location.
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L560-L571
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator._from_string
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
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 ...
Requests CourseLocator to deserialize its part and then adds the local deserialization of block
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L720-L730
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator.for_branch
def for_branch(self, branch): """ Return a UsageLocator for the same block in a different branch of the course. """ return self.replace(course_key=self.course_key.for_branch(branch))
python
def for_branch(self, branch): """ Return a UsageLocator for the same block in a different branch of the course. """ return self.replace(course_key=self.course_key.for_branch(branch))
Return a UsageLocator for the same block in a different branch of the course.
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L753-L757
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator.for_version
def for_version(self, version_guid): """ Return a UsageLocator for the same block in a different branch of the course. """ return self.replace(course_key=self.course_key.for_version(version_guid))
python
def for_version(self, version_guid): """ Return a UsageLocator for the same block in a different branch of the course. """ return self.replace(course_key=self.course_key.for_version(version_guid))
Return a UsageLocator for the same block in a different branch of the course.
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L759-L763
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator._parse_block_ref
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
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: ...
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.
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L766-L788
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator.make_relative
def make_relative(cls, course_locator, block_type, block_id): """ Return a new instance which has the given block_id in the given course :param course_locator: may be a BlockUsageLocator in the same snapshot """ if hasattr(course_locator, 'course_key'): course_locator...
python
def make_relative(cls, course_locator, block_type, block_id): """ Return a new instance which has the given block_id in the given course :param course_locator: may be a BlockUsageLocator in the same snapshot """ if hasattr(course_locator, 'course_key'): course_locator...
Return a new instance which has the given block_id in the given course :param course_locator: may be a BlockUsageLocator in the same snapshot
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L898-L908
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator._to_string
def _to_string(self): """ Return a string representing this location. """ # Allow access to _to_string protected method return u"{course_key}+{BLOCK_TYPE_PREFIX}@{block_type}+{BLOCK_PREFIX}@{block_id}".format( course_key=self.course_key._to_string(), # pylint: disabl...
python
def _to_string(self): """ Return a string representing this location. """ # Allow access to _to_string protected method return u"{course_key}+{BLOCK_TYPE_PREFIX}@{block_type}+{BLOCK_PREFIX}@{block_id}".format( course_key=self.course_key._to_string(), # pylint: disabl...
Return a string representing this location.
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L917-L928
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator.html_id
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
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...
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, but I have no way to override. We sho...
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L930-L944
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator._to_deprecated_string
def _to_deprecated_string(self): """ Returns an old-style location, represented as: i4x://org/course/category/name[@revision] # Revision is optional """ # pylint: disable=missing-format-attribute url = u"{0.DEPRECATED_TAG}://{0.course_key.org}/{0.course_key.course}/{0.bl...
python
def _to_deprecated_string(self): """ Returns an old-style location, represented as: i4x://org/course/category/name[@revision] # Revision is optional """ # pylint: disable=missing-format-attribute url = u"{0.DEPRECATED_TAG}://{0.course_key.org}/{0.course_key.course}/{0.bl...
Returns an old-style location, represented as: i4x://org/course/category/name[@revision] # Revision is optional
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L946-L955
edx/opaque-keys
opaque_keys/edx/locator.py
BlockUsageLocator._from_deprecated_string
def _from_deprecated_string(cls, serialized): """ Return an instance of `cls` parsed from its deprecated `serialized` form. This will be called only if :meth:`OpaqueKey.from_string` is unable to parse a key out of `serialized`, and only if `set_deprecated_fallback` has been call...
python
def _from_deprecated_string(cls, serialized): """ Return an instance of `cls` parsed from its deprecated `serialized` form. This will be called only if :meth:`OpaqueKey.from_string` is unable to parse a key out of `serialized`, and only if `set_deprecated_fallback` has been call...
Return an instance of `cls` parsed from its deprecated `serialized` form. This will be called only if :meth:`OpaqueKey.from_string` is unable to parse a key out of `serialized`, and only if `set_deprecated_fallback` has been called to register a fallback class. Args: cls: T...
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L967-L994