id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
227,900 | tensorflow/mesh | mesh_tensorflow/ops.py | serialize_training_step | def serialize_training_step(features, model_fn, batch_dim, num_splits):
"""Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary of Tensors corresponding to the output dictionary of
model_fn. Each value is either summed across all microbatches (if it
has no batch-dimension), or concatenated across all microbatches to
represent the original batch (if it does have a batch-dimension).
Args:
features: a dictionary of Tensors, each with a batch_dim dimension
model_fn: a function from feature dictionary to output dictionary
output_dictionary must contain "loss"
batch_dim: a Dimension
num_splits: an integer dividing batch_dim.size
Returns:
grads: a list of Tensors corresponding to the gradients on
graph.trainable_variables
outputs: dictionary of output Tensors summed across microbatches
"""
for v in features.values():
mesh = v.mesh
graph = v.graph
microbatch_dim = Dimension("microbatch", num_splits)
smaller_batch_dim = Dimension(batch_dim.name, batch_dim.size // num_splits)
cache = {}
def select(t, microbatch_num):
return gather(
replace_dimensions(t, batch_dim, [smaller_batch_dim, microbatch_dim]),
microbatch_num, microbatch_dim)
def cond_fn(microbatch_num):
return less(microbatch_num, num_splits)
def body_fn(microbatch_num):
"""Body function for mtf.while_loop.
Args:
microbatch_num: a mtf Scalar
Returns:
a list of mtf Tensors
"""
my_features = {}
for k, v in six.iteritems(features):
my_features[k] = select(v, microbatch_num)
outputs = model_fn(my_features)
grads = gradients(
[outputs["loss"]], [v.outputs[0] for v in graph.trainable_variables])
output_keys = outputs.keys()
cache["output_keys"] = output_keys
ret = []
ret.append(microbatch_num + 1)
# The rest of the returned values are "accumulators" that get summed
# across all microbatches.
for t in outputs.values():
if smaller_batch_dim in t.shape:
# The output contains a batch dimension, so we want to concatenate
# across microbatches.
# Here we pad the tensor for each microbatch - summing will complete
# the concatenation.
t = einsum(
[t, one_hot(microbatch_num, microbatch_dim, dtype=t.dtype)],
output_shape=replace_dimensions(
t.shape, smaller_batch_dim,
[smaller_batch_dim, microbatch_dim]))
t = replace_dimensions(
t, [smaller_batch_dim, microbatch_dim], batch_dim)
ret.append(t)
else:
# There is no batch dimension. Sum across all microbatches.
ret.append(t)
# we also want to sum the gradients.
ret.extend(grads)
return ret
while_out = while_loop(
cond_fn, body_fn, [constant(mesh, 0, dtype=tf.int32)],
has_accumulators=True)
num_outputs = len(cache["output_keys"])
combined_outputs = {}
for k, v in zip(cache["output_keys"], while_out[1:1 + num_outputs]):
combined_outputs[k] = v
combined_grads = while_out[1 + num_outputs:]
return combined_grads, combined_outputs | python | def serialize_training_step(features, model_fn, batch_dim, num_splits):
"""Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary of Tensors corresponding to the output dictionary of
model_fn. Each value is either summed across all microbatches (if it
has no batch-dimension), or concatenated across all microbatches to
represent the original batch (if it does have a batch-dimension).
Args:
features: a dictionary of Tensors, each with a batch_dim dimension
model_fn: a function from feature dictionary to output dictionary
output_dictionary must contain "loss"
batch_dim: a Dimension
num_splits: an integer dividing batch_dim.size
Returns:
grads: a list of Tensors corresponding to the gradients on
graph.trainable_variables
outputs: dictionary of output Tensors summed across microbatches
"""
for v in features.values():
mesh = v.mesh
graph = v.graph
microbatch_dim = Dimension("microbatch", num_splits)
smaller_batch_dim = Dimension(batch_dim.name, batch_dim.size // num_splits)
cache = {}
def select(t, microbatch_num):
return gather(
replace_dimensions(t, batch_dim, [smaller_batch_dim, microbatch_dim]),
microbatch_num, microbatch_dim)
def cond_fn(microbatch_num):
return less(microbatch_num, num_splits)
def body_fn(microbatch_num):
"""Body function for mtf.while_loop.
Args:
microbatch_num: a mtf Scalar
Returns:
a list of mtf Tensors
"""
my_features = {}
for k, v in six.iteritems(features):
my_features[k] = select(v, microbatch_num)
outputs = model_fn(my_features)
grads = gradients(
[outputs["loss"]], [v.outputs[0] for v in graph.trainable_variables])
output_keys = outputs.keys()
cache["output_keys"] = output_keys
ret = []
ret.append(microbatch_num + 1)
# The rest of the returned values are "accumulators" that get summed
# across all microbatches.
for t in outputs.values():
if smaller_batch_dim in t.shape:
# The output contains a batch dimension, so we want to concatenate
# across microbatches.
# Here we pad the tensor for each microbatch - summing will complete
# the concatenation.
t = einsum(
[t, one_hot(microbatch_num, microbatch_dim, dtype=t.dtype)],
output_shape=replace_dimensions(
t.shape, smaller_batch_dim,
[smaller_batch_dim, microbatch_dim]))
t = replace_dimensions(
t, [smaller_batch_dim, microbatch_dim], batch_dim)
ret.append(t)
else:
# There is no batch dimension. Sum across all microbatches.
ret.append(t)
# we also want to sum the gradients.
ret.extend(grads)
return ret
while_out = while_loop(
cond_fn, body_fn, [constant(mesh, 0, dtype=tf.int32)],
has_accumulators=True)
num_outputs = len(cache["output_keys"])
combined_outputs = {}
for k, v in zip(cache["output_keys"], while_out[1:1 + num_outputs]):
combined_outputs[k] = v
combined_grads = while_out[1 + num_outputs:]
return combined_grads, combined_outputs | [
"def",
"serialize_training_step",
"(",
"features",
",",
"model_fn",
",",
"batch_dim",
",",
"num_splits",
")",
":",
"for",
"v",
"in",
"features",
".",
"values",
"(",
")",
":",
"mesh",
"=",
"v",
".",
"mesh",
"graph",
"=",
"v",
".",
"graph",
"microbatch_dim",
"=",
"Dimension",
"(",
"\"microbatch\"",
",",
"num_splits",
")",
"smaller_batch_dim",
"=",
"Dimension",
"(",
"batch_dim",
".",
"name",
",",
"batch_dim",
".",
"size",
"//",
"num_splits",
")",
"cache",
"=",
"{",
"}",
"def",
"select",
"(",
"t",
",",
"microbatch_num",
")",
":",
"return",
"gather",
"(",
"replace_dimensions",
"(",
"t",
",",
"batch_dim",
",",
"[",
"smaller_batch_dim",
",",
"microbatch_dim",
"]",
")",
",",
"microbatch_num",
",",
"microbatch_dim",
")",
"def",
"cond_fn",
"(",
"microbatch_num",
")",
":",
"return",
"less",
"(",
"microbatch_num",
",",
"num_splits",
")",
"def",
"body_fn",
"(",
"microbatch_num",
")",
":",
"\"\"\"Body function for mtf.while_loop.\n\n Args:\n microbatch_num: a mtf Scalar\n Returns:\n a list of mtf Tensors\n \"\"\"",
"my_features",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"features",
")",
":",
"my_features",
"[",
"k",
"]",
"=",
"select",
"(",
"v",
",",
"microbatch_num",
")",
"outputs",
"=",
"model_fn",
"(",
"my_features",
")",
"grads",
"=",
"gradients",
"(",
"[",
"outputs",
"[",
"\"loss\"",
"]",
"]",
",",
"[",
"v",
".",
"outputs",
"[",
"0",
"]",
"for",
"v",
"in",
"graph",
".",
"trainable_variables",
"]",
")",
"output_keys",
"=",
"outputs",
".",
"keys",
"(",
")",
"cache",
"[",
"\"output_keys\"",
"]",
"=",
"output_keys",
"ret",
"=",
"[",
"]",
"ret",
".",
"append",
"(",
"microbatch_num",
"+",
"1",
")",
"# The rest of the returned values are \"accumulators\" that get summed",
"# across all microbatches.",
"for",
"t",
"in",
"outputs",
".",
"values",
"(",
")",
":",
"if",
"smaller_batch_dim",
"in",
"t",
".",
"shape",
":",
"# The output contains a batch dimension, so we want to concatenate",
"# across microbatches.",
"# Here we pad the tensor for each microbatch - summing will complete",
"# the concatenation.",
"t",
"=",
"einsum",
"(",
"[",
"t",
",",
"one_hot",
"(",
"microbatch_num",
",",
"microbatch_dim",
",",
"dtype",
"=",
"t",
".",
"dtype",
")",
"]",
",",
"output_shape",
"=",
"replace_dimensions",
"(",
"t",
".",
"shape",
",",
"smaller_batch_dim",
",",
"[",
"smaller_batch_dim",
",",
"microbatch_dim",
"]",
")",
")",
"t",
"=",
"replace_dimensions",
"(",
"t",
",",
"[",
"smaller_batch_dim",
",",
"microbatch_dim",
"]",
",",
"batch_dim",
")",
"ret",
".",
"append",
"(",
"t",
")",
"else",
":",
"# There is no batch dimension. Sum across all microbatches.",
"ret",
".",
"append",
"(",
"t",
")",
"# we also want to sum the gradients.",
"ret",
".",
"extend",
"(",
"grads",
")",
"return",
"ret",
"while_out",
"=",
"while_loop",
"(",
"cond_fn",
",",
"body_fn",
",",
"[",
"constant",
"(",
"mesh",
",",
"0",
",",
"dtype",
"=",
"tf",
".",
"int32",
")",
"]",
",",
"has_accumulators",
"=",
"True",
")",
"num_outputs",
"=",
"len",
"(",
"cache",
"[",
"\"output_keys\"",
"]",
")",
"combined_outputs",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"zip",
"(",
"cache",
"[",
"\"output_keys\"",
"]",
",",
"while_out",
"[",
"1",
":",
"1",
"+",
"num_outputs",
"]",
")",
":",
"combined_outputs",
"[",
"k",
"]",
"=",
"v",
"combined_grads",
"=",
"while_out",
"[",
"1",
"+",
"num_outputs",
":",
"]",
"return",
"combined_grads",
",",
"combined_outputs"
] | Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary of Tensors corresponding to the output dictionary of
model_fn. Each value is either summed across all microbatches (if it
has no batch-dimension), or concatenated across all microbatches to
represent the original batch (if it does have a batch-dimension).
Args:
features: a dictionary of Tensors, each with a batch_dim dimension
model_fn: a function from feature dictionary to output dictionary
output_dictionary must contain "loss"
batch_dim: a Dimension
num_splits: an integer dividing batch_dim.size
Returns:
grads: a list of Tensors corresponding to the gradients on
graph.trainable_variables
outputs: dictionary of output Tensors summed across microbatches | [
"Break",
"the",
"training",
"batch",
"into",
"multiple",
"microbatches",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L5146-L5231 |
227,901 | tensorflow/mesh | mesh_tensorflow/ops.py | Shape.rename_dimension | def rename_dimension(self, old_name, new_name):
"""Returns a copy where one dimension is renamed."""
if old_name not in self.dimension_names:
raise ValueError("Shape %s does not have dimension named %s"
% (self, old_name))
return Shape(
[Dimension(new_name, d.size) if d.name == old_name else d
for d in self.dims]) | python | def rename_dimension(self, old_name, new_name):
"""Returns a copy where one dimension is renamed."""
if old_name not in self.dimension_names:
raise ValueError("Shape %s does not have dimension named %s"
% (self, old_name))
return Shape(
[Dimension(new_name, d.size) if d.name == old_name else d
for d in self.dims]) | [
"def",
"rename_dimension",
"(",
"self",
",",
"old_name",
",",
"new_name",
")",
":",
"if",
"old_name",
"not",
"in",
"self",
".",
"dimension_names",
":",
"raise",
"ValueError",
"(",
"\"Shape %s does not have dimension named %s\"",
"%",
"(",
"self",
",",
"old_name",
")",
")",
"return",
"Shape",
"(",
"[",
"Dimension",
"(",
"new_name",
",",
"d",
".",
"size",
")",
"if",
"d",
".",
"name",
"==",
"old_name",
"else",
"d",
"for",
"d",
"in",
"self",
".",
"dims",
"]",
")"
] | Returns a copy where one dimension is renamed. | [
"Returns",
"a",
"copy",
"where",
"one",
"dimension",
"is",
"renamed",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L163-L170 |
227,902 | tensorflow/mesh | mesh_tensorflow/ops.py | Shape.resize_dimension | def resize_dimension(self, name, new_size):
"""Returns a copy where one dimension has a different size."""
if name not in self.dimension_names:
raise ValueError("Shape %s does not have dimension named %s"
% (self, name))
return Shape(
[Dimension(name, new_size) if d.name == name else d
for d in self.dims]) | python | def resize_dimension(self, name, new_size):
"""Returns a copy where one dimension has a different size."""
if name not in self.dimension_names:
raise ValueError("Shape %s does not have dimension named %s"
% (self, name))
return Shape(
[Dimension(name, new_size) if d.name == name else d
for d in self.dims]) | [
"def",
"resize_dimension",
"(",
"self",
",",
"name",
",",
"new_size",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"dimension_names",
":",
"raise",
"ValueError",
"(",
"\"Shape %s does not have dimension named %s\"",
"%",
"(",
"self",
",",
"name",
")",
")",
"return",
"Shape",
"(",
"[",
"Dimension",
"(",
"name",
",",
"new_size",
")",
"if",
"d",
".",
"name",
"==",
"name",
"else",
"d",
"for",
"d",
"in",
"self",
".",
"dims",
"]",
")"
] | Returns a copy where one dimension has a different size. | [
"Returns",
"a",
"copy",
"where",
"one",
"dimension",
"has",
"a",
"different",
"size",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L172-L179 |
227,903 | tensorflow/mesh | mesh_tensorflow/ops.py | LayoutRules.tensor_layout | def tensor_layout(self, tensor_shape, mesh_shape):
"""Computes TensorLayout given a Tensor Shape and a Mesh Shape.
Args:
tensor_shape: Shape.
mesh_shape: Shape.
Returns:
TensorLayout.
Raises:
ValueError: If two Tensor Dimensions map to the same Mesh Dimensions.
"""
ret = [self.tensor_dimension_to_mesh_axis(d, mesh_shape)
for d in tensor_shape]
not_nones = [a for a in ret if a is not None]
if len(not_nones) != len(set(not_nones)):
raise ValueError(
"Two Tensor Dimensions may not map to the same Mesh Dimension:"
" layout=%s tensor_shape=%s mesh_shape=%s " %
(self, tensor_shape, mesh_shape))
return TensorLayout(ret) | python | def tensor_layout(self, tensor_shape, mesh_shape):
"""Computes TensorLayout given a Tensor Shape and a Mesh Shape.
Args:
tensor_shape: Shape.
mesh_shape: Shape.
Returns:
TensorLayout.
Raises:
ValueError: If two Tensor Dimensions map to the same Mesh Dimensions.
"""
ret = [self.tensor_dimension_to_mesh_axis(d, mesh_shape)
for d in tensor_shape]
not_nones = [a for a in ret if a is not None]
if len(not_nones) != len(set(not_nones)):
raise ValueError(
"Two Tensor Dimensions may not map to the same Mesh Dimension:"
" layout=%s tensor_shape=%s mesh_shape=%s " %
(self, tensor_shape, mesh_shape))
return TensorLayout(ret) | [
"def",
"tensor_layout",
"(",
"self",
",",
"tensor_shape",
",",
"mesh_shape",
")",
":",
"ret",
"=",
"[",
"self",
".",
"tensor_dimension_to_mesh_axis",
"(",
"d",
",",
"mesh_shape",
")",
"for",
"d",
"in",
"tensor_shape",
"]",
"not_nones",
"=",
"[",
"a",
"for",
"a",
"in",
"ret",
"if",
"a",
"is",
"not",
"None",
"]",
"if",
"len",
"(",
"not_nones",
")",
"!=",
"len",
"(",
"set",
"(",
"not_nones",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Two Tensor Dimensions may not map to the same Mesh Dimension:\"",
"\" layout=%s tensor_shape=%s mesh_shape=%s \"",
"%",
"(",
"self",
",",
"tensor_shape",
",",
"mesh_shape",
")",
")",
"return",
"TensorLayout",
"(",
"ret",
")"
] | Computes TensorLayout given a Tensor Shape and a Mesh Shape.
Args:
tensor_shape: Shape.
mesh_shape: Shape.
Returns:
TensorLayout.
Raises:
ValueError: If two Tensor Dimensions map to the same Mesh Dimensions. | [
"Computes",
"TensorLayout",
"given",
"a",
"Tensor",
"Shape",
"and",
"a",
"Mesh",
"Shape",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L247-L268 |
227,904 | tensorflow/mesh | mesh_tensorflow/ops.py | TensorLayout.mesh_axis_to_tensor_axis | def mesh_axis_to_tensor_axis(self, mesh_ndims):
"""For each mesh axis, which Tensor axis maps to it.
Args:
mesh_ndims: int.
Returns:
Tuple of optional integers, with length mesh_ndims.
"""
ta2ma = self._tensor_axis_to_mesh_axis
return tuple(
[ta2ma.index(mesh_axis) if mesh_axis in ta2ma else None
for mesh_axis in xrange(mesh_ndims)]) | python | def mesh_axis_to_tensor_axis(self, mesh_ndims):
"""For each mesh axis, which Tensor axis maps to it.
Args:
mesh_ndims: int.
Returns:
Tuple of optional integers, with length mesh_ndims.
"""
ta2ma = self._tensor_axis_to_mesh_axis
return tuple(
[ta2ma.index(mesh_axis) if mesh_axis in ta2ma else None
for mesh_axis in xrange(mesh_ndims)]) | [
"def",
"mesh_axis_to_tensor_axis",
"(",
"self",
",",
"mesh_ndims",
")",
":",
"ta2ma",
"=",
"self",
".",
"_tensor_axis_to_mesh_axis",
"return",
"tuple",
"(",
"[",
"ta2ma",
".",
"index",
"(",
"mesh_axis",
")",
"if",
"mesh_axis",
"in",
"ta2ma",
"else",
"None",
"for",
"mesh_axis",
"in",
"xrange",
"(",
"mesh_ndims",
")",
"]",
")"
] | For each mesh axis, which Tensor axis maps to it.
Args:
mesh_ndims: int.
Returns:
Tuple of optional integers, with length mesh_ndims. | [
"For",
"each",
"mesh",
"axis",
"which",
"Tensor",
"axis",
"maps",
"to",
"it",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L339-L351 |
227,905 | tensorflow/mesh | mesh_tensorflow/ops.py | Graph.unique_name | def unique_name(self, name, mark_as_used=True):
"""Like tf.Graph.unique_name, returns a unique operation name for `name`.
Args:
name: The name for an operation.
mark_as_used: whether to mark this name as being used.
Returns:
A string to use as the name for the operation.
"""
scope_name = tf.get_variable_scope().name
if scope_name:
name = scope_name + "/" + name
# As in TensorFlow, treat names as case insensitive when deciding whether
# they are in use.
name_key = name.lower()
i = self._names_in_use.get(name_key, 0)
if mark_as_used:
self._names_in_use[name_key] = i + 1
if i > 0:
base_name_key = name_key
while name_key in self._names_in_use:
name_key = "%s_%d" % (base_name_key, i)
i += 1
if mark_as_used:
self._names_in_use[name_key] = 1
name = "%s_%d" % (name, i-1)
return name | python | def unique_name(self, name, mark_as_used=True):
"""Like tf.Graph.unique_name, returns a unique operation name for `name`.
Args:
name: The name for an operation.
mark_as_used: whether to mark this name as being used.
Returns:
A string to use as the name for the operation.
"""
scope_name = tf.get_variable_scope().name
if scope_name:
name = scope_name + "/" + name
# As in TensorFlow, treat names as case insensitive when deciding whether
# they are in use.
name_key = name.lower()
i = self._names_in_use.get(name_key, 0)
if mark_as_used:
self._names_in_use[name_key] = i + 1
if i > 0:
base_name_key = name_key
while name_key in self._names_in_use:
name_key = "%s_%d" % (base_name_key, i)
i += 1
if mark_as_used:
self._names_in_use[name_key] = 1
name = "%s_%d" % (name, i-1)
return name | [
"def",
"unique_name",
"(",
"self",
",",
"name",
",",
"mark_as_used",
"=",
"True",
")",
":",
"scope_name",
"=",
"tf",
".",
"get_variable_scope",
"(",
")",
".",
"name",
"if",
"scope_name",
":",
"name",
"=",
"scope_name",
"+",
"\"/\"",
"+",
"name",
"# As in TensorFlow, treat names as case insensitive when deciding whether",
"# they are in use.",
"name_key",
"=",
"name",
".",
"lower",
"(",
")",
"i",
"=",
"self",
".",
"_names_in_use",
".",
"get",
"(",
"name_key",
",",
"0",
")",
"if",
"mark_as_used",
":",
"self",
".",
"_names_in_use",
"[",
"name_key",
"]",
"=",
"i",
"+",
"1",
"if",
"i",
">",
"0",
":",
"base_name_key",
"=",
"name_key",
"while",
"name_key",
"in",
"self",
".",
"_names_in_use",
":",
"name_key",
"=",
"\"%s_%d\"",
"%",
"(",
"base_name_key",
",",
"i",
")",
"i",
"+=",
"1",
"if",
"mark_as_used",
":",
"self",
".",
"_names_in_use",
"[",
"name_key",
"]",
"=",
"1",
"name",
"=",
"\"%s_%d\"",
"%",
"(",
"name",
",",
"i",
"-",
"1",
")",
"return",
"name"
] | Like tf.Graph.unique_name, returns a unique operation name for `name`.
Args:
name: The name for an operation.
mark_as_used: whether to mark this name as being used.
Returns:
A string to use as the name for the operation. | [
"Like",
"tf",
".",
"Graph",
".",
"unique_name",
"returns",
"a",
"unique",
"operation",
"name",
"for",
"name",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L384-L413 |
227,906 | tensorflow/mesh | mesh_tensorflow/ops.py | Graph.combine_assignments | def combine_assignments(self, assignments):
"""Rewrite the current graph to combine "Assign" operations.
Combine similar Assign operations into grouped Assign operations.
This is useful when using the rewrite_stack_variables() optimization,
since variables can only be stacked if they are present in the same set
of Assign operations.
This function takes a list of Assign operations and returns a possibly
shorter list of Assign operations. The input Assignment operations
are removed from the graph and become invalid.
Args:
assignments: a list of Assign objects
Returns:
a list of Assign objects
"""
group_by_fn = collections.defaultdict(list)
for a in assignments:
if not isinstance(a, Assign):
raise ValueError("ops should be instances of mtf.Assign")
group_by_fn[a.assign_fn].append(a)
assignments_set = set(assignments)
self._operations = [
op for op in self._operations if op not in assignments_set]
ret = []
for fn, ops in six.iteritems(group_by_fn):
variables = []
values = []
for a in ops:
variables.extend(a.variables)
values.extend(a.inputs)
ret.append(Assign(variables, values, fn))
return ret | python | def combine_assignments(self, assignments):
"""Rewrite the current graph to combine "Assign" operations.
Combine similar Assign operations into grouped Assign operations.
This is useful when using the rewrite_stack_variables() optimization,
since variables can only be stacked if they are present in the same set
of Assign operations.
This function takes a list of Assign operations and returns a possibly
shorter list of Assign operations. The input Assignment operations
are removed from the graph and become invalid.
Args:
assignments: a list of Assign objects
Returns:
a list of Assign objects
"""
group_by_fn = collections.defaultdict(list)
for a in assignments:
if not isinstance(a, Assign):
raise ValueError("ops should be instances of mtf.Assign")
group_by_fn[a.assign_fn].append(a)
assignments_set = set(assignments)
self._operations = [
op for op in self._operations if op not in assignments_set]
ret = []
for fn, ops in six.iteritems(group_by_fn):
variables = []
values = []
for a in ops:
variables.extend(a.variables)
values.extend(a.inputs)
ret.append(Assign(variables, values, fn))
return ret | [
"def",
"combine_assignments",
"(",
"self",
",",
"assignments",
")",
":",
"group_by_fn",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"a",
"in",
"assignments",
":",
"if",
"not",
"isinstance",
"(",
"a",
",",
"Assign",
")",
":",
"raise",
"ValueError",
"(",
"\"ops should be instances of mtf.Assign\"",
")",
"group_by_fn",
"[",
"a",
".",
"assign_fn",
"]",
".",
"append",
"(",
"a",
")",
"assignments_set",
"=",
"set",
"(",
"assignments",
")",
"self",
".",
"_operations",
"=",
"[",
"op",
"for",
"op",
"in",
"self",
".",
"_operations",
"if",
"op",
"not",
"in",
"assignments_set",
"]",
"ret",
"=",
"[",
"]",
"for",
"fn",
",",
"ops",
"in",
"six",
".",
"iteritems",
"(",
"group_by_fn",
")",
":",
"variables",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"for",
"a",
"in",
"ops",
":",
"variables",
".",
"extend",
"(",
"a",
".",
"variables",
")",
"values",
".",
"extend",
"(",
"a",
".",
"inputs",
")",
"ret",
".",
"append",
"(",
"Assign",
"(",
"variables",
",",
"values",
",",
"fn",
")",
")",
"return",
"ret"
] | Rewrite the current graph to combine "Assign" operations.
Combine similar Assign operations into grouped Assign operations.
This is useful when using the rewrite_stack_variables() optimization,
since variables can only be stacked if they are present in the same set
of Assign operations.
This function takes a list of Assign operations and returns a possibly
shorter list of Assign operations. The input Assignment operations
are removed from the graph and become invalid.
Args:
assignments: a list of Assign objects
Returns:
a list of Assign objects | [
"Rewrite",
"the",
"current",
"graph",
"to",
"combine",
"Assign",
"operations",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L534-L567 |
227,907 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.tensor_layout | def tensor_layout(self, arg):
"""Compute TensorLayout for a Tensor or a Shape.
Args:
arg: Tensor or Shape.
Returns:
TensorLayout.
"""
if isinstance(arg, Tensor):
arg = arg.shape
return self.layout_rules.tensor_layout(arg, self.shape) | python | def tensor_layout(self, arg):
"""Compute TensorLayout for a Tensor or a Shape.
Args:
arg: Tensor or Shape.
Returns:
TensorLayout.
"""
if isinstance(arg, Tensor):
arg = arg.shape
return self.layout_rules.tensor_layout(arg, self.shape) | [
"def",
"tensor_layout",
"(",
"self",
",",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Tensor",
")",
":",
"arg",
"=",
"arg",
".",
"shape",
"return",
"self",
".",
"layout_rules",
".",
"tensor_layout",
"(",
"arg",
",",
"self",
".",
"shape",
")"
] | Compute TensorLayout for a Tensor or a Shape.
Args:
arg: Tensor or Shape.
Returns:
TensorLayout. | [
"Compute",
"TensorLayout",
"for",
"a",
"Tensor",
"or",
"a",
"Shape",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L803-L814 |
227,908 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.mesh_axis_to_cumprod | def mesh_axis_to_cumprod(self, tensor_shape):
"""For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None.
"""
tensor_layout = self.tensor_layout(tensor_shape)
ma2ta = tensor_layout.mesh_axis_to_tensor_axis(self.ndims)
ta2cumprod = tensor_shape.cumprod
return [None if ta is None else ta2cumprod[ta] for ta in ma2ta] | python | def mesh_axis_to_cumprod(self, tensor_shape):
"""For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None.
"""
tensor_layout = self.tensor_layout(tensor_shape)
ma2ta = tensor_layout.mesh_axis_to_tensor_axis(self.ndims)
ta2cumprod = tensor_shape.cumprod
return [None if ta is None else ta2cumprod[ta] for ta in ma2ta] | [
"def",
"mesh_axis_to_cumprod",
"(",
"self",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"ma2ta",
"=",
"tensor_layout",
".",
"mesh_axis_to_tensor_axis",
"(",
"self",
".",
"ndims",
")",
"ta2cumprod",
"=",
"tensor_shape",
".",
"cumprod",
"return",
"[",
"None",
"if",
"ta",
"is",
"None",
"else",
"ta2cumprod",
"[",
"ta",
"]",
"for",
"ta",
"in",
"ma2ta",
"]"
] | For each mesh axis, give the product of previous tensor axes.
Args:
tensor_shape: Shape.
Returns:
list with length self.ndims where each element is an integer or None. | [
"For",
"each",
"mesh",
"axis",
"give",
"the",
"product",
"of",
"previous",
"tensor",
"axes",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L816-L828 |
227,909 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.slice_shape | def slice_shape(self, tensor_shape):
"""Shape of each slice of the Tensor.
Args:
tensor_shape: Shape.
Returns:
list of integers with length tensor_shape.ndims.
Raises:
ValueError: If a Tensor dimension is not divisible by the corresponding
Mesh dimension.
"""
tensor_layout = self.tensor_layout(tensor_shape)
ret = []
for tensor_dim, mesh_axis in zip(
tensor_shape, tensor_layout.tensor_axis_to_mesh_axis):
if mesh_axis is None:
ret.append(tensor_dim.size)
else:
mesh_dim = self.shape[mesh_axis]
if tensor_dim.size % mesh_dim.size != 0:
raise ValueError(
"Tensor dimension size not divisible by mesh dimension size:"
" tensor_shape=%s tensor_layout=%s"
% (tensor_shape, tensor_layout))
ret.append(tensor_dim.size // mesh_dim.size)
return ret | python | def slice_shape(self, tensor_shape):
"""Shape of each slice of the Tensor.
Args:
tensor_shape: Shape.
Returns:
list of integers with length tensor_shape.ndims.
Raises:
ValueError: If a Tensor dimension is not divisible by the corresponding
Mesh dimension.
"""
tensor_layout = self.tensor_layout(tensor_shape)
ret = []
for tensor_dim, mesh_axis in zip(
tensor_shape, tensor_layout.tensor_axis_to_mesh_axis):
if mesh_axis is None:
ret.append(tensor_dim.size)
else:
mesh_dim = self.shape[mesh_axis]
if tensor_dim.size % mesh_dim.size != 0:
raise ValueError(
"Tensor dimension size not divisible by mesh dimension size:"
" tensor_shape=%s tensor_layout=%s"
% (tensor_shape, tensor_layout))
ret.append(tensor_dim.size // mesh_dim.size)
return ret | [
"def",
"slice_shape",
"(",
"self",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"ret",
"=",
"[",
"]",
"for",
"tensor_dim",
",",
"mesh_axis",
"in",
"zip",
"(",
"tensor_shape",
",",
"tensor_layout",
".",
"tensor_axis_to_mesh_axis",
")",
":",
"if",
"mesh_axis",
"is",
"None",
":",
"ret",
".",
"append",
"(",
"tensor_dim",
".",
"size",
")",
"else",
":",
"mesh_dim",
"=",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
"if",
"tensor_dim",
".",
"size",
"%",
"mesh_dim",
".",
"size",
"!=",
"0",
":",
"raise",
"ValueError",
"(",
"\"Tensor dimension size not divisible by mesh dimension size:\"",
"\" tensor_shape=%s tensor_layout=%s\"",
"%",
"(",
"tensor_shape",
",",
"tensor_layout",
")",
")",
"ret",
".",
"append",
"(",
"tensor_dim",
".",
"size",
"//",
"mesh_dim",
".",
"size",
")",
"return",
"ret"
] | Shape of each slice of the Tensor.
Args:
tensor_shape: Shape.
Returns:
list of integers with length tensor_shape.ndims.
Raises:
ValueError: If a Tensor dimension is not divisible by the corresponding
Mesh dimension. | [
"Shape",
"of",
"each",
"slice",
"of",
"the",
"Tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L830-L857 |
227,910 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.slice_begin | def slice_begin(self, tensor_shape, pnum):
"""Begin position for the tensor slice for the given processor.
Args:
tensor_shape: Shape.
pnum: int <= self.size.
Returns:
list of integers with length tensor_shape.ndims.
"""
tensor_layout = self.tensor_layout(tensor_shape)
coordinates = pnum_to_processor_coordinates(self.shape, pnum)
ret = []
for dim_size, mesh_axis in zip(
tensor_shape.to_integer_list, tensor_layout.tensor_axis_to_mesh_axis):
if mesh_axis is None:
ret.append(0)
else:
ret.append(
dim_size // self.shape[mesh_axis].size * coordinates[mesh_axis])
return ret | python | def slice_begin(self, tensor_shape, pnum):
"""Begin position for the tensor slice for the given processor.
Args:
tensor_shape: Shape.
pnum: int <= self.size.
Returns:
list of integers with length tensor_shape.ndims.
"""
tensor_layout = self.tensor_layout(tensor_shape)
coordinates = pnum_to_processor_coordinates(self.shape, pnum)
ret = []
for dim_size, mesh_axis in zip(
tensor_shape.to_integer_list, tensor_layout.tensor_axis_to_mesh_axis):
if mesh_axis is None:
ret.append(0)
else:
ret.append(
dim_size // self.shape[mesh_axis].size * coordinates[mesh_axis])
return ret | [
"def",
"slice_begin",
"(",
"self",
",",
"tensor_shape",
",",
"pnum",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"coordinates",
"=",
"pnum_to_processor_coordinates",
"(",
"self",
".",
"shape",
",",
"pnum",
")",
"ret",
"=",
"[",
"]",
"for",
"dim_size",
",",
"mesh_axis",
"in",
"zip",
"(",
"tensor_shape",
".",
"to_integer_list",
",",
"tensor_layout",
".",
"tensor_axis_to_mesh_axis",
")",
":",
"if",
"mesh_axis",
"is",
"None",
":",
"ret",
".",
"append",
"(",
"0",
")",
"else",
":",
"ret",
".",
"append",
"(",
"dim_size",
"//",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
"*",
"coordinates",
"[",
"mesh_axis",
"]",
")",
"return",
"ret"
] | Begin position for the tensor slice for the given processor.
Args:
tensor_shape: Shape.
pnum: int <= self.size.
Returns:
list of integers with length tensor_shape.ndims. | [
"Begin",
"position",
"for",
"the",
"tensor",
"slice",
"for",
"the",
"given",
"processor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L859-L879 |
227,911 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.Print | def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name
"""Calls tf.Print.
Args:
x: LaidOutTensor.
data: list of LaidOutTensor.
message: str.
**kwargs: keyword arguments to tf.print.
Returns:
LaidOutTensor.
"""
del data, message, kwargs
tf.logging.warning("Warning - mtf.Print not implemented for this mesh type")
return x | python | def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name
"""Calls tf.Print.
Args:
x: LaidOutTensor.
data: list of LaidOutTensor.
message: str.
**kwargs: keyword arguments to tf.print.
Returns:
LaidOutTensor.
"""
del data, message, kwargs
tf.logging.warning("Warning - mtf.Print not implemented for this mesh type")
return x | [
"def",
"Print",
"(",
"self",
",",
"x",
",",
"data",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"del",
"data",
",",
"message",
",",
"kwargs",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Warning - mtf.Print not implemented for this mesh type\"",
")",
"return",
"x"
] | Calls tf.Print.
Args:
x: LaidOutTensor.
data: list of LaidOutTensor.
message: str.
**kwargs: keyword arguments to tf.print.
Returns:
LaidOutTensor. | [
"Calls",
"tf",
".",
"Print",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L908-L922 |
227,912 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.allsplit | def allsplit(self, x, mesh_axis, split_axis, which=None):
"""Inverse of allconcat - split each slice and keep only one piece of it.
The number of ways to split is the number of processors in the group.
The part that is kept corresponds to the processor's index in the group.
Args:
x: LaidOutTensor.
mesh_axis: int, the mesh axis along which to split.
split_axis: int, the Tensor axis along which to split.
which: an optional LaidOutTensor of integer scalars. Selects the slice to
to keep, instead of the coordinate.
Returns:
LaidOutTensor.
"""
if which is None:
which = self.laid_out_pcoord(mesh_axis)
num_splits = self.shape[mesh_axis].size
def my_fn(x, which):
slice_begin = [
dimsize // num_splits * which if i == split_axis else 0
for i, dimsize in enumerate(x.shape.as_list())]
slice_size = [
dimsize // num_splits if i == split_axis else dimsize
for i, dimsize in enumerate(x.shape.as_list())]
return tf.slice(x, slice_begin, slice_size)
return self.slicewise(my_fn, x, which) | python | def allsplit(self, x, mesh_axis, split_axis, which=None):
"""Inverse of allconcat - split each slice and keep only one piece of it.
The number of ways to split is the number of processors in the group.
The part that is kept corresponds to the processor's index in the group.
Args:
x: LaidOutTensor.
mesh_axis: int, the mesh axis along which to split.
split_axis: int, the Tensor axis along which to split.
which: an optional LaidOutTensor of integer scalars. Selects the slice to
to keep, instead of the coordinate.
Returns:
LaidOutTensor.
"""
if which is None:
which = self.laid_out_pcoord(mesh_axis)
num_splits = self.shape[mesh_axis].size
def my_fn(x, which):
slice_begin = [
dimsize // num_splits * which if i == split_axis else 0
for i, dimsize in enumerate(x.shape.as_list())]
slice_size = [
dimsize // num_splits if i == split_axis else dimsize
for i, dimsize in enumerate(x.shape.as_list())]
return tf.slice(x, slice_begin, slice_size)
return self.slicewise(my_fn, x, which) | [
"def",
"allsplit",
"(",
"self",
",",
"x",
",",
"mesh_axis",
",",
"split_axis",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"is",
"None",
":",
"which",
"=",
"self",
".",
"laid_out_pcoord",
"(",
"mesh_axis",
")",
"num_splits",
"=",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
"def",
"my_fn",
"(",
"x",
",",
"which",
")",
":",
"slice_begin",
"=",
"[",
"dimsize",
"//",
"num_splits",
"*",
"which",
"if",
"i",
"==",
"split_axis",
"else",
"0",
"for",
"i",
",",
"dimsize",
"in",
"enumerate",
"(",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
")",
"]",
"slice_size",
"=",
"[",
"dimsize",
"//",
"num_splits",
"if",
"i",
"==",
"split_axis",
"else",
"dimsize",
"for",
"i",
",",
"dimsize",
"in",
"enumerate",
"(",
"x",
".",
"shape",
".",
"as_list",
"(",
")",
")",
"]",
"return",
"tf",
".",
"slice",
"(",
"x",
",",
"slice_begin",
",",
"slice_size",
")",
"return",
"self",
".",
"slicewise",
"(",
"my_fn",
",",
"x",
",",
"which",
")"
] | Inverse of allconcat - split each slice and keep only one piece of it.
The number of ways to split is the number of processors in the group.
The part that is kept corresponds to the processor's index in the group.
Args:
x: LaidOutTensor.
mesh_axis: int, the mesh axis along which to split.
split_axis: int, the Tensor axis along which to split.
which: an optional LaidOutTensor of integer scalars. Selects the slice to
to keep, instead of the coordinate.
Returns:
LaidOutTensor. | [
"Inverse",
"of",
"allconcat",
"-",
"split",
"each",
"slice",
"and",
"keep",
"only",
"one",
"piece",
"of",
"it",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L937-L964 |
227,913 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.shift_by_n_processors | def shift_by_n_processors(self, x, mesh_axis, offset, wrap):
"""Receive the slice from processor pcoord - offset.
Args:
x: a LaidOutTensor
mesh_axis: an integer
offset: an integer
wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros.
"""
n = self.shape[mesh_axis].size
source_pcoord = []
for i in xrange(n):
c = i - offset
if c != c % n:
if wrap:
c = c % n
else:
c = None
source_pcoord.append(c)
return self.receive(x, mesh_axis, source_pcoord) | python | def shift_by_n_processors(self, x, mesh_axis, offset, wrap):
"""Receive the slice from processor pcoord - offset.
Args:
x: a LaidOutTensor
mesh_axis: an integer
offset: an integer
wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros.
"""
n = self.shape[mesh_axis].size
source_pcoord = []
for i in xrange(n):
c = i - offset
if c != c % n:
if wrap:
c = c % n
else:
c = None
source_pcoord.append(c)
return self.receive(x, mesh_axis, source_pcoord) | [
"def",
"shift_by_n_processors",
"(",
"self",
",",
"x",
",",
"mesh_axis",
",",
"offset",
",",
"wrap",
")",
":",
"n",
"=",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
"source_pcoord",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"c",
"=",
"i",
"-",
"offset",
"if",
"c",
"!=",
"c",
"%",
"n",
":",
"if",
"wrap",
":",
"c",
"=",
"c",
"%",
"n",
"else",
":",
"c",
"=",
"None",
"source_pcoord",
".",
"append",
"(",
"c",
")",
"return",
"self",
".",
"receive",
"(",
"x",
",",
"mesh_axis",
",",
"source_pcoord",
")"
] | Receive the slice from processor pcoord - offset.
Args:
x: a LaidOutTensor
mesh_axis: an integer
offset: an integer
wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros. | [
"Receive",
"the",
"slice",
"from",
"processor",
"pcoord",
"-",
"offset",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1017-L1036 |
227,914 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.laid_out_pcoord | def laid_out_pcoord(self, mesh_axis):
"""Returns a LaidOutTensor containing the processor coordinate.
Args:
mesh_axis: int.
Returns:
LaidOutTensor where each slice is an integer scalar.
"""
divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:])
modulus = self.shape[mesh_axis].size
def my_fn(pnum):
return (pnum // divisor) % modulus
return self.slicewise(my_fn, self.laid_out_pnum()) | python | def laid_out_pcoord(self, mesh_axis):
"""Returns a LaidOutTensor containing the processor coordinate.
Args:
mesh_axis: int.
Returns:
LaidOutTensor where each slice is an integer scalar.
"""
divisor = list_product(self.shape.to_integer_list[mesh_axis + 1:])
modulus = self.shape[mesh_axis].size
def my_fn(pnum):
return (pnum // divisor) % modulus
return self.slicewise(my_fn, self.laid_out_pnum()) | [
"def",
"laid_out_pcoord",
"(",
"self",
",",
"mesh_axis",
")",
":",
"divisor",
"=",
"list_product",
"(",
"self",
".",
"shape",
".",
"to_integer_list",
"[",
"mesh_axis",
"+",
"1",
":",
"]",
")",
"modulus",
"=",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
"def",
"my_fn",
"(",
"pnum",
")",
":",
"return",
"(",
"pnum",
"//",
"divisor",
")",
"%",
"modulus",
"return",
"self",
".",
"slicewise",
"(",
"my_fn",
",",
"self",
".",
"laid_out_pnum",
"(",
")",
")"
] | Returns a LaidOutTensor containing the processor coordinate.
Args:
mesh_axis: int.
Returns:
LaidOutTensor where each slice is an integer scalar. | [
"Returns",
"a",
"LaidOutTensor",
"containing",
"the",
"processor",
"coordinate",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1046-L1059 |
227,915 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.laid_out_slice_num | def laid_out_slice_num(self, tensor_shape):
"""A LaidOutTensor with an int32 scalar, identical for identical slices.
This is useful for synchronizing random operations.
Args:
tensor_shape: a TensorShape
Returns:
a LaidOutTensor where each slice is an integer scalar.
"""
ret = self.slicewise(lambda: tf.to_int32(0))
tensor_layout = self.tensor_layout(tensor_shape)
for mesh_axis in tensor_layout.tensor_axis_to_mesh_axis:
if mesh_axis is not None:
def my_fn(x, pcoord, mesh_dim_size):
return x * mesh_dim_size + pcoord
ret = self.slicewise(
my_fn, ret, self.laid_out_pcoord(mesh_axis),
self.shape[mesh_axis].size)
return ret | python | def laid_out_slice_num(self, tensor_shape):
"""A LaidOutTensor with an int32 scalar, identical for identical slices.
This is useful for synchronizing random operations.
Args:
tensor_shape: a TensorShape
Returns:
a LaidOutTensor where each slice is an integer scalar.
"""
ret = self.slicewise(lambda: tf.to_int32(0))
tensor_layout = self.tensor_layout(tensor_shape)
for mesh_axis in tensor_layout.tensor_axis_to_mesh_axis:
if mesh_axis is not None:
def my_fn(x, pcoord, mesh_dim_size):
return x * mesh_dim_size + pcoord
ret = self.slicewise(
my_fn, ret, self.laid_out_pcoord(mesh_axis),
self.shape[mesh_axis].size)
return ret | [
"def",
"laid_out_slice_num",
"(",
"self",
",",
"tensor_shape",
")",
":",
"ret",
"=",
"self",
".",
"slicewise",
"(",
"lambda",
":",
"tf",
".",
"to_int32",
"(",
"0",
")",
")",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"for",
"mesh_axis",
"in",
"tensor_layout",
".",
"tensor_axis_to_mesh_axis",
":",
"if",
"mesh_axis",
"is",
"not",
"None",
":",
"def",
"my_fn",
"(",
"x",
",",
"pcoord",
",",
"mesh_dim_size",
")",
":",
"return",
"x",
"*",
"mesh_dim_size",
"+",
"pcoord",
"ret",
"=",
"self",
".",
"slicewise",
"(",
"my_fn",
",",
"ret",
",",
"self",
".",
"laid_out_pcoord",
"(",
"mesh_axis",
")",
",",
"self",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
")",
"return",
"ret"
] | A LaidOutTensor with an int32 scalar, identical for identical slices.
This is useful for synchronizing random operations.
Args:
tensor_shape: a TensorShape
Returns:
a LaidOutTensor where each slice is an integer scalar. | [
"A",
"LaidOutTensor",
"with",
"an",
"int32",
"scalar",
"identical",
"for",
"identical",
"slices",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1061-L1080 |
227,916 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.broadcast_impl | def broadcast_impl(self, old_slices, old_shape, new_shape):
"""Implementation of a broadcast operation.
Args:
old_slices: LaidOutTensor.
old_shape: Shape.
new_shape: Shape.
Returns:
LaidOutTensor.
"""
new_slice_shape = self.slice_shape(new_shape)
def tf_fn(x):
return (tf.zeros(new_slice_shape, dtype=x.dtype) +
_expand_dims(x, old_shape, new_shape))
return self.slicewise(tf_fn, old_slices) | python | def broadcast_impl(self, old_slices, old_shape, new_shape):
"""Implementation of a broadcast operation.
Args:
old_slices: LaidOutTensor.
old_shape: Shape.
new_shape: Shape.
Returns:
LaidOutTensor.
"""
new_slice_shape = self.slice_shape(new_shape)
def tf_fn(x):
return (tf.zeros(new_slice_shape, dtype=x.dtype) +
_expand_dims(x, old_shape, new_shape))
return self.slicewise(tf_fn, old_slices) | [
"def",
"broadcast_impl",
"(",
"self",
",",
"old_slices",
",",
"old_shape",
",",
"new_shape",
")",
":",
"new_slice_shape",
"=",
"self",
".",
"slice_shape",
"(",
"new_shape",
")",
"def",
"tf_fn",
"(",
"x",
")",
":",
"return",
"(",
"tf",
".",
"zeros",
"(",
"new_slice_shape",
",",
"dtype",
"=",
"x",
".",
"dtype",
")",
"+",
"_expand_dims",
"(",
"x",
",",
"old_shape",
",",
"new_shape",
")",
")",
"return",
"self",
".",
"slicewise",
"(",
"tf_fn",
",",
"old_slices",
")"
] | Implementation of a broadcast operation.
Args:
old_slices: LaidOutTensor.
old_shape: Shape.
new_shape: Shape.
Returns:
LaidOutTensor. | [
"Implementation",
"of",
"a",
"broadcast",
"operation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1082-L1097 |
227,917 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.make_slices | def make_slices(self, tf_tensor, tensor_shape):
"""Turns a single tf.Tensor into a list of slices, one for each processor.
Args:
tf_tensor: tf.Tensor.
tensor_shape: Shape.
Returns:
list of tf.tensor with length self.size.
"""
tensor_layout = self.tensor_layout(tensor_shape)
slice_shape = self.slice_shape(tensor_shape)
def my_fn(pnum):
if tensor_layout.is_fully_replicated:
return tf_tensor
else:
slice_begin = self.slice_begin(tensor_shape, pnum)
return tf.slice(tf_tensor, slice_begin, slice_shape)
return parallel([tf_tensor.device] * self.size, my_fn,
list(xrange(self.size))) | python | def make_slices(self, tf_tensor, tensor_shape):
"""Turns a single tf.Tensor into a list of slices, one for each processor.
Args:
tf_tensor: tf.Tensor.
tensor_shape: Shape.
Returns:
list of tf.tensor with length self.size.
"""
tensor_layout = self.tensor_layout(tensor_shape)
slice_shape = self.slice_shape(tensor_shape)
def my_fn(pnum):
if tensor_layout.is_fully_replicated:
return tf_tensor
else:
slice_begin = self.slice_begin(tensor_shape, pnum)
return tf.slice(tf_tensor, slice_begin, slice_shape)
return parallel([tf_tensor.device] * self.size, my_fn,
list(xrange(self.size))) | [
"def",
"make_slices",
"(",
"self",
",",
"tf_tensor",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"slice_shape",
"=",
"self",
".",
"slice_shape",
"(",
"tensor_shape",
")",
"def",
"my_fn",
"(",
"pnum",
")",
":",
"if",
"tensor_layout",
".",
"is_fully_replicated",
":",
"return",
"tf_tensor",
"else",
":",
"slice_begin",
"=",
"self",
".",
"slice_begin",
"(",
"tensor_shape",
",",
"pnum",
")",
"return",
"tf",
".",
"slice",
"(",
"tf_tensor",
",",
"slice_begin",
",",
"slice_shape",
")",
"return",
"parallel",
"(",
"[",
"tf_tensor",
".",
"device",
"]",
"*",
"self",
".",
"size",
",",
"my_fn",
",",
"list",
"(",
"xrange",
"(",
"self",
".",
"size",
")",
")",
")"
] | Turns a single tf.Tensor into a list of slices, one for each processor.
Args:
tf_tensor: tf.Tensor.
tensor_shape: Shape.
Returns:
list of tf.tensor with length self.size. | [
"Turns",
"a",
"single",
"tf",
".",
"Tensor",
"into",
"a",
"list",
"of",
"slices",
"one",
"for",
"each",
"processor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1099-L1119 |
227,918 | tensorflow/mesh | mesh_tensorflow/ops.py | MeshImpl.combine_slices | def combine_slices(self, slices, tensor_shape, device=None):
"""Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor.
"""
if tensor_shape.ndims == 0:
return slices[0]
ret = slices[:]
tensor_layout = self.tensor_layout(tensor_shape)
for mesh_dim, tensor_axis in zip(
self.shape, tensor_layout.mesh_axis_to_tensor_axis(self.ndims)):
slice_size = len(ret) // mesh_dim.size
if tensor_axis is None:
ret = ret[:slice_size]
else:
if device:
devices = [device] * slice_size
else:
devices = [ret[i].device for i in xrange(slice_size)]
concat_inputs = []
for i in xrange(slice_size):
concat_inputs.append(
[ret[i + slice_size * j] for j in xrange(mesh_dim.size)])
ret = parallel(
devices, tf.concat, concat_inputs,
axis=[tensor_axis] * len(devices))
assert len(ret) == 1
return ret[0] | python | def combine_slices(self, slices, tensor_shape, device=None):
"""Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor.
"""
if tensor_shape.ndims == 0:
return slices[0]
ret = slices[:]
tensor_layout = self.tensor_layout(tensor_shape)
for mesh_dim, tensor_axis in zip(
self.shape, tensor_layout.mesh_axis_to_tensor_axis(self.ndims)):
slice_size = len(ret) // mesh_dim.size
if tensor_axis is None:
ret = ret[:slice_size]
else:
if device:
devices = [device] * slice_size
else:
devices = [ret[i].device for i in xrange(slice_size)]
concat_inputs = []
for i in xrange(slice_size):
concat_inputs.append(
[ret[i + slice_size * j] for j in xrange(mesh_dim.size)])
ret = parallel(
devices, tf.concat, concat_inputs,
axis=[tensor_axis] * len(devices))
assert len(ret) == 1
return ret[0] | [
"def",
"combine_slices",
"(",
"self",
",",
"slices",
",",
"tensor_shape",
",",
"device",
"=",
"None",
")",
":",
"if",
"tensor_shape",
".",
"ndims",
"==",
"0",
":",
"return",
"slices",
"[",
"0",
"]",
"ret",
"=",
"slices",
"[",
":",
"]",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"for",
"mesh_dim",
",",
"tensor_axis",
"in",
"zip",
"(",
"self",
".",
"shape",
",",
"tensor_layout",
".",
"mesh_axis_to_tensor_axis",
"(",
"self",
".",
"ndims",
")",
")",
":",
"slice_size",
"=",
"len",
"(",
"ret",
")",
"//",
"mesh_dim",
".",
"size",
"if",
"tensor_axis",
"is",
"None",
":",
"ret",
"=",
"ret",
"[",
":",
"slice_size",
"]",
"else",
":",
"if",
"device",
":",
"devices",
"=",
"[",
"device",
"]",
"*",
"slice_size",
"else",
":",
"devices",
"=",
"[",
"ret",
"[",
"i",
"]",
".",
"device",
"for",
"i",
"in",
"xrange",
"(",
"slice_size",
")",
"]",
"concat_inputs",
"=",
"[",
"]",
"for",
"i",
"in",
"xrange",
"(",
"slice_size",
")",
":",
"concat_inputs",
".",
"append",
"(",
"[",
"ret",
"[",
"i",
"+",
"slice_size",
"*",
"j",
"]",
"for",
"j",
"in",
"xrange",
"(",
"mesh_dim",
".",
"size",
")",
"]",
")",
"ret",
"=",
"parallel",
"(",
"devices",
",",
"tf",
".",
"concat",
",",
"concat_inputs",
",",
"axis",
"=",
"[",
"tensor_axis",
"]",
"*",
"len",
"(",
"devices",
")",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"1",
"return",
"ret",
"[",
"0",
"]"
] | Turns a set of slices into a single tensor.
Args:
slices: list of tf.Tensor with length self.size.
tensor_shape: Shape.
device: optional str. If absent, we use the devices of the slices.
Returns:
tf.Tensor. | [
"Turns",
"a",
"set",
"of",
"slices",
"into",
"a",
"single",
"tensor",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1121-L1155 |
227,919 | tensorflow/mesh | mesh_tensorflow/ops.py | Operation._initialize_splittable_and_unsplittable_dims | def _initialize_splittable_and_unsplittable_dims(
self, default_splittability, exception_dims_iterable=None):
"""Initializer for splittable_dims and unsplittable_dims.
Helper method to categorize all dimensions in the input/output tensors as
either splittable or unsplittable.
Args:
default_splittability: a string which is either "splittable" or
"unsplittable".
exception_dims_iterable: an optional iterable of names of dimensions
which are exceptions to the default splittability.
Returns:
splittable_dims and unsplittable_dims, two frozensets of names of
dimensions (strings)
Raises:
ValueError: default_splittability is not one of "splittable" or
"unsplittable".
"""
default_dims = set()
exception_dims = set()
if exception_dims_iterable:
exception_dims.update(exception_dims_iterable)
for t in itertools.chain(self.inputs, self.outputs):
for dim_name in t.shape.dimension_names:
if dim_name not in exception_dims:
default_dims.add(dim_name)
if default_splittability == "splittable":
return frozenset(default_dims), frozenset(exception_dims)
elif default_splittability == "unsplittable":
return frozenset(exception_dims), frozenset(default_dims)
else:
raise ValueError("default_splittability should be either \"splittable\" "
"or \"unsplittable\" but was {}"
.format(default_splittability)) | python | def _initialize_splittable_and_unsplittable_dims(
self, default_splittability, exception_dims_iterable=None):
"""Initializer for splittable_dims and unsplittable_dims.
Helper method to categorize all dimensions in the input/output tensors as
either splittable or unsplittable.
Args:
default_splittability: a string which is either "splittable" or
"unsplittable".
exception_dims_iterable: an optional iterable of names of dimensions
which are exceptions to the default splittability.
Returns:
splittable_dims and unsplittable_dims, two frozensets of names of
dimensions (strings)
Raises:
ValueError: default_splittability is not one of "splittable" or
"unsplittable".
"""
default_dims = set()
exception_dims = set()
if exception_dims_iterable:
exception_dims.update(exception_dims_iterable)
for t in itertools.chain(self.inputs, self.outputs):
for dim_name in t.shape.dimension_names:
if dim_name not in exception_dims:
default_dims.add(dim_name)
if default_splittability == "splittable":
return frozenset(default_dims), frozenset(exception_dims)
elif default_splittability == "unsplittable":
return frozenset(exception_dims), frozenset(default_dims)
else:
raise ValueError("default_splittability should be either \"splittable\" "
"or \"unsplittable\" but was {}"
.format(default_splittability)) | [
"def",
"_initialize_splittable_and_unsplittable_dims",
"(",
"self",
",",
"default_splittability",
",",
"exception_dims_iterable",
"=",
"None",
")",
":",
"default_dims",
"=",
"set",
"(",
")",
"exception_dims",
"=",
"set",
"(",
")",
"if",
"exception_dims_iterable",
":",
"exception_dims",
".",
"update",
"(",
"exception_dims_iterable",
")",
"for",
"t",
"in",
"itertools",
".",
"chain",
"(",
"self",
".",
"inputs",
",",
"self",
".",
"outputs",
")",
":",
"for",
"dim_name",
"in",
"t",
".",
"shape",
".",
"dimension_names",
":",
"if",
"dim_name",
"not",
"in",
"exception_dims",
":",
"default_dims",
".",
"add",
"(",
"dim_name",
")",
"if",
"default_splittability",
"==",
"\"splittable\"",
":",
"return",
"frozenset",
"(",
"default_dims",
")",
",",
"frozenset",
"(",
"exception_dims",
")",
"elif",
"default_splittability",
"==",
"\"unsplittable\"",
":",
"return",
"frozenset",
"(",
"exception_dims",
")",
",",
"frozenset",
"(",
"default_dims",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"default_splittability should be either \\\"splittable\\\" \"",
"\"or \\\"unsplittable\\\" but was {}\"",
".",
"format",
"(",
"default_splittability",
")",
")"
] | Initializer for splittable_dims and unsplittable_dims.
Helper method to categorize all dimensions in the input/output tensors as
either splittable or unsplittable.
Args:
default_splittability: a string which is either "splittable" or
"unsplittable".
exception_dims_iterable: an optional iterable of names of dimensions
which are exceptions to the default splittability.
Returns:
splittable_dims and unsplittable_dims, two frozensets of names of
dimensions (strings)
Raises:
ValueError: default_splittability is not one of "splittable" or
"unsplittable". | [
"Initializer",
"for",
"splittable_dims",
"and",
"unsplittable_dims",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L1448-L1486 |
227,920 | tensorflow/mesh | mesh_tensorflow/ops.py | ReshapeOperation.lower | def lower(self, lowering):
"""Lower the ReshapeOperation.
Reshaping can require collective communication between processors.
We haven't yet implemented all possible reshapes. We try to handle the
common cases here - otherwise we raise a NotImplementedError.
Args:
lowering: a Lowering
Raises:
NotImplementedError: if we haven't covered this case
"""
old_shape = self.inputs[0].shape
new_shape = self.outputs[0].shape
mesh_impl = lowering.mesh_impl(self)
slices = lowering.tensors[self.inputs[0]]
mesh_axis_to_cumprod_old = mesh_impl.mesh_axis_to_cumprod(old_shape)
mesh_axis_to_cumprod_new = mesh_impl.mesh_axis_to_cumprod(new_shape)
# Figure out what needs to be done for different mesh-axes
mesh_axes_allsplit = []
mesh_axes_allconcat = []
mesh_axes_alltoall = []
for mesh_axis, (old_cumprod, new_cumprod) in enumerate(
zip(mesh_axis_to_cumprod_old, mesh_axis_to_cumprod_new)):
if new_cumprod != old_cumprod:
if old_cumprod is None:
# split in new layout but not in old layout - we need an allsplit
mesh_axes_allsplit.append(mesh_axis)
elif new_cumprod is None:
# split in old layout but not in new layout - we need an allconcat
mesh_axes_allconcat.append(mesh_axis)
else:
# split differently in old and new layouts - we need an alltoall
mesh_axes_alltoall.append(mesh_axis)
laid_out_size = mesh_impl.laid_out_size(old_shape)
for mesh_axis in mesh_axes_allsplit:
tensor_axis = old_shape.cumprod_to_tensor_axis(
mesh_axis_to_cumprod_new[mesh_axis])
if tensor_axis is None:
# TODO(noam): try to handle this case
raise NotImplementedError(
"Try first reshaping to insert a new tf dimension,"
" then changing layout. input_shape=%s output_shape=%s"
% (self.inputs[0].shape, self.outputs[0].shape))
slices = mesh_impl.allsplit(slices, mesh_axis, tensor_axis)
laid_out_size //= mesh_impl.shape[mesh_axis].size
for mesh_axis in mesh_axes_alltoall:
split_tensor_axis = old_shape.cumprod_to_tensor_axis(
mesh_axis_to_cumprod_new[mesh_axis])
if split_tensor_axis is None:
# TODO(noam): try to handle this case
raise NotImplementedError(
"Try first reshaping to insert a new tf dimension,"
" then changing layout. input_shape=%s output_shape=%s"
% (self.inputs[0].shape, self.outputs[0].shape))
concat_tensor_axis = old_shape.cumprod_to_tensor_axis(
mesh_axis_to_cumprod_old[mesh_axis])
assert concat_tensor_axis is not None
slices = mesh_impl.alltoall(
slices, mesh_axis, split_tensor_axis, concat_tensor_axis)
lowering.add_counter(
"alltoall/%s/reshape_op" % mesh_axis, laid_out_size)
for mesh_axis in mesh_axes_allconcat:
tensor_axis = old_shape.cumprod_to_tensor_axis(
mesh_axis_to_cumprod_old[mesh_axis])
assert tensor_axis is not None
slices = mesh_impl.allconcat(slices, mesh_axis, tensor_axis)
laid_out_size *= mesh_impl.shape[mesh_axis].size
lowering.add_counter(
"allconcat/%s/reshape_op" % mesh_axis, laid_out_size)
# now reshape the slices
old_slice_shape = mesh_impl.slice_shape(old_shape)
new_slice_shape = mesh_impl.slice_shape(new_shape)
if new_slice_shape != old_slice_shape:
def reshape_fn(x):
return tf.reshape(x, new_slice_shape)
slices = mesh_impl.slicewise(reshape_fn, slices)
lowering.set_tensor_lowering(self.outputs[0], slices) | python | def lower(self, lowering):
"""Lower the ReshapeOperation.
Reshaping can require collective communication between processors.
We haven't yet implemented all possible reshapes. We try to handle the
common cases here - otherwise we raise a NotImplementedError.
Args:
lowering: a Lowering
Raises:
NotImplementedError: if we haven't covered this case
"""
old_shape = self.inputs[0].shape
new_shape = self.outputs[0].shape
mesh_impl = lowering.mesh_impl(self)
slices = lowering.tensors[self.inputs[0]]
mesh_axis_to_cumprod_old = mesh_impl.mesh_axis_to_cumprod(old_shape)
mesh_axis_to_cumprod_new = mesh_impl.mesh_axis_to_cumprod(new_shape)
# Figure out what needs to be done for different mesh-axes
mesh_axes_allsplit = []
mesh_axes_allconcat = []
mesh_axes_alltoall = []
for mesh_axis, (old_cumprod, new_cumprod) in enumerate(
zip(mesh_axis_to_cumprod_old, mesh_axis_to_cumprod_new)):
if new_cumprod != old_cumprod:
if old_cumprod is None:
# split in new layout but not in old layout - we need an allsplit
mesh_axes_allsplit.append(mesh_axis)
elif new_cumprod is None:
# split in old layout but not in new layout - we need an allconcat
mesh_axes_allconcat.append(mesh_axis)
else:
# split differently in old and new layouts - we need an alltoall
mesh_axes_alltoall.append(mesh_axis)
laid_out_size = mesh_impl.laid_out_size(old_shape)
for mesh_axis in mesh_axes_allsplit:
tensor_axis = old_shape.cumprod_to_tensor_axis(
mesh_axis_to_cumprod_new[mesh_axis])
if tensor_axis is None:
# TODO(noam): try to handle this case
raise NotImplementedError(
"Try first reshaping to insert a new tf dimension,"
" then changing layout. input_shape=%s output_shape=%s"
% (self.inputs[0].shape, self.outputs[0].shape))
slices = mesh_impl.allsplit(slices, mesh_axis, tensor_axis)
laid_out_size //= mesh_impl.shape[mesh_axis].size
for mesh_axis in mesh_axes_alltoall:
split_tensor_axis = old_shape.cumprod_to_tensor_axis(
mesh_axis_to_cumprod_new[mesh_axis])
if split_tensor_axis is None:
# TODO(noam): try to handle this case
raise NotImplementedError(
"Try first reshaping to insert a new tf dimension,"
" then changing layout. input_shape=%s output_shape=%s"
% (self.inputs[0].shape, self.outputs[0].shape))
concat_tensor_axis = old_shape.cumprod_to_tensor_axis(
mesh_axis_to_cumprod_old[mesh_axis])
assert concat_tensor_axis is not None
slices = mesh_impl.alltoall(
slices, mesh_axis, split_tensor_axis, concat_tensor_axis)
lowering.add_counter(
"alltoall/%s/reshape_op" % mesh_axis, laid_out_size)
for mesh_axis in mesh_axes_allconcat:
tensor_axis = old_shape.cumprod_to_tensor_axis(
mesh_axis_to_cumprod_old[mesh_axis])
assert tensor_axis is not None
slices = mesh_impl.allconcat(slices, mesh_axis, tensor_axis)
laid_out_size *= mesh_impl.shape[mesh_axis].size
lowering.add_counter(
"allconcat/%s/reshape_op" % mesh_axis, laid_out_size)
# now reshape the slices
old_slice_shape = mesh_impl.slice_shape(old_shape)
new_slice_shape = mesh_impl.slice_shape(new_shape)
if new_slice_shape != old_slice_shape:
def reshape_fn(x):
return tf.reshape(x, new_slice_shape)
slices = mesh_impl.slicewise(reshape_fn, slices)
lowering.set_tensor_lowering(self.outputs[0], slices) | [
"def",
"lower",
"(",
"self",
",",
"lowering",
")",
":",
"old_shape",
"=",
"self",
".",
"inputs",
"[",
"0",
"]",
".",
"shape",
"new_shape",
"=",
"self",
".",
"outputs",
"[",
"0",
"]",
".",
"shape",
"mesh_impl",
"=",
"lowering",
".",
"mesh_impl",
"(",
"self",
")",
"slices",
"=",
"lowering",
".",
"tensors",
"[",
"self",
".",
"inputs",
"[",
"0",
"]",
"]",
"mesh_axis_to_cumprod_old",
"=",
"mesh_impl",
".",
"mesh_axis_to_cumprod",
"(",
"old_shape",
")",
"mesh_axis_to_cumprod_new",
"=",
"mesh_impl",
".",
"mesh_axis_to_cumprod",
"(",
"new_shape",
")",
"# Figure out what needs to be done for different mesh-axes",
"mesh_axes_allsplit",
"=",
"[",
"]",
"mesh_axes_allconcat",
"=",
"[",
"]",
"mesh_axes_alltoall",
"=",
"[",
"]",
"for",
"mesh_axis",
",",
"(",
"old_cumprod",
",",
"new_cumprod",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"mesh_axis_to_cumprod_old",
",",
"mesh_axis_to_cumprod_new",
")",
")",
":",
"if",
"new_cumprod",
"!=",
"old_cumprod",
":",
"if",
"old_cumprod",
"is",
"None",
":",
"# split in new layout but not in old layout - we need an allsplit",
"mesh_axes_allsplit",
".",
"append",
"(",
"mesh_axis",
")",
"elif",
"new_cumprod",
"is",
"None",
":",
"# split in old layout but not in new layout - we need an allconcat",
"mesh_axes_allconcat",
".",
"append",
"(",
"mesh_axis",
")",
"else",
":",
"# split differently in old and new layouts - we need an alltoall",
"mesh_axes_alltoall",
".",
"append",
"(",
"mesh_axis",
")",
"laid_out_size",
"=",
"mesh_impl",
".",
"laid_out_size",
"(",
"old_shape",
")",
"for",
"mesh_axis",
"in",
"mesh_axes_allsplit",
":",
"tensor_axis",
"=",
"old_shape",
".",
"cumprod_to_tensor_axis",
"(",
"mesh_axis_to_cumprod_new",
"[",
"mesh_axis",
"]",
")",
"if",
"tensor_axis",
"is",
"None",
":",
"# TODO(noam): try to handle this case",
"raise",
"NotImplementedError",
"(",
"\"Try first reshaping to insert a new tf dimension,\"",
"\" then changing layout. input_shape=%s output_shape=%s\"",
"%",
"(",
"self",
".",
"inputs",
"[",
"0",
"]",
".",
"shape",
",",
"self",
".",
"outputs",
"[",
"0",
"]",
".",
"shape",
")",
")",
"slices",
"=",
"mesh_impl",
".",
"allsplit",
"(",
"slices",
",",
"mesh_axis",
",",
"tensor_axis",
")",
"laid_out_size",
"//=",
"mesh_impl",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
"for",
"mesh_axis",
"in",
"mesh_axes_alltoall",
":",
"split_tensor_axis",
"=",
"old_shape",
".",
"cumprod_to_tensor_axis",
"(",
"mesh_axis_to_cumprod_new",
"[",
"mesh_axis",
"]",
")",
"if",
"split_tensor_axis",
"is",
"None",
":",
"# TODO(noam): try to handle this case",
"raise",
"NotImplementedError",
"(",
"\"Try first reshaping to insert a new tf dimension,\"",
"\" then changing layout. input_shape=%s output_shape=%s\"",
"%",
"(",
"self",
".",
"inputs",
"[",
"0",
"]",
".",
"shape",
",",
"self",
".",
"outputs",
"[",
"0",
"]",
".",
"shape",
")",
")",
"concat_tensor_axis",
"=",
"old_shape",
".",
"cumprod_to_tensor_axis",
"(",
"mesh_axis_to_cumprod_old",
"[",
"mesh_axis",
"]",
")",
"assert",
"concat_tensor_axis",
"is",
"not",
"None",
"slices",
"=",
"mesh_impl",
".",
"alltoall",
"(",
"slices",
",",
"mesh_axis",
",",
"split_tensor_axis",
",",
"concat_tensor_axis",
")",
"lowering",
".",
"add_counter",
"(",
"\"alltoall/%s/reshape_op\"",
"%",
"mesh_axis",
",",
"laid_out_size",
")",
"for",
"mesh_axis",
"in",
"mesh_axes_allconcat",
":",
"tensor_axis",
"=",
"old_shape",
".",
"cumprod_to_tensor_axis",
"(",
"mesh_axis_to_cumprod_old",
"[",
"mesh_axis",
"]",
")",
"assert",
"tensor_axis",
"is",
"not",
"None",
"slices",
"=",
"mesh_impl",
".",
"allconcat",
"(",
"slices",
",",
"mesh_axis",
",",
"tensor_axis",
")",
"laid_out_size",
"*=",
"mesh_impl",
".",
"shape",
"[",
"mesh_axis",
"]",
".",
"size",
"lowering",
".",
"add_counter",
"(",
"\"allconcat/%s/reshape_op\"",
"%",
"mesh_axis",
",",
"laid_out_size",
")",
"# now reshape the slices",
"old_slice_shape",
"=",
"mesh_impl",
".",
"slice_shape",
"(",
"old_shape",
")",
"new_slice_shape",
"=",
"mesh_impl",
".",
"slice_shape",
"(",
"new_shape",
")",
"if",
"new_slice_shape",
"!=",
"old_slice_shape",
":",
"def",
"reshape_fn",
"(",
"x",
")",
":",
"return",
"tf",
".",
"reshape",
"(",
"x",
",",
"new_slice_shape",
")",
"slices",
"=",
"mesh_impl",
".",
"slicewise",
"(",
"reshape_fn",
",",
"slices",
")",
"lowering",
".",
"set_tensor_lowering",
"(",
"self",
".",
"outputs",
"[",
"0",
"]",
",",
"slices",
")"
] | Lower the ReshapeOperation.
Reshaping can require collective communication between processors.
We haven't yet implemented all possible reshapes. We try to handle the
common cases here - otherwise we raise a NotImplementedError.
Args:
lowering: a Lowering
Raises:
NotImplementedError: if we haven't covered this case | [
"Lower",
"the",
"ReshapeOperation",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/ops.py#L3478-L3558 |
227,921 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | get_variable_dtype | def get_variable_dtype(
master_dtype=tf.bfloat16,
slice_dtype=tf.float32,
activation_dtype=tf.float32):
"""Datatypes to use for the run.
Args:
master_dtype: string, datatype for checkpoints
keep this the same between training and eval/inference
slice_dtype: string, datatype for variables in memory
must be tf.float32 for training
activation_dtype: string, datatype for activations
less memory usage if tf.bfloat16 but possible numerical issues
Returns:
a mtf.VariableDtype
"""
return mtf.VariableDType(
master_dtype=tf.as_dtype(master_dtype),
slice_dtype=tf.as_dtype(slice_dtype),
activation_dtype=tf.as_dtype(activation_dtype)) | python | def get_variable_dtype(
master_dtype=tf.bfloat16,
slice_dtype=tf.float32,
activation_dtype=tf.float32):
"""Datatypes to use for the run.
Args:
master_dtype: string, datatype for checkpoints
keep this the same between training and eval/inference
slice_dtype: string, datatype for variables in memory
must be tf.float32 for training
activation_dtype: string, datatype for activations
less memory usage if tf.bfloat16 but possible numerical issues
Returns:
a mtf.VariableDtype
"""
return mtf.VariableDType(
master_dtype=tf.as_dtype(master_dtype),
slice_dtype=tf.as_dtype(slice_dtype),
activation_dtype=tf.as_dtype(activation_dtype)) | [
"def",
"get_variable_dtype",
"(",
"master_dtype",
"=",
"tf",
".",
"bfloat16",
",",
"slice_dtype",
"=",
"tf",
".",
"float32",
",",
"activation_dtype",
"=",
"tf",
".",
"float32",
")",
":",
"return",
"mtf",
".",
"VariableDType",
"(",
"master_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"master_dtype",
")",
",",
"slice_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"slice_dtype",
")",
",",
"activation_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"activation_dtype",
")",
")"
] | Datatypes to use for the run.
Args:
master_dtype: string, datatype for checkpoints
keep this the same between training and eval/inference
slice_dtype: string, datatype for variables in memory
must be tf.float32 for training
activation_dtype: string, datatype for activations
less memory usage if tf.bfloat16 but possible numerical issues
Returns:
a mtf.VariableDtype | [
"Datatypes",
"to",
"use",
"for",
"the",
"run",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L38-L57 |
227,922 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | build_model | def build_model(model_type="bitransformer",
input_vocab_size=gin.REQUIRED,
output_vocab_size=gin.REQUIRED,
layout_rules=None,
mesh_shape=None):
"""Build a transformer model.
Currently, three types of models are supported:
"bitransformer": The traditional encoder-decoder architecture from
"attention is all you need". Requires a non-text2self dataset.
"lm": an autoregressive language model (one layer stack). This is similar
to the decoder part of a bitransformer, but with no attention over an
encoder, since there is no encoder. Requires a text2self dataset,
with targets, but no inputs.
"aligned": a non-autoregressive single-stack model (like BERT). Requires
a non-text2self dataset with inputs and targets. The targets are
aligned with the inputs.
Args:
model_type: a string - "bitransformer", "lm" or "aligned"
input_vocab_size: an integer
output_vocab_size: an integer
layout_rules: optional - an input to mtf.convert_to_layout_rules
mesh_shape: optional - an input to mtf.convert_to_shape
Returns:
a Unitransformer or Bitransformer
"""
if model_type == "bitransformer":
return transformer.make_bitransformer(
input_vocab_size=input_vocab_size,
output_vocab_size=output_vocab_size,
mesh_shape=mesh_shape,
layout=layout_rules)
elif model_type == "lm" or model_type == "aligned":
return transformer.Unitransformer(
autoregressive=model_type == "lm",
layer_stack=transformer.make_layer_stack(),
input_vocab_size=input_vocab_size,
output_vocab_size=output_vocab_size,
mesh_shape=mesh_shape,
layout=layout_rules)
else:
raise ValueError("unknown model_type") | python | def build_model(model_type="bitransformer",
input_vocab_size=gin.REQUIRED,
output_vocab_size=gin.REQUIRED,
layout_rules=None,
mesh_shape=None):
"""Build a transformer model.
Currently, three types of models are supported:
"bitransformer": The traditional encoder-decoder architecture from
"attention is all you need". Requires a non-text2self dataset.
"lm": an autoregressive language model (one layer stack). This is similar
to the decoder part of a bitransformer, but with no attention over an
encoder, since there is no encoder. Requires a text2self dataset,
with targets, but no inputs.
"aligned": a non-autoregressive single-stack model (like BERT). Requires
a non-text2self dataset with inputs and targets. The targets are
aligned with the inputs.
Args:
model_type: a string - "bitransformer", "lm" or "aligned"
input_vocab_size: an integer
output_vocab_size: an integer
layout_rules: optional - an input to mtf.convert_to_layout_rules
mesh_shape: optional - an input to mtf.convert_to_shape
Returns:
a Unitransformer or Bitransformer
"""
if model_type == "bitransformer":
return transformer.make_bitransformer(
input_vocab_size=input_vocab_size,
output_vocab_size=output_vocab_size,
mesh_shape=mesh_shape,
layout=layout_rules)
elif model_type == "lm" or model_type == "aligned":
return transformer.Unitransformer(
autoregressive=model_type == "lm",
layer_stack=transformer.make_layer_stack(),
input_vocab_size=input_vocab_size,
output_vocab_size=output_vocab_size,
mesh_shape=mesh_shape,
layout=layout_rules)
else:
raise ValueError("unknown model_type") | [
"def",
"build_model",
"(",
"model_type",
"=",
"\"bitransformer\"",
",",
"input_vocab_size",
"=",
"gin",
".",
"REQUIRED",
",",
"output_vocab_size",
"=",
"gin",
".",
"REQUIRED",
",",
"layout_rules",
"=",
"None",
",",
"mesh_shape",
"=",
"None",
")",
":",
"if",
"model_type",
"==",
"\"bitransformer\"",
":",
"return",
"transformer",
".",
"make_bitransformer",
"(",
"input_vocab_size",
"=",
"input_vocab_size",
",",
"output_vocab_size",
"=",
"output_vocab_size",
",",
"mesh_shape",
"=",
"mesh_shape",
",",
"layout",
"=",
"layout_rules",
")",
"elif",
"model_type",
"==",
"\"lm\"",
"or",
"model_type",
"==",
"\"aligned\"",
":",
"return",
"transformer",
".",
"Unitransformer",
"(",
"autoregressive",
"=",
"model_type",
"==",
"\"lm\"",
",",
"layer_stack",
"=",
"transformer",
".",
"make_layer_stack",
"(",
")",
",",
"input_vocab_size",
"=",
"input_vocab_size",
",",
"output_vocab_size",
"=",
"output_vocab_size",
",",
"mesh_shape",
"=",
"mesh_shape",
",",
"layout",
"=",
"layout_rules",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"unknown model_type\"",
")"
] | Build a transformer model.
Currently, three types of models are supported:
"bitransformer": The traditional encoder-decoder architecture from
"attention is all you need". Requires a non-text2self dataset.
"lm": an autoregressive language model (one layer stack). This is similar
to the decoder part of a bitransformer, but with no attention over an
encoder, since there is no encoder. Requires a text2self dataset,
with targets, but no inputs.
"aligned": a non-autoregressive single-stack model (like BERT). Requires
a non-text2self dataset with inputs and targets. The targets are
aligned with the inputs.
Args:
model_type: a string - "bitransformer", "lm" or "aligned"
input_vocab_size: an integer
output_vocab_size: an integer
layout_rules: optional - an input to mtf.convert_to_layout_rules
mesh_shape: optional - an input to mtf.convert_to_shape
Returns:
a Unitransformer or Bitransformer | [
"Build",
"a",
"transformer",
"model",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L94-L139 |
227,923 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | decode_from_file | def decode_from_file(estimator,
vocabulary,
model_type,
batch_size,
sequence_length,
checkpoint_path="",
input_filename=gin.REQUIRED,
output_filename=gin.REQUIRED,
eos_id=1):
"""Decode from a text file.
Args:
estimator: a TPUEstimator
vocabulary: a mtf.transformer.vocabulary.Vocabulary
model_type: a string
batch_size: an integer
sequence_length: an integer (maximum decode length)
checkpoint_path: an optional string
input_filename: a string
output_filename: a string
eos_id: EOS id
"""
with tf.gfile.Open(input_filename) as f:
text = f.read()
records = text.split("\n")
inputs = [record.strip() for record in records]
# Strip the last empty line.
if not inputs[-1]:
inputs.pop()
n = len(inputs)
# encode all inputs
all_input_ids = []
for line in inputs:
ids = inputs_vocabulary(vocabulary).encode(line.strip())
if model_type != "lm":
# for text2self problems, the inputs represent a partial sequence
# to be continued, and should not be terminated by EOS.
# for sequence-to-sequence problems, the input needs to be EOS-terminated
ids += [eos_id]
if len(ids) > sequence_length:
ids = ids[:sequence_length]
else:
ids.extend([0] * (sequence_length - len(ids)))
all_input_ids.append(ids)
# pad to make an integral number of batches
all_input_ids.extend([all_input_ids[0]] * (-n % batch_size))
padded_n = len(all_input_ids)
all_input_ids = np.array(all_input_ids, dtype=np.int32)
def input_fn(params):
del params
dataset = tf.data.Dataset.from_tensor_slices({"inputs": all_input_ids})
dataset = dataset.batch(batch_size, drop_remainder=True)
return dataset
result_iter = estimator.predict(input_fn, checkpoint_path=checkpoint_path)
vocab_size = targets_vocabulary(vocabulary).vocab_size
decodes = []
for i, result in enumerate(result_iter):
output_ids = clean_decodes(list(result["outputs"]), vocab_size)
output_string = targets_vocabulary(vocabulary).decode(
[int(x) for x in output_ids])
decodes.append(output_string)
if i & (i - 1) == 0:
if i < len(inputs):
# LOG every power of 2, don't log if it's padded input i >= len(inputs)
tf.logging.info("decode %d input = %s" % (i, inputs[i]))
tf.logging.info(" output = %s" % output_string)
# BUG WORKAROUND - on TF1.13 and earlier, the output for each batch is
# repeated a number of times equal to the number of cores.
if len(decodes) == padded_n:
tf.logging.info("number of decodes matches number of inputs")
elif len(decodes) % padded_n == 0:
num_cores = len(decodes) // padded_n
tf.logging.info("output is repeated num_cores times - removing extras")
def keep(i):
return i % (batch_size * num_cores) < batch_size
decodes = [d for i, d in enumerate(decodes) if keep(i)]
else:
raise ValueError("unexpected number of outputs")
output_file = tf.gfile.Open(output_filename, "w")
decodes = decodes[:n]
for d in decodes:
output_file.write(d)
output_file.write("\n")
output_file.close() | python | def decode_from_file(estimator,
vocabulary,
model_type,
batch_size,
sequence_length,
checkpoint_path="",
input_filename=gin.REQUIRED,
output_filename=gin.REQUIRED,
eos_id=1):
"""Decode from a text file.
Args:
estimator: a TPUEstimator
vocabulary: a mtf.transformer.vocabulary.Vocabulary
model_type: a string
batch_size: an integer
sequence_length: an integer (maximum decode length)
checkpoint_path: an optional string
input_filename: a string
output_filename: a string
eos_id: EOS id
"""
with tf.gfile.Open(input_filename) as f:
text = f.read()
records = text.split("\n")
inputs = [record.strip() for record in records]
# Strip the last empty line.
if not inputs[-1]:
inputs.pop()
n = len(inputs)
# encode all inputs
all_input_ids = []
for line in inputs:
ids = inputs_vocabulary(vocabulary).encode(line.strip())
if model_type != "lm":
# for text2self problems, the inputs represent a partial sequence
# to be continued, and should not be terminated by EOS.
# for sequence-to-sequence problems, the input needs to be EOS-terminated
ids += [eos_id]
if len(ids) > sequence_length:
ids = ids[:sequence_length]
else:
ids.extend([0] * (sequence_length - len(ids)))
all_input_ids.append(ids)
# pad to make an integral number of batches
all_input_ids.extend([all_input_ids[0]] * (-n % batch_size))
padded_n = len(all_input_ids)
all_input_ids = np.array(all_input_ids, dtype=np.int32)
def input_fn(params):
del params
dataset = tf.data.Dataset.from_tensor_slices({"inputs": all_input_ids})
dataset = dataset.batch(batch_size, drop_remainder=True)
return dataset
result_iter = estimator.predict(input_fn, checkpoint_path=checkpoint_path)
vocab_size = targets_vocabulary(vocabulary).vocab_size
decodes = []
for i, result in enumerate(result_iter):
output_ids = clean_decodes(list(result["outputs"]), vocab_size)
output_string = targets_vocabulary(vocabulary).decode(
[int(x) for x in output_ids])
decodes.append(output_string)
if i & (i - 1) == 0:
if i < len(inputs):
# LOG every power of 2, don't log if it's padded input i >= len(inputs)
tf.logging.info("decode %d input = %s" % (i, inputs[i]))
tf.logging.info(" output = %s" % output_string)
# BUG WORKAROUND - on TF1.13 and earlier, the output for each batch is
# repeated a number of times equal to the number of cores.
if len(decodes) == padded_n:
tf.logging.info("number of decodes matches number of inputs")
elif len(decodes) % padded_n == 0:
num_cores = len(decodes) // padded_n
tf.logging.info("output is repeated num_cores times - removing extras")
def keep(i):
return i % (batch_size * num_cores) < batch_size
decodes = [d for i, d in enumerate(decodes) if keep(i)]
else:
raise ValueError("unexpected number of outputs")
output_file = tf.gfile.Open(output_filename, "w")
decodes = decodes[:n]
for d in decodes:
output_file.write(d)
output_file.write("\n")
output_file.close() | [
"def",
"decode_from_file",
"(",
"estimator",
",",
"vocabulary",
",",
"model_type",
",",
"batch_size",
",",
"sequence_length",
",",
"checkpoint_path",
"=",
"\"\"",
",",
"input_filename",
"=",
"gin",
".",
"REQUIRED",
",",
"output_filename",
"=",
"gin",
".",
"REQUIRED",
",",
"eos_id",
"=",
"1",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"input_filename",
")",
"as",
"f",
":",
"text",
"=",
"f",
".",
"read",
"(",
")",
"records",
"=",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
"inputs",
"=",
"[",
"record",
".",
"strip",
"(",
")",
"for",
"record",
"in",
"records",
"]",
"# Strip the last empty line.",
"if",
"not",
"inputs",
"[",
"-",
"1",
"]",
":",
"inputs",
".",
"pop",
"(",
")",
"n",
"=",
"len",
"(",
"inputs",
")",
"# encode all inputs",
"all_input_ids",
"=",
"[",
"]",
"for",
"line",
"in",
"inputs",
":",
"ids",
"=",
"inputs_vocabulary",
"(",
"vocabulary",
")",
".",
"encode",
"(",
"line",
".",
"strip",
"(",
")",
")",
"if",
"model_type",
"!=",
"\"lm\"",
":",
"# for text2self problems, the inputs represent a partial sequence",
"# to be continued, and should not be terminated by EOS.",
"# for sequence-to-sequence problems, the input needs to be EOS-terminated",
"ids",
"+=",
"[",
"eos_id",
"]",
"if",
"len",
"(",
"ids",
")",
">",
"sequence_length",
":",
"ids",
"=",
"ids",
"[",
":",
"sequence_length",
"]",
"else",
":",
"ids",
".",
"extend",
"(",
"[",
"0",
"]",
"*",
"(",
"sequence_length",
"-",
"len",
"(",
"ids",
")",
")",
")",
"all_input_ids",
".",
"append",
"(",
"ids",
")",
"# pad to make an integral number of batches",
"all_input_ids",
".",
"extend",
"(",
"[",
"all_input_ids",
"[",
"0",
"]",
"]",
"*",
"(",
"-",
"n",
"%",
"batch_size",
")",
")",
"padded_n",
"=",
"len",
"(",
"all_input_ids",
")",
"all_input_ids",
"=",
"np",
".",
"array",
"(",
"all_input_ids",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
"def",
"input_fn",
"(",
"params",
")",
":",
"del",
"params",
"dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_tensor_slices",
"(",
"{",
"\"inputs\"",
":",
"all_input_ids",
"}",
")",
"dataset",
"=",
"dataset",
".",
"batch",
"(",
"batch_size",
",",
"drop_remainder",
"=",
"True",
")",
"return",
"dataset",
"result_iter",
"=",
"estimator",
".",
"predict",
"(",
"input_fn",
",",
"checkpoint_path",
"=",
"checkpoint_path",
")",
"vocab_size",
"=",
"targets_vocabulary",
"(",
"vocabulary",
")",
".",
"vocab_size",
"decodes",
"=",
"[",
"]",
"for",
"i",
",",
"result",
"in",
"enumerate",
"(",
"result_iter",
")",
":",
"output_ids",
"=",
"clean_decodes",
"(",
"list",
"(",
"result",
"[",
"\"outputs\"",
"]",
")",
",",
"vocab_size",
")",
"output_string",
"=",
"targets_vocabulary",
"(",
"vocabulary",
")",
".",
"decode",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"output_ids",
"]",
")",
"decodes",
".",
"append",
"(",
"output_string",
")",
"if",
"i",
"&",
"(",
"i",
"-",
"1",
")",
"==",
"0",
":",
"if",
"i",
"<",
"len",
"(",
"inputs",
")",
":",
"# LOG every power of 2, don't log if it's padded input i >= len(inputs)",
"tf",
".",
"logging",
".",
"info",
"(",
"\"decode %d input = %s\"",
"%",
"(",
"i",
",",
"inputs",
"[",
"i",
"]",
")",
")",
"tf",
".",
"logging",
".",
"info",
"(",
"\" output = %s\"",
"%",
"output_string",
")",
"# BUG WORKAROUND - on TF1.13 and earlier, the output for each batch is",
"# repeated a number of times equal to the number of cores.",
"if",
"len",
"(",
"decodes",
")",
"==",
"padded_n",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"number of decodes matches number of inputs\"",
")",
"elif",
"len",
"(",
"decodes",
")",
"%",
"padded_n",
"==",
"0",
":",
"num_cores",
"=",
"len",
"(",
"decodes",
")",
"//",
"padded_n",
"tf",
".",
"logging",
".",
"info",
"(",
"\"output is repeated num_cores times - removing extras\"",
")",
"def",
"keep",
"(",
"i",
")",
":",
"return",
"i",
"%",
"(",
"batch_size",
"*",
"num_cores",
")",
"<",
"batch_size",
"decodes",
"=",
"[",
"d",
"for",
"i",
",",
"d",
"in",
"enumerate",
"(",
"decodes",
")",
"if",
"keep",
"(",
"i",
")",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"\"unexpected number of outputs\"",
")",
"output_file",
"=",
"tf",
".",
"gfile",
".",
"Open",
"(",
"output_filename",
",",
"\"w\"",
")",
"decodes",
"=",
"decodes",
"[",
":",
"n",
"]",
"for",
"d",
"in",
"decodes",
":",
"output_file",
".",
"write",
"(",
"d",
")",
"output_file",
".",
"write",
"(",
"\"\\n\"",
")",
"output_file",
".",
"close",
"(",
")"
] | Decode from a text file.
Args:
estimator: a TPUEstimator
vocabulary: a mtf.transformer.vocabulary.Vocabulary
model_type: a string
batch_size: an integer
sequence_length: an integer (maximum decode length)
checkpoint_path: an optional string
input_filename: a string
output_filename: a string
eos_id: EOS id | [
"Decode",
"from",
"a",
"text",
"file",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L385-L473 |
227,924 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | clean_decodes | def clean_decodes(ids, vocab_size, eos_id=1):
"""Stop at EOS or padding or OOV.
Args:
ids: a list of integers
vocab_size: an integer
eos_id: EOS id
Returns:
a list of integers
"""
ret = []
for i in ids:
if i == eos_id:
break
if i >= vocab_size:
break
ret.append(int(i))
return ret | python | def clean_decodes(ids, vocab_size, eos_id=1):
"""Stop at EOS or padding or OOV.
Args:
ids: a list of integers
vocab_size: an integer
eos_id: EOS id
Returns:
a list of integers
"""
ret = []
for i in ids:
if i == eos_id:
break
if i >= vocab_size:
break
ret.append(int(i))
return ret | [
"def",
"clean_decodes",
"(",
"ids",
",",
"vocab_size",
",",
"eos_id",
"=",
"1",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"i",
"in",
"ids",
":",
"if",
"i",
"==",
"eos_id",
":",
"break",
"if",
"i",
">=",
"vocab_size",
":",
"break",
"ret",
".",
"append",
"(",
"int",
"(",
"i",
")",
")",
"return",
"ret"
] | Stop at EOS or padding or OOV.
Args:
ids: a list of integers
vocab_size: an integer
eos_id: EOS id
Returns:
a list of integers | [
"Stop",
"at",
"EOS",
"or",
"padding",
"or",
"OOV",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L477-L495 |
227,925 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | auto_batch_size | def auto_batch_size(sequence_length,
mesh_shape,
layout_rules,
tokens_per_split=2048):
"""Automatically compute batch size.
Args:
sequence_length: an integer
mesh_shape: an input to mtf.convert_to_shape()
layout_rules: an input to mtf.convert_to_layout_rules()
tokens_per_split: an integer
Returns:
an integer
"""
num_splits = mtf.tensor_dim_to_mesh_dim_size(
layout_rules, mesh_shape, mtf.Dimension("batch", 0))
ret = max(1, tokens_per_split // sequence_length) * num_splits
tf.logging.info(
"AUTO_BATCH_SIZE tokens_per_split=%s num_splits=%s"
" sequence_length=%s batch_size=%s"
% (tokens_per_split, num_splits, sequence_length, ret))
return ret | python | def auto_batch_size(sequence_length,
mesh_shape,
layout_rules,
tokens_per_split=2048):
"""Automatically compute batch size.
Args:
sequence_length: an integer
mesh_shape: an input to mtf.convert_to_shape()
layout_rules: an input to mtf.convert_to_layout_rules()
tokens_per_split: an integer
Returns:
an integer
"""
num_splits = mtf.tensor_dim_to_mesh_dim_size(
layout_rules, mesh_shape, mtf.Dimension("batch", 0))
ret = max(1, tokens_per_split // sequence_length) * num_splits
tf.logging.info(
"AUTO_BATCH_SIZE tokens_per_split=%s num_splits=%s"
" sequence_length=%s batch_size=%s"
% (tokens_per_split, num_splits, sequence_length, ret))
return ret | [
"def",
"auto_batch_size",
"(",
"sequence_length",
",",
"mesh_shape",
",",
"layout_rules",
",",
"tokens_per_split",
"=",
"2048",
")",
":",
"num_splits",
"=",
"mtf",
".",
"tensor_dim_to_mesh_dim_size",
"(",
"layout_rules",
",",
"mesh_shape",
",",
"mtf",
".",
"Dimension",
"(",
"\"batch\"",
",",
"0",
")",
")",
"ret",
"=",
"max",
"(",
"1",
",",
"tokens_per_split",
"//",
"sequence_length",
")",
"*",
"num_splits",
"tf",
".",
"logging",
".",
"info",
"(",
"\"AUTO_BATCH_SIZE tokens_per_split=%s num_splits=%s\"",
"\" sequence_length=%s batch_size=%s\"",
"%",
"(",
"tokens_per_split",
",",
"num_splits",
",",
"sequence_length",
",",
"ret",
")",
")",
"return",
"ret"
] | Automatically compute batch size.
Args:
sequence_length: an integer
mesh_shape: an input to mtf.convert_to_shape()
layout_rules: an input to mtf.convert_to_layout_rules()
tokens_per_split: an integer
Returns:
an integer | [
"Automatically",
"compute",
"batch",
"size",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L499-L520 |
227,926 | tensorflow/mesh | mesh_tensorflow/transformer/utils.py | evaluate | def evaluate(estimator, eval_args):
"""Runs evaluation on the latest model checkpoint & logs to tensorboard.
Args:
estimator: A tf.Estimator object.
eval_args: Dictionary of {eval_name: (input_fn, eval_steps)} where eval_name
is the name of the evaluation set, e.g. "train" or "val", input_fn is an
input function returning a tuple (features, labels), and eval_steps is the
number of steps for which to evaluate the model. If None, evaluates until
input_fn raises an end-of-input exception.
Returns:
A dict of metric values from the evaluation. May be empty, e.g. if the
training job has not yet saved a checkpoint or the checkpoint is deleted by
the time the TPU worker initializes.
"""
values = {} # Default return value if evaluation fails.
checkpoint_path = estimator.latest_checkpoint()
if not checkpoint_path:
# This is expected if the training job has not yet saved a checkpoint.
return values
tf.logging.info("Starting evaluation on checkpoint %s", checkpoint_path)
for eval_name in eval_args:
input_fn, eval_steps = eval_args[eval_name]
metric_values = estimator.evaluate(
input_fn,
steps=eval_steps,
name=eval_name,
checkpoint_path=checkpoint_path)
for key, val in metric_values.iteritems():
values[eval_name + "/" + key] = val
tf.logging.info(values)
return values | python | def evaluate(estimator, eval_args):
"""Runs evaluation on the latest model checkpoint & logs to tensorboard.
Args:
estimator: A tf.Estimator object.
eval_args: Dictionary of {eval_name: (input_fn, eval_steps)} where eval_name
is the name of the evaluation set, e.g. "train" or "val", input_fn is an
input function returning a tuple (features, labels), and eval_steps is the
number of steps for which to evaluate the model. If None, evaluates until
input_fn raises an end-of-input exception.
Returns:
A dict of metric values from the evaluation. May be empty, e.g. if the
training job has not yet saved a checkpoint or the checkpoint is deleted by
the time the TPU worker initializes.
"""
values = {} # Default return value if evaluation fails.
checkpoint_path = estimator.latest_checkpoint()
if not checkpoint_path:
# This is expected if the training job has not yet saved a checkpoint.
return values
tf.logging.info("Starting evaluation on checkpoint %s", checkpoint_path)
for eval_name in eval_args:
input_fn, eval_steps = eval_args[eval_name]
metric_values = estimator.evaluate(
input_fn,
steps=eval_steps,
name=eval_name,
checkpoint_path=checkpoint_path)
for key, val in metric_values.iteritems():
values[eval_name + "/" + key] = val
tf.logging.info(values)
return values | [
"def",
"evaluate",
"(",
"estimator",
",",
"eval_args",
")",
":",
"values",
"=",
"{",
"}",
"# Default return value if evaluation fails.",
"checkpoint_path",
"=",
"estimator",
".",
"latest_checkpoint",
"(",
")",
"if",
"not",
"checkpoint_path",
":",
"# This is expected if the training job has not yet saved a checkpoint.",
"return",
"values",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Starting evaluation on checkpoint %s\"",
",",
"checkpoint_path",
")",
"for",
"eval_name",
"in",
"eval_args",
":",
"input_fn",
",",
"eval_steps",
"=",
"eval_args",
"[",
"eval_name",
"]",
"metric_values",
"=",
"estimator",
".",
"evaluate",
"(",
"input_fn",
",",
"steps",
"=",
"eval_steps",
",",
"name",
"=",
"eval_name",
",",
"checkpoint_path",
"=",
"checkpoint_path",
")",
"for",
"key",
",",
"val",
"in",
"metric_values",
".",
"iteritems",
"(",
")",
":",
"values",
"[",
"eval_name",
"+",
"\"/\"",
"+",
"key",
"]",
"=",
"val",
"tf",
".",
"logging",
".",
"info",
"(",
"values",
")",
"return",
"values"
] | Runs evaluation on the latest model checkpoint & logs to tensorboard.
Args:
estimator: A tf.Estimator object.
eval_args: Dictionary of {eval_name: (input_fn, eval_steps)} where eval_name
is the name of the evaluation set, e.g. "train" or "val", input_fn is an
input function returning a tuple (features, labels), and eval_steps is the
number of steps for which to evaluate the model. If None, evaluates until
input_fn raises an end-of-input exception.
Returns:
A dict of metric values from the evaluation. May be empty, e.g. if the
training job has not yet saved a checkpoint or the checkpoint is deleted by
the time the TPU worker initializes. | [
"Runs",
"evaluation",
"on",
"the",
"latest",
"model",
"checkpoint",
"&",
"logs",
"to",
"tensorboard",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/transformer/utils.py#L715-L750 |
227,927 | tensorflow/mesh | mesh_tensorflow/simd_mesh_impl.py | _ring_2d | def _ring_2d(m, n):
"""Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs
"""
if m == 1:
return [(0, i) for i in range(n)]
if n == 1:
return [(i, 0) for i in range(m)]
if m % 2 != 0:
tf.logging.warning("Odd dimension")
return [(i % m, i // m) for i in range(n * m)]
ret = [(0, 0)]
for i in range(m // 2):
for j in range(1, n):
ret.append((2 * i, j))
for j in range(n-1, 0, -1):
ret.append((2 * i + 1, j))
for i in range(m-1, 0, -1):
ret.append((i, 0))
return ret | python | def _ring_2d(m, n):
"""Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs
"""
if m == 1:
return [(0, i) for i in range(n)]
if n == 1:
return [(i, 0) for i in range(m)]
if m % 2 != 0:
tf.logging.warning("Odd dimension")
return [(i % m, i // m) for i in range(n * m)]
ret = [(0, 0)]
for i in range(m // 2):
for j in range(1, n):
ret.append((2 * i, j))
for j in range(n-1, 0, -1):
ret.append((2 * i + 1, j))
for i in range(m-1, 0, -1):
ret.append((i, 0))
return ret | [
"def",
"_ring_2d",
"(",
"m",
",",
"n",
")",
":",
"if",
"m",
"==",
"1",
":",
"return",
"[",
"(",
"0",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"if",
"n",
"==",
"1",
":",
"return",
"[",
"(",
"i",
",",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"m",
")",
"]",
"if",
"m",
"%",
"2",
"!=",
"0",
":",
"tf",
".",
"logging",
".",
"warning",
"(",
"\"Odd dimension\"",
")",
"return",
"[",
"(",
"i",
"%",
"m",
",",
"i",
"//",
"m",
")",
"for",
"i",
"in",
"range",
"(",
"n",
"*",
"m",
")",
"]",
"ret",
"=",
"[",
"(",
"0",
",",
"0",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"m",
"//",
"2",
")",
":",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"ret",
".",
"append",
"(",
"(",
"2",
"*",
"i",
",",
"j",
")",
")",
"for",
"j",
"in",
"range",
"(",
"n",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"ret",
".",
"append",
"(",
"(",
"2",
"*",
"i",
"+",
"1",
",",
"j",
")",
")",
"for",
"i",
"in",
"range",
"(",
"m",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"ret",
".",
"append",
"(",
"(",
"i",
",",
"0",
")",
")",
"return",
"ret"
] | Ring-order of a mxn mesh.
Args:
m: an integer
n: an integer
Returns:
a list of mxn pairs | [
"Ring",
"-",
"order",
"of",
"a",
"mxn",
"mesh",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L568-L592 |
227,928 | tensorflow/mesh | mesh_tensorflow/simd_mesh_impl.py | tile_2d | def tile_2d(physical_shape, tile_shape,
outer_name="outer",
inner_name="inner",
cores_name=None):
"""2D tiling of a 3d physical mesh.
The "outer" mesh dimension corresponds to which tile.
The "inner" mesh dimension corresponds to the position within a tile
of processors.
Optionally, if cores_name is specified, then a 3 dimensional logical mesh
is returned, with the third dimension representing the two different
cores within a chip. If cores_name is not specified, then the
cores-in-a-chip dimension is folded into the inner dimension.
TODO(noam): explain this better.
Example:
tile_2d(physical_shape=[8, 16, 2], tile_shape=[4, 4])
The "inner" dimension has size 4x4x2=32 and corresponds to the position
within a 4x4 tile of processors.
The "outer" dimension has size 8/4 * 16/4 = 8, and corresponds to the 8
tiles in the mesh.
Args:
physical_shape: a triple of integers [X, Y, cores]
tile_shape: a pair
outer_name: a string
inner_name: a string
cores_name: an optional string
Returns:
mesh_shape: a mtf.Shape
logical_to_physical: a list
"""
logical_to_physical = []
p0, p1, p2 = physical_shape
t0, t1 = tile_shape
tile_ring = _ring_2d(t0, t1)
tiles_ring = _ring_2d(p0 // t0, p1 // t1)
for logical_pnum in range(p0 * p1 * p2):
core_on_chip = logical_pnum % p2
logical_chip_num = logical_pnum // p2
logical_pos_in_tile = logical_chip_num % (t0 * t1)
logical_tile_num = logical_chip_num // (t0 * t1)
tile_i, tile_j = tile_ring[logical_pos_in_tile]
tiles_i, tiles_j = tiles_ring[logical_tile_num]
physical_pnum = core_on_chip + p2 * (
tile_i * p1 + tile_j +
tiles_i * p1 * t0 + tiles_j * t1)
logical_to_physical.append(physical_pnum)
assert sorted(logical_to_physical) == list(range(p0 * p1 * p2))
tile_size = t0 * t1 * p2
num_tiles = p0 * p1 // (t0 * t1)
if cores_name:
mesh_shape = mtf.Shape(
[mtf.Dimension(outer_name, int(num_tiles)),
mtf.Dimension(inner_name, int(t0 * t1)),
mtf.Dimension(cores_name, int(p2))])
else:
mesh_shape = mtf.Shape(
[mtf.Dimension(outer_name, int(num_tiles)),
mtf.Dimension(inner_name, int(tile_size))])
return mesh_shape, logical_to_physical | python | def tile_2d(physical_shape, tile_shape,
outer_name="outer",
inner_name="inner",
cores_name=None):
"""2D tiling of a 3d physical mesh.
The "outer" mesh dimension corresponds to which tile.
The "inner" mesh dimension corresponds to the position within a tile
of processors.
Optionally, if cores_name is specified, then a 3 dimensional logical mesh
is returned, with the third dimension representing the two different
cores within a chip. If cores_name is not specified, then the
cores-in-a-chip dimension is folded into the inner dimension.
TODO(noam): explain this better.
Example:
tile_2d(physical_shape=[8, 16, 2], tile_shape=[4, 4])
The "inner" dimension has size 4x4x2=32 and corresponds to the position
within a 4x4 tile of processors.
The "outer" dimension has size 8/4 * 16/4 = 8, and corresponds to the 8
tiles in the mesh.
Args:
physical_shape: a triple of integers [X, Y, cores]
tile_shape: a pair
outer_name: a string
inner_name: a string
cores_name: an optional string
Returns:
mesh_shape: a mtf.Shape
logical_to_physical: a list
"""
logical_to_physical = []
p0, p1, p2 = physical_shape
t0, t1 = tile_shape
tile_ring = _ring_2d(t0, t1)
tiles_ring = _ring_2d(p0 // t0, p1 // t1)
for logical_pnum in range(p0 * p1 * p2):
core_on_chip = logical_pnum % p2
logical_chip_num = logical_pnum // p2
logical_pos_in_tile = logical_chip_num % (t0 * t1)
logical_tile_num = logical_chip_num // (t0 * t1)
tile_i, tile_j = tile_ring[logical_pos_in_tile]
tiles_i, tiles_j = tiles_ring[logical_tile_num]
physical_pnum = core_on_chip + p2 * (
tile_i * p1 + tile_j +
tiles_i * p1 * t0 + tiles_j * t1)
logical_to_physical.append(physical_pnum)
assert sorted(logical_to_physical) == list(range(p0 * p1 * p2))
tile_size = t0 * t1 * p2
num_tiles = p0 * p1 // (t0 * t1)
if cores_name:
mesh_shape = mtf.Shape(
[mtf.Dimension(outer_name, int(num_tiles)),
mtf.Dimension(inner_name, int(t0 * t1)),
mtf.Dimension(cores_name, int(p2))])
else:
mesh_shape = mtf.Shape(
[mtf.Dimension(outer_name, int(num_tiles)),
mtf.Dimension(inner_name, int(tile_size))])
return mesh_shape, logical_to_physical | [
"def",
"tile_2d",
"(",
"physical_shape",
",",
"tile_shape",
",",
"outer_name",
"=",
"\"outer\"",
",",
"inner_name",
"=",
"\"inner\"",
",",
"cores_name",
"=",
"None",
")",
":",
"logical_to_physical",
"=",
"[",
"]",
"p0",
",",
"p1",
",",
"p2",
"=",
"physical_shape",
"t0",
",",
"t1",
"=",
"tile_shape",
"tile_ring",
"=",
"_ring_2d",
"(",
"t0",
",",
"t1",
")",
"tiles_ring",
"=",
"_ring_2d",
"(",
"p0",
"//",
"t0",
",",
"p1",
"//",
"t1",
")",
"for",
"logical_pnum",
"in",
"range",
"(",
"p0",
"*",
"p1",
"*",
"p2",
")",
":",
"core_on_chip",
"=",
"logical_pnum",
"%",
"p2",
"logical_chip_num",
"=",
"logical_pnum",
"//",
"p2",
"logical_pos_in_tile",
"=",
"logical_chip_num",
"%",
"(",
"t0",
"*",
"t1",
")",
"logical_tile_num",
"=",
"logical_chip_num",
"//",
"(",
"t0",
"*",
"t1",
")",
"tile_i",
",",
"tile_j",
"=",
"tile_ring",
"[",
"logical_pos_in_tile",
"]",
"tiles_i",
",",
"tiles_j",
"=",
"tiles_ring",
"[",
"logical_tile_num",
"]",
"physical_pnum",
"=",
"core_on_chip",
"+",
"p2",
"*",
"(",
"tile_i",
"*",
"p1",
"+",
"tile_j",
"+",
"tiles_i",
"*",
"p1",
"*",
"t0",
"+",
"tiles_j",
"*",
"t1",
")",
"logical_to_physical",
".",
"append",
"(",
"physical_pnum",
")",
"assert",
"sorted",
"(",
"logical_to_physical",
")",
"==",
"list",
"(",
"range",
"(",
"p0",
"*",
"p1",
"*",
"p2",
")",
")",
"tile_size",
"=",
"t0",
"*",
"t1",
"*",
"p2",
"num_tiles",
"=",
"p0",
"*",
"p1",
"//",
"(",
"t0",
"*",
"t1",
")",
"if",
"cores_name",
":",
"mesh_shape",
"=",
"mtf",
".",
"Shape",
"(",
"[",
"mtf",
".",
"Dimension",
"(",
"outer_name",
",",
"int",
"(",
"num_tiles",
")",
")",
",",
"mtf",
".",
"Dimension",
"(",
"inner_name",
",",
"int",
"(",
"t0",
"*",
"t1",
")",
")",
",",
"mtf",
".",
"Dimension",
"(",
"cores_name",
",",
"int",
"(",
"p2",
")",
")",
"]",
")",
"else",
":",
"mesh_shape",
"=",
"mtf",
".",
"Shape",
"(",
"[",
"mtf",
".",
"Dimension",
"(",
"outer_name",
",",
"int",
"(",
"num_tiles",
")",
")",
",",
"mtf",
".",
"Dimension",
"(",
"inner_name",
",",
"int",
"(",
"tile_size",
")",
")",
"]",
")",
"return",
"mesh_shape",
",",
"logical_to_physical"
] | 2D tiling of a 3d physical mesh.
The "outer" mesh dimension corresponds to which tile.
The "inner" mesh dimension corresponds to the position within a tile
of processors.
Optionally, if cores_name is specified, then a 3 dimensional logical mesh
is returned, with the third dimension representing the two different
cores within a chip. If cores_name is not specified, then the
cores-in-a-chip dimension is folded into the inner dimension.
TODO(noam): explain this better.
Example:
tile_2d(physical_shape=[8, 16, 2], tile_shape=[4, 4])
The "inner" dimension has size 4x4x2=32 and corresponds to the position
within a 4x4 tile of processors.
The "outer" dimension has size 8/4 * 16/4 = 8, and corresponds to the 8
tiles in the mesh.
Args:
physical_shape: a triple of integers [X, Y, cores]
tile_shape: a pair
outer_name: a string
inner_name: a string
cores_name: an optional string
Returns:
mesh_shape: a mtf.Shape
logical_to_physical: a list | [
"2D",
"tiling",
"of",
"a",
"3d",
"physical",
"mesh",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L595-L661 |
227,929 | tensorflow/mesh | mesh_tensorflow/simd_mesh_impl.py | SimdMeshImpl.slice | def slice(self, tf_tensor, tensor_shape):
""""Slice out the corresponding part of tensor given the pnum variable."""
tensor_layout = self.tensor_layout(tensor_shape)
if tensor_layout.is_fully_replicated:
return self.LaidOutTensor([tf_tensor])
else:
slice_shape = self.slice_shape(tensor_shape)
slice_begins = [
self.slice_begin(tensor_shape, pnum) for pnum in xrange(self.size)
]
slice_begins_tensor = tf.stack(slice_begins)
# slice on source device
selected_slice_begin = tf.gather(slice_begins_tensor, self.pnum_tensor)
return self.LaidOutTensor(
[tf.slice(tf_tensor, selected_slice_begin, slice_shape)]) | python | def slice(self, tf_tensor, tensor_shape):
""""Slice out the corresponding part of tensor given the pnum variable."""
tensor_layout = self.tensor_layout(tensor_shape)
if tensor_layout.is_fully_replicated:
return self.LaidOutTensor([tf_tensor])
else:
slice_shape = self.slice_shape(tensor_shape)
slice_begins = [
self.slice_begin(tensor_shape, pnum) for pnum in xrange(self.size)
]
slice_begins_tensor = tf.stack(slice_begins)
# slice on source device
selected_slice_begin = tf.gather(slice_begins_tensor, self.pnum_tensor)
return self.LaidOutTensor(
[tf.slice(tf_tensor, selected_slice_begin, slice_shape)]) | [
"def",
"slice",
"(",
"self",
",",
"tf_tensor",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"if",
"tensor_layout",
".",
"is_fully_replicated",
":",
"return",
"self",
".",
"LaidOutTensor",
"(",
"[",
"tf_tensor",
"]",
")",
"else",
":",
"slice_shape",
"=",
"self",
".",
"slice_shape",
"(",
"tensor_shape",
")",
"slice_begins",
"=",
"[",
"self",
".",
"slice_begin",
"(",
"tensor_shape",
",",
"pnum",
")",
"for",
"pnum",
"in",
"xrange",
"(",
"self",
".",
"size",
")",
"]",
"slice_begins_tensor",
"=",
"tf",
".",
"stack",
"(",
"slice_begins",
")",
"# slice on source device",
"selected_slice_begin",
"=",
"tf",
".",
"gather",
"(",
"slice_begins_tensor",
",",
"self",
".",
"pnum_tensor",
")",
"return",
"self",
".",
"LaidOutTensor",
"(",
"[",
"tf",
".",
"slice",
"(",
"tf_tensor",
",",
"selected_slice_begin",
",",
"slice_shape",
")",
"]",
")"
] | Slice out the corresponding part of tensor given the pnum variable. | [
"Slice",
"out",
"the",
"corresponding",
"part",
"of",
"tensor",
"given",
"the",
"pnum",
"variable",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/simd_mesh_impl.py#L443-L458 |
227,930 | tensorflow/mesh | examples/mnist_dataset.py | read32 | def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0] | python | def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0] | [
"def",
"read32",
"(",
"bytestream",
")",
":",
"dt",
"=",
"np",
".",
"dtype",
"(",
"np",
".",
"uint32",
")",
".",
"newbyteorder",
"(",
"'>'",
")",
"return",
"np",
".",
"frombuffer",
"(",
"bytestream",
".",
"read",
"(",
"4",
")",
",",
"dtype",
"=",
"dt",
")",
"[",
"0",
"]"
] | Read 4 bytes from bytestream as an unsigned 32-bit integer. | [
"Read",
"4",
"bytes",
"from",
"bytestream",
"as",
"an",
"unsigned",
"32",
"-",
"bit",
"integer",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L45-L48 |
227,931 | tensorflow/mesh | examples/mnist_dataset.py | check_image_file_header | def check_image_file_header(filename):
"""Validate that filename corresponds to images for the MNIST dataset."""
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_images, unused
rows = read32(f)
cols = read32(f)
if magic != 2051:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
f.name))
if rows != 28 or cols != 28:
raise ValueError(
'Invalid MNIST file %s: Expected 28x28 images, found %dx%d' %
(f.name, rows, cols)) | python | def check_image_file_header(filename):
"""Validate that filename corresponds to images for the MNIST dataset."""
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_images, unused
rows = read32(f)
cols = read32(f)
if magic != 2051:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
f.name))
if rows != 28 or cols != 28:
raise ValueError(
'Invalid MNIST file %s: Expected 28x28 images, found %dx%d' %
(f.name, rows, cols)) | [
"def",
"check_image_file_header",
"(",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"magic",
"=",
"read32",
"(",
"f",
")",
"read32",
"(",
"f",
")",
"# num_images, unused",
"rows",
"=",
"read32",
"(",
"f",
")",
"cols",
"=",
"read32",
"(",
"f",
")",
"if",
"magic",
"!=",
"2051",
":",
"raise",
"ValueError",
"(",
"'Invalid magic number %d in MNIST file %s'",
"%",
"(",
"magic",
",",
"f",
".",
"name",
")",
")",
"if",
"rows",
"!=",
"28",
"or",
"cols",
"!=",
"28",
":",
"raise",
"ValueError",
"(",
"'Invalid MNIST file %s: Expected 28x28 images, found %dx%d'",
"%",
"(",
"f",
".",
"name",
",",
"rows",
",",
"cols",
")",
")"
] | Validate that filename corresponds to images for the MNIST dataset. | [
"Validate",
"that",
"filename",
"corresponds",
"to",
"images",
"for",
"the",
"MNIST",
"dataset",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L51-L64 |
227,932 | tensorflow/mesh | examples/mnist_dataset.py | check_labels_file_header | def check_labels_file_header(filename):
"""Validate that filename corresponds to labels for the MNIST dataset."""
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_items, unused
if magic != 2049:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
f.name)) | python | def check_labels_file_header(filename):
"""Validate that filename corresponds to labels for the MNIST dataset."""
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_items, unused
if magic != 2049:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
f.name)) | [
"def",
"check_labels_file_header",
"(",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"magic",
"=",
"read32",
"(",
"f",
")",
"read32",
"(",
"f",
")",
"# num_items, unused",
"if",
"magic",
"!=",
"2049",
":",
"raise",
"ValueError",
"(",
"'Invalid magic number %d in MNIST file %s'",
"%",
"(",
"magic",
",",
"f",
".",
"name",
")",
")"
] | Validate that filename corresponds to labels for the MNIST dataset. | [
"Validate",
"that",
"filename",
"corresponds",
"to",
"labels",
"for",
"the",
"MNIST",
"dataset",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L67-L74 |
227,933 | tensorflow/mesh | examples/mnist_dataset.py | dataset | def dataset(directory, images_file, labels_file):
"""Download and parse MNIST dataset."""
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
# Normalize from [0, 255] to [0.0, 1.0]
image = tf.decode_raw(image, tf.uint8)
image = tf.cast(image, tf.float32)
image = tf.reshape(image, [784])
return image / 255.0
def decode_label(label):
label = tf.decode_raw(label, tf.uint8) # tf.string -> [tf.uint8]
label = tf.reshape(label, []) # label is a scalar
return tf.to_int32(label)
images = tf.data.FixedLengthRecordDataset(
images_file, 28 * 28, header_bytes=16).map(decode_image)
labels = tf.data.FixedLengthRecordDataset(
labels_file, 1, header_bytes=8).map(decode_label)
return tf.data.Dataset.zip((images, labels)) | python | def dataset(directory, images_file, labels_file):
"""Download and parse MNIST dataset."""
images_file = download(directory, images_file)
labels_file = download(directory, labels_file)
check_image_file_header(images_file)
check_labels_file_header(labels_file)
def decode_image(image):
# Normalize from [0, 255] to [0.0, 1.0]
image = tf.decode_raw(image, tf.uint8)
image = tf.cast(image, tf.float32)
image = tf.reshape(image, [784])
return image / 255.0
def decode_label(label):
label = tf.decode_raw(label, tf.uint8) # tf.string -> [tf.uint8]
label = tf.reshape(label, []) # label is a scalar
return tf.to_int32(label)
images = tf.data.FixedLengthRecordDataset(
images_file, 28 * 28, header_bytes=16).map(decode_image)
labels = tf.data.FixedLengthRecordDataset(
labels_file, 1, header_bytes=8).map(decode_label)
return tf.data.Dataset.zip((images, labels)) | [
"def",
"dataset",
"(",
"directory",
",",
"images_file",
",",
"labels_file",
")",
":",
"images_file",
"=",
"download",
"(",
"directory",
",",
"images_file",
")",
"labels_file",
"=",
"download",
"(",
"directory",
",",
"labels_file",
")",
"check_image_file_header",
"(",
"images_file",
")",
"check_labels_file_header",
"(",
"labels_file",
")",
"def",
"decode_image",
"(",
"image",
")",
":",
"# Normalize from [0, 255] to [0.0, 1.0]",
"image",
"=",
"tf",
".",
"decode_raw",
"(",
"image",
",",
"tf",
".",
"uint8",
")",
"image",
"=",
"tf",
".",
"cast",
"(",
"image",
",",
"tf",
".",
"float32",
")",
"image",
"=",
"tf",
".",
"reshape",
"(",
"image",
",",
"[",
"784",
"]",
")",
"return",
"image",
"/",
"255.0",
"def",
"decode_label",
"(",
"label",
")",
":",
"label",
"=",
"tf",
".",
"decode_raw",
"(",
"label",
",",
"tf",
".",
"uint8",
")",
"# tf.string -> [tf.uint8]",
"label",
"=",
"tf",
".",
"reshape",
"(",
"label",
",",
"[",
"]",
")",
"# label is a scalar",
"return",
"tf",
".",
"to_int32",
"(",
"label",
")",
"images",
"=",
"tf",
".",
"data",
".",
"FixedLengthRecordDataset",
"(",
"images_file",
",",
"28",
"*",
"28",
",",
"header_bytes",
"=",
"16",
")",
".",
"map",
"(",
"decode_image",
")",
"labels",
"=",
"tf",
".",
"data",
".",
"FixedLengthRecordDataset",
"(",
"labels_file",
",",
"1",
",",
"header_bytes",
"=",
"8",
")",
".",
"map",
"(",
"decode_label",
")",
"return",
"tf",
".",
"data",
".",
"Dataset",
".",
"zip",
"(",
"(",
"images",
",",
"labels",
")",
")"
] | Download and parse MNIST dataset. | [
"Download",
"and",
"parse",
"MNIST",
"dataset",
"."
] | 3921196e5e43302e820da0a87329f25d7e2a3016 | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist_dataset.py#L95-L120 |
227,934 | mattjj/pyhsmm | pyhsmm/util/stats.py | sample_discrete | def sample_discrete(distn,size=[],dtype=np.int32):
'samples from a one-dimensional finite pmf'
distn = np.atleast_1d(distn)
assert (distn >=0).all() and distn.ndim == 1
if (0 == distn).all():
return np.random.randint(distn.shape[0],size=size)
cumvals = np.cumsum(distn)
return np.sum(np.array(random(size))[...,na] * cumvals[-1] > cumvals, axis=-1,dtype=dtype) | python | def sample_discrete(distn,size=[],dtype=np.int32):
'samples from a one-dimensional finite pmf'
distn = np.atleast_1d(distn)
assert (distn >=0).all() and distn.ndim == 1
if (0 == distn).all():
return np.random.randint(distn.shape[0],size=size)
cumvals = np.cumsum(distn)
return np.sum(np.array(random(size))[...,na] * cumvals[-1] > cumvals, axis=-1,dtype=dtype) | [
"def",
"sample_discrete",
"(",
"distn",
",",
"size",
"=",
"[",
"]",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
":",
"distn",
"=",
"np",
".",
"atleast_1d",
"(",
"distn",
")",
"assert",
"(",
"distn",
">=",
"0",
")",
".",
"all",
"(",
")",
"and",
"distn",
".",
"ndim",
"==",
"1",
"if",
"(",
"0",
"==",
"distn",
")",
".",
"all",
"(",
")",
":",
"return",
"np",
".",
"random",
".",
"randint",
"(",
"distn",
".",
"shape",
"[",
"0",
"]",
",",
"size",
"=",
"size",
")",
"cumvals",
"=",
"np",
".",
"cumsum",
"(",
"distn",
")",
"return",
"np",
".",
"sum",
"(",
"np",
".",
"array",
"(",
"random",
"(",
"size",
")",
")",
"[",
"...",
",",
"na",
"]",
"*",
"cumvals",
"[",
"-",
"1",
"]",
">",
"cumvals",
",",
"axis",
"=",
"-",
"1",
",",
"dtype",
"=",
"dtype",
")"
] | samples from a one-dimensional finite pmf | [
"samples",
"from",
"a",
"one",
"-",
"dimensional",
"finite",
"pmf"
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/stats.py#L116-L123 |
227,935 | mattjj/pyhsmm | pyhsmm/models.py | _HMMBase.used_states | def used_states(self):
'a list of the used states in the order they appear'
c = itertools.count()
canonical_ids = collections.defaultdict(lambda: next(c))
for s in self.states_list:
for state in s.stateseq:
canonical_ids[state]
return list(map(operator.itemgetter(0),
sorted(canonical_ids.items(),key=operator.itemgetter(1)))) | python | def used_states(self):
'a list of the used states in the order they appear'
c = itertools.count()
canonical_ids = collections.defaultdict(lambda: next(c))
for s in self.states_list:
for state in s.stateseq:
canonical_ids[state]
return list(map(operator.itemgetter(0),
sorted(canonical_ids.items(),key=operator.itemgetter(1)))) | [
"def",
"used_states",
"(",
"self",
")",
":",
"c",
"=",
"itertools",
".",
"count",
"(",
")",
"canonical_ids",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"next",
"(",
"c",
")",
")",
"for",
"s",
"in",
"self",
".",
"states_list",
":",
"for",
"state",
"in",
"s",
".",
"stateseq",
":",
"canonical_ids",
"[",
"state",
"]",
"return",
"list",
"(",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"0",
")",
",",
"sorted",
"(",
"canonical_ids",
".",
"items",
"(",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
")",
")",
")"
] | a list of the used states in the order they appear | [
"a",
"list",
"of",
"the",
"used",
"states",
"in",
"the",
"order",
"they",
"appear"
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/models.py#L188-L196 |
227,936 | mattjj/pyhsmm | pyhsmm/util/plot.py | plot_gaussian_2D | def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None):
'''
Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix.
'''
assert len(mu) == 2
ax = ax if ax else plt.gca()
# TODO use artists!
t = np.hstack([np.arange(0,2*np.pi,0.01),0])
circle = np.vstack([np.sin(t),np.cos(t)])
ellipse = np.dot(np.linalg.cholesky(lmbda),circle)
if artists is None:
point = ax.scatter([mu[0]],[mu[1]],marker='D',color=color,s=4,alpha=alpha) \
if centermarker else None
line, = ax.plot(ellipse[0,:] + mu[0], ellipse[1,:] + mu[1],linestyle='-',
linewidth=2,color=color,label=label,alpha=alpha)
else:
line, point = artists
if centermarker:
point.set_offsets(np.atleast_2d(mu))
line.set_xdata(ellipse[0,:] + mu[0])
line.set_ydata(ellipse[1,:] + mu[1])
line.set_alpha(alpha)
line.set_color(color)
return line, point | python | def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None):
'''
Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix.
'''
assert len(mu) == 2
ax = ax if ax else plt.gca()
# TODO use artists!
t = np.hstack([np.arange(0,2*np.pi,0.01),0])
circle = np.vstack([np.sin(t),np.cos(t)])
ellipse = np.dot(np.linalg.cholesky(lmbda),circle)
if artists is None:
point = ax.scatter([mu[0]],[mu[1]],marker='D',color=color,s=4,alpha=alpha) \
if centermarker else None
line, = ax.plot(ellipse[0,:] + mu[0], ellipse[1,:] + mu[1],linestyle='-',
linewidth=2,color=color,label=label,alpha=alpha)
else:
line, point = artists
if centermarker:
point.set_offsets(np.atleast_2d(mu))
line.set_xdata(ellipse[0,:] + mu[0])
line.set_ydata(ellipse[1,:] + mu[1])
line.set_alpha(alpha)
line.set_color(color)
return line, point | [
"def",
"plot_gaussian_2D",
"(",
"mu",
",",
"lmbda",
",",
"color",
"=",
"'b'",
",",
"centermarker",
"=",
"True",
",",
"label",
"=",
"''",
",",
"alpha",
"=",
"1.",
",",
"ax",
"=",
"None",
",",
"artists",
"=",
"None",
")",
":",
"assert",
"len",
"(",
"mu",
")",
"==",
"2",
"ax",
"=",
"ax",
"if",
"ax",
"else",
"plt",
".",
"gca",
"(",
")",
"# TODO use artists!",
"t",
"=",
"np",
".",
"hstack",
"(",
"[",
"np",
".",
"arange",
"(",
"0",
",",
"2",
"*",
"np",
".",
"pi",
",",
"0.01",
")",
",",
"0",
"]",
")",
"circle",
"=",
"np",
".",
"vstack",
"(",
"[",
"np",
".",
"sin",
"(",
"t",
")",
",",
"np",
".",
"cos",
"(",
"t",
")",
"]",
")",
"ellipse",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"linalg",
".",
"cholesky",
"(",
"lmbda",
")",
",",
"circle",
")",
"if",
"artists",
"is",
"None",
":",
"point",
"=",
"ax",
".",
"scatter",
"(",
"[",
"mu",
"[",
"0",
"]",
"]",
",",
"[",
"mu",
"[",
"1",
"]",
"]",
",",
"marker",
"=",
"'D'",
",",
"color",
"=",
"color",
",",
"s",
"=",
"4",
",",
"alpha",
"=",
"alpha",
")",
"if",
"centermarker",
"else",
"None",
"line",
",",
"=",
"ax",
".",
"plot",
"(",
"ellipse",
"[",
"0",
",",
":",
"]",
"+",
"mu",
"[",
"0",
"]",
",",
"ellipse",
"[",
"1",
",",
":",
"]",
"+",
"mu",
"[",
"1",
"]",
",",
"linestyle",
"=",
"'-'",
",",
"linewidth",
"=",
"2",
",",
"color",
"=",
"color",
",",
"label",
"=",
"label",
",",
"alpha",
"=",
"alpha",
")",
"else",
":",
"line",
",",
"point",
"=",
"artists",
"if",
"centermarker",
":",
"point",
".",
"set_offsets",
"(",
"np",
".",
"atleast_2d",
"(",
"mu",
")",
")",
"line",
".",
"set_xdata",
"(",
"ellipse",
"[",
"0",
",",
":",
"]",
"+",
"mu",
"[",
"0",
"]",
")",
"line",
".",
"set_ydata",
"(",
"ellipse",
"[",
"1",
",",
":",
"]",
"+",
"mu",
"[",
"1",
"]",
")",
"line",
".",
"set_alpha",
"(",
"alpha",
")",
"line",
".",
"set_color",
"(",
"color",
")",
"return",
"line",
",",
"point"
] | Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix. | [
"Plots",
"mean",
"and",
"cov",
"ellipsoid",
"into",
"current",
"axes",
".",
"Must",
"be",
"2D",
".",
"lmbda",
"is",
"a",
"covariance",
"matrix",
"."
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/plot.py#L7-L34 |
227,937 | mattjj/pyhsmm | pyhsmm/basic/abstractions.py | DurationDistribution.resample_with_censoring | def resample_with_censoring(self,data=[],censored_data=[]):
'''
censored_data is full of observations that were censored, meaning a
value of x really could have been anything >= x, so this method samples
them out to be at least that large
'''
filled_in = self._uncensor_data(censored_data)
return self.resample(data=combinedata((data,filled_in))) | python | def resample_with_censoring(self,data=[],censored_data=[]):
'''
censored_data is full of observations that were censored, meaning a
value of x really could have been anything >= x, so this method samples
them out to be at least that large
'''
filled_in = self._uncensor_data(censored_data)
return self.resample(data=combinedata((data,filled_in))) | [
"def",
"resample_with_censoring",
"(",
"self",
",",
"data",
"=",
"[",
"]",
",",
"censored_data",
"=",
"[",
"]",
")",
":",
"filled_in",
"=",
"self",
".",
"_uncensor_data",
"(",
"censored_data",
")",
"return",
"self",
".",
"resample",
"(",
"data",
"=",
"combinedata",
"(",
"(",
"data",
",",
"filled_in",
")",
")",
")"
] | censored_data is full of observations that were censored, meaning a
value of x really could have been anything >= x, so this method samples
them out to be at least that large | [
"censored_data",
"is",
"full",
"of",
"observations",
"that",
"were",
"censored",
"meaning",
"a",
"value",
"of",
"x",
"really",
"could",
"have",
"been",
"anything",
">",
"=",
"x",
"so",
"this",
"method",
"samples",
"them",
"out",
"to",
"be",
"at",
"least",
"that",
"large"
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/basic/abstractions.py#L70-L77 |
227,938 | mattjj/pyhsmm | pyhsmm/util/general.py | scoreatpercentile | def scoreatpercentile(data,per,axis=0):
'like the function in scipy.stats but with an axis argument and works on arrays'
a = np.sort(data,axis=axis)
idx = per/100. * (data.shape[axis]-1)
if (idx % 1 == 0):
return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]]
else:
lowerweight = 1-(idx % 1)
upperweight = (idx % 1)
idx = int(np.floor(idx))
return lowerweight * a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]] \
+ upperweight * a[[slice(None) if ii != axis else idx+1 for ii in range(a.ndim)]] | python | def scoreatpercentile(data,per,axis=0):
'like the function in scipy.stats but with an axis argument and works on arrays'
a = np.sort(data,axis=axis)
idx = per/100. * (data.shape[axis]-1)
if (idx % 1 == 0):
return a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]]
else:
lowerweight = 1-(idx % 1)
upperweight = (idx % 1)
idx = int(np.floor(idx))
return lowerweight * a[[slice(None) if ii != axis else idx for ii in range(a.ndim)]] \
+ upperweight * a[[slice(None) if ii != axis else idx+1 for ii in range(a.ndim)]] | [
"def",
"scoreatpercentile",
"(",
"data",
",",
"per",
",",
"axis",
"=",
"0",
")",
":",
"a",
"=",
"np",
".",
"sort",
"(",
"data",
",",
"axis",
"=",
"axis",
")",
"idx",
"=",
"per",
"/",
"100.",
"*",
"(",
"data",
".",
"shape",
"[",
"axis",
"]",
"-",
"1",
")",
"if",
"(",
"idx",
"%",
"1",
"==",
"0",
")",
":",
"return",
"a",
"[",
"[",
"slice",
"(",
"None",
")",
"if",
"ii",
"!=",
"axis",
"else",
"idx",
"for",
"ii",
"in",
"range",
"(",
"a",
".",
"ndim",
")",
"]",
"]",
"else",
":",
"lowerweight",
"=",
"1",
"-",
"(",
"idx",
"%",
"1",
")",
"upperweight",
"=",
"(",
"idx",
"%",
"1",
")",
"idx",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"idx",
")",
")",
"return",
"lowerweight",
"*",
"a",
"[",
"[",
"slice",
"(",
"None",
")",
"if",
"ii",
"!=",
"axis",
"else",
"idx",
"for",
"ii",
"in",
"range",
"(",
"a",
".",
"ndim",
")",
"]",
"]",
"+",
"upperweight",
"*",
"a",
"[",
"[",
"slice",
"(",
"None",
")",
"if",
"ii",
"!=",
"axis",
"else",
"idx",
"+",
"1",
"for",
"ii",
"in",
"range",
"(",
"a",
".",
"ndim",
")",
"]",
"]"
] | like the function in scipy.stats but with an axis argument and works on arrays | [
"like",
"the",
"function",
"in",
"scipy",
".",
"stats",
"but",
"with",
"an",
"axis",
"argument",
"and",
"works",
"on",
"arrays"
] | a9a39c2bfd539048e35877cb13283552eadc24e2 | https://github.com/mattjj/pyhsmm/blob/a9a39c2bfd539048e35877cb13283552eadc24e2/pyhsmm/util/general.py#L119-L131 |
227,939 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.content_type | def content_type(self, mime_type: Optional[MimeType] = None) -> str:
"""Get a random HTTP content type.
:return: Content type.
:Example:
Content-Type: application/json
"""
fmt = self.__file.mime_type(type_=mime_type)
return 'Content-Type: {}'.format(fmt) | python | def content_type(self, mime_type: Optional[MimeType] = None) -> str:
"""Get a random HTTP content type.
:return: Content type.
:Example:
Content-Type: application/json
"""
fmt = self.__file.mime_type(type_=mime_type)
return 'Content-Type: {}'.format(fmt) | [
"def",
"content_type",
"(",
"self",
",",
"mime_type",
":",
"Optional",
"[",
"MimeType",
"]",
"=",
"None",
")",
"->",
"str",
":",
"fmt",
"=",
"self",
".",
"__file",
".",
"mime_type",
"(",
"type_",
"=",
"mime_type",
")",
"return",
"'Content-Type: {}'",
".",
"format",
"(",
"fmt",
")"
] | Get a random HTTP content type.
:return: Content type.
:Example:
Content-Type: application/json | [
"Get",
"a",
"random",
"HTTP",
"content",
"type",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L46-L55 |
227,940 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.ip_v4 | def ip_v4(self, with_port: bool = False) -> str:
"""Generate a random IPv4 address.
:param with_port: Add port to IP.
:return: Random IPv4 address.
:Example:
19.121.223.58
"""
ip = '.'.join(str(self.random.randint(0, 255)) for _ in range(4))
if with_port:
ip += ':{}'.format(self.port())
return ip | python | def ip_v4(self, with_port: bool = False) -> str:
"""Generate a random IPv4 address.
:param with_port: Add port to IP.
:return: Random IPv4 address.
:Example:
19.121.223.58
"""
ip = '.'.join(str(self.random.randint(0, 255)) for _ in range(4))
if with_port:
ip += ':{}'.format(self.port())
return ip | [
"def",
"ip_v4",
"(",
"self",
",",
"with_port",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"ip",
"=",
"'.'",
".",
"join",
"(",
"str",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"255",
")",
")",
"for",
"_",
"in",
"range",
"(",
"4",
")",
")",
"if",
"with_port",
":",
"ip",
"+=",
"':{}'",
".",
"format",
"(",
"self",
".",
"port",
"(",
")",
")",
"return",
"ip"
] | Generate a random IPv4 address.
:param with_port: Add port to IP.
:return: Random IPv4 address.
:Example:
19.121.223.58 | [
"Generate",
"a",
"random",
"IPv4",
"address",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L87-L101 |
227,941 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.ip_v6 | def ip_v6(self) -> str:
"""Generate a random IPv6 address.
:return: Random IPv6 address.
:Example:
2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3
"""
ipv6 = IPv6Address(
self.random.randint(
0, 2 ** 128 - 1,
),
)
return str(ipv6) | python | def ip_v6(self) -> str:
"""Generate a random IPv6 address.
:return: Random IPv6 address.
:Example:
2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3
"""
ipv6 = IPv6Address(
self.random.randint(
0, 2 ** 128 - 1,
),
)
return str(ipv6) | [
"def",
"ip_v6",
"(",
"self",
")",
"->",
"str",
":",
"ipv6",
"=",
"IPv6Address",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"2",
"**",
"128",
"-",
"1",
",",
")",
",",
")",
"return",
"str",
"(",
"ipv6",
")"
] | Generate a random IPv6 address.
:return: Random IPv6 address.
:Example:
2001:c244:cf9d:1fb1:c56d:f52c:8a04:94f3 | [
"Generate",
"a",
"random",
"IPv6",
"address",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L103-L116 |
227,942 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.mac_address | def mac_address(self) -> str:
"""Generate a random MAC address.
:return: Random MAC address.
:Example:
00:16:3e:25:e7:b1
"""
mac_hex = [
0x00, 0x16, 0x3e,
self.random.randint(0x00, 0x7f),
self.random.randint(0x00, 0xff),
self.random.randint(0x00, 0xff),
]
mac = map(lambda x: '%02x' % x, mac_hex)
return ':'.join(mac) | python | def mac_address(self) -> str:
"""Generate a random MAC address.
:return: Random MAC address.
:Example:
00:16:3e:25:e7:b1
"""
mac_hex = [
0x00, 0x16, 0x3e,
self.random.randint(0x00, 0x7f),
self.random.randint(0x00, 0xff),
self.random.randint(0x00, 0xff),
]
mac = map(lambda x: '%02x' % x, mac_hex)
return ':'.join(mac) | [
"def",
"mac_address",
"(",
"self",
")",
"->",
"str",
":",
"mac_hex",
"=",
"[",
"0x00",
",",
"0x16",
",",
"0x3e",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0x00",
",",
"0x7f",
")",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0x00",
",",
"0xff",
")",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0x00",
",",
"0xff",
")",
",",
"]",
"mac",
"=",
"map",
"(",
"lambda",
"x",
":",
"'%02x'",
"%",
"x",
",",
"mac_hex",
")",
"return",
"':'",
".",
"join",
"(",
"mac",
")"
] | Generate a random MAC address.
:return: Random MAC address.
:Example:
00:16:3e:25:e7:b1 | [
"Generate",
"a",
"random",
"MAC",
"address",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L118-L133 |
227,943 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.image_placeholder | def image_placeholder(width: Union[int, str] = 1920,
height: Union[int, str] = 1080) -> str:
"""Generate a link to the image placeholder.
:param width: Width of image.
:param height: Height of image.
:return: URL to image placeholder.
"""
url = 'http://placehold.it/{width}x{height}'
return url.format(width=width, height=height) | python | def image_placeholder(width: Union[int, str] = 1920,
height: Union[int, str] = 1080) -> str:
"""Generate a link to the image placeholder.
:param width: Width of image.
:param height: Height of image.
:return: URL to image placeholder.
"""
url = 'http://placehold.it/{width}x{height}'
return url.format(width=width, height=height) | [
"def",
"image_placeholder",
"(",
"width",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"1920",
",",
"height",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"1080",
")",
"->",
"str",
":",
"url",
"=",
"'http://placehold.it/{width}x{height}'",
"return",
"url",
".",
"format",
"(",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")"
] | Generate a link to the image placeholder.
:param width: Width of image.
:param height: Height of image.
:return: URL to image placeholder. | [
"Generate",
"a",
"link",
"to",
"the",
"image",
"placeholder",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L146-L155 |
227,944 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.hashtags | def hashtags(self, quantity: int = 4) -> Union[str, list]:
"""Generate a list of hashtags.
:param quantity: The quantity of hashtags.
:return: The list of hashtags.
:raises NonEnumerableError: if category is not in Hashtag.
:Example:
['#love', '#sky', '#nice']
"""
tags = ['#' + self.random.choice(HASHTAGS)
for _ in range(quantity)]
if int(quantity) == 1:
return tags[0]
return tags | python | def hashtags(self, quantity: int = 4) -> Union[str, list]:
"""Generate a list of hashtags.
:param quantity: The quantity of hashtags.
:return: The list of hashtags.
:raises NonEnumerableError: if category is not in Hashtag.
:Example:
['#love', '#sky', '#nice']
"""
tags = ['#' + self.random.choice(HASHTAGS)
for _ in range(quantity)]
if int(quantity) == 1:
return tags[0]
return tags | [
"def",
"hashtags",
"(",
"self",
",",
"quantity",
":",
"int",
"=",
"4",
")",
"->",
"Union",
"[",
"str",
",",
"list",
"]",
":",
"tags",
"=",
"[",
"'#'",
"+",
"self",
".",
"random",
".",
"choice",
"(",
"HASHTAGS",
")",
"for",
"_",
"in",
"range",
"(",
"quantity",
")",
"]",
"if",
"int",
"(",
"quantity",
")",
"==",
"1",
":",
"return",
"tags",
"[",
"0",
"]",
"return",
"tags"
] | Generate a list of hashtags.
:param quantity: The quantity of hashtags.
:return: The list of hashtags.
:raises NonEnumerableError: if category is not in Hashtag.
:Example:
['#love', '#sky', '#nice'] | [
"Generate",
"a",
"list",
"of",
"hashtags",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L191-L207 |
227,945 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.home_page | def home_page(self, tld_type: Optional[TLDType] = None) -> str:
"""Generate a random home page.
:param tld_type: TLD type.
:return: Random home page.
:Example:
http://www.fontir.info
"""
resource = self.random.choice(USERNAMES)
domain = self.top_level_domain(
tld_type=tld_type,
)
return 'http://www.{}{}'.format(
resource, domain) | python | def home_page(self, tld_type: Optional[TLDType] = None) -> str:
"""Generate a random home page.
:param tld_type: TLD type.
:return: Random home page.
:Example:
http://www.fontir.info
"""
resource = self.random.choice(USERNAMES)
domain = self.top_level_domain(
tld_type=tld_type,
)
return 'http://www.{}{}'.format(
resource, domain) | [
"def",
"home_page",
"(",
"self",
",",
"tld_type",
":",
"Optional",
"[",
"TLDType",
"]",
"=",
"None",
")",
"->",
"str",
":",
"resource",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"USERNAMES",
")",
"domain",
"=",
"self",
".",
"top_level_domain",
"(",
"tld_type",
"=",
"tld_type",
",",
")",
"return",
"'http://www.{}{}'",
".",
"format",
"(",
"resource",
",",
"domain",
")"
] | Generate a random home page.
:param tld_type: TLD type.
:return: Random home page.
:Example:
http://www.fontir.info | [
"Generate",
"a",
"random",
"home",
"page",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L209-L224 |
227,946 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.top_level_domain | def top_level_domain(self, tld_type: Optional[TLDType] = None) -> str:
"""Return random top level domain.
:param tld_type: Enum object DomainType
:return: Top level domain.
:raises NonEnumerableError: if tld_type not in DomainType.
"""
key = self._validate_enum(item=tld_type, enum=TLDType)
return self.random.choice(TLD[key]) | python | def top_level_domain(self, tld_type: Optional[TLDType] = None) -> str:
"""Return random top level domain.
:param tld_type: Enum object DomainType
:return: Top level domain.
:raises NonEnumerableError: if tld_type not in DomainType.
"""
key = self._validate_enum(item=tld_type, enum=TLDType)
return self.random.choice(TLD[key]) | [
"def",
"top_level_domain",
"(",
"self",
",",
"tld_type",
":",
"Optional",
"[",
"TLDType",
"]",
"=",
"None",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"item",
"=",
"tld_type",
",",
"enum",
"=",
"TLDType",
")",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"TLD",
"[",
"key",
"]",
")"
] | Return random top level domain.
:param tld_type: Enum object DomainType
:return: Top level domain.
:raises NonEnumerableError: if tld_type not in DomainType. | [
"Return",
"random",
"top",
"level",
"domain",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L226-L234 |
227,947 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.network_protocol | def network_protocol(self, layer: Optional[Layer] = None) -> str:
"""Get a random network protocol form OSI model.
:param layer: Enum object Layer.
:return: Protocol name.
:Example:
AMQP
"""
key = self._validate_enum(item=layer, enum=Layer)
protocols = NETWORK_PROTOCOLS[key]
return self.random.choice(protocols) | python | def network_protocol(self, layer: Optional[Layer] = None) -> str:
"""Get a random network protocol form OSI model.
:param layer: Enum object Layer.
:return: Protocol name.
:Example:
AMQP
"""
key = self._validate_enum(item=layer, enum=Layer)
protocols = NETWORK_PROTOCOLS[key]
return self.random.choice(protocols) | [
"def",
"network_protocol",
"(",
"self",
",",
"layer",
":",
"Optional",
"[",
"Layer",
"]",
"=",
"None",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"item",
"=",
"layer",
",",
"enum",
"=",
"Layer",
")",
"protocols",
"=",
"NETWORK_PROTOCOLS",
"[",
"key",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"protocols",
")"
] | Get a random network protocol form OSI model.
:param layer: Enum object Layer.
:return: Protocol name.
:Example:
AMQP | [
"Get",
"a",
"random",
"network",
"protocol",
"form",
"OSI",
"model",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L247-L258 |
227,948 | lk-geimfari/mimesis | mimesis/providers/internet.py | Internet.port | def port(self, port_range: PortRange = PortRange.ALL) -> int:
"""Generate random port.
:param port_range: Range enum object.
:return: Port number.
:raises NonEnumerableError: if port_range is not in PortRange.
:Example:
8080
"""
if port_range and port_range in PortRange:
return self.random.randint(*port_range.value)
else:
raise NonEnumerableError(PortRange) | python | def port(self, port_range: PortRange = PortRange.ALL) -> int:
"""Generate random port.
:param port_range: Range enum object.
:return: Port number.
:raises NonEnumerableError: if port_range is not in PortRange.
:Example:
8080
"""
if port_range and port_range in PortRange:
return self.random.randint(*port_range.value)
else:
raise NonEnumerableError(PortRange) | [
"def",
"port",
"(",
"self",
",",
"port_range",
":",
"PortRange",
"=",
"PortRange",
".",
"ALL",
")",
"->",
"int",
":",
"if",
"port_range",
"and",
"port_range",
"in",
"PortRange",
":",
"return",
"self",
".",
"random",
".",
"randint",
"(",
"*",
"port_range",
".",
"value",
")",
"else",
":",
"raise",
"NonEnumerableError",
"(",
"PortRange",
")"
] | Generate random port.
:param port_range: Range enum object.
:return: Port number.
:raises NonEnumerableError: if port_range is not in PortRange.
:Example:
8080 | [
"Generate",
"random",
"port",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/internet.py#L260-L273 |
227,949 | lk-geimfari/mimesis | mimesis/providers/transport.py | Transport.truck | def truck(self, model_mask: str = '#### @@') -> str:
"""Generate a truck model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Dummy truck model.
:Example:
Caledon-966O.
"""
return '{}-{}'.format(
self.random.choice(TRUCKS),
self.random.custom_code(model_mask),
) | python | def truck(self, model_mask: str = '#### @@') -> str:
"""Generate a truck model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Dummy truck model.
:Example:
Caledon-966O.
"""
return '{}-{}'.format(
self.random.choice(TRUCKS),
self.random.custom_code(model_mask),
) | [
"def",
"truck",
"(",
"self",
",",
"model_mask",
":",
"str",
"=",
"'#### @@'",
")",
"->",
"str",
":",
"return",
"'{}-{}'",
".",
"format",
"(",
"self",
".",
"random",
".",
"choice",
"(",
"TRUCKS",
")",
",",
"self",
".",
"random",
".",
"custom_code",
"(",
"model_mask",
")",
",",
")"
] | Generate a truck model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Dummy truck model.
:Example:
Caledon-966O. | [
"Generate",
"a",
"truck",
"model",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/transport.py#L29-L42 |
227,950 | lk-geimfari/mimesis | mimesis/providers/transport.py | Transport.airplane | def airplane(self, model_mask: str = '###') -> str:
"""Generate a dummy airplane model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Airplane model.
:Example:
Boeing 727.
"""
model = self.random.custom_code(mask=model_mask)
plane = self.random.choice(AIRPLANES)
return '{} {}'.format(plane, model) | python | def airplane(self, model_mask: str = '###') -> str:
"""Generate a dummy airplane model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Airplane model.
:Example:
Boeing 727.
"""
model = self.random.custom_code(mask=model_mask)
plane = self.random.choice(AIRPLANES)
return '{} {}'.format(plane, model) | [
"def",
"airplane",
"(",
"self",
",",
"model_mask",
":",
"str",
"=",
"'###'",
")",
"->",
"str",
":",
"model",
"=",
"self",
".",
"random",
".",
"custom_code",
"(",
"mask",
"=",
"model_mask",
")",
"plane",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"AIRPLANES",
")",
"return",
"'{} {}'",
".",
"format",
"(",
"plane",
",",
"model",
")"
] | Generate a dummy airplane model.
:param model_mask: Mask of truck model. Here '@' is a
placeholder of characters and '#' is a placeholder of digits.
:return: Airplane model.
:Example:
Boeing 727. | [
"Generate",
"a",
"dummy",
"airplane",
"model",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/transport.py#L54-L66 |
227,951 | lk-geimfari/mimesis | mimesis/providers/transport.py | Transport.vehicle_registration_code | def vehicle_registration_code(self, locale: Optional[str] = None) -> str:
"""Get vehicle registration code of country.
:param locale: Registration code for locale (country).
:return: Vehicle registration code.
"""
if locale:
return VRC_BY_LOCALES[locale]
return self.random.choice(VR_CODES) | python | def vehicle_registration_code(self, locale: Optional[str] = None) -> str:
"""Get vehicle registration code of country.
:param locale: Registration code for locale (country).
:return: Vehicle registration code.
"""
if locale:
return VRC_BY_LOCALES[locale]
return self.random.choice(VR_CODES) | [
"def",
"vehicle_registration_code",
"(",
"self",
",",
"locale",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"if",
"locale",
":",
"return",
"VRC_BY_LOCALES",
"[",
"locale",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"VR_CODES",
")"
] | Get vehicle registration code of country.
:param locale: Registration code for locale (country).
:return: Vehicle registration code. | [
"Get",
"vehicle",
"registration",
"code",
"of",
"country",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/transport.py#L68-L77 |
227,952 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.bulk_create_datetimes | def bulk_create_datetimes(date_start: DateTime,
date_end: DateTime, **kwargs) -> List[DateTime]:
"""Bulk create datetime objects.
This method creates list of datetime objects from
``date_start`` to ``date_end``.
You can use the following keyword arguments:
* ``days``
* ``hours``
* ``minutes``
* ``seconds``
* ``microseconds``
See datetime module documentation for more:
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
:param date_start: Begin of the range.
:param date_end: End of the range.
:param kwargs: Keyword arguments for datetime.timedelta
:return: List of datetime objects
:raises: ValueError: When ``date_start``/``date_end`` not passed and
when ``date_start`` larger than ``date_end``.
"""
dt_objects = []
if not date_start and not date_end:
raise ValueError('You must pass date_start and date_end')
if date_end < date_start:
raise ValueError('date_start can not be larger than date_end')
while date_start <= date_end:
date_start += timedelta(**kwargs)
dt_objects.append(date_start)
return dt_objects | python | def bulk_create_datetimes(date_start: DateTime,
date_end: DateTime, **kwargs) -> List[DateTime]:
"""Bulk create datetime objects.
This method creates list of datetime objects from
``date_start`` to ``date_end``.
You can use the following keyword arguments:
* ``days``
* ``hours``
* ``minutes``
* ``seconds``
* ``microseconds``
See datetime module documentation for more:
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
:param date_start: Begin of the range.
:param date_end: End of the range.
:param kwargs: Keyword arguments for datetime.timedelta
:return: List of datetime objects
:raises: ValueError: When ``date_start``/``date_end`` not passed and
when ``date_start`` larger than ``date_end``.
"""
dt_objects = []
if not date_start and not date_end:
raise ValueError('You must pass date_start and date_end')
if date_end < date_start:
raise ValueError('date_start can not be larger than date_end')
while date_start <= date_end:
date_start += timedelta(**kwargs)
dt_objects.append(date_start)
return dt_objects | [
"def",
"bulk_create_datetimes",
"(",
"date_start",
":",
"DateTime",
",",
"date_end",
":",
"DateTime",
",",
"*",
"*",
"kwargs",
")",
"->",
"List",
"[",
"DateTime",
"]",
":",
"dt_objects",
"=",
"[",
"]",
"if",
"not",
"date_start",
"and",
"not",
"date_end",
":",
"raise",
"ValueError",
"(",
"'You must pass date_start and date_end'",
")",
"if",
"date_end",
"<",
"date_start",
":",
"raise",
"ValueError",
"(",
"'date_start can not be larger than date_end'",
")",
"while",
"date_start",
"<=",
"date_end",
":",
"date_start",
"+=",
"timedelta",
"(",
"*",
"*",
"kwargs",
")",
"dt_objects",
".",
"append",
"(",
"date_start",
")",
"return",
"dt_objects"
] | Bulk create datetime objects.
This method creates list of datetime objects from
``date_start`` to ``date_end``.
You can use the following keyword arguments:
* ``days``
* ``hours``
* ``minutes``
* ``seconds``
* ``microseconds``
See datetime module documentation for more:
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
:param date_start: Begin of the range.
:param date_end: End of the range.
:param kwargs: Keyword arguments for datetime.timedelta
:return: List of datetime objects
:raises: ValueError: When ``date_start``/``date_end`` not passed and
when ``date_start`` larger than ``date_end``. | [
"Bulk",
"create",
"datetime",
"objects",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L35-L73 |
227,953 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.week_date | def week_date(self, start: int = 2017, end: int = 2018) -> str:
"""Get week number with year.
:param start: From start.
:param end: To end.
:return: Week number.
"""
year = self.year(start, end)
week = self.random.randint(1, 52)
return '{year}-W{week}'.format(
year=year,
week=week,
) | python | def week_date(self, start: int = 2017, end: int = 2018) -> str:
"""Get week number with year.
:param start: From start.
:param end: To end.
:return: Week number.
"""
year = self.year(start, end)
week = self.random.randint(1, 52)
return '{year}-W{week}'.format(
year=year,
week=week,
) | [
"def",
"week_date",
"(",
"self",
",",
"start",
":",
"int",
"=",
"2017",
",",
"end",
":",
"int",
"=",
"2018",
")",
"->",
"str",
":",
"year",
"=",
"self",
".",
"year",
"(",
"start",
",",
"end",
")",
"week",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"52",
")",
"return",
"'{year}-W{week}'",
".",
"format",
"(",
"year",
"=",
"year",
",",
"week",
"=",
"week",
",",
")"
] | Get week number with year.
:param start: From start.
:param end: To end.
:return: Week number. | [
"Get",
"week",
"number",
"with",
"year",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L75-L87 |
227,954 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.day_of_week | def day_of_week(self, abbr: bool = False) -> str:
"""Get a random day of week.
:param abbr: Abbreviated day name.
:return: Day of the week.
"""
key = 'abbr' if abbr else 'name'
days = self._data['day'].get(key)
return self.random.choice(days) | python | def day_of_week(self, abbr: bool = False) -> str:
"""Get a random day of week.
:param abbr: Abbreviated day name.
:return: Day of the week.
"""
key = 'abbr' if abbr else 'name'
days = self._data['day'].get(key)
return self.random.choice(days) | [
"def",
"day_of_week",
"(",
"self",
",",
"abbr",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"key",
"=",
"'abbr'",
"if",
"abbr",
"else",
"'name'",
"days",
"=",
"self",
".",
"_data",
"[",
"'day'",
"]",
".",
"get",
"(",
"key",
")",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"days",
")"
] | Get a random day of week.
:param abbr: Abbreviated day name.
:return: Day of the week. | [
"Get",
"a",
"random",
"day",
"of",
"week",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L89-L97 |
227,955 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.month | def month(self, abbr: bool = False) -> str:
"""Get a random month.
:param abbr: Abbreviated month name.
:return: Month name.
"""
key = 'abbr' if abbr else 'name'
months = self._data['month'].get(key)
return self.random.choice(months) | python | def month(self, abbr: bool = False) -> str:
"""Get a random month.
:param abbr: Abbreviated month name.
:return: Month name.
"""
key = 'abbr' if abbr else 'name'
months = self._data['month'].get(key)
return self.random.choice(months) | [
"def",
"month",
"(",
"self",
",",
"abbr",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"key",
"=",
"'abbr'",
"if",
"abbr",
"else",
"'name'",
"months",
"=",
"self",
".",
"_data",
"[",
"'month'",
"]",
".",
"get",
"(",
"key",
")",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"months",
")"
] | Get a random month.
:param abbr: Abbreviated month name.
:return: Month name. | [
"Get",
"a",
"random",
"month",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L99-L107 |
227,956 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.year | def year(self, minimum: int = 1990, maximum: int = 2050) -> int:
"""Generate a random year.
:param minimum: Minimum value.
:param maximum: Maximum value.
:return: Year.
"""
return self.random.randint(minimum, maximum) | python | def year(self, minimum: int = 1990, maximum: int = 2050) -> int:
"""Generate a random year.
:param minimum: Minimum value.
:param maximum: Maximum value.
:return: Year.
"""
return self.random.randint(minimum, maximum) | [
"def",
"year",
"(",
"self",
",",
"minimum",
":",
"int",
"=",
"1990",
",",
"maximum",
":",
"int",
"=",
"2050",
")",
"->",
"int",
":",
"return",
"self",
".",
"random",
".",
"randint",
"(",
"minimum",
",",
"maximum",
")"
] | Generate a random year.
:param minimum: Minimum value.
:param maximum: Maximum value.
:return: Year. | [
"Generate",
"a",
"random",
"year",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L109-L116 |
227,957 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.periodicity | def periodicity(self) -> str:
"""Get a random periodicity string.
:return: Periodicity.
"""
periodicity = self._data['periodicity']
return self.random.choice(periodicity) | python | def periodicity(self) -> str:
"""Get a random periodicity string.
:return: Periodicity.
"""
periodicity = self._data['periodicity']
return self.random.choice(periodicity) | [
"def",
"periodicity",
"(",
"self",
")",
"->",
"str",
":",
"periodicity",
"=",
"self",
".",
"_data",
"[",
"'periodicity'",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"periodicity",
")"
] | Get a random periodicity string.
:return: Periodicity. | [
"Get",
"a",
"random",
"periodicity",
"string",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L125-L131 |
227,958 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.date | def date(self, start: int = 2000, end: int = 2019) -> Date:
"""Generate random date object.
:param start: Minimum value of year.
:param end: Maximum value of year.
:return: Formatted date.
"""
year = self.random.randint(start, end)
month = self.random.randint(1, 12)
day = self.random.randint(1, monthrange(year, month)[1])
date_object = date(year, month, day)
return date_object | python | def date(self, start: int = 2000, end: int = 2019) -> Date:
"""Generate random date object.
:param start: Minimum value of year.
:param end: Maximum value of year.
:return: Formatted date.
"""
year = self.random.randint(start, end)
month = self.random.randint(1, 12)
day = self.random.randint(1, monthrange(year, month)[1])
date_object = date(year, month, day)
return date_object | [
"def",
"date",
"(",
"self",
",",
"start",
":",
"int",
"=",
"2000",
",",
"end",
":",
"int",
"=",
"2019",
")",
"->",
"Date",
":",
"year",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"start",
",",
"end",
")",
"month",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"12",
")",
"day",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"monthrange",
"(",
"year",
",",
"month",
")",
"[",
"1",
"]",
")",
"date_object",
"=",
"date",
"(",
"year",
",",
"month",
",",
"day",
")",
"return",
"date_object"
] | Generate random date object.
:param start: Minimum value of year.
:param end: Maximum value of year.
:return: Formatted date. | [
"Generate",
"random",
"date",
"object",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L133-L144 |
227,959 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.formatted_date | def formatted_date(self, fmt: str = '', **kwargs) -> str:
"""Generate random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~Datetime.date()`
:return: Formatted date.
"""
date_obj = self.date(**kwargs)
if not fmt:
fmt = self._data['formats'].get('date')
return date_obj.strftime(fmt) | python | def formatted_date(self, fmt: str = '', **kwargs) -> str:
"""Generate random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~Datetime.date()`
:return: Formatted date.
"""
date_obj = self.date(**kwargs)
if not fmt:
fmt = self._data['formats'].get('date')
return date_obj.strftime(fmt) | [
"def",
"formatted_date",
"(",
"self",
",",
"fmt",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"date_obj",
"=",
"self",
".",
"date",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"fmt",
":",
"fmt",
"=",
"self",
".",
"_data",
"[",
"'formats'",
"]",
".",
"get",
"(",
"'date'",
")",
"return",
"date_obj",
".",
"strftime",
"(",
"fmt",
")"
] | Generate random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~Datetime.date()`
:return: Formatted date. | [
"Generate",
"random",
"date",
"as",
"string",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L146-L159 |
227,960 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.time | def time(self) -> Time:
"""Generate a random time object.
:return: ``datetime.time`` object.
"""
random_time = time(
self.random.randint(0, 23),
self.random.randint(0, 59),
self.random.randint(0, 59),
self.random.randint(0, 999999),
)
return random_time | python | def time(self) -> Time:
"""Generate a random time object.
:return: ``datetime.time`` object.
"""
random_time = time(
self.random.randint(0, 23),
self.random.randint(0, 59),
self.random.randint(0, 59),
self.random.randint(0, 999999),
)
return random_time | [
"def",
"time",
"(",
"self",
")",
"->",
"Time",
":",
"random_time",
"=",
"time",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"23",
")",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"59",
")",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"59",
")",
",",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"999999",
")",
",",
")",
"return",
"random_time"
] | Generate a random time object.
:return: ``datetime.time`` object. | [
"Generate",
"a",
"random",
"time",
"object",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L161-L172 |
227,961 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.formatted_time | def formatted_time(self, fmt: str = '') -> str:
"""Generate string formatted time.
:param fmt: The format of time, if None then use standard
accepted in the current locale.
:return: String formatted time.
"""
time_obj = self.time()
if not fmt:
fmt = self._data['formats'].get('time')
return time_obj.strftime(fmt) | python | def formatted_time(self, fmt: str = '') -> str:
"""Generate string formatted time.
:param fmt: The format of time, if None then use standard
accepted in the current locale.
:return: String formatted time.
"""
time_obj = self.time()
if not fmt:
fmt = self._data['formats'].get('time')
return time_obj.strftime(fmt) | [
"def",
"formatted_time",
"(",
"self",
",",
"fmt",
":",
"str",
"=",
"''",
")",
"->",
"str",
":",
"time_obj",
"=",
"self",
".",
"time",
"(",
")",
"if",
"not",
"fmt",
":",
"fmt",
"=",
"self",
".",
"_data",
"[",
"'formats'",
"]",
".",
"get",
"(",
"'time'",
")",
"return",
"time_obj",
".",
"strftime",
"(",
"fmt",
")"
] | Generate string formatted time.
:param fmt: The format of time, if None then use standard
accepted in the current locale.
:return: String formatted time. | [
"Generate",
"string",
"formatted",
"time",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L174-L185 |
227,962 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.datetime | def datetime(self, start: int = 2000, end: int = 2035,
timezone: Optional[str] = None) -> DateTime:
"""Generate random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom timezone (pytz required).
:return: Datetime
"""
datetime_obj = datetime.combine(
date=self.date(start, end),
time=self.time(),
)
if timezone:
if not pytz:
raise ImportError('Timezones are supported only with pytz')
tz = pytz.timezone(timezone)
datetime_obj = tz.localize(datetime_obj)
return datetime_obj | python | def datetime(self, start: int = 2000, end: int = 2035,
timezone: Optional[str] = None) -> DateTime:
"""Generate random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom timezone (pytz required).
:return: Datetime
"""
datetime_obj = datetime.combine(
date=self.date(start, end),
time=self.time(),
)
if timezone:
if not pytz:
raise ImportError('Timezones are supported only with pytz')
tz = pytz.timezone(timezone)
datetime_obj = tz.localize(datetime_obj)
return datetime_obj | [
"def",
"datetime",
"(",
"self",
",",
"start",
":",
"int",
"=",
"2000",
",",
"end",
":",
"int",
"=",
"2035",
",",
"timezone",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"DateTime",
":",
"datetime_obj",
"=",
"datetime",
".",
"combine",
"(",
"date",
"=",
"self",
".",
"date",
"(",
"start",
",",
"end",
")",
",",
"time",
"=",
"self",
".",
"time",
"(",
")",
",",
")",
"if",
"timezone",
":",
"if",
"not",
"pytz",
":",
"raise",
"ImportError",
"(",
"'Timezones are supported only with pytz'",
")",
"tz",
"=",
"pytz",
".",
"timezone",
"(",
"timezone",
")",
"datetime_obj",
"=",
"tz",
".",
"localize",
"(",
"datetime_obj",
")",
"return",
"datetime_obj"
] | Generate random datetime.
:param start: Minimum value of year.
:param end: Maximum value of year.
:param timezone: Set custom timezone (pytz required).
:return: Datetime | [
"Generate",
"random",
"datetime",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L208-L227 |
227,963 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.formatted_datetime | def formatted_datetime(self, fmt: str = '', **kwargs) -> str:
"""Generate datetime string in human readable format.
:param fmt: Custom format (default is format for current locale)
:param kwargs: Keyword arguments for :meth:`~Datetime.datetime()`
:return: Formatted datetime string.
"""
dt_obj = self.datetime(**kwargs)
if not fmt:
date_fmt = self._data['formats'].get('date')
time_fmt = self._data['formats'].get('time')
fmt = '{} {}'.format(date_fmt, time_fmt)
return dt_obj.strftime(fmt) | python | def formatted_datetime(self, fmt: str = '', **kwargs) -> str:
"""Generate datetime string in human readable format.
:param fmt: Custom format (default is format for current locale)
:param kwargs: Keyword arguments for :meth:`~Datetime.datetime()`
:return: Formatted datetime string.
"""
dt_obj = self.datetime(**kwargs)
if not fmt:
date_fmt = self._data['formats'].get('date')
time_fmt = self._data['formats'].get('time')
fmt = '{} {}'.format(date_fmt, time_fmt)
return dt_obj.strftime(fmt) | [
"def",
"formatted_datetime",
"(",
"self",
",",
"fmt",
":",
"str",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"dt_obj",
"=",
"self",
".",
"datetime",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"fmt",
":",
"date_fmt",
"=",
"self",
".",
"_data",
"[",
"'formats'",
"]",
".",
"get",
"(",
"'date'",
")",
"time_fmt",
"=",
"self",
".",
"_data",
"[",
"'formats'",
"]",
".",
"get",
"(",
"'time'",
")",
"fmt",
"=",
"'{} {}'",
".",
"format",
"(",
"date_fmt",
",",
"time_fmt",
")",
"return",
"dt_obj",
".",
"strftime",
"(",
"fmt",
")"
] | Generate datetime string in human readable format.
:param fmt: Custom format (default is format for current locale)
:param kwargs: Keyword arguments for :meth:`~Datetime.datetime()`
:return: Formatted datetime string. | [
"Generate",
"datetime",
"string",
"in",
"human",
"readable",
"format",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L229-L243 |
227,964 | lk-geimfari/mimesis | mimesis/providers/date.py | Datetime.timestamp | def timestamp(self, posix: bool = True, **kwargs) -> Union[str, int]:
"""Generate random timestamp.
:param posix: POSIX time.
:param kwargs: Kwargs for :meth:`~Datetime.datetime()`.
:return: Timestamp.
"""
stamp = self.datetime(**kwargs)
if posix:
return timegm(stamp.utctimetuple())
return stamp.strftime('%Y-%m-%dT%H:%M:%SZ') | python | def timestamp(self, posix: bool = True, **kwargs) -> Union[str, int]:
"""Generate random timestamp.
:param posix: POSIX time.
:param kwargs: Kwargs for :meth:`~Datetime.datetime()`.
:return: Timestamp.
"""
stamp = self.datetime(**kwargs)
if posix:
return timegm(stamp.utctimetuple())
return stamp.strftime('%Y-%m-%dT%H:%M:%SZ') | [
"def",
"timestamp",
"(",
"self",
",",
"posix",
":",
"bool",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"->",
"Union",
"[",
"str",
",",
"int",
"]",
":",
"stamp",
"=",
"self",
".",
"datetime",
"(",
"*",
"*",
"kwargs",
")",
"if",
"posix",
":",
"return",
"timegm",
"(",
"stamp",
".",
"utctimetuple",
"(",
")",
")",
"return",
"stamp",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%SZ'",
")"
] | Generate random timestamp.
:param posix: POSIX time.
:param kwargs: Kwargs for :meth:`~Datetime.datetime()`.
:return: Timestamp. | [
"Generate",
"random",
"timestamp",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L245-L257 |
227,965 | lk-geimfari/mimesis | mimesis/providers/cryptographic.py | Cryptographic.uuid | def uuid(self, version: int = None) -> str:
"""Generate random UUID.
:param version: UUID version.
:return: UUID
"""
bits = self.random.getrandbits(128)
return str(uuid.UUID(int=bits, version=version)) | python | def uuid(self, version: int = None) -> str:
"""Generate random UUID.
:param version: UUID version.
:return: UUID
"""
bits = self.random.getrandbits(128)
return str(uuid.UUID(int=bits, version=version)) | [
"def",
"uuid",
"(",
"self",
",",
"version",
":",
"int",
"=",
"None",
")",
"->",
"str",
":",
"bits",
"=",
"self",
".",
"random",
".",
"getrandbits",
"(",
"128",
")",
"return",
"str",
"(",
"uuid",
".",
"UUID",
"(",
"int",
"=",
"bits",
",",
"version",
"=",
"version",
")",
")"
] | Generate random UUID.
:param version: UUID version.
:return: UUID | [
"Generate",
"random",
"UUID",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/cryptographic.py#L32-L39 |
227,966 | lk-geimfari/mimesis | mimesis/providers/cryptographic.py | Cryptographic.hash | def hash(self, algorithm: Algorithm = None) -> str: # noqa: A003
"""Generate random hash.
To change hashing algorithm, pass parameter ``algorithm``
with needed value of the enum object :class:`~mimesis.enums.Algorithm`
:param algorithm: Enum object :class:`~mimesis.enums.Algorithm`.
:return: Hash.
:raises NonEnumerableError: if algorithm is not supported.
"""
key = self._validate_enum(algorithm, Algorithm)
if hasattr(hashlib, key):
fn = getattr(hashlib, key)
return fn(self.uuid().encode()).hexdigest() | python | def hash(self, algorithm: Algorithm = None) -> str: # noqa: A003
"""Generate random hash.
To change hashing algorithm, pass parameter ``algorithm``
with needed value of the enum object :class:`~mimesis.enums.Algorithm`
:param algorithm: Enum object :class:`~mimesis.enums.Algorithm`.
:return: Hash.
:raises NonEnumerableError: if algorithm is not supported.
"""
key = self._validate_enum(algorithm, Algorithm)
if hasattr(hashlib, key):
fn = getattr(hashlib, key)
return fn(self.uuid().encode()).hexdigest() | [
"def",
"hash",
"(",
"self",
",",
"algorithm",
":",
"Algorithm",
"=",
"None",
")",
"->",
"str",
":",
"# noqa: A003",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"algorithm",
",",
"Algorithm",
")",
"if",
"hasattr",
"(",
"hashlib",
",",
"key",
")",
":",
"fn",
"=",
"getattr",
"(",
"hashlib",
",",
"key",
")",
"return",
"fn",
"(",
"self",
".",
"uuid",
"(",
")",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")"
] | Generate random hash.
To change hashing algorithm, pass parameter ``algorithm``
with needed value of the enum object :class:`~mimesis.enums.Algorithm`
:param algorithm: Enum object :class:`~mimesis.enums.Algorithm`.
:return: Hash.
:raises NonEnumerableError: if algorithm is not supported. | [
"Generate",
"random",
"hash",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/cryptographic.py#L41-L55 |
227,967 | lk-geimfari/mimesis | mimesis/providers/cryptographic.py | Cryptographic.mnemonic_phrase | def mnemonic_phrase(self, length: int = 12) -> str:
"""Generate pseudo mnemonic phrase.
:param length: Number of words.
:return: Mnemonic code.
"""
words = self.__words['normal']
return ' '.join(self.random.choice(words) for _ in range(length)) | python | def mnemonic_phrase(self, length: int = 12) -> str:
"""Generate pseudo mnemonic phrase.
:param length: Number of words.
:return: Mnemonic code.
"""
words = self.__words['normal']
return ' '.join(self.random.choice(words) for _ in range(length)) | [
"def",
"mnemonic_phrase",
"(",
"self",
",",
"length",
":",
"int",
"=",
"12",
")",
"->",
"str",
":",
"words",
"=",
"self",
".",
"__words",
"[",
"'normal'",
"]",
"return",
"' '",
".",
"join",
"(",
"self",
".",
"random",
".",
"choice",
"(",
"words",
")",
"for",
"_",
"in",
"range",
"(",
"length",
")",
")"
] | Generate pseudo mnemonic phrase.
:param length: Number of words.
:return: Mnemonic code. | [
"Generate",
"pseudo",
"mnemonic",
"phrase",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/cryptographic.py#L104-L111 |
227,968 | lk-geimfari/mimesis | setup.py | Minimizer.initialize_options | def initialize_options(self):
"""Find all files of all locales."""
self.paths = []
self.separators = (',', ':')
self.data_dir = join(here, 'mimesis', 'data')
self.before_total = 0
self.after_total = 0
for root, _, files in os.walk(self.data_dir):
for file in sorted(files):
if splitext(file)[1] == '.json':
self.paths.append(join(
relpath(root, self.data_dir), file)) | python | def initialize_options(self):
"""Find all files of all locales."""
self.paths = []
self.separators = (',', ':')
self.data_dir = join(here, 'mimesis', 'data')
self.before_total = 0
self.after_total = 0
for root, _, files in os.walk(self.data_dir):
for file in sorted(files):
if splitext(file)[1] == '.json':
self.paths.append(join(
relpath(root, self.data_dir), file)) | [
"def",
"initialize_options",
"(",
"self",
")",
":",
"self",
".",
"paths",
"=",
"[",
"]",
"self",
".",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
"self",
".",
"data_dir",
"=",
"join",
"(",
"here",
",",
"'mimesis'",
",",
"'data'",
")",
"self",
".",
"before_total",
"=",
"0",
"self",
".",
"after_total",
"=",
"0",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"data_dir",
")",
":",
"for",
"file",
"in",
"sorted",
"(",
"files",
")",
":",
"if",
"splitext",
"(",
"file",
")",
"[",
"1",
"]",
"==",
"'.json'",
":",
"self",
".",
"paths",
".",
"append",
"(",
"join",
"(",
"relpath",
"(",
"root",
",",
"self",
".",
"data_dir",
")",
",",
"file",
")",
")"
] | Find all files of all locales. | [
"Find",
"all",
"files",
"of",
"all",
"locales",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/setup.py#L34-L46 |
227,969 | lk-geimfari/mimesis | setup.py | Minimizer.run | def run(self):
"""Start json minimizer and exit when all json files were minimized."""
for rel_path in sorted(self.paths):
file_path = join(self.data_dir, rel_path)
self.minify(file_path)
after = self.size_of(self.after_total)
before = self.size_of(self.before_total)
saved = self.size_of(self.before_total - self.after_total)
template = '\nTotal: ' \
'\033[92m{}\033[0m -> \033[92m{}\033[0m. ' \
'Compressed: \033[92m{}\033[0m\n'
print(template.format(before, after, saved)) | python | def run(self):
"""Start json minimizer and exit when all json files were minimized."""
for rel_path in sorted(self.paths):
file_path = join(self.data_dir, rel_path)
self.minify(file_path)
after = self.size_of(self.after_total)
before = self.size_of(self.before_total)
saved = self.size_of(self.before_total - self.after_total)
template = '\nTotal: ' \
'\033[92m{}\033[0m -> \033[92m{}\033[0m. ' \
'Compressed: \033[92m{}\033[0m\n'
print(template.format(before, after, saved)) | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"rel_path",
"in",
"sorted",
"(",
"self",
".",
"paths",
")",
":",
"file_path",
"=",
"join",
"(",
"self",
".",
"data_dir",
",",
"rel_path",
")",
"self",
".",
"minify",
"(",
"file_path",
")",
"after",
"=",
"self",
".",
"size_of",
"(",
"self",
".",
"after_total",
")",
"before",
"=",
"self",
".",
"size_of",
"(",
"self",
".",
"before_total",
")",
"saved",
"=",
"self",
".",
"size_of",
"(",
"self",
".",
"before_total",
"-",
"self",
".",
"after_total",
")",
"template",
"=",
"'\\nTotal: '",
"'\\033[92m{}\\033[0m -> \\033[92m{}\\033[0m. '",
"'Compressed: \\033[92m{}\\033[0m\\n'",
"print",
"(",
"template",
".",
"format",
"(",
"before",
",",
"after",
",",
"saved",
")",
")"
] | Start json minimizer and exit when all json files were minimized. | [
"Start",
"json",
"minimizer",
"and",
"exit",
"when",
"all",
"json",
"files",
"were",
"minimized",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/setup.py#L92-L106 |
227,970 | lk-geimfari/mimesis | mimesis/providers/structure.py | Structure.css | def css(self) -> str:
"""Generate a random snippet of CSS.
:return: CSS.
"""
selector = self.random.choice(CSS_SELECTORS)
css_sel = '{}{}'.format(selector, self.__text.word())
cont_tag = self.random.choice(list(HTML_CONTAINER_TAGS.keys()))
mrk_tag = self.random.choice(HTML_MARKUP_TAGS)
base = '{}'.format(self.random.choice([cont_tag, mrk_tag, css_sel]))
props = '; '.join(
[self.css_property() for _ in range(self.random.randint(1, 6))])
return '{} {{{}}}'.format(base, props) | python | def css(self) -> str:
"""Generate a random snippet of CSS.
:return: CSS.
"""
selector = self.random.choice(CSS_SELECTORS)
css_sel = '{}{}'.format(selector, self.__text.word())
cont_tag = self.random.choice(list(HTML_CONTAINER_TAGS.keys()))
mrk_tag = self.random.choice(HTML_MARKUP_TAGS)
base = '{}'.format(self.random.choice([cont_tag, mrk_tag, css_sel]))
props = '; '.join(
[self.css_property() for _ in range(self.random.randint(1, 6))])
return '{} {{{}}}'.format(base, props) | [
"def",
"css",
"(",
"self",
")",
"->",
"str",
":",
"selector",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"CSS_SELECTORS",
")",
"css_sel",
"=",
"'{}{}'",
".",
"format",
"(",
"selector",
",",
"self",
".",
"__text",
".",
"word",
"(",
")",
")",
"cont_tag",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"list",
"(",
"HTML_CONTAINER_TAGS",
".",
"keys",
"(",
")",
")",
")",
"mrk_tag",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"HTML_MARKUP_TAGS",
")",
"base",
"=",
"'{}'",
".",
"format",
"(",
"self",
".",
"random",
".",
"choice",
"(",
"[",
"cont_tag",
",",
"mrk_tag",
",",
"css_sel",
"]",
")",
")",
"props",
"=",
"'; '",
".",
"join",
"(",
"[",
"self",
".",
"css_property",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"6",
")",
")",
"]",
")",
"return",
"'{} {{{}}}'",
".",
"format",
"(",
"base",
",",
"props",
")"
] | Generate a random snippet of CSS.
:return: CSS. | [
"Generate",
"a",
"random",
"snippet",
"of",
"CSS",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/structure.py#L37-L51 |
227,971 | lk-geimfari/mimesis | mimesis/providers/structure.py | Structure.css_property | def css_property(self) -> str:
"""Generate a random snippet of CSS that assigns value to a property.
:return: CSS property.
:Examples:
'background-color: #f4d3a1'
"""
prop = self.random.choice(list(CSS_PROPERTIES.keys()))
val = CSS_PROPERTIES[prop]
if isinstance(val, list):
val = self.random.choice(val)
elif val == 'color':
val = self.__text.hex_color()
elif val == 'size':
val = '{}{}'.format(self.random.randint(1, 99),
self.random.choice(CSS_SIZE_UNITS))
return '{}: {}'.format(prop, val) | python | def css_property(self) -> str:
"""Generate a random snippet of CSS that assigns value to a property.
:return: CSS property.
:Examples:
'background-color: #f4d3a1'
"""
prop = self.random.choice(list(CSS_PROPERTIES.keys()))
val = CSS_PROPERTIES[prop]
if isinstance(val, list):
val = self.random.choice(val)
elif val == 'color':
val = self.__text.hex_color()
elif val == 'size':
val = '{}{}'.format(self.random.randint(1, 99),
self.random.choice(CSS_SIZE_UNITS))
return '{}: {}'.format(prop, val) | [
"def",
"css_property",
"(",
"self",
")",
"->",
"str",
":",
"prop",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"list",
"(",
"CSS_PROPERTIES",
".",
"keys",
"(",
")",
")",
")",
"val",
"=",
"CSS_PROPERTIES",
"[",
"prop",
"]",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"val",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"val",
")",
"elif",
"val",
"==",
"'color'",
":",
"val",
"=",
"self",
".",
"__text",
".",
"hex_color",
"(",
")",
"elif",
"val",
"==",
"'size'",
":",
"val",
"=",
"'{}{}'",
".",
"format",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"99",
")",
",",
"self",
".",
"random",
".",
"choice",
"(",
"CSS_SIZE_UNITS",
")",
")",
"return",
"'{}: {}'",
".",
"format",
"(",
"prop",
",",
"val",
")"
] | Generate a random snippet of CSS that assigns value to a property.
:return: CSS property.
:Examples:
'background-color: #f4d3a1' | [
"Generate",
"a",
"random",
"snippet",
"of",
"CSS",
"that",
"assigns",
"value",
"to",
"a",
"property",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/structure.py#L53-L72 |
227,972 | lk-geimfari/mimesis | mimesis/providers/structure.py | Structure.html | def html(self) -> str:
"""Generate a random HTML tag with text inside and some attrs set.
:return: HTML.
:Examples:
'<span class="select" id="careers">
Ports are created with the built-in function open_port.
</span>'
"""
tag_name = self.random.choice(list(HTML_CONTAINER_TAGS))
tag_attributes = list(HTML_CONTAINER_TAGS[tag_name]) # type: ignore
k = self.random.randint(1, len(tag_attributes))
selected_attrs = self.random.sample(tag_attributes, k=k)
attrs = []
for attr in selected_attrs:
attrs.append('{}="{}"'.format(
attr, self.html_attribute_value(tag_name, attr)))
html_result = '<{tag} {attrs}>{content}</{tag}>'
return html_result.format(
tag=tag_name,
attrs=' '.join(attrs),
content=self.__text.sentence(),
) | python | def html(self) -> str:
"""Generate a random HTML tag with text inside and some attrs set.
:return: HTML.
:Examples:
'<span class="select" id="careers">
Ports are created with the built-in function open_port.
</span>'
"""
tag_name = self.random.choice(list(HTML_CONTAINER_TAGS))
tag_attributes = list(HTML_CONTAINER_TAGS[tag_name]) # type: ignore
k = self.random.randint(1, len(tag_attributes))
selected_attrs = self.random.sample(tag_attributes, k=k)
attrs = []
for attr in selected_attrs:
attrs.append('{}="{}"'.format(
attr, self.html_attribute_value(tag_name, attr)))
html_result = '<{tag} {attrs}>{content}</{tag}>'
return html_result.format(
tag=tag_name,
attrs=' '.join(attrs),
content=self.__text.sentence(),
) | [
"def",
"html",
"(",
"self",
")",
"->",
"str",
":",
"tag_name",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"list",
"(",
"HTML_CONTAINER_TAGS",
")",
")",
"tag_attributes",
"=",
"list",
"(",
"HTML_CONTAINER_TAGS",
"[",
"tag_name",
"]",
")",
"# type: ignore",
"k",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"len",
"(",
"tag_attributes",
")",
")",
"selected_attrs",
"=",
"self",
".",
"random",
".",
"sample",
"(",
"tag_attributes",
",",
"k",
"=",
"k",
")",
"attrs",
"=",
"[",
"]",
"for",
"attr",
"in",
"selected_attrs",
":",
"attrs",
".",
"append",
"(",
"'{}=\"{}\"'",
".",
"format",
"(",
"attr",
",",
"self",
".",
"html_attribute_value",
"(",
"tag_name",
",",
"attr",
")",
")",
")",
"html_result",
"=",
"'<{tag} {attrs}>{content}</{tag}>'",
"return",
"html_result",
".",
"format",
"(",
"tag",
"=",
"tag_name",
",",
"attrs",
"=",
"' '",
".",
"join",
"(",
"attrs",
")",
",",
"content",
"=",
"self",
".",
"__text",
".",
"sentence",
"(",
")",
",",
")"
] | Generate a random HTML tag with text inside and some attrs set.
:return: HTML.
:Examples:
'<span class="select" id="careers">
Ports are created with the built-in function open_port.
</span>' | [
"Generate",
"a",
"random",
"HTML",
"tag",
"with",
"text",
"inside",
"and",
"some",
"attrs",
"set",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/structure.py#L74-L100 |
227,973 | lk-geimfari/mimesis | mimesis/providers/structure.py | Structure.html_attribute_value | def html_attribute_value(self, tag: str = None,
attribute: str = None) -> str:
"""Generate random value for specified HTML tag attribute.
:param tag: An HTML tag.
:param attribute: An attribute of the specified tag.
:return: An attribute.
:raises NotImplementedError: if tag is unsupported.
"""
if not tag:
tag = self.random.choice(
list(HTML_CONTAINER_TAGS.keys()),
)
if not attribute:
attribute = self.random.choice(
list(HTML_CONTAINER_TAGS[tag]), # type: ignore
)
try:
value = HTML_CONTAINER_TAGS[tag][attribute] # type: ignore
except KeyError:
raise NotImplementedError(
'Tag {} or attribute {} is not supported'.format(
tag, attribute))
if isinstance(value, list):
value = self.random.choice(value)
elif value == 'css':
value = self.css_property()
elif value == 'word':
value = self.__text.word()
elif value == 'url':
value = self.__inet.home_page()
else:
raise NotImplementedError(
'Attribute type {} is not implemented'.format(value))
return value | python | def html_attribute_value(self, tag: str = None,
attribute: str = None) -> str:
"""Generate random value for specified HTML tag attribute.
:param tag: An HTML tag.
:param attribute: An attribute of the specified tag.
:return: An attribute.
:raises NotImplementedError: if tag is unsupported.
"""
if not tag:
tag = self.random.choice(
list(HTML_CONTAINER_TAGS.keys()),
)
if not attribute:
attribute = self.random.choice(
list(HTML_CONTAINER_TAGS[tag]), # type: ignore
)
try:
value = HTML_CONTAINER_TAGS[tag][attribute] # type: ignore
except KeyError:
raise NotImplementedError(
'Tag {} or attribute {} is not supported'.format(
tag, attribute))
if isinstance(value, list):
value = self.random.choice(value)
elif value == 'css':
value = self.css_property()
elif value == 'word':
value = self.__text.word()
elif value == 'url':
value = self.__inet.home_page()
else:
raise NotImplementedError(
'Attribute type {} is not implemented'.format(value))
return value | [
"def",
"html_attribute_value",
"(",
"self",
",",
"tag",
":",
"str",
"=",
"None",
",",
"attribute",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"not",
"tag",
":",
"tag",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"list",
"(",
"HTML_CONTAINER_TAGS",
".",
"keys",
"(",
")",
")",
",",
")",
"if",
"not",
"attribute",
":",
"attribute",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"list",
"(",
"HTML_CONTAINER_TAGS",
"[",
"tag",
"]",
")",
",",
"# type: ignore",
")",
"try",
":",
"value",
"=",
"HTML_CONTAINER_TAGS",
"[",
"tag",
"]",
"[",
"attribute",
"]",
"# type: ignore",
"except",
"KeyError",
":",
"raise",
"NotImplementedError",
"(",
"'Tag {} or attribute {} is not supported'",
".",
"format",
"(",
"tag",
",",
"attribute",
")",
")",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"value",
")",
"elif",
"value",
"==",
"'css'",
":",
"value",
"=",
"self",
".",
"css_property",
"(",
")",
"elif",
"value",
"==",
"'word'",
":",
"value",
"=",
"self",
".",
"__text",
".",
"word",
"(",
")",
"elif",
"value",
"==",
"'url'",
":",
"value",
"=",
"self",
".",
"__inet",
".",
"home_page",
"(",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Attribute type {} is not implemented'",
".",
"format",
"(",
"value",
")",
")",
"return",
"value"
] | Generate random value for specified HTML tag attribute.
:param tag: An HTML tag.
:param attribute: An attribute of the specified tag.
:return: An attribute.
:raises NotImplementedError: if tag is unsupported. | [
"Generate",
"random",
"value",
"for",
"specified",
"HTML",
"tag",
"attribute",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/structure.py#L102-L138 |
227,974 | lk-geimfari/mimesis | mimesis/providers/development.py | Development.version | def version(self, calver: bool = False, pre_release: bool = False) -> str:
"""Generate version number.
:param calver: Calendar versioning.
:param pre_release: Pre-release.
:return: Version.
:Example:
0.2.1
"""
# TODO: Optimize
version = '{}.{}.{}'
major, minor, patch = self.random.randints(3, 0, 10)
if calver:
if minor == 0:
minor += 1
if patch == 0:
patch += 1
major = self.random.randint(2016, 2018)
return version.format(major, minor, patch)
version = '{}.{}.{}'.format(major, minor, patch)
if pre_release:
suffixes = ('alpha', 'beta', 'rc')
suffix = self.random.choice(suffixes)
number = self.random.randint(1, 11)
return '{}-{}.{}'.format(version, suffix, number)
return version | python | def version(self, calver: bool = False, pre_release: bool = False) -> str:
"""Generate version number.
:param calver: Calendar versioning.
:param pre_release: Pre-release.
:return: Version.
:Example:
0.2.1
"""
# TODO: Optimize
version = '{}.{}.{}'
major, minor, patch = self.random.randints(3, 0, 10)
if calver:
if minor == 0:
minor += 1
if patch == 0:
patch += 1
major = self.random.randint(2016, 2018)
return version.format(major, minor, patch)
version = '{}.{}.{}'.format(major, minor, patch)
if pre_release:
suffixes = ('alpha', 'beta', 'rc')
suffix = self.random.choice(suffixes)
number = self.random.randint(1, 11)
return '{}-{}.{}'.format(version, suffix, number)
return version | [
"def",
"version",
"(",
"self",
",",
"calver",
":",
"bool",
"=",
"False",
",",
"pre_release",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"# TODO: Optimize",
"version",
"=",
"'{}.{}.{}'",
"major",
",",
"minor",
",",
"patch",
"=",
"self",
".",
"random",
".",
"randints",
"(",
"3",
",",
"0",
",",
"10",
")",
"if",
"calver",
":",
"if",
"minor",
"==",
"0",
":",
"minor",
"+=",
"1",
"if",
"patch",
"==",
"0",
":",
"patch",
"+=",
"1",
"major",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"2016",
",",
"2018",
")",
"return",
"version",
".",
"format",
"(",
"major",
",",
"minor",
",",
"patch",
")",
"version",
"=",
"'{}.{}.{}'",
".",
"format",
"(",
"major",
",",
"minor",
",",
"patch",
")",
"if",
"pre_release",
":",
"suffixes",
"=",
"(",
"'alpha'",
",",
"'beta'",
",",
"'rc'",
")",
"suffix",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"suffixes",
")",
"number",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"11",
")",
"return",
"'{}-{}.{}'",
".",
"format",
"(",
"version",
",",
"suffix",
",",
"number",
")",
"return",
"version"
] | Generate version number.
:param calver: Calendar versioning.
:param pre_release: Pre-release.
:return: Version.
:Example:
0.2.1 | [
"Generate",
"version",
"number",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/development.py#L29-L60 |
227,975 | lk-geimfari/mimesis | mimesis/providers/science.py | Science.chemical_element | def chemical_element(self, name_only: bool = True) -> Union[dict, str]:
"""Generate a random chemical element.
:param name_only: If False then will be returned dict.
:return: Name of chemical element or dict.
:rtype: dict or str
:Example:
{'Symbol': 'S', 'Name': 'Sulfur', 'Atomic number': '16'}
"""
elements = self._data['chemical_element']
nm, sm, an = self.random.choice(elements).split('|')
if not name_only:
return {
'name': nm.strip(),
'symbol': sm.strip(),
'atomic_number': an.strip(),
}
return nm.strip() | python | def chemical_element(self, name_only: bool = True) -> Union[dict, str]:
"""Generate a random chemical element.
:param name_only: If False then will be returned dict.
:return: Name of chemical element or dict.
:rtype: dict or str
:Example:
{'Symbol': 'S', 'Name': 'Sulfur', 'Atomic number': '16'}
"""
elements = self._data['chemical_element']
nm, sm, an = self.random.choice(elements).split('|')
if not name_only:
return {
'name': nm.strip(),
'symbol': sm.strip(),
'atomic_number': an.strip(),
}
return nm.strip() | [
"def",
"chemical_element",
"(",
"self",
",",
"name_only",
":",
"bool",
"=",
"True",
")",
"->",
"Union",
"[",
"dict",
",",
"str",
"]",
":",
"elements",
"=",
"self",
".",
"_data",
"[",
"'chemical_element'",
"]",
"nm",
",",
"sm",
",",
"an",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"elements",
")",
".",
"split",
"(",
"'|'",
")",
"if",
"not",
"name_only",
":",
"return",
"{",
"'name'",
":",
"nm",
".",
"strip",
"(",
")",
",",
"'symbol'",
":",
"sm",
".",
"strip",
"(",
")",
",",
"'atomic_number'",
":",
"an",
".",
"strip",
"(",
")",
",",
"}",
"return",
"nm",
".",
"strip",
"(",
")"
] | Generate a random chemical element.
:param name_only: If False then will be returned dict.
:return: Name of chemical element or dict.
:rtype: dict or str
:Example:
{'Symbol': 'S', 'Name': 'Sulfur', 'Atomic number': '16'} | [
"Generate",
"a",
"random",
"chemical",
"element",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/science.py#L42-L62 |
227,976 | lk-geimfari/mimesis | mimesis/builtins/pt_br.py | BrazilSpecProvider.cpf | def cpf(self, with_mask: bool = True) -> str:
"""Get a random CPF.
:param with_mask: Use CPF mask (###.###.###-##).
:returns: Random CPF.
:Example:
001.137.297-40
"""
def get_verifying_digit_cpf(cpf, peso):
"""Calculate the verifying digit for the CPF.
:param cpf: List of integers with the CPF.
:param peso: Integer with the weight for the modulo 11 calculate.
:returns: The verifying digit for the CPF.
"""
soma = 0
for index, digit in enumerate(cpf):
soma += digit * (peso - index)
resto = soma % 11
if resto == 0 or resto == 1 or resto >= 11:
return 0
return 11 - resto
cpf_without_dv = [self.random.randint(0, 9) for _ in range(9)]
first_dv = get_verifying_digit_cpf(cpf_without_dv, 10)
cpf_without_dv.append(first_dv)
second_dv = get_verifying_digit_cpf(cpf_without_dv, 11)
cpf_without_dv.append(second_dv)
cpf = ''.join([str(i) for i in cpf_without_dv])
if with_mask:
return cpf[:3] + '.' + cpf[3:6] + '.' + cpf[6:9] + '-' + cpf[9:]
return cpf | python | def cpf(self, with_mask: bool = True) -> str:
"""Get a random CPF.
:param with_mask: Use CPF mask (###.###.###-##).
:returns: Random CPF.
:Example:
001.137.297-40
"""
def get_verifying_digit_cpf(cpf, peso):
"""Calculate the verifying digit for the CPF.
:param cpf: List of integers with the CPF.
:param peso: Integer with the weight for the modulo 11 calculate.
:returns: The verifying digit for the CPF.
"""
soma = 0
for index, digit in enumerate(cpf):
soma += digit * (peso - index)
resto = soma % 11
if resto == 0 or resto == 1 or resto >= 11:
return 0
return 11 - resto
cpf_without_dv = [self.random.randint(0, 9) for _ in range(9)]
first_dv = get_verifying_digit_cpf(cpf_without_dv, 10)
cpf_without_dv.append(first_dv)
second_dv = get_verifying_digit_cpf(cpf_without_dv, 11)
cpf_without_dv.append(second_dv)
cpf = ''.join([str(i) for i in cpf_without_dv])
if with_mask:
return cpf[:3] + '.' + cpf[3:6] + '.' + cpf[6:9] + '-' + cpf[9:]
return cpf | [
"def",
"cpf",
"(",
"self",
",",
"with_mask",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"def",
"get_verifying_digit_cpf",
"(",
"cpf",
",",
"peso",
")",
":",
"\"\"\"Calculate the verifying digit for the CPF.\n\n :param cpf: List of integers with the CPF.\n :param peso: Integer with the weight for the modulo 11 calculate.\n :returns: The verifying digit for the CPF.\n \"\"\"",
"soma",
"=",
"0",
"for",
"index",
",",
"digit",
"in",
"enumerate",
"(",
"cpf",
")",
":",
"soma",
"+=",
"digit",
"*",
"(",
"peso",
"-",
"index",
")",
"resto",
"=",
"soma",
"%",
"11",
"if",
"resto",
"==",
"0",
"or",
"resto",
"==",
"1",
"or",
"resto",
">=",
"11",
":",
"return",
"0",
"return",
"11",
"-",
"resto",
"cpf_without_dv",
"=",
"[",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
"for",
"_",
"in",
"range",
"(",
"9",
")",
"]",
"first_dv",
"=",
"get_verifying_digit_cpf",
"(",
"cpf_without_dv",
",",
"10",
")",
"cpf_without_dv",
".",
"append",
"(",
"first_dv",
")",
"second_dv",
"=",
"get_verifying_digit_cpf",
"(",
"cpf_without_dv",
",",
"11",
")",
"cpf_without_dv",
".",
"append",
"(",
"second_dv",
")",
"cpf",
"=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"cpf_without_dv",
"]",
")",
"if",
"with_mask",
":",
"return",
"cpf",
"[",
":",
"3",
"]",
"+",
"'.'",
"+",
"cpf",
"[",
"3",
":",
"6",
"]",
"+",
"'.'",
"+",
"cpf",
"[",
"6",
":",
"9",
"]",
"+",
"'-'",
"+",
"cpf",
"[",
"9",
":",
"]",
"return",
"cpf"
] | Get a random CPF.
:param with_mask: Use CPF mask (###.###.###-##).
:returns: Random CPF.
:Example:
001.137.297-40 | [
"Get",
"a",
"random",
"CPF",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/pt_br.py#L23-L58 |
227,977 | lk-geimfari/mimesis | mimesis/builtins/pt_br.py | BrazilSpecProvider.cnpj | def cnpj(self, with_mask: bool = True) -> str:
"""Get a random CNPJ.
:param with_mask: Use cnpj mask (###.###.###-##)
:returns: Random cnpj.
:Example:
77.732.230/0001-70
"""
def get_verifying_digit_cnpj(cnpj, peso):
"""Calculate the verifying digit for the CNPJ.
:param cnpj: List of integers with the CNPJ.
:param peso: Integer with the weight for the modulo 11 calculate.
:returns: The verifying digit for the CNPJ.
"""
soma = 0
if peso == 5:
peso_list = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
elif peso == 6:
peso_list = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
for i, _ in enumerate(cnpj):
soma += peso_list[i] * cnpj[i]
resto = soma % 11
if resto < 2:
return 0
return 11 - resto
cnpj_without_dv = [self.random.randint(0, 9) for _ in range(12)]
first_dv = get_verifying_digit_cnpj(cnpj_without_dv, 5)
cnpj_without_dv.append(first_dv)
second_dv = get_verifying_digit_cnpj(cnpj_without_dv, 6)
cnpj_without_dv.append(second_dv)
cnpj = ''.join([str(i) for i in cnpj_without_dv])
if with_mask:
return '{}.{}.{}/{}-{}'.format(cnpj[:2], cnpj[2:5],
cnpj[5:8], cnpj[8:12], cnpj[12:])
return cnpj | python | def cnpj(self, with_mask: bool = True) -> str:
"""Get a random CNPJ.
:param with_mask: Use cnpj mask (###.###.###-##)
:returns: Random cnpj.
:Example:
77.732.230/0001-70
"""
def get_verifying_digit_cnpj(cnpj, peso):
"""Calculate the verifying digit for the CNPJ.
:param cnpj: List of integers with the CNPJ.
:param peso: Integer with the weight for the modulo 11 calculate.
:returns: The verifying digit for the CNPJ.
"""
soma = 0
if peso == 5:
peso_list = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
elif peso == 6:
peso_list = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]
for i, _ in enumerate(cnpj):
soma += peso_list[i] * cnpj[i]
resto = soma % 11
if resto < 2:
return 0
return 11 - resto
cnpj_without_dv = [self.random.randint(0, 9) for _ in range(12)]
first_dv = get_verifying_digit_cnpj(cnpj_without_dv, 5)
cnpj_without_dv.append(first_dv)
second_dv = get_verifying_digit_cnpj(cnpj_without_dv, 6)
cnpj_without_dv.append(second_dv)
cnpj = ''.join([str(i) for i in cnpj_without_dv])
if with_mask:
return '{}.{}.{}/{}-{}'.format(cnpj[:2], cnpj[2:5],
cnpj[5:8], cnpj[8:12], cnpj[12:])
return cnpj | [
"def",
"cnpj",
"(",
"self",
",",
"with_mask",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"def",
"get_verifying_digit_cnpj",
"(",
"cnpj",
",",
"peso",
")",
":",
"\"\"\"Calculate the verifying digit for the CNPJ.\n\n :param cnpj: List of integers with the CNPJ.\n :param peso: Integer with the weight for the modulo 11 calculate.\n :returns: The verifying digit for the CNPJ.\n \"\"\"",
"soma",
"=",
"0",
"if",
"peso",
"==",
"5",
":",
"peso_list",
"=",
"[",
"5",
",",
"4",
",",
"3",
",",
"2",
",",
"9",
",",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
"]",
"elif",
"peso",
"==",
"6",
":",
"peso_list",
"=",
"[",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
",",
"9",
",",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3",
",",
"2",
"]",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"cnpj",
")",
":",
"soma",
"+=",
"peso_list",
"[",
"i",
"]",
"*",
"cnpj",
"[",
"i",
"]",
"resto",
"=",
"soma",
"%",
"11",
"if",
"resto",
"<",
"2",
":",
"return",
"0",
"return",
"11",
"-",
"resto",
"cnpj_without_dv",
"=",
"[",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
"for",
"_",
"in",
"range",
"(",
"12",
")",
"]",
"first_dv",
"=",
"get_verifying_digit_cnpj",
"(",
"cnpj_without_dv",
",",
"5",
")",
"cnpj_without_dv",
".",
"append",
"(",
"first_dv",
")",
"second_dv",
"=",
"get_verifying_digit_cnpj",
"(",
"cnpj_without_dv",
",",
"6",
")",
"cnpj_without_dv",
".",
"append",
"(",
"second_dv",
")",
"cnpj",
"=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"cnpj_without_dv",
"]",
")",
"if",
"with_mask",
":",
"return",
"'{}.{}.{}/{}-{}'",
".",
"format",
"(",
"cnpj",
"[",
":",
"2",
"]",
",",
"cnpj",
"[",
"2",
":",
"5",
"]",
",",
"cnpj",
"[",
"5",
":",
"8",
"]",
",",
"cnpj",
"[",
"8",
":",
"12",
"]",
",",
"cnpj",
"[",
"12",
":",
"]",
")",
"return",
"cnpj"
] | Get a random CNPJ.
:param with_mask: Use cnpj mask (###.###.###-##)
:returns: Random cnpj.
:Example:
77.732.230/0001-70 | [
"Get",
"a",
"random",
"CNPJ",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/pt_br.py#L60-L101 |
227,978 | lk-geimfari/mimesis | mimesis/decorators.py | romanized | def romanized(locale: str = '') -> Callable:
"""Romanize the Cyrillic text.
Transliterate the Cyrillic language from the Cyrillic
script into the Latin alphabet.
.. note:: At this moment it works only for `ru`, `uk`, `kk`.
:param locale: Locale code.
:return: Latinized text.
"""
def romanized_deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
# String can contain ascii symbols, digits and
# punctuation symbols.
alphabet = {s: s for s in
letters + digits + punctuation}
alphabet.update(data.ROMANIZATION_DICT[locale])
# Add common cyrillic letters
alphabet.update(data.COMMON_LETTERS)
except KeyError:
raise UnsupportedLocale(locale)
result = func(*args, **kwargs)
txt = ''.join([alphabet[i] for i in result if i in alphabet])
return txt
return wrapper
return romanized_deco | python | def romanized(locale: str = '') -> Callable:
"""Romanize the Cyrillic text.
Transliterate the Cyrillic language from the Cyrillic
script into the Latin alphabet.
.. note:: At this moment it works only for `ru`, `uk`, `kk`.
:param locale: Locale code.
:return: Latinized text.
"""
def romanized_deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
# String can contain ascii symbols, digits and
# punctuation symbols.
alphabet = {s: s for s in
letters + digits + punctuation}
alphabet.update(data.ROMANIZATION_DICT[locale])
# Add common cyrillic letters
alphabet.update(data.COMMON_LETTERS)
except KeyError:
raise UnsupportedLocale(locale)
result = func(*args, **kwargs)
txt = ''.join([alphabet[i] for i in result if i in alphabet])
return txt
return wrapper
return romanized_deco | [
"def",
"romanized",
"(",
"locale",
":",
"str",
"=",
"''",
")",
"->",
"Callable",
":",
"def",
"romanized_deco",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# String can contain ascii symbols, digits and",
"# punctuation symbols.",
"alphabet",
"=",
"{",
"s",
":",
"s",
"for",
"s",
"in",
"letters",
"+",
"digits",
"+",
"punctuation",
"}",
"alphabet",
".",
"update",
"(",
"data",
".",
"ROMANIZATION_DICT",
"[",
"locale",
"]",
")",
"# Add common cyrillic letters",
"alphabet",
".",
"update",
"(",
"data",
".",
"COMMON_LETTERS",
")",
"except",
"KeyError",
":",
"raise",
"UnsupportedLocale",
"(",
"locale",
")",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"txt",
"=",
"''",
".",
"join",
"(",
"[",
"alphabet",
"[",
"i",
"]",
"for",
"i",
"in",
"result",
"if",
"i",
"in",
"alphabet",
"]",
")",
"return",
"txt",
"return",
"wrapper",
"return",
"romanized_deco"
] | Romanize the Cyrillic text.
Transliterate the Cyrillic language from the Cyrillic
script into the Latin alphabet.
.. note:: At this moment it works only for `ru`, `uk`, `kk`.
:param locale: Locale code.
:return: Latinized text. | [
"Romanize",
"the",
"Cyrillic",
"text",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/decorators.py#L14-L44 |
227,979 | lk-geimfari/mimesis | mimesis/providers/food.py | Food._choice_from | def _choice_from(self, key: str) -> str:
"""Choice random element."""
data = self._data[key]
return self.random.choice(data) | python | def _choice_from(self, key: str) -> str:
"""Choice random element."""
data = self._data[key]
return self.random.choice(data) | [
"def",
"_choice_from",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"str",
":",
"data",
"=",
"self",
".",
"_data",
"[",
"key",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"data",
")"
] | Choice random element. | [
"Choice",
"random",
"element",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/food.py#L27-L30 |
227,980 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.generate_sentence | def generate_sentence(self) -> str:
"""Generate sentence from the parts.
:return: Sentence.
"""
sentences = self._data['sentence']
sentence = [
self.random.choice(sentences[k]) for k
in ('head', 'p1', 'p2', 'tail')
]
return '{0} {1} {2} {3}'.format(*sentence) | python | def generate_sentence(self) -> str:
"""Generate sentence from the parts.
:return: Sentence.
"""
sentences = self._data['sentence']
sentence = [
self.random.choice(sentences[k]) for k
in ('head', 'p1', 'p2', 'tail')
]
return '{0} {1} {2} {3}'.format(*sentence) | [
"def",
"generate_sentence",
"(",
"self",
")",
"->",
"str",
":",
"sentences",
"=",
"self",
".",
"_data",
"[",
"'sentence'",
"]",
"sentence",
"=",
"[",
"self",
".",
"random",
".",
"choice",
"(",
"sentences",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"(",
"'head'",
",",
"'p1'",
",",
"'p2'",
",",
"'tail'",
")",
"]",
"return",
"'{0} {1} {2} {3}'",
".",
"format",
"(",
"*",
"sentence",
")"
] | Generate sentence from the parts.
:return: Sentence. | [
"Generate",
"sentence",
"from",
"the",
"parts",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L25-L35 |
227,981 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.patronymic | def patronymic(self, gender: Gender = None) -> str:
"""Generate random patronymic name.
:param gender: Gender of person.
:return: Patronymic name.
:Example:
Алексеевна.
"""
gender = self._validate_enum(gender, Gender)
patronymics = self._data['patronymic'][gender]
return self.random.choice(patronymics) | python | def patronymic(self, gender: Gender = None) -> str:
"""Generate random patronymic name.
:param gender: Gender of person.
:return: Patronymic name.
:Example:
Алексеевна.
"""
gender = self._validate_enum(gender, Gender)
patronymics = self._data['patronymic'][gender]
return self.random.choice(patronymics) | [
"def",
"patronymic",
"(",
"self",
",",
"gender",
":",
"Gender",
"=",
"None",
")",
"->",
"str",
":",
"gender",
"=",
"self",
".",
"_validate_enum",
"(",
"gender",
",",
"Gender",
")",
"patronymics",
"=",
"self",
".",
"_data",
"[",
"'patronymic'",
"]",
"[",
"gender",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"patronymics",
")"
] | Generate random patronymic name.
:param gender: Gender of person.
:return: Patronymic name.
:Example:
Алексеевна. | [
"Generate",
"random",
"patronymic",
"name",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L37-L48 |
227,982 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.passport_series | def passport_series(self, year: int = None) -> str:
"""Generate random series of passport.
:param year: Year of manufacture.
:type year: int or None
:return: Series.
:Example:
02 15.
"""
if not year:
year = self.random.randint(10, 18)
region = self.random.randint(1, 99)
return '{:02d} {}'.format(region, year) | python | def passport_series(self, year: int = None) -> str:
"""Generate random series of passport.
:param year: Year of manufacture.
:type year: int or None
:return: Series.
:Example:
02 15.
"""
if not year:
year = self.random.randint(10, 18)
region = self.random.randint(1, 99)
return '{:02d} {}'.format(region, year) | [
"def",
"passport_series",
"(",
"self",
",",
"year",
":",
"int",
"=",
"None",
")",
"->",
"str",
":",
"if",
"not",
"year",
":",
"year",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"10",
",",
"18",
")",
"region",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"99",
")",
"return",
"'{:02d} {}'",
".",
"format",
"(",
"region",
",",
"year",
")"
] | Generate random series of passport.
:param year: Year of manufacture.
:type year: int or None
:return: Series.
:Example:
02 15. | [
"Generate",
"random",
"series",
"of",
"passport",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L50-L64 |
227,983 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.snils | def snils(self) -> str:
"""Generate snils with special algorithm.
:return: SNILS.
:Example:
41917492600.
"""
numbers = []
control_codes = []
for i in range(0, 9):
numbers.append(self.random.randint(0, 9))
for i in range(9, 0, -1):
control_codes.append(numbers[9 - i] * i)
control_code = sum(control_codes)
code = ''.join(str(number) for number in numbers)
if control_code in (100, 101):
snils = code + '00'
return snils
if control_code < 100:
snils = code + str(control_code)
return snils
if control_code > 101:
control_code = control_code % 101
if control_code == 100:
control_code = 0
snils = code + '{:02}'.format(control_code)
return snils | python | def snils(self) -> str:
"""Generate snils with special algorithm.
:return: SNILS.
:Example:
41917492600.
"""
numbers = []
control_codes = []
for i in range(0, 9):
numbers.append(self.random.randint(0, 9))
for i in range(9, 0, -1):
control_codes.append(numbers[9 - i] * i)
control_code = sum(control_codes)
code = ''.join(str(number) for number in numbers)
if control_code in (100, 101):
snils = code + '00'
return snils
if control_code < 100:
snils = code + str(control_code)
return snils
if control_code > 101:
control_code = control_code % 101
if control_code == 100:
control_code = 0
snils = code + '{:02}'.format(control_code)
return snils | [
"def",
"snils",
"(",
"self",
")",
"->",
"str",
":",
"numbers",
"=",
"[",
"]",
"control_codes",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"9",
")",
":",
"numbers",
".",
"append",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
")",
"for",
"i",
"in",
"range",
"(",
"9",
",",
"0",
",",
"-",
"1",
")",
":",
"control_codes",
".",
"append",
"(",
"numbers",
"[",
"9",
"-",
"i",
"]",
"*",
"i",
")",
"control_code",
"=",
"sum",
"(",
"control_codes",
")",
"code",
"=",
"''",
".",
"join",
"(",
"str",
"(",
"number",
")",
"for",
"number",
"in",
"numbers",
")",
"if",
"control_code",
"in",
"(",
"100",
",",
"101",
")",
":",
"snils",
"=",
"code",
"+",
"'00'",
"return",
"snils",
"if",
"control_code",
"<",
"100",
":",
"snils",
"=",
"code",
"+",
"str",
"(",
"control_code",
")",
"return",
"snils",
"if",
"control_code",
">",
"101",
":",
"control_code",
"=",
"control_code",
"%",
"101",
"if",
"control_code",
"==",
"100",
":",
"control_code",
"=",
"0",
"snils",
"=",
"code",
"+",
"'{:02}'",
".",
"format",
"(",
"control_code",
")",
"return",
"snils"
] | Generate snils with special algorithm.
:return: SNILS.
:Example:
41917492600. | [
"Generate",
"snils",
"with",
"special",
"algorithm",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L90-L123 |
227,984 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.inn | def inn(self) -> str:
"""Generate random, but valid ``INN``.
:return: INN.
"""
def control_sum(nums: list, t: str) -> int:
digits = {
'n2': [7, 2, 4, 10, 3, 5, 9, 4, 6, 8],
'n1': [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8],
}
number = 0
length = digits[t]
for i in range(0, len(length)):
number += nums[i] * length[i]
return number % 11 % 10
numbers = []
for x in range(0, 10):
numbers.append(self.random.randint(1 if x == 0 else 0, 9))
n2 = control_sum(numbers, 'n2')
numbers.append(n2)
n1 = control_sum(numbers, 'n1')
numbers.append(n1)
return ''.join([str(x) for x in numbers]) | python | def inn(self) -> str:
"""Generate random, but valid ``INN``.
:return: INN.
"""
def control_sum(nums: list, t: str) -> int:
digits = {
'n2': [7, 2, 4, 10, 3, 5, 9, 4, 6, 8],
'n1': [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8],
}
number = 0
length = digits[t]
for i in range(0, len(length)):
number += nums[i] * length[i]
return number % 11 % 10
numbers = []
for x in range(0, 10):
numbers.append(self.random.randint(1 if x == 0 else 0, 9))
n2 = control_sum(numbers, 'n2')
numbers.append(n2)
n1 = control_sum(numbers, 'n1')
numbers.append(n1)
return ''.join([str(x) for x in numbers]) | [
"def",
"inn",
"(",
"self",
")",
"->",
"str",
":",
"def",
"control_sum",
"(",
"nums",
":",
"list",
",",
"t",
":",
"str",
")",
"->",
"int",
":",
"digits",
"=",
"{",
"'n2'",
":",
"[",
"7",
",",
"2",
",",
"4",
",",
"10",
",",
"3",
",",
"5",
",",
"9",
",",
"4",
",",
"6",
",",
"8",
"]",
",",
"'n1'",
":",
"[",
"3",
",",
"7",
",",
"2",
",",
"4",
",",
"10",
",",
"3",
",",
"5",
",",
"9",
",",
"4",
",",
"6",
",",
"8",
"]",
",",
"}",
"number",
"=",
"0",
"length",
"=",
"digits",
"[",
"t",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"length",
")",
")",
":",
"number",
"+=",
"nums",
"[",
"i",
"]",
"*",
"length",
"[",
"i",
"]",
"return",
"number",
"%",
"11",
"%",
"10",
"numbers",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"10",
")",
":",
"numbers",
".",
"append",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"1",
"if",
"x",
"==",
"0",
"else",
"0",
",",
"9",
")",
")",
"n2",
"=",
"control_sum",
"(",
"numbers",
",",
"'n2'",
")",
"numbers",
".",
"append",
"(",
"n2",
")",
"n1",
"=",
"control_sum",
"(",
"numbers",
",",
"'n1'",
")",
"numbers",
".",
"append",
"(",
"n1",
")",
"return",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"numbers",
"]",
")"
] | Generate random, but valid ``INN``.
:return: INN. | [
"Generate",
"random",
"but",
"valid",
"INN",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L125-L149 |
227,985 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.ogrn | def ogrn(self) -> str:
"""Generate random valid ``OGRN``.
:return: OGRN.
:Example:
4715113303725.
"""
numbers = []
for _ in range(0, 12):
numbers.append(self.random.randint(1 if _ == 0 else 0, 9))
ogrn = ''.join([str(x) for x in numbers])
check_sum = str(int(ogrn) % 11 % 10)
return '{}{}'.format(ogrn, check_sum) | python | def ogrn(self) -> str:
"""Generate random valid ``OGRN``.
:return: OGRN.
:Example:
4715113303725.
"""
numbers = []
for _ in range(0, 12):
numbers.append(self.random.randint(1 if _ == 0 else 0, 9))
ogrn = ''.join([str(x) for x in numbers])
check_sum = str(int(ogrn) % 11 % 10)
return '{}{}'.format(ogrn, check_sum) | [
"def",
"ogrn",
"(",
"self",
")",
"->",
"str",
":",
"numbers",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"12",
")",
":",
"numbers",
".",
"append",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"1",
"if",
"_",
"==",
"0",
"else",
"0",
",",
"9",
")",
")",
"ogrn",
"=",
"''",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"numbers",
"]",
")",
"check_sum",
"=",
"str",
"(",
"int",
"(",
"ogrn",
")",
"%",
"11",
"%",
"10",
")",
"return",
"'{}{}'",
".",
"format",
"(",
"ogrn",
",",
"check_sum",
")"
] | Generate random valid ``OGRN``.
:return: OGRN.
:Example:
4715113303725. | [
"Generate",
"random",
"valid",
"OGRN",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L151-L166 |
227,986 | lk-geimfari/mimesis | mimesis/builtins/ru.py | RussiaSpecProvider.kpp | def kpp(self) -> str:
"""Generate random ``KPP``.
:return: 'KPP'.
:Example:
560058652.
"""
tax_codes = [
'7700', '7800', '5000', '0100',
'0200', '0300', '0500', '0600',
'0700', '0800', '0900', '1000',
'1100', '1200', '1300', '1400',
'1500', '1600', '1700', '1800',
'1900', '2000', '2100', '2200',
'2300', '2400', '2500', '2600',
'2700', '2800', '2900', '3000',
'3100', '3200', '3300', '3400',
'3500', '3600', '3700', '3800',
'3900', '4000', '4100', '4900',
'5100', '5200', '5300', '5400',
'5500', '5600', '5700', '5800',
'5900', '6000', '6100', '6200',
'6300', '6400', '6500', '6600',
'6700', '6800', '6900', '7000',
'7100', '7200', '7300', '7400',
'7500', '7600', '7900', '8600',
'8700', '8900', '9100', '9200',
'9800', '9900', '9901', '9951',
'9952', '9953', '9954', '9955',
'9956', '9957', '9958', '9959',
'9961', '9962', '9965', '9966',
'9971', '9972', '9973', '9974',
'9975', '9976', '9977', '9979',
'9998',
]
tax_code = tax_codes[self.random.randint(0, len(tax_codes) - 1)]
reg_code = '{:02}'.format(self.random.randint(1, 99))
reg_number = '{:03}'.format(self.random.randint(1, 999))
kpp = tax_code + reg_code + reg_number
return kpp | python | def kpp(self) -> str:
"""Generate random ``KPP``.
:return: 'KPP'.
:Example:
560058652.
"""
tax_codes = [
'7700', '7800', '5000', '0100',
'0200', '0300', '0500', '0600',
'0700', '0800', '0900', '1000',
'1100', '1200', '1300', '1400',
'1500', '1600', '1700', '1800',
'1900', '2000', '2100', '2200',
'2300', '2400', '2500', '2600',
'2700', '2800', '2900', '3000',
'3100', '3200', '3300', '3400',
'3500', '3600', '3700', '3800',
'3900', '4000', '4100', '4900',
'5100', '5200', '5300', '5400',
'5500', '5600', '5700', '5800',
'5900', '6000', '6100', '6200',
'6300', '6400', '6500', '6600',
'6700', '6800', '6900', '7000',
'7100', '7200', '7300', '7400',
'7500', '7600', '7900', '8600',
'8700', '8900', '9100', '9200',
'9800', '9900', '9901', '9951',
'9952', '9953', '9954', '9955',
'9956', '9957', '9958', '9959',
'9961', '9962', '9965', '9966',
'9971', '9972', '9973', '9974',
'9975', '9976', '9977', '9979',
'9998',
]
tax_code = tax_codes[self.random.randint(0, len(tax_codes) - 1)]
reg_code = '{:02}'.format(self.random.randint(1, 99))
reg_number = '{:03}'.format(self.random.randint(1, 999))
kpp = tax_code + reg_code + reg_number
return kpp | [
"def",
"kpp",
"(",
"self",
")",
"->",
"str",
":",
"tax_codes",
"=",
"[",
"'7700'",
",",
"'7800'",
",",
"'5000'",
",",
"'0100'",
",",
"'0200'",
",",
"'0300'",
",",
"'0500'",
",",
"'0600'",
",",
"'0700'",
",",
"'0800'",
",",
"'0900'",
",",
"'1000'",
",",
"'1100'",
",",
"'1200'",
",",
"'1300'",
",",
"'1400'",
",",
"'1500'",
",",
"'1600'",
",",
"'1700'",
",",
"'1800'",
",",
"'1900'",
",",
"'2000'",
",",
"'2100'",
",",
"'2200'",
",",
"'2300'",
",",
"'2400'",
",",
"'2500'",
",",
"'2600'",
",",
"'2700'",
",",
"'2800'",
",",
"'2900'",
",",
"'3000'",
",",
"'3100'",
",",
"'3200'",
",",
"'3300'",
",",
"'3400'",
",",
"'3500'",
",",
"'3600'",
",",
"'3700'",
",",
"'3800'",
",",
"'3900'",
",",
"'4000'",
",",
"'4100'",
",",
"'4900'",
",",
"'5100'",
",",
"'5200'",
",",
"'5300'",
",",
"'5400'",
",",
"'5500'",
",",
"'5600'",
",",
"'5700'",
",",
"'5800'",
",",
"'5900'",
",",
"'6000'",
",",
"'6100'",
",",
"'6200'",
",",
"'6300'",
",",
"'6400'",
",",
"'6500'",
",",
"'6600'",
",",
"'6700'",
",",
"'6800'",
",",
"'6900'",
",",
"'7000'",
",",
"'7100'",
",",
"'7200'",
",",
"'7300'",
",",
"'7400'",
",",
"'7500'",
",",
"'7600'",
",",
"'7900'",
",",
"'8600'",
",",
"'8700'",
",",
"'8900'",
",",
"'9100'",
",",
"'9200'",
",",
"'9800'",
",",
"'9900'",
",",
"'9901'",
",",
"'9951'",
",",
"'9952'",
",",
"'9953'",
",",
"'9954'",
",",
"'9955'",
",",
"'9956'",
",",
"'9957'",
",",
"'9958'",
",",
"'9959'",
",",
"'9961'",
",",
"'9962'",
",",
"'9965'",
",",
"'9966'",
",",
"'9971'",
",",
"'9972'",
",",
"'9973'",
",",
"'9974'",
",",
"'9975'",
",",
"'9976'",
",",
"'9977'",
",",
"'9979'",
",",
"'9998'",
",",
"]",
"tax_code",
"=",
"tax_codes",
"[",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"tax_codes",
")",
"-",
"1",
")",
"]",
"reg_code",
"=",
"'{:02}'",
".",
"format",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"99",
")",
")",
"reg_number",
"=",
"'{:03}'",
".",
"format",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"1",
",",
"999",
")",
")",
"kpp",
"=",
"tax_code",
"+",
"reg_code",
"+",
"reg_number",
"return",
"kpp"
] | Generate random ``KPP``.
:return: 'KPP'.
:Example:
560058652. | [
"Generate",
"random",
"KPP",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/builtins/ru.py#L183-L224 |
227,987 | lk-geimfari/mimesis | mimesis/providers/hardware.py | Hardware.cpu_frequency | def cpu_frequency(self) -> str:
"""Get a random frequency of CPU.
:return: Frequency of CPU.
:Example:
4.0 GHz.
"""
return '{}GHz'.format(
self.random.uniform(
a=1.5,
b=4.3,
precision=1,
),
) | python | def cpu_frequency(self) -> str:
"""Get a random frequency of CPU.
:return: Frequency of CPU.
:Example:
4.0 GHz.
"""
return '{}GHz'.format(
self.random.uniform(
a=1.5,
b=4.3,
precision=1,
),
) | [
"def",
"cpu_frequency",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'{}GHz'",
".",
"format",
"(",
"self",
".",
"random",
".",
"uniform",
"(",
"a",
"=",
"1.5",
",",
"b",
"=",
"4.3",
",",
"precision",
"=",
"1",
",",
")",
",",
")"
] | Get a random frequency of CPU.
:return: Frequency of CPU.
:Example:
4.0 GHz. | [
"Get",
"a",
"random",
"frequency",
"of",
"CPU",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/hardware.py#L62-L76 |
227,988 | lk-geimfari/mimesis | mimesis/providers/numbers.py | Numbers.floats | def floats(self, n: int = 2) -> List[float]:
"""Generate a list of random float numbers.
:param n: Raise 10 to the 'n' power.
:return: The list of floating-point numbers.
"""
nums = [self.random.random()
for _ in range(10 ** int(n))]
return nums | python | def floats(self, n: int = 2) -> List[float]:
"""Generate a list of random float numbers.
:param n: Raise 10 to the 'n' power.
:return: The list of floating-point numbers.
"""
nums = [self.random.random()
for _ in range(10 ** int(n))]
return nums | [
"def",
"floats",
"(",
"self",
",",
"n",
":",
"int",
"=",
"2",
")",
"->",
"List",
"[",
"float",
"]",
":",
"nums",
"=",
"[",
"self",
".",
"random",
".",
"random",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"10",
"**",
"int",
"(",
"n",
")",
")",
"]",
"return",
"nums"
] | Generate a list of random float numbers.
:param n: Raise 10 to the 'n' power.
:return: The list of floating-point numbers. | [
"Generate",
"a",
"list",
"of",
"random",
"float",
"numbers",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/numbers.py#L20-L28 |
227,989 | lk-geimfari/mimesis | mimesis/providers/numbers.py | Numbers.integers | def integers(self, start: int = 0, end: int = 10,
length: int = 10) -> List[int]:
"""Generate a list of random integers.
Integers can be negative or positive numbers.
.. note: You can use both positive and negative numbers.
:param start: Start.
:param end: End.
:param length: Length of list.
:return: List of integers.
:Example:
[-20, -19, -18, -17]
"""
return self.random.randints(
length, start, end) | python | def integers(self, start: int = 0, end: int = 10,
length: int = 10) -> List[int]:
"""Generate a list of random integers.
Integers can be negative or positive numbers.
.. note: You can use both positive and negative numbers.
:param start: Start.
:param end: End.
:param length: Length of list.
:return: List of integers.
:Example:
[-20, -19, -18, -17]
"""
return self.random.randints(
length, start, end) | [
"def",
"integers",
"(",
"self",
",",
"start",
":",
"int",
"=",
"0",
",",
"end",
":",
"int",
"=",
"10",
",",
"length",
":",
"int",
"=",
"10",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"self",
".",
"random",
".",
"randints",
"(",
"length",
",",
"start",
",",
"end",
")"
] | Generate a list of random integers.
Integers can be negative or positive numbers.
.. note: You can use both positive and negative numbers.
:param start: Start.
:param end: End.
:param length: Length of list.
:return: List of integers.
:Example:
[-20, -19, -18, -17] | [
"Generate",
"a",
"list",
"of",
"random",
"integers",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/numbers.py#L30-L46 |
227,990 | lk-geimfari/mimesis | mimesis/providers/numbers.py | Numbers.primes | def primes(start: int = 1, end: int = 999) -> List[int]:
"""Generate a list of prime numbers.
:param start: First value of range.
:param end: Last value of range.
:return: A list of prime numbers from start to end.
"""
# TODO: It should generate random primes with passed length.
sieve_size = (end // 2 - 1) if end % 2 == 0 else (end // 2)
sieve = [True] * sieve_size
primes = [] # list of primes
# add 2 to the list if it's in the given range
if end >= 2:
primes.append(2)
for i in range(sieve_size):
if sieve[i]:
value_at_i = i * 2 + 3
primes.append(value_at_i)
for j in range(i, sieve_size, value_at_i):
sieve[j] = False
chop_index = 0
for i in range(len(primes)):
if primes[i] >= start:
chop_index = i
break
return primes[chop_index:] | python | def primes(start: int = 1, end: int = 999) -> List[int]:
"""Generate a list of prime numbers.
:param start: First value of range.
:param end: Last value of range.
:return: A list of prime numbers from start to end.
"""
# TODO: It should generate random primes with passed length.
sieve_size = (end // 2 - 1) if end % 2 == 0 else (end // 2)
sieve = [True] * sieve_size
primes = [] # list of primes
# add 2 to the list if it's in the given range
if end >= 2:
primes.append(2)
for i in range(sieve_size):
if sieve[i]:
value_at_i = i * 2 + 3
primes.append(value_at_i)
for j in range(i, sieve_size, value_at_i):
sieve[j] = False
chop_index = 0
for i in range(len(primes)):
if primes[i] >= start:
chop_index = i
break
return primes[chop_index:] | [
"def",
"primes",
"(",
"start",
":",
"int",
"=",
"1",
",",
"end",
":",
"int",
"=",
"999",
")",
"->",
"List",
"[",
"int",
"]",
":",
"# TODO: It should generate random primes with passed length.",
"sieve_size",
"=",
"(",
"end",
"//",
"2",
"-",
"1",
")",
"if",
"end",
"%",
"2",
"==",
"0",
"else",
"(",
"end",
"//",
"2",
")",
"sieve",
"=",
"[",
"True",
"]",
"*",
"sieve_size",
"primes",
"=",
"[",
"]",
"# list of primes",
"# add 2 to the list if it's in the given range",
"if",
"end",
">=",
"2",
":",
"primes",
".",
"append",
"(",
"2",
")",
"for",
"i",
"in",
"range",
"(",
"sieve_size",
")",
":",
"if",
"sieve",
"[",
"i",
"]",
":",
"value_at_i",
"=",
"i",
"*",
"2",
"+",
"3",
"primes",
".",
"append",
"(",
"value_at_i",
")",
"for",
"j",
"in",
"range",
"(",
"i",
",",
"sieve_size",
",",
"value_at_i",
")",
":",
"sieve",
"[",
"j",
"]",
"=",
"False",
"chop_index",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"primes",
")",
")",
":",
"if",
"primes",
"[",
"i",
"]",
">=",
"start",
":",
"chop_index",
"=",
"i",
"break",
"return",
"primes",
"[",
"chop_index",
":",
"]"
] | Generate a list of prime numbers.
:param start: First value of range.
:param end: Last value of range.
:return: A list of prime numbers from start to end. | [
"Generate",
"a",
"list",
"of",
"prime",
"numbers",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/numbers.py#L49-L76 |
227,991 | lk-geimfari/mimesis | mimesis/providers/numbers.py | Numbers.digit | def digit(self, to_bin: bool = False) -> Union[str, int]:
"""Get a random digit.
:param to_bin: If True then convert to binary.
:return: Digit.
:Example:
4.
"""
digit = self.random.randint(0, 9)
if to_bin:
return bin(digit)
return digit | python | def digit(self, to_bin: bool = False) -> Union[str, int]:
"""Get a random digit.
:param to_bin: If True then convert to binary.
:return: Digit.
:Example:
4.
"""
digit = self.random.randint(0, 9)
if to_bin:
return bin(digit)
return digit | [
"def",
"digit",
"(",
"self",
",",
"to_bin",
":",
"bool",
"=",
"False",
")",
"->",
"Union",
"[",
"str",
",",
"int",
"]",
":",
"digit",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"0",
",",
"9",
")",
"if",
"to_bin",
":",
"return",
"bin",
"(",
"digit",
")",
"return",
"digit"
] | Get a random digit.
:param to_bin: If True then convert to binary.
:return: Digit.
:Example:
4. | [
"Get",
"a",
"random",
"digit",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/numbers.py#L78-L92 |
227,992 | lk-geimfari/mimesis | mimesis/providers/numbers.py | Numbers.between | def between(self, minimum: int = 1, maximum: int = 1000) -> int:
"""Generate a random number between minimum and maximum.
:param minimum: Minimum of range.
:param maximum: Maximum of range.
:return: Number.
"""
return self.random.randint(minimum, maximum) | python | def between(self, minimum: int = 1, maximum: int = 1000) -> int:
"""Generate a random number between minimum and maximum.
:param minimum: Minimum of range.
:param maximum: Maximum of range.
:return: Number.
"""
return self.random.randint(minimum, maximum) | [
"def",
"between",
"(",
"self",
",",
"minimum",
":",
"int",
"=",
"1",
",",
"maximum",
":",
"int",
"=",
"1000",
")",
"->",
"int",
":",
"return",
"self",
".",
"random",
".",
"randint",
"(",
"minimum",
",",
"maximum",
")"
] | Generate a random number between minimum and maximum.
:param minimum: Minimum of range.
:param maximum: Maximum of range.
:return: Number. | [
"Generate",
"a",
"random",
"number",
"between",
"minimum",
"and",
"maximum",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/numbers.py#L94-L101 |
227,993 | lk-geimfari/mimesis | mimesis/providers/person.py | Person.age | def age(self, minimum: int = 16, maximum: int = 66) -> int:
"""Get a random integer value.
:param maximum: Maximum value of age.
:param minimum: Minimum value of age.
:return: Random integer.
:Example:
23.
"""
age = self.random.randint(minimum, maximum)
self._store['age'] = age
return age | python | def age(self, minimum: int = 16, maximum: int = 66) -> int:
"""Get a random integer value.
:param maximum: Maximum value of age.
:param minimum: Minimum value of age.
:return: Random integer.
:Example:
23.
"""
age = self.random.randint(minimum, maximum)
self._store['age'] = age
return age | [
"def",
"age",
"(",
"self",
",",
"minimum",
":",
"int",
"=",
"16",
",",
"maximum",
":",
"int",
"=",
"66",
")",
"->",
"int",
":",
"age",
"=",
"self",
".",
"random",
".",
"randint",
"(",
"minimum",
",",
"maximum",
")",
"self",
".",
"_store",
"[",
"'age'",
"]",
"=",
"age",
"return",
"age"
] | Get a random integer value.
:param maximum: Maximum value of age.
:param minimum: Minimum value of age.
:return: Random integer.
:Example:
23. | [
"Get",
"a",
"random",
"integer",
"value",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/person.py#L48-L60 |
227,994 | lk-geimfari/mimesis | mimesis/providers/person.py | Person.work_experience | def work_experience(self, working_start_age: int = 22) -> int:
"""Get a work experience.
:param working_start_age: Age then person start to work.
:return: Depend on previous generated age.
"""
age = self._store['age']
if age == 0:
age = self.age()
return max(age - working_start_age, 0) | python | def work_experience(self, working_start_age: int = 22) -> int:
"""Get a work experience.
:param working_start_age: Age then person start to work.
:return: Depend on previous generated age.
"""
age = self._store['age']
if age == 0:
age = self.age()
return max(age - working_start_age, 0) | [
"def",
"work_experience",
"(",
"self",
",",
"working_start_age",
":",
"int",
"=",
"22",
")",
"->",
"int",
":",
"age",
"=",
"self",
".",
"_store",
"[",
"'age'",
"]",
"if",
"age",
"==",
"0",
":",
"age",
"=",
"self",
".",
"age",
"(",
")",
"return",
"max",
"(",
"age",
"-",
"working_start_age",
",",
"0",
")"
] | Get a work experience.
:param working_start_age: Age then person start to work.
:return: Depend on previous generated age. | [
"Get",
"a",
"work",
"experience",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/person.py#L62-L72 |
227,995 | lk-geimfari/mimesis | mimesis/providers/person.py | Person.name | def name(self, gender: Optional[Gender] = None) -> str:
"""Generate a random name.
:param gender: Gender's enum object.
:return: Name.
:Example:
John.
"""
key = self._validate_enum(gender, Gender)
names = self._data['names'].get(key)
return self.random.choice(names) | python | def name(self, gender: Optional[Gender] = None) -> str:
"""Generate a random name.
:param gender: Gender's enum object.
:return: Name.
:Example:
John.
"""
key = self._validate_enum(gender, Gender)
names = self._data['names'].get(key)
return self.random.choice(names) | [
"def",
"name",
"(",
"self",
",",
"gender",
":",
"Optional",
"[",
"Gender",
"]",
"=",
"None",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"gender",
",",
"Gender",
")",
"names",
"=",
"self",
".",
"_data",
"[",
"'names'",
"]",
".",
"get",
"(",
"key",
")",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"names",
")"
] | Generate a random name.
:param gender: Gender's enum object.
:return: Name.
:Example:
John. | [
"Generate",
"a",
"random",
"name",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/person.py#L74-L85 |
227,996 | lk-geimfari/mimesis | mimesis/providers/person.py | Person.surname | def surname(self, gender: Optional[Gender] = None) -> str:
"""Generate a random surname.
:param gender: Gender's enum object.
:return: Surname.
:Example:
Smith.
"""
surnames = self._data['surnames']
# Surnames separated by gender.
if isinstance(surnames, dict):
key = self._validate_enum(gender, Gender)
surnames = surnames[key]
return self.random.choice(surnames) | python | def surname(self, gender: Optional[Gender] = None) -> str:
"""Generate a random surname.
:param gender: Gender's enum object.
:return: Surname.
:Example:
Smith.
"""
surnames = self._data['surnames']
# Surnames separated by gender.
if isinstance(surnames, dict):
key = self._validate_enum(gender, Gender)
surnames = surnames[key]
return self.random.choice(surnames) | [
"def",
"surname",
"(",
"self",
",",
"gender",
":",
"Optional",
"[",
"Gender",
"]",
"=",
"None",
")",
"->",
"str",
":",
"surnames",
"=",
"self",
".",
"_data",
"[",
"'surnames'",
"]",
"# Surnames separated by gender.",
"if",
"isinstance",
"(",
"surnames",
",",
"dict",
")",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"gender",
",",
"Gender",
")",
"surnames",
"=",
"surnames",
"[",
"key",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"surnames",
")"
] | Generate a random surname.
:param gender: Gender's enum object.
:return: Surname.
:Example:
Smith. | [
"Generate",
"a",
"random",
"surname",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/person.py#L87-L103 |
227,997 | lk-geimfari/mimesis | mimesis/providers/person.py | Person.title | def title(self, gender: Optional[Gender] = None,
title_type: Optional[TitleType] = None) -> str:
"""Generate a random title for name.
You can generate random prefix or suffix
for name using this method.
:param gender: The gender.
:param title_type: TitleType enum object.
:return: The title.
:raises NonEnumerableError: if gender or title_type in incorrect format.
:Example:
PhD.
"""
gender_key = self._validate_enum(gender, Gender)
title_key = self._validate_enum(title_type, TitleType)
titles = self._data['title'][gender_key][title_key]
return self.random.choice(titles) | python | def title(self, gender: Optional[Gender] = None,
title_type: Optional[TitleType] = None) -> str:
"""Generate a random title for name.
You can generate random prefix or suffix
for name using this method.
:param gender: The gender.
:param title_type: TitleType enum object.
:return: The title.
:raises NonEnumerableError: if gender or title_type in incorrect format.
:Example:
PhD.
"""
gender_key = self._validate_enum(gender, Gender)
title_key = self._validate_enum(title_type, TitleType)
titles = self._data['title'][gender_key][title_key]
return self.random.choice(titles) | [
"def",
"title",
"(",
"self",
",",
"gender",
":",
"Optional",
"[",
"Gender",
"]",
"=",
"None",
",",
"title_type",
":",
"Optional",
"[",
"TitleType",
"]",
"=",
"None",
")",
"->",
"str",
":",
"gender_key",
"=",
"self",
".",
"_validate_enum",
"(",
"gender",
",",
"Gender",
")",
"title_key",
"=",
"self",
".",
"_validate_enum",
"(",
"title_type",
",",
"TitleType",
")",
"titles",
"=",
"self",
".",
"_data",
"[",
"'title'",
"]",
"[",
"gender_key",
"]",
"[",
"title_key",
"]",
"return",
"self",
".",
"random",
".",
"choice",
"(",
"titles",
")"
] | Generate a random title for name.
You can generate random prefix or suffix
for name using this method.
:param gender: The gender.
:param title_type: TitleType enum object.
:return: The title.
:raises NonEnumerableError: if gender or title_type in incorrect format.
:Example:
PhD. | [
"Generate",
"a",
"random",
"title",
"for",
"name",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/person.py#L115-L134 |
227,998 | lk-geimfari/mimesis | mimesis/providers/person.py | Person.full_name | def full_name(self, gender: Optional[Gender] = None,
reverse: bool = False) -> str:
"""Generate a random full name.
:param reverse: Return reversed full name.
:param gender: Gender's enum object.
:return: Full name.
:Example:
Johann Wolfgang.
"""
if gender is None:
gender = get_random_item(Gender, rnd=self.random)
if gender and isinstance(gender, Gender):
gender = gender
else:
raise NonEnumerableError(Gender)
fmt = '{1} {0}' if reverse else '{0} {1}'
return fmt.format(
self.name(gender),
self.surname(gender),
) | python | def full_name(self, gender: Optional[Gender] = None,
reverse: bool = False) -> str:
"""Generate a random full name.
:param reverse: Return reversed full name.
:param gender: Gender's enum object.
:return: Full name.
:Example:
Johann Wolfgang.
"""
if gender is None:
gender = get_random_item(Gender, rnd=self.random)
if gender and isinstance(gender, Gender):
gender = gender
else:
raise NonEnumerableError(Gender)
fmt = '{1} {0}' if reverse else '{0} {1}'
return fmt.format(
self.name(gender),
self.surname(gender),
) | [
"def",
"full_name",
"(",
"self",
",",
"gender",
":",
"Optional",
"[",
"Gender",
"]",
"=",
"None",
",",
"reverse",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"if",
"gender",
"is",
"None",
":",
"gender",
"=",
"get_random_item",
"(",
"Gender",
",",
"rnd",
"=",
"self",
".",
"random",
")",
"if",
"gender",
"and",
"isinstance",
"(",
"gender",
",",
"Gender",
")",
":",
"gender",
"=",
"gender",
"else",
":",
"raise",
"NonEnumerableError",
"(",
"Gender",
")",
"fmt",
"=",
"'{1} {0}'",
"if",
"reverse",
"else",
"'{0} {1}'",
"return",
"fmt",
".",
"format",
"(",
"self",
".",
"name",
"(",
"gender",
")",
",",
"self",
".",
"surname",
"(",
"gender",
")",
",",
")"
] | Generate a random full name.
:param reverse: Return reversed full name.
:param gender: Gender's enum object.
:return: Full name.
:Example:
Johann Wolfgang. | [
"Generate",
"a",
"random",
"full",
"name",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/person.py#L136-L159 |
227,999 | lk-geimfari/mimesis | mimesis/providers/person.py | Person.username | def username(self, template: Optional[str] = None) -> str:
"""Generate username by template.
Supported template placeholders: (U, l, d)
Supported separators: (-, ., _)
Template must contain at least one "U" or "l" placeholder.
If template is None one of the following templates is used:
('U_d', 'U.d', 'U-d', 'UU-d', 'UU.d', 'UU_d',
'ld', 'l-d', 'Ud', 'l.d', 'l_d', 'default')
:param template: Template.
:return: Username.
:raises ValueError: If template is not supported.
:Example:
Celloid1873
"""
MIN_DATE = 1800
MAX_DATE = 2070
DEFAULT_TEMPLATE = 'l.d'
templates = ('U_d', 'U.d', 'U-d', 'UU-d', 'UU.d', 'UU_d',
'ld', 'l-d', 'Ud', 'l.d', 'l_d', 'default')
if template is None:
template = self.random.choice(templates)
if template == 'default':
template = DEFAULT_TEMPLATE
if not re.fullmatch(r'[Ul\.\-\_d]*[Ul]+[Ul\.\-\_d]*', template):
raise ValueError(
"Template '{}' is not supported.".format(template))
tags = re.findall(r'[Uld\.\-\_]', template)
username = ''
for tag in tags:
if tag == 'U':
username += self.random.choice(USERNAMES).capitalize()
elif tag == 'l':
username += self.random.choice(USERNAMES)
elif tag == 'd':
username += str(self.random.randint(MIN_DATE, MAX_DATE))
elif tag in '-_.':
username += tag
return username | python | def username(self, template: Optional[str] = None) -> str:
"""Generate username by template.
Supported template placeholders: (U, l, d)
Supported separators: (-, ., _)
Template must contain at least one "U" or "l" placeholder.
If template is None one of the following templates is used:
('U_d', 'U.d', 'U-d', 'UU-d', 'UU.d', 'UU_d',
'ld', 'l-d', 'Ud', 'l.d', 'l_d', 'default')
:param template: Template.
:return: Username.
:raises ValueError: If template is not supported.
:Example:
Celloid1873
"""
MIN_DATE = 1800
MAX_DATE = 2070
DEFAULT_TEMPLATE = 'l.d'
templates = ('U_d', 'U.d', 'U-d', 'UU-d', 'UU.d', 'UU_d',
'ld', 'l-d', 'Ud', 'l.d', 'l_d', 'default')
if template is None:
template = self.random.choice(templates)
if template == 'default':
template = DEFAULT_TEMPLATE
if not re.fullmatch(r'[Ul\.\-\_d]*[Ul]+[Ul\.\-\_d]*', template):
raise ValueError(
"Template '{}' is not supported.".format(template))
tags = re.findall(r'[Uld\.\-\_]', template)
username = ''
for tag in tags:
if tag == 'U':
username += self.random.choice(USERNAMES).capitalize()
elif tag == 'l':
username += self.random.choice(USERNAMES)
elif tag == 'd':
username += str(self.random.randint(MIN_DATE, MAX_DATE))
elif tag in '-_.':
username += tag
return username | [
"def",
"username",
"(",
"self",
",",
"template",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"MIN_DATE",
"=",
"1800",
"MAX_DATE",
"=",
"2070",
"DEFAULT_TEMPLATE",
"=",
"'l.d'",
"templates",
"=",
"(",
"'U_d'",
",",
"'U.d'",
",",
"'U-d'",
",",
"'UU-d'",
",",
"'UU.d'",
",",
"'UU_d'",
",",
"'ld'",
",",
"'l-d'",
",",
"'Ud'",
",",
"'l.d'",
",",
"'l_d'",
",",
"'default'",
")",
"if",
"template",
"is",
"None",
":",
"template",
"=",
"self",
".",
"random",
".",
"choice",
"(",
"templates",
")",
"if",
"template",
"==",
"'default'",
":",
"template",
"=",
"DEFAULT_TEMPLATE",
"if",
"not",
"re",
".",
"fullmatch",
"(",
"r'[Ul\\.\\-\\_d]*[Ul]+[Ul\\.\\-\\_d]*'",
",",
"template",
")",
":",
"raise",
"ValueError",
"(",
"\"Template '{}' is not supported.\"",
".",
"format",
"(",
"template",
")",
")",
"tags",
"=",
"re",
".",
"findall",
"(",
"r'[Uld\\.\\-\\_]'",
",",
"template",
")",
"username",
"=",
"''",
"for",
"tag",
"in",
"tags",
":",
"if",
"tag",
"==",
"'U'",
":",
"username",
"+=",
"self",
".",
"random",
".",
"choice",
"(",
"USERNAMES",
")",
".",
"capitalize",
"(",
")",
"elif",
"tag",
"==",
"'l'",
":",
"username",
"+=",
"self",
".",
"random",
".",
"choice",
"(",
"USERNAMES",
")",
"elif",
"tag",
"==",
"'d'",
":",
"username",
"+=",
"str",
"(",
"self",
".",
"random",
".",
"randint",
"(",
"MIN_DATE",
",",
"MAX_DATE",
")",
")",
"elif",
"tag",
"in",
"'-_.'",
":",
"username",
"+=",
"tag",
"return",
"username"
] | Generate username by template.
Supported template placeholders: (U, l, d)
Supported separators: (-, ., _)
Template must contain at least one "U" or "l" placeholder.
If template is None one of the following templates is used:
('U_d', 'U.d', 'U-d', 'UU-d', 'UU.d', 'UU_d',
'ld', 'l-d', 'Ud', 'l.d', 'l_d', 'default')
:param template: Template.
:return: Username.
:raises ValueError: If template is not supported.
:Example:
Celloid1873 | [
"Generate",
"username",
"by",
"template",
"."
] | 4b16ee7a8dba6281a904654a88dbb4b052869fc5 | https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/person.py#L161-L211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.