repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
tensorflow/cleverhans | cleverhans/utils_tfe.py | train | def train(model, X_train=None, Y_train=None, save=False,
predictions_adv=None, evaluate=None,
args=None, rng=None, var_list=None,
attack=None, attack_args=None):
"""
Train a TF Eager model
:param model: cleverhans.model.Model
:param X_train: numpy array with training inputs
:para... | python | def train(model, X_train=None, Y_train=None, save=False,
predictions_adv=None, evaluate=None,
args=None, rng=None, var_list=None,
attack=None, attack_args=None):
"""
Train a TF Eager model
:param model: cleverhans.model.Model
:param X_train: numpy array with training inputs
:para... | [
"def",
"train",
"(",
"model",
",",
"X_train",
"=",
"None",
",",
"Y_train",
"=",
"None",
",",
"save",
"=",
"False",
",",
"predictions_adv",
"=",
"None",
",",
"evaluate",
"=",
"None",
",",
"args",
"=",
"None",
",",
"rng",
"=",
"None",
",",
"var_list",
... | Train a TF Eager model
:param model: cleverhans.model.Model
:param X_train: numpy array with training inputs
:param Y_train: numpy array with training outputs
:param save: boolean controlling the save operation
:param predictions_adv: if set with the adversarial example tensor,
will ... | [
"Train",
"a",
"TF",
"Eager",
"model",
":",
"param",
"model",
":",
"cleverhans",
".",
"model",
".",
"Model",
":",
"param",
"X_train",
":",
"numpy",
"array",
"with",
"training",
"inputs",
":",
"param",
"Y_train",
":",
"numpy",
"array",
"with",
"training",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tfe.py#L24-L128 | train |
tensorflow/cleverhans | cleverhans/utils_tfe.py | model_eval | def model_eval(model, X_test=None, Y_test=None, args=None,
attack=None, attack_args=None):
"""
Compute the accuracy of a TF Eager model on some data
:param model: instance of cleverhans.model.Model_Eager
with pretrained weights for evaluation.
:param X_test: numpy array with tra... | python | def model_eval(model, X_test=None, Y_test=None, args=None,
attack=None, attack_args=None):
"""
Compute the accuracy of a TF Eager model on some data
:param model: instance of cleverhans.model.Model_Eager
with pretrained weights for evaluation.
:param X_test: numpy array with tra... | [
"def",
"model_eval",
"(",
"model",
",",
"X_test",
"=",
"None",
",",
"Y_test",
"=",
"None",
",",
"args",
"=",
"None",
",",
"attack",
"=",
"None",
",",
"attack_args",
"=",
"None",
")",
":",
"args",
"=",
"_ArgsWrapper",
"(",
"args",
"or",
"{",
"}",
")... | Compute the accuracy of a TF Eager model on some data
:param model: instance of cleverhans.model.Model_Eager
with pretrained weights for evaluation.
:param X_test: numpy array with training inputs
:param Y_test: numpy array with training outputs
:param args: dict or argparse `Namespace` object... | [
"Compute",
"the",
"accuracy",
"of",
"a",
"TF",
"Eager",
"model",
"on",
"some",
"data",
":",
"param",
"model",
":",
"instance",
"of",
"cleverhans",
".",
"model",
".",
"Model_Eager",
"with",
"pretrained",
"weights",
"for",
"evaluation",
".",
":",
"param",
"X... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tfe.py#L131-L202 | train |
tensorflow/cleverhans | cleverhans/utils_tfe.py | model_argmax | def model_argmax(model, samples):
"""
Helper function that computes the current class prediction
:param samples: numpy array with input samples (dims must match x)
:return: the argmax output of predictions, i.e. the current predicted class
"""
tfe = tf.contrib.eager
tf_samples = tfe.Variable(samples)
pr... | python | def model_argmax(model, samples):
"""
Helper function that computes the current class prediction
:param samples: numpy array with input samples (dims must match x)
:return: the argmax output of predictions, i.e. the current predicted class
"""
tfe = tf.contrib.eager
tf_samples = tfe.Variable(samples)
pr... | [
"def",
"model_argmax",
"(",
"model",
",",
"samples",
")",
":",
"tfe",
"=",
"tf",
".",
"contrib",
".",
"eager",
"tf_samples",
"=",
"tfe",
".",
"Variable",
"(",
"samples",
")",
"probabilities",
"=",
"model",
".",
"get_probs",
"(",
"tf_samples",
")",
"if",
... | Helper function that computes the current class prediction
:param samples: numpy array with input samples (dims must match x)
:return: the argmax output of predictions, i.e. the current predicted class | [
"Helper",
"function",
"that",
"computes",
"the",
"current",
"class",
"prediction",
":",
"param",
"samples",
":",
"numpy",
"array",
"with",
"input",
"samples",
"(",
"dims",
"must",
"match",
"x",
")",
":",
"return",
":",
"the",
"argmax",
"output",
"of",
"pre... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/utils_tfe.py#L205-L218 | train |
tensorflow/cleverhans | cleverhans/attacks/noise.py | Noise.generate | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
if self.ord != np.inf:
rai... | python | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
if self.ord != np.inf:
rai... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"ord",
"!=",
"np",
".",
"inf",
":",
"raise... | Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params` | [
"Generate",
"symbolic",
"graph",
"for",
"adversarial",
"examples",
"and",
"return",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/noise.py#L38-L57 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/utils.py | initialize_dual | def initialize_dual(neural_net_params_object, init_dual_file=None,
random_init_variance=0.01, init_nu=200.0):
"""Function to initialize the dual variables of the class.
Args:
neural_net_params_object: Object with the neural net weights, biases
and types
init_dual_file: Path to fil... | python | def initialize_dual(neural_net_params_object, init_dual_file=None,
random_init_variance=0.01, init_nu=200.0):
"""Function to initialize the dual variables of the class.
Args:
neural_net_params_object: Object with the neural net weights, biases
and types
init_dual_file: Path to fil... | [
"def",
"initialize_dual",
"(",
"neural_net_params_object",
",",
"init_dual_file",
"=",
"None",
",",
"random_init_variance",
"=",
"0.01",
",",
"init_nu",
"=",
"200.0",
")",
":",
"lambda_pos",
"=",
"[",
"]",
"lambda_neg",
"=",
"[",
"]",
"lambda_quad",
"=",
"[",
... | Function to initialize the dual variables of the class.
Args:
neural_net_params_object: Object with the neural net weights, biases
and types
init_dual_file: Path to file containing dual variables, if the path
is empty, perform random initialization
Expects numpy dictionary with
lambda... | [
"Function",
"to",
"initialize",
"the",
"dual",
"variables",
"of",
"the",
"class",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L22-L93 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/utils.py | eig_one_step | def eig_one_step(current_vector, learning_rate, vector_prod_fn):
"""Function that performs one step of gd (variant) for min eigen value.
Args:
current_vector: current estimate of the eigen vector with minimum eigen
value.
learning_rate: learning rate.
vector_prod_fn: function which returns produc... | python | def eig_one_step(current_vector, learning_rate, vector_prod_fn):
"""Function that performs one step of gd (variant) for min eigen value.
Args:
current_vector: current estimate of the eigen vector with minimum eigen
value.
learning_rate: learning rate.
vector_prod_fn: function which returns produc... | [
"def",
"eig_one_step",
"(",
"current_vector",
",",
"learning_rate",
",",
"vector_prod_fn",
")",
":",
"grad",
"=",
"2",
"*",
"vector_prod_fn",
"(",
"current_vector",
")",
"# Current objective = (1/2)*v^T (2*M*v); v = current_vector",
"# grad = 2*M*v",
"current_objective",
"=... | Function that performs one step of gd (variant) for min eigen value.
Args:
current_vector: current estimate of the eigen vector with minimum eigen
value.
learning_rate: learning rate.
vector_prod_fn: function which returns product H*x, where H is a matrix for
which we computing eigenvector.
... | [
"Function",
"that",
"performs",
"one",
"step",
"of",
"gd",
"(",
"variant",
")",
"for",
"min",
"eigen",
"value",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L95-L159 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/utils.py | minimum_eigen_vector | def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn):
"""Computes eigenvector which corresponds to minimum eigenvalue.
Args:
x: initial value of eigenvector.
num_steps: number of optimization steps.
learning_rate: learning rate.
vector_prod_fn: function which takes x and returns pr... | python | def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn):
"""Computes eigenvector which corresponds to minimum eigenvalue.
Args:
x: initial value of eigenvector.
num_steps: number of optimization steps.
learning_rate: learning rate.
vector_prod_fn: function which takes x and returns pr... | [
"def",
"minimum_eigen_vector",
"(",
"x",
",",
"num_steps",
",",
"learning_rate",
",",
"vector_prod_fn",
")",
":",
"x",
"=",
"tf",
".",
"nn",
".",
"l2_normalize",
"(",
"x",
")",
"for",
"_",
"in",
"range",
"(",
"num_steps",
")",
":",
"x",
"=",
"eig_one_s... | Computes eigenvector which corresponds to minimum eigenvalue.
Args:
x: initial value of eigenvector.
num_steps: number of optimization steps.
learning_rate: learning rate.
vector_prod_fn: function which takes x and returns product H*x.
Returns:
approximate value of eigenvector.
This functio... | [
"Computes",
"eigenvector",
"which",
"corresponds",
"to",
"minimum",
"eigenvalue",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L162-L181 | train |
tensorflow/cleverhans | cleverhans/experimental/certification/utils.py | tf_lanczos_smallest_eigval | def tf_lanczos_smallest_eigval(vector_prod_fn,
matrix_dim,
initial_vector,
num_iter=1000,
max_iter=1000,
collapse_tol=1e-9,
dtype=tf.f... | python | def tf_lanczos_smallest_eigval(vector_prod_fn,
matrix_dim,
initial_vector,
num_iter=1000,
max_iter=1000,
collapse_tol=1e-9,
dtype=tf.f... | [
"def",
"tf_lanczos_smallest_eigval",
"(",
"vector_prod_fn",
",",
"matrix_dim",
",",
"initial_vector",
",",
"num_iter",
"=",
"1000",
",",
"max_iter",
"=",
"1000",
",",
"collapse_tol",
"=",
"1e-9",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"# alpha will... | Computes smallest eigenvector and eigenvalue using Lanczos in pure TF.
This function computes smallest eigenvector and eigenvalue of the matrix
which is implicitly specified by `vector_prod_fn`.
`vector_prod_fn` is a function which takes `x` and returns a product of matrix
in consideration and `x`.
Computati... | [
"Computes",
"smallest",
"eigenvector",
"and",
"eigenvalue",
"using",
"Lanczos",
"in",
"pure",
"TF",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L184-L278 | train |
tensorflow/cleverhans | cleverhans/serial.py | NoRefModel.get_vars | def get_vars(self):
"""
Provides access to the model's Variables.
This may include Variables that are not parameters, such as batch
norm running moments.
:return: A list of all Variables defining the model.
"""
# Catch eager execution and assert function overload.
try:
if tf.execu... | python | def get_vars(self):
"""
Provides access to the model's Variables.
This may include Variables that are not parameters, such as batch
norm running moments.
:return: A list of all Variables defining the model.
"""
# Catch eager execution and assert function overload.
try:
if tf.execu... | [
"def",
"get_vars",
"(",
"self",
")",
":",
"# Catch eager execution and assert function overload.",
"try",
":",
"if",
"tf",
".",
"executing_eagerly",
"(",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"For Eager execution - get_vars \"",
"\"must be overridden.\"",
")",
... | Provides access to the model's Variables.
This may include Variables that are not parameters, such as batch
norm running moments.
:return: A list of all Variables defining the model. | [
"Provides",
"access",
"to",
"the",
"model",
"s",
"Variables",
".",
"This",
"may",
"include",
"Variables",
"that",
"are",
"not",
"parameters",
"such",
"as",
"batch",
"norm",
"running",
"moments",
".",
":",
"return",
":",
"A",
"list",
"of",
"all",
"Variables... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/serial.py#L151-L194 | train |
tensorflow/cleverhans | cleverhans/picklable_model.py | Dropout.fprop | def fprop(self, x, dropout=False, dropout_dict=None, **kwargs):
"""
Forward propagation as either no-op or dropping random units.
:param x: The input to the layer
:param dropout: bool specifying whether to drop units
:param dropout_dict: dict
This dictionary is usually not needed.
In... | python | def fprop(self, x, dropout=False, dropout_dict=None, **kwargs):
"""
Forward propagation as either no-op or dropping random units.
:param x: The input to the layer
:param dropout: bool specifying whether to drop units
:param dropout_dict: dict
This dictionary is usually not needed.
In... | [
"def",
"fprop",
"(",
"self",
",",
"x",
",",
"dropout",
"=",
"False",
",",
"dropout_dict",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"include_prob",
"=",
"self",
".",
"include_prob",
"if",
"dropout_dict",
"is",
"not",
"None",
":",
"assert",
"dropo... | Forward propagation as either no-op or dropping random units.
:param x: The input to the layer
:param dropout: bool specifying whether to drop units
:param dropout_dict: dict
This dictionary is usually not needed.
In rare cases, generally for research purposes, this dictionary
makes ... | [
"Forward",
"propagation",
"as",
"either",
"no",
"-",
"op",
"or",
"dropping",
"random",
"units",
".",
":",
"param",
"x",
":",
"The",
"input",
"to",
"the",
"layer",
":",
"param",
"dropout",
":",
"bool",
"specifying",
"whether",
"to",
"drop",
"units",
":",
... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/picklable_model.py#L616-L639 | train |
tensorflow/cleverhans | cleverhans/attacks/carlini_wagner_l2.py | CarliniWagnerL2.generate | def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: A tensor with the inputs.
:param kwargs: See `parse_params`
"""
assert self.sess is not None, \
'Cannot... | python | def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: A tensor with the inputs.
:param kwargs: See `parse_params`
"""
assert self.sess is not None, \
'Cannot... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"self",
".",
"sess",
"is",
"not",
"None",
",",
"'Cannot use `generate` when no `sess` was provided'",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"labels",
... | Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: A tensor with the inputs.
:param kwargs: See `parse_params` | [
"Return",
"a",
"tensor",
"that",
"constructs",
"adversarial",
"examples",
"for",
"the",
"given",
"input",
".",
"Generate",
"uses",
"tf",
".",
"py_func",
"in",
"order",
"to",
"operate",
"over",
"tensors",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L58-L85 | train |
tensorflow/cleverhans | cleverhans/attacks/carlini_wagner_l2.py | CarliniWagnerL2.parse_params | def parse_params(self,
y=None,
y_target=None,
batch_size=1,
confidence=0,
learning_rate=5e-3,
binary_search_steps=5,
max_iterations=1000,
abort_early=True,
... | python | def parse_params(self,
y=None,
y_target=None,
batch_size=1,
confidence=0,
learning_rate=5e-3,
binary_search_steps=5,
max_iterations=1000,
abort_early=True,
... | [
"def",
"parse_params",
"(",
"self",
",",
"y",
"=",
"None",
",",
"y_target",
"=",
"None",
",",
"batch_size",
"=",
"1",
",",
"confidence",
"=",
"0",
",",
"learning_rate",
"=",
"5e-3",
",",
"binary_search_steps",
"=",
"5",
",",
"max_iterations",
"=",
"1000"... | :param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
:param confidence: Confide... | [
":",
"param",
"y",
":",
"(",
"optional",
")",
"A",
"tensor",
"with",
"the",
"true",
"labels",
"for",
"an",
"untargeted",
"attack",
".",
"If",
"None",
"(",
"and",
"y_target",
"is",
"None",
")",
"then",
"use",
"the",
"original",
"labels",
"the",
"classif... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L87-L143 | train |
tensorflow/cleverhans | cleverhans/attacks/carlini_wagner_l2.py | CWL2.attack | def attack(self, imgs, targets):
"""
Perform the L_2 attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
r = []
for i in range(0, len(imgs), sel... | python | def attack(self, imgs, targets):
"""
Perform the L_2 attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
r = []
for i in range(0, len(imgs), sel... | [
"def",
"attack",
"(",
"self",
",",
"imgs",
",",
"targets",
")",
":",
"r",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"imgs",
")",
",",
"self",
".",
"batch_size",
")",
":",
"_logger",
".",
"debug",
"(",
"(",
"\"Running ... | Perform the L_2 attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels | [
"Perform",
"the",
"L_2",
"attack",
"on",
"the",
"given",
"instance",
"for",
"the",
"given",
"targets",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L276-L291 | train |
tensorflow/cleverhans | cleverhans/attacks/carlini_wagner_l2.py | CWL2.attack_batch | def attack_batch(self, imgs, labs):
"""
Run the attack on a batch of instance and labels.
"""
def compare(x, y):
if not isinstance(x, (float, int, np.int64)):
x = np.copy(x)
if self.TARGETED:
x[y] -= self.CONFIDENCE
else:
x[y] += self.CONFIDENCE
... | python | def attack_batch(self, imgs, labs):
"""
Run the attack on a batch of instance and labels.
"""
def compare(x, y):
if not isinstance(x, (float, int, np.int64)):
x = np.copy(x)
if self.TARGETED:
x[y] -= self.CONFIDENCE
else:
x[y] += self.CONFIDENCE
... | [
"def",
"attack_batch",
"(",
"self",
",",
"imgs",
",",
"labs",
")",
":",
"def",
"compare",
"(",
"x",
",",
"y",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"float",
",",
"int",
",",
"np",
".",
"int64",
")",
")",
":",
"x",
"=",
"np"... | Run the attack on a batch of instance and labels. | [
"Run",
"the",
"attack",
"on",
"a",
"batch",
"of",
"instance",
"and",
"labels",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L293-L415 | train |
tensorflow/cleverhans | examples/RL-attack/train.py | maybe_load_model | def maybe_load_model(savedir, container):
"""Load model if present at the specified path."""
if savedir is None:
return
state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip'))
if container is not None:
logger.log("Attempting to download model from Azure")
found_model = container.... | python | def maybe_load_model(savedir, container):
"""Load model if present at the specified path."""
if savedir is None:
return
state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip'))
if container is not None:
logger.log("Attempting to download model from Azure")
found_model = container.... | [
"def",
"maybe_load_model",
"(",
"savedir",
",",
"container",
")",
":",
"if",
"savedir",
"is",
"None",
":",
"return",
"state_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"join",
"(",
"savedir",
",",
"'training_state.pkl.zip'",
... | Load model if present at the specified path. | [
"Load",
"model",
"if",
"present",
"at",
"the",
"specified",
"path",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/RL-attack/train.py#L130-L149 | train |
tensorflow/cleverhans | cleverhans_tutorials/__init__.py | check_installation | def check_installation(cur_file):
"""Warn user if running cleverhans from a different directory than tutorial."""
cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0]
ch_dir = os.path.split(cleverhans.__path__[0])[0]
if cur_dir != ch_dir:
warnings.warn("It appears that you have at least tw... | python | def check_installation(cur_file):
"""Warn user if running cleverhans from a different directory than tutorial."""
cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0]
ch_dir = os.path.split(cleverhans.__path__[0])[0]
if cur_dir != ch_dir:
warnings.warn("It appears that you have at least tw... | [
"def",
"check_installation",
"(",
"cur_file",
")",
":",
"cur_dir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"cur_file",
")",
")",
")",
"[",
"0",
"]",
"ch_dir",
"=",
... | Warn user if running cleverhans from a different directory than tutorial. | [
"Warn",
"user",
"if",
"running",
"cleverhans",
"from",
"a",
"different",
"directory",
"than",
"tutorial",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/__init__.py#L13-L24 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dataset/download_images.py | parse_args | def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(
description='Tool to download dataset images.')
parser.add_argument('--input_file', required=True,
help='Location of dataset.csv')
parser.add_argument('--output_dir', required=True,
... | python | def parse_args():
"""Parses command line arguments."""
parser = argparse.ArgumentParser(
description='Tool to download dataset images.')
parser.add_argument('--input_file', required=True,
help='Location of dataset.csv')
parser.add_argument('--output_dir', required=True,
... | [
"def",
"parse_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Tool to download dataset images.'",
")",
"parser",
".",
"add_argument",
"(",
"'--input_file'",
",",
"required",
"=",
"True",
",",
"help",
"=",
"'Loca... | Parses command line arguments. | [
"Parses",
"command",
"line",
"arguments",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dataset/download_images.py#L43-L54 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dataset/download_images.py | get_image | def get_image(row, output_dir):
"""Downloads the image that corresponds to the given row.
Prints a notification if the download fails."""
if not download_image(image_id=row[0],
url=row[1],
x1=float(row[2]),
y1=float(row[3]),
... | python | def get_image(row, output_dir):
"""Downloads the image that corresponds to the given row.
Prints a notification if the download fails."""
if not download_image(image_id=row[0],
url=row[1],
x1=float(row[2]),
y1=float(row[3]),
... | [
"def",
"get_image",
"(",
"row",
",",
"output_dir",
")",
":",
"if",
"not",
"download_image",
"(",
"image_id",
"=",
"row",
"[",
"0",
"]",
",",
"url",
"=",
"row",
"[",
"1",
"]",
",",
"x1",
"=",
"float",
"(",
"row",
"[",
"2",
"]",
")",
",",
"y1",
... | Downloads the image that corresponds to the given row.
Prints a notification if the download fails. | [
"Downloads",
"the",
"image",
"that",
"corresponds",
"to",
"the",
"given",
"row",
".",
"Prints",
"a",
"notification",
"if",
"the",
"download",
"fails",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dataset/download_images.py#L57-L67 | train |
tensorflow/cleverhans | examples/nips17_adversarial_competition/dataset/download_images.py | download_image | def download_image(image_id, url, x1, y1, x2, y2, output_dir):
"""Downloads one image, crops it, resizes it and saves it locally."""
output_filename = os.path.join(output_dir, image_id + '.png')
if os.path.exists(output_filename):
# Don't download image if it's already there
return True
try:
# Downl... | python | def download_image(image_id, url, x1, y1, x2, y2, output_dir):
"""Downloads one image, crops it, resizes it and saves it locally."""
output_filename = os.path.join(output_dir, image_id + '.png')
if os.path.exists(output_filename):
# Don't download image if it's already there
return True
try:
# Downl... | [
"def",
"download_image",
"(",
"image_id",
",",
"url",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"output_dir",
")",
":",
"output_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"image_id",
"+",
"'.png'",
")",
"if",
"os",... | Downloads one image, crops it, resizes it and saves it locally. | [
"Downloads",
"one",
"image",
"crops",
"it",
"resizes",
"it",
"and",
"saves",
"it",
"locally",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dataset/download_images.py#L70-L92 | train |
tensorflow/cleverhans | examples/robust_vision_benchmark/cleverhans_attack_example/utils.py | py_func_grad | def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None):
"""Custom py_func with gradient support
"""
# Need to generate a unique name to avoid duplicates:
rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))
tf.RegisterGradient(rnd_name)(grad)
g = tf.get_default_graph()
with g.gradie... | python | def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None):
"""Custom py_func with gradient support
"""
# Need to generate a unique name to avoid duplicates:
rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))
tf.RegisterGradient(rnd_name)(grad)
g = tf.get_default_graph()
with g.gradie... | [
"def",
"py_func_grad",
"(",
"func",
",",
"inp",
",",
"Tout",
",",
"stateful",
"=",
"True",
",",
"name",
"=",
"None",
",",
"grad",
"=",
"None",
")",
":",
"# Need to generate a unique name to avoid duplicates:",
"rnd_name",
"=",
"'PyFuncGrad'",
"+",
"str",
"(",
... | Custom py_func with gradient support | [
"Custom",
"py_func",
"with",
"gradient",
"support"
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/robust_vision_benchmark/cleverhans_attack_example/utils.py#L25-L36 | train |
tensorflow/cleverhans | cleverhans_tutorials/tutorial_models_tfe.py | ModelBasicCNNTFE.fprop | def fprop(self, x):
"""
Forward propagation throught the network
:return: dictionary with layer names mapping to activation values.
"""
# Feed forward through the network layers
for layer_name in self.layer_names:
if layer_name == 'input':
prev_layer_act = x
continue
... | python | def fprop(self, x):
"""
Forward propagation throught the network
:return: dictionary with layer names mapping to activation values.
"""
# Feed forward through the network layers
for layer_name in self.layer_names:
if layer_name == 'input':
prev_layer_act = x
continue
... | [
"def",
"fprop",
"(",
"self",
",",
"x",
")",
":",
"# Feed forward through the network layers",
"for",
"layer_name",
"in",
"self",
".",
"layer_names",
":",
"if",
"layer_name",
"==",
"'input'",
":",
"prev_layer_act",
"=",
"x",
"continue",
"else",
":",
"self",
"."... | Forward propagation throught the network
:return: dictionary with layer names mapping to activation values. | [
"Forward",
"propagation",
"throught",
"the",
"network",
":",
"return",
":",
"dictionary",
"with",
"layer",
"names",
"mapping",
"to",
"activation",
"values",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/tutorial_models_tfe.py#L54-L73 | train |
tensorflow/cleverhans | cleverhans_tutorials/tutorial_models_tfe.py | ModelBasicCNNTFE.get_layer_params | def get_layer_params(self, layer_name):
"""
Provides access to the parameters of the given layer.
Works arounds the non-availability of graph collections in
eager mode.
:layer_name: name of the layer for which parameters are
required, must be one of the string in the
... | python | def get_layer_params(self, layer_name):
"""
Provides access to the parameters of the given layer.
Works arounds the non-availability of graph collections in
eager mode.
:layer_name: name of the layer for which parameters are
required, must be one of the string in the
... | [
"def",
"get_layer_params",
"(",
"self",
",",
"layer_name",
")",
":",
"assert",
"layer_name",
"in",
"self",
".",
"layer_names",
"out",
"=",
"[",
"]",
"layer",
"=",
"self",
".",
"layers",
"[",
"layer_name",
"]",
"layer_variables",
"=",
"layer",
".",
"variabl... | Provides access to the parameters of the given layer.
Works arounds the non-availability of graph collections in
eager mode.
:layer_name: name of the layer for which parameters are
required, must be one of the string in the
list layer_names
:return: list of pa... | [
"Provides",
"access",
"to",
"the",
"parameters",
"of",
"the",
"given",
"layer",
".",
"Works",
"arounds",
"the",
"non",
"-",
"availability",
"of",
"graph",
"collections",
"in",
"eager",
"mode",
".",
":",
"layer_name",
":",
"name",
"of",
"the",
"layer",
"for... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/tutorial_models_tfe.py#L75-L96 | train |
tensorflow/cleverhans | cleverhans_tutorials/tutorial_models_tfe.py | ModelBasicCNNTFE.get_params | def get_params(self):
"""
Provides access to the model's parameters.
Works arounds the non-availability of graph collections in
eager mode.
:return: A list of all Variables defining the model parameters.
"""
assert tf.executing_eagerly()
out = []
# Collecting params ... | python | def get_params(self):
"""
Provides access to the model's parameters.
Works arounds the non-availability of graph collections in
eager mode.
:return: A list of all Variables defining the model parameters.
"""
assert tf.executing_eagerly()
out = []
# Collecting params ... | [
"def",
"get_params",
"(",
"self",
")",
":",
"assert",
"tf",
".",
"executing_eagerly",
"(",
")",
"out",
"=",
"[",
"]",
"# Collecting params from each layer.",
"for",
"layer_name",
"in",
"self",
".",
"layers",
":",
"out",
"+=",
"self",
".",
"get_layer_params",
... | Provides access to the model's parameters.
Works arounds the non-availability of graph collections in
eager mode.
:return: A list of all Variables defining the model parameters. | [
"Provides",
"access",
"to",
"the",
"model",
"s",
"parameters",
".",
"Works",
"arounds",
"the",
"non",
"-",
"availability",
"of",
"graph",
"collections",
"in",
"eager",
"mode",
".",
":",
"return",
":",
"A",
"list",
"of",
"all",
"Variables",
"defining",
"the... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/tutorial_models_tfe.py#L98-L111 | train |
tensorflow/cleverhans | cleverhans/plot/pyplot_image.py | pair_visual | def pair_visual(original, adversarial, figure=None):
"""
This function displays two images: the original and the adversarial sample
:param original: the original input
:param adversarial: the input after perturbations have been applied
:param figure: if we've already displayed images, use the same plot
:ret... | python | def pair_visual(original, adversarial, figure=None):
"""
This function displays two images: the original and the adversarial sample
:param original: the original input
:param adversarial: the input after perturbations have been applied
:param figure: if we've already displayed images, use the same plot
:ret... | [
"def",
"pair_visual",
"(",
"original",
",",
"adversarial",
",",
"figure",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# Squeeze the image to remove single-dimensional entries from array shape",
"original",
"=",
"np",
".",
"squeeze",
"("... | This function displays two images: the original and the adversarial sample
:param original: the original input
:param adversarial: the input after perturbations have been applied
:param figure: if we've already displayed images, use the same plot
:return: the matplot figure to reuse for future samples | [
"This",
"function",
"displays",
"two",
"images",
":",
"the",
"original",
"and",
"the",
"adversarial",
"sample",
":",
"param",
"original",
":",
"the",
"original",
"input",
":",
"param",
"adversarial",
":",
"the",
"input",
"after",
"perturbations",
"have",
"been... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/pyplot_image.py#L9-L49 | train |
tensorflow/cleverhans | cleverhans/plot/pyplot_image.py | grid_visual | def grid_visual(data):
"""
This function displays a grid of images to show full misclassification
:param data: grid data of the form;
[nb_classes : nb_classes : img_rows : img_cols : nb_channels]
:return: if necessary, the matplot figure to reuse
"""
import matplotlib.pyplot as plt
# Ensure interac... | python | def grid_visual(data):
"""
This function displays a grid of images to show full misclassification
:param data: grid data of the form;
[nb_classes : nb_classes : img_rows : img_cols : nb_channels]
:return: if necessary, the matplot figure to reuse
"""
import matplotlib.pyplot as plt
# Ensure interac... | [
"def",
"grid_visual",
"(",
"data",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"# Ensure interactive mode is disabled and initialize our graph",
"plt",
".",
"ioff",
"(",
")",
"figure",
"=",
"plt",
".",
"figure",
"(",
")",
"figure",
".",
"canvas... | This function displays a grid of images to show full misclassification
:param data: grid data of the form;
[nb_classes : nb_classes : img_rows : img_cols : nb_channels]
:return: if necessary, the matplot figure to reuse | [
"This",
"function",
"displays",
"a",
"grid",
"of",
"images",
"to",
"show",
"full",
"misclassification",
":",
"param",
"data",
":",
"grid",
"data",
"of",
"the",
"form",
";",
"[",
"nb_classes",
":",
"nb_classes",
":",
"img_rows",
":",
"img_cols",
":",
"nb_ch... | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/pyplot_image.py#L51-L81 | train |
tensorflow/cleverhans | cleverhans/plot/pyplot_image.py | get_logits_over_interval | def get_logits_over_interval(sess, model, x_data, fgsm_params,
min_epsilon=-10., max_epsilon=10.,
num_points=21):
"""Get logits when the input is perturbed in an interval in adv direction.
Args:
sess: Tf session
model: Model for which we wish to... | python | def get_logits_over_interval(sess, model, x_data, fgsm_params,
min_epsilon=-10., max_epsilon=10.,
num_points=21):
"""Get logits when the input is perturbed in an interval in adv direction.
Args:
sess: Tf session
model: Model for which we wish to... | [
"def",
"get_logits_over_interval",
"(",
"sess",
",",
"model",
",",
"x_data",
",",
"fgsm_params",
",",
"min_epsilon",
"=",
"-",
"10.",
",",
"max_epsilon",
"=",
"10.",
",",
"num_points",
"=",
"21",
")",
":",
"# Get the height, width and number of channels",
"height"... | Get logits when the input is perturbed in an interval in adv direction.
Args:
sess: Tf session
model: Model for which we wish to get logits.
x_data: Numpy array corresponding to single data.
point of shape [height, width, channels].
fgsm_params: Parameters for generating adversa... | [
"Get",
"logits",
"when",
"the",
"input",
"is",
"perturbed",
"in",
"an",
"interval",
"in",
"adv",
"direction",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/pyplot_image.py#L84-L137 | train |
tensorflow/cleverhans | cleverhans/plot/pyplot_image.py | linear_extrapolation_plot | def linear_extrapolation_plot(log_prob_adv_array, y, file_name,
min_epsilon=-10, max_epsilon=10,
num_points=21):
"""Generate linear extrapolation plot.
Args:
log_prob_adv_array: Numpy array containing log probabilities
y: Tf placeholder for th... | python | def linear_extrapolation_plot(log_prob_adv_array, y, file_name,
min_epsilon=-10, max_epsilon=10,
num_points=21):
"""Generate linear extrapolation plot.
Args:
log_prob_adv_array: Numpy array containing log probabilities
y: Tf placeholder for th... | [
"def",
"linear_extrapolation_plot",
"(",
"log_prob_adv_array",
",",
"y",
",",
"file_name",
",",
"min_epsilon",
"=",
"-",
"10",
",",
"max_epsilon",
"=",
"10",
",",
"num_points",
"=",
"21",
")",
":",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'Agg... | Generate linear extrapolation plot.
Args:
log_prob_adv_array: Numpy array containing log probabilities
y: Tf placeholder for the labels
file_name: Plot filename
min_epsilon: Minimum value of epsilon over the interval
max_epsilon: Maximum value of epsilon over the interval
num_poin... | [
"Generate",
"linear",
"extrapolation",
"plot",
"."
] | 97488e215760547b81afc53f5e5de8ba7da5bd98 | https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/pyplot_image.py#L139-L182 | train |
backtrader/backtrader | contrib/utils/iqfeed-to-influxdb.py | IQFeedTool._send_cmd | def _send_cmd(self, cmd: str):
"""Encode IQFeed API messages."""
self._sock.sendall(cmd.encode(encoding='latin-1', errors='strict')) | python | def _send_cmd(self, cmd: str):
"""Encode IQFeed API messages."""
self._sock.sendall(cmd.encode(encoding='latin-1', errors='strict')) | [
"def",
"_send_cmd",
"(",
"self",
",",
"cmd",
":",
"str",
")",
":",
"self",
".",
"_sock",
".",
"sendall",
"(",
"cmd",
".",
"encode",
"(",
"encoding",
"=",
"'latin-1'",
",",
"errors",
"=",
"'strict'",
")",
")"
] | Encode IQFeed API messages. | [
"Encode",
"IQFeed",
"API",
"messages",
"."
] | 59ee9521f9887c2a1030c6f1db8c918a5816fd64 | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L59-L61 | train |
backtrader/backtrader | contrib/utils/iqfeed-to-influxdb.py | IQFeedTool.iq_query | def iq_query(self, message: str):
"""Send data query to IQFeed API."""
end_msg = '!ENDMSG!'
recv_buffer = 4096
# Send the historical data request message and buffer the data
self._send_cmd(message)
chunk = ""
data = ""
while True:
chunk = sel... | python | def iq_query(self, message: str):
"""Send data query to IQFeed API."""
end_msg = '!ENDMSG!'
recv_buffer = 4096
# Send the historical data request message and buffer the data
self._send_cmd(message)
chunk = ""
data = ""
while True:
chunk = sel... | [
"def",
"iq_query",
"(",
"self",
",",
"message",
":",
"str",
")",
":",
"end_msg",
"=",
"'!ENDMSG!'",
"recv_buffer",
"=",
"4096",
"# Send the historical data request message and buffer the data",
"self",
".",
"_send_cmd",
"(",
"message",
")",
"chunk",
"=",
"\"\"",
"... | Send data query to IQFeed API. | [
"Send",
"data",
"query",
"to",
"IQFeed",
"API",
"."
] | 59ee9521f9887c2a1030c6f1db8c918a5816fd64 | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L63-L90 | train |
backtrader/backtrader | contrib/utils/iqfeed-to-influxdb.py | IQFeedTool.get_historical_minute_data | def get_historical_minute_data(self, ticker: str):
"""Request historical 5 minute data from DTN."""
start = self._start
stop = self._stop
if len(stop) > 4:
stop = stop[:4]
if len(start) > 4:
start = start[:4]
for year in range(int(start), int(st... | python | def get_historical_minute_data(self, ticker: str):
"""Request historical 5 minute data from DTN."""
start = self._start
stop = self._stop
if len(stop) > 4:
stop = stop[:4]
if len(start) > 4:
start = start[:4]
for year in range(int(start), int(st... | [
"def",
"get_historical_minute_data",
"(",
"self",
",",
"ticker",
":",
"str",
")",
":",
"start",
"=",
"self",
".",
"_start",
"stop",
"=",
"self",
".",
"_stop",
"if",
"len",
"(",
"stop",
")",
">",
"4",
":",
"stop",
"=",
"stop",
"[",
":",
"4",
"]",
... | Request historical 5 minute data from DTN. | [
"Request",
"historical",
"5",
"minute",
"data",
"from",
"DTN",
"."
] | 59ee9521f9887c2a1030c6f1db8c918a5816fd64 | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L92-L118 | train |
backtrader/backtrader | contrib/utils/iqfeed-to-influxdb.py | IQFeedTool.add_data_to_df | def add_data_to_df(self, data: np.array):
"""Build Pandas Dataframe in memory"""
col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi']
data = np.array(data).reshape(-1, len(col_names) + 1)
df = pd.DataFrame(data=data[:, 1:], index=data[:, 0],
co... | python | def add_data_to_df(self, data: np.array):
"""Build Pandas Dataframe in memory"""
col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi']
data = np.array(data).reshape(-1, len(col_names) + 1)
df = pd.DataFrame(data=data[:, 1:], index=data[:, 0],
co... | [
"def",
"add_data_to_df",
"(",
"self",
",",
"data",
":",
"np",
".",
"array",
")",
":",
"col_names",
"=",
"[",
"'high_p'",
",",
"'low_p'",
",",
"'open_p'",
",",
"'close_p'",
",",
"'volume'",
",",
"'oi'",
"]",
"data",
"=",
"np",
".",
"array",
"(",
"data... | Build Pandas Dataframe in memory | [
"Build",
"Pandas",
"Dataframe",
"in",
"memory"
] | 59ee9521f9887c2a1030c6f1db8c918a5816fd64 | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L120-L142 | train |
backtrader/backtrader | contrib/utils/iqfeed-to-influxdb.py | IQFeedTool.get_tickers_from_file | def get_tickers_from_file(self, filename):
"""Load ticker list from txt file"""
if not os.path.exists(filename):
log.error("Ticker List file does not exist: %s", filename)
tickers = []
with io.open(filename, 'r') as fd:
for ticker in fd:
tickers.a... | python | def get_tickers_from_file(self, filename):
"""Load ticker list from txt file"""
if not os.path.exists(filename):
log.error("Ticker List file does not exist: %s", filename)
tickers = []
with io.open(filename, 'r') as fd:
for ticker in fd:
tickers.a... | [
"def",
"get_tickers_from_file",
"(",
"self",
",",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"log",
".",
"error",
"(",
"\"Ticker List file does not exist: %s\"",
",",
"filename",
")",
"tickers",
"=",
"[",
... | Load ticker list from txt file | [
"Load",
"ticker",
"list",
"from",
"txt",
"file"
] | 59ee9521f9887c2a1030c6f1db8c918a5816fd64 | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L144-L153 | train |
backtrader/backtrader | contrib/utils/influxdb-import.py | InfluxDBTool.write_dataframe_to_idb | def write_dataframe_to_idb(self, ticker):
"""Write Pandas Dataframe to InfluxDB database"""
cachepath = self._cache
cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker))
if not os.path.exists(cachefile):
log.warn('Import file does not exist: %s' %
(cache... | python | def write_dataframe_to_idb(self, ticker):
"""Write Pandas Dataframe to InfluxDB database"""
cachepath = self._cache
cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker))
if not os.path.exists(cachefile):
log.warn('Import file does not exist: %s' %
(cache... | [
"def",
"write_dataframe_to_idb",
"(",
"self",
",",
"ticker",
")",
":",
"cachepath",
"=",
"self",
".",
"_cache",
"cachefile",
"=",
"(",
"'%s/%s-1M.csv.gz'",
"%",
"(",
"cachepath",
",",
"ticker",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"("... | Write Pandas Dataframe to InfluxDB database | [
"Write",
"Pandas",
"Dataframe",
"to",
"InfluxDB",
"database"
] | 59ee9521f9887c2a1030c6f1db8c918a5816fd64 | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/influxdb-import.py#L29-L49 | train |
backtrader/backtrader | backtrader/plot/multicursor.py | MultiCursor.connect | def connect(self):
"""connect events"""
self._cidmotion = self.canvas.mpl_connect('motion_notify_event',
self.onmove)
self._ciddraw = self.canvas.mpl_connect('draw_event', self.clear) | python | def connect(self):
"""connect events"""
self._cidmotion = self.canvas.mpl_connect('motion_notify_event',
self.onmove)
self._ciddraw = self.canvas.mpl_connect('draw_event', self.clear) | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"_cidmotion",
"=",
"self",
".",
"canvas",
".",
"mpl_connect",
"(",
"'motion_notify_event'",
",",
"self",
".",
"onmove",
")",
"self",
".",
"_ciddraw",
"=",
"self",
".",
"canvas",
".",
"mpl_connect",
"(... | connect events | [
"connect",
"events"
] | 59ee9521f9887c2a1030c6f1db8c918a5816fd64 | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/backtrader/plot/multicursor.py#L173-L177 | train |
backtrader/backtrader | backtrader/plot/multicursor.py | MultiCursor.disconnect | def disconnect(self):
"""disconnect events"""
self.canvas.mpl_disconnect(self._cidmotion)
self.canvas.mpl_disconnect(self._ciddraw) | python | def disconnect(self):
"""disconnect events"""
self.canvas.mpl_disconnect(self._cidmotion)
self.canvas.mpl_disconnect(self._ciddraw) | [
"def",
"disconnect",
"(",
"self",
")",
":",
"self",
".",
"canvas",
".",
"mpl_disconnect",
"(",
"self",
".",
"_cidmotion",
")",
"self",
".",
"canvas",
".",
"mpl_disconnect",
"(",
"self",
".",
"_ciddraw",
")"
] | disconnect events | [
"disconnect",
"events"
] | 59ee9521f9887c2a1030c6f1db8c918a5816fd64 | https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/backtrader/plot/multicursor.py#L179-L182 | train |
AirtestProject/Airtest | playground/win_ide.py | WindowsInIDE.connect | def connect(self, **kwargs):
"""
Connect to window and set it foreground
Args:
**kwargs: optional arguments
Returns:
None
"""
self.app = self._app.connect(**kwargs)
try:
self._top_window = self.app.top_window().wrapper_object... | python | def connect(self, **kwargs):
"""
Connect to window and set it foreground
Args:
**kwargs: optional arguments
Returns:
None
"""
self.app = self._app.connect(**kwargs)
try:
self._top_window = self.app.top_window().wrapper_object... | [
"def",
"connect",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"app",
"=",
"self",
".",
"_app",
".",
"connect",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"self",
".",
"_top_window",
"=",
"self",
".",
"app",
".",
"top_window",
"(",... | Connect to window and set it foreground
Args:
**kwargs: optional arguments
Returns:
None | [
"Connect",
"to",
"window",
"and",
"set",
"it",
"foreground"
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/playground/win_ide.py#L19-L35 | train |
AirtestProject/Airtest | playground/win_ide.py | WindowsInIDE.get_rect | def get_rect(self):
"""
Get rectangle of app or desktop resolution
Returns:
RECT(left, top, right, bottom)
"""
if self.handle:
left, top, right, bottom = win32gui.GetWindowRect(self.handle)
return RECT(left, top, right, bottom)
else:
... | python | def get_rect(self):
"""
Get rectangle of app or desktop resolution
Returns:
RECT(left, top, right, bottom)
"""
if self.handle:
left, top, right, bottom = win32gui.GetWindowRect(self.handle)
return RECT(left, top, right, bottom)
else:
... | [
"def",
"get_rect",
"(",
"self",
")",
":",
"if",
"self",
".",
"handle",
":",
"left",
",",
"top",
",",
"right",
",",
"bottom",
"=",
"win32gui",
".",
"GetWindowRect",
"(",
"self",
".",
"handle",
")",
"return",
"RECT",
"(",
"left",
",",
"top",
",",
"ri... | Get rectangle of app or desktop resolution
Returns:
RECT(left, top, right, bottom) | [
"Get",
"rectangle",
"of",
"app",
"or",
"desktop",
"resolution"
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/playground/win_ide.py#L37-L51 | train |
AirtestProject/Airtest | playground/win_ide.py | WindowsInIDE.snapshot | def snapshot(self, filename="tmp.png"):
"""
Take a screenshot and save it to `tmp.png` filename by default
Args:
filename: name of file where to store the screenshot
Returns:
display the screenshot
"""
if not filename:
filename = "tm... | python | def snapshot(self, filename="tmp.png"):
"""
Take a screenshot and save it to `tmp.png` filename by default
Args:
filename: name of file where to store the screenshot
Returns:
display the screenshot
"""
if not filename:
filename = "tm... | [
"def",
"snapshot",
"(",
"self",
",",
"filename",
"=",
"\"tmp.png\"",
")",
":",
"if",
"not",
"filename",
":",
"filename",
"=",
"\"tmp.png\"",
"if",
"self",
".",
"handle",
":",
"try",
":",
"screenshot",
"(",
"filename",
",",
"self",
".",
"handle",
")",
"... | Take a screenshot and save it to `tmp.png` filename by default
Args:
filename: name of file where to store the screenshot
Returns:
display the screenshot | [
"Take",
"a",
"screenshot",
"and",
"save",
"it",
"to",
"tmp",
".",
"png",
"filename",
"by",
"default"
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/playground/win_ide.py#L53-L78 | train |
AirtestProject/Airtest | benchmark/plot.py | PlotResult.extract_data | def extract_data(self):
"""从数据中获取到绘图相关的有用信息."""
self.time_axis = []
self.cpu_axis = []
self.mem_axis = []
self.timestamp_list = []
plot_data = self.data.get("plot_data", [])
# 按照时间分割线,划分成几段数据,取其中的最值
for i in plot_data:
timestamp = i["timestamp"... | python | def extract_data(self):
"""从数据中获取到绘图相关的有用信息."""
self.time_axis = []
self.cpu_axis = []
self.mem_axis = []
self.timestamp_list = []
plot_data = self.data.get("plot_data", [])
# 按照时间分割线,划分成几段数据,取其中的最值
for i in plot_data:
timestamp = i["timestamp"... | [
"def",
"extract_data",
"(",
"self",
")",
":",
"self",
".",
"time_axis",
"=",
"[",
"]",
"self",
".",
"cpu_axis",
"=",
"[",
"]",
"self",
".",
"mem_axis",
"=",
"[",
"]",
"self",
".",
"timestamp_list",
"=",
"[",
"]",
"plot_data",
"=",
"self",
".",
"dat... | 从数据中获取到绘图相关的有用信息. | [
"从数据中获取到绘图相关的有用信息",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/plot.py#L38-L59 | train |
AirtestProject/Airtest | benchmark/plot.py | PlotResult.get_each_method_maximun_cpu_mem | def get_each_method_maximun_cpu_mem(self):
"""获取每个方法中的cpu和内存耗费最值点."""
# 本函数用于丰富self.method_exec_info的信息:存入cpu、mem最值点
self.method_exec_info = deepcopy(self.data.get("method_exec_info", []))
method_exec_info = deepcopy(self.method_exec_info) # 用来辅助循环
method_index, cpu_max, cpu_max... | python | def get_each_method_maximun_cpu_mem(self):
"""获取每个方法中的cpu和内存耗费最值点."""
# 本函数用于丰富self.method_exec_info的信息:存入cpu、mem最值点
self.method_exec_info = deepcopy(self.data.get("method_exec_info", []))
method_exec_info = deepcopy(self.method_exec_info) # 用来辅助循环
method_index, cpu_max, cpu_max... | [
"def",
"get_each_method_maximun_cpu_mem",
"(",
"self",
")",
":",
"# 本函数用于丰富self.method_exec_info的信息:存入cpu、mem最值点",
"self",
".",
"method_exec_info",
"=",
"deepcopy",
"(",
"self",
".",
"data",
".",
"get",
"(",
"\"method_exec_info\"",
",",
"[",
"]",
")",
")",
"method_e... | 获取每个方法中的cpu和内存耗费最值点. | [
"获取每个方法中的cpu和内存耗费最值点",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/plot.py#L61-L95 | train |
AirtestProject/Airtest | benchmark/plot.py | PlotResult._get_graph_title | def _get_graph_title(self):
"""获取图像的title."""
start_time = datetime.fromtimestamp(int(self.timestamp_list[0]))
end_time = datetime.fromtimestamp(int(self.timestamp_list[-1]))
end_time = end_time.strftime('%H:%M:%S')
title = "Timespan: %s —— %s" % (start_time, end_time)
r... | python | def _get_graph_title(self):
"""获取图像的title."""
start_time = datetime.fromtimestamp(int(self.timestamp_list[0]))
end_time = datetime.fromtimestamp(int(self.timestamp_list[-1]))
end_time = end_time.strftime('%H:%M:%S')
title = "Timespan: %s —— %s" % (start_time, end_time)
r... | [
"def",
"_get_graph_title",
"(",
"self",
")",
":",
"start_time",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"self",
".",
"timestamp_list",
"[",
"0",
"]",
")",
")",
"end_time",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"self",
".... | 获取图像的title. | [
"获取图像的title",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/plot.py#L97-L104 | train |
AirtestProject/Airtest | benchmark/plot.py | PlotResult.plot_cpu_mem_keypoints | def plot_cpu_mem_keypoints(self):
"""绘制CPU/Mem/特征点数量."""
plt.figure(1)
# 开始绘制子图:
plt.subplot(311)
title = self._get_graph_title()
plt.title(title, loc="center") # 设置绘图的标题
mem_ins = plt.plot(self.time_axis, self.mem_axis, "-", label="Mem(MB)", color='deepskyblue',... | python | def plot_cpu_mem_keypoints(self):
"""绘制CPU/Mem/特征点数量."""
plt.figure(1)
# 开始绘制子图:
plt.subplot(311)
title = self._get_graph_title()
plt.title(title, loc="center") # 设置绘图的标题
mem_ins = plt.plot(self.time_axis, self.mem_axis, "-", label="Mem(MB)", color='deepskyblue',... | [
"def",
"plot_cpu_mem_keypoints",
"(",
"self",
")",
":",
"plt",
".",
"figure",
"(",
"1",
")",
"# 开始绘制子图:",
"plt",
".",
"subplot",
"(",
"311",
")",
"title",
"=",
"self",
".",
"_get_graph_title",
"(",
")",
"plt",
".",
"title",
"(",
"title",
",",
"loc",
... | 绘制CPU/Mem/特征点数量. | [
"绘制CPU",
"/",
"Mem",
"/",
"特征点数量",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/plot.py#L106-L172 | train |
AirtestProject/Airtest | benchmark/profile_recorder.py | CheckKeypointResult.refresh_method_objects | def refresh_method_objects(self):
"""初始化方法对象."""
self.method_object_dict = {}
for key, method in self.MATCHING_METHODS.items():
method_object = method(self.im_search, self.im_source, self.threshold, self.rgb)
self.method_object_dict.update({key: method_object}) | python | def refresh_method_objects(self):
"""初始化方法对象."""
self.method_object_dict = {}
for key, method in self.MATCHING_METHODS.items():
method_object = method(self.im_search, self.im_source, self.threshold, self.rgb)
self.method_object_dict.update({key: method_object}) | [
"def",
"refresh_method_objects",
"(",
"self",
")",
":",
"self",
".",
"method_object_dict",
"=",
"{",
"}",
"for",
"key",
",",
"method",
"in",
"self",
".",
"MATCHING_METHODS",
".",
"items",
"(",
")",
":",
"method_object",
"=",
"method",
"(",
"self",
".",
"... | 初始化方法对象. | [
"初始化方法对象",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/profile_recorder.py#L44-L49 | train |
AirtestProject/Airtest | benchmark/profile_recorder.py | CheckKeypointResult._get_result | def _get_result(self, method_name="kaze"):
"""获取特征点."""
method_object = self.method_object_dict.get(method_name)
# 提取结果和特征点:
try:
result = method_object.find_best_result()
except Exception:
import traceback
traceback.print_exc()
ret... | python | def _get_result(self, method_name="kaze"):
"""获取特征点."""
method_object = self.method_object_dict.get(method_name)
# 提取结果和特征点:
try:
result = method_object.find_best_result()
except Exception:
import traceback
traceback.print_exc()
ret... | [
"def",
"_get_result",
"(",
"self",
",",
"method_name",
"=",
"\"kaze\"",
")",
":",
"method_object",
"=",
"self",
".",
"method_object_dict",
".",
"get",
"(",
"method_name",
")",
"# 提取结果和特征点:",
"try",
":",
"result",
"=",
"method_object",
".",
"find_best_result",
... | 获取特征点. | [
"获取特征点",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/profile_recorder.py#L51-L62 | train |
AirtestProject/Airtest | benchmark/profile_recorder.py | CheckKeypointResult.get_and_plot_keypoints | def get_and_plot_keypoints(self, method_name, plot=False):
"""获取并且绘制出特征点匹配结果."""
if method_name not in self.method_object_dict.keys():
print("'%s' is not in MATCHING_METHODS" % method_name)
return None
kp_sch, kp_src, good, result = self._get_result(method_name)
... | python | def get_and_plot_keypoints(self, method_name, plot=False):
"""获取并且绘制出特征点匹配结果."""
if method_name not in self.method_object_dict.keys():
print("'%s' is not in MATCHING_METHODS" % method_name)
return None
kp_sch, kp_src, good, result = self._get_result(method_name)
... | [
"def",
"get_and_plot_keypoints",
"(",
"self",
",",
"method_name",
",",
"plot",
"=",
"False",
")",
":",
"if",
"method_name",
"not",
"in",
"self",
".",
"method_object_dict",
".",
"keys",
"(",
")",
":",
"print",
"(",
"\"'%s' is not in MATCHING_METHODS\"",
"%",
"m... | 获取并且绘制出特征点匹配结果. | [
"获取并且绘制出特征点匹配结果",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/profile_recorder.py#L64-L100 | train |
AirtestProject/Airtest | benchmark/profile_recorder.py | RecordThread.run | def run(self):
"""开始线程."""
while not self.stop_flag:
timestamp = time.time()
cpu_percent = self.process.cpu_percent() / self.cpu_num
# mem_percent = mem = self.process.memory_percent()
mem_info = dict(self.process.memory_info()._asdict())
mem_g... | python | def run(self):
"""开始线程."""
while not self.stop_flag:
timestamp = time.time()
cpu_percent = self.process.cpu_percent() / self.cpu_num
# mem_percent = mem = self.process.memory_percent()
mem_info = dict(self.process.memory_info()._asdict())
mem_g... | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"stop_flag",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"cpu_percent",
"=",
"self",
".",
"process",
".",
"cpu_percent",
"(",
")",
"/",
"self",
".",
"cpu_num",
"# mem_percent =... | 开始线程. | [
"开始线程",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/profile_recorder.py#L121-L132 | train |
AirtestProject/Airtest | benchmark/profile_recorder.py | ProfileRecorder.load_images | def load_images(self, search_file, source_file):
"""加载待匹配图片."""
self.search_file, self.source_file = search_file, source_file
self.im_search, self.im_source = imread(self.search_file), imread(self.source_file)
# 初始化对象
self.check_macthing_object = CheckKeypointResult(self.im_searc... | python | def load_images(self, search_file, source_file):
"""加载待匹配图片."""
self.search_file, self.source_file = search_file, source_file
self.im_search, self.im_source = imread(self.search_file), imread(self.source_file)
# 初始化对象
self.check_macthing_object = CheckKeypointResult(self.im_searc... | [
"def",
"load_images",
"(",
"self",
",",
"search_file",
",",
"source_file",
")",
":",
"self",
".",
"search_file",
",",
"self",
".",
"source_file",
"=",
"search_file",
",",
"source_file",
"self",
".",
"im_search",
",",
"self",
".",
"im_source",
"=",
"imread",
... | 加载待匹配图片. | [
"加载待匹配图片",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/profile_recorder.py#L145-L150 | train |
AirtestProject/Airtest | benchmark/profile_recorder.py | ProfileRecorder.profile_methods | def profile_methods(self, method_list):
"""帮助函数执行时记录数据."""
self.method_exec_info = []
# 开始数据记录进程
self.record_thread.stop_flag = False
self.record_thread.start()
for name in method_list:
if name not in self.check_macthing_object.MATCHING_METHODS.keys():
... | python | def profile_methods(self, method_list):
"""帮助函数执行时记录数据."""
self.method_exec_info = []
# 开始数据记录进程
self.record_thread.stop_flag = False
self.record_thread.start()
for name in method_list:
if name not in self.check_macthing_object.MATCHING_METHODS.keys():
... | [
"def",
"profile_methods",
"(",
"self",
",",
"method_list",
")",
":",
"self",
".",
"method_exec_info",
"=",
"[",
"]",
"# 开始数据记录进程",
"self",
".",
"record_thread",
".",
"stop_flag",
"=",
"False",
"self",
".",
"record_thread",
".",
"start",
"(",
")",
"for",
"n... | 帮助函数执行时记录数据. | [
"帮助函数执行时记录数据",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/profile_recorder.py#L152-L180 | train |
AirtestProject/Airtest | benchmark/profile_recorder.py | ProfileRecorder.wite_to_json | def wite_to_json(self, dir_path="", file_name=""):
"""将性能数据写入文件."""
# 提取数据
data = {
"plot_data": self.record_thread.profile_data,
"method_exec_info": self.method_exec_info,
"search_file": self.search_file,
"source_file": self.source_file}
#... | python | def wite_to_json(self, dir_path="", file_name=""):
"""将性能数据写入文件."""
# 提取数据
data = {
"plot_data": self.record_thread.profile_data,
"method_exec_info": self.method_exec_info,
"search_file": self.search_file,
"source_file": self.source_file}
#... | [
"def",
"wite_to_json",
"(",
"self",
",",
"dir_path",
"=",
"\"\"",
",",
"file_name",
"=",
"\"\"",
")",
":",
"# 提取数据",
"data",
"=",
"{",
"\"plot_data\"",
":",
"self",
".",
"record_thread",
".",
"profile_data",
",",
"\"method_exec_info\"",
":",
"self",
".",
"... | 将性能数据写入文件. | [
"将性能数据写入文件",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/profile_recorder.py#L182-L194 | train |
AirtestProject/Airtest | playground/poco.py | PocoReport.translate_poco_step | def translate_poco_step(self, step):
"""
处理poco的相关操作,参数与airtest的不同,由一个截图和一个操作构成,需要合成一个步骤
Parameters
----------
step 一个完整的操作,如click
prev_step 前一个步骤,应该是截图
Returns
-------
"""
ret = {}
prev_step = self._steps[-1]
if prev_step... | python | def translate_poco_step(self, step):
"""
处理poco的相关操作,参数与airtest的不同,由一个截图和一个操作构成,需要合成一个步骤
Parameters
----------
step 一个完整的操作,如click
prev_step 前一个步骤,应该是截图
Returns
-------
"""
ret = {}
prev_step = self._steps[-1]
if prev_step... | [
"def",
"translate_poco_step",
"(",
"self",
",",
"step",
")",
":",
"ret",
"=",
"{",
"}",
"prev_step",
"=",
"self",
".",
"_steps",
"[",
"-",
"1",
"]",
"if",
"prev_step",
":",
"ret",
".",
"update",
"(",
"prev_step",
")",
"ret",
"[",
"'type'",
"]",
"="... | 处理poco的相关操作,参数与airtest的不同,由一个截图和一个操作构成,需要合成一个步骤
Parameters
----------
step 一个完整的操作,如click
prev_step 前一个步骤,应该是截图
Returns
------- | [
"处理poco的相关操作,参数与airtest的不同,由一个截图和一个操作构成,需要合成一个步骤",
"Parameters",
"----------",
"step",
"一个完整的操作,如click",
"prev_step",
"前一个步骤,应该是截图"
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/playground/poco.py#L12-L53 | train |
AirtestProject/Airtest | playground/poco.py | PocoReport.func_desc_poco | def func_desc_poco(self, step):
""" 把对应的poco操作显示成中文"""
desc = {
"touch": u"点击UI组件 {name}".format(name=step.get("text", "")),
}
if step['type'] in desc:
return desc.get(step['type'])
else:
return self._translate_desc(step) | python | def func_desc_poco(self, step):
""" 把对应的poco操作显示成中文"""
desc = {
"touch": u"点击UI组件 {name}".format(name=step.get("text", "")),
}
if step['type'] in desc:
return desc.get(step['type'])
else:
return self._translate_desc(step) | [
"def",
"func_desc_poco",
"(",
"self",
",",
"step",
")",
":",
"desc",
"=",
"{",
"\"touch\"",
":",
"u\"点击UI组件 {name}\".format(",
"n",
"ame=st",
"e",
"p.ge",
"t",
"(\"te",
"x",
"t\",",
" ",
"\"\")),",
"",
"",
"",
"",
"",
"}",
"if",
"step",
"[",
"'type'"... | 把对应的poco操作显示成中文 | [
"把对应的poco操作显示成中文"
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/playground/poco.py#L55-L63 | train |
AirtestProject/Airtest | benchmark/benchmark.py | profile_different_methods | def profile_different_methods(search_file, screen_file, method_list, dir_path, file_name):
"""对指定的图片进行性能测试."""
profiler = ProfileRecorder(0.05)
# 加载图片
profiler.load_images(search_file, screen_file)
# 传入待测试的方法列表
profiler.profile_methods(method_list)
# 将性能数据写入文件
profiler.wite_to_json(dir_p... | python | def profile_different_methods(search_file, screen_file, method_list, dir_path, file_name):
"""对指定的图片进行性能测试."""
profiler = ProfileRecorder(0.05)
# 加载图片
profiler.load_images(search_file, screen_file)
# 传入待测试的方法列表
profiler.profile_methods(method_list)
# 将性能数据写入文件
profiler.wite_to_json(dir_p... | [
"def",
"profile_different_methods",
"(",
"search_file",
",",
"screen_file",
",",
"method_list",
",",
"dir_path",
",",
"file_name",
")",
":",
"profiler",
"=",
"ProfileRecorder",
"(",
"0.05",
")",
"# 加载图片",
"profiler",
".",
"load_images",
"(",
"search_file",
",",
... | 对指定的图片进行性能测试. | [
"对指定的图片进行性能测试",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/benchmark.py#L12-L20 | train |
AirtestProject/Airtest | benchmark/benchmark.py | plot_profiled_all_images_table | def plot_profiled_all_images_table(method_list):
"""绘制多个图片的结果."""
high_dpi_dir_path, high_dpi_file_name = "result", "high_dpi.json"
rich_texture_dir_path, rich_texture_file_name = "result", "rich_texture.json"
text_dir_path, text_file_name = "result", "text.json"
image_list = ['high_dpi', 'rich_tex... | python | def plot_profiled_all_images_table(method_list):
"""绘制多个图片的结果."""
high_dpi_dir_path, high_dpi_file_name = "result", "high_dpi.json"
rich_texture_dir_path, rich_texture_file_name = "result", "rich_texture.json"
text_dir_path, text_file_name = "result", "text.json"
image_list = ['high_dpi', 'rich_tex... | [
"def",
"plot_profiled_all_images_table",
"(",
"method_list",
")",
":",
"high_dpi_dir_path",
",",
"high_dpi_file_name",
"=",
"\"result\"",
",",
"\"high_dpi.json\"",
"rich_texture_dir_path",
",",
"rich_texture_file_name",
"=",
"\"result\"",
",",
"\"rich_texture.json\"",
"text_d... | 绘制多个图片的结果. | [
"绘制多个图片的结果",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/benchmark.py#L53-L99 | train |
AirtestProject/Airtest | benchmark/benchmark.py | get_color_list | def get_color_list(method_list):
"""获取method对应的color列表."""
color_list = []
for method in method_list:
color = tuple([random() for _ in range(3)]) # 随机颜色画线
color_list.append(color)
return color_list | python | def get_color_list(method_list):
"""获取method对应的color列表."""
color_list = []
for method in method_list:
color = tuple([random() for _ in range(3)]) # 随机颜色画线
color_list.append(color)
return color_list | [
"def",
"get_color_list",
"(",
"method_list",
")",
":",
"color_list",
"=",
"[",
"]",
"for",
"method",
"in",
"method_list",
":",
"color",
"=",
"tuple",
"(",
"[",
"random",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"3",
")",
"]",
")",
"# 随机颜色画线",
"color... | 获取method对应的color列表. | [
"获取method对应的color列表",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/benchmark.py#L102-L108 | train |
AirtestProject/Airtest | benchmark/benchmark.py | plot_compare_table | def plot_compare_table(image_list, method_list, color_list, compare_dict, fig_name="", fig_num=111):
"""绘制了对比表格."""
row_labels = image_list
# 写入值:
table_vals = []
for i in range(len(row_labels)):
row_vals = []
for method in method_list:
row_vals.append(compare_dict[method... | python | def plot_compare_table(image_list, method_list, color_list, compare_dict, fig_name="", fig_num=111):
"""绘制了对比表格."""
row_labels = image_list
# 写入值:
table_vals = []
for i in range(len(row_labels)):
row_vals = []
for method in method_list:
row_vals.append(compare_dict[method... | [
"def",
"plot_compare_table",
"(",
"image_list",
",",
"method_list",
",",
"color_list",
",",
"compare_dict",
",",
"fig_name",
"=",
"\"\"",
",",
"fig_num",
"=",
"111",
")",
":",
"row_labels",
"=",
"image_list",
"# 写入值:",
"table_vals",
"=",
"[",
"]",
"for",
"i"... | 绘制了对比表格. | [
"绘制了对比表格",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/benchmark.py#L111-L136 | train |
AirtestProject/Airtest | benchmark/benchmark.py | plot_compare_curves | def plot_compare_curves(image_list, method_list, color_list, compare_dict, fig_name="", fig_num=111):
"""绘制对比曲线."""
plt.subplot(fig_num)
plt.title(fig_name, loc="center") # 设置绘图的标题
mix_ins = []
for index, method in enumerate(method_list):
mem_ins = plt.plot(image_list, compare_dict[method],... | python | def plot_compare_curves(image_list, method_list, color_list, compare_dict, fig_name="", fig_num=111):
"""绘制对比曲线."""
plt.subplot(fig_num)
plt.title(fig_name, loc="center") # 设置绘图的标题
mix_ins = []
for index, method in enumerate(method_list):
mem_ins = plt.plot(image_list, compare_dict[method],... | [
"def",
"plot_compare_curves",
"(",
"image_list",
",",
"method_list",
",",
"color_list",
",",
"compare_dict",
",",
"fig_name",
"=",
"\"\"",
",",
"fig_num",
"=",
"111",
")",
":",
"plt",
".",
"subplot",
"(",
"fig_num",
")",
"plt",
".",
"title",
"(",
"fig_name... | 绘制对比曲线. | [
"绘制对比曲线",
"."
] | 21583da2698a601cd632228228fc16d41f60a517 | https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/benchmark/benchmark.py#L139-L153 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | ReadTag | def ReadTag(buffer, pos):
"""Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
us to trade some work that would be done in pure-python (decodi... | python | def ReadTag(buffer, pos):
"""Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
us to trade some work that would be done in pure-python (decodi... | [
"def",
"ReadTag",
"(",
"buffer",
",",
"pos",
")",
":",
"start",
"=",
"pos",
"while",
"six",
".",
"indexbytes",
"(",
"buffer",
",",
"pos",
")",
"&",
"0x80",
":",
"pos",
"+=",
"1",
"pos",
"+=",
"1",
"return",
"(",
"buffer",
"[",
"start",
":",
"pos"... | Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
We return the raw bytes of the tag rather than decoding them. The raw
bytes can then be used to look up the proper decoder. This effectively allows
us to trade some work that would be done in pure-python (decoding a varint)
for work that is... | [
"Read",
"a",
"tag",
"from",
"the",
"buffer",
"and",
"return",
"a",
"(",
"tag_bytes",
"new_pos",
")",
"tuple",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L169-L184 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _SimpleDecoder | def _SimpleDecoder(wire_type, decode_value):
"""Return a constructor for a decoder for fields of a particular type.
Args:
wire_type: The field's wire type.
decode_value: A function which decodes an individual value, e.g.
_DecodeVarint()
"""
def SpecificDecoder(field_number, is_repeated, ... | python | def _SimpleDecoder(wire_type, decode_value):
"""Return a constructor for a decoder for fields of a particular type.
Args:
wire_type: The field's wire type.
decode_value: A function which decodes an individual value, e.g.
_DecodeVarint()
"""
def SpecificDecoder(field_number, is_repeated, ... | [
"def",
"_SimpleDecoder",
"(",
"wire_type",
",",
"decode_value",
")",
":",
"def",
"SpecificDecoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
",",
"key",
",",
"new_default",
")",
":",
"if",
"is_packed",
":",
"local_DecodeVarint",
"=",
"_DecodeVa... | Return a constructor for a decoder for fields of a particular type.
Args:
wire_type: The field's wire type.
decode_value: A function which decodes an individual value, e.g.
_DecodeVarint() | [
"Return",
"a",
"constructor",
"for",
"a",
"decoder",
"for",
"fields",
"of",
"a",
"particular",
"type",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L190-L246 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _ModifiedDecoder | def _ModifiedDecoder(wire_type, decode_value, modify_value):
"""Like SimpleDecoder but additionally invokes modify_value on every value
before storing it. Usually modify_value is ZigZagDecode.
"""
# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
# not enough to make a significan... | python | def _ModifiedDecoder(wire_type, decode_value, modify_value):
"""Like SimpleDecoder but additionally invokes modify_value on every value
before storing it. Usually modify_value is ZigZagDecode.
"""
# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
# not enough to make a significan... | [
"def",
"_ModifiedDecoder",
"(",
"wire_type",
",",
"decode_value",
",",
"modify_value",
")",
":",
"# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but",
"# not enough to make a significant difference.",
"def",
"InnerDecode",
"(",
"buffer",
",",
"pos",
")"... | Like SimpleDecoder but additionally invokes modify_value on every value
before storing it. Usually modify_value is ZigZagDecode. | [
"Like",
"SimpleDecoder",
"but",
"additionally",
"invokes",
"modify_value",
"on",
"every",
"value",
"before",
"storing",
"it",
".",
"Usually",
"modify_value",
"is",
"ZigZagDecode",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L249-L260 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _StructPackDecoder | def _StructPackDecoder(wire_type, format):
"""Return a constructor for a decoder for a fixed-width field.
Args:
wire_type: The field's wire type.
format: The format string to pass to struct.unpack().
"""
value_size = struct.calcsize(format)
local_unpack = struct.unpack
# Reusing _SimpleDeco... | python | def _StructPackDecoder(wire_type, format):
"""Return a constructor for a decoder for a fixed-width field.
Args:
wire_type: The field's wire type.
format: The format string to pass to struct.unpack().
"""
value_size = struct.calcsize(format)
local_unpack = struct.unpack
# Reusing _SimpleDeco... | [
"def",
"_StructPackDecoder",
"(",
"wire_type",
",",
"format",
")",
":",
"value_size",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"local_unpack",
"=",
"struct",
".",
"unpack",
"# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but",
"# not ... | Return a constructor for a decoder for a fixed-width field.
Args:
wire_type: The field's wire type.
format: The format string to pass to struct.unpack(). | [
"Return",
"a",
"constructor",
"for",
"a",
"decoder",
"for",
"a",
"fixed",
"-",
"width",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L263-L285 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _FloatDecoder | def _FloatDecoder():
"""Returns a decoder for a float field.
This code works around a bug in struct.unpack for non-finite 32-bit
floating-point values.
"""
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 32-bit value in little-endian byte order. Bit 1 is the sign
# bit, ... | python | def _FloatDecoder():
"""Returns a decoder for a float field.
This code works around a bug in struct.unpack for non-finite 32-bit
floating-point values.
"""
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 32-bit value in little-endian byte order. Bit 1 is the sign
# bit, ... | [
"def",
"_FloatDecoder",
"(",
")",
":",
"local_unpack",
"=",
"struct",
".",
"unpack",
"def",
"InnerDecode",
"(",
"buffer",
",",
"pos",
")",
":",
"# We expect a 32-bit value in little-endian byte order. Bit 1 is the sign",
"# bit, bits 2-9 represent the exponent, and bits 10-32 ... | Returns a decoder for a float field.
This code works around a bug in struct.unpack for non-finite 32-bit
floating-point values. | [
"Returns",
"a",
"decoder",
"for",
"a",
"float",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L288-L320 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _DoubleDecoder | def _DoubleDecoder():
"""Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number.
"""
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-12 represent the exp... | python | def _DoubleDecoder():
"""Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number.
"""
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-12 represent the exp... | [
"def",
"_DoubleDecoder",
"(",
")",
":",
"local_unpack",
"=",
"struct",
".",
"unpack",
"def",
"InnerDecode",
"(",
"buffer",
",",
"pos",
")",
":",
"# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign",
"# bit, bits 2-12 represent the exponent, and bits 13-6... | Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number. | [
"Returns",
"a",
"decoder",
"for",
"a",
"double",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L323-L350 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | StringDecoder | def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a string field."""
local_DecodeVarint = _DecodeVarint
local_unicode = six.text_type
def _ConvertToUnicode(byte_str):
try:
return local_unicode(byte_str, 'utf-8')
except UnicodeDecodeError as e:
... | python | def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a string field."""
local_DecodeVarint = _DecodeVarint
local_unicode = six.text_type
def _ConvertToUnicode(byte_str):
try:
return local_unicode(byte_str, 'utf-8')
except UnicodeDecodeError as e:
... | [
"def",
"StringDecoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
",",
"key",
",",
"new_default",
")",
":",
"local_DecodeVarint",
"=",
"_DecodeVarint",
"local_unicode",
"=",
"six",
".",
"text_type",
"def",
"_ConvertToUnicode",
"(",
"byte_str",
")"... | Returns a decoder for a string field. | [
"Returns",
"a",
"decoder",
"for",
"a",
"string",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L461-L504 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | BytesDecoder | def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a bytes field."""
local_DecodeVarint = _DecodeVarint
assert not is_packed
if is_repeated:
tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_LENGTH_DELIMITED)
... | python | def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a bytes field."""
local_DecodeVarint = _DecodeVarint
assert not is_packed
if is_repeated:
tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_LENGTH_DELIMITED)
... | [
"def",
"BytesDecoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
",",
"key",
",",
"new_default",
")",
":",
"local_DecodeVarint",
"=",
"_DecodeVarint",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"tag_bytes",
"=",
"encoder",
".",
"Tag... | Returns a decoder for a bytes field. | [
"Returns",
"a",
"decoder",
"for",
"a",
"bytes",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L507-L541 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | GroupDecoder | def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a group field."""
end_tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_END_GROUP)
end_tag_len = len(end_tag_bytes)
assert not is_packed
if is_repeated:
tag... | python | def GroupDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a group field."""
end_tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_END_GROUP)
end_tag_len = len(end_tag_bytes)
assert not is_packed
if is_repeated:
tag... | [
"def",
"GroupDecoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
",",
"key",
",",
"new_default",
")",
":",
"end_tag_bytes",
"=",
"encoder",
".",
"TagBytes",
"(",
"field_number",
",",
"wire_format",
".",
"WIRETYPE_END_GROUP",
")",
"end_tag_len",
... | Returns a decoder for a group field. | [
"Returns",
"a",
"decoder",
"for",
"a",
"group",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L544-L588 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | MapDecoder | def MapDecoder(field_descriptor, new_default, is_message_map):
"""Returns a decoder for a map field."""
key = field_descriptor
tag_bytes = encoder.TagBytes(field_descriptor.number,
wire_format.WIRETYPE_LENGTH_DELIMITED)
tag_len = len(tag_bytes)
local_DecodeVarint = _DecodeVarin... | python | def MapDecoder(field_descriptor, new_default, is_message_map):
"""Returns a decoder for a map field."""
key = field_descriptor
tag_bytes = encoder.TagBytes(field_descriptor.number,
wire_format.WIRETYPE_LENGTH_DELIMITED)
tag_len = len(tag_bytes)
local_DecodeVarint = _DecodeVarin... | [
"def",
"MapDecoder",
"(",
"field_descriptor",
",",
"new_default",
",",
"is_message_map",
")",
":",
"key",
"=",
"field_descriptor",
"tag_bytes",
"=",
"encoder",
".",
"TagBytes",
"(",
"field_descriptor",
".",
"number",
",",
"wire_format",
".",
"WIRETYPE_LENGTH_DELIMIT... | Returns a decoder for a map field. | [
"Returns",
"a",
"decoder",
"for",
"a",
"map",
"field",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L719-L759 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _SkipVarint | def _SkipVarint(buffer, pos, end):
"""Skip a varint value. Returns the new position."""
# Previously ord(buffer[pos]) raised IndexError when pos is out of range.
# With this code, ord(b'') raises TypeError. Both are handled in
# python_message.py to generate a 'Truncated message' error.
while ord(buffer[pos... | python | def _SkipVarint(buffer, pos, end):
"""Skip a varint value. Returns the new position."""
# Previously ord(buffer[pos]) raised IndexError when pos is out of range.
# With this code, ord(b'') raises TypeError. Both are handled in
# python_message.py to generate a 'Truncated message' error.
while ord(buffer[pos... | [
"def",
"_SkipVarint",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"# Previously ord(buffer[pos]) raised IndexError when pos is out of range.",
"# With this code, ord(b'') raises TypeError. Both are handled in",
"# python_message.py to generate a 'Truncated message' error.",
"while",
... | Skip a varint value. Returns the new position. | [
"Skip",
"a",
"varint",
"value",
".",
"Returns",
"the",
"new",
"position",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L765-L775 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _SkipLengthDelimited | def _SkipLengthDelimited(buffer, pos, end):
"""Skip a length-delimited value. Returns the new position."""
(size, pos) = _DecodeVarint(buffer, pos)
pos += size
if pos > end:
raise _DecodeError('Truncated message.')
return pos | python | def _SkipLengthDelimited(buffer, pos, end):
"""Skip a length-delimited value. Returns the new position."""
(size, pos) = _DecodeVarint(buffer, pos)
pos += size
if pos > end:
raise _DecodeError('Truncated message.')
return pos | [
"def",
"_SkipLengthDelimited",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"(",
"size",
",",
"pos",
")",
"=",
"_DecodeVarint",
"(",
"buffer",
",",
"pos",
")",
"pos",
"+=",
"size",
"if",
"pos",
">",
"end",
":",
"raise",
"_DecodeError",
"(",
"'Tru... | Skip a length-delimited value. Returns the new position. | [
"Skip",
"a",
"length",
"-",
"delimited",
"value",
".",
"Returns",
"the",
"new",
"position",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L785-L792 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _SkipGroup | def _SkipGroup(buffer, pos, end):
"""Skip sub-group. Returns the new position."""
while 1:
(tag_bytes, pos) = ReadTag(buffer, pos)
new_pos = SkipField(buffer, pos, end, tag_bytes)
if new_pos == -1:
return pos
pos = new_pos | python | def _SkipGroup(buffer, pos, end):
"""Skip sub-group. Returns the new position."""
while 1:
(tag_bytes, pos) = ReadTag(buffer, pos)
new_pos = SkipField(buffer, pos, end, tag_bytes)
if new_pos == -1:
return pos
pos = new_pos | [
"def",
"_SkipGroup",
"(",
"buffer",
",",
"pos",
",",
"end",
")",
":",
"while",
"1",
":",
"(",
"tag_bytes",
",",
"pos",
")",
"=",
"ReadTag",
"(",
"buffer",
",",
"pos",
")",
"new_pos",
"=",
"SkipField",
"(",
"buffer",
",",
"pos",
",",
"end",
",",
"... | Skip sub-group. Returns the new position. | [
"Skip",
"sub",
"-",
"group",
".",
"Returns",
"the",
"new",
"position",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L794-L802 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py | _FieldSkipper | def _FieldSkipper():
"""Constructs the SkipField function."""
WIRETYPE_TO_SKIPPER = [
_SkipVarint,
_SkipFixed64,
_SkipLengthDelimited,
_SkipGroup,
_EndGroup,
_SkipFixed32,
_RaiseInvalidWireType,
_RaiseInvalidWireType,
]
wiretype_mask = wire_format.TAG_TYPE_M... | python | def _FieldSkipper():
"""Constructs the SkipField function."""
WIRETYPE_TO_SKIPPER = [
_SkipVarint,
_SkipFixed64,
_SkipLengthDelimited,
_SkipGroup,
_EndGroup,
_SkipFixed32,
_RaiseInvalidWireType,
_RaiseInvalidWireType,
]
wiretype_mask = wire_format.TAG_TYPE_M... | [
"def",
"_FieldSkipper",
"(",
")",
":",
"WIRETYPE_TO_SKIPPER",
"=",
"[",
"_SkipVarint",
",",
"_SkipFixed64",
",",
"_SkipLengthDelimited",
",",
"_SkipGroup",
",",
"_EndGroup",
",",
"_SkipFixed32",
",",
"_RaiseInvalidWireType",
",",
"_RaiseInvalidWireType",
",",
"]",
"... | Constructs the SkipField function. | [
"Constructs",
"the",
"SkipField",
"function",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L822-L852 | train |
apple/turicreate | src/external/xgboost/python-package/xgboost/plotting.py | _parse_node | def _parse_node(graph, text):
"""parse dumped node"""
match = _NODEPAT.match(text)
if match is not None:
node = match.group(1)
graph.node(node, label=match.group(2), shape='circle')
return node
match = _LEAFPAT.match(text)
if match is not None:
node = match.group(1)
... | python | def _parse_node(graph, text):
"""parse dumped node"""
match = _NODEPAT.match(text)
if match is not None:
node = match.group(1)
graph.node(node, label=match.group(2), shape='circle')
return node
match = _LEAFPAT.match(text)
if match is not None:
node = match.group(1)
... | [
"def",
"_parse_node",
"(",
"graph",
",",
"text",
")",
":",
"match",
"=",
"_NODEPAT",
".",
"match",
"(",
"text",
")",
"if",
"match",
"is",
"not",
"None",
":",
"node",
"=",
"match",
".",
"group",
"(",
"1",
")",
"graph",
".",
"node",
"(",
"node",
",... | parse dumped node | [
"parse",
"dumped",
"node"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/plotting.py#L109-L121 | train |
apple/turicreate | src/external/xgboost/python-package/xgboost/plotting.py | plot_tree | def plot_tree(booster, num_trees=0, rankdir='UT', ax=None, **kwargs):
"""Plot specified tree.
Parameters
----------
booster : Booster, XGBModel
Booster or XGBModel instance
num_trees : int, default 0
Specify the ordinal number of target tree
rankdir : str, default "UT"
P... | python | def plot_tree(booster, num_trees=0, rankdir='UT', ax=None, **kwargs):
"""Plot specified tree.
Parameters
----------
booster : Booster, XGBModel
Booster or XGBModel instance
num_trees : int, default 0
Specify the ordinal number of target tree
rankdir : str, default "UT"
P... | [
"def",
"plot_tree",
"(",
"booster",
",",
"num_trees",
"=",
"0",
",",
"rankdir",
"=",
"'UT'",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"matplotlib",
".",
"imag... | Plot specified tree.
Parameters
----------
booster : Booster, XGBModel
Booster or XGBModel instance
num_trees : int, default 0
Specify the ordinal number of target tree
rankdir : str, default "UT"
Passed to graphiz via graph_attr
ax : matplotlib Axes, default None
... | [
"Plot",
"specified",
"tree",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/python-package/xgboost/plotting.py#L206-L246 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/manager.py | Manager.construct | def construct (self, properties = [], targets = []):
""" Constructs the dependency graph.
properties: the build properties.
targets: the targets to consider. If none is specified, uses all.
"""
if not targets:
for name, project in self.projects ().project... | python | def construct (self, properties = [], targets = []):
""" Constructs the dependency graph.
properties: the build properties.
targets: the targets to consider. If none is specified, uses all.
"""
if not targets:
for name, project in self.projects ().project... | [
"def",
"construct",
"(",
"self",
",",
"properties",
"=",
"[",
"]",
",",
"targets",
"=",
"[",
"]",
")",
":",
"if",
"not",
"targets",
":",
"for",
"name",
",",
"project",
"in",
"self",
".",
"projects",
"(",
")",
".",
"projects",
"(",
")",
":",
"targ... | Constructs the dependency graph.
properties: the build properties.
targets: the targets to consider. If none is specified, uses all. | [
"Constructs",
"the",
"dependency",
"graph",
".",
"properties",
":",
"the",
"build",
"properties",
".",
"targets",
":",
"the",
"targets",
"to",
"consider",
".",
"If",
"none",
"is",
"specified",
"uses",
"all",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/manager.py#L83-L109 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py | DecisionTreeClassifier.evaluate | def evaluate(self, dataset, metric='auto', missing_value_action='auto'):
"""
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include colum... | python | def evaluate(self, dataset, metric='auto', missing_value_action='auto'):
"""
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include colum... | [
"def",
"evaluate",
"(",
"self",
",",
"dataset",
",",
"metric",
"=",
"'auto'",
",",
"missing_value_action",
"=",
"'auto'",
")",
":",
"_raise_error_evaluation_metric_is_valid",
"(",
"metric",
",",
"[",
"'auto'",
",",
"'accuracy'",
",",
"'confusion_matrix'",
",",
"... | Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the target and features used for model training. Additi... | [
"Evaluate",
"the",
"model",
"by",
"making",
"predictions",
"of",
"target",
"values",
"and",
"comparing",
"these",
"to",
"actual",
"values",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py#L143-L208 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py | DecisionTreeClassifier.predict | def predict(self, dataset, output_type='class', missing_value_action='auto'):
"""
A flexible and advanced prediction API.
The target column is provided during
:func:`~turicreate.decision_tree.create`. If the target column is in the
`dataset` it will be ignored.
Paramete... | python | def predict(self, dataset, output_type='class', missing_value_action='auto'):
"""
A flexible and advanced prediction API.
The target column is provided during
:func:`~turicreate.decision_tree.create`. If the target column is in the
`dataset` it will be ignored.
Paramete... | [
"def",
"predict",
"(",
"self",
",",
"dataset",
",",
"output_type",
"=",
"'class'",
",",
"missing_value_action",
"=",
"'auto'",
")",
":",
"_check_categorical_option_type",
"(",
"'output_type'",
",",
"output_type",
",",
"[",
"'class'",
",",
"'margin'",
",",
"'prob... | A flexible and advanced prediction API.
The target column is provided during
:func:`~turicreate.decision_tree.create`. If the target column is in the
`dataset` it will be ignored.
Parameters
----------
dataset : SFrame
A dataset that has the same columns that ... | [
"A",
"flexible",
"and",
"advanced",
"prediction",
"API",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py#L210-L271 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py | DecisionTreeClassifier.predict_topk | def predict_topk(self, dataset, output_type="probability", k=3, missing_value_action='auto'):
"""
Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability`, `margin`, or `rank`, depen... | python | def predict_topk(self, dataset, output_type="probability", k=3, missing_value_action='auto'):
"""
Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability`, `margin`, or `rank`, depen... | [
"def",
"predict_topk",
"(",
"self",
",",
"dataset",
",",
"output_type",
"=",
"\"probability\"",
",",
"k",
"=",
"3",
",",
"missing_value_action",
"=",
"'auto'",
")",
":",
"_check_categorical_option_type",
"(",
"'output_type'",
",",
"output_type",
",",
"[",
"'rank... | Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability`, `margin`, or `rank`, depending on the ``output_type``
parameter. Input dataset size must be the same as for training of the model.
... | [
"Return",
"top",
"-",
"k",
"predictions",
"for",
"the",
"dataset",
"using",
"the",
"trained",
"model",
".",
"Predictions",
"are",
"returned",
"as",
"an",
"SFrame",
"with",
"three",
"columns",
":",
"id",
"class",
"and",
"probability",
"margin",
"or",
"rank",
... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py#L273-L353 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py | DecisionTreeClassifier.classify | def classify(self, dataset, missing_value_action='auto'):
"""
Return a classification, for each example in the ``dataset``, using the
trained model. The output SFrame contains predictions as class labels
(0 or 1) and probabilities associated with the the example.
Parameters
... | python | def classify(self, dataset, missing_value_action='auto'):
"""
Return a classification, for each example in the ``dataset``, using the
trained model. The output SFrame contains predictions as class labels
(0 or 1) and probabilities associated with the the example.
Parameters
... | [
"def",
"classify",
"(",
"self",
",",
"dataset",
",",
"missing_value_action",
"=",
"'auto'",
")",
":",
"return",
"super",
"(",
"DecisionTreeClassifier",
",",
"self",
")",
".",
"classify",
"(",
"dataset",
",",
"missing_value_action",
"=",
"missing_value_action",
"... | Return a classification, for each example in the ``dataset``, using the
trained model. The output SFrame contains predictions as class labels
(0 or 1) and probabilities associated with the the example.
Parameters
----------
dataset : SFrame
Dataset of new observation... | [
"Return",
"a",
"classification",
"for",
"each",
"example",
"in",
"the",
"dataset",
"using",
"the",
"trained",
"model",
".",
"The",
"output",
"SFrame",
"contains",
"predictions",
"as",
"class",
"labels",
"(",
"0",
"or",
"1",
")",
"and",
"probabilities",
"asso... | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py#L355-L403 | train |
apple/turicreate | src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py | Tracker.slave_envs | def slave_envs(self):
"""
get enviroment variables for slaves
can be passed in as args or envs
"""
if self.hostIP == 'dns':
host = socket.gethostname()
elif self.hostIP == 'ip':
host = socket.gethostbyname(socket.getfqdn())
else:
... | python | def slave_envs(self):
"""
get enviroment variables for slaves
can be passed in as args or envs
"""
if self.hostIP == 'dns':
host = socket.gethostname()
elif self.hostIP == 'ip':
host = socket.gethostbyname(socket.getfqdn())
else:
... | [
"def",
"slave_envs",
"(",
"self",
")",
":",
"if",
"self",
".",
"hostIP",
"==",
"'dns'",
":",
"host",
"=",
"socket",
".",
"gethostname",
"(",
")",
"elif",
"self",
".",
"hostIP",
"==",
"'ip'",
":",
"host",
"=",
"socket",
".",
"gethostbyname",
"(",
"soc... | get enviroment variables for slaves
can be passed in as args or envs | [
"get",
"enviroment",
"variables",
"for",
"slaves",
"can",
"be",
"passed",
"in",
"as",
"args",
"or",
"envs"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py#L144-L156 | train |
apple/turicreate | src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py | Tracker.find_share_ring | def find_share_ring(self, tree_map, parent_map, r):
"""
get a ring structure that tends to share nodes with the tree
return a list starting from r
"""
nset = set(tree_map[r])
cset = nset - set([parent_map[r]])
if len(cset) == 0:
return [r]
rlst... | python | def find_share_ring(self, tree_map, parent_map, r):
"""
get a ring structure that tends to share nodes with the tree
return a list starting from r
"""
nset = set(tree_map[r])
cset = nset - set([parent_map[r]])
if len(cset) == 0:
return [r]
rlst... | [
"def",
"find_share_ring",
"(",
"self",
",",
"tree_map",
",",
"parent_map",
",",
"r",
")",
":",
"nset",
"=",
"set",
"(",
"tree_map",
"[",
"r",
"]",
")",
"cset",
"=",
"nset",
"-",
"set",
"(",
"[",
"parent_map",
"[",
"r",
"]",
"]",
")",
"if",
"len",... | get a ring structure that tends to share nodes with the tree
return a list starting from r | [
"get",
"a",
"ring",
"structure",
"that",
"tends",
"to",
"share",
"nodes",
"with",
"the",
"tree",
"return",
"a",
"list",
"starting",
"from",
"r"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py#L174-L191 | train |
apple/turicreate | src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py | Tracker.get_ring | def get_ring(self, tree_map, parent_map):
"""
get a ring connection used to recover local data
"""
assert parent_map[0] == -1
rlst = self.find_share_ring(tree_map, parent_map, 0)
assert len(rlst) == len(tree_map)
ring_map = {}
nslave = len(tree_map)
... | python | def get_ring(self, tree_map, parent_map):
"""
get a ring connection used to recover local data
"""
assert parent_map[0] == -1
rlst = self.find_share_ring(tree_map, parent_map, 0)
assert len(rlst) == len(tree_map)
ring_map = {}
nslave = len(tree_map)
... | [
"def",
"get_ring",
"(",
"self",
",",
"tree_map",
",",
"parent_map",
")",
":",
"assert",
"parent_map",
"[",
"0",
"]",
"==",
"-",
"1",
"rlst",
"=",
"self",
".",
"find_share_ring",
"(",
"tree_map",
",",
"parent_map",
",",
"0",
")",
"assert",
"len",
"(",
... | get a ring connection used to recover local data | [
"get",
"a",
"ring",
"connection",
"used",
"to",
"recover",
"local",
"data"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py#L193-L206 | train |
apple/turicreate | src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py | Tracker.get_link_map | def get_link_map(self, nslave):
"""
get the link map, this is a bit hacky, call for better algorithm
to place similar nodes together
"""
tree_map, parent_map = self.get_tree(nslave)
ring_map = self.get_ring(tree_map, parent_map)
rmap = {0 : 0}
k = 0
... | python | def get_link_map(self, nslave):
"""
get the link map, this is a bit hacky, call for better algorithm
to place similar nodes together
"""
tree_map, parent_map = self.get_tree(nslave)
ring_map = self.get_ring(tree_map, parent_map)
rmap = {0 : 0}
k = 0
... | [
"def",
"get_link_map",
"(",
"self",
",",
"nslave",
")",
":",
"tree_map",
",",
"parent_map",
"=",
"self",
".",
"get_tree",
"(",
"nslave",
")",
"ring_map",
"=",
"self",
".",
"get_ring",
"(",
"tree_map",
",",
"parent_map",
")",
"rmap",
"=",
"{",
"0",
":",... | get the link map, this is a bit hacky, call for better algorithm
to place similar nodes together | [
"get",
"the",
"link",
"map",
"this",
"is",
"a",
"bit",
"hacky",
"call",
"for",
"better",
"algorithm",
"to",
"place",
"similar",
"nodes",
"together"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py#L208-L233 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/tools/msvc.py | maybe_rewrite_setup | def maybe_rewrite_setup(toolset, setup_script, setup_options, version, rewrite_setup='off'):
"""
Helper rule to generate a faster alternative to MSVC setup scripts.
We used to call MSVC setup scripts directly in every action, however in
newer MSVC versions (10.0+) they make long-lasting registry querie... | python | def maybe_rewrite_setup(toolset, setup_script, setup_options, version, rewrite_setup='off'):
"""
Helper rule to generate a faster alternative to MSVC setup scripts.
We used to call MSVC setup scripts directly in every action, however in
newer MSVC versions (10.0+) they make long-lasting registry querie... | [
"def",
"maybe_rewrite_setup",
"(",
"toolset",
",",
"setup_script",
",",
"setup_options",
",",
"version",
",",
"rewrite_setup",
"=",
"'off'",
")",
":",
"result",
"=",
"'\"{}\" {}'",
".",
"format",
"(",
"setup_script",
",",
"setup_options",
")",
"# At the moment we ... | Helper rule to generate a faster alternative to MSVC setup scripts.
We used to call MSVC setup scripts directly in every action, however in
newer MSVC versions (10.0+) they make long-lasting registry queries
which have a significant impact on build time. | [
"Helper",
"rule",
"to",
"generate",
"a",
"faster",
"alternative",
"to",
"MSVC",
"setup",
"scripts",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/msvc.py#L626-L682 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/classifier/_classifier.py | create | def create(dataset, target, features=None, validation_set = 'auto',
verbose=True):
"""
Automatically create a suitable classifier model based on the provided
training data.
To use specific options of a desired model, use the ``create`` function
of the corresponding model.
Parameters
... | python | def create(dataset, target, features=None, validation_set = 'auto',
verbose=True):
"""
Automatically create a suitable classifier model based on the provided
training data.
To use specific options of a desired model, use the ``create`` function
of the corresponding model.
Parameters
... | [
"def",
"create",
"(",
"dataset",
",",
"target",
",",
"features",
"=",
"None",
",",
"validation_set",
"=",
"'auto'",
",",
"verbose",
"=",
"True",
")",
":",
"return",
"_sl",
".",
"create_classification_with_model_selector",
"(",
"dataset",
",",
"target",
",",
... | Automatically create a suitable classifier model based on the provided
training data.
To use specific options of a desired model, use the ``create`` function
of the corresponding model.
Parameters
----------
dataset : SFrame
Dataset for training the model.
target : string
... | [
"Automatically",
"create",
"a",
"suitable",
"classifier",
"model",
"based",
"on",
"the",
"provided",
"training",
"data",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/_classifier.py#L12-L106 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | GFrame.add_column | def add_column(self, data, column_name="", inplace=False):
"""
Adds the specified column to this SFrame. The number of elements in
the data given must match every other column of the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, return... | python | def add_column(self, data, column_name="", inplace=False):
"""
Adds the specified column to this SFrame. The number of elements in
the data given must match every other column of the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, return... | [
"def",
"add_column",
"(",
"self",
",",
"data",
",",
"column_name",
"=",
"\"\"",
",",
"inplace",
"=",
"False",
")",
":",
"# Check type for pandas dataframe or SArray?",
"if",
"not",
"isinstance",
"(",
"data",
",",
"SArray",
")",
":",
"raise",
"TypeError",
"(",
... | Adds the specified column to this SFrame. The number of elements in
the data given must match every other column of the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the curr... | [
"Adds",
"the",
"specified",
"column",
"to",
"this",
"SFrame",
".",
"The",
"number",
"of",
"elements",
"in",
"the",
"data",
"given",
"must",
"match",
"every",
"other",
"column",
"of",
"the",
"SFrame",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L62-L101 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | GFrame.add_columns | def add_columns(self, data, column_names=None, inplace=False):
"""
Adds columns to the SFrame. The number of elements in all columns must
match every other column of the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFr... | python | def add_columns(self, data, column_names=None, inplace=False):
"""
Adds columns to the SFrame. The number of elements in all columns must
match every other column of the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFr... | [
"def",
"add_columns",
"(",
"self",
",",
"data",
",",
"column_names",
"=",
"None",
",",
"inplace",
"=",
"False",
")",
":",
"datalist",
"=",
"data",
"if",
"isinstance",
"(",
"data",
",",
"SFrame",
")",
":",
"other",
"=",
"data",
"datalist",
"=",
"[",
"... | Adds columns to the SFrame. The number of elements in all columns must
match every other column of the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFram... | [
"Adds",
"columns",
"to",
"the",
"SFrame",
".",
"The",
"number",
"of",
"elements",
"in",
"all",
"columns",
"must",
"match",
"every",
"other",
"column",
"of",
"the",
"SFrame",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L104-L154 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | GFrame.remove_column | def remove_column(self, column_name, inplace=False):
"""
Removes the column with the given name from the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
... | python | def remove_column(self, column_name, inplace=False):
"""
Removes the column with the given name from the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
... | [
"def",
"remove_column",
"(",
"self",
",",
"column_name",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"column_name",
"not",
"in",
"self",
".",
"column_names",
"(",
")",
":",
"raise",
"KeyError",
"(",
"'Cannot find column %s'",
"%",
"column_name",
")",
"if",... | Removes the column with the given name from the SFrame.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, returning self.
Parameters
----------
... | [
"Removes",
"the",
"column",
"with",
"the",
"given",
"name",
"from",
"the",
"SFrame",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L157-L195 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | GFrame.swap_columns | def swap_columns(self, column_name_1, column_name_2, inplace=False):
"""
Swaps the columns with the given names.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
... | python | def swap_columns(self, column_name_1, column_name_2, inplace=False):
"""
Swaps the columns with the given names.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
... | [
"def",
"swap_columns",
"(",
"self",
",",
"column_name_1",
",",
"column_name_2",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"inplace",
":",
"self",
".",
"__is_dirty__",
"=",
"True",
"with",
"cython_context",
"(",
")",
":",
"if",
"self",
".",
"_is_vertex_... | Swaps the columns with the given names.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, returning self.
Parameters
----------
column_name_1 ... | [
"Swaps",
"the",
"columns",
"with",
"the",
"given",
"names",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L211-L243 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | GFrame.rename | def rename(self, names, inplace=False):
"""
Rename the columns using the 'names' dict. This changes the names of
the columns given as the keys and replaces them with the names given as
the values.
If inplace == False (default) this operation does not modify the
current ... | python | def rename(self, names, inplace=False):
"""
Rename the columns using the 'names' dict. This changes the names of
the columns given as the keys and replaces them with the names given as
the values.
If inplace == False (default) this operation does not modify the
current ... | [
"def",
"rename",
"(",
"self",
",",
"names",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"(",
"type",
"(",
"names",
")",
"is",
"not",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"'names must be a dictionary: oldname -> newname'",
")",
"if",
"inplace",
":... | Rename the columns using the 'names' dict. This changes the names of
the columns given as the keys and replaces them with the names given as
the values.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True,... | [
"Rename",
"the",
"columns",
"using",
"the",
"names",
"dict",
".",
"This",
"changes",
"the",
"names",
"of",
"the",
"columns",
"given",
"as",
"the",
"keys",
"and",
"replaces",
"them",
"with",
"the",
"names",
"given",
"as",
"the",
"values",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L245-L279 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | GFrame.num_rows | def num_rows(self):
"""
Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame.
"""
if self._is_vertex_frame():
return self.__graph__.summary()['num_vertices']
elif self._is_edge_frame():
ret... | python | def num_rows(self):
"""
Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame.
"""
if self._is_vertex_frame():
return self.__graph__.summary()['num_vertices']
elif self._is_edge_frame():
ret... | [
"def",
"num_rows",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_vertex_frame",
"(",
")",
":",
"return",
"self",
".",
"__graph__",
".",
"summary",
"(",
")",
"[",
"'num_vertices'",
"]",
"elif",
"self",
".",
"_is_edge_frame",
"(",
")",
":",
"return",
"s... | Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame. | [
"Returns",
"the",
"number",
"of",
"rows",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L321-L333 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | GFrame.column_names | def column_names(self):
"""
Returns the column names.
Returns
-------
out : list[string]
Column names of the SFrame.
"""
if self._is_vertex_frame():
return self.__graph__.__proxy__.get_vertex_fields()
elif self._is_edge_frame():
... | python | def column_names(self):
"""
Returns the column names.
Returns
-------
out : list[string]
Column names of the SFrame.
"""
if self._is_vertex_frame():
return self.__graph__.__proxy__.get_vertex_fields()
elif self._is_edge_frame():
... | [
"def",
"column_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_vertex_frame",
"(",
")",
":",
"return",
"self",
".",
"__graph__",
".",
"__proxy__",
".",
"get_vertex_fields",
"(",
")",
"elif",
"self",
".",
"_is_edge_frame",
"(",
")",
":",
"return",
... | Returns the column names.
Returns
-------
out : list[string]
Column names of the SFrame. | [
"Returns",
"the",
"column",
"names",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L346-L358 | train |
apple/turicreate | src/unity/python/turicreate/data_structures/gframe.py | GFrame.column_types | def column_types(self):
"""
Returns the column types.
Returns
-------
out : list[type]
Column types of the SFrame.
"""
if self.__type__ == VERTEX_GFRAME:
return self.__graph__.__proxy__.get_vertex_field_types()
elif self.__type__ =... | python | def column_types(self):
"""
Returns the column types.
Returns
-------
out : list[type]
Column types of the SFrame.
"""
if self.__type__ == VERTEX_GFRAME:
return self.__graph__.__proxy__.get_vertex_field_types()
elif self.__type__ =... | [
"def",
"column_types",
"(",
"self",
")",
":",
"if",
"self",
".",
"__type__",
"==",
"VERTEX_GFRAME",
":",
"return",
"self",
".",
"__graph__",
".",
"__proxy__",
".",
"get_vertex_field_types",
"(",
")",
"elif",
"self",
".",
"__type__",
"==",
"EDGE_GFRAME",
":",... | Returns the column types.
Returns
-------
out : list[type]
Column types of the SFrame. | [
"Returns",
"the",
"column",
"types",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L360-L372 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/regression/_regression.py | create | def create(dataset, target, features=None, validation_set = 'auto',
verbose=True):
"""
Automatically create a suitable regression model based on the provided
training data.
To use specific options of a desired model, use the ``create`` function
of the corresponding model.
Parameters
... | python | def create(dataset, target, features=None, validation_set = 'auto',
verbose=True):
"""
Automatically create a suitable regression model based on the provided
training data.
To use specific options of a desired model, use the ``create`` function
of the corresponding model.
Parameters
... | [
"def",
"create",
"(",
"dataset",
",",
"target",
",",
"features",
"=",
"None",
",",
"validation_set",
"=",
"'auto'",
",",
"verbose",
"=",
"True",
")",
":",
"dataset",
",",
"validation_set",
"=",
"_validate_data",
"(",
"dataset",
",",
"target",
",",
"feature... | Automatically create a suitable regression model based on the provided
training data.
To use specific options of a desired model, use the ``create`` function
of the corresponding model.
Parameters
----------
dataset : SFrame
Dataset for training the model.
target : str
The... | [
"Automatically",
"create",
"a",
"suitable",
"regression",
"model",
"based",
"on",
"the",
"provided",
"training",
"data",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/regression/_regression.py#L14-L116 | train |
apple/turicreate | src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py | removable | def removable(self, node):
'''
node is removable only if all of its children are as well.
'''
throw_away = []
for child in self.children(node):
throw_away.append(self.visit(child))
if self.mode == 'exclusive':
return all(throw_away)
elif self.mode == 'inclusive':
ret... | python | def removable(self, node):
'''
node is removable only if all of its children are as well.
'''
throw_away = []
for child in self.children(node):
throw_away.append(self.visit(child))
if self.mode == 'exclusive':
return all(throw_away)
elif self.mode == 'inclusive':
ret... | [
"def",
"removable",
"(",
"self",
",",
"node",
")",
":",
"throw_away",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
".",
"children",
"(",
"node",
")",
":",
"throw_away",
".",
"append",
"(",
"self",
".",
"visit",
"(",
"child",
")",
")",
"if",
"self",... | node is removable only if all of its children are as well. | [
"node",
"is",
"removable",
"only",
"if",
"all",
"of",
"its",
"children",
"are",
"as",
"well",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py#L17-L30 | train |
apple/turicreate | src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py | PruneVisitor.reduce | def reduce(self, body):
'''
remove nodes from a list
'''
i = 0
while i < len(body):
stmnt = body[i]
if self.visit(stmnt):
body.pop(i)
else:
i += 1 | python | def reduce(self, body):
'''
remove nodes from a list
'''
i = 0
while i < len(body):
stmnt = body[i]
if self.visit(stmnt):
body.pop(i)
else:
i += 1 | [
"def",
"reduce",
"(",
"self",
",",
"body",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"body",
")",
":",
"stmnt",
"=",
"body",
"[",
"i",
"]",
"if",
"self",
".",
"visit",
"(",
"stmnt",
")",
":",
"body",
".",
"pop",
"(",
"i",
")",... | remove nodes from a list | [
"remove",
"nodes",
"from",
"a",
"list"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py#L52-L62 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/audio_analysis/audio_analysis.py | load_audio | def load_audio(path, with_path=True, recursive=True, ignore_failure=True, random_order=False):
"""
Loads WAV file(s) from a path.
Parameters
----------
path : str
Path to WAV files to be loaded.
with_path : bool, optional
Indicates whether a path column is added to the returned... | python | def load_audio(path, with_path=True, recursive=True, ignore_failure=True, random_order=False):
"""
Loads WAV file(s) from a path.
Parameters
----------
path : str
Path to WAV files to be loaded.
with_path : bool, optional
Indicates whether a path column is added to the returned... | [
"def",
"load_audio",
"(",
"path",
",",
"with_path",
"=",
"True",
",",
"recursive",
"=",
"True",
",",
"ignore_failure",
"=",
"True",
",",
"random_order",
"=",
"False",
")",
":",
"from",
"scipy",
".",
"io",
"import",
"wavfile",
"as",
"_wavfile",
"all_wav_fil... | Loads WAV file(s) from a path.
Parameters
----------
path : str
Path to WAV files to be loaded.
with_path : bool, optional
Indicates whether a path column is added to the returned SFrame.
recursive : bool, optional
Indicates whether ``load_audio`` should do a recursive dir... | [
"Loads",
"WAV",
"file",
"(",
"s",
")",
"from",
"a",
"path",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/audio_analysis/audio_analysis.py#L21-L95 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/symbol_database.py | SymbolDatabase.RegisterMessage | def RegisterMessage(self, message):
"""Registers the given message type in the local database.
Calls to GetSymbol() and GetMessages() will return messages registered here.
Args:
message: a message.Message, to be registered.
Returns:
The provided message.
"""
desc = message.DESCRI... | python | def RegisterMessage(self, message):
"""Registers the given message type in the local database.
Calls to GetSymbol() and GetMessages() will return messages registered here.
Args:
message: a message.Message, to be registered.
Returns:
The provided message.
"""
desc = message.DESCRI... | [
"def",
"RegisterMessage",
"(",
"self",
",",
"message",
")",
":",
"desc",
"=",
"message",
".",
"DESCRIPTOR",
"self",
".",
"_classes",
"[",
"desc",
".",
"full_name",
"]",
"=",
"message",
"self",
".",
"pool",
".",
"AddDescriptor",
"(",
"desc",
")",
"return"... | Registers the given message type in the local database.
Calls to GetSymbol() and GetMessages() will return messages registered here.
Args:
message: a message.Message, to be registered.
Returns:
The provided message. | [
"Registers",
"the",
"given",
"message",
"type",
"in",
"the",
"local",
"database",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/symbol_database.py#L68-L83 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/symbol_database.py | SymbolDatabase.GetMessages | def GetMessages(self, files):
# TODO(amauryfa): Fix the differences with MessageFactory.
"""Gets all registered messages from a specified file.
Only messages already created and registered will be returned; (this is the
case for imported _pb2 modules)
But unlike MessageFactory, this version also re... | python | def GetMessages(self, files):
# TODO(amauryfa): Fix the differences with MessageFactory.
"""Gets all registered messages from a specified file.
Only messages already created and registered will be returned; (this is the
case for imported _pb2 modules)
But unlike MessageFactory, this version also re... | [
"def",
"GetMessages",
"(",
"self",
",",
"files",
")",
":",
"# TODO(amauryfa): Fix the differences with MessageFactory.",
"def",
"_GetAllMessageNames",
"(",
"desc",
")",
":",
"\"\"\"Walk a message Descriptor and recursively yields all message names.\"\"\"",
"yield",
"desc",
".",
... | Gets all registered messages from a specified file.
Only messages already created and registered will be returned; (this is the
case for imported _pb2 modules)
But unlike MessageFactory, this version also returns already defined nested
messages, but does not register any message extensions.
Args:
... | [
"Gets",
"all",
"registered",
"messages",
"from",
"a",
"specified",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/symbol_database.py#L137-L173 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/object_detector/util/_visualization.py | _string_hash | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | python | def _string_hash(s):
"""String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`)."""
h = 5381
for c in s:
h = h * 33 + ord(c)
return h | [
"def",
"_string_hash",
"(",
"s",
")",
":",
"h",
"=",
"5381",
"for",
"c",
"in",
"s",
":",
"h",
"=",
"h",
"*",
"33",
"+",
"ord",
"(",
"c",
")",
"return",
"h"
] | String hash (djb2) with consistency between py2/py3 and persistency between runs (unlike `hash`). | [
"String",
"hash",
"(",
"djb2",
")",
"with",
"consistency",
"between",
"py2",
"/",
"py3",
"and",
"persistency",
"between",
"runs",
"(",
"unlike",
"hash",
")",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/object_detector/util/_visualization.py#L14-L19 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/object_detector/util/_visualization.py | draw_bounding_boxes | def draw_bounding_boxes(images, annotations, confidence_threshold=0):
"""
Visualizes bounding boxes (ground truth or predictions) by
returning annotated copies of the images.
Parameters
----------
images: SArray or Image
An `SArray` of type `Image`. A single `Image` instance may also be... | python | def draw_bounding_boxes(images, annotations, confidence_threshold=0):
"""
Visualizes bounding boxes (ground truth or predictions) by
returning annotated copies of the images.
Parameters
----------
images: SArray or Image
An `SArray` of type `Image`. A single `Image` instance may also be... | [
"def",
"draw_bounding_boxes",
"(",
"images",
",",
"annotations",
",",
"confidence_threshold",
"=",
"0",
")",
":",
"_numeric_param_check_range",
"(",
"'confidence_threshold'",
",",
"confidence_threshold",
",",
"0.0",
",",
"1.0",
")",
"from",
"PIL",
"import",
"Image",... | Visualizes bounding boxes (ground truth or predictions) by
returning annotated copies of the images.
Parameters
----------
images: SArray or Image
An `SArray` of type `Image`. A single `Image` instance may also be
given.
annotations: SArray or list
An `SArray` of annotation... | [
"Visualizes",
"bounding",
"boxes",
"(",
"ground",
"truth",
"or",
"predictions",
")",
"by",
"returning",
"annotated",
"copies",
"of",
"the",
"images",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/object_detector/util/_visualization.py#L94-L151 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_supervised_learning.py | create | def create(dataset, target, model_name, features=None,
validation_set='auto', distributed='auto',
verbose=True, seed=None, **kwargs):
"""
Create a :class:`~turicreate.toolkits.SupervisedLearningModel`,
This is generic function that allows you to create any model that
implements Su... | python | def create(dataset, target, model_name, features=None,
validation_set='auto', distributed='auto',
verbose=True, seed=None, **kwargs):
"""
Create a :class:`~turicreate.toolkits.SupervisedLearningModel`,
This is generic function that allows you to create any model that
implements Su... | [
"def",
"create",
"(",
"dataset",
",",
"target",
",",
"model_name",
",",
"features",
"=",
"None",
",",
"validation_set",
"=",
"'auto'",
",",
"distributed",
"=",
"'auto'",
",",
"verbose",
"=",
"True",
",",
"seed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")... | Create a :class:`~turicreate.toolkits.SupervisedLearningModel`,
This is generic function that allows you to create any model that
implements SupervisedLearningModel This function is normally not called, call
specific model's create function instead
Parameters
----------
dataset : SFrame
... | [
"Create",
"a",
":",
"class",
":",
"~turicreate",
".",
"toolkits",
".",
"SupervisedLearningModel"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_supervised_learning.py#L261-L334 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.