id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
18,600 | bslatkin/dpxdt | dpxdt/server/auth.py | can_user_access_build | def can_user_access_build(param_name):
"""Determines if the current user can access the build ID in the request.
Args:
param_name: Parameter name to use for getting the build ID from the
request. Will fetch from GET or POST requests.
Returns:
The build the user has access to.
"""
build_id = (
request.args.get(param_name, type=int) or
request.form.get(param_name, type=int) or
request.json[param_name])
if not build_id:
logging.debug('Build ID in param_name=%r was missing', param_name)
abort(400)
ops = operations.UserOps(current_user.get_id())
build, user_is_owner = ops.owns_build(build_id)
if not build:
logging.debug('Could not find build_id=%r', build_id)
abort(404)
if current_user.is_authenticated() and not user_is_owner:
# Assume the user should be able to access the build but can't because
# the cache is out of date. This forces the cache to repopulate, any
# outstanding user invitations to be completed, hopefully resulting in
# the user having access to the build.
ops.evict()
claim_invitations(current_user)
build, user_is_owner = ops.owns_build(build_id)
if not user_is_owner:
if current_user.is_authenticated() and current_user.superuser:
pass
elif request.method != 'GET':
logging.debug('No way to log in user via modifying request')
abort(403)
elif build.public:
pass
elif current_user.is_authenticated():
logging.debug('User does not have access to this build')
abort(flask.Response('You cannot access this build', 403))
else:
logging.debug('Redirecting user to login to get build access')
abort(login.unauthorized())
elif not login_fresh():
logging.debug('User login is old; forcing refresh')
abort(login.needs_refresh())
return build | python | def can_user_access_build(param_name):
build_id = (
request.args.get(param_name, type=int) or
request.form.get(param_name, type=int) or
request.json[param_name])
if not build_id:
logging.debug('Build ID in param_name=%r was missing', param_name)
abort(400)
ops = operations.UserOps(current_user.get_id())
build, user_is_owner = ops.owns_build(build_id)
if not build:
logging.debug('Could not find build_id=%r', build_id)
abort(404)
if current_user.is_authenticated() and not user_is_owner:
# Assume the user should be able to access the build but can't because
# the cache is out of date. This forces the cache to repopulate, any
# outstanding user invitations to be completed, hopefully resulting in
# the user having access to the build.
ops.evict()
claim_invitations(current_user)
build, user_is_owner = ops.owns_build(build_id)
if not user_is_owner:
if current_user.is_authenticated() and current_user.superuser:
pass
elif request.method != 'GET':
logging.debug('No way to log in user via modifying request')
abort(403)
elif build.public:
pass
elif current_user.is_authenticated():
logging.debug('User does not have access to this build')
abort(flask.Response('You cannot access this build', 403))
else:
logging.debug('Redirecting user to login to get build access')
abort(login.unauthorized())
elif not login_fresh():
logging.debug('User login is old; forcing refresh')
abort(login.needs_refresh())
return build | [
"def",
"can_user_access_build",
"(",
"param_name",
")",
":",
"build_id",
"=",
"(",
"request",
".",
"args",
".",
"get",
"(",
"param_name",
",",
"type",
"=",
"int",
")",
"or",
"request",
".",
"form",
".",
"get",
"(",
"param_name",
",",
"type",
"=",
"int"... | Determines if the current user can access the build ID in the request.
Args:
param_name: Parameter name to use for getting the build ID from the
request. Will fetch from GET or POST requests.
Returns:
The build the user has access to. | [
"Determines",
"if",
"the",
"current",
"user",
"can",
"access",
"the",
"build",
"ID",
"in",
"the",
"request",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L185-L236 |
18,601 | bslatkin/dpxdt | dpxdt/server/auth.py | build_access_required | def build_access_required(function_or_param_name):
"""Decorator ensures user has access to the build ID in the request.
May be used in two ways:
@build_access_required
def my_func(build):
...
@build_access_required('custom_build_id_param')
def my_func(build):
...
Always calls the given function with the models.Build entity as the
first positional argument.
"""
def get_wrapper(param_name, f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
g.build = can_user_access_build(param_name)
if not utils.is_production():
# Insert a sleep to emulate page loading in production.
time.sleep(0.5)
return f(*args, **kwargs)
return wrapped
if isinstance(function_or_param_name, basestring):
return lambda f: get_wrapper(function_or_param_name, f)
else:
return get_wrapper('id', function_or_param_name) | python | def build_access_required(function_or_param_name):
def get_wrapper(param_name, f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
g.build = can_user_access_build(param_name)
if not utils.is_production():
# Insert a sleep to emulate page loading in production.
time.sleep(0.5)
return f(*args, **kwargs)
return wrapped
if isinstance(function_or_param_name, basestring):
return lambda f: get_wrapper(function_or_param_name, f)
else:
return get_wrapper('id', function_or_param_name) | [
"def",
"build_access_required",
"(",
"function_or_param_name",
")",
":",
"def",
"get_wrapper",
"(",
"param_name",
",",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | Decorator ensures user has access to the build ID in the request.
May be used in two ways:
@build_access_required
def my_func(build):
...
@build_access_required('custom_build_id_param')
def my_func(build):
...
Always calls the given function with the models.Build entity as the
first positional argument. | [
"Decorator",
"ensures",
"user",
"has",
"access",
"to",
"the",
"build",
"ID",
"in",
"the",
"request",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L239-L268 |
18,602 | bslatkin/dpxdt | dpxdt/server/auth.py | _get_api_key_ops | def _get_api_key_ops():
"""Gets the operations.ApiKeyOps instance for the current request."""
auth_header = request.authorization
if not auth_header:
logging.debug('API request lacks authorization header')
abort(flask.Response(
'API key required', 401,
{'WWW-Authenticate': 'Basic realm="API key required"'}))
return operations.ApiKeyOps(auth_header.username, auth_header.password) | python | def _get_api_key_ops():
auth_header = request.authorization
if not auth_header:
logging.debug('API request lacks authorization header')
abort(flask.Response(
'API key required', 401,
{'WWW-Authenticate': 'Basic realm="API key required"'}))
return operations.ApiKeyOps(auth_header.username, auth_header.password) | [
"def",
"_get_api_key_ops",
"(",
")",
":",
"auth_header",
"=",
"request",
".",
"authorization",
"if",
"not",
"auth_header",
":",
"logging",
".",
"debug",
"(",
"'API request lacks authorization header'",
")",
"abort",
"(",
"flask",
".",
"Response",
"(",
"'API key re... | Gets the operations.ApiKeyOps instance for the current request. | [
"Gets",
"the",
"operations",
".",
"ApiKeyOps",
"instance",
"for",
"the",
"current",
"request",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L271-L280 |
18,603 | bslatkin/dpxdt | dpxdt/server/auth.py | current_api_key | def current_api_key():
"""Determines the API key for the current request.
Returns:
The ApiKey instance.
"""
if app.config.get('IGNORE_AUTH'):
return models.ApiKey(
id='anonymous_superuser',
secret='',
superuser=True)
ops = _get_api_key_ops()
api_key = ops.get()
logging.debug('Authenticated as API key=%r', api_key.id)
return api_key | python | def current_api_key():
if app.config.get('IGNORE_AUTH'):
return models.ApiKey(
id='anonymous_superuser',
secret='',
superuser=True)
ops = _get_api_key_ops()
api_key = ops.get()
logging.debug('Authenticated as API key=%r', api_key.id)
return api_key | [
"def",
"current_api_key",
"(",
")",
":",
"if",
"app",
".",
"config",
".",
"get",
"(",
"'IGNORE_AUTH'",
")",
":",
"return",
"models",
".",
"ApiKey",
"(",
"id",
"=",
"'anonymous_superuser'",
",",
"secret",
"=",
"''",
",",
"superuser",
"=",
"True",
")",
"... | Determines the API key for the current request.
Returns:
The ApiKey instance. | [
"Determines",
"the",
"API",
"key",
"for",
"the",
"current",
"request",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L283-L299 |
18,604 | bslatkin/dpxdt | dpxdt/server/auth.py | can_api_key_access_build | def can_api_key_access_build(param_name):
"""Determines if the current API key can access the build in the request.
Args:
param_name: Parameter name to use for getting the build ID from the
request. Will fetch from GET or POST requests.
Returns:
(api_key, build) The API Key and the Build it has access to.
"""
build_id = (
request.args.get(param_name, type=int) or
request.form.get(param_name, type=int) or
request.json[param_name])
utils.jsonify_assert(build_id, 'build_id required')
if app.config.get('IGNORE_AUTH'):
api_key = models.ApiKey(
id='anonymous_superuser',
secret='',
superuser=True)
build = models.Build.query.get(build_id)
utils.jsonify_assert(build is not None, 'build must exist', 404)
else:
ops = _get_api_key_ops()
api_key, build = ops.can_access_build(build_id)
return api_key, build | python | def can_api_key_access_build(param_name):
build_id = (
request.args.get(param_name, type=int) or
request.form.get(param_name, type=int) or
request.json[param_name])
utils.jsonify_assert(build_id, 'build_id required')
if app.config.get('IGNORE_AUTH'):
api_key = models.ApiKey(
id='anonymous_superuser',
secret='',
superuser=True)
build = models.Build.query.get(build_id)
utils.jsonify_assert(build is not None, 'build must exist', 404)
else:
ops = _get_api_key_ops()
api_key, build = ops.can_access_build(build_id)
return api_key, build | [
"def",
"can_api_key_access_build",
"(",
"param_name",
")",
":",
"build_id",
"=",
"(",
"request",
".",
"args",
".",
"get",
"(",
"param_name",
",",
"type",
"=",
"int",
")",
"or",
"request",
".",
"form",
".",
"get",
"(",
"param_name",
",",
"type",
"=",
"i... | Determines if the current API key can access the build in the request.
Args:
param_name: Parameter name to use for getting the build ID from the
request. Will fetch from GET or POST requests.
Returns:
(api_key, build) The API Key and the Build it has access to. | [
"Determines",
"if",
"the",
"current",
"API",
"key",
"can",
"access",
"the",
"build",
"in",
"the",
"request",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L302-L329 |
18,605 | bslatkin/dpxdt | dpxdt/server/auth.py | build_api_access_required | def build_api_access_required(f):
"""Decorator ensures API key has access to the build ID in the request.
Always calls the given function with the models.Build entity as the
first positional argument.
"""
@functools.wraps(f)
def wrapped(*args, **kwargs):
g.api_key, g.build = can_api_key_access_build('build_id')
return f(*args, **kwargs)
return wrapped | python | def build_api_access_required(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
g.api_key, g.build = can_api_key_access_build('build_id')
return f(*args, **kwargs)
return wrapped | [
"def",
"build_api_access_required",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"g",
".",
"api_key",
",",
"g",
".",
"build",
"=",
"can_api_key_access_build",
... | Decorator ensures API key has access to the build ID in the request.
Always calls the given function with the models.Build entity as the
first positional argument. | [
"Decorator",
"ensures",
"API",
"key",
"has",
"access",
"to",
"the",
"build",
"ID",
"in",
"the",
"request",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L332-L342 |
18,606 | bslatkin/dpxdt | dpxdt/server/auth.py | superuser_api_key_required | def superuser_api_key_required(f):
"""Decorator ensures only superuser API keys can request this function."""
@functools.wraps(f)
def wrapped(*args, **kwargs):
api_key = current_api_key()
g.api_key = api_key
utils.jsonify_assert(
api_key.superuser,
'API key=%r must be a super user' % api_key.id,
403)
return f(*args, **kwargs)
return wrapped | python | def superuser_api_key_required(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
api_key = current_api_key()
g.api_key = api_key
utils.jsonify_assert(
api_key.superuser,
'API key=%r must be a super user' % api_key.id,
403)
return f(*args, **kwargs)
return wrapped | [
"def",
"superuser_api_key_required",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"api_key",
"=",
"current_api_key",
"(",
")",
"g",
".",
"api_key",
"=",
"api... | Decorator ensures only superuser API keys can request this function. | [
"Decorator",
"ensures",
"only",
"superuser",
"API",
"keys",
"can",
"request",
"this",
"function",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L345-L359 |
18,607 | bslatkin/dpxdt | dpxdt/server/auth.py | manage_api_keys | def manage_api_keys():
"""Page for viewing and creating API keys."""
build = g.build
create_form = forms.CreateApiKeyForm()
if create_form.validate_on_submit():
api_key = models.ApiKey()
create_form.populate_obj(api_key)
api_key.id = utils.human_uuid()
api_key.secret = utils.password_uuid()
save_admin_log(build, created_api_key=True, message=api_key.id)
db.session.add(api_key)
db.session.commit()
logging.info('Created API key=%r for build_id=%r',
api_key.id, build.id)
return redirect(url_for('manage_api_keys', build_id=build.id))
create_form.build_id.data = build.id
api_key_query = (
models.ApiKey.query
.filter_by(build_id=build.id)
.order_by(models.ApiKey.created.desc())
.limit(1000))
revoke_form_list = []
for api_key in api_key_query:
form = forms.RevokeApiKeyForm()
form.id.data = api_key.id
form.build_id.data = build.id
form.revoke.data = True
revoke_form_list.append((api_key, form))
return render_template(
'view_api_keys.html',
build=build,
create_form=create_form,
revoke_form_list=revoke_form_list) | python | def manage_api_keys():
build = g.build
create_form = forms.CreateApiKeyForm()
if create_form.validate_on_submit():
api_key = models.ApiKey()
create_form.populate_obj(api_key)
api_key.id = utils.human_uuid()
api_key.secret = utils.password_uuid()
save_admin_log(build, created_api_key=True, message=api_key.id)
db.session.add(api_key)
db.session.commit()
logging.info('Created API key=%r for build_id=%r',
api_key.id, build.id)
return redirect(url_for('manage_api_keys', build_id=build.id))
create_form.build_id.data = build.id
api_key_query = (
models.ApiKey.query
.filter_by(build_id=build.id)
.order_by(models.ApiKey.created.desc())
.limit(1000))
revoke_form_list = []
for api_key in api_key_query:
form = forms.RevokeApiKeyForm()
form.id.data = api_key.id
form.build_id.data = build.id
form.revoke.data = True
revoke_form_list.append((api_key, form))
return render_template(
'view_api_keys.html',
build=build,
create_form=create_form,
revoke_form_list=revoke_form_list) | [
"def",
"manage_api_keys",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"create_form",
"=",
"forms",
".",
"CreateApiKeyForm",
"(",
")",
"if",
"create_form",
".",
"validate_on_submit",
"(",
")",
":",
"api_key",
"=",
"models",
".",
"ApiKey",
"(",
")",
"c... | Page for viewing and creating API keys. | [
"Page",
"for",
"viewing",
"and",
"creating",
"API",
"keys",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L365-L404 |
18,608 | bslatkin/dpxdt | dpxdt/server/auth.py | revoke_api_key | def revoke_api_key():
"""Form submission handler for revoking API keys."""
build = g.build
form = forms.RevokeApiKeyForm()
if form.validate_on_submit():
api_key = models.ApiKey.query.get(form.id.data)
if api_key.build_id != build.id:
logging.debug('User does not have access to API key=%r',
api_key.id)
abort(403)
api_key.active = False
save_admin_log(build, revoked_api_key=True, message=api_key.id)
db.session.add(api_key)
db.session.commit()
ops = operations.ApiKeyOps(api_key.id, api_key.secret)
ops.evict()
return redirect(url_for('manage_api_keys', build_id=build.id)) | python | def revoke_api_key():
build = g.build
form = forms.RevokeApiKeyForm()
if form.validate_on_submit():
api_key = models.ApiKey.query.get(form.id.data)
if api_key.build_id != build.id:
logging.debug('User does not have access to API key=%r',
api_key.id)
abort(403)
api_key.active = False
save_admin_log(build, revoked_api_key=True, message=api_key.id)
db.session.add(api_key)
db.session.commit()
ops = operations.ApiKeyOps(api_key.id, api_key.secret)
ops.evict()
return redirect(url_for('manage_api_keys', build_id=build.id)) | [
"def",
"revoke_api_key",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"form",
"=",
"forms",
".",
"RevokeApiKeyForm",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"api_key",
"=",
"models",
".",
"ApiKey",
".",
"query",
".",
"get",... | Form submission handler for revoking API keys. | [
"Form",
"submission",
"handler",
"for",
"revoking",
"API",
"keys",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L410-L430 |
18,609 | bslatkin/dpxdt | dpxdt/server/auth.py | claim_invitations | def claim_invitations(user):
"""Claims any pending invitations for the given user's email address."""
# See if there are any build invitations present for the user with this
# email address. If so, replace all those invitations with the real user.
invitation_user_id = '%s:%s' % (
models.User.EMAIL_INVITATION, user.email_address)
invitation_user = models.User.query.get(invitation_user_id)
if invitation_user:
invited_build_list = list(invitation_user.builds)
if not invited_build_list:
return
db.session.add(user)
logging.debug('Found %d build admin invitations for id=%r, user=%r',
len(invited_build_list), invitation_user_id, user)
for build in invited_build_list:
build.owners.remove(invitation_user)
if not build.is_owned_by(user.id):
build.owners.append(user)
logging.debug('Claiming invitation for build_id=%r', build.id)
save_admin_log(build, invite_accepted=True)
else:
logging.debug('User already owner of build. '
'id=%r, build_id=%r', user.id, build.id)
db.session.add(build)
db.session.delete(invitation_user)
db.session.commit()
# Re-add the user to the current session so we can query with it.
db.session.add(current_user) | python | def claim_invitations(user):
# See if there are any build invitations present for the user with this
# email address. If so, replace all those invitations with the real user.
invitation_user_id = '%s:%s' % (
models.User.EMAIL_INVITATION, user.email_address)
invitation_user = models.User.query.get(invitation_user_id)
if invitation_user:
invited_build_list = list(invitation_user.builds)
if not invited_build_list:
return
db.session.add(user)
logging.debug('Found %d build admin invitations for id=%r, user=%r',
len(invited_build_list), invitation_user_id, user)
for build in invited_build_list:
build.owners.remove(invitation_user)
if not build.is_owned_by(user.id):
build.owners.append(user)
logging.debug('Claiming invitation for build_id=%r', build.id)
save_admin_log(build, invite_accepted=True)
else:
logging.debug('User already owner of build. '
'id=%r, build_id=%r', user.id, build.id)
db.session.add(build)
db.session.delete(invitation_user)
db.session.commit()
# Re-add the user to the current session so we can query with it.
db.session.add(current_user) | [
"def",
"claim_invitations",
"(",
"user",
")",
":",
"# See if there are any build invitations present for the user with this",
"# email address. If so, replace all those invitations with the real user.",
"invitation_user_id",
"=",
"'%s:%s'",
"%",
"(",
"models",
".",
"User",
".",
"EM... | Claims any pending invitations for the given user's email address. | [
"Claims",
"any",
"pending",
"invitations",
"for",
"the",
"given",
"user",
"s",
"email",
"address",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L433-L463 |
18,610 | bslatkin/dpxdt | dpxdt/server/auth.py | manage_admins | def manage_admins():
"""Page for viewing and managing build admins."""
build = g.build
# Do not show cached data
db.session.add(build)
db.session.refresh(build)
add_form = forms.AddAdminForm()
if add_form.validate_on_submit():
invitation_user_id = '%s:%s' % (
models.User.EMAIL_INVITATION, add_form.email_address.data)
invitation_user = models.User.query.get(invitation_user_id)
if not invitation_user:
invitation_user = models.User(
id=invitation_user_id,
email_address=add_form.email_address.data)
db.session.add(invitation_user)
db.session.add(build)
db.session.add(invitation_user)
db.session.refresh(build, lockmode='update')
build.owners.append(invitation_user)
save_admin_log(build, invited_new_admin=True,
message=invitation_user.email_address)
db.session.commit()
logging.info('Added user=%r as owner to build_id=%r',
invitation_user.id, build.id)
return redirect(url_for('manage_admins', build_id=build.id))
add_form.build_id.data = build.id
revoke_form_list = []
for user in build.owners:
form = forms.RemoveAdminForm()
form.user_id.data = user.id
form.build_id.data = build.id
form.revoke.data = True
revoke_form_list.append((user, form))
return render_template(
'view_admins.html',
build=build,
add_form=add_form,
revoke_form_list=revoke_form_list) | python | def manage_admins():
build = g.build
# Do not show cached data
db.session.add(build)
db.session.refresh(build)
add_form = forms.AddAdminForm()
if add_form.validate_on_submit():
invitation_user_id = '%s:%s' % (
models.User.EMAIL_INVITATION, add_form.email_address.data)
invitation_user = models.User.query.get(invitation_user_id)
if not invitation_user:
invitation_user = models.User(
id=invitation_user_id,
email_address=add_form.email_address.data)
db.session.add(invitation_user)
db.session.add(build)
db.session.add(invitation_user)
db.session.refresh(build, lockmode='update')
build.owners.append(invitation_user)
save_admin_log(build, invited_new_admin=True,
message=invitation_user.email_address)
db.session.commit()
logging.info('Added user=%r as owner to build_id=%r',
invitation_user.id, build.id)
return redirect(url_for('manage_admins', build_id=build.id))
add_form.build_id.data = build.id
revoke_form_list = []
for user in build.owners:
form = forms.RemoveAdminForm()
form.user_id.data = user.id
form.build_id.data = build.id
form.revoke.data = True
revoke_form_list.append((user, form))
return render_template(
'view_admins.html',
build=build,
add_form=add_form,
revoke_form_list=revoke_form_list) | [
"def",
"manage_admins",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"# Do not show cached data",
"db",
".",
"session",
".",
"add",
"(",
"build",
")",
"db",
".",
"session",
".",
"refresh",
"(",
"build",
")",
"add_form",
"=",
"forms",
".",
"AddAdminFor... | Page for viewing and managing build admins. | [
"Page",
"for",
"viewing",
"and",
"managing",
"build",
"admins",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L469-L518 |
18,611 | bslatkin/dpxdt | dpxdt/server/auth.py | revoke_admin | def revoke_admin():
"""Form submission handler for revoking admin access to a build."""
build = g.build
form = forms.RemoveAdminForm()
if form.validate_on_submit():
user = models.User.query.get(form.user_id.data)
if not user:
logging.debug('User being revoked admin access does not exist.'
'id=%r, build_id=%r', form.user_id.data, build.id)
abort(400)
if user == current_user:
logging.debug('User trying to remove themself as admin. '
'id=%r, build_id=%r', user.id, build.id)
abort(400)
db.session.add(build)
db.session.add(user)
db.session.refresh(build, lockmode='update')
db.session.refresh(user, lockmode='update')
user_is_owner = build.owners.filter_by(id=user.id)
if not user_is_owner:
logging.debug('User being revoked admin access is not owner. '
'id=%r, build_id=%r.', user.id, build.id)
abort(400)
build.owners.remove(user)
save_admin_log(build, revoked_admin=True, message=user.email_address)
db.session.commit()
operations.UserOps(user.get_id()).evict()
return redirect(url_for('manage_admins', build_id=build.id)) | python | def revoke_admin():
build = g.build
form = forms.RemoveAdminForm()
if form.validate_on_submit():
user = models.User.query.get(form.user_id.data)
if not user:
logging.debug('User being revoked admin access does not exist.'
'id=%r, build_id=%r', form.user_id.data, build.id)
abort(400)
if user == current_user:
logging.debug('User trying to remove themself as admin. '
'id=%r, build_id=%r', user.id, build.id)
abort(400)
db.session.add(build)
db.session.add(user)
db.session.refresh(build, lockmode='update')
db.session.refresh(user, lockmode='update')
user_is_owner = build.owners.filter_by(id=user.id)
if not user_is_owner:
logging.debug('User being revoked admin access is not owner. '
'id=%r, build_id=%r.', user.id, build.id)
abort(400)
build.owners.remove(user)
save_admin_log(build, revoked_admin=True, message=user.email_address)
db.session.commit()
operations.UserOps(user.get_id()).evict()
return redirect(url_for('manage_admins', build_id=build.id)) | [
"def",
"revoke_admin",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"form",
"=",
"forms",
".",
"RemoveAdminForm",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"user",
"=",
"models",
".",
"User",
".",
"query",
".",
"get",
"(",
... | Form submission handler for revoking admin access to a build. | [
"Form",
"submission",
"handler",
"for",
"revoking",
"admin",
"access",
"to",
"a",
"build",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L524-L558 |
18,612 | bslatkin/dpxdt | dpxdt/server/auth.py | save_admin_log | def save_admin_log(build, **kwargs):
"""Saves an action to the admin log."""
message = kwargs.pop('message', None)
release = kwargs.pop('release', None)
run = kwargs.pop('run', None)
if not len(kwargs) == 1:
raise TypeError('Must specify a LOG_TYPE argument')
log_enum = kwargs.keys()[0]
log_type = getattr(models.AdminLog, log_enum.upper(), None)
if not log_type:
raise TypeError('Bad log_type argument: %s' % log_enum)
if current_user.is_anonymous():
user_id = None
else:
user_id = current_user.get_id()
log = models.AdminLog(
build_id=build.id,
log_type=log_type,
message=message,
user_id=user_id)
if release:
log.release_id = release.id
if run:
log.run_id = run.id
log.release_id = run.release_id
db.session.add(log) | python | def save_admin_log(build, **kwargs):
message = kwargs.pop('message', None)
release = kwargs.pop('release', None)
run = kwargs.pop('run', None)
if not len(kwargs) == 1:
raise TypeError('Must specify a LOG_TYPE argument')
log_enum = kwargs.keys()[0]
log_type = getattr(models.AdminLog, log_enum.upper(), None)
if not log_type:
raise TypeError('Bad log_type argument: %s' % log_enum)
if current_user.is_anonymous():
user_id = None
else:
user_id = current_user.get_id()
log = models.AdminLog(
build_id=build.id,
log_type=log_type,
message=message,
user_id=user_id)
if release:
log.release_id = release.id
if run:
log.run_id = run.id
log.release_id = run.release_id
db.session.add(log) | [
"def",
"save_admin_log",
"(",
"build",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"kwargs",
".",
"pop",
"(",
"'message'",
",",
"None",
")",
"release",
"=",
"kwargs",
".",
"pop",
"(",
"'release'",
",",
"None",
")",
"run",
"=",
"kwargs",
".",
... | Saves an action to the admin log. | [
"Saves",
"an",
"action",
"to",
"the",
"admin",
"log",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L561-L593 |
18,613 | bslatkin/dpxdt | dpxdt/server/auth.py | view_admin_log | def view_admin_log():
"""Page for viewing the log of admin activity."""
build = g.build
# TODO: Add paging
log_list = (
models.AdminLog.query
.filter_by(build_id=build.id)
.order_by(models.AdminLog.created.desc())
.all())
return render_template(
'view_admin_log.html',
build=build,
log_list=log_list) | python | def view_admin_log():
build = g.build
# TODO: Add paging
log_list = (
models.AdminLog.query
.filter_by(build_id=build.id)
.order_by(models.AdminLog.created.desc())
.all())
return render_template(
'view_admin_log.html',
build=build,
log_list=log_list) | [
"def",
"view_admin_log",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"# TODO: Add paging",
"log_list",
"=",
"(",
"models",
".",
"AdminLog",
".",
"query",
".",
"filter_by",
"(",
"build_id",
"=",
"build",
".",
"id",
")",
".",
"order_by",
"(",
"models",... | Page for viewing the log of admin activity. | [
"Page",
"for",
"viewing",
"the",
"log",
"of",
"admin",
"activity",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/auth.py#L599-L614 |
18,614 | bslatkin/dpxdt | dpxdt/client/utils.py | verify_binary | def verify_binary(flag_name, process_args=None):
"""Exits the program if the binary from the given flag doesn't run.
Args:
flag_name: Name of the flag that should be the path to the binary.
process_args: Args to pass to the binary to do nothing but verify
that it's working correctly (something like "--version") is good.
Optional. Defaults to no args.
Raises:
SystemExit with error if the process did not work.
"""
if process_args is None:
process_args = []
path = getattr(FLAGS, flag_name)
if not path:
logging.error('Flag %r not set' % flag_name)
sys.exit(1)
with open(os.devnull, 'w') as dev_null:
try:
subprocess.check_call(
[path] + process_args,
stdout=dev_null,
stderr=subprocess.STDOUT)
except:
logging.exception('--%s binary at path %r does not work',
flag_name, path)
sys.exit(1) | python | def verify_binary(flag_name, process_args=None):
if process_args is None:
process_args = []
path = getattr(FLAGS, flag_name)
if not path:
logging.error('Flag %r not set' % flag_name)
sys.exit(1)
with open(os.devnull, 'w') as dev_null:
try:
subprocess.check_call(
[path] + process_args,
stdout=dev_null,
stderr=subprocess.STDOUT)
except:
logging.exception('--%s binary at path %r does not work',
flag_name, path)
sys.exit(1) | [
"def",
"verify_binary",
"(",
"flag_name",
",",
"process_args",
"=",
"None",
")",
":",
"if",
"process_args",
"is",
"None",
":",
"process_args",
"=",
"[",
"]",
"path",
"=",
"getattr",
"(",
"FLAGS",
",",
"flag_name",
")",
"if",
"not",
"path",
":",
"logging"... | Exits the program if the binary from the given flag doesn't run.
Args:
flag_name: Name of the flag that should be the path to the binary.
process_args: Args to pass to the binary to do nothing but verify
that it's working correctly (something like "--version") is good.
Optional. Defaults to no args.
Raises:
SystemExit with error if the process did not work. | [
"Exits",
"the",
"program",
"if",
"the",
"binary",
"from",
"the",
"given",
"flag",
"doesn",
"t",
"run",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/client/utils.py#L28-L57 |
18,615 | bslatkin/dpxdt | dpxdt/server/api.py | create_release | def create_release():
"""Creates a new release candidate for a build."""
build = g.build
release_name = request.form.get('release_name')
utils.jsonify_assert(release_name, 'release_name required')
url = request.form.get('url')
utils.jsonify_assert(release_name, 'url required')
release = models.Release(
name=release_name,
url=url,
number=1,
build_id=build.id)
last_candidate = (
models.Release.query
.filter_by(build_id=build.id, name=release_name)
.order_by(models.Release.number.desc())
.first())
if last_candidate:
release.number += last_candidate.number
if last_candidate.status == models.Release.PROCESSING:
canceled_task_count = work_queue.cancel(
release_id=last_candidate.id)
logging.info('Canceling %d tasks for previous attempt '
'build_id=%r, release_name=%r, release_number=%d',
canceled_task_count, build.id, last_candidate.name,
last_candidate.number)
last_candidate.status = models.Release.BAD
db.session.add(last_candidate)
db.session.add(release)
db.session.commit()
signals.release_updated_via_api.send(app, build=build, release=release)
logging.info('Created release: build_id=%r, release_name=%r, url=%r, '
'release_number=%d', build.id, release.name,
url, release.number)
return flask.jsonify(
success=True,
build_id=build.id,
release_name=release.name,
release_number=release.number,
url=url) | python | def create_release():
build = g.build
release_name = request.form.get('release_name')
utils.jsonify_assert(release_name, 'release_name required')
url = request.form.get('url')
utils.jsonify_assert(release_name, 'url required')
release = models.Release(
name=release_name,
url=url,
number=1,
build_id=build.id)
last_candidate = (
models.Release.query
.filter_by(build_id=build.id, name=release_name)
.order_by(models.Release.number.desc())
.first())
if last_candidate:
release.number += last_candidate.number
if last_candidate.status == models.Release.PROCESSING:
canceled_task_count = work_queue.cancel(
release_id=last_candidate.id)
logging.info('Canceling %d tasks for previous attempt '
'build_id=%r, release_name=%r, release_number=%d',
canceled_task_count, build.id, last_candidate.name,
last_candidate.number)
last_candidate.status = models.Release.BAD
db.session.add(last_candidate)
db.session.add(release)
db.session.commit()
signals.release_updated_via_api.send(app, build=build, release=release)
logging.info('Created release: build_id=%r, release_name=%r, url=%r, '
'release_number=%d', build.id, release.name,
url, release.number)
return flask.jsonify(
success=True,
build_id=build.id,
release_name=release.name,
release_number=release.number,
url=url) | [
"def",
"create_release",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"release_name",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'release_name'",
")",
"utils",
".",
"jsonify_assert",
"(",
"release_name",
",",
"'release_name required'",
")",
"url",
"="... | Creates a new release candidate for a build. | [
"Creates",
"a",
"new",
"release",
"candidate",
"for",
"a",
"build",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L109-L154 |
18,616 | bslatkin/dpxdt | dpxdt/server/api.py | _check_release_done_processing | def _check_release_done_processing(release):
"""Moves a release candidate to reviewing if all runs are done."""
if release.status != models.Release.PROCESSING:
# NOTE: This statement also guards for situations where the user has
# prematurely specified that the release is good or bad. Once the user
# has done that, the system will not automatically move the release
# back into the 'reviewing' state or send the email notification below.
logging.info('Release not in processing state yet: build_id=%r, '
'name=%r, number=%d', release.build_id, release.name,
release.number)
return False
query = models.Run.query.filter_by(release_id=release.id)
for run in query:
if run.status == models.Run.NEEDS_DIFF:
# Still waiting for the diff to finish.
return False
if run.ref_config and not run.ref_image:
# Still waiting for the ref capture to process.
return False
if run.config and not run.image:
# Still waiting for the run capture to process.
return False
logging.info('Release done processing, now reviewing: build_id=%r, '
'name=%r, number=%d', release.build_id, release.name,
release.number)
# Send the email at the end of this request so we know it's only
# sent a single time (guarded by the release.status check above).
build_id = release.build_id
release_name = release.name
release_number = release.number
@utils.after_this_request
def send_notification_email(response):
emails.send_ready_for_review(build_id, release_name, release_number)
release.status = models.Release.REVIEWING
db.session.add(release)
return True | python | def _check_release_done_processing(release):
if release.status != models.Release.PROCESSING:
# NOTE: This statement also guards for situations where the user has
# prematurely specified that the release is good or bad. Once the user
# has done that, the system will not automatically move the release
# back into the 'reviewing' state or send the email notification below.
logging.info('Release not in processing state yet: build_id=%r, '
'name=%r, number=%d', release.build_id, release.name,
release.number)
return False
query = models.Run.query.filter_by(release_id=release.id)
for run in query:
if run.status == models.Run.NEEDS_DIFF:
# Still waiting for the diff to finish.
return False
if run.ref_config and not run.ref_image:
# Still waiting for the ref capture to process.
return False
if run.config and not run.image:
# Still waiting for the run capture to process.
return False
logging.info('Release done processing, now reviewing: build_id=%r, '
'name=%r, number=%d', release.build_id, release.name,
release.number)
# Send the email at the end of this request so we know it's only
# sent a single time (guarded by the release.status check above).
build_id = release.build_id
release_name = release.name
release_number = release.number
@utils.after_this_request
def send_notification_email(response):
emails.send_ready_for_review(build_id, release_name, release_number)
release.status = models.Release.REVIEWING
db.session.add(release)
return True | [
"def",
"_check_release_done_processing",
"(",
"release",
")",
":",
"if",
"release",
".",
"status",
"!=",
"models",
".",
"Release",
".",
"PROCESSING",
":",
"# NOTE: This statement also guards for situations where the user has",
"# prematurely specified that the release is good or ... | Moves a release candidate to reviewing if all runs are done. | [
"Moves",
"a",
"release",
"candidate",
"to",
"reviewing",
"if",
"all",
"runs",
"are",
"done",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L157-L197 |
18,617 | bslatkin/dpxdt | dpxdt/server/api.py | _get_release_params | def _get_release_params():
"""Gets the release params from the current request."""
release_name = request.form.get('release_name')
utils.jsonify_assert(release_name, 'release_name required')
release_number = request.form.get('release_number', type=int)
utils.jsonify_assert(release_number is not None, 'release_number required')
return release_name, release_number | python | def _get_release_params():
release_name = request.form.get('release_name')
utils.jsonify_assert(release_name, 'release_name required')
release_number = request.form.get('release_number', type=int)
utils.jsonify_assert(release_number is not None, 'release_number required')
return release_name, release_number | [
"def",
"_get_release_params",
"(",
")",
":",
"release_name",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'release_name'",
")",
"utils",
".",
"jsonify_assert",
"(",
"release_name",
",",
"'release_name required'",
")",
"release_number",
"=",
"request",
".",
"fo... | Gets the release params from the current request. | [
"Gets",
"the",
"release",
"params",
"from",
"the",
"current",
"request",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L200-L206 |
18,618 | bslatkin/dpxdt | dpxdt/server/api.py | _find_last_good_run | def _find_last_good_run(build):
"""Finds the last good release and run for a build."""
run_name = request.form.get('run_name', type=str)
utils.jsonify_assert(run_name, 'run_name required')
last_good_release = (
models.Release.query
.filter_by(
build_id=build.id,
status=models.Release.GOOD)
.order_by(models.Release.created.desc())
.first())
last_good_run = None
if last_good_release:
logging.debug('Found last good release for: build_id=%r, '
'release_name=%r, release_number=%d',
build.id, last_good_release.name,
last_good_release.number)
last_good_run = (
models.Run.query
.filter_by(release_id=last_good_release.id, name=run_name)
.first())
if last_good_run:
logging.debug('Found last good run for: build_id=%r, '
'release_name=%r, release_number=%d, '
'run_name=%r',
build.id, last_good_release.name,
last_good_release.number, last_good_run.name)
return last_good_release, last_good_run | python | def _find_last_good_run(build):
run_name = request.form.get('run_name', type=str)
utils.jsonify_assert(run_name, 'run_name required')
last_good_release = (
models.Release.query
.filter_by(
build_id=build.id,
status=models.Release.GOOD)
.order_by(models.Release.created.desc())
.first())
last_good_run = None
if last_good_release:
logging.debug('Found last good release for: build_id=%r, '
'release_name=%r, release_number=%d',
build.id, last_good_release.name,
last_good_release.number)
last_good_run = (
models.Run.query
.filter_by(release_id=last_good_release.id, name=run_name)
.first())
if last_good_run:
logging.debug('Found last good run for: build_id=%r, '
'release_name=%r, release_number=%d, '
'run_name=%r',
build.id, last_good_release.name,
last_good_release.number, last_good_run.name)
return last_good_release, last_good_run | [
"def",
"_find_last_good_run",
"(",
"build",
")",
":",
"run_name",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'run_name'",
",",
"type",
"=",
"str",
")",
"utils",
".",
"jsonify_assert",
"(",
"run_name",
",",
"'run_name required'",
")",
"last_good_release",
... | Finds the last good release and run for a build. | [
"Finds",
"the",
"last",
"good",
"release",
"and",
"run",
"for",
"a",
"build",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L209-L240 |
18,619 | bslatkin/dpxdt | dpxdt/server/api.py | find_run | def find_run():
"""Finds the last good run of the given name for a release."""
build = g.build
last_good_release, last_good_run = _find_last_good_run(build)
if last_good_run:
return flask.jsonify(
success=True,
build_id=build.id,
release_name=last_good_release.name,
release_number=last_good_release.number,
run_name=last_good_run.name,
url=last_good_run.url,
image=last_good_run.image,
log=last_good_run.log,
config=last_good_run.config)
return utils.jsonify_error('Run not found') | python | def find_run():
build = g.build
last_good_release, last_good_run = _find_last_good_run(build)
if last_good_run:
return flask.jsonify(
success=True,
build_id=build.id,
release_name=last_good_release.name,
release_number=last_good_release.number,
run_name=last_good_run.name,
url=last_good_run.url,
image=last_good_run.image,
log=last_good_run.log,
config=last_good_run.config)
return utils.jsonify_error('Run not found') | [
"def",
"find_run",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"last_good_release",
",",
"last_good_run",
"=",
"_find_last_good_run",
"(",
"build",
")",
"if",
"last_good_run",
":",
"return",
"flask",
".",
"jsonify",
"(",
"success",
"=",
"True",
",",
"b... | Finds the last good run of the given name for a release. | [
"Finds",
"the",
"last",
"good",
"run",
"of",
"the",
"given",
"name",
"for",
"a",
"release",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L245-L262 |
18,620 | bslatkin/dpxdt | dpxdt/server/api.py | _get_or_create_run | def _get_or_create_run(build):
"""Gets a run for a build or creates it if it does not exist."""
release_name, release_number = _get_release_params()
run_name = request.form.get('run_name', type=str)
utils.jsonify_assert(run_name, 'run_name required')
release = (
models.Release.query
.filter_by(build_id=build.id, name=release_name, number=release_number)
.first())
utils.jsonify_assert(release, 'release does not exist')
run = (
models.Run.query
.filter_by(release_id=release.id, name=run_name)
.first())
if not run:
# Ignore re-reports of the same run name for this release.
logging.info('Created run: build_id=%r, release_name=%r, '
'release_number=%d, run_name=%r',
build.id, release.name, release.number, run_name)
run = models.Run(
release_id=release.id,
name=run_name,
status=models.Run.DATA_PENDING)
db.session.add(run)
db.session.flush()
return release, run | python | def _get_or_create_run(build):
release_name, release_number = _get_release_params()
run_name = request.form.get('run_name', type=str)
utils.jsonify_assert(run_name, 'run_name required')
release = (
models.Release.query
.filter_by(build_id=build.id, name=release_name, number=release_number)
.first())
utils.jsonify_assert(release, 'release does not exist')
run = (
models.Run.query
.filter_by(release_id=release.id, name=run_name)
.first())
if not run:
# Ignore re-reports of the same run name for this release.
logging.info('Created run: build_id=%r, release_name=%r, '
'release_number=%d, run_name=%r',
build.id, release.name, release.number, run_name)
run = models.Run(
release_id=release.id,
name=run_name,
status=models.Run.DATA_PENDING)
db.session.add(run)
db.session.flush()
return release, run | [
"def",
"_get_or_create_run",
"(",
"build",
")",
":",
"release_name",
",",
"release_number",
"=",
"_get_release_params",
"(",
")",
"run_name",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'run_name'",
",",
"type",
"=",
"str",
")",
"utils",
".",
"jsonify_ass... | Gets a run for a build or creates it if it does not exist. | [
"Gets",
"a",
"run",
"for",
"a",
"build",
"or",
"creates",
"it",
"if",
"it",
"does",
"not",
"exist",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L265-L293 |
18,621 | bslatkin/dpxdt | dpxdt/server/api.py | _enqueue_capture | def _enqueue_capture(build, release, run, url, config_data, baseline=False):
"""Enqueues a task to run a capture process."""
# Validate the JSON config parses.
try:
config_dict = json.loads(config_data)
except Exception, e:
abort(utils.jsonify_error(e))
# Rewrite the config JSON to include the URL specified in this request.
# Blindly overwrite anything that was there.
config_dict['targetUrl'] = url
config_data = json.dumps(config_dict)
config_artifact = _save_artifact(build, config_data, 'application/json')
db.session.add(config_artifact)
db.session.flush()
suffix = ''
if baseline:
suffix = ':baseline'
task_id = '%s:%s%s' % (run.id, hashlib.sha1(url).hexdigest(), suffix)
logging.info('Enqueueing capture task=%r, baseline=%r', task_id, baseline)
work_queue.add(
constants.CAPTURE_QUEUE_NAME,
payload=dict(
build_id=build.id,
release_name=release.name,
release_number=release.number,
run_name=run.name,
url=url,
config_sha1sum=config_artifact.id,
baseline=baseline,
),
build_id=build.id,
release_id=release.id,
run_id=run.id,
source='request_run',
task_id=task_id)
# Set the URL and config early to indicate to report_run that there is
# still data pending even if 'image' and 'ref_image' are unset.
if baseline:
run.ref_url = url
run.ref_config = config_artifact.id
else:
run.url = url
run.config = config_artifact.id | python | def _enqueue_capture(build, release, run, url, config_data, baseline=False):
# Validate the JSON config parses.
try:
config_dict = json.loads(config_data)
except Exception, e:
abort(utils.jsonify_error(e))
# Rewrite the config JSON to include the URL specified in this request.
# Blindly overwrite anything that was there.
config_dict['targetUrl'] = url
config_data = json.dumps(config_dict)
config_artifact = _save_artifact(build, config_data, 'application/json')
db.session.add(config_artifact)
db.session.flush()
suffix = ''
if baseline:
suffix = ':baseline'
task_id = '%s:%s%s' % (run.id, hashlib.sha1(url).hexdigest(), suffix)
logging.info('Enqueueing capture task=%r, baseline=%r', task_id, baseline)
work_queue.add(
constants.CAPTURE_QUEUE_NAME,
payload=dict(
build_id=build.id,
release_name=release.name,
release_number=release.number,
run_name=run.name,
url=url,
config_sha1sum=config_artifact.id,
baseline=baseline,
),
build_id=build.id,
release_id=release.id,
run_id=run.id,
source='request_run',
task_id=task_id)
# Set the URL and config early to indicate to report_run that there is
# still data pending even if 'image' and 'ref_image' are unset.
if baseline:
run.ref_url = url
run.ref_config = config_artifact.id
else:
run.url = url
run.config = config_artifact.id | [
"def",
"_enqueue_capture",
"(",
"build",
",",
"release",
",",
"run",
",",
"url",
",",
"config_data",
",",
"baseline",
"=",
"False",
")",
":",
"# Validate the JSON config parses.",
"try",
":",
"config_dict",
"=",
"json",
".",
"loads",
"(",
"config_data",
")",
... | Enqueues a task to run a capture process. | [
"Enqueues",
"a",
"task",
"to",
"run",
"a",
"capture",
"process",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L296-L344 |
18,622 | bslatkin/dpxdt | dpxdt/server/api.py | request_run | def request_run():
"""Requests a new run for a release candidate."""
build = g.build
current_release, current_run = _get_or_create_run(build)
current_url = request.form.get('url', type=str)
config_data = request.form.get('config', default='{}', type=str)
utils.jsonify_assert(current_url, 'url to capture required')
utils.jsonify_assert(config_data, 'config document required')
config_artifact = _enqueue_capture(
build, current_release, current_run, current_url, config_data)
ref_url = request.form.get('ref_url', type=str)
ref_config_data = request.form.get('ref_config', type=str)
utils.jsonify_assert(
bool(ref_url) == bool(ref_config_data),
'ref_url and ref_config must both be specified or not specified')
if ref_url and ref_config_data:
ref_config_artifact = _enqueue_capture(
build, current_release, current_run, ref_url, ref_config_data,
baseline=True)
else:
_, last_good_run = _find_last_good_run(build)
if last_good_run:
current_run.ref_url = last_good_run.url
current_run.ref_image = last_good_run.image
current_run.ref_log = last_good_run.log
current_run.ref_config = last_good_run.config
db.session.add(current_run)
db.session.commit()
signals.run_updated_via_api.send(
app, build=build, release=current_release, run=current_run)
return flask.jsonify(
success=True,
build_id=build.id,
release_name=current_release.name,
release_number=current_release.number,
run_name=current_run.name,
url=current_run.url,
config=current_run.config,
ref_url=current_run.ref_url,
ref_config=current_run.ref_config) | python | def request_run():
build = g.build
current_release, current_run = _get_or_create_run(build)
current_url = request.form.get('url', type=str)
config_data = request.form.get('config', default='{}', type=str)
utils.jsonify_assert(current_url, 'url to capture required')
utils.jsonify_assert(config_data, 'config document required')
config_artifact = _enqueue_capture(
build, current_release, current_run, current_url, config_data)
ref_url = request.form.get('ref_url', type=str)
ref_config_data = request.form.get('ref_config', type=str)
utils.jsonify_assert(
bool(ref_url) == bool(ref_config_data),
'ref_url and ref_config must both be specified or not specified')
if ref_url and ref_config_data:
ref_config_artifact = _enqueue_capture(
build, current_release, current_run, ref_url, ref_config_data,
baseline=True)
else:
_, last_good_run = _find_last_good_run(build)
if last_good_run:
current_run.ref_url = last_good_run.url
current_run.ref_image = last_good_run.image
current_run.ref_log = last_good_run.log
current_run.ref_config = last_good_run.config
db.session.add(current_run)
db.session.commit()
signals.run_updated_via_api.send(
app, build=build, release=current_release, run=current_run)
return flask.jsonify(
success=True,
build_id=build.id,
release_name=current_release.name,
release_number=current_release.number,
run_name=current_run.name,
url=current_run.url,
config=current_run.config,
ref_url=current_run.ref_url,
ref_config=current_run.ref_config) | [
"def",
"request_run",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"current_release",
",",
"current_run",
"=",
"_get_or_create_run",
"(",
"build",
")",
"current_url",
"=",
"request",
".",
"form",
".",
"get",
"(",
"'url'",
",",
"type",
"=",
"str",
")",... | Requests a new run for a release candidate. | [
"Requests",
"a",
"new",
"run",
"for",
"a",
"release",
"candidate",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L350-L396 |
18,623 | 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')
.first())
utils.jsonify_assert(release, 'Release does not exist')
release.status = models.Release.PROCESSING
db.session.add(release)
_check_release_done_processing(release)
db.session.commit()
signals.release_updated_via_api.send(app, build=build, release=release)
logging.info('Runs done for release: build_id=%r, release_name=%r, '
'release_number=%d', build.id, release.name, release.number)
results_url = url_for(
'view_release',
id=build.id,
name=release.name,
number=release.number,
_external=True)
return flask.jsonify(
success=True,
results_url=results_url) | python | def runs_done():
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')
.first())
utils.jsonify_assert(release, 'Release does not exist')
release.status = models.Release.PROCESSING
db.session.add(release)
_check_release_done_processing(release)
db.session.commit()
signals.release_updated_via_api.send(app, build=build, release=release)
logging.info('Runs done for release: build_id=%r, release_name=%r, '
'release_number=%d', build.id, release.name, release.number)
results_url = url_for(
'view_release',
id=build.id,
name=release.name,
number=release.number,
_external=True)
return flask.jsonify(
success=True,
results_url=results_url) | [
"def",
"runs_done",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"release_name",
",",
"release_number",
"=",
"_get_release_params",
"(",
")",
"release",
"=",
"(",
"models",
".",
"Release",
".",
"query",
".",
"filter_by",
"(",
"build_id",
"=",
"build",
... | Marks a release candidate as having all runs reported. | [
"Marks",
"a",
"release",
"candidate",
"as",
"having",
"all",
"runs",
"reported",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L531-L562 |
18,624 | 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:
logging.info('Upload received: artifact_id=%r, content_type=%r',
sha1sum, content_type)
artifact = models.Artifact(
id=sha1sum,
content_type=content_type,
data=data)
_artifact_created(artifact)
artifact.owners.append(build)
return artifact | python | def _save_artifact(build, data, content_type):
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:
logging.info('Upload received: artifact_id=%r, content_type=%r',
sha1sum, content_type)
artifact = models.Artifact(
id=sha1sum,
content_type=content_type,
data=data)
_artifact_created(artifact)
artifact.owners.append(build)
return artifact | [
"def",
"_save_artifact",
"(",
"build",
",",
"data",
",",
"content_type",
")",
":",
"sha1sum",
"=",
"hashlib",
".",
"sha1",
"(",
"data",
")",
".",
"hexdigest",
"(",
")",
"artifact",
"=",
"models",
".",
"Artifact",
".",
"query",
".",
"filter_by",
"(",
"i... | Saves an artifact to the DB and returns it. | [
"Saves",
"an",
"artifact",
"to",
"the",
"DB",
"and",
"returns",
"it",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L575-L592 |
18,625 | 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_storage.filename)
artifact = _save_artifact(build, data, content_type)
db.session.add(artifact)
db.session.commit()
return flask.jsonify(
success=True,
build_id=build.id,
sha1sum=artifact.id,
content_type=content_type) | python | def upload():
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_storage.filename)
artifact = _save_artifact(build, data, content_type)
db.session.add(artifact)
db.session.commit()
return flask.jsonify(
success=True,
build_id=build.id,
sha1sum=artifact.id,
content_type=content_type) | [
"def",
"upload",
"(",
")",
":",
"build",
"=",
"g",
".",
"build",
"utils",
".",
"jsonify_assert",
"(",
"len",
"(",
"request",
".",
"files",
")",
"==",
"1",
",",
"'Need exactly one uploaded file'",
")",
"file_storage",
"=",
"request",
".",
"files",
".",
"v... | Uploads an artifact referenced by a run. | [
"Uploads",
"an",
"artifact",
"referenced",
"by",
"a",
"run",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L598-L617 |
18,626 | 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_type)
response.cache_control.public = True
response.cache_control.max_age = 8640000
response.set_etag(artifact.id)
return response | python | def _get_artifact_response(artifact):
response = flask.Response(
artifact.data,
mimetype=artifact.content_type)
response.cache_control.public = True
response.cache_control.max_age = 8640000
response.set_etag(artifact.id)
return response | [
"def",
"_get_artifact_response",
"(",
"artifact",
")",
":",
"response",
"=",
"flask",
".",
"Response",
"(",
"artifact",
".",
"data",
",",
"mimetype",
"=",
"artifact",
".",
"content_type",
")",
"response",
".",
"cache_control",
".",
"public",
"=",
"True",
"re... | 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. | [
"Gets",
"the",
"response",
"object",
"for",
"the",
"given",
"artifact",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L620-L632 |
18,627 | 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:
logging.debug('User access to artifact failed. Trying API key.')
_, build = auth.can_api_key_access_build('build_id')
sha1sum = request.args.get('sha1sum', type=str)
if not sha1sum:
logging.debug('Artifact sha1sum=%r not supplied', sha1sum)
abort(404)
artifact = models.Artifact.query.get(sha1sum)
if not artifact:
logging.debug('Artifact sha1sum=%r does not exist', sha1sum)
abort(404)
build_id = request.args.get('build_id', type=int)
if not build_id:
logging.debug('build_id missing for artifact sha1sum=%r', sha1sum)
abort(404)
is_owned = artifact.owners.filter_by(id=build_id).first()
if not is_owned:
logging.debug('build_id=%r not owner of artifact sha1sum=%r',
build_id, sha1sum)
abort(403)
# Make sure there are no Set-Cookie headers on the response so this
# request is cachable by all HTTP frontends.
@utils.after_this_request
def no_session(response):
if 'Set-Cookie' in response.headers:
del response.headers['Set-Cookie']
if not utils.is_production():
# Insert a sleep to emulate how the page loading looks in production.
time.sleep(1.5)
if request.if_none_match and request.if_none_match.contains(sha1sum):
response = flask.Response(status=304)
return response
return _get_artifact_response(artifact) | python | def download():
# 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:
logging.debug('User access to artifact failed. Trying API key.')
_, build = auth.can_api_key_access_build('build_id')
sha1sum = request.args.get('sha1sum', type=str)
if not sha1sum:
logging.debug('Artifact sha1sum=%r not supplied', sha1sum)
abort(404)
artifact = models.Artifact.query.get(sha1sum)
if not artifact:
logging.debug('Artifact sha1sum=%r does not exist', sha1sum)
abort(404)
build_id = request.args.get('build_id', type=int)
if not build_id:
logging.debug('build_id missing for artifact sha1sum=%r', sha1sum)
abort(404)
is_owned = artifact.owners.filter_by(id=build_id).first()
if not is_owned:
logging.debug('build_id=%r not owner of artifact sha1sum=%r',
build_id, sha1sum)
abort(403)
# Make sure there are no Set-Cookie headers on the response so this
# request is cachable by all HTTP frontends.
@utils.after_this_request
def no_session(response):
if 'Set-Cookie' in response.headers:
del response.headers['Set-Cookie']
if not utils.is_production():
# Insert a sleep to emulate how the page loading looks in production.
time.sleep(1.5)
if request.if_none_match and request.if_none_match.contains(sha1sum):
response = flask.Response(status=304)
return response
return _get_artifact_response(artifact) | [
"def",
"download",
"(",
")",
":",
"# 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",
"... | Downloads an artifact by it's content hash. | [
"Downloads",
"an",
"artifact",
"by",
"it",
"s",
"content",
"hash",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/api.py#L636-L682 |
18,628 | 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.
self.versioned_cache_key = None | python | def evict(self):
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.
self.versioned_cache_key = None | [
"def",
"evict",
"(",
"self",
")",
":",
"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 ... | Evict all caches related to these operations. | [
"Evict",
"all",
"caches",
"related",
"to",
"these",
"operations",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/operations.py#L72-L78 |
18,629 | 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_STATES:
return (0, run.name)
return (1, run.name) | python | def sort_run(run):
# 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_STATES:
return (0, run.name)
return (1, run.name) | [
"def",
"sort_run",
"(",
"run",
")",
":",
"# 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",
".... | Sort function for runs within a release. | [
"Sort",
"function",
"for",
"runs",
"within",
"a",
"release",
"."
] | 9f860de1731021d99253670429e5f2157e1f6297 | https://github.com/bslatkin/dpxdt/blob/9f860de1731021d99253670429e5f2157e1f6297/dpxdt/server/operations.py#L170-L177 |
18,630 | 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:`Validator` subclass, instantiate it without arguments and
return it.
- :py:attr:`~Validator.name` of a known :py:class:`Validator` subclass,
instantiate the subclass without arguments and return it.
- otherwise find the first registered :py:class:`Validator` factory that
can create it. The search order is the reverse of the factory registration
order. The caller is responsible for ensuring there are no ambiguous
values that can be parsed by more than one factory.
:param required_properties: Specifies for this parse call whether parsed
:py:class:`~valideer.validators.Object` properties are required or
optional by default. It can be:
- ``True`` for required.
- ``False`` for optional.
- ``None`` to use the value of the
:py:attr:`~valideer.validators.Object.REQUIRED_PROPERTIES` attribute.
:param additional_properties: Specifies for this parse call the schema of
all :py:class:`~valideer.validators.Object` properties that are not
explicitly defined as optional or required. It can also be:
- ``True`` to allow any value for additional properties.
- ``False`` to disallow any additional properties.
- :py:attr:`~valideer.validators.Object.REMOVE` to remove any additional
properties from the adapted object.
- ``None`` to use the value of the
:py:attr:`~valideer.validators.Object.ADDITIONAL_PROPERTIES` attribute.
:param ignore_optional_property_errors: Determines if invalid optional
properties are ignored:
- ``True`` to ignore invalid optional properties.
- ``False`` to raise ValidationError for invalid optional properties.
- ``None`` to use the value of the
:py:attr:`~valideer.validators.Object.IGNORE_OPTIONAL_PROPERTY_ERRORS`
attribute.
:raises SchemaError: If no appropriate validator could be found.
.. warning:: Passing ``required_properties`` and/or ``additional_properties``
with value other than ``None`` may be non intuitive for schemas that
involve nested validators. Take for example the following schema::
v = V.parse({
"x": "integer",
"child": V.Nullable({
"y": "integer"
})
}, required_properties=True)
Here the top-level properties 'x' and 'child' are required but the nested
'y' property is not. This is because by the time :py:meth:`parse` is called,
:py:class:`~valideer.validators.Nullable` has already parsed its argument
with the default value of ``required_properties``. Several other builtin
validators work similarly to :py:class:`~valideer.validators.Nullable`,
accepting one or more schemas to parse. In order to parse an arbitrarily
complex nested validator with the same value for ``required_properties``
and/or ``additional_properties``, use the :py:func:`parsing` context
manager instead::
with V.parsing(required_properties=True):
v = V.parse({
"x": "integer",
"child": V.Nullable({
"y": "integer"
})
})
"""
if not (required_properties is
additional_properties is
ignore_optional_property_errors is None):
with parsing(required_properties=required_properties,
additional_properties=additional_properties,
ignore_optional_property_errors=ignore_optional_property_errors):
return parse(obj)
validator = None
if isinstance(obj, Validator):
validator = obj
elif inspect.isclass(obj) and issubclass(obj, Validator):
validator = obj()
else:
try:
validator = _NAMED_VALIDATORS[obj]
except (KeyError, TypeError):
for factory in _VALIDATOR_FACTORIES:
validator = factory(obj)
if validator is not None:
break
else:
if inspect.isclass(validator) and issubclass(validator, Validator):
_NAMED_VALIDATORS[obj] = validator = validator()
if not isinstance(validator, Validator):
raise SchemaError("%r cannot be parsed as a Validator" % obj)
return validator | python | def parse(obj, required_properties=None, additional_properties=None,
ignore_optional_property_errors=None):
if not (required_properties is
additional_properties is
ignore_optional_property_errors is None):
with parsing(required_properties=required_properties,
additional_properties=additional_properties,
ignore_optional_property_errors=ignore_optional_property_errors):
return parse(obj)
validator = None
if isinstance(obj, Validator):
validator = obj
elif inspect.isclass(obj) and issubclass(obj, Validator):
validator = obj()
else:
try:
validator = _NAMED_VALIDATORS[obj]
except (KeyError, TypeError):
for factory in _VALIDATOR_FACTORIES:
validator = factory(obj)
if validator is not None:
break
else:
if inspect.isclass(validator) and issubclass(validator, Validator):
_NAMED_VALIDATORS[obj] = validator = validator()
if not isinstance(validator, Validator):
raise SchemaError("%r cannot be parsed as a Validator" % obj)
return validator | [
"def",
"parse",
"(",
"obj",
",",
"required_properties",
"=",
"None",
",",
"additional_properties",
"=",
"None",
",",
"ignore_optional_property_errors",
"=",
"None",
")",
":",
"if",
"not",
"(",
"required_properties",
"is",
"additional_properties",
"is",
"ignore_optio... | 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:class:`Validator` subclass,
instantiate the subclass without arguments and return it.
- otherwise find the first registered :py:class:`Validator` factory that
can create it. The search order is the reverse of the factory registration
order. The caller is responsible for ensuring there are no ambiguous
values that can be parsed by more than one factory.
:param required_properties: Specifies for this parse call whether parsed
:py:class:`~valideer.validators.Object` properties are required or
optional by default. It can be:
- ``True`` for required.
- ``False`` for optional.
- ``None`` to use the value of the
:py:attr:`~valideer.validators.Object.REQUIRED_PROPERTIES` attribute.
:param additional_properties: Specifies for this parse call the schema of
all :py:class:`~valideer.validators.Object` properties that are not
explicitly defined as optional or required. It can also be:
- ``True`` to allow any value for additional properties.
- ``False`` to disallow any additional properties.
- :py:attr:`~valideer.validators.Object.REMOVE` to remove any additional
properties from the adapted object.
- ``None`` to use the value of the
:py:attr:`~valideer.validators.Object.ADDITIONAL_PROPERTIES` attribute.
:param ignore_optional_property_errors: Determines if invalid optional
properties are ignored:
- ``True`` to ignore invalid optional properties.
- ``False`` to raise ValidationError for invalid optional properties.
- ``None`` to use the value of the
:py:attr:`~valideer.validators.Object.IGNORE_OPTIONAL_PROPERTY_ERRORS`
attribute.
:raises SchemaError: If no appropriate validator could be found.
.. warning:: Passing ``required_properties`` and/or ``additional_properties``
with value other than ``None`` may be non intuitive for schemas that
involve nested validators. Take for example the following schema::
v = V.parse({
"x": "integer",
"child": V.Nullable({
"y": "integer"
})
}, required_properties=True)
Here the top-level properties 'x' and 'child' are required but the nested
'y' property is not. This is because by the time :py:meth:`parse` is called,
:py:class:`~valideer.validators.Nullable` has already parsed its argument
with the default value of ``required_properties``. Several other builtin
validators work similarly to :py:class:`~valideer.validators.Nullable`,
accepting one or more schemas to parse. In order to parse an arbitrarily
complex nested validator with the same value for ``required_properties``
and/or ``additional_properties``, use the :py:func:`parsing` context
manager instead::
with V.parsing(required_properties=True):
v = V.parse({
"x": "integer",
"child": V.Nullable({
"y": "integer"
})
}) | [
"Try",
"to",
"parse",
"the",
"given",
"obj",
"as",
"a",
"validator",
"instance",
"."
] | d35be173cb40c9fa1adb879673786b346b6841db | https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L60-L165 |
18,631 | 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:
attr = key.upper()
old_values[key] = getattr(Object, attr)
setattr(Object, attr, value)
try:
yield
finally:
for key, value in iteritems(kwargs):
if value is not None:
setattr(Object, key.upper(), old_values[key]) | python | def parsing(**kwargs):
from .validators import Object
with _VALIDATOR_FACTORIES_LOCK:
old_values = {}
for key, value in iteritems(kwargs):
if value is not None:
attr = key.upper()
old_values[key] = getattr(Object, attr)
setattr(Object, attr, value)
try:
yield
finally:
for key, value in iteritems(kwargs):
if value is not None:
setattr(Object, key.upper(), old_values[key]) | [
"def",
"parsing",
"(",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"validators",
"import",
"Object",
"with",
"_VALIDATOR_FACTORIES_LOCK",
":",
"old_values",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"kwargs",
")",
":",
"if",
"valu... | Context manager for overriding the default validator parsing rules for the
following code block. | [
"Context",
"manager",
"for",
"overriding",
"the",
"default",
"validator",
"parsing",
"rules",
"for",
"the",
"following",
"code",
"block",
"."
] | d35be173cb40c9fa1adb879673786b346b6841db | https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L169-L188 |
18,632 | 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):
if not isinstance(validator, Validator):
raise TypeError("Validator instance expected, %s given" % validator.__class__)
_NAMED_VALIDATORS[name] = validator | [
"def",
"register",
"(",
"name",
",",
"validator",
")",
":",
"if",
"not",
"isinstance",
"(",
"validator",
",",
"Validator",
")",
":",
"raise",
"TypeError",
"(",
"\"Validator instance expected, %s given\"",
"%",
"validator",
".",
"__class__",
")",
"_NAMED_VALIDATORS... | Register a validator instance under the given ``name``. | [
"Register",
"a",
"validator",
"instance",
"under",
"the",
"given",
"name",
"."
] | d35be173cb40c9fa1adb879673786b346b6841db | https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L191-L195 |
18,633 | 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 parameter.
"""
validate = parse(schemas).validate
@decorator
def validating(func, *args, **kwargs):
validate(inspect.getcallargs(func, *args, **kwargs), adapt=False)
return func(*args, **kwargs)
return validating | python | def accepts(**schemas):
validate = parse(schemas).validate
@decorator
def validating(func, *args, **kwargs):
validate(inspect.getcallargs(func, *args, **kwargs), adapt=False)
return func(*args, **kwargs)
return validating | [
"def",
"accepts",
"(",
"*",
"*",
"schemas",
")",
":",
"validate",
"=",
"parse",
"(",
"schemas",
")",
".",
"validate",
"@",
"decorator",
"def",
"validating",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"validate",
"(",
"inspect",... | 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. | [
"Create",
"a",
"decorator",
"for",
"validating",
"function",
"parameters",
"."
] | d35be173cb40c9fa1adb879673786b346b6841db | https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L272-L289 |
18,634 | 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
@decorator
def validating(func, *args, **kwargs):
ret = func(*args, **kwargs)
validate(ret, adapt=False)
return ret
return validating | python | def returns(schema):
validate = parse(schema).validate
@decorator
def validating(func, *args, **kwargs):
ret = func(*args, **kwargs)
validate(ret, adapt=False)
return ret
return validating | [
"def",
"returns",
"(",
"schema",
")",
":",
"validate",
"=",
"parse",
"(",
"schema",
")",
".",
"validate",
"@",
"decorator",
"def",
"validating",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"args",... | 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. | [
"Create",
"a",
"decorator",
"for",
"validating",
"function",
"return",
"value",
"."
] | d35be173cb40c9fa1adb879673786b346b6841db | https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L292-L310 |
18,635 | 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 given parameter.
"""
validate = parse(schemas).validate
@decorator
def adapting(func, *args, **kwargs):
adapted = validate(inspect.getcallargs(func, *args, **kwargs), adapt=True)
argspec = inspect.getargspec(func)
if argspec.varargs is argspec.keywords is None:
# optimization for the common no varargs, no keywords case
return func(**adapted)
adapted_varargs = adapted.pop(argspec.varargs, ())
adapted_keywords = adapted.pop(argspec.keywords, {})
if not adapted_varargs: # keywords only
if adapted_keywords:
adapted.update(adapted_keywords)
return func(**adapted)
adapted_posargs = [adapted[arg] for arg in argspec.args]
adapted_posargs.extend(adapted_varargs)
return func(*adapted_posargs, **adapted_keywords)
return adapting | python | def adapts(**schemas):
validate = parse(schemas).validate
@decorator
def adapting(func, *args, **kwargs):
adapted = validate(inspect.getcallargs(func, *args, **kwargs), adapt=True)
argspec = inspect.getargspec(func)
if argspec.varargs is argspec.keywords is None:
# optimization for the common no varargs, no keywords case
return func(**adapted)
adapted_varargs = adapted.pop(argspec.varargs, ())
adapted_keywords = adapted.pop(argspec.keywords, {})
if not adapted_varargs: # keywords only
if adapted_keywords:
adapted.update(adapted_keywords)
return func(**adapted)
adapted_posargs = [adapted[arg] for arg in argspec.args]
adapted_posargs.extend(adapted_varargs)
return func(*adapted_posargs, **adapted_keywords)
return adapting | [
"def",
"adapts",
"(",
"*",
"*",
"schemas",
")",
":",
"validate",
"=",
"parse",
"(",
"schemas",
")",
".",
"validate",
"@",
"decorator",
"def",
"adapting",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"adapted",
"=",
"validate",
... | 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. | [
"Create",
"a",
"decorator",
"for",
"validating",
"and",
"adapting",
"function",
"parameters",
"."
] | d35be173cb40c9fa1adb879673786b346b6841db | https://github.com/podio/valideer/blob/d35be173cb40c9fa1adb879673786b346b6841db/valideer/base.py#L313-L346 |
18,636 | 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_value in self._checksums.items()} | python | def get_checksum_metadata_tag(self):
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_value in self._checksums.items()} | [
"def",
"get_checksum_metadata_tag",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_checksums",
":",
"print",
"(",
"\"Warning: No checksums have been computed for this file.\"",
")",
"return",
"{",
"str",
"(",
"_hash_name",
")",
":",
"str",
"(",
"_hash_value",
... | Returns a map of checksum values by the name of the hashing function that produced it. | [
"Returns",
"a",
"map",
"of",
"checksum",
"values",
"by",
"the",
"name",
"of",
"the",
"hashing",
"function",
"that",
"produced",
"it",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/client_side_checksum_handler.py#L20-L24 |
18,637 | 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.ChecksumCalculator(self._filename)
self._checksums = checksumCalculator.compute() | python | def compute_checksum(self):
if self._filename.startswith("s3://"):
print("Warning: Did not perform client-side checksumming for file in S3. To be implemented.")
pass
else:
checksumCalculator = self.ChecksumCalculator(self._filename)
self._checksums = checksumCalculator.compute() | [
"def",
"compute_checksum",
"(",
"self",
")",
":",
"if",
"self",
".",
"_filename",
".",
"startswith",
"(",
"\"s3://\"",
")",
":",
"print",
"(",
"\"Warning: Did not perform client-side checksumming for file in S3. To be implemented.\"",
")",
"pass",
"else",
":",
"checksum... | Calculates checksums for a given file. | [
"Calculates",
"checksums",
"for",
"a",
"given",
"file",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/client_side_checksum_handler.py#L26-L33 |
18,638 | 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._setup_s3_agent_for_file_upload(file_count=len(file_paths),
file_size_sum=file_size_sum,
use_transfer_acceleration=use_transfer_acceleration)
pool = ThreadPool()
if report_progress:
print("\nStarting upload of %s files to upload area %s" % (len(file_paths), self.uuid))
for file_path in file_paths:
pool.add_task(self._upload_file, file_path,
target_filename=target_filename,
use_transfer_acceleration=use_transfer_acceleration,
report_progress=report_progress,
sync=sync)
pool.wait_for_completion()
if report_progress:
number_of_errors = len(self.s3agent.failed_uploads)
if number_of_errors == 0:
print(
"Completed upload of %d files to upload area %s\n" %
(self.s3agent.file_upload_completed_count, self.uuid))
else:
error = "\nThe following files failed:"
for k, v in self.s3agent.failed_uploads.items():
error += "\n%s: [Exception] %s" % (k, v)
error += "\nPlease retry or contact an hca administrator at data-help@humancellatlas.org for help.\n"
raise UploadException(error) | 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):
self._setup_s3_agent_for_file_upload(file_count=len(file_paths),
file_size_sum=file_size_sum,
use_transfer_acceleration=use_transfer_acceleration)
pool = ThreadPool()
if report_progress:
print("\nStarting upload of %s files to upload area %s" % (len(file_paths), self.uuid))
for file_path in file_paths:
pool.add_task(self._upload_file, file_path,
target_filename=target_filename,
use_transfer_acceleration=use_transfer_acceleration,
report_progress=report_progress,
sync=sync)
pool.wait_for_completion()
if report_progress:
number_of_errors = len(self.s3agent.failed_uploads)
if number_of_errors == 0:
print(
"Completed upload of %d files to upload area %s\n" %
(self.s3agent.file_upload_completed_count, self.uuid))
else:
error = "\nThe following files failed:"
for k, v in self.s3agent.failed_uploads.items():
error += "\n%s: [Exception] %s" % (k, v)
error += "\nPlease retry or contact an hca administrator at data-help@humancellatlas.org for help.\n"
raise UploadException(error) | [
"def",
"upload_files",
"(",
"self",
",",
"file_paths",
",",
"file_size_sum",
"=",
"0",
",",
"dcp_type",
"=",
"\"data\"",
",",
"target_filename",
"=",
"None",
",",
"use_transfer_acceleration",
"=",
"True",
",",
"report_progress",
"=",
"False",
",",
"sync",
"=",... | A function that takes in a list of file paths and other optional args for parallel file upload | [
"A",
"function",
"that",
"takes",
"in",
"a",
"list",
"of",
"file",
"paths",
"and",
"other",
"optional",
"args",
"for",
"parallel",
"file",
"upload"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L109-L138 |
18,639 | 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 could not be obtained
"""
return self.upload_service.api_client.validation_status(area_uuid=self.uuid, filename=filename) | python | def validation_status(self, filename):
return self.upload_service.api_client.validation_status(area_uuid=self.uuid, filename=filename) | [
"def",
"validation_status",
"(",
"self",
",",
"filename",
")",
":",
"return",
"self",
".",
"upload_service",
".",
"api_client",
".",
"validation_status",
"(",
"area_uuid",
"=",
"self",
".",
"uuid",
",",
"filename",
"=",
"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 could not be obtained | [
"Get",
"status",
"and",
"results",
"of",
"latest",
"validation",
"job",
"for",
"a",
"file",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_area.py#L181-L190 |
18,640 | 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)
if obj and obj.containsKey('Metadata'):
if obj['Metadata'] == checksums:
return True
except ClientError:
# An exception from calling `head_object` indicates that no file with the specified name could be found
# in the specified bucket.
return False | python | def _item_exists_in_bucket(self, bucket, key, checksums):
try:
obj = self.target_s3.meta.client.head_object(Bucket=bucket, Key=key)
if obj and obj.containsKey('Metadata'):
if obj['Metadata'] == checksums:
return True
except ClientError:
# An exception from calling `head_object` indicates that no file with the specified name could be found
# in the specified bucket.
return False | [
"def",
"_item_exists_in_bucket",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"checksums",
")",
":",
"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. | [
"Returns",
"true",
"if",
"the",
"key",
"already",
"exists",
"in",
"the",
"current",
"bucket",
"and",
"the",
"clientside",
"checksum",
"matches",
"the",
"file",
"s",
"checksums",
"and",
"false",
"otherwise",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/s3_agent.py#L130-L141 |
18,641 | 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.
:param staging_bucket: The aws bucket to upload the files to.
:param replica: The cloud replica to write to. One of 'aws', 'gc', or 'azure'. No functionality now.
:return: a list of file uuids, key-names, and absolute file paths (local) for uploaded files
"""
s3 = boto3.resource("s3")
file_uuids = []
key_names = []
abs_file_paths = []
if from_cloud:
file_uuids, key_names = _copy_from_s3(file_handles[0], s3)
else:
destination_bucket = s3.Bucket(staging_bucket)
for raw_fh in file_handles:
file_size = os.path.getsize(raw_fh.name)
multipart_chunksize = s3_multipart.get_s3_multipart_chunk_size(file_size)
tx_cfg = TransferConfig(multipart_threshold=s3_multipart.MULTIPART_THRESHOLD,
multipart_chunksize=multipart_chunksize)
with ChecksummingBufferedReader(raw_fh, multipart_chunksize) as fh:
file_uuid = str(uuid.uuid4())
key_name = "{}/{}".format(file_uuid, os.path.basename(fh.raw.name))
destination_bucket.upload_fileobj(
fh,
key_name,
Config=tx_cfg,
ExtraArgs={
'ContentType': _mime_type(fh.raw.name),
}
)
sums = fh.get_checksums()
metadata = {
"hca-dss-s3_etag": sums["s3_etag"],
"hca-dss-sha1": sums["sha1"],
"hca-dss-sha256": sums["sha256"],
"hca-dss-crc32c": sums["crc32c"],
}
s3.meta.client.put_object_tagging(Bucket=destination_bucket.name,
Key=key_name,
Tagging=dict(TagSet=encode_tags(metadata)))
file_uuids.append(file_uuid)
key_names.append(key_name)
abs_file_paths.append(fh.raw.name)
return file_uuids, key_names, abs_file_paths | python | def upload_to_cloud(file_handles, staging_bucket, replica, from_cloud=False):
s3 = boto3.resource("s3")
file_uuids = []
key_names = []
abs_file_paths = []
if from_cloud:
file_uuids, key_names = _copy_from_s3(file_handles[0], s3)
else:
destination_bucket = s3.Bucket(staging_bucket)
for raw_fh in file_handles:
file_size = os.path.getsize(raw_fh.name)
multipart_chunksize = s3_multipart.get_s3_multipart_chunk_size(file_size)
tx_cfg = TransferConfig(multipart_threshold=s3_multipart.MULTIPART_THRESHOLD,
multipart_chunksize=multipart_chunksize)
with ChecksummingBufferedReader(raw_fh, multipart_chunksize) as fh:
file_uuid = str(uuid.uuid4())
key_name = "{}/{}".format(file_uuid, os.path.basename(fh.raw.name))
destination_bucket.upload_fileobj(
fh,
key_name,
Config=tx_cfg,
ExtraArgs={
'ContentType': _mime_type(fh.raw.name),
}
)
sums = fh.get_checksums()
metadata = {
"hca-dss-s3_etag": sums["s3_etag"],
"hca-dss-sha1": sums["sha1"],
"hca-dss-sha256": sums["sha256"],
"hca-dss-crc32c": sums["crc32c"],
}
s3.meta.client.put_object_tagging(Bucket=destination_bucket.name,
Key=key_name,
Tagging=dict(TagSet=encode_tags(metadata)))
file_uuids.append(file_uuid)
key_names.append(key_name)
abs_file_paths.append(fh.raw.name)
return file_uuids, key_names, abs_file_paths | [
"def",
"upload_to_cloud",
"(",
"file_handles",
",",
"staging_bucket",
",",
"replica",
",",
"from_cloud",
"=",
"False",
")",
":",
"s3",
"=",
"boto3",
".",
"resource",
"(",
"\"s3\"",
")",
"file_uuids",
"=",
"[",
"]",
"key_names",
"=",
"[",
"]",
"abs_file_pat... | 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 replica to write to. One of 'aws', 'gc', or 'azure'. No functionality now.
:return: a list of file uuids, key-names, and absolute file paths (local) for uploaded files | [
"Upload",
"files",
"to",
"cloud",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/upload_to_cloud.py#L53-L102 |
18,642 | 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 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]
:param str version: The version to download, else if not specified, download the latest. The version is a
timestamp of bundle creation in RFC3339
:param str dest_name: The destination file path for the download
:param iterable metadata_files: one or more shell patterns against which all metadata files in the bundle will be
matched case-sensitively. A file is considered a metadata file if the `indexed` property in the manifest is
set. If and only if a metadata file matches any of the patterns in `metadata_files` will it be downloaded.
:param iterable data_files: one or more shell patterns against which all data files in the bundle will be matched
case-sensitively. A file is considered a data file if the `indexed` property in the manifest is not set. The
file will be downloaded only if a data file matches any of the patterns in `data_files` will it be
downloaded.
:param int num_retries: The initial quota of download failures to accept before exiting due to
failures. The number of retries increase and decrease as file chucks succeed and fail.
:param float min_delay_seconds: The minimum number of seconds to wait in between retries.
Download a bundle and save it to the local filesystem as a directory.
By default, all data and metadata files are downloaded. To disable the downloading of data files,
use `--data-files ''` if using the CLI (or `data_files=()` if invoking `download` programmatically).
Likewise for metadata files.
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.
"""
errors = 0
with concurrent.futures.ThreadPoolExecutor(self.threads) as executor:
futures_to_dss_file = {executor.submit(task): dss_file
for dss_file, task in self._download_tasks(bundle_uuid,
replica,
version,
download_dir,
metadata_files,
data_files,
num_retries,
min_delay_seconds)}
for future in concurrent.futures.as_completed(futures_to_dss_file):
dss_file = futures_to_dss_file[future]
try:
future.result()
except Exception as e:
errors += 1
logger.warning('Failed to download file %s version %s from replica %s',
dss_file.uuid, dss_file.version, dss_file.replica, exc_info=e)
if errors:
raise RuntimeError('{} file(s) failed to download'.format(errors)) | python | def download(self, bundle_uuid, replica, version="", download_dir="",
metadata_files=('*',), data_files=('*',),
num_retries=10, min_delay_seconds=0.25):
errors = 0
with concurrent.futures.ThreadPoolExecutor(self.threads) as executor:
futures_to_dss_file = {executor.submit(task): dss_file
for dss_file, task in self._download_tasks(bundle_uuid,
replica,
version,
download_dir,
metadata_files,
data_files,
num_retries,
min_delay_seconds)}
for future in concurrent.futures.as_completed(futures_to_dss_file):
dss_file = futures_to_dss_file[future]
try:
future.result()
except Exception as e:
errors += 1
logger.warning('Failed to download file %s version %s from replica %s',
dss_file.uuid, dss_file.version, dss_file.replica, exc_info=e)
if errors:
raise RuntimeError('{} file(s) failed to download'.format(errors)) | [
"def",
"download",
"(",
"self",
",",
"bundle_uuid",
",",
"replica",
",",
"version",
"=",
"\"\"",
",",
"download_dir",
"=",
"\"\"",
",",
"metadata_files",
"=",
"(",
"'*'",
",",
")",
",",
"data_files",
"=",
"(",
"'*'",
",",
")",
",",
"num_retries",
"=",
... | 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]
:param str version: The version to download, else if not specified, download the latest. The version is a
timestamp of bundle creation in RFC3339
:param str dest_name: The destination file path for the download
:param iterable metadata_files: one or more shell patterns against which all metadata files in the bundle will be
matched case-sensitively. A file is considered a metadata file if the `indexed` property in the manifest is
set. If and only if a metadata file matches any of the patterns in `metadata_files` will it be downloaded.
:param iterable data_files: one or more shell patterns against which all data files in the bundle will be matched
case-sensitively. A file is considered a data file if the `indexed` property in the manifest is not set. The
file will be downloaded only if a data file matches any of the patterns in `data_files` will it be
downloaded.
:param int num_retries: The initial quota of download failures to accept before exiting due to
failures. The number of retries increase and decrease as file chucks succeed and fail.
:param float min_delay_seconds: The minimum number of seconds to wait in between retries.
Download a bundle and save it to the local filesystem as a directory.
By default, all data and metadata files are downloaded. To disable the downloading of data files,
use `--data-files ''` if using the CLI (or `data_files=()` if invoking `download` programmatically).
Likewise for metadata files.
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. | [
"Download",
"a",
"bundle",
"and",
"save",
"it",
"to",
"the",
"local",
"filesystem",
"as",
"a",
"directory",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L87-L140 |
18,643 | 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 for the
number of failures that goes up with every successful block read and down with each failure.
If we can, we will attempt HTTP resume. However, we verify that the server supports HTTP resume. If the
ranged get doesn't yield the correct header, then we start over.
"""
directory, _ = os.path.split(dest_path)
if directory:
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
with atomic_write(dest_path, mode="wb", overwrite=True) as fh:
if dss_file.size == 0:
return
download_hash = self._do_download_file(dss_file, fh, num_retries, min_delay_seconds)
if download_hash.lower() != dss_file.sha256.lower():
# No need to delete what's been written. atomic_write ensures we're cleaned up
logger.error("%s", "File {}: GET FAILED. Checksum mismatch.".format(dss_file.uuid))
raise ValueError("Expected sha256 {} Received sha256 {}".format(
dss_file.sha256.lower(), download_hash.lower())) | python | def _download_file(self, dss_file, dest_path, num_retries=10, min_delay_seconds=0.25):
directory, _ = os.path.split(dest_path)
if directory:
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise
with atomic_write(dest_path, mode="wb", overwrite=True) as fh:
if dss_file.size == 0:
return
download_hash = self._do_download_file(dss_file, fh, num_retries, min_delay_seconds)
if download_hash.lower() != dss_file.sha256.lower():
# No need to delete what's been written. atomic_write ensures we're cleaned up
logger.error("%s", "File {}: GET FAILED. Checksum mismatch.".format(dss_file.uuid))
raise ValueError("Expected sha256 {} Received sha256 {}".format(
dss_file.sha256.lower(), download_hash.lower())) | [
"def",
"_download_file",
"(",
"self",
",",
"dss_file",
",",
"dest_path",
",",
"num_retries",
"=",
"10",
",",
"min_delay_seconds",
"=",
"0.25",
")",
":",
"directory",
",",
"_",
"=",
"os",
".",
"path",
".",
"split",
"(",
"dest_path",
")",
"if",
"directory"... | 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.
If we can, we will attempt HTTP resume. However, we verify that the server supports HTTP resume. If the
ranged get doesn't yield the correct header, then we start over. | [
"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",
"... | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L211-L237 |
18,644 | 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
while True:
try:
response = self.get_file._request(
dict(uuid=dss_file.uuid, version=dss_file.version, replica=dss_file.replica),
stream=True,
headers={
'Range': "bytes={}-".format(fh.tell())
},
)
try:
if not response.ok:
logger.error("%s", "File {}: GET FAILED.".format(dss_file.uuid))
logger.error("%s", "Response: {}".format(response.text))
break
consume_bytes = int(fh.tell())
server_start = 0
content_range_header = response.headers.get('Content-Range', None)
if content_range_header is not None:
cre = re.compile("bytes (\d+)-(\d+)")
mo = cre.search(content_range_header)
if mo is not None:
server_start = int(mo.group(1))
consume_bytes -= server_start
assert consume_bytes >= 0
if server_start > 0 and consume_bytes == 0:
logger.info("%s", "File {}: Resuming at {}.".format(
dss_file.uuid, server_start))
elif consume_bytes > 0:
logger.info("%s", "File {}: Resuming at {}. Dropping {} bytes to match".format(
dss_file.uuid, server_start, consume_bytes))
while consume_bytes > 0:
bytes_to_read = min(consume_bytes, 1024*1024)
content = response.iter_content(chunk_size=bytes_to_read)
chunk = next(content)
if chunk:
consume_bytes -= len(chunk)
for chunk in response.iter_content(chunk_size=1024*1024):
if chunk:
fh.write(chunk)
hasher.update(chunk)
retries_left = min(retries_left + 1, num_retries)
delay = max(delay / 2, min_delay_seconds)
break
finally:
response.close()
except (ChunkedEncodingError, ConnectionError, ReadTimeout):
if retries_left > 0:
logger.info("%s", "File {}: GET FAILED. Attempting to resume.".format(dss_file.uuid))
time.sleep(delay)
delay *= 2
retries_left -= 1
continue
raise
return hasher.hexdigest() | python | def _do_download_file(self, dss_file, fh, num_retries, min_delay_seconds):
hasher = hashlib.sha256()
delay = min_delay_seconds
retries_left = num_retries
while True:
try:
response = self.get_file._request(
dict(uuid=dss_file.uuid, version=dss_file.version, replica=dss_file.replica),
stream=True,
headers={
'Range': "bytes={}-".format(fh.tell())
},
)
try:
if not response.ok:
logger.error("%s", "File {}: GET FAILED.".format(dss_file.uuid))
logger.error("%s", "Response: {}".format(response.text))
break
consume_bytes = int(fh.tell())
server_start = 0
content_range_header = response.headers.get('Content-Range', None)
if content_range_header is not None:
cre = re.compile("bytes (\d+)-(\d+)")
mo = cre.search(content_range_header)
if mo is not None:
server_start = int(mo.group(1))
consume_bytes -= server_start
assert consume_bytes >= 0
if server_start > 0 and consume_bytes == 0:
logger.info("%s", "File {}: Resuming at {}.".format(
dss_file.uuid, server_start))
elif consume_bytes > 0:
logger.info("%s", "File {}: Resuming at {}. Dropping {} bytes to match".format(
dss_file.uuid, server_start, consume_bytes))
while consume_bytes > 0:
bytes_to_read = min(consume_bytes, 1024*1024)
content = response.iter_content(chunk_size=bytes_to_read)
chunk = next(content)
if chunk:
consume_bytes -= len(chunk)
for chunk in response.iter_content(chunk_size=1024*1024):
if chunk:
fh.write(chunk)
hasher.update(chunk)
retries_left = min(retries_left + 1, num_retries)
delay = max(delay / 2, min_delay_seconds)
break
finally:
response.close()
except (ChunkedEncodingError, ConnectionError, ReadTimeout):
if retries_left > 0:
logger.info("%s", "File {}: GET FAILED. Attempting to resume.".format(dss_file.uuid))
time.sleep(delay)
delay *= 2
retries_left -= 1
continue
raise
return hasher.hexdigest() | [
"def",
"_do_download_file",
"(",
"self",
",",
"dss_file",
",",
"fh",
",",
"num_retries",
",",
"min_delay_seconds",
")",
":",
"hasher",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"delay",
"=",
"min_delay_seconds",
"retries_left",
"=",
"num_retries",
"while",
"Tru... | Abstracts away complications for downloading a file, handles retries and delays, and computes its hash | [
"Abstracts",
"away",
"complications",
"for",
"downloading",
"a",
"file",
"handles",
"retries",
"and",
"delays",
"and",
"computes",
"its",
"hash"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L239-L303 |
18,645 | 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)
fieldnames, source_manifest = self._parse_manifest(manifest)
if 'file_path' not in fieldnames:
fieldnames.append('file_path')
with atomic_write(output, overwrite=True) as f:
delimiter = b'\t' if USING_PYTHON2 else '\t'
writer = csv.DictWriter(f, fieldnames, delimiter=delimiter, quoting=csv.QUOTE_NONE)
writer.writeheader()
for row in source_manifest:
row['file_path'] = self._file_path(row['file_sha256'], filestore_root)
writer.writerow(row)
if os.path.isfile(output):
logger.warning('Overwriting manifest %s', output)
logger.info('Rewrote manifest %s with additional column containing path to downloaded files.', output) | python | def _write_output_manifest(self, manifest, filestore_root):
output = os.path.basename(manifest)
fieldnames, source_manifest = self._parse_manifest(manifest)
if 'file_path' not in fieldnames:
fieldnames.append('file_path')
with atomic_write(output, overwrite=True) as f:
delimiter = b'\t' if USING_PYTHON2 else '\t'
writer = csv.DictWriter(f, fieldnames, delimiter=delimiter, quoting=csv.QUOTE_NONE)
writer.writeheader()
for row in source_manifest:
row['file_path'] = self._file_path(row['file_sha256'], filestore_root)
writer.writerow(row)
if os.path.isfile(output):
logger.warning('Overwriting manifest %s', output)
logger.info('Rewrote manifest %s with additional column containing path to downloaded files.', output) | [
"def",
"_write_output_manifest",
"(",
"self",
",",
"manifest",
",",
"filestore_root",
")",
":",
"output",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"manifest",
")",
"fieldnames",
",",
"source_manifest",
"=",
"self",
".",
"_parse_manifest",
"(",
"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. | [
"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",
"... | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/__init__.py#L332-L350 |
18,646 | 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 ctypes
create_hard_link = ctypes.windll.kernel32.CreateHardLinkW
create_hard_link.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p]
create_hard_link.restype = ctypes.wintypes.BOOL
res = create_hard_link(link_name, source, None)
if res == 0:
raise ctypes.WinError()
else:
try:
os.link(source, link_name)
except OSError as e:
if e.errno != errno.EEXIST:
raise
else:
# It's possible that the user created a different file with the same name as the
# one we're trying to download. Thus we need to check the if the inode is different
# and raise an error in this case.
source_stat = os.stat(source)
dest_stat = os.stat(link_name)
# Check device first because different drives can have the same inode number
if source_stat.st_dev != dest_stat.st_dev or source_stat.st_ino != dest_stat.st_ino:
raise | python | def hardlink(source, link_name):
if sys.version_info < (3,) and platform.system() == 'Windows': # pragma: no cover
import ctypes
create_hard_link = ctypes.windll.kernel32.CreateHardLinkW
create_hard_link.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p]
create_hard_link.restype = ctypes.wintypes.BOOL
res = create_hard_link(link_name, source, None)
if res == 0:
raise ctypes.WinError()
else:
try:
os.link(source, link_name)
except OSError as e:
if e.errno != errno.EEXIST:
raise
else:
# It's possible that the user created a different file with the same name as the
# one we're trying to download. Thus we need to check the if the inode is different
# and raise an error in this case.
source_stat = os.stat(source)
dest_stat = os.stat(link_name)
# Check device first because different drives can have the same inode number
if source_stat.st_dev != dest_stat.st_dev or source_stat.st_ino != dest_stat.st_ino:
raise | [
"def",
"hardlink",
"(",
"source",
",",
"link_name",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
")",
"and",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"# pragma: no cover",
"import",
"ctypes",
"create_hard_link",
"=",
... | 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 | [
"Create",
"a",
"hardlink",
"in",
"a",
"portable",
"way"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/dss/util/__init__.py#L40-L69 |
18,647 | 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 applied to prod. In the meantime, this function will add
retries specifically for POST search (and any other POST requests will not be retried).
"""
# TODO: Revert this PR as soon as the appropriate swagger definitions have percolated up
# to prod and merged; see https://github.com/HumanCellAtlas/data-store/pull/1961
status_code = 500
if '/v1/search' in url:
retry_count = 10
else:
retry_count = 1
while status_code in (500, 502, 503, 504) and retry_count > 0:
try:
retry_count -= 1
res = session.request(self.http_method,
url,
params=query,
json=json_input,
stream=stream,
headers=headers,
timeout=self.client.timeout_policy)
status_code = res.status_code
except SwaggerAPIException:
if retry_count > 0:
pass
else:
raise
return res | python | def request_with_retries_on_post_search(self, session, url, query, json_input, stream, headers):
# TODO: Revert this PR as soon as the appropriate swagger definitions have percolated up
# to prod and merged; see https://github.com/HumanCellAtlas/data-store/pull/1961
status_code = 500
if '/v1/search' in url:
retry_count = 10
else:
retry_count = 1
while status_code in (500, 502, 503, 504) and retry_count > 0:
try:
retry_count -= 1
res = session.request(self.http_method,
url,
params=query,
json=json_input,
stream=stream,
headers=headers,
timeout=self.client.timeout_policy)
status_code = res.status_code
except SwaggerAPIException:
if retry_count > 0:
pass
else:
raise
return res | [
"def",
"request_with_retries_on_post_search",
"(",
"self",
",",
"session",
",",
"url",
",",
"query",
",",
"json_input",
",",
"stream",
",",
"headers",
")",
":",
"# TODO: Revert this PR as soon as the appropriate swagger definitions have percolated up",
"# to prod and merged; se... | 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 POST requests will not be retried). | [
"Submit",
"a",
"request",
"and",
"retry",
"POST",
"search",
"requests",
"specifically",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/__init__.py#L143-L174 |
18,648 | 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))
else:
self.__init__() | python | def refresh_swagger(self):
try:
os.remove(self._get_swagger_filename(self.swagger_url))
except EnvironmentError as e:
logger.warn(os.strerror(e.errno))
else:
self.__init__() | [
"def",
"refresh_swagger",
"(",
"self",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"self",
".",
"_get_swagger_filename",
"(",
"self",
".",
"swagger_url",
")",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"logger",
".",
"warn",
"(",
"os",
".",
... | Manually refresh the swagger document. This can help resolve errors communicate with the API. | [
"Manually",
"refresh",
"the",
"swagger",
"document",
".",
"This",
"can",
"help",
"resolve",
"errors",
"communicate",
"with",
"the",
"API",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/util/__init__.py#L335-L344 |
18,649 | 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):
if uri.area_uuid not in self._config.upload.areas:
self._config.upload.areas[uri.area_uuid] = {'uri': uri.uri}
self.save() | [
"def",
"add_area",
"(",
"self",
",",
"uri",
")",
":",
"if",
"uri",
".",
"area_uuid",
"not",
"in",
"self",
".",
"_config",
".",
"upload",
".",
"areas",
":",
"self",
".",
"_config",
".",
"upload",
".",
"areas",
"[",
"uri",
".",
"area_uuid",
"]",
"=",... | Record information about a new Upload Area
:param UploadAreaURI uri: An Upload Area URI. | [
"Record",
"information",
"about",
"a",
"new",
"Upload",
"Area"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L97-L105 |
18,650 | 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):
self._config.upload.current_area = area_uuid
self.save() | [
"def",
"select_area",
"(",
"self",
",",
"area_uuid",
")",
":",
"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. | [
"Update",
"the",
"current",
"area",
"to",
"be",
"the",
"area",
"with",
"this",
"UUID",
"."
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/upload_config.py#L107-L115 |
18,651 | 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 not created
"""
response = self._make_request('post',
path="/area/{id}".format(id=area_uuid),
headers={'Api-Key': self.auth_token})
return response.json() | python | def create_area(self, area_uuid):
response = self._make_request('post',
path="/area/{id}".format(id=area_uuid),
headers={'Api-Key': self.auth_token})
return response.json() | [
"def",
"create_area",
"(",
"self",
",",
"area_uuid",
")",
":",
"response",
"=",
"self",
".",
"_make_request",
"(",
"'post'",
",",
"path",
"=",
"\"/area/{id}\"",
".",
"format",
"(",
"id",
"=",
"area_uuid",
")",
",",
"headers",
"=",
"{",
"'Api-Key'",
":",
... | 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 | [
"Create",
"an",
"Upload",
"Area"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L35-L47 |
18,652 | 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)))
return response.ok | python | def area_exists(self, area_uuid):
response = requests.head(self._url(path="/area/{id}".format(id=area_uuid)))
return response.ok | [
"def",
"area_exists",
"(",
"self",
",",
"area_uuid",
")",
":",
"response",
"=",
"requests",
".",
"head",
"(",
"self",
".",
"_url",
"(",
"path",
"=",
"\"/area/{id}\"",
".",
"format",
"(",
"id",
"=",
"area_uuid",
")",
")",
")",
"return",
"response",
".",... | Check if an Upload Area exists
:param str area_uuid: A RFC4122-compliant ID for the upload area
:return: True or False
:rtype: bool | [
"Check",
"if",
"an",
"Upload",
"Area",
"exists"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L49-L58 |
18,653 | 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="/area/{id}".format(id=area_uuid),
headers={'Api-Key': self.auth_token})
return True | python | def delete_area(self, area_uuid):
self._make_request('delete', path="/area/{id}".format(id=area_uuid),
headers={'Api-Key': self.auth_token})
return True | [
"def",
"delete_area",
"(",
"self",
",",
"area_uuid",
")",
":",
"self",
".",
"_make_request",
"(",
"'delete'",
",",
"path",
"=",
"\"/area/{id}\"",
".",
"format",
"(",
"id",
"=",
"area_uuid",
")",
",",
"headers",
"=",
"{",
"'Api-Key'",
":",
"self",
".",
... | 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 | [
"Delete",
"an",
"Upload",
"Area"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L60-L71 |
18,654 | 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 UploadApiException: if credentials could not be obtained
"""
response = self._make_request("post", path="/area/{uuid}/credentials".format(uuid=area_uuid))
return response.json() | python | def credentials(self, area_uuid):
response = self._make_request("post", path="/area/{uuid}/credentials".format(uuid=area_uuid))
return response.json() | [
"def",
"credentials",
"(",
"self",
",",
"area_uuid",
")",
":",
"response",
"=",
"self",
".",
"_make_request",
"(",
"\"post\"",
",",
"path",
"=",
"\"/area/{uuid}/credentials\"",
".",
"format",
"(",
"uuid",
"=",
"area_uuid",
")",
")",
"return",
"response",
"."... | 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 obtained | [
"Get",
"AWS",
"credentials",
"required",
"to",
"directly",
"upload",
"files",
"to",
"Upload",
"Area",
"in",
"S3"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L73-L83 |
18,655 | 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
:rtype: bool
:raises UploadApiException: if file could not be stored
"""
url_safe_filename = urlparse.quote(filename)
path = ("/area/{area_uuid}/{filename}".format(area_uuid=area_uuid, filename=url_safe_filename))
response = self._make_request('post', path=path)
return response.ok | python | def file_upload_notification(self, area_uuid, filename):
url_safe_filename = urlparse.quote(filename)
path = ("/area/{area_uuid}/{filename}".format(area_uuid=area_uuid, filename=url_safe_filename))
response = self._make_request('post', path=path)
return response.ok | [
"def",
"file_upload_notification",
"(",
"self",
",",
"area_uuid",
",",
"filename",
")",
":",
"url_safe_filename",
"=",
"urlparse",
".",
"quote",
"(",
"filename",
")",
"path",
"=",
"(",
"\"/area/{area_uuid}/{filename}\"",
".",
"format",
"(",
"area_uuid",
"=",
"ar... | 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 | [
"Notify",
"Upload",
"Service",
"that",
"a",
"file",
"has",
"been",
"placed",
"in",
"an",
"Upload",
"Area"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L111-L124 |
18,656 | 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
:rtype: list of dicts
:raises UploadApiException: if information could not be obtained
"""
path = "/area/{uuid}/files_info".format(uuid=area_uuid)
file_list = [urlparse.quote(filename) for filename in file_list]
response = self._make_request('put', path=path, json=file_list)
return response.json() | python | def files_info(self, area_uuid, file_list):
path = "/area/{uuid}/files_info".format(uuid=area_uuid)
file_list = [urlparse.quote(filename) for filename in file_list]
response = self._make_request('put', path=path, json=file_list)
return response.json() | [
"def",
"files_info",
"(",
"self",
",",
"area_uuid",
",",
"file_list",
")",
":",
"path",
"=",
"\"/area/{uuid}/files_info\"",
".",
"format",
"(",
"uuid",
"=",
"area_uuid",
")",
"file_list",
"=",
"[",
"urlparse",
".",
"quote",
"(",
"filename",
")",
"for",
"fi... | 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: if information could not be obtained | [
"Get",
"information",
"about",
"files"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L126-L139 |
18,657 | 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
:raises UploadApiException: if information could not be obtained
"""
path = "/area/{uuid}/validations".format(uuid=area_uuid)
result = self._make_request('get', path)
return result.json() | python | def validation_statuses(self, area_uuid):
path = "/area/{uuid}/validations".format(uuid=area_uuid)
result = self._make_request('get', path)
return result.json() | [
"def",
"validation_statuses",
"(",
"self",
",",
"area_uuid",
")",
":",
"path",
"=",
"\"/area/{uuid}/validations\"",
".",
"format",
"(",
"uuid",
"=",
"area_uuid",
")",
"result",
"=",
"self",
".",
"_make_request",
"(",
"'get'",
",",
"path",
")",
"return",
"res... | 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 obtained | [
"Get",
"count",
"of",
"validation",
"statuses",
"for",
"all",
"files",
"in",
"upload_area"
] | cc70817bc4e50944c709eaae160de0bf7a19f0f3 | https://github.com/HumanCellAtlas/dcp-cli/blob/cc70817bc4e50944c709eaae160de0bf7a19f0f3/hca/upload/lib/api_client.py#L214-L225 |
18,658 | 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_classes(input_fn=input_fn))
LOGGER.debug("Predicted language position %s", pos)
return sorted(self.languages)[pos] | python | def language_name(self, text: str) -> str:
values = extract(text)
input_fn = _to_func(([values], []))
pos: int = next(self._classifier.predict_classes(input_fn=input_fn))
LOGGER.debug("Predicted language position %s", pos)
return sorted(self.languages)[pos] | [
"def",
"language_name",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"str",
":",
"values",
"=",
"extract",
"(",
"text",
")",
"input_fn",
"=",
"_to_func",
"(",
"(",
"[",
"values",
"]",
",",
"[",
"]",
")",
")",
"pos",
":",
"int",
"=",
"next",
... | Predict the programming language name of the given source code.
:param text: source code.
:return: language name | [
"Predict",
"the",
"programming",
"language",
"name",
"of",
"the",
"given",
"source",
"code",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L61-L72 |
18,659 | 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
"""
values = extract(text)
input_fn = _to_func(([values], []))
prediction = self._classifier.predict_proba(input_fn=input_fn)
probabilities = next(prediction).tolist()
sorted_languages = sorted(self.languages)
return dict(zip(sorted_languages, probabilities)) | python | def scores(self, text: str) -> Dict[str, float]:
values = extract(text)
input_fn = _to_func(([values], []))
prediction = self._classifier.predict_proba(input_fn=input_fn)
probabilities = next(prediction).tolist()
sorted_languages = sorted(self.languages)
return dict(zip(sorted_languages, probabilities)) | [
"def",
"scores",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"float",
"]",
":",
"values",
"=",
"extract",
"(",
"text",
")",
"input_fn",
"=",
"_to_func",
"(",
"(",
"[",
"values",
"]",
",",
"[",
"]",
")",
")",
"predi... | 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",
".",
... | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L74-L87 |
18,660 | 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: maximum number of listed languages.
:return: languages list
"""
scores = self.scores(text)
# Sorted from the most probable language to the least probable
sorted_scores = sorted(scores.items(), key=itemgetter(1), reverse=True)
languages, probabilities = list(zip(*sorted_scores))
# Find the most distant consecutive languages.
# A logarithmic scale is used here because the probabilities
# are most of the time really close to zero
rescaled_probabilities = [log(proba) for proba in probabilities]
distances = [
rescaled_probabilities[pos] - rescaled_probabilities[pos+1]
for pos in range(len(rescaled_probabilities)-1)]
max_distance_pos = max(enumerate(distances, 1), key=itemgetter(1))[0]
limit = min(max_distance_pos, max_languages)
return languages[:limit] | python | def probable_languages(
self,
text: str,
max_languages: int = 3) -> Tuple[str, ...]:
scores = self.scores(text)
# Sorted from the most probable language to the least probable
sorted_scores = sorted(scores.items(), key=itemgetter(1), reverse=True)
languages, probabilities = list(zip(*sorted_scores))
# Find the most distant consecutive languages.
# A logarithmic scale is used here because the probabilities
# are most of the time really close to zero
rescaled_probabilities = [log(proba) for proba in probabilities]
distances = [
rescaled_probabilities[pos] - rescaled_probabilities[pos+1]
for pos in range(len(rescaled_probabilities)-1)]
max_distance_pos = max(enumerate(distances, 1), key=itemgetter(1))[0]
limit = min(max_distance_pos, max_languages)
return languages[:limit] | [
"def",
"probable_languages",
"(",
"self",
",",
"text",
":",
"str",
",",
"max_languages",
":",
"int",
"=",
"3",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"scores",
"=",
"self",
".",
"scores",
"(",
"text",
")",
"# Sorted from the most probable ... | 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 | [
"List",
"of",
"most",
"probable",
"programming",
"languages",
"the",
"list",
"is",
"ordered",
"from",
"the",
"most",
"probable",
"to",
"the",
"least",
"probable",
"one",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L89-L116 |
18,661 | 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:
LOGGER.error("Cannot learn using default model")
raise GuesslangError('Cannot learn using default "readonly" model')
languages = self.languages
LOGGER.info("Extract training data")
extensions = [ext for exts in languages.values() for ext in exts]
files = search_files(input_dir, extensions)
nb_files = len(files)
chunk_size = min(int(CHUNK_PROPORTION * nb_files), CHUNK_SIZE)
LOGGER.debug("Evaluation files count: %d", chunk_size)
LOGGER.debug("Training files count: %d", nb_files - chunk_size)
batches = _pop_many(files, chunk_size)
LOGGER.debug("Prepare evaluation data")
evaluation_data = extract_from_files(next(batches), languages)
LOGGER.debug("Evaluation data count: %d", len(evaluation_data[0]))
accuracy = 0
total = ceil(nb_files / chunk_size) - 1
LOGGER.info("Start learning")
for pos, training_files in enumerate(batches, 1):
LOGGER.info("Step %.2f%%", 100 * pos / total)
LOGGER.debug("Training data extraction")
training_data = extract_from_files(training_files, languages)
LOGGER.debug("Training data count: %d", len(training_data[0]))
steps = int(FITTING_FACTOR * len(training_data[0]) / 100)
LOGGER.debug("Fitting, steps count: %d", steps)
self._classifier.fit(input_fn=_to_func(training_data), steps=steps)
LOGGER.debug("Evaluation")
accuracy = self._classifier.evaluate(
input_fn=_to_func(evaluation_data), steps=1)['accuracy']
_comment(accuracy)
return accuracy | python | def learn(self, input_dir: str) -> float:
if self.is_default:
LOGGER.error("Cannot learn using default model")
raise GuesslangError('Cannot learn using default "readonly" model')
languages = self.languages
LOGGER.info("Extract training data")
extensions = [ext for exts in languages.values() for ext in exts]
files = search_files(input_dir, extensions)
nb_files = len(files)
chunk_size = min(int(CHUNK_PROPORTION * nb_files), CHUNK_SIZE)
LOGGER.debug("Evaluation files count: %d", chunk_size)
LOGGER.debug("Training files count: %d", nb_files - chunk_size)
batches = _pop_many(files, chunk_size)
LOGGER.debug("Prepare evaluation data")
evaluation_data = extract_from_files(next(batches), languages)
LOGGER.debug("Evaluation data count: %d", len(evaluation_data[0]))
accuracy = 0
total = ceil(nb_files / chunk_size) - 1
LOGGER.info("Start learning")
for pos, training_files in enumerate(batches, 1):
LOGGER.info("Step %.2f%%", 100 * pos / total)
LOGGER.debug("Training data extraction")
training_data = extract_from_files(training_files, languages)
LOGGER.debug("Training data count: %d", len(training_data[0]))
steps = int(FITTING_FACTOR * len(training_data[0]) / 100)
LOGGER.debug("Fitting, steps count: %d", steps)
self._classifier.fit(input_fn=_to_func(training_data), steps=steps)
LOGGER.debug("Evaluation")
accuracy = self._classifier.evaluate(
input_fn=_to_func(evaluation_data), steps=1)['accuracy']
_comment(accuracy)
return accuracy | [
"def",
"learn",
"(",
"self",
",",
"input_dir",
":",
"str",
")",
"->",
"float",
":",
"if",
"self",
".",
"is_default",
":",
"LOGGER",
".",
"error",
"(",
"\"Cannot learn using default model\"",
")",
"raise",
"GuesslangError",
"(",
"'Cannot learn using default \"reado... | 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 | [
"Learn",
"languages",
"features",
"from",
"source",
"files",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L118-L164 |
18,662 | 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', default=False, action='store_true',
help="show debug messages")
args = parser.parse_args()
config_logging(args.debug)
report = json.load(args.reportfile)
graph_data = _build_graph(report)
index_path = _prepare_resources(graph_data)
webbrowser.open(str(index_path)) | python | def main():
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', default=False, action='store_true',
help="show debug messages")
args = parser.parse_args()
config_logging(args.debug)
report = json.load(args.reportfile)
graph_data = _build_graph(report)
index_path = _prepare_resources(graph_data)
webbrowser.open(str(index_path)) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'reportfile'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'r'",
")",
",",
"help",
"=",... | Report graph creator command line | [
"Report",
"graph",
"creator",
"command",
"line"
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/report_graph.py#L25-L42 |
18,663 | 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 extensions: list of file extensions
:return: filenames
"""
files = [
path for path in Path(source).glob('**/*')
if path.is_file() and path.suffix.lstrip('.') in extensions]
nb_files = len(files)
LOGGER.debug("Total files found: %d", nb_files)
if nb_files < NB_FILES_MIN:
LOGGER.error("Too few source files")
raise GuesslangError(
'{} source files found in {}. {} files minimum is required'.format(
nb_files, source, NB_FILES_MIN))
random.shuffle(files)
return files | python | def search_files(source: str, extensions: List[str]) -> List[Path]:
files = [
path for path in Path(source).glob('**/*')
if path.is_file() and path.suffix.lstrip('.') in extensions]
nb_files = len(files)
LOGGER.debug("Total files found: %d", nb_files)
if nb_files < NB_FILES_MIN:
LOGGER.error("Too few source files")
raise GuesslangError(
'{} source files found in {}. {} files minimum is required'.format(
nb_files, source, NB_FILES_MIN))
random.shuffle(files)
return files | [
"def",
"search_files",
"(",
"source",
":",
"str",
",",
"extensions",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Path",
"]",
":",
"files",
"=",
"[",
"path",
"for",
"path",
"in",
"Path",
"(",
"source",
")",
".",
"glob",
"(",
"'**/*'",
"... | 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 | [
"Retrieve",
"files",
"located",
"the",
"source",
"directory",
"and",
"its",
"subdirectories",
"whose",
"extension",
"match",
"one",
"of",
"the",
"listed",
"extensions",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L30-L52 |
18,664 | 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 = enumerate(sorted(languages.items()))
rank_map = {ext: rank for rank, (_, exts) in enumerator for ext in exts}
with multiprocessing.Pool(initializer=_process_init) as pool:
file_iterator = ((path, rank_map) for path in files)
arrays = _to_arrays(pool.starmap(_extract_features, file_iterator))
LOGGER.debug("Extracted arrays count: %d", len(arrays[0]))
return arrays | python | def extract_from_files(
files: List[Path],
languages: Dict[str, List[str]]) -> DataSet:
enumerator = enumerate(sorted(languages.items()))
rank_map = {ext: rank for rank, (_, exts) in enumerator for ext in exts}
with multiprocessing.Pool(initializer=_process_init) as pool:
file_iterator = ((path, rank_map) for path in files)
arrays = _to_arrays(pool.starmap(_extract_features, file_iterator))
LOGGER.debug("Extracted arrays count: %d", len(arrays[0]))
return arrays | [
"def",
"extract_from_files",
"(",
"files",
":",
"List",
"[",
"Path",
"]",
",",
"languages",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
"->",
"DataSet",
":",
"enumerator",
"=",
"enumerate",
"(",
"sorted",
"(",
"languages",
".",
"... | Extract arrays of features from the given files.
:param files: list of paths
:param languages: language name =>
associated file extension list
:return: features | [
"Extract",
"arrays",
"of",
"features",
"from",
"the",
"given",
"files",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L55-L73 |
18,665 | 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 in FILE_ENCODINGS:
try:
return file_path.read_text(encoding=encoding)
except UnicodeError:
pass # Ignore encoding error
raise GuesslangError('Encoding not supported for {!s}'.format(file_path)) | python | def safe_read_file(file_path: Path) -> str:
for encoding in FILE_ENCODINGS:
try:
return file_path.read_text(encoding=encoding)
except UnicodeError:
pass # Ignore encoding error
raise GuesslangError('Encoding not supported for {!s}'.format(file_path)) | [
"def",
"safe_read_file",
"(",
"file_path",
":",
"Path",
")",
"->",
"str",
":",
"for",
"encoding",
"in",
"FILE_ENCODINGS",
":",
"try",
":",
"return",
"file_path",
".",
"read_text",
"(",
"encoding",
"=",
"encoding",
")",
"except",
"UnicodeError",
":",
"pass",
... | 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 | [
"Read",
"a",
"text",
"file",
".",
"Several",
"text",
"encodings",
"are",
"tried",
"until",
"the",
"file",
"content",
"is",
"correctly",
"decoded",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L106-L120 |
18,666 | 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 = config_dict('logging.json')
for logger in logging_config['loggers'].values():
logger['level'] = level
logging.config.dictConfig(logging_config)
tf.logging.set_verbosity(tf_level) | python | def config_logging(debug: bool = False) -> None:
if debug:
level = 'DEBUG'
tf_level = tf.logging.INFO
else:
level = 'INFO'
tf_level = tf.logging.ERROR
logging_config = config_dict('logging.json')
for logger in logging_config['loggers'].values():
logger['level'] = level
logging.config.dictConfig(logging_config)
tf.logging.set_verbosity(tf_level) | [
"def",
"config_logging",
"(",
"debug",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"debug",
":",
"level",
"=",
"'DEBUG'",
"tf_level",
"=",
"tf",
".",
"logging",
".",
"INFO",
"else",
":",
"level",
"=",
"'INFO'",
"tf_level",
"=",
"tf",
"."... | Set-up application and `tensorflow` logging.
:param debug: show or hide debug messages | [
"Set",
"-",
"up",
"application",
"and",
"tensorflow",
"logging",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L53-L70 |
18,667 | 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:
LOGGER.warning("Cannot load %s from packages: %s", name, error)
content = DATA_FALLBACK.joinpath(name).read_text()
return cast(Dict[str, Any], json.loads(content)) | python | def config_dict(name: str) -> Dict[str, Any]:
try:
content = resource_string(PACKAGE, DATADIR.format(name)).decode()
except DistributionNotFound as error:
LOGGER.warning("Cannot load %s from packages: %s", name, error)
content = DATA_FALLBACK.joinpath(name).read_text()
return cast(Dict[str, Any], json.loads(content)) | [
"def",
"config_dict",
"(",
"name",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"try",
":",
"content",
"=",
"resource_string",
"(",
"PACKAGE",
",",
"DATADIR",
".",
"format",
"(",
"name",
")",
")",
".",
"decode",
"(",
")",
"excep... | Load a JSON configuration dict from Guesslang config directory.
:param name: the JSON file name.
:return: configuration | [
"Load",
"a",
"JSON",
"configuration",
"dict",
"from",
"Guesslang",
"config",
"directory",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L73-L85 |
18,668 | 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 default or not
"""
if model_dir is None:
try:
model_dir = resource_filename(PACKAGE, DATADIR.format('model'))
except DistributionNotFound as error:
LOGGER.warning("Cannot load model from packages: %s", error)
model_dir = str(DATA_FALLBACK.joinpath('model').absolute())
is_default_model = True
else:
is_default_model = False
model_path = Path(model_dir)
model_path.mkdir(exist_ok=True)
LOGGER.debug("Using model: %s, default: %s", model_path, is_default_model)
return (model_dir, is_default_model) | python | def model_info(model_dir: Optional[str] = None) -> Tuple[str, bool]:
if model_dir is None:
try:
model_dir = resource_filename(PACKAGE, DATADIR.format('model'))
except DistributionNotFound as error:
LOGGER.warning("Cannot load model from packages: %s", error)
model_dir = str(DATA_FALLBACK.joinpath('model').absolute())
is_default_model = True
else:
is_default_model = False
model_path = Path(model_dir)
model_path.mkdir(exist_ok=True)
LOGGER.debug("Using model: %s, default: %s", model_path, is_default_model)
return (model_dir, is_default_model) | [
"def",
"model_info",
"(",
"model_dir",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"str",
",",
"bool",
"]",
":",
"if",
"model_dir",
"is",
"None",
":",
"try",
":",
"model_dir",
"=",
"resource_filename",
"(",
"PACKAGE",
",",
... | 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 | [
"Retrieve",
"Guesslang",
"model",
"directory",
"name",
"and",
"tells",
"if",
"it",
"is",
"the",
"default",
"model",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L88-L110 |
18,669 | 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)
record.msg = (
self.STYLE[record.levelname] + record.msg + self.STYLE['END'])
record.levelname = (
self.STYLE['LEVEL'] + record.levelname + self.STYLE['END'])
return super().format(record) | python | def format(self, record: logging.LogRecord) -> str:
if platform.system() != 'Linux': # Avoid funny logs on Windows & MacOS
return super().format(record)
record.msg = (
self.STYLE[record.levelname] + record.msg + self.STYLE['END'])
record.levelname = (
self.STYLE['LEVEL'] + record.levelname + self.STYLE['END'])
return super().format(record) | [
"def",
"format",
"(",
"self",
",",
"record",
":",
"logging",
".",
"LogRecord",
")",
"->",
"str",
":",
"if",
"platform",
".",
"system",
"(",
")",
"!=",
"'Linux'",
":",
"# Avoid funny logs on Windows & MacOS",
"return",
"super",
"(",
")",
".",
"format",
"(",... | Format log records to produce colored messages.
:param record: log record
:return: log message | [
"Format",
"log",
"records",
"to",
"produce",
"colored",
"messages",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L37-L50 |
18,670 | 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 downloaded repos")
parser.add_argument(
'-n', '--nbrepo', help="number of repositories per language",
type=int, default=1000)
parser.add_argument(
'-d', '--debug', default=False, action='store_true',
help="show debug messages")
args = parser.parse_args()
config_logging(args.debug)
destination = Path(args.destination)
nb_repos = args.nbrepo
token = args.githubtoken
languages = config_dict('languages.json')
destination.mkdir(exist_ok=True)
for pos, language in enumerate(sorted(languages), 1):
LOGGER.info("Step %.2f%%, %s", 100 * pos / len(languages), language)
LOGGER.info("Fetch %d repos infos for language %s", nb_repos, language)
repos = _retrieve_repo_details(language, nb_repos, token)
LOGGER.info("%d repos details kept. Downloading", len(repos))
_download_repos(language, repos, destination)
LOGGER.info("Language %s repos downloaded", language)
LOGGER.debug("Exit OK") | python | def main():
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 downloaded repos")
parser.add_argument(
'-n', '--nbrepo', help="number of repositories per language",
type=int, default=1000)
parser.add_argument(
'-d', '--debug', default=False, action='store_true',
help="show debug messages")
args = parser.parse_args()
config_logging(args.debug)
destination = Path(args.destination)
nb_repos = args.nbrepo
token = args.githubtoken
languages = config_dict('languages.json')
destination.mkdir(exist_ok=True)
for pos, language in enumerate(sorted(languages), 1):
LOGGER.info("Step %.2f%%, %s", 100 * pos / len(languages), language)
LOGGER.info("Fetch %d repos infos for language %s", nb_repos, language)
repos = _retrieve_repo_details(language, nb_repos, token)
LOGGER.info("%d repos details kept. Downloading", len(repos))
_download_repos(language, repos, destination)
LOGGER.info("Language %s repos downloaded", language)
LOGGER.debug("Exit OK") | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'githubtoken'",
",",
"help",
"=",
"\"Github OAuth token, see https://developer.github.com/v3/oauth/\"",
")",
... | Github repositories downloaded command line | [
"Github",
"repositories",
"downloaded",
"command",
"line"
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/download_github_repo.py#L54-L87 |
18,671 | 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)
except (RuntimeError, requests.ConnectionError) as error:
LOGGER.warning("Failed: %s, %s", type(error), error)
# Wait a bit before retrying
for _ in range(pos):
_rest()
LOGGER.warning("Request Aborted")
return default
return _wrapper
return decorator | python | def retry(default=None):
def decorator(func):
"""Retry decorator"""
@functools.wraps(func)
def _wrapper(*args, **kw):
for pos in range(1, MAX_RETRIES):
try:
return func(*args, **kw)
except (RuntimeError, requests.ConnectionError) as error:
LOGGER.warning("Failed: %s, %s", type(error), error)
# Wait a bit before retrying
for _ in range(pos):
_rest()
LOGGER.warning("Request Aborted")
return default
return _wrapper
return decorator | [
"def",
"retry",
"(",
"default",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"Retry decorator\"\"\"",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"fo... | Retry functions after failures | [
"Retry",
"functions",
"after",
"failures"
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/download_github_repo.py#L117-L140 |
18,672 | 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, default=10000,
help="the number of keywords to keep")
parser.add_argument(
'-d', '--debug', default=False, action='store_true',
help="show debug messages")
args = parser.parse_args()
config_logging(args.debug)
learn_path = Path(args.learn)
keywords_path = Path(args.keywords)
nb_keywords = args.nbkeywords
languages = config_dict('languages.json')
exts = {ext: lang for lang, exts in languages.items() for ext in exts}
term_count = Counter()
document_count = Counter()
pos = 0
LOGGER.info("Reading files form %s", learn_path)
for pos, path in enumerate(Path(learn_path).glob('**/*'), 1):
if pos % STEP == 0:
LOGGER.debug("Processed %d", pos)
gc.collect() # Cleanup dirt
if not path.is_file() or not exts.get(path.suffix.lstrip('.')):
continue
counter = _extract(path)
term_count.update(counter)
document_count.update(counter.keys())
nb_terms = sum(term_count.values())
nb_documents = pos - 1
if not nb_documents:
LOGGER.error("No source files found in %s", learn_path)
raise RuntimeError('No source files in {}'.format(learn_path))
LOGGER.info("%d unique terms found", len(term_count))
terms = _most_frequent(
(term_count, nb_terms), (document_count, nb_documents), nb_keywords)
keywords = {
token: int(hashlib.sha1(token.encode()).hexdigest(), 16)
for token in terms
}
with keywords_path.open('w') as keywords_file:
json.dump(keywords, keywords_file, indent=2, sort_keys=True)
LOGGER.info("%d keywords written into %s", len(keywords), keywords_path)
LOGGER.debug("Exit OK") | python | def main():
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, default=10000,
help="the number of keywords to keep")
parser.add_argument(
'-d', '--debug', default=False, action='store_true',
help="show debug messages")
args = parser.parse_args()
config_logging(args.debug)
learn_path = Path(args.learn)
keywords_path = Path(args.keywords)
nb_keywords = args.nbkeywords
languages = config_dict('languages.json')
exts = {ext: lang for lang, exts in languages.items() for ext in exts}
term_count = Counter()
document_count = Counter()
pos = 0
LOGGER.info("Reading files form %s", learn_path)
for pos, path in enumerate(Path(learn_path).glob('**/*'), 1):
if pos % STEP == 0:
LOGGER.debug("Processed %d", pos)
gc.collect() # Cleanup dirt
if not path.is_file() or not exts.get(path.suffix.lstrip('.')):
continue
counter = _extract(path)
term_count.update(counter)
document_count.update(counter.keys())
nb_terms = sum(term_count.values())
nb_documents = pos - 1
if not nb_documents:
LOGGER.error("No source files found in %s", learn_path)
raise RuntimeError('No source files in {}'.format(learn_path))
LOGGER.info("%d unique terms found", len(term_count))
terms = _most_frequent(
(term_count, nb_terms), (document_count, nb_documents), nb_keywords)
keywords = {
token: int(hashlib.sha1(token.encode()).hexdigest(), 16)
for token in terms
}
with keywords_path.open('w') as keywords_file:
json.dump(keywords, keywords_file, indent=2, sort_keys=True)
LOGGER.info("%d keywords written into %s", len(keywords), keywords_path)
LOGGER.debug("Exit OK") | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'learn'",
",",
"help",
"=",
"\"learning source codes directory\"",
")",
"parser",
".",
"add_argument",
... | Keywords generator command line | [
"Keywords",
"generator",
"command",
"line"
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/make_keywords.py#L29-L87 |
18,673 | 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:
try:
_real_main()
except GuesslangError as error:
LOGGER.critical("Failed: %s", error)
sys.exit(-1)
except KeyboardInterrupt:
LOGGER.critical("Cancelled!")
sys.exit(-2) | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"try",
":",
"_real_main",
"(",
")",
"except",
"GuesslangError",
"as",
"error",
":",
"LOGGER",
".",
"critical",
"(",
"\"Failed: %s\"",
",",
"error",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")",
"except",
"Ke... | Run command line | [
"Run",
"command",
"line"
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/__main__.py#L19-L28 |
18,674 | 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]:
return [word for word in SEPARATOR.split(text) if word.strip(' \t')] | [
"def",
"split",
"(",
"text",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"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 | [
"Split",
"a",
"text",
"into",
"a",
"list",
"of",
"tokens",
"."
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/extractor.py#L34-L40 |
18,675 | 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 extracted files")
parser.add_argument(
'-t', '--nb-test-files', help="number of testing files per language",
type=int, default=5000)
parser.add_argument(
'-l', '--nb-learn-files', help="number of learning files per language",
type=int, default=10000)
parser.add_argument(
'-r', '--remove', help="remove repos that cannot be read",
action='store_true', default=False)
parser.add_argument(
'-d', '--debug', default=False, action='store_true',
help="show debug messages")
args = parser.parse_args()
config_logging(args.debug)
source = Path(args.source)
destination = Path(args.destination)
nb_test = args.nb_test_files
nb_learn = args.nb_learn_files
remove = args.remove
repos = _find_repos(source)
split_repos = _split_repos(repos, nb_test, nb_learn)
split_files = _find_files(*split_repos, nb_test, nb_learn, remove)
_unzip_all(*split_files, destination)
LOGGER.info("Files saved into %s", destination)
LOGGER.debug("Exit OK") | python | def main():
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 extracted files")
parser.add_argument(
'-t', '--nb-test-files', help="number of testing files per language",
type=int, default=5000)
parser.add_argument(
'-l', '--nb-learn-files', help="number of learning files per language",
type=int, default=10000)
parser.add_argument(
'-r', '--remove', help="remove repos that cannot be read",
action='store_true', default=False)
parser.add_argument(
'-d', '--debug', default=False, action='store_true',
help="show debug messages")
args = parser.parse_args()
config_logging(args.debug)
source = Path(args.source)
destination = Path(args.destination)
nb_test = args.nb_test_files
nb_learn = args.nb_learn_files
remove = args.remove
repos = _find_repos(source)
split_repos = _split_repos(repos, nb_test, nb_learn)
split_files = _find_files(*split_repos, nb_test, nb_learn, remove)
_unzip_all(*split_files, destination)
LOGGER.info("Files saved into %s", destination)
LOGGER.debug("Exit OK") | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"'source'",
",",
"help",
"... | Files extractor command line | [
"Files",
"extractor",
"command",
"line"
] | 03e33b77c73238c0fe4600147e8c926515a2887f | https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/unzip_repos.py#L30-L65 |
18,676 | 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's coordinate system.
Returns a two-tuple containing the 3D-ndarray and the affine matrix.
If `rescale` is set to `None` (the default), then the image array dtype
will be preserved, unless any of the DICOM images contain either the
`Rescale Slope
<https://dicom.innolitics.com/ciods/ct-image/ct-image/00281053>`_ or the
`Rescale Intercept <https://dicom.innolitics.com/ciods/ct-image/ct-image/00281052>`_
attributes. If either of these attributes are present, they will be
applied to each slice individually.
If `rescale` is `True` the voxels will be cast to `float32`, if set to
`False`, the original dtype will be preserved even if DICOM rescaling information is present.
The returned array has the column-major byte-order.
This function requires that the datasets:
- Be in same series (have the same
`Series Instance UID <https://dicom.innolitics.com/ciods/ct-image/general-series/0020000e>`_,
`Modality <https://dicom.innolitics.com/ciods/ct-image/general-series/00080060>`_,
and `SOP Class UID <https://dicom.innolitics.com/ciods/ct-image/sop-common/00080016>`_).
- The binary storage of each slice must be the same (have the same
`Bits Allocated <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280100>`_,
`Bits Stored <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280101>`_,
`High Bit <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280102>`_, and
`Pixel Representation <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280103>`_).
- The image slice must approximately form a grid. This means there can not
be any missing internal slices (missing slices on the ends of the dataset
are not detected).
- It also means that each slice must have the same
`Rows <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280010>`_,
`Columns <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280011>`_,
`Pixel Spacing <https://dicom.innolitics.com/ciods/ct-image/image-plane/00280030>`_, and
`Image Orientation (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200037>`_
attribute values.
- The direction cosines derived from the
`Image Orientation (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200037>`_
attribute must, within 1e-4, have a magnitude of 1. The cosines must
also be approximately perpendicular (their dot-product must be within
1e-4 of 0). Warnings are displayed if any of these approximations are
below 1e-8, however, since we have seen real datasets with values up to
1e-4, we let them pass.
- The `Image Position (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200032>`_
values must approximately form a line.
If any of these conditions are not met, a `dicom_numpy.DicomImportException` is raised.
'''
if len(slice_datasets) == 0:
raise DicomImportException("Must provide at least one DICOM dataset")
_validate_slices_form_uniform_grid(slice_datasets)
voxels = _merge_slice_pixel_arrays(slice_datasets, rescale)
transform = _ijk_to_patient_xyz_transform_matrix(slice_datasets)
return voxels, transform | 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's coordinate system.
Returns a two-tuple containing the 3D-ndarray and the affine matrix.
If `rescale` is set to `None` (the default), then the image array dtype
will be preserved, unless any of the DICOM images contain either the
`Rescale Slope
<https://dicom.innolitics.com/ciods/ct-image/ct-image/00281053>`_ or the
`Rescale Intercept <https://dicom.innolitics.com/ciods/ct-image/ct-image/00281052>`_
attributes. If either of these attributes are present, they will be
applied to each slice individually.
If `rescale` is `True` the voxels will be cast to `float32`, if set to
`False`, the original dtype will be preserved even if DICOM rescaling information is present.
The returned array has the column-major byte-order.
This function requires that the datasets:
- Be in same series (have the same
`Series Instance UID <https://dicom.innolitics.com/ciods/ct-image/general-series/0020000e>`_,
`Modality <https://dicom.innolitics.com/ciods/ct-image/general-series/00080060>`_,
and `SOP Class UID <https://dicom.innolitics.com/ciods/ct-image/sop-common/00080016>`_).
- The binary storage of each slice must be the same (have the same
`Bits Allocated <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280100>`_,
`Bits Stored <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280101>`_,
`High Bit <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280102>`_, and
`Pixel Representation <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280103>`_).
- The image slice must approximately form a grid. This means there can not
be any missing internal slices (missing slices on the ends of the dataset
are not detected).
- It also means that each slice must have the same
`Rows <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280010>`_,
`Columns <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280011>`_,
`Pixel Spacing <https://dicom.innolitics.com/ciods/ct-image/image-plane/00280030>`_, and
`Image Orientation (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200037>`_
attribute values.
- The direction cosines derived from the
`Image Orientation (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200037>`_
attribute must, within 1e-4, have a magnitude of 1. The cosines must
also be approximately perpendicular (their dot-product must be within
1e-4 of 0). Warnings are displayed if any of these approximations are
below 1e-8, however, since we have seen real datasets with values up to
1e-4, we let them pass.
- The `Image Position (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200032>`_
values must approximately form a line.
If any of these conditions are not met, a `dicom_numpy.DicomImportException` is raised.
'''
if len(slice_datasets) == 0:
raise DicomImportException("Must provide at least one DICOM dataset")
_validate_slices_form_uniform_grid(slice_datasets)
voxels = _merge_slice_pixel_arrays(slice_datasets, rescale)
transform = _ijk_to_patient_xyz_transform_matrix(slice_datasets)
return voxels, transform | [
"def",
"combine_slices",
"(",
"slice_datasets",
",",
"rescale",
"=",
"None",
")",
":",
"if",
"len",
"(",
"slice_datasets",
")",
"==",
"0",
":",
"raise",
"DicomImportException",
"(",
"\"Must provide at least one DICOM dataset\"",
")",
"_validate_slices_form_uniform_grid"... | 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 3D-ndarray and the affine matrix.
If `rescale` is set to `None` (the default), then the image array dtype
will be preserved, unless any of the DICOM images contain either the
`Rescale Slope
<https://dicom.innolitics.com/ciods/ct-image/ct-image/00281053>`_ or the
`Rescale Intercept <https://dicom.innolitics.com/ciods/ct-image/ct-image/00281052>`_
attributes. If either of these attributes are present, they will be
applied to each slice individually.
If `rescale` is `True` the voxels will be cast to `float32`, if set to
`False`, the original dtype will be preserved even if DICOM rescaling information is present.
The returned array has the column-major byte-order.
This function requires that the datasets:
- Be in same series (have the same
`Series Instance UID <https://dicom.innolitics.com/ciods/ct-image/general-series/0020000e>`_,
`Modality <https://dicom.innolitics.com/ciods/ct-image/general-series/00080060>`_,
and `SOP Class UID <https://dicom.innolitics.com/ciods/ct-image/sop-common/00080016>`_).
- The binary storage of each slice must be the same (have the same
`Bits Allocated <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280100>`_,
`Bits Stored <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280101>`_,
`High Bit <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280102>`_, and
`Pixel Representation <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280103>`_).
- The image slice must approximately form a grid. This means there can not
be any missing internal slices (missing slices on the ends of the dataset
are not detected).
- It also means that each slice must have the same
`Rows <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280010>`_,
`Columns <https://dicom.innolitics.com/ciods/ct-image/image-pixel/00280011>`_,
`Pixel Spacing <https://dicom.innolitics.com/ciods/ct-image/image-plane/00280030>`_, and
`Image Orientation (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200037>`_
attribute values.
- The direction cosines derived from the
`Image Orientation (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200037>`_
attribute must, within 1e-4, have a magnitude of 1. The cosines must
also be approximately perpendicular (their dot-product must be within
1e-4 of 0). Warnings are displayed if any of these approximations are
below 1e-8, however, since we have seen real datasets with values up to
1e-4, we let them pass.
- The `Image Position (Patient) <https://dicom.innolitics.com/ciods/ct-image/image-plane/00200032>`_
values must approximately form a line.
If any of these conditions are not met, a `dicom_numpy.DicomImportException` is raised. | [
"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",
"... | c870f0302276e7eaa0b66e641bacee19fe090296 | https://github.com/innolitics/dicom-numpy/blob/c870f0302276e7eaa0b66e641bacee19fe090296/dicom_numpy/combine_slices.py#L12-L74 |
18,677 | 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.
'''
invariant_properties = [
'Modality',
'SOPClassUID',
'SeriesInstanceUID',
'Rows',
'Columns',
'PixelSpacing',
'PixelRepresentation',
'BitsAllocated',
'BitsStored',
'HighBit',
]
for property_name in invariant_properties:
_slice_attribute_equal(slice_datasets, property_name)
_validate_image_orientation(slice_datasets[0].ImageOrientationPatient)
_slice_ndarray_attribute_almost_equal(slice_datasets, 'ImageOrientationPatient', 1e-5)
slice_positions = _slice_positions(slice_datasets)
_check_for_missing_slices(slice_positions) | 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.
'''
invariant_properties = [
'Modality',
'SOPClassUID',
'SeriesInstanceUID',
'Rows',
'Columns',
'PixelSpacing',
'PixelRepresentation',
'BitsAllocated',
'BitsStored',
'HighBit',
]
for property_name in invariant_properties:
_slice_attribute_equal(slice_datasets, property_name)
_validate_image_orientation(slice_datasets[0].ImageOrientationPatient)
_slice_ndarray_attribute_almost_equal(slice_datasets, 'ImageOrientationPatient', 1e-5)
slice_positions = _slice_positions(slice_datasets)
_check_for_missing_slices(slice_positions) | [
"def",
"_validate_slices_form_uniform_grid",
"(",
"slice_datasets",
")",
":",
"invariant_properties",
"=",
"[",
"'Modality'",
",",
"'SOPClassUID'",
",",
"'SeriesInstanceUID'",
",",
"'Rows'",
",",
"'Columns'",
",",
"'PixelSpacing'",
",",
"'PixelRepresentation'",
",",
"'B... | 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",
"f... | c870f0302276e7eaa0b66e641bacee19fe090296 | https://github.com/innolitics/dicom-numpy/blob/c870f0302276e7eaa0b66e641bacee19fe090296/dicom_numpy/combine_slices.py#L126-L153 |
18,678 | 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 optional keys 'branch' and 'version_guid'.
Raises:
InvalidKeyError: if string cannot be parsed -or- string ends with a newline.
"""
match = cls.URL_RE.match(string)
if not match:
raise InvalidKeyError(cls, string)
return match.groupdict() | python | def parse_url(cls, string): # pylint: disable=redefined-outer-name
match = cls.URL_RE.match(string)
if not match:
raise InvalidKeyError(cls, string)
return match.groupdict() | [
"def",
"parse_url",
"(",
"cls",
",",
"string",
")",
":",
"# pylint: disable=redefined-outer-name",
"match",
"=",
"cls",
".",
"URL_RE",
".",
"match",
"(",
"string",
")",
"if",
"not",
"match",
":",
"raise",
"InvalidKeyError",
"(",
"cls",
",",
"string",
")",
... | 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 string cannot be parsed -or- string ends with a newline. | [
"If",
"it",
"can",
"be",
"parsed",
"as",
"a",
"version_guid",
"with",
"no",
"preceding",
"org",
"+",
"offering",
"returns",
"a",
"dict",
"with",
"key",
"version_guid",
"and",
"the",
"value"
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L110-L124 |
18,679 | 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.course and not self.run:
return None
elif not self.run and self.course:
return self.course
return "/".join([self.course, self.run]) | python | def offering(self):
warnings.warn(
"Offering is no longer a supported property of Locator. Please use the course and run properties.",
DeprecationWarning,
stacklevel=2
)
if not self.course and not self.run:
return None
elif not self.run and self.course:
return self.course
return "/".join([self.course, self.run]) | [
"def",
"offering",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Offering is no longer a supported property of Locator. Please use the course and run properties.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"if",
"not",
"self",
".",
"course",... | Deprecated. Use course and run independently. | [
"Deprecated",
".",
"Use",
"course",
"and",
"run",
"independently",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L234-L247 |
18,680 | 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 does not parse
"""
warnings.warn(
"make_usage_key_from_deprecated_string is deprecated! Please use make_usage_key",
DeprecationWarning,
stacklevel=2
)
return BlockUsageLocator.from_string(location_url).replace(run=self.run) | python | def make_usage_key_from_deprecated_string(self, location_url):
warnings.warn(
"make_usage_key_from_deprecated_string is deprecated! Please use make_usage_key",
DeprecationWarning,
stacklevel=2
)
return BlockUsageLocator.from_string(location_url).replace(run=self.run) | [
"def",
"make_usage_key_from_deprecated_string",
"(",
"self",
",",
"location_url",
")",
":",
"warnings",
".",
"warn",
"(",
"\"make_usage_key_from_deprecated_string is deprecated! Please use make_usage_key\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return... | 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 | [
"Deprecated",
"mechanism",
"for",
"creating",
"a",
"UsageKey",
"given",
"a",
"CourseKey",
"and",
"a",
"serialized",
"Location",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L283-L297 |
18,681 | 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
parsed_parts = cls.parse_url(serialized)
block_id = parsed_parts.get('block_id', None)
if block_id is None:
raise InvalidKeyError(cls, serialized)
return cls(course_key, parsed_parts.get('block_type'), block_id) | python | def _from_string(cls, serialized):
# Allow access to _from_string protected method
course_key = CourseLocator._from_string(serialized) # pylint: disable=protected-access
parsed_parts = cls.parse_url(serialized)
block_id = parsed_parts.get('block_id', None)
if block_id is None:
raise InvalidKeyError(cls, serialized)
return cls(course_key, parsed_parts.get('block_type'), block_id) | [
"def",
"_from_string",
"(",
"cls",
",",
"serialized",
")",
":",
"# Allow access to _from_string protected method",
"course_key",
"=",
"CourseLocator",
".",
"_from_string",
"(",
"serialized",
")",
"# pylint: disable=protected-access",
"parsed_parts",
"=",
"cls",
".",
"pars... | Requests CourseLocator to deserialize its part and then adds the local deserialization of block | [
"Requests",
"CourseLocator",
"to",
"deserialize",
"its",
"part",
"and",
"then",
"adds",
"the",
"local",
"deserialization",
"of",
"block"
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L720-L730 |
18,682 | 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:
return None
if isinstance(block_ref, LocalId):
return block_ref
is_valid_deprecated = deprecated and cls.DEPRECATED_ALLOWED_ID_RE.match(block_ref)
is_valid = cls.ALLOWED_ID_RE.match(block_ref)
if is_valid or is_valid_deprecated:
return block_ref
else:
raise InvalidKeyError(cls, block_ref) | python | def _parse_block_ref(cls, block_ref, deprecated=False):
if deprecated and block_ref is None:
return None
if isinstance(block_ref, LocalId):
return block_ref
is_valid_deprecated = deprecated and cls.DEPRECATED_ALLOWED_ID_RE.match(block_ref)
is_valid = cls.ALLOWED_ID_RE.match(block_ref)
if is_valid or is_valid_deprecated:
return block_ref
else:
raise InvalidKeyError(cls, block_ref) | [
"def",
"_parse_block_ref",
"(",
"cls",
",",
"block_ref",
",",
"deprecated",
"=",
"False",
")",
":",
"if",
"deprecated",
"and",
"block_ref",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"block_ref",
",",
"LocalId",
")",
":",
"return",
"bloc... | 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. | [
"Given",
"block_ref",
"tries",
"to",
"parse",
"it",
"into",
"a",
"valid",
"block",
"reference",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L766-L788 |
18,683 | 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, but I have no way to override. We should clearly define the purpose and restrictions of this
(e.g., I'm assuming periods are fine).
"""
if self.deprecated:
id_fields = [self.DEPRECATED_TAG, self.org, self.course, self.block_type, self.block_id, self.version_guid]
id_string = u"-".join([v for v in id_fields if v is not None])
return self.clean_for_html(id_string)
else:
return self.block_id | python | def html_id(self):
if self.deprecated:
id_fields = [self.DEPRECATED_TAG, self.org, self.course, self.block_type, self.block_id, self.version_guid]
id_string = u"-".join([v for v in id_fields if v is not None])
return self.clean_for_html(id_string)
else:
return self.block_id | [
"def",
"html_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"deprecated",
":",
"id_fields",
"=",
"[",
"self",
".",
"DEPRECATED_TAG",
",",
"self",
".",
"org",
",",
"self",
".",
"course",
",",
"self",
".",
"block_type",
",",
"self",
".",
"block_id",
",... | 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 should clearly define the purpose and restrictions of this
(e.g., I'm assuming periods are fine). | [
"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",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L930-L944 |
18,684 | edx/opaque-keys | opaque_keys/edx/locator.py | BlockUsageLocator.to_deprecated_son | def to_deprecated_son(self, prefix='', tag='i4x'):
"""
Returns a SON object that represents this location
"""
# This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'),
# because that format was used to store data historically in mongo
# adding tag b/c deprecated form used it
son = SON({prefix + 'tag': tag})
for field_name in ('org', 'course'):
# Temporary filtering of run field because deprecated form left it out
son[prefix + field_name] = getattr(self.course_key, field_name)
for (dep_field_name, field_name) in [('category', 'block_type'), ('name', 'block_id')]:
son[prefix + dep_field_name] = getattr(self, field_name)
son[prefix + 'revision'] = self.course_key.branch
return son | python | def to_deprecated_son(self, prefix='', tag='i4x'):
# This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'),
# because that format was used to store data historically in mongo
# adding tag b/c deprecated form used it
son = SON({prefix + 'tag': tag})
for field_name in ('org', 'course'):
# Temporary filtering of run field because deprecated form left it out
son[prefix + field_name] = getattr(self.course_key, field_name)
for (dep_field_name, field_name) in [('category', 'block_type'), ('name', 'block_id')]:
son[prefix + dep_field_name] = getattr(self, field_name)
son[prefix + 'revision'] = self.course_key.branch
return son | [
"def",
"to_deprecated_son",
"(",
"self",
",",
"prefix",
"=",
"''",
",",
"tag",
"=",
"'i4x'",
")",
":",
"# This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'),",
"# because that format was used to store data historically in mongo",
"# adding tag b/... | Returns a SON object that represents this location | [
"Returns",
"a",
"SON",
"object",
"that",
"represents",
"this",
"location"
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L996-L1012 |
18,685 | edx/opaque-keys | opaque_keys/edx/locator.py | BlockUsageLocator._from_deprecated_son | def _from_deprecated_son(cls, id_dict, run):
"""
Return the Location decoding this id_dict and run
"""
course_key = CourseLocator(
id_dict['org'],
id_dict['course'],
run,
id_dict['revision'],
deprecated=True,
)
return cls(course_key, id_dict['category'], id_dict['name'], deprecated=True) | python | def _from_deprecated_son(cls, id_dict, run):
course_key = CourseLocator(
id_dict['org'],
id_dict['course'],
run,
id_dict['revision'],
deprecated=True,
)
return cls(course_key, id_dict['category'], id_dict['name'], deprecated=True) | [
"def",
"_from_deprecated_son",
"(",
"cls",
",",
"id_dict",
",",
"run",
")",
":",
"course_key",
"=",
"CourseLocator",
"(",
"id_dict",
"[",
"'org'",
"]",
",",
"id_dict",
"[",
"'course'",
"]",
",",
"run",
",",
"id_dict",
"[",
"'revision'",
"]",
",",
"deprec... | Return the Location decoding this id_dict and run | [
"Return",
"the",
"Location",
"decoding",
"this",
"id_dict",
"and",
"run"
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1015-L1026 |
18,686 | edx/opaque-keys | opaque_keys/edx/locator.py | LibraryUsageLocator._from_string | def _from_string(cls, serialized):
"""
Requests LibraryLocator to deserialize its part and then adds the local deserialization of block
"""
# Allow access to _from_string protected method
library_key = LibraryLocator._from_string(serialized) # pylint: disable=protected-access
parsed_parts = LibraryLocator.parse_url(serialized)
block_id = parsed_parts.get('block_id', None)
if block_id is None:
raise InvalidKeyError(cls, serialized)
block_type = parsed_parts.get('block_type')
if block_type is None:
raise InvalidKeyError(cls, serialized)
return cls(library_key, parsed_parts.get('block_type'), block_id) | python | def _from_string(cls, serialized):
# Allow access to _from_string protected method
library_key = LibraryLocator._from_string(serialized) # pylint: disable=protected-access
parsed_parts = LibraryLocator.parse_url(serialized)
block_id = parsed_parts.get('block_id', None)
if block_id is None:
raise InvalidKeyError(cls, serialized)
block_type = parsed_parts.get('block_type')
if block_type is None:
raise InvalidKeyError(cls, serialized)
return cls(library_key, parsed_parts.get('block_type'), block_id) | [
"def",
"_from_string",
"(",
"cls",
",",
"serialized",
")",
":",
"# Allow access to _from_string protected method",
"library_key",
"=",
"LibraryLocator",
".",
"_from_string",
"(",
"serialized",
")",
"# pylint: disable=protected-access",
"parsed_parts",
"=",
"LibraryLocator",
... | Requests LibraryLocator to deserialize its part and then adds the local deserialization of block | [
"Requests",
"LibraryLocator",
"to",
"deserialize",
"its",
"part",
"and",
"then",
"adds",
"the",
"local",
"deserialization",
"of",
"block"
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1087-L1103 |
18,687 | edx/opaque-keys | opaque_keys/edx/locator.py | LibraryUsageLocator.for_branch | def for_branch(self, branch):
"""
Return a UsageLocator for the same block in a different branch of the library.
"""
return self.replace(library_key=self.library_key.for_branch(branch)) | python | def for_branch(self, branch):
return self.replace(library_key=self.library_key.for_branch(branch)) | [
"def",
"for_branch",
"(",
"self",
",",
"branch",
")",
":",
"return",
"self",
".",
"replace",
"(",
"library_key",
"=",
"self",
".",
"library_key",
".",
"for_branch",
"(",
"branch",
")",
")"
] | Return a UsageLocator for the same block in a different branch of the library. | [
"Return",
"a",
"UsageLocator",
"for",
"the",
"same",
"block",
"in",
"a",
"different",
"branch",
"of",
"the",
"library",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1116-L1120 |
18,688 | edx/opaque-keys | opaque_keys/edx/locator.py | LibraryUsageLocator.for_version | def for_version(self, version_guid):
"""
Return a UsageLocator for the same block in a different version of the library.
"""
return self.replace(library_key=self.library_key.for_version(version_guid)) | python | def for_version(self, version_guid):
return self.replace(library_key=self.library_key.for_version(version_guid)) | [
"def",
"for_version",
"(",
"self",
",",
"version_guid",
")",
":",
"return",
"self",
".",
"replace",
"(",
"library_key",
"=",
"self",
".",
"library_key",
".",
"for_version",
"(",
"version_guid",
")",
")"
] | Return a UsageLocator for the same block in a different version of the library. | [
"Return",
"a",
"UsageLocator",
"for",
"the",
"same",
"block",
"in",
"a",
"different",
"version",
"of",
"the",
"library",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1122-L1126 |
18,689 | edx/opaque-keys | opaque_keys/edx/django/models.py | _strip_object | def _strip_object(key):
"""
Strips branch and version info if the given key supports those attributes.
"""
if hasattr(key, 'version_agnostic') and hasattr(key, 'for_branch'):
return key.for_branch(None).version_agnostic()
else:
return key | python | def _strip_object(key):
if hasattr(key, 'version_agnostic') and hasattr(key, 'for_branch'):
return key.for_branch(None).version_agnostic()
else:
return key | [
"def",
"_strip_object",
"(",
"key",
")",
":",
"if",
"hasattr",
"(",
"key",
",",
"'version_agnostic'",
")",
"and",
"hasattr",
"(",
"key",
",",
"'for_branch'",
")",
":",
"return",
"key",
".",
"for_branch",
"(",
"None",
")",
".",
"version_agnostic",
"(",
")... | Strips branch and version info if the given key supports those attributes. | [
"Strips",
"branch",
"and",
"version",
"info",
"if",
"the",
"given",
"key",
"supports",
"those",
"attributes",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/django/models.py#L58-L65 |
18,690 | edx/opaque-keys | opaque_keys/edx/django/models.py | _strip_value | def _strip_value(value, lookup='exact'):
"""
Helper function to remove the branch and version information from the given value,
which could be a single object or a list.
"""
if lookup == 'in':
stripped_value = [_strip_object(el) for el in value]
else:
stripped_value = _strip_object(value)
return stripped_value | python | def _strip_value(value, lookup='exact'):
if lookup == 'in':
stripped_value = [_strip_object(el) for el in value]
else:
stripped_value = _strip_object(value)
return stripped_value | [
"def",
"_strip_value",
"(",
"value",
",",
"lookup",
"=",
"'exact'",
")",
":",
"if",
"lookup",
"==",
"'in'",
":",
"stripped_value",
"=",
"[",
"_strip_object",
"(",
"el",
")",
"for",
"el",
"in",
"value",
"]",
"else",
":",
"stripped_value",
"=",
"_strip_obj... | Helper function to remove the branch and version information from the given value,
which could be a single object or a list. | [
"Helper",
"function",
"to",
"remove",
"the",
"branch",
"and",
"version",
"information",
"from",
"the",
"given",
"value",
"which",
"could",
"be",
"a",
"single",
"object",
"or",
"a",
"list",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/django/models.py#L68-L77 |
18,691 | edx/opaque-keys | opaque_keys/edx/locations.py | LocationBase._deprecation_warning | def _deprecation_warning(cls):
"""Display a deprecation warning for the given cls"""
if issubclass(cls, Location):
warnings.warn(
"Location is deprecated! Please use locator.BlockUsageLocator",
DeprecationWarning,
stacklevel=3
)
elif issubclass(cls, AssetLocation):
warnings.warn(
"AssetLocation is deprecated! Please use locator.AssetLocator",
DeprecationWarning,
stacklevel=3
)
else:
warnings.warn(
"{} is deprecated!".format(cls),
DeprecationWarning,
stacklevel=3
) | python | def _deprecation_warning(cls):
if issubclass(cls, Location):
warnings.warn(
"Location is deprecated! Please use locator.BlockUsageLocator",
DeprecationWarning,
stacklevel=3
)
elif issubclass(cls, AssetLocation):
warnings.warn(
"AssetLocation is deprecated! Please use locator.AssetLocator",
DeprecationWarning,
stacklevel=3
)
else:
warnings.warn(
"{} is deprecated!".format(cls),
DeprecationWarning,
stacklevel=3
) | [
"def",
"_deprecation_warning",
"(",
"cls",
")",
":",
"if",
"issubclass",
"(",
"cls",
",",
"Location",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Location is deprecated! Please use locator.BlockUsageLocator\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"3",
... | Display a deprecation warning for the given cls | [
"Display",
"a",
"deprecation",
"warning",
"for",
"the",
"given",
"cls"
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L84-L103 |
18,692 | edx/opaque-keys | opaque_keys/edx/locations.py | LocationBase._check_location_part | def _check_location_part(cls, val, regexp):
"""Deprecated. See CourseLocator._check_location_part"""
cls._deprecation_warning()
return CourseLocator._check_location_part(val, regexp) | python | def _check_location_part(cls, val, regexp):
cls._deprecation_warning()
return CourseLocator._check_location_part(val, regexp) | [
"def",
"_check_location_part",
"(",
"cls",
",",
"val",
",",
"regexp",
")",
":",
"cls",
".",
"_deprecation_warning",
"(",
")",
"return",
"CourseLocator",
".",
"_check_location_part",
"(",
"val",
",",
"regexp",
")"
] | Deprecated. See CourseLocator._check_location_part | [
"Deprecated",
".",
"See",
"CourseLocator",
".",
"_check_location_part"
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L116-L119 |
18,693 | edx/opaque-keys | opaque_keys/edx/locations.py | LocationBase._clean | def _clean(cls, value, invalid):
"""Deprecated. See BlockUsageLocator._clean"""
cls._deprecation_warning()
return BlockUsageLocator._clean(value, invalid) | python | def _clean(cls, value, invalid):
cls._deprecation_warning()
return BlockUsageLocator._clean(value, invalid) | [
"def",
"_clean",
"(",
"cls",
",",
"value",
",",
"invalid",
")",
":",
"cls",
".",
"_deprecation_warning",
"(",
")",
"return",
"BlockUsageLocator",
".",
"_clean",
"(",
"value",
",",
"invalid",
")"
] | Deprecated. See BlockUsageLocator._clean | [
"Deprecated",
".",
"See",
"BlockUsageLocator",
".",
"_clean"
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locations.py#L122-L125 |
18,694 | edx/opaque-keys | opaque_keys/edx/asides.py | _join_keys_v1 | def _join_keys_v1(left, right):
"""
Join two keys into a format separable by using _split_keys_v1.
"""
if left.endswith(':') or '::' in left:
raise ValueError("Can't join a left string ending in ':' or containing '::'")
return u"{}::{}".format(_encode_v1(left), _encode_v1(right)) | python | def _join_keys_v1(left, right):
if left.endswith(':') or '::' in left:
raise ValueError("Can't join a left string ending in ':' or containing '::'")
return u"{}::{}".format(_encode_v1(left), _encode_v1(right)) | [
"def",
"_join_keys_v1",
"(",
"left",
",",
"right",
")",
":",
"if",
"left",
".",
"endswith",
"(",
"':'",
")",
"or",
"'::'",
"in",
"left",
":",
"raise",
"ValueError",
"(",
"\"Can't join a left string ending in ':' or containing '::'\"",
")",
"return",
"u\"{}::{}\"",... | Join two keys into a format separable by using _split_keys_v1. | [
"Join",
"two",
"keys",
"into",
"a",
"format",
"separable",
"by",
"using",
"_split_keys_v1",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L49-L55 |
18,695 | edx/opaque-keys | opaque_keys/edx/asides.py | _split_keys_v1 | def _split_keys_v1(joined):
"""
Split two keys out a string created by _join_keys_v1.
"""
left, _, right = joined.partition('::')
return _decode_v1(left), _decode_v1(right) | python | def _split_keys_v1(joined):
left, _, right = joined.partition('::')
return _decode_v1(left), _decode_v1(right) | [
"def",
"_split_keys_v1",
"(",
"joined",
")",
":",
"left",
",",
"_",
",",
"right",
"=",
"joined",
".",
"partition",
"(",
"'::'",
")",
"return",
"_decode_v1",
"(",
"left",
")",
",",
"_decode_v1",
"(",
"right",
")"
] | Split two keys out a string created by _join_keys_v1. | [
"Split",
"two",
"keys",
"out",
"a",
"string",
"created",
"by",
"_join_keys_v1",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L58-L63 |
18,696 | edx/opaque-keys | opaque_keys/edx/asides.py | _split_keys_v2 | def _split_keys_v2(joined):
"""
Split two keys out a string created by _join_keys_v2.
"""
left, _, right = joined.rpartition('::')
return _decode_v2(left), _decode_v2(right) | python | def _split_keys_v2(joined):
left, _, right = joined.rpartition('::')
return _decode_v2(left), _decode_v2(right) | [
"def",
"_split_keys_v2",
"(",
"joined",
")",
":",
"left",
",",
"_",
",",
"right",
"=",
"joined",
".",
"rpartition",
"(",
"'::'",
")",
"return",
"_decode_v2",
"(",
"left",
")",
",",
"_decode_v2",
"(",
"right",
")"
] | Split two keys out a string created by _join_keys_v2. | [
"Split",
"two",
"keys",
"out",
"a",
"string",
"created",
"by",
"_join_keys_v2",
"."
] | 9807168660c12e0551c8fdd58fd1bc6b0bcb0a54 | https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/asides.py#L97-L102 |
18,697 | dbcli/athenacli | athenacli/completion_refresher.py | refresher | def refresher(name, refreshers=CompletionRefresher.refreshers):
"""Decorator to add the decorated function to the dictionary of
refreshers. Any function decorated with a @refresher will be executed as
part of the completion refresh routine."""
def wrapper(wrapped):
refreshers[name] = wrapped
return wrapped
return wrapper | python | def refresher(name, refreshers=CompletionRefresher.refreshers):
def wrapper(wrapped):
refreshers[name] = wrapped
return wrapped
return wrapper | [
"def",
"refresher",
"(",
"name",
",",
"refreshers",
"=",
"CompletionRefresher",
".",
"refreshers",
")",
":",
"def",
"wrapper",
"(",
"wrapped",
")",
":",
"refreshers",
"[",
"name",
"]",
"=",
"wrapped",
"return",
"wrapped",
"return",
"wrapper"
] | Decorator to add the decorated function to the dictionary of
refreshers. Any function decorated with a @refresher will be executed as
part of the completion refresh routine. | [
"Decorator",
"to",
"add",
"the",
"decorated",
"function",
"to",
"the",
"dictionary",
"of",
"refreshers",
".",
"Any",
"function",
"decorated",
"with",
"a"
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completion_refresher.py#L86-L93 |
18,698 | dbcli/athenacli | athenacli/completion_refresher.py | CompletionRefresher.refresh | def refresh(self, executor, callbacks, completer_options=None):
"""Creates a SQLCompleter object and populates it with the relevant
completion suggestions in a background thread.
executor - SQLExecute object, used to extract the credentials to connect
to the database.
callbacks - A function or a list of functions to call after the thread
has completed the refresh. The newly created completion
object will be passed in as an argument to each callback.
completer_options - dict of options to pass to SQLCompleter.
"""
if completer_options is None:
completer_options = {}
if self.is_refreshing():
self._restart_refresh.set()
return [(None, None, None, 'Auto-completion refresh restarted.')]
else:
self._completer_thread = threading.Thread(
target=self._bg_refresh,
args=(executor, callbacks, completer_options),
name='completion_refresh')
self._completer_thread.setDaemon(True)
self._completer_thread.start()
return [(None, None, None,
'Auto-completion refresh started in the background.')] | python | def refresh(self, executor, callbacks, completer_options=None):
if completer_options is None:
completer_options = {}
if self.is_refreshing():
self._restart_refresh.set()
return [(None, None, None, 'Auto-completion refresh restarted.')]
else:
self._completer_thread = threading.Thread(
target=self._bg_refresh,
args=(executor, callbacks, completer_options),
name='completion_refresh')
self._completer_thread.setDaemon(True)
self._completer_thread.start()
return [(None, None, None,
'Auto-completion refresh started in the background.')] | [
"def",
"refresh",
"(",
"self",
",",
"executor",
",",
"callbacks",
",",
"completer_options",
"=",
"None",
")",
":",
"if",
"completer_options",
"is",
"None",
":",
"completer_options",
"=",
"{",
"}",
"if",
"self",
".",
"is_refreshing",
"(",
")",
":",
"self",
... | Creates a SQLCompleter object and populates it with the relevant
completion suggestions in a background thread.
executor - SQLExecute object, used to extract the credentials to connect
to the database.
callbacks - A function or a list of functions to call after the thread
has completed the refresh. The newly created completion
object will be passed in as an argument to each callback.
completer_options - dict of options to pass to SQLCompleter. | [
"Creates",
"a",
"SQLCompleter",
"object",
"and",
"populates",
"it",
"with",
"the",
"relevant",
"completion",
"suggestions",
"in",
"a",
"background",
"thread",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/completion_refresher.py#L20-L45 |
18,699 | dbcli/athenacli | athenacli/packages/special/utils.py | handle_cd_command | def handle_cd_command(arg):
"""Handles a `cd` shell command by calling python's os.chdir."""
CD_CMD = 'cd'
tokens = arg.split(CD_CMD + ' ')
directory = tokens[-1] if len(tokens) > 1 else None
if not directory:
return False, "No folder name was provided."
try:
os.chdir(directory)
subprocess.call(['pwd'])
return True, None
except OSError as e:
return False, e.strerror | python | def handle_cd_command(arg):
CD_CMD = 'cd'
tokens = arg.split(CD_CMD + ' ')
directory = tokens[-1] if len(tokens) > 1 else None
if not directory:
return False, "No folder name was provided."
try:
os.chdir(directory)
subprocess.call(['pwd'])
return True, None
except OSError as e:
return False, e.strerror | [
"def",
"handle_cd_command",
"(",
"arg",
")",
":",
"CD_CMD",
"=",
"'cd'",
"tokens",
"=",
"arg",
".",
"split",
"(",
"CD_CMD",
"+",
"' '",
")",
"directory",
"=",
"tokens",
"[",
"-",
"1",
"]",
"if",
"len",
"(",
"tokens",
")",
">",
"1",
"else",
"None",
... | Handles a `cd` shell command by calling python's os.chdir. | [
"Handles",
"a",
"cd",
"shell",
"command",
"by",
"calling",
"python",
"s",
"os",
".",
"chdir",
"."
] | bcab59e4953145866430083e902ed4d042d4ebba | https://github.com/dbcli/athenacli/blob/bcab59e4953145866430083e902ed4d042d4ebba/athenacli/packages/special/utils.py#L5-L17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.