repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
skulumani/kinematics | kinematics/attitude.py | hat_map | def hat_map(vec):
"""Return that hat map of a vector
Inputs:
vec - 3 element vector
Outputs:
skew - 3,3 skew symmetric matrix
"""
vec = np.squeeze(vec)
skew = np.array([
[0, -vec[2], vec[1]],
[vec[2], 0, -vec[0]],
[-vec[1], vec[0], 0]])
return skew | python | def hat_map(vec):
"""Return that hat map of a vector
Inputs:
vec - 3 element vector
Outputs:
skew - 3,3 skew symmetric matrix
"""
vec = np.squeeze(vec)
skew = np.array([
[0, -vec[2], vec[1]],
[vec[2], 0, -vec[0]],
[-vec[1], vec[0], 0]])
return skew | [
"def",
"hat_map",
"(",
"vec",
")",
":",
"vec",
"=",
"np",
".",
"squeeze",
"(",
"vec",
")",
"skew",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0",
",",
"-",
"vec",
"[",
"2",
"]",
",",
"vec",
"[",
"1",
"]",
"]",
",",
"[",
"vec",
"[",
"2",
"... | Return that hat map of a vector
Inputs:
vec - 3 element vector
Outputs:
skew - 3,3 skew symmetric matrix | [
"Return",
"that",
"hat",
"map",
"of",
"a",
"vector",
"Inputs",
":",
"vec",
"-",
"3",
"element",
"vector"
] | train | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L244-L260 |
skulumani/kinematics | kinematics/attitude.py | vee_map | def vee_map(skew):
"""Return the vee map of a vector
"""
vec = 1/2 * np.array([skew[2,1] - skew[1,2],
skew[0,2] - skew[2,0],
skew[1,0] - skew[0,1]])
return vec | python | def vee_map(skew):
"""Return the vee map of a vector
"""
vec = 1/2 * np.array([skew[2,1] - skew[1,2],
skew[0,2] - skew[2,0],
skew[1,0] - skew[0,1]])
return vec | [
"def",
"vee_map",
"(",
"skew",
")",
":",
"vec",
"=",
"1",
"/",
"2",
"*",
"np",
".",
"array",
"(",
"[",
"skew",
"[",
"2",
",",
"1",
"]",
"-",
"skew",
"[",
"1",
",",
"2",
"]",
",",
"skew",
"[",
"0",
",",
"2",
"]",
"-",
"skew",
"[",
"2",
... | Return the vee map of a vector | [
"Return",
"the",
"vee",
"map",
"of",
"a",
"vector"
] | train | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L262-L271 |
skulumani/kinematics | kinematics/attitude.py | dcmtoquat | def dcmtoquat(dcm):
"""Convert DCM to quaternion
This function will convert a rotation matrix, also called a direction
cosine matrix into the equivalent quaternion.
Parameters:
----------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame
Returns:
--------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w]
"""
quat = np.zeros(4)
quat[-1] = 1/2*np.sqrt(np.trace(dcm)+1)
quat[0:3] = 1/4/quat[-1]*vee_map(dcm-dcm.T)
return quat | python | def dcmtoquat(dcm):
"""Convert DCM to quaternion
This function will convert a rotation matrix, also called a direction
cosine matrix into the equivalent quaternion.
Parameters:
----------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame
Returns:
--------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w]
"""
quat = np.zeros(4)
quat[-1] = 1/2*np.sqrt(np.trace(dcm)+1)
quat[0:3] = 1/4/quat[-1]*vee_map(dcm-dcm.T)
return quat | [
"def",
"dcmtoquat",
"(",
"dcm",
")",
":",
"quat",
"=",
"np",
".",
"zeros",
"(",
"4",
")",
"quat",
"[",
"-",
"1",
"]",
"=",
"1",
"/",
"2",
"*",
"np",
".",
"sqrt",
"(",
"np",
".",
"trace",
"(",
"dcm",
")",
"+",
"1",
")",
"quat",
"[",
"0",
... | Convert DCM to quaternion
This function will convert a rotation matrix, also called a direction
cosine matrix into the equivalent quaternion.
Parameters:
----------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame
Returns:
--------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w] | [
"Convert",
"DCM",
"to",
"quaternion",
"This",
"function",
"will",
"convert",
"a",
"rotation",
"matrix",
"also",
"called",
"a",
"direction",
"cosine",
"matrix",
"into",
"the",
"equivalent",
"quaternion",
"."
] | train | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L273-L295 |
skulumani/kinematics | kinematics/attitude.py | quattodcm | def quattodcm(quat):
"""Convert quaternion to DCM
This function will convert a quaternion to the equivalent rotation matrix,
or direction cosine matrix.
Parameters:
----------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w]
Returns:
--------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame
"""
dcm = (quat[-1]**2-np.inner(quat[0:3], quat[0:3]))*np.eye(3,3) + 2*np.outer(quat[0:3],quat[0:3]) + 2*quat[-1]*hat_map(quat[0:3])
return dcm | python | def quattodcm(quat):
"""Convert quaternion to DCM
This function will convert a quaternion to the equivalent rotation matrix,
or direction cosine matrix.
Parameters:
----------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w]
Returns:
--------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame
"""
dcm = (quat[-1]**2-np.inner(quat[0:3], quat[0:3]))*np.eye(3,3) + 2*np.outer(quat[0:3],quat[0:3]) + 2*quat[-1]*hat_map(quat[0:3])
return dcm | [
"def",
"quattodcm",
"(",
"quat",
")",
":",
"dcm",
"=",
"(",
"quat",
"[",
"-",
"1",
"]",
"**",
"2",
"-",
"np",
".",
"inner",
"(",
"quat",
"[",
"0",
":",
"3",
"]",
",",
"quat",
"[",
"0",
":",
"3",
"]",
")",
")",
"*",
"np",
".",
"eye",
"("... | Convert quaternion to DCM
This function will convert a quaternion to the equivalent rotation matrix,
or direction cosine matrix.
Parameters:
----------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w]
Returns:
--------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame | [
"Convert",
"quaternion",
"to",
"DCM"
] | train | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L297-L318 |
skulumani/kinematics | kinematics/attitude.py | dcmdottoang_vel | def dcmdottoang_vel(R,Rdot):
"""Convert a rotation matrix to angular velocity
w - angular velocity in inertial frame
Omega - angular velocity in body frame
"""
w = vee_map(Rdot.dot(R.T))
Omega = vee_map(R.T.dot(Rdot))
return (w, Omega) | python | def dcmdottoang_vel(R,Rdot):
"""Convert a rotation matrix to angular velocity
w - angular velocity in inertial frame
Omega - angular velocity in body frame
"""
w = vee_map(Rdot.dot(R.T))
Omega = vee_map(R.T.dot(Rdot))
return (w, Omega) | [
"def",
"dcmdottoang_vel",
"(",
"R",
",",
"Rdot",
")",
":",
"w",
"=",
"vee_map",
"(",
"Rdot",
".",
"dot",
"(",
"R",
".",
"T",
")",
")",
"Omega",
"=",
"vee_map",
"(",
"R",
".",
"T",
".",
"dot",
"(",
"Rdot",
")",
")",
"return",
"(",
"w",
",",
... | Convert a rotation matrix to angular velocity
w - angular velocity in inertial frame
Omega - angular velocity in body frame | [
"Convert",
"a",
"rotation",
"matrix",
"to",
"angular",
"velocity",
"w",
"-",
"angular",
"velocity",
"in",
"inertial",
"frame",
"Omega",
"-",
"angular",
"velocity",
"in",
"body",
"frame"
] | train | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L349-L358 |
skulumani/kinematics | kinematics/attitude.py | ang_veltoaxisangledot | def ang_veltoaxisangledot(angle, axis, Omega):
"""Compute kinematics for axis angle representation
"""
angle_dot = axis.dot(Omega)
axis_dot = 1/2*(hat_map(axis) - 1/np.tan(angle/2) * hat_map(axis).dot(hat_map(axis))).dot(Omega)
return angle_dot, axis_dot | python | def ang_veltoaxisangledot(angle, axis, Omega):
"""Compute kinematics for axis angle representation
"""
angle_dot = axis.dot(Omega)
axis_dot = 1/2*(hat_map(axis) - 1/np.tan(angle/2) * hat_map(axis).dot(hat_map(axis))).dot(Omega)
return angle_dot, axis_dot | [
"def",
"ang_veltoaxisangledot",
"(",
"angle",
",",
"axis",
",",
"Omega",
")",
":",
"angle_dot",
"=",
"axis",
".",
"dot",
"(",
"Omega",
")",
"axis_dot",
"=",
"1",
"/",
"2",
"*",
"(",
"hat_map",
"(",
"axis",
")",
"-",
"1",
"/",
"np",
".",
"tan",
"(... | Compute kinematics for axis angle representation | [
"Compute",
"kinematics",
"for",
"axis",
"angle",
"representation"
] | train | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L368-L374 |
skulumani/kinematics | kinematics/attitude.py | axisangledottoang_vel | def axisangledottoang_vel(angle,axis, angle_dot,axis_dot):
"""Convert axis angle represetnation to angular velocity in body frame
"""
Omega = angle_dot*axis + np.sin(angle)*axis_dot - (1-np.cos(angle))*hat_map(axis).dot(axis_dot)
return Omega | python | def axisangledottoang_vel(angle,axis, angle_dot,axis_dot):
"""Convert axis angle represetnation to angular velocity in body frame
"""
Omega = angle_dot*axis + np.sin(angle)*axis_dot - (1-np.cos(angle))*hat_map(axis).dot(axis_dot)
return Omega | [
"def",
"axisangledottoang_vel",
"(",
"angle",
",",
"axis",
",",
"angle_dot",
",",
"axis_dot",
")",
":",
"Omega",
"=",
"angle_dot",
"*",
"axis",
"+",
"np",
".",
"sin",
"(",
"angle",
")",
"*",
"axis_dot",
"-",
"(",
"1",
"-",
"np",
".",
"cos",
"(",
"a... | Convert axis angle represetnation to angular velocity in body frame | [
"Convert",
"axis",
"angle",
"represetnation",
"to",
"angular",
"velocity",
"in",
"body",
"frame"
] | train | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L376-L382 |
skulumani/kinematics | kinematics/attitude.py | normalize | def normalize(num_in, lower=0, upper=360, b=False):
"""Normalize number to range [lower, upper) or [lower, upper].
Parameters
----------
num : float
The number to be normalized.
lower : int
Lower limit of range. Default is 0.
upper : int
Upper limit of range. Default is 360.
b : bool
Type of normalization. Default is False. See notes.
When b=True, the range must be symmetric about 0.
When b=False, the range must be symmetric about 0 or ``lower`` must
be equal to 0.
Returns
-------
n : float
A number in the range [lower, upper) or [lower, upper].
Raises
------
ValueError
If lower >= upper.
Notes
-----
If the keyword `b == False`, then the normalization is done in the
following way. Consider the numbers to be arranged in a circle,
with the lower and upper ends sitting on top of each other. Moving
past one limit, takes the number into the beginning of the other
end. For example, if range is [0 - 360), then 361 becomes 1 and 360
becomes 0. Negative numbers move from higher to lower numbers. So,
-1 normalized to [0 - 360) becomes 359.
When b=False range must be symmetric about 0 or lower=0.
If the keyword `b == True`, then the given number is considered to
"bounce" between the two limits. So, -91 normalized to [-90, 90],
becomes -89, instead of 89. In this case the range is [lower,
upper]. This code is based on the function `fmt_delta` of `TPM`.
When b=True range must be symmetric about 0.
Examples
--------
>>> normalize(-270,-180,180)
90.0
>>> import math
>>> math.degrees(normalize(-2*math.pi,-math.pi,math.pi))
0.0
>>> normalize(-180, -180, 180)
-180.0
>>> normalize(180, -180, 180)
-180.0
>>> normalize(180, -180, 180, b=True)
180.0
>>> normalize(181,-180,180)
-179.0
>>> normalize(181, -180, 180, b=True)
179.0
>>> normalize(-180,0,360)
180.0
>>> normalize(36,0,24)
12.0
>>> normalize(368.5,-180,180)
8.5
>>> normalize(-100, -90, 90)
80.0
>>> normalize(-100, -90, 90, b=True)
-80.0
>>> normalize(100, -90, 90, b=True)
80.0
>>> normalize(181, -90, 90, b=True)
-1.0
>>> normalize(270, -90, 90, b=True)
-90.0
>>> normalize(271, -90, 90, b=True)
-89.0
"""
if lower >= upper:
ValueError("lower must be lesser than upper")
if not b:
if not ((lower + upper == 0) or (lower == 0)):
raise ValueError('When b=False lower=0 or range must be symmetric about 0.')
else:
if not (lower + upper == 0):
raise ValueError('When b=True range must be symmetric about 0.')
# abs(num + upper) and abs(num - lower) are needed, instead of
# abs(num), since the lower and upper limits need not be 0. We need
# to add half size of the range, so that the final result is lower +
# <value> or upper - <value>, respectively.
if not hasattr(num_in, "__iter__"):
num_in = np.asarray([num_in], dtype=np.float)
res = []
for num in num_in:
if not b:
if num > upper or num == lower:
num = lower + abs(num + upper) % (abs(lower) + abs(upper))
if num < lower or num == upper:
num = upper - abs(num - lower) % (abs(lower) + abs(upper))
res.append(lower if num == upper else num)
else:
total_length = abs(lower) + abs(upper)
if num < -total_length:
num += ceil(num / (-2 * total_length)) * 2 * total_length
if num > total_length:
num -= floor(num / (2 * total_length)) * 2 * total_length
if num > upper:
num = total_length - num
if num < lower:
num = -total_length - num
res.append(num)
return np.asarray(res, dtype=np.float) | python | def normalize(num_in, lower=0, upper=360, b=False):
"""Normalize number to range [lower, upper) or [lower, upper].
Parameters
----------
num : float
The number to be normalized.
lower : int
Lower limit of range. Default is 0.
upper : int
Upper limit of range. Default is 360.
b : bool
Type of normalization. Default is False. See notes.
When b=True, the range must be symmetric about 0.
When b=False, the range must be symmetric about 0 or ``lower`` must
be equal to 0.
Returns
-------
n : float
A number in the range [lower, upper) or [lower, upper].
Raises
------
ValueError
If lower >= upper.
Notes
-----
If the keyword `b == False`, then the normalization is done in the
following way. Consider the numbers to be arranged in a circle,
with the lower and upper ends sitting on top of each other. Moving
past one limit, takes the number into the beginning of the other
end. For example, if range is [0 - 360), then 361 becomes 1 and 360
becomes 0. Negative numbers move from higher to lower numbers. So,
-1 normalized to [0 - 360) becomes 359.
When b=False range must be symmetric about 0 or lower=0.
If the keyword `b == True`, then the given number is considered to
"bounce" between the two limits. So, -91 normalized to [-90, 90],
becomes -89, instead of 89. In this case the range is [lower,
upper]. This code is based on the function `fmt_delta` of `TPM`.
When b=True range must be symmetric about 0.
Examples
--------
>>> normalize(-270,-180,180)
90.0
>>> import math
>>> math.degrees(normalize(-2*math.pi,-math.pi,math.pi))
0.0
>>> normalize(-180, -180, 180)
-180.0
>>> normalize(180, -180, 180)
-180.0
>>> normalize(180, -180, 180, b=True)
180.0
>>> normalize(181,-180,180)
-179.0
>>> normalize(181, -180, 180, b=True)
179.0
>>> normalize(-180,0,360)
180.0
>>> normalize(36,0,24)
12.0
>>> normalize(368.5,-180,180)
8.5
>>> normalize(-100, -90, 90)
80.0
>>> normalize(-100, -90, 90, b=True)
-80.0
>>> normalize(100, -90, 90, b=True)
80.0
>>> normalize(181, -90, 90, b=True)
-1.0
>>> normalize(270, -90, 90, b=True)
-90.0
>>> normalize(271, -90, 90, b=True)
-89.0
"""
if lower >= upper:
ValueError("lower must be lesser than upper")
if not b:
if not ((lower + upper == 0) or (lower == 0)):
raise ValueError('When b=False lower=0 or range must be symmetric about 0.')
else:
if not (lower + upper == 0):
raise ValueError('When b=True range must be symmetric about 0.')
# abs(num + upper) and abs(num - lower) are needed, instead of
# abs(num), since the lower and upper limits need not be 0. We need
# to add half size of the range, so that the final result is lower +
# <value> or upper - <value>, respectively.
if not hasattr(num_in, "__iter__"):
num_in = np.asarray([num_in], dtype=np.float)
res = []
for num in num_in:
if not b:
if num > upper or num == lower:
num = lower + abs(num + upper) % (abs(lower) + abs(upper))
if num < lower or num == upper:
num = upper - abs(num - lower) % (abs(lower) + abs(upper))
res.append(lower if num == upper else num)
else:
total_length = abs(lower) + abs(upper)
if num < -total_length:
num += ceil(num / (-2 * total_length)) * 2 * total_length
if num > total_length:
num -= floor(num / (2 * total_length)) * 2 * total_length
if num > upper:
num = total_length - num
if num < lower:
num = -total_length - num
res.append(num)
return np.asarray(res, dtype=np.float) | [
"def",
"normalize",
"(",
"num_in",
",",
"lower",
"=",
"0",
",",
"upper",
"=",
"360",
",",
"b",
"=",
"False",
")",
":",
"if",
"lower",
">=",
"upper",
":",
"ValueError",
"(",
"\"lower must be lesser than upper\"",
")",
"if",
"not",
"b",
":",
"if",
"not",... | Normalize number to range [lower, upper) or [lower, upper].
Parameters
----------
num : float
The number to be normalized.
lower : int
Lower limit of range. Default is 0.
upper : int
Upper limit of range. Default is 360.
b : bool
Type of normalization. Default is False. See notes.
When b=True, the range must be symmetric about 0.
When b=False, the range must be symmetric about 0 or ``lower`` must
be equal to 0.
Returns
-------
n : float
A number in the range [lower, upper) or [lower, upper].
Raises
------
ValueError
If lower >= upper.
Notes
-----
If the keyword `b == False`, then the normalization is done in the
following way. Consider the numbers to be arranged in a circle,
with the lower and upper ends sitting on top of each other. Moving
past one limit, takes the number into the beginning of the other
end. For example, if range is [0 - 360), then 361 becomes 1 and 360
becomes 0. Negative numbers move from higher to lower numbers. So,
-1 normalized to [0 - 360) becomes 359.
When b=False range must be symmetric about 0 or lower=0.
If the keyword `b == True`, then the given number is considered to
"bounce" between the two limits. So, -91 normalized to [-90, 90],
becomes -89, instead of 89. In this case the range is [lower,
upper]. This code is based on the function `fmt_delta` of `TPM`.
When b=True range must be symmetric about 0.
Examples
--------
>>> normalize(-270,-180,180)
90.0
>>> import math
>>> math.degrees(normalize(-2*math.pi,-math.pi,math.pi))
0.0
>>> normalize(-180, -180, 180)
-180.0
>>> normalize(180, -180, 180)
-180.0
>>> normalize(180, -180, 180, b=True)
180.0
>>> normalize(181,-180,180)
-179.0
>>> normalize(181, -180, 180, b=True)
179.0
>>> normalize(-180,0,360)
180.0
>>> normalize(36,0,24)
12.0
>>> normalize(368.5,-180,180)
8.5
>>> normalize(-100, -90, 90)
80.0
>>> normalize(-100, -90, 90, b=True)
-80.0
>>> normalize(100, -90, 90, b=True)
80.0
>>> normalize(181, -90, 90, b=True)
-1.0
>>> normalize(270, -90, 90, b=True)
-90.0
>>> normalize(271, -90, 90, b=True)
-89.0 | [
"Normalize",
"number",
"to",
"range",
"[",
"lower",
"upper",
")",
"or",
"[",
"lower",
"upper",
"]",
"."
] | train | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L388-L509 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/repos.py | list_repos | def list_repos(owner=None, **kwargs):
"""List repositories in a namespace."""
client = get_repos_api()
api_kwargs = {}
api_kwargs.update(utils.get_page_kwargs(**kwargs))
# pylint: disable=fixme
# FIXME: Compatibility code until we work out how to conflate
# the overlapping repos_list methods into one.
repos_list = client.repos_list_with_http_info
if owner is not None:
api_kwargs["owner"] = owner
if hasattr(client, "repos_list0_with_http_info"):
# pylint: disable=no-member
repos_list = client.repos_list0_with_http_info
else:
if hasattr(client, "repos_all_list_with_http_info"):
# pylint: disable=no-member
repos_list = client.repos_all_list_with_http_info
with catch_raise_api_exception():
res, _, headers = repos_list(**api_kwargs)
ratelimits.maybe_rate_limit(client, headers)
page_info = PageInfo.from_headers(headers)
return [x.to_dict() for x in res], page_info | python | def list_repos(owner=None, **kwargs):
"""List repositories in a namespace."""
client = get_repos_api()
api_kwargs = {}
api_kwargs.update(utils.get_page_kwargs(**kwargs))
# pylint: disable=fixme
# FIXME: Compatibility code until we work out how to conflate
# the overlapping repos_list methods into one.
repos_list = client.repos_list_with_http_info
if owner is not None:
api_kwargs["owner"] = owner
if hasattr(client, "repos_list0_with_http_info"):
# pylint: disable=no-member
repos_list = client.repos_list0_with_http_info
else:
if hasattr(client, "repos_all_list_with_http_info"):
# pylint: disable=no-member
repos_list = client.repos_all_list_with_http_info
with catch_raise_api_exception():
res, _, headers = repos_list(**api_kwargs)
ratelimits.maybe_rate_limit(client, headers)
page_info = PageInfo.from_headers(headers)
return [x.to_dict() for x in res], page_info | [
"def",
"list_repos",
"(",
"owner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"get_repos_api",
"(",
")",
"api_kwargs",
"=",
"{",
"}",
"api_kwargs",
".",
"update",
"(",
"utils",
".",
"get_page_kwargs",
"(",
"*",
"*",
"kwargs",
")",
... | List repositories in a namespace. | [
"List",
"repositories",
"in",
"a",
"namespace",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/repos.py#L18-L45 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/copy.py | copy | def copy(
ctx,
opts,
owner_repo_package,
destination,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'.
- DEST: Specify the DEST (destination) repository to copy the package to.
This *must* be in the same namespace as the source repository.
Example: 'other-repo'
Full CLI example:
$ cloudsmith cp your-org/awesome-repo/better-pkg other-repo
"""
owner, source, slug = owner_repo_package
click.echo(
"Copying %(slug)s package from %(source)s to %(dest)s ... "
% {
"slug": click.style(slug, bold=True),
"source": click.style(source, bold=True),
"dest": click.style(destination, bold=True),
},
nl=False,
)
context_msg = "Failed to copy package!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
_, new_slug = copy_package(
owner=owner, repo=source, identifier=slug, destination=destination
)
click.secho("OK", fg="green")
if no_wait_for_sync:
return
wait_for_package_sync(
ctx=ctx,
opts=opts,
owner=owner,
repo=destination,
slug=new_slug,
wait_interval=wait_interval,
skip_errors=skip_errors,
attempts=sync_attempts,
) | python | def copy(
ctx,
opts,
owner_repo_package,
destination,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'.
- DEST: Specify the DEST (destination) repository to copy the package to.
This *must* be in the same namespace as the source repository.
Example: 'other-repo'
Full CLI example:
$ cloudsmith cp your-org/awesome-repo/better-pkg other-repo
"""
owner, source, slug = owner_repo_package
click.echo(
"Copying %(slug)s package from %(source)s to %(dest)s ... "
% {
"slug": click.style(slug, bold=True),
"source": click.style(source, bold=True),
"dest": click.style(destination, bold=True),
},
nl=False,
)
context_msg = "Failed to copy package!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
_, new_slug = copy_package(
owner=owner, repo=source, identifier=slug, destination=destination
)
click.secho("OK", fg="green")
if no_wait_for_sync:
return
wait_for_package_sync(
ctx=ctx,
opts=opts,
owner=owner,
repo=destination,
slug=new_slug,
wait_interval=wait_interval,
skip_errors=skip_errors,
attempts=sync_attempts,
) | [
"def",
"copy",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_package",
",",
"destination",
",",
"skip_errors",
",",
"wait_interval",
",",
"no_wait_for_sync",
",",
"sync_attempts",
",",
")",
":",
"owner",
",",
"source",
",",
"slug",
"=",
"owner_repo_package",
"clic... | Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'.
- DEST: Specify the DEST (destination) repository to copy the package to.
This *must* be in the same namespace as the source repository.
Example: 'other-repo'
Full CLI example:
$ cloudsmith cp your-org/awesome-repo/better-pkg other-repo | [
"Copy",
"a",
"package",
"to",
"another",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/copy.py#L28-L94 |
visualfabriq/bquery | bquery/ctable.py | rm_file_or_dir | def rm_file_or_dir(path, ignore_errors=True):
"""
Helper function to clean a certain filepath
Parameters
----------
path
Returns
-------
"""
if os.path.exists(path):
if os.path.isdir(path):
if os.path.islink(path):
os.unlink(path)
else:
shutil.rmtree(path, ignore_errors=ignore_errors)
else:
if os.path.islink(path):
os.unlink(path)
else:
os.remove(path) | python | def rm_file_or_dir(path, ignore_errors=True):
"""
Helper function to clean a certain filepath
Parameters
----------
path
Returns
-------
"""
if os.path.exists(path):
if os.path.isdir(path):
if os.path.islink(path):
os.unlink(path)
else:
shutil.rmtree(path, ignore_errors=ignore_errors)
else:
if os.path.islink(path):
os.unlink(path)
else:
os.remove(path) | [
"def",
"rm_file_or_dir",
"(",
"path",
",",
"ignore_errors",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"islink"... | Helper function to clean a certain filepath
Parameters
----------
path
Returns
------- | [
"Helper",
"function",
"to",
"clean",
"a",
"certain",
"filepath"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L12-L34 |
visualfabriq/bquery | bquery/ctable.py | ctable.cache_valid | def cache_valid(self, col):
"""
Checks whether the column has a factorization that exists and is not older than the source
:param col:
:return:
"""
cache_valid = False
if self.rootdir:
col_org_file_check = self[col].rootdir + '/__attrs__'
col_values_file_check = self[col].rootdir + '.values/__attrs__'
cache_valid = os.path.exists(col_org_file_check) and os.path.exists(col_values_file_check)
return cache_valid | python | def cache_valid(self, col):
"""
Checks whether the column has a factorization that exists and is not older than the source
:param col:
:return:
"""
cache_valid = False
if self.rootdir:
col_org_file_check = self[col].rootdir + '/__attrs__'
col_values_file_check = self[col].rootdir + '.values/__attrs__'
cache_valid = os.path.exists(col_org_file_check) and os.path.exists(col_values_file_check)
return cache_valid | [
"def",
"cache_valid",
"(",
"self",
",",
"col",
")",
":",
"cache_valid",
"=",
"False",
"if",
"self",
".",
"rootdir",
":",
"col_org_file_check",
"=",
"self",
"[",
"col",
"]",
".",
"rootdir",
"+",
"'/__attrs__'",
"col_values_file_check",
"=",
"self",
"[",
"co... | Checks whether the column has a factorization that exists and is not older than the source
:param col:
:return: | [
"Checks",
"whether",
"the",
"column",
"has",
"a",
"factorization",
"that",
"exists",
"and",
"is",
"not",
"older",
"than",
"the",
"source"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L60-L74 |
visualfabriq/bquery | bquery/ctable.py | ctable.group_cache_valid | def group_cache_valid(self, col_list):
"""
Checks whether the column has a factorization that exists and is not older than the source
:param col:
:return:
"""
cache_valid = False
if self.rootdir:
col_values_file_check = os.path.join(self.rootdir, self.create_group_base_name(col_list)) + \
'.values/__attrs__'
exists_group_index = os.path.exists(col_values_file_check)
missing_col_check = [1 for col in col_list if not os.path.exists(self[col].rootdir + '/__attrs__')]
cache_valid = (exists_group_index and not missing_col_check)
return cache_valid | python | def group_cache_valid(self, col_list):
"""
Checks whether the column has a factorization that exists and is not older than the source
:param col:
:return:
"""
cache_valid = False
if self.rootdir:
col_values_file_check = os.path.join(self.rootdir, self.create_group_base_name(col_list)) + \
'.values/__attrs__'
exists_group_index = os.path.exists(col_values_file_check)
missing_col_check = [1 for col in col_list if not os.path.exists(self[col].rootdir + '/__attrs__')]
cache_valid = (exists_group_index and not missing_col_check)
return cache_valid | [
"def",
"group_cache_valid",
"(",
"self",
",",
"col_list",
")",
":",
"cache_valid",
"=",
"False",
"if",
"self",
".",
"rootdir",
":",
"col_values_file_check",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"rootdir",
",",
"self",
".",
"create_group_b... | Checks whether the column has a factorization that exists and is not older than the source
:param col:
:return: | [
"Checks",
"whether",
"the",
"column",
"has",
"a",
"factorization",
"that",
"exists",
"and",
"is",
"not",
"older",
"than",
"the",
"source"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L76-L93 |
visualfabriq/bquery | bquery/ctable.py | ctable.cache_factor | def cache_factor(self, col_list, refresh=False):
"""
Existing todos here are: these should be hidden helper carrays
As in: not normal columns that you would normally see as a user
The factor (label index) carray is as long as the original carray
(and the rest of the table therefore)
But the (unique) values carray is not as long (as long as the number
of unique values)
:param col_list:
:param refresh:
:return:
"""
if not self.rootdir:
raise TypeError('Only out-of-core ctables can have '
'factorization caching at the moment')
if not isinstance(col_list, list):
col_list = [col_list]
if refresh:
kill_list = [x for x in os.listdir(self.rootdir) if '.factor' in x or '.values' in x]
for kill_dir in kill_list:
rm_file_or_dir(os.path.join(self.rootdir, kill_dir))
for col in col_list:
# create cache if needed
if refresh or not self.cache_valid(col):
# todo: also add locking mechanism here
# create directories
col_rootdir = self[col].rootdir
col_factor_rootdir = col_rootdir + '.factor'
col_factor_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
col_values_rootdir = col_rootdir + '.values'
col_values_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
# create factor
carray_factor = \
bcolz.carray([], dtype='int64', expectedlen=self.size,
rootdir=col_factor_rootdir_tmp, mode='w')
_, values = \
ctable_ext.factorize(self[col], labels=carray_factor)
carray_factor.flush()
rm_file_or_dir(col_factor_rootdir, ignore_errors=True)
shutil.move(col_factor_rootdir_tmp, col_factor_rootdir)
# create values
carray_values = \
bcolz.carray(np.fromiter(values.values(), dtype=self[col].dtype),
rootdir=col_values_rootdir_tmp, mode='w')
carray_values.flush()
rm_file_or_dir(col_values_rootdir, ignore_errors=True)
shutil.move(col_values_rootdir_tmp, col_values_rootdir) | python | def cache_factor(self, col_list, refresh=False):
"""
Existing todos here are: these should be hidden helper carrays
As in: not normal columns that you would normally see as a user
The factor (label index) carray is as long as the original carray
(and the rest of the table therefore)
But the (unique) values carray is not as long (as long as the number
of unique values)
:param col_list:
:param refresh:
:return:
"""
if not self.rootdir:
raise TypeError('Only out-of-core ctables can have '
'factorization caching at the moment')
if not isinstance(col_list, list):
col_list = [col_list]
if refresh:
kill_list = [x for x in os.listdir(self.rootdir) if '.factor' in x or '.values' in x]
for kill_dir in kill_list:
rm_file_or_dir(os.path.join(self.rootdir, kill_dir))
for col in col_list:
# create cache if needed
if refresh or not self.cache_valid(col):
# todo: also add locking mechanism here
# create directories
col_rootdir = self[col].rootdir
col_factor_rootdir = col_rootdir + '.factor'
col_factor_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
col_values_rootdir = col_rootdir + '.values'
col_values_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
# create factor
carray_factor = \
bcolz.carray([], dtype='int64', expectedlen=self.size,
rootdir=col_factor_rootdir_tmp, mode='w')
_, values = \
ctable_ext.factorize(self[col], labels=carray_factor)
carray_factor.flush()
rm_file_or_dir(col_factor_rootdir, ignore_errors=True)
shutil.move(col_factor_rootdir_tmp, col_factor_rootdir)
# create values
carray_values = \
bcolz.carray(np.fromiter(values.values(), dtype=self[col].dtype),
rootdir=col_values_rootdir_tmp, mode='w')
carray_values.flush()
rm_file_or_dir(col_values_rootdir, ignore_errors=True)
shutil.move(col_values_rootdir_tmp, col_values_rootdir) | [
"def",
"cache_factor",
"(",
"self",
",",
"col_list",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"rootdir",
":",
"raise",
"TypeError",
"(",
"'Only out-of-core ctables can have '",
"'factorization caching at the moment'",
")",
"if",
"not",
"is... | Existing todos here are: these should be hidden helper carrays
As in: not normal columns that you would normally see as a user
The factor (label index) carray is as long as the original carray
(and the rest of the table therefore)
But the (unique) values carray is not as long (as long as the number
of unique values)
:param col_list:
:param refresh:
:return: | [
"Existing",
"todos",
"here",
"are",
":",
"these",
"should",
"be",
"hidden",
"helper",
"carrays",
"As",
"in",
":",
"not",
"normal",
"columns",
"that",
"you",
"would",
"normally",
"see",
"as",
"a",
"user"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L95-L152 |
visualfabriq/bquery | bquery/ctable.py | ctable.unique | def unique(self, col_or_col_list):
"""
Return a list of unique values of a column or a list of lists of column list
:param col_or_col_list: a column or a list of columns
:return:
"""
if isinstance(col_or_col_list, list):
col_is_list = True
col_list = col_or_col_list
else:
col_is_list = False
col_list = [col_or_col_list]
output = []
for col in col_list:
if self.auto_cache or self.cache_valid(col):
# create factorization cache
if not self.cache_valid(col):
self.cache_factor([col])
# retrieve values from existing disk-based factorization
col_values_rootdir = self[col].rootdir + '.values'
carray_values = bcolz.carray(rootdir=col_values_rootdir, mode='r')
values = list(carray_values)
else:
# factorize on-the-fly
_, values = ctable_ext.factorize(self[col])
values = values.values()
output.append(values)
if not col_is_list:
output = output[0]
return output | python | def unique(self, col_or_col_list):
"""
Return a list of unique values of a column or a list of lists of column list
:param col_or_col_list: a column or a list of columns
:return:
"""
if isinstance(col_or_col_list, list):
col_is_list = True
col_list = col_or_col_list
else:
col_is_list = False
col_list = [col_or_col_list]
output = []
for col in col_list:
if self.auto_cache or self.cache_valid(col):
# create factorization cache
if not self.cache_valid(col):
self.cache_factor([col])
# retrieve values from existing disk-based factorization
col_values_rootdir = self[col].rootdir + '.values'
carray_values = bcolz.carray(rootdir=col_values_rootdir, mode='r')
values = list(carray_values)
else:
# factorize on-the-fly
_, values = ctable_ext.factorize(self[col])
values = values.values()
output.append(values)
if not col_is_list:
output = output[0]
return output | [
"def",
"unique",
"(",
"self",
",",
"col_or_col_list",
")",
":",
"if",
"isinstance",
"(",
"col_or_col_list",
",",
"list",
")",
":",
"col_is_list",
"=",
"True",
"col_list",
"=",
"col_or_col_list",
"else",
":",
"col_is_list",
"=",
"False",
"col_list",
"=",
"[",... | Return a list of unique values of a column or a list of lists of column list
:param col_or_col_list: a column or a list of columns
:return: | [
"Return",
"a",
"list",
"of",
"unique",
"values",
"of",
"a",
"column",
"or",
"a",
"list",
"of",
"lists",
"of",
"column",
"list"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L154-L192 |
visualfabriq/bquery | bquery/ctable.py | ctable.aggregate_groups | def aggregate_groups(self, ct_agg, nr_groups, skip_key,
carray_factor, groupby_cols, agg_ops,
dtype_dict, bool_arr=None):
'''Perform aggregation and place the result in the given ctable.
Args:
ct_agg (ctable): the table to hold the aggregation
nr_groups (int): the number of groups (number of rows in output table)
skip_key (int): index of the output row to remove from results (used for filtering)
carray_factor: the carray for each row in the table a reference to the the unique group index
groupby_cols: the list of 'dimension' columns that are used to perform the groupby over
output_agg_ops (list): list of tuples of the form: (input_col, agg_op)
input_col (string): name of the column to act on
agg_op (int): aggregation operation to perform
bool_arr: a boolean array containing the filter
'''
# this creates the groupby columns
for col in groupby_cols:
result_array = ctable_ext.groupby_value(self[col], carray_factor,
nr_groups, skip_key)
if bool_arr is not None:
result_array = np.delete(result_array, skip_key)
ct_agg.addcol(result_array, name=col)
del result_array
# this creates the aggregation columns
for input_col_name, output_col_name, agg_op in agg_ops:
input_col = self[input_col_name]
output_col_dtype = dtype_dict[output_col_name]
input_buffer = np.empty(input_col.chunklen, dtype=input_col.dtype)
output_buffer = np.zeros(nr_groups, dtype=output_col_dtype)
if agg_op == 'sum':
ctable_ext.aggregate_sum(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'mean':
ctable_ext.aggregate_mean(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'std':
ctable_ext.aggregate_std(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'count':
ctable_ext.aggregate_count(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'count_distinct':
ctable_ext.aggregate_count_distinct(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'sorted_count_distinct':
ctable_ext.aggregate_sorted_count_distinct(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
else:
raise KeyError('Unknown aggregation operation ' + str(agg_op))
if bool_arr is not None:
output_buffer = np.delete(output_buffer, skip_key)
ct_agg.addcol(output_buffer, name=output_col_name)
del output_buffer
ct_agg.delcol('tmp_col_bquery__') | python | def aggregate_groups(self, ct_agg, nr_groups, skip_key,
carray_factor, groupby_cols, agg_ops,
dtype_dict, bool_arr=None):
'''Perform aggregation and place the result in the given ctable.
Args:
ct_agg (ctable): the table to hold the aggregation
nr_groups (int): the number of groups (number of rows in output table)
skip_key (int): index of the output row to remove from results (used for filtering)
carray_factor: the carray for each row in the table a reference to the the unique group index
groupby_cols: the list of 'dimension' columns that are used to perform the groupby over
output_agg_ops (list): list of tuples of the form: (input_col, agg_op)
input_col (string): name of the column to act on
agg_op (int): aggregation operation to perform
bool_arr: a boolean array containing the filter
'''
# this creates the groupby columns
for col in groupby_cols:
result_array = ctable_ext.groupby_value(self[col], carray_factor,
nr_groups, skip_key)
if bool_arr is not None:
result_array = np.delete(result_array, skip_key)
ct_agg.addcol(result_array, name=col)
del result_array
# this creates the aggregation columns
for input_col_name, output_col_name, agg_op in agg_ops:
input_col = self[input_col_name]
output_col_dtype = dtype_dict[output_col_name]
input_buffer = np.empty(input_col.chunklen, dtype=input_col.dtype)
output_buffer = np.zeros(nr_groups, dtype=output_col_dtype)
if agg_op == 'sum':
ctable_ext.aggregate_sum(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'mean':
ctable_ext.aggregate_mean(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'std':
ctable_ext.aggregate_std(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'count':
ctable_ext.aggregate_count(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'count_distinct':
ctable_ext.aggregate_count_distinct(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
elif agg_op == 'sorted_count_distinct':
ctable_ext.aggregate_sorted_count_distinct(input_col, carray_factor, nr_groups,
skip_key, input_buffer, output_buffer)
else:
raise KeyError('Unknown aggregation operation ' + str(agg_op))
if bool_arr is not None:
output_buffer = np.delete(output_buffer, skip_key)
ct_agg.addcol(output_buffer, name=output_col_name)
del output_buffer
ct_agg.delcol('tmp_col_bquery__') | [
"def",
"aggregate_groups",
"(",
"self",
",",
"ct_agg",
",",
"nr_groups",
",",
"skip_key",
",",
"carray_factor",
",",
"groupby_cols",
",",
"agg_ops",
",",
"dtype_dict",
",",
"bool_arr",
"=",
"None",
")",
":",
"# this creates the groupby columns",
"for",
"col",
"i... | Perform aggregation and place the result in the given ctable.
Args:
ct_agg (ctable): the table to hold the aggregation
nr_groups (int): the number of groups (number of rows in output table)
skip_key (int): index of the output row to remove from results (used for filtering)
carray_factor: the carray for each row in the table a reference to the the unique group index
groupby_cols: the list of 'dimension' columns that are used to perform the groupby over
output_agg_ops (list): list of tuples of the form: (input_col, agg_op)
input_col (string): name of the column to act on
agg_op (int): aggregation operation to perform
bool_arr: a boolean array containing the filter | [
"Perform",
"aggregation",
"and",
"place",
"the",
"result",
"in",
"the",
"given",
"ctable",
"."
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L194-L260 |
visualfabriq/bquery | bquery/ctable.py | ctable.factorize_groupby_cols | def factorize_groupby_cols(self, groupby_cols):
"""
factorizes all columns that are used in the groupby
it will use cache carrays if available
if not yet auto_cache is valid, it will create cache carrays
"""
# first check if the factorized arrays already exist
# unless we need to refresh the cache
factor_list = []
values_list = []
# factorize the groupby columns
for col in groupby_cols:
if self.auto_cache or self.cache_valid(col):
# create factorization cache if needed
if not self.cache_valid(col):
self.cache_factor([col])
col_rootdir = self[col].rootdir
col_factor_rootdir = col_rootdir + '.factor'
col_values_rootdir = col_rootdir + '.values'
col_carray_factor = \
bcolz.carray(rootdir=col_factor_rootdir, mode='r')
col_carray_values = \
bcolz.carray(rootdir=col_values_rootdir, mode='r')
else:
col_carray_factor, values = ctable_ext.factorize(self[col])
col_carray_values = \
bcolz.carray(np.fromiter(values.values(), dtype=self[col].dtype))
factor_list.append(col_carray_factor)
values_list.append(col_carray_values)
return factor_list, values_list | python | def factorize_groupby_cols(self, groupby_cols):
"""
factorizes all columns that are used in the groupby
it will use cache carrays if available
if not yet auto_cache is valid, it will create cache carrays
"""
# first check if the factorized arrays already exist
# unless we need to refresh the cache
factor_list = []
values_list = []
# factorize the groupby columns
for col in groupby_cols:
if self.auto_cache or self.cache_valid(col):
# create factorization cache if needed
if not self.cache_valid(col):
self.cache_factor([col])
col_rootdir = self[col].rootdir
col_factor_rootdir = col_rootdir + '.factor'
col_values_rootdir = col_rootdir + '.values'
col_carray_factor = \
bcolz.carray(rootdir=col_factor_rootdir, mode='r')
col_carray_values = \
bcolz.carray(rootdir=col_values_rootdir, mode='r')
else:
col_carray_factor, values = ctable_ext.factorize(self[col])
col_carray_values = \
bcolz.carray(np.fromiter(values.values(), dtype=self[col].dtype))
factor_list.append(col_carray_factor)
values_list.append(col_carray_values)
return factor_list, values_list | [
"def",
"factorize_groupby_cols",
"(",
"self",
",",
"groupby_cols",
")",
":",
"# first check if the factorized arrays already exist",
"# unless we need to refresh the cache",
"factor_list",
"=",
"[",
"]",
"values_list",
"=",
"[",
"]",
"# factorize the groupby columns",
"for",
... | factorizes all columns that are used in the groupby
it will use cache carrays if available
if not yet auto_cache is valid, it will create cache carrays | [
"factorizes",
"all",
"columns",
"that",
"are",
"used",
"in",
"the",
"groupby",
"it",
"will",
"use",
"cache",
"carrays",
"if",
"available",
"if",
"not",
"yet",
"auto_cache",
"is",
"valid",
"it",
"will",
"create",
"cache",
"carrays"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L318-L353 |
visualfabriq/bquery | bquery/ctable.py | ctable._int_array_hash | def _int_array_hash(input_list):
"""
A function to calculate a hash value of multiple integer values, not used at the moment
Parameters
----------
input_list
Returns
-------
"""
list_len = len(input_list)
arr_len = len(input_list[0])
mult_arr = np.full(arr_len, 1000003, dtype=np.long)
value_arr = np.full(arr_len, 0x345678, dtype=np.long)
for i, current_arr in enumerate(input_list):
index = list_len - i - 1
value_arr ^= current_arr
value_arr *= mult_arr
mult_arr += (82520 + index + index)
value_arr += 97531
result_carray = bcolz.carray(value_arr)
del value_arr
return result_carray | python | def _int_array_hash(input_list):
"""
A function to calculate a hash value of multiple integer values, not used at the moment
Parameters
----------
input_list
Returns
-------
"""
list_len = len(input_list)
arr_len = len(input_list[0])
mult_arr = np.full(arr_len, 1000003, dtype=np.long)
value_arr = np.full(arr_len, 0x345678, dtype=np.long)
for i, current_arr in enumerate(input_list):
index = list_len - i - 1
value_arr ^= current_arr
value_arr *= mult_arr
mult_arr += (82520 + index + index)
value_arr += 97531
result_carray = bcolz.carray(value_arr)
del value_arr
return result_carray | [
"def",
"_int_array_hash",
"(",
"input_list",
")",
":",
"list_len",
"=",
"len",
"(",
"input_list",
")",
"arr_len",
"=",
"len",
"(",
"input_list",
"[",
"0",
"]",
")",
"mult_arr",
"=",
"np",
".",
"full",
"(",
"arr_len",
",",
"1000003",
",",
"dtype",
"=",
... | A function to calculate a hash value of multiple integer values, not used at the moment
Parameters
----------
input_list
Returns
------- | [
"A",
"function",
"to",
"calculate",
"a",
"hash",
"value",
"of",
"multiple",
"integer",
"values",
"not",
"used",
"at",
"the",
"moment"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L356-L383 |
visualfabriq/bquery | bquery/ctable.py | ctable.create_group_column_factor | def create_group_column_factor(self, factor_list, groupby_cols, cache=False):
"""
Create a unique, factorized column out of several individual columns
Parameters
----------
factor_list
groupby_cols
cache
Returns
-------
"""
if not self.rootdir:
# in-memory scenario
input_rootdir = None
col_rootdir = None
col_factor_rootdir = None
col_values_rootdir = None
col_factor_rootdir_tmp = None
col_values_rootdir_tmp = None
else:
# temporary
input_rootdir = tempfile.mkdtemp(prefix='bcolz-')
col_factor_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
col_values_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
# create combination of groupby columns
group_array = bcolz.zeros(0, dtype=np.int64, expectedlen=len(self), rootdir=input_rootdir, mode='w')
factor_table = bcolz.ctable(factor_list, names=groupby_cols)
ctable_iter = factor_table.iter(outcols=groupby_cols, out_flavor=tuple)
ctable_ext.create_group_index(ctable_iter, len(groupby_cols), group_array)
# now factorize the results
carray_factor = \
bcolz.carray([], dtype='int64', expectedlen=self.size, rootdir=col_factor_rootdir_tmp, mode='w')
carray_factor, values = ctable_ext.factorize(group_array, labels=carray_factor)
carray_factor.flush()
carray_values = \
bcolz.carray(np.fromiter(values.values(), dtype=np.int64), rootdir=col_values_rootdir_tmp, mode='w')
carray_values.flush()
del group_array
if cache:
# clean up the temporary file
rm_file_or_dir(input_rootdir, ignore_errors=True)
if cache:
# official end destination
col_rootdir = os.path.join(self.rootdir, self.create_group_base_name(groupby_cols))
col_factor_rootdir = col_rootdir + '.factor'
col_values_rootdir = col_rootdir + '.values'
lock_file = col_rootdir + '.lock'
# only works for linux
if not os.path.exists(lock_file):
uid = str(uuid.uuid4())
try:
with open(lock_file, 'a+') as fn:
fn.write(uid + '\n')
with open(lock_file, 'r') as fn:
temp = fn.read().splitlines()
if temp[0] == uid:
lock = True
else:
lock = False
del temp
except:
lock = False
else:
lock = False
if lock:
rm_file_or_dir(col_factor_rootdir, ignore_errors=False)
shutil.move(col_factor_rootdir_tmp, col_factor_rootdir)
carray_factor = bcolz.carray(rootdir=col_factor_rootdir, mode='r')
rm_file_or_dir(col_values_rootdir, ignore_errors=False)
shutil.move(col_values_rootdir_tmp, col_values_rootdir)
carray_values = bcolz.carray(rootdir=col_values_rootdir, mode='r')
else:
# another process has a lock, we will work with our current files and clean up later
self._dir_clean_list.append(col_factor_rootdir)
self._dir_clean_list.append(col_values_rootdir)
return carray_factor, carray_values | python | def create_group_column_factor(self, factor_list, groupby_cols, cache=False):
"""
Create a unique, factorized column out of several individual columns
Parameters
----------
factor_list
groupby_cols
cache
Returns
-------
"""
if not self.rootdir:
# in-memory scenario
input_rootdir = None
col_rootdir = None
col_factor_rootdir = None
col_values_rootdir = None
col_factor_rootdir_tmp = None
col_values_rootdir_tmp = None
else:
# temporary
input_rootdir = tempfile.mkdtemp(prefix='bcolz-')
col_factor_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
col_values_rootdir_tmp = tempfile.mkdtemp(prefix='bcolz-')
# create combination of groupby columns
group_array = bcolz.zeros(0, dtype=np.int64, expectedlen=len(self), rootdir=input_rootdir, mode='w')
factor_table = bcolz.ctable(factor_list, names=groupby_cols)
ctable_iter = factor_table.iter(outcols=groupby_cols, out_flavor=tuple)
ctable_ext.create_group_index(ctable_iter, len(groupby_cols), group_array)
# now factorize the results
carray_factor = \
bcolz.carray([], dtype='int64', expectedlen=self.size, rootdir=col_factor_rootdir_tmp, mode='w')
carray_factor, values = ctable_ext.factorize(group_array, labels=carray_factor)
carray_factor.flush()
carray_values = \
bcolz.carray(np.fromiter(values.values(), dtype=np.int64), rootdir=col_values_rootdir_tmp, mode='w')
carray_values.flush()
del group_array
if cache:
# clean up the temporary file
rm_file_or_dir(input_rootdir, ignore_errors=True)
if cache:
# official end destination
col_rootdir = os.path.join(self.rootdir, self.create_group_base_name(groupby_cols))
col_factor_rootdir = col_rootdir + '.factor'
col_values_rootdir = col_rootdir + '.values'
lock_file = col_rootdir + '.lock'
# only works for linux
if not os.path.exists(lock_file):
uid = str(uuid.uuid4())
try:
with open(lock_file, 'a+') as fn:
fn.write(uid + '\n')
with open(lock_file, 'r') as fn:
temp = fn.read().splitlines()
if temp[0] == uid:
lock = True
else:
lock = False
del temp
except:
lock = False
else:
lock = False
if lock:
rm_file_or_dir(col_factor_rootdir, ignore_errors=False)
shutil.move(col_factor_rootdir_tmp, col_factor_rootdir)
carray_factor = bcolz.carray(rootdir=col_factor_rootdir, mode='r')
rm_file_or_dir(col_values_rootdir, ignore_errors=False)
shutil.move(col_values_rootdir_tmp, col_values_rootdir)
carray_values = bcolz.carray(rootdir=col_values_rootdir, mode='r')
else:
# another process has a lock, we will work with our current files and clean up later
self._dir_clean_list.append(col_factor_rootdir)
self._dir_clean_list.append(col_values_rootdir)
return carray_factor, carray_values | [
"def",
"create_group_column_factor",
"(",
"self",
",",
"factor_list",
",",
"groupby_cols",
",",
"cache",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"rootdir",
":",
"# in-memory scenario",
"input_rootdir",
"=",
"None",
"col_rootdir",
"=",
"None",
"col_fact... | Create a unique, factorized column out of several individual columns
Parameters
----------
factor_list
groupby_cols
cache
Returns
------- | [
"Create",
"a",
"unique",
"factorized",
"column",
"out",
"of",
"several",
"individual",
"columns"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L385-L472 |
visualfabriq/bquery | bquery/ctable.py | ctable.make_group_index | def make_group_index(self, groupby_cols, bool_arr):
'''Create unique groups for groupby loop
Args:
factor_list:
values_list:
groupby_cols:
bool_arr:
Returns:
carray: (carray_factor)
int: (nr_groups) the number of resulting groups
int: (skip_key)
'''
factor_list, values_list = self.factorize_groupby_cols(groupby_cols)
# create unique groups for groupby loop
if len(factor_list) == 0:
# no columns to groupby over, so directly aggregate the measure
# columns to 1 total
tmp_rootdir = self.create_tmp_rootdir()
carray_factor = bcolz.zeros(len(self), dtype='int64', rootdir=tmp_rootdir, mode='w')
carray_values = ['Total']
elif len(factor_list) == 1:
# single column groupby, the groupby output column
# here is 1:1 to the values
carray_factor = factor_list[0]
carray_values = values_list[0]
else:
# multi column groupby
# first combine the factorized columns to single values
if self.group_cache_valid(col_list=groupby_cols):
# there is a group cache that we can use
col_rootdir = os.path.join(self.rootdir, self.create_group_base_name(groupby_cols))
col_factor_rootdir = col_rootdir + '.factor'
carray_factor = bcolz.carray(rootdir=col_factor_rootdir)
col_values_rootdir = col_rootdir + '.values'
carray_values = bcolz.carray(rootdir=col_values_rootdir)
else:
# create a brand new groupby col combination
carray_factor, carray_values = \
self.create_group_column_factor(factor_list, groupby_cols, cache=self.auto_cache)
nr_groups = len(carray_values)
skip_key = None
if bool_arr is not None:
# make all non relevant combinations -1
tmp_rootdir = self.create_tmp_rootdir()
carray_factor = bcolz.eval(
'(factor + 1) * bool - 1',
user_dict={'factor': carray_factor, 'bool': bool_arr}, rootdir=tmp_rootdir, mode='w')
# now check how many unique values there are left
tmp_rootdir = self.create_tmp_rootdir()
labels = bcolz.carray([], dtype='int64', expectedlen=len(carray_factor), rootdir=tmp_rootdir, mode='w')
carray_factor, values = ctable_ext.factorize(carray_factor, labels)
# values might contain one value too much (-1) (no direct lookup
# possible because values is a reversed dict)
filter_check = \
[key for key, value in values.items() if value == -1]
if filter_check:
skip_key = filter_check[0]
# the new nr of groups depends on the outcome after filtering
nr_groups = len(values)
# using nr_groups as a total length might be one one off due to the skip_key
# (skipping a row in aggregation)
# but that is okay normally
if skip_key is None:
# if we shouldn't skip a row, set it at the first row after the total number of groups
skip_key = nr_groups
return carray_factor, nr_groups, skip_key | python | def make_group_index(self, groupby_cols, bool_arr):
'''Create unique groups for groupby loop
Args:
factor_list:
values_list:
groupby_cols:
bool_arr:
Returns:
carray: (carray_factor)
int: (nr_groups) the number of resulting groups
int: (skip_key)
'''
factor_list, values_list = self.factorize_groupby_cols(groupby_cols)
# create unique groups for groupby loop
if len(factor_list) == 0:
# no columns to groupby over, so directly aggregate the measure
# columns to 1 total
tmp_rootdir = self.create_tmp_rootdir()
carray_factor = bcolz.zeros(len(self), dtype='int64', rootdir=tmp_rootdir, mode='w')
carray_values = ['Total']
elif len(factor_list) == 1:
# single column groupby, the groupby output column
# here is 1:1 to the values
carray_factor = factor_list[0]
carray_values = values_list[0]
else:
# multi column groupby
# first combine the factorized columns to single values
if self.group_cache_valid(col_list=groupby_cols):
# there is a group cache that we can use
col_rootdir = os.path.join(self.rootdir, self.create_group_base_name(groupby_cols))
col_factor_rootdir = col_rootdir + '.factor'
carray_factor = bcolz.carray(rootdir=col_factor_rootdir)
col_values_rootdir = col_rootdir + '.values'
carray_values = bcolz.carray(rootdir=col_values_rootdir)
else:
# create a brand new groupby col combination
carray_factor, carray_values = \
self.create_group_column_factor(factor_list, groupby_cols, cache=self.auto_cache)
nr_groups = len(carray_values)
skip_key = None
if bool_arr is not None:
# make all non relevant combinations -1
tmp_rootdir = self.create_tmp_rootdir()
carray_factor = bcolz.eval(
'(factor + 1) * bool - 1',
user_dict={'factor': carray_factor, 'bool': bool_arr}, rootdir=tmp_rootdir, mode='w')
# now check how many unique values there are left
tmp_rootdir = self.create_tmp_rootdir()
labels = bcolz.carray([], dtype='int64', expectedlen=len(carray_factor), rootdir=tmp_rootdir, mode='w')
carray_factor, values = ctable_ext.factorize(carray_factor, labels)
# values might contain one value too much (-1) (no direct lookup
# possible because values is a reversed dict)
filter_check = \
[key for key, value in values.items() if value == -1]
if filter_check:
skip_key = filter_check[0]
# the new nr of groups depends on the outcome after filtering
nr_groups = len(values)
# using nr_groups as a total length might be one one off due to the skip_key
# (skipping a row in aggregation)
# but that is okay normally
if skip_key is None:
# if we shouldn't skip a row, set it at the first row after the total number of groups
skip_key = nr_groups
return carray_factor, nr_groups, skip_key | [
"def",
"make_group_index",
"(",
"self",
",",
"groupby_cols",
",",
"bool_arr",
")",
":",
"factor_list",
",",
"values_list",
"=",
"self",
".",
"factorize_groupby_cols",
"(",
"groupby_cols",
")",
"# create unique groups for groupby loop",
"if",
"len",
"(",
"factor_list",... | Create unique groups for groupby loop
Args:
factor_list:
values_list:
groupby_cols:
bool_arr:
Returns:
carray: (carray_factor)
int: (nr_groups) the number of resulting groups
int: (skip_key) | [
"Create",
"unique",
"groups",
"for",
"groupby",
"loop"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L474-L547 |
visualfabriq/bquery | bquery/ctable.py | ctable.create_tmp_rootdir | def create_tmp_rootdir(self):
"""
create a rootdir that we can destroy later again
Returns
-------
"""
if self.rootdir:
tmp_rootdir = tempfile.mkdtemp(prefix='bcolz-')
self._dir_clean_list.append(tmp_rootdir)
else:
tmp_rootdir = None
return tmp_rootdir | python | def create_tmp_rootdir(self):
"""
create a rootdir that we can destroy later again
Returns
-------
"""
if self.rootdir:
tmp_rootdir = tempfile.mkdtemp(prefix='bcolz-')
self._dir_clean_list.append(tmp_rootdir)
else:
tmp_rootdir = None
return tmp_rootdir | [
"def",
"create_tmp_rootdir",
"(",
"self",
")",
":",
"if",
"self",
".",
"rootdir",
":",
"tmp_rootdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'bcolz-'",
")",
"self",
".",
"_dir_clean_list",
".",
"append",
"(",
"tmp_rootdir",
")",
"else",
":",... | create a rootdir that we can destroy later again
Returns
------- | [
"create",
"a",
"rootdir",
"that",
"we",
"can",
"destroy",
"later",
"again"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L549-L562 |
visualfabriq/bquery | bquery/ctable.py | ctable.clean_tmp_rootdir | def clean_tmp_rootdir(self):
"""
clean up all used temporary rootdirs
Returns
-------
"""
for tmp_rootdir in list(self._dir_clean_list):
rm_file_or_dir(tmp_rootdir)
self._dir_clean_list.remove(tmp_rootdir) | python | def clean_tmp_rootdir(self):
"""
clean up all used temporary rootdirs
Returns
-------
"""
for tmp_rootdir in list(self._dir_clean_list):
rm_file_or_dir(tmp_rootdir)
self._dir_clean_list.remove(tmp_rootdir) | [
"def",
"clean_tmp_rootdir",
"(",
"self",
")",
":",
"for",
"tmp_rootdir",
"in",
"list",
"(",
"self",
".",
"_dir_clean_list",
")",
":",
"rm_file_or_dir",
"(",
"tmp_rootdir",
")",
"self",
".",
"_dir_clean_list",
".",
"remove",
"(",
"tmp_rootdir",
")"
] | clean up all used temporary rootdirs
Returns
------- | [
"clean",
"up",
"all",
"used",
"temporary",
"rootdirs"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L564-L574 |
visualfabriq/bquery | bquery/ctable.py | ctable.create_agg_ctable | def create_agg_ctable(self, groupby_cols, agg_list, expectedlen, rootdir):
'''Create a container for the output table, a dictionary describing it's
columns and a list of tuples describing aggregation
operations to perform.
Args:
groupby_cols (list): a list of columns to groupby over
agg_list (list): the aggregation operations (see groupby for more info)
expectedlen (int): expected length of output table
rootdir (string): the directory to write the table to
Returns:
ctable: A table in the correct format for containing the output of
the specified aggregation operations.
dict: (dtype_dict) dictionary describing columns to create
list: (agg_ops) list of tuples of the form:
(input_col_name, output_col_name, agg_op)
input_col_name (string): name of the column to act on
output_col_name (string): name of the column to output to
agg_op (int): aggregation operation to perform
'''
dtype_dict = {}
# include all the groupby columns
for col in groupby_cols:
dtype_dict[col] = self[col].dtype
agg_ops_list = ['sum', 'count', 'count_distinct', 'sorted_count_distinct', 'mean', 'std']
agg_ops = []
for agg_info in agg_list:
if not isinstance(agg_info, list):
# example: ['m1', 'm2', ...]
# default operation (sum) and default output column name (same is input)
output_col_name = agg_info
input_col_name = agg_info
agg_op = 'sum'
else:
input_col_name = agg_info[0]
agg_op = agg_info[1]
if len(agg_info) == 2:
# example: [['m1', 'sum'], ['m2', 'mean], ...]
# default output column name
output_col_name = input_col_name
else:
# example: [['m1', 'sum', 'mnew1'], ['m1, 'mean','mnew2'], ...]
# fully specified
output_col_name = agg_info[2]
if agg_op not in agg_ops_list:
raise NotImplementedError(
'Unknown Aggregation Type: ' + str(agg_op))
# choose output column dtype based on aggregation operation and
# input column dtype
# TODO: check if the aggregation columns is numeric
# NB: we could build a concatenation for strings like pandas, but I would really prefer to see that as a
# separate operation
if agg_op in ('count', 'count_distinct', 'sorted_count_distinct'):
output_col_dtype = np.dtype(np.int64)
elif agg_op in ('mean', 'std'):
output_col_dtype = np.dtype(np.float64)
else:
output_col_dtype = self[input_col_name].dtype
dtype_dict[output_col_name] = output_col_dtype
# save output
agg_ops.append((input_col_name, output_col_name, agg_op))
# create aggregation table
ct_agg = bcolz.ctable(
np.zeros(expectedlen, [('tmp_col_bquery__', np.bool)]),
expectedlen=expectedlen,
rootdir=rootdir)
return ct_agg, dtype_dict, agg_ops | python | def create_agg_ctable(self, groupby_cols, agg_list, expectedlen, rootdir):
'''Create a container for the output table, a dictionary describing it's
columns and a list of tuples describing aggregation
operations to perform.
Args:
groupby_cols (list): a list of columns to groupby over
agg_list (list): the aggregation operations (see groupby for more info)
expectedlen (int): expected length of output table
rootdir (string): the directory to write the table to
Returns:
ctable: A table in the correct format for containing the output of
the specified aggregation operations.
dict: (dtype_dict) dictionary describing columns to create
list: (agg_ops) list of tuples of the form:
(input_col_name, output_col_name, agg_op)
input_col_name (string): name of the column to act on
output_col_name (string): name of the column to output to
agg_op (int): aggregation operation to perform
'''
dtype_dict = {}
# include all the groupby columns
for col in groupby_cols:
dtype_dict[col] = self[col].dtype
agg_ops_list = ['sum', 'count', 'count_distinct', 'sorted_count_distinct', 'mean', 'std']
agg_ops = []
for agg_info in agg_list:
if not isinstance(agg_info, list):
# example: ['m1', 'm2', ...]
# default operation (sum) and default output column name (same is input)
output_col_name = agg_info
input_col_name = agg_info
agg_op = 'sum'
else:
input_col_name = agg_info[0]
agg_op = agg_info[1]
if len(agg_info) == 2:
# example: [['m1', 'sum'], ['m2', 'mean], ...]
# default output column name
output_col_name = input_col_name
else:
# example: [['m1', 'sum', 'mnew1'], ['m1, 'mean','mnew2'], ...]
# fully specified
output_col_name = agg_info[2]
if agg_op not in agg_ops_list:
raise NotImplementedError(
'Unknown Aggregation Type: ' + str(agg_op))
# choose output column dtype based on aggregation operation and
# input column dtype
# TODO: check if the aggregation columns is numeric
# NB: we could build a concatenation for strings like pandas, but I would really prefer to see that as a
# separate operation
if agg_op in ('count', 'count_distinct', 'sorted_count_distinct'):
output_col_dtype = np.dtype(np.int64)
elif agg_op in ('mean', 'std'):
output_col_dtype = np.dtype(np.float64)
else:
output_col_dtype = self[input_col_name].dtype
dtype_dict[output_col_name] = output_col_dtype
# save output
agg_ops.append((input_col_name, output_col_name, agg_op))
# create aggregation table
ct_agg = bcolz.ctable(
np.zeros(expectedlen, [('tmp_col_bquery__', np.bool)]),
expectedlen=expectedlen,
rootdir=rootdir)
return ct_agg, dtype_dict, agg_ops | [
"def",
"create_agg_ctable",
"(",
"self",
",",
"groupby_cols",
",",
"agg_list",
",",
"expectedlen",
",",
"rootdir",
")",
":",
"dtype_dict",
"=",
"{",
"}",
"# include all the groupby columns",
"for",
"col",
"in",
"groupby_cols",
":",
"dtype_dict",
"[",
"col",
"]",... | Create a container for the output table, a dictionary describing it's
columns and a list of tuples describing aggregation
operations to perform.
Args:
groupby_cols (list): a list of columns to groupby over
agg_list (list): the aggregation operations (see groupby for more info)
expectedlen (int): expected length of output table
rootdir (string): the directory to write the table to
Returns:
ctable: A table in the correct format for containing the output of
the specified aggregation operations.
dict: (dtype_dict) dictionary describing columns to create
list: (agg_ops) list of tuples of the form:
(input_col_name, output_col_name, agg_op)
input_col_name (string): name of the column to act on
output_col_name (string): name of the column to output to
agg_op (int): aggregation operation to perform | [
"Create",
"a",
"container",
"for",
"the",
"output",
"table",
"a",
"dictionary",
"describing",
"it",
"s",
"columns",
"and",
"a",
"list",
"of",
"tuples",
"describing",
"aggregation",
"operations",
"to",
"perform",
"."
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L576-L654 |
visualfabriq/bquery | bquery/ctable.py | ctable.where_terms | def where_terms(self, term_list, cache=False):
"""
Create a boolean array where `term_list` is true.
A terms list has a [(col, operator, value), ..] construction.
Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])]
:param term_list:
:param outcols:
:param limit:
:param skip:
:return: :raise ValueError:
"""
if type(term_list) not in [list, set, tuple]:
raise ValueError("Only term lists are supported")
col_list = []
op_list = []
value_list = []
for term in term_list:
# get terms
filter_col = term[0]
filter_operator = term[1].lower().strip(' ')
filter_value = term[2]
# check values
if filter_col not in self.cols:
raise KeyError(unicode(filter_col) + ' not in table')
if filter_operator in ['==', 'eq']:
op_id = 1
elif filter_operator in ['!=', 'neq']:
op_id = 2
elif filter_operator in ['in']:
op_id = 3
elif filter_operator in ['nin', 'not in']:
op_id = 4
elif filter_operator in ['>']:
op_id = 5
elif filter_operator in ['>=']:
op_id = 6
elif filter_operator in ['<']:
op_id = 7
elif filter_operator in ['<=']:
op_id = 8
else:
raise KeyError(unicode(filter_operator) + ' is not an accepted operator for filtering')
if op_id in [3, 4]:
if type(filter_value) not in [list, set, tuple]:
raise ValueError("In selections need lists, sets or tuples")
if len(filter_value) < 1:
raise ValueError("A value list needs to have values")
# optimize lists of 1 value
if len(filter_value) == 1:
if op_id == 3:
op_id = 1
else:
op_id = 2
filter_value = filter_value[0]
else:
filter_value = set(filter_value)
# prepare input for filter creation
col_list.append(filter_col)
op_list.append(op_id)
value_list.append(filter_value)
# rootdir
if cache:
# nb: this directory is not destroyed until the end of the groupby
rootdir = self.create_tmp_rootdir()
else:
rootdir = None
# create boolean array and fill it
boolarr = bcolz.carray(np.ones(0, dtype=np.bool), expectedlen=self.len, rootdir=rootdir, mode='w')
ctable_iter = self[col_list].iter(out_flavor='tuple')
ctable_ext.apply_where_terms(ctable_iter, op_list, value_list, boolarr)
return boolarr | python | def where_terms(self, term_list, cache=False):
"""
Create a boolean array where `term_list` is true.
A terms list has a [(col, operator, value), ..] construction.
Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])]
:param term_list:
:param outcols:
:param limit:
:param skip:
:return: :raise ValueError:
"""
if type(term_list) not in [list, set, tuple]:
raise ValueError("Only term lists are supported")
col_list = []
op_list = []
value_list = []
for term in term_list:
# get terms
filter_col = term[0]
filter_operator = term[1].lower().strip(' ')
filter_value = term[2]
# check values
if filter_col not in self.cols:
raise KeyError(unicode(filter_col) + ' not in table')
if filter_operator in ['==', 'eq']:
op_id = 1
elif filter_operator in ['!=', 'neq']:
op_id = 2
elif filter_operator in ['in']:
op_id = 3
elif filter_operator in ['nin', 'not in']:
op_id = 4
elif filter_operator in ['>']:
op_id = 5
elif filter_operator in ['>=']:
op_id = 6
elif filter_operator in ['<']:
op_id = 7
elif filter_operator in ['<=']:
op_id = 8
else:
raise KeyError(unicode(filter_operator) + ' is not an accepted operator for filtering')
if op_id in [3, 4]:
if type(filter_value) not in [list, set, tuple]:
raise ValueError("In selections need lists, sets or tuples")
if len(filter_value) < 1:
raise ValueError("A value list needs to have values")
# optimize lists of 1 value
if len(filter_value) == 1:
if op_id == 3:
op_id = 1
else:
op_id = 2
filter_value = filter_value[0]
else:
filter_value = set(filter_value)
# prepare input for filter creation
col_list.append(filter_col)
op_list.append(op_id)
value_list.append(filter_value)
# rootdir
if cache:
# nb: this directory is not destroyed until the end of the groupby
rootdir = self.create_tmp_rootdir()
else:
rootdir = None
# create boolean array and fill it
boolarr = bcolz.carray(np.ones(0, dtype=np.bool), expectedlen=self.len, rootdir=rootdir, mode='w')
ctable_iter = self[col_list].iter(out_flavor='tuple')
ctable_ext.apply_where_terms(ctable_iter, op_list, value_list, boolarr)
return boolarr | [
"def",
"where_terms",
"(",
"self",
",",
"term_list",
",",
"cache",
"=",
"False",
")",
":",
"if",
"type",
"(",
"term_list",
")",
"not",
"in",
"[",
"list",
",",
"set",
",",
"tuple",
"]",
":",
"raise",
"ValueError",
"(",
"\"Only term lists are supported\"",
... | Create a boolean array where `term_list` is true.
A terms list has a [(col, operator, value), ..] construction.
Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])]
:param term_list:
:param outcols:
:param limit:
:param skip:
:return: :raise ValueError: | [
"Create",
"a",
"boolean",
"array",
"where",
"term_list",
"is",
"true",
".",
"A",
"terms",
"list",
"has",
"a",
"[",
"(",
"col",
"operator",
"value",
")",
"..",
"]",
"construction",
".",
"Eg",
".",
"[",
"(",
"sales",
">",
"2",
")",
"(",
"state",
"in"... | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L656-L740 |
visualfabriq/bquery | bquery/ctable.py | ctable.where_terms_factorization_check | def where_terms_factorization_check(self, term_list):
"""
check for where terms if they are applicable
Create a boolean array where `term_list` is true.
A terms list has a [(col, operator, value), ..] construction.
Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])]
:param term_list:
:param outcols:
:param limit:
:param skip:
:return: :raise ValueError:
"""
if type(term_list) not in [list, set, tuple]:
raise ValueError("Only term lists are supported")
valid = True
for term in term_list:
# get terms
filter_col = term[0]
filter_operator = term[1].lower().strip(' ')
filter_value = term[2]
# check values
if filter_col not in self.cols:
raise KeyError(unicode(filter_col) + ' not in table')
col_values_rootdir = os.path.join(self.rootdir, filter_col + '.values')
if not os.path.exists(col_values_rootdir):
# no factorization available
break
col_carray = bcolz.carray(rootdir=col_values_rootdir, mode='r')
col_values = set(col_carray)
if filter_operator in ['in', 'not in', 'nin']:
if type(filter_value) not in [list, set, tuple]:
raise ValueError("In selections need lists, sets or tuples")
if len(filter_value) < 1:
raise ValueError("A value list needs to have values")
# optimize lists of 1 value
if len(filter_value) == 1:
filter_value = filter_value[0]
if filter_operator == 'in':
filter_operator = '=='
else:
filter_operator = '!='
else:
filter_value = set(filter_value)
if filter_operator in ['==', 'eq']:
valid = filter_value in col_values
elif filter_operator in ['!=', 'neq']:
valid = any(val for val in col_values if val != filter_value)
elif filter_operator in ['in']:
valid = any(val for val in filter_value if val in col_values)
elif filter_operator in ['nin', 'not in']:
valid = any(val for val in col_values if val not in filter_value)
elif filter_operator in ['>']:
valid = any(val for val in col_values if val > filter_value)
elif filter_operator in ['>=']:
valid = any(val for val in col_values if val >= filter_value)
elif filter_operator in ['<']:
valid = any(val for val in col_values if val < filter_value)
elif filter_operator in ['<=']:
valid = any(val for val in col_values if val >= filter_value)
else:
raise KeyError(str(filter_operator) + ' is not an accepted operator for filtering')
# if one of the filters is blocking, we can stop
if not valid:
break
return valid | python | def where_terms_factorization_check(self, term_list):
"""
check for where terms if they are applicable
Create a boolean array where `term_list` is true.
A terms list has a [(col, operator, value), ..] construction.
Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])]
:param term_list:
:param outcols:
:param limit:
:param skip:
:return: :raise ValueError:
"""
if type(term_list) not in [list, set, tuple]:
raise ValueError("Only term lists are supported")
valid = True
for term in term_list:
# get terms
filter_col = term[0]
filter_operator = term[1].lower().strip(' ')
filter_value = term[2]
# check values
if filter_col not in self.cols:
raise KeyError(unicode(filter_col) + ' not in table')
col_values_rootdir = os.path.join(self.rootdir, filter_col + '.values')
if not os.path.exists(col_values_rootdir):
# no factorization available
break
col_carray = bcolz.carray(rootdir=col_values_rootdir, mode='r')
col_values = set(col_carray)
if filter_operator in ['in', 'not in', 'nin']:
if type(filter_value) not in [list, set, tuple]:
raise ValueError("In selections need lists, sets or tuples")
if len(filter_value) < 1:
raise ValueError("A value list needs to have values")
# optimize lists of 1 value
if len(filter_value) == 1:
filter_value = filter_value[0]
if filter_operator == 'in':
filter_operator = '=='
else:
filter_operator = '!='
else:
filter_value = set(filter_value)
if filter_operator in ['==', 'eq']:
valid = filter_value in col_values
elif filter_operator in ['!=', 'neq']:
valid = any(val for val in col_values if val != filter_value)
elif filter_operator in ['in']:
valid = any(val for val in filter_value if val in col_values)
elif filter_operator in ['nin', 'not in']:
valid = any(val for val in col_values if val not in filter_value)
elif filter_operator in ['>']:
valid = any(val for val in col_values if val > filter_value)
elif filter_operator in ['>=']:
valid = any(val for val in col_values if val >= filter_value)
elif filter_operator in ['<']:
valid = any(val for val in col_values if val < filter_value)
elif filter_operator in ['<=']:
valid = any(val for val in col_values if val >= filter_value)
else:
raise KeyError(str(filter_operator) + ' is not an accepted operator for filtering')
# if one of the filters is blocking, we can stop
if not valid:
break
return valid | [
"def",
"where_terms_factorization_check",
"(",
"self",
",",
"term_list",
")",
":",
"if",
"type",
"(",
"term_list",
")",
"not",
"in",
"[",
"list",
",",
"set",
",",
"tuple",
"]",
":",
"raise",
"ValueError",
"(",
"\"Only term lists are supported\"",
")",
"valid",... | check for where terms if they are applicable
Create a boolean array where `term_list` is true.
A terms list has a [(col, operator, value), ..] construction.
Eg. [('sales', '>', 2), ('state', 'in', ['IL', 'AR'])]
:param term_list:
:param outcols:
:param limit:
:param skip:
:return: :raise ValueError: | [
"check",
"for",
"where",
"terms",
"if",
"they",
"are",
"applicable",
"Create",
"a",
"boolean",
"array",
"where",
"term_list",
"is",
"true",
".",
"A",
"terms",
"list",
"has",
"a",
"[",
"(",
"col",
"operator",
"value",
")",
"..",
"]",
"construction",
".",
... | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L742-L819 |
visualfabriq/bquery | bquery/ctable.py | ctable.is_in_ordered_subgroups | def is_in_ordered_subgroups(self, basket_col=None, bool_arr=None,
_max_len_subgroup=1000):
"""
Expands the filter using a specified column
Parameters
----------
basket_col
bool_arr
_max_len_subgroup
Returns
-------
"""
assert basket_col is not None
if bool_arr is None:
return None
if self.auto_cache and bool_arr.rootdir is not None:
rootdir = self.create_tmp_rootdir()
else:
rootdir = None
return \
ctable_ext.is_in_ordered_subgroups(
self[basket_col], bool_arr=bool_arr, rootdir=rootdir,
_max_len_subgroup=_max_len_subgroup) | python | def is_in_ordered_subgroups(self, basket_col=None, bool_arr=None,
_max_len_subgroup=1000):
"""
Expands the filter using a specified column
Parameters
----------
basket_col
bool_arr
_max_len_subgroup
Returns
-------
"""
assert basket_col is not None
if bool_arr is None:
return None
if self.auto_cache and bool_arr.rootdir is not None:
rootdir = self.create_tmp_rootdir()
else:
rootdir = None
return \
ctable_ext.is_in_ordered_subgroups(
self[basket_col], bool_arr=bool_arr, rootdir=rootdir,
_max_len_subgroup=_max_len_subgroup) | [
"def",
"is_in_ordered_subgroups",
"(",
"self",
",",
"basket_col",
"=",
"None",
",",
"bool_arr",
"=",
"None",
",",
"_max_len_subgroup",
"=",
"1000",
")",
":",
"assert",
"basket_col",
"is",
"not",
"None",
"if",
"bool_arr",
"is",
"None",
":",
"return",
"None",
... | Expands the filter using a specified column
Parameters
----------
basket_col
bool_arr
_max_len_subgroup
Returns
------- | [
"Expands",
"the",
"filter",
"using",
"a",
"specified",
"column"
] | train | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L821-L849 |
kalefranz/auxlib | auxlib/_vendor/five.py | with_metaclass | def with_metaclass(Type, skip_attrs=set(('__dict__', '__weakref__'))):
"""Class decorator to set metaclass.
Works with both Python 2 and Python 3 and it does not add
an extra class in the lookup order like ``six.with_metaclass`` does
(that is -- it copies the original class instead of using inheritance).
"""
def _clone_with_metaclass(Class):
attrs = dict((key, value) for key, value in items(vars(Class))
if key not in skip_attrs)
return Type(Class.__name__, Class.__bases__, attrs)
return _clone_with_metaclass | python | def with_metaclass(Type, skip_attrs=set(('__dict__', '__weakref__'))):
"""Class decorator to set metaclass.
Works with both Python 2 and Python 3 and it does not add
an extra class in the lookup order like ``six.with_metaclass`` does
(that is -- it copies the original class instead of using inheritance).
"""
def _clone_with_metaclass(Class):
attrs = dict((key, value) for key, value in items(vars(Class))
if key not in skip_attrs)
return Type(Class.__name__, Class.__bases__, attrs)
return _clone_with_metaclass | [
"def",
"with_metaclass",
"(",
"Type",
",",
"skip_attrs",
"=",
"set",
"(",
"(",
"'__dict__'",
",",
"'__weakref__'",
")",
")",
")",
":",
"def",
"_clone_with_metaclass",
"(",
"Class",
")",
":",
"attrs",
"=",
"dict",
"(",
"(",
"key",
",",
"value",
")",
"fo... | Class decorator to set metaclass.
Works with both Python 2 and Python 3 and it does not add
an extra class in the lookup order like ``six.with_metaclass`` does
(that is -- it copies the original class instead of using inheritance). | [
"Class",
"decorator",
"to",
"set",
"metaclass",
"."
] | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/five.py#L202-L216 |
marrow/schema | marrow/schema/util.py | ensure_tuple | def ensure_tuple(length, tuples):
"""Yield `length`-sized tuples from the given collection.
Will truncate longer tuples to the desired length, and pad using the leading element if shorter.
"""
for elem in tuples:
# Handle non-tuples and non-lists as a single repeated element.
if not isinstance(elem, (tuple, list)):
yield (elem, ) * length
continue
l = len(elem)
# If we have the correct length already, yield it.
if l == length:
yield elem
# If we're too long, truncate.
elif l > length:
yield tuple(elem[:length])
# If we're too short, pad the *leading* element out.
elif l < length:
yield (elem[0], ) * (length - l) + tuple(elem) | python | def ensure_tuple(length, tuples):
"""Yield `length`-sized tuples from the given collection.
Will truncate longer tuples to the desired length, and pad using the leading element if shorter.
"""
for elem in tuples:
# Handle non-tuples and non-lists as a single repeated element.
if not isinstance(elem, (tuple, list)):
yield (elem, ) * length
continue
l = len(elem)
# If we have the correct length already, yield it.
if l == length:
yield elem
# If we're too long, truncate.
elif l > length:
yield tuple(elem[:length])
# If we're too short, pad the *leading* element out.
elif l < length:
yield (elem[0], ) * (length - l) + tuple(elem) | [
"def",
"ensure_tuple",
"(",
"length",
",",
"tuples",
")",
":",
"for",
"elem",
"in",
"tuples",
":",
"# Handle non-tuples and non-lists as a single repeated element.",
"if",
"not",
"isinstance",
"(",
"elem",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"yield",
... | Yield `length`-sized tuples from the given collection.
Will truncate longer tuples to the desired length, and pad using the leading element if shorter. | [
"Yield",
"length",
"-",
"sized",
"tuples",
"from",
"the",
"given",
"collection",
".",
"Will",
"truncate",
"longer",
"tuples",
"to",
"the",
"desired",
"length",
"and",
"pad",
"using",
"the",
"leading",
"element",
"if",
"shorter",
"."
] | train | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/util.py#L24-L48 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/main.py | print_version | def print_version():
"""Print the environment versions."""
click.echo("Versions:")
click.secho(
"CLI Package Version: %(version)s"
% {"version": click.style(get_cli_version(), bold=True)}
)
click.secho(
"API Package Version: %(version)s"
% {"version": click.style(get_api_version(), bold=True)}
) | python | def print_version():
"""Print the environment versions."""
click.echo("Versions:")
click.secho(
"CLI Package Version: %(version)s"
% {"version": click.style(get_cli_version(), bold=True)}
)
click.secho(
"API Package Version: %(version)s"
% {"version": click.style(get_api_version(), bold=True)}
) | [
"def",
"print_version",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"Versions:\"",
")",
"click",
".",
"secho",
"(",
"\"CLI Package Version: %(version)s\"",
"%",
"{",
"\"version\"",
":",
"click",
".",
"style",
"(",
"get_cli_version",
"(",
")",
",",
"bold",
"=... | Print the environment versions. | [
"Print",
"the",
"environment",
"versions",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/main.py#L15-L25 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/main.py | main | def main(ctx, opts, version):
"""Handle entrypoint to CLI."""
# pylint: disable=unused-argument
if version:
print_version()
elif ctx.invoked_subcommand is None:
click.echo(ctx.get_help()) | python | def main(ctx, opts, version):
"""Handle entrypoint to CLI."""
# pylint: disable=unused-argument
if version:
print_version()
elif ctx.invoked_subcommand is None:
click.echo(ctx.get_help()) | [
"def",
"main",
"(",
"ctx",
",",
"opts",
",",
"version",
")",
":",
"# pylint: disable=unused-argument",
"if",
"version",
":",
"print_version",
"(",
")",
"elif",
"ctx",
".",
"invoked_subcommand",
"is",
"None",
":",
"click",
".",
"echo",
"(",
"ctx",
".",
"get... | Handle entrypoint to CLI. | [
"Handle",
"entrypoint",
"to",
"CLI",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/main.py#L58-L64 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/push.py | validate_upload_file | def validate_upload_file(ctx, opts, owner, repo, filepath, skip_errors):
"""Validate parameters for requesting a file upload."""
filename = click.format_filename(filepath)
basename = os.path.basename(filename)
click.echo(
"Checking %(filename)s file upload parameters ... "
% {"filename": click.style(basename, bold=True)},
nl=False,
)
context_msg = "Failed to validate upload parameters!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
md5_checksum = validate_request_file_upload(
owner=owner, repo=repo, filepath=filename
)
click.secho("OK", fg="green")
return md5_checksum | python | def validate_upload_file(ctx, opts, owner, repo, filepath, skip_errors):
"""Validate parameters for requesting a file upload."""
filename = click.format_filename(filepath)
basename = os.path.basename(filename)
click.echo(
"Checking %(filename)s file upload parameters ... "
% {"filename": click.style(basename, bold=True)},
nl=False,
)
context_msg = "Failed to validate upload parameters!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
md5_checksum = validate_request_file_upload(
owner=owner, repo=repo, filepath=filename
)
click.secho("OK", fg="green")
return md5_checksum | [
"def",
"validate_upload_file",
"(",
"ctx",
",",
"opts",
",",
"owner",
",",
"repo",
",",
"filepath",
",",
"skip_errors",
")",
":",
"filename",
"=",
"click",
".",
"format_filename",
"(",
"filepath",
")",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
... | Validate parameters for requesting a file upload. | [
"Validate",
"parameters",
"for",
"requesting",
"a",
"file",
"upload",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L31-L53 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/push.py | upload_file | def upload_file(ctx, opts, owner, repo, filepath, skip_errors, md5_checksum):
"""Upload a package file via the API."""
filename = click.format_filename(filepath)
basename = os.path.basename(filename)
click.echo(
"Requesting file upload for %(filename)s ... "
% {"filename": click.style(basename, bold=True)},
nl=False,
)
context_msg = "Failed to request file upload!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
identifier, upload_url, upload_fields = request_file_upload(
owner=owner, repo=repo, filepath=filename, md5_checksum=md5_checksum
)
click.secho("OK", fg="green")
context_msg = "Failed to upload file!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
filesize = utils.get_file_size(filepath=filename)
label = "Uploading %(filename)s:" % {
"filename": click.style(basename, bold=True)
}
with click.progressbar(
length=filesize,
label=label,
fill_char=click.style("#", fg="green"),
empty_char=click.style("-", fg="red"),
) as pb:
def progress_callback(monitor):
pb.update(monitor.bytes_read)
api_upload_file(
upload_url=upload_url,
upload_fields=upload_fields,
filepath=filename,
callback=progress_callback,
)
return identifier | python | def upload_file(ctx, opts, owner, repo, filepath, skip_errors, md5_checksum):
"""Upload a package file via the API."""
filename = click.format_filename(filepath)
basename = os.path.basename(filename)
click.echo(
"Requesting file upload for %(filename)s ... "
% {"filename": click.style(basename, bold=True)},
nl=False,
)
context_msg = "Failed to request file upload!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
identifier, upload_url, upload_fields = request_file_upload(
owner=owner, repo=repo, filepath=filename, md5_checksum=md5_checksum
)
click.secho("OK", fg="green")
context_msg = "Failed to upload file!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
filesize = utils.get_file_size(filepath=filename)
label = "Uploading %(filename)s:" % {
"filename": click.style(basename, bold=True)
}
with click.progressbar(
length=filesize,
label=label,
fill_char=click.style("#", fg="green"),
empty_char=click.style("-", fg="red"),
) as pb:
def progress_callback(monitor):
pb.update(monitor.bytes_read)
api_upload_file(
upload_url=upload_url,
upload_fields=upload_fields,
filepath=filename,
callback=progress_callback,
)
return identifier | [
"def",
"upload_file",
"(",
"ctx",
",",
"opts",
",",
"owner",
",",
"repo",
",",
"filepath",
",",
"skip_errors",
",",
"md5_checksum",
")",
":",
"filename",
"=",
"click",
".",
"format_filename",
"(",
"filepath",
")",
"basename",
"=",
"os",
".",
"path",
".",... | Upload a package file via the API. | [
"Upload",
"a",
"package",
"file",
"via",
"the",
"API",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L56-L103 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/push.py | validate_create_package | def validate_create_package(
ctx, opts, owner, repo, package_type, skip_errors, **kwargs
):
"""Check new package parameters via the API."""
click.echo(
"Checking %(package_type)s package upload parameters ... "
% {"package_type": click.style(package_type, bold=True)},
nl=False,
)
context_msg = "Failed to validate upload parameters!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
api_validate_create_package(
package_format=package_type, owner=owner, repo=repo, **kwargs
)
click.secho("OK", fg="green")
return True | python | def validate_create_package(
ctx, opts, owner, repo, package_type, skip_errors, **kwargs
):
"""Check new package parameters via the API."""
click.echo(
"Checking %(package_type)s package upload parameters ... "
% {"package_type": click.style(package_type, bold=True)},
nl=False,
)
context_msg = "Failed to validate upload parameters!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
api_validate_create_package(
package_format=package_type, owner=owner, repo=repo, **kwargs
)
click.secho("OK", fg="green")
return True | [
"def",
"validate_create_package",
"(",
"ctx",
",",
"opts",
",",
"owner",
",",
"repo",
",",
"package_type",
",",
"skip_errors",
",",
"*",
"*",
"kwargs",
")",
":",
"click",
".",
"echo",
"(",
"\"Checking %(package_type)s package upload parameters ... \"",
"%",
"{",
... | Check new package parameters via the API. | [
"Check",
"new",
"package",
"parameters",
"via",
"the",
"API",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L106-L126 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/push.py | create_package | def create_package(ctx, opts, owner, repo, package_type, skip_errors, **kwargs):
"""Create a new package via the API."""
click.echo(
"Creating a new %(package_type)s package ... "
% {"package_type": click.style(package_type, bold=True)},
nl=False,
)
context_msg = "Failed to create package!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
slug_perm, slug = api_create_package(
package_format=package_type, owner=owner, repo=repo, **kwargs
)
click.secho("OK", fg="green")
click.echo(
"Created: %(owner)s/%(repo)s/%(slug)s (%(slug_perm)s)"
% {
"owner": click.style(owner, fg="magenta"),
"repo": click.style(repo, fg="magenta"),
"slug": click.style(slug, fg="green"),
"slug_perm": click.style(slug_perm, bold=True),
}
)
return slug_perm, slug | python | def create_package(ctx, opts, owner, repo, package_type, skip_errors, **kwargs):
"""Create a new package via the API."""
click.echo(
"Creating a new %(package_type)s package ... "
% {"package_type": click.style(package_type, bold=True)},
nl=False,
)
context_msg = "Failed to create package!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
slug_perm, slug = api_create_package(
package_format=package_type, owner=owner, repo=repo, **kwargs
)
click.secho("OK", fg="green")
click.echo(
"Created: %(owner)s/%(repo)s/%(slug)s (%(slug_perm)s)"
% {
"owner": click.style(owner, fg="magenta"),
"repo": click.style(repo, fg="magenta"),
"slug": click.style(slug, fg="green"),
"slug_perm": click.style(slug_perm, bold=True),
}
)
return slug_perm, slug | [
"def",
"create_package",
"(",
"ctx",
",",
"opts",
",",
"owner",
",",
"repo",
",",
"package_type",
",",
"skip_errors",
",",
"*",
"*",
"kwargs",
")",
":",
"click",
".",
"echo",
"(",
"\"Creating a new %(package_type)s package ... \"",
"%",
"{",
"\"package_type\"",
... | Create a new package via the API. | [
"Create",
"a",
"new",
"package",
"via",
"the",
"API",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L129-L158 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/push.py | wait_for_package_sync | def wait_for_package_sync(
ctx, opts, owner, repo, slug, wait_interval, skip_errors, attempts=3
):
"""Wait for a package to synchronise (or fail)."""
# pylint: disable=too-many-locals
attempts -= 1
click.echo()
label = "Synchronising %(package)s:" % {"package": click.style(slug, fg="green")}
status_str = "Waiting"
stage_str = None
def display_status(current):
"""Display current sync status."""
# pylint: disable=unused-argument
if not stage_str:
return status_str
return click.style(
"%(status)s / %(stage)s" % {"status": status_str, "stage": stage_str},
fg="cyan",
)
context_msg = "Failed to synchronise file!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
last_progress = 0
with click.progressbar(
length=100,
label=label,
fill_char=click.style("#", fg="green"),
empty_char=click.style("-", fg="red"),
item_show_func=display_status,
) as pb:
while True:
res = get_package_status(owner, repo, slug)
ok, failed, progress, status_str, stage_str, reason = res
delta = progress - last_progress
if delta > 0:
last_progress = progress
pb.update(delta)
if ok or failed:
break
time.sleep(wait_interval)
if ok:
click.secho("Package synchronised successfully!", fg="green")
return
click.secho(
"Package failed to synchronise during stage: %(stage)s"
% {"stage": click.style(stage_str or "Unknown", fg="yellow")},
fg="red",
)
if reason:
click.secho(
"Reason given: %(reason)s" % {"reason": click.style(reason, fg="yellow")},
fg="red",
)
# pylint: disable=fixme
# FIXME: The API should communicate "no retry" fails
if "package should be deleted" in reason and attempts > 1:
click.secho(
"This is not recoverable, so stopping further attempts!", fg="red"
)
click.echo()
attempts = 0
if attempts + 1 > 0:
# Show attempts upto and including zero attempts left
click.secho(
"Attempts left: %(left)s (%(action)s)"
% {
"left": click.style(six.text_type(attempts), bold=True),
"action": "trying again" if attempts > 0 else "giving up",
}
)
click.echo()
if attempts > 0:
from .resync import resync_package
resync_package(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
slug=slug,
skip_errors=skip_errors,
)
wait_for_package_sync(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
slug=slug,
wait_interval=wait_interval,
skip_errors=skip_errors,
attempts=attempts,
)
else:
ctx.exit(1) | python | def wait_for_package_sync(
ctx, opts, owner, repo, slug, wait_interval, skip_errors, attempts=3
):
"""Wait for a package to synchronise (or fail)."""
# pylint: disable=too-many-locals
attempts -= 1
click.echo()
label = "Synchronising %(package)s:" % {"package": click.style(slug, fg="green")}
status_str = "Waiting"
stage_str = None
def display_status(current):
"""Display current sync status."""
# pylint: disable=unused-argument
if not stage_str:
return status_str
return click.style(
"%(status)s / %(stage)s" % {"status": status_str, "stage": stage_str},
fg="cyan",
)
context_msg = "Failed to synchronise file!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
last_progress = 0
with click.progressbar(
length=100,
label=label,
fill_char=click.style("#", fg="green"),
empty_char=click.style("-", fg="red"),
item_show_func=display_status,
) as pb:
while True:
res = get_package_status(owner, repo, slug)
ok, failed, progress, status_str, stage_str, reason = res
delta = progress - last_progress
if delta > 0:
last_progress = progress
pb.update(delta)
if ok or failed:
break
time.sleep(wait_interval)
if ok:
click.secho("Package synchronised successfully!", fg="green")
return
click.secho(
"Package failed to synchronise during stage: %(stage)s"
% {"stage": click.style(stage_str or "Unknown", fg="yellow")},
fg="red",
)
if reason:
click.secho(
"Reason given: %(reason)s" % {"reason": click.style(reason, fg="yellow")},
fg="red",
)
# pylint: disable=fixme
# FIXME: The API should communicate "no retry" fails
if "package should be deleted" in reason and attempts > 1:
click.secho(
"This is not recoverable, so stopping further attempts!", fg="red"
)
click.echo()
attempts = 0
if attempts + 1 > 0:
# Show attempts upto and including zero attempts left
click.secho(
"Attempts left: %(left)s (%(action)s)"
% {
"left": click.style(six.text_type(attempts), bold=True),
"action": "trying again" if attempts > 0 else "giving up",
}
)
click.echo()
if attempts > 0:
from .resync import resync_package
resync_package(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
slug=slug,
skip_errors=skip_errors,
)
wait_for_package_sync(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
slug=slug,
wait_interval=wait_interval,
skip_errors=skip_errors,
attempts=attempts,
)
else:
ctx.exit(1) | [
"def",
"wait_for_package_sync",
"(",
"ctx",
",",
"opts",
",",
"owner",
",",
"repo",
",",
"slug",
",",
"wait_interval",
",",
"skip_errors",
",",
"attempts",
"=",
"3",
")",
":",
"# pylint: disable=too-many-locals",
"attempts",
"-=",
"1",
"click",
".",
"echo",
... | Wait for a package to synchronise (or fail). | [
"Wait",
"for",
"a",
"package",
"to",
"synchronise",
"(",
"or",
"fail",
")",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L161-L265 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/push.py | upload_files_and_create_package | def upload_files_and_create_package(
ctx,
opts,
package_type,
owner_repo,
dry_run,
no_wait_for_sync,
wait_interval,
skip_errors,
sync_attempts,
**kwargs
):
"""Upload package files and create a new package."""
# pylint: disable=unused-argument
owner, repo = owner_repo
# 1. Validate package create parameters
validate_create_package(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
package_type=package_type,
skip_errors=skip_errors,
**kwargs
)
# 2. Validate file upload parameters
md5_checksums = {}
for k, v in kwargs.items():
if not v or not k.endswith("_file"):
continue
md5_checksums[k] = validate_upload_file(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
filepath=v,
skip_errors=skip_errors,
)
if dry_run:
click.echo()
click.secho("You requested a dry run so skipping upload.", fg="yellow")
return
# 3. Upload any arguments that look like files
for k, v in kwargs.items():
if not v or not k.endswith("_file"):
continue
kwargs[k] = upload_file(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
filepath=v,
skip_errors=skip_errors,
md5_checksum=md5_checksums[k],
)
# 4. Create the package with package files and additional arguments
_, slug = create_package(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
package_type=package_type,
skip_errors=skip_errors,
**kwargs
)
if no_wait_for_sync:
return
# 5. (optionally) Wait for the package to synchronise
wait_for_package_sync(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
slug=slug,
wait_interval=wait_interval,
skip_errors=skip_errors,
attempts=sync_attempts,
) | python | def upload_files_and_create_package(
ctx,
opts,
package_type,
owner_repo,
dry_run,
no_wait_for_sync,
wait_interval,
skip_errors,
sync_attempts,
**kwargs
):
"""Upload package files and create a new package."""
# pylint: disable=unused-argument
owner, repo = owner_repo
# 1. Validate package create parameters
validate_create_package(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
package_type=package_type,
skip_errors=skip_errors,
**kwargs
)
# 2. Validate file upload parameters
md5_checksums = {}
for k, v in kwargs.items():
if not v or not k.endswith("_file"):
continue
md5_checksums[k] = validate_upload_file(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
filepath=v,
skip_errors=skip_errors,
)
if dry_run:
click.echo()
click.secho("You requested a dry run so skipping upload.", fg="yellow")
return
# 3. Upload any arguments that look like files
for k, v in kwargs.items():
if not v or not k.endswith("_file"):
continue
kwargs[k] = upload_file(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
filepath=v,
skip_errors=skip_errors,
md5_checksum=md5_checksums[k],
)
# 4. Create the package with package files and additional arguments
_, slug = create_package(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
package_type=package_type,
skip_errors=skip_errors,
**kwargs
)
if no_wait_for_sync:
return
# 5. (optionally) Wait for the package to synchronise
wait_for_package_sync(
ctx=ctx,
opts=opts,
owner=owner,
repo=repo,
slug=slug,
wait_interval=wait_interval,
skip_errors=skip_errors,
attempts=sync_attempts,
) | [
"def",
"upload_files_and_create_package",
"(",
"ctx",
",",
"opts",
",",
"package_type",
",",
"owner_repo",
",",
"dry_run",
",",
"no_wait_for_sync",
",",
"wait_interval",
",",
"skip_errors",
",",
"sync_attempts",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disabl... | Upload package files and create a new package. | [
"Upload",
"package",
"files",
"and",
"create",
"a",
"new",
"package",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L268-L354 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/push.py | create_push_handlers | def create_push_handlers():
"""Create a handler for upload per package format."""
# pylint: disable=fixme
# HACK: hacky territory - Dynamically generate a handler for each of the
# package formats, until we have slightly more clever 'guess type'
# handling. :-)
handlers = create_push_handlers.handlers = {}
context = create_push_handlers.context = get_package_formats()
for key, parameters in six.iteritems(context):
kwargs = parameters.copy()
# Remove standard arguments
kwargs.pop("package_file")
if "distribution" in parameters:
has_distribution_param = True
kwargs.pop("distribution")
else:
has_distribution_param = False
has_additional_params = len(kwargs) > 0
help_text = """
Push/upload a new %(type)s package upstream.
""" % {
"type": key.capitalize()
}
if has_additional_params:
help_text += """
PACKAGE_FILE: The main file to create the package from.
"""
else:
help_text += """
PACKAGE_FILE: Any number of files to create packages from. Each
file will result in a separate package.
"""
if has_distribution_param:
target_metavar = "OWNER/REPO/DISTRO/RELEASE"
target_callback = validators.validate_owner_repo_distro
help_text += """
OWNER/REPO/DISTRO/RELEASE: Specify the OWNER namespace (i.e.
user or org), the REPO name where the package file will be uploaded
to, and the DISTRO and RELEASE the package is for. All separated by
a slash.
Example: 'your-org/awesome-repo/ubuntu/xenial'.
"""
else:
target_metavar = "OWNER/REPO"
target_callback = validators.validate_owner_repo
help_text += """
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name where the package file will be uploaded to. All separated
by a slash.
Example: 'your-org/awesome-repo'.
"""
@push.command(name=key, help=help_text)
@decorators.common_api_auth_options
@decorators.common_cli_config_options
@decorators.common_cli_output_options
@decorators.common_package_action_options
@decorators.initialise_api
@click.argument("owner_repo", metavar=target_metavar, callback=target_callback)
@click.argument(
"package_file",
nargs=1 if has_additional_params else -1,
type=ExpandPath(
dir_okay=False, exists=True, writable=False, resolve_path=True
),
)
@click.option(
"-n",
"--dry-run",
default=False,
is_flag=True,
help="Execute in dry run mode (don't upload anything.)",
)
@click.option(
"-n",
"--dry-run",
default=False,
is_flag=True,
help="Execute in dry run mode (don't upload anything.)",
)
@click.pass_context
def push_handler(ctx, *args, **kwargs):
"""Handle upload for a specific package format."""
parameters = context.get(ctx.info_name)
kwargs["package_type"] = ctx.info_name
owner_repo = kwargs.pop("owner_repo")
if "distribution" in parameters:
kwargs["distribution"] = "/".join(owner_repo[2:])
owner_repo = owner_repo[0:2]
kwargs["owner_repo"] = owner_repo
package_files = kwargs.pop("package_file")
if not isinstance(package_files, tuple):
package_files = (package_files,)
for package_file in package_files:
kwargs["package_file"] = package_file
try:
click.echo()
upload_files_and_create_package(ctx, *args, **kwargs)
except ApiException:
click.secho("Skipping error and moving on.", fg="yellow")
click.echo()
# Add any additional arguments
for k, info in six.iteritems(kwargs):
option_kwargs = {}
option_name_fmt = "--%(key)s"
if k.endswith("_file"):
# Treat parameters that end with _file as uploadable filepaths.
option_kwargs["type"] = ExpandPath(
dir_okay=False, exists=True, writable=False, resolve_path=True
)
elif info["type"] == "bool":
option_name_fmt = "--%(key)s/--no-%(key)s"
option_kwargs["is_flag"] = True
else:
option_kwargs["type"] = str
option_name = option_name_fmt % {"key": k.replace("_", "-")}
decorator = click.option(
option_name,
required=info["required"],
help=info["help"],
**option_kwargs
)
push_handler = decorator(push_handler)
handlers[key] = push_handler | python | def create_push_handlers():
"""Create a handler for upload per package format."""
# pylint: disable=fixme
# HACK: hacky territory - Dynamically generate a handler for each of the
# package formats, until we have slightly more clever 'guess type'
# handling. :-)
handlers = create_push_handlers.handlers = {}
context = create_push_handlers.context = get_package_formats()
for key, parameters in six.iteritems(context):
kwargs = parameters.copy()
# Remove standard arguments
kwargs.pop("package_file")
if "distribution" in parameters:
has_distribution_param = True
kwargs.pop("distribution")
else:
has_distribution_param = False
has_additional_params = len(kwargs) > 0
help_text = """
Push/upload a new %(type)s package upstream.
""" % {
"type": key.capitalize()
}
if has_additional_params:
help_text += """
PACKAGE_FILE: The main file to create the package from.
"""
else:
help_text += """
PACKAGE_FILE: Any number of files to create packages from. Each
file will result in a separate package.
"""
if has_distribution_param:
target_metavar = "OWNER/REPO/DISTRO/RELEASE"
target_callback = validators.validate_owner_repo_distro
help_text += """
OWNER/REPO/DISTRO/RELEASE: Specify the OWNER namespace (i.e.
user or org), the REPO name where the package file will be uploaded
to, and the DISTRO and RELEASE the package is for. All separated by
a slash.
Example: 'your-org/awesome-repo/ubuntu/xenial'.
"""
else:
target_metavar = "OWNER/REPO"
target_callback = validators.validate_owner_repo
help_text += """
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name where the package file will be uploaded to. All separated
by a slash.
Example: 'your-org/awesome-repo'.
"""
@push.command(name=key, help=help_text)
@decorators.common_api_auth_options
@decorators.common_cli_config_options
@decorators.common_cli_output_options
@decorators.common_package_action_options
@decorators.initialise_api
@click.argument("owner_repo", metavar=target_metavar, callback=target_callback)
@click.argument(
"package_file",
nargs=1 if has_additional_params else -1,
type=ExpandPath(
dir_okay=False, exists=True, writable=False, resolve_path=True
),
)
@click.option(
"-n",
"--dry-run",
default=False,
is_flag=True,
help="Execute in dry run mode (don't upload anything.)",
)
@click.option(
"-n",
"--dry-run",
default=False,
is_flag=True,
help="Execute in dry run mode (don't upload anything.)",
)
@click.pass_context
def push_handler(ctx, *args, **kwargs):
"""Handle upload for a specific package format."""
parameters = context.get(ctx.info_name)
kwargs["package_type"] = ctx.info_name
owner_repo = kwargs.pop("owner_repo")
if "distribution" in parameters:
kwargs["distribution"] = "/".join(owner_repo[2:])
owner_repo = owner_repo[0:2]
kwargs["owner_repo"] = owner_repo
package_files = kwargs.pop("package_file")
if not isinstance(package_files, tuple):
package_files = (package_files,)
for package_file in package_files:
kwargs["package_file"] = package_file
try:
click.echo()
upload_files_and_create_package(ctx, *args, **kwargs)
except ApiException:
click.secho("Skipping error and moving on.", fg="yellow")
click.echo()
# Add any additional arguments
for k, info in six.iteritems(kwargs):
option_kwargs = {}
option_name_fmt = "--%(key)s"
if k.endswith("_file"):
# Treat parameters that end with _file as uploadable filepaths.
option_kwargs["type"] = ExpandPath(
dir_okay=False, exists=True, writable=False, resolve_path=True
)
elif info["type"] == "bool":
option_name_fmt = "--%(key)s/--no-%(key)s"
option_kwargs["is_flag"] = True
else:
option_kwargs["type"] = str
option_name = option_name_fmt % {"key": k.replace("_", "-")}
decorator = click.option(
option_name,
required=info["required"],
help=info["help"],
**option_kwargs
)
push_handler = decorator(push_handler)
handlers[key] = push_handler | [
"def",
"create_push_handlers",
"(",
")",
":",
"# pylint: disable=fixme",
"# HACK: hacky territory - Dynamically generate a handler for each of the",
"# package formats, until we have slightly more clever 'guess type'",
"# handling. :-)",
"handlers",
"=",
"create_push_handlers",
".",
"handl... | Create a handler for upload per package format. | [
"Create",
"a",
"handler",
"for",
"upload",
"per",
"package",
"format",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L357-L501 |
kalefranz/auxlib | auxlib/decorators.py | memoize | def memoize(func):
"""
Decorator to cause a function to cache it's results for each combination of
inputs and return the cached result on subsequent calls. Does not support
named arguments or arg values that are not hashable.
>>> @memoize
... def foo(x):
... print('running function with', x)
... return x+3
...
>>> foo(10)
running function with 10
13
>>> foo(10)
13
>>> foo(11)
running function with 11
14
>>> @memoize
... def range_tuple(limit):
... print('running function')
... return tuple(i for i in range(limit))
...
>>> range_tuple(3)
running function
(0, 1, 2)
>>> range_tuple(3)
(0, 1, 2)
>>> @memoize
... def range_iter(limit):
... print('running function')
... return (i for i in range(limit))
...
>>> range_iter(3)
Traceback (most recent call last):
TypeError: Can't memoize a generator or non-hashable object!
"""
func._result_cache = {} # pylint: disable-msg=W0212
@wraps(func)
def _memoized_func(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key in func._result_cache: # pylint: disable-msg=W0212
return func._result_cache[key] # pylint: disable-msg=W0212
else:
result = func(*args, **kwargs)
if isinstance(result, GeneratorType) or not isinstance(result, Hashable):
raise TypeError("Can't memoize a generator or non-hashable object!")
func._result_cache[key] = result # pylint: disable-msg=W0212
return result
return _memoized_func | python | def memoize(func):
"""
Decorator to cause a function to cache it's results for each combination of
inputs and return the cached result on subsequent calls. Does not support
named arguments or arg values that are not hashable.
>>> @memoize
... def foo(x):
... print('running function with', x)
... return x+3
...
>>> foo(10)
running function with 10
13
>>> foo(10)
13
>>> foo(11)
running function with 11
14
>>> @memoize
... def range_tuple(limit):
... print('running function')
... return tuple(i for i in range(limit))
...
>>> range_tuple(3)
running function
(0, 1, 2)
>>> range_tuple(3)
(0, 1, 2)
>>> @memoize
... def range_iter(limit):
... print('running function')
... return (i for i in range(limit))
...
>>> range_iter(3)
Traceback (most recent call last):
TypeError: Can't memoize a generator or non-hashable object!
"""
func._result_cache = {} # pylint: disable-msg=W0212
@wraps(func)
def _memoized_func(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key in func._result_cache: # pylint: disable-msg=W0212
return func._result_cache[key] # pylint: disable-msg=W0212
else:
result = func(*args, **kwargs)
if isinstance(result, GeneratorType) or not isinstance(result, Hashable):
raise TypeError("Can't memoize a generator or non-hashable object!")
func._result_cache[key] = result # pylint: disable-msg=W0212
return result
return _memoized_func | [
"def",
"memoize",
"(",
"func",
")",
":",
"func",
".",
"_result_cache",
"=",
"{",
"}",
"# pylint: disable-msg=W0212",
"@",
"wraps",
"(",
"func",
")",
"def",
"_memoized_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"(",
"args",
... | Decorator to cause a function to cache it's results for each combination of
inputs and return the cached result on subsequent calls. Does not support
named arguments or arg values that are not hashable.
>>> @memoize
... def foo(x):
... print('running function with', x)
... return x+3
...
>>> foo(10)
running function with 10
13
>>> foo(10)
13
>>> foo(11)
running function with 11
14
>>> @memoize
... def range_tuple(limit):
... print('running function')
... return tuple(i for i in range(limit))
...
>>> range_tuple(3)
running function
(0, 1, 2)
>>> range_tuple(3)
(0, 1, 2)
>>> @memoize
... def range_iter(limit):
... print('running function')
... return (i for i in range(limit))
...
>>> range_iter(3)
Traceback (most recent call last):
TypeError: Can't memoize a generator or non-hashable object! | [
"Decorator",
"to",
"cause",
"a",
"function",
"to",
"cache",
"it",
"s",
"results",
"for",
"each",
"combination",
"of",
"inputs",
"and",
"return",
"the",
"cached",
"result",
"on",
"subsequent",
"calls",
".",
"Does",
"not",
"support",
"named",
"arguments",
"or"... | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/decorators.py#L10-L62 |
kalefranz/auxlib | auxlib/decorators.py | memoizemethod | def memoizemethod(method):
"""
Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
... @memoizemethod
... def foo(self, x, y=0):
... print('running method with', x, y)
... return x + y + 3
...
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.foo(10)
running method with 10 0
13
>>> foo1.foo(10)
13
>>> foo2.foo(11, y=7)
running method with 11 7
21
>>> foo2.foo(11)
running method with 11 0
14
>>> foo2.foo(11, y=7)
21
>>> class Foo (object):
... def __init__(self, lower):
... self.lower = lower
... @memoizemethod
... def range_tuple(self, upper):
... print('running function')
... return tuple(i for i in range(self.lower, upper))
... @memoizemethod
... def range_iter(self, upper):
... print('running function')
... return (i for i in range(self.lower, upper))
...
>>> foo = Foo(3)
>>> foo.range_tuple(6)
running function
(3, 4, 5)
>>> foo.range_tuple(7)
running function
(3, 4, 5, 6)
>>> foo.range_tuple(6)
(3, 4, 5)
>>> foo.range_iter(6)
Traceback (most recent call last):
TypeError: Can't memoize a generator or non-hashable object!
"""
@wraps(method)
def _wrapper(self, *args, **kwargs):
# NOTE: a __dict__ check is performed here rather than using the
# built-in hasattr function because hasattr will look up to an object's
# class if the attr is not directly found in the object's dict. That's
# bad for this if the class itself has a memoized classmethod for
# example that has been called before the memoized instance method,
# then the instance method will use the class's result cache, causing
# its results to be globally stored rather than on a per instance
# basis.
if '_memoized_results' not in self.__dict__:
self._memoized_results = {}
memoized_results = self._memoized_results
key = (method.__name__, args, tuple(sorted(kwargs.items())))
if key in memoized_results:
return memoized_results[key]
else:
try:
result = method(self, *args, **kwargs)
except KeyError as e:
if '__wrapped__' in str(e):
result = None # is this the right thing to do? happened during py3 conversion
else:
raise
if isinstance(result, GeneratorType) or not isinstance(result, Hashable):
raise TypeError("Can't memoize a generator or non-hashable object!")
return memoized_results.setdefault(key, result)
return _wrapper | python | def memoizemethod(method):
"""
Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
... @memoizemethod
... def foo(self, x, y=0):
... print('running method with', x, y)
... return x + y + 3
...
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.foo(10)
running method with 10 0
13
>>> foo1.foo(10)
13
>>> foo2.foo(11, y=7)
running method with 11 7
21
>>> foo2.foo(11)
running method with 11 0
14
>>> foo2.foo(11, y=7)
21
>>> class Foo (object):
... def __init__(self, lower):
... self.lower = lower
... @memoizemethod
... def range_tuple(self, upper):
... print('running function')
... return tuple(i for i in range(self.lower, upper))
... @memoizemethod
... def range_iter(self, upper):
... print('running function')
... return (i for i in range(self.lower, upper))
...
>>> foo = Foo(3)
>>> foo.range_tuple(6)
running function
(3, 4, 5)
>>> foo.range_tuple(7)
running function
(3, 4, 5, 6)
>>> foo.range_tuple(6)
(3, 4, 5)
>>> foo.range_iter(6)
Traceback (most recent call last):
TypeError: Can't memoize a generator or non-hashable object!
"""
@wraps(method)
def _wrapper(self, *args, **kwargs):
# NOTE: a __dict__ check is performed here rather than using the
# built-in hasattr function because hasattr will look up to an object's
# class if the attr is not directly found in the object's dict. That's
# bad for this if the class itself has a memoized classmethod for
# example that has been called before the memoized instance method,
# then the instance method will use the class's result cache, causing
# its results to be globally stored rather than on a per instance
# basis.
if '_memoized_results' not in self.__dict__:
self._memoized_results = {}
memoized_results = self._memoized_results
key = (method.__name__, args, tuple(sorted(kwargs.items())))
if key in memoized_results:
return memoized_results[key]
else:
try:
result = method(self, *args, **kwargs)
except KeyError as e:
if '__wrapped__' in str(e):
result = None # is this the right thing to do? happened during py3 conversion
else:
raise
if isinstance(result, GeneratorType) or not isinstance(result, Hashable):
raise TypeError("Can't memoize a generator or non-hashable object!")
return memoized_results.setdefault(key, result)
return _wrapper | [
"def",
"memoizemethod",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# NOTE: a __dict__ check is performed here rather than using the",
"# built-in hasattr function ... | Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
... @memoizemethod
... def foo(self, x, y=0):
... print('running method with', x, y)
... return x + y + 3
...
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.foo(10)
running method with 10 0
13
>>> foo1.foo(10)
13
>>> foo2.foo(11, y=7)
running method with 11 7
21
>>> foo2.foo(11)
running method with 11 0
14
>>> foo2.foo(11, y=7)
21
>>> class Foo (object):
... def __init__(self, lower):
... self.lower = lower
... @memoizemethod
... def range_tuple(self, upper):
... print('running function')
... return tuple(i for i in range(self.lower, upper))
... @memoizemethod
... def range_iter(self, upper):
... print('running function')
... return (i for i in range(self.lower, upper))
...
>>> foo = Foo(3)
>>> foo.range_tuple(6)
running function
(3, 4, 5)
>>> foo.range_tuple(7)
running function
(3, 4, 5, 6)
>>> foo.range_tuple(6)
(3, 4, 5)
>>> foo.range_iter(6)
Traceback (most recent call last):
TypeError: Can't memoize a generator or non-hashable object! | [
"Decorator",
"to",
"cause",
"a",
"method",
"to",
"cache",
"it",
"s",
"results",
"in",
"self",
"for",
"each",
"combination",
"of",
"inputs",
"and",
"return",
"the",
"cached",
"result",
"on",
"subsequent",
"calls",
".",
"Does",
"not",
"support",
"named",
"ar... | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/decorators.py#L65-L147 |
kalefranz/auxlib | auxlib/decorators.py | clear_memoized_methods | def clear_memoized_methods(obj, *method_names):
"""
Clear the memoized method or @memoizedproperty results for the given
method names from the given object.
>>> v = [0]
>>> def inc():
... v[0] += 1
... return v[0]
...
>>> class Foo(object):
... @memoizemethod
... def foo(self):
... return inc()
... @memoizedproperty
... def g(self):
... return inc()
...
>>> f = Foo()
>>> f.foo(), f.foo()
(1, 1)
>>> clear_memoized_methods(f, 'foo')
>>> (f.foo(), f.foo(), f.g, f.g)
(2, 2, 3, 3)
>>> (f.foo(), f.foo(), f.g, f.g)
(2, 2, 3, 3)
>>> clear_memoized_methods(f, 'g', 'no_problem_if_undefined')
>>> f.g, f.foo(), f.g
(4, 2, 4)
>>> f.foo()
2
"""
for key in list(getattr(obj, '_memoized_results', {}).keys()):
# key[0] is the method name
if key[0] in method_names:
del obj._memoized_results[key]
try:
property_dict = obj._cache_
except AttributeError:
property_dict = obj._cache_ = {}
for prop in method_names:
inner_attname = '__%s' % prop
if inner_attname in property_dict:
del property_dict[inner_attname] | python | def clear_memoized_methods(obj, *method_names):
"""
Clear the memoized method or @memoizedproperty results for the given
method names from the given object.
>>> v = [0]
>>> def inc():
... v[0] += 1
... return v[0]
...
>>> class Foo(object):
... @memoizemethod
... def foo(self):
... return inc()
... @memoizedproperty
... def g(self):
... return inc()
...
>>> f = Foo()
>>> f.foo(), f.foo()
(1, 1)
>>> clear_memoized_methods(f, 'foo')
>>> (f.foo(), f.foo(), f.g, f.g)
(2, 2, 3, 3)
>>> (f.foo(), f.foo(), f.g, f.g)
(2, 2, 3, 3)
>>> clear_memoized_methods(f, 'g', 'no_problem_if_undefined')
>>> f.g, f.foo(), f.g
(4, 2, 4)
>>> f.foo()
2
"""
for key in list(getattr(obj, '_memoized_results', {}).keys()):
# key[0] is the method name
if key[0] in method_names:
del obj._memoized_results[key]
try:
property_dict = obj._cache_
except AttributeError:
property_dict = obj._cache_ = {}
for prop in method_names:
inner_attname = '__%s' % prop
if inner_attname in property_dict:
del property_dict[inner_attname] | [
"def",
"clear_memoized_methods",
"(",
"obj",
",",
"*",
"method_names",
")",
":",
"for",
"key",
"in",
"list",
"(",
"getattr",
"(",
"obj",
",",
"'_memoized_results'",
",",
"{",
"}",
")",
".",
"keys",
"(",
")",
")",
":",
"# key[0] is the method name",
"if",
... | Clear the memoized method or @memoizedproperty results for the given
method names from the given object.
>>> v = [0]
>>> def inc():
... v[0] += 1
... return v[0]
...
>>> class Foo(object):
... @memoizemethod
... def foo(self):
... return inc()
... @memoizedproperty
... def g(self):
... return inc()
...
>>> f = Foo()
>>> f.foo(), f.foo()
(1, 1)
>>> clear_memoized_methods(f, 'foo')
>>> (f.foo(), f.foo(), f.g, f.g)
(2, 2, 3, 3)
>>> (f.foo(), f.foo(), f.g, f.g)
(2, 2, 3, 3)
>>> clear_memoized_methods(f, 'g', 'no_problem_if_undefined')
>>> f.g, f.foo(), f.g
(4, 2, 4)
>>> f.foo()
2 | [
"Clear",
"the",
"memoized",
"method",
"or",
"@memoizedproperty",
"results",
"for",
"the",
"given",
"method",
"names",
"from",
"the",
"given",
"object",
"."
] | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/decorators.py#L187-L232 |
kalefranz/auxlib | auxlib/decorators.py | memoizedproperty | def memoizedproperty(func):
"""
Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
... _x = 1
... @memoizedproperty
... def foo(self):
... self._x += 1
... print('updating and returning {0}'.format(self._x))
... return self._x
...
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.foo
updating and returning 2
2
>>> foo1.foo
2
>>> foo2.foo
updating and returning 2
2
>>> foo1.foo
2
"""
inner_attname = '__%s' % func.__name__
def new_fget(self):
if not hasattr(self, '_cache_'):
self._cache_ = dict()
cache = self._cache_
if inner_attname not in cache:
cache[inner_attname] = func(self)
return cache[inner_attname]
return property(new_fget) | python | def memoizedproperty(func):
"""
Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
... _x = 1
... @memoizedproperty
... def foo(self):
... self._x += 1
... print('updating and returning {0}'.format(self._x))
... return self._x
...
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.foo
updating and returning 2
2
>>> foo1.foo
2
>>> foo2.foo
updating and returning 2
2
>>> foo1.foo
2
"""
inner_attname = '__%s' % func.__name__
def new_fget(self):
if not hasattr(self, '_cache_'):
self._cache_ = dict()
cache = self._cache_
if inner_attname not in cache:
cache[inner_attname] = func(self)
return cache[inner_attname]
return property(new_fget) | [
"def",
"memoizedproperty",
"(",
"func",
")",
":",
"inner_attname",
"=",
"'__%s'",
"%",
"func",
".",
"__name__",
"def",
"new_fget",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_cache_'",
")",
":",
"self",
".",
"_cache_",
"=",
"dic... | Decorator to cause a method to cache it's results in self for each
combination of inputs and return the cached result on subsequent calls.
Does not support named arguments or arg values that are not hashable.
>>> class Foo (object):
... _x = 1
... @memoizedproperty
... def foo(self):
... self._x += 1
... print('updating and returning {0}'.format(self._x))
... return self._x
...
>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.foo
updating and returning 2
2
>>> foo1.foo
2
>>> foo2.foo
updating and returning 2
2
>>> foo1.foo
2 | [
"Decorator",
"to",
"cause",
"a",
"method",
"to",
"cache",
"it",
"s",
"results",
"in",
"self",
"for",
"each",
"combination",
"of",
"inputs",
"and",
"return",
"the",
"cached",
"result",
"on",
"subsequent",
"calls",
".",
"Does",
"not",
"support",
"named",
"ar... | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/decorators.py#L235-L272 |
kalefranz/auxlib | auxlib/crypt.py | aes_encrypt | def aes_encrypt(base64_encryption_key, data):
"""Encrypt data with AES-CBC and sign it with HMAC-SHA256
Arguments:
base64_encryption_key (str): a base64-encoded string containing an AES encryption key
and HMAC signing key as generated by generate_encryption_key()
data (str): a byte string containing the data to be encrypted
Returns:
str: the encrypted data as a byte string with the HMAC signature appended to the end
"""
if isinstance(data, text_type):
data = data.encode("UTF-8")
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data = _pad(data)
iv_bytes = os.urandom(AES_BLOCK_SIZE)
cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv_bytes)
data = iv_bytes + cipher.encrypt(data) # prepend init vector
hmac_signature = hmac.new(hmac_key_bytes, data, hashlib.sha256).digest()
return as_base64(data + hmac_signature) | python | def aes_encrypt(base64_encryption_key, data):
"""Encrypt data with AES-CBC and sign it with HMAC-SHA256
Arguments:
base64_encryption_key (str): a base64-encoded string containing an AES encryption key
and HMAC signing key as generated by generate_encryption_key()
data (str): a byte string containing the data to be encrypted
Returns:
str: the encrypted data as a byte string with the HMAC signature appended to the end
"""
if isinstance(data, text_type):
data = data.encode("UTF-8")
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data = _pad(data)
iv_bytes = os.urandom(AES_BLOCK_SIZE)
cipher = AES.new(aes_key_bytes, mode=AES.MODE_CBC, IV=iv_bytes)
data = iv_bytes + cipher.encrypt(data) # prepend init vector
hmac_signature = hmac.new(hmac_key_bytes, data, hashlib.sha256).digest()
return as_base64(data + hmac_signature) | [
"def",
"aes_encrypt",
"(",
"base64_encryption_key",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"text_type",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"\"UTF-8\"",
")",
"aes_key_bytes",
",",
"hmac_key_bytes",
"=",
"_extract_keys",
"... | Encrypt data with AES-CBC and sign it with HMAC-SHA256
Arguments:
base64_encryption_key (str): a base64-encoded string containing an AES encryption key
and HMAC signing key as generated by generate_encryption_key()
data (str): a byte string containing the data to be encrypted
Returns:
str: the encrypted data as a byte string with the HMAC signature appended to the end | [
"Encrypt",
"data",
"with",
"AES",
"-",
"CBC",
"and",
"sign",
"it",
"with",
"HMAC",
"-",
"SHA256"
] | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/crypt.py#L77-L97 |
kalefranz/auxlib | auxlib/crypt.py | aes_decrypt | def aes_decrypt(base64_encryption_key, base64_data):
"""Verify HMAC-SHA256 signature and decrypt data with AES-CBC
Arguments:
encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC
signing key as generated by generate_encryption_key()
data (str): a byte string containing the data decrypted with an HMAC signing key
appended to the end
Returns:
str: a byte string containing the data that was originally encrypted
Raises:
AuthenticationError: when the HMAC-SHA256 signature authentication fails
"""
data = from_base64(base64_data)
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data, hmac_signature = data[:-HMAC_SIG_SIZE], data[-HMAC_SIG_SIZE:]
if hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() != hmac_signature:
raise AuthenticationError("HMAC authentication failed")
iv_bytes, data = data[:AES_BLOCK_SIZE], data[AES_BLOCK_SIZE:]
cipher = AES.new(aes_key_bytes, AES.MODE_CBC, iv_bytes)
data = cipher.decrypt(data)
return _unpad(data) | python | def aes_decrypt(base64_encryption_key, base64_data):
"""Verify HMAC-SHA256 signature and decrypt data with AES-CBC
Arguments:
encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC
signing key as generated by generate_encryption_key()
data (str): a byte string containing the data decrypted with an HMAC signing key
appended to the end
Returns:
str: a byte string containing the data that was originally encrypted
Raises:
AuthenticationError: when the HMAC-SHA256 signature authentication fails
"""
data = from_base64(base64_data)
aes_key_bytes, hmac_key_bytes = _extract_keys(base64_encryption_key)
data, hmac_signature = data[:-HMAC_SIG_SIZE], data[-HMAC_SIG_SIZE:]
if hmac.new(hmac_key_bytes, data, hashlib.sha256).digest() != hmac_signature:
raise AuthenticationError("HMAC authentication failed")
iv_bytes, data = data[:AES_BLOCK_SIZE], data[AES_BLOCK_SIZE:]
cipher = AES.new(aes_key_bytes, AES.MODE_CBC, iv_bytes)
data = cipher.decrypt(data)
return _unpad(data) | [
"def",
"aes_decrypt",
"(",
"base64_encryption_key",
",",
"base64_data",
")",
":",
"data",
"=",
"from_base64",
"(",
"base64_data",
")",
"aes_key_bytes",
",",
"hmac_key_bytes",
"=",
"_extract_keys",
"(",
"base64_encryption_key",
")",
"data",
",",
"hmac_signature",
"="... | Verify HMAC-SHA256 signature and decrypt data with AES-CBC
Arguments:
encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC
signing key as generated by generate_encryption_key()
data (str): a byte string containing the data decrypted with an HMAC signing key
appended to the end
Returns:
str: a byte string containing the data that was originally encrypted
Raises:
AuthenticationError: when the HMAC-SHA256 signature authentication fails | [
"Verify",
"HMAC",
"-",
"SHA256",
"signature",
"and",
"decrypt",
"data",
"with",
"AES",
"-",
"CBC"
] | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/crypt.py#L100-L124 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/whoami.py | whoami | def whoami(ctx, opts):
"""Retrieve your current authentication status."""
click.echo("Retrieving your authentication status from the API ... ", nl=False)
context_msg = "Failed to retrieve your authentication status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
is_auth, username, email, name = get_user_brief()
click.secho("OK", fg="green")
click.echo("You are authenticated as:")
if not is_auth:
click.secho("Nobody (i.e. anonymous user)", fg="yellow")
else:
click.secho(
"%(name)s (slug: %(username)s, email: %(email)s)"
% {
"name": click.style(name, fg="cyan"),
"username": click.style(username, fg="magenta"),
"email": click.style(email, fg="green"),
}
) | python | def whoami(ctx, opts):
"""Retrieve your current authentication status."""
click.echo("Retrieving your authentication status from the API ... ", nl=False)
context_msg = "Failed to retrieve your authentication status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
is_auth, username, email, name = get_user_brief()
click.secho("OK", fg="green")
click.echo("You are authenticated as:")
if not is_auth:
click.secho("Nobody (i.e. anonymous user)", fg="yellow")
else:
click.secho(
"%(name)s (slug: %(username)s, email: %(email)s)"
% {
"name": click.style(name, fg="cyan"),
"username": click.style(username, fg="magenta"),
"email": click.style(email, fg="green"),
}
) | [
"def",
"whoami",
"(",
"ctx",
",",
"opts",
")",
":",
"click",
".",
"echo",
"(",
"\"Retrieving your authentication status from the API ... \"",
",",
"nl",
"=",
"False",
")",
"context_msg",
"=",
"\"Failed to retrieve your authentication status!\"",
"with",
"handle_api_except... | Retrieve your current authentication status. | [
"Retrieve",
"your",
"current",
"authentication",
"status",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/whoami.py#L20-L41 |
marrow/schema | marrow/schema/transform/container.py | Array._clean | def _clean(self, value):
"""Perform a standardized pipline of operations across an iterable."""
value = (str(v) for v in value)
if self.strip:
value = (v.strip() for v in value)
if not self.empty:
value = (v for v in value if v)
return value | python | def _clean(self, value):
"""Perform a standardized pipline of operations across an iterable."""
value = (str(v) for v in value)
if self.strip:
value = (v.strip() for v in value)
if not self.empty:
value = (v for v in value if v)
return value | [
"def",
"_clean",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"value",
")",
"if",
"self",
".",
"strip",
":",
"value",
"=",
"(",
"v",
".",
"strip",
"(",
")",
"for",
"v",
"in",
"value",
")",
... | Perform a standardized pipline of operations across an iterable. | [
"Perform",
"a",
"standardized",
"pipline",
"of",
"operations",
"across",
"an",
"iterable",
"."
] | train | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/container.py#L21-L32 |
marrow/schema | marrow/schema/transform/container.py | Array.native | def native(self, value, context=None):
"""Convert the given string into a list of substrings."""
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = super().native(value, context)
if value is None:
return self.cast()
if hasattr(value, 'split'):
value = value.split(separator)
value = self._clean(value)
try:
return self.cast(value) if self.cast else value
except Exception as e:
raise Concern("{0} caught, failed to perform array transform: {1}", e.__class__.__name__, str(e)) | python | def native(self, value, context=None):
"""Convert the given string into a list of substrings."""
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = super().native(value, context)
if value is None:
return self.cast()
if hasattr(value, 'split'):
value = value.split(separator)
value = self._clean(value)
try:
return self.cast(value) if self.cast else value
except Exception as e:
raise Concern("{0} caught, failed to perform array transform: {1}", e.__class__.__name__, str(e)) | [
"def",
"native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"separator",
"=",
"self",
".",
"separator",
".",
"strip",
"(",
")",
"if",
"self",
".",
"strip",
"and",
"hasattr",
"(",
"self",
".",
"separator",
",",
"'strip'",
")",
... | Convert the given string into a list of substrings. | [
"Convert",
"the",
"given",
"string",
"into",
"a",
"list",
"of",
"substrings",
"."
] | train | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/container.py#L34-L51 |
marrow/schema | marrow/schema/transform/container.py | Array.foreign | def foreign(self, value, context=None):
"""Construct a string-like representation for an iterable of string-like objects."""
if self.separator is None:
separator = ' '
else:
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = self._clean(value)
try:
value = separator.join(value)
except Exception as e:
raise Concern("{0} caught, failed to convert to string: {1}", e.__class__.__name__, str(e))
return super().foreign(value) | python | def foreign(self, value, context=None):
"""Construct a string-like representation for an iterable of string-like objects."""
if self.separator is None:
separator = ' '
else:
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = self._clean(value)
try:
value = separator.join(value)
except Exception as e:
raise Concern("{0} caught, failed to convert to string: {1}", e.__class__.__name__, str(e))
return super().foreign(value) | [
"def",
"foreign",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"separator",
"is",
"None",
":",
"separator",
"=",
"' '",
"else",
":",
"separator",
"=",
"self",
".",
"separator",
".",
"strip",
"(",
")",
"if",
"... | Construct a string-like representation for an iterable of string-like objects. | [
"Construct",
"a",
"string",
"-",
"like",
"representation",
"for",
"an",
"iterable",
"of",
"string",
"-",
"like",
"objects",
"."
] | train | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/container.py#L53-L68 |
ndf-zz/asfv1 | asfv1.py | tob32 | def tob32(val):
"""Return provided 32 bit value as a string of four bytes."""
ret = bytearray(4)
ret[0] = (val>>24)&M8
ret[1] = (val>>16)&M8
ret[2] = (val>>8)&M8
ret[3] = val&M8
return ret | python | def tob32(val):
"""Return provided 32 bit value as a string of four bytes."""
ret = bytearray(4)
ret[0] = (val>>24)&M8
ret[1] = (val>>16)&M8
ret[2] = (val>>8)&M8
ret[3] = val&M8
return ret | [
"def",
"tob32",
"(",
"val",
")",
":",
"ret",
"=",
"bytearray",
"(",
"4",
")",
"ret",
"[",
"0",
"]",
"=",
"(",
"val",
">>",
"24",
")",
"&",
"M8",
"ret",
"[",
"1",
"]",
"=",
"(",
"val",
">>",
"16",
")",
"&",
"M8",
"ret",
"[",
"2",
"]",
"=... | Return provided 32 bit value as a string of four bytes. | [
"Return",
"provided",
"32",
"bit",
"value",
"as",
"a",
"string",
"of",
"four",
"bytes",
"."
] | train | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L129-L136 |
ndf-zz/asfv1 | asfv1.py | bintoihex | def bintoihex(buf, spos=0x0000):
"""Convert binary buffer to ihex and return as string."""
c = 0
olen = len(buf)
ret = ""
# 16 byte lines
while (c+0x10) <= olen:
adr = c + spos
l = ':10{0:04X}00'.format(adr)
sum = 0x10+((adr>>8)&M8)+(adr&M8)
for j in range(0,0x10):
nb = buf[c+j]
l += '{0:02X}'.format(nb)
sum = (sum + nb)&M8
l += '{0:02X}'.format((~sum+1)&M8)
ret += l + '\n'
c += 0x10
# remainder
if c < olen:
rem = olen-c
sum = rem
adr = c + spos
l = ':{0:02X}{1:04X}00'.format(rem,adr) # rem < 0x10
sum += ((adr>>8)&M8)+(adr&M8)
for j in range(0,rem):
nb = buf[c+j]
l += '{0:02X}'.format(nb)
sum = (sum + nb)&M8
l += '{0:02X}'.format((~sum+1)&M8)
ret += l + '\n'
ret += ':00000001FF\n' # EOF
return ret | python | def bintoihex(buf, spos=0x0000):
"""Convert binary buffer to ihex and return as string."""
c = 0
olen = len(buf)
ret = ""
# 16 byte lines
while (c+0x10) <= olen:
adr = c + spos
l = ':10{0:04X}00'.format(adr)
sum = 0x10+((adr>>8)&M8)+(adr&M8)
for j in range(0,0x10):
nb = buf[c+j]
l += '{0:02X}'.format(nb)
sum = (sum + nb)&M8
l += '{0:02X}'.format((~sum+1)&M8)
ret += l + '\n'
c += 0x10
# remainder
if c < olen:
rem = olen-c
sum = rem
adr = c + spos
l = ':{0:02X}{1:04X}00'.format(rem,adr) # rem < 0x10
sum += ((adr>>8)&M8)+(adr&M8)
for j in range(0,rem):
nb = buf[c+j]
l += '{0:02X}'.format(nb)
sum = (sum + nb)&M8
l += '{0:02X}'.format((~sum+1)&M8)
ret += l + '\n'
ret += ':00000001FF\n' # EOF
return ret | [
"def",
"bintoihex",
"(",
"buf",
",",
"spos",
"=",
"0x0000",
")",
":",
"c",
"=",
"0",
"olen",
"=",
"len",
"(",
"buf",
")",
"ret",
"=",
"\"\"",
"# 16 byte lines",
"while",
"(",
"c",
"+",
"0x10",
")",
"<=",
"olen",
":",
"adr",
"=",
"c",
"+",
"spos... | Convert binary buffer to ihex and return as string. | [
"Convert",
"binary",
"buffer",
"to",
"ihex",
"and",
"return",
"as",
"string",
"."
] | train | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L138-L169 |
ndf-zz/asfv1 | asfv1.py | op_gen | def op_gen(mcode):
"""Generate a machine instruction using the op gen table."""
gen = op_tbl[mcode[0]]
ret = gen[0] # opcode
nargs = len(gen)
i = 1
while i < nargs:
if i < len(mcode): # or assume they are same len
ret |= (mcode[i]&gen[i][0]) << gen[i][1]
i += 1
return ret | python | def op_gen(mcode):
"""Generate a machine instruction using the op gen table."""
gen = op_tbl[mcode[0]]
ret = gen[0] # opcode
nargs = len(gen)
i = 1
while i < nargs:
if i < len(mcode): # or assume they are same len
ret |= (mcode[i]&gen[i][0]) << gen[i][1]
i += 1
return ret | [
"def",
"op_gen",
"(",
"mcode",
")",
":",
"gen",
"=",
"op_tbl",
"[",
"mcode",
"[",
"0",
"]",
"]",
"ret",
"=",
"gen",
"[",
"0",
"]",
"# opcode",
"nargs",
"=",
"len",
"(",
"gen",
")",
"i",
"=",
"1",
"while",
"i",
"<",
"nargs",
":",
"if",
"i",
... | Generate a machine instruction using the op gen table. | [
"Generate",
"a",
"machine",
"instruction",
"using",
"the",
"op",
"gen",
"table",
"."
] | train | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L207-L217 |
ndf-zz/asfv1 | asfv1.py | fv1parse.scanerror | def scanerror(self, msg):
"""Emit scan error and abort assembly."""
error('scan error: ' + msg + ' on line {}'.format(self.sline))
sys.exit(-1) | python | def scanerror(self, msg):
"""Emit scan error and abort assembly."""
error('scan error: ' + msg + ' on line {}'.format(self.sline))
sys.exit(-1) | [
"def",
"scanerror",
"(",
"self",
",",
"msg",
")",
":",
"error",
"(",
"'scan error: '",
"+",
"msg",
"+",
"' on line {}'",
".",
"format",
"(",
"self",
".",
"sline",
")",
")",
"sys",
".",
"exit",
"(",
"-",
"1",
")"
] | Emit scan error and abort assembly. | [
"Emit",
"scan",
"error",
"and",
"abort",
"assembly",
"."
] | train | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L792-L795 |
ndf-zz/asfv1 | asfv1.py | fv1parse.parsewarn | def parsewarn(self, msg, line=None):
"""Emit parse warning."""
if line is None:
line = self.sline
self.dowarn('warning: ' + msg + ' on line {}'.format(line)) | python | def parsewarn(self, msg, line=None):
"""Emit parse warning."""
if line is None:
line = self.sline
self.dowarn('warning: ' + msg + ' on line {}'.format(line)) | [
"def",
"parsewarn",
"(",
"self",
",",
"msg",
",",
"line",
"=",
"None",
")",
":",
"if",
"line",
"is",
"None",
":",
"line",
"=",
"self",
".",
"sline",
"self",
".",
"dowarn",
"(",
"'warning: '",
"+",
"msg",
"+",
"' on line {}'",
".",
"format",
"(",
"l... | Emit parse warning. | [
"Emit",
"parse",
"warning",
"."
] | train | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L797-L801 |
ndf-zz/asfv1 | asfv1.py | fv1parse.parseerror | def parseerror(self, msg, line=None):
"""Emit parse error and abort assembly."""
if line is None:
line = self.sline
error('parse error: ' + msg + ' on line {}'.format(line))
sys.exit(-2) | python | def parseerror(self, msg, line=None):
"""Emit parse error and abort assembly."""
if line is None:
line = self.sline
error('parse error: ' + msg + ' on line {}'.format(line))
sys.exit(-2) | [
"def",
"parseerror",
"(",
"self",
",",
"msg",
",",
"line",
"=",
"None",
")",
":",
"if",
"line",
"is",
"None",
":",
"line",
"=",
"self",
".",
"sline",
"error",
"(",
"'parse error: '",
"+",
"msg",
"+",
"' on line {}'",
".",
"format",
"(",
"line",
")",
... | Emit parse error and abort assembly. | [
"Emit",
"parse",
"error",
"and",
"abort",
"assembly",
"."
] | train | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L803-L808 |
ndf-zz/asfv1 | asfv1.py | fv1parse.parse | def parse(self):
"""Parse input."""
self.__next__()
while self.sym['type'] != 'EOF':
if self.sym['type'] == 'LABEL':
self.__label__()
elif self.sym['type'] == 'MNEMONIC':
self.__instruction__()
elif self.sym['type'] == 'NAME' or self.sym['type'] == 'ASSEMBLER':
self.__assembler__()
else:
self.parseerror('Unexpected input {}/{}'.format(
self.sym['type'], repr(self.sym['txt'])))
# patch skip targets if required
for i in self.pl:
if i['cmd'][0] == 'SKP':
if i['target'] is not None:
if i['target'] in self.jmptbl:
iloc = i['addr']
dest = self.jmptbl[i['target']]
if dest > iloc:
oft = dest - iloc - 1
if oft > M6:
self.parseerror('Offset from SKP to '
+ repr(i['target'])
+ ' (' + hex(oft)
+ ') too large',
i['line'])
else:
i['cmd'][2] = oft
else:
self.parseerror('Target '
+ repr(i['target'])
+' does not follow SKP',
i['line'])
else:
self.parseerror('Undefined target for SKP '
+ repr(i['target']),
i['line'])
else:
pass # assume offset is immediate
self.__mkopcodes__() | python | def parse(self):
"""Parse input."""
self.__next__()
while self.sym['type'] != 'EOF':
if self.sym['type'] == 'LABEL':
self.__label__()
elif self.sym['type'] == 'MNEMONIC':
self.__instruction__()
elif self.sym['type'] == 'NAME' or self.sym['type'] == 'ASSEMBLER':
self.__assembler__()
else:
self.parseerror('Unexpected input {}/{}'.format(
self.sym['type'], repr(self.sym['txt'])))
# patch skip targets if required
for i in self.pl:
if i['cmd'][0] == 'SKP':
if i['target'] is not None:
if i['target'] in self.jmptbl:
iloc = i['addr']
dest = self.jmptbl[i['target']]
if dest > iloc:
oft = dest - iloc - 1
if oft > M6:
self.parseerror('Offset from SKP to '
+ repr(i['target'])
+ ' (' + hex(oft)
+ ') too large',
i['line'])
else:
i['cmd'][2] = oft
else:
self.parseerror('Target '
+ repr(i['target'])
+' does not follow SKP',
i['line'])
else:
self.parseerror('Undefined target for SKP '
+ repr(i['target']),
i['line'])
else:
pass # assume offset is immediate
self.__mkopcodes__() | [
"def",
"parse",
"(",
"self",
")",
":",
"self",
".",
"__next__",
"(",
")",
"while",
"self",
".",
"sym",
"[",
"'type'",
"]",
"!=",
"'EOF'",
":",
"if",
"self",
".",
"sym",
"[",
"'type'",
"]",
"==",
"'LABEL'",
":",
"self",
".",
"__label__",
"(",
")",... | Parse input. | [
"Parse",
"input",
"."
] | train | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L1114-L1155 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/resync.py | resync | def resync(
ctx,
opts,
owner_repo_package,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Resynchronise a package in a repository.
This requires appropriate permissions for package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'.
Full CLI example:
$ cloudsmith resync your-org/awesome-repo/better-pkg
"""
owner, source, slug = owner_repo_package
resync_package(
ctx=ctx, opts=opts, owner=owner, repo=source, slug=slug, skip_errors=skip_errors
)
if no_wait_for_sync:
return
wait_for_package_sync(
ctx=ctx,
opts=opts,
owner=owner,
repo=source,
slug=slug,
wait_interval=wait_interval,
skip_errors=skip_errors,
attempts=sync_attempts,
) | python | def resync(
ctx,
opts,
owner_repo_package,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Resynchronise a package in a repository.
This requires appropriate permissions for package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'.
Full CLI example:
$ cloudsmith resync your-org/awesome-repo/better-pkg
"""
owner, source, slug = owner_repo_package
resync_package(
ctx=ctx, opts=opts, owner=owner, repo=source, slug=slug, skip_errors=skip_errors
)
if no_wait_for_sync:
return
wait_for_package_sync(
ctx=ctx,
opts=opts,
owner=owner,
repo=source,
slug=slug,
wait_interval=wait_interval,
skip_errors=skip_errors,
attempts=sync_attempts,
) | [
"def",
"resync",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_package",
",",
"skip_errors",
",",
"wait_interval",
",",
"no_wait_for_sync",
",",
"sync_attempts",
",",
")",
":",
"owner",
",",
"source",
",",
"slug",
"=",
"owner_repo_package",
"resync_package",
"(",
... | Resynchronise a package in a repository.
This requires appropriate permissions for package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'.
Full CLI example:
$ cloudsmith resync your-org/awesome-repo/better-pkg | [
"Resynchronise",
"a",
"package",
"in",
"a",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/resync.py#L27-L69 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/resync.py | resync_package | def resync_package(ctx, opts, owner, repo, slug, skip_errors):
"""Resynchronise a package."""
click.echo(
"Resynchonising the %(slug)s package ... "
% {"slug": click.style(slug, bold=True)},
nl=False,
)
context_msg = "Failed to resynchronise package!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
api_resync_package(owner=owner, repo=repo, identifier=slug)
click.secho("OK", fg="green") | python | def resync_package(ctx, opts, owner, repo, slug, skip_errors):
"""Resynchronise a package."""
click.echo(
"Resynchonising the %(slug)s package ... "
% {"slug": click.style(slug, bold=True)},
nl=False,
)
context_msg = "Failed to resynchronise package!"
with handle_api_exceptions(
ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
):
with maybe_spinner(opts):
api_resync_package(owner=owner, repo=repo, identifier=slug)
click.secho("OK", fg="green") | [
"def",
"resync_package",
"(",
"ctx",
",",
"opts",
",",
"owner",
",",
"repo",
",",
"slug",
",",
"skip_errors",
")",
":",
"click",
".",
"echo",
"(",
"\"Resynchonising the %(slug)s package ... \"",
"%",
"{",
"\"slug\"",
":",
"click",
".",
"style",
"(",
"slug",
... | Resynchronise a package. | [
"Resynchronise",
"a",
"package",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/resync.py#L72-L87 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | make_create_payload | def make_create_payload(**kwargs):
"""Create payload for upload/check-upload operations."""
payload = {}
# Add non-empty arguments
for k, v in six.iteritems(kwargs):
if v is not None:
payload[k] = v
return payload | python | def make_create_payload(**kwargs):
"""Create payload for upload/check-upload operations."""
payload = {}
# Add non-empty arguments
for k, v in six.iteritems(kwargs):
if v is not None:
payload[k] = v
return payload | [
"def",
"make_create_payload",
"(",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"}",
"# Add non-empty arguments",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"payload",
"[",
... | Create payload for upload/check-upload operations. | [
"Create",
"payload",
"for",
"upload",
"/",
"check",
"-",
"upload",
"operations",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L21-L29 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | create_package | def create_package(package_format, owner, repo, **kwargs):
"""Create a new package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
upload = getattr(client, "packages_upload_%s_with_http_info" % package_format)
data, _, headers = upload(
owner=owner, repo=repo, data=make_create_payload(**kwargs)
)
ratelimits.maybe_rate_limit(client, headers)
return data.slug_perm, data.slug | python | def create_package(package_format, owner, repo, **kwargs):
"""Create a new package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
upload = getattr(client, "packages_upload_%s_with_http_info" % package_format)
data, _, headers = upload(
owner=owner, repo=repo, data=make_create_payload(**kwargs)
)
ratelimits.maybe_rate_limit(client, headers)
return data.slug_perm, data.slug | [
"def",
"create_package",
"(",
"package_format",
",",
"owner",
",",
"repo",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"upload",
"=",
"getattr",
"(",
"client",
",",
"\"... | Create a new package in a repository. | [
"Create",
"a",
"new",
"package",
"in",
"a",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L32-L44 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | validate_create_package | def validate_create_package(package_format, owner, repo, **kwargs):
"""Validate parameters for creating a package."""
client = get_packages_api()
with catch_raise_api_exception():
check = getattr(
client, "packages_validate_upload_%s_with_http_info" % package_format
)
_, _, headers = check(
owner=owner, repo=repo, data=make_create_payload(**kwargs)
)
ratelimits.maybe_rate_limit(client, headers)
return True | python | def validate_create_package(package_format, owner, repo, **kwargs):
"""Validate parameters for creating a package."""
client = get_packages_api()
with catch_raise_api_exception():
check = getattr(
client, "packages_validate_upload_%s_with_http_info" % package_format
)
_, _, headers = check(
owner=owner, repo=repo, data=make_create_payload(**kwargs)
)
ratelimits.maybe_rate_limit(client, headers)
return True | [
"def",
"validate_create_package",
"(",
"package_format",
",",
"owner",
",",
"repo",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"check",
"=",
"getattr",
"(",
"client",
",... | Validate parameters for creating a package. | [
"Validate",
"parameters",
"for",
"creating",
"a",
"package",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L47-L61 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | copy_package | def copy_package(owner, repo, identifier, destination):
"""Copy a package to another repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_copy_with_http_info(
owner=owner,
repo=repo,
identifier=identifier,
data={"destination": destination},
)
ratelimits.maybe_rate_limit(client, headers)
return data.slug_perm, data.slug | python | def copy_package(owner, repo, identifier, destination):
"""Copy a package to another repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_copy_with_http_info(
owner=owner,
repo=repo,
identifier=identifier,
data={"destination": destination},
)
ratelimits.maybe_rate_limit(client, headers)
return data.slug_perm, data.slug | [
"def",
"copy_package",
"(",
"owner",
",",
"repo",
",",
"identifier",
",",
"destination",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"packa... | Copy a package to another repository. | [
"Copy",
"a",
"package",
"to",
"another",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L64-L77 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | move_package | def move_package(owner, repo, identifier, destination):
"""Move a package to another repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_move_with_http_info(
owner=owner,
repo=repo,
identifier=identifier,
data={"destination": destination},
)
ratelimits.maybe_rate_limit(client, headers)
return data.slug_perm, data.slug | python | def move_package(owner, repo, identifier, destination):
"""Move a package to another repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_move_with_http_info(
owner=owner,
repo=repo,
identifier=identifier,
data={"destination": destination},
)
ratelimits.maybe_rate_limit(client, headers)
return data.slug_perm, data.slug | [
"def",
"move_package",
"(",
"owner",
",",
"repo",
",",
"identifier",
",",
"destination",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"packa... | Move a package to another repository. | [
"Move",
"a",
"package",
"to",
"another",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L80-L93 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | delete_package | def delete_package(owner, repo, identifier):
"""Delete a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
_, _, headers = client.packages_delete_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_limit(client, headers)
return True | python | def delete_package(owner, repo, identifier):
"""Delete a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
_, _, headers = client.packages_delete_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_limit(client, headers)
return True | [
"def",
"delete_package",
"(",
"owner",
",",
"repo",
",",
"identifier",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"_",
",",
"_",
",",
"headers",
"=",
"client",
".",
"packages_delete_with_http_info... | Delete a package in a repository. | [
"Delete",
"a",
"package",
"in",
"a",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L96-L106 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | resync_package | def resync_package(owner, repo, identifier):
"""Resync a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_resync_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_limit(client, headers)
return data.slug_perm, data.slug | python | def resync_package(owner, repo, identifier):
"""Resync a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_resync_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_limit(client, headers)
return data.slug_perm, data.slug | [
"def",
"resync_package",
"(",
"owner",
",",
"repo",
",",
"identifier",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"packages_resync_with_http_i... | Resync a package in a repository. | [
"Resync",
"a",
"package",
"in",
"a",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L109-L119 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | get_package_status | def get_package_status(owner, repo, identifier):
"""Get the status for a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_status_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_limit(client, headers)
# pylint: disable=no-member
# Pylint detects the returned value as a tuple
return (
data.is_sync_completed,
data.is_sync_failed,
data.sync_progress,
data.status_str,
data.stage_str,
data.status_reason,
) | python | def get_package_status(owner, repo, identifier):
"""Get the status for a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_status_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_limit(client, headers)
# pylint: disable=no-member
# Pylint detects the returned value as a tuple
return (
data.is_sync_completed,
data.is_sync_failed,
data.sync_progress,
data.status_str,
data.stage_str,
data.status_reason,
) | [
"def",
"get_package_status",
"(",
"owner",
",",
"repo",
",",
"identifier",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"packages_status_with_ht... | Get the status for a package in a repository. | [
"Get",
"the",
"status",
"for",
"a",
"package",
"in",
"a",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L122-L142 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | list_packages | def list_packages(owner, repo, **kwargs):
"""List packages for a repository."""
client = get_packages_api()
api_kwargs = {}
api_kwargs.update(utils.get_page_kwargs(**kwargs))
api_kwargs.update(utils.get_query_kwargs(**kwargs))
with catch_raise_api_exception():
data, _, headers = client.packages_list_with_http_info(
owner=owner, repo=repo, **api_kwargs
)
ratelimits.maybe_rate_limit(client, headers)
page_info = PageInfo.from_headers(headers)
return [x.to_dict() for x in data], page_info | python | def list_packages(owner, repo, **kwargs):
"""List packages for a repository."""
client = get_packages_api()
api_kwargs = {}
api_kwargs.update(utils.get_page_kwargs(**kwargs))
api_kwargs.update(utils.get_query_kwargs(**kwargs))
with catch_raise_api_exception():
data, _, headers = client.packages_list_with_http_info(
owner=owner, repo=repo, **api_kwargs
)
ratelimits.maybe_rate_limit(client, headers)
page_info = PageInfo.from_headers(headers)
return [x.to_dict() for x in data], page_info | [
"def",
"list_packages",
"(",
"owner",
",",
"repo",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"api_kwargs",
"=",
"{",
"}",
"api_kwargs",
".",
"update",
"(",
"utils",
".",
"get_page_kwargs",
"(",
"*",
"*",
"kwargs",
... | List packages for a repository. | [
"List",
"packages",
"for",
"a",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L145-L160 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | get_package_formats | def get_package_formats():
"""Get the list of available package formats and parameters."""
# pylint: disable=fixme
# HACK: This obviously isn't great, and it is subject to change as
# the API changes, but it'll do for now as a interim method of
# introspection to get the parameters we need.
def get_parameters(cls):
"""Build parameters for a package format."""
params = {}
# Create a dummy instance so we can check if a parameter is required.
# As with the rest of this function, this is obviously hacky. We'll
# figure out a way to pull this information in from the API later.
dummy_kwargs = {k: "dummy" for k in cls.swagger_types}
instance = cls(**dummy_kwargs)
for k, v in six.iteritems(cls.swagger_types):
attr = getattr(cls, k)
docs = attr.__doc__.strip().split("\n")
doc = (docs[1] if docs[1] else docs[0]).strip()
try:
setattr(instance, k, None)
required = False
except ValueError:
required = True
params[cls.attribute_map.get(k)] = {
"type": v,
"help": doc,
"required": required,
}
return params
return {
key.replace("PackagesUpload", "").lower(): get_parameters(cls)
for key, cls in inspect.getmembers(cloudsmith_api.models)
if key.startswith("PackagesUpload")
} | python | def get_package_formats():
"""Get the list of available package formats and parameters."""
# pylint: disable=fixme
# HACK: This obviously isn't great, and it is subject to change as
# the API changes, but it'll do for now as a interim method of
# introspection to get the parameters we need.
def get_parameters(cls):
"""Build parameters for a package format."""
params = {}
# Create a dummy instance so we can check if a parameter is required.
# As with the rest of this function, this is obviously hacky. We'll
# figure out a way to pull this information in from the API later.
dummy_kwargs = {k: "dummy" for k in cls.swagger_types}
instance = cls(**dummy_kwargs)
for k, v in six.iteritems(cls.swagger_types):
attr = getattr(cls, k)
docs = attr.__doc__.strip().split("\n")
doc = (docs[1] if docs[1] else docs[0]).strip()
try:
setattr(instance, k, None)
required = False
except ValueError:
required = True
params[cls.attribute_map.get(k)] = {
"type": v,
"help": doc,
"required": required,
}
return params
return {
key.replace("PackagesUpload", "").lower(): get_parameters(cls)
for key, cls in inspect.getmembers(cloudsmith_api.models)
if key.startswith("PackagesUpload")
} | [
"def",
"get_package_formats",
"(",
")",
":",
"# pylint: disable=fixme",
"# HACK: This obviously isn't great, and it is subject to change as",
"# the API changes, but it'll do for now as a interim method of",
"# introspection to get the parameters we need.",
"def",
"get_parameters",
"(",
"cls... | Get the list of available package formats and parameters. | [
"Get",
"the",
"list",
"of",
"available",
"package",
"formats",
"and",
"parameters",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L163-L202 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/packages.py | get_package_format_names | def get_package_format_names(predicate=None):
"""Get names for available package formats."""
return [
k
for k, v in six.iteritems(get_package_formats())
if not predicate or predicate(k, v)
] | python | def get_package_format_names(predicate=None):
"""Get names for available package formats."""
return [
k
for k, v in six.iteritems(get_package_formats())
if not predicate or predicate(k, v)
] | [
"def",
"get_package_format_names",
"(",
"predicate",
"=",
"None",
")",
":",
"return",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"get_package_formats",
"(",
")",
")",
"if",
"not",
"predicate",
"or",
"predicate",
"(",
"k",
",",
... | Get names for available package formats. | [
"Get",
"names",
"for",
"available",
"package",
"formats",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L205-L211 |
venmo/slouch | example.py | start | def start(opts, bot, event):
"""Usage: start [--name=<name>]
Start a timer.
Without _name_, start the default timer.
To run more than one timer at once, pass _name_ to start and stop.
"""
name = opts['--name']
now = datetime.datetime.now()
bot.timers[name] = now
return bot.start_fmt.format(now) | python | def start(opts, bot, event):
"""Usage: start [--name=<name>]
Start a timer.
Without _name_, start the default timer.
To run more than one timer at once, pass _name_ to start and stop.
"""
name = opts['--name']
now = datetime.datetime.now()
bot.timers[name] = now
return bot.start_fmt.format(now) | [
"def",
"start",
"(",
"opts",
",",
"bot",
",",
"event",
")",
":",
"name",
"=",
"opts",
"[",
"'--name'",
"]",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"bot",
".",
"timers",
"[",
"name",
"]",
"=",
"now",
"return",
"bot",
".",
... | Usage: start [--name=<name>]
Start a timer.
Without _name_, start the default timer.
To run more than one timer at once, pass _name_ to start and stop. | [
"Usage",
":",
"start",
"[",
"--",
"name",
"=",
"<name",
">",
"]"
] | train | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/example.py#L40-L54 |
venmo/slouch | example.py | stop | def stop(opts, bot, event):
"""Usage: stop [--name=<name>] [--notify=<slack_username>]
Stop a timer.
_name_ works the same as for `start`.
If given _slack_username_, reply with an at-mention to the given user.
"""
name = opts['--name']
slack_username = opts['--notify']
now = datetime.datetime.now()
delta = now - bot.timers.pop(name)
response = bot.stop_fmt.format(delta)
if slack_username:
mention = ''
# The slack api (provided by https://github.com/os/slacker) is available on all bots.
users = bot.slack.users.list().body['members']
for user in users:
if user['name'] == slack_username:
mention = "<@%s>" % user['id']
break
response = "%s: %s" % (mention, response)
return response | python | def stop(opts, bot, event):
"""Usage: stop [--name=<name>] [--notify=<slack_username>]
Stop a timer.
_name_ works the same as for `start`.
If given _slack_username_, reply with an at-mention to the given user.
"""
name = opts['--name']
slack_username = opts['--notify']
now = datetime.datetime.now()
delta = now - bot.timers.pop(name)
response = bot.stop_fmt.format(delta)
if slack_username:
mention = ''
# The slack api (provided by https://github.com/os/slacker) is available on all bots.
users = bot.slack.users.list().body['members']
for user in users:
if user['name'] == slack_username:
mention = "<@%s>" % user['id']
break
response = "%s: %s" % (mention, response)
return response | [
"def",
"stop",
"(",
"opts",
",",
"bot",
",",
"event",
")",
":",
"name",
"=",
"opts",
"[",
"'--name'",
"]",
"slack_username",
"=",
"opts",
"[",
"'--notify'",
"]",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"delta",
"=",
"now",
"-... | Usage: stop [--name=<name>] [--notify=<slack_username>]
Stop a timer.
_name_ works the same as for `start`.
If given _slack_username_, reply with an at-mention to the given user. | [
"Usage",
":",
"stop",
"[",
"--",
"name",
"=",
"<name",
">",
"]",
"[",
"--",
"notify",
"=",
"<slack_username",
">",
"]"
] | train | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/example.py#L58-L86 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/user.py | get_user_token | def get_user_token(login, password):
"""Retrieve user token from the API (via authentication)."""
client = get_user_api()
# Never use API key for the token endpoint
config = cloudsmith_api.Configuration()
set_api_key(config, None)
with catch_raise_api_exception():
data, _, headers = client.user_token_create_with_http_info(
data={"email": login, "password": password}
)
ratelimits.maybe_rate_limit(client, headers)
return data.token | python | def get_user_token(login, password):
"""Retrieve user token from the API (via authentication)."""
client = get_user_api()
# Never use API key for the token endpoint
config = cloudsmith_api.Configuration()
set_api_key(config, None)
with catch_raise_api_exception():
data, _, headers = client.user_token_create_with_http_info(
data={"email": login, "password": password}
)
ratelimits.maybe_rate_limit(client, headers)
return data.token | [
"def",
"get_user_token",
"(",
"login",
",",
"password",
")",
":",
"client",
"=",
"get_user_api",
"(",
")",
"# Never use API key for the token endpoint",
"config",
"=",
"cloudsmith_api",
".",
"Configuration",
"(",
")",
"set_api_key",
"(",
"config",
",",
"None",
")"... | Retrieve user token from the API (via authentication). | [
"Retrieve",
"user",
"token",
"from",
"the",
"API",
"(",
"via",
"authentication",
")",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/user.py#L17-L31 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/user.py | get_user_brief | def get_user_brief():
"""Retrieve brief for current user (if any)."""
client = get_user_api()
with catch_raise_api_exception():
data, _, headers = client.user_self_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return data.authenticated, data.slug, data.email, data.name | python | def get_user_brief():
"""Retrieve brief for current user (if any)."""
client = get_user_api()
with catch_raise_api_exception():
data, _, headers = client.user_self_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return data.authenticated, data.slug, data.email, data.name | [
"def",
"get_user_brief",
"(",
")",
":",
"client",
"=",
"get_user_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"user_self_with_http_info",
"(",
")",
"ratelimits",
".",
"maybe_rate_limi... | Retrieve brief for current user (if any). | [
"Retrieve",
"brief",
"for",
"current",
"user",
"(",
"if",
"any",
")",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/user.py#L34-L42 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/exceptions.py | catch_raise_api_exception | def catch_raise_api_exception():
"""Context manager that translates upstream API exceptions."""
try:
yield
except _ApiException as exc:
detail = None
fields = None
if exc.body:
try:
# pylint: disable=no-member
data = json.loads(exc.body)
detail = data.get("detail", None)
fields = data.get("fields", None)
except ValueError:
pass
detail = detail or exc.reason
raise ApiException(
exc.status, detail=detail, headers=exc.headers, body=exc.body, fields=fields
) | python | def catch_raise_api_exception():
"""Context manager that translates upstream API exceptions."""
try:
yield
except _ApiException as exc:
detail = None
fields = None
if exc.body:
try:
# pylint: disable=no-member
data = json.loads(exc.body)
detail = data.get("detail", None)
fields = data.get("fields", None)
except ValueError:
pass
detail = detail or exc.reason
raise ApiException(
exc.status, detail=detail, headers=exc.headers, body=exc.body, fields=fields
) | [
"def",
"catch_raise_api_exception",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_ApiException",
"as",
"exc",
":",
"detail",
"=",
"None",
"fields",
"=",
"None",
"if",
"exc",
".",
"body",
":",
"try",
":",
"# pylint: disable=no-member",
"data",
"=",
"json",
... | Context manager that translates upstream API exceptions. | [
"Context",
"manager",
"that",
"translates",
"upstream",
"API",
"exceptions",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/exceptions.py#L36-L57 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | ConfigReader.get_default_filepath | def get_default_filepath(cls):
"""Get the default filepath for the configuratin file."""
if not cls.config_files:
return None
if not cls.config_searchpath:
return None
filename = cls.config_files[0]
filepath = cls.config_searchpath[0]
return os.path.join(filepath, filename) | python | def get_default_filepath(cls):
"""Get the default filepath for the configuratin file."""
if not cls.config_files:
return None
if not cls.config_searchpath:
return None
filename = cls.config_files[0]
filepath = cls.config_searchpath[0]
return os.path.join(filepath, filename) | [
"def",
"get_default_filepath",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"config_files",
":",
"return",
"None",
"if",
"not",
"cls",
".",
"config_searchpath",
":",
"return",
"None",
"filename",
"=",
"cls",
".",
"config_files",
"[",
"0",
"]",
"filepath"... | Get the default filepath for the configuratin file. | [
"Get",
"the",
"default",
"filepath",
"for",
"the",
"configuratin",
"file",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L54-L62 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | ConfigReader.create_default_file | def create_default_file(cls, data=None, mode=None):
"""Create a config file and override data if specified."""
filepath = cls.get_default_filepath()
if not filepath:
return False
filename = os.path.basename(filepath)
config = read_file(get_data_path(), filename)
# Find and replace data in default config
data = data or {}
for k, v in six.iteritems(data):
v = v or ""
config = re.sub(
r"^(%(key)s) =[ ]*$" % {"key": k},
"%(key)s = %(value)s" % {"key": k, "value": v},
config,
flags=re.MULTILINE,
)
dirpath = os.path.dirname(filepath)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
with click.open_file(filepath, "w+") as f:
f.write(config)
if mode is not None:
os.chmod(filepath, mode)
return True | python | def create_default_file(cls, data=None, mode=None):
"""Create a config file and override data if specified."""
filepath = cls.get_default_filepath()
if not filepath:
return False
filename = os.path.basename(filepath)
config = read_file(get_data_path(), filename)
# Find and replace data in default config
data = data or {}
for k, v in six.iteritems(data):
v = v or ""
config = re.sub(
r"^(%(key)s) =[ ]*$" % {"key": k},
"%(key)s = %(value)s" % {"key": k, "value": v},
config,
flags=re.MULTILINE,
)
dirpath = os.path.dirname(filepath)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
with click.open_file(filepath, "w+") as f:
f.write(config)
if mode is not None:
os.chmod(filepath, mode)
return True | [
"def",
"create_default_file",
"(",
"cls",
",",
"data",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"filepath",
"=",
"cls",
".",
"get_default_filepath",
"(",
")",
"if",
"not",
"filepath",
":",
"return",
"False",
"filename",
"=",
"os",
".",
"path",
... | Create a config file and override data if specified. | [
"Create",
"a",
"config",
"file",
"and",
"override",
"data",
"if",
"specified",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L65-L94 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | ConfigReader.has_default_file | def has_default_file(cls):
"""Check if a configuration file exists."""
for filename in cls.config_files:
for searchpath in cls.config_searchpath:
path = os.path.join(searchpath, filename)
if os.path.exists(path):
return True
return False | python | def has_default_file(cls):
"""Check if a configuration file exists."""
for filename in cls.config_files:
for searchpath in cls.config_searchpath:
path = os.path.join(searchpath, filename)
if os.path.exists(path):
return True
return False | [
"def",
"has_default_file",
"(",
"cls",
")",
":",
"for",
"filename",
"in",
"cls",
".",
"config_files",
":",
"for",
"searchpath",
"in",
"cls",
".",
"config_searchpath",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"searchpath",
",",
"filename",
"... | Check if a configuration file exists. | [
"Check",
"if",
"a",
"configuration",
"file",
"exists",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L97-L105 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | ConfigReader.load_config | def load_config(cls, opts, path=None, profile=None):
"""Load a configuration file into an options object."""
if path and os.path.exists(path):
if os.path.isdir(path):
cls.config_searchpath.insert(0, path)
else:
cls.config_files.insert(0, path)
config = cls.read_config()
values = config.get("default", {})
cls._load_values_into_opts(opts, values)
if profile and profile != "default":
values = config.get("profile:%s" % profile, {})
cls._load_values_into_opts(opts, values)
return values | python | def load_config(cls, opts, path=None, profile=None):
"""Load a configuration file into an options object."""
if path and os.path.exists(path):
if os.path.isdir(path):
cls.config_searchpath.insert(0, path)
else:
cls.config_files.insert(0, path)
config = cls.read_config()
values = config.get("default", {})
cls._load_values_into_opts(opts, values)
if profile and profile != "default":
values = config.get("profile:%s" % profile, {})
cls._load_values_into_opts(opts, values)
return values | [
"def",
"load_config",
"(",
"cls",
",",
"opts",
",",
"path",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")... | Load a configuration file into an options object. | [
"Load",
"a",
"configuration",
"file",
"into",
"an",
"options",
"object",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L108-L124 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | Options.load_config_file | def load_config_file(self, path, profile=None):
"""Load the standard config file."""
config_cls = self.get_config_reader()
return config_cls.load_config(self, path, profile=profile) | python | def load_config_file(self, path, profile=None):
"""Load the standard config file."""
config_cls = self.get_config_reader()
return config_cls.load_config(self, path, profile=profile) | [
"def",
"load_config_file",
"(",
"self",
",",
"path",
",",
"profile",
"=",
"None",
")",
":",
"config_cls",
"=",
"self",
".",
"get_config_reader",
"(",
")",
"return",
"config_cls",
".",
"load_config",
"(",
"self",
",",
"path",
",",
"profile",
"=",
"profile",... | Load the standard config file. | [
"Load",
"the",
"standard",
"config",
"file",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L183-L186 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | Options.load_creds_file | def load_creds_file(self, path, profile=None):
"""Load the credentials config file."""
config_cls = self.get_creds_reader()
return config_cls.load_config(self, path, profile=profile) | python | def load_creds_file(self, path, profile=None):
"""Load the credentials config file."""
config_cls = self.get_creds_reader()
return config_cls.load_config(self, path, profile=profile) | [
"def",
"load_creds_file",
"(",
"self",
",",
"path",
",",
"profile",
"=",
"None",
")",
":",
"config_cls",
"=",
"self",
".",
"get_creds_reader",
"(",
")",
"return",
"config_cls",
".",
"load_config",
"(",
"self",
",",
"path",
",",
"profile",
"=",
"profile",
... | Load the credentials config file. | [
"Load",
"the",
"credentials",
"config",
"file",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L188-L191 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | Options.api_headers | def api_headers(self, value):
"""Set value for API headers."""
value = validators.validate_api_headers("api_headers", value)
self._set_option("api_headers", value) | python | def api_headers(self, value):
"""Set value for API headers."""
value = validators.validate_api_headers("api_headers", value)
self._set_option("api_headers", value) | [
"def",
"api_headers",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"validators",
".",
"validate_api_headers",
"(",
"\"api_headers\"",
",",
"value",
")",
"self",
".",
"_set_option",
"(",
"\"api_headers\"",
",",
"value",
")"
] | Set value for API headers. | [
"Set",
"value",
"for",
"API",
"headers",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L209-L212 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | Options.error_retry_codes | def error_retry_codes(self, value):
"""Set value for error_retry_codes."""
if isinstance(value, six.string_types):
value = [int(x) for x in value.split(",")]
self._set_option("error_retry_codes", value) | python | def error_retry_codes(self, value):
"""Set value for error_retry_codes."""
if isinstance(value, six.string_types):
value = [int(x) for x in value.split(",")]
self._set_option("error_retry_codes", value) | [
"def",
"error_retry_codes",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"value",
".",
"split",
"(",
"\",\"",
")",
"]",
... | Set value for error_retry_codes. | [
"Set",
"value",
"for",
"error_retry_codes",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L340-L344 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/config.py | Options._set_option | def _set_option(self, name, value, allow_clear=False):
"""Set value for an option."""
if not allow_clear:
# Prevent clears if value was set
try:
current_value = self._get_option(name)
if value is None and current_value is not None:
return
except AttributeError:
pass
self.opts[name] = value | python | def _set_option(self, name, value, allow_clear=False):
"""Set value for an option."""
if not allow_clear:
# Prevent clears if value was set
try:
current_value = self._get_option(name)
if value is None and current_value is not None:
return
except AttributeError:
pass
self.opts[name] = value | [
"def",
"_set_option",
"(",
"self",
",",
"name",
",",
"value",
",",
"allow_clear",
"=",
"False",
")",
":",
"if",
"not",
"allow_clear",
":",
"# Prevent clears if value was set",
"try",
":",
"current_value",
"=",
"self",
".",
"_get_option",
"(",
"name",
")",
"i... | Set value for an option. | [
"Set",
"value",
"for",
"an",
"option",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L350-L361 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/rates.py | get_rate_limits | def get_rate_limits():
"""Retrieve status (and optionally) version from the API."""
client = get_rates_api()
with catch_raise_api_exception():
data, _, headers = client.rates_limits_list_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return {
k: RateLimitsInfo.from_dict(v)
for k, v in six.iteritems(data.to_dict().get("resources", {}))
} | python | def get_rate_limits():
"""Retrieve status (and optionally) version from the API."""
client = get_rates_api()
with catch_raise_api_exception():
data, _, headers = client.rates_limits_list_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return {
k: RateLimitsInfo.from_dict(v)
for k, v in six.iteritems(data.to_dict().get("resources", {}))
} | [
"def",
"get_rate_limits",
"(",
")",
":",
"client",
"=",
"get_rates_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"rates_limits_list_with_http_info",
"(",
")",
"ratelimits",
".",
"maybe... | Retrieve status (and optionally) version from the API. | [
"Retrieve",
"status",
"(",
"and",
"optionally",
")",
"version",
"from",
"the",
"API",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/rates.py#L19-L31 |
marrow/schema | marrow/schema/transform/base.py | BaseTransform.loads | def loads(self, value, context=None):
"""Attempt to load a string-based value into the native representation.
Empty strings are treated as ``None`` values.
"""
if value == '' or (hasattr(value, 'strip') and value.strip() == ''):
return None
return self.native(value) | python | def loads(self, value, context=None):
"""Attempt to load a string-based value into the native representation.
Empty strings are treated as ``None`` values.
"""
if value == '' or (hasattr(value, 'strip') and value.strip() == ''):
return None
return self.native(value) | [
"def",
"loads",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"value",
"==",
"''",
"or",
"(",
"hasattr",
"(",
"value",
",",
"'strip'",
")",
"and",
"value",
".",
"strip",
"(",
")",
"==",
"''",
")",
":",
"return",
"None",
... | Attempt to load a string-based value into the native representation.
Empty strings are treated as ``None`` values. | [
"Attempt",
"to",
"load",
"a",
"string",
"-",
"based",
"value",
"into",
"the",
"native",
"representation",
".",
"Empty",
"strings",
"are",
"treated",
"as",
"None",
"values",
"."
] | train | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/base.py#L23-L32 |
marrow/schema | marrow/schema/transform/base.py | BaseTransform.dump | def dump(self, fh, value, context=None):
"""Attempt to transform and write a string-based foreign value to the given file-like object.
Returns the length written.
"""
value = self.dumps(value)
fh.write(value)
return len(value) | python | def dump(self, fh, value, context=None):
"""Attempt to transform and write a string-based foreign value to the given file-like object.
Returns the length written.
"""
value = self.dumps(value)
fh.write(value)
return len(value) | [
"def",
"dump",
"(",
"self",
",",
"fh",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"dumps",
"(",
"value",
")",
"fh",
".",
"write",
"(",
"value",
")",
"return",
"len",
"(",
"value",
")"
] | Attempt to transform and write a string-based foreign value to the given file-like object.
Returns the length written. | [
"Attempt",
"to",
"transform",
"and",
"write",
"a",
"string",
"-",
"based",
"foreign",
"value",
"to",
"the",
"given",
"file",
"-",
"like",
"object",
".",
"Returns",
"the",
"length",
"written",
"."
] | train | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/base.py#L50-L58 |
marrow/schema | marrow/schema/transform/base.py | Transform.native | def native(self, value, context=None):
"""Convert a value from a foriegn type (i.e. web-safe) to Python-native."""
if self.strip and hasattr(value, 'strip'):
value = value.strip()
if self.none and value == '':
return None
if self.encoding and isinstance(value, bytes):
return value.decode(self.encoding)
return value | python | def native(self, value, context=None):
"""Convert a value from a foriegn type (i.e. web-safe) to Python-native."""
if self.strip and hasattr(value, 'strip'):
value = value.strip()
if self.none and value == '':
return None
if self.encoding and isinstance(value, bytes):
return value.decode(self.encoding)
return value | [
"def",
"native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"strip",
"and",
"hasattr",
"(",
"value",
",",
"'strip'",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"self",
".",
"none",
"an... | Convert a value from a foriegn type (i.e. web-safe) to Python-native. | [
"Convert",
"a",
"value",
"from",
"a",
"foriegn",
"type",
"(",
"i",
".",
"e",
".",
"web",
"-",
"safe",
")",
"to",
"Python",
"-",
"native",
"."
] | train | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/base.py#L77-L89 |
marrow/schema | marrow/schema/transform/base.py | IngressTransform.native | def native(self, value, context=None):
"""Convert a value from a foriegn type (i.e. web-safe) to Python-native."""
value = super().native(value, context)
if value is None: return
try:
return self.ingress(value)
except Exception as e:
raise Concern("Unable to transform incoming value: {0}", str(e)) | python | def native(self, value, context=None):
"""Convert a value from a foriegn type (i.e. web-safe) to Python-native."""
value = super().native(value, context)
if value is None: return
try:
return self.ingress(value)
except Exception as e:
raise Concern("Unable to transform incoming value: {0}", str(e)) | [
"def",
"native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"value",
"=",
"super",
"(",
")",
".",
"native",
"(",
"value",
",",
"context",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"return",
"self",
".",
"... | Convert a value from a foriegn type (i.e. web-safe) to Python-native. | [
"Convert",
"a",
"value",
"from",
"a",
"foriegn",
"type",
"(",
"i",
".",
"e",
".",
"web",
"-",
"safe",
")",
"to",
"Python",
"-",
"native",
"."
] | train | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/base.py#L109-L119 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/check.py | rates | def rates(ctx, opts):
"""Check current API rate limits."""
click.echo("Retrieving rate limits ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
resources_limits = get_rate_limits()
click.secho("OK", fg="green")
headers = ["Resource", "Throttled", "Remaining", "Interval (Seconds)", "Reset"]
rows = []
for resource, limits in six.iteritems(resources_limits):
rows.append(
[
click.style(resource, fg="cyan"),
click.style(
"Yes" if limits.throttled else "No",
fg="red" if limits.throttled else "green",
),
"%(remaining)s/%(limit)s"
% {
"remaining": click.style(
six.text_type(limits.remaining), fg="yellow"
),
"limit": click.style(six.text_type(limits.limit), fg="yellow"),
},
click.style(six.text_type(limits.interval), fg="blue"),
click.style(six.text_type(limits.reset), fg="magenta"),
]
)
if resources_limits:
click.echo()
utils.pretty_print_table(headers, rows)
click.echo()
num_results = len(resources_limits)
list_suffix = "resource%s" % ("s" if num_results != 1 else "")
utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix) | python | def rates(ctx, opts):
"""Check current API rate limits."""
click.echo("Retrieving rate limits ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
resources_limits = get_rate_limits()
click.secho("OK", fg="green")
headers = ["Resource", "Throttled", "Remaining", "Interval (Seconds)", "Reset"]
rows = []
for resource, limits in six.iteritems(resources_limits):
rows.append(
[
click.style(resource, fg="cyan"),
click.style(
"Yes" if limits.throttled else "No",
fg="red" if limits.throttled else "green",
),
"%(remaining)s/%(limit)s"
% {
"remaining": click.style(
six.text_type(limits.remaining), fg="yellow"
),
"limit": click.style(six.text_type(limits.limit), fg="yellow"),
},
click.style(six.text_type(limits.interval), fg="blue"),
click.style(six.text_type(limits.reset), fg="magenta"),
]
)
if resources_limits:
click.echo()
utils.pretty_print_table(headers, rows)
click.echo()
num_results = len(resources_limits)
list_suffix = "resource%s" % ("s" if num_results != 1 else "")
utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix) | [
"def",
"rates",
"(",
"ctx",
",",
"opts",
")",
":",
"click",
".",
"echo",
"(",
"\"Retrieving rate limits ... \"",
",",
"nl",
"=",
"False",
")",
"context_msg",
"=",
"\"Failed to retrieve status!\"",
"with",
"handle_api_exceptions",
"(",
"ctx",
",",
"opts",
"=",
... | Check current API rate limits. | [
"Check",
"current",
"API",
"rate",
"limits",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/check.py#L34-L76 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/check.py | service | def service(ctx, opts):
"""Check the status of the Cloudsmith service."""
click.echo("Retrieving service status ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
status, version = get_status(with_version=True)
click.secho("OK", fg="green")
config = cloudsmith_api.Configuration()
click.echo()
click.echo(
"The service endpoint is: %(endpoint)s"
% {"endpoint": click.style(config.host, bold=True)}
)
click.echo(
"The service status is: %(status)s"
% {"status": click.style(status, bold=True)}
)
click.echo(
"The service version is: %(version)s "
% {"version": click.style(version, bold=True)},
nl=False,
)
api_version = get_api_version_info()
if semver.compare(version, api_version) > 0:
click.secho("(maybe out-of-date)", fg="yellow")
click.echo()
click.secho(
"The API library used by this CLI tool is built against "
"service version: %(version)s"
% {"version": click.style(api_version, bold=True)},
fg="yellow",
)
else:
click.secho("(up-to-date)", fg="green")
click.echo()
click.secho(
"The API library used by this CLI tool seems to be up-to-date.", fg="green"
) | python | def service(ctx, opts):
"""Check the status of the Cloudsmith service."""
click.echo("Retrieving service status ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
status, version = get_status(with_version=True)
click.secho("OK", fg="green")
config = cloudsmith_api.Configuration()
click.echo()
click.echo(
"The service endpoint is: %(endpoint)s"
% {"endpoint": click.style(config.host, bold=True)}
)
click.echo(
"The service status is: %(status)s"
% {"status": click.style(status, bold=True)}
)
click.echo(
"The service version is: %(version)s "
% {"version": click.style(version, bold=True)},
nl=False,
)
api_version = get_api_version_info()
if semver.compare(version, api_version) > 0:
click.secho("(maybe out-of-date)", fg="yellow")
click.echo()
click.secho(
"The API library used by this CLI tool is built against "
"service version: %(version)s"
% {"version": click.style(api_version, bold=True)},
fg="yellow",
)
else:
click.secho("(up-to-date)", fg="green")
click.echo()
click.secho(
"The API library used by this CLI tool seems to be up-to-date.", fg="green"
) | [
"def",
"service",
"(",
"ctx",
",",
"opts",
")",
":",
"click",
".",
"echo",
"(",
"\"Retrieving service status ... \"",
",",
"nl",
"=",
"False",
")",
"context_msg",
"=",
"\"Failed to retrieve status!\"",
"with",
"handle_api_exceptions",
"(",
"ctx",
",",
"opts",
"=... | Check the status of the Cloudsmith service. | [
"Check",
"the",
"status",
"of",
"the",
"Cloudsmith",
"service",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/check.py#L84-L130 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/distros.py | list_distros | def list_distros(package_format=None):
"""List available distributions."""
client = get_distros_api()
# pylint: disable=fixme
# TODO(ls): Add package format param on the server-side to filter distros
# instead of doing it here.
with catch_raise_api_exception():
distros, _, headers = client.distros_list_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return [
distro.to_dict()
for distro in distros
if not package_format or distro.format == package_format
] | python | def list_distros(package_format=None):
"""List available distributions."""
client = get_distros_api()
# pylint: disable=fixme
# TODO(ls): Add package format param on the server-side to filter distros
# instead of doing it here.
with catch_raise_api_exception():
distros, _, headers = client.distros_list_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return [
distro.to_dict()
for distro in distros
if not package_format or distro.format == package_format
] | [
"def",
"list_distros",
"(",
"package_format",
"=",
"None",
")",
":",
"client",
"=",
"get_distros_api",
"(",
")",
"# pylint: disable=fixme",
"# TODO(ls): Add package format param on the server-side to filter distros",
"# instead of doing it here.",
"with",
"catch_raise_api_exception... | List available distributions. | [
"List",
"available",
"distributions",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/distros.py#L17-L33 |
kalefranz/auxlib | auxlib/_vendor/boltons/timeutils.py | total_seconds | def total_seconds(td):
"""For those with older versions of Python, a pure-Python
implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`.
Args:
td (datetime.timedelta): The timedelta to convert to seconds.
Returns:
float: total number of seconds
>>> td = timedelta(days=4, seconds=33)
>>> total_seconds(td)
345633.0
"""
a_milli = 1000000.0
td_ds = td.seconds + (td.days * 86400) # 24 * 60 * 60
td_micro = td.microseconds + (td_ds * a_milli)
return td_micro / a_milli | python | def total_seconds(td):
"""For those with older versions of Python, a pure-Python
implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`.
Args:
td (datetime.timedelta): The timedelta to convert to seconds.
Returns:
float: total number of seconds
>>> td = timedelta(days=4, seconds=33)
>>> total_seconds(td)
345633.0
"""
a_milli = 1000000.0
td_ds = td.seconds + (td.days * 86400) # 24 * 60 * 60
td_micro = td.microseconds + (td_ds * a_milli)
return td_micro / a_milli | [
"def",
"total_seconds",
"(",
"td",
")",
":",
"a_milli",
"=",
"1000000.0",
"td_ds",
"=",
"td",
".",
"seconds",
"+",
"(",
"td",
".",
"days",
"*",
"86400",
")",
"# 24 * 60 * 60",
"td_micro",
"=",
"td",
".",
"microseconds",
"+",
"(",
"td_ds",
"*",
"a_milli... | For those with older versions of Python, a pure-Python
implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`.
Args:
td (datetime.timedelta): The timedelta to convert to seconds.
Returns:
float: total number of seconds
>>> td = timedelta(days=4, seconds=33)
>>> total_seconds(td)
345633.0 | [
"For",
"those",
"with",
"older",
"versions",
"of",
"Python",
"a",
"pure",
"-",
"Python",
"implementation",
"of",
"Python",
"2",
".",
"7",
"s",
":",
"meth",
":",
"~datetime",
".",
"timedelta",
".",
"total_seconds",
"."
] | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L30-L46 |
kalefranz/auxlib | auxlib/_vendor/boltons/timeutils.py | dt_to_timestamp | def dt_to_timestamp(dt):
"""Converts from a :class:`~datetime.datetime` object to an integer
timestamp, suitable interoperation with :func:`time.time` and
other `Epoch-based timestamps`.
.. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time
>>> abs(round(time.time() - dt_to_timestamp(datetime.utcnow()), 2))
0.0
``dt_to_timestamp`` supports both timezone-aware and naïve
:class:`~datetime.datetime` objects. Note that it assumes naïve
datetime objects are implied UTC, such as those generated with
:meth:`datetime.datetime.utcnow`. If your datetime objects are
local time, such as those generated with
:meth:`datetime.datetime.now`, first convert it using the
:meth:`datetime.datetime.replace` method with ``tzinfo=``
:class:`LocalTZ` object in this module, then pass the result of
that to ``dt_to_timestamp``.
"""
if dt.tzinfo:
td = dt - EPOCH_AWARE
else:
td = dt - EPOCH_NAIVE
return total_seconds(td) | python | def dt_to_timestamp(dt):
"""Converts from a :class:`~datetime.datetime` object to an integer
timestamp, suitable interoperation with :func:`time.time` and
other `Epoch-based timestamps`.
.. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time
>>> abs(round(time.time() - dt_to_timestamp(datetime.utcnow()), 2))
0.0
``dt_to_timestamp`` supports both timezone-aware and naïve
:class:`~datetime.datetime` objects. Note that it assumes naïve
datetime objects are implied UTC, such as those generated with
:meth:`datetime.datetime.utcnow`. If your datetime objects are
local time, such as those generated with
:meth:`datetime.datetime.now`, first convert it using the
:meth:`datetime.datetime.replace` method with ``tzinfo=``
:class:`LocalTZ` object in this module, then pass the result of
that to ``dt_to_timestamp``.
"""
if dt.tzinfo:
td = dt - EPOCH_AWARE
else:
td = dt - EPOCH_NAIVE
return total_seconds(td) | [
"def",
"dt_to_timestamp",
"(",
"dt",
")",
":",
"if",
"dt",
".",
"tzinfo",
":",
"td",
"=",
"dt",
"-",
"EPOCH_AWARE",
"else",
":",
"td",
"=",
"dt",
"-",
"EPOCH_NAIVE",
"return",
"total_seconds",
"(",
"td",
")"
] | Converts from a :class:`~datetime.datetime` object to an integer
timestamp, suitable interoperation with :func:`time.time` and
other `Epoch-based timestamps`.
.. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time
>>> abs(round(time.time() - dt_to_timestamp(datetime.utcnow()), 2))
0.0
``dt_to_timestamp`` supports both timezone-aware and naïve
:class:`~datetime.datetime` objects. Note that it assumes naïve
datetime objects are implied UTC, such as those generated with
:meth:`datetime.datetime.utcnow`. If your datetime objects are
local time, such as those generated with
:meth:`datetime.datetime.now`, first convert it using the
:meth:`datetime.datetime.replace` method with ``tzinfo=``
:class:`LocalTZ` object in this module, then pass the result of
that to ``dt_to_timestamp``. | [
"Converts",
"from",
"a",
":",
"class",
":",
"~datetime",
".",
"datetime",
"object",
"to",
"an",
"integer",
"timestamp",
"suitable",
"interoperation",
"with",
":",
"func",
":",
"time",
".",
"time",
"and",
"other",
"Epoch",
"-",
"based",
"timestamps",
"."
] | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L49-L73 |
kalefranz/auxlib | auxlib/_vendor/boltons/timeutils.py | isoparse | def isoparse(iso_str):
"""Parses the limited subset of `ISO8601-formatted time`_ strings as
returned by :meth:`datetime.datetime.isoformat`.
>>> epoch_dt = datetime.utcfromtimestamp(0)
>>> iso_str = epoch_dt.isoformat()
>>> print(iso_str)
1970-01-01T00:00:00
>>> isoparse(iso_str)
datetime.datetime(1970, 1, 1, 0, 0)
>>> utcnow = datetime.utcnow()
>>> utcnow == isoparse(utcnow.isoformat())
True
For further datetime parsing, see the `iso8601`_ package for strict
ISO parsing and `dateutil`_ package for loose parsing and more.
.. _ISO8601-formatted time: https://en.wikipedia.org/wiki/ISO_8601
.. _iso8601: https://pypi.python.org/pypi/iso8601
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
"""
dt_args = [int(p) for p in _NONDIGIT_RE.split(iso_str)]
return datetime(*dt_args) | python | def isoparse(iso_str):
"""Parses the limited subset of `ISO8601-formatted time`_ strings as
returned by :meth:`datetime.datetime.isoformat`.
>>> epoch_dt = datetime.utcfromtimestamp(0)
>>> iso_str = epoch_dt.isoformat()
>>> print(iso_str)
1970-01-01T00:00:00
>>> isoparse(iso_str)
datetime.datetime(1970, 1, 1, 0, 0)
>>> utcnow = datetime.utcnow()
>>> utcnow == isoparse(utcnow.isoformat())
True
For further datetime parsing, see the `iso8601`_ package for strict
ISO parsing and `dateutil`_ package for loose parsing and more.
.. _ISO8601-formatted time: https://en.wikipedia.org/wiki/ISO_8601
.. _iso8601: https://pypi.python.org/pypi/iso8601
.. _dateutil: https://pypi.python.org/pypi/python-dateutil
"""
dt_args = [int(p) for p in _NONDIGIT_RE.split(iso_str)]
return datetime(*dt_args) | [
"def",
"isoparse",
"(",
"iso_str",
")",
":",
"dt_args",
"=",
"[",
"int",
"(",
"p",
")",
"for",
"p",
"in",
"_NONDIGIT_RE",
".",
"split",
"(",
"iso_str",
")",
"]",
"return",
"datetime",
"(",
"*",
"dt_args",
")"
] | Parses the limited subset of `ISO8601-formatted time`_ strings as
returned by :meth:`datetime.datetime.isoformat`.
>>> epoch_dt = datetime.utcfromtimestamp(0)
>>> iso_str = epoch_dt.isoformat()
>>> print(iso_str)
1970-01-01T00:00:00
>>> isoparse(iso_str)
datetime.datetime(1970, 1, 1, 0, 0)
>>> utcnow = datetime.utcnow()
>>> utcnow == isoparse(utcnow.isoformat())
True
For further datetime parsing, see the `iso8601`_ package for strict
ISO parsing and `dateutil`_ package for loose parsing and more.
.. _ISO8601-formatted time: https://en.wikipedia.org/wiki/ISO_8601
.. _iso8601: https://pypi.python.org/pypi/iso8601
.. _dateutil: https://pypi.python.org/pypi/python-dateutil | [
"Parses",
"the",
"limited",
"subset",
"of",
"ISO8601",
"-",
"formatted",
"time",
"_",
"strings",
"as",
"returned",
"by",
":",
"meth",
":",
"datetime",
".",
"datetime",
".",
"isoformat",
"."
] | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L79-L103 |
kalefranz/auxlib | auxlib/_vendor/boltons/timeutils.py | parse_timedelta | def parse_timedelta(text):
"""Robustly parses a short text description of a time period into a
:class:`datetime.timedelta`. Supports weeks, days, hours, minutes,
and seconds, with or without decimal points:
Args:
text (str): Text to parse.
Returns:
datetime.timedelta
Raises:
ValueError: on parse failure.
>>> parse_td('1d 2h 3.5m 0s')
datetime.timedelta(1, 7410)
Also supports full words and whitespace.
>>> parse_td('2 weeks 1 day')
datetime.timedelta(15)
Negative times are supported, too:
>>> parse_td('-1.5 weeks 3m 20s')
datetime.timedelta(-11, 43400)
"""
td_kwargs = {}
for match in _PARSE_TD_RE.finditer(text):
value, unit = match.group('value'), match.group('unit')
try:
unit_key = _PARSE_TD_KW_MAP[unit]
except KeyError:
raise ValueError('invalid time unit %r, expected one of %r'
% (unit, _PARSE_TD_KW_MAP.keys()))
try:
value = float(value)
except ValueError:
raise ValueError('invalid time value for unit %r: %r'
% (unit, value))
td_kwargs[unit_key] = value
return timedelta(**td_kwargs) | python | def parse_timedelta(text):
"""Robustly parses a short text description of a time period into a
:class:`datetime.timedelta`. Supports weeks, days, hours, minutes,
and seconds, with or without decimal points:
Args:
text (str): Text to parse.
Returns:
datetime.timedelta
Raises:
ValueError: on parse failure.
>>> parse_td('1d 2h 3.5m 0s')
datetime.timedelta(1, 7410)
Also supports full words and whitespace.
>>> parse_td('2 weeks 1 day')
datetime.timedelta(15)
Negative times are supported, too:
>>> parse_td('-1.5 weeks 3m 20s')
datetime.timedelta(-11, 43400)
"""
td_kwargs = {}
for match in _PARSE_TD_RE.finditer(text):
value, unit = match.group('value'), match.group('unit')
try:
unit_key = _PARSE_TD_KW_MAP[unit]
except KeyError:
raise ValueError('invalid time unit %r, expected one of %r'
% (unit, _PARSE_TD_KW_MAP.keys()))
try:
value = float(value)
except ValueError:
raise ValueError('invalid time value for unit %r: %r'
% (unit, value))
td_kwargs[unit_key] = value
return timedelta(**td_kwargs) | [
"def",
"parse_timedelta",
"(",
"text",
")",
":",
"td_kwargs",
"=",
"{",
"}",
"for",
"match",
"in",
"_PARSE_TD_RE",
".",
"finditer",
"(",
"text",
")",
":",
"value",
",",
"unit",
"=",
"match",
".",
"group",
"(",
"'value'",
")",
",",
"match",
".",
"grou... | Robustly parses a short text description of a time period into a
:class:`datetime.timedelta`. Supports weeks, days, hours, minutes,
and seconds, with or without decimal points:
Args:
text (str): Text to parse.
Returns:
datetime.timedelta
Raises:
ValueError: on parse failure.
>>> parse_td('1d 2h 3.5m 0s')
datetime.timedelta(1, 7410)
Also supports full words and whitespace.
>>> parse_td('2 weeks 1 day')
datetime.timedelta(15)
Negative times are supported, too:
>>> parse_td('-1.5 weeks 3m 20s')
datetime.timedelta(-11, 43400) | [
"Robustly",
"parses",
"a",
"short",
"text",
"description",
"of",
"a",
"time",
"period",
"into",
"a",
":",
"class",
":",
"datetime",
".",
"timedelta",
".",
"Supports",
"weeks",
"days",
"hours",
"minutes",
"and",
"seconds",
"with",
"or",
"without",
"decimal",
... | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L122-L161 |
kalefranz/auxlib | auxlib/_vendor/boltons/timeutils.py | decimal_relative_time | def decimal_relative_time(d, other=None, ndigits=0, cardinalize=True):
"""Get a tuple representing the relative time difference between two
:class:`~datetime.datetime` objects or one
:class:`~datetime.datetime` and now.
Args:
d (datetime): The first datetime object.
other (datetime): An optional second datetime object. If
unset, defaults to the current time as determined
:meth:`datetime.utcnow`.
ndigits (int): The number of decimal digits to round to,
defaults to ``0``.
cardinalize (bool): Whether to pluralize the time unit if
appropriate, defaults to ``True``.
Returns:
(float, str): A tuple of the :class:`float` difference and
respective unit of time, pluralized if appropriate and
*cardinalize* is set to ``True``.
Unlike :func:`relative_time`, this method's return is amenable to
localization into other languages and custom phrasing and
formatting.
>>> now = datetime.utcnow()
>>> decimal_relative_time(now - timedelta(days=1, seconds=3600), now)
(1.0, 'day')
>>> decimal_relative_time(now - timedelta(seconds=0.002), now, ndigits=5)
(0.002, 'seconds')
>>> decimal_relative_time(now, now - timedelta(days=900), ndigits=1)
(-2.5, 'years')
"""
if other is None:
other = datetime.utcnow()
diff = other - d
diff_seconds = total_seconds(diff)
abs_diff = abs(diff)
b_idx = bisect.bisect(_BOUND_DELTAS, abs_diff) - 1
bbound, bunit, bname = _BOUNDS[b_idx]
f_diff = diff_seconds / total_seconds(bunit)
rounded_diff = round(f_diff, ndigits)
if cardinalize:
return rounded_diff, _cardinalize_time_unit(bname, abs(rounded_diff))
return rounded_diff, bname | python | def decimal_relative_time(d, other=None, ndigits=0, cardinalize=True):
"""Get a tuple representing the relative time difference between two
:class:`~datetime.datetime` objects or one
:class:`~datetime.datetime` and now.
Args:
d (datetime): The first datetime object.
other (datetime): An optional second datetime object. If
unset, defaults to the current time as determined
:meth:`datetime.utcnow`.
ndigits (int): The number of decimal digits to round to,
defaults to ``0``.
cardinalize (bool): Whether to pluralize the time unit if
appropriate, defaults to ``True``.
Returns:
(float, str): A tuple of the :class:`float` difference and
respective unit of time, pluralized if appropriate and
*cardinalize* is set to ``True``.
Unlike :func:`relative_time`, this method's return is amenable to
localization into other languages and custom phrasing and
formatting.
>>> now = datetime.utcnow()
>>> decimal_relative_time(now - timedelta(days=1, seconds=3600), now)
(1.0, 'day')
>>> decimal_relative_time(now - timedelta(seconds=0.002), now, ndigits=5)
(0.002, 'seconds')
>>> decimal_relative_time(now, now - timedelta(days=900), ndigits=1)
(-2.5, 'years')
"""
if other is None:
other = datetime.utcnow()
diff = other - d
diff_seconds = total_seconds(diff)
abs_diff = abs(diff)
b_idx = bisect.bisect(_BOUND_DELTAS, abs_diff) - 1
bbound, bunit, bname = _BOUNDS[b_idx]
f_diff = diff_seconds / total_seconds(bunit)
rounded_diff = round(f_diff, ndigits)
if cardinalize:
return rounded_diff, _cardinalize_time_unit(bname, abs(rounded_diff))
return rounded_diff, bname | [
"def",
"decimal_relative_time",
"(",
"d",
",",
"other",
"=",
"None",
",",
"ndigits",
"=",
"0",
",",
"cardinalize",
"=",
"True",
")",
":",
"if",
"other",
"is",
"None",
":",
"other",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"diff",
"=",
"other",
"-",
... | Get a tuple representing the relative time difference between two
:class:`~datetime.datetime` objects or one
:class:`~datetime.datetime` and now.
Args:
d (datetime): The first datetime object.
other (datetime): An optional second datetime object. If
unset, defaults to the current time as determined
:meth:`datetime.utcnow`.
ndigits (int): The number of decimal digits to round to,
defaults to ``0``.
cardinalize (bool): Whether to pluralize the time unit if
appropriate, defaults to ``True``.
Returns:
(float, str): A tuple of the :class:`float` difference and
respective unit of time, pluralized if appropriate and
*cardinalize* is set to ``True``.
Unlike :func:`relative_time`, this method's return is amenable to
localization into other languages and custom phrasing and
formatting.
>>> now = datetime.utcnow()
>>> decimal_relative_time(now - timedelta(days=1, seconds=3600), now)
(1.0, 'day')
>>> decimal_relative_time(now - timedelta(seconds=0.002), now, ndigits=5)
(0.002, 'seconds')
>>> decimal_relative_time(now, now - timedelta(days=900), ndigits=1)
(-2.5, 'years') | [
"Get",
"a",
"tuple",
"representing",
"the",
"relative",
"time",
"difference",
"between",
"two",
":",
"class",
":",
"~datetime",
".",
"datetime",
"objects",
"or",
"one",
":",
"class",
":",
"~datetime",
".",
"datetime",
"and",
"now",
"."
] | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L175-L218 |
kalefranz/auxlib | auxlib/_vendor/boltons/timeutils.py | relative_time | def relative_time(d, other=None, ndigits=0):
"""Get a string representation of the difference between two
:class:`~datetime.datetime` objects or one
:class:`~datetime.datetime` and the current time. Handles past and
future times.
Args:
d (datetime): The first datetime object.
other (datetime): An optional second datetime object. If
unset, defaults to the current time as determined
:meth:`datetime.utcnow`.
ndigits (int): The number of decimal digits to round to,
defaults to ``0``.
Returns:
A short English-language string.
>>> now = datetime.utcnow()
>>> relative_time(now, ndigits=1)
'0 seconds ago'
>>> relative_time(now - timedelta(days=1, seconds=36000), ndigits=1)
'1.4 days ago'
>>> relative_time(now + timedelta(days=7), now, ndigits=1)
'1 week from now'
"""
drt, unit = decimal_relative_time(d, other, ndigits, cardinalize=True)
phrase = 'ago'
if drt < 0:
phrase = 'from now'
return '%g %s %s' % (abs(drt), unit, phrase) | python | def relative_time(d, other=None, ndigits=0):
"""Get a string representation of the difference between two
:class:`~datetime.datetime` objects or one
:class:`~datetime.datetime` and the current time. Handles past and
future times.
Args:
d (datetime): The first datetime object.
other (datetime): An optional second datetime object. If
unset, defaults to the current time as determined
:meth:`datetime.utcnow`.
ndigits (int): The number of decimal digits to round to,
defaults to ``0``.
Returns:
A short English-language string.
>>> now = datetime.utcnow()
>>> relative_time(now, ndigits=1)
'0 seconds ago'
>>> relative_time(now - timedelta(days=1, seconds=36000), ndigits=1)
'1.4 days ago'
>>> relative_time(now + timedelta(days=7), now, ndigits=1)
'1 week from now'
"""
drt, unit = decimal_relative_time(d, other, ndigits, cardinalize=True)
phrase = 'ago'
if drt < 0:
phrase = 'from now'
return '%g %s %s' % (abs(drt), unit, phrase) | [
"def",
"relative_time",
"(",
"d",
",",
"other",
"=",
"None",
",",
"ndigits",
"=",
"0",
")",
":",
"drt",
",",
"unit",
"=",
"decimal_relative_time",
"(",
"d",
",",
"other",
",",
"ndigits",
",",
"cardinalize",
"=",
"True",
")",
"phrase",
"=",
"'ago'",
"... | Get a string representation of the difference between two
:class:`~datetime.datetime` objects or one
:class:`~datetime.datetime` and the current time. Handles past and
future times.
Args:
d (datetime): The first datetime object.
other (datetime): An optional second datetime object. If
unset, defaults to the current time as determined
:meth:`datetime.utcnow`.
ndigits (int): The number of decimal digits to round to,
defaults to ``0``.
Returns:
A short English-language string.
>>> now = datetime.utcnow()
>>> relative_time(now, ndigits=1)
'0 seconds ago'
>>> relative_time(now - timedelta(days=1, seconds=36000), ndigits=1)
'1.4 days ago'
>>> relative_time(now + timedelta(days=7), now, ndigits=1)
'1 week from now' | [
"Get",
"a",
"string",
"representation",
"of",
"the",
"difference",
"between",
"two",
":",
"class",
":",
"~datetime",
".",
"datetime",
"objects",
"or",
"one",
":",
"class",
":",
"~datetime",
".",
"datetime",
"and",
"the",
"current",
"time",
".",
"Handles",
... | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L221-L250 |
kalefranz/auxlib | auxlib/_vendor/boltons/timeutils.py | strpdate | def strpdate(string, format):
"""Parse the date string according to the format in `format`. Returns a
:class:`date` object. Internally, :meth:`datetime.strptime` is used to
parse the string and thus conversion specifiers for time fields (e.g. `%H`)
may be provided; these will be parsed but ignored.
Args:
string (str): The date string to be parsed.
format (str): The `strptime`_-style date format string.
Returns:
datetime.date
.. _`strptime`: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
>>> strpdate('2016-02-14', '%Y-%m-%d')
datetime.date(2016, 2, 14)
>>> strpdate('26/12 (2015)', '%d/%m (%Y)')
datetime.date(2015, 12, 26)
>>> strpdate('20151231 23:59:59', '%Y%m%d %H:%M:%S')
datetime.date(2015, 12, 31)
>>> strpdate('20160101 00:00:00.001', '%Y%m%d %H:%M:%S.%f')
datetime.date(2016, 1, 1)
"""
whence = datetime.strptime(string, format)
return whence.date() | python | def strpdate(string, format):
"""Parse the date string according to the format in `format`. Returns a
:class:`date` object. Internally, :meth:`datetime.strptime` is used to
parse the string and thus conversion specifiers for time fields (e.g. `%H`)
may be provided; these will be parsed but ignored.
Args:
string (str): The date string to be parsed.
format (str): The `strptime`_-style date format string.
Returns:
datetime.date
.. _`strptime`: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
>>> strpdate('2016-02-14', '%Y-%m-%d')
datetime.date(2016, 2, 14)
>>> strpdate('26/12 (2015)', '%d/%m (%Y)')
datetime.date(2015, 12, 26)
>>> strpdate('20151231 23:59:59', '%Y%m%d %H:%M:%S')
datetime.date(2015, 12, 31)
>>> strpdate('20160101 00:00:00.001', '%Y%m%d %H:%M:%S.%f')
datetime.date(2016, 1, 1)
"""
whence = datetime.strptime(string, format)
return whence.date() | [
"def",
"strpdate",
"(",
"string",
",",
"format",
")",
":",
"whence",
"=",
"datetime",
".",
"strptime",
"(",
"string",
",",
"format",
")",
"return",
"whence",
".",
"date",
"(",
")"
] | Parse the date string according to the format in `format`. Returns a
:class:`date` object. Internally, :meth:`datetime.strptime` is used to
parse the string and thus conversion specifiers for time fields (e.g. `%H`)
may be provided; these will be parsed but ignored.
Args:
string (str): The date string to be parsed.
format (str): The `strptime`_-style date format string.
Returns:
datetime.date
.. _`strptime`: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
>>> strpdate('2016-02-14', '%Y-%m-%d')
datetime.date(2016, 2, 14)
>>> strpdate('26/12 (2015)', '%d/%m (%Y)')
datetime.date(2015, 12, 26)
>>> strpdate('20151231 23:59:59', '%Y%m%d %H:%M:%S')
datetime.date(2015, 12, 31)
>>> strpdate('20160101 00:00:00.001', '%Y%m%d %H:%M:%S.%f')
datetime.date(2016, 1, 1) | [
"Parse",
"the",
"date",
"string",
"according",
"to",
"the",
"format",
"in",
"format",
".",
"Returns",
"a",
":",
"class",
":",
"date",
"object",
".",
"Internally",
":",
"meth",
":",
"datetime",
".",
"strptime",
"is",
"used",
"to",
"parse",
"the",
"string"... | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L253-L277 |
kalefranz/auxlib | auxlib/_vendor/boltons/timeutils.py | daterange | def daterange(start, stop, step=1, inclusive=False):
"""In the spirit of :func:`range` and :func:`xrange`, the `daterange`
generator that yields a sequence of :class:`~datetime.date`
objects, starting at *start*, incrementing by *step*, until *stop*
is reached.
When *inclusive* is True, the final date may be *stop*, **if**
*step* falls evenly on it. By default, *step* is one day. See
details below for many more details.
Args:
start (datetime.date): The starting date The first value in
the sequence.
stop (datetime.date): The stopping date. By default not
included in return. Can be `None` to yield an infinite
sequence.
step (int): The value to increment *start* by to reach
*stop*. Can be an :class:`int` number of days, a
:class:`datetime.timedelta`, or a :class:`tuple` of integers,
`(year, month, day)`. Positive and negative *step* values
are supported.
inclusive (bool): Whether or not the *stop* date can be
returned. *stop* is only returned when a *step* falls evenly
on it.
>>> christmas = date(year=2015, month=12, day=25)
>>> boxing_day = date(year=2015, month=12, day=26)
>>> new_year = date(year=2016, month=1, day=1)
>>> for day in daterange(christmas, new_year):
... print(repr(day))
datetime.date(2015, 12, 25)
datetime.date(2015, 12, 26)
datetime.date(2015, 12, 27)
datetime.date(2015, 12, 28)
datetime.date(2015, 12, 29)
datetime.date(2015, 12, 30)
datetime.date(2015, 12, 31)
>>> for day in daterange(christmas, boxing_day):
... print(repr(day))
datetime.date(2015, 12, 25)
>>> for day in daterange(date(2017, 5, 1), date(2017, 8, 1),
... step=(0, 1, 0), inclusive=True):
... print(repr(day))
datetime.date(2017, 5, 1)
datetime.date(2017, 6, 1)
datetime.date(2017, 7, 1)
datetime.date(2017, 8, 1)
*Be careful when using stop=None, as this will yield an infinite
sequence of dates.*
"""
if not isinstance(start, date):
raise TypeError("start expected datetime.date instance")
if stop and not isinstance(stop, date):
raise TypeError("stop expected datetime.date instance or None")
try:
y_step, m_step, d_step = step
except TypeError:
y_step, m_step, d_step = 0, 0, step
else:
y_step, m_step = int(y_step), int(m_step)
if isinstance(d_step, int):
d_step = timedelta(days=int(d_step))
elif isinstance(d_step, timedelta):
pass
else:
raise ValueError('step expected int, timedelta, or tuple'
' (year, month, day), not: %r' % step)
if stop is None:
finished = lambda t: False
elif start < stop:
finished = operator.gt if inclusive else operator.ge
else:
finished = operator.lt if inclusive else operator.le
now = start
while not finished(now, stop):
yield now
if y_step or m_step:
m_y_step, cur_month = divmod(now.month + m_step, 12)
now = now.replace(year=now.year + y_step + m_y_step,
month=cur_month or 12)
now = now + d_step
return | python | def daterange(start, stop, step=1, inclusive=False):
"""In the spirit of :func:`range` and :func:`xrange`, the `daterange`
generator that yields a sequence of :class:`~datetime.date`
objects, starting at *start*, incrementing by *step*, until *stop*
is reached.
When *inclusive* is True, the final date may be *stop*, **if**
*step* falls evenly on it. By default, *step* is one day. See
details below for many more details.
Args:
start (datetime.date): The starting date The first value in
the sequence.
stop (datetime.date): The stopping date. By default not
included in return. Can be `None` to yield an infinite
sequence.
step (int): The value to increment *start* by to reach
*stop*. Can be an :class:`int` number of days, a
:class:`datetime.timedelta`, or a :class:`tuple` of integers,
`(year, month, day)`. Positive and negative *step* values
are supported.
inclusive (bool): Whether or not the *stop* date can be
returned. *stop* is only returned when a *step* falls evenly
on it.
>>> christmas = date(year=2015, month=12, day=25)
>>> boxing_day = date(year=2015, month=12, day=26)
>>> new_year = date(year=2016, month=1, day=1)
>>> for day in daterange(christmas, new_year):
... print(repr(day))
datetime.date(2015, 12, 25)
datetime.date(2015, 12, 26)
datetime.date(2015, 12, 27)
datetime.date(2015, 12, 28)
datetime.date(2015, 12, 29)
datetime.date(2015, 12, 30)
datetime.date(2015, 12, 31)
>>> for day in daterange(christmas, boxing_day):
... print(repr(day))
datetime.date(2015, 12, 25)
>>> for day in daterange(date(2017, 5, 1), date(2017, 8, 1),
... step=(0, 1, 0), inclusive=True):
... print(repr(day))
datetime.date(2017, 5, 1)
datetime.date(2017, 6, 1)
datetime.date(2017, 7, 1)
datetime.date(2017, 8, 1)
*Be careful when using stop=None, as this will yield an infinite
sequence of dates.*
"""
if not isinstance(start, date):
raise TypeError("start expected datetime.date instance")
if stop and not isinstance(stop, date):
raise TypeError("stop expected datetime.date instance or None")
try:
y_step, m_step, d_step = step
except TypeError:
y_step, m_step, d_step = 0, 0, step
else:
y_step, m_step = int(y_step), int(m_step)
if isinstance(d_step, int):
d_step = timedelta(days=int(d_step))
elif isinstance(d_step, timedelta):
pass
else:
raise ValueError('step expected int, timedelta, or tuple'
' (year, month, day), not: %r' % step)
if stop is None:
finished = lambda t: False
elif start < stop:
finished = operator.gt if inclusive else operator.ge
else:
finished = operator.lt if inclusive else operator.le
now = start
while not finished(now, stop):
yield now
if y_step or m_step:
m_y_step, cur_month = divmod(now.month + m_step, 12)
now = now.replace(year=now.year + y_step + m_y_step,
month=cur_month or 12)
now = now + d_step
return | [
"def",
"daterange",
"(",
"start",
",",
"stop",
",",
"step",
"=",
"1",
",",
"inclusive",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"start",
",",
"date",
")",
":",
"raise",
"TypeError",
"(",
"\"start expected datetime.date instance\"",
")",
"if... | In the spirit of :func:`range` and :func:`xrange`, the `daterange`
generator that yields a sequence of :class:`~datetime.date`
objects, starting at *start*, incrementing by *step*, until *stop*
is reached.
When *inclusive* is True, the final date may be *stop*, **if**
*step* falls evenly on it. By default, *step* is one day. See
details below for many more details.
Args:
start (datetime.date): The starting date The first value in
the sequence.
stop (datetime.date): The stopping date. By default not
included in return. Can be `None` to yield an infinite
sequence.
step (int): The value to increment *start* by to reach
*stop*. Can be an :class:`int` number of days, a
:class:`datetime.timedelta`, or a :class:`tuple` of integers,
`(year, month, day)`. Positive and negative *step* values
are supported.
inclusive (bool): Whether or not the *stop* date can be
returned. *stop* is only returned when a *step* falls evenly
on it.
>>> christmas = date(year=2015, month=12, day=25)
>>> boxing_day = date(year=2015, month=12, day=26)
>>> new_year = date(year=2016, month=1, day=1)
>>> for day in daterange(christmas, new_year):
... print(repr(day))
datetime.date(2015, 12, 25)
datetime.date(2015, 12, 26)
datetime.date(2015, 12, 27)
datetime.date(2015, 12, 28)
datetime.date(2015, 12, 29)
datetime.date(2015, 12, 30)
datetime.date(2015, 12, 31)
>>> for day in daterange(christmas, boxing_day):
... print(repr(day))
datetime.date(2015, 12, 25)
>>> for day in daterange(date(2017, 5, 1), date(2017, 8, 1),
... step=(0, 1, 0), inclusive=True):
... print(repr(day))
datetime.date(2017, 5, 1)
datetime.date(2017, 6, 1)
datetime.date(2017, 7, 1)
datetime.date(2017, 8, 1)
*Be careful when using stop=None, as this will yield an infinite
sequence of dates.* | [
"In",
"the",
"spirit",
"of",
":",
"func",
":",
"range",
"and",
":",
"func",
":",
"xrange",
"the",
"daterange",
"generator",
"that",
"yields",
"a",
"sequence",
"of",
":",
"class",
":",
"~datetime",
".",
"date",
"objects",
"starting",
"at",
"*",
"start",
... | train | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/boltons/timeutils.py#L280-L364 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/list_.py | distros | def distros(ctx, opts, package_format):
"""List available distributions."""
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.echo("Getting list of distributions ... ", nl=False, err=use_stderr)
context_msg = "Failed to get list of distributions!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
distros_ = list_distros(package_format=package_format)
click.secho("OK", fg="green", err=use_stderr)
if utils.maybe_print_as_json(opts, distros_):
return
headers = ["Distro", "Release", "Format", "Distro / Release (Identifier)"]
if package_format:
headers.remove("Format")
rows = []
for distro in sorted(distros_, key=itemgetter("slug")):
if not distro["versions"]:
continue
for release in sorted(distro["versions"], key=itemgetter("slug")):
row = [
click.style(distro["name"], fg="cyan"),
click.style(release["name"], fg="yellow"),
click.style(distro["format"], fg="blue"),
"%(distro)s/%(release)s"
% {
"distro": click.style(distro["slug"], fg="magenta"),
"release": click.style(release["slug"], fg="green"),
},
]
if package_format:
row.pop(2) # Remove format column
rows.append(row)
if distros_:
click.echo()
utils.pretty_print_table(headers, rows)
click.echo()
num_results = sum(
1 for distro in distros_ for release in distro["versions"] if release
)
list_suffix = "distribution release%s" % ("s" if num_results != 1 else "")
utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix) | python | def distros(ctx, opts, package_format):
"""List available distributions."""
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.echo("Getting list of distributions ... ", nl=False, err=use_stderr)
context_msg = "Failed to get list of distributions!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
distros_ = list_distros(package_format=package_format)
click.secho("OK", fg="green", err=use_stderr)
if utils.maybe_print_as_json(opts, distros_):
return
headers = ["Distro", "Release", "Format", "Distro / Release (Identifier)"]
if package_format:
headers.remove("Format")
rows = []
for distro in sorted(distros_, key=itemgetter("slug")):
if not distro["versions"]:
continue
for release in sorted(distro["versions"], key=itemgetter("slug")):
row = [
click.style(distro["name"], fg="cyan"),
click.style(release["name"], fg="yellow"),
click.style(distro["format"], fg="blue"),
"%(distro)s/%(release)s"
% {
"distro": click.style(distro["slug"], fg="magenta"),
"release": click.style(release["slug"], fg="green"),
},
]
if package_format:
row.pop(2) # Remove format column
rows.append(row)
if distros_:
click.echo()
utils.pretty_print_table(headers, rows)
click.echo()
num_results = sum(
1 for distro in distros_ for release in distro["versions"] if release
)
list_suffix = "distribution release%s" % ("s" if num_results != 1 else "")
utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix) | [
"def",
"distros",
"(",
"ctx",
",",
"opts",
",",
"package_format",
")",
":",
"# Use stderr for messages if the output is something else (e.g. # JSON)",
"use_stderr",
"=",
"opts",
".",
"output",
"!=",
"\"pretty\"",
"click",
".",
"echo",
"(",
"\"Getting list of distribution... | List available distributions. | [
"List",
"available",
"distributions",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/list_.py#L47-L100 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/list_.py | packages | def packages(ctx, opts, owner_repo, page, page_size, query):
"""
List packages for a repository.
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name to list packages for that namespace and repository. All separated
by a slash.
You can use the search query (-q|--query) to filter packages:
- By name: 'my-package' (implicit) or 'name:my-package'
- By filename: 'pkg.ext' (implicit) or 'filename:pkg.ext' (explicit)
- By version: '1.0.0' (implicit) or 'version:1.0.0' (explicit)
- By arch: 'x86_64' (implicit) or 'architecture:x86_64' (explicit)
- By disto: 'el' (implicit) or 'distribution:el' (explicit)
You can also modify the search terms:
- '^foo' to anchor to start of term
- 'foo$' to anchor to end of term
- 'foo*bar' for fuzzy matching
- '~foo' for negation of the term (explicit only, e.g. name:~foo)
Multiple search terms are conjunctive (AND).
Examples, to find packages named exactly foo, with a zip filename, that are
NOT the x86 architecture, use something like this:
--query 'name:^foo$ filename:.zip$ architecture:~x86'
"""
owner, repo = owner_repo
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.echo("Getting list of packages ... ", nl=False, err=use_stderr)
context_msg = "Failed to get list of packages!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
packages_, page_info = list_packages(
owner=owner, repo=repo, page=page, page_size=page_size, query=query
)
click.secho("OK", fg="green", err=use_stderr)
if utils.maybe_print_as_json(opts, packages_, page_info):
return
headers = ["Name", "Version", "Status", "Owner / Repository (Identifier)"]
rows = []
for package in sorted(packages_, key=itemgetter("namespace", "slug")):
rows.append(
[
click.style(_get_package_name(package), fg="cyan"),
click.style(_get_package_version(package), fg="yellow"),
click.style(_get_package_status(package), fg="blue"),
"%(owner_slug)s/%(repo_slug)s/%(slug)s"
% {
"owner_slug": click.style(package["namespace"], fg="magenta"),
"repo_slug": click.style(package["repository"], fg="magenta"),
"slug": click.style(package["slug"], fg="green"),
},
]
)
if packages_:
click.echo()
utils.pretty_print_table(headers, rows)
click.echo()
num_results = len(packages_)
list_suffix = "package%s visible" % ("s" if num_results != 1 else "")
utils.pretty_print_list_info(
num_results=num_results, page_info=page_info, suffix=list_suffix
) | python | def packages(ctx, opts, owner_repo, page, page_size, query):
"""
List packages for a repository.
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name to list packages for that namespace and repository. All separated
by a slash.
You can use the search query (-q|--query) to filter packages:
- By name: 'my-package' (implicit) or 'name:my-package'
- By filename: 'pkg.ext' (implicit) or 'filename:pkg.ext' (explicit)
- By version: '1.0.0' (implicit) or 'version:1.0.0' (explicit)
- By arch: 'x86_64' (implicit) or 'architecture:x86_64' (explicit)
- By disto: 'el' (implicit) or 'distribution:el' (explicit)
You can also modify the search terms:
- '^foo' to anchor to start of term
- 'foo$' to anchor to end of term
- 'foo*bar' for fuzzy matching
- '~foo' for negation of the term (explicit only, e.g. name:~foo)
Multiple search terms are conjunctive (AND).
Examples, to find packages named exactly foo, with a zip filename, that are
NOT the x86 architecture, use something like this:
--query 'name:^foo$ filename:.zip$ architecture:~x86'
"""
owner, repo = owner_repo
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.echo("Getting list of packages ... ", nl=False, err=use_stderr)
context_msg = "Failed to get list of packages!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
packages_, page_info = list_packages(
owner=owner, repo=repo, page=page, page_size=page_size, query=query
)
click.secho("OK", fg="green", err=use_stderr)
if utils.maybe_print_as_json(opts, packages_, page_info):
return
headers = ["Name", "Version", "Status", "Owner / Repository (Identifier)"]
rows = []
for package in sorted(packages_, key=itemgetter("namespace", "slug")):
rows.append(
[
click.style(_get_package_name(package), fg="cyan"),
click.style(_get_package_version(package), fg="yellow"),
click.style(_get_package_status(package), fg="blue"),
"%(owner_slug)s/%(repo_slug)s/%(slug)s"
% {
"owner_slug": click.style(package["namespace"], fg="magenta"),
"repo_slug": click.style(package["repository"], fg="magenta"),
"slug": click.style(package["slug"], fg="green"),
},
]
)
if packages_:
click.echo()
utils.pretty_print_table(headers, rows)
click.echo()
num_results = len(packages_)
list_suffix = "package%s visible" % ("s" if num_results != 1 else "")
utils.pretty_print_list_info(
num_results=num_results, page_info=page_info, suffix=list_suffix
) | [
"def",
"packages",
"(",
"ctx",
",",
"opts",
",",
"owner_repo",
",",
"page",
",",
"page_size",
",",
"query",
")",
":",
"owner",
",",
"repo",
"=",
"owner_repo",
"# Use stderr for messages if the output is something else (e.g. # JSON)",
"use_stderr",
"=",
"opts",
".",... | List packages for a repository.
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name to list packages for that namespace and repository. All separated
by a slash.
You can use the search query (-q|--query) to filter packages:
- By name: 'my-package' (implicit) or 'name:my-package'
- By filename: 'pkg.ext' (implicit) or 'filename:pkg.ext' (explicit)
- By version: '1.0.0' (implicit) or 'version:1.0.0' (explicit)
- By arch: 'x86_64' (implicit) or 'architecture:x86_64' (explicit)
- By disto: 'el' (implicit) or 'distribution:el' (explicit)
You can also modify the search terms:
- '^foo' to anchor to start of term
- 'foo$' to anchor to end of term
- 'foo*bar' for fuzzy matching
- '~foo' for negation of the term (explicit only, e.g. name:~foo)
Multiple search terms are conjunctive (AND).
Examples, to find packages named exactly foo, with a zip filename, that are
NOT the x86 architecture, use something like this:
--query 'name:^foo$ filename:.zip$ architecture:~x86' | [
"List",
"packages",
"for",
"a",
"repository",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/list_.py#L126-L210 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/list_.py | repos | def repos(ctx, opts, owner, page, page_size):
"""
List repositories for a namespace (owner).
OWNER: Specify the OWNER namespace (i.e. user or org) to list the
repositories for that namespace.
If OWNER isn't specified it'll default to the currently authenticated user
(if any). If you're unauthenticated, no results will be returned.
"""
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.echo("Getting list of repositories ... ", nl=False, err=use_stderr)
context_msg = "Failed to get list of repositories!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
repos_, page_info = list_repos(owner=owner, page=page, page_size=page_size)
click.secho("OK", fg="green", err=use_stderr)
if utils.maybe_print_as_json(opts, repos_, page_info):
return
headers = [
"Name",
"Type",
"Packages",
"Groups",
"Downloads",
"Size",
"Owner / Repository (Identifier)",
]
rows = []
for repo in sorted(repos_, key=itemgetter("namespace", "slug")):
rows.append(
[
click.style(repo["name"], fg="cyan"),
click.style(repo["repository_type_str"], fg="yellow"),
click.style(six.text_type(repo["package_count"]), fg="blue"),
click.style(six.text_type(repo["package_group_count"]), fg="blue"),
click.style(six.text_type(repo["num_downloads"]), fg="blue"),
click.style(six.text_type(repo["size_str"]), fg="blue"),
"%(owner_slug)s/%(slug)s"
% {
"owner_slug": click.style(repo["namespace"], fg="magenta"),
"slug": click.style(repo["slug"], fg="green"),
},
]
)
if repos_:
click.echo()
utils.pretty_print_table(headers, rows)
click.echo()
num_results = len(repos_)
list_suffix = "repositor%s visible" % ("ies" if num_results != 1 else "y")
utils.pretty_print_list_info(
num_results=num_results, page_info=page_info, suffix=list_suffix
) | python | def repos(ctx, opts, owner, page, page_size):
"""
List repositories for a namespace (owner).
OWNER: Specify the OWNER namespace (i.e. user or org) to list the
repositories for that namespace.
If OWNER isn't specified it'll default to the currently authenticated user
(if any). If you're unauthenticated, no results will be returned.
"""
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.echo("Getting list of repositories ... ", nl=False, err=use_stderr)
context_msg = "Failed to get list of repositories!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
repos_, page_info = list_repos(owner=owner, page=page, page_size=page_size)
click.secho("OK", fg="green", err=use_stderr)
if utils.maybe_print_as_json(opts, repos_, page_info):
return
headers = [
"Name",
"Type",
"Packages",
"Groups",
"Downloads",
"Size",
"Owner / Repository (Identifier)",
]
rows = []
for repo in sorted(repos_, key=itemgetter("namespace", "slug")):
rows.append(
[
click.style(repo["name"], fg="cyan"),
click.style(repo["repository_type_str"], fg="yellow"),
click.style(six.text_type(repo["package_count"]), fg="blue"),
click.style(six.text_type(repo["package_group_count"]), fg="blue"),
click.style(six.text_type(repo["num_downloads"]), fg="blue"),
click.style(six.text_type(repo["size_str"]), fg="blue"),
"%(owner_slug)s/%(slug)s"
% {
"owner_slug": click.style(repo["namespace"], fg="magenta"),
"slug": click.style(repo["slug"], fg="green"),
},
]
)
if repos_:
click.echo()
utils.pretty_print_table(headers, rows)
click.echo()
num_results = len(repos_)
list_suffix = "repositor%s visible" % ("ies" if num_results != 1 else "y")
utils.pretty_print_list_info(
num_results=num_results, page_info=page_info, suffix=list_suffix
) | [
"def",
"repos",
"(",
"ctx",
",",
"opts",
",",
"owner",
",",
"page",
",",
"page_size",
")",
":",
"# Use stderr for messages if the output is something else (e.g. # JSON)",
"use_stderr",
"=",
"opts",
".",
"output",
"!=",
"\"pretty\"",
"click",
".",
"echo",
"(",
"\"... | List repositories for a namespace (owner).
OWNER: Specify the OWNER namespace (i.e. user or org) to list the
repositories for that namespace.
If OWNER isn't specified it'll default to the currently authenticated user
(if any). If you're unauthenticated, no results will be returned. | [
"List",
"repositories",
"for",
"a",
"namespace",
"(",
"owner",
")",
"."
] | train | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/list_.py#L221-L284 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.