repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L297-L318 | train | 48,200 |
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"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L349-L358 | train | 48,201 |
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"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L368-L374 | train | 48,202 |
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"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L376-L382 | train | 48,203 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/repos.py#L18-L45 | train | 48,204 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L12-L34 | train | 48,205 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L154-L192 | train | 48,206 |
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",
"."
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L194-L260 | train | 48,207 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L318-L353 | train | 48,208 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L356-L383 | train | 48,209 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L385-L472 | train | 48,210 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L474-L547 | train | 48,211 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L549-L562 | train | 48,212 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L564-L574 | train | 48,213 |
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",
"."
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L576-L654 | train | 48,214 |
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"
] | 3702e974696e22876944a3339affad2f29e1ee06 | https://github.com/visualfabriq/bquery/blob/3702e974696e22876944a3339affad2f29e1ee06/bquery/ctable.py#L821-L849 | train | 48,215 |
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",
"."
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/_vendor/five.py#L202-L216 | train | 48,216 |
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",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/util.py#L24-L48 | train | 48,217 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/main.py#L15-L25 | train | 48,218 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/main.py#L58-L64 | train | 48,219 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L56-L103 | train | 48,220 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L106-L126 | train | 48,221 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L129-L158 | train | 48,222 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/push.py#L268-L354 | train | 48,223 |
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"... | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/decorators.py#L10-L62 | train | 48,224 |
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"
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/crypt.py#L77-L97 | train | 48,225 |
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"
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/crypt.py#L100-L124 | train | 48,226 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/whoami.py#L20-L41 | train | 48,227 |
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",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/container.py#L21-L32 | train | 48,228 |
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",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/container.py#L34-L51 | train | 48,229 |
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",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/container.py#L53-L68 | train | 48,230 |
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",
"."
] | c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L129-L136 | train | 48,231 |
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",
"."
] | c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L138-L169 | train | 48,232 |
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",
"."
] | c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L207-L217 | train | 48,233 |
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",
"."
] | c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L792-L795 | train | 48,234 |
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",
"."
] | c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L797-L801 | train | 48,235 |
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",
"."
] | c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L803-L808 | train | 48,236 |
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",
"."
] | c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a | https://github.com/ndf-zz/asfv1/blob/c18f940d7ee86b14e6b201e6d8a4b71e3a57c34a/asfv1.py#L1114-L1155 | train | 48,237 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/resync.py#L27-L69 | train | 48,238 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/resync.py#L72-L87 | train | 48,239 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L32-L44 | train | 48,240 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L47-L61 | train | 48,241 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L80-L93 | train | 48,242 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L96-L106 | train | 48,243 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L109-L119 | train | 48,244 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L122-L142 | train | 48,245 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L163-L202 | train | 48,246 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/packages.py#L205-L211 | train | 48,247 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/exceptions.py#L36-L57 | train | 48,248 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L54-L62 | train | 48,249 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L65-L94 | train | 48,250 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L97-L105 | train | 48,251 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L108-L124 | train | 48,252 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L183-L186 | train | 48,253 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L188-L191 | train | 48,254 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L209-L212 | train | 48,255 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L340-L344 | train | 48,256 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/config.py#L350-L361 | train | 48,257 |
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",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/base.py#L23-L32 | train | 48,258 |
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",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/base.py#L50-L58 | train | 48,259 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/check.py#L34-L76 | train | 48,260 |
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",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/check.py#L84-L130 | train | 48,261 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/list_.py | _get_package_status | def _get_package_status(package):
"""Get the status for a package."""
status = package["status_str"] or "Unknown"
stage = package["stage_str"] or "Unknown"
if stage == "Fully Synchronised":
return status
return "%(status)s / %(stage)s" % {"status": status, "stage": stage} | python | def _get_package_status(package):
"""Get the status for a package."""
status = package["status_str"] or "Unknown"
stage = package["stage_str"] or "Unknown"
if stage == "Fully Synchronised":
return status
return "%(status)s / %(stage)s" % {"status": status, "stage": stage} | [
"def",
"_get_package_status",
"(",
"package",
")",
":",
"status",
"=",
"package",
"[",
"\"status_str\"",
"]",
"or",
"\"Unknown\"",
"stage",
"=",
"package",
"[",
"\"stage_str\"",
"]",
"or",
"\"Unknown\"",
"if",
"stage",
"==",
"\"Fully Synchronised\"",
":",
"retur... | Get the status for a package. | [
"Get",
"the",
"status",
"for",
"a",
"package",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/list_.py#L292-L298 | train | 48,262 |
kalefranz/auxlib | auxlib/type_coercion.py | boolify | def boolify(value, nullable=False, return_string=False):
"""Convert a number, string, or sequence type into a pure boolean.
Args:
value (number, string, sequence): pretty much anything
Returns:
bool: boolean representation of the given value
Examples:
>>> [boolify(x) for x in ('yes', 'no')]
[True, False]
>>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')]
[True, False, True, False, False, True, True]
>>> [boolify(x) for x in ("true", "yes", "on", "y")]
[True, True, True, True]
>>> [boolify(x) for x in ("no", "non", "none", "off", "")]
[False, False, False, False, False]
>>> [boolify(x) for x in ([], set(), dict(), tuple())]
[False, False, False, False]
>>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))]
[True, True, True, True]
"""
# cast number types naturally
if isinstance(value, BOOL_COERCEABLE_TYPES):
return bool(value)
# try to coerce string into number
val = text_type(value).strip().lower().replace('.', '', 1)
if val.isnumeric():
return bool(float(val))
elif val in BOOLISH_TRUE:
return True
elif nullable and val in NULL_STRINGS:
return None
elif val in BOOLISH_FALSE:
return False
else: # must be False
try:
return bool(complex(val))
except ValueError:
if isinstance(value, string_types) and return_string:
return value
raise TypeCoercionError(value, "The value %r cannot be boolified." % value) | python | def boolify(value, nullable=False, return_string=False):
"""Convert a number, string, or sequence type into a pure boolean.
Args:
value (number, string, sequence): pretty much anything
Returns:
bool: boolean representation of the given value
Examples:
>>> [boolify(x) for x in ('yes', 'no')]
[True, False]
>>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')]
[True, False, True, False, False, True, True]
>>> [boolify(x) for x in ("true", "yes", "on", "y")]
[True, True, True, True]
>>> [boolify(x) for x in ("no", "non", "none", "off", "")]
[False, False, False, False, False]
>>> [boolify(x) for x in ([], set(), dict(), tuple())]
[False, False, False, False]
>>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))]
[True, True, True, True]
"""
# cast number types naturally
if isinstance(value, BOOL_COERCEABLE_TYPES):
return bool(value)
# try to coerce string into number
val = text_type(value).strip().lower().replace('.', '', 1)
if val.isnumeric():
return bool(float(val))
elif val in BOOLISH_TRUE:
return True
elif nullable and val in NULL_STRINGS:
return None
elif val in BOOLISH_FALSE:
return False
else: # must be False
try:
return bool(complex(val))
except ValueError:
if isinstance(value, string_types) and return_string:
return value
raise TypeCoercionError(value, "The value %r cannot be boolified." % value) | [
"def",
"boolify",
"(",
"value",
",",
"nullable",
"=",
"False",
",",
"return_string",
"=",
"False",
")",
":",
"# cast number types naturally",
"if",
"isinstance",
"(",
"value",
",",
"BOOL_COERCEABLE_TYPES",
")",
":",
"return",
"bool",
"(",
"value",
")",
"# try ... | Convert a number, string, or sequence type into a pure boolean.
Args:
value (number, string, sequence): pretty much anything
Returns:
bool: boolean representation of the given value
Examples:
>>> [boolify(x) for x in ('yes', 'no')]
[True, False]
>>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')]
[True, False, True, False, False, True, True]
>>> [boolify(x) for x in ("true", "yes", "on", "y")]
[True, True, True, True]
>>> [boolify(x) for x in ("no", "non", "none", "off", "")]
[False, False, False, False, False]
>>> [boolify(x) for x in ([], set(), dict(), tuple())]
[False, False, False, False]
>>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))]
[True, True, True, True] | [
"Convert",
"a",
"number",
"string",
"or",
"sequence",
"type",
"into",
"a",
"pure",
"boolean",
"."
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/type_coercion.py#L126-L169 | train | 48,263 |
kalefranz/auxlib | auxlib/type_coercion.py | typify | def typify(value, type_hint=None):
"""Take a primitive value, usually a string, and try to make a more relevant type out of it.
An optional type_hint will try to coerce the value to that type.
Args:
value (Any): Usually a string, not a sequence
type_hint (type or Tuple[type]):
Examples:
>>> typify('32')
32
>>> typify('32', float)
32.0
>>> typify('32.0')
32.0
>>> typify('32.0.0')
'32.0.0'
>>> [typify(x) for x in ('true', 'yes', 'on')]
[True, True, True]
>>> [typify(x) for x in ('no', 'FALSe', 'off')]
[False, False, False]
>>> [typify(x) for x in ('none', 'None', None)]
[None, None, None]
"""
# value must be a string, or there at least needs to be a type hint
if isinstance(value, string_types):
value = value.strip()
elif type_hint is None:
# can't do anything because value isn't a string and there's no type hint
return value
# now we either have a stripped string, a type hint, or both
# use the hint if it exists
if isiterable(type_hint):
if isinstance(type_hint, type) and issubclass(type_hint, Enum):
try:
return type_hint(value)
except ValueError:
return type_hint[value]
type_hint = set(type_hint)
if not (type_hint - NUMBER_TYPES_SET):
return numberify(value)
elif not (type_hint - STRING_TYPES_SET):
return text_type(value)
elif not (type_hint - {bool, NoneType}):
return boolify(value, nullable=True)
elif not (type_hint - (STRING_TYPES_SET | {bool})):
return boolify(value, return_string=True)
elif not (type_hint - (STRING_TYPES_SET | {NoneType})):
value = text_type(value)
return None if value.lower() == 'none' else value
elif not (type_hint - {bool, int}):
return typify_str_no_hint(text_type(value))
else:
raise NotImplementedError()
elif type_hint is not None:
# coerce using the type hint, or use boolify for bool
try:
return boolify(value) if type_hint == bool else type_hint(value)
except ValueError as e:
# ValueError: invalid literal for int() with base 10: 'nope'
raise TypeCoercionError(value, text_type(e))
else:
# no type hint, but we know value is a string, so try to match with the regex patterns
# if there's still no match, `typify_str_no_hint` will return `value`
return typify_str_no_hint(value) | python | def typify(value, type_hint=None):
"""Take a primitive value, usually a string, and try to make a more relevant type out of it.
An optional type_hint will try to coerce the value to that type.
Args:
value (Any): Usually a string, not a sequence
type_hint (type or Tuple[type]):
Examples:
>>> typify('32')
32
>>> typify('32', float)
32.0
>>> typify('32.0')
32.0
>>> typify('32.0.0')
'32.0.0'
>>> [typify(x) for x in ('true', 'yes', 'on')]
[True, True, True]
>>> [typify(x) for x in ('no', 'FALSe', 'off')]
[False, False, False]
>>> [typify(x) for x in ('none', 'None', None)]
[None, None, None]
"""
# value must be a string, or there at least needs to be a type hint
if isinstance(value, string_types):
value = value.strip()
elif type_hint is None:
# can't do anything because value isn't a string and there's no type hint
return value
# now we either have a stripped string, a type hint, or both
# use the hint if it exists
if isiterable(type_hint):
if isinstance(type_hint, type) and issubclass(type_hint, Enum):
try:
return type_hint(value)
except ValueError:
return type_hint[value]
type_hint = set(type_hint)
if not (type_hint - NUMBER_TYPES_SET):
return numberify(value)
elif not (type_hint - STRING_TYPES_SET):
return text_type(value)
elif not (type_hint - {bool, NoneType}):
return boolify(value, nullable=True)
elif not (type_hint - (STRING_TYPES_SET | {bool})):
return boolify(value, return_string=True)
elif not (type_hint - (STRING_TYPES_SET | {NoneType})):
value = text_type(value)
return None if value.lower() == 'none' else value
elif not (type_hint - {bool, int}):
return typify_str_no_hint(text_type(value))
else:
raise NotImplementedError()
elif type_hint is not None:
# coerce using the type hint, or use boolify for bool
try:
return boolify(value) if type_hint == bool else type_hint(value)
except ValueError as e:
# ValueError: invalid literal for int() with base 10: 'nope'
raise TypeCoercionError(value, text_type(e))
else:
# no type hint, but we know value is a string, so try to match with the regex patterns
# if there's still no match, `typify_str_no_hint` will return `value`
return typify_str_no_hint(value) | [
"def",
"typify",
"(",
"value",
",",
"type_hint",
"=",
"None",
")",
":",
"# value must be a string, or there at least needs to be a type hint",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"elif",
... | Take a primitive value, usually a string, and try to make a more relevant type out of it.
An optional type_hint will try to coerce the value to that type.
Args:
value (Any): Usually a string, not a sequence
type_hint (type or Tuple[type]):
Examples:
>>> typify('32')
32
>>> typify('32', float)
32.0
>>> typify('32.0')
32.0
>>> typify('32.0.0')
'32.0.0'
>>> [typify(x) for x in ('true', 'yes', 'on')]
[True, True, True]
>>> [typify(x) for x in ('no', 'FALSe', 'off')]
[False, False, False]
>>> [typify(x) for x in ('none', 'None', None)]
[None, None, None] | [
"Take",
"a",
"primitive",
"value",
"usually",
"a",
"string",
"and",
"try",
"to",
"make",
"a",
"more",
"relevant",
"type",
"out",
"of",
"it",
".",
"An",
"optional",
"type_hint",
"will",
"try",
"to",
"coerce",
"the",
"value",
"to",
"that",
"type",
"."
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/type_coercion.py#L185-L251 | train | 48,264 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/delete.py | delete | def delete(ctx, opts, owner_repo_package, yes):
"""
Delete a package from a 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'.
"""
owner, repo, slug = owner_repo_package
delete_args = {
"owner": click.style(owner, bold=True),
"repo": click.style(repo, bold=True),
"package": click.style(slug, bold=True),
}
prompt = "delete the %(package)s from %(owner)s/%(repo)s" % delete_args
if not utils.confirm_operation(prompt, assume_yes=yes):
return
click.echo(
"Deleting %(package)s from %(owner)s/%(repo)s ... " % delete_args, nl=False
)
context_msg = "Failed to delete the package!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
delete_package(owner=owner, repo=repo, identifier=slug)
click.secho("OK", fg="green") | python | def delete(ctx, opts, owner_repo_package, yes):
"""
Delete a package from a 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'.
"""
owner, repo, slug = owner_repo_package
delete_args = {
"owner": click.style(owner, bold=True),
"repo": click.style(repo, bold=True),
"package": click.style(slug, bold=True),
}
prompt = "delete the %(package)s from %(owner)s/%(repo)s" % delete_args
if not utils.confirm_operation(prompt, assume_yes=yes):
return
click.echo(
"Deleting %(package)s from %(owner)s/%(repo)s ... " % delete_args, nl=False
)
context_msg = "Failed to delete the package!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
delete_package(owner=owner, repo=repo, identifier=slug)
click.secho("OK", fg="green") | [
"def",
"delete",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_package",
",",
"yes",
")",
":",
"owner",
",",
"repo",
",",
"slug",
"=",
"owner_repo_package",
"delete_args",
"=",
"{",
"\"owner\"",
":",
"click",
".",
"style",
"(",
"owner",
",",
"bold",
"=",
"... | Delete a package from a 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'. | [
"Delete",
"a",
"package",
"from",
"a",
"repository",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/delete.py#L32-L63 | train | 48,265 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/entitlements.py | common_entitlements_options | def common_entitlements_options(f):
"""Add common options for entitlement commands."""
@click.option(
"--show-tokens",
default=False,
is_flag=True,
help="Show entitlement token string contents in output.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
return ctx.invoke(f, *args, **kwargs)
return wrapper | python | def common_entitlements_options(f):
"""Add common options for entitlement commands."""
@click.option(
"--show-tokens",
default=False,
is_flag=True,
help="Show entitlement token string contents in output.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
return ctx.invoke(f, *args, **kwargs)
return wrapper | [
"def",
"common_entitlements_options",
"(",
"f",
")",
":",
"@",
"click",
".",
"option",
"(",
"\"--show-tokens\"",
",",
"default",
"=",
"False",
",",
"is_flag",
"=",
"True",
",",
"help",
"=",
"\"Show entitlement token string contents in output.\"",
",",
")",
"@",
... | Add common options for entitlement commands. | [
"Add",
"common",
"options",
"for",
"entitlement",
"commands",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L24-L39 | train | 48,266 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/entitlements.py | list_entitlements_options | def list_entitlements_options(f):
"""Options for list entitlements subcommand."""
@common_entitlements_options
@decorators.common_cli_config_options
@decorators.common_cli_list_options
@decorators.common_cli_output_options
@decorators.common_api_auth_options
@decorators.initialise_api
@click.argument(
"owner_repo", metavar="OWNER/REPO", callback=validators.validate_owner_repo
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
return ctx.invoke(f, *args, **kwargs)
return wrapper | python | def list_entitlements_options(f):
"""Options for list entitlements subcommand."""
@common_entitlements_options
@decorators.common_cli_config_options
@decorators.common_cli_list_options
@decorators.common_cli_output_options
@decorators.common_api_auth_options
@decorators.initialise_api
@click.argument(
"owner_repo", metavar="OWNER/REPO", callback=validators.validate_owner_repo
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
return ctx.invoke(f, *args, **kwargs)
return wrapper | [
"def",
"list_entitlements_options",
"(",
"f",
")",
":",
"@",
"common_entitlements_options",
"@",
"decorators",
".",
"common_cli_config_options",
"@",
"decorators",
".",
"common_cli_list_options",
"@",
"decorators",
".",
"common_cli_output_options",
"@",
"decorators",
".",... | Options for list entitlements subcommand. | [
"Options",
"for",
"list",
"entitlements",
"subcommand",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L56-L74 | train | 48,267 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/entitlements.py | list_entitlements | def list_entitlements(ctx, opts, owner_repo, page, page_size, show_tokens):
"""
List entitlements for a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to list entitlements for. All separated by a slash.
Example: 'your-org/your-repo'
Full CLI example:
$ cloudsmith ents list your-org/your-repo
"""
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 entitlements for the %(repository)s "
"repository ... " % {"repository": click.style(repo, bold=True)},
nl=False,
err=use_stderr,
)
context_msg = "Failed to get list of entitlements!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
entitlements_, page_info = api.list_entitlements(
owner=owner,
repo=repo,
page=page,
page_size=page_size,
show_tokens=show_tokens,
)
click.secho("OK", fg="green", err=use_stderr)
print_entitlements(opts=opts, data=entitlements_, page_info=page_info) | python | def list_entitlements(ctx, opts, owner_repo, page, page_size, show_tokens):
"""
List entitlements for a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to list entitlements for. All separated by a slash.
Example: 'your-org/your-repo'
Full CLI example:
$ cloudsmith ents list your-org/your-repo
"""
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 entitlements for the %(repository)s "
"repository ... " % {"repository": click.style(repo, bold=True)},
nl=False,
err=use_stderr,
)
context_msg = "Failed to get list of entitlements!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
entitlements_, page_info = api.list_entitlements(
owner=owner,
repo=repo,
page=page,
page_size=page_size,
show_tokens=show_tokens,
)
click.secho("OK", fg="green", err=use_stderr)
print_entitlements(opts=opts, data=entitlements_, page_info=page_info) | [
"def",
"list_entitlements",
"(",
"ctx",
",",
"opts",
",",
"owner_repo",
",",
"page",
",",
"page_size",
",",
"show_tokens",
")",
":",
"owner",
",",
"repo",
"=",
"owner_repo",
"# Use stderr for messages if the output is something else (e.g. # JSON)",
"use_stderr",
"=",
... | List entitlements for a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to list entitlements for. All separated by a slash.
Example: 'your-org/your-repo'
Full CLI example:
$ cloudsmith ents list your-org/your-repo | [
"List",
"entitlements",
"for",
"a",
"repository",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L77-L115 | train | 48,268 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/entitlements.py | print_entitlements | def print_entitlements(opts, data, page_info=None, show_list_info=True):
"""Print entitlements as a table or output in another format."""
if utils.maybe_print_as_json(opts, data, page_info):
return
headers = ["Name", "Token", "Created / Updated", "Identifier"]
rows = []
for entitlement in sorted(data, key=itemgetter("name")):
rows.append(
[
click.style(
"%(name)s (%(type)s)"
% {
"name": click.style(entitlement["name"], fg="cyan"),
"type": "user" if entitlement["user"] else "token",
}
),
click.style(entitlement["token"], fg="yellow"),
click.style(entitlement["updated_at"], fg="blue"),
click.style(entitlement["slug_perm"], fg="green"),
]
)
if data:
click.echo()
utils.pretty_print_table(headers, rows)
if not show_list_info:
return
click.echo()
num_results = len(data)
list_suffix = "entitlement%s" % ("s" if num_results != 1 else "")
utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix) | python | def print_entitlements(opts, data, page_info=None, show_list_info=True):
"""Print entitlements as a table or output in another format."""
if utils.maybe_print_as_json(opts, data, page_info):
return
headers = ["Name", "Token", "Created / Updated", "Identifier"]
rows = []
for entitlement in sorted(data, key=itemgetter("name")):
rows.append(
[
click.style(
"%(name)s (%(type)s)"
% {
"name": click.style(entitlement["name"], fg="cyan"),
"type": "user" if entitlement["user"] else "token",
}
),
click.style(entitlement["token"], fg="yellow"),
click.style(entitlement["updated_at"], fg="blue"),
click.style(entitlement["slug_perm"], fg="green"),
]
)
if data:
click.echo()
utils.pretty_print_table(headers, rows)
if not show_list_info:
return
click.echo()
num_results = len(data)
list_suffix = "entitlement%s" % ("s" if num_results != 1 else "")
utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix) | [
"def",
"print_entitlements",
"(",
"opts",
",",
"data",
",",
"page_info",
"=",
"None",
",",
"show_list_info",
"=",
"True",
")",
":",
"if",
"utils",
".",
"maybe_print_as_json",
"(",
"opts",
",",
"data",
",",
"page_info",
")",
":",
"return",
"headers",
"=",
... | Print entitlements as a table or output in another format. | [
"Print",
"entitlements",
"as",
"a",
"table",
"or",
"output",
"in",
"another",
"format",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L126-L161 | train | 48,269 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/entitlements.py | create | def create(ctx, opts, owner_repo, show_tokens, name, token):
"""
Create a new entitlement in a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to create an entitlement. All separated by a slash.
Example: 'your-org/your-repo'
Full CLI example:
$ cloudsmith ents create your-org/your-repo --name 'Foobar'
"""
owner, repo = owner_repo
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.secho(
"Creating %(name)s entitlement for the %(repository)s "
"repository ... "
% {
"name": click.style(name, bold=True),
"repository": click.style(repo, bold=True),
},
nl=False,
err=use_stderr,
)
context_msg = "Failed to create the entitlement!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
entitlement = api.create_entitlement(
owner=owner, repo=repo, name=name, token=token, show_tokens=show_tokens
)
click.secho("OK", fg="green", err=use_stderr)
print_entitlements(opts=opts, data=[entitlement], show_list_info=False) | python | def create(ctx, opts, owner_repo, show_tokens, name, token):
"""
Create a new entitlement in a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to create an entitlement. All separated by a slash.
Example: 'your-org/your-repo'
Full CLI example:
$ cloudsmith ents create your-org/your-repo --name 'Foobar'
"""
owner, repo = owner_repo
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.secho(
"Creating %(name)s entitlement for the %(repository)s "
"repository ... "
% {
"name": click.style(name, bold=True),
"repository": click.style(repo, bold=True),
},
nl=False,
err=use_stderr,
)
context_msg = "Failed to create the entitlement!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
entitlement = api.create_entitlement(
owner=owner, repo=repo, name=name, token=token, show_tokens=show_tokens
)
click.secho("OK", fg="green", err=use_stderr)
print_entitlements(opts=opts, data=[entitlement], show_list_info=False) | [
"def",
"create",
"(",
"ctx",
",",
"opts",
",",
"owner_repo",
",",
"show_tokens",
",",
"name",
",",
"token",
")",
":",
"owner",
",",
"repo",
"=",
"owner_repo",
"# Use stderr for messages if the output is something else (e.g. # JSON)",
"use_stderr",
"=",
"opts",
".",... | Create a new entitlement in a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to create an entitlement. All separated by a slash.
Example: 'your-org/your-repo'
Full CLI example:
$ cloudsmith ents create your-org/your-repo --name 'Foobar' | [
"Create",
"a",
"new",
"entitlement",
"in",
"a",
"repository",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/entitlements.py#L189-L227 | train | 48,270 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/ratelimits.py | maybe_rate_limit | def maybe_rate_limit(client, headers, atexit=False):
"""Optionally pause the process based on suggested rate interval."""
# pylint: disable=fixme
# pylint: disable=global-statement
# FIXME: Yes, I know this is not great. We'll fix it later. :-)
global LAST_CLIENT, LAST_HEADERS
if LAST_CLIENT and LAST_HEADERS:
# Wait based on previous client/headers
rate_limit(LAST_CLIENT, LAST_HEADERS, atexit=atexit)
LAST_CLIENT = copy.copy(client)
LAST_HEADERS = copy.copy(headers) | python | def maybe_rate_limit(client, headers, atexit=False):
"""Optionally pause the process based on suggested rate interval."""
# pylint: disable=fixme
# pylint: disable=global-statement
# FIXME: Yes, I know this is not great. We'll fix it later. :-)
global LAST_CLIENT, LAST_HEADERS
if LAST_CLIENT and LAST_HEADERS:
# Wait based on previous client/headers
rate_limit(LAST_CLIENT, LAST_HEADERS, atexit=atexit)
LAST_CLIENT = copy.copy(client)
LAST_HEADERS = copy.copy(headers) | [
"def",
"maybe_rate_limit",
"(",
"client",
",",
"headers",
",",
"atexit",
"=",
"False",
")",
":",
"# pylint: disable=fixme",
"# pylint: disable=global-statement",
"# FIXME: Yes, I know this is not great. We'll fix it later. :-)",
"global",
"LAST_CLIENT",
",",
"LAST_HEADERS",
"if... | Optionally pause the process based on suggested rate interval. | [
"Optionally",
"pause",
"the",
"process",
"based",
"on",
"suggested",
"rate",
"interval",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/ratelimits.py#L85-L97 | train | 48,271 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/ratelimits.py | rate_limit | def rate_limit(client, headers, atexit=False):
"""Pause the process based on suggested rate interval."""
if not client or not headers:
return False
if not getattr(client.config, "rate_limit", False):
return False
rate_info = RateLimitsInfo.from_headers(headers)
if not rate_info or not rate_info.interval:
return False
if rate_info.interval:
cb = getattr(client.config, "rate_limit_callback", None)
if cb and callable(cb):
cb(rate_info, atexit=atexit)
time.sleep(rate_info.interval)
return True | python | def rate_limit(client, headers, atexit=False):
"""Pause the process based on suggested rate interval."""
if not client or not headers:
return False
if not getattr(client.config, "rate_limit", False):
return False
rate_info = RateLimitsInfo.from_headers(headers)
if not rate_info or not rate_info.interval:
return False
if rate_info.interval:
cb = getattr(client.config, "rate_limit_callback", None)
if cb and callable(cb):
cb(rate_info, atexit=atexit)
time.sleep(rate_info.interval)
return True | [
"def",
"rate_limit",
"(",
"client",
",",
"headers",
",",
"atexit",
"=",
"False",
")",
":",
"if",
"not",
"client",
"or",
"not",
"headers",
":",
"return",
"False",
"if",
"not",
"getattr",
"(",
"client",
".",
"config",
",",
"\"rate_limit\"",
",",
"False",
... | Pause the process based on suggested rate interval. | [
"Pause",
"the",
"process",
"based",
"on",
"suggested",
"rate",
"interval",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/ratelimits.py#L100-L117 | train | 48,272 |
kalefranz/auxlib | auxlib/collection.py | first | def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
"""Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element before return, but not to default value
Returns: first element in seq that passes key, mutated with optional apply
Examples:
>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'
The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4
"""
return next((apply(x) for x in seq if key(x)), default() if callable(default) else default) | python | def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
"""Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element before return, but not to default value
Returns: first element in seq that passes key, mutated with optional apply
Examples:
>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'
The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4
"""
return next((apply(x) for x in seq if key(x)), default() if callable(default) else default) | [
"def",
"first",
"(",
"seq",
",",
"key",
"=",
"lambda",
"x",
":",
"bool",
"(",
"x",
")",
",",
"default",
"=",
"None",
",",
"apply",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"return",
"next",
"(",
"(",
"apply",
"(",
"x",
")",
"for",
"x",
"in",
... | Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element before return, but not to default value
Returns: first element in seq that passes key, mutated with optional apply
Examples:
>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'
The optional `key` argument specifies a one-argument predicate function
like that used for `filter()`. The `key` argument, if supplied, must be
in keyword form. For example:
>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4 | [
"Give",
"the",
"first",
"value",
"that",
"satisfies",
"the",
"key",
"test",
"."
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/collection.py#L87-L117 | train | 48,273 |
kalefranz/auxlib | auxlib/collection.py | call_each | def call_each(seq):
"""Calls each element of sequence to invoke the side effect.
Args:
seq:
Returns: None
"""
try:
reduce(lambda _, y: y(), seq)
except TypeError as e:
if text_type(e) != "reduce() of empty sequence with no initial value":
raise | python | def call_each(seq):
"""Calls each element of sequence to invoke the side effect.
Args:
seq:
Returns: None
"""
try:
reduce(lambda _, y: y(), seq)
except TypeError as e:
if text_type(e) != "reduce() of empty sequence with no initial value":
raise | [
"def",
"call_each",
"(",
"seq",
")",
":",
"try",
":",
"reduce",
"(",
"lambda",
"_",
",",
"y",
":",
"y",
"(",
")",
",",
"seq",
")",
"except",
"TypeError",
"as",
"e",
":",
"if",
"text_type",
"(",
"e",
")",
"!=",
"\"reduce() of empty sequence with no init... | Calls each element of sequence to invoke the side effect.
Args:
seq:
Returns: None | [
"Calls",
"each",
"element",
"of",
"sequence",
"to",
"invoke",
"the",
"side",
"effect",
"."
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/collection.py#L128-L141 | train | 48,274 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/validators.py | validate_api_headers | def validate_api_headers(param, value):
"""Validate that API headers is a CSV of k=v pairs."""
# pylint: disable=unused-argument
if not value:
return None
headers = {}
for kv in value.split(","):
try:
k, v = kv.split("=", 1)
k = k.strip()
for bad_header in BAD_API_HEADERS:
if bad_header == k:
raise click.BadParameter(
"%(key)s is not an allowed header" % {"key": bad_header},
param=param,
)
if k in API_HEADER_TRANSFORMS:
transform_func = API_HEADER_TRANSFORMS[k]
v = transform_func(param, v)
except ValueError:
raise click.BadParameter(
"Values need to be a CSV of key=value pairs", param=param
)
headers[k] = v
return headers | python | def validate_api_headers(param, value):
"""Validate that API headers is a CSV of k=v pairs."""
# pylint: disable=unused-argument
if not value:
return None
headers = {}
for kv in value.split(","):
try:
k, v = kv.split("=", 1)
k = k.strip()
for bad_header in BAD_API_HEADERS:
if bad_header == k:
raise click.BadParameter(
"%(key)s is not an allowed header" % {"key": bad_header},
param=param,
)
if k in API_HEADER_TRANSFORMS:
transform_func = API_HEADER_TRANSFORMS[k]
v = transform_func(param, v)
except ValueError:
raise click.BadParameter(
"Values need to be a CSV of key=value pairs", param=param
)
headers[k] = v
return headers | [
"def",
"validate_api_headers",
"(",
"param",
",",
"value",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"value",
":",
"return",
"None",
"headers",
"=",
"{",
"}",
"for",
"kv",
"in",
"value",
".",
"split",
"(",
"\",\"",
")",
":",
"try",
":",
... | Validate that API headers is a CSV of k=v pairs. | [
"Validate",
"that",
"API",
"headers",
"is",
"a",
"CSV",
"of",
"k",
"=",
"v",
"pairs",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L32-L61 | train | 48,275 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/validators.py | validate_slashes | def validate_slashes(param, value, minimum=2, maximum=None, form=None):
"""Ensure that parameter has slashes and minimum parts."""
try:
value = value.split("/")
except ValueError:
value = None
if value:
if len(value) < minimum:
value = None
elif maximum and len(value) > maximum:
value = None
if not value:
form = form or "/".join("VALUE" for _ in range(minimum))
raise click.BadParameter(
"Must be in the form of %(form)s" % {"form": form}, param=param
)
value = [v.strip() for v in value]
if not all(value):
raise click.BadParameter("Individual values cannot be blank", param=param)
return value | python | def validate_slashes(param, value, minimum=2, maximum=None, form=None):
"""Ensure that parameter has slashes and minimum parts."""
try:
value = value.split("/")
except ValueError:
value = None
if value:
if len(value) < minimum:
value = None
elif maximum and len(value) > maximum:
value = None
if not value:
form = form or "/".join("VALUE" for _ in range(minimum))
raise click.BadParameter(
"Must be in the form of %(form)s" % {"form": form}, param=param
)
value = [v.strip() for v in value]
if not all(value):
raise click.BadParameter("Individual values cannot be blank", param=param)
return value | [
"def",
"validate_slashes",
"(",
"param",
",",
"value",
",",
"minimum",
"=",
"2",
",",
"maximum",
"=",
"None",
",",
"form",
"=",
"None",
")",
":",
"try",
":",
"value",
"=",
"value",
".",
"split",
"(",
"\"/\"",
")",
"except",
"ValueError",
":",
"value"... | Ensure that parameter has slashes and minimum parts. | [
"Ensure",
"that",
"parameter",
"has",
"slashes",
"and",
"minimum",
"parts",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L64-L87 | train | 48,276 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/validators.py | validate_page | def validate_page(ctx, param, value):
"""Ensure that a valid value for page is chosen."""
# pylint: disable=unused-argument
if value == 0:
raise click.BadParameter(
"Page is not zero-based, please set a value to 1 or higher.", param=param
)
return value | python | def validate_page(ctx, param, value):
"""Ensure that a valid value for page is chosen."""
# pylint: disable=unused-argument
if value == 0:
raise click.BadParameter(
"Page is not zero-based, please set a value to 1 or higher.", param=param
)
return value | [
"def",
"validate_page",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# pylint: disable=unused-argument",
"if",
"value",
"==",
"0",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"\"Page is not zero-based, please set a value to 1 or higher.\"",
",",
"param",
"=... | Ensure that a valid value for page is chosen. | [
"Ensure",
"that",
"a",
"valid",
"value",
"for",
"page",
"is",
"chosen",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L111-L118 | train | 48,277 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/validators.py | validate_page_size | def validate_page_size(ctx, param, value):
"""Ensure that a valid value for page size is chosen."""
# pylint: disable=unused-argument
if value == 0:
raise click.BadParameter("Page size must be non-zero or unset.", param=param)
return value | python | def validate_page_size(ctx, param, value):
"""Ensure that a valid value for page size is chosen."""
# pylint: disable=unused-argument
if value == 0:
raise click.BadParameter("Page size must be non-zero or unset.", param=param)
return value | [
"def",
"validate_page_size",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# pylint: disable=unused-argument",
"if",
"value",
"==",
"0",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"\"Page size must be non-zero or unset.\"",
",",
"param",
"=",
"param",
"... | Ensure that a valid value for page size is chosen. | [
"Ensure",
"that",
"a",
"valid",
"value",
"for",
"page",
"size",
"is",
"chosen",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/validators.py#L121-L126 | train | 48,278 |
yagays/pybitflyer | pybitflyer/pybitflyer.py | API.getbalance | def getbalance(self, **params):
"""Get Account Asset Balance
API Type
--------
HTTP Private API
Docs
----
https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance
"""
if not all([self.api_key, self.api_secret]):
raise AuthException()
endpoint = "/v1/me/getbalance"
return self.request(endpoint, params=params) | python | def getbalance(self, **params):
"""Get Account Asset Balance
API Type
--------
HTTP Private API
Docs
----
https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance
"""
if not all([self.api_key, self.api_secret]):
raise AuthException()
endpoint = "/v1/me/getbalance"
return self.request(endpoint, params=params) | [
"def",
"getbalance",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"all",
"(",
"[",
"self",
".",
"api_key",
",",
"self",
".",
"api_secret",
"]",
")",
":",
"raise",
"AuthException",
"(",
")",
"endpoint",
"=",
"\"/v1/me/getbalance\"",
"ret... | Get Account Asset Balance
API Type
--------
HTTP Private API
Docs
----
https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance | [
"Get",
"Account",
"Asset",
"Balance"
] | 05858240e5f9e0367b0a397d96b4ced5e55150d9 | https://github.com/yagays/pybitflyer/blob/05858240e5f9e0367b0a397d96b4ced5e55150d9/pybitflyer/pybitflyer.py#L188-L203 | train | 48,279 |
willthames/ansible-inventory-grapher | lib/ansibleinventorygrapher/__init__.py | tidy_all_the_variables | def tidy_all_the_variables(host, inventory_mgr):
''' removes all overridden and inherited variables from hosts
and groups '''
global _vars
_vars = dict()
_vars[host] = inventory_mgr.inventory.get_host_vars(host)
for group in host.get_groups():
remove_inherited_and_overridden_vars(_vars[host], group, inventory_mgr)
remove_inherited_and_overridden_group_vars(group, inventory_mgr)
return _vars | python | def tidy_all_the_variables(host, inventory_mgr):
''' removes all overridden and inherited variables from hosts
and groups '''
global _vars
_vars = dict()
_vars[host] = inventory_mgr.inventory.get_host_vars(host)
for group in host.get_groups():
remove_inherited_and_overridden_vars(_vars[host], group, inventory_mgr)
remove_inherited_and_overridden_group_vars(group, inventory_mgr)
return _vars | [
"def",
"tidy_all_the_variables",
"(",
"host",
",",
"inventory_mgr",
")",
":",
"global",
"_vars",
"_vars",
"=",
"dict",
"(",
")",
"_vars",
"[",
"host",
"]",
"=",
"inventory_mgr",
".",
"inventory",
".",
"get_host_vars",
"(",
"host",
")",
"for",
"group",
"in"... | removes all overridden and inherited variables from hosts
and groups | [
"removes",
"all",
"overridden",
"and",
"inherited",
"variables",
"from",
"hosts",
"and",
"groups"
] | 018908594776486a317ef9ed9293a9ef391fe3e9 | https://github.com/willthames/ansible-inventory-grapher/blob/018908594776486a317ef9ed9293a9ef391fe3e9/lib/ansibleinventorygrapher/__init__.py#L90-L99 | train | 48,280 |
willthames/ansible-inventory-grapher | lib/ansibleinventorygrapher/inventory.py | Inventory24._plugins_inventory | def _plugins_inventory(self, entities):
import os
from ansible.plugins.loader import vars_loader
from ansible.utils.vars import combine_vars
''' merges all entities by inventory source '''
data = {}
for inventory_dir in self.variable_manager._inventory._sources:
if ',' in inventory_dir: # skip host lists
continue
elif not os.path.isdir(inventory_dir): # always pass 'inventory directory'
inventory_dir = os.path.dirname(inventory_dir)
for plugin in vars_loader.all():
data = combine_vars(data, self._get_plugin_vars(plugin, inventory_dir, entities))
return data | python | def _plugins_inventory(self, entities):
import os
from ansible.plugins.loader import vars_loader
from ansible.utils.vars import combine_vars
''' merges all entities by inventory source '''
data = {}
for inventory_dir in self.variable_manager._inventory._sources:
if ',' in inventory_dir: # skip host lists
continue
elif not os.path.isdir(inventory_dir): # always pass 'inventory directory'
inventory_dir = os.path.dirname(inventory_dir)
for plugin in vars_loader.all():
data = combine_vars(data, self._get_plugin_vars(plugin, inventory_dir, entities))
return data | [
"def",
"_plugins_inventory",
"(",
"self",
",",
"entities",
")",
":",
"import",
"os",
"from",
"ansible",
".",
"plugins",
".",
"loader",
"import",
"vars_loader",
"from",
"ansible",
".",
"utils",
".",
"vars",
"import",
"combine_vars",
"data",
"=",
"{",
"}",
"... | merges all entities by inventory source | [
"merges",
"all",
"entities",
"by",
"inventory",
"source"
] | 018908594776486a317ef9ed9293a9ef391fe3e9 | https://github.com/willthames/ansible-inventory-grapher/blob/018908594776486a317ef9ed9293a9ef391fe3e9/lib/ansibleinventorygrapher/inventory.py#L121-L135 | train | 48,281 |
thelabnyc/wagtail_blog | blog/management/commands/wordpress_to_wagtail.py | Command.handle | def handle(self, *args, **options):
"""gets data from WordPress site"""
# TODO: refactor these with .get
if 'username' in options:
self.username = options['username']
else:
self.username = None
if 'password' in options:
self.password = options['password']
else:
self.password = None
self.xml_path = options.get('xml')
self.url = options.get('url')
try:
blog_index = BlogIndexPage.objects.get(
title__icontains=options['blog_index'])
except BlogIndexPage.DoesNotExist:
raise CommandError("Incorrect blog index title - have you created it?")
if self.url == "just_testing":
with open('test-data.json') as test_json:
posts = json.load(test_json)
elif self.xml_path:
try:
import lxml
from blog.wp_xml_parser import XML_parser
except ImportError as e:
print("You must have lxml installed to run xml imports."
" Run `pip install lxml`.")
raise e
self.xml_parser = XML_parser(self.xml_path)
posts = self.xml_parser.get_posts_data()
else:
posts = self.get_posts_data(self.url)
self.should_import_comments = options.get('import_comments')
self.create_blog_pages(posts, blog_index) | python | def handle(self, *args, **options):
"""gets data from WordPress site"""
# TODO: refactor these with .get
if 'username' in options:
self.username = options['username']
else:
self.username = None
if 'password' in options:
self.password = options['password']
else:
self.password = None
self.xml_path = options.get('xml')
self.url = options.get('url')
try:
blog_index = BlogIndexPage.objects.get(
title__icontains=options['blog_index'])
except BlogIndexPage.DoesNotExist:
raise CommandError("Incorrect blog index title - have you created it?")
if self.url == "just_testing":
with open('test-data.json') as test_json:
posts = json.load(test_json)
elif self.xml_path:
try:
import lxml
from blog.wp_xml_parser import XML_parser
except ImportError as e:
print("You must have lxml installed to run xml imports."
" Run `pip install lxml`.")
raise e
self.xml_parser = XML_parser(self.xml_path)
posts = self.xml_parser.get_posts_data()
else:
posts = self.get_posts_data(self.url)
self.should_import_comments = options.get('import_comments')
self.create_blog_pages(posts, blog_index) | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"# TODO: refactor these with .get",
"if",
"'username'",
"in",
"options",
":",
"self",
".",
"username",
"=",
"options",
"[",
"'username'",
"]",
"else",
":",
"self",
".",
"... | gets data from WordPress site | [
"gets",
"data",
"from",
"WordPress",
"site"
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L64-L99 | train | 48,282 |
thelabnyc/wagtail_blog | blog/management/commands/wordpress_to_wagtail.py | Command.create_images_from_urls_in_content | def create_images_from_urls_in_content(self, body):
"""create Image objects and transfer image files to media root"""
soup = BeautifulSoup(body, "html5lib")
for img in soup.findAll('img'):
old_url = img['src']
if 'width' in img:
width = img['width']
if 'height' in img:
height = img['height']
else:
width = 100
height = 100
path, file_ = os.path.split(img['src'])
if not img['src']:
continue # Blank image
if img['src'].startswith('data:'):
continue # Embedded image
try:
remote_image = urllib.request.urlretrieve(
self.prepare_url(img['src']))
except (urllib.error.HTTPError,
urllib.error.URLError,
UnicodeEncodeError,
ValueError):
print("Unable to import " + img['src'])
continue
image = Image(title=file_, width=width, height=height)
try:
image.file.save(file_, File(open(remote_image[0], 'rb')))
image.save()
new_url = image.file.url
body = body.replace(old_url, new_url)
body = self.convert_html_entities(body)
except TypeError:
print("Unable to import image {}".format(remote_image[0]))
return body | python | def create_images_from_urls_in_content(self, body):
"""create Image objects and transfer image files to media root"""
soup = BeautifulSoup(body, "html5lib")
for img in soup.findAll('img'):
old_url = img['src']
if 'width' in img:
width = img['width']
if 'height' in img:
height = img['height']
else:
width = 100
height = 100
path, file_ = os.path.split(img['src'])
if not img['src']:
continue # Blank image
if img['src'].startswith('data:'):
continue # Embedded image
try:
remote_image = urllib.request.urlretrieve(
self.prepare_url(img['src']))
except (urllib.error.HTTPError,
urllib.error.URLError,
UnicodeEncodeError,
ValueError):
print("Unable to import " + img['src'])
continue
image = Image(title=file_, width=width, height=height)
try:
image.file.save(file_, File(open(remote_image[0], 'rb')))
image.save()
new_url = image.file.url
body = body.replace(old_url, new_url)
body = self.convert_html_entities(body)
except TypeError:
print("Unable to import image {}".format(remote_image[0]))
return body | [
"def",
"create_images_from_urls_in_content",
"(",
"self",
",",
"body",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"body",
",",
"\"html5lib\"",
")",
"for",
"img",
"in",
"soup",
".",
"findAll",
"(",
"'img'",
")",
":",
"old_url",
"=",
"img",
"[",
"'src'",
... | create Image objects and transfer image files to media root | [
"create",
"Image",
"objects",
"and",
"transfer",
"image",
"files",
"to",
"media",
"root"
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L159-L194 | train | 48,283 |
thelabnyc/wagtail_blog | blog/management/commands/wordpress_to_wagtail.py | Command.lookup_comment_by_wordpress_id | def lookup_comment_by_wordpress_id(self, comment_id, comments):
""" Returns Django comment object with this wordpress id """
for comment in comments:
if comment.wordpress_id == comment_id:
return comment | python | def lookup_comment_by_wordpress_id(self, comment_id, comments):
""" Returns Django comment object with this wordpress id """
for comment in comments:
if comment.wordpress_id == comment_id:
return comment | [
"def",
"lookup_comment_by_wordpress_id",
"(",
"self",
",",
"comment_id",
",",
"comments",
")",
":",
"for",
"comment",
"in",
"comments",
":",
"if",
"comment",
".",
"wordpress_id",
"==",
"comment_id",
":",
"return",
"comment"
] | Returns Django comment object with this wordpress id | [
"Returns",
"Django",
"comment",
"object",
"with",
"this",
"wordpress",
"id"
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L223-L227 | train | 48,284 |
thelabnyc/wagtail_blog | blog/management/commands/wordpress_to_wagtail.py | Command.create_blog_pages | def create_blog_pages(self, posts, blog_index, *args, **options):
"""create Blog post entries from wordpress data"""
for post in posts:
post_id = post.get('ID')
title = post.get('title')
if title:
new_title = self.convert_html_entities(title)
title = new_title
slug = post.get('slug')
description = post.get('description')
if description:
description = self.convert_html_entities(description)
body = post.get('content')
if not "<p>" in body:
body = linebreaks(body)
# get image info from content and create image objects
body = self.create_images_from_urls_in_content(body)
# author/user data
author = post.get('author')
user = self.create_user(author)
categories = post.get('terms')
# format the date
date = post.get('date')[:10]
try:
new_entry = BlogPage.objects.get(slug=slug)
new_entry.title = title
new_entry.body = body
new_entry.owner = user
new_entry.save()
except BlogPage.DoesNotExist:
new_entry = blog_index.add_child(instance=BlogPage(
title=title, slug=slug, search_description="description",
date=date, body=body, owner=user))
featured_image = post.get('featured_image')
if featured_image is not None:
title = post['featured_image']['title']
source = post['featured_image']['source']
path, file_ = os.path.split(source)
source = source.replace('stage.swoon', 'swoon')
try:
remote_image = urllib.request.urlretrieve(
self.prepare_url(source))
width = 640
height = 290
header_image = Image(title=title, width=width, height=height)
header_image.file.save(
file_, File(open(remote_image[0], 'rb')))
header_image.save()
except UnicodeEncodeError:
header_image = None
print('unable to set header image {}'.format(source))
else:
header_image = None
new_entry.header_image = header_image
new_entry.save()
if categories:
self.create_categories_and_tags(new_entry, categories)
if self.should_import_comments:
self.import_comments(post_id, slug) | python | def create_blog_pages(self, posts, blog_index, *args, **options):
"""create Blog post entries from wordpress data"""
for post in posts:
post_id = post.get('ID')
title = post.get('title')
if title:
new_title = self.convert_html_entities(title)
title = new_title
slug = post.get('slug')
description = post.get('description')
if description:
description = self.convert_html_entities(description)
body = post.get('content')
if not "<p>" in body:
body = linebreaks(body)
# get image info from content and create image objects
body = self.create_images_from_urls_in_content(body)
# author/user data
author = post.get('author')
user = self.create_user(author)
categories = post.get('terms')
# format the date
date = post.get('date')[:10]
try:
new_entry = BlogPage.objects.get(slug=slug)
new_entry.title = title
new_entry.body = body
new_entry.owner = user
new_entry.save()
except BlogPage.DoesNotExist:
new_entry = blog_index.add_child(instance=BlogPage(
title=title, slug=slug, search_description="description",
date=date, body=body, owner=user))
featured_image = post.get('featured_image')
if featured_image is not None:
title = post['featured_image']['title']
source = post['featured_image']['source']
path, file_ = os.path.split(source)
source = source.replace('stage.swoon', 'swoon')
try:
remote_image = urllib.request.urlretrieve(
self.prepare_url(source))
width = 640
height = 290
header_image = Image(title=title, width=width, height=height)
header_image.file.save(
file_, File(open(remote_image[0], 'rb')))
header_image.save()
except UnicodeEncodeError:
header_image = None
print('unable to set header image {}'.format(source))
else:
header_image = None
new_entry.header_image = header_image
new_entry.save()
if categories:
self.create_categories_and_tags(new_entry, categories)
if self.should_import_comments:
self.import_comments(post_id, slug) | [
"def",
"create_blog_pages",
"(",
"self",
",",
"posts",
",",
"blog_index",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"for",
"post",
"in",
"posts",
":",
"post_id",
"=",
"post",
".",
"get",
"(",
"'ID'",
")",
"title",
"=",
"post",
".",
"get... | create Blog post entries from wordpress data | [
"create",
"Blog",
"post",
"entries",
"from",
"wordpress",
"data"
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/management/commands/wordpress_to_wagtail.py#L327-L388 | train | 48,285 |
thelabnyc/wagtail_blog | blog/utils.py | unique_slugify | def unique_slugify(instance, value, slug_field_name='slug', queryset=None,
slug_separator='-'):
"""
Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check against for uniqueness).
``queryset`` usually doesn't need to be explicitly provided - it'll default
to using the ``.all()`` queryset from the model's default manager.
"""
slug_field = instance._meta.get_field(slug_field_name)
slug = getattr(instance, slug_field.attname)
slug_len = slug_field.max_length
# Sort out the initial slug, limiting its length if necessary.
slug = slugify(value)
if slug_len:
slug = slug[:slug_len]
slug = _slug_strip(slug, slug_separator)
original_slug = slug
# Create the queryset if one wasn't explicitly provided and exclude the
# current instance from the queryset.
if queryset is None:
queryset = instance.__class__._default_manager.all()
if instance.pk:
queryset = queryset.exclude(pk=instance.pk)
# Find a unique slug. If one matches, at '-2' to the end and try again
# (then '-3', etc).
next = 2
while not slug or queryset.filter(**{slug_field_name: slug}):
slug = original_slug
end = '%s%s' % (slug_separator, next)
if slug_len and len(slug) + len(end) > slug_len:
slug = slug[:slug_len-len(end)]
slug = _slug_strip(slug, slug_separator)
slug = '%s%s' % (slug, end)
next += 1
setattr(instance, slug_field.attname, slug) | python | def unique_slugify(instance, value, slug_field_name='slug', queryset=None,
slug_separator='-'):
"""
Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check against for uniqueness).
``queryset`` usually doesn't need to be explicitly provided - it'll default
to using the ``.all()`` queryset from the model's default manager.
"""
slug_field = instance._meta.get_field(slug_field_name)
slug = getattr(instance, slug_field.attname)
slug_len = slug_field.max_length
# Sort out the initial slug, limiting its length if necessary.
slug = slugify(value)
if slug_len:
slug = slug[:slug_len]
slug = _slug_strip(slug, slug_separator)
original_slug = slug
# Create the queryset if one wasn't explicitly provided and exclude the
# current instance from the queryset.
if queryset is None:
queryset = instance.__class__._default_manager.all()
if instance.pk:
queryset = queryset.exclude(pk=instance.pk)
# Find a unique slug. If one matches, at '-2' to the end and try again
# (then '-3', etc).
next = 2
while not slug or queryset.filter(**{slug_field_name: slug}):
slug = original_slug
end = '%s%s' % (slug_separator, next)
if slug_len and len(slug) + len(end) > slug_len:
slug = slug[:slug_len-len(end)]
slug = _slug_strip(slug, slug_separator)
slug = '%s%s' % (slug, end)
next += 1
setattr(instance, slug_field.attname, slug) | [
"def",
"unique_slugify",
"(",
"instance",
",",
"value",
",",
"slug_field_name",
"=",
"'slug'",
",",
"queryset",
"=",
"None",
",",
"slug_separator",
"=",
"'-'",
")",
":",
"slug_field",
"=",
"instance",
".",
"_meta",
".",
"get_field",
"(",
"slug_field_name",
"... | Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check against for uniqueness).
``queryset`` usually doesn't need to be explicitly provided - it'll default
to using the ``.all()`` queryset from the model's default manager. | [
"Calculates",
"and",
"stores",
"a",
"unique",
"slug",
"of",
"value",
"for",
"an",
"instance",
"."
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/utils.py#L6-L48 | train | 48,286 |
thelabnyc/wagtail_blog | blog/utils.py | _slug_strip | def _slug_strip(value, separator='-'):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator.
"""
separator = separator or ''
if separator == '-' or not separator:
re_sep = '-'
else:
re_sep = '(?:-|%s)' % re.escape(separator)
# Remove multiple instances and if an alternate separator is provided,
# replace the default '-' separator.
if separator != re_sep:
value = re.sub('%s+' % re_sep, separator, value)
# Remove separator from the beginning and end of the slug.
if separator:
if separator != '-':
re_sep = re.escape(separator)
value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)
return value | python | def _slug_strip(value, separator='-'):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator.
"""
separator = separator or ''
if separator == '-' or not separator:
re_sep = '-'
else:
re_sep = '(?:-|%s)' % re.escape(separator)
# Remove multiple instances and if an alternate separator is provided,
# replace the default '-' separator.
if separator != re_sep:
value = re.sub('%s+' % re_sep, separator, value)
# Remove separator from the beginning and end of the slug.
if separator:
if separator != '-':
re_sep = re.escape(separator)
value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)
return value | [
"def",
"_slug_strip",
"(",
"value",
",",
"separator",
"=",
"'-'",
")",
":",
"separator",
"=",
"separator",
"or",
"''",
"if",
"separator",
"==",
"'-'",
"or",
"not",
"separator",
":",
"re_sep",
"=",
"'-'",
"else",
":",
"re_sep",
"=",
"'(?:-|%s)'",
"%",
"... | Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator. | [
"Cleans",
"up",
"a",
"slug",
"by",
"removing",
"slug",
"separator",
"characters",
"that",
"occur",
"at",
"the",
"beginning",
"or",
"end",
"of",
"a",
"slug",
"."
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/utils.py#L51-L73 | train | 48,287 |
thelabnyc/wagtail_blog | blog/abstract.py | limit_author_choices | def limit_author_choices():
""" Limit choices in blog author field based on config settings """
LIMIT_AUTHOR_CHOICES = getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP', None)
if LIMIT_AUTHOR_CHOICES:
if isinstance(LIMIT_AUTHOR_CHOICES, str):
limit = Q(groups__name=LIMIT_AUTHOR_CHOICES)
else:
limit = Q()
for s in LIMIT_AUTHOR_CHOICES:
limit = limit | Q(groups__name=s)
if getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_ADMIN', False):
limit = limit | Q(is_staff=True)
else:
limit = {'is_staff': True}
return limit | python | def limit_author_choices():
""" Limit choices in blog author field based on config settings """
LIMIT_AUTHOR_CHOICES = getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP', None)
if LIMIT_AUTHOR_CHOICES:
if isinstance(LIMIT_AUTHOR_CHOICES, str):
limit = Q(groups__name=LIMIT_AUTHOR_CHOICES)
else:
limit = Q()
for s in LIMIT_AUTHOR_CHOICES:
limit = limit | Q(groups__name=s)
if getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_ADMIN', False):
limit = limit | Q(is_staff=True)
else:
limit = {'is_staff': True}
return limit | [
"def",
"limit_author_choices",
"(",
")",
":",
"LIMIT_AUTHOR_CHOICES",
"=",
"getattr",
"(",
"settings",
",",
"'BLOG_LIMIT_AUTHOR_CHOICES_GROUP'",
",",
"None",
")",
"if",
"LIMIT_AUTHOR_CHOICES",
":",
"if",
"isinstance",
"(",
"LIMIT_AUTHOR_CHOICES",
",",
"str",
")",
":... | Limit choices in blog author field based on config settings | [
"Limit",
"choices",
"in",
"blog",
"author",
"field",
"based",
"on",
"config",
"settings"
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/abstract.py#L95-L109 | train | 48,288 |
thelabnyc/wagtail_blog | blog/models.py | get_blog_context | def get_blog_context(context):
""" Get context data useful on all blog related pages """
context['authors'] = get_user_model().objects.filter(
owned_pages__live=True,
owned_pages__content_type__model='blogpage'
).annotate(Count('owned_pages')).order_by('-owned_pages__count')
context['all_categories'] = BlogCategory.objects.all()
context['root_categories'] = BlogCategory.objects.filter(
parent=None,
).prefetch_related(
'children',
).annotate(
blog_count=Count('blogpage'),
)
return context | python | def get_blog_context(context):
""" Get context data useful on all blog related pages """
context['authors'] = get_user_model().objects.filter(
owned_pages__live=True,
owned_pages__content_type__model='blogpage'
).annotate(Count('owned_pages')).order_by('-owned_pages__count')
context['all_categories'] = BlogCategory.objects.all()
context['root_categories'] = BlogCategory.objects.filter(
parent=None,
).prefetch_related(
'children',
).annotate(
blog_count=Count('blogpage'),
)
return context | [
"def",
"get_blog_context",
"(",
"context",
")",
":",
"context",
"[",
"'authors'",
"]",
"=",
"get_user_model",
"(",
")",
".",
"objects",
".",
"filter",
"(",
"owned_pages__live",
"=",
"True",
",",
"owned_pages__content_type__model",
"=",
"'blogpage'",
")",
".",
... | Get context data useful on all blog related pages | [
"Get",
"context",
"data",
"useful",
"on",
"all",
"blog",
"related",
"pages"
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/models.py#L118-L132 | train | 48,289 |
thelabnyc/wagtail_blog | blog/wp_xml_parser.py | XML_parser.item_dict | def item_dict(self, item):
"""
create a default dict of values, including
category and tag lookup
"""
# mocking wierd JSON structure
ret_dict = {"terms":{"category":[],"post_tag":[]}}
for e in item:
# is it a category or tag??
if "category" in e.tag:
# get details
slug = e.attrib["nicename"]
name = htmlparser.unescape(e.text)
# lookup the category or create one
cat_dict = self.category_dict.get(slug) or {"slug":slug,
"name":name,
"taxonomy":"category"}
ret_dict['terms']['category'].append(cat_dict)
elif e.tag[-3:] == 'tag':
# get details
slug = e.attrib.get("tag_slug")
name = htmlparser.unescape(e.text)
# lookup the tag or create one
tag_dict = self.tags_dict.get(slug) or {"slug":slug,
"name":name,
"taxonomy":"post_tag"}
ret_dict['terms']['post_tag'].append(tag_dict)
# else use tagname:tag inner test
else:
ret_dict[e.tag] = e.text
# remove empty accumulators
empty_keys = [k for k,v in ret_dict["terms"].items() if not v]
for k in empty_keys:
ret_dict["terms"].pop(k)
return ret_dict | python | def item_dict(self, item):
"""
create a default dict of values, including
category and tag lookup
"""
# mocking wierd JSON structure
ret_dict = {"terms":{"category":[],"post_tag":[]}}
for e in item:
# is it a category or tag??
if "category" in e.tag:
# get details
slug = e.attrib["nicename"]
name = htmlparser.unescape(e.text)
# lookup the category or create one
cat_dict = self.category_dict.get(slug) or {"slug":slug,
"name":name,
"taxonomy":"category"}
ret_dict['terms']['category'].append(cat_dict)
elif e.tag[-3:] == 'tag':
# get details
slug = e.attrib.get("tag_slug")
name = htmlparser.unescape(e.text)
# lookup the tag or create one
tag_dict = self.tags_dict.get(slug) or {"slug":slug,
"name":name,
"taxonomy":"post_tag"}
ret_dict['terms']['post_tag'].append(tag_dict)
# else use tagname:tag inner test
else:
ret_dict[e.tag] = e.text
# remove empty accumulators
empty_keys = [k for k,v in ret_dict["terms"].items() if not v]
for k in empty_keys:
ret_dict["terms"].pop(k)
return ret_dict | [
"def",
"item_dict",
"(",
"self",
",",
"item",
")",
":",
"# mocking wierd JSON structure",
"ret_dict",
"=",
"{",
"\"terms\"",
":",
"{",
"\"category\"",
":",
"[",
"]",
",",
"\"post_tag\"",
":",
"[",
"]",
"}",
"}",
"for",
"e",
"in",
"item",
":",
"# is it a ... | create a default dict of values, including
category and tag lookup | [
"create",
"a",
"default",
"dict",
"of",
"values",
"including",
"category",
"and",
"tag",
"lookup"
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L93-L129 | train | 48,290 |
thelabnyc/wagtail_blog | blog/wp_xml_parser.py | XML_parser.convert_date | def convert_date(d, custom_date_string=None, fallback=None):
"""
for whatever reason, sometimes WP XML has unintelligible
datetime strings for pubDate.
In this case default to custom_date_string or today
Use fallback in case a secondary date string is available.
Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000'
shows up.
>>> xp = XML_parser
>>> xp.convert_date("Mon, 30 Mar 2015 11:11:11 +0000")
'2015-03-30'
"""
if d == 'Mon, 30 Nov -0001 00:00:00 +0000' and fallback:
d = fallback
try:
date = time.strftime("%Y-%m-%d", time.strptime(d, '%a, %d %b %Y %H:%M:%S %z'))
except ValueError:
date = time.strftime("%Y-%m-%d", time.strptime(d, '%Y-%m-%d %H:%M:%S'))
except ValueError:
date = custom_date_string or datetime.datetime.today().strftime("%Y-%m-%d")
return date | python | def convert_date(d, custom_date_string=None, fallback=None):
"""
for whatever reason, sometimes WP XML has unintelligible
datetime strings for pubDate.
In this case default to custom_date_string or today
Use fallback in case a secondary date string is available.
Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000'
shows up.
>>> xp = XML_parser
>>> xp.convert_date("Mon, 30 Mar 2015 11:11:11 +0000")
'2015-03-30'
"""
if d == 'Mon, 30 Nov -0001 00:00:00 +0000' and fallback:
d = fallback
try:
date = time.strftime("%Y-%m-%d", time.strptime(d, '%a, %d %b %Y %H:%M:%S %z'))
except ValueError:
date = time.strftime("%Y-%m-%d", time.strptime(d, '%Y-%m-%d %H:%M:%S'))
except ValueError:
date = custom_date_string or datetime.datetime.today().strftime("%Y-%m-%d")
return date | [
"def",
"convert_date",
"(",
"d",
",",
"custom_date_string",
"=",
"None",
",",
"fallback",
"=",
"None",
")",
":",
"if",
"d",
"==",
"'Mon, 30 Nov -0001 00:00:00 +0000'",
"and",
"fallback",
":",
"d",
"=",
"fallback",
"try",
":",
"date",
"=",
"time",
".",
"str... | for whatever reason, sometimes WP XML has unintelligible
datetime strings for pubDate.
In this case default to custom_date_string or today
Use fallback in case a secondary date string is available.
Incidentally, somehow the string 'Mon, 30 Nov -0001 00:00:00 +0000'
shows up.
>>> xp = XML_parser
>>> xp.convert_date("Mon, 30 Mar 2015 11:11:11 +0000")
'2015-03-30' | [
"for",
"whatever",
"reason",
"sometimes",
"WP",
"XML",
"has",
"unintelligible",
"datetime",
"strings",
"for",
"pubDate",
".",
"In",
"this",
"case",
"default",
"to",
"custom_date_string",
"or",
"today",
"Use",
"fallback",
"in",
"case",
"a",
"secondary",
"date",
... | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L132-L153 | train | 48,291 |
thelabnyc/wagtail_blog | blog/wp_xml_parser.py | XML_parser.translate_item | def translate_item(self, item_dict):
"""cleanup item keys to match API json format"""
if not item_dict.get('title'):
return None
# Skip attachments
if item_dict.get('{wp}post_type', None) == 'attachment':
return None
ret_dict = {}
# slugify post title if no slug exists
ret_dict['slug']= item_dict.get('{wp}post_name') or re.sub(item_dict['title'],' ','-')
ret_dict['ID']= item_dict['guid']
ret_dict['title']= item_dict['title']
ret_dict['description']= item_dict['description']
ret_dict['content']= item_dict['{content}encoded']
# fake user object
ret_dict['author']= {'username':item_dict['{dc}creator'],
'first_name':'',
'last_name':''}
ret_dict['terms']= item_dict.get('terms')
ret_dict['date']= self.convert_date(
item_dict['pubDate'],
fallback=item_dict.get('{wp}post_date','')
)
return ret_dict | python | def translate_item(self, item_dict):
"""cleanup item keys to match API json format"""
if not item_dict.get('title'):
return None
# Skip attachments
if item_dict.get('{wp}post_type', None) == 'attachment':
return None
ret_dict = {}
# slugify post title if no slug exists
ret_dict['slug']= item_dict.get('{wp}post_name') or re.sub(item_dict['title'],' ','-')
ret_dict['ID']= item_dict['guid']
ret_dict['title']= item_dict['title']
ret_dict['description']= item_dict['description']
ret_dict['content']= item_dict['{content}encoded']
# fake user object
ret_dict['author']= {'username':item_dict['{dc}creator'],
'first_name':'',
'last_name':''}
ret_dict['terms']= item_dict.get('terms')
ret_dict['date']= self.convert_date(
item_dict['pubDate'],
fallback=item_dict.get('{wp}post_date','')
)
return ret_dict | [
"def",
"translate_item",
"(",
"self",
",",
"item_dict",
")",
":",
"if",
"not",
"item_dict",
".",
"get",
"(",
"'title'",
")",
":",
"return",
"None",
"# Skip attachments",
"if",
"item_dict",
".",
"get",
"(",
"'{wp}post_type'",
",",
"None",
")",
"==",
"'attac... | cleanup item keys to match API json format | [
"cleanup",
"item",
"keys",
"to",
"match",
"API",
"json",
"format"
] | 7e092c02d10ec427c9a2c4b5dcbe910d88c628cf | https://github.com/thelabnyc/wagtail_blog/blob/7e092c02d10ec427c9a2c4b5dcbe910d88c628cf/blog/wp_xml_parser.py#L155-L178 | train | 48,292 |
ajenhl/tacl | tacl/highlighter.py | HighlightReport._format_content | def _format_content(self, content):
"""Returns `content` with consecutive spaces converted to non-break
spaces, and linebreak converted into HTML br elements.
:param content: text to format
:type content: `str`
:rtype: `str`
"""
content = re.sub(r'\n', '<br/>\n', content)
content = re.sub(r' ', '  ', content)
content = re.sub(r'  ', '  ', content)
return content | python | def _format_content(self, content):
"""Returns `content` with consecutive spaces converted to non-break
spaces, and linebreak converted into HTML br elements.
:param content: text to format
:type content: `str`
:rtype: `str`
"""
content = re.sub(r'\n', '<br/>\n', content)
content = re.sub(r' ', '  ', content)
content = re.sub(r'  ', '  ', content)
return content | [
"def",
"_format_content",
"(",
"self",
",",
"content",
")",
":",
"content",
"=",
"re",
".",
"sub",
"(",
"r'\\n'",
",",
"'<br/>\\n'",
",",
"content",
")",
"content",
"=",
"re",
".",
"sub",
"(",
"r' '",
",",
"'  '",
",",
"content",
")",
"conte... | Returns `content` with consecutive spaces converted to non-break
spaces, and linebreak converted into HTML br elements.
:param content: text to format
:type content: `str`
:rtype: `str` | [
"Returns",
"content",
"with",
"consecutive",
"spaces",
"converted",
"to",
"non",
"-",
"break",
"spaces",
"and",
"linebreak",
"converted",
"into",
"HTML",
"br",
"elements",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L24-L36 | train | 48,293 |
ajenhl/tacl | tacl/highlighter.py | HighlightReport._prepare_text | def _prepare_text(self, text):
"""Returns `text` with each consituent token wrapped in HTML markup
for later match annotation.
:param text: text to be marked up
:type text: `str`
:rtype: `str`
"""
# Remove characters that should be escaped for XML input (but
# which cause problems when escaped, since they become
# tokens).
text = re.sub(r'[<>&]', '', text)
pattern = r'({})'.format(self._tokenizer.pattern)
return re.sub(pattern, self._base_token_markup, text) | python | def _prepare_text(self, text):
"""Returns `text` with each consituent token wrapped in HTML markup
for later match annotation.
:param text: text to be marked up
:type text: `str`
:rtype: `str`
"""
# Remove characters that should be escaped for XML input (but
# which cause problems when escaped, since they become
# tokens).
text = re.sub(r'[<>&]', '', text)
pattern = r'({})'.format(self._tokenizer.pattern)
return re.sub(pattern, self._base_token_markup, text) | [
"def",
"_prepare_text",
"(",
"self",
",",
"text",
")",
":",
"# Remove characters that should be escaped for XML input (but",
"# which cause problems when escaped, since they become",
"# tokens).",
"text",
"=",
"re",
".",
"sub",
"(",
"r'[<>&]'",
",",
"''",
",",
"text",
")"... | Returns `text` with each consituent token wrapped in HTML markup
for later match annotation.
:param text: text to be marked up
:type text: `str`
:rtype: `str` | [
"Returns",
"text",
"with",
"each",
"consituent",
"token",
"wrapped",
"in",
"HTML",
"markup",
"for",
"later",
"match",
"annotation",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L52-L66 | train | 48,294 |
ajenhl/tacl | tacl/highlighter.py | NgramHighlightReport.generate | def generate(self, output_dir, work, ngrams, labels, minus_ngrams):
"""Generates HTML reports for each witness to `work`, showing its text
with the n-grams in `ngrams` highlighted.
Any n-grams in `minus_ngrams` have any highlighting of them
(or subsets of them) removed.
:param output_dir: directory to write report to
:type output_dir: `str`
:param work: name of work to highlight
:type work: `str`
:param ngrams: groups of n-grams to highlight
:type ngrams: `list` of `list` of `str`
:param labels: labels for the groups of n-grams
:type labels: `list` of `str`
:param minus_ngrams: n-grams to remove highlighting from
:type minus_ngrams: `list` of `str`
:rtype: `str`
"""
template = self._get_template()
colours = generate_colours(len(ngrams))
for siglum in self._corpus.get_sigla(work):
ngram_data = zip(labels, ngrams)
content = self._generate_base(work, siglum)
for ngrams_group in ngrams:
content = self._highlight(content, ngrams_group, True)
content = self._highlight(content, minus_ngrams, False)
self._ngrams_count = 1
content = self._format_content(content)
report_name = '{}-{}.html'.format(work, siglum)
self._write(work, siglum, content, output_dir, report_name,
template, ngram_data=ngram_data,
minus_ngrams=minus_ngrams, colours=colours) | python | def generate(self, output_dir, work, ngrams, labels, minus_ngrams):
"""Generates HTML reports for each witness to `work`, showing its text
with the n-grams in `ngrams` highlighted.
Any n-grams in `minus_ngrams` have any highlighting of them
(or subsets of them) removed.
:param output_dir: directory to write report to
:type output_dir: `str`
:param work: name of work to highlight
:type work: `str`
:param ngrams: groups of n-grams to highlight
:type ngrams: `list` of `list` of `str`
:param labels: labels for the groups of n-grams
:type labels: `list` of `str`
:param minus_ngrams: n-grams to remove highlighting from
:type minus_ngrams: `list` of `str`
:rtype: `str`
"""
template = self._get_template()
colours = generate_colours(len(ngrams))
for siglum in self._corpus.get_sigla(work):
ngram_data = zip(labels, ngrams)
content = self._generate_base(work, siglum)
for ngrams_group in ngrams:
content = self._highlight(content, ngrams_group, True)
content = self._highlight(content, minus_ngrams, False)
self._ngrams_count = 1
content = self._format_content(content)
report_name = '{}-{}.html'.format(work, siglum)
self._write(work, siglum, content, output_dir, report_name,
template, ngram_data=ngram_data,
minus_ngrams=minus_ngrams, colours=colours) | [
"def",
"generate",
"(",
"self",
",",
"output_dir",
",",
"work",
",",
"ngrams",
",",
"labels",
",",
"minus_ngrams",
")",
":",
"template",
"=",
"self",
".",
"_get_template",
"(",
")",
"colours",
"=",
"generate_colours",
"(",
"len",
"(",
"ngrams",
")",
")",... | Generates HTML reports for each witness to `work`, showing its text
with the n-grams in `ngrams` highlighted.
Any n-grams in `minus_ngrams` have any highlighting of them
(or subsets of them) removed.
:param output_dir: directory to write report to
:type output_dir: `str`
:param work: name of work to highlight
:type work: `str`
:param ngrams: groups of n-grams to highlight
:type ngrams: `list` of `list` of `str`
:param labels: labels for the groups of n-grams
:type labels: `list` of `str`
:param minus_ngrams: n-grams to remove highlighting from
:type minus_ngrams: `list` of `str`
:rtype: `str` | [
"Generates",
"HTML",
"reports",
"for",
"each",
"witness",
"to",
"work",
"showing",
"its",
"text",
"with",
"the",
"n",
"-",
"grams",
"in",
"ngrams",
"highlighted",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L94-L127 | train | 48,295 |
ajenhl/tacl | tacl/highlighter.py | ResultsHighlightReport.generate | def generate(self, output_dir, work, matches_filename):
"""Generates HTML reports showing the text of each witness to `work`
with its matches in `matches` highlighted.
:param output_dir: directory to write report to
:type output_dir: `str`
:param work: name of work to highlight
:type text_name: `str`
:param matches_filename: file containing matches to highlight
:type matches_filename: `str`
:rtype: `str`
"""
template = self._get_template()
matches = pd.read_csv(matches_filename)
for siglum in self._corpus.get_sigla(work):
subm = matches[(matches[constants.WORK_FIELDNAME] != work) |
(matches[constants.SIGLUM_FIELDNAME] != siglum)]
content = self._generate_base(work, siglum)
content = self._highlight(content, subm)
content = self._format_content(content)
text_list = self._generate_text_list(subm)
report_name = '{}-{}.html'.format(work, siglum)
self._write(work, siglum, content, output_dir, report_name,
template, True, text_list=text_list) | python | def generate(self, output_dir, work, matches_filename):
"""Generates HTML reports showing the text of each witness to `work`
with its matches in `matches` highlighted.
:param output_dir: directory to write report to
:type output_dir: `str`
:param work: name of work to highlight
:type text_name: `str`
:param matches_filename: file containing matches to highlight
:type matches_filename: `str`
:rtype: `str`
"""
template = self._get_template()
matches = pd.read_csv(matches_filename)
for siglum in self._corpus.get_sigla(work):
subm = matches[(matches[constants.WORK_FIELDNAME] != work) |
(matches[constants.SIGLUM_FIELDNAME] != siglum)]
content = self._generate_base(work, siglum)
content = self._highlight(content, subm)
content = self._format_content(content)
text_list = self._generate_text_list(subm)
report_name = '{}-{}.html'.format(work, siglum)
self._write(work, siglum, content, output_dir, report_name,
template, True, text_list=text_list) | [
"def",
"generate",
"(",
"self",
",",
"output_dir",
",",
"work",
",",
"matches_filename",
")",
":",
"template",
"=",
"self",
".",
"_get_template",
"(",
")",
"matches",
"=",
"pd",
".",
"read_csv",
"(",
"matches_filename",
")",
"for",
"siglum",
"in",
"self",
... | Generates HTML reports showing the text of each witness to `work`
with its matches in `matches` highlighted.
:param output_dir: directory to write report to
:type output_dir: `str`
:param work: name of work to highlight
:type text_name: `str`
:param matches_filename: file containing matches to highlight
:type matches_filename: `str`
:rtype: `str` | [
"Generates",
"HTML",
"reports",
"showing",
"the",
"text",
"of",
"each",
"witness",
"to",
"work",
"with",
"its",
"matches",
"in",
"matches",
"highlighted",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/highlighter.py#L175-L199 | train | 48,296 |
SuperCowPowers/chains | chains/links/flows.py | print_flow_info | def print_flow_info(flow):
"""Print a summary of the flow information"""
print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']),
len(flow['payload']), repr(flow['payload'])[:30])) | python | def print_flow_info(flow):
"""Print a summary of the flow information"""
print('Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...' % (flow['flow_id'], flow['direction'], len(flow['packet_list']),
len(flow['payload']), repr(flow['payload'])[:30])) | [
"def",
"print_flow_info",
"(",
"flow",
")",
":",
"print",
"(",
"'Flow %s (%s)-- Packets:%d Bytes:%d Payload: %s...'",
"%",
"(",
"flow",
"[",
"'flow_id'",
"]",
",",
"flow",
"[",
"'direction'",
"]",
",",
"len",
"(",
"flow",
"[",
"'packet_list'",
"]",
")",
",",
... | Print a summary of the flow information | [
"Print",
"a",
"summary",
"of",
"the",
"flow",
"information"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/flows.py#L52-L55 | train | 48,297 |
SuperCowPowers/chains | chains/links/flows.py | Flows.packets_to_flows | def packets_to_flows(self):
"""Combine packets into flows"""
# For each packet, place it into either an existing flow or a new flow
for packet in self.input_stream:
# Compute flow tuple and add the packet to the flow
flow_id = flow_utils.flow_tuple(packet)
self._flows[flow_id].add_packet(packet)
# Yield flows that are ready to go
for flow in list(self._flows.values()):
if flow.ready():
flow_info = flow.get_flow()
yield flow_info
del self._flows[flow_info['flow_id']]
# All done so just dump what we have left
print('---- NO MORE INPUT ----')
for flow in sorted(self._flows.values(), key=lambda x: x.meta['start']):
yield flow.get_flow() | python | def packets_to_flows(self):
"""Combine packets into flows"""
# For each packet, place it into either an existing flow or a new flow
for packet in self.input_stream:
# Compute flow tuple and add the packet to the flow
flow_id = flow_utils.flow_tuple(packet)
self._flows[flow_id].add_packet(packet)
# Yield flows that are ready to go
for flow in list(self._flows.values()):
if flow.ready():
flow_info = flow.get_flow()
yield flow_info
del self._flows[flow_info['flow_id']]
# All done so just dump what we have left
print('---- NO MORE INPUT ----')
for flow in sorted(self._flows.values(), key=lambda x: x.meta['start']):
yield flow.get_flow() | [
"def",
"packets_to_flows",
"(",
"self",
")",
":",
"# For each packet, place it into either an existing flow or a new flow",
"for",
"packet",
"in",
"self",
".",
"input_stream",
":",
"# Compute flow tuple and add the packet to the flow",
"flow_id",
"=",
"flow_utils",
".",
"flow_t... | Combine packets into flows | [
"Combine",
"packets",
"into",
"flows"
] | b0227847b0c43083b456f0bae52daee0b62a3e03 | https://github.com/SuperCowPowers/chains/blob/b0227847b0c43083b456f0bae52daee0b62a3e03/chains/links/flows.py#L30-L50 | train | 48,298 |
ajenhl/tacl | tacl/report.py | Report._copy_static_assets | def _copy_static_assets(self, output_dir):
"""Copy assets for the report to `output_dir`.
:param output_dir: directory to output assets to
:type output_dir: `str`
"""
base_directory = 'assets/{}'.format(self._report_name)
for asset in resource_listdir(self._package_name, base_directory):
filename = resource_filename(
self._package_name, '{}/{}'.format(base_directory, asset))
shutil.copy2(filename, output_dir) | python | def _copy_static_assets(self, output_dir):
"""Copy assets for the report to `output_dir`.
:param output_dir: directory to output assets to
:type output_dir: `str`
"""
base_directory = 'assets/{}'.format(self._report_name)
for asset in resource_listdir(self._package_name, base_directory):
filename = resource_filename(
self._package_name, '{}/{}'.format(base_directory, asset))
shutil.copy2(filename, output_dir) | [
"def",
"_copy_static_assets",
"(",
"self",
",",
"output_dir",
")",
":",
"base_directory",
"=",
"'assets/{}'",
".",
"format",
"(",
"self",
".",
"_report_name",
")",
"for",
"asset",
"in",
"resource_listdir",
"(",
"self",
".",
"_package_name",
",",
"base_directory"... | Copy assets for the report to `output_dir`.
:param output_dir: directory to output assets to
:type output_dir: `str` | [
"Copy",
"assets",
"for",
"the",
"report",
"to",
"output_dir",
"."
] | b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2 | https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/report.py#L29-L40 | train | 48,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.