repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
MillionIntegrals/vel | vel/util/network.py | convolutional_layer_series | def convolutional_layer_series(initial_size, layer_sequence):
""" Execute a series of convolutional layer transformations to the size number """
size = initial_size
for filter_size, padding, stride in layer_sequence:
size = convolution_size_equation(size, filter_size, padding, stride)
return size | python | def convolutional_layer_series(initial_size, layer_sequence):
""" Execute a series of convolutional layer transformations to the size number """
size = initial_size
for filter_size, padding, stride in layer_sequence:
size = convolution_size_equation(size, filter_size, padding, stride)
return size | [
"def",
"convolutional_layer_series",
"(",
"initial_size",
",",
"layer_sequence",
")",
":",
"size",
"=",
"initial_size",
"for",
"filter_size",
",",
"padding",
",",
"stride",
"in",
"layer_sequence",
":",
"size",
"=",
"convolution_size_equation",
"(",
"size",
",",
"filter_size",
",",
"padding",
",",
"stride",
")",
"return",
"size"
] | Execute a series of convolutional layer transformations to the size number | [
"Execute",
"a",
"series",
"of",
"convolutional",
"layer",
"transformations",
"to",
"the",
"size",
"number"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/network.py#L34-L41 | train | 232,400 |
MillionIntegrals/vel | vel/api/model.py | Model.train | def train(self, mode=True):
r"""
Sets the module in training mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
etc.
Returns:
Module: self
"""
super().train(mode)
if mode:
mu.apply_leaf(self, mu.set_train_mode)
return self | python | def train(self, mode=True):
r"""
Sets the module in training mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
etc.
Returns:
Module: self
"""
super().train(mode)
if mode:
mu.apply_leaf(self, mu.set_train_mode)
return self | [
"def",
"train",
"(",
"self",
",",
"mode",
"=",
"True",
")",
":",
"super",
"(",
")",
".",
"train",
"(",
"mode",
")",
"if",
"mode",
":",
"mu",
".",
"apply_leaf",
"(",
"self",
",",
"mu",
".",
"set_train_mode",
")",
"return",
"self"
] | r"""
Sets the module in training mode.
This has any effect only on certain modules. See documentations of
particular modules for details of their behaviors in training/evaluation
mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
etc.
Returns:
Module: self | [
"r",
"Sets",
"the",
"module",
"in",
"training",
"mode",
"."
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L18-L35 | train | 232,401 |
MillionIntegrals/vel | vel/api/model.py | Model.summary | def summary(self, input_size=None, hashsummary=False):
""" Print a model summary """
if input_size is None:
print(self)
print("-" * 120)
number = sum(p.numel() for p in self.model.parameters())
print("Number of model parameters: {:,}".format(number))
print("-" * 120)
else:
summary(self, input_size)
if hashsummary:
for idx, hashvalue in enumerate(self.hashsummary()):
print(f"{idx}: {hashvalue}") | python | def summary(self, input_size=None, hashsummary=False):
""" Print a model summary """
if input_size is None:
print(self)
print("-" * 120)
number = sum(p.numel() for p in self.model.parameters())
print("Number of model parameters: {:,}".format(number))
print("-" * 120)
else:
summary(self, input_size)
if hashsummary:
for idx, hashvalue in enumerate(self.hashsummary()):
print(f"{idx}: {hashvalue}") | [
"def",
"summary",
"(",
"self",
",",
"input_size",
"=",
"None",
",",
"hashsummary",
"=",
"False",
")",
":",
"if",
"input_size",
"is",
"None",
":",
"print",
"(",
"self",
")",
"print",
"(",
"\"-\"",
"*",
"120",
")",
"number",
"=",
"sum",
"(",
"p",
".",
"numel",
"(",
")",
"for",
"p",
"in",
"self",
".",
"model",
".",
"parameters",
"(",
")",
")",
"print",
"(",
"\"Number of model parameters: {:,}\"",
".",
"format",
"(",
"number",
")",
")",
"print",
"(",
"\"-\"",
"*",
"120",
")",
"else",
":",
"summary",
"(",
"self",
",",
"input_size",
")",
"if",
"hashsummary",
":",
"for",
"idx",
",",
"hashvalue",
"in",
"enumerate",
"(",
"self",
".",
"hashsummary",
"(",
")",
")",
":",
"print",
"(",
"f\"{idx}: {hashvalue}\"",
")"
] | Print a model summary | [
"Print",
"a",
"model",
"summary"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L37-L51 | train | 232,402 |
MillionIntegrals/vel | vel/api/model.py | Model.hashsummary | def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()).hexdigest() for x in child.parameters())
return result | python | def hashsummary(self):
""" Print a model summary - checksums of each layer parameters """
children = list(self.children())
result = []
for child in children:
result.extend(hashlib.sha256(x.detach().cpu().numpy().tobytes()).hexdigest() for x in child.parameters())
return result | [
"def",
"hashsummary",
"(",
"self",
")",
":",
"children",
"=",
"list",
"(",
"self",
".",
"children",
"(",
")",
")",
"result",
"=",
"[",
"]",
"for",
"child",
"in",
"children",
":",
"result",
".",
"extend",
"(",
"hashlib",
".",
"sha256",
"(",
"x",
".",
"detach",
"(",
")",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
".",
"tobytes",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"for",
"x",
"in",
"child",
".",
"parameters",
"(",
")",
")",
"return",
"result"
] | Print a model summary - checksums of each layer parameters | [
"Print",
"a",
"model",
"summary",
"-",
"checksums",
"of",
"each",
"layer",
"parameters"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L53-L62 | train | 232,403 |
MillionIntegrals/vel | vel/api/model.py | RnnLinearBackboneModel.zero_state | def zero_state(self, batch_size):
""" Initial state of the network """
return torch.zeros(batch_size, self.state_dim, dtype=torch.float32) | python | def zero_state(self, batch_size):
""" Initial state of the network """
return torch.zeros(batch_size, self.state_dim, dtype=torch.float32) | [
"def",
"zero_state",
"(",
"self",
",",
"batch_size",
")",
":",
"return",
"torch",
".",
"zeros",
"(",
"batch_size",
",",
"self",
".",
"state_dim",
",",
"dtype",
"=",
"torch",
".",
"float32",
")"
] | Initial state of the network | [
"Initial",
"state",
"of",
"the",
"network"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L121-L123 | train | 232,404 |
MillionIntegrals/vel | vel/api/model.py | SupervisedModel.loss | def loss(self, x_data, y_true):
""" Forward propagate network and return a value of loss function """
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred) | python | def loss(self, x_data, y_true):
""" Forward propagate network and return a value of loss function """
y_pred = self(x_data)
return y_pred, self.loss_value(x_data, y_true, y_pred) | [
"def",
"loss",
"(",
"self",
",",
"x_data",
",",
"y_true",
")",
":",
"y_pred",
"=",
"self",
"(",
"x_data",
")",
"return",
"y_pred",
",",
"self",
".",
"loss_value",
"(",
"x_data",
",",
"y_true",
",",
"y_pred",
")"
] | Forward propagate network and return a value of loss function | [
"Forward",
"propagate",
"network",
"and",
"return",
"a",
"value",
"of",
"loss",
"function"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/api/model.py#L139-L142 | train | 232,405 |
MillionIntegrals/vel | vel/models/vision/cifar_resnet_v2.py | ResNetV2.metrics | def metrics(self):
""" Set of metrics for this model """
from vel.metrics.loss_metric import Loss
from vel.metrics.accuracy import Accuracy
return [Loss(), Accuracy()] | python | def metrics(self):
""" Set of metrics for this model """
from vel.metrics.loss_metric import Loss
from vel.metrics.accuracy import Accuracy
return [Loss(), Accuracy()] | [
"def",
"metrics",
"(",
"self",
")",
":",
"from",
"vel",
".",
"metrics",
".",
"loss_metric",
"import",
"Loss",
"from",
"vel",
".",
"metrics",
".",
"accuracy",
"import",
"Accuracy",
"return",
"[",
"Loss",
"(",
")",
",",
"Accuracy",
"(",
")",
"]"
] | Set of metrics for this model | [
"Set",
"of",
"metrics",
"for",
"this",
"model"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/vision/cifar_resnet_v2.py#L77-L81 | train | 232,406 |
MillionIntegrals/vel | vel/util/tensor_util.py | one_hot_encoding | def one_hot_encoding(input_tensor, num_labels):
""" One-hot encode labels from input """
xview = input_tensor.view(-1, 1).to(torch.long)
onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)
onehot.scatter_(1, xview, 1)
return onehot.view(list(input_tensor.shape) + [-1]) | python | def one_hot_encoding(input_tensor, num_labels):
""" One-hot encode labels from input """
xview = input_tensor.view(-1, 1).to(torch.long)
onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)
onehot.scatter_(1, xview, 1)
return onehot.view(list(input_tensor.shape) + [-1]) | [
"def",
"one_hot_encoding",
"(",
"input_tensor",
",",
"num_labels",
")",
":",
"xview",
"=",
"input_tensor",
".",
"view",
"(",
"-",
"1",
",",
"1",
")",
".",
"to",
"(",
"torch",
".",
"long",
")",
"onehot",
"=",
"torch",
".",
"zeros",
"(",
"xview",
".",
"size",
"(",
"0",
")",
",",
"num_labels",
",",
"device",
"=",
"input_tensor",
".",
"device",
",",
"dtype",
"=",
"torch",
".",
"float",
")",
"onehot",
".",
"scatter_",
"(",
"1",
",",
"xview",
",",
"1",
")",
"return",
"onehot",
".",
"view",
"(",
"list",
"(",
"input_tensor",
".",
"shape",
")",
"+",
"[",
"-",
"1",
"]",
")"
] | One-hot encode labels from input | [
"One",
"-",
"hot",
"encode",
"labels",
"from",
"input"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/tensor_util.py#L4-L10 | train | 232,407 |
MillionIntegrals/vel | vel/util/tensor_util.py | merge_first_two_dims | def merge_first_two_dims(tensor):
""" Reshape tensor to merge first two dimensions """
shape = tensor.shape
batch_size = shape[0] * shape[1]
new_shape = tuple([batch_size] + list(shape[2:]))
return tensor.view(new_shape) | python | def merge_first_two_dims(tensor):
""" Reshape tensor to merge first two dimensions """
shape = tensor.shape
batch_size = shape[0] * shape[1]
new_shape = tuple([batch_size] + list(shape[2:]))
return tensor.view(new_shape) | [
"def",
"merge_first_two_dims",
"(",
"tensor",
")",
":",
"shape",
"=",
"tensor",
".",
"shape",
"batch_size",
"=",
"shape",
"[",
"0",
"]",
"*",
"shape",
"[",
"1",
"]",
"new_shape",
"=",
"tuple",
"(",
"[",
"batch_size",
"]",
"+",
"list",
"(",
"shape",
"[",
"2",
":",
"]",
")",
")",
"return",
"tensor",
".",
"view",
"(",
"new_shape",
")"
] | Reshape tensor to merge first two dimensions | [
"Reshape",
"tensor",
"to",
"merge",
"first",
"two",
"dimensions"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/tensor_util.py#L13-L18 | train | 232,408 |
MillionIntegrals/vel | vel/rl/vecenv/dummy.py | DummyVecEnvWrapper.instantiate | def instantiate(self, parallel_envs, seed=0, preset='default') -> VecEnv:
""" Create vectorized environments """
envs = DummyVecEnv([self._creation_function(i, seed, preset) for i in range(parallel_envs)])
if self.frame_history is not None:
envs = VecFrameStack(envs, self.frame_history)
return envs | python | def instantiate(self, parallel_envs, seed=0, preset='default') -> VecEnv:
""" Create vectorized environments """
envs = DummyVecEnv([self._creation_function(i, seed, preset) for i in range(parallel_envs)])
if self.frame_history is not None:
envs = VecFrameStack(envs, self.frame_history)
return envs | [
"def",
"instantiate",
"(",
"self",
",",
"parallel_envs",
",",
"seed",
"=",
"0",
",",
"preset",
"=",
"'default'",
")",
"->",
"VecEnv",
":",
"envs",
"=",
"DummyVecEnv",
"(",
"[",
"self",
".",
"_creation_function",
"(",
"i",
",",
"seed",
",",
"preset",
")",
"for",
"i",
"in",
"range",
"(",
"parallel_envs",
")",
"]",
")",
"if",
"self",
".",
"frame_history",
"is",
"not",
"None",
":",
"envs",
"=",
"VecFrameStack",
"(",
"envs",
",",
"self",
".",
"frame_history",
")",
"return",
"envs"
] | Create vectorized environments | [
"Create",
"vectorized",
"environments"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/vecenv/dummy.py#L16-L23 | train | 232,409 |
MillionIntegrals/vel | vel/rl/vecenv/dummy.py | DummyVecEnvWrapper.instantiate_single | def instantiate_single(self, seed=0, preset='default'):
""" Create a new Env instance - single """
env = self.env.instantiate(seed=seed, serial_id=0, preset=preset)
if self.frame_history is not None:
env = FrameStack(env, self.frame_history)
return env | python | def instantiate_single(self, seed=0, preset='default'):
""" Create a new Env instance - single """
env = self.env.instantiate(seed=seed, serial_id=0, preset=preset)
if self.frame_history is not None:
env = FrameStack(env, self.frame_history)
return env | [
"def",
"instantiate_single",
"(",
"self",
",",
"seed",
"=",
"0",
",",
"preset",
"=",
"'default'",
")",
":",
"env",
"=",
"self",
".",
"env",
".",
"instantiate",
"(",
"seed",
"=",
"seed",
",",
"serial_id",
"=",
"0",
",",
"preset",
"=",
"preset",
")",
"if",
"self",
".",
"frame_history",
"is",
"not",
"None",
":",
"env",
"=",
"FrameStack",
"(",
"env",
",",
"self",
".",
"frame_history",
")",
"return",
"env"
] | Create a new Env instance - single | [
"Create",
"a",
"new",
"Env",
"instance",
"-",
"single"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/vecenv/dummy.py#L25-L32 | train | 232,410 |
MillionIntegrals/vel | vel/rl/vecenv/dummy.py | DummyVecEnvWrapper._creation_function | def _creation_function(self, idx, seed, preset):
""" Helper function to create a proper closure around supplied values """
return lambda: self.env.instantiate(seed=seed, serial_id=idx, preset=preset) | python | def _creation_function(self, idx, seed, preset):
""" Helper function to create a proper closure around supplied values """
return lambda: self.env.instantiate(seed=seed, serial_id=idx, preset=preset) | [
"def",
"_creation_function",
"(",
"self",
",",
"idx",
",",
"seed",
",",
"preset",
")",
":",
"return",
"lambda",
":",
"self",
".",
"env",
".",
"instantiate",
"(",
"seed",
"=",
"seed",
",",
"serial_id",
"=",
"idx",
",",
"preset",
"=",
"preset",
")"
] | Helper function to create a proper closure around supplied values | [
"Helper",
"function",
"to",
"create",
"a",
"proper",
"closure",
"around",
"supplied",
"values"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/vecenv/dummy.py#L34-L36 | train | 232,411 |
MillionIntegrals/vel | vel/rl/models/stochastic_policy_model_separate.py | StochasticPolicyModelSeparate.policy | def policy(self, observations):
""" Calculate only action head for given state """
input_data = self.input_block(observations)
policy_base_output = self.policy_backbone(input_data)
policy_params = self.action_head(policy_base_output)
return policy_params | python | def policy(self, observations):
""" Calculate only action head for given state """
input_data = self.input_block(observations)
policy_base_output = self.policy_backbone(input_data)
policy_params = self.action_head(policy_base_output)
return policy_params | [
"def",
"policy",
"(",
"self",
",",
"observations",
")",
":",
"input_data",
"=",
"self",
".",
"input_block",
"(",
"observations",
")",
"policy_base_output",
"=",
"self",
".",
"policy_backbone",
"(",
"input_data",
")",
"policy_params",
"=",
"self",
".",
"action_head",
"(",
"policy_base_output",
")",
"return",
"policy_params"
] | Calculate only action head for given state | [
"Calculate",
"only",
"action",
"head",
"for",
"given",
"state"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/models/stochastic_policy_model_separate.py#L85-L90 | train | 232,412 |
MillionIntegrals/vel | vel/phase/cycle.py | CycleCallback._init_cycle_dict | def _init_cycle_dict(self):
""" Populate a cycle dict """
dict_arr = np.zeros(self.epochs, dtype=int)
length_arr = np.zeros(self.epochs, dtype=int)
start_arr = np.zeros(self.epochs, dtype=int)
c_len = self.cycle_len
idx = 0
for i in range(self.cycles):
current_start = idx
for j in range(c_len):
dict_arr[idx] = i
length_arr[idx] = c_len
start_arr[idx] = current_start
idx += 1
c_len *= self.cycle_mult
return dict_arr, length_arr, start_arr | python | def _init_cycle_dict(self):
""" Populate a cycle dict """
dict_arr = np.zeros(self.epochs, dtype=int)
length_arr = np.zeros(self.epochs, dtype=int)
start_arr = np.zeros(self.epochs, dtype=int)
c_len = self.cycle_len
idx = 0
for i in range(self.cycles):
current_start = idx
for j in range(c_len):
dict_arr[idx] = i
length_arr[idx] = c_len
start_arr[idx] = current_start
idx += 1
c_len *= self.cycle_mult
return dict_arr, length_arr, start_arr | [
"def",
"_init_cycle_dict",
"(",
"self",
")",
":",
"dict_arr",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"epochs",
",",
"dtype",
"=",
"int",
")",
"length_arr",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"epochs",
",",
"dtype",
"=",
"int",
")",
"start_arr",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"epochs",
",",
"dtype",
"=",
"int",
")",
"c_len",
"=",
"self",
".",
"cycle_len",
"idx",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"cycles",
")",
":",
"current_start",
"=",
"idx",
"for",
"j",
"in",
"range",
"(",
"c_len",
")",
":",
"dict_arr",
"[",
"idx",
"]",
"=",
"i",
"length_arr",
"[",
"idx",
"]",
"=",
"c_len",
"start_arr",
"[",
"idx",
"]",
"=",
"current_start",
"idx",
"+=",
"1",
"c_len",
"*=",
"self",
".",
"cycle_mult",
"return",
"dict_arr",
",",
"length_arr",
",",
"start_arr"
] | Populate a cycle dict | [
"Populate",
"a",
"cycle",
"dict"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/phase/cycle.py#L34-L53 | train | 232,413 |
MillionIntegrals/vel | vel/phase/cycle.py | CycleCallback.on_batch_begin | def on_batch_begin(self, batch_info: BatchInfo):
""" Set proper learning rate """
cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1]
cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1]
numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch_info.batches_per_epoch + batch_info.batch_number
denominator = cycle_length * batch_info.batches_per_epoch
interpolation_number = numerator / denominator
if cycle_start == 0 and numerator < self.init_iter:
lr = self.init_lr
else:
if isinstance(self.max_lr, list):
lr = [interp.interpolate_single(max_lr, min_lr, interpolation_number, how=self.interpolate) for max_lr, min_lr in zip(self.max_lr, self.min_lr)]
else:
lr = interp.interpolate_single(self.max_lr, self.min_lr, interpolation_number, how=self.interpolate)
self.set_lr(lr) | python | def on_batch_begin(self, batch_info: BatchInfo):
""" Set proper learning rate """
cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1]
cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1]
numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch_info.batches_per_epoch + batch_info.batch_number
denominator = cycle_length * batch_info.batches_per_epoch
interpolation_number = numerator / denominator
if cycle_start == 0 and numerator < self.init_iter:
lr = self.init_lr
else:
if isinstance(self.max_lr, list):
lr = [interp.interpolate_single(max_lr, min_lr, interpolation_number, how=self.interpolate) for max_lr, min_lr in zip(self.max_lr, self.min_lr)]
else:
lr = interp.interpolate_single(self.max_lr, self.min_lr, interpolation_number, how=self.interpolate)
self.set_lr(lr) | [
"def",
"on_batch_begin",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"cycle_length",
"=",
"self",
".",
"cycle_lengths",
"[",
"batch_info",
".",
"local_epoch_number",
"-",
"1",
"]",
"cycle_start",
"=",
"self",
".",
"cycle_starts",
"[",
"batch_info",
".",
"local_epoch_number",
"-",
"1",
"]",
"numerator",
"=",
"(",
"batch_info",
".",
"local_epoch_number",
"-",
"cycle_start",
"-",
"1",
")",
"*",
"batch_info",
".",
"batches_per_epoch",
"+",
"batch_info",
".",
"batch_number",
"denominator",
"=",
"cycle_length",
"*",
"batch_info",
".",
"batches_per_epoch",
"interpolation_number",
"=",
"numerator",
"/",
"denominator",
"if",
"cycle_start",
"==",
"0",
"and",
"numerator",
"<",
"self",
".",
"init_iter",
":",
"lr",
"=",
"self",
".",
"init_lr",
"else",
":",
"if",
"isinstance",
"(",
"self",
".",
"max_lr",
",",
"list",
")",
":",
"lr",
"=",
"[",
"interp",
".",
"interpolate_single",
"(",
"max_lr",
",",
"min_lr",
",",
"interpolation_number",
",",
"how",
"=",
"self",
".",
"interpolate",
")",
"for",
"max_lr",
",",
"min_lr",
"in",
"zip",
"(",
"self",
".",
"max_lr",
",",
"self",
".",
"min_lr",
")",
"]",
"else",
":",
"lr",
"=",
"interp",
".",
"interpolate_single",
"(",
"self",
".",
"max_lr",
",",
"self",
".",
"min_lr",
",",
"interpolation_number",
",",
"how",
"=",
"self",
".",
"interpolate",
")",
"self",
".",
"set_lr",
"(",
"lr",
")"
] | Set proper learning rate | [
"Set",
"proper",
"learning",
"rate"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/phase/cycle.py#L55-L73 | train | 232,414 |
MillionIntegrals/vel | vel/phase/cycle.py | CycleCallback.set_lr | def set_lr(self, lr):
""" Set a learning rate for the optimizer """
if isinstance(lr, list):
for group_lr, param_group in zip(lr, self.optimizer.param_groups):
param_group['lr'] = group_lr
else:
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr | python | def set_lr(self, lr):
""" Set a learning rate for the optimizer """
if isinstance(lr, list):
for group_lr, param_group in zip(lr, self.optimizer.param_groups):
param_group['lr'] = group_lr
else:
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr | [
"def",
"set_lr",
"(",
"self",
",",
"lr",
")",
":",
"if",
"isinstance",
"(",
"lr",
",",
"list",
")",
":",
"for",
"group_lr",
",",
"param_group",
"in",
"zip",
"(",
"lr",
",",
"self",
".",
"optimizer",
".",
"param_groups",
")",
":",
"param_group",
"[",
"'lr'",
"]",
"=",
"group_lr",
"else",
":",
"for",
"param_group",
"in",
"self",
".",
"optimizer",
".",
"param_groups",
":",
"param_group",
"[",
"'lr'",
"]",
"=",
"lr"
] | Set a learning rate for the optimizer | [
"Set",
"a",
"learning",
"rate",
"for",
"the",
"optimizer"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/phase/cycle.py#L75-L82 | train | 232,415 |
MillionIntegrals/vel | vel/internals/parser.py | Variable.parameter_constructor | def parameter_constructor(cls, loader, node):
""" Construct variable instance from yaml node """
value = loader.construct_scalar(node)
if isinstance(value, str):
if '=' in value:
(varname, varvalue) = Parser.parse_equality(value)
return cls(varname, varvalue)
else:
return cls(value)
else:
return cls(value) | python | def parameter_constructor(cls, loader, node):
""" Construct variable instance from yaml node """
value = loader.construct_scalar(node)
if isinstance(value, str):
if '=' in value:
(varname, varvalue) = Parser.parse_equality(value)
return cls(varname, varvalue)
else:
return cls(value)
else:
return cls(value) | [
"def",
"parameter_constructor",
"(",
"cls",
",",
"loader",
",",
"node",
")",
":",
"value",
"=",
"loader",
".",
"construct_scalar",
"(",
"node",
")",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"if",
"'='",
"in",
"value",
":",
"(",
"varname",
",",
"varvalue",
")",
"=",
"Parser",
".",
"parse_equality",
"(",
"value",
")",
"return",
"cls",
"(",
"varname",
",",
"varvalue",
")",
"else",
":",
"return",
"cls",
"(",
"value",
")",
"else",
":",
"return",
"cls",
"(",
"value",
")"
] | Construct variable instance from yaml node | [
"Construct",
"variable",
"instance",
"from",
"yaml",
"node"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/parser.py#L18-L29 | train | 232,416 |
MillionIntegrals/vel | vel/internals/parser.py | Parser.register | def register(cls):
""" Register variable handling in YAML """
if not cls.IS_LOADED:
cls.IS_LOADED = True
yaml.add_constructor('!param', Parameter.parameter_constructor, Loader=yaml.SafeLoader)
yaml.add_constructor('!env', EnvironmentVariable.parameter_constructor, Loader=yaml.SafeLoader) | python | def register(cls):
""" Register variable handling in YAML """
if not cls.IS_LOADED:
cls.IS_LOADED = True
yaml.add_constructor('!param', Parameter.parameter_constructor, Loader=yaml.SafeLoader)
yaml.add_constructor('!env', EnvironmentVariable.parameter_constructor, Loader=yaml.SafeLoader) | [
"def",
"register",
"(",
"cls",
")",
":",
"if",
"not",
"cls",
".",
"IS_LOADED",
":",
"cls",
".",
"IS_LOADED",
"=",
"True",
"yaml",
".",
"add_constructor",
"(",
"'!param'",
",",
"Parameter",
".",
"parameter_constructor",
",",
"Loader",
"=",
"yaml",
".",
"SafeLoader",
")",
"yaml",
".",
"add_constructor",
"(",
"'!env'",
",",
"EnvironmentVariable",
".",
"parameter_constructor",
",",
"Loader",
"=",
"yaml",
".",
"SafeLoader",
")"
] | Register variable handling in YAML | [
"Register",
"variable",
"handling",
"in",
"YAML"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/parser.py#L74-L80 | train | 232,417 |
MillionIntegrals/vel | vel/internals/parser.py | Parser.parse_equality | def parse_equality(cls, equality_string):
""" Parse some simple equality statements """
cls.register()
assert '=' in equality_string, "There must be an '=' sign in the equality"
[left_side, right_side] = equality_string.split('=', 1)
left_side_value = yaml.safe_load(left_side.strip())
right_side_value = yaml.safe_load(right_side.strip())
assert isinstance(left_side_value, str), "Left side of equality must be a string"
return left_side_value, right_side_value | python | def parse_equality(cls, equality_string):
""" Parse some simple equality statements """
cls.register()
assert '=' in equality_string, "There must be an '=' sign in the equality"
[left_side, right_side] = equality_string.split('=', 1)
left_side_value = yaml.safe_load(left_side.strip())
right_side_value = yaml.safe_load(right_side.strip())
assert isinstance(left_side_value, str), "Left side of equality must be a string"
return left_side_value, right_side_value | [
"def",
"parse_equality",
"(",
"cls",
",",
"equality_string",
")",
":",
"cls",
".",
"register",
"(",
")",
"assert",
"'='",
"in",
"equality_string",
",",
"\"There must be an '=' sign in the equality\"",
"[",
"left_side",
",",
"right_side",
"]",
"=",
"equality_string",
".",
"split",
"(",
"'='",
",",
"1",
")",
"left_side_value",
"=",
"yaml",
".",
"safe_load",
"(",
"left_side",
".",
"strip",
"(",
")",
")",
"right_side_value",
"=",
"yaml",
".",
"safe_load",
"(",
"right_side",
".",
"strip",
"(",
")",
")",
"assert",
"isinstance",
"(",
"left_side_value",
",",
"str",
")",
",",
"\"Left side of equality must be a string\"",
"return",
"left_side_value",
",",
"right_side_value"
] | Parse some simple equality statements | [
"Parse",
"some",
"simple",
"equality",
"statements"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/parser.py#L89-L100 | train | 232,418 |
MillionIntegrals/vel | vel/storage/backend/mongodb.py | MongoDbBackend.clean | def clean(self, initial_epoch):
""" Remove entries from database that would get overwritten """
self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}}) | python | def clean(self, initial_epoch):
""" Remove entries from database that would get overwritten """
self.db.metrics.delete_many({'run_name': self.model_config.run_name, 'epoch_idx': {'$gt': initial_epoch}}) | [
"def",
"clean",
"(",
"self",
",",
"initial_epoch",
")",
":",
"self",
".",
"db",
".",
"metrics",
".",
"delete_many",
"(",
"{",
"'run_name'",
":",
"self",
".",
"model_config",
".",
"run_name",
",",
"'epoch_idx'",
":",
"{",
"'$gt'",
":",
"initial_epoch",
"}",
"}",
")"
] | Remove entries from database that would get overwritten | [
"Remove",
"entries",
"from",
"database",
"that",
"would",
"get",
"overwritten"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/backend/mongodb.py#L13-L15 | train | 232,419 |
MillionIntegrals/vel | vel/storage/backend/mongodb.py | MongoDbBackend.store_config | def store_config(self, configuration):
""" Store model parameters in the database """
run_name = self.model_config.run_name
self.db.configs.delete_many({'run_name': self.model_config.run_name})
configuration = configuration.copy()
configuration['run_name'] = run_name
self.db.configs.insert_one(configuration) | python | def store_config(self, configuration):
""" Store model parameters in the database """
run_name = self.model_config.run_name
self.db.configs.delete_many({'run_name': self.model_config.run_name})
configuration = configuration.copy()
configuration['run_name'] = run_name
self.db.configs.insert_one(configuration) | [
"def",
"store_config",
"(",
"self",
",",
"configuration",
")",
":",
"run_name",
"=",
"self",
".",
"model_config",
".",
"run_name",
"self",
".",
"db",
".",
"configs",
".",
"delete_many",
"(",
"{",
"'run_name'",
":",
"self",
".",
"model_config",
".",
"run_name",
"}",
")",
"configuration",
"=",
"configuration",
".",
"copy",
"(",
")",
"configuration",
"[",
"'run_name'",
"]",
"=",
"run_name",
"self",
".",
"db",
".",
"configs",
".",
"insert_one",
"(",
"configuration",
")"
] | Store model parameters in the database | [
"Store",
"model",
"parameters",
"in",
"the",
"database"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/backend/mongodb.py#L17-L26 | train | 232,420 |
MillionIntegrals/vel | vel/storage/backend/mongodb.py | MongoDbBackend.get_frame | def get_frame(self):
""" Get a dataframe of metrics from this storage """
metric_items = list(self.db.metrics.find({'run_name': self.model_config.run_name}).sort('epoch_idx'))
if len(metric_items) == 0:
return pd.DataFrame(columns=['run_name'])
else:
return pd.DataFrame(metric_items).drop(['_id', 'model_name'], axis=1).set_index('epoch_idx') | python | def get_frame(self):
""" Get a dataframe of metrics from this storage """
metric_items = list(self.db.metrics.find({'run_name': self.model_config.run_name}).sort('epoch_idx'))
if len(metric_items) == 0:
return pd.DataFrame(columns=['run_name'])
else:
return pd.DataFrame(metric_items).drop(['_id', 'model_name'], axis=1).set_index('epoch_idx') | [
"def",
"get_frame",
"(",
"self",
")",
":",
"metric_items",
"=",
"list",
"(",
"self",
".",
"db",
".",
"metrics",
".",
"find",
"(",
"{",
"'run_name'",
":",
"self",
".",
"model_config",
".",
"run_name",
"}",
")",
".",
"sort",
"(",
"'epoch_idx'",
")",
")",
"if",
"len",
"(",
"metric_items",
")",
"==",
"0",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"[",
"'run_name'",
"]",
")",
"else",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"metric_items",
")",
".",
"drop",
"(",
"[",
"'_id'",
",",
"'model_name'",
"]",
",",
"axis",
"=",
"1",
")",
".",
"set_index",
"(",
"'epoch_idx'",
")"
] | Get a dataframe of metrics from this storage | [
"Get",
"a",
"dataframe",
"of",
"metrics",
"from",
"this",
"storage"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/backend/mongodb.py#L28-L34 | train | 232,421 |
MillionIntegrals/vel | vel/rl/buffers/prioritized_circular_replay_buffer.py | PrioritizedCircularReplayBuffer._get_transitions | def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0):
""" Return batch of frames for given indexes """
if forward_steps > 1:
transition_arrays = self.backend.get_transitions_forward_steps(indexes, forward_steps, discount_factor)
else:
transition_arrays = self.backend.get_transitions(indexes)
priority_weight = self.priority_weight.value(batch_info['progress'])
# Normalize by sum of all probs
probs = probs / np.array([s.total() for s in self.backend.segment_trees], dtype=float).reshape(1, -1)
capacity = self.backend.current_size
weights = (capacity * probs) ** (-priority_weight)
weights = weights / weights.max(axis=0, keepdims=True)
transition_arrays['weights'] = weights
transition_tensors = {k: torch.from_numpy(v) for k, v in transition_arrays.items()}
transitions = Trajectories(
num_steps=indexes.shape[0],
num_envs=indexes.shape[1],
environment_information=None,
transition_tensors=transition_tensors,
rollout_tensors={},
extra_data={
'tree_idxs': tree_idxs
}
)
return transitions.to_transitions() | python | def _get_transitions(self, probs, indexes, tree_idxs, batch_info, forward_steps=1, discount_factor=1.0):
""" Return batch of frames for given indexes """
if forward_steps > 1:
transition_arrays = self.backend.get_transitions_forward_steps(indexes, forward_steps, discount_factor)
else:
transition_arrays = self.backend.get_transitions(indexes)
priority_weight = self.priority_weight.value(batch_info['progress'])
# Normalize by sum of all probs
probs = probs / np.array([s.total() for s in self.backend.segment_trees], dtype=float).reshape(1, -1)
capacity = self.backend.current_size
weights = (capacity * probs) ** (-priority_weight)
weights = weights / weights.max(axis=0, keepdims=True)
transition_arrays['weights'] = weights
transition_tensors = {k: torch.from_numpy(v) for k, v in transition_arrays.items()}
transitions = Trajectories(
num_steps=indexes.shape[0],
num_envs=indexes.shape[1],
environment_information=None,
transition_tensors=transition_tensors,
rollout_tensors={},
extra_data={
'tree_idxs': tree_idxs
}
)
return transitions.to_transitions() | [
"def",
"_get_transitions",
"(",
"self",
",",
"probs",
",",
"indexes",
",",
"tree_idxs",
",",
"batch_info",
",",
"forward_steps",
"=",
"1",
",",
"discount_factor",
"=",
"1.0",
")",
":",
"if",
"forward_steps",
">",
"1",
":",
"transition_arrays",
"=",
"self",
".",
"backend",
".",
"get_transitions_forward_steps",
"(",
"indexes",
",",
"forward_steps",
",",
"discount_factor",
")",
"else",
":",
"transition_arrays",
"=",
"self",
".",
"backend",
".",
"get_transitions",
"(",
"indexes",
")",
"priority_weight",
"=",
"self",
".",
"priority_weight",
".",
"value",
"(",
"batch_info",
"[",
"'progress'",
"]",
")",
"# Normalize by sum of all probs",
"probs",
"=",
"probs",
"/",
"np",
".",
"array",
"(",
"[",
"s",
".",
"total",
"(",
")",
"for",
"s",
"in",
"self",
".",
"backend",
".",
"segment_trees",
"]",
",",
"dtype",
"=",
"float",
")",
".",
"reshape",
"(",
"1",
",",
"-",
"1",
")",
"capacity",
"=",
"self",
".",
"backend",
".",
"current_size",
"weights",
"=",
"(",
"capacity",
"*",
"probs",
")",
"**",
"(",
"-",
"priority_weight",
")",
"weights",
"=",
"weights",
"/",
"weights",
".",
"max",
"(",
"axis",
"=",
"0",
",",
"keepdims",
"=",
"True",
")",
"transition_arrays",
"[",
"'weights'",
"]",
"=",
"weights",
"transition_tensors",
"=",
"{",
"k",
":",
"torch",
".",
"from_numpy",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"transition_arrays",
".",
"items",
"(",
")",
"}",
"transitions",
"=",
"Trajectories",
"(",
"num_steps",
"=",
"indexes",
".",
"shape",
"[",
"0",
"]",
",",
"num_envs",
"=",
"indexes",
".",
"shape",
"[",
"1",
"]",
",",
"environment_information",
"=",
"None",
",",
"transition_tensors",
"=",
"transition_tensors",
",",
"rollout_tensors",
"=",
"{",
"}",
",",
"extra_data",
"=",
"{",
"'tree_idxs'",
":",
"tree_idxs",
"}",
")",
"return",
"transitions",
".",
"to_transitions",
"(",
")"
] | Return batch of frames for given indexes | [
"Return",
"batch",
"of",
"frames",
"for",
"given",
"indexes"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/buffers/prioritized_circular_replay_buffer.py#L46-L75 | train | 232,422 |
MillionIntegrals/vel | vel/rl/api/env_roller.py | EnvRollerBase.rollout | def rollout(self, batch_info: BatchInfo, model: Model, number_of_steps: int) -> Rollout:
""" Roll-out the environment and return it """
raise NotImplementedError | python | def rollout(self, batch_info: BatchInfo, model: Model, number_of_steps: int) -> Rollout:
""" Roll-out the environment and return it """
raise NotImplementedError | [
"def",
"rollout",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
",",
"model",
":",
"Model",
",",
"number_of_steps",
":",
"int",
")",
"->",
"Rollout",
":",
"raise",
"NotImplementedError"
] | Roll-out the environment and return it | [
"Roll",
"-",
"out",
"the",
"environment",
"and",
"return",
"it"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/api/env_roller.py#L17-L19 | train | 232,423 |
MillionIntegrals/vel | vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py | BufferedMixedPolicyIterationReinforcer.train_epoch | def train_epoch(self, epoch_info: EpochInfo, interactive=True):
""" Train model on an epoch of a fixed number of batch updates """
epoch_info.on_epoch_begin()
if interactive:
iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch")
else:
iterator = range(epoch_info.batches_per_epoch)
for batch_idx in iterator:
batch_info = BatchInfo(epoch_info, batch_idx)
batch_info.on_batch_begin()
self.train_batch(batch_info)
batch_info.on_batch_end()
epoch_info.result_accumulator.freeze_results()
epoch_info.on_epoch_end() | python | def train_epoch(self, epoch_info: EpochInfo, interactive=True):
""" Train model on an epoch of a fixed number of batch updates """
epoch_info.on_epoch_begin()
if interactive:
iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch")
else:
iterator = range(epoch_info.batches_per_epoch)
for batch_idx in iterator:
batch_info = BatchInfo(epoch_info, batch_idx)
batch_info.on_batch_begin()
self.train_batch(batch_info)
batch_info.on_batch_end()
epoch_info.result_accumulator.freeze_results()
epoch_info.on_epoch_end() | [
"def",
"train_epoch",
"(",
"self",
",",
"epoch_info",
":",
"EpochInfo",
",",
"interactive",
"=",
"True",
")",
":",
"epoch_info",
".",
"on_epoch_begin",
"(",
")",
"if",
"interactive",
":",
"iterator",
"=",
"tqdm",
".",
"trange",
"(",
"epoch_info",
".",
"batches_per_epoch",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"desc",
"=",
"\"Training\"",
",",
"unit",
"=",
"\"batch\"",
")",
"else",
":",
"iterator",
"=",
"range",
"(",
"epoch_info",
".",
"batches_per_epoch",
")",
"for",
"batch_idx",
"in",
"iterator",
":",
"batch_info",
"=",
"BatchInfo",
"(",
"epoch_info",
",",
"batch_idx",
")",
"batch_info",
".",
"on_batch_begin",
"(",
")",
"self",
".",
"train_batch",
"(",
"batch_info",
")",
"batch_info",
".",
"on_batch_end",
"(",
")",
"epoch_info",
".",
"result_accumulator",
".",
"freeze_results",
"(",
")",
"epoch_info",
".",
"on_epoch_end",
"(",
")"
] | Train model on an epoch of a fixed number of batch updates | [
"Train",
"model",
"on",
"an",
"epoch",
"of",
"a",
"fixed",
"number",
"of",
"batch",
"updates"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py#L75-L92 | train | 232,424 |
MillionIntegrals/vel | vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py | BufferedMixedPolicyIterationReinforcer.train_batch | def train_batch(self, batch_info: BatchInfo):
""" Single, most atomic 'step' of learning this reinforcer can perform """
batch_info['sub_batch_data'] = []
self.on_policy_train_batch(batch_info)
if self.settings.experience_replay > 0 and self.env_roller.is_ready_for_sampling():
if self.settings.stochastic_experience_replay:
experience_replay_count = np.random.poisson(self.settings.experience_replay)
else:
experience_replay_count = self.settings.experience_replay
for i in range(experience_replay_count):
self.off_policy_train_batch(batch_info)
# Even with all the experience replay, we count the single rollout as a single batch
batch_info.aggregate_key('sub_batch_data') | python | def train_batch(self, batch_info: BatchInfo):
""" Single, most atomic 'step' of learning this reinforcer can perform """
batch_info['sub_batch_data'] = []
self.on_policy_train_batch(batch_info)
if self.settings.experience_replay > 0 and self.env_roller.is_ready_for_sampling():
if self.settings.stochastic_experience_replay:
experience_replay_count = np.random.poisson(self.settings.experience_replay)
else:
experience_replay_count = self.settings.experience_replay
for i in range(experience_replay_count):
self.off_policy_train_batch(batch_info)
# Even with all the experience replay, we count the single rollout as a single batch
batch_info.aggregate_key('sub_batch_data') | [
"def",
"train_batch",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"batch_info",
"[",
"'sub_batch_data'",
"]",
"=",
"[",
"]",
"self",
".",
"on_policy_train_batch",
"(",
"batch_info",
")",
"if",
"self",
".",
"settings",
".",
"experience_replay",
">",
"0",
"and",
"self",
".",
"env_roller",
".",
"is_ready_for_sampling",
"(",
")",
":",
"if",
"self",
".",
"settings",
".",
"stochastic_experience_replay",
":",
"experience_replay_count",
"=",
"np",
".",
"random",
".",
"poisson",
"(",
"self",
".",
"settings",
".",
"experience_replay",
")",
"else",
":",
"experience_replay_count",
"=",
"self",
".",
"settings",
".",
"experience_replay",
"for",
"i",
"in",
"range",
"(",
"experience_replay_count",
")",
":",
"self",
".",
"off_policy_train_batch",
"(",
"batch_info",
")",
"# Even with all the experience replay, we count the single rollout as a single batch",
"batch_info",
".",
"aggregate_key",
"(",
"'sub_batch_data'",
")"
] | Single, most atomic 'step' of learning this reinforcer can perform | [
"Single",
"most",
"atomic",
"step",
"of",
"learning",
"this",
"reinforcer",
"can",
"perform"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py#L94-L110 | train | 232,425 |
MillionIntegrals/vel | vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py | BufferedMixedPolicyIterationReinforcer.on_policy_train_batch | def on_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'on-policy' training step of evaluating an env and a single backpropagation step """
self.model.train()
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
batch_result = self.algo.optimizer_step(
batch_info=batch_info,
device=self.device,
model=self.model,
rollout=rollout
)
batch_info['sub_batch_data'].append(batch_result)
batch_info['frames'] = rollout.frames()
batch_info['episode_infos'] = rollout.episode_information() | python | def on_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'on-policy' training step of evaluating an env and a single backpropagation step """
self.model.train()
rollout = self.env_roller.rollout(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
batch_result = self.algo.optimizer_step(
batch_info=batch_info,
device=self.device,
model=self.model,
rollout=rollout
)
batch_info['sub_batch_data'].append(batch_result)
batch_info['frames'] = rollout.frames()
batch_info['episode_infos'] = rollout.episode_information() | [
"def",
"on_policy_train_batch",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"self",
".",
"model",
".",
"train",
"(",
")",
"rollout",
"=",
"self",
".",
"env_roller",
".",
"rollout",
"(",
"batch_info",
",",
"self",
".",
"model",
",",
"self",
".",
"settings",
".",
"number_of_steps",
")",
".",
"to_device",
"(",
"self",
".",
"device",
")",
"batch_result",
"=",
"self",
".",
"algo",
".",
"optimizer_step",
"(",
"batch_info",
"=",
"batch_info",
",",
"device",
"=",
"self",
".",
"device",
",",
"model",
"=",
"self",
".",
"model",
",",
"rollout",
"=",
"rollout",
")",
"batch_info",
"[",
"'sub_batch_data'",
"]",
".",
"append",
"(",
"batch_result",
")",
"batch_info",
"[",
"'frames'",
"]",
"=",
"rollout",
".",
"frames",
"(",
")",
"batch_info",
"[",
"'episode_infos'",
"]",
"=",
"rollout",
".",
"episode_information",
"(",
")"
] | Perform an 'on-policy' training step of evaluating an env and a single backpropagation step | [
"Perform",
"an",
"on",
"-",
"policy",
"training",
"step",
"of",
"evaluating",
"an",
"env",
"and",
"a",
"single",
"backpropagation",
"step"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py#L112-L127 | train | 232,426 |
MillionIntegrals/vel | vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py | BufferedMixedPolicyIterationReinforcer.off_policy_train_batch | def off_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'off-policy' training step of sampling the replay buffer and gradient descent """
self.model.train()
rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
batch_result = self.algo.optimizer_step(
batch_info=batch_info,
device=self.device,
model=self.model,
rollout=rollout
)
batch_info['sub_batch_data'].append(batch_result) | python | def off_policy_train_batch(self, batch_info: BatchInfo):
""" Perform an 'off-policy' training step of sampling the replay buffer and gradient descent """
self.model.train()
rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device)
batch_result = self.algo.optimizer_step(
batch_info=batch_info,
device=self.device,
model=self.model,
rollout=rollout
)
batch_info['sub_batch_data'].append(batch_result) | [
"def",
"off_policy_train_batch",
"(",
"self",
",",
"batch_info",
":",
"BatchInfo",
")",
":",
"self",
".",
"model",
".",
"train",
"(",
")",
"rollout",
"=",
"self",
".",
"env_roller",
".",
"sample",
"(",
"batch_info",
",",
"self",
".",
"model",
",",
"self",
".",
"settings",
".",
"number_of_steps",
")",
".",
"to_device",
"(",
"self",
".",
"device",
")",
"batch_result",
"=",
"self",
".",
"algo",
".",
"optimizer_step",
"(",
"batch_info",
"=",
"batch_info",
",",
"device",
"=",
"self",
".",
"device",
",",
"model",
"=",
"self",
".",
"model",
",",
"rollout",
"=",
"rollout",
")",
"batch_info",
"[",
"'sub_batch_data'",
"]",
".",
"append",
"(",
"batch_result",
")"
] | Perform an 'off-policy' training step of sampling the replay buffer and gradient descent | [
"Perform",
"an",
"off",
"-",
"policy",
"training",
"step",
"of",
"sampling",
"the",
"replay",
"buffer",
"and",
"gradient",
"descent"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_mixed_policy_iteration_reinforcer.py#L129-L142 | train | 232,427 |
MillionIntegrals/vel | vel/storage/strategy/classic_checkpoint_strategy.py | ClassicCheckpointStrategy.should_store_best_checkpoint | def should_store_best_checkpoint(self, epoch_idx, metrics) -> bool:
""" Should we store current checkpoint as the best """
if not self.store_best:
return False
metric = metrics[self.metric]
if better(self._current_best_metric_value, metric, self.metric_mode):
self._current_best_metric_value = metric
return True
return False | python | def should_store_best_checkpoint(self, epoch_idx, metrics) -> bool:
""" Should we store current checkpoint as the best """
if not self.store_best:
return False
metric = metrics[self.metric]
if better(self._current_best_metric_value, metric, self.metric_mode):
self._current_best_metric_value = metric
return True
return False | [
"def",
"should_store_best_checkpoint",
"(",
"self",
",",
"epoch_idx",
",",
"metrics",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"store_best",
":",
"return",
"False",
"metric",
"=",
"metrics",
"[",
"self",
".",
"metric",
"]",
"if",
"better",
"(",
"self",
".",
"_current_best_metric_value",
",",
"metric",
",",
"self",
".",
"metric_mode",
")",
":",
"self",
".",
"_current_best_metric_value",
"=",
"metric",
"return",
"True",
"return",
"False"
] | Should we store current checkpoint as the best | [
"Should",
"we",
"store",
"current",
"checkpoint",
"as",
"the",
"best"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/strategy/classic_checkpoint_strategy.py#L27-L38 | train | 232,428 |
MillionIntegrals/vel | vel/sources/nlp/imdb.py | create | def create(model_config, batch_size, vectors=None):
""" Create an IMDB dataset """
path = model_config.data_dir('imdb')
text_field = data.Field(lower=True, tokenize='spacy', batch_first=True)
label_field = data.LabelField(is_target=True)
train_source, test_source = IMDBCached.splits(
root=path,
text_field=text_field,
label_field=label_field
)
text_field.build_vocab(train_source, max_size=25_000, vectors=vectors)
label_field.build_vocab(train_source)
train_iterator, test_iterator = data.BucketIterator.splits(
(train_source, test_source),
batch_size=batch_size,
device=model_config.torch_device(),
shuffle=True
)
return TextData(
train_source, test_source, train_iterator, test_iterator, text_field, label_field
) | python | def create(model_config, batch_size, vectors=None):
""" Create an IMDB dataset """
path = model_config.data_dir('imdb')
text_field = data.Field(lower=True, tokenize='spacy', batch_first=True)
label_field = data.LabelField(is_target=True)
train_source, test_source = IMDBCached.splits(
root=path,
text_field=text_field,
label_field=label_field
)
text_field.build_vocab(train_source, max_size=25_000, vectors=vectors)
label_field.build_vocab(train_source)
train_iterator, test_iterator = data.BucketIterator.splits(
(train_source, test_source),
batch_size=batch_size,
device=model_config.torch_device(),
shuffle=True
)
return TextData(
train_source, test_source, train_iterator, test_iterator, text_field, label_field
) | [
"def",
"create",
"(",
"model_config",
",",
"batch_size",
",",
"vectors",
"=",
"None",
")",
":",
"path",
"=",
"model_config",
".",
"data_dir",
"(",
"'imdb'",
")",
"text_field",
"=",
"data",
".",
"Field",
"(",
"lower",
"=",
"True",
",",
"tokenize",
"=",
"'spacy'",
",",
"batch_first",
"=",
"True",
")",
"label_field",
"=",
"data",
".",
"LabelField",
"(",
"is_target",
"=",
"True",
")",
"train_source",
",",
"test_source",
"=",
"IMDBCached",
".",
"splits",
"(",
"root",
"=",
"path",
",",
"text_field",
"=",
"text_field",
",",
"label_field",
"=",
"label_field",
")",
"text_field",
".",
"build_vocab",
"(",
"train_source",
",",
"max_size",
"=",
"25_000",
",",
"vectors",
"=",
"vectors",
")",
"label_field",
".",
"build_vocab",
"(",
"train_source",
")",
"train_iterator",
",",
"test_iterator",
"=",
"data",
".",
"BucketIterator",
".",
"splits",
"(",
"(",
"train_source",
",",
"test_source",
")",
",",
"batch_size",
"=",
"batch_size",
",",
"device",
"=",
"model_config",
".",
"torch_device",
"(",
")",
",",
"shuffle",
"=",
"True",
")",
"return",
"TextData",
"(",
"train_source",
",",
"test_source",
",",
"train_iterator",
",",
"test_iterator",
",",
"text_field",
",",
"label_field",
")"
] | Create an IMDB dataset | [
"Create",
"an",
"IMDB",
"dataset"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/sources/nlp/imdb.py#L48-L73 | train | 232,429 |
MillionIntegrals/vel | vel/commands/augvis_command.py | AugmentationVisualizationCommand.run | def run(self):
""" Run the visualization """
dataset = self.source.train_dataset()
num_samples = len(dataset)
fig, ax = plt.subplots(self.cases, self.samples+1)
selected_sample = np.sort(np.random.choice(num_samples, self.cases, replace=False))
for i in range(self.cases):
raw_image, _ = dataset.get_raw(selected_sample[i])
ax[i, 0].imshow(raw_image)
ax[i, 0].set_title("Original image")
for j in range(self.samples):
augmented_image, _ = dataset[selected_sample[i]]
augmented_image = dataset.denormalize(augmented_image)
ax[i, j+1].imshow(augmented_image)
plt.show() | python | def run(self):
""" Run the visualization """
dataset = self.source.train_dataset()
num_samples = len(dataset)
fig, ax = plt.subplots(self.cases, self.samples+1)
selected_sample = np.sort(np.random.choice(num_samples, self.cases, replace=False))
for i in range(self.cases):
raw_image, _ = dataset.get_raw(selected_sample[i])
ax[i, 0].imshow(raw_image)
ax[i, 0].set_title("Original image")
for j in range(self.samples):
augmented_image, _ = dataset[selected_sample[i]]
augmented_image = dataset.denormalize(augmented_image)
ax[i, j+1].imshow(augmented_image)
plt.show() | [
"def",
"run",
"(",
"self",
")",
":",
"dataset",
"=",
"self",
".",
"source",
".",
"train_dataset",
"(",
")",
"num_samples",
"=",
"len",
"(",
"dataset",
")",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"self",
".",
"cases",
",",
"self",
".",
"samples",
"+",
"1",
")",
"selected_sample",
"=",
"np",
".",
"sort",
"(",
"np",
".",
"random",
".",
"choice",
"(",
"num_samples",
",",
"self",
".",
"cases",
",",
"replace",
"=",
"False",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"cases",
")",
":",
"raw_image",
",",
"_",
"=",
"dataset",
".",
"get_raw",
"(",
"selected_sample",
"[",
"i",
"]",
")",
"ax",
"[",
"i",
",",
"0",
"]",
".",
"imshow",
"(",
"raw_image",
")",
"ax",
"[",
"i",
",",
"0",
"]",
".",
"set_title",
"(",
"\"Original image\"",
")",
"for",
"j",
"in",
"range",
"(",
"self",
".",
"samples",
")",
":",
"augmented_image",
",",
"_",
"=",
"dataset",
"[",
"selected_sample",
"[",
"i",
"]",
"]",
"augmented_image",
"=",
"dataset",
".",
"denormalize",
"(",
"augmented_image",
")",
"ax",
"[",
"i",
",",
"j",
"+",
"1",
"]",
".",
"imshow",
"(",
"augmented_image",
")",
"plt",
".",
"show",
"(",
")"
] | Run the visualization | [
"Run",
"the",
"visualization"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/commands/augvis_command.py#L14-L34 | train | 232,430 |
MillionIntegrals/vel | vel/rl/env/classic_control.py | env_maker | def env_maker(environment_id, seed, serial_id, monitor=False, allow_early_resets=False):
""" Create a classic control environment with basic set of wrappers """
env = gym.make(environment_id)
env.seed(seed + serial_id)
# Monitoring the env
if monitor:
logdir = logger.get_dir() and os.path.join(logger.get_dir(), str(serial_id))
else:
logdir = None
env = Monitor(env, logdir, allow_early_resets=allow_early_resets)
return env | python | def env_maker(environment_id, seed, serial_id, monitor=False, allow_early_resets=False):
""" Create a classic control environment with basic set of wrappers """
env = gym.make(environment_id)
env.seed(seed + serial_id)
# Monitoring the env
if monitor:
logdir = logger.get_dir() and os.path.join(logger.get_dir(), str(serial_id))
else:
logdir = None
env = Monitor(env, logdir, allow_early_resets=allow_early_resets)
return env | [
"def",
"env_maker",
"(",
"environment_id",
",",
"seed",
",",
"serial_id",
",",
"monitor",
"=",
"False",
",",
"allow_early_resets",
"=",
"False",
")",
":",
"env",
"=",
"gym",
".",
"make",
"(",
"environment_id",
")",
"env",
".",
"seed",
"(",
"seed",
"+",
"serial_id",
")",
"# Monitoring the env",
"if",
"monitor",
":",
"logdir",
"=",
"logger",
".",
"get_dir",
"(",
")",
"and",
"os",
".",
"path",
".",
"join",
"(",
"logger",
".",
"get_dir",
"(",
")",
",",
"str",
"(",
"serial_id",
")",
")",
"else",
":",
"logdir",
"=",
"None",
"env",
"=",
"Monitor",
"(",
"env",
",",
"logdir",
",",
"allow_early_resets",
"=",
"allow_early_resets",
")",
"return",
"env"
] | Create a classic control environment with basic set of wrappers | [
"Create",
"a",
"classic",
"control",
"environment",
"with",
"basic",
"set",
"of",
"wrappers"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/env/classic_control.py#L25-L38 | train | 232,431 |
MillionIntegrals/vel | vel/models/imagenet/resnet34.py | Resnet34.freeze | def freeze(self, number=None):
""" Freeze given number of layers in the model """
if number is None:
number = self.head_layers
for idx, child in enumerate(self.model.children()):
if idx < number:
mu.freeze_layer(child) | python | def freeze(self, number=None):
""" Freeze given number of layers in the model """
if number is None:
number = self.head_layers
for idx, child in enumerate(self.model.children()):
if idx < number:
mu.freeze_layer(child) | [
"def",
"freeze",
"(",
"self",
",",
"number",
"=",
"None",
")",
":",
"if",
"number",
"is",
"None",
":",
"number",
"=",
"self",
".",
"head_layers",
"for",
"idx",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"model",
".",
"children",
"(",
")",
")",
":",
"if",
"idx",
"<",
"number",
":",
"mu",
".",
"freeze_layer",
"(",
"child",
")"
] | Freeze given number of layers in the model | [
"Freeze",
"given",
"number",
"of",
"layers",
"in",
"the",
"model"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/imagenet/resnet34.py#L66-L73 | train | 232,432 |
MillionIntegrals/vel | vel/models/imagenet/resnet34.py | Resnet34.unfreeze | def unfreeze(self):
""" Unfreeze model layers """
for idx, child in enumerate(self.model.children()):
mu.unfreeze_layer(child) | python | def unfreeze(self):
""" Unfreeze model layers """
for idx, child in enumerate(self.model.children()):
mu.unfreeze_layer(child) | [
"def",
"unfreeze",
"(",
"self",
")",
":",
"for",
"idx",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"model",
".",
"children",
"(",
")",
")",
":",
"mu",
".",
"unfreeze_layer",
"(",
"child",
")"
] | Unfreeze model layers | [
"Unfreeze",
"model",
"layers"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/imagenet/resnet34.py#L75-L78 | train | 232,433 |
MillionIntegrals/vel | vel/rl/algo/policy_gradient/acer.py | AcerPolicyGradient.update_average_model | def update_average_model(self, model):
""" Update weights of the average model with new model observation """
for model_param, average_param in zip(model.parameters(), self.average_model.parameters()):
# EWMA average model update
average_param.data.mul_(self.average_model_alpha).add_(model_param.data * (1 - self.average_model_alpha)) | python | def update_average_model(self, model):
""" Update weights of the average model with new model observation """
for model_param, average_param in zip(model.parameters(), self.average_model.parameters()):
# EWMA average model update
average_param.data.mul_(self.average_model_alpha).add_(model_param.data * (1 - self.average_model_alpha)) | [
"def",
"update_average_model",
"(",
"self",
",",
"model",
")",
":",
"for",
"model_param",
",",
"average_param",
"in",
"zip",
"(",
"model",
".",
"parameters",
"(",
")",
",",
"self",
".",
"average_model",
".",
"parameters",
"(",
")",
")",
":",
"# EWMA average model update",
"average_param",
".",
"data",
".",
"mul_",
"(",
"self",
".",
"average_model_alpha",
")",
".",
"add_",
"(",
"model_param",
".",
"data",
"*",
"(",
"1",
"-",
"self",
".",
"average_model_alpha",
")",
")"
] | Update weights of the average model with new model observation | [
"Update",
"weights",
"of",
"the",
"average",
"model",
"with",
"new",
"model",
"observation"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/acer.py#L43-L47 | train | 232,434 |
MillionIntegrals/vel | vel/rl/algo/policy_gradient/acer.py | AcerPolicyGradient.retrace | def retrace(self, rewards, dones, q_values, state_values, rho, final_values):
""" Calculate Q retraced targets """
rho_bar = torch.min(torch.ones_like(rho) * self.retrace_rho_cap, rho)
q_retraced_buffer = torch.zeros_like(rewards)
next_value = final_values
for i in reversed(range(rewards.size(0))):
q_retraced = rewards[i] + self.discount_factor * next_value * (1.0 - dones[i])
# Next iteration
next_value = rho_bar[i] * (q_retraced - q_values[i]) + state_values[i]
q_retraced_buffer[i] = q_retraced
return q_retraced_buffer | python | def retrace(self, rewards, dones, q_values, state_values, rho, final_values):
""" Calculate Q retraced targets """
rho_bar = torch.min(torch.ones_like(rho) * self.retrace_rho_cap, rho)
q_retraced_buffer = torch.zeros_like(rewards)
next_value = final_values
for i in reversed(range(rewards.size(0))):
q_retraced = rewards[i] + self.discount_factor * next_value * (1.0 - dones[i])
# Next iteration
next_value = rho_bar[i] * (q_retraced - q_values[i]) + state_values[i]
q_retraced_buffer[i] = q_retraced
return q_retraced_buffer | [
"def",
"retrace",
"(",
"self",
",",
"rewards",
",",
"dones",
",",
"q_values",
",",
"state_values",
",",
"rho",
",",
"final_values",
")",
":",
"rho_bar",
"=",
"torch",
".",
"min",
"(",
"torch",
".",
"ones_like",
"(",
"rho",
")",
"*",
"self",
".",
"retrace_rho_cap",
",",
"rho",
")",
"q_retraced_buffer",
"=",
"torch",
".",
"zeros_like",
"(",
"rewards",
")",
"next_value",
"=",
"final_values",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"rewards",
".",
"size",
"(",
"0",
")",
")",
")",
":",
"q_retraced",
"=",
"rewards",
"[",
"i",
"]",
"+",
"self",
".",
"discount_factor",
"*",
"next_value",
"*",
"(",
"1.0",
"-",
"dones",
"[",
"i",
"]",
")",
"# Next iteration",
"next_value",
"=",
"rho_bar",
"[",
"i",
"]",
"*",
"(",
"q_retraced",
"-",
"q_values",
"[",
"i",
"]",
")",
"+",
"state_values",
"[",
"i",
"]",
"q_retraced_buffer",
"[",
"i",
"]",
"=",
"q_retraced",
"return",
"q_retraced_buffer"
] | Calculate Q retraced targets | [
"Calculate",
"Q",
"retraced",
"targets"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/acer.py#L170-L186 | train | 232,435 |
MillionIntegrals/vel | vel/rl/modules/action_head.py | DiagGaussianActionHead.logprob | def logprob(self, action_sample, pd_params):
""" Log-likelihood """
means = pd_params[:, :, 0]
log_std = pd_params[:, :, 1]
std = torch.exp(log_std)
z_score = (action_sample - means) / std
return - (0.5 * ((z_score**2 + self.LOG2PI).sum(dim=-1)) + log_std.sum(dim=-1)) | python | def logprob(self, action_sample, pd_params):
""" Log-likelihood """
means = pd_params[:, :, 0]
log_std = pd_params[:, :, 1]
std = torch.exp(log_std)
z_score = (action_sample - means) / std
return - (0.5 * ((z_score**2 + self.LOG2PI).sum(dim=-1)) + log_std.sum(dim=-1)) | [
"def",
"logprob",
"(",
"self",
",",
"action_sample",
",",
"pd_params",
")",
":",
"means",
"=",
"pd_params",
"[",
":",
",",
":",
",",
"0",
"]",
"log_std",
"=",
"pd_params",
"[",
":",
",",
":",
",",
"1",
"]",
"std",
"=",
"torch",
".",
"exp",
"(",
"log_std",
")",
"z_score",
"=",
"(",
"action_sample",
"-",
"means",
")",
"/",
"std",
"return",
"-",
"(",
"0.5",
"*",
"(",
"(",
"z_score",
"**",
"2",
"+",
"self",
".",
"LOG2PI",
")",
".",
"sum",
"(",
"dim",
"=",
"-",
"1",
")",
")",
"+",
"log_std",
".",
"sum",
"(",
"dim",
"=",
"-",
"1",
")",
")"
] | Log-likelihood | [
"Log",
"-",
"likelihood"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/action_head.py#L45-L54 | train | 232,436 |
MillionIntegrals/vel | vel/rl/modules/action_head.py | CategoricalActionHead.logprob | def logprob(self, actions, action_logits):
""" Logarithm of probability of given sample """
neg_log_prob = F.nll_loss(action_logits, actions, reduction='none')
return -neg_log_prob | python | def logprob(self, actions, action_logits):
""" Logarithm of probability of given sample """
neg_log_prob = F.nll_loss(action_logits, actions, reduction='none')
return -neg_log_prob | [
"def",
"logprob",
"(",
"self",
",",
"actions",
",",
"action_logits",
")",
":",
"neg_log_prob",
"=",
"F",
".",
"nll_loss",
"(",
"action_logits",
",",
"actions",
",",
"reduction",
"=",
"'none'",
")",
"return",
"-",
"neg_log_prob"
] | Logarithm of probability of given sample | [
"Logarithm",
"of",
"probability",
"of",
"given",
"sample"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/action_head.py#L103-L106 | train | 232,437 |
MillionIntegrals/vel | vel/metrics/accuracy.py | Accuracy._value_function | def _value_function(self, x_input, y_true, y_pred):
""" Return classification accuracy of input """
if len(y_true.shape) == 1:
return y_pred.argmax(1).eq(y_true).double().mean().item()
else:
raise NotImplementedError | python | def _value_function(self, x_input, y_true, y_pred):
""" Return classification accuracy of input """
if len(y_true.shape) == 1:
return y_pred.argmax(1).eq(y_true).double().mean().item()
else:
raise NotImplementedError | [
"def",
"_value_function",
"(",
"self",
",",
"x_input",
",",
"y_true",
",",
"y_pred",
")",
":",
"if",
"len",
"(",
"y_true",
".",
"shape",
")",
"==",
"1",
":",
"return",
"y_pred",
".",
"argmax",
"(",
"1",
")",
".",
"eq",
"(",
"y_true",
")",
".",
"double",
"(",
")",
".",
"mean",
"(",
")",
".",
"item",
"(",
")",
"else",
":",
"raise",
"NotImplementedError"
] | Return classification accuracy of input | [
"Return",
"classification",
"accuracy",
"of",
"input"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/metrics/accuracy.py#L9-L14 | train | 232,438 |
MillionIntegrals/vel | vel/storage/streaming/visdom.py | VisdomStreaming.on_epoch_end | def on_epoch_end(self, epoch_info):
""" Update data in visdom on push """
metrics_df = pd.DataFrame([epoch_info.result]).set_index('epoch_idx')
visdom_append_metrics(
self.vis,
metrics_df,
first_epoch=epoch_info.global_epoch_idx == 1
) | python | def on_epoch_end(self, epoch_info):
""" Update data in visdom on push """
metrics_df = pd.DataFrame([epoch_info.result]).set_index('epoch_idx')
visdom_append_metrics(
self.vis,
metrics_df,
first_epoch=epoch_info.global_epoch_idx == 1
) | [
"def",
"on_epoch_end",
"(",
"self",
",",
"epoch_info",
")",
":",
"metrics_df",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"epoch_info",
".",
"result",
"]",
")",
".",
"set_index",
"(",
"'epoch_idx'",
")",
"visdom_append_metrics",
"(",
"self",
".",
"vis",
",",
"metrics_df",
",",
"first_epoch",
"=",
"epoch_info",
".",
"global_epoch_idx",
"==",
"1",
")"
] | Update data in visdom on push | [
"Update",
"data",
"in",
"visdom",
"on",
"push"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/streaming/visdom.py#L22-L30 | train | 232,439 |
MillionIntegrals/vel | vel/storage/streaming/visdom.py | VisdomStreaming.on_batch_end | def on_batch_end(self, batch_info):
""" Stream LR to visdom """
if self.settings.stream_lr:
iteration_idx = (
float(batch_info.epoch_number) +
float(batch_info.batch_number) / batch_info.batches_per_epoch
)
lr = batch_info.optimizer.param_groups[-1]['lr']
metrics_df = pd.DataFrame([lr], index=[iteration_idx], columns=['lr'])
visdom_append_metrics(
self.vis,
metrics_df,
first_epoch=(batch_info.epoch_number == 1) and (batch_info.batch_number == 0)
) | python | def on_batch_end(self, batch_info):
""" Stream LR to visdom """
if self.settings.stream_lr:
iteration_idx = (
float(batch_info.epoch_number) +
float(batch_info.batch_number) / batch_info.batches_per_epoch
)
lr = batch_info.optimizer.param_groups[-1]['lr']
metrics_df = pd.DataFrame([lr], index=[iteration_idx], columns=['lr'])
visdom_append_metrics(
self.vis,
metrics_df,
first_epoch=(batch_info.epoch_number == 1) and (batch_info.batch_number == 0)
) | [
"def",
"on_batch_end",
"(",
"self",
",",
"batch_info",
")",
":",
"if",
"self",
".",
"settings",
".",
"stream_lr",
":",
"iteration_idx",
"=",
"(",
"float",
"(",
"batch_info",
".",
"epoch_number",
")",
"+",
"float",
"(",
"batch_info",
".",
"batch_number",
")",
"/",
"batch_info",
".",
"batches_per_epoch",
")",
"lr",
"=",
"batch_info",
".",
"optimizer",
".",
"param_groups",
"[",
"-",
"1",
"]",
"[",
"'lr'",
"]",
"metrics_df",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"lr",
"]",
",",
"index",
"=",
"[",
"iteration_idx",
"]",
",",
"columns",
"=",
"[",
"'lr'",
"]",
")",
"visdom_append_metrics",
"(",
"self",
".",
"vis",
",",
"metrics_df",
",",
"first_epoch",
"=",
"(",
"batch_info",
".",
"epoch_number",
"==",
"1",
")",
"and",
"(",
"batch_info",
".",
"batch_number",
"==",
"0",
")",
")"
] | Stream LR to visdom | [
"Stream",
"LR",
"to",
"visdom"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/storage/streaming/visdom.py#L32-L48 | train | 232,440 |
MillionIntegrals/vel | vel/launcher.py | main | def main():
""" Paperboy entry point - parse the arguments and run a command """
parser = argparse.ArgumentParser(description='Paperboy deep learning launcher')
parser.add_argument('config', metavar='FILENAME', help='Configuration file for the run')
parser.add_argument('command', metavar='COMMAND', help='A command to run')
parser.add_argument('varargs', nargs='*', metavar='VARARGS', help='Extra options to the command')
parser.add_argument('-r', '--run_number', type=int, default=0, help="A run number")
parser.add_argument('-d', '--device', default='cuda', help="A device to run the model on")
parser.add_argument('-s', '--seed', type=int, default=None, help="Random seed for the project")
parser.add_argument(
'-p', '--param', type=str, metavar='NAME=VALUE', action='append', default=[],
help="Configuration parameters"
)
parser.add_argument(
'--continue', action='store_true', default=False, help="Continue previously started learning process"
)
parser.add_argument(
'--profile', type=str, default=None, help="Profiler output"
)
args = parser.parse_args()
model_config = ModelConfig.from_file(
args.config, args.run_number, continue_training=getattr(args, 'continue'), device=args.device, seed=args.seed,
params={k: v for (k, v) in (Parser.parse_equality(eq) for eq in args.param)}
)
if model_config.project_dir not in sys.path:
sys.path.append(model_config.project_dir)
multiprocessing_setting = model_config.provide_with_default('multiprocessing', default=None)
if multiprocessing_setting:
# This needs to be called before any of PyTorch module is imported
multiprocessing.set_start_method(multiprocessing_setting)
# Set seed already in the launcher
from vel.util.random import set_seed
set_seed(model_config.seed)
model_config.banner(args.command)
if args.profile:
print("[PROFILER] Running Vel in profiling mode, output filename={}".format(args.profile))
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
model_config.run_command(args.command, args.varargs)
profiler.disable()
profiler.dump_stats(args.profile)
profiler.print_stats(sort='tottime')
print("======================================================================")
pstats.Stats(profiler).strip_dirs().sort_stats('tottime').print_stats(30)
print("======================================================================")
pstats.Stats(profiler).strip_dirs().sort_stats('cumtime').print_stats(30)
else:
model_config.run_command(args.command, args.varargs)
model_config.quit_banner() | python | def main():
""" Paperboy entry point - parse the arguments and run a command """
parser = argparse.ArgumentParser(description='Paperboy deep learning launcher')
parser.add_argument('config', metavar='FILENAME', help='Configuration file for the run')
parser.add_argument('command', metavar='COMMAND', help='A command to run')
parser.add_argument('varargs', nargs='*', metavar='VARARGS', help='Extra options to the command')
parser.add_argument('-r', '--run_number', type=int, default=0, help="A run number")
parser.add_argument('-d', '--device', default='cuda', help="A device to run the model on")
parser.add_argument('-s', '--seed', type=int, default=None, help="Random seed for the project")
parser.add_argument(
'-p', '--param', type=str, metavar='NAME=VALUE', action='append', default=[],
help="Configuration parameters"
)
parser.add_argument(
'--continue', action='store_true', default=False, help="Continue previously started learning process"
)
parser.add_argument(
'--profile', type=str, default=None, help="Profiler output"
)
args = parser.parse_args()
model_config = ModelConfig.from_file(
args.config, args.run_number, continue_training=getattr(args, 'continue'), device=args.device, seed=args.seed,
params={k: v for (k, v) in (Parser.parse_equality(eq) for eq in args.param)}
)
if model_config.project_dir not in sys.path:
sys.path.append(model_config.project_dir)
multiprocessing_setting = model_config.provide_with_default('multiprocessing', default=None)
if multiprocessing_setting:
# This needs to be called before any of PyTorch module is imported
multiprocessing.set_start_method(multiprocessing_setting)
# Set seed already in the launcher
from vel.util.random import set_seed
set_seed(model_config.seed)
model_config.banner(args.command)
if args.profile:
print("[PROFILER] Running Vel in profiling mode, output filename={}".format(args.profile))
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
model_config.run_command(args.command, args.varargs)
profiler.disable()
profiler.dump_stats(args.profile)
profiler.print_stats(sort='tottime')
print("======================================================================")
pstats.Stats(profiler).strip_dirs().sort_stats('tottime').print_stats(30)
print("======================================================================")
pstats.Stats(profiler).strip_dirs().sort_stats('cumtime').print_stats(30)
else:
model_config.run_command(args.command, args.varargs)
model_config.quit_banner() | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Paperboy deep learning launcher'",
")",
"parser",
".",
"add_argument",
"(",
"'config'",
",",
"metavar",
"=",
"'FILENAME'",
",",
"help",
"=",
"'Configuration file for the run'",
")",
"parser",
".",
"add_argument",
"(",
"'command'",
",",
"metavar",
"=",
"'COMMAND'",
",",
"help",
"=",
"'A command to run'",
")",
"parser",
".",
"add_argument",
"(",
"'varargs'",
",",
"nargs",
"=",
"'*'",
",",
"metavar",
"=",
"'VARARGS'",
",",
"help",
"=",
"'Extra options to the command'",
")",
"parser",
".",
"add_argument",
"(",
"'-r'",
",",
"'--run_number'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
",",
"help",
"=",
"\"A run number\"",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--device'",
",",
"default",
"=",
"'cuda'",
",",
"help",
"=",
"\"A device to run the model on\"",
")",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--seed'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"None",
",",
"help",
"=",
"\"Random seed for the project\"",
")",
"parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--param'",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"'NAME=VALUE'",
",",
"action",
"=",
"'append'",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"\"Configuration parameters\"",
")",
"parser",
".",
"add_argument",
"(",
"'--continue'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"\"Continue previously started learning process\"",
")",
"parser",
".",
"add_argument",
"(",
"'--profile'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"None",
",",
"help",
"=",
"\"Profiler output\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"model_config",
"=",
"ModelConfig",
".",
"from_file",
"(",
"args",
".",
"config",
",",
"args",
".",
"run_number",
",",
"continue_training",
"=",
"getattr",
"(",
"args",
",",
"'continue'",
")",
",",
"device",
"=",
"args",
".",
"device",
",",
"seed",
"=",
"args",
".",
"seed",
",",
"params",
"=",
"{",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"(",
"Parser",
".",
"parse_equality",
"(",
"eq",
")",
"for",
"eq",
"in",
"args",
".",
"param",
")",
"}",
")",
"if",
"model_config",
".",
"project_dir",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"model_config",
".",
"project_dir",
")",
"multiprocessing_setting",
"=",
"model_config",
".",
"provide_with_default",
"(",
"'multiprocessing'",
",",
"default",
"=",
"None",
")",
"if",
"multiprocessing_setting",
":",
"# This needs to be called before any of PyTorch module is imported",
"multiprocessing",
".",
"set_start_method",
"(",
"multiprocessing_setting",
")",
"# Set seed already in the launcher",
"from",
"vel",
".",
"util",
".",
"random",
"import",
"set_seed",
"set_seed",
"(",
"model_config",
".",
"seed",
")",
"model_config",
".",
"banner",
"(",
"args",
".",
"command",
")",
"if",
"args",
".",
"profile",
":",
"print",
"(",
"\"[PROFILER] Running Vel in profiling mode, output filename={}\"",
".",
"format",
"(",
"args",
".",
"profile",
")",
")",
"import",
"cProfile",
"import",
"pstats",
"profiler",
"=",
"cProfile",
".",
"Profile",
"(",
")",
"profiler",
".",
"enable",
"(",
")",
"model_config",
".",
"run_command",
"(",
"args",
".",
"command",
",",
"args",
".",
"varargs",
")",
"profiler",
".",
"disable",
"(",
")",
"profiler",
".",
"dump_stats",
"(",
"args",
".",
"profile",
")",
"profiler",
".",
"print_stats",
"(",
"sort",
"=",
"'tottime'",
")",
"print",
"(",
"\"======================================================================\"",
")",
"pstats",
".",
"Stats",
"(",
"profiler",
")",
".",
"strip_dirs",
"(",
")",
".",
"sort_stats",
"(",
"'tottime'",
")",
".",
"print_stats",
"(",
"30",
")",
"print",
"(",
"\"======================================================================\"",
")",
"pstats",
".",
"Stats",
"(",
"profiler",
")",
".",
"strip_dirs",
"(",
")",
".",
"sort_stats",
"(",
"'cumtime'",
")",
".",
"print_stats",
"(",
"30",
")",
"else",
":",
"model_config",
".",
"run_command",
"(",
"args",
".",
"command",
",",
"args",
".",
"varargs",
")",
"model_config",
".",
"quit_banner",
"(",
")"
] | Paperboy entry point - parse the arguments and run a command | [
"Paperboy",
"entry",
"point",
"-",
"parse",
"the",
"arguments",
"and",
"run",
"a",
"command"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/launcher.py#L10-L72 | train | 232,441 |
MillionIntegrals/vel | vel/util/random.py | set_seed | def set_seed(seed: int):
""" Set random seed for python, numpy and pytorch RNGs """
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed) | python | def set_seed(seed: int):
""" Set random seed for python, numpy and pytorch RNGs """
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed) | [
"def",
"set_seed",
"(",
"seed",
":",
"int",
")",
":",
"random",
".",
"seed",
"(",
"seed",
")",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"torch",
".",
"random",
".",
"manual_seed",
"(",
"seed",
")"
] | Set random seed for python, numpy and pytorch RNGs | [
"Set",
"random",
"seed",
"for",
"python",
"numpy",
"and",
"pytorch",
"RNGs"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/random.py#L6-L10 | train | 232,442 |
MillionIntegrals/vel | vel/util/better.py | better | def better(old_value, new_value, mode):
""" Check if new value is better than the old value"""
if (old_value is None or np.isnan(old_value)) and (new_value is not None and not np.isnan(new_value)):
return True
if mode == 'min':
return new_value < old_value
elif mode == 'max':
return new_value > old_value
else:
raise RuntimeError(f"Mode '{mode}' value is not supported") | python | def better(old_value, new_value, mode):
""" Check if new value is better than the old value"""
if (old_value is None or np.isnan(old_value)) and (new_value is not None and not np.isnan(new_value)):
return True
if mode == 'min':
return new_value < old_value
elif mode == 'max':
return new_value > old_value
else:
raise RuntimeError(f"Mode '{mode}' value is not supported") | [
"def",
"better",
"(",
"old_value",
",",
"new_value",
",",
"mode",
")",
":",
"if",
"(",
"old_value",
"is",
"None",
"or",
"np",
".",
"isnan",
"(",
"old_value",
")",
")",
"and",
"(",
"new_value",
"is",
"not",
"None",
"and",
"not",
"np",
".",
"isnan",
"(",
"new_value",
")",
")",
":",
"return",
"True",
"if",
"mode",
"==",
"'min'",
":",
"return",
"new_value",
"<",
"old_value",
"elif",
"mode",
"==",
"'max'",
":",
"return",
"new_value",
">",
"old_value",
"else",
":",
"raise",
"RuntimeError",
"(",
"f\"Mode '{mode}' value is not supported\"",
")"
] | Check if new value is better than the old value | [
"Check",
"if",
"new",
"value",
"is",
"better",
"than",
"the",
"old",
"value"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/util/better.py#L4-L14 | train | 232,443 |
MillionIntegrals/vel | vel/rl/modules/deterministic_critic_head.py | DeterministicCriticHead.reset_weights | def reset_weights(self):
""" Initialize weights to sane defaults """
init.uniform_(self.linear.weight, -3e-3, 3e-3)
init.zeros_(self.linear.bias) | python | def reset_weights(self):
""" Initialize weights to sane defaults """
init.uniform_(self.linear.weight, -3e-3, 3e-3)
init.zeros_(self.linear.bias) | [
"def",
"reset_weights",
"(",
"self",
")",
":",
"init",
".",
"uniform_",
"(",
"self",
".",
"linear",
".",
"weight",
",",
"-",
"3e-3",
",",
"3e-3",
")",
"init",
".",
"zeros_",
"(",
"self",
".",
"linear",
".",
"bias",
")"
] | Initialize weights to sane defaults | [
"Initialize",
"weights",
"to",
"sane",
"defaults"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/deterministic_critic_head.py#L20-L23 | train | 232,444 |
MillionIntegrals/vel | vel/rl/discount_bootstrap.py | discount_bootstrap | def discount_bootstrap(rewards_buffer, dones_buffer, final_values, discount_factor, number_of_steps):
""" Calculate state values bootstrapping off the following state values """
true_value_buffer = torch.zeros_like(rewards_buffer)
# discount/bootstrap off value fn
current_value = final_values
for i in reversed(range(number_of_steps)):
current_value = rewards_buffer[i] + discount_factor * current_value * (1.0 - dones_buffer[i])
true_value_buffer[i] = current_value
return true_value_buffer | python | def discount_bootstrap(rewards_buffer, dones_buffer, final_values, discount_factor, number_of_steps):
""" Calculate state values bootstrapping off the following state values """
true_value_buffer = torch.zeros_like(rewards_buffer)
# discount/bootstrap off value fn
current_value = final_values
for i in reversed(range(number_of_steps)):
current_value = rewards_buffer[i] + discount_factor * current_value * (1.0 - dones_buffer[i])
true_value_buffer[i] = current_value
return true_value_buffer | [
"def",
"discount_bootstrap",
"(",
"rewards_buffer",
",",
"dones_buffer",
",",
"final_values",
",",
"discount_factor",
",",
"number_of_steps",
")",
":",
"true_value_buffer",
"=",
"torch",
".",
"zeros_like",
"(",
"rewards_buffer",
")",
"# discount/bootstrap off value fn",
"current_value",
"=",
"final_values",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"number_of_steps",
")",
")",
":",
"current_value",
"=",
"rewards_buffer",
"[",
"i",
"]",
"+",
"discount_factor",
"*",
"current_value",
"*",
"(",
"1.0",
"-",
"dones_buffer",
"[",
"i",
"]",
")",
"true_value_buffer",
"[",
"i",
"]",
"=",
"current_value",
"return",
"true_value_buffer"
] | Calculate state values bootstrapping off the following state values | [
"Calculate",
"state",
"values",
"bootstrapping",
"off",
"the",
"following",
"state",
"values"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/discount_bootstrap.py#L4-L15 | train | 232,445 |
MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.find_project_directory | def find_project_directory(start_path) -> str:
""" Locate top-level project directory """
start_path = os.path.realpath(start_path)
possible_name = os.path.join(start_path, ModelConfig.PROJECT_FILE_NAME)
if os.path.exists(possible_name):
return start_path
else:
up_path = os.path.realpath(os.path.join(start_path, '..'))
if os.path.realpath(start_path) == up_path:
raise RuntimeError(f"Couldn't find project file starting from {start_path}")
else:
return ModelConfig.find_project_directory(up_path) | python | def find_project_directory(start_path) -> str:
""" Locate top-level project directory """
start_path = os.path.realpath(start_path)
possible_name = os.path.join(start_path, ModelConfig.PROJECT_FILE_NAME)
if os.path.exists(possible_name):
return start_path
else:
up_path = os.path.realpath(os.path.join(start_path, '..'))
if os.path.realpath(start_path) == up_path:
raise RuntimeError(f"Couldn't find project file starting from {start_path}")
else:
return ModelConfig.find_project_directory(up_path) | [
"def",
"find_project_directory",
"(",
"start_path",
")",
"->",
"str",
":",
"start_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"start_path",
")",
"possible_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"start_path",
",",
"ModelConfig",
".",
"PROJECT_FILE_NAME",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"possible_name",
")",
":",
"return",
"start_path",
"else",
":",
"up_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"start_path",
",",
"'..'",
")",
")",
"if",
"os",
".",
"path",
".",
"realpath",
"(",
"start_path",
")",
"==",
"up_path",
":",
"raise",
"RuntimeError",
"(",
"f\"Couldn't find project file starting from {start_path}\"",
")",
"else",
":",
"return",
"ModelConfig",
".",
"find_project_directory",
"(",
"up_path",
")"
] | Locate top-level project directory | [
"Locate",
"top",
"-",
"level",
"project",
"directory"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L18-L30 | train | 232,446 |
MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.from_file | def from_file(cls, filename: str, run_number: int, continue_training: bool = False, seed: int = None,
device: str = 'cuda', params=None):
""" Create model config from file """
with open(filename, 'r') as fp:
model_config_contents = Parser.parse(fp)
project_config_path = ModelConfig.find_project_directory(os.path.dirname(os.path.abspath(filename)))
with open(os.path.join(project_config_path, cls.PROJECT_FILE_NAME), 'r') as fp:
project_config_contents = Parser.parse(fp)
aggregate_dictionary = {
**project_config_contents,
**model_config_contents
}
return ModelConfig(
filename=filename,
configuration=aggregate_dictionary,
run_number=run_number,
project_dir=project_config_path,
continue_training=continue_training,
seed=seed,
device=device,
parameters=params
) | python | def from_file(cls, filename: str, run_number: int, continue_training: bool = False, seed: int = None,
device: str = 'cuda', params=None):
""" Create model config from file """
with open(filename, 'r') as fp:
model_config_contents = Parser.parse(fp)
project_config_path = ModelConfig.find_project_directory(os.path.dirname(os.path.abspath(filename)))
with open(os.path.join(project_config_path, cls.PROJECT_FILE_NAME), 'r') as fp:
project_config_contents = Parser.parse(fp)
aggregate_dictionary = {
**project_config_contents,
**model_config_contents
}
return ModelConfig(
filename=filename,
configuration=aggregate_dictionary,
run_number=run_number,
project_dir=project_config_path,
continue_training=continue_training,
seed=seed,
device=device,
parameters=params
) | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
":",
"str",
",",
"run_number",
":",
"int",
",",
"continue_training",
":",
"bool",
"=",
"False",
",",
"seed",
":",
"int",
"=",
"None",
",",
"device",
":",
"str",
"=",
"'cuda'",
",",
"params",
"=",
"None",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fp",
":",
"model_config_contents",
"=",
"Parser",
".",
"parse",
"(",
"fp",
")",
"project_config_path",
"=",
"ModelConfig",
".",
"find_project_directory",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"project_config_path",
",",
"cls",
".",
"PROJECT_FILE_NAME",
")",
",",
"'r'",
")",
"as",
"fp",
":",
"project_config_contents",
"=",
"Parser",
".",
"parse",
"(",
"fp",
")",
"aggregate_dictionary",
"=",
"{",
"*",
"*",
"project_config_contents",
",",
"*",
"*",
"model_config_contents",
"}",
"return",
"ModelConfig",
"(",
"filename",
"=",
"filename",
",",
"configuration",
"=",
"aggregate_dictionary",
",",
"run_number",
"=",
"run_number",
",",
"project_dir",
"=",
"project_config_path",
",",
"continue_training",
"=",
"continue_training",
",",
"seed",
"=",
"seed",
",",
"device",
"=",
"device",
",",
"parameters",
"=",
"params",
")"
] | Create model config from file | [
"Create",
"model",
"config",
"from",
"file"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L33-L58 | train | 232,447 |
MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.from_memory | def from_memory(cls, model_data: dict, run_number: int, project_dir: str,
continue_training=False, seed: int = None, device: str = 'cuda', params=None):
""" Create model config from supplied data """
return ModelConfig(
filename="[memory]",
configuration=model_data,
run_number=run_number,
project_dir=project_dir,
continue_training=continue_training,
seed=seed,
device=device,
parameters=params
) | python | def from_memory(cls, model_data: dict, run_number: int, project_dir: str,
continue_training=False, seed: int = None, device: str = 'cuda', params=None):
""" Create model config from supplied data """
return ModelConfig(
filename="[memory]",
configuration=model_data,
run_number=run_number,
project_dir=project_dir,
continue_training=continue_training,
seed=seed,
device=device,
parameters=params
) | [
"def",
"from_memory",
"(",
"cls",
",",
"model_data",
":",
"dict",
",",
"run_number",
":",
"int",
",",
"project_dir",
":",
"str",
",",
"continue_training",
"=",
"False",
",",
"seed",
":",
"int",
"=",
"None",
",",
"device",
":",
"str",
"=",
"'cuda'",
",",
"params",
"=",
"None",
")",
":",
"return",
"ModelConfig",
"(",
"filename",
"=",
"\"[memory]\"",
",",
"configuration",
"=",
"model_data",
",",
"run_number",
"=",
"run_number",
",",
"project_dir",
"=",
"project_dir",
",",
"continue_training",
"=",
"continue_training",
",",
"seed",
"=",
"seed",
",",
"device",
"=",
"device",
",",
"parameters",
"=",
"params",
")"
] | Create model config from supplied data | [
"Create",
"model",
"config",
"from",
"supplied",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L61-L73 | train | 232,448 |
MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.run_command | def run_command(self, command_name, varargs):
""" Instantiate model class """
command_descriptor = self.get_command(command_name)
return command_descriptor.run(*varargs) | python | def run_command(self, command_name, varargs):
""" Instantiate model class """
command_descriptor = self.get_command(command_name)
return command_descriptor.run(*varargs) | [
"def",
"run_command",
"(",
"self",
",",
"command_name",
",",
"varargs",
")",
":",
"command_descriptor",
"=",
"self",
".",
"get_command",
"(",
"command_name",
")",
"return",
"command_descriptor",
".",
"run",
"(",
"*",
"varargs",
")"
] | Instantiate model class | [
"Instantiate",
"model",
"class"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L109-L112 | train | 232,449 |
MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.project_data_dir | def project_data_dir(self, *args) -> str:
""" Directory where to store data """
return os.path.normpath(os.path.join(self.project_dir, 'data', *args)) | python | def project_data_dir(self, *args) -> str:
""" Directory where to store data """
return os.path.normpath(os.path.join(self.project_dir, 'data', *args)) | [
"def",
"project_data_dir",
"(",
"self",
",",
"*",
"args",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project_dir",
",",
"'data'",
",",
"*",
"args",
")",
")"
] | Directory where to store data | [
"Directory",
"where",
"to",
"store",
"data"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L128-L130 | train | 232,450 |
MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.output_dir | def output_dir(self, *args) -> str:
""" Directory where to store output """
return os.path.join(self.project_dir, 'output', *args) | python | def output_dir(self, *args) -> str:
""" Directory where to store output """
return os.path.join(self.project_dir, 'output', *args) | [
"def",
"output_dir",
"(",
"self",
",",
"*",
"args",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project_dir",
",",
"'output'",
",",
"*",
"args",
")"
] | Directory where to store output | [
"Directory",
"where",
"to",
"store",
"output"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L132-L134 | train | 232,451 |
MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.project_top_dir | def project_top_dir(self, *args) -> str:
""" Project top-level directory """
return os.path.join(self.project_dir, *args) | python | def project_top_dir(self, *args) -> str:
""" Project top-level directory """
return os.path.join(self.project_dir, *args) | [
"def",
"project_top_dir",
"(",
"self",
",",
"*",
"args",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"project_dir",
",",
"*",
"args",
")"
] | Project top-level directory | [
"Project",
"top",
"-",
"level",
"directory"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L136-L138 | train | 232,452 |
MillionIntegrals/vel | vel/internals/model_config.py | ModelConfig.provide_with_default | def provide_with_default(self, name, default=None):
""" Return a dependency-injected instance """
return self.provider.instantiate_by_name_with_default(name, default_value=default) | python | def provide_with_default(self, name, default=None):
""" Return a dependency-injected instance """
return self.provider.instantiate_by_name_with_default(name, default_value=default) | [
"def",
"provide_with_default",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"provider",
".",
"instantiate_by_name_with_default",
"(",
"name",
",",
"default_value",
"=",
"default",
")"
] | Return a dependency-injected instance | [
"Return",
"a",
"dependency",
"-",
"injected",
"instance"
] | e0726e1f63742b728966ccae0c8b825ea0ba491a | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/internals/model_config.py#L165-L167 | train | 232,453 |
douban/libmc | misc/runbench.py | benchmark_method | def benchmark_method(f):
"decorator to turn f into a factory of benchmarks"
@wraps(f)
def inner(name, *args, **kwargs):
return Benchmark(name, f, args, kwargs)
return inner | python | def benchmark_method(f):
"decorator to turn f into a factory of benchmarks"
@wraps(f)
def inner(name, *args, **kwargs):
return Benchmark(name, f, args, kwargs)
return inner | [
"def",
"benchmark_method",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Benchmark",
"(",
"name",
",",
"f",
",",
"args",
",",
"kwargs",
")",
"return",
"inner"
] | decorator to turn f into a factory of benchmarks | [
"decorator",
"to",
"turn",
"f",
"into",
"a",
"factory",
"of",
"benchmarks"
] | 12e5528e55708d08003671c10267287ed77e4dc4 | https://github.com/douban/libmc/blob/12e5528e55708d08003671c10267287ed77e4dc4/misc/runbench.py#L118-L123 | train | 232,454 |
douban/libmc | misc/runbench.py | bench | def bench(participants=participants, benchmarks=benchmarks,
bench_time=BENCH_TIME):
"""Do you even lift?"""
mcs = [p.factory() for p in participants]
means = [[] for p in participants]
stddevs = [[] for p in participants]
# Have each lifter do one benchmark each
last_fn = None
for benchmark_name, fn, args, kwargs in benchmarks:
logger.info('')
logger.info('%s', benchmark_name)
for i, (participant, mc) in enumerate(zip(participants, mcs)):
# FIXME: set before bench for get
if 'get' in fn.__name__:
last_fn(mc, *args, **kwargs)
sw = Stopwatch()
while sw.total() < bench_time:
with sw.timing():
fn(mc, *args, **kwargs)
means[i].append(sw.mean())
stddevs[i].append(sw.stddev())
logger.info(u'%76s: %s', participant.name, sw)
last_fn = fn
return means, stddevs | python | def bench(participants=participants, benchmarks=benchmarks,
bench_time=BENCH_TIME):
"""Do you even lift?"""
mcs = [p.factory() for p in participants]
means = [[] for p in participants]
stddevs = [[] for p in participants]
# Have each lifter do one benchmark each
last_fn = None
for benchmark_name, fn, args, kwargs in benchmarks:
logger.info('')
logger.info('%s', benchmark_name)
for i, (participant, mc) in enumerate(zip(participants, mcs)):
# FIXME: set before bench for get
if 'get' in fn.__name__:
last_fn(mc, *args, **kwargs)
sw = Stopwatch()
while sw.total() < bench_time:
with sw.timing():
fn(mc, *args, **kwargs)
means[i].append(sw.mean())
stddevs[i].append(sw.stddev())
logger.info(u'%76s: %s', participant.name, sw)
last_fn = fn
return means, stddevs | [
"def",
"bench",
"(",
"participants",
"=",
"participants",
",",
"benchmarks",
"=",
"benchmarks",
",",
"bench_time",
"=",
"BENCH_TIME",
")",
":",
"mcs",
"=",
"[",
"p",
".",
"factory",
"(",
")",
"for",
"p",
"in",
"participants",
"]",
"means",
"=",
"[",
"[",
"]",
"for",
"p",
"in",
"participants",
"]",
"stddevs",
"=",
"[",
"[",
"]",
"for",
"p",
"in",
"participants",
"]",
"# Have each lifter do one benchmark each",
"last_fn",
"=",
"None",
"for",
"benchmark_name",
",",
"fn",
",",
"args",
",",
"kwargs",
"in",
"benchmarks",
":",
"logger",
".",
"info",
"(",
"''",
")",
"logger",
".",
"info",
"(",
"'%s'",
",",
"benchmark_name",
")",
"for",
"i",
",",
"(",
"participant",
",",
"mc",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"participants",
",",
"mcs",
")",
")",
":",
"# FIXME: set before bench for get",
"if",
"'get'",
"in",
"fn",
".",
"__name__",
":",
"last_fn",
"(",
"mc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"sw",
"=",
"Stopwatch",
"(",
")",
"while",
"sw",
".",
"total",
"(",
")",
"<",
"bench_time",
":",
"with",
"sw",
".",
"timing",
"(",
")",
":",
"fn",
"(",
"mc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"means",
"[",
"i",
"]",
".",
"append",
"(",
"sw",
".",
"mean",
"(",
")",
")",
"stddevs",
"[",
"i",
"]",
".",
"append",
"(",
"sw",
".",
"stddev",
"(",
")",
")",
"logger",
".",
"info",
"(",
"u'%76s: %s'",
",",
"participant",
".",
"name",
",",
"sw",
")",
"last_fn",
"=",
"fn",
"return",
"means",
",",
"stddevs"
] | Do you even lift? | [
"Do",
"you",
"even",
"lift?"
] | 12e5528e55708d08003671c10267287ed77e4dc4 | https://github.com/douban/libmc/blob/12e5528e55708d08003671c10267287ed77e4dc4/misc/runbench.py#L266-L297 | train | 232,455 |
liampauling/betfair | betfairlightweight/resources/baseresource.py | BaseResource.strip_datetime | def strip_datetime(value):
"""
Converts value to datetime if string or int.
"""
if isinstance(value, basestring):
try:
return parse_datetime(value)
except ValueError:
return
elif isinstance(value, integer_types):
try:
return datetime.datetime.utcfromtimestamp(value / 1e3)
except (ValueError, OverflowError, OSError):
return | python | def strip_datetime(value):
"""
Converts value to datetime if string or int.
"""
if isinstance(value, basestring):
try:
return parse_datetime(value)
except ValueError:
return
elif isinstance(value, integer_types):
try:
return datetime.datetime.utcfromtimestamp(value / 1e3)
except (ValueError, OverflowError, OSError):
return | [
"def",
"strip_datetime",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
":",
"try",
":",
"return",
"parse_datetime",
"(",
"value",
")",
"except",
"ValueError",
":",
"return",
"elif",
"isinstance",
"(",
"value",
",",
"integer_types",
")",
":",
"try",
":",
"return",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"value",
"/",
"1e3",
")",
"except",
"(",
"ValueError",
",",
"OverflowError",
",",
"OSError",
")",
":",
"return"
] | Converts value to datetime if string or int. | [
"Converts",
"value",
"to",
"datetime",
"if",
"string",
"or",
"int",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/resources/baseresource.py#L26-L39 | train | 232,456 |
liampauling/betfair | betfairlightweight/baseclient.py | BaseClient.set_session_token | def set_session_token(self, session_token):
"""
Sets session token and new login time.
:param str session_token: Session token from request.
"""
self.session_token = session_token
self._login_time = datetime.datetime.now() | python | def set_session_token(self, session_token):
"""
Sets session token and new login time.
:param str session_token: Session token from request.
"""
self.session_token = session_token
self._login_time = datetime.datetime.now() | [
"def",
"set_session_token",
"(",
"self",
",",
"session_token",
")",
":",
"self",
".",
"session_token",
"=",
"session_token",
"self",
".",
"_login_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")"
] | Sets session token and new login time.
:param str session_token: Session token from request. | [
"Sets",
"session",
"token",
"and",
"new",
"login",
"time",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/baseclient.py#L78-L85 | train | 232,457 |
liampauling/betfair | betfairlightweight/baseclient.py | BaseClient.get_password | def get_password(self):
"""
If password is not provided will look in environment variables
for username+'password'.
"""
if self.password is None:
if os.environ.get(self.username+'password'):
self.password = os.environ.get(self.username+'password')
else:
raise PasswordError(self.username) | python | def get_password(self):
"""
If password is not provided will look in environment variables
for username+'password'.
"""
if self.password is None:
if os.environ.get(self.username+'password'):
self.password = os.environ.get(self.username+'password')
else:
raise PasswordError(self.username) | [
"def",
"get_password",
"(",
"self",
")",
":",
"if",
"self",
".",
"password",
"is",
"None",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"self",
".",
"username",
"+",
"'password'",
")",
":",
"self",
".",
"password",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"self",
".",
"username",
"+",
"'password'",
")",
"else",
":",
"raise",
"PasswordError",
"(",
"self",
".",
"username",
")"
] | If password is not provided will look in environment variables
for username+'password'. | [
"If",
"password",
"is",
"not",
"provided",
"will",
"look",
"in",
"environment",
"variables",
"for",
"username",
"+",
"password",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/baseclient.py#L87-L96 | train | 232,458 |
liampauling/betfair | betfairlightweight/baseclient.py | BaseClient.get_app_key | def get_app_key(self):
"""
If app_key is not provided will look in environment
variables for username.
"""
if self.app_key is None:
if os.environ.get(self.username):
self.app_key = os.environ.get(self.username)
else:
raise AppKeyError(self.username) | python | def get_app_key(self):
"""
If app_key is not provided will look in environment
variables for username.
"""
if self.app_key is None:
if os.environ.get(self.username):
self.app_key = os.environ.get(self.username)
else:
raise AppKeyError(self.username) | [
"def",
"get_app_key",
"(",
"self",
")",
":",
"if",
"self",
".",
"app_key",
"is",
"None",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"self",
".",
"username",
")",
":",
"self",
".",
"app_key",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"self",
".",
"username",
")",
"else",
":",
"raise",
"AppKeyError",
"(",
"self",
".",
"username",
")"
] | If app_key is not provided will look in environment
variables for username. | [
"If",
"app_key",
"is",
"not",
"provided",
"will",
"look",
"in",
"environment",
"variables",
"for",
"username",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/baseclient.py#L98-L107 | train | 232,459 |
liampauling/betfair | betfairlightweight/baseclient.py | BaseClient.session_expired | def session_expired(self):
"""
Returns True if login_time not set or seconds since
login time is greater than 200 mins.
"""
if not self._login_time or (datetime.datetime.now()-self._login_time).total_seconds() > 12000:
return True | python | def session_expired(self):
"""
Returns True if login_time not set or seconds since
login time is greater than 200 mins.
"""
if not self._login_time or (datetime.datetime.now()-self._login_time).total_seconds() > 12000:
return True | [
"def",
"session_expired",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_login_time",
"or",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_login_time",
")",
".",
"total_seconds",
"(",
")",
">",
"12000",
":",
"return",
"True"
] | Returns True if login_time not set or seconds since
login time is greater than 200 mins. | [
"Returns",
"True",
"if",
"login_time",
"not",
"set",
"or",
"seconds",
"since",
"login",
"time",
"is",
"greater",
"than",
"200",
"mins",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/baseclient.py#L117-L123 | train | 232,460 |
liampauling/betfair | betfairlightweight/utils.py | check_status_code | def check_status_code(response, codes=None):
"""
Checks response.status_code is in codes.
:param requests.request response: Requests response
:param list codes: List of accepted codes or callable
:raises: StatusCodeError if code invalid
"""
codes = codes or [200]
if response.status_code not in codes:
raise StatusCodeError(response.status_code) | python | def check_status_code(response, codes=None):
"""
Checks response.status_code is in codes.
:param requests.request response: Requests response
:param list codes: List of accepted codes or callable
:raises: StatusCodeError if code invalid
"""
codes = codes or [200]
if response.status_code not in codes:
raise StatusCodeError(response.status_code) | [
"def",
"check_status_code",
"(",
"response",
",",
"codes",
"=",
"None",
")",
":",
"codes",
"=",
"codes",
"or",
"[",
"200",
"]",
"if",
"response",
".",
"status_code",
"not",
"in",
"codes",
":",
"raise",
"StatusCodeError",
"(",
"response",
".",
"status_code",
")"
] | Checks response.status_code is in codes.
:param requests.request response: Requests response
:param list codes: List of accepted codes or callable
:raises: StatusCodeError if code invalid | [
"Checks",
"response",
".",
"status_code",
"is",
"in",
"codes",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/utils.py#L7-L17 | train | 232,461 |
liampauling/betfair | betfairlightweight/endpoints/betting.py | Betting.list_runner_book | def list_runner_book(self, market_id, selection_id, handicap=None, price_projection=None, order_projection=None,
match_projection=None, include_overall_position=None, partition_matched_by_strategy_ref=None,
customer_strategy_refs=None, currency_code=None, matched_since=None, bet_ids=None, locale=None,
session=None, lightweight=None):
"""
Returns a list of dynamic data about a market and a specified runner.
Dynamic data includes prices, the status of the market, the status of selections,
the traded volume, and the status of any orders you have placed in the market
:param unicode market_id: The unique id for the market
:param int selection_id: The unique id for the selection in the market
:param double handicap: The projection of price data you want to receive in the response
:param dict price_projection: The projection of price data you want to receive in the response
:param str order_projection: The orders you want to receive in the response
:param str match_projection: If you ask for orders, specifies the representation of matches
:param bool include_overall_position: If you ask for orders, returns matches for each selection
:param bool partition_matched_by_strategy_ref: If you ask for orders, returns the breakdown of matches
by strategy for each selection
:param list customer_strategy_refs: If you ask for orders, restricts the results to orders matching
any of the specified set of customer defined strategies
:param str currency_code: A Betfair standard currency code
:param str matched_since: If you ask for orders, restricts the results to orders that have at
least one fragment matched since the specified date
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param str locale: The language used for the response
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.MarketBook]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listRunnerBook')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.MarketBook, elapsed_time, lightweight) | python | def list_runner_book(self, market_id, selection_id, handicap=None, price_projection=None, order_projection=None,
match_projection=None, include_overall_position=None, partition_matched_by_strategy_ref=None,
customer_strategy_refs=None, currency_code=None, matched_since=None, bet_ids=None, locale=None,
session=None, lightweight=None):
"""
Returns a list of dynamic data about a market and a specified runner.
Dynamic data includes prices, the status of the market, the status of selections,
the traded volume, and the status of any orders you have placed in the market
:param unicode market_id: The unique id for the market
:param int selection_id: The unique id for the selection in the market
:param double handicap: The projection of price data you want to receive in the response
:param dict price_projection: The projection of price data you want to receive in the response
:param str order_projection: The orders you want to receive in the response
:param str match_projection: If you ask for orders, specifies the representation of matches
:param bool include_overall_position: If you ask for orders, returns matches for each selection
:param bool partition_matched_by_strategy_ref: If you ask for orders, returns the breakdown of matches
by strategy for each selection
:param list customer_strategy_refs: If you ask for orders, restricts the results to orders matching
any of the specified set of customer defined strategies
:param str currency_code: A Betfair standard currency code
:param str matched_since: If you ask for orders, restricts the results to orders that have at
least one fragment matched since the specified date
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param str locale: The language used for the response
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.MarketBook]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listRunnerBook')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.MarketBook, elapsed_time, lightweight) | [
"def",
"list_runner_book",
"(",
"self",
",",
"market_id",
",",
"selection_id",
",",
"handicap",
"=",
"None",
",",
"price_projection",
"=",
"None",
",",
"order_projection",
"=",
"None",
",",
"match_projection",
"=",
"None",
",",
"include_overall_position",
"=",
"None",
",",
"partition_matched_by_strategy_ref",
"=",
"None",
",",
"customer_strategy_refs",
"=",
"None",
",",
"currency_code",
"=",
"None",
",",
"matched_since",
"=",
"None",
",",
"bet_ids",
"=",
"None",
",",
"locale",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'listRunnerBook'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"MarketBook",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns a list of dynamic data about a market and a specified runner.
Dynamic data includes prices, the status of the market, the status of selections,
the traded volume, and the status of any orders you have placed in the market
:param unicode market_id: The unique id for the market
:param int selection_id: The unique id for the selection in the market
:param double handicap: The projection of price data you want to receive in the response
:param dict price_projection: The projection of price data you want to receive in the response
:param str order_projection: The orders you want to receive in the response
:param str match_projection: If you ask for orders, specifies the representation of matches
:param bool include_overall_position: If you ask for orders, returns matches for each selection
:param bool partition_matched_by_strategy_ref: If you ask for orders, returns the breakdown of matches
by strategy for each selection
:param list customer_strategy_refs: If you ask for orders, restricts the results to orders matching
any of the specified set of customer defined strategies
:param str currency_code: A Betfair standard currency code
:param str matched_since: If you ask for orders, restricts the results to orders that have at
least one fragment matched since the specified date
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param str locale: The language used for the response
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.MarketBook] | [
"Returns",
"a",
"list",
"of",
"dynamic",
"data",
"about",
"a",
"market",
"and",
"a",
"specified",
"runner",
".",
"Dynamic",
"data",
"includes",
"prices",
"the",
"status",
"of",
"the",
"market",
"the",
"status",
"of",
"selections",
"the",
"traded",
"volume",
"and",
"the",
"status",
"of",
"any",
"orders",
"you",
"have",
"placed",
"in",
"the",
"market"
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/betting.py#L193-L226 | train | 232,462 |
liampauling/betfair | betfairlightweight/endpoints/betting.py | Betting.list_current_orders | def list_current_orders(self, bet_ids=None, market_ids=None, order_projection=None, customer_order_refs=None,
customer_strategy_refs=None, date_range=time_range(), order_by=None, sort_dir=None,
from_record=None, record_count=None, session=None, lightweight=None):
"""
Returns a list of your current orders.
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param list market_ids: One or more market ids
:param str order_projection: Optionally restricts the results to the specified order status
:param list customer_order_refs: Optionally restricts the results to the specified customer order references
:param list customer_strategy_refs: Optionally restricts the results to the specified customer strategy
references
:param dict date_range: Optionally restricts the results to be from/to the specified date, these dates
are contextual to the orders being returned and therefore the dates used to filter on will change
to placed, matched, voided or settled dates depending on the orderBy
:param str order_by: Specifies how the results will be ordered. If no value is passed in, it defaults to BY_BET
:param str sort_dir: Specifies the direction the results will be sorted in
:param int from_record: Specifies the first record that will be returned
:param int record_count: Specifies how many records will be returned from the index position 'fromRecord'
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.CurrentOrders
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listCurrentOrders')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.CurrentOrders, elapsed_time, lightweight) | python | def list_current_orders(self, bet_ids=None, market_ids=None, order_projection=None, customer_order_refs=None,
customer_strategy_refs=None, date_range=time_range(), order_by=None, sort_dir=None,
from_record=None, record_count=None, session=None, lightweight=None):
"""
Returns a list of your current orders.
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param list market_ids: One or more market ids
:param str order_projection: Optionally restricts the results to the specified order status
:param list customer_order_refs: Optionally restricts the results to the specified customer order references
:param list customer_strategy_refs: Optionally restricts the results to the specified customer strategy
references
:param dict date_range: Optionally restricts the results to be from/to the specified date, these dates
are contextual to the orders being returned and therefore the dates used to filter on will change
to placed, matched, voided or settled dates depending on the orderBy
:param str order_by: Specifies how the results will be ordered. If no value is passed in, it defaults to BY_BET
:param str sort_dir: Specifies the direction the results will be sorted in
:param int from_record: Specifies the first record that will be returned
:param int record_count: Specifies how many records will be returned from the index position 'fromRecord'
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.CurrentOrders
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listCurrentOrders')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.CurrentOrders, elapsed_time, lightweight) | [
"def",
"list_current_orders",
"(",
"self",
",",
"bet_ids",
"=",
"None",
",",
"market_ids",
"=",
"None",
",",
"order_projection",
"=",
"None",
",",
"customer_order_refs",
"=",
"None",
",",
"customer_strategy_refs",
"=",
"None",
",",
"date_range",
"=",
"time_range",
"(",
")",
",",
"order_by",
"=",
"None",
",",
"sort_dir",
"=",
"None",
",",
"from_record",
"=",
"None",
",",
"record_count",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'listCurrentOrders'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"CurrentOrders",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns a list of your current orders.
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param list market_ids: One or more market ids
:param str order_projection: Optionally restricts the results to the specified order status
:param list customer_order_refs: Optionally restricts the results to the specified customer order references
:param list customer_strategy_refs: Optionally restricts the results to the specified customer strategy
references
:param dict date_range: Optionally restricts the results to be from/to the specified date, these dates
are contextual to the orders being returned and therefore the dates used to filter on will change
to placed, matched, voided or settled dates depending on the orderBy
:param str order_by: Specifies how the results will be ordered. If no value is passed in, it defaults to BY_BET
:param str sort_dir: Specifies the direction the results will be sorted in
:param int from_record: Specifies the first record that will be returned
:param int record_count: Specifies how many records will be returned from the index position 'fromRecord'
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.CurrentOrders | [
"Returns",
"a",
"list",
"of",
"your",
"current",
"orders",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/betting.py#L228-L255 | train | 232,463 |
liampauling/betfair | betfairlightweight/endpoints/betting.py | Betting.list_cleared_orders | def list_cleared_orders(self, bet_status='SETTLED', event_type_ids=None, event_ids=None, market_ids=None,
runner_ids=None, bet_ids=None, customer_order_refs=None, customer_strategy_refs=None,
side=None, settled_date_range=time_range(), group_by=None, include_item_description=None,
locale=None, from_record=None, record_count=None, session=None, lightweight=None):
"""
Returns a list of settled bets based on the bet status,
ordered by settled date.
:param str bet_status: Restricts the results to the specified status
:param list event_type_ids: Optionally restricts the results to the specified Event Type IDs
:param list event_ids: Optionally restricts the results to the specified Event IDs
:param list market_ids: Optionally restricts the results to the specified market IDs
:param list runner_ids: Optionally restricts the results to the specified Runners
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param list customer_order_refs: Optionally restricts the results to the specified customer order references
:param list customer_strategy_refs: Optionally restricts the results to the specified customer strategy
references
:param str side: Optionally restricts the results to the specified side
:param dict settled_date_range: Optionally restricts the results to be from/to the specified settled date
:param str group_by: How to aggregate the lines, if not supplied then the lowest level is returned
:param bool include_item_description: If true then an ItemDescription object is included in the response
:param str locale: The language used for the response
:param int from_record: Specifies the first record that will be returned
:param int record_count: Specifies how many records will be returned from the index position 'fromRecord'
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.ClearedOrders
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listClearedOrders')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.ClearedOrders, elapsed_time, lightweight) | python | def list_cleared_orders(self, bet_status='SETTLED', event_type_ids=None, event_ids=None, market_ids=None,
runner_ids=None, bet_ids=None, customer_order_refs=None, customer_strategy_refs=None,
side=None, settled_date_range=time_range(), group_by=None, include_item_description=None,
locale=None, from_record=None, record_count=None, session=None, lightweight=None):
"""
Returns a list of settled bets based on the bet status,
ordered by settled date.
:param str bet_status: Restricts the results to the specified status
:param list event_type_ids: Optionally restricts the results to the specified Event Type IDs
:param list event_ids: Optionally restricts the results to the specified Event IDs
:param list market_ids: Optionally restricts the results to the specified market IDs
:param list runner_ids: Optionally restricts the results to the specified Runners
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param list customer_order_refs: Optionally restricts the results to the specified customer order references
:param list customer_strategy_refs: Optionally restricts the results to the specified customer strategy
references
:param str side: Optionally restricts the results to the specified side
:param dict settled_date_range: Optionally restricts the results to be from/to the specified settled date
:param str group_by: How to aggregate the lines, if not supplied then the lowest level is returned
:param bool include_item_description: If true then an ItemDescription object is included in the response
:param str locale: The language used for the response
:param int from_record: Specifies the first record that will be returned
:param int record_count: Specifies how many records will be returned from the index position 'fromRecord'
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.ClearedOrders
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listClearedOrders')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.ClearedOrders, elapsed_time, lightweight) | [
"def",
"list_cleared_orders",
"(",
"self",
",",
"bet_status",
"=",
"'SETTLED'",
",",
"event_type_ids",
"=",
"None",
",",
"event_ids",
"=",
"None",
",",
"market_ids",
"=",
"None",
",",
"runner_ids",
"=",
"None",
",",
"bet_ids",
"=",
"None",
",",
"customer_order_refs",
"=",
"None",
",",
"customer_strategy_refs",
"=",
"None",
",",
"side",
"=",
"None",
",",
"settled_date_range",
"=",
"time_range",
"(",
")",
",",
"group_by",
"=",
"None",
",",
"include_item_description",
"=",
"None",
",",
"locale",
"=",
"None",
",",
"from_record",
"=",
"None",
",",
"record_count",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'listClearedOrders'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"ClearedOrders",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns a list of settled bets based on the bet status,
ordered by settled date.
:param str bet_status: Restricts the results to the specified status
:param list event_type_ids: Optionally restricts the results to the specified Event Type IDs
:param list event_ids: Optionally restricts the results to the specified Event IDs
:param list market_ids: Optionally restricts the results to the specified market IDs
:param list runner_ids: Optionally restricts the results to the specified Runners
:param list bet_ids: If you ask for orders, restricts the results to orders with the specified bet IDs
:param list customer_order_refs: Optionally restricts the results to the specified customer order references
:param list customer_strategy_refs: Optionally restricts the results to the specified customer strategy
references
:param str side: Optionally restricts the results to the specified side
:param dict settled_date_range: Optionally restricts the results to be from/to the specified settled date
:param str group_by: How to aggregate the lines, if not supplied then the lowest level is returned
:param bool include_item_description: If true then an ItemDescription object is included in the response
:param str locale: The language used for the response
:param int from_record: Specifies the first record that will be returned
:param int record_count: Specifies how many records will be returned from the index position 'fromRecord'
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.ClearedOrders | [
"Returns",
"a",
"list",
"of",
"settled",
"bets",
"based",
"on",
"the",
"bet",
"status",
"ordered",
"by",
"settled",
"date",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/betting.py#L257-L289 | train | 232,464 |
liampauling/betfair | betfairlightweight/endpoints/betting.py | Betting.list_market_profit_and_loss | def list_market_profit_and_loss(self, market_ids, include_settled_bets=None, include_bsp_bets=None,
net_of_commission=None, session=None, lightweight=None):
"""
Retrieve profit and loss for a given list of OPEN markets.
:param list market_ids: List of markets to calculate profit and loss
:param bool include_settled_bets: Option to include settled bets (partially settled markets only)
:param bool include_bsp_bets: Option to include BSP bets
:param bool net_of_commission: Option to return profit and loss net of users current commission
rate for this market including any special tariffs
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.MarketProfitLoss]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listMarketProfitAndLoss')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.MarketProfitLoss, elapsed_time, lightweight) | python | def list_market_profit_and_loss(self, market_ids, include_settled_bets=None, include_bsp_bets=None,
net_of_commission=None, session=None, lightweight=None):
"""
Retrieve profit and loss for a given list of OPEN markets.
:param list market_ids: List of markets to calculate profit and loss
:param bool include_settled_bets: Option to include settled bets (partially settled markets only)
:param bool include_bsp_bets: Option to include BSP bets
:param bool net_of_commission: Option to return profit and loss net of users current commission
rate for this market including any special tariffs
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.MarketProfitLoss]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listMarketProfitAndLoss')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.MarketProfitLoss, elapsed_time, lightweight) | [
"def",
"list_market_profit_and_loss",
"(",
"self",
",",
"market_ids",
",",
"include_settled_bets",
"=",
"None",
",",
"include_bsp_bets",
"=",
"None",
",",
"net_of_commission",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'listMarketProfitAndLoss'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"MarketProfitLoss",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Retrieve profit and loss for a given list of OPEN markets.
:param list market_ids: List of markets to calculate profit and loss
:param bool include_settled_bets: Option to include settled bets (partially settled markets only)
:param bool include_bsp_bets: Option to include BSP bets
:param bool net_of_commission: Option to return profit and loss net of users current commission
rate for this market including any special tariffs
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.MarketProfitLoss] | [
"Retrieve",
"profit",
"and",
"loss",
"for",
"a",
"given",
"list",
"of",
"OPEN",
"markets",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/betting.py#L291-L309 | train | 232,465 |
liampauling/betfair | betfairlightweight/endpoints/betting.py | Betting.place_orders | def place_orders(self, market_id, instructions, customer_ref=None, market_version=None,
customer_strategy_ref=None, async_=None, session=None, lightweight=None):
"""
Place new orders into market.
:param str market_id: The market id these orders are to be placed on
:param list instructions: The number of place instructions
:param str customer_ref: Optional parameter allowing the client to pass a unique string
(up to 32 chars) that is used to de-dupe mistaken re-submissions
:param dict market_version: Optional parameter allowing the client to specify which
version of the market the orders should be placed on, e.g. "{'version': 123456}"
:param str customer_strategy_ref: An optional reference customers can use to specify
which strategy has sent the order
:param bool async_: An optional flag (not setting equates to false) which specifies if
the orders should be placed asynchronously
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.PlaceOrders
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'placeOrders')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.PlaceOrders, elapsed_time, lightweight) | python | def place_orders(self, market_id, instructions, customer_ref=None, market_version=None,
customer_strategy_ref=None, async_=None, session=None, lightweight=None):
"""
Place new orders into market.
:param str market_id: The market id these orders are to be placed on
:param list instructions: The number of place instructions
:param str customer_ref: Optional parameter allowing the client to pass a unique string
(up to 32 chars) that is used to de-dupe mistaken re-submissions
:param dict market_version: Optional parameter allowing the client to specify which
version of the market the orders should be placed on, e.g. "{'version': 123456}"
:param str customer_strategy_ref: An optional reference customers can use to specify
which strategy has sent the order
:param bool async_: An optional flag (not setting equates to false) which specifies if
the orders should be placed asynchronously
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.PlaceOrders
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'placeOrders')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.PlaceOrders, elapsed_time, lightweight) | [
"def",
"place_orders",
"(",
"self",
",",
"market_id",
",",
"instructions",
",",
"customer_ref",
"=",
"None",
",",
"market_version",
"=",
"None",
",",
"customer_strategy_ref",
"=",
"None",
",",
"async_",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'placeOrders'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"PlaceOrders",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Place new orders into market.
:param str market_id: The market id these orders are to be placed on
:param list instructions: The number of place instructions
:param str customer_ref: Optional parameter allowing the client to pass a unique string
(up to 32 chars) that is used to de-dupe mistaken re-submissions
:param dict market_version: Optional parameter allowing the client to specify which
version of the market the orders should be placed on, e.g. "{'version': 123456}"
:param str customer_strategy_ref: An optional reference customers can use to specify
which strategy has sent the order
:param bool async_: An optional flag (not setting equates to false) which specifies if
the orders should be placed asynchronously
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.PlaceOrders | [
"Place",
"new",
"orders",
"into",
"market",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/betting.py#L311-L334 | train | 232,466 |
liampauling/betfair | betfairlightweight/streaming/cache.py | MarketBookCache.serialise | def serialise(self):
"""Creates standard market book json response,
will error if EX_MARKET_DEF not incl.
"""
return {
'marketId': self.market_id,
'totalAvailable': None,
'isMarketDataDelayed': None,
'lastMatchTime': None,
'betDelay': self.market_definition.get('betDelay'),
'version': self.market_definition.get('version'),
'complete': self.market_definition.get('complete'),
'runnersVoidable': self.market_definition.get('runnersVoidable'),
'totalMatched': self.total_matched,
'status': self.market_definition.get('status'),
'bspReconciled': self.market_definition.get('bspReconciled'),
'crossMatching': self.market_definition.get('crossMatching'),
'inplay': self.market_definition.get('inPlay'),
'numberOfWinners': self.market_definition.get('numberOfWinners'),
'numberOfRunners': len(self.market_definition.get('runners')),
'numberOfActiveRunners': self.market_definition.get('numberOfActiveRunners'),
'runners': [
runner.serialise(
self.market_definition_runner_dict[(runner.selection_id, runner.handicap)]
) for runner in self.runners
],
'publishTime': self.publish_time,
'priceLadderDefinition': self.market_definition.get('priceLadderDefinition'),
'keyLineDescription': self.market_definition.get('keyLineDefinition'),
'marketDefinition': self.market_definition, # used in lightweight
} | python | def serialise(self):
"""Creates standard market book json response,
will error if EX_MARKET_DEF not incl.
"""
return {
'marketId': self.market_id,
'totalAvailable': None,
'isMarketDataDelayed': None,
'lastMatchTime': None,
'betDelay': self.market_definition.get('betDelay'),
'version': self.market_definition.get('version'),
'complete': self.market_definition.get('complete'),
'runnersVoidable': self.market_definition.get('runnersVoidable'),
'totalMatched': self.total_matched,
'status': self.market_definition.get('status'),
'bspReconciled': self.market_definition.get('bspReconciled'),
'crossMatching': self.market_definition.get('crossMatching'),
'inplay': self.market_definition.get('inPlay'),
'numberOfWinners': self.market_definition.get('numberOfWinners'),
'numberOfRunners': len(self.market_definition.get('runners')),
'numberOfActiveRunners': self.market_definition.get('numberOfActiveRunners'),
'runners': [
runner.serialise(
self.market_definition_runner_dict[(runner.selection_id, runner.handicap)]
) for runner in self.runners
],
'publishTime': self.publish_time,
'priceLadderDefinition': self.market_definition.get('priceLadderDefinition'),
'keyLineDescription': self.market_definition.get('keyLineDefinition'),
'marketDefinition': self.market_definition, # used in lightweight
} | [
"def",
"serialise",
"(",
"self",
")",
":",
"return",
"{",
"'marketId'",
":",
"self",
".",
"market_id",
",",
"'totalAvailable'",
":",
"None",
",",
"'isMarketDataDelayed'",
":",
"None",
",",
"'lastMatchTime'",
":",
"None",
",",
"'betDelay'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'betDelay'",
")",
",",
"'version'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'version'",
")",
",",
"'complete'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'complete'",
")",
",",
"'runnersVoidable'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'runnersVoidable'",
")",
",",
"'totalMatched'",
":",
"self",
".",
"total_matched",
",",
"'status'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'status'",
")",
",",
"'bspReconciled'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'bspReconciled'",
")",
",",
"'crossMatching'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'crossMatching'",
")",
",",
"'inplay'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'inPlay'",
")",
",",
"'numberOfWinners'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'numberOfWinners'",
")",
",",
"'numberOfRunners'",
":",
"len",
"(",
"self",
".",
"market_definition",
".",
"get",
"(",
"'runners'",
")",
")",
",",
"'numberOfActiveRunners'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'numberOfActiveRunners'",
")",
",",
"'runners'",
":",
"[",
"runner",
".",
"serialise",
"(",
"self",
".",
"market_definition_runner_dict",
"[",
"(",
"runner",
".",
"selection_id",
",",
"runner",
".",
"handicap",
")",
"]",
")",
"for",
"runner",
"in",
"self",
".",
"runners",
"]",
",",
"'publishTime'",
":",
"self",
".",
"publish_time",
",",
"'priceLadderDefinition'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'priceLadderDefinition'",
")",
",",
"'keyLineDescription'",
":",
"self",
".",
"market_definition",
".",
"get",
"(",
"'keyLineDefinition'",
")",
",",
"'marketDefinition'",
":",
"self",
".",
"market_definition",
",",
"# used in lightweight",
"}"
] | Creates standard market book json response,
will error if EX_MARKET_DEF not incl. | [
"Creates",
"standard",
"market",
"book",
"json",
"response",
"will",
"error",
"if",
"EX_MARKET_DEF",
"not",
"incl",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/cache.py#L223-L253 | train | 232,467 |
liampauling/betfair | betfairlightweight/endpoints/scores.py | Scores.list_race_details | def list_race_details(self, meeting_ids=None, race_ids=None, session=None, lightweight=None):
"""
Search for races to get their details.
:param dict meeting_ids: Optionally restricts the results to the specified meeting IDs.
The unique Id for the meeting equivalent to the eventId for that specific race as
returned by listEvents
:param str race_ids: Optionally restricts the results to the specified race IDs. The
unique Id for the race in the format meetingid.raceTime (hhmm). raceTime is in GMT
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.RaceDetail]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listRaceDetails')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.RaceDetails, elapsed_time, lightweight) | python | def list_race_details(self, meeting_ids=None, race_ids=None, session=None, lightweight=None):
"""
Search for races to get their details.
:param dict meeting_ids: Optionally restricts the results to the specified meeting IDs.
The unique Id for the meeting equivalent to the eventId for that specific race as
returned by listEvents
:param str race_ids: Optionally restricts the results to the specified race IDs. The
unique Id for the race in the format meetingid.raceTime (hhmm). raceTime is in GMT
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.RaceDetail]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listRaceDetails')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.RaceDetails, elapsed_time, lightweight) | [
"def",
"list_race_details",
"(",
"self",
",",
"meeting_ids",
"=",
"None",
",",
"race_ids",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'listRaceDetails'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"RaceDetails",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Search for races to get their details.
:param dict meeting_ids: Optionally restricts the results to the specified meeting IDs.
The unique Id for the meeting equivalent to the eventId for that specific race as
returned by listEvents
:param str race_ids: Optionally restricts the results to the specified race IDs. The
unique Id for the race in the format meetingid.raceTime (hhmm). raceTime is in GMT
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.RaceDetail] | [
"Search",
"for",
"races",
"to",
"get",
"their",
"details",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/scores.py#L13-L30 | train | 232,468 |
liampauling/betfair | betfairlightweight/endpoints/scores.py | Scores.list_available_events | def list_available_events(self, event_ids=None, event_type_ids=None, event_status=None, session=None,
lightweight=None):
"""
Search for events that have live score data available.
:param list event_ids: Optionally restricts the results to the specified event IDs
:param list event_type_ids: Optionally restricts the results to the specified event type IDs
:param list event_status: Optionally restricts the results to the specified event status
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.AvailableEvent]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listAvailableEvents')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.AvailableEvent, elapsed_time, lightweight) | python | def list_available_events(self, event_ids=None, event_type_ids=None, event_status=None, session=None,
lightweight=None):
"""
Search for events that have live score data available.
:param list event_ids: Optionally restricts the results to the specified event IDs
:param list event_type_ids: Optionally restricts the results to the specified event type IDs
:param list event_status: Optionally restricts the results to the specified event status
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.AvailableEvent]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listAvailableEvents')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.AvailableEvent, elapsed_time, lightweight) | [
"def",
"list_available_events",
"(",
"self",
",",
"event_ids",
"=",
"None",
",",
"event_type_ids",
"=",
"None",
",",
"event_status",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'listAvailableEvents'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"AvailableEvent",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Search for events that have live score data available.
:param list event_ids: Optionally restricts the results to the specified event IDs
:param list event_type_ids: Optionally restricts the results to the specified event type IDs
:param list event_status: Optionally restricts the results to the specified event status
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.AvailableEvent] | [
"Search",
"for",
"events",
"that",
"have",
"live",
"score",
"data",
"available",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/scores.py#L34-L50 | train | 232,469 |
liampauling/betfair | betfairlightweight/endpoints/scores.py | Scores.list_scores | def list_scores(self, update_keys, session=None, lightweight=None):
"""
Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Score]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listScores')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.Score, elapsed_time, lightweight) | python | def list_scores(self, update_keys, session=None, lightweight=None):
"""
Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Score]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listScores')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.Score, elapsed_time, lightweight) | [
"def",
"list_scores",
"(",
"self",
",",
"update_keys",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'listScores'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"Score",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Score] | [
"Returns",
"a",
"list",
"of",
"current",
"scores",
"for",
"the",
"given",
"events",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/scores.py#L52-L66 | train | 232,470 |
liampauling/betfair | betfairlightweight/endpoints/scores.py | Scores.list_incidents | def list_incidents(self, update_keys, session=None, lightweight=None):
"""
Returns a list of incidents for the given events.
:param dict update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Incidents]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listIncidents')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.Incidents, elapsed_time, lightweight) | python | def list_incidents(self, update_keys, session=None, lightweight=None):
"""
Returns a list of incidents for the given events.
:param dict update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Incidents]
"""
params = clean_locals(locals())
method = '%s%s' % (self.URI, 'listIncidents')
(response, elapsed_time) = self.request(method, params, session)
return self.process_response(response, resources.Incidents, elapsed_time, lightweight) | [
"def",
"list_incidents",
"(",
"self",
",",
"update_keys",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"URI",
",",
"'listIncidents'",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"Incidents",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns a list of incidents for the given events.
:param dict update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Incidents] | [
"Returns",
"a",
"list",
"of",
"incidents",
"for",
"the",
"given",
"events",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/scores.py#L68-L82 | train | 232,471 |
liampauling/betfair | betfairlightweight/endpoints/inplayservice.py | InPlayService.get_event_timeline | def get_event_timeline(self, event_id, session=None, lightweight=None):
"""
Returns event timeline for event id provided.
:param int event_id: Event id to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.EventTimeline
"""
url = '%s%s' % (self.url, 'eventTimeline')
params = {
'eventId': event_id,
'alt': 'json',
'regionCode': 'UK',
'locale': 'en_GB'
}
(response, elapsed_time) = self.request(params=params, session=session, url=url)
return self.process_response(response, resources.EventTimeline, elapsed_time, lightweight) | python | def get_event_timeline(self, event_id, session=None, lightweight=None):
"""
Returns event timeline for event id provided.
:param int event_id: Event id to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.EventTimeline
"""
url = '%s%s' % (self.url, 'eventTimeline')
params = {
'eventId': event_id,
'alt': 'json',
'regionCode': 'UK',
'locale': 'en_GB'
}
(response, elapsed_time) = self.request(params=params, session=session, url=url)
return self.process_response(response, resources.EventTimeline, elapsed_time, lightweight) | [
"def",
"get_event_timeline",
"(",
"self",
",",
"event_id",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"url",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"url",
",",
"'eventTimeline'",
")",
"params",
"=",
"{",
"'eventId'",
":",
"event_id",
",",
"'alt'",
":",
"'json'",
",",
"'regionCode'",
":",
"'UK'",
",",
"'locale'",
":",
"'en_GB'",
"}",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"params",
"=",
"params",
",",
"session",
"=",
"session",
",",
"url",
"=",
"url",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"EventTimeline",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns event timeline for event id provided.
:param int event_id: Event id to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.EventTimeline | [
"Returns",
"event",
"timeline",
"for",
"event",
"id",
"provided",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/inplayservice.py#L18-L36 | train | 232,472 |
liampauling/betfair | betfairlightweight/endpoints/inplayservice.py | InPlayService.get_event_timelines | def get_event_timelines(self, event_ids, session=None, lightweight=None):
"""
Returns a list of event timelines based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.EventTimeline]
"""
url = '%s%s' % (self.url, 'eventTimelines')
params = {
'eventIds': ','.join(str(x) for x in event_ids),
'alt': 'json',
'regionCode': 'UK',
'locale': 'en_GB'
}
(response, elapsed_time) = self.request(params=params, session=session, url=url)
return self.process_response(response, resources.EventTimeline, elapsed_time, lightweight) | python | def get_event_timelines(self, event_ids, session=None, lightweight=None):
"""
Returns a list of event timelines based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.EventTimeline]
"""
url = '%s%s' % (self.url, 'eventTimelines')
params = {
'eventIds': ','.join(str(x) for x in event_ids),
'alt': 'json',
'regionCode': 'UK',
'locale': 'en_GB'
}
(response, elapsed_time) = self.request(params=params, session=session, url=url)
return self.process_response(response, resources.EventTimeline, elapsed_time, lightweight) | [
"def",
"get_event_timelines",
"(",
"self",
",",
"event_ids",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"url",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"url",
",",
"'eventTimelines'",
")",
"params",
"=",
"{",
"'eventIds'",
":",
"','",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"event_ids",
")",
",",
"'alt'",
":",
"'json'",
",",
"'regionCode'",
":",
"'UK'",
",",
"'locale'",
":",
"'en_GB'",
"}",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"params",
"=",
"params",
",",
"session",
"=",
"session",
",",
"url",
"=",
"url",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"EventTimeline",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns a list of event timelines based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.EventTimeline] | [
"Returns",
"a",
"list",
"of",
"event",
"timelines",
"based",
"on",
"event",
"id",
"s",
"supplied",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/inplayservice.py#L38-L57 | train | 232,473 |
liampauling/betfair | betfairlightweight/endpoints/inplayservice.py | InPlayService.get_scores | def get_scores(self, event_ids, session=None, lightweight=None):
"""
Returns a list of scores based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Scores]
"""
url = '%s%s' % (self.url, 'scores')
params = {
'eventIds': ','.join(str(x) for x in event_ids),
'alt': 'json',
'regionCode': 'UK',
'locale': 'en_GB'
}
(response, elapsed_time) = self.request(params=params, session=session, url=url)
return self.process_response(response, resources.Scores, elapsed_time, lightweight) | python | def get_scores(self, event_ids, session=None, lightweight=None):
"""
Returns a list of scores based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Scores]
"""
url = '%s%s' % (self.url, 'scores')
params = {
'eventIds': ','.join(str(x) for x in event_ids),
'alt': 'json',
'regionCode': 'UK',
'locale': 'en_GB'
}
(response, elapsed_time) = self.request(params=params, session=session, url=url)
return self.process_response(response, resources.Scores, elapsed_time, lightweight) | [
"def",
"get_scores",
"(",
"self",
",",
"event_ids",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"url",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
"url",
",",
"'scores'",
")",
"params",
"=",
"{",
"'eventIds'",
":",
"','",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"event_ids",
")",
",",
"'alt'",
":",
"'json'",
",",
"'regionCode'",
":",
"'UK'",
",",
"'locale'",
":",
"'en_GB'",
"}",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"params",
"=",
"params",
",",
"session",
"=",
"session",
",",
"url",
"=",
"url",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"Scores",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns a list of scores based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.Scores] | [
"Returns",
"a",
"list",
"of",
"scores",
"based",
"on",
"event",
"id",
"s",
"supplied",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/inplayservice.py#L59-L78 | train | 232,474 |
liampauling/betfair | betfairlightweight/endpoints/streaming.py | Streaming.create_stream | def create_stream(self, unique_id=0, listener=None, timeout=11, buffer_size=1024, description='BetfairSocket',
host=None):
"""
Creates BetfairStream.
:param dict unique_id: Id used to start unique id's of the stream (+1 before every request)
:param resources.Listener listener: Listener class to use
:param float timeout: Socket timeout
:param int buffer_size: Socket buffer size
:param str description: Betfair stream description
:param str host: Host endpoint (prod (default) or integration)
:rtype: BetfairStream
"""
listener = listener if listener else BaseListener()
return BetfairStream(
unique_id,
listener,
app_key=self.client.app_key,
session_token=self.client.session_token,
timeout=timeout,
buffer_size=buffer_size,
description=description,
host=host,
) | python | def create_stream(self, unique_id=0, listener=None, timeout=11, buffer_size=1024, description='BetfairSocket',
host=None):
"""
Creates BetfairStream.
:param dict unique_id: Id used to start unique id's of the stream (+1 before every request)
:param resources.Listener listener: Listener class to use
:param float timeout: Socket timeout
:param int buffer_size: Socket buffer size
:param str description: Betfair stream description
:param str host: Host endpoint (prod (default) or integration)
:rtype: BetfairStream
"""
listener = listener if listener else BaseListener()
return BetfairStream(
unique_id,
listener,
app_key=self.client.app_key,
session_token=self.client.session_token,
timeout=timeout,
buffer_size=buffer_size,
description=description,
host=host,
) | [
"def",
"create_stream",
"(",
"self",
",",
"unique_id",
"=",
"0",
",",
"listener",
"=",
"None",
",",
"timeout",
"=",
"11",
",",
"buffer_size",
"=",
"1024",
",",
"description",
"=",
"'BetfairSocket'",
",",
"host",
"=",
"None",
")",
":",
"listener",
"=",
"listener",
"if",
"listener",
"else",
"BaseListener",
"(",
")",
"return",
"BetfairStream",
"(",
"unique_id",
",",
"listener",
",",
"app_key",
"=",
"self",
".",
"client",
".",
"app_key",
",",
"session_token",
"=",
"self",
".",
"client",
".",
"session_token",
",",
"timeout",
"=",
"timeout",
",",
"buffer_size",
"=",
"buffer_size",
",",
"description",
"=",
"description",
",",
"host",
"=",
"host",
",",
")"
] | Creates BetfairStream.
:param dict unique_id: Id used to start unique id's of the stream (+1 before every request)
:param resources.Listener listener: Listener class to use
:param float timeout: Socket timeout
:param int buffer_size: Socket buffer size
:param str description: Betfair stream description
:param str host: Host endpoint (prod (default) or integration)
:rtype: BetfairStream | [
"Creates",
"BetfairStream",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/streaming.py#L19-L43 | train | 232,475 |
liampauling/betfair | betfairlightweight/endpoints/historic.py | Historic.get_my_data | def get_my_data(self, session=None):
"""
Returns a list of data descriptions for data which has been purchased by the signed in user.
:param requests.session session: Requests session object
:rtype: dict
"""
params = clean_locals(locals())
method = 'GetMyData'
(response, elapsed_time) = self.request(method, params, session)
return response | python | def get_my_data(self, session=None):
"""
Returns a list of data descriptions for data which has been purchased by the signed in user.
:param requests.session session: Requests session object
:rtype: dict
"""
params = clean_locals(locals())
method = 'GetMyData'
(response, elapsed_time) = self.request(method, params, session)
return response | [
"def",
"get_my_data",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'GetMyData'",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"response"
] | Returns a list of data descriptions for data which has been purchased by the signed in user.
:param requests.session session: Requests session object
:rtype: dict | [
"Returns",
"a",
"list",
"of",
"data",
"descriptions",
"for",
"data",
"which",
"has",
"been",
"purchased",
"by",
"the",
"signed",
"in",
"user",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/historic.py#L22-L33 | train | 232,476 |
liampauling/betfair | betfairlightweight/endpoints/historic.py | Historic.get_data_size | def get_data_size(self, sport, plan, from_day, from_month, from_year, to_day, to_month, to_year, event_id=None,
event_name=None, market_types_collection=None, countries_collection=None,
file_type_collection=None, session=None):
"""
Returns a dictionary of file count and combines size files.
:param sport: sport to filter data for.
:param plan: plan type to filter for, Basic Plan, Advanced Plan or Pro Plan.
:param from_day: day of month to start data from.
:param from_month: month to start data from.
:param from_year: year to start data from.
:param to_day: day of month to end data at.
:param to_month: month to end data at.
:param to_year: year to end data at.
:param event_id: id of a specific event to get data for.
:param event_name: name of a specific event to get data for.
:param market_types_collection: list of specific marketTypes to filter for.
:param countries_collection: list of countries to filter for.
:param file_type_collection: list of file types.
:param requests.session session: Requests session object
:rtype: dict
"""
params = clean_locals(locals())
method = 'GetAdvBasketDataSize'
(response, elapsed_time) = self.request(method, params, session)
return response | python | def get_data_size(self, sport, plan, from_day, from_month, from_year, to_day, to_month, to_year, event_id=None,
event_name=None, market_types_collection=None, countries_collection=None,
file_type_collection=None, session=None):
"""
Returns a dictionary of file count and combines size files.
:param sport: sport to filter data for.
:param plan: plan type to filter for, Basic Plan, Advanced Plan or Pro Plan.
:param from_day: day of month to start data from.
:param from_month: month to start data from.
:param from_year: year to start data from.
:param to_day: day of month to end data at.
:param to_month: month to end data at.
:param to_year: year to end data at.
:param event_id: id of a specific event to get data for.
:param event_name: name of a specific event to get data for.
:param market_types_collection: list of specific marketTypes to filter for.
:param countries_collection: list of countries to filter for.
:param file_type_collection: list of file types.
:param requests.session session: Requests session object
:rtype: dict
"""
params = clean_locals(locals())
method = 'GetAdvBasketDataSize'
(response, elapsed_time) = self.request(method, params, session)
return response | [
"def",
"get_data_size",
"(",
"self",
",",
"sport",
",",
"plan",
",",
"from_day",
",",
"from_month",
",",
"from_year",
",",
"to_day",
",",
"to_month",
",",
"to_year",
",",
"event_id",
"=",
"None",
",",
"event_name",
"=",
"None",
",",
"market_types_collection",
"=",
"None",
",",
"countries_collection",
"=",
"None",
",",
"file_type_collection",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'GetAdvBasketDataSize'",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"method",
",",
"params",
",",
"session",
")",
"return",
"response"
] | Returns a dictionary of file count and combines size files.
:param sport: sport to filter data for.
:param plan: plan type to filter for, Basic Plan, Advanced Plan or Pro Plan.
:param from_day: day of month to start data from.
:param from_month: month to start data from.
:param from_year: year to start data from.
:param to_day: day of month to end data at.
:param to_month: month to end data at.
:param to_year: year to end data at.
:param event_id: id of a specific event to get data for.
:param event_name: name of a specific event to get data for.
:param market_types_collection: list of specific marketTypes to filter for.
:param countries_collection: list of countries to filter for.
:param file_type_collection: list of file types.
:param requests.session session: Requests session object
:rtype: dict | [
"Returns",
"a",
"dictionary",
"of",
"file",
"count",
"and",
"combines",
"size",
"files",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/historic.py#L63-L89 | train | 232,477 |
liampauling/betfair | betfairlightweight/endpoints/racecard.py | RaceCard.login | def login(self, session=None):
"""
Parses app key from betfair exchange site.
:param requests.session session: Requests session object
"""
session = session or self.client.session
try:
response = session.get(self.login_url)
except ConnectionError:
raise APIError(None, self.login_url, None, 'ConnectionError')
except Exception as e:
raise APIError(None, self.login_url, None, e)
app_key = re.findall(r'''"appKey":\s"(.*?)"''', response.text)
if app_key:
self.app_key = app_key[0]
else:
raise RaceCardError("Unable to find appKey") | python | def login(self, session=None):
"""
Parses app key from betfair exchange site.
:param requests.session session: Requests session object
"""
session = session or self.client.session
try:
response = session.get(self.login_url)
except ConnectionError:
raise APIError(None, self.login_url, None, 'ConnectionError')
except Exception as e:
raise APIError(None, self.login_url, None, e)
app_key = re.findall(r'''"appKey":\s"(.*?)"''', response.text)
if app_key:
self.app_key = app_key[0]
else:
raise RaceCardError("Unable to find appKey") | [
"def",
"login",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"session",
"=",
"session",
"or",
"self",
".",
"client",
".",
"session",
"try",
":",
"response",
"=",
"session",
".",
"get",
"(",
"self",
".",
"login_url",
")",
"except",
"ConnectionError",
":",
"raise",
"APIError",
"(",
"None",
",",
"self",
".",
"login_url",
",",
"None",
",",
"'ConnectionError'",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"APIError",
"(",
"None",
",",
"self",
".",
"login_url",
",",
"None",
",",
"e",
")",
"app_key",
"=",
"re",
".",
"findall",
"(",
"r'''\"appKey\":\\s\"(.*?)\"'''",
",",
"response",
".",
"text",
")",
"if",
"app_key",
":",
"self",
".",
"app_key",
"=",
"app_key",
"[",
"0",
"]",
"else",
":",
"raise",
"RaceCardError",
"(",
"\"Unable to find appKey\"",
")"
] | Parses app key from betfair exchange site.
:param requests.session session: Requests session object | [
"Parses",
"app",
"key",
"from",
"betfair",
"exchange",
"site",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/racecard.py#L22-L39 | train | 232,478 |
liampauling/betfair | betfairlightweight/endpoints/racecard.py | RaceCard.get_race_card | def get_race_card(self, market_ids, data_entries=None, session=None, lightweight=None):
"""
Returns a list of race cards based on market ids provided.
:param list market_ids: The filter to select desired markets
:param str data_entries: Data to be returned
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.RaceCard]
"""
if not self.app_key:
raise RaceCardError("You need to login before requesting a race_card\n"
"APIClient.race_card.login()")
params = self.create_race_card_req(market_ids, data_entries)
(response, elapsed_time) = self.request(params=params, session=session)
return self.process_response(response, resources.RaceCard, elapsed_time, lightweight) | python | def get_race_card(self, market_ids, data_entries=None, session=None, lightweight=None):
"""
Returns a list of race cards based on market ids provided.
:param list market_ids: The filter to select desired markets
:param str data_entries: Data to be returned
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.RaceCard]
"""
if not self.app_key:
raise RaceCardError("You need to login before requesting a race_card\n"
"APIClient.race_card.login()")
params = self.create_race_card_req(market_ids, data_entries)
(response, elapsed_time) = self.request(params=params, session=session)
return self.process_response(response, resources.RaceCard, elapsed_time, lightweight) | [
"def",
"get_race_card",
"(",
"self",
",",
"market_ids",
",",
"data_entries",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"app_key",
":",
"raise",
"RaceCardError",
"(",
"\"You need to login before requesting a race_card\\n\"",
"\"APIClient.race_card.login()\"",
")",
"params",
"=",
"self",
".",
"create_race_card_req",
"(",
"market_ids",
",",
"data_entries",
")",
"(",
"response",
",",
"elapsed_time",
")",
"=",
"self",
".",
"request",
"(",
"params",
"=",
"params",
",",
"session",
"=",
"session",
")",
"return",
"self",
".",
"process_response",
"(",
"response",
",",
"resources",
".",
"RaceCard",
",",
"elapsed_time",
",",
"lightweight",
")"
] | Returns a list of race cards based on market ids provided.
:param list market_ids: The filter to select desired markets
:param str data_entries: Data to be returned
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.RaceCard] | [
"Returns",
"a",
"list",
"of",
"race",
"cards",
"based",
"on",
"market",
"ids",
"provided",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/endpoints/racecard.py#L41-L57 | train | 232,479 |
liampauling/betfair | betfairlightweight/streaming/listener.py | StreamListener.on_data | def on_data(self, raw_data):
"""Called when raw data is received from connection.
Override this method if you wish to manually handle
the stream data
:param raw_data: Received raw data
:return: Return False to stop stream and close connection
"""
try:
data = json.loads(raw_data)
except ValueError:
logger.error('value error: %s' % raw_data)
return
unique_id = data.get('id')
if self._error_handler(data, unique_id):
return False
operation = data['op']
if operation == 'connection':
self._on_connection(data, unique_id)
elif operation == 'status':
self._on_status(data, unique_id)
elif operation in ['mcm', 'ocm']:
# historic data does not contain unique_id
if self.stream_unique_id not in [unique_id, 'HISTORICAL']:
logger.warning('Unwanted data received from uniqueId: %s, expecting: %s' %
(unique_id, self.stream_unique_id))
return
self._on_change_message(data, unique_id) | python | def on_data(self, raw_data):
"""Called when raw data is received from connection.
Override this method if you wish to manually handle
the stream data
:param raw_data: Received raw data
:return: Return False to stop stream and close connection
"""
try:
data = json.loads(raw_data)
except ValueError:
logger.error('value error: %s' % raw_data)
return
unique_id = data.get('id')
if self._error_handler(data, unique_id):
return False
operation = data['op']
if operation == 'connection':
self._on_connection(data, unique_id)
elif operation == 'status':
self._on_status(data, unique_id)
elif operation in ['mcm', 'ocm']:
# historic data does not contain unique_id
if self.stream_unique_id not in [unique_id, 'HISTORICAL']:
logger.warning('Unwanted data received from uniqueId: %s, expecting: %s' %
(unique_id, self.stream_unique_id))
return
self._on_change_message(data, unique_id) | [
"def",
"on_data",
"(",
"self",
",",
"raw_data",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"raw_data",
")",
"except",
"ValueError",
":",
"logger",
".",
"error",
"(",
"'value error: %s'",
"%",
"raw_data",
")",
"return",
"unique_id",
"=",
"data",
".",
"get",
"(",
"'id'",
")",
"if",
"self",
".",
"_error_handler",
"(",
"data",
",",
"unique_id",
")",
":",
"return",
"False",
"operation",
"=",
"data",
"[",
"'op'",
"]",
"if",
"operation",
"==",
"'connection'",
":",
"self",
".",
"_on_connection",
"(",
"data",
",",
"unique_id",
")",
"elif",
"operation",
"==",
"'status'",
":",
"self",
".",
"_on_status",
"(",
"data",
",",
"unique_id",
")",
"elif",
"operation",
"in",
"[",
"'mcm'",
",",
"'ocm'",
"]",
":",
"# historic data does not contain unique_id",
"if",
"self",
".",
"stream_unique_id",
"not",
"in",
"[",
"unique_id",
",",
"'HISTORICAL'",
"]",
":",
"logger",
".",
"warning",
"(",
"'Unwanted data received from uniqueId: %s, expecting: %s'",
"%",
"(",
"unique_id",
",",
"self",
".",
"stream_unique_id",
")",
")",
"return",
"self",
".",
"_on_change_message",
"(",
"data",
",",
"unique_id",
")"
] | Called when raw data is received from connection.
Override this method if you wish to manually handle
the stream data
:param raw_data: Received raw data
:return: Return False to stop stream and close connection | [
"Called",
"when",
"raw",
"data",
"is",
"received",
"from",
"connection",
".",
"Override",
"this",
"method",
"if",
"you",
"wish",
"to",
"manually",
"handle",
"the",
"stream",
"data"
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/listener.py#L85-L115 | train | 232,480 |
liampauling/betfair | betfairlightweight/streaming/listener.py | StreamListener._on_connection | def _on_connection(self, data, unique_id):
"""Called on collection operation
:param data: Received data
"""
if unique_id is None:
unique_id = self.stream_unique_id
self.connection_id = data.get('connectionId')
logger.info('[Connect: %s]: connection_id: %s' % (unique_id, self.connection_id)) | python | def _on_connection(self, data, unique_id):
"""Called on collection operation
:param data: Received data
"""
if unique_id is None:
unique_id = self.stream_unique_id
self.connection_id = data.get('connectionId')
logger.info('[Connect: %s]: connection_id: %s' % (unique_id, self.connection_id)) | [
"def",
"_on_connection",
"(",
"self",
",",
"data",
",",
"unique_id",
")",
":",
"if",
"unique_id",
"is",
"None",
":",
"unique_id",
"=",
"self",
".",
"stream_unique_id",
"self",
".",
"connection_id",
"=",
"data",
".",
"get",
"(",
"'connectionId'",
")",
"logger",
".",
"info",
"(",
"'[Connect: %s]: connection_id: %s'",
"%",
"(",
"unique_id",
",",
"self",
".",
"connection_id",
")",
")"
] | Called on collection operation
:param data: Received data | [
"Called",
"on",
"collection",
"operation"
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/listener.py#L117-L125 | train | 232,481 |
liampauling/betfair | betfairlightweight/streaming/listener.py | StreamListener._on_status | def _on_status(data, unique_id):
"""Called on status operation
:param data: Received data
"""
status_code = data.get('statusCode')
logger.info('[Subscription: %s]: %s' % (unique_id, status_code)) | python | def _on_status(data, unique_id):
"""Called on status operation
:param data: Received data
"""
status_code = data.get('statusCode')
logger.info('[Subscription: %s]: %s' % (unique_id, status_code)) | [
"def",
"_on_status",
"(",
"data",
",",
"unique_id",
")",
":",
"status_code",
"=",
"data",
".",
"get",
"(",
"'statusCode'",
")",
"logger",
".",
"info",
"(",
"'[Subscription: %s]: %s'",
"%",
"(",
"unique_id",
",",
"status_code",
")",
")"
] | Called on status operation
:param data: Received data | [
"Called",
"on",
"status",
"operation"
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/listener.py#L128-L134 | train | 232,482 |
liampauling/betfair | betfairlightweight/streaming/listener.py | StreamListener._error_handler | def _error_handler(data, unique_id):
"""Called when data first received
:param data: Received data
:param unique_id: Unique id
:return: True if error present
"""
if data.get('statusCode') == 'FAILURE':
logger.error('[Subscription: %s] %s: %s' % (unique_id, data.get('errorCode'), data.get('errorMessage')))
if data.get('connectionClosed'):
return True
if data.get('status'):
# Clients shouldn't disconnect if status 503 is returned; when the stream
# recovers updates will be sent containing the latest data
logger.warning('[Subscription: %s] status: %s' % (unique_id, data['status'])) | python | def _error_handler(data, unique_id):
"""Called when data first received
:param data: Received data
:param unique_id: Unique id
:return: True if error present
"""
if data.get('statusCode') == 'FAILURE':
logger.error('[Subscription: %s] %s: %s' % (unique_id, data.get('errorCode'), data.get('errorMessage')))
if data.get('connectionClosed'):
return True
if data.get('status'):
# Clients shouldn't disconnect if status 503 is returned; when the stream
# recovers updates will be sent containing the latest data
logger.warning('[Subscription: %s] status: %s' % (unique_id, data['status'])) | [
"def",
"_error_handler",
"(",
"data",
",",
"unique_id",
")",
":",
"if",
"data",
".",
"get",
"(",
"'statusCode'",
")",
"==",
"'FAILURE'",
":",
"logger",
".",
"error",
"(",
"'[Subscription: %s] %s: %s'",
"%",
"(",
"unique_id",
",",
"data",
".",
"get",
"(",
"'errorCode'",
")",
",",
"data",
".",
"get",
"(",
"'errorMessage'",
")",
")",
")",
"if",
"data",
".",
"get",
"(",
"'connectionClosed'",
")",
":",
"return",
"True",
"if",
"data",
".",
"get",
"(",
"'status'",
")",
":",
"# Clients shouldn't disconnect if status 503 is returned; when the stream",
"# recovers updates will be sent containing the latest data",
"logger",
".",
"warning",
"(",
"'[Subscription: %s] status: %s'",
"%",
"(",
"unique_id",
",",
"data",
"[",
"'status'",
"]",
")",
")"
] | Called when data first received
:param data: Received data
:param unique_id: Unique id
:return: True if error present | [
"Called",
"when",
"data",
"first",
"received"
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/listener.py#L157-L171 | train | 232,483 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream.stop | def stop(self):
"""Stops read loop and closes socket if it has been created.
"""
self._running = False
if self._socket is None:
return
try:
self._socket.shutdown(socket.SHUT_RDWR)
self._socket.close()
except socket.error:
pass
self._socket = None | python | def stop(self):
"""Stops read loop and closes socket if it has been created.
"""
self._running = False
if self._socket is None:
return
try:
self._socket.shutdown(socket.SHUT_RDWR)
self._socket.close()
except socket.error:
pass
self._socket = None | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_running",
"=",
"False",
"if",
"self",
".",
"_socket",
"is",
"None",
":",
"return",
"try",
":",
"self",
".",
"_socket",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"self",
".",
"_socket",
".",
"close",
"(",
")",
"except",
"socket",
".",
"error",
":",
"pass",
"self",
".",
"_socket",
"=",
"None"
] | Stops read loop and closes socket if it has been created. | [
"Stops",
"read",
"loop",
"and",
"closes",
"socket",
"if",
"it",
"has",
"been",
"created",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L62-L74 | train | 232,484 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream.authenticate | def authenticate(self):
"""Authentication request.
"""
unique_id = self.new_unique_id()
message = {
'op': 'authentication',
'id': unique_id,
'appKey': self.app_key,
'session': self.session_token,
}
self._send(message)
return unique_id | python | def authenticate(self):
"""Authentication request.
"""
unique_id = self.new_unique_id()
message = {
'op': 'authentication',
'id': unique_id,
'appKey': self.app_key,
'session': self.session_token,
}
self._send(message)
return unique_id | [
"def",
"authenticate",
"(",
"self",
")",
":",
"unique_id",
"=",
"self",
".",
"new_unique_id",
"(",
")",
"message",
"=",
"{",
"'op'",
":",
"'authentication'",
",",
"'id'",
":",
"unique_id",
",",
"'appKey'",
":",
"self",
".",
"app_key",
",",
"'session'",
":",
"self",
".",
"session_token",
",",
"}",
"self",
".",
"_send",
"(",
"message",
")",
"return",
"unique_id"
] | Authentication request. | [
"Authentication",
"request",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L76-L87 | train | 232,485 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream.heartbeat | def heartbeat(self):
"""Heartbeat request to keep session alive.
"""
unique_id = self.new_unique_id()
message = {
'op': 'heartbeat',
'id': unique_id,
}
self._send(message)
return unique_id | python | def heartbeat(self):
"""Heartbeat request to keep session alive.
"""
unique_id = self.new_unique_id()
message = {
'op': 'heartbeat',
'id': unique_id,
}
self._send(message)
return unique_id | [
"def",
"heartbeat",
"(",
"self",
")",
":",
"unique_id",
"=",
"self",
".",
"new_unique_id",
"(",
")",
"message",
"=",
"{",
"'op'",
":",
"'heartbeat'",
",",
"'id'",
":",
"unique_id",
",",
"}",
"self",
".",
"_send",
"(",
"message",
")",
"return",
"unique_id"
] | Heartbeat request to keep session alive. | [
"Heartbeat",
"request",
"to",
"keep",
"session",
"alive",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L89-L98 | train | 232,486 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream.subscribe_to_markets | def subscribe_to_markets(self, market_filter, market_data_filter, initial_clk=None, clk=None,
conflate_ms=None, heartbeat_ms=None, segmentation_enabled=True):
"""
Market subscription request.
:param dict market_filter: Market filter
:param dict market_data_filter: Market data filter
:param str initial_clk: Sequence token for reconnect
:param str clk: Sequence token for reconnect
:param int conflate_ms: conflation rate (bounds are 0 to 120000)
:param int heartbeat_ms: heartbeat rate (500 to 5000)
:param bool segmentation_enabled: allow the server to send large sets of data
in segments, instead of a single block
"""
unique_id = self.new_unique_id()
message = {
'op': 'marketSubscription',
'id': unique_id,
'marketFilter': market_filter,
'marketDataFilter': market_data_filter,
'initialClk': initial_clk,
'clk': clk,
'conflateMs': conflate_ms,
'heartbeatMs': heartbeat_ms,
'segmentationEnabled': segmentation_enabled,
}
if initial_clk and clk:
# if resubscribe only update unique_id
self.listener.stream_unique_id = unique_id
else:
self.listener.register_stream(unique_id, 'marketSubscription')
self._send(message)
return unique_id | python | def subscribe_to_markets(self, market_filter, market_data_filter, initial_clk=None, clk=None,
conflate_ms=None, heartbeat_ms=None, segmentation_enabled=True):
"""
Market subscription request.
:param dict market_filter: Market filter
:param dict market_data_filter: Market data filter
:param str initial_clk: Sequence token for reconnect
:param str clk: Sequence token for reconnect
:param int conflate_ms: conflation rate (bounds are 0 to 120000)
:param int heartbeat_ms: heartbeat rate (500 to 5000)
:param bool segmentation_enabled: allow the server to send large sets of data
in segments, instead of a single block
"""
unique_id = self.new_unique_id()
message = {
'op': 'marketSubscription',
'id': unique_id,
'marketFilter': market_filter,
'marketDataFilter': market_data_filter,
'initialClk': initial_clk,
'clk': clk,
'conflateMs': conflate_ms,
'heartbeatMs': heartbeat_ms,
'segmentationEnabled': segmentation_enabled,
}
if initial_clk and clk:
# if resubscribe only update unique_id
self.listener.stream_unique_id = unique_id
else:
self.listener.register_stream(unique_id, 'marketSubscription')
self._send(message)
return unique_id | [
"def",
"subscribe_to_markets",
"(",
"self",
",",
"market_filter",
",",
"market_data_filter",
",",
"initial_clk",
"=",
"None",
",",
"clk",
"=",
"None",
",",
"conflate_ms",
"=",
"None",
",",
"heartbeat_ms",
"=",
"None",
",",
"segmentation_enabled",
"=",
"True",
")",
":",
"unique_id",
"=",
"self",
".",
"new_unique_id",
"(",
")",
"message",
"=",
"{",
"'op'",
":",
"'marketSubscription'",
",",
"'id'",
":",
"unique_id",
",",
"'marketFilter'",
":",
"market_filter",
",",
"'marketDataFilter'",
":",
"market_data_filter",
",",
"'initialClk'",
":",
"initial_clk",
",",
"'clk'",
":",
"clk",
",",
"'conflateMs'",
":",
"conflate_ms",
",",
"'heartbeatMs'",
":",
"heartbeat_ms",
",",
"'segmentationEnabled'",
":",
"segmentation_enabled",
",",
"}",
"if",
"initial_clk",
"and",
"clk",
":",
"# if resubscribe only update unique_id",
"self",
".",
"listener",
".",
"stream_unique_id",
"=",
"unique_id",
"else",
":",
"self",
".",
"listener",
".",
"register_stream",
"(",
"unique_id",
",",
"'marketSubscription'",
")",
"self",
".",
"_send",
"(",
"message",
")",
"return",
"unique_id"
] | Market subscription request.
:param dict market_filter: Market filter
:param dict market_data_filter: Market data filter
:param str initial_clk: Sequence token for reconnect
:param str clk: Sequence token for reconnect
:param int conflate_ms: conflation rate (bounds are 0 to 120000)
:param int heartbeat_ms: heartbeat rate (500 to 5000)
:param bool segmentation_enabled: allow the server to send large sets of data
in segments, instead of a single block | [
"Market",
"subscription",
"request",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L100-L132 | train | 232,487 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream.subscribe_to_orders | def subscribe_to_orders(self, order_filter=None, initial_clk=None, clk=None, conflate_ms=None,
heartbeat_ms=None, segmentation_enabled=True):
"""
Order subscription request.
:param dict order_filter: Order filter to be applied
:param str initial_clk: Sequence token for reconnect
:param str clk: Sequence token for reconnect
:param int conflate_ms: conflation rate (bounds are 0 to 120000)
:param int heartbeat_ms: heartbeat rate (500 to 5000)
:param bool segmentation_enabled: allow the server to send large sets of data
in segments, instead of a single block
"""
unique_id = self.new_unique_id()
message = {
'op': 'orderSubscription',
'id': unique_id,
'orderFilter': order_filter,
'initialClk': initial_clk,
'clk': clk,
'conflateMs': conflate_ms,
'heartbeatMs': heartbeat_ms,
'segmentationEnabled': segmentation_enabled,
}
if initial_clk and clk:
# if resubscribe only update unique_id
self.listener.stream_unique_id = unique_id
else:
self.listener.register_stream(unique_id, 'orderSubscription')
self._send(message)
return unique_id | python | def subscribe_to_orders(self, order_filter=None, initial_clk=None, clk=None, conflate_ms=None,
heartbeat_ms=None, segmentation_enabled=True):
"""
Order subscription request.
:param dict order_filter: Order filter to be applied
:param str initial_clk: Sequence token for reconnect
:param str clk: Sequence token for reconnect
:param int conflate_ms: conflation rate (bounds are 0 to 120000)
:param int heartbeat_ms: heartbeat rate (500 to 5000)
:param bool segmentation_enabled: allow the server to send large sets of data
in segments, instead of a single block
"""
unique_id = self.new_unique_id()
message = {
'op': 'orderSubscription',
'id': unique_id,
'orderFilter': order_filter,
'initialClk': initial_clk,
'clk': clk,
'conflateMs': conflate_ms,
'heartbeatMs': heartbeat_ms,
'segmentationEnabled': segmentation_enabled,
}
if initial_clk and clk:
# if resubscribe only update unique_id
self.listener.stream_unique_id = unique_id
else:
self.listener.register_stream(unique_id, 'orderSubscription')
self._send(message)
return unique_id | [
"def",
"subscribe_to_orders",
"(",
"self",
",",
"order_filter",
"=",
"None",
",",
"initial_clk",
"=",
"None",
",",
"clk",
"=",
"None",
",",
"conflate_ms",
"=",
"None",
",",
"heartbeat_ms",
"=",
"None",
",",
"segmentation_enabled",
"=",
"True",
")",
":",
"unique_id",
"=",
"self",
".",
"new_unique_id",
"(",
")",
"message",
"=",
"{",
"'op'",
":",
"'orderSubscription'",
",",
"'id'",
":",
"unique_id",
",",
"'orderFilter'",
":",
"order_filter",
",",
"'initialClk'",
":",
"initial_clk",
",",
"'clk'",
":",
"clk",
",",
"'conflateMs'",
":",
"conflate_ms",
",",
"'heartbeatMs'",
":",
"heartbeat_ms",
",",
"'segmentationEnabled'",
":",
"segmentation_enabled",
",",
"}",
"if",
"initial_clk",
"and",
"clk",
":",
"# if resubscribe only update unique_id",
"self",
".",
"listener",
".",
"stream_unique_id",
"=",
"unique_id",
"else",
":",
"self",
".",
"listener",
".",
"register_stream",
"(",
"unique_id",
",",
"'orderSubscription'",
")",
"self",
".",
"_send",
"(",
"message",
")",
"return",
"unique_id"
] | Order subscription request.
:param dict order_filter: Order filter to be applied
:param str initial_clk: Sequence token for reconnect
:param str clk: Sequence token for reconnect
:param int conflate_ms: conflation rate (bounds are 0 to 120000)
:param int heartbeat_ms: heartbeat rate (500 to 5000)
:param bool segmentation_enabled: allow the server to send large sets of data
in segments, instead of a single block | [
"Order",
"subscription",
"request",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L134-L164 | train | 232,488 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream._create_socket | def _create_socket(self):
"""Creates ssl socket, connects to stream api and
sets timeout.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s)
s.connect((self.host, self.__port))
s.settimeout(self.timeout)
return s | python | def _create_socket(self):
"""Creates ssl socket, connects to stream api and
sets timeout.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s)
s.connect((self.host, self.__port))
s.settimeout(self.timeout)
return s | [
"def",
"_create_socket",
"(",
"self",
")",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"s",
"=",
"ssl",
".",
"wrap_socket",
"(",
"s",
")",
"s",
".",
"connect",
"(",
"(",
"self",
".",
"host",
",",
"self",
".",
"__port",
")",
")",
"s",
".",
"settimeout",
"(",
"self",
".",
"timeout",
")",
"return",
"s"
] | Creates ssl socket, connects to stream api and
sets timeout. | [
"Creates",
"ssl",
"socket",
"connects",
"to",
"stream",
"api",
"and",
"sets",
"timeout",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L176-L184 | train | 232,489 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream._read_loop | def _read_loop(self):
"""Read loop, splits by CRLF and pushes received data
to _data.
"""
while self._running:
received_data_raw = self._receive_all()
if self._running:
self.receive_count += 1
self.datetime_last_received = datetime.datetime.utcnow()
received_data_split = received_data_raw.split(self.__CRLF)
for received_data in received_data_split:
if received_data:
self._data(received_data) | python | def _read_loop(self):
"""Read loop, splits by CRLF and pushes received data
to _data.
"""
while self._running:
received_data_raw = self._receive_all()
if self._running:
self.receive_count += 1
self.datetime_last_received = datetime.datetime.utcnow()
received_data_split = received_data_raw.split(self.__CRLF)
for received_data in received_data_split:
if received_data:
self._data(received_data) | [
"def",
"_read_loop",
"(",
"self",
")",
":",
"while",
"self",
".",
"_running",
":",
"received_data_raw",
"=",
"self",
".",
"_receive_all",
"(",
")",
"if",
"self",
".",
"_running",
":",
"self",
".",
"receive_count",
"+=",
"1",
"self",
".",
"datetime_last_received",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"received_data_split",
"=",
"received_data_raw",
".",
"split",
"(",
"self",
".",
"__CRLF",
")",
"for",
"received_data",
"in",
"received_data_split",
":",
"if",
"received_data",
":",
"self",
".",
"_data",
"(",
"received_data",
")"
] | Read loop, splits by CRLF and pushes received data
to _data. | [
"Read",
"loop",
"splits",
"by",
"CRLF",
"and",
"pushes",
"received",
"data",
"to",
"_data",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L186-L198 | train | 232,490 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream._receive_all | def _receive_all(self):
"""Whilst socket is running receives data from socket,
till CRLF is detected.
"""
(data, part) = ('', '')
if is_py3:
crlf_bytes = bytes(self.__CRLF, encoding=self.__encoding)
else:
crlf_bytes = self.__CRLF
while self._running and part[-2:] != crlf_bytes:
try:
part = self._socket.recv(self.buffer_size)
except (socket.timeout, socket.error) as e:
if self._running:
self.stop()
raise SocketError('[Connect: %s]: Socket %s' % (self._unique_id, e))
else:
return # 133, prevents error if stop is called mid recv
# an empty string indicates the server shutdown the socket
if len(part) == 0:
self.stop()
raise SocketError('Connection closed by server')
data += part.decode(self.__encoding)
return data | python | def _receive_all(self):
"""Whilst socket is running receives data from socket,
till CRLF is detected.
"""
(data, part) = ('', '')
if is_py3:
crlf_bytes = bytes(self.__CRLF, encoding=self.__encoding)
else:
crlf_bytes = self.__CRLF
while self._running and part[-2:] != crlf_bytes:
try:
part = self._socket.recv(self.buffer_size)
except (socket.timeout, socket.error) as e:
if self._running:
self.stop()
raise SocketError('[Connect: %s]: Socket %s' % (self._unique_id, e))
else:
return # 133, prevents error if stop is called mid recv
# an empty string indicates the server shutdown the socket
if len(part) == 0:
self.stop()
raise SocketError('Connection closed by server')
data += part.decode(self.__encoding)
return data | [
"def",
"_receive_all",
"(",
"self",
")",
":",
"(",
"data",
",",
"part",
")",
"=",
"(",
"''",
",",
"''",
")",
"if",
"is_py3",
":",
"crlf_bytes",
"=",
"bytes",
"(",
"self",
".",
"__CRLF",
",",
"encoding",
"=",
"self",
".",
"__encoding",
")",
"else",
":",
"crlf_bytes",
"=",
"self",
".",
"__CRLF",
"while",
"self",
".",
"_running",
"and",
"part",
"[",
"-",
"2",
":",
"]",
"!=",
"crlf_bytes",
":",
"try",
":",
"part",
"=",
"self",
".",
"_socket",
".",
"recv",
"(",
"self",
".",
"buffer_size",
")",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"error",
")",
"as",
"e",
":",
"if",
"self",
".",
"_running",
":",
"self",
".",
"stop",
"(",
")",
"raise",
"SocketError",
"(",
"'[Connect: %s]: Socket %s'",
"%",
"(",
"self",
".",
"_unique_id",
",",
"e",
")",
")",
"else",
":",
"return",
"# 133, prevents error if stop is called mid recv",
"# an empty string indicates the server shutdown the socket",
"if",
"len",
"(",
"part",
")",
"==",
"0",
":",
"self",
".",
"stop",
"(",
")",
"raise",
"SocketError",
"(",
"'Connection closed by server'",
")",
"data",
"+=",
"part",
".",
"decode",
"(",
"self",
".",
"__encoding",
")",
"return",
"data"
] | Whilst socket is running receives data from socket,
till CRLF is detected. | [
"Whilst",
"socket",
"is",
"running",
"receives",
"data",
"from",
"socket",
"till",
"CRLF",
"is",
"detected",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L200-L226 | train | 232,491 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream._data | def _data(self, received_data):
"""Sends data to listener, if False is returned; socket
is closed.
:param received_data: Decoded data received from socket.
"""
if self.listener.on_data(received_data) is False:
self.stop()
raise ListenerError(self.listener.connection_id, received_data) | python | def _data(self, received_data):
"""Sends data to listener, if False is returned; socket
is closed.
:param received_data: Decoded data received from socket.
"""
if self.listener.on_data(received_data) is False:
self.stop()
raise ListenerError(self.listener.connection_id, received_data) | [
"def",
"_data",
"(",
"self",
",",
"received_data",
")",
":",
"if",
"self",
".",
"listener",
".",
"on_data",
"(",
"received_data",
")",
"is",
"False",
":",
"self",
".",
"stop",
"(",
")",
"raise",
"ListenerError",
"(",
"self",
".",
"listener",
".",
"connection_id",
",",
"received_data",
")"
] | Sends data to listener, if False is returned; socket
is closed.
:param received_data: Decoded data received from socket. | [
"Sends",
"data",
"to",
"listener",
"if",
"False",
"is",
"returned",
";",
"socket",
"is",
"closed",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L228-L236 | train | 232,492 |
liampauling/betfair | betfairlightweight/streaming/betfairstream.py | BetfairStream._send | def _send(self, message):
"""If not running connects socket and
authenticates. Adds CRLF and sends message
to Betfair.
:param message: Data to be sent to Betfair.
"""
if not self._running:
self._connect()
self.authenticate()
message_dumped = json.dumps(message) + self.__CRLF
try:
self._socket.send(message_dumped.encode())
except (socket.timeout, socket.error) as e:
self.stop()
raise SocketError('[Connect: %s]: Socket %s' % (self._unique_id, e)) | python | def _send(self, message):
"""If not running connects socket and
authenticates. Adds CRLF and sends message
to Betfair.
:param message: Data to be sent to Betfair.
"""
if not self._running:
self._connect()
self.authenticate()
message_dumped = json.dumps(message) + self.__CRLF
try:
self._socket.send(message_dumped.encode())
except (socket.timeout, socket.error) as e:
self.stop()
raise SocketError('[Connect: %s]: Socket %s' % (self._unique_id, e)) | [
"def",
"_send",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"_running",
":",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"authenticate",
"(",
")",
"message_dumped",
"=",
"json",
".",
"dumps",
"(",
"message",
")",
"+",
"self",
".",
"__CRLF",
"try",
":",
"self",
".",
"_socket",
".",
"send",
"(",
"message_dumped",
".",
"encode",
"(",
")",
")",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"error",
")",
"as",
"e",
":",
"self",
".",
"stop",
"(",
")",
"raise",
"SocketError",
"(",
"'[Connect: %s]: Socket %s'",
"%",
"(",
"self",
".",
"_unique_id",
",",
"e",
")",
")"
] | If not running connects socket and
authenticates. Adds CRLF and sends message
to Betfair.
:param message: Data to be sent to Betfair. | [
"If",
"not",
"running",
"connects",
"socket",
"and",
"authenticates",
".",
"Adds",
"CRLF",
"and",
"sends",
"message",
"to",
"Betfair",
"."
] | 8479392eb4849c525d78d43497c32c0bb108e977 | https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/streaming/betfairstream.py#L238-L253 | train | 232,493 |
dmbee/seglearn | seglearn/pipe.py | Pype.fit_transform | def fit_transform(self, X, y=None, **fit_params):
"""
Fit the model and transform with the final estimator
Fits all the transforms one after the other and transforms the
data, then uses fit_transform on transformed data with the final
estimator.
Parameters
----------
X : iterable
Training data. Must fulfill input requirements of first step of the
pipeline.
y : iterable, default=None
Training targets. Must fulfill label requirements for all steps of
the pipeline.
**fit_params : dict of string -> object
Parameters passed to the ``fit`` method of each step, where
each parameter name is prefixed such that parameter ``p`` for step
``s`` has key ``s__p``.
Returns
-------
Xt : array-like, shape = [n_samples, n_transformed_features]
Transformed samples
yt : array-like, shape = [n_samples]
Transformed target
"""
Xt, yt, fit_params = self._fit(X, y, **fit_params)
if isinstance(self._final_estimator, XyTransformerMixin):
Xt, yt, _ = self._final_estimator.fit_transform(Xt, yt)
else:
if hasattr(self._final_estimator, 'fit_transform'):
Xt = self._final_estimator.fit_transform(Xt, yt)
else:
self._final_estimator.fit(Xt, yt)
Xt = self._final_estimator.transform(Xt)
self.N_fit = len(yt)
return Xt, yt | python | def fit_transform(self, X, y=None, **fit_params):
"""
Fit the model and transform with the final estimator
Fits all the transforms one after the other and transforms the
data, then uses fit_transform on transformed data with the final
estimator.
Parameters
----------
X : iterable
Training data. Must fulfill input requirements of first step of the
pipeline.
y : iterable, default=None
Training targets. Must fulfill label requirements for all steps of
the pipeline.
**fit_params : dict of string -> object
Parameters passed to the ``fit`` method of each step, where
each parameter name is prefixed such that parameter ``p`` for step
``s`` has key ``s__p``.
Returns
-------
Xt : array-like, shape = [n_samples, n_transformed_features]
Transformed samples
yt : array-like, shape = [n_samples]
Transformed target
"""
Xt, yt, fit_params = self._fit(X, y, **fit_params)
if isinstance(self._final_estimator, XyTransformerMixin):
Xt, yt, _ = self._final_estimator.fit_transform(Xt, yt)
else:
if hasattr(self._final_estimator, 'fit_transform'):
Xt = self._final_estimator.fit_transform(Xt, yt)
else:
self._final_estimator.fit(Xt, yt)
Xt = self._final_estimator.transform(Xt)
self.N_fit = len(yt)
return Xt, yt | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"fit_params",
")",
":",
"Xt",
",",
"yt",
",",
"fit_params",
"=",
"self",
".",
"_fit",
"(",
"X",
",",
"y",
",",
"*",
"*",
"fit_params",
")",
"if",
"isinstance",
"(",
"self",
".",
"_final_estimator",
",",
"XyTransformerMixin",
")",
":",
"Xt",
",",
"yt",
",",
"_",
"=",
"self",
".",
"_final_estimator",
".",
"fit_transform",
"(",
"Xt",
",",
"yt",
")",
"else",
":",
"if",
"hasattr",
"(",
"self",
".",
"_final_estimator",
",",
"'fit_transform'",
")",
":",
"Xt",
"=",
"self",
".",
"_final_estimator",
".",
"fit_transform",
"(",
"Xt",
",",
"yt",
")",
"else",
":",
"self",
".",
"_final_estimator",
".",
"fit",
"(",
"Xt",
",",
"yt",
")",
"Xt",
"=",
"self",
".",
"_final_estimator",
".",
"transform",
"(",
"Xt",
")",
"self",
".",
"N_fit",
"=",
"len",
"(",
"yt",
")",
"return",
"Xt",
",",
"yt"
] | Fit the model and transform with the final estimator
Fits all the transforms one after the other and transforms the
data, then uses fit_transform on transformed data with the final
estimator.
Parameters
----------
X : iterable
Training data. Must fulfill input requirements of first step of the
pipeline.
y : iterable, default=None
Training targets. Must fulfill label requirements for all steps of
the pipeline.
**fit_params : dict of string -> object
Parameters passed to the ``fit`` method of each step, where
each parameter name is prefixed such that parameter ``p`` for step
``s`` has key ``s__p``.
Returns
-------
Xt : array-like, shape = [n_samples, n_transformed_features]
Transformed samples
yt : array-like, shape = [n_samples]
Transformed target | [
"Fit",
"the",
"model",
"and",
"transform",
"with",
"the",
"final",
"estimator",
"Fits",
"all",
"the",
"transforms",
"one",
"after",
"the",
"other",
"and",
"transforms",
"the",
"data",
"then",
"uses",
"fit_transform",
"on",
"transformed",
"data",
"with",
"the",
"final",
"estimator",
"."
] | d8d7039e92c4c6571a70350c03298aceab8dbeec | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/pipe.py#L173-L214 | train | 232,494 |
dmbee/seglearn | seglearn/pipe.py | Pype.predict | def predict(self, X):
"""
Apply transforms to the data, and predict with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
yp : array-like
Predicted transformed target
"""
Xt, _, _ = self._transform(X)
return self._final_estimator.predict(Xt) | python | def predict(self, X):
"""
Apply transforms to the data, and predict with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
yp : array-like
Predicted transformed target
"""
Xt, _, _ = self._transform(X)
return self._final_estimator.predict(Xt) | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"Xt",
",",
"_",
",",
"_",
"=",
"self",
".",
"_transform",
"(",
"X",
")",
"return",
"self",
".",
"_final_estimator",
".",
"predict",
"(",
"Xt",
")"
] | Apply transforms to the data, and predict with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
yp : array-like
Predicted transformed target | [
"Apply",
"transforms",
"to",
"the",
"data",
"and",
"predict",
"with",
"the",
"final",
"estimator"
] | d8d7039e92c4c6571a70350c03298aceab8dbeec | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/pipe.py#L216-L232 | train | 232,495 |
dmbee/seglearn | seglearn/pipe.py | Pype.transform_predict | def transform_predict(self, X, y):
"""
Apply transforms to the data, and predict with the final estimator.
Unlike predict, this also returns the transformed target
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : array-like
target
Returns
-------
yt : array-like
Transformed target
yp : array-like
Predicted transformed target
"""
Xt, yt, _ = self._transform(X, y)
yp = self._final_estimator.predict(Xt)
return yt, yp | python | def transform_predict(self, X, y):
"""
Apply transforms to the data, and predict with the final estimator.
Unlike predict, this also returns the transformed target
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : array-like
target
Returns
-------
yt : array-like
Transformed target
yp : array-like
Predicted transformed target
"""
Xt, yt, _ = self._transform(X, y)
yp = self._final_estimator.predict(Xt)
return yt, yp | [
"def",
"transform_predict",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"Xt",
",",
"yt",
",",
"_",
"=",
"self",
".",
"_transform",
"(",
"X",
",",
"y",
")",
"yp",
"=",
"self",
".",
"_final_estimator",
".",
"predict",
"(",
"Xt",
")",
"return",
"yt",
",",
"yp"
] | Apply transforms to the data, and predict with the final estimator.
Unlike predict, this also returns the transformed target
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : array-like
target
Returns
-------
yt : array-like
Transformed target
yp : array-like
Predicted transformed target | [
"Apply",
"transforms",
"to",
"the",
"data",
"and",
"predict",
"with",
"the",
"final",
"estimator",
".",
"Unlike",
"predict",
"this",
"also",
"returns",
"the",
"transformed",
"target"
] | d8d7039e92c4c6571a70350c03298aceab8dbeec | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/pipe.py#L234-L256 | train | 232,496 |
dmbee/seglearn | seglearn/pipe.py | Pype.score | def score(self, X, y=None, sample_weight=None):
"""
Apply transforms, and score with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : iterable, default=None
Targets used for scoring. Must fulfill label requirements for all
steps of the pipeline.
sample_weight : array-like, default=None
If not None, this argument is passed as ``sample_weight`` keyword
argument to the ``score`` method of the final estimator.
Returns
-------
score : float
"""
Xt, yt, swt = self._transform(X, y, sample_weight)
self.N_test = len(yt)
score_params = {}
if swt is not None:
score_params['sample_weight'] = swt
if self.scorer is None:
return self._final_estimator.score(Xt, yt, **score_params)
return self.scorer(self._final_estimator, Xt, yt, **score_params) | python | def score(self, X, y=None, sample_weight=None):
"""
Apply transforms, and score with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : iterable, default=None
Targets used for scoring. Must fulfill label requirements for all
steps of the pipeline.
sample_weight : array-like, default=None
If not None, this argument is passed as ``sample_weight`` keyword
argument to the ``score`` method of the final estimator.
Returns
-------
score : float
"""
Xt, yt, swt = self._transform(X, y, sample_weight)
self.N_test = len(yt)
score_params = {}
if swt is not None:
score_params['sample_weight'] = swt
if self.scorer is None:
return self._final_estimator.score(Xt, yt, **score_params)
return self.scorer(self._final_estimator, Xt, yt, **score_params) | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"sample_weight",
"=",
"None",
")",
":",
"Xt",
",",
"yt",
",",
"swt",
"=",
"self",
".",
"_transform",
"(",
"X",
",",
"y",
",",
"sample_weight",
")",
"self",
".",
"N_test",
"=",
"len",
"(",
"yt",
")",
"score_params",
"=",
"{",
"}",
"if",
"swt",
"is",
"not",
"None",
":",
"score_params",
"[",
"'sample_weight'",
"]",
"=",
"swt",
"if",
"self",
".",
"scorer",
"is",
"None",
":",
"return",
"self",
".",
"_final_estimator",
".",
"score",
"(",
"Xt",
",",
"yt",
",",
"*",
"*",
"score_params",
")",
"return",
"self",
".",
"scorer",
"(",
"self",
".",
"_final_estimator",
",",
"Xt",
",",
"yt",
",",
"*",
"*",
"score_params",
")"
] | Apply transforms, and score with the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
y : iterable, default=None
Targets used for scoring. Must fulfill label requirements for all
steps of the pipeline.
sample_weight : array-like, default=None
If not None, this argument is passed as ``sample_weight`` keyword
argument to the ``score`` method of the final estimator.
Returns
-------
score : float | [
"Apply",
"transforms",
"and",
"score",
"with",
"the",
"final",
"estimator"
] | d8d7039e92c4c6571a70350c03298aceab8dbeec | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/pipe.py#L258-L290 | train | 232,497 |
dmbee/seglearn | seglearn/pipe.py | Pype.predict_proba | def predict_proba(self, X):
"""
Apply transforms, and predict_proba of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_proba : array-like, shape = [n_samples, n_classes]
Predicted probability of each class
"""
Xt, _, _ = self._transform(X)
return self._final_estimator.predict_proba(Xt) | python | def predict_proba(self, X):
"""
Apply transforms, and predict_proba of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_proba : array-like, shape = [n_samples, n_classes]
Predicted probability of each class
"""
Xt, _, _ = self._transform(X)
return self._final_estimator.predict_proba(Xt) | [
"def",
"predict_proba",
"(",
"self",
",",
"X",
")",
":",
"Xt",
",",
"_",
",",
"_",
"=",
"self",
".",
"_transform",
"(",
"X",
")",
"return",
"self",
".",
"_final_estimator",
".",
"predict_proba",
"(",
"Xt",
")"
] | Apply transforms, and predict_proba of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_proba : array-like, shape = [n_samples, n_classes]
Predicted probability of each class | [
"Apply",
"transforms",
"and",
"predict_proba",
"of",
"the",
"final",
"estimator"
] | d8d7039e92c4c6571a70350c03298aceab8dbeec | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/pipe.py#L292-L308 | train | 232,498 |
dmbee/seglearn | seglearn/pipe.py | Pype.decision_function | def decision_function(self, X):
"""
Apply transforms, and decision_function of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_score : array-like, shape = [n_samples, n_classes]
"""
Xt, _, _ = self._transform(X)
return self._final_estimator.decision_function(Xt) | python | def decision_function(self, X):
"""
Apply transforms, and decision_function of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_score : array-like, shape = [n_samples, n_classes]
"""
Xt, _, _ = self._transform(X)
return self._final_estimator.decision_function(Xt) | [
"def",
"decision_function",
"(",
"self",
",",
"X",
")",
":",
"Xt",
",",
"_",
",",
"_",
"=",
"self",
".",
"_transform",
"(",
"X",
")",
"return",
"self",
".",
"_final_estimator",
".",
"decision_function",
"(",
"Xt",
")"
] | Apply transforms, and decision_function of the final estimator
Parameters
----------
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
-------
y_score : array-like, shape = [n_samples, n_classes] | [
"Apply",
"transforms",
"and",
"decision_function",
"of",
"the",
"final",
"estimator"
] | d8d7039e92c4c6571a70350c03298aceab8dbeec | https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/pipe.py#L310-L325 | train | 232,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.