docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Resolve the given credential request in the provided mapping definition.
The result is printed automatically.
Args:
request:
The credential request specified as a dict of key-value pairs.
mapping:
The mapping configuration as a ConfigParser instance. | def get_password(request, mapping) -> None:
LOGGER.debug('Received request "%s"', request)
if 'host' not in request:
LOGGER.error('host= entry missing in request. '
'Cannot query without a host')
return
host = request['host']
if 'path' in request:
host ... | 463,936 |
Start the pass-git-helper script.
Args:
argv:
If not ``None``, use the provided command line arguments for
parsing. Otherwise, extract them automatically. | def main(argv: Optional[Sequence[str]] = None) -> None:
args = parse_arguments(argv=argv)
if args.logging:
logging.basicConfig(level=logging.DEBUG)
handle_skip()
action = args.action
request = parse_request()
LOGGER.debug('Received action %s with request:\n%s',
a... | 463,937 |
Create a new instance.
Args:
prefix_length:
Amount of characters to skip at the beginning of the entry | def __init__(self, prefix_length: int, option_suffix: Text = '') -> None:
super().__init__(option_suffix)
self._prefix_length = prefix_length | 463,938 |
Create a new instance.
Args:
line:
the line to extract, counting from zero
prefix_length:
Amount of characters to skip at the beginning of the line
option_suffix:
Suffix for each configuration option | def __init__(self,
line: int, prefix_length: int,
option_suffix: Text = '') -> None:
super().__init__(prefix_length, option_suffix)
self._line = line | 463,941 |
Create a new instance.
Args:
regex:
The regular expression describing the entry line to match. The
first matching line is selected. The expression must contain a
single capture group that contains the data to return.
option_suffix:
... | def __init__(self, regex: str, option_suffix: str):
super().__init__(option_suffix)
self._regex = self._build_matcher(regex) | 463,944 |
Returns a list of Commit objects.
Args:
since_sha - (optional) A sha to search from | def get_commits(self, since_sha=None):
assert self.tempdir
cmd = ['git', 'log', '--first-parent', '--reverse', COMMIT_FORMAT]
if since_sha:
commits = [self.get_commit(since_sha)]
cmd.append('{}..HEAD'.format(since_sha))
else:
commits = []
... | 464,052 |
Returns a set of classes in the directory matched by cls_match_func
Args:
path - A Python package
cls_match_func - Function taking a class and returning true if the
class is to be included in the output. | def discover(package, cls_match_func):
matched_classes = set()
for _, module_name, _ in pkgutil.walk_packages(
package.__path__,
prefix=package.__name__ + '.',
):
module = __import__(module_name, fromlist=[str('__trash')], level=0)
# Check all the classes in th... | 464,070 |
Yields an iterator in chunks
For example you can do
for a, b in chunk_iter([1, 2, 3, 4, 5, 6], 2):
print('{} {}'.format(a, b))
# Prints
# 1 2
# 3 4
# 5 6
Args:
iterable - Some iterable
n - Chunk size (must be greater than 0) | def chunk_iter(iterable, n):
assert n > 0
iterable = iter(iterable)
chunk = tuple(itertools.islice(iterable, n))
while chunk:
yield chunk
chunk = tuple(itertools.islice(iterable, n)) | 464,073 |
Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
A metric package must be imported using import a.b.c
include_d... | def get_metric_parsers(metric_packages=tuple(), include_defaults=True):
metric_parsers = set()
if include_defaults:
import git_code_debt.metrics
metric_parsers.update(discover(git_code_debt.metrics, is_metric_cls))
for metric_package in metric_packages:
metric_parsers.update(d... | 464,075 |
Sys.out replacer, by default with stderr.
Use it like this:
with replace_print_with(fileobj):
print "hello" # writes to the file
print "done" # prints to stdout
Args:
fileobj: a file object to replace stdout.
Yields:
The printer. | def replace_print(fileobj=sys.stderr):
printer = _Printer(fileobj)
previous_stdout = sys.stdout
sys.stdout = printer
try:
yield printer
finally:
sys.stdout = previous_stdout | 464,325 |
Compact a list of integers into a comma-separated string of intervals.
Args:
value_list: A list of sortable integers such as a list of numbers
Returns:
A compact string representation, such as "1-5,8,12-15" | def compact_interval_string(value_list):
if not value_list:
return ''
value_list.sort()
# Start by simply building up a list of separate contiguous intervals
interval_list = []
curr = []
for val in value_list:
if curr and (val > curr[-1] + 1):
interval_list.append((curr[0], curr[-1]))
... | 464,326 |
Load context from a text file in gcs.
Args:
gcs_file_path: The target file path; should have the 'gs://' prefix.
credentials: Optional credential to be used to load the file from gcs.
Returns:
The content of the text file as a string. | def _load_file_from_gcs(gcs_file_path, credentials=None):
gcs_service = _get_storage_service(credentials)
bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1)
request = gcs_service.objects().get_media(
bucket=bucket_name, object=object_name)
file_handle = io.BytesIO()
downloader = ... | 464,329 |
Load a file from either local or gcs.
Args:
file_path: The target file path, which should have the prefix 'gs://' if
to be loaded from gcs.
credentials: Optional credential to be used to load the file from gcs.
Returns:
A python File object if loading file from local or a StringIO objec... | def load_file(file_path, credentials=None):
if file_path.startswith('gs://'):
return _load_file_from_gcs(file_path, credentials)
else:
return open(file_path, 'r') | 464,330 |
Check whether the file exists, in GCS.
Args:
gcs_file_path: The target file path; should have the 'gs://' prefix.
credentials: Optional credential to be used to load the file from gcs.
Returns:
True if the file's there. | def _file_exists_in_gcs(gcs_file_path, credentials=None):
gcs_service = _get_storage_service(credentials)
bucket_name, object_name = gcs_file_path[len('gs://'):].split('/', 1)
request = gcs_service.objects().get(
bucket=bucket_name, object=object_name, projection='noAcl')
try:
request.execute()
... | 464,331 |
Check whether the file exists, on local disk or GCS.
Args:
file_path: The target file path; should have the 'gs://' prefix if in gcs.
credentials: Optional credential to be used to load the file from gcs.
Returns:
True if the file's there. | def file_exists(file_path, credentials=None):
if file_path.startswith('gs://'):
return _file_exists_in_gcs(file_path, credentials)
else:
return os.path.isfile(file_path) | 464,332 |
Check whether there is a GCS object whose name starts with the prefix.
Since GCS doesn't actually have folders, this is how we check instead.
Args:
gcs_prefix: The path; should start with 'gs://'.
credentials: Optional credential to be used to load the file from gcs.
Returns:
True if the prefix mat... | def _prefix_exists_in_gcs(gcs_prefix, credentials=None):
gcs_service = _get_storage_service(credentials)
bucket_name, prefix = gcs_prefix[len('gs://'):].split('/', 1)
# documentation in
# https://cloud.google.com/storage/docs/json_api/v1/objects/list
request = gcs_service.objects().list(
bucket=buck... | 464,333 |
Gets the list of operations for the specified filter.
Args:
service: Google Genomics API service object
ops_filter: string filter of operations to return
page_size: the number of operations to requested on each list operation to
the pipelines API (if 0 or None, the API default is used)
... | def list(cls, service, ops_filter, page_size=0):
page_token = None
more_operations = True
documented_default_page_size = 256
documented_max_page_size = 2048
if not page_size:
page_size = documented_default_page_size
page_size = min(page_size, documented_max_page_size)
while mor... | 464,346 |
Returns a value from the operation for a specific set of field names.
Args:
field: a dsub-specific job metadata key
default: default value to return if field does not exist or is empty.
Returns:
A text string for the field or a list for 'inputs'.
Raises:
ValueError: if the field l... | def get_field(self, field, default=None):
metadata = self._op.get('metadata')
value = None
if field == 'internal-id':
value = self._op['name']
elif field == 'job-id':
value = metadata['labels'].get('job-id')
elif field == 'job-name':
value = metadata['labels'].get('job-name'... | 464,353 |
Returns a dictionary of envs or file inputs for an operation.
Args:
metadata: operation metadata field
file_input: True to return a dict of file inputs, False to return envs.
Returns:
A dictionary of input field name value pairs | def _get_operation_input_field_values(self, metadata, file_input):
# To determine input parameter type, we iterate through the
# pipeline inputParameters.
# The values come from the pipelineArgs inputs.
input_args = metadata['request']['ephemeralPipeline']['inputParameters']
vals_dict = metada... | 464,355 |
Create a task name from a job-id, task-id, and task-attempt.
Task names are used internally by dsub as well as by the docker task runner.
The name is formatted as "<job-id>.<task-id>[.task-attempt]". Task names
follow formatting conventions allowing them to be safely used as a docker
name.
Args:
job_id:... | def _format_task_name(job_id, task_id, task_attempt):
docker_name = '%s.%s' % (job_id, 'task' if task_id is None else task_id)
if task_attempt is not None:
docker_name += '.' + str(task_attempt)
# Docker container names must match: [a-zA-Z0-9][a-zA-Z0-9_.-]
# So 1) prefix it with "dsub-" and 2) change ... | 464,358 |
Returns a command to delocalize logs.
Args:
logging_path: location of log files.
user_project: name of the project to be billed for the request.
Returns:
eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12' | def _delocalize_logging_command(self, logging_path, user_project):
# Get the logging prefix (everything up to ".log")
logging_prefix = os.path.splitext(logging_path.uri)[0]
# Set the provider-specific mkdir and file copy commands
if logging_path.file_provider == job_model.P_LOCAL:
mkdir_cmd... | 464,376 |
Returns a directory or file path to be the target for "gsutil cp".
If the filename contains a wildcard, then the target path must
be a directory in order to ensure consistency whether the source pattern
contains one or multiple files.
Args:
local_file_path: A full path terminating in a file or ... | def _get_input_target_path(self, local_file_path):
path, filename = os.path.split(local_file_path)
if '*' in filename:
return path + '/'
else:
return local_file_path | 464,380 |
Gets the list of operations for the specified filter.
Args:
ops_filter: string filter of operations to return
max_tasks: the maximum number of job tasks to return or 0 for no limit.
page_size: the number of operations to requested on each list operation to
the pipelines API (if 0 or None,... | def _operations_list(self, ops_filter, max_tasks, page_size, page_token):
# We are not using the documented default page size of 256,
# nor allowing for the maximum page size of 2048 as larger page sizes
# currently cause the operations.list() API to return an error:
# HttpError 429 ... Resource h... | 464,414 |
Returns a value from the operation for a specific set of field names.
Args:
field: a dsub-specific job metadata key
default: default value to return if field does not exist or is empty.
Returns:
A text string for the field or a list for 'inputs'.
Raises:
ValueError: if the field l... | def get_field(self, field, default=None):
value = None
if field == 'internal-id':
value = self._op['name']
elif field == 'user-project':
if self._job_descriptor:
value = self._job_descriptor.job_metadata.get(field)
elif field in [
'job-id', 'job-name', 'task-id', 'task-... | 464,422 |
Parses command line arguments.
Args:
prog: The path of the program (dsub.py) or an alternate program name to
display in usage.
argv: The list of program arguments to parse.
Returns:
A Namespace of parsed arguments. | def _parse_arguments(prog, argv):
# Handle version flag and exit if it was passed.
param_util.handle_version_flag()
parser = provider_base.create_parser(prog)
# Add dsub core job submission arguments
parser.add_argument(
'--version', '-v', default=False, help='Print the dsub version and exit.')
... | 464,439 |
Extract job-global resources requirements from input args.
Args:
args: parsed command-line arguments
Returns:
Resources object containing the requested resources for the job | def _get_job_resources(args):
logging = param_util.build_logging_param(
args.logging) if args.logging else None
timeout = param_util.timeout_in_seconds(args.timeout)
log_interval = param_util.log_interval_in_seconds(args.log_interval)
return job_model.Resources(
min_cores=args.min_cores,
m... | 464,440 |
Allow provider to extract job-specific metadata from command-line args.
Args:
provider: job service provider
user_id: user submitting the job
job_name: name for the job
script: the script to run
task_ids: a set of the task-ids for all tasks in the job
user_project: name of the project to be b... | def _get_job_metadata(provider, user_id, job_name, script, task_ids,
user_project, unique_job_id):
create_time = dsub_util.replace_timezone(datetime.datetime.now(), tzlocal())
user_id = user_id or dsub_util.get_os_user()
job_metadata = provider.prepare_job_metadata(script.name, job_name, ... | 464,441 |
Resolve the logging path from job and task properties.
Args:
job_metadata: Job metadata, such as job-id, job-name, and user-id.
job_resources: Resources specified such as ram, cpu, and logging path.
task_descriptors: Task metadata, parameters, and resources.
Resolve the logging path, which may have su... | def _resolve_task_logging(job_metadata, job_resources, task_descriptors):
if not job_resources.logging:
return
for task_descriptor in task_descriptors:
logging_uri = provider_base.format_logging_uri(
job_resources.logging.uri, job_metadata, task_descriptor.task_metadata)
logging_path = job_m... | 464,442 |
Print status info as we wait for those jobs.
Blocks until either all of the listed jobs succeed,
or one of them fails.
Args:
provider: job service provider
job_ids: a set of job IDs (string) to wait for
poll_interval: integer seconds to wait between iterations
stop_on_failure: whether to stop wa... | def _wait_after(provider, job_ids, poll_interval, stop_on_failure):
# Each time through the loop, the job_set is re-set to the jobs remaining to
# check. Jobs are removed from the list when they complete.
#
# We exit the loop when:
# * No jobs remain are running, OR
# * stop_on_failure is TRUE AND at le... | 464,443 |
A list with, for each job, its dominant task.
The dominant task is the one that exemplifies its job's
status. It is either:
- the first (FAILURE or CANCELED) task, or if none
- the first RUNNING task, or if none
- the first SUCCESS task.
Args:
tasks: a list of tasks to consider
Returns:
A list ... | def _dominant_task_for_jobs(tasks):
per_job = _group_tasks_by_jobid(tasks)
ret = []
for job_id in per_job.keys():
tasks_in_salience_order = sorted(per_job[job_id], key=_importance_of_task)
ret.append(tasks_in_salience_order[0])
return ret | 464,446 |
Waits until any of the listed jobs is not running.
In particular, if any of the jobs sees one of its tasks fail,
we count the whole job as failing (but do not terminate the remaining
tasks ourselves).
Args:
provider: job service provider
job_ids: a list of job IDs (string) to wait for
poll_interva... | def _wait_for_any_job(provider, job_ids, poll_interval):
if not job_ids:
return
while True:
tasks = provider.lookup_job_tasks({'*'}, job_ids=job_ids)
running_jobs = set()
failed_jobs = set()
for t in tasks:
status = t.get_field('task-status')
job_id = t.get_field('job-id')
i... | 464,449 |
Split a string into a pair, which can have one empty value.
Args:
pair_string: The string to be split.
separator: The separator to be used for splitting.
nullable_idx: The location to be set to null if the separator is not in the
input string. Should be either 0 or 1.
Returns:
A ... | def split_pair(pair_string, separator, nullable_idx=1):
pair = pair_string.split(separator, 1)
if len(pair) == 1:
if nullable_idx == 0:
return [None, pair[0]]
elif nullable_idx == 1:
return [pair[0], None]
else:
raise IndexError('nullable_idx should be either 0 or 1.')
else:
... | 464,461 |
Parse flags of key=value pairs and return a list of argclass.
For pair variables, we need to:
* split the input into name=value pairs (value optional)
* Create the EnvParam object
Args:
labels: list of 'key' or 'key=value' strings.
argclass: Container class for args, must instantiate with argcla... | def parse_pair_args(labels, argclass):
label_data = set()
for arg in labels:
name, value = split_pair(arg, '=', nullable_idx=1)
label_data.add(argclass(name, value))
return label_data | 464,464 |
Compute the create time (UTC) for the list filter.
If the age is an integer value it is treated as a UTC date.
Otherwise the value must be of the form "<integer><unit>" where supported
units are s, m, h, d, w (seconds, minutes, hours, days, weeks).
Args:
age: A "<integer><unit>" string or integer value.
... | def age_to_create_time(age, from_time=None):
if not age:
return None
if not from_time:
from_time = dsub_util.replace_timezone(datetime.datetime.now(), tzlocal())
try:
last_char = age[-1]
if last_char == 's':
return from_time - datetime.timedelta(seconds=int(age[:-1]))
elif last_ch... | 464,469 |
Convert the timeout duration to seconds.
The value must be of the form "<integer><unit>" where supported
units are s, m, h, d, w (seconds, minutes, hours, days, weeks).
Args:
interval: A "<integer><unit>" string.
valid_units: A list of supported units.
Returns:
A string of the form "<integer>s" o... | def _interval_to_seconds(interval, valid_units='smhdw'):
if not interval:
return None
try:
last_char = interval[-1]
if last_char == 's' and 's' in valid_units:
return str(float(interval[:-1])) + 's'
elif last_char == 'm' and 'm' in valid_units:
return str(float(interval[:-1]) * 60) ... | 464,470 |
Generator that yields a task-specific view of the job.
This generator exists to make it easy for callers to iterate over the tasks
in a JobDescriptor. Each pass yields a new JobDescriptor with a single task.
Args:
job_descriptor: A JobDescriptor with 1 or more tasks.
Yields:
A JobDescriptor with a si... | def task_view_generator(job_descriptor):
for task_descriptor in job_descriptor.task_descriptors:
jd = JobDescriptor(job_descriptor.job_metadata, job_descriptor.job_params,
job_descriptor.job_resources, [task_descriptor])
yield jd | 464,491 |
Converts a task-id to the numeric task-id.
Args:
task_id: task-id in either task-n or n format
Returns:
n | def numeric_task_id(task_id):
# This function exists to support the legacy "task-id" format in the "google"
# provider. Google labels originally could not be numeric. When the google
# provider is completely replaced by the google-v2 provider, this function can
# go away.
if task_id is not None:
if t... | 464,492 |
Return a multi-line string with export statements for the variables.
Arguments:
destination: Folder where the data will be put.
For example /mnt/data
inputs: a list of InputFileParam
Returns:
a multi-line string with a shell script that sets environment variables
corresponding to ... | def build_recursive_localize_env(destination, inputs):
export_input_dirs = '\n'.join([
'export {0}={1}/{2}'.format(var.name, destination.rstrip('/'),
var.docker_path.rstrip('/'))
for var in inputs
if var.recursive and var.docker_path
])
return export_input_di... | 464,521 |
Return a multi-line string with export statements for the variables.
Arguments:
source: Folder with the data.
For example /mnt/data
outputs: a list of OutputFileParam
Returns:
a multi-line string with a shell script that sets environment variables
corresponding to the outputs. | def build_recursive_gcs_delocalize_env(source, outputs):
filtered_outs = [
var for var in outputs
if var.recursive and var.file_provider == job_model.P_GCS
]
return '\n'.join([
'export {0}={1}/{2}'.format(var.name,
source.rstrip('/'),
... | 464,523 |
Return a multi-line string with a shell script to copy recursively.
Arguments:
source: Folder with the data.
For example /mnt/data
outputs: a list of OutputFileParam.
file_provider: file provider string used to filter the output params; the
returned command will only apply ou... | def build_recursive_delocalize_command(source, outputs, file_provider):
command = _LOCALIZE_COMMAND_MAP[file_provider]
filtered_outputs = [
var for var in outputs
if var.recursive and var.file_provider == file_provider
]
return '\n'.join([
textwrap.dedent().format(
command=comman... | 464,524 |
Return a multi-line string with export statements for the variables.
Arguments:
source: Folder with the data. For example /mnt/data
mounts: a list of MountParam
Returns:
a multi-line string with a shell script that sets environment variables
corresponding to the mounts. | def build_mount_env(source, mounts):
return '\n'.join([
'export {0}={1}/{2}'.format(var.name, source.rstrip('/'),
var.docker_path.rstrip('/')) for var in mounts
]) | 464,525 |
Create a JobError to indicate something went wrong.
Args:
message: user-friendly message
error_list: what went wrong
launched_job: if the job is launched, but has errors in
"--wait"ing on the tasks. | def __init__(self, message, error_list, launched_job):
super(JobError, self).__init__(message)
self.message = message
self.error_list = error_list
self.launched_job = launched_job | 464,527 |
Determine if a pipelines operation is a dsub request.
We don't have a rigorous way to identify an operation as being submitted
by dsub. Our best option is to check for certain fields that have always
been part of dsub operations.
- labels: job-id, job-name, and user-id have always existed. The dsub-version
... | def is_dsub_operation(op):
if not is_pipeline(op):
return False
for name in ['dsub-version', 'job-id', 'job-name', 'user-id']:
if not get_label(op, name):
return False
return True | 464,539 |
Create a new table that is a summary of the input rows.
All with the same (job-name or job-id, status) go together.
Args:
rows: the input rows, a list of dictionaries.
Returns:
A new row set of summary information. | def _prepare_summary_table(rows):
if not rows:
return []
# We either group on the job-name (if present) or fall back to the job-id
key_field = 'job-name'
if key_field not in rows[0]:
key_field = 'job-id'
# Group each of the rows based on (job-name or job-id, status)
grouped = collections.defaul... | 464,540 |
Build a set() of standard job and task labels.
Args:
job_metadata: Job metadata, such as job-id, job-name, and user-id.
task_metadata: Task metadata, such as the task-id.
task_id_pattern: A pattern for the task-id value, such as "task-%d"; the
original google label values could not be strictly nume... | def build_pipeline_labels(job_metadata, task_metadata, task_id_pattern=None):
labels = {
Label(name, job_metadata[name])
for name in ['job-name', 'job-id', 'user-id', 'dsub-version']
}
task_id = task_metadata.get('task-id')
if task_id is not None: # Check for None (as 0 is conceivably valid)
... | 464,558 |
Converts a datestamp from RFC3339 UTC to a datetime.
Args:
rfc3339_utc_string: a datetime string in RFC3339 UTC "Zulu" format
Returns:
A datetime. | def parse_rfc3339_utc_string(rfc3339_utc_string):
# The timestamp from the Google Operations are all in RFC3339 format, but
# they are sometimes formatted to millisconds, microseconds, sometimes
# nanoseconds, and sometimes only seconds:
# * 2016-11-14T23:05:56Z
# * 2016-11-14T23:05:56.010Z
# * 2016-11-... | 464,560 |
Cancel a batch of operations.
Args:
batch_fn: API-specific batch function.
cancel_fn: API-specific cancel function.
ops: A list of operations to cancel.
Returns:
A list of operations canceled and a list of error messages. | def _cancel_batch(batch_fn, cancel_fn, ops):
# We define an inline callback which will populate a list of
# successfully canceled operations as well as a list of operations
# which were not successfully canceled.
canceled = []
failed = []
def handle_cancel_response(request_id, response, exception):
... | 464,562 |
Cancel operations.
Args:
batch_fn: API-specific batch function.
cancel_fn: API-specific cancel function.
ops: A list of operations to cancel.
Returns:
A list of operations canceled and a list of error messages. | def cancel(batch_fn, cancel_fn, ops):
# Canceling many operations one-by-one can be slow.
# The Pipelines API doesn't directly support a list of operations to cancel,
# but the requests can be performed in batch.
canceled_ops = []
error_messages = []
max_batch = 256
total_ops = len(ops)
for first_... | 464,563 |
Return True if we should retry. False otherwise.
Args:
exception: An exception to test for transience.
Returns:
True if we should retry. False otherwise. | def retry_api_check(exception):
if isinstance(exception, apiclient.errors.HttpError):
if exception.resp.status in TRANSIENT_HTTP_ERROR_CODES:
_print_error('Retrying...')
return True
if isinstance(exception, socket.error):
if exception.errno in TRANSIENT_SOCKET_ERROR_CODES:
_print_error... | 464,564 |
Specific check for auth error codes.
Return True if we should retry.
False otherwise.
Args:
exception: An exception to test for transience.
Returns:
True if we should retry. False otherwise. | def retry_auth_check(exception):
if isinstance(exception, apiclient.errors.HttpError):
if exception.resp.status in HTTP_AUTH_ERROR_CODES:
_print_error('Retrying...')
return True
return False | 464,565 |
Configures genomics API client.
Args:
api_name: Name of the Google API (for example: "genomics")
api_version: Version of the API (for example: "v2alpha1")
credentials: Credentials to be used for the gcloud API calls.
Returns:
A configured Google Genomics API client with appropriate credentials. | def setup_service(api_name, api_version, credentials=None):
if not credentials:
credentials = oauth2client.client.GoogleCredentials.get_application_default(
)
return apiclient.discovery.build(
api_name, api_version, credentials=credentials) | 464,566 |
Executes operation.
Args:
api: The base API object
Returns:
A response body object | def execute(api):
try:
return api.execute()
except Exception as exception:
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
_print_error('%s: Exception %s: %s' % (now, type(exception).__name__,
str(exception)))
# Re-raise exception t... | 464,567 |
check response
Args:
respond (str): HTTP response.
Returns:
bool: True if the response is good, else False.
Raises:
ApiError: response isn't formatted properly. | def _response_good(self, respond):
if respond.status_code != requests.codes.ok:
log.warning('Got a {} code response to {}: {}'.format(
respond.status_code,
respond.url,
respond.text))
if respond.status_code in self.errorsNotRetry:
... | 466,180 |
parse text of response for HTTP errors
This parses the text of the response to decide whether to
retry request or raise exception. At the moment this only
detects an exception condition.
Args:
respond (Response): requests.Response object
Returns:
bool: ... | def _parse_response(self, respond):
# convert error messages into exceptions
mobj = self._max_qubit_error_re.match(respond.text)
if mobj:
raise RegisterSizeError(
'device register size must be <= {}'.format(mobj.group(1)))
return True | 466,181 |
根据sql查询
Args:
sql: sql 语句 str
return:
成功: 查询的结果
失败: -1 并打印返回报错信息 | def query(self, sql):
try:
self.connect()
with self.con.cursor() as cursor:
cursor.execute(sql)
self.con.commit()
res = cursor.fetchall()
return res
except Exception as e:
print(e)
re... | 466,204 |
将一条记录保存到数据库
Args:
table: 表名字 str
data: 记录 dict
return:
成功: 1
失败: -1 并打印返回报错信息
每条记录都以一个字典的形式传进来 | def save_one_data(self, data, table):
key_map = {}
if len(data) == 0:
print('请确保data被正确传入了')
return -1
fields = ''
values = ''
datas = {}
for k, v in data.items():
# 防止sql注入
datas.update({k: pymysql.escape_string(st... | 466,205 |
通过id更新记录
Args:
table: 表名字 str
data: 记录 dict
id_value: id值
return:
成功: 1
失败: -1 并打印返回报错信息
每条记录都以一个字典的形式传进来 | def update_by_id(self, data, table, id_value):
key_map = {}
if len(data) == 0:
print('请确保data被正确传入了')
return -1
datas = {}
updates = ''
for k, v in data.items():
# 防止sql注入
datas.update({k: pymysql.escape_string(str(v))})
... | 466,206 |
从数据库里查询所有记录
Args:
table: 表名字 str
limit: 限制数量
return:
成功: [dict] 保存的记录
失败: -1 并打印返回报错信息 | def find_all(self, table, limit=10):
sql = "select * from {} limit 0,{}".format(table, limit)
res = self.query(sql)
return res | 466,207 |
从数据库里查询指定条件的记录
Args:
table: 表名字 str
field: 字段名
field_value: 字段值
return:
成功: [dict] 保存的记录
失败: -1 并打印返回报错信息 | def find_by_field(self, table, field, field_value):
sql = "select * from {} where {} = '{}'".format(
table, field, field_value)
res = self.query(sql)
return res | 466,208 |
从数据库里查询 符合多个条件的记录
Args:
table: 表名字 str
queryset : key 字段 value 值 dict
return:
成功: [dict] 保存的记录
失败: -1 并打印返回报错信息 | def find_by_fields(self, table, queryset={}):
querys = ""
for k, v in queryset.items():
querys += "{} = '{}' and ".format(k, v)
sql = "select * from {} where {} ".format(
table, querys[:-4])
res = self.query(sql)
return res | 466,209 |
Starts tracing with the given callable.
Args:
predicate (callable that accepts a single :obj:`hunter.Event` argument):
Return:
self | def trace(self, predicate):
self._handler = predicate
if self.threading_support is None or self.threading_support:
self._threading_previous = getattr(threading, '_trace_hook', None)
threading.settrace(self)
self._previous = sys.gettrace()
sys.settrace(sel... | 466,218 |
load HAR file and return log entries list
Args:
file_path (str)
Returns:
list: entries
[
{
"request": {},
"response": {}
},
{
"request": {},
"response": {... | def load_har_log_entries(file_path):
with io.open(file_path, "r+", encoding="utf-8-sig") as f:
try:
content_json = json.loads(f.read())
return content_json["log"]["entries"]
except (KeyError, TypeError):
logging.error("HAR file content error: {}".format(file_... | 466,299 |
convert origin dict to x-www-form-urlencoded
Args:
post_data (dict):
{"a": 1, "b":2}
Returns:
str:
a=1&b=2 | def x_www_form_urlencoded(post_data):
if isinstance(post_data, dict):
return "&".join([
u"{}={}".format(key, value)
for key, value in post_data.items()
])
else:
return post_data | 466,300 |
convert x_www_form_urlencoded data to dict
Args:
post_data (str): a=1&b=2
Returns:
dict: {"a":1, "b":2} | def convert_x_www_form_urlencoded_to_dict(post_data):
if isinstance(post_data, str):
converted_dict = {}
for k_v in post_data.split("&"):
try:
key, value = k_v.split("=")
except ValueError:
raise Exception(
"Invalid x_w... | 466,301 |
Short implementation for Adf.ly
Args:
url: the URL you want to shorten
Returns:
A string containing the shortened URL
Raises:
BadAPIResponseException: If the data is malformed or we got a bad
status code on API response
ShorteningErro... | def short(self, url):
url = self.clean_url(url)
shorten_url = f'{self.api_url}v1/shorten'
payload = {
'domain': getattr(self, 'domain', 'adf.ly'),
'advert_type': getattr(self, 'type', 'int'),
'group_id': getattr(self, 'group_id', None),
'k... | 466,321 |
Expand implementation for Adf.ly
Args:
url: the URL you want to expand
Returns:
A string containing the expanded URL
Raises:
BadAPIResponseException: If the data is malformed or we got a bad
status code on API response
ShorteningError... | def expand(self, url):
url = self.clean_url(url)
expand_url = f'{self.api_url}v1/expand'
payload = {
'domain': getattr(self, 'domain', 'adf.ly'),
'advert_type': getattr(self, 'type', 'int'),
'group_id': getattr(self, 'group_id', None),
'ke... | 466,322 |
Short implementation for Bit.ly
Args:
url: the URL you want to shorten
Returns:
A string containing the shortened URL
Raises:
BadAPIResponseException: If the data is malformed or we got a bad
status code on API response
ShorteningErro... | def short(self, url):
self.clean_url(url)
shorten_url = f'{self.api_url}v3/shorten'
params = {
'uri': url,
'access_token': self.api_key,
'format': 'txt',
}
response = self._get(shorten_url, params=params)
if response.ok:
... | 466,323 |
Expand implementation for Bit.ly
Args:
url: the URL you want to shorten
Returns:
A string containing the expanded URL
Raises:
ExpandingErrorException: If the API Returns an error as response | def expand(self, url):
expand_url = f'{self.api_url}v3/expand'
params = {
'shortUrl': url,
'access_token': self.api_key,
'format': 'txt',
}
response = self._get(expand_url, params=params)
if response.ok:
return response.tex... | 466,324 |
Total clicks implementation for Bit.ly
Args:
url: the URL you want to get the total clicks count
Returns:
An int containing the total clicks count
Raises:
BadAPIResponseException: If the API Returns an error as response | def total_clicks(self, url):
url = self.clean_url(url)
clicks_url = f'{self.api_url}v3/link/clicks'
params = {
'link': url,
'access_token': self.api_key,
'format': 'txt'
}
response = self._get(clicks_url, params=params)
if not ... | 466,325 |
Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
Defaults to |True|. | def dump(self, output, close_after_write=True):
try:
output.write
self.stream = output
except AttributeError:
self.stream = io.open(output, "w", encoding="utf-8")
try:
self.write_table()
finally:
if close_after_write:... | 466,644 |
Make a worksheet to the current workbook.
Args:
sheet_name (str):
Name of the worksheet to create. The name will be automatically generated
(like ``"Sheet1"``) if the ``sheet_name`` is empty. | def make_worksheet(self, sheet_name=None):
if sheet_name is None:
sheet_name = self.table_name
if not sheet_name:
sheet_name = ""
self._stream = self.workbook.add_worksheet(sheet_name)
self._current_data_row = self._first_data_row | 466,673 |
Write a worksheet to the current workbook.
Args:
output (str):
Path to the workbook file to write.
close_after_write (bool, optional):
Close the workbook after write.
Defaults to |True|. | def dump(self, output, close_after_write=True):
self.open(output)
try:
self.make_worksheet(self.table_name)
self.write_table()
finally:
if close_after_write:
self.close() | 466,674 |
Set |Style| for a specific column.
Args:
column (|int| or |str|):
Column specifier. column index or header name correlated with the column.
style (|Style|):
Style value to be set to the column.
Raises:
ValueError: If the column specif... | def set_style(self, column, style):
column_idx = None
while len(self.headers) > len(self.__style_list):
self.__style_list.append(None)
if isinstance(column, six.integer_types):
column_idx = column
elif isinstance(column, six.string_types):
... | 466,714 |
Set tabular attributes to the writer from :py:class:`pandas.Series`.
Following attributes are set by the method:
- :py:attr:`~.headers`
- :py:attr:`~.value_matrix`
- :py:attr:`~.type_hints`
Args:
series(pandas.Series):
Input pandas.Series... | def from_series(self, series, add_index_column=True):
if series.name:
self.headers = [series.name]
else:
self.headers = ["value"]
self.type_hints = [self.__get_typehint_from_dtype(series.dtype)]
if add_index_column:
self.headers = [""] + se... | 466,719 |
Establish a connection to a Loom file.
Args:
filename: Name of the .loom file to open
mode: read/write mode, accepts 'r+' (read/write) or
'r' (read-only), defaults to 'r+' without arguments,
and to 'r' with incorrect arguments
validate: Validate that the file conforms with the Loom sp... | def __init__(self, filename: str, mode: str = 'r+', *, validate: bool = True, spec_version: str = "2.0.1") -> None:
if not os.path.exists(filename):
raise IOError(f"File '{filename}' not found")
# make sure a valid mode was passed
if mode != 'r+' and mode != 'r':
raise ValueError("Mode must be either 'r'... | 467,950 |
Get a summary of the parts of the file that changed since the given time
Args:
timestamp: ISO8601 timestamp
Return:
dict: Dictionary like ``{"row_graphs": rg, "col_graphs": cg, "row_attrs": ra, "col_attrs": ca, "layers": layers}`` listing the names of objects that were modified since the given time | def get_changes_since(self, timestamp: str) -> Dict[str, List]:
rg = []
cg = []
ra = []
ca = []
layers = []
if self.last_modified() > timestamp:
if self.row_graphs.last_modified() > timestamp:
for name in self.row_graphs.keys():
if self.row_graphs.last_modified(name) > timestamp:
rg.ap... | 467,952 |
Get a slice of the main matrix.
Args:
slice: A slice object (see http://docs.h5py.org/en/latest/high/dataset.html), or np.ndarray, or int
Returns:
A numpy ndarray matrix | def __getitem__(self, slice_: Any) -> np.ndarray:
if type(slice_) is str:
return self.layers[slice_]
if type(slice_) is not tuple:
raise ValueError("Slice must be a 2-tuple")
return self.layers[""][slice_] | 467,954 |
Assign a slice of the main matrix.
Args:
slice_: A slice object (see http://docs.h5py.org/en/latest/high/dataset.html), or np.ndarray, or int
data: A matrix corresponding to the slice, of the same datatype as the main matrix
Returns:
Nothing. | def __setitem__(self, slice_: Any, data: np.ndarray) -> None:
if type(slice_) is str:
self.layers[slice_] = data
else:
self.layers[""][slice_] = data | 467,955 |
Return the main matrix or specified layer as a scipy.sparse.coo_matrix, without loading dense matrix in RAM
Args:
rows: Rows to include, or None to include all
cols: Columns to include, or None to include all
layer: Layer to return, or None to return the default layer
Returns:
Sparse matrix (:class... | def sparse(self, rows: np.ndarray = None, cols: np.ndarray = None, layer: str = None) -> scipy.sparse.coo_matrix:
if layer is None:
return self.layers[""].sparse(rows=rows, cols=cols)
else:
return self.layers[layer].sparse(rows=rows, cols=cols) | 467,956 |
Close the connection. After this, the connection object becomes invalid. Warns user if called after closing.
Args:
suppress_warning: Suppresses warning message if True (defaults to false) | def close(self, suppress_warning: bool = False) -> None:
if self._file is None:
if not suppress_warning:
# Warn user that they're being paranoid
# and should clean up their code
logging.warn("Connection to %s is already closed", self.filename)
else:
self._file.close()
self._file = None
sel... | 467,957 |
Permute the dataset along the indicated axis.
Args:
ordering (list of int): The desired order along the axis
axis (int): The axis along which to permute
Returns:
Nothing. | def permute(self, ordering: np.ndarray, axis: int) -> None:
if self._file.__contains__("tiles"):
del self._file['tiles']
ordering = list(np.array(ordering).flatten()) # Flatten the ordering, in case we got a column vector
self.layers._permute(ordering, axis=axis)
if axis == 0:
self.row_attrs._permute... | 467,970 |
Export the specified layer and row/col attributes as tab-delimited file.
Args:
out_file: Path to the output file
layer: Name of the layer to export, or None to export the main matrix
format: Desired file format (only 'tab' is supported) | def export(self, out_file: str, layer: str = None, format: str = "tab") -> None:
if format != "tab":
raise NotImplementedError("Only 'tab' is supported")
with open(out_file, "w") as f:
# Emit column attributes
for ca in self.col_attrs.keys():
for ra in self.row_attrs.keys():
f.write("\t")
... | 467,973 |
Access a layer by name, or slice through all the layers
Args:
thing: if string, return the specified layer ("" is the default layer)
if slice 2-tuple, return a new LayerManager with all layers sliced | def __getitem__(self, thing: Any) -> np.ndarray:
if type(thing) is str:
return self.__getattr__(thing)
else:
# Assume some kind of slice
lm = LayerManager(None)
for key, layer in self.items():
lm[key] = loompy.MemoryLoomLayer(key, layer[thing])
return lm | 467,984 |
Create a new view by slicing through the loom file or view
Args:
slice_ (2-tuple of slice, int or np.ndarray): How to slice the file or view
Returns:
A LoomView object, an in-memory representation of the sliced file | def __getitem__(self, slice_: Tuple[Union[slice, np.ndarray, int], Union[slice, np.ndarray, int]]) -> loompy.LoomView:
if type(slice_) is not tuple or len(slice_) is not 2:
raise ValueError("Views require slices along two dimensions")
rows = slice_[0]
cols = slice_[1]
ra = self.ds.ra[rows]
row_graphs ... | 468,010 |
Validate a file for conformance to the Loom specification
Args:
path: Full path to the file to be validated
strictness: "speconly" or "conventions"
Remarks:
In "speconly" mode, conformance is assessed relative to the file format specification
at http://linnarssonlab.org/loompy/format/. In "convent... | def validate(self, path: str, strictness: str = "speconly") -> bool:
valid1 = True
with h5py.File(path, mode="r") as f:
valid1 = self.validate_spec(f)
if not valid1:
self.errors.append("For help, see http://linnarssonlab.org/loompy/format/")
valid2 = True
if strictness == "conventions":
with lo... | 468,014 |
Validate the LoomConnection object against the attribute name/dtype conventions.
Args:
ds: LoomConnection object
Returns:
True if the file conforms to the conventions, else False
Remarks:
Upon return, the instance attributes 'self.errors' and 'self.warnings' contain
lists of errors and warnin... | def validate_conventions(self, ds: loompy.LoomConnection) -> bool:
(n_genes, n_cells) = ds.shape
self._warn("Description" in ds.attrs, "Optional global attribute 'Description' is missing")
self._warn("Journal" in ds.attrs, "Optional global attribute 'Journal' is missing")
self._warn("Authors" in ds.attrs, "... | 468,015 |
Validate the LoomConnection object against the format specification.
Args:
file: h5py File object
Returns:
True if the file conforms to the specs, else False
Remarks:
Upon return, the instance attributes 'self.errors' and 'self.warnings' contain
lists of errors and warnings, and the 'self.sum... | def validate_spec(self, file: h5py.File) -> bool:
matrix_types = ["float16", "float32", "float64", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"]
vertex_types = ["int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"]
weight_types = ["float16", "float32", "float64"]... | 468,016 |
Return a named attribute, or a slice through all the attributes
Args:
thing: if string, return the named attribute
if slice, np.ndarray or int, return a slice through all the attributes | def __getitem__(self, thing: Any) -> np.ndarray:
if type(thing) is slice or type(thing) is np.ndarray or type(thing) is int:
am = AttributeManager(None, axis=self.axis)
for key, val in self.items():
am[key] = val[thing]
return am
elif type(thing) is tuple:
# A tuple of strings giving alternative ... | 468,019 |
Return the named attribute
Args:
name (str) Name of the attribute
Remarks:
The values will be loaded from file, and properly HTML unescaped | def __getattr__(self, name: str) -> np.ndarray:
try:
vals = self.__dict__["storage"][name]
if vals is None:
# Read values from the HDF5 file
a = ["/row_attrs/", "/col_attrs/"][self.axis]
vals = loompy.materialize_attr_values(self.ds._file[a][name][:])
self.__dict__["storage"][name] = vals
... | 468,020 |
Set the value of a named attribute
Args:
name (str) Name of the attribute
val (np.ndarray) Value of the attribute
Remarks:
Length must match the corresponding matrix dimension
The values are automatically HMTL escaped and converted to ASCII for storage | def __setattr__(self, name: str, val: np.ndarray) -> None:
if name.startswith("!"):
super(AttributeManager, self).__setattr__(name[1:], val)
elif "/" in name:
raise KeyError("Attribute name cannot contain slash (/)")
else:
if self.ds is not None:
values = loompy.normalize_attr_values(val)
a = ... | 468,021 |
Take all kinds of input values and validate/normalize them.
Args:
a List, tuple, np.matrix, np.ndarray or sparse matrix
Elements can be strings, numbers or bools
Returns
a_normalized An np.ndarray with elements conforming to one of the valid Loom attribute types
Remarks:
This method should be used ... | def normalize_attr_values(a: Any) -> np.ndarray:
scalar = False
if np.isscalar(a):
a = np.array([a])
scalar = True
arr = normalize_attr_array(a)
if np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating):
pass # We allow all these types
elif np.issubdtype(arr.dtype, np.character) or ... | 468,027 |
Get a slice of the main matrix.
Args:
slice: A 2D slice object (see http://docs.h5py.org/en/latest/high/dataset.html) or np.ndarrays or ints
Returns:
A numpy matrix | def __getitem__(self, slice_: Union[str, Tuple[Union[int, np.ndarray, slice], Union[int, np.ndarray, slice]]]) -> np.ndarray:
if type(slice_) is str:
return self.layers[slice_]
else:
return self.layers[""][slice_] | 468,031 |
Permute the view, by permuting its layers, attributes and graphs
Args:
ordering (np.ndarray): The desired ordering along the axis
axis (int): 0, permute rows; 1, permute columns | def permute(self, ordering: np.ndarray, *, axis: int) -> None:
if axis not in (0, 1):
raise ValueError("Axis must be 0 (rows) or 1 (columns)")
for layer in self.layers.values():
layer._permute(ordering, axis=axis)
if axis == 0:
if self.row_graphs is not None:
for g in self.row_graphs.values():
... | 468,032 |
Permute the layer along an axis
Args:
axis: The axis to permute (0, permute the rows; 1, permute the columns)
ordering: The permutation vector | def permute(self, ordering: np.ndarray, *, axis: int) -> None:
if axis == 0:
self.values = self.values[ordering, :]
elif axis == 1:
self.values = self.values[:, ordering]
else:
raise ValueError("axis must be 0 or 1") | 468,041 |
Given a datafile determine if it is valid or not.
Args:
datafile: JSON string representing the project.
Returns:
Boolean depending upon whether datafile is valid or not. | def is_datafile_valid(datafile):
try:
datafile_json = json.loads(datafile)
except:
return False
try:
jsonschema.Draft4Validator(constants.JSON_SCHEMA).validate(datafile_json)
except:
return False
return True | 468,081 |
Determine if provided user profile is valid or not.
Args:
user_profile: User's profile which needs to be validated.
Returns:
Boolean depending upon whether profile is valid or not. | def is_user_profile_valid(user_profile):
if not user_profile:
return False
if not type(user_profile) is dict:
return False
if UserProfile.USER_ID_KEY not in user_profile:
return False
if UserProfile.EXPERIMENT_BUCKET_MAP_KEY not in user_profile:
return False
experiment_bucket_map = use... | 468,082 |
Determine if given attribute is valid.
Args:
attribute_key: Variable which needs to be validated
attribute_value: Variable which needs to be validated
Returns:
False if attribute_key is not a string
False if attribute_value is not one of the supported attribute types
True otherwise | def is_attribute_valid(attribute_key, attribute_value):
if not isinstance(attribute_key, string_types):
return False
if isinstance(attribute_value, (string_types, bool)):
return True
if isinstance(attribute_value, (numbers.Integral, float)):
return is_finite_number(attribute_value)
return Fal... | 468,083 |
Validates if the given value is a number, enforces
absolute limit of 2^53 and restricts NAN, INF, -INF.
Args:
value: Value to be validated.
Returns:
Boolean: True if value is a number and not NAN, INF, -INF or
greater than absolute limit of 2^53 else False. | def is_finite_number(value):
if not isinstance(value, (numbers.Integral, float)):
# numbers.Integral instead of int to accomodate long integer in python 2
return False
if isinstance(value, bool):
# bool is a subclass of int
return False
if isinstance(value, float):
if math.isnan(value) ... | 468,084 |
Method to verify that both values belong to same type. Float and integer are
considered as same type.
Args:
first_val: Value to validate.
second_Val: Value to validate.
Returns:
Boolean: True if both values belong to same type. Otherwise False. | def are_values_same_type(first_val, second_val):
first_val_type = type(first_val)
second_val_type = type(second_val)
# use isinstance to accomodate Python 2 unicode and str types.
if isinstance(first_val, string_types) and isinstance(second_val, string_types):
return True
# Compare types if one of t... | 468,085 |
Make a standard python logger object with default formatter, handler, etc.
Defaults are:
- level == logging.INFO
- handler == logging.StreamHandler()
Args:
name: a logger name.
level: an optional initial log level for this logger.
handler: an optional initial handler for this logger.
Return... | def reset_logger(name, level=None, handler=None):
# Make the logger and set its level.
if level is None:
level = logging.INFO
logger = logging.getLogger(name)
logger.setLevel(level)
# Make the handler and attach it.
handler = handler or logging.StreamHandler()
handler.setFormatter(logging.Formatte... | 468,086 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.