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
raiden-network/raiden
raiden/utils/filters.py
get_filter_args_for_all_events_from_channel
def get_filter_args_for_all_events_from_channel( token_network_address: TokenNetworkAddress, channel_identifier: ChannelID, contract_manager: ContractManager, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ) -> Dict: """ Return the filter params for all events of a given channel. """ event_filter_params = get_filter_args_for_specific_event_from_channel( token_network_address=token_network_address, channel_identifier=channel_identifier, event_name=ChannelEvent.OPENED, contract_manager=contract_manager, from_block=from_block, to_block=to_block, ) # As we want to get all events for a certain channel we remove the event specific code here # and filter just for the channel identifier # We also have to remove the trailing topics to get all filters event_filter_params['topics'] = [None, event_filter_params['topics'][1]] return event_filter_params
python
def get_filter_args_for_all_events_from_channel( token_network_address: TokenNetworkAddress, channel_identifier: ChannelID, contract_manager: ContractManager, from_block: BlockSpecification = GENESIS_BLOCK_NUMBER, to_block: BlockSpecification = 'latest', ) -> Dict: """ Return the filter params for all events of a given channel. """ event_filter_params = get_filter_args_for_specific_event_from_channel( token_network_address=token_network_address, channel_identifier=channel_identifier, event_name=ChannelEvent.OPENED, contract_manager=contract_manager, from_block=from_block, to_block=to_block, ) # As we want to get all events for a certain channel we remove the event specific code here # and filter just for the channel identifier # We also have to remove the trailing topics to get all filters event_filter_params['topics'] = [None, event_filter_params['topics'][1]] return event_filter_params
[ "def", "get_filter_args_for_all_events_from_channel", "(", "token_network_address", ":", "TokenNetworkAddress", ",", "channel_identifier", ":", "ChannelID", ",", "contract_manager", ":", "ContractManager", ",", "from_block", ":", "BlockSpecification", "=", "GENESIS_BLOCK_NUMBER...
Return the filter params for all events of a given channel.
[ "Return", "the", "filter", "params", "for", "all", "events", "of", "a", "given", "channel", "." ]
407ba15c72074e9de88771d6b9661ff4dc36bef5
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/filters.py#L62-L85
train
216,700
pytorch/tnt
torchnet/meter/confusionmeter.py
ConfusionMeter.add
def add(self, predicted, target): """Computes the confusion matrix of K x K size where K is no of classes Args: predicted (tensor): Can be an N x K tensor of predicted scores obtained from the model for N examples and K classes or an N-tensor of integer values between 0 and K-1. target (tensor): Can be a N-tensor of integer values assumed to be integer values between 0 and K-1 or N x K tensor, where targets are assumed to be provided as one-hot vectors """ predicted = predicted.cpu().numpy() target = target.cpu().numpy() assert predicted.shape[0] == target.shape[0], \ 'number of targets and predicted outputs do not match' if np.ndim(predicted) != 1: assert predicted.shape[1] == self.k, \ 'number of predictions does not match size of confusion matrix' predicted = np.argmax(predicted, 1) else: assert (predicted.max() < self.k) and (predicted.min() >= 0), \ 'predicted values are not between 1 and k' onehot_target = np.ndim(target) != 1 if onehot_target: assert target.shape[1] == self.k, \ 'Onehot target does not match size of confusion matrix' assert (target >= 0).all() and (target <= 1).all(), \ 'in one-hot encoding, target values should be 0 or 1' assert (target.sum(1) == 1).all(), \ 'multi-label setting is not supported' target = np.argmax(target, 1) else: assert (predicted.max() < self.k) and (predicted.min() >= 0), \ 'predicted values are not between 0 and k-1' # hack for bincounting 2 arrays together x = predicted + self.k * target bincount_2d = np.bincount(x.astype(np.int32), minlength=self.k ** 2) assert bincount_2d.size == self.k ** 2 conf = bincount_2d.reshape((self.k, self.k)) self.conf += conf
python
def add(self, predicted, target): """Computes the confusion matrix of K x K size where K is no of classes Args: predicted (tensor): Can be an N x K tensor of predicted scores obtained from the model for N examples and K classes or an N-tensor of integer values between 0 and K-1. target (tensor): Can be a N-tensor of integer values assumed to be integer values between 0 and K-1 or N x K tensor, where targets are assumed to be provided as one-hot vectors """ predicted = predicted.cpu().numpy() target = target.cpu().numpy() assert predicted.shape[0] == target.shape[0], \ 'number of targets and predicted outputs do not match' if np.ndim(predicted) != 1: assert predicted.shape[1] == self.k, \ 'number of predictions does not match size of confusion matrix' predicted = np.argmax(predicted, 1) else: assert (predicted.max() < self.k) and (predicted.min() >= 0), \ 'predicted values are not between 1 and k' onehot_target = np.ndim(target) != 1 if onehot_target: assert target.shape[1] == self.k, \ 'Onehot target does not match size of confusion matrix' assert (target >= 0).all() and (target <= 1).all(), \ 'in one-hot encoding, target values should be 0 or 1' assert (target.sum(1) == 1).all(), \ 'multi-label setting is not supported' target = np.argmax(target, 1) else: assert (predicted.max() < self.k) and (predicted.min() >= 0), \ 'predicted values are not between 0 and k-1' # hack for bincounting 2 arrays together x = predicted + self.k * target bincount_2d = np.bincount(x.astype(np.int32), minlength=self.k ** 2) assert bincount_2d.size == self.k ** 2 conf = bincount_2d.reshape((self.k, self.k)) self.conf += conf
[ "def", "add", "(", "self", ",", "predicted", ",", "target", ")", ":", "predicted", "=", "predicted", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "target", "=", "target", ".", "cpu", "(", ")", ".", "numpy", "(", ")", "assert", "predicted", ".", ...
Computes the confusion matrix of K x K size where K is no of classes Args: predicted (tensor): Can be an N x K tensor of predicted scores obtained from the model for N examples and K classes or an N-tensor of integer values between 0 and K-1. target (tensor): Can be a N-tensor of integer values assumed to be integer values between 0 and K-1 or N x K tensor, where targets are assumed to be provided as one-hot vectors
[ "Computes", "the", "confusion", "matrix", "of", "K", "x", "K", "size", "where", "K", "is", "no", "of", "classes" ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/meter/confusionmeter.py#L29-L75
train
216,701
pytorch/tnt
torchnet/dataset/shuffledataset.py
ShuffleDataset.resample
def resample(self, seed=None): """Resample the dataset. Args: seed (int, optional): Seed for resampling. By default no seed is used. """ if seed is not None: gen = torch.manual_seed(seed) else: gen = torch.default_generator if self.replacement: self.perm = torch.LongTensor(len(self)).random_( len(self.dataset), generator=gen) else: self.perm = torch.randperm( len(self.dataset), generator=gen).narrow(0, 0, len(self))
python
def resample(self, seed=None): """Resample the dataset. Args: seed (int, optional): Seed for resampling. By default no seed is used. """ if seed is not None: gen = torch.manual_seed(seed) else: gen = torch.default_generator if self.replacement: self.perm = torch.LongTensor(len(self)).random_( len(self.dataset), generator=gen) else: self.perm = torch.randperm( len(self.dataset), generator=gen).narrow(0, 0, len(self))
[ "def", "resample", "(", "self", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "not", "None", ":", "gen", "=", "torch", ".", "manual_seed", "(", "seed", ")", "else", ":", "gen", "=", "torch", ".", "default_generator", "if", "self", ".", "r...
Resample the dataset. Args: seed (int, optional): Seed for resampling. By default no seed is used.
[ "Resample", "the", "dataset", "." ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/dataset/shuffledataset.py#L44-L61
train
216,702
pytorch/tnt
torchnet/meter/apmeter.py
APMeter.reset
def reset(self): """Resets the meter with empty member variables""" self.scores = torch.FloatTensor(torch.FloatStorage()) self.targets = torch.LongTensor(torch.LongStorage()) self.weights = torch.FloatTensor(torch.FloatStorage())
python
def reset(self): """Resets the meter with empty member variables""" self.scores = torch.FloatTensor(torch.FloatStorage()) self.targets = torch.LongTensor(torch.LongStorage()) self.weights = torch.FloatTensor(torch.FloatStorage())
[ "def", "reset", "(", "self", ")", ":", "self", ".", "scores", "=", "torch", ".", "FloatTensor", "(", "torch", ".", "FloatStorage", "(", ")", ")", "self", ".", "targets", "=", "torch", ".", "LongTensor", "(", "torch", ".", "LongStorage", "(", ")", ")"...
Resets the meter with empty member variables
[ "Resets", "the", "meter", "with", "empty", "member", "variables" ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/meter/apmeter.py#L26-L30
train
216,703
pytorch/tnt
torchnet/meter/apmeter.py
APMeter.value
def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k """ if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) if hasattr(torch, "arange"): rg = torch.arange(1, self.scores.size(0) + 1).float() else: rg = torch.range(1, self.scores.size(0)).float() if self.weights.numel() > 0: weight = self.weights.new(self.weights.size()) weighted_truth = self.weights.new(self.weights.size()) # compute average precision for each class for k in range(self.scores.size(1)): # sort scores scores = self.scores[:, k] targets = self.targets[:, k] _, sortind = torch.sort(scores, 0, True) truth = targets[sortind] if self.weights.numel() > 0: weight = self.weights[sortind] weighted_truth = truth.float() * weight rg = weight.cumsum(0) # compute true positive sums if self.weights.numel() > 0: tp = weighted_truth.cumsum(0) else: tp = truth.float().cumsum(0) # compute precision curve precision = tp.div(rg) # compute average precision ap[k] = precision[truth.byte()].sum() / max(float(truth.sum()), 1) return ap
python
def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k """ if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) if hasattr(torch, "arange"): rg = torch.arange(1, self.scores.size(0) + 1).float() else: rg = torch.range(1, self.scores.size(0)).float() if self.weights.numel() > 0: weight = self.weights.new(self.weights.size()) weighted_truth = self.weights.new(self.weights.size()) # compute average precision for each class for k in range(self.scores.size(1)): # sort scores scores = self.scores[:, k] targets = self.targets[:, k] _, sortind = torch.sort(scores, 0, True) truth = targets[sortind] if self.weights.numel() > 0: weight = self.weights[sortind] weighted_truth = truth.float() * weight rg = weight.cumsum(0) # compute true positive sums if self.weights.numel() > 0: tp = weighted_truth.cumsum(0) else: tp = truth.float().cumsum(0) # compute precision curve precision = tp.div(rg) # compute average precision ap[k] = precision[truth.byte()].sum() / max(float(truth.sum()), 1) return ap
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "scores", ".", "numel", "(", ")", "==", "0", ":", "return", "0", "ap", "=", "torch", ".", "zeros", "(", "self", ".", "scores", ".", "size", "(", "1", ")", ")", "if", "hasattr", "(", "t...
Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k
[ "Returns", "the", "model", "s", "average", "precision", "for", "each", "class" ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/meter/apmeter.py#L100-L142
train
216,704
pytorch/tnt
torchnet/engine/engine.py
Engine.hook
def hook(self, name, state): r"""Registers a backward hook. The hook will be called every time a gradient with respect to the Tensor is computed. The hook should have the following signature:: hook (grad) -> Tensor or None The hook should not modify its argument, but it can optionally return a new gradient which will be used in place of :attr:`grad`. This function returns a handle with a method ``handle.remove()`` that removes the hook from the module. Example: >>> v = torch.tensor([0., 0., 0.], requires_grad=True) >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient >>> v.backward(torch.tensor([1., 2., 3.])) >>> v.grad 2 4 6 [torch.FloatTensor of size (3,)] >>> h.remove() # removes the hook """ if name in self.hooks: self.hooks[name](state)
python
def hook(self, name, state): r"""Registers a backward hook. The hook will be called every time a gradient with respect to the Tensor is computed. The hook should have the following signature:: hook (grad) -> Tensor or None The hook should not modify its argument, but it can optionally return a new gradient which will be used in place of :attr:`grad`. This function returns a handle with a method ``handle.remove()`` that removes the hook from the module. Example: >>> v = torch.tensor([0., 0., 0.], requires_grad=True) >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient >>> v.backward(torch.tensor([1., 2., 3.])) >>> v.grad 2 4 6 [torch.FloatTensor of size (3,)] >>> h.remove() # removes the hook """ if name in self.hooks: self.hooks[name](state)
[ "def", "hook", "(", "self", ",", "name", ",", "state", ")", ":", "if", "name", "in", "self", ".", "hooks", ":", "self", ".", "hooks", "[", "name", "]", "(", "state", ")" ]
r"""Registers a backward hook. The hook will be called every time a gradient with respect to the Tensor is computed. The hook should have the following signature:: hook (grad) -> Tensor or None The hook should not modify its argument, but it can optionally return a new gradient which will be used in place of :attr:`grad`. This function returns a handle with a method ``handle.remove()`` that removes the hook from the module. Example: >>> v = torch.tensor([0., 0., 0.], requires_grad=True) >>> h = v.register_hook(lambda grad: grad * 2) # double the gradient >>> v.backward(torch.tensor([1., 2., 3.])) >>> v.grad 2 4 6 [torch.FloatTensor of size (3,)] >>> h.remove() # removes the hook
[ "r", "Registers", "a", "backward", "hook", "." ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/engine/engine.py#L5-L31
train
216,705
pytorch/tnt
torchnet/logger/visdomlogger.py
BaseVisdomLogger._viz_prototype
def _viz_prototype(self, vis_fn): ''' Outputs a function which will log the arguments to Visdom in an appropriate way. Args: vis_fn: A function, such as self.vis.image ''' def _viz_logger(*args, **kwargs): self.win = vis_fn(*args, win=self.win, env=self.env, opts=self.opts, **kwargs) return _viz_logger
python
def _viz_prototype(self, vis_fn): ''' Outputs a function which will log the arguments to Visdom in an appropriate way. Args: vis_fn: A function, such as self.vis.image ''' def _viz_logger(*args, **kwargs): self.win = vis_fn(*args, win=self.win, env=self.env, opts=self.opts, **kwargs) return _viz_logger
[ "def", "_viz_prototype", "(", "self", ",", "vis_fn", ")", ":", "def", "_viz_logger", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "win", "=", "vis_fn", "(", "*", "args", ",", "win", "=", "self", ".", "win", ",", "env", "=", ...
Outputs a function which will log the arguments to Visdom in an appropriate way. Args: vis_fn: A function, such as self.vis.image
[ "Outputs", "a", "function", "which", "will", "log", "the", "arguments", "to", "Visdom", "in", "an", "appropriate", "way", "." ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/logger/visdomlogger.py#L36-L48
train
216,706
pytorch/tnt
torchnet/logger/visdomlogger.py
BaseVisdomLogger.log_state
def log_state(self, state): """ Gathers the stats from self.trainer.stats and passes them into self.log, as a list """ results = [] for field_idx, field in enumerate(self.fields): parent, stat = None, state for f in field: parent, stat = stat, stat[f] results.append(stat) self.log(*results)
python
def log_state(self, state): """ Gathers the stats from self.trainer.stats and passes them into self.log, as a list """ results = [] for field_idx, field in enumerate(self.fields): parent, stat = None, state for f in field: parent, stat = stat, stat[f] results.append(stat) self.log(*results)
[ "def", "log_state", "(", "self", ",", "state", ")", ":", "results", "=", "[", "]", "for", "field_idx", ",", "field", "in", "enumerate", "(", "self", ".", "fields", ")", ":", "parent", ",", "stat", "=", "None", ",", "state", "for", "f", "in", "field...
Gathers the stats from self.trainer.stats and passes them into self.log, as a list
[ "Gathers", "the", "stats", "from", "self", ".", "trainer", ".", "stats", "and", "passes", "them", "into", "self", ".", "log", "as", "a", "list" ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/logger/visdomlogger.py#L50-L59
train
216,707
pytorch/tnt
torchnet/logger/meterlogger.py
MeterLogger.peek_meter
def peek_meter(self): '''Returns a dict of all meters and their values.''' result = {} for key in self.meter.keys(): val = self.meter[key].value() val = val[0] if isinstance(val, (list, tuple)) else val result[key] = val return result
python
def peek_meter(self): '''Returns a dict of all meters and their values.''' result = {} for key in self.meter.keys(): val = self.meter[key].value() val = val[0] if isinstance(val, (list, tuple)) else val result[key] = val return result
[ "def", "peek_meter", "(", "self", ")", ":", "result", "=", "{", "}", "for", "key", "in", "self", ".", "meter", ".", "keys", "(", ")", ":", "val", "=", "self", ".", "meter", "[", "key", "]", ".", "value", "(", ")", "val", "=", "val", "[", "0",...
Returns a dict of all meters and their values.
[ "Returns", "a", "dict", "of", "all", "meters", "and", "their", "values", "." ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/logger/meterlogger.py#L103-L110
train
216,708
pytorch/tnt
torchnet/utils/resultswriter.py
ResultsWriter.update
def update(self, task_name, result): ''' Update the results file with new information. Args: task_name (str): Name of the currently running task. A previously unseen ``task_name`` will create a new entry in both :attr:`tasks` and :attr:`results`. result: This will be appended to the list in :attr:`results` which corresponds to the ``task_name`` in ``task_name``:attr:`tasks`. ''' with open(self.filepath, 'rb') as f: existing_results = pickle.load(f) if task_name not in self.tasks: self._add_task(task_name) existing_results['tasks'].append(task_name) existing_results['results'].append([]) task_name_idx = existing_results['tasks'].index(task_name) results = existing_results['results'][task_name_idx] results.append(result) with open(self.filepath, 'wb') as f: pickle.dump(existing_results, f)
python
def update(self, task_name, result): ''' Update the results file with new information. Args: task_name (str): Name of the currently running task. A previously unseen ``task_name`` will create a new entry in both :attr:`tasks` and :attr:`results`. result: This will be appended to the list in :attr:`results` which corresponds to the ``task_name`` in ``task_name``:attr:`tasks`. ''' with open(self.filepath, 'rb') as f: existing_results = pickle.load(f) if task_name not in self.tasks: self._add_task(task_name) existing_results['tasks'].append(task_name) existing_results['results'].append([]) task_name_idx = existing_results['tasks'].index(task_name) results = existing_results['results'][task_name_idx] results.append(result) with open(self.filepath, 'wb') as f: pickle.dump(existing_results, f)
[ "def", "update", "(", "self", ",", "task_name", ",", "result", ")", ":", "with", "open", "(", "self", ".", "filepath", ",", "'rb'", ")", "as", "f", ":", "existing_results", "=", "pickle", ".", "load", "(", "f", ")", "if", "task_name", "not", "in", ...
Update the results file with new information. Args: task_name (str): Name of the currently running task. A previously unseen ``task_name`` will create a new entry in both :attr:`tasks` and :attr:`results`. result: This will be appended to the list in :attr:`results` which corresponds to the ``task_name`` in ``task_name``:attr:`tasks`.
[ "Update", "the", "results", "file", "with", "new", "information", "." ]
3ed904b2cbed16d3bab368bb9ca5adc876d3ce69
https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/utils/resultswriter.py#L49-L70
train
216,709
onelogin/python3-saml
src/onelogin/saml2/xml_utils.py
OneLogin_Saml2_XML.query
def query(dom, query, context=None, tagid=None): """ Extracts nodes that match the query from the Element :param dom: The root of the lxml objet :type: Element :param query: Xpath Expresion :type: string :param context: Context Node :type: DOMElement :param tagid: Tag ID :type query: String :returns: The queried nodes :rtype: list """ if context is None: source = dom else: source = context if tagid is None: return source.xpath(query, namespaces=OneLogin_Saml2_Constants.NSMAP) else: return source.xpath(query, tagid=tagid, namespaces=OneLogin_Saml2_Constants.NSMAP)
python
def query(dom, query, context=None, tagid=None): """ Extracts nodes that match the query from the Element :param dom: The root of the lxml objet :type: Element :param query: Xpath Expresion :type: string :param context: Context Node :type: DOMElement :param tagid: Tag ID :type query: String :returns: The queried nodes :rtype: list """ if context is None: source = dom else: source = context if tagid is None: return source.xpath(query, namespaces=OneLogin_Saml2_Constants.NSMAP) else: return source.xpath(query, tagid=tagid, namespaces=OneLogin_Saml2_Constants.NSMAP)
[ "def", "query", "(", "dom", ",", "query", ",", "context", "=", "None", ",", "tagid", "=", "None", ")", ":", "if", "context", "is", "None", ":", "source", "=", "dom", "else", ":", "source", "=", "context", "if", "tagid", "is", "None", ":", "return",...
Extracts nodes that match the query from the Element :param dom: The root of the lxml objet :type: Element :param query: Xpath Expresion :type: string :param context: Context Node :type: DOMElement :param tagid: Tag ID :type query: String :returns: The queried nodes :rtype: list
[ "Extracts", "nodes", "that", "match", "the", "query", "from", "the", "Element" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/xml_utils.py#L107-L134
train
216,710
onelogin/python3-saml
src/onelogin/saml2/idp_metadata_parser.py
dict_deep_merge
def dict_deep_merge(a, b, path=None): """Deep-merge dictionary `b` into dictionary `a`. Kudos to http://stackoverflow.com/a/7205107/145400 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): dict_deep_merge(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: # Key conflict, but equal value. pass else: # Key/value conflict. Prioritize b over a. a[key] = b[key] else: a[key] = b[key] return a
python
def dict_deep_merge(a, b, path=None): """Deep-merge dictionary `b` into dictionary `a`. Kudos to http://stackoverflow.com/a/7205107/145400 """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): dict_deep_merge(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: # Key conflict, but equal value. pass else: # Key/value conflict. Prioritize b over a. a[key] = b[key] else: a[key] = b[key] return a
[ "def", "dict_deep_merge", "(", "a", ",", "b", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "[", "]", "for", "key", "in", "b", ":", "if", "key", "in", "a", ":", "if", "isinstance", "(", "a", "[", "key", "]"...
Deep-merge dictionary `b` into dictionary `a`. Kudos to http://stackoverflow.com/a/7205107/145400
[ "Deep", "-", "merge", "dictionary", "b", "into", "dictionary", "a", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/idp_metadata_parser.py#L248-L267
train
216,711
onelogin/python3-saml
src/onelogin/saml2/settings.py
OneLogin_Saml2_Settings.__load_paths
def __load_paths(self, base_path=None): """ Set the paths of the different folders """ if base_path is None: base_path = dirname(dirname(dirname(__file__))) if not base_path.endswith(sep): base_path += sep self.__paths = { 'base': base_path, 'cert': base_path + 'certs' + sep, 'lib': base_path + 'lib' + sep, 'extlib': base_path + 'extlib' + sep, }
python
def __load_paths(self, base_path=None): """ Set the paths of the different folders """ if base_path is None: base_path = dirname(dirname(dirname(__file__))) if not base_path.endswith(sep): base_path += sep self.__paths = { 'base': base_path, 'cert': base_path + 'certs' + sep, 'lib': base_path + 'lib' + sep, 'extlib': base_path + 'extlib' + sep, }
[ "def", "__load_paths", "(", "self", ",", "base_path", "=", "None", ")", ":", "if", "base_path", "is", "None", ":", "base_path", "=", "dirname", "(", "dirname", "(", "dirname", "(", "__file__", ")", ")", ")", "if", "not", "base_path", ".", "endswith", "...
Set the paths of the different folders
[ "Set", "the", "paths", "of", "the", "different", "folders" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L130-L143
train
216,712
onelogin/python3-saml
src/onelogin/saml2/settings.py
OneLogin_Saml2_Settings.__update_paths
def __update_paths(self, settings): """ Set custom paths if necessary """ if not isinstance(settings, dict): return if 'custom_base_path' in settings: base_path = settings['custom_base_path'] base_path = join(dirname(__file__), base_path) self.__load_paths(base_path)
python
def __update_paths(self, settings): """ Set custom paths if necessary """ if not isinstance(settings, dict): return if 'custom_base_path' in settings: base_path = settings['custom_base_path'] base_path = join(dirname(__file__), base_path) self.__load_paths(base_path)
[ "def", "__update_paths", "(", "self", ",", "settings", ")", ":", "if", "not", "isinstance", "(", "settings", ",", "dict", ")", ":", "return", "if", "'custom_base_path'", "in", "settings", ":", "base_path", "=", "settings", "[", "'custom_base_path'", "]", "ba...
Set custom paths if necessary
[ "Set", "custom", "paths", "if", "necessary" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L145-L155
train
216,713
onelogin/python3-saml
src/onelogin/saml2/settings.py
OneLogin_Saml2_Settings.__load_settings_from_dict
def __load_settings_from_dict(self, settings): """ Loads settings info from a settings Dict :param settings: SAML Toolkit Settings :type settings: dict :returns: True if the settings info is valid :rtype: boolean """ errors = self.check_settings(settings) if len(errors) == 0: self.__errors = [] self.__sp = settings['sp'] self.__idp = settings.get('idp', {}) self.__strict = settings.get('strict', False) self.__debug = settings.get('debug', False) self.__security = settings.get('security', {}) self.__contacts = settings.get('contactPerson', {}) self.__organization = settings.get('organization', {}) self.__add_default_values() return True self.__errors = errors return False
python
def __load_settings_from_dict(self, settings): """ Loads settings info from a settings Dict :param settings: SAML Toolkit Settings :type settings: dict :returns: True if the settings info is valid :rtype: boolean """ errors = self.check_settings(settings) if len(errors) == 0: self.__errors = [] self.__sp = settings['sp'] self.__idp = settings.get('idp', {}) self.__strict = settings.get('strict', False) self.__debug = settings.get('debug', False) self.__security = settings.get('security', {}) self.__contacts = settings.get('contactPerson', {}) self.__organization = settings.get('organization', {}) self.__add_default_values() return True self.__errors = errors return False
[ "def", "__load_settings_from_dict", "(", "self", ",", "settings", ")", ":", "errors", "=", "self", ".", "check_settings", "(", "settings", ")", "if", "len", "(", "errors", ")", "==", "0", ":", "self", ".", "__errors", "=", "[", "]", "self", ".", "__sp"...
Loads settings info from a settings Dict :param settings: SAML Toolkit Settings :type settings: dict :returns: True if the settings info is valid :rtype: boolean
[ "Loads", "settings", "info", "from", "a", "settings", "Dict" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L202-L227
train
216,714
onelogin/python3-saml
src/onelogin/saml2/settings.py
OneLogin_Saml2_Settings.check_settings
def check_settings(self, settings): """ Checks the settings info. :param settings: Dict with settings data :type settings: dict :returns: Errors found on the settings data :rtype: list """ assert isinstance(settings, dict) errors = [] if not isinstance(settings, dict) or len(settings) == 0: errors.append('invalid_syntax') else: if not self.__sp_validation_only: errors += self.check_idp_settings(settings) sp_errors = self.check_sp_settings(settings) errors += sp_errors return errors
python
def check_settings(self, settings): """ Checks the settings info. :param settings: Dict with settings data :type settings: dict :returns: Errors found on the settings data :rtype: list """ assert isinstance(settings, dict) errors = [] if not isinstance(settings, dict) or len(settings) == 0: errors.append('invalid_syntax') else: if not self.__sp_validation_only: errors += self.check_idp_settings(settings) sp_errors = self.check_sp_settings(settings) errors += sp_errors return errors
[ "def", "check_settings", "(", "self", ",", "settings", ")", ":", "assert", "isinstance", "(", "settings", ",", "dict", ")", "errors", "=", "[", "]", "if", "not", "isinstance", "(", "settings", ",", "dict", ")", "or", "len", "(", "settings", ")", "==", ...
Checks the settings info. :param settings: Dict with settings data :type settings: dict :returns: Errors found on the settings data :rtype: list
[ "Checks", "the", "settings", "info", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L315-L336
train
216,715
onelogin/python3-saml
src/onelogin/saml2/settings.py
OneLogin_Saml2_Settings.format_idp_cert_multi
def format_idp_cert_multi(self): """ Formats the Multple IdP certs. """ if 'x509certMulti' in self.__idp: if 'signing' in self.__idp['x509certMulti']: for idx in range(len(self.__idp['x509certMulti']['signing'])): self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['signing'][idx]) if 'encryption' in self.__idp['x509certMulti']: for idx in range(len(self.__idp['x509certMulti']['encryption'])): self.__idp['x509certMulti']['encryption'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['encryption'][idx])
python
def format_idp_cert_multi(self): """ Formats the Multple IdP certs. """ if 'x509certMulti' in self.__idp: if 'signing' in self.__idp['x509certMulti']: for idx in range(len(self.__idp['x509certMulti']['signing'])): self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['signing'][idx]) if 'encryption' in self.__idp['x509certMulti']: for idx in range(len(self.__idp['x509certMulti']['encryption'])): self.__idp['x509certMulti']['encryption'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['encryption'][idx])
[ "def", "format_idp_cert_multi", "(", "self", ")", ":", "if", "'x509certMulti'", "in", "self", ".", "__idp", ":", "if", "'signing'", "in", "self", ".", "__idp", "[", "'x509certMulti'", "]", ":", "for", "idx", "in", "range", "(", "len", "(", "self", ".", ...
Formats the Multple IdP certs.
[ "Formats", "the", "Multple", "IdP", "certs", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L730-L741
train
216,716
onelogin/python3-saml
src/onelogin/saml2/utils.py
return_false_on_exception
def return_false_on_exception(func): """ Decorator. When applied to a function, it will, by default, suppress any exceptions raised by that function and return False. It may be overridden by passing a "raise_exceptions" keyword argument when calling the wrapped function. """ @wraps(func) def exceptfalse(*args, **kwargs): if not kwargs.pop('raise_exceptions', False): try: return func(*args, **kwargs) except Exception: return False else: return func(*args, **kwargs) return exceptfalse
python
def return_false_on_exception(func): """ Decorator. When applied to a function, it will, by default, suppress any exceptions raised by that function and return False. It may be overridden by passing a "raise_exceptions" keyword argument when calling the wrapped function. """ @wraps(func) def exceptfalse(*args, **kwargs): if not kwargs.pop('raise_exceptions', False): try: return func(*args, **kwargs) except Exception: return False else: return func(*args, **kwargs) return exceptfalse
[ "def", "return_false_on_exception", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "exceptfalse", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "kwargs", ".", "pop", "(", "'raise_exceptions'", ",", "False", ")", ":", ...
Decorator. When applied to a function, it will, by default, suppress any exceptions raised by that function and return False. It may be overridden by passing a "raise_exceptions" keyword argument when calling the wrapped function.
[ "Decorator", ".", "When", "applied", "to", "a", "function", "it", "will", "by", "default", "suppress", "any", "exceptions", "raised", "by", "that", "function", "and", "return", "False", ".", "It", "may", "be", "overridden", "by", "passing", "a", "raise_excep...
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L39-L54
train
216,717
onelogin/python3-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.is_https
def is_https(request_data): """ Checks if https or http. :param request_data: The request as a dict :type: dict :return: False if https is not active :rtype: boolean """ is_https = 'https' in request_data and request_data['https'] != 'off' is_https = is_https or ('server_port' in request_data and str(request_data['server_port']) == '443') return is_https
python
def is_https(request_data): """ Checks if https or http. :param request_data: The request as a dict :type: dict :return: False if https is not active :rtype: boolean """ is_https = 'https' in request_data and request_data['https'] != 'off' is_https = is_https or ('server_port' in request_data and str(request_data['server_port']) == '443') return is_https
[ "def", "is_https", "(", "request_data", ")", ":", "is_https", "=", "'https'", "in", "request_data", "and", "request_data", "[", "'https'", "]", "!=", "'off'", "is_https", "=", "is_https", "or", "(", "'server_port'", "in", "request_data", "and", "str", "(", "...
Checks if https or http. :param request_data: The request as a dict :type: dict :return: False if https is not active :rtype: boolean
[ "Checks", "if", "https", "or", "http", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L300-L312
train
216,718
onelogin/python3-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.get_self_url_no_query
def get_self_url_no_query(request_data): """ Returns the URL of the current host + current view. :param request_data: The request as a dict :type: dict :return: The url of current host + current view :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) script_name = request_data['script_name'] if script_name: if script_name[0] != '/': script_name = '/' + script_name else: script_name = '' self_url_no_query = self_url_host + script_name if 'path_info' in request_data: self_url_no_query += request_data['path_info'] return self_url_no_query
python
def get_self_url_no_query(request_data): """ Returns the URL of the current host + current view. :param request_data: The request as a dict :type: dict :return: The url of current host + current view :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) script_name = request_data['script_name'] if script_name: if script_name[0] != '/': script_name = '/' + script_name else: script_name = '' self_url_no_query = self_url_host + script_name if 'path_info' in request_data: self_url_no_query += request_data['path_info'] return self_url_no_query
[ "def", "get_self_url_no_query", "(", "request_data", ")", ":", "self_url_host", "=", "OneLogin_Saml2_Utils", ".", "get_self_url_host", "(", "request_data", ")", "script_name", "=", "request_data", "[", "'script_name'", "]", "if", "script_name", ":", "if", "script_name...
Returns the URL of the current host + current view. :param request_data: The request as a dict :type: dict :return: The url of current host + current view :rtype: string
[ "Returns", "the", "URL", "of", "the", "current", "host", "+", "current", "view", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L315-L336
train
216,719
onelogin/python3-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.get_self_routed_url_no_query
def get_self_routed_url_no_query(request_data): """ Returns the routed URL of the current host + current view. :param request_data: The request as a dict :type: dict :return: The url of current host + current view :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) route = '' if 'request_uri' in request_data and request_data['request_uri']: route = request_data['request_uri'] if 'query_string' in request_data and request_data['query_string']: route = route.replace(request_data['query_string'], '') return self_url_host + route
python
def get_self_routed_url_no_query(request_data): """ Returns the routed URL of the current host + current view. :param request_data: The request as a dict :type: dict :return: The url of current host + current view :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) route = '' if 'request_uri' in request_data and request_data['request_uri']: route = request_data['request_uri'] if 'query_string' in request_data and request_data['query_string']: route = route.replace(request_data['query_string'], '') return self_url_host + route
[ "def", "get_self_routed_url_no_query", "(", "request_data", ")", ":", "self_url_host", "=", "OneLogin_Saml2_Utils", ".", "get_self_url_host", "(", "request_data", ")", "route", "=", "''", "if", "'request_uri'", "in", "request_data", "and", "request_data", "[", "'reque...
Returns the routed URL of the current host + current view. :param request_data: The request as a dict :type: dict :return: The url of current host + current view :rtype: string
[ "Returns", "the", "routed", "URL", "of", "the", "current", "host", "+", "current", "view", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L339-L356
train
216,720
onelogin/python3-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.get_self_url
def get_self_url(request_data): """ Returns the URL of the current host + current view + query. :param request_data: The request as a dict :type: dict :return: The url of current host + current view + query :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) request_uri = '' if 'request_uri' in request_data: request_uri = request_data['request_uri'] if not request_uri.startswith('/'): match = re.search('^https?://[^/]*(/.*)', request_uri) if match is not None: request_uri = match.groups()[0] return self_url_host + request_uri
python
def get_self_url(request_data): """ Returns the URL of the current host + current view + query. :param request_data: The request as a dict :type: dict :return: The url of current host + current view + query :rtype: string """ self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data) request_uri = '' if 'request_uri' in request_data: request_uri = request_data['request_uri'] if not request_uri.startswith('/'): match = re.search('^https?://[^/]*(/.*)', request_uri) if match is not None: request_uri = match.groups()[0] return self_url_host + request_uri
[ "def", "get_self_url", "(", "request_data", ")", ":", "self_url_host", "=", "OneLogin_Saml2_Utils", ".", "get_self_url_host", "(", "request_data", ")", "request_uri", "=", "''", "if", "'request_uri'", "in", "request_data", ":", "request_uri", "=", "request_data", "[...
Returns the URL of the current host + current view + query. :param request_data: The request as a dict :type: dict :return: The url of current host + current view + query :rtype: string
[ "Returns", "the", "URL", "of", "the", "current", "host", "+", "current", "view", "+", "query", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L359-L379
train
216,721
onelogin/python3-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.get_expire_time
def get_expire_time(cache_duration=None, valid_until=None): """ Compares 2 dates and returns the earliest. :param cache_duration: The duration, as a string. :type: string :param valid_until: The valid until date, as a string or as a timestamp :type: string :return: The expiration time. :rtype: int """ expire_time = None if cache_duration is not None: expire_time = OneLogin_Saml2_Utils.parse_duration(cache_duration) if valid_until is not None: if isinstance(valid_until, int): valid_until_time = valid_until else: valid_until_time = OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until) if expire_time is None or expire_time > valid_until_time: expire_time = valid_until_time if expire_time is not None: return '%d' % expire_time return None
python
def get_expire_time(cache_duration=None, valid_until=None): """ Compares 2 dates and returns the earliest. :param cache_duration: The duration, as a string. :type: string :param valid_until: The valid until date, as a string or as a timestamp :type: string :return: The expiration time. :rtype: int """ expire_time = None if cache_duration is not None: expire_time = OneLogin_Saml2_Utils.parse_duration(cache_duration) if valid_until is not None: if isinstance(valid_until, int): valid_until_time = valid_until else: valid_until_time = OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until) if expire_time is None or expire_time > valid_until_time: expire_time = valid_until_time if expire_time is not None: return '%d' % expire_time return None
[ "def", "get_expire_time", "(", "cache_duration", "=", "None", ",", "valid_until", "=", "None", ")", ":", "expire_time", "=", "None", "if", "cache_duration", "is", "not", "None", ":", "expire_time", "=", "OneLogin_Saml2_Utils", ".", "parse_duration", "(", "cache_...
Compares 2 dates and returns the earliest. :param cache_duration: The duration, as a string. :type: string :param valid_until: The valid until date, as a string or as a timestamp :type: string :return: The expiration time. :rtype: int
[ "Compares", "2", "dates", "and", "returns", "the", "earliest", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L458-L486
train
216,722
onelogin/python3-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.calculate_x509_fingerprint
def calculate_x509_fingerprint(x509_cert, alg='sha1'): """ Calculates the fingerprint of a formatted x509cert. :param x509_cert: x509 cert formatted :type: string :param alg: The algorithm to build the fingerprint :type: string :returns: fingerprint :rtype: string """ assert isinstance(x509_cert, compat.str_type) lines = x509_cert.split('\n') data = '' inData = False for line in lines: # Remove '\r' from end of line if present. line = line.rstrip() if not inData: if line == '-----BEGIN CERTIFICATE-----': inData = True elif line == '-----BEGIN PUBLIC KEY-----' or line == '-----BEGIN RSA PRIVATE KEY-----': # This isn't an X509 certificate. return None else: if line == '-----END CERTIFICATE-----': break # Append the current line to the certificate data. data += line if not data: return None decoded_data = base64.b64decode(compat.to_bytes(data)) if alg == 'sha512': fingerprint = sha512(decoded_data) elif alg == 'sha384': fingerprint = sha384(decoded_data) elif alg == 'sha256': fingerprint = sha256(decoded_data) else: fingerprint = sha1(decoded_data) return fingerprint.hexdigest().lower()
python
def calculate_x509_fingerprint(x509_cert, alg='sha1'): """ Calculates the fingerprint of a formatted x509cert. :param x509_cert: x509 cert formatted :type: string :param alg: The algorithm to build the fingerprint :type: string :returns: fingerprint :rtype: string """ assert isinstance(x509_cert, compat.str_type) lines = x509_cert.split('\n') data = '' inData = False for line in lines: # Remove '\r' from end of line if present. line = line.rstrip() if not inData: if line == '-----BEGIN CERTIFICATE-----': inData = True elif line == '-----BEGIN PUBLIC KEY-----' or line == '-----BEGIN RSA PRIVATE KEY-----': # This isn't an X509 certificate. return None else: if line == '-----END CERTIFICATE-----': break # Append the current line to the certificate data. data += line if not data: return None decoded_data = base64.b64decode(compat.to_bytes(data)) if alg == 'sha512': fingerprint = sha512(decoded_data) elif alg == 'sha384': fingerprint = sha384(decoded_data) elif alg == 'sha256': fingerprint = sha256(decoded_data) else: fingerprint = sha1(decoded_data) return fingerprint.hexdigest().lower()
[ "def", "calculate_x509_fingerprint", "(", "x509_cert", ",", "alg", "=", "'sha1'", ")", ":", "assert", "isinstance", "(", "x509_cert", ",", "compat", ".", "str_type", ")", "lines", "=", "x509_cert", ".", "split", "(", "'\\n'", ")", "data", "=", "''", "inDat...
Calculates the fingerprint of a formatted x509cert. :param x509_cert: x509 cert formatted :type: string :param alg: The algorithm to build the fingerprint :type: string :returns: fingerprint :rtype: string
[ "Calculates", "the", "fingerprint", "of", "a", "formatted", "x509cert", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L498-L547
train
216,723
onelogin/python3-saml
src/onelogin/saml2/utils.py
OneLogin_Saml2_Utils.sign_binary
def sign_binary(msg, key, algorithm=xmlsec.Transform.RSA_SHA1, debug=False): """ Sign binary message :param msg: The element we should validate :type: bytes :param key: The private key :type: string :param debug: Activate the xmlsec debug :type: bool :return signed message :rtype str """ if isinstance(msg, str): msg = msg.encode('utf8') xmlsec.enable_debug_trace(debug) dsig_ctx = xmlsec.SignatureContext() dsig_ctx.key = xmlsec.Key.from_memory(key, xmlsec.KeyFormat.PEM, None) return dsig_ctx.sign_binary(compat.to_bytes(msg), algorithm)
python
def sign_binary(msg, key, algorithm=xmlsec.Transform.RSA_SHA1, debug=False): """ Sign binary message :param msg: The element we should validate :type: bytes :param key: The private key :type: string :param debug: Activate the xmlsec debug :type: bool :return signed message :rtype str """ if isinstance(msg, str): msg = msg.encode('utf8') xmlsec.enable_debug_trace(debug) dsig_ctx = xmlsec.SignatureContext() dsig_ctx.key = xmlsec.Key.from_memory(key, xmlsec.KeyFormat.PEM, None) return dsig_ctx.sign_binary(compat.to_bytes(msg), algorithm)
[ "def", "sign_binary", "(", "msg", ",", "key", ",", "algorithm", "=", "xmlsec", ".", "Transform", ".", "RSA_SHA1", ",", "debug", "=", "False", ")", ":", "if", "isinstance", "(", "msg", ",", "str", ")", ":", "msg", "=", "msg", ".", "encode", "(", "'u...
Sign binary message :param msg: The element we should validate :type: bytes :param key: The private key :type: string :param debug: Activate the xmlsec debug :type: bool :return signed message :rtype str
[ "Sign", "binary", "message" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L986-L1009
train
216,724
onelogin/python3-saml
src/onelogin/saml2/auth.py
OneLogin_Saml2_Auth.process_response
def process_response(self, request_id=None): """ Process the SAML Response sent by the IdP. :param request_id: Is an optional argument. Is the ID of the AuthNRequest sent by this SP to the IdP. :type request_id: string :raises: OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND, when a POST with a SAMLResponse is not found """ self.__errors = [] self.__error_reason = None if 'post_data' in self.__request_data and 'SAMLResponse' in self.__request_data['post_data']: # AuthnResponse -- HTTP_POST Binding response = OneLogin_Saml2_Response(self.__settings, self.__request_data['post_data']['SAMLResponse']) self.__last_response = response.get_xml_document() if response.is_valid(self.__request_data, request_id): self.__attributes = response.get_attributes() self.__nameid = response.get_nameid() self.__nameid_format = response.get_nameid_format() self.__session_index = response.get_session_index() self.__session_expiration = response.get_session_not_on_or_after() self.__last_message_id = response.get_id() self.__last_assertion_id = response.get_assertion_id() self.__last_authn_contexts = response.get_authn_contexts() self.__authenticated = True self.__last_assertion_not_on_or_after = response.get_assertion_not_on_or_after() else: self.__errors.append('invalid_response') self.__error_reason = response.get_error() else: self.__errors.append('invalid_binding') raise OneLogin_Saml2_Error( 'SAML Response not found, Only supported HTTP_POST Binding', OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND )
python
def process_response(self, request_id=None): """ Process the SAML Response sent by the IdP. :param request_id: Is an optional argument. Is the ID of the AuthNRequest sent by this SP to the IdP. :type request_id: string :raises: OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND, when a POST with a SAMLResponse is not found """ self.__errors = [] self.__error_reason = None if 'post_data' in self.__request_data and 'SAMLResponse' in self.__request_data['post_data']: # AuthnResponse -- HTTP_POST Binding response = OneLogin_Saml2_Response(self.__settings, self.__request_data['post_data']['SAMLResponse']) self.__last_response = response.get_xml_document() if response.is_valid(self.__request_data, request_id): self.__attributes = response.get_attributes() self.__nameid = response.get_nameid() self.__nameid_format = response.get_nameid_format() self.__session_index = response.get_session_index() self.__session_expiration = response.get_session_not_on_or_after() self.__last_message_id = response.get_id() self.__last_assertion_id = response.get_assertion_id() self.__last_authn_contexts = response.get_authn_contexts() self.__authenticated = True self.__last_assertion_not_on_or_after = response.get_assertion_not_on_or_after() else: self.__errors.append('invalid_response') self.__error_reason = response.get_error() else: self.__errors.append('invalid_binding') raise OneLogin_Saml2_Error( 'SAML Response not found, Only supported HTTP_POST Binding', OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND )
[ "def", "process_response", "(", "self", ",", "request_id", "=", "None", ")", ":", "self", ".", "__errors", "=", "[", "]", "self", ".", "__error_reason", "=", "None", "if", "'post_data'", "in", "self", ".", "__request_data", "and", "'SAMLResponse'", "in", "...
Process the SAML Response sent by the IdP. :param request_id: Is an optional argument. Is the ID of the AuthNRequest sent by this SP to the IdP. :type request_id: string :raises: OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND, when a POST with a SAMLResponse is not found
[ "Process", "the", "SAML", "Response", "sent", "by", "the", "IdP", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/auth.py#L89-L127
train
216,725
onelogin/python3-saml
src/onelogin/saml2/auth.py
OneLogin_Saml2_Auth.redirect_to
def redirect_to(self, url=None, parameters={}): """ Redirects the user to the URL passed by parameter or to the URL that we defined in our SSO Request. :param url: The target URL to redirect the user :type url: string :param parameters: Extra parameters to be passed as part of the URL :type parameters: dict :returns: Redirection URL """ if url is None and 'RelayState' in self.__request_data['get_data']: url = self.__request_data['get_data']['RelayState'] return OneLogin_Saml2_Utils.redirect(url, parameters, request_data=self.__request_data)
python
def redirect_to(self, url=None, parameters={}): """ Redirects the user to the URL passed by parameter or to the URL that we defined in our SSO Request. :param url: The target URL to redirect the user :type url: string :param parameters: Extra parameters to be passed as part of the URL :type parameters: dict :returns: Redirection URL """ if url is None and 'RelayState' in self.__request_data['get_data']: url = self.__request_data['get_data']['RelayState'] return OneLogin_Saml2_Utils.redirect(url, parameters, request_data=self.__request_data)
[ "def", "redirect_to", "(", "self", ",", "url", "=", "None", ",", "parameters", "=", "{", "}", ")", ":", "if", "url", "is", "None", "and", "'RelayState'", "in", "self", ".", "__request_data", "[", "'get_data'", "]", ":", "url", "=", "self", ".", "__re...
Redirects the user to the URL passed by parameter or to the URL that we defined in our SSO Request. :param url: The target URL to redirect the user :type url: string :param parameters: Extra parameters to be passed as part of the URL :type parameters: dict :returns: Redirection URL
[ "Redirects", "the", "user", "to", "the", "URL", "passed", "by", "parameter", "or", "to", "the", "URL", "that", "we", "defined", "in", "our", "SSO", "Request", "." ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/auth.py#L197-L210
train
216,726
onelogin/python3-saml
src/onelogin/saml2/auth.py
OneLogin_Saml2_Auth.__build_sign_query
def __build_sign_query(saml_data, relay_state, algorithm, saml_type, lowercase_urlencoding=False): """ Build sign query :param saml_data: The Request data :type saml_data: str :param relay_state: The Relay State :type relay_state: str :param algorithm: The Signature Algorithm :type algorithm: str :param saml_type: The target URL the user should be redirected to :type saml_type: string SAMLRequest | SAMLResponse :param lowercase_urlencoding: lowercase or no :type lowercase_urlencoding: boolean """ sign_data = ['%s=%s' % (saml_type, OneLogin_Saml2_Utils.escape_url(saml_data, lowercase_urlencoding))] if relay_state is not None: sign_data.append('RelayState=%s' % OneLogin_Saml2_Utils.escape_url(relay_state, lowercase_urlencoding)) sign_data.append('SigAlg=%s' % OneLogin_Saml2_Utils.escape_url(algorithm, lowercase_urlencoding)) return '&'.join(sign_data)
python
def __build_sign_query(saml_data, relay_state, algorithm, saml_type, lowercase_urlencoding=False): """ Build sign query :param saml_data: The Request data :type saml_data: str :param relay_state: The Relay State :type relay_state: str :param algorithm: The Signature Algorithm :type algorithm: str :param saml_type: The target URL the user should be redirected to :type saml_type: string SAMLRequest | SAMLResponse :param lowercase_urlencoding: lowercase or no :type lowercase_urlencoding: boolean """ sign_data = ['%s=%s' % (saml_type, OneLogin_Saml2_Utils.escape_url(saml_data, lowercase_urlencoding))] if relay_state is not None: sign_data.append('RelayState=%s' % OneLogin_Saml2_Utils.escape_url(relay_state, lowercase_urlencoding)) sign_data.append('SigAlg=%s' % OneLogin_Saml2_Utils.escape_url(algorithm, lowercase_urlencoding)) return '&'.join(sign_data)
[ "def", "__build_sign_query", "(", "saml_data", ",", "relay_state", ",", "algorithm", ",", "saml_type", ",", "lowercase_urlencoding", "=", "False", ")", ":", "sign_data", "=", "[", "'%s=%s'", "%", "(", "saml_type", ",", "OneLogin_Saml2_Utils", ".", "escape_url", ...
Build sign query :param saml_data: The Request data :type saml_data: str :param relay_state: The Relay State :type relay_state: str :param algorithm: The Signature Algorithm :type algorithm: str :param saml_type: The target URL the user should be redirected to :type saml_type: string SAMLRequest | SAMLResponse :param lowercase_urlencoding: lowercase or no :type lowercase_urlencoding: boolean
[ "Build", "sign", "query" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/auth.py#L469-L492
train
216,727
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.check_status
def check_status(self): """ Check if the status of the response is success or not :raises: Exception. If the status is not success """ status = OneLogin_Saml2_Utils.get_status(self.document) code = status.get('code', None) if code and code != OneLogin_Saml2_Constants.STATUS_SUCCESS: splited_code = code.split(':') printable_code = splited_code.pop() status_exception_msg = 'The status code of the Response was not Success, was %s' % printable_code status_msg = status.get('msg', None) if status_msg: status_exception_msg += ' -> ' + status_msg raise OneLogin_Saml2_ValidationError( status_exception_msg, OneLogin_Saml2_ValidationError.STATUS_CODE_IS_NOT_SUCCESS )
python
def check_status(self): """ Check if the status of the response is success or not :raises: Exception. If the status is not success """ status = OneLogin_Saml2_Utils.get_status(self.document) code = status.get('code', None) if code and code != OneLogin_Saml2_Constants.STATUS_SUCCESS: splited_code = code.split(':') printable_code = splited_code.pop() status_exception_msg = 'The status code of the Response was not Success, was %s' % printable_code status_msg = status.get('msg', None) if status_msg: status_exception_msg += ' -> ' + status_msg raise OneLogin_Saml2_ValidationError( status_exception_msg, OneLogin_Saml2_ValidationError.STATUS_CODE_IS_NOT_SUCCESS )
[ "def", "check_status", "(", "self", ")", ":", "status", "=", "OneLogin_Saml2_Utils", ".", "get_status", "(", "self", ".", "document", ")", "code", "=", "status", ".", "get", "(", "'code'", ",", "None", ")", "if", "code", "and", "code", "!=", "OneLogin_Sa...
Check if the status of the response is success or not :raises: Exception. If the status is not success
[ "Check", "if", "the", "status", "of", "the", "response", "is", "success", "or", "not" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L330-L348
train
216,728
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.get_authn_contexts
def get_authn_contexts(self): """ Gets the authentication contexts :returns: The authentication classes for the SAML Response :rtype: list """ authn_context_nodes = self.__query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef') return [OneLogin_Saml2_XML.element_text(node) for node in authn_context_nodes]
python
def get_authn_contexts(self): """ Gets the authentication contexts :returns: The authentication classes for the SAML Response :rtype: list """ authn_context_nodes = self.__query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef') return [OneLogin_Saml2_XML.element_text(node) for node in authn_context_nodes]
[ "def", "get_authn_contexts", "(", "self", ")", ":", "authn_context_nodes", "=", "self", ".", "__query_assertion", "(", "'/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef'", ")", "return", "[", "OneLogin_Saml2_XML", ".", "element_text", "(", "node", ")", "f...
Gets the authentication contexts :returns: The authentication classes for the SAML Response :rtype: list
[ "Gets", "the", "authentication", "contexts" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L380-L388
train
216,729
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.get_nameid
def get_nameid(self): """ Gets the NameID provided by the SAML Response from the IdP :returns: NameID (value) :rtype: string|None """ nameid_value = None nameid_data = self.get_nameid_data() if nameid_data and 'Value' in nameid_data.keys(): nameid_value = nameid_data['Value'] return nameid_value
python
def get_nameid(self): """ Gets the NameID provided by the SAML Response from the IdP :returns: NameID (value) :rtype: string|None """ nameid_value = None nameid_data = self.get_nameid_data() if nameid_data and 'Value' in nameid_data.keys(): nameid_value = nameid_data['Value'] return nameid_value
[ "def", "get_nameid", "(", "self", ")", ":", "nameid_value", "=", "None", "nameid_data", "=", "self", ".", "get_nameid_data", "(", ")", "if", "nameid_data", "and", "'Value'", "in", "nameid_data", ".", "keys", "(", ")", ":", "nameid_value", "=", "nameid_data",...
Gets the NameID provided by the SAML Response from the IdP :returns: NameID (value) :rtype: string|None
[ "Gets", "the", "NameID", "provided", "by", "the", "SAML", "Response", "from", "the", "IdP" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L475-L486
train
216,730
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.get_nameid_format
def get_nameid_format(self): """ Gets the NameID Format provided by the SAML Response from the IdP :returns: NameID Format :rtype: string|None """ nameid_format = None nameid_data = self.get_nameid_data() if nameid_data and 'Format' in nameid_data.keys(): nameid_format = nameid_data['Format'] return nameid_format
python
def get_nameid_format(self): """ Gets the NameID Format provided by the SAML Response from the IdP :returns: NameID Format :rtype: string|None """ nameid_format = None nameid_data = self.get_nameid_data() if nameid_data and 'Format' in nameid_data.keys(): nameid_format = nameid_data['Format'] return nameid_format
[ "def", "get_nameid_format", "(", "self", ")", ":", "nameid_format", "=", "None", "nameid_data", "=", "self", ".", "get_nameid_data", "(", ")", "if", "nameid_data", "and", "'Format'", "in", "nameid_data", ".", "keys", "(", ")", ":", "nameid_format", "=", "nam...
Gets the NameID Format provided by the SAML Response from the IdP :returns: NameID Format :rtype: string|None
[ "Gets", "the", "NameID", "Format", "provided", "by", "the", "SAML", "Response", "from", "the", "IdP" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L488-L499
train
216,731
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.get_session_not_on_or_after
def get_session_not_on_or_after(self): """ Gets the SessionNotOnOrAfter from the AuthnStatement Could be used to set the local session expiration :returns: The SessionNotOnOrAfter value :rtype: time|None """ not_on_or_after = None authn_statement_nodes = self.__query_assertion('/saml:AuthnStatement[@SessionNotOnOrAfter]') if authn_statement_nodes: not_on_or_after = OneLogin_Saml2_Utils.parse_SAML_to_time(authn_statement_nodes[0].get('SessionNotOnOrAfter')) return not_on_or_after
python
def get_session_not_on_or_after(self): """ Gets the SessionNotOnOrAfter from the AuthnStatement Could be used to set the local session expiration :returns: The SessionNotOnOrAfter value :rtype: time|None """ not_on_or_after = None authn_statement_nodes = self.__query_assertion('/saml:AuthnStatement[@SessionNotOnOrAfter]') if authn_statement_nodes: not_on_or_after = OneLogin_Saml2_Utils.parse_SAML_to_time(authn_statement_nodes[0].get('SessionNotOnOrAfter')) return not_on_or_after
[ "def", "get_session_not_on_or_after", "(", "self", ")", ":", "not_on_or_after", "=", "None", "authn_statement_nodes", "=", "self", ".", "__query_assertion", "(", "'/saml:AuthnStatement[@SessionNotOnOrAfter]'", ")", "if", "authn_statement_nodes", ":", "not_on_or_after", "=",...
Gets the SessionNotOnOrAfter from the AuthnStatement Could be used to set the local session expiration :returns: The SessionNotOnOrAfter value :rtype: time|None
[ "Gets", "the", "SessionNotOnOrAfter", "from", "the", "AuthnStatement", "Could", "be", "used", "to", "set", "the", "local", "session", "expiration" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L501-L513
train
216,732
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.get_session_index
def get_session_index(self): """ Gets the SessionIndex from the AuthnStatement Could be used to be stored in the local session in order to be used in a future Logout Request that the SP could send to the SP, to set what specific session must be deleted :returns: The SessionIndex value :rtype: string|None """ session_index = None authn_statement_nodes = self.__query_assertion('/saml:AuthnStatement[@SessionIndex]') if authn_statement_nodes: session_index = authn_statement_nodes[0].get('SessionIndex') return session_index
python
def get_session_index(self): """ Gets the SessionIndex from the AuthnStatement Could be used to be stored in the local session in order to be used in a future Logout Request that the SP could send to the SP, to set what specific session must be deleted :returns: The SessionIndex value :rtype: string|None """ session_index = None authn_statement_nodes = self.__query_assertion('/saml:AuthnStatement[@SessionIndex]') if authn_statement_nodes: session_index = authn_statement_nodes[0].get('SessionIndex') return session_index
[ "def", "get_session_index", "(", "self", ")", ":", "session_index", "=", "None", "authn_statement_nodes", "=", "self", ".", "__query_assertion", "(", "'/saml:AuthnStatement[@SessionIndex]'", ")", "if", "authn_statement_nodes", ":", "session_index", "=", "authn_statement_n...
Gets the SessionIndex from the AuthnStatement Could be used to be stored in the local session in order to be used in a future Logout Request that the SP could send to the SP, to set what specific session must be deleted :returns: The SessionIndex value :rtype: string|None
[ "Gets", "the", "SessionIndex", "from", "the", "AuthnStatement", "Could", "be", "used", "to", "be", "stored", "in", "the", "local", "session", "in", "order", "to", "be", "used", "in", "a", "future", "Logout", "Request", "that", "the", "SP", "could", "send",...
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L521-L535
train
216,733
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.get_attributes
def get_attributes(self): """ Gets the Attributes from the AttributeStatement element. EncryptedAttributes are not supported """ attributes = {} attribute_nodes = self.__query_assertion('/saml:AttributeStatement/saml:Attribute') for attribute_node in attribute_nodes: attr_name = attribute_node.get('Name') if attr_name in attributes.keys(): raise OneLogin_Saml2_ValidationError( 'Found an Attribute element with duplicated Name', OneLogin_Saml2_ValidationError.DUPLICATED_ATTRIBUTE_NAME_FOUND ) values = [] for attr in attribute_node.iterchildren('{%s}AttributeValue' % OneLogin_Saml2_Constants.NSMAP['saml']): attr_text = OneLogin_Saml2_XML.element_text(attr) if attr_text: attr_text = attr_text.strip() if attr_text: values.append(attr_text) # Parse any nested NameID children for nameid in attr.iterchildren('{%s}NameID' % OneLogin_Saml2_Constants.NSMAP['saml']): values.append({ 'NameID': { 'Format': nameid.get('Format'), 'NameQualifier': nameid.get('NameQualifier'), 'value': nameid.text } }) attributes[attr_name] = values return attributes
python
def get_attributes(self): """ Gets the Attributes from the AttributeStatement element. EncryptedAttributes are not supported """ attributes = {} attribute_nodes = self.__query_assertion('/saml:AttributeStatement/saml:Attribute') for attribute_node in attribute_nodes: attr_name = attribute_node.get('Name') if attr_name in attributes.keys(): raise OneLogin_Saml2_ValidationError( 'Found an Attribute element with duplicated Name', OneLogin_Saml2_ValidationError.DUPLICATED_ATTRIBUTE_NAME_FOUND ) values = [] for attr in attribute_node.iterchildren('{%s}AttributeValue' % OneLogin_Saml2_Constants.NSMAP['saml']): attr_text = OneLogin_Saml2_XML.element_text(attr) if attr_text: attr_text = attr_text.strip() if attr_text: values.append(attr_text) # Parse any nested NameID children for nameid in attr.iterchildren('{%s}NameID' % OneLogin_Saml2_Constants.NSMAP['saml']): values.append({ 'NameID': { 'Format': nameid.get('Format'), 'NameQualifier': nameid.get('NameQualifier'), 'value': nameid.text } }) attributes[attr_name] = values return attributes
[ "def", "get_attributes", "(", "self", ")", ":", "attributes", "=", "{", "}", "attribute_nodes", "=", "self", ".", "__query_assertion", "(", "'/saml:AttributeStatement/saml:Attribute'", ")", "for", "attribute_node", "in", "attribute_nodes", ":", "attr_name", "=", "at...
Gets the Attributes from the AttributeStatement element. EncryptedAttributes are not supported
[ "Gets", "the", "Attributes", "from", "the", "AttributeStatement", "element", ".", "EncryptedAttributes", "are", "not", "supported" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L537-L570
train
216,734
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.validate_timestamps
def validate_timestamps(self): """ Verifies that the document is valid according to Conditions Element :returns: True if the condition is valid, False otherwise :rtype: bool """ conditions_nodes = self.__query_assertion('/saml:Conditions') for conditions_node in conditions_nodes: nb_attr = conditions_node.get('NotBefore') nooa_attr = conditions_node.get('NotOnOrAfter') if nb_attr and OneLogin_Saml2_Utils.parse_SAML_to_time(nb_attr) > OneLogin_Saml2_Utils.now() + OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT: raise OneLogin_Saml2_ValidationError( 'Could not validate timestamp: not yet valid. Check system clock.', OneLogin_Saml2_ValidationError.ASSERTION_TOO_EARLY ) if nooa_attr and OneLogin_Saml2_Utils.parse_SAML_to_time(nooa_attr) + OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT <= OneLogin_Saml2_Utils.now(): raise OneLogin_Saml2_ValidationError( 'Could not validate timestamp: expired. Check system clock.', OneLogin_Saml2_ValidationError.ASSERTION_EXPIRED ) return True
python
def validate_timestamps(self): """ Verifies that the document is valid according to Conditions Element :returns: True if the condition is valid, False otherwise :rtype: bool """ conditions_nodes = self.__query_assertion('/saml:Conditions') for conditions_node in conditions_nodes: nb_attr = conditions_node.get('NotBefore') nooa_attr = conditions_node.get('NotOnOrAfter') if nb_attr and OneLogin_Saml2_Utils.parse_SAML_to_time(nb_attr) > OneLogin_Saml2_Utils.now() + OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT: raise OneLogin_Saml2_ValidationError( 'Could not validate timestamp: not yet valid. Check system clock.', OneLogin_Saml2_ValidationError.ASSERTION_TOO_EARLY ) if nooa_attr and OneLogin_Saml2_Utils.parse_SAML_to_time(nooa_attr) + OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT <= OneLogin_Saml2_Utils.now(): raise OneLogin_Saml2_ValidationError( 'Could not validate timestamp: expired. Check system clock.', OneLogin_Saml2_ValidationError.ASSERTION_EXPIRED ) return True
[ "def", "validate_timestamps", "(", "self", ")", ":", "conditions_nodes", "=", "self", ".", "__query_assertion", "(", "'/saml:Conditions'", ")", "for", "conditions_node", "in", "conditions_nodes", ":", "nb_attr", "=", "conditions_node", ".", "get", "(", "'NotBefore'"...
Verifies that the document is valid according to Conditions Element :returns: True if the condition is valid, False otherwise :rtype: bool
[ "Verifies", "that", "the", "document", "is", "valid", "according", "to", "Conditions", "Element" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L701-L723
train
216,735
onelogin/python3-saml
src/onelogin/saml2/response.py
OneLogin_Saml2_Response.__query_assertion
def __query_assertion(self, xpath_expr): """ Extracts nodes that match the query from the Assertion :param xpath_expr: Xpath Expresion :type xpath_expr: String :returns: The queried nodes :rtype: list """ assertion_expr = '/saml:Assertion' signature_expr = '/ds:Signature/ds:SignedInfo/ds:Reference' signed_assertion_query = '/samlp:Response' + assertion_expr + signature_expr assertion_reference_nodes = self.__query(signed_assertion_query) tagid = None if not assertion_reference_nodes: # Check if the message is signed signed_message_query = '/samlp:Response' + signature_expr message_reference_nodes = self.__query(signed_message_query) if message_reference_nodes: message_id = message_reference_nodes[0].get('URI') final_query = "/samlp:Response[@ID=$tagid]/" tagid = message_id[1:] else: final_query = "/samlp:Response" final_query += assertion_expr else: assertion_id = assertion_reference_nodes[0].get('URI') final_query = '/samlp:Response' + assertion_expr + "[@ID=$tagid]" tagid = assertion_id[1:] final_query += xpath_expr return self.__query(final_query, tagid)
python
def __query_assertion(self, xpath_expr): """ Extracts nodes that match the query from the Assertion :param xpath_expr: Xpath Expresion :type xpath_expr: String :returns: The queried nodes :rtype: list """ assertion_expr = '/saml:Assertion' signature_expr = '/ds:Signature/ds:SignedInfo/ds:Reference' signed_assertion_query = '/samlp:Response' + assertion_expr + signature_expr assertion_reference_nodes = self.__query(signed_assertion_query) tagid = None if not assertion_reference_nodes: # Check if the message is signed signed_message_query = '/samlp:Response' + signature_expr message_reference_nodes = self.__query(signed_message_query) if message_reference_nodes: message_id = message_reference_nodes[0].get('URI') final_query = "/samlp:Response[@ID=$tagid]/" tagid = message_id[1:] else: final_query = "/samlp:Response" final_query += assertion_expr else: assertion_id = assertion_reference_nodes[0].get('URI') final_query = '/samlp:Response' + assertion_expr + "[@ID=$tagid]" tagid = assertion_id[1:] final_query += xpath_expr return self.__query(final_query, tagid)
[ "def", "__query_assertion", "(", "self", ",", "xpath_expr", ")", ":", "assertion_expr", "=", "'/saml:Assertion'", "signature_expr", "=", "'/ds:Signature/ds:SignedInfo/ds:Reference'", "signed_assertion_query", "=", "'/samlp:Response'", "+", "assertion_expr", "+", "signature_ex...
Extracts nodes that match the query from the Assertion :param xpath_expr: Xpath Expresion :type xpath_expr: String :returns: The queried nodes :rtype: list
[ "Extracts", "nodes", "that", "match", "the", "query", "from", "the", "Assertion" ]
064b7275fba1e5f39a9116ba1cdcc5d01fc34daa
https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L725-L758
train
216,736
automl/HpBandSter
hpbandster/optimizers/kde/mvkde.py
MultivariateKDE.pdf
def pdf(self, x_test): """ Computes the probability density function at all x_test """ N,D = self.data.shape x_test = np.asfortranarray(x_test) x_test = x_test.reshape([-1, D]) pdfs = self._individual_pdfs(x_test) #import pdb; pdb.set_trace() # combine values based on fully_dimensional! if self.fully_dimensional: # first the product of the individual pdfs for each point in the data across dimensions and then the average (factorized kernel) pdfs = np.sum(np.prod(pdfs, axis=-1)*self.weights[None, :], axis=-1) else: # first the average over the 1d pdfs and the the product over dimensions (TPE like factorization of the pdf) pdfs = np.prod(np.sum(pdfs*self.weights[None,:,None], axis=-2), axis=-1) return(pdfs)
python
def pdf(self, x_test): """ Computes the probability density function at all x_test """ N,D = self.data.shape x_test = np.asfortranarray(x_test) x_test = x_test.reshape([-1, D]) pdfs = self._individual_pdfs(x_test) #import pdb; pdb.set_trace() # combine values based on fully_dimensional! if self.fully_dimensional: # first the product of the individual pdfs for each point in the data across dimensions and then the average (factorized kernel) pdfs = np.sum(np.prod(pdfs, axis=-1)*self.weights[None, :], axis=-1) else: # first the average over the 1d pdfs and the the product over dimensions (TPE like factorization of the pdf) pdfs = np.prod(np.sum(pdfs*self.weights[None,:,None], axis=-2), axis=-1) return(pdfs)
[ "def", "pdf", "(", "self", ",", "x_test", ")", ":", "N", ",", "D", "=", "self", ".", "data", ".", "shape", "x_test", "=", "np", ".", "asfortranarray", "(", "x_test", ")", "x_test", "=", "x_test", ".", "reshape", "(", "[", "-", "1", ",", "D", "]...
Computes the probability density function at all x_test
[ "Computes", "the", "probability", "density", "function", "at", "all", "x_test" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/kde/mvkde.py#L172-L189
train
216,737
automl/HpBandSter
hpbandster/examples/plot_example_7_interactive_plot.py
realtime_learning_curves
def realtime_learning_curves(runs): """ example how to extract a different kind of learning curve. The x values are now the time the runs finished, not the budget anymore. We no longer plot the validation loss on the y axis, but now the test accuracy. This is just to show how to get different information into the interactive plot. """ sr = sorted(runs, key=lambda r: r.budget) lc = list(filter(lambda t: not t[1] is None, [(r.time_stamps['finished'], r.info['test accuracy']) for r in sr])) return([lc,])
python
def realtime_learning_curves(runs): """ example how to extract a different kind of learning curve. The x values are now the time the runs finished, not the budget anymore. We no longer plot the validation loss on the y axis, but now the test accuracy. This is just to show how to get different information into the interactive plot. """ sr = sorted(runs, key=lambda r: r.budget) lc = list(filter(lambda t: not t[1] is None, [(r.time_stamps['finished'], r.info['test accuracy']) for r in sr])) return([lc,])
[ "def", "realtime_learning_curves", "(", "runs", ")", ":", "sr", "=", "sorted", "(", "runs", ",", "key", "=", "lambda", "r", ":", "r", ".", "budget", ")", "lc", "=", "list", "(", "filter", "(", "lambda", "t", ":", "not", "t", "[", "1", "]", "is", ...
example how to extract a different kind of learning curve. The x values are now the time the runs finished, not the budget anymore. We no longer plot the validation loss on the y axis, but now the test accuracy. This is just to show how to get different information into the interactive plot.
[ "example", "how", "to", "extract", "a", "different", "kind", "of", "learning", "curve", ".", "The", "x", "values", "are", "now", "the", "time", "the", "runs", "finished", "not", "the", "budget", "anymore", ".", "We", "no", "longer", "plot", "the", "valid...
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/examples/plot_example_7_interactive_plot.py#L39-L51
train
216,738
automl/HpBandSter
hpbandster/core/worker.py
Worker.load_nameserver_credentials
def load_nameserver_credentials(self, working_directory, num_tries=60, interval=1): """ loads the nameserver credentials in cases where master and workers share a filesystem Parameters ---------- working_directory: str the working directory for the HPB run (see master) num_tries: int number of attempts to find the file (default 60) interval: float waiting period between the attempts """ fn = os.path.join(working_directory, 'HPB_run_%s_pyro.pkl'%self.run_id) for i in range(num_tries): try: with open(fn, 'rb') as fh: self.nameserver, self.nameserver_port = pickle.load(fh) return except FileNotFoundError: self.logger.warning('config file %s not found (trail %i/%i)'%(fn, i+1, num_tries)) time.sleep(interval) except: raise raise RuntimeError("Could not find the nameserver information, aborting!")
python
def load_nameserver_credentials(self, working_directory, num_tries=60, interval=1): """ loads the nameserver credentials in cases where master and workers share a filesystem Parameters ---------- working_directory: str the working directory for the HPB run (see master) num_tries: int number of attempts to find the file (default 60) interval: float waiting period between the attempts """ fn = os.path.join(working_directory, 'HPB_run_%s_pyro.pkl'%self.run_id) for i in range(num_tries): try: with open(fn, 'rb') as fh: self.nameserver, self.nameserver_port = pickle.load(fh) return except FileNotFoundError: self.logger.warning('config file %s not found (trail %i/%i)'%(fn, i+1, num_tries)) time.sleep(interval) except: raise raise RuntimeError("Could not find the nameserver information, aborting!")
[ "def", "load_nameserver_credentials", "(", "self", ",", "working_directory", ",", "num_tries", "=", "60", ",", "interval", "=", "1", ")", ":", "fn", "=", "os", ".", "path", ".", "join", "(", "working_directory", ",", "'HPB_run_%s_pyro.pkl'", "%", "self", "."...
loads the nameserver credentials in cases where master and workers share a filesystem Parameters ---------- working_directory: str the working directory for the HPB run (see master) num_tries: int number of attempts to find the file (default 60) interval: float waiting period between the attempts
[ "loads", "the", "nameserver", "credentials", "in", "cases", "where", "master", "and", "workers", "share", "a", "filesystem" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/worker.py#L70-L95
train
216,739
automl/HpBandSter
hpbandster/core/master.py
Master.wait_for_workers
def wait_for_workers(self, min_n_workers=1): """ helper function to hold execution until some workers are active Parameters ---------- min_n_workers: int minimum number of workers present before the run starts """ self.logger.debug('wait_for_workers trying to get the condition') with self.thread_cond: while (self.dispatcher.number_of_workers() < min_n_workers): self.logger.debug('HBMASTER: only %i worker(s) available, waiting for at least %i.'%(self.dispatcher.number_of_workers(), min_n_workers)) self.thread_cond.wait(1) self.dispatcher.trigger_discover_worker() self.logger.debug('Enough workers to start this run!')
python
def wait_for_workers(self, min_n_workers=1): """ helper function to hold execution until some workers are active Parameters ---------- min_n_workers: int minimum number of workers present before the run starts """ self.logger.debug('wait_for_workers trying to get the condition') with self.thread_cond: while (self.dispatcher.number_of_workers() < min_n_workers): self.logger.debug('HBMASTER: only %i worker(s) available, waiting for at least %i.'%(self.dispatcher.number_of_workers(), min_n_workers)) self.thread_cond.wait(1) self.dispatcher.trigger_discover_worker() self.logger.debug('Enough workers to start this run!')
[ "def", "wait_for_workers", "(", "self", ",", "min_n_workers", "=", "1", ")", ":", "self", ".", "logger", ".", "debug", "(", "'wait_for_workers trying to get the condition'", ")", "with", "self", ".", "thread_cond", ":", "while", "(", "self", ".", "dispatcher", ...
helper function to hold execution until some workers are active Parameters ---------- min_n_workers: int minimum number of workers present before the run starts
[ "helper", "function", "to", "hold", "execution", "until", "some", "workers", "are", "active" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L135-L152
train
216,740
automl/HpBandSter
hpbandster/core/master.py
Master.run
def run(self, n_iterations=1, min_n_workers=1, iteration_kwargs = {},): """ run n_iterations of SuccessiveHalving Parameters ---------- n_iterations: int number of iterations to be performed in this run min_n_workers: int minimum number of workers before starting the run """ self.wait_for_workers(min_n_workers) iteration_kwargs.update({'result_logger': self.result_logger}) if self.time_ref is None: self.time_ref = time.time() self.config['time_ref'] = self.time_ref self.logger.info('HBMASTER: starting run at %s'%(str(self.time_ref))) self.thread_cond.acquire() while True: self._queue_wait() next_run = None # find a new run to schedule for i in self.active_iterations(): next_run = self.iterations[i].get_next_run() if not next_run is None: break if not next_run is None: self.logger.debug('HBMASTER: schedule new run for iteration %i'%i) self._submit_job(*next_run) continue else: if n_iterations > 0: #we might be able to start the next iteration self.iterations.append(self.get_next_iteration(len(self.iterations), iteration_kwargs)) n_iterations -= 1 continue # at this point there is no imediate run that can be scheduled, # so wait for some job to finish if there are active iterations if self.active_iterations(): self.thread_cond.wait() else: break self.thread_cond.release() for i in self.warmstart_iteration: i.fix_timestamps(self.time_ref) ws_data = [i.data for i in self.warmstart_iteration] return Result([copy.deepcopy(i.data) for i in self.iterations] + ws_data, self.config)
python
def run(self, n_iterations=1, min_n_workers=1, iteration_kwargs = {},): """ run n_iterations of SuccessiveHalving Parameters ---------- n_iterations: int number of iterations to be performed in this run min_n_workers: int minimum number of workers before starting the run """ self.wait_for_workers(min_n_workers) iteration_kwargs.update({'result_logger': self.result_logger}) if self.time_ref is None: self.time_ref = time.time() self.config['time_ref'] = self.time_ref self.logger.info('HBMASTER: starting run at %s'%(str(self.time_ref))) self.thread_cond.acquire() while True: self._queue_wait() next_run = None # find a new run to schedule for i in self.active_iterations(): next_run = self.iterations[i].get_next_run() if not next_run is None: break if not next_run is None: self.logger.debug('HBMASTER: schedule new run for iteration %i'%i) self._submit_job(*next_run) continue else: if n_iterations > 0: #we might be able to start the next iteration self.iterations.append(self.get_next_iteration(len(self.iterations), iteration_kwargs)) n_iterations -= 1 continue # at this point there is no imediate run that can be scheduled, # so wait for some job to finish if there are active iterations if self.active_iterations(): self.thread_cond.wait() else: break self.thread_cond.release() for i in self.warmstart_iteration: i.fix_timestamps(self.time_ref) ws_data = [i.data for i in self.warmstart_iteration] return Result([copy.deepcopy(i.data) for i in self.iterations] + ws_data, self.config)
[ "def", "run", "(", "self", ",", "n_iterations", "=", "1", ",", "min_n_workers", "=", "1", ",", "iteration_kwargs", "=", "{", "}", ",", ")", ":", "self", ".", "wait_for_workers", "(", "min_n_workers", ")", "iteration_kwargs", ".", "update", "(", "{", "'re...
run n_iterations of SuccessiveHalving Parameters ---------- n_iterations: int number of iterations to be performed in this run min_n_workers: int minimum number of workers before starting the run
[ "run", "n_iterations", "of", "SuccessiveHalving" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L176-L233
train
216,741
automl/HpBandSter
hpbandster/core/master.py
Master.job_callback
def job_callback(self, job): """ method to be called when a job has finished this will do some book keeping and call the user defined new_result_callback if one was specified """ self.logger.debug('job_callback for %s started'%str(job.id)) with self.thread_cond: self.logger.debug('job_callback for %s got condition'%str(job.id)) self.num_running_jobs -= 1 if not self.result_logger is None: self.result_logger(job) self.iterations[job.id[0]].register_result(job) self.config_generator.new_result(job) if self.num_running_jobs <= self.job_queue_sizes[0]: self.logger.debug("HBMASTER: Trying to run another job!") self.thread_cond.notify() self.logger.debug('job_callback for %s finished'%str(job.id))
python
def job_callback(self, job): """ method to be called when a job has finished this will do some book keeping and call the user defined new_result_callback if one was specified """ self.logger.debug('job_callback for %s started'%str(job.id)) with self.thread_cond: self.logger.debug('job_callback for %s got condition'%str(job.id)) self.num_running_jobs -= 1 if not self.result_logger is None: self.result_logger(job) self.iterations[job.id[0]].register_result(job) self.config_generator.new_result(job) if self.num_running_jobs <= self.job_queue_sizes[0]: self.logger.debug("HBMASTER: Trying to run another job!") self.thread_cond.notify() self.logger.debug('job_callback for %s finished'%str(job.id))
[ "def", "job_callback", "(", "self", ",", "job", ")", ":", "self", ".", "logger", ".", "debug", "(", "'job_callback for %s started'", "%", "str", "(", "job", ".", "id", ")", ")", "with", "self", ".", "thread_cond", ":", "self", ".", "logger", ".", "debu...
method to be called when a job has finished this will do some book keeping and call the user defined new_result_callback if one was specified
[ "method", "to", "be", "called", "when", "a", "job", "has", "finished" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L248-L269
train
216,742
automl/HpBandSter
hpbandster/core/master.py
Master._submit_job
def _submit_job(self, config_id, config, budget): """ hidden function to submit a new job to the dispatcher This function handles the actual submission in a (hopefully) thread save way """ self.logger.debug('HBMASTER: trying submitting job %s to dispatcher'%str(config_id)) with self.thread_cond: self.logger.debug('HBMASTER: submitting job %s to dispatcher'%str(config_id)) self.dispatcher.submit_job(config_id, config=config, budget=budget, working_directory=self.working_directory) self.num_running_jobs += 1 #shouldn't the next line be executed while holding the condition? self.logger.debug("HBMASTER: job %s submitted to dispatcher"%str(config_id))
python
def _submit_job(self, config_id, config, budget): """ hidden function to submit a new job to the dispatcher This function handles the actual submission in a (hopefully) thread save way """ self.logger.debug('HBMASTER: trying submitting job %s to dispatcher'%str(config_id)) with self.thread_cond: self.logger.debug('HBMASTER: submitting job %s to dispatcher'%str(config_id)) self.dispatcher.submit_job(config_id, config=config, budget=budget, working_directory=self.working_directory) self.num_running_jobs += 1 #shouldn't the next line be executed while holding the condition? self.logger.debug("HBMASTER: job %s submitted to dispatcher"%str(config_id))
[ "def", "_submit_job", "(", "self", ",", "config_id", ",", "config", ",", "budget", ")", ":", "self", ".", "logger", ".", "debug", "(", "'HBMASTER: trying submitting job %s to dispatcher'", "%", "str", "(", "config_id", ")", ")", "with", "self", ".", "thread_co...
hidden function to submit a new job to the dispatcher This function handles the actual submission in a (hopefully) thread save way
[ "hidden", "function", "to", "submit", "a", "new", "job", "to", "the", "dispatcher" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/master.py#L281-L295
train
216,743
automl/HpBandSter
hpbandster/optimizers/learning_curve_models/lcnet.py
LCNetWrapper.fit
def fit(self, times, losses, configs=None): """ function to train the model on the observed data Parameters: ----------- times: list list of numpy arrays of the timesteps for each curve losses: list list of numpy arrays of the loss (the actual learning curve) configs: list or None list of the configurations for each sample. Each element has to be a numpy array. Set to None, if no configuration information is available. """ assert np.all(times > 0) and np.all(times <= self.max_num_epochs) train = None targets = None for i in range(len(configs)): t_idx = times[i] / self.max_num_epochs x = np.repeat(np.array(configs[i])[None, :], t_idx.shape[0], axis=0) x = np.concatenate((x, t_idx[:, None]), axis=1) # LCNet assumes increasing curves, if we feed in losses here we have to flip the curves lc = [1 - l for l in losses[i]] if train is None: train = x targets = lc else: train = np.concatenate((train, x), 0) targets = np.concatenate((targets, lc), 0) self.model.train(train, targets)
python
def fit(self, times, losses, configs=None): """ function to train the model on the observed data Parameters: ----------- times: list list of numpy arrays of the timesteps for each curve losses: list list of numpy arrays of the loss (the actual learning curve) configs: list or None list of the configurations for each sample. Each element has to be a numpy array. Set to None, if no configuration information is available. """ assert np.all(times > 0) and np.all(times <= self.max_num_epochs) train = None targets = None for i in range(len(configs)): t_idx = times[i] / self.max_num_epochs x = np.repeat(np.array(configs[i])[None, :], t_idx.shape[0], axis=0) x = np.concatenate((x, t_idx[:, None]), axis=1) # LCNet assumes increasing curves, if we feed in losses here we have to flip the curves lc = [1 - l for l in losses[i]] if train is None: train = x targets = lc else: train = np.concatenate((train, x), 0) targets = np.concatenate((targets, lc), 0) self.model.train(train, targets)
[ "def", "fit", "(", "self", ",", "times", ",", "losses", ",", "configs", "=", "None", ")", ":", "assert", "np", ".", "all", "(", "times", ">", "0", ")", "and", "np", ".", "all", "(", "times", "<=", "self", ".", "max_num_epochs", ")", "train", "=",...
function to train the model on the observed data Parameters: ----------- times: list list of numpy arrays of the timesteps for each curve losses: list list of numpy arrays of the loss (the actual learning curve) configs: list or None list of the configurations for each sample. Each element has to be a numpy array. Set to None, if no configuration information is available.
[ "function", "to", "train", "the", "model", "on", "the", "observed", "data" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/learning_curve_models/lcnet.py#L24-L63
train
216,744
automl/HpBandSter
hpbandster/optimizers/learning_curve_models/lcnet.py
LCNetWrapper.predict_unseen
def predict_unseen(self, times, config): """ predict the loss of an unseen configuration Parameters: ----------- times: numpy array times where to predict the loss config: numpy array the numerical representation of the config Returns: -------- mean and variance prediction at input times for the given config """ assert np.all(times > 0) and np.all(times <= self.max_num_epochs) x = np.array(config)[None, :] idx = times / self.max_num_epochs x = np.repeat(x, idx.shape[0], axis=0) x = np.concatenate((x, idx[:, None]), axis=1) mean, var = self.model.predict(x) return 1 - mean, var
python
def predict_unseen(self, times, config): """ predict the loss of an unseen configuration Parameters: ----------- times: numpy array times where to predict the loss config: numpy array the numerical representation of the config Returns: -------- mean and variance prediction at input times for the given config """ assert np.all(times > 0) and np.all(times <= self.max_num_epochs) x = np.array(config)[None, :] idx = times / self.max_num_epochs x = np.repeat(x, idx.shape[0], axis=0) x = np.concatenate((x, idx[:, None]), axis=1) mean, var = self.model.predict(x) return 1 - mean, var
[ "def", "predict_unseen", "(", "self", ",", "times", ",", "config", ")", ":", "assert", "np", ".", "all", "(", "times", ">", "0", ")", "and", "np", ".", "all", "(", "times", "<=", "self", ".", "max_num_epochs", ")", "x", "=", "np", ".", "array", "...
predict the loss of an unseen configuration Parameters: ----------- times: numpy array times where to predict the loss config: numpy array the numerical representation of the config Returns: -------- mean and variance prediction at input times for the given config
[ "predict", "the", "loss", "of", "an", "unseen", "configuration" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/learning_curve_models/lcnet.py#L65-L93
train
216,745
automl/HpBandSter
hpbandster/optimizers/learning_curve_models/lcnet.py
LCNetWrapper.extend_partial
def extend_partial(self, times, obs_times, obs_losses, config=None): """ extends a partially observed curve Parameters: ----------- times: numpy array times where to predict the loss obs_times: numpy array times where the curve has already been observed obs_losses: numpy array corresponding observed losses config: numpy array numerical reperesentation of the config; None if no config information is available Returns: -------- mean and variance prediction at input times """ return self.predict_unseen(times, config)
python
def extend_partial(self, times, obs_times, obs_losses, config=None): """ extends a partially observed curve Parameters: ----------- times: numpy array times where to predict the loss obs_times: numpy array times where the curve has already been observed obs_losses: numpy array corresponding observed losses config: numpy array numerical reperesentation of the config; None if no config information is available Returns: -------- mean and variance prediction at input times """ return self.predict_unseen(times, config)
[ "def", "extend_partial", "(", "self", ",", "times", ",", "obs_times", ",", "obs_losses", ",", "config", "=", "None", ")", ":", "return", "self", ".", "predict_unseen", "(", "times", ",", "config", ")" ]
extends a partially observed curve Parameters: ----------- times: numpy array times where to predict the loss obs_times: numpy array times where the curve has already been observed obs_losses: numpy array corresponding observed losses config: numpy array numerical reperesentation of the config; None if no config information is available Returns: -------- mean and variance prediction at input times
[ "extends", "a", "partially", "observed", "curve" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/learning_curve_models/lcnet.py#L95-L119
train
216,746
automl/HpBandSter
hpbandster/core/base_config_generator.py
base_config_generator.new_result
def new_result(self, job, update_model=True): """ registers finished runs Every time a run has finished, this function should be called to register it with the result logger. If overwritten, make sure to call this method from the base class to ensure proper logging. Parameters ---------- job: instance of hpbandster.distributed.dispatcher.Job contains all necessary information about the job update_model: boolean determines whether a model inside the config_generator should be updated """ if not job.exception is None: self.logger.warning("job {} failed with exception\n{}".format(job.id, job.exception))
python
def new_result(self, job, update_model=True): """ registers finished runs Every time a run has finished, this function should be called to register it with the result logger. If overwritten, make sure to call this method from the base class to ensure proper logging. Parameters ---------- job: instance of hpbandster.distributed.dispatcher.Job contains all necessary information about the job update_model: boolean determines whether a model inside the config_generator should be updated """ if not job.exception is None: self.logger.warning("job {} failed with exception\n{}".format(job.id, job.exception))
[ "def", "new_result", "(", "self", ",", "job", ",", "update_model", "=", "True", ")", ":", "if", "not", "job", ".", "exception", "is", "None", ":", "self", ".", "logger", ".", "warning", "(", "\"job {} failed with exception\\n{}\"", ".", "format", "(", "job...
registers finished runs Every time a run has finished, this function should be called to register it with the result logger. If overwritten, make sure to call this method from the base class to ensure proper logging. Parameters ---------- job: instance of hpbandster.distributed.dispatcher.Job contains all necessary information about the job update_model: boolean determines whether a model inside the config_generator should be updated
[ "registers", "finished", "runs" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_config_generator.py#L47-L65
train
216,747
automl/HpBandSter
hpbandster/optimizers/learning_curve_models/arif.py
ARIF.invert_differencing
def invert_differencing(self, initial_part, differenced_rest, order=None): """ function to invert the differencing """ if order is None: order = self.diff_order # compute the differenced values of the initial part: starting_points = [ self.apply_differencing(initial_part, order=order)[-1] for order in range(self.diff_order)] actual_predictions = differenced_rest import pdb pdb.set_trace() for s in starting_points[::-1]: actual_predictions = np.cumsum(np.hstack([s, actual_predictions]))[1:] return(actual_predictions)
python
def invert_differencing(self, initial_part, differenced_rest, order=None): """ function to invert the differencing """ if order is None: order = self.diff_order # compute the differenced values of the initial part: starting_points = [ self.apply_differencing(initial_part, order=order)[-1] for order in range(self.diff_order)] actual_predictions = differenced_rest import pdb pdb.set_trace() for s in starting_points[::-1]: actual_predictions = np.cumsum(np.hstack([s, actual_predictions]))[1:] return(actual_predictions)
[ "def", "invert_differencing", "(", "self", ",", "initial_part", ",", "differenced_rest", ",", "order", "=", "None", ")", ":", "if", "order", "is", "None", ":", "order", "=", "self", ".", "diff_order", "# compute the differenced values of the initial part:", "startin...
function to invert the differencing
[ "function", "to", "invert", "the", "differencing" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/learning_curve_models/arif.py#L38-L54
train
216,748
automl/HpBandSter
hpbandster/core/nameserver.py
nic_name_to_host
def nic_name_to_host(nic_name): """ helper function to translate the name of a network card into a valid host name""" from netifaces import ifaddresses, AF_INET host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr'] return(host)
python
def nic_name_to_host(nic_name): """ helper function to translate the name of a network card into a valid host name""" from netifaces import ifaddresses, AF_INET host = ifaddresses(nic_name).setdefault(AF_INET, [{'addr': 'No IP addr'}] )[0]['addr'] return(host)
[ "def", "nic_name_to_host", "(", "nic_name", ")", ":", "from", "netifaces", "import", "ifaddresses", ",", "AF_INET", "host", "=", "ifaddresses", "(", "nic_name", ")", ".", "setdefault", "(", "AF_INET", ",", "[", "{", "'addr'", ":", "'No IP addr'", "}", "]", ...
helper function to translate the name of a network card into a valid host name
[ "helper", "function", "to", "translate", "the", "name", "of", "a", "network", "card", "into", "a", "valid", "host", "name" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/nameserver.py#L9-L13
train
216,749
automl/HpBandSter
hpbandster/core/base_iteration.py
BaseIteration.register_result
def register_result(self, job, skip_sanity_checks=False): """ function to register the result of a job This function is called from HB_master, don't call this from your script. """ if self.is_finished: raise RuntimeError("This HB iteration is finished, you can't register more results!") config_id = job.id config = job.kwargs['config'] budget = job.kwargs['budget'] timestamps = job.timestamps result = job.result exception = job.exception d = self.data[config_id] if not skip_sanity_checks: assert d.config == config, 'Configurations differ!' assert d.status == 'RUNNING', "Configuration wasn't scheduled for a run." assert d.budget == budget, 'Budgets differ (%f != %f)!'%(self.data[config_id]['budget'], budget) d.time_stamps[budget] = timestamps d.results[budget] = result if (not job.result is None) and np.isfinite(result['loss']): d.status = 'REVIEW' else: d.status = 'CRASHED' d.exceptions[budget] = exception self.num_running -= 1
python
def register_result(self, job, skip_sanity_checks=False): """ function to register the result of a job This function is called from HB_master, don't call this from your script. """ if self.is_finished: raise RuntimeError("This HB iteration is finished, you can't register more results!") config_id = job.id config = job.kwargs['config'] budget = job.kwargs['budget'] timestamps = job.timestamps result = job.result exception = job.exception d = self.data[config_id] if not skip_sanity_checks: assert d.config == config, 'Configurations differ!' assert d.status == 'RUNNING', "Configuration wasn't scheduled for a run." assert d.budget == budget, 'Budgets differ (%f != %f)!'%(self.data[config_id]['budget'], budget) d.time_stamps[budget] = timestamps d.results[budget] = result if (not job.result is None) and np.isfinite(result['loss']): d.status = 'REVIEW' else: d.status = 'CRASHED' d.exceptions[budget] = exception self.num_running -= 1
[ "def", "register_result", "(", "self", ",", "job", ",", "skip_sanity_checks", "=", "False", ")", ":", "if", "self", ".", "is_finished", ":", "raise", "RuntimeError", "(", "\"This HB iteration is finished, you can't register more results!\"", ")", "config_id", "=", "jo...
function to register the result of a job This function is called from HB_master, don't call this from your script.
[ "function", "to", "register", "the", "result", "of", "a", "job" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_iteration.py#L105-L139
train
216,750
automl/HpBandSter
hpbandster/core/base_iteration.py
BaseIteration.get_next_run
def get_next_run(self): """ function to return the next configuration and budget to run. This function is called from HB_master, don't call this from your script. It returns None if this run of SH is finished or there are pending jobs that need to finish to progress to the next stage. If there are empty slots to be filled in the current SH stage (which never happens in the original SH version), a new configuration will be sampled and scheduled to run next. """ if self.is_finished: return(None) for k,v in self.data.items(): if v.status == 'QUEUED': assert v.budget == self.budgets[self.stage], 'Configuration budget does not align with current stage!' v.status = 'RUNNING' self.num_running += 1 return(k, v.config, v.budget) # check if there are still slots to fill in the current stage and return that if (self.actual_num_configs[self.stage] < self.num_configs[self.stage]): self.add_configuration() return(self.get_next_run()) if self.num_running == 0: # at this point a stage is completed self.process_results() return(self.get_next_run()) return(None)
python
def get_next_run(self): """ function to return the next configuration and budget to run. This function is called from HB_master, don't call this from your script. It returns None if this run of SH is finished or there are pending jobs that need to finish to progress to the next stage. If there are empty slots to be filled in the current SH stage (which never happens in the original SH version), a new configuration will be sampled and scheduled to run next. """ if self.is_finished: return(None) for k,v in self.data.items(): if v.status == 'QUEUED': assert v.budget == self.budgets[self.stage], 'Configuration budget does not align with current stage!' v.status = 'RUNNING' self.num_running += 1 return(k, v.config, v.budget) # check if there are still slots to fill in the current stage and return that if (self.actual_num_configs[self.stage] < self.num_configs[self.stage]): self.add_configuration() return(self.get_next_run()) if self.num_running == 0: # at this point a stage is completed self.process_results() return(self.get_next_run()) return(None)
[ "def", "get_next_run", "(", "self", ")", ":", "if", "self", ".", "is_finished", ":", "return", "(", "None", ")", "for", "k", ",", "v", "in", "self", ".", "data", ".", "items", "(", ")", ":", "if", "v", ".", "status", "==", "'QUEUED'", ":", "asser...
function to return the next configuration and budget to run. This function is called from HB_master, don't call this from your script. It returns None if this run of SH is finished or there are pending jobs that need to finish to progress to the next stage. If there are empty slots to be filled in the current SH stage (which never happens in the original SH version), a new configuration will be sampled and scheduled to run next.
[ "function", "to", "return", "the", "next", "configuration", "and", "budget", "to", "run", "." ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_iteration.py#L141-L176
train
216,751
automl/HpBandSter
hpbandster/core/base_iteration.py
BaseIteration.process_results
def process_results(self): """ function that is called when a stage is completed and needs to be analyzed befor further computations. The code here implements the original SH algorithms by advancing the k-best (lowest loss) configurations at the current budget. k is defined by the num_configs list (see __init__) and the current stage value. For more advanced methods like resampling after each stage, overload this function only. """ self.stage += 1 # collect all config_ids that need to be compared config_ids = list(filter(lambda cid: self.data[cid].status == 'REVIEW', self.data.keys())) if (self.stage >= len(self.num_configs)): self.finish_up() return budgets = [self.data[cid].budget for cid in config_ids] if len(set(budgets)) > 1: raise RuntimeError('Not all configurations have the same budget!') budget = self.budgets[self.stage-1] losses = np.array([self.data[cid].results[budget]['loss'] for cid in config_ids]) advance = self._advance_to_next_stage(config_ids, losses) for i, a in enumerate(advance): if a: self.logger.debug('ITERATION: Advancing config %s to next budget %f'%(config_ids[i], self.budgets[self.stage])) for i, cid in enumerate(config_ids): if advance[i]: self.data[cid].status = 'QUEUED' self.data[cid].budget = self.budgets[self.stage] self.actual_num_configs[self.stage] += 1 else: self.data[cid].status = 'TERMINATED'
python
def process_results(self): """ function that is called when a stage is completed and needs to be analyzed befor further computations. The code here implements the original SH algorithms by advancing the k-best (lowest loss) configurations at the current budget. k is defined by the num_configs list (see __init__) and the current stage value. For more advanced methods like resampling after each stage, overload this function only. """ self.stage += 1 # collect all config_ids that need to be compared config_ids = list(filter(lambda cid: self.data[cid].status == 'REVIEW', self.data.keys())) if (self.stage >= len(self.num_configs)): self.finish_up() return budgets = [self.data[cid].budget for cid in config_ids] if len(set(budgets)) > 1: raise RuntimeError('Not all configurations have the same budget!') budget = self.budgets[self.stage-1] losses = np.array([self.data[cid].results[budget]['loss'] for cid in config_ids]) advance = self._advance_to_next_stage(config_ids, losses) for i, a in enumerate(advance): if a: self.logger.debug('ITERATION: Advancing config %s to next budget %f'%(config_ids[i], self.budgets[self.stage])) for i, cid in enumerate(config_ids): if advance[i]: self.data[cid].status = 'QUEUED' self.data[cid].budget = self.budgets[self.stage] self.actual_num_configs[self.stage] += 1 else: self.data[cid].status = 'TERMINATED'
[ "def", "process_results", "(", "self", ")", ":", "self", ".", "stage", "+=", "1", "# collect all config_ids that need to be compared", "config_ids", "=", "list", "(", "filter", "(", "lambda", "cid", ":", "self", ".", "data", "[", "cid", "]", ".", "status", "...
function that is called when a stage is completed and needs to be analyzed befor further computations. The code here implements the original SH algorithms by advancing the k-best (lowest loss) configurations at the current budget. k is defined by the num_configs list (see __init__) and the current stage value. For more advanced methods like resampling after each stage, overload this function only.
[ "function", "that", "is", "called", "when", "a", "stage", "is", "completed", "and", "needs", "to", "be", "analyzed", "befor", "further", "computations", "." ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_iteration.py#L201-L242
train
216,752
automl/HpBandSter
hpbandster/core/base_iteration.py
WarmStartIteration.fix_timestamps
def fix_timestamps(self, time_ref): """ manipulates internal time stamps such that the last run ends at time 0 """ for k,v in self.data.items(): for kk, vv in v.time_stamps.items(): for kkk,vvv in vv.items(): self.data[k].time_stamps[kk][kkk] += time_ref
python
def fix_timestamps(self, time_ref): """ manipulates internal time stamps such that the last run ends at time 0 """ for k,v in self.data.items(): for kk, vv in v.time_stamps.items(): for kkk,vvv in vv.items(): self.data[k].time_stamps[kk][kkk] += time_ref
[ "def", "fix_timestamps", "(", "self", ",", "time_ref", ")", ":", "for", "k", ",", "v", "in", "self", ".", "data", ".", "items", "(", ")", ":", "for", "kk", ",", "vv", "in", "v", ".", "time_stamps", ".", "items", "(", ")", ":", "for", "kkk", ","...
manipulates internal time stamps such that the last run ends at time 0
[ "manipulates", "internal", "time", "stamps", "such", "that", "the", "last", "run", "ends", "at", "time", "0" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/base_iteration.py#L290-L298
train
216,753
automl/HpBandSter
hpbandster/optimizers/config_generators/lcnet.py
LCNetWrapper.get_config
def get_config(self, budget): """ function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration """ self.lock.acquire() if not self.is_trained: c = self.config_space.sample_configuration().get_array() else: candidates = np.array([self.config_space.sample_configuration().get_array() for _ in range(self.n_candidates)]) # We are only interested on the asymptotic value projected_candidates = np.concatenate((candidates, np.ones([self.n_candidates, 1])), axis=1) # Compute the upper confidence bound of the function at the asymptote m, v = self.model.predict(projected_candidates) ucb_values = m + self.delta * np.sqrt(v) print(ucb_values) # Sample a configuration based on the ucb values p = np.ones(self.n_candidates) * (ucb_values / np.sum(ucb_values)) idx = np.random.choice(self.n_candidates, 1, False, p) c = candidates[idx][0] config = ConfigSpace.Configuration(self.config_space, vector=c) self.lock.release() return config.get_dictionary(), {}
python
def get_config(self, budget): """ function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration """ self.lock.acquire() if not self.is_trained: c = self.config_space.sample_configuration().get_array() else: candidates = np.array([self.config_space.sample_configuration().get_array() for _ in range(self.n_candidates)]) # We are only interested on the asymptotic value projected_candidates = np.concatenate((candidates, np.ones([self.n_candidates, 1])), axis=1) # Compute the upper confidence bound of the function at the asymptote m, v = self.model.predict(projected_candidates) ucb_values = m + self.delta * np.sqrt(v) print(ucb_values) # Sample a configuration based on the ucb values p = np.ones(self.n_candidates) * (ucb_values / np.sum(ucb_values)) idx = np.random.choice(self.n_candidates, 1, False, p) c = candidates[idx][0] config = ConfigSpace.Configuration(self.config_space, vector=c) self.lock.release() return config.get_dictionary(), {}
[ "def", "get_config", "(", "self", ",", "budget", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "if", "not", "self", ".", "is_trained", ":", "c", "=", "self", ".", "config_space", ".", "sample_configuration", "(", ")", ".", "get_array", "(", ...
function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration
[ "function", "to", "sample", "a", "new", "configuration" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/config_generators/lcnet.py#L63-L103
train
216,754
automl/HpBandSter
hpbandster/core/result.py
extract_HBS_learning_curves
def extract_HBS_learning_curves(runs): """ function to get the hyperband learning curves This is an example function showing the interface to use the HB_result.get_learning_curves method. Parameters ---------- runs: list of HB_result.run objects the performed runs for an unspecified config Returns ------- list of learning curves: list of lists of tuples An individual learning curve is a list of (t, x_t) tuples. This function must return a list of these. One could think of cases where one could extract multiple learning curves from these runs, e.g. if each run is an independent training run of a neural network on the data. """ sr = sorted(runs, key=lambda r: r.budget) lc = list(filter(lambda t: not t[1] is None, [(r.budget, r.loss) for r in sr])) return([lc,])
python
def extract_HBS_learning_curves(runs): """ function to get the hyperband learning curves This is an example function showing the interface to use the HB_result.get_learning_curves method. Parameters ---------- runs: list of HB_result.run objects the performed runs for an unspecified config Returns ------- list of learning curves: list of lists of tuples An individual learning curve is a list of (t, x_t) tuples. This function must return a list of these. One could think of cases where one could extract multiple learning curves from these runs, e.g. if each run is an independent training run of a neural network on the data. """ sr = sorted(runs, key=lambda r: r.budget) lc = list(filter(lambda t: not t[1] is None, [(r.budget, r.loss) for r in sr])) return([lc,])
[ "def", "extract_HBS_learning_curves", "(", "runs", ")", ":", "sr", "=", "sorted", "(", "runs", ",", "key", "=", "lambda", "r", ":", "r", ".", "budget", ")", "lc", "=", "list", "(", "filter", "(", "lambda", "t", ":", "not", "t", "[", "1", "]", "is...
function to get the hyperband learning curves This is an example function showing the interface to use the HB_result.get_learning_curves method. Parameters ---------- runs: list of HB_result.run objects the performed runs for an unspecified config Returns ------- list of learning curves: list of lists of tuples An individual learning curve is a list of (t, x_t) tuples. This function must return a list of these. One could think of cases where one could extract multiple learning curves from these runs, e.g. if each run is an independent training run of a neural network on the data.
[ "function", "to", "get", "the", "hyperband", "learning", "curves" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L35-L61
train
216,755
automl/HpBandSter
hpbandster/core/result.py
logged_results_to_HBS_result
def logged_results_to_HBS_result(directory): """ function to import logged 'live-results' and return a HB_result object You can load live run results with this function and the returned HB_result object gives you access to the results the same way a finished run would. Parameters ---------- directory: str the directory containing the results.json and config.json files Returns ------- hpbandster.core.result.Result: :object: TODO """ data = {} time_ref = float('inf') budget_set = set() with open(os.path.join(directory, 'configs.json')) as fh: for line in fh: line = json.loads(line) if len(line) == 3: config_id, config, config_info = line if len(line) == 2: config_id, config, = line config_info = 'N/A' data[tuple(config_id)] = Datum(config=config, config_info=config_info) with open(os.path.join(directory, 'results.json')) as fh: for line in fh: config_id, budget,time_stamps, result, exception = json.loads(line) id = tuple(config_id) data[id].time_stamps[budget] = time_stamps data[id].results[budget] = result data[id].exceptions[budget] = exception budget_set.add(budget) time_ref = min(time_ref, time_stamps['submitted']) # infer the hyperband configuration from the data budget_list = sorted(list(budget_set)) HB_config = { 'eta' : None if len(budget_list) < 2 else budget_list[1]/budget_list[0], 'min_budget' : min(budget_set), 'max_budget' : max(budget_set), 'budgets' : budget_list, 'max_SH_iter': len(budget_set), 'time_ref' : time_ref } return(Result([data], HB_config))
python
def logged_results_to_HBS_result(directory): """ function to import logged 'live-results' and return a HB_result object You can load live run results with this function and the returned HB_result object gives you access to the results the same way a finished run would. Parameters ---------- directory: str the directory containing the results.json and config.json files Returns ------- hpbandster.core.result.Result: :object: TODO """ data = {} time_ref = float('inf') budget_set = set() with open(os.path.join(directory, 'configs.json')) as fh: for line in fh: line = json.loads(line) if len(line) == 3: config_id, config, config_info = line if len(line) == 2: config_id, config, = line config_info = 'N/A' data[tuple(config_id)] = Datum(config=config, config_info=config_info) with open(os.path.join(directory, 'results.json')) as fh: for line in fh: config_id, budget,time_stamps, result, exception = json.loads(line) id = tuple(config_id) data[id].time_stamps[budget] = time_stamps data[id].results[budget] = result data[id].exceptions[budget] = exception budget_set.add(budget) time_ref = min(time_ref, time_stamps['submitted']) # infer the hyperband configuration from the data budget_list = sorted(list(budget_set)) HB_config = { 'eta' : None if len(budget_list) < 2 else budget_list[1]/budget_list[0], 'min_budget' : min(budget_set), 'max_budget' : max(budget_set), 'budgets' : budget_list, 'max_SH_iter': len(budget_set), 'time_ref' : time_ref } return(Result([data], HB_config))
[ "def", "logged_results_to_HBS_result", "(", "directory", ")", ":", "data", "=", "{", "}", "time_ref", "=", "float", "(", "'inf'", ")", "budget_set", "=", "set", "(", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "'con...
function to import logged 'live-results' and return a HB_result object You can load live run results with this function and the returned HB_result object gives you access to the results the same way a finished run would. Parameters ---------- directory: str the directory containing the results.json and config.json files Returns ------- hpbandster.core.result.Result: :object: TODO
[ "function", "to", "import", "logged", "live", "-", "results", "and", "return", "a", "HB_result", "object" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L139-L200
train
216,756
automl/HpBandSter
hpbandster/core/result.py
Result.get_incumbent_id
def get_incumbent_id(self): """ Find the config_id of the incumbent. The incumbent here is the configuration with the smallest loss among all runs on the maximum budget! If no run finishes on the maximum budget, None is returned! """ tmp_list = [] for k,v in self.data.items(): try: # only things run for the max budget are considered res = v.results[self.HB_config['max_budget']] if not res is None: tmp_list.append((res['loss'], k)) except KeyError as e: pass except: raise if len(tmp_list) > 0: return(min(tmp_list)[1]) return(None)
python
def get_incumbent_id(self): """ Find the config_id of the incumbent. The incumbent here is the configuration with the smallest loss among all runs on the maximum budget! If no run finishes on the maximum budget, None is returned! """ tmp_list = [] for k,v in self.data.items(): try: # only things run for the max budget are considered res = v.results[self.HB_config['max_budget']] if not res is None: tmp_list.append((res['loss'], k)) except KeyError as e: pass except: raise if len(tmp_list) > 0: return(min(tmp_list)[1]) return(None)
[ "def", "get_incumbent_id", "(", "self", ")", ":", "tmp_list", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "data", ".", "items", "(", ")", ":", "try", ":", "# only things run for the max budget are considered", "res", "=", "v", ".", "results", ...
Find the config_id of the incumbent. The incumbent here is the configuration with the smallest loss among all runs on the maximum budget! If no run finishes on the maximum budget, None is returned!
[ "Find", "the", "config_id", "of", "the", "incumbent", "." ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L219-L241
train
216,757
automl/HpBandSter
hpbandster/core/result.py
Result.get_runs_by_id
def get_runs_by_id(self, config_id): """ returns a list of runs for a given config id The runs are sorted by ascending budget, so '-1' will give the longest run for this config. """ d = self.data[config_id] runs = [] for b in d.results.keys(): try: err_logs = d.exceptions.get(b, None) if d.results[b] is None: r = Run(config_id, b, None, None , d.time_stamps[b], err_logs) else: r = Run(config_id, b, d.results[b]['loss'], d.results[b]['info'] , d.time_stamps[b], err_logs) runs.append(r) except: raise runs.sort(key=lambda r: r.budget) return(runs)
python
def get_runs_by_id(self, config_id): """ returns a list of runs for a given config id The runs are sorted by ascending budget, so '-1' will give the longest run for this config. """ d = self.data[config_id] runs = [] for b in d.results.keys(): try: err_logs = d.exceptions.get(b, None) if d.results[b] is None: r = Run(config_id, b, None, None , d.time_stamps[b], err_logs) else: r = Run(config_id, b, d.results[b]['loss'], d.results[b]['info'] , d.time_stamps[b], err_logs) runs.append(r) except: raise runs.sort(key=lambda r: r.budget) return(runs)
[ "def", "get_runs_by_id", "(", "self", ",", "config_id", ")", ":", "d", "=", "self", ".", "data", "[", "config_id", "]", "runs", "=", "[", "]", "for", "b", "in", "d", ".", "results", ".", "keys", "(", ")", ":", "try", ":", "err_logs", "=", "d", ...
returns a list of runs for a given config id The runs are sorted by ascending budget, so '-1' will give the longest run for this config.
[ "returns", "a", "list", "of", "runs", "for", "a", "given", "config", "id" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L319-L341
train
216,758
automl/HpBandSter
hpbandster/core/result.py
Result.get_learning_curves
def get_learning_curves(self, lc_extractor=extract_HBS_learning_curves, config_ids=None): """ extracts all learning curves from all run configurations Parameters ---------- lc_extractor: callable a function to return a list of learning_curves. defaults to hpbanster.HB_result.extract_HP_learning_curves config_ids: list of valid config ids if only a subset of the config ids is wanted Returns ------- dict a dictionary with the config_ids as keys and the learning curves as values """ config_ids = self.data.keys() if config_ids is None else config_ids lc_dict = {} for id in config_ids: runs = self.get_runs_by_id(id) lc_dict[id] = lc_extractor(runs) return(lc_dict)
python
def get_learning_curves(self, lc_extractor=extract_HBS_learning_curves, config_ids=None): """ extracts all learning curves from all run configurations Parameters ---------- lc_extractor: callable a function to return a list of learning_curves. defaults to hpbanster.HB_result.extract_HP_learning_curves config_ids: list of valid config ids if only a subset of the config ids is wanted Returns ------- dict a dictionary with the config_ids as keys and the learning curves as values """ config_ids = self.data.keys() if config_ids is None else config_ids lc_dict = {} for id in config_ids: runs = self.get_runs_by_id(id) lc_dict[id] = lc_extractor(runs) return(lc_dict)
[ "def", "get_learning_curves", "(", "self", ",", "lc_extractor", "=", "extract_HBS_learning_curves", ",", "config_ids", "=", "None", ")", ":", "config_ids", "=", "self", ".", "data", ".", "keys", "(", ")", "if", "config_ids", "is", "None", "else", "config_ids",...
extracts all learning curves from all run configurations Parameters ---------- lc_extractor: callable a function to return a list of learning_curves. defaults to hpbanster.HB_result.extract_HP_learning_curves config_ids: list of valid config ids if only a subset of the config ids is wanted Returns ------- dict a dictionary with the config_ids as keys and the learning curves as values
[ "extracts", "all", "learning", "curves", "from", "all", "run", "configurations" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L344-L371
train
216,759
automl/HpBandSter
hpbandster/core/result.py
Result.get_all_runs
def get_all_runs(self, only_largest_budget=False): """ returns all runs performed Parameters ---------- only_largest_budget: boolean if True, only the largest budget for each configuration is returned. This makes sense if the runs are continued across budgets and the info field contains the information you care about. If False, all runs of a configuration are returned """ all_runs = [] for k in self.data.keys(): runs = self.get_runs_by_id(k) if len(runs) > 0: if only_largest_budget: all_runs.append(runs[-1]) else: all_runs.extend(runs) return(all_runs)
python
def get_all_runs(self, only_largest_budget=False): """ returns all runs performed Parameters ---------- only_largest_budget: boolean if True, only the largest budget for each configuration is returned. This makes sense if the runs are continued across budgets and the info field contains the information you care about. If False, all runs of a configuration are returned """ all_runs = [] for k in self.data.keys(): runs = self.get_runs_by_id(k) if len(runs) > 0: if only_largest_budget: all_runs.append(runs[-1]) else: all_runs.extend(runs) return(all_runs)
[ "def", "get_all_runs", "(", "self", ",", "only_largest_budget", "=", "False", ")", ":", "all_runs", "=", "[", "]", "for", "k", "in", "self", ".", "data", ".", "keys", "(", ")", ":", "runs", "=", "self", ".", "get_runs_by_id", "(", "k", ")", "if", "...
returns all runs performed Parameters ---------- only_largest_budget: boolean if True, only the largest budget for each configuration is returned. This makes sense if the runs are continued across budgets and the info field contains the information you care about. If False, all runs of a configuration are returned
[ "returns", "all", "runs", "performed" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L374-L398
train
216,760
automl/HpBandSter
hpbandster/core/result.py
Result.get_id2config_mapping
def get_id2config_mapping(self): """ returns a dict where the keys are the config_ids and the values are the actual configurations """ new_dict = {} for k, v in self.data.items(): new_dict[k] = {} new_dict[k]['config'] = copy.deepcopy(v.config) try: new_dict[k]['config_info'] = copy.deepcopy(v.config_info) except: pass return(new_dict)
python
def get_id2config_mapping(self): """ returns a dict where the keys are the config_ids and the values are the actual configurations """ new_dict = {} for k, v in self.data.items(): new_dict[k] = {} new_dict[k]['config'] = copy.deepcopy(v.config) try: new_dict[k]['config_info'] = copy.deepcopy(v.config_info) except: pass return(new_dict)
[ "def", "get_id2config_mapping", "(", "self", ")", ":", "new_dict", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "data", ".", "items", "(", ")", ":", "new_dict", "[", "k", "]", "=", "{", "}", "new_dict", "[", "k", "]", "[", "'config'", ...
returns a dict where the keys are the config_ids and the values are the actual configurations
[ "returns", "a", "dict", "where", "the", "keys", "are", "the", "config_ids", "and", "the", "values", "are", "the", "actual", "configurations" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L400-L413
train
216,761
automl/HpBandSter
hpbandster/core/result.py
Result._merge_results
def _merge_results(self): """ hidden function to merge the list of results into one dictionary and 'normalize' the time stamps """ new_dict = {} for it in self.data: new_dict.update(it) for k,v in new_dict.items(): for kk, vv in v.time_stamps.items(): for kkk,vvv in vv.items(): new_dict[k].time_stamps[kk][kkk] = vvv - self.HB_config['time_ref'] self.data = new_dict
python
def _merge_results(self): """ hidden function to merge the list of results into one dictionary and 'normalize' the time stamps """ new_dict = {} for it in self.data: new_dict.update(it) for k,v in new_dict.items(): for kk, vv in v.time_stamps.items(): for kkk,vvv in vv.items(): new_dict[k].time_stamps[kk][kkk] = vvv - self.HB_config['time_ref'] self.data = new_dict
[ "def", "_merge_results", "(", "self", ")", ":", "new_dict", "=", "{", "}", "for", "it", "in", "self", ".", "data", ":", "new_dict", ".", "update", "(", "it", ")", "for", "k", ",", "v", "in", "new_dict", ".", "items", "(", ")", ":", "for", "kk", ...
hidden function to merge the list of results into one dictionary and 'normalize' the time stamps
[ "hidden", "function", "to", "merge", "the", "list", "of", "results", "into", "one", "dictionary", "and", "normalize", "the", "time", "stamps" ]
841db4b827f342e5eb7f725723ea6461ac52d45a
https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/core/result.py#L415-L429
train
216,762
Koed00/django-q
django_q/core_signing.py
TimestampSigner.unsign
def unsign(self, value, max_age=None): """ Retrieve original value and check it wasn't signed more than max_age seconds ago. """ result = super(TimestampSigner, self).unsign(value) value, timestamp = result.rsplit(self.sep, 1) timestamp = baseconv.base62.decode(timestamp) if max_age is not None: if isinstance(max_age, datetime.timedelta): max_age = max_age.total_seconds() # Check timestamp is not older than max_age age = time.time() - timestamp if age > max_age: raise SignatureExpired( 'Signature age %s > %s seconds' % (age, max_age)) return value
python
def unsign(self, value, max_age=None): """ Retrieve original value and check it wasn't signed more than max_age seconds ago. """ result = super(TimestampSigner, self).unsign(value) value, timestamp = result.rsplit(self.sep, 1) timestamp = baseconv.base62.decode(timestamp) if max_age is not None: if isinstance(max_age, datetime.timedelta): max_age = max_age.total_seconds() # Check timestamp is not older than max_age age = time.time() - timestamp if age > max_age: raise SignatureExpired( 'Signature age %s > %s seconds' % (age, max_age)) return value
[ "def", "unsign", "(", "self", ",", "value", ",", "max_age", "=", "None", ")", ":", "result", "=", "super", "(", "TimestampSigner", ",", "self", ")", ".", "unsign", "(", "value", ")", "value", ",", "timestamp", "=", "result", ".", "rsplit", "(", "self...
Retrieve original value and check it wasn't signed more than max_age seconds ago.
[ "Retrieve", "original", "value", "and", "check", "it", "wasn", "t", "signed", "more", "than", "max_age", "seconds", "ago", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/core_signing.py#L63-L79
train
216,763
Koed00/django-q
django_q/humanhash.py
HumanHasher.humanize
def humanize(self, hexdigest, words=4, separator='-'): """ Humanize a given hexadecimal digest. Change the number of words output by specifying `words`. Change the word separator with `separator`. >>> digest = '60ad8d0d871b6095808297' >>> HumanHasher().humanize(digest) 'sodium-magnesium-nineteen-hydrogen' """ # Gets a list of byte values between 0-255. bytes = [int(x, 16) for x in list(map(''.join, list(zip(hexdigest[::2], hexdigest[1::2]))))] # Compress an arbitrary number of bytes to `words`. compressed = self.compress(bytes, words) # Map the compressed byte values through the word list. return separator.join(self.wordlist[byte] for byte in compressed)
python
def humanize(self, hexdigest, words=4, separator='-'): """ Humanize a given hexadecimal digest. Change the number of words output by specifying `words`. Change the word separator with `separator`. >>> digest = '60ad8d0d871b6095808297' >>> HumanHasher().humanize(digest) 'sodium-magnesium-nineteen-hydrogen' """ # Gets a list of byte values between 0-255. bytes = [int(x, 16) for x in list(map(''.join, list(zip(hexdigest[::2], hexdigest[1::2]))))] # Compress an arbitrary number of bytes to `words`. compressed = self.compress(bytes, words) # Map the compressed byte values through the word list. return separator.join(self.wordlist[byte] for byte in compressed)
[ "def", "humanize", "(", "self", ",", "hexdigest", ",", "words", "=", "4", ",", "separator", "=", "'-'", ")", ":", "# Gets a list of byte values between 0-255.", "bytes", "=", "[", "int", "(", "x", ",", "16", ")", "for", "x", "in", "list", "(", "map", "...
Humanize a given hexadecimal digest. Change the number of words output by specifying `words`. Change the word separator with `separator`. >>> digest = '60ad8d0d871b6095808297' >>> HumanHasher().humanize(digest) 'sodium-magnesium-nineteen-hydrogen'
[ "Humanize", "a", "given", "hexadecimal", "digest", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/humanhash.py#L73-L91
train
216,764
Koed00/django-q
django_q/humanhash.py
HumanHasher.compress
def compress(bytes, target): """ Compress a list of byte values to a fixed target length. >>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151] >>> HumanHasher.compress(bytes, 4) [205, 128, 156, 96] Attempting to compress a smaller number of bytes to a larger number is an error: >>> HumanHasher.compress(bytes, 15) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Fewer input bytes than requested output """ length = len(bytes) if target > length: raise ValueError("Fewer input bytes than requested output") # Split `bytes` into `target` segments. seg_size = length // target segments = [bytes[i * seg_size:(i + 1) * seg_size] for i in range(target)] # Catch any left-over bytes in the last segment. segments[-1].extend(bytes[target * seg_size:]) # Use a simple XOR checksum-like function for compression. checksum = lambda bytes: reduce(operator.xor, bytes, 0) checksums = list(map(checksum, segments)) return checksums
python
def compress(bytes, target): """ Compress a list of byte values to a fixed target length. >>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151] >>> HumanHasher.compress(bytes, 4) [205, 128, 156, 96] Attempting to compress a smaller number of bytes to a larger number is an error: >>> HumanHasher.compress(bytes, 15) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Fewer input bytes than requested output """ length = len(bytes) if target > length: raise ValueError("Fewer input bytes than requested output") # Split `bytes` into `target` segments. seg_size = length // target segments = [bytes[i * seg_size:(i + 1) * seg_size] for i in range(target)] # Catch any left-over bytes in the last segment. segments[-1].extend(bytes[target * seg_size:]) # Use a simple XOR checksum-like function for compression. checksum = lambda bytes: reduce(operator.xor, bytes, 0) checksums = list(map(checksum, segments)) return checksums
[ "def", "compress", "(", "bytes", ",", "target", ")", ":", "length", "=", "len", "(", "bytes", ")", "if", "target", ">", "length", ":", "raise", "ValueError", "(", "\"Fewer input bytes than requested output\"", ")", "# Split `bytes` into `target` segments.", "seg_siz...
Compress a list of byte values to a fixed target length. >>> bytes = [96, 173, 141, 13, 135, 27, 96, 149, 128, 130, 151] >>> HumanHasher.compress(bytes, 4) [205, 128, 156, 96] Attempting to compress a smaller number of bytes to a larger number is an error: >>> HumanHasher.compress(bytes, 15) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Fewer input bytes than requested output
[ "Compress", "a", "list", "of", "byte", "values", "to", "a", "fixed", "target", "length", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/humanhash.py#L94-L126
train
216,765
Koed00/django-q
django_q/humanhash.py
HumanHasher.uuid
def uuid(self, **params): """ Generate a UUID with a human-readable representation. Returns `(human_repr, full_digest)`. Accepts the same keyword arguments as :meth:`humanize` (they'll be passed straight through). """ digest = str(uuidlib.uuid4()).replace('-', '') return self.humanize(digest, **params), digest
python
def uuid(self, **params): """ Generate a UUID with a human-readable representation. Returns `(human_repr, full_digest)`. Accepts the same keyword arguments as :meth:`humanize` (they'll be passed straight through). """ digest = str(uuidlib.uuid4()).replace('-', '') return self.humanize(digest, **params), digest
[ "def", "uuid", "(", "self", ",", "*", "*", "params", ")", ":", "digest", "=", "str", "(", "uuidlib", ".", "uuid4", "(", ")", ")", ".", "replace", "(", "'-'", ",", "''", ")", "return", "self", ".", "humanize", "(", "digest", ",", "*", "*", "para...
Generate a UUID with a human-readable representation. Returns `(human_repr, full_digest)`. Accepts the same keyword arguments as :meth:`humanize` (they'll be passed straight through).
[ "Generate", "a", "UUID", "with", "a", "human", "-", "readable", "representation", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/humanhash.py#L128-L138
train
216,766
Koed00/django-q
django_q/tasks.py
async_task
def async_task(func, *args, **kwargs): """Queue a task for the cluster.""" keywords = kwargs.copy() opt_keys = ( 'hook', 'group', 'save', 'sync', 'cached', 'ack_failure', 'iter_count', 'iter_cached', 'chain', 'broker') q_options = keywords.pop('q_options', {}) # get an id tag = uuid() # build the task package task = {'id': tag[1], 'name': keywords.pop('task_name', None) or q_options.pop('task_name', None) or tag[0], 'func': func, 'args': args} # push optionals for key in opt_keys: if q_options and key in q_options: task[key] = q_options[key] elif key in keywords: task[key] = keywords.pop(key) # don't serialize the broker broker = task.pop('broker', get_broker()) # overrides if 'cached' not in task and Conf.CACHED: task['cached'] = Conf.CACHED if 'sync' not in task and Conf.SYNC: task['sync'] = Conf.SYNC if 'ack_failure' not in task and Conf.ACK_FAILURES: task['ack_failure'] = Conf.ACK_FAILURES # finalize task['kwargs'] = keywords task['started'] = timezone.now() # signal it pre_enqueue.send(sender="django_q", task=task) # sign it pack = SignedPackage.dumps(task) if task.get('sync', False): return _sync(pack) # push it enqueue_id = broker.enqueue(pack) logger.info('Enqueued {}'.format(enqueue_id)) logger.debug('Pushed {}'.format(tag)) return task['id']
python
def async_task(func, *args, **kwargs): """Queue a task for the cluster.""" keywords = kwargs.copy() opt_keys = ( 'hook', 'group', 'save', 'sync', 'cached', 'ack_failure', 'iter_count', 'iter_cached', 'chain', 'broker') q_options = keywords.pop('q_options', {}) # get an id tag = uuid() # build the task package task = {'id': tag[1], 'name': keywords.pop('task_name', None) or q_options.pop('task_name', None) or tag[0], 'func': func, 'args': args} # push optionals for key in opt_keys: if q_options and key in q_options: task[key] = q_options[key] elif key in keywords: task[key] = keywords.pop(key) # don't serialize the broker broker = task.pop('broker', get_broker()) # overrides if 'cached' not in task and Conf.CACHED: task['cached'] = Conf.CACHED if 'sync' not in task and Conf.SYNC: task['sync'] = Conf.SYNC if 'ack_failure' not in task and Conf.ACK_FAILURES: task['ack_failure'] = Conf.ACK_FAILURES # finalize task['kwargs'] = keywords task['started'] = timezone.now() # signal it pre_enqueue.send(sender="django_q", task=task) # sign it pack = SignedPackage.dumps(task) if task.get('sync', False): return _sync(pack) # push it enqueue_id = broker.enqueue(pack) logger.info('Enqueued {}'.format(enqueue_id)) logger.debug('Pushed {}'.format(tag)) return task['id']
[ "def", "async_task", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "keywords", "=", "kwargs", ".", "copy", "(", ")", "opt_keys", "=", "(", "'hook'", ",", "'group'", ",", "'save'", ",", "'sync'", ",", "'cached'", ",", "'ack_failure...
Queue a task for the cluster.
[ "Queue", "a", "task", "for", "the", "cluster", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L21-L62
train
216,767
Koed00/django-q
django_q/tasks.py
schedule
def schedule(func, *args, **kwargs): """ Create a schedule. :param func: function to schedule. :param args: function arguments. :param name: optional name for the schedule. :param hook: optional result hook function. :type schedule_type: Schedule.TYPE :param repeats: how many times to repeat. 0=never, -1=always. :param next_run: Next scheduled run. :type next_run: datetime.datetime :param kwargs: function keyword arguments. :return: the schedule object. :rtype: Schedule """ name = kwargs.pop('name', None) hook = kwargs.pop('hook', None) schedule_type = kwargs.pop('schedule_type', Schedule.ONCE) minutes = kwargs.pop('minutes', None) repeats = kwargs.pop('repeats', -1) next_run = kwargs.pop('next_run', timezone.now()) # check for name duplicates instead of am unique constraint if name and Schedule.objects.filter(name=name).exists(): raise IntegrityError("A schedule with the same name already exists.") # create and return the schedule return Schedule.objects.create(name=name, func=func, hook=hook, args=args, kwargs=kwargs, schedule_type=schedule_type, minutes=minutes, repeats=repeats, next_run=next_run )
python
def schedule(func, *args, **kwargs): """ Create a schedule. :param func: function to schedule. :param args: function arguments. :param name: optional name for the schedule. :param hook: optional result hook function. :type schedule_type: Schedule.TYPE :param repeats: how many times to repeat. 0=never, -1=always. :param next_run: Next scheduled run. :type next_run: datetime.datetime :param kwargs: function keyword arguments. :return: the schedule object. :rtype: Schedule """ name = kwargs.pop('name', None) hook = kwargs.pop('hook', None) schedule_type = kwargs.pop('schedule_type', Schedule.ONCE) minutes = kwargs.pop('minutes', None) repeats = kwargs.pop('repeats', -1) next_run = kwargs.pop('next_run', timezone.now()) # check for name duplicates instead of am unique constraint if name and Schedule.objects.filter(name=name).exists(): raise IntegrityError("A schedule with the same name already exists.") # create and return the schedule return Schedule.objects.create(name=name, func=func, hook=hook, args=args, kwargs=kwargs, schedule_type=schedule_type, minutes=minutes, repeats=repeats, next_run=next_run )
[ "def", "schedule", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ",", "None", ")", "hook", "=", "kwargs", ".", "pop", "(", "'hook'", ",", "None", ")", "schedule_type", "=", "kw...
Create a schedule. :param func: function to schedule. :param args: function arguments. :param name: optional name for the schedule. :param hook: optional result hook function. :type schedule_type: Schedule.TYPE :param repeats: how many times to repeat. 0=never, -1=always. :param next_run: Next scheduled run. :type next_run: datetime.datetime :param kwargs: function keyword arguments. :return: the schedule object. :rtype: Schedule
[ "Create", "a", "schedule", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L65-L102
train
216,768
Koed00/django-q
django_q/tasks.py
result
def result(task_id, wait=0, cached=Conf.CACHED): """ Return the result of the named task. :type task_id: str or uuid :param task_id: the task name or uuid :type wait: int :param wait: number of milliseconds to wait for a result :param bool cached: run this against the cache backend :return: the result object of this task :rtype: object """ if cached: return result_cached(task_id, wait) start = time() while True: r = Task.get_result(task_id) if r: return r if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
python
def result(task_id, wait=0, cached=Conf.CACHED): """ Return the result of the named task. :type task_id: str or uuid :param task_id: the task name or uuid :type wait: int :param wait: number of milliseconds to wait for a result :param bool cached: run this against the cache backend :return: the result object of this task :rtype: object """ if cached: return result_cached(task_id, wait) start = time() while True: r = Task.get_result(task_id) if r: return r if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
[ "def", "result", "(", "task_id", ",", "wait", "=", "0", ",", "cached", "=", "Conf", ".", "CACHED", ")", ":", "if", "cached", ":", "return", "result_cached", "(", "task_id", ",", "wait", ")", "start", "=", "time", "(", ")", "while", "True", ":", "r"...
Return the result of the named task. :type task_id: str or uuid :param task_id: the task name or uuid :type wait: int :param wait: number of milliseconds to wait for a result :param bool cached: run this against the cache backend :return: the result object of this task :rtype: object
[ "Return", "the", "result", "of", "the", "named", "task", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L105-L126
train
216,769
Koed00/django-q
django_q/tasks.py
result_cached
def result_cached(task_id, wait=0, broker=None): """ Return the result from the cache backend """ if not broker: broker = get_broker() start = time() while True: r = broker.cache.get('{}:{}'.format(broker.list_key, task_id)) if r: return SignedPackage.loads(r)['result'] if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
python
def result_cached(task_id, wait=0, broker=None): """ Return the result from the cache backend """ if not broker: broker = get_broker() start = time() while True: r = broker.cache.get('{}:{}'.format(broker.list_key, task_id)) if r: return SignedPackage.loads(r)['result'] if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
[ "def", "result_cached", "(", "task_id", ",", "wait", "=", "0", ",", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "start", "=", "time", "(", ")", "while", "True", ":", "r", "=", "broker", ".", ...
Return the result from the cache backend
[ "Return", "the", "result", "from", "the", "cache", "backend" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L129-L142
train
216,770
Koed00/django-q
django_q/tasks.py
result_group
def result_group(group_id, failures=False, wait=0, count=None, cached=Conf.CACHED): """ Return a list of results for a task group. :param str group_id: the group id :param bool failures: set to True to include failures :param int count: Block until there are this many results in the group :param bool cached: run this against the cache backend :return: list or results """ if cached: return result_group_cached(group_id, failures, wait, count) start = time() if count: while True: if count_group(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0: break sleep(0.01) while True: r = Task.get_result_group(group_id, failures) if r: return r if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
python
def result_group(group_id, failures=False, wait=0, count=None, cached=Conf.CACHED): """ Return a list of results for a task group. :param str group_id: the group id :param bool failures: set to True to include failures :param int count: Block until there are this many results in the group :param bool cached: run this against the cache backend :return: list or results """ if cached: return result_group_cached(group_id, failures, wait, count) start = time() if count: while True: if count_group(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0: break sleep(0.01) while True: r = Task.get_result_group(group_id, failures) if r: return r if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
[ "def", "result_group", "(", "group_id", ",", "failures", "=", "False", ",", "wait", "=", "0", ",", "count", "=", "None", ",", "cached", "=", "Conf", ".", "CACHED", ")", ":", "if", "cached", ":", "return", "result_group_cached", "(", "group_id", ",", "f...
Return a list of results for a task group. :param str group_id: the group id :param bool failures: set to True to include failures :param int count: Block until there are this many results in the group :param bool cached: run this against the cache backend :return: list or results
[ "Return", "a", "list", "of", "results", "for", "a", "task", "group", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L145-L169
train
216,771
Koed00/django-q
django_q/tasks.py
result_group_cached
def result_group_cached(group_id, failures=False, wait=0, count=None, broker=None): """ Return a list of results for a task group from the cache backend """ if not broker: broker = get_broker() start = time() if count: while True: if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait > 0: break sleep(0.01) while True: group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id)) if group_list: result_list = [] for task_key in group_list: task = SignedPackage.loads(broker.cache.get(task_key)) if task['success'] or failures: result_list.append(task['result']) return result_list if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
python
def result_group_cached(group_id, failures=False, wait=0, count=None, broker=None): """ Return a list of results for a task group from the cache backend """ if not broker: broker = get_broker() start = time() if count: while True: if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait > 0: break sleep(0.01) while True: group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id)) if group_list: result_list = [] for task_key in group_list: task = SignedPackage.loads(broker.cache.get(task_key)) if task['success'] or failures: result_list.append(task['result']) return result_list if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
[ "def", "result_group_cached", "(", "group_id", ",", "failures", "=", "False", ",", "wait", "=", "0", ",", "count", "=", "None", ",", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "start", "=", "ti...
Return a list of results for a task group from the cache backend
[ "Return", "a", "list", "of", "results", "for", "a", "task", "group", "from", "the", "cache", "backend" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L172-L195
train
216,772
Koed00/django-q
django_q/tasks.py
fetch
def fetch(task_id, wait=0, cached=Conf.CACHED): """ Return the processed task. :param task_id: the task name or uuid :type task_id: str or uuid :param wait: the number of milliseconds to wait for a result :type wait: int :param bool cached: run this against the cache backend :return: the full task object :rtype: Task """ if cached: return fetch_cached(task_id, wait) start = time() while True: t = Task.get_task(task_id) if t: return t if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
python
def fetch(task_id, wait=0, cached=Conf.CACHED): """ Return the processed task. :param task_id: the task name or uuid :type task_id: str or uuid :param wait: the number of milliseconds to wait for a result :type wait: int :param bool cached: run this against the cache backend :return: the full task object :rtype: Task """ if cached: return fetch_cached(task_id, wait) start = time() while True: t = Task.get_task(task_id) if t: return t if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
[ "def", "fetch", "(", "task_id", ",", "wait", "=", "0", ",", "cached", "=", "Conf", ".", "CACHED", ")", ":", "if", "cached", ":", "return", "fetch_cached", "(", "task_id", ",", "wait", ")", "start", "=", "time", "(", ")", "while", "True", ":", "t", ...
Return the processed task. :param task_id: the task name or uuid :type task_id: str or uuid :param wait: the number of milliseconds to wait for a result :type wait: int :param bool cached: run this against the cache backend :return: the full task object :rtype: Task
[ "Return", "the", "processed", "task", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L198-L219
train
216,773
Koed00/django-q
django_q/tasks.py
fetch_cached
def fetch_cached(task_id, wait=0, broker=None): """ Return the processed task from the cache backend """ if not broker: broker = get_broker() start = time() while True: r = broker.cache.get('{}:{}'.format(broker.list_key, task_id)) if r: task = SignedPackage.loads(r) t = Task(id=task['id'], name=task['name'], func=task['func'], hook=task.get('hook'), args=task['args'], kwargs=task['kwargs'], started=task['started'], stopped=task['stopped'], result=task['result'], success=task['success']) return t if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
python
def fetch_cached(task_id, wait=0, broker=None): """ Return the processed task from the cache backend """ if not broker: broker = get_broker() start = time() while True: r = broker.cache.get('{}:{}'.format(broker.list_key, task_id)) if r: task = SignedPackage.loads(r) t = Task(id=task['id'], name=task['name'], func=task['func'], hook=task.get('hook'), args=task['args'], kwargs=task['kwargs'], started=task['started'], stopped=task['stopped'], result=task['result'], success=task['success']) return t if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
[ "def", "fetch_cached", "(", "task_id", ",", "wait", "=", "0", ",", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "start", "=", "time", "(", ")", "while", "True", ":", "r", "=", "broker", ".", ...
Return the processed task from the cache backend
[ "Return", "the", "processed", "task", "from", "the", "cache", "backend" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L222-L246
train
216,774
Koed00/django-q
django_q/tasks.py
fetch_group
def fetch_group(group_id, failures=True, wait=0, count=None, cached=Conf.CACHED): """ Return a list of Tasks for a task group. :param str group_id: the group id :param bool failures: set to False to exclude failures :param bool cached: run this against the cache backend :return: list of Tasks """ if cached: return fetch_group_cached(group_id, failures, wait, count) start = time() if count: while True: if count_group(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0: break sleep(0.01) while True: r = Task.get_task_group(group_id, failures) if r: return r if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
python
def fetch_group(group_id, failures=True, wait=0, count=None, cached=Conf.CACHED): """ Return a list of Tasks for a task group. :param str group_id: the group id :param bool failures: set to False to exclude failures :param bool cached: run this against the cache backend :return: list of Tasks """ if cached: return fetch_group_cached(group_id, failures, wait, count) start = time() if count: while True: if count_group(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0: break sleep(0.01) while True: r = Task.get_task_group(group_id, failures) if r: return r if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
[ "def", "fetch_group", "(", "group_id", ",", "failures", "=", "True", ",", "wait", "=", "0", ",", "count", "=", "None", ",", "cached", "=", "Conf", ".", "CACHED", ")", ":", "if", "cached", ":", "return", "fetch_group_cached", "(", "group_id", ",", "fail...
Return a list of Tasks for a task group. :param str group_id: the group id :param bool failures: set to False to exclude failures :param bool cached: run this against the cache backend :return: list of Tasks
[ "Return", "a", "list", "of", "Tasks", "for", "a", "task", "group", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L249-L272
train
216,775
Koed00/django-q
django_q/tasks.py
fetch_group_cached
def fetch_group_cached(group_id, failures=True, wait=0, count=None, broker=None): """ Return a list of Tasks for a task group in the cache backend """ if not broker: broker = get_broker() start = time() if count: while True: if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0: break sleep(0.01) while True: group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id)) if group_list: task_list = [] for task_key in group_list: task = SignedPackage.loads(broker.cache.get(task_key)) if task['success'] or failures: t = Task(id=task['id'], name=task['name'], func=task['func'], hook=task.get('hook'), args=task['args'], kwargs=task['kwargs'], started=task['started'], stopped=task['stopped'], result=task['result'], group=task.get('group'), success=task['success']) task_list.append(t) return task_list if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
python
def fetch_group_cached(group_id, failures=True, wait=0, count=None, broker=None): """ Return a list of Tasks for a task group in the cache backend """ if not broker: broker = get_broker() start = time() if count: while True: if count_group_cached(group_id) == count or wait and (time() - start) * 1000 >= wait >= 0: break sleep(0.01) while True: group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id)) if group_list: task_list = [] for task_key in group_list: task = SignedPackage.loads(broker.cache.get(task_key)) if task['success'] or failures: t = Task(id=task['id'], name=task['name'], func=task['func'], hook=task.get('hook'), args=task['args'], kwargs=task['kwargs'], started=task['started'], stopped=task['stopped'], result=task['result'], group=task.get('group'), success=task['success']) task_list.append(t) return task_list if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
[ "def", "fetch_group_cached", "(", "group_id", ",", "failures", "=", "True", ",", "wait", "=", "0", ",", "count", "=", "None", ",", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "start", "=", "time...
Return a list of Tasks for a task group in the cache backend
[ "Return", "a", "list", "of", "Tasks", "for", "a", "task", "group", "in", "the", "cache", "backend" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L275-L309
train
216,776
Koed00/django-q
django_q/tasks.py
count_group
def count_group(group_id, failures=False, cached=Conf.CACHED): """ Count the results in a group. :param str group_id: the group id :param bool failures: Returns failure count if True :param bool cached: run this against the cache backend :return: the number of tasks/results in a group :rtype: int """ if cached: return count_group_cached(group_id, failures) return Task.get_group_count(group_id, failures)
python
def count_group(group_id, failures=False, cached=Conf.CACHED): """ Count the results in a group. :param str group_id: the group id :param bool failures: Returns failure count if True :param bool cached: run this against the cache backend :return: the number of tasks/results in a group :rtype: int """ if cached: return count_group_cached(group_id, failures) return Task.get_group_count(group_id, failures)
[ "def", "count_group", "(", "group_id", ",", "failures", "=", "False", ",", "cached", "=", "Conf", ".", "CACHED", ")", ":", "if", "cached", ":", "return", "count_group_cached", "(", "group_id", ",", "failures", ")", "return", "Task", ".", "get_group_count", ...
Count the results in a group. :param str group_id: the group id :param bool failures: Returns failure count if True :param bool cached: run this against the cache backend :return: the number of tasks/results in a group :rtype: int
[ "Count", "the", "results", "in", "a", "group", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L312-L324
train
216,777
Koed00/django-q
django_q/tasks.py
count_group_cached
def count_group_cached(group_id, failures=False, broker=None): """ Count the results in a group in the cache backend """ if not broker: broker = get_broker() group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id)) if group_list: if not failures: return len(group_list) failure_count = 0 for task_key in group_list: task = SignedPackage.loads(broker.cache.get(task_key)) if not task['success']: failure_count += 1 return failure_count
python
def count_group_cached(group_id, failures=False, broker=None): """ Count the results in a group in the cache backend """ if not broker: broker = get_broker() group_list = broker.cache.get('{}:{}:keys'.format(broker.list_key, group_id)) if group_list: if not failures: return len(group_list) failure_count = 0 for task_key in group_list: task = SignedPackage.loads(broker.cache.get(task_key)) if not task['success']: failure_count += 1 return failure_count
[ "def", "count_group_cached", "(", "group_id", ",", "failures", "=", "False", ",", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "group_list", "=", "broker", ".", "cache", ".", "get", "(", "'{}:{}:keys...
Count the results in a group in the cache backend
[ "Count", "the", "results", "in", "a", "group", "in", "the", "cache", "backend" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L327-L342
train
216,778
Koed00/django-q
django_q/tasks.py
delete_group_cached
def delete_group_cached(group_id, broker=None): """ Delete a group from the cache backend """ if not broker: broker = get_broker() group_key = '{}:{}:keys'.format(broker.list_key, group_id) group_list = broker.cache.get(group_key) broker.cache.delete_many(group_list) broker.cache.delete(group_key)
python
def delete_group_cached(group_id, broker=None): """ Delete a group from the cache backend """ if not broker: broker = get_broker() group_key = '{}:{}:keys'.format(broker.list_key, group_id) group_list = broker.cache.get(group_key) broker.cache.delete_many(group_list) broker.cache.delete(group_key)
[ "def", "delete_group_cached", "(", "group_id", ",", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "group_key", "=", "'{}:{}:keys'", ".", "format", "(", "broker", ".", "list_key", ",", "group_id", ")", ...
Delete a group from the cache backend
[ "Delete", "a", "group", "from", "the", "cache", "backend" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L360-L369
train
216,779
Koed00/django-q
django_q/tasks.py
delete_cached
def delete_cached(task_id, broker=None): """ Delete a task from the cache backend """ if not broker: broker = get_broker() return broker.cache.delete('{}:{}'.format(broker.list_key, task_id))
python
def delete_cached(task_id, broker=None): """ Delete a task from the cache backend """ if not broker: broker = get_broker() return broker.cache.delete('{}:{}'.format(broker.list_key, task_id))
[ "def", "delete_cached", "(", "task_id", ",", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "return", "broker", ".", "cache", ".", "delete", "(", "'{}:{}'", ".", "format", "(", "broker", ".", "list_k...
Delete a task from the cache backend
[ "Delete", "a", "task", "from", "the", "cache", "backend" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L372-L378
train
216,780
Koed00/django-q
django_q/tasks.py
async_iter
def async_iter(func, args_iter, **kwargs): """ enqueues a function with iterable arguments """ iter_count = len(args_iter) iter_group = uuid()[1] # clean up the kwargs options = kwargs.get('q_options', kwargs) options.pop('hook', None) options['broker'] = options.get('broker', get_broker()) options['group'] = iter_group options['iter_count'] = iter_count if options.get('cached', None): options['iter_cached'] = options['cached'] options['cached'] = True # save the original arguments broker = options['broker'] broker.cache.set('{}:{}:args'.format(broker.list_key, iter_group), SignedPackage.dumps(args_iter)) for args in args_iter: if not isinstance(args, tuple): args = (args,) async_task(func, *args, **options) return iter_group
python
def async_iter(func, args_iter, **kwargs): """ enqueues a function with iterable arguments """ iter_count = len(args_iter) iter_group = uuid()[1] # clean up the kwargs options = kwargs.get('q_options', kwargs) options.pop('hook', None) options['broker'] = options.get('broker', get_broker()) options['group'] = iter_group options['iter_count'] = iter_count if options.get('cached', None): options['iter_cached'] = options['cached'] options['cached'] = True # save the original arguments broker = options['broker'] broker.cache.set('{}:{}:args'.format(broker.list_key, iter_group), SignedPackage.dumps(args_iter)) for args in args_iter: if not isinstance(args, tuple): args = (args,) async_task(func, *args, **options) return iter_group
[ "def", "async_iter", "(", "func", ",", "args_iter", ",", "*", "*", "kwargs", ")", ":", "iter_count", "=", "len", "(", "args_iter", ")", "iter_group", "=", "uuid", "(", ")", "[", "1", "]", "# clean up the kwargs", "options", "=", "kwargs", ".", "get", "...
enqueues a function with iterable arguments
[ "enqueues", "a", "function", "with", "iterable", "arguments" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L395-L417
train
216,781
Koed00/django-q
django_q/tasks.py
_sync
def _sync(pack): """Simulate a package travelling through the cluster.""" task_queue = Queue() result_queue = Queue() task = SignedPackage.loads(pack) task_queue.put(task) task_queue.put('STOP') worker(task_queue, result_queue, Value('f', -1)) result_queue.put('STOP') monitor(result_queue) task_queue.close() task_queue.join_thread() result_queue.close() result_queue.join_thread() return task['id']
python
def _sync(pack): """Simulate a package travelling through the cluster.""" task_queue = Queue() result_queue = Queue() task = SignedPackage.loads(pack) task_queue.put(task) task_queue.put('STOP') worker(task_queue, result_queue, Value('f', -1)) result_queue.put('STOP') monitor(result_queue) task_queue.close() task_queue.join_thread() result_queue.close() result_queue.join_thread() return task['id']
[ "def", "_sync", "(", "pack", ")", ":", "task_queue", "=", "Queue", "(", ")", "result_queue", "=", "Queue", "(", ")", "task", "=", "SignedPackage", ".", "loads", "(", "pack", ")", "task_queue", ".", "put", "(", "task", ")", "task_queue", ".", "put", "...
Simulate a package travelling through the cluster.
[ "Simulate", "a", "package", "travelling", "through", "the", "cluster", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L677-L691
train
216,782
Koed00/django-q
django_q/tasks.py
Iter.append
def append(self, *args): """ add arguments to the set """ self.args.append(args) if self.started: self.started = False return self.length()
python
def append(self, *args): """ add arguments to the set """ self.args.append(args) if self.started: self.started = False return self.length()
[ "def", "append", "(", "self", ",", "*", "args", ")", ":", "self", ".", "args", ".", "append", "(", "args", ")", "if", "self", ".", "started", ":", "self", ".", "started", "=", "False", "return", "self", ".", "length", "(", ")" ]
add arguments to the set
[ "add", "arguments", "to", "the", "set" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/tasks.py#L460-L467
train
216,783
Koed00/django-q
django_q/admin.py
retry_failed
def retry_failed(FailAdmin, request, queryset): """Submit selected tasks back to the queue.""" for task in queryset: async_task(task.func, *task.args or (), hook=task.hook, **task.kwargs or {}) task.delete()
python
def retry_failed(FailAdmin, request, queryset): """Submit selected tasks back to the queue.""" for task in queryset: async_task(task.func, *task.args or (), hook=task.hook, **task.kwargs or {}) task.delete()
[ "def", "retry_failed", "(", "FailAdmin", ",", "request", ",", "queryset", ")", ":", "for", "task", "in", "queryset", ":", "async_task", "(", "task", ".", "func", ",", "*", "task", ".", "args", "or", "(", ")", ",", "hook", "=", "task", ".", "hook", ...
Submit selected tasks back to the queue.
[ "Submit", "selected", "tasks", "back", "to", "the", "queue", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/admin.py#L40-L44
train
216,784
Koed00/django-q
django_q/admin.py
TaskAdmin.get_queryset
def get_queryset(self, request): """Only show successes.""" qs = super(TaskAdmin, self).get_queryset(request) return qs.filter(success=True)
python
def get_queryset(self, request): """Only show successes.""" qs = super(TaskAdmin, self).get_queryset(request) return qs.filter(success=True)
[ "def", "get_queryset", "(", "self", ",", "request", ")", ":", "qs", "=", "super", "(", "TaskAdmin", ",", "self", ")", ".", "get_queryset", "(", "request", ")", "return", "qs", ".", "filter", "(", "success", "=", "True", ")" ]
Only show successes.
[ "Only", "show", "successes", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/admin.py#L26-L29
train
216,785
Koed00/django-q
django_q/admin.py
TaskAdmin.get_readonly_fields
def get_readonly_fields(self, request, obj=None): """Set all fields readonly.""" return list(self.readonly_fields) + [field.name for field in obj._meta.fields]
python
def get_readonly_fields(self, request, obj=None): """Set all fields readonly.""" return list(self.readonly_fields) + [field.name for field in obj._meta.fields]
[ "def", "get_readonly_fields", "(", "self", ",", "request", ",", "obj", "=", "None", ")", ":", "return", "list", "(", "self", ".", "readonly_fields", ")", "+", "[", "field", ".", "name", "for", "field", "in", "obj", ".", "_meta", ".", "fields", "]" ]
Set all fields readonly.
[ "Set", "all", "fields", "readonly", "." ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/admin.py#L35-L37
train
216,786
Koed00/django-q
django_q/cluster.py
save_task
def save_task(task, broker): """ Saves the task package to Django or the cache """ # SAVE LIMIT < 0 : Don't save success if not task.get('save', Conf.SAVE_LIMIT >= 0) and task['success']: return # enqueues next in a chain if task.get('chain', None): django_q.tasks.async_chain(task['chain'], group=task['group'], cached=task['cached'], sync=task['sync'], broker=broker) # SAVE LIMIT > 0: Prune database, SAVE_LIMIT 0: No pruning db.close_old_connections() try: if task['success'] and 0 < Conf.SAVE_LIMIT <= Success.objects.count(): Success.objects.last().delete() # check if this task has previous results if Task.objects.filter(id=task['id'], name=task['name']).exists(): existing_task = Task.objects.get(id=task['id'], name=task['name']) # only update the result if it hasn't succeeded yet if not existing_task.success: existing_task.stopped = task['stopped'] existing_task.result = task['result'] existing_task.success = task['success'] existing_task.save() else: Task.objects.create(id=task['id'], name=task['name'], func=task['func'], hook=task.get('hook'), args=task['args'], kwargs=task['kwargs'], started=task['started'], stopped=task['stopped'], result=task['result'], group=task.get('group'), success=task['success'] ) except Exception as e: logger.error(e)
python
def save_task(task, broker): """ Saves the task package to Django or the cache """ # SAVE LIMIT < 0 : Don't save success if not task.get('save', Conf.SAVE_LIMIT >= 0) and task['success']: return # enqueues next in a chain if task.get('chain', None): django_q.tasks.async_chain(task['chain'], group=task['group'], cached=task['cached'], sync=task['sync'], broker=broker) # SAVE LIMIT > 0: Prune database, SAVE_LIMIT 0: No pruning db.close_old_connections() try: if task['success'] and 0 < Conf.SAVE_LIMIT <= Success.objects.count(): Success.objects.last().delete() # check if this task has previous results if Task.objects.filter(id=task['id'], name=task['name']).exists(): existing_task = Task.objects.get(id=task['id'], name=task['name']) # only update the result if it hasn't succeeded yet if not existing_task.success: existing_task.stopped = task['stopped'] existing_task.result = task['result'] existing_task.success = task['success'] existing_task.save() else: Task.objects.create(id=task['id'], name=task['name'], func=task['func'], hook=task.get('hook'), args=task['args'], kwargs=task['kwargs'], started=task['started'], stopped=task['stopped'], result=task['result'], group=task.get('group'), success=task['success'] ) except Exception as e: logger.error(e)
[ "def", "save_task", "(", "task", ",", "broker", ")", ":", "# SAVE LIMIT < 0 : Don't save success", "if", "not", "task", ".", "get", "(", "'save'", ",", "Conf", ".", "SAVE_LIMIT", ">=", "0", ")", "and", "task", "[", "'success'", "]", ":", "return", "# enque...
Saves the task package to Django or the cache
[ "Saves", "the", "task", "package", "to", "Django", "or", "the", "cache" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/cluster.py#L400-L438
train
216,787
Koed00/django-q
django_q/cluster.py
scheduler
def scheduler(broker=None): """ Creates a task from a schedule at the scheduled time and schedules next run """ if not broker: broker = get_broker() db.close_old_connections() try: for s in Schedule.objects.exclude(repeats=0).filter(next_run__lt=timezone.now()): args = () kwargs = {} # get args, kwargs and hook if s.kwargs: try: # eval should be safe here because dict() kwargs = eval('dict({})'.format(s.kwargs)) except SyntaxError: kwargs = {} if s.args: args = ast.literal_eval(s.args) # single value won't eval to tuple, so: if type(args) != tuple: args = (args,) q_options = kwargs.get('q_options', {}) if s.hook: q_options['hook'] = s.hook # set up the next run time if not s.schedule_type == s.ONCE: next_run = arrow.get(s.next_run) while True: if s.schedule_type == s.MINUTES: next_run = next_run.replace(minutes=+(s.minutes or 1)) elif s.schedule_type == s.HOURLY: next_run = next_run.replace(hours=+1) elif s.schedule_type == s.DAILY: next_run = next_run.replace(days=+1) elif s.schedule_type == s.WEEKLY: next_run = next_run.replace(weeks=+1) elif s.schedule_type == s.MONTHLY: next_run = next_run.replace(months=+1) elif s.schedule_type == s.QUARTERLY: next_run = next_run.replace(months=+3) elif s.schedule_type == s.YEARLY: next_run = next_run.replace(years=+1) if Conf.CATCH_UP or next_run > arrow.utcnow(): break s.next_run = next_run.datetime s.repeats += -1 # send it to the cluster q_options['broker'] = broker q_options['group'] = q_options.get('group', s.name or s.id) kwargs['q_options'] = q_options s.task = django_q.tasks.async_task(s.func, *args, **kwargs) # log it if not s.task: logger.error( _('{} failed to create a task from schedule [{}]').format(current_process().name, s.name or s.id)) else: logger.info( _('{} created a task from schedule [{}]').format(current_process().name, s.name or s.id)) # default behavior is to delete a ONCE schedule if s.schedule_type == s.ONCE: if s.repeats < 0: s.delete() continue # but not if it has a positive repeats s.repeats = 0 # save the schedule s.save() except Exception as e: logger.error(e)
python
def scheduler(broker=None): """ Creates a task from a schedule at the scheduled time and schedules next run """ if not broker: broker = get_broker() db.close_old_connections() try: for s in Schedule.objects.exclude(repeats=0).filter(next_run__lt=timezone.now()): args = () kwargs = {} # get args, kwargs and hook if s.kwargs: try: # eval should be safe here because dict() kwargs = eval('dict({})'.format(s.kwargs)) except SyntaxError: kwargs = {} if s.args: args = ast.literal_eval(s.args) # single value won't eval to tuple, so: if type(args) != tuple: args = (args,) q_options = kwargs.get('q_options', {}) if s.hook: q_options['hook'] = s.hook # set up the next run time if not s.schedule_type == s.ONCE: next_run = arrow.get(s.next_run) while True: if s.schedule_type == s.MINUTES: next_run = next_run.replace(minutes=+(s.minutes or 1)) elif s.schedule_type == s.HOURLY: next_run = next_run.replace(hours=+1) elif s.schedule_type == s.DAILY: next_run = next_run.replace(days=+1) elif s.schedule_type == s.WEEKLY: next_run = next_run.replace(weeks=+1) elif s.schedule_type == s.MONTHLY: next_run = next_run.replace(months=+1) elif s.schedule_type == s.QUARTERLY: next_run = next_run.replace(months=+3) elif s.schedule_type == s.YEARLY: next_run = next_run.replace(years=+1) if Conf.CATCH_UP or next_run > arrow.utcnow(): break s.next_run = next_run.datetime s.repeats += -1 # send it to the cluster q_options['broker'] = broker q_options['group'] = q_options.get('group', s.name or s.id) kwargs['q_options'] = q_options s.task = django_q.tasks.async_task(s.func, *args, **kwargs) # log it if not s.task: logger.error( _('{} failed to create a task from schedule [{}]').format(current_process().name, s.name or s.id)) else: logger.info( _('{} created a task from schedule [{}]').format(current_process().name, s.name or s.id)) # default behavior is to delete a ONCE schedule if s.schedule_type == s.ONCE: if s.repeats < 0: s.delete() continue # but not if it has a positive repeats s.repeats = 0 # save the schedule s.save() except Exception as e: logger.error(e)
[ "def", "scheduler", "(", "broker", "=", "None", ")", ":", "if", "not", "broker", ":", "broker", "=", "get_broker", "(", ")", "db", ".", "close_old_connections", "(", ")", "try", ":", "for", "s", "in", "Schedule", ".", "objects", ".", "exclude", "(", ...
Creates a task from a schedule at the scheduled time and schedules next run
[ "Creates", "a", "task", "from", "a", "schedule", "at", "the", "scheduled", "time", "and", "schedules", "next", "run" ]
c84fd11a67c9a47d821786dfcdc189bb258c6f54
https://github.com/Koed00/django-q/blob/c84fd11a67c9a47d821786dfcdc189bb258c6f54/django_q/cluster.py#L486-L557
train
216,788
google/python-adb
adb/adb_commands.py
AdbCommands._get_service_connection
def _get_service_connection(self, service, service_command=None, create=True, timeout_ms=None): """ Based on the service, get the AdbConnection for that service or create one if it doesnt exist :param service: :param service_command: Additional service parameters to append :param create: If False, dont create a connection if it does not exist :return: """ connection = self._service_connections.get(service, None) if connection: return connection if not connection and not create: return None if service_command: destination_str = b'%s:%s' % (service, service_command) else: destination_str = service connection = self.protocol_handler.Open( self._handle, destination=destination_str, timeout_ms=timeout_ms) self._service_connections.update({service: connection}) return connection
python
def _get_service_connection(self, service, service_command=None, create=True, timeout_ms=None): """ Based on the service, get the AdbConnection for that service or create one if it doesnt exist :param service: :param service_command: Additional service parameters to append :param create: If False, dont create a connection if it does not exist :return: """ connection = self._service_connections.get(service, None) if connection: return connection if not connection and not create: return None if service_command: destination_str = b'%s:%s' % (service, service_command) else: destination_str = service connection = self.protocol_handler.Open( self._handle, destination=destination_str, timeout_ms=timeout_ms) self._service_connections.update({service: connection}) return connection
[ "def", "_get_service_connection", "(", "self", ",", "service", ",", "service_command", "=", "None", ",", "create", "=", "True", ",", "timeout_ms", "=", "None", ")", ":", "connection", "=", "self", ".", "_service_connections", ".", "get", "(", "service", ",",...
Based on the service, get the AdbConnection for that service or create one if it doesnt exist :param service: :param service_command: Additional service parameters to append :param create: If False, dont create a connection if it does not exist :return:
[ "Based", "on", "the", "service", "get", "the", "AdbConnection", "for", "that", "service", "or", "create", "one", "if", "it", "doesnt", "exist" ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L71-L99
train
216,789
google/python-adb
adb/adb_commands.py
AdbCommands.ConnectDevice
def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, **kwargs): """Convenience function to setup a transport handle for the adb device from usb path or serial then connect to it. Args: port_path: The filename of usb port to use. serial: The serial number of the device to use. default_timeout_ms: The default timeout in milliseconds to use. kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle) banner: Connection banner to pass to the remote device rsa_keys: List of AuthSigner subclass instances to be used for authentication. The device can either accept one of these via the Sign method, or we will send the result of GetPublicKey from the first one if the device doesn't accept any of them. auth_timeout_ms: Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this should be low to catch such a case as a failure quickly; while in interactive settings it should be high to allow users to accept the dialog. We default to automation here, so it's low by default. If serial specifies a TCP address:port, then a TCP connection is used instead of a USB connection. """ # If there isnt a handle override (used by tests), build one here if 'handle' in kwargs: self._handle = kwargs.pop('handle') else: # if necessary, convert serial to a unicode string if isinstance(serial, (bytes, bytearray)): serial = serial.decode('utf-8') if serial and ':' in serial: self._handle = common.TcpHandle(serial, timeout_ms=default_timeout_ms) else: self._handle = common.UsbHandle.FindAndOpen( DeviceIsAvailable, port_path=port_path, serial=serial, timeout_ms=default_timeout_ms) self._Connect(**kwargs) return self
python
def ConnectDevice(self, port_path=None, serial=None, default_timeout_ms=None, **kwargs): """Convenience function to setup a transport handle for the adb device from usb path or serial then connect to it. Args: port_path: The filename of usb port to use. serial: The serial number of the device to use. default_timeout_ms: The default timeout in milliseconds to use. kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle) banner: Connection banner to pass to the remote device rsa_keys: List of AuthSigner subclass instances to be used for authentication. The device can either accept one of these via the Sign method, or we will send the result of GetPublicKey from the first one if the device doesn't accept any of them. auth_timeout_ms: Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this should be low to catch such a case as a failure quickly; while in interactive settings it should be high to allow users to accept the dialog. We default to automation here, so it's low by default. If serial specifies a TCP address:port, then a TCP connection is used instead of a USB connection. """ # If there isnt a handle override (used by tests), build one here if 'handle' in kwargs: self._handle = kwargs.pop('handle') else: # if necessary, convert serial to a unicode string if isinstance(serial, (bytes, bytearray)): serial = serial.decode('utf-8') if serial and ':' in serial: self._handle = common.TcpHandle(serial, timeout_ms=default_timeout_ms) else: self._handle = common.UsbHandle.FindAndOpen( DeviceIsAvailable, port_path=port_path, serial=serial, timeout_ms=default_timeout_ms) self._Connect(**kwargs) return self
[ "def", "ConnectDevice", "(", "self", ",", "port_path", "=", "None", ",", "serial", "=", "None", ",", "default_timeout_ms", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# If there isnt a handle override (used by tests), build one here", "if", "'handle'", "in", ...
Convenience function to setup a transport handle for the adb device from usb path or serial then connect to it. Args: port_path: The filename of usb port to use. serial: The serial number of the device to use. default_timeout_ms: The default timeout in milliseconds to use. kwargs: handle: Device handle to use (instance of common.TcpHandle or common.UsbHandle) banner: Connection banner to pass to the remote device rsa_keys: List of AuthSigner subclass instances to be used for authentication. The device can either accept one of these via the Sign method, or we will send the result of GetPublicKey from the first one if the device doesn't accept any of them. auth_timeout_ms: Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this should be low to catch such a case as a failure quickly; while in interactive settings it should be high to allow users to accept the dialog. We default to automation here, so it's low by default. If serial specifies a TCP address:port, then a TCP connection is used instead of a USB connection.
[ "Convenience", "function", "to", "setup", "a", "transport", "handle", "for", "the", "adb", "device", "from", "usb", "path", "or", "serial", "then", "connect", "to", "it", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L101-L144
train
216,790
google/python-adb
adb/adb_commands.py
AdbCommands.Install
def Install(self, apk_path, destination_dir='', replace_existing=True, grant_permissions=False, timeout_ms=None, transfer_progress_callback=None): """Install an apk to the device. Doesn't support verifier file, instead allows destination directory to be overridden. Args: apk_path: Local path to apk to install. destination_dir: Optional destination directory. Use /system/app/ for persistent applications. replace_existing: whether to replace existing application grant_permissions: If True, grant all permissions to the app specified in its manifest timeout_ms: Expected timeout for pushing and installing. transfer_progress_callback: callback method that accepts filename, bytes_written and total_bytes of APK transfer Returns: The pm install output. """ if not destination_dir: destination_dir = '/data/local/tmp/' basename = os.path.basename(apk_path) destination_path = posixpath.join(destination_dir, basename) self.Push(apk_path, destination_path, timeout_ms=timeout_ms, progress_callback=transfer_progress_callback) cmd = ['pm install'] if grant_permissions: cmd.append('-g') if replace_existing: cmd.append('-r') cmd.append('"{}"'.format(destination_path)) ret = self.Shell(' '.join(cmd), timeout_ms=timeout_ms) # Remove the apk rm_cmd = ['rm', destination_path] rmret = self.Shell(' '.join(rm_cmd), timeout_ms=timeout_ms) return ret
python
def Install(self, apk_path, destination_dir='', replace_existing=True, grant_permissions=False, timeout_ms=None, transfer_progress_callback=None): """Install an apk to the device. Doesn't support verifier file, instead allows destination directory to be overridden. Args: apk_path: Local path to apk to install. destination_dir: Optional destination directory. Use /system/app/ for persistent applications. replace_existing: whether to replace existing application grant_permissions: If True, grant all permissions to the app specified in its manifest timeout_ms: Expected timeout for pushing and installing. transfer_progress_callback: callback method that accepts filename, bytes_written and total_bytes of APK transfer Returns: The pm install output. """ if not destination_dir: destination_dir = '/data/local/tmp/' basename = os.path.basename(apk_path) destination_path = posixpath.join(destination_dir, basename) self.Push(apk_path, destination_path, timeout_ms=timeout_ms, progress_callback=transfer_progress_callback) cmd = ['pm install'] if grant_permissions: cmd.append('-g') if replace_existing: cmd.append('-r') cmd.append('"{}"'.format(destination_path)) ret = self.Shell(' '.join(cmd), timeout_ms=timeout_ms) # Remove the apk rm_cmd = ['rm', destination_path] rmret = self.Shell(' '.join(rm_cmd), timeout_ms=timeout_ms) return ret
[ "def", "Install", "(", "self", ",", "apk_path", ",", "destination_dir", "=", "''", ",", "replace_existing", "=", "True", ",", "grant_permissions", "=", "False", ",", "timeout_ms", "=", "None", ",", "transfer_progress_callback", "=", "None", ")", ":", "if", "...
Install an apk to the device. Doesn't support verifier file, instead allows destination directory to be overridden. Args: apk_path: Local path to apk to install. destination_dir: Optional destination directory. Use /system/app/ for persistent applications. replace_existing: whether to replace existing application grant_permissions: If True, grant all permissions to the app specified in its manifest timeout_ms: Expected timeout for pushing and installing. transfer_progress_callback: callback method that accepts filename, bytes_written and total_bytes of APK transfer Returns: The pm install output.
[ "Install", "an", "apk", "to", "the", "device", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L192-L230
train
216,791
google/python-adb
adb/adb_commands.py
AdbCommands.Uninstall
def Uninstall(self, package_name, keep_data=False, timeout_ms=None): """Removes a package from the device. Args: package_name: Package name of target package. keep_data: whether to keep the data and cache directories timeout_ms: Expected timeout for pushing and installing. Returns: The pm uninstall output. """ cmd = ['pm uninstall'] if keep_data: cmd.append('-k') cmd.append('"%s"' % package_name) return self.Shell(' '.join(cmd), timeout_ms=timeout_ms)
python
def Uninstall(self, package_name, keep_data=False, timeout_ms=None): """Removes a package from the device. Args: package_name: Package name of target package. keep_data: whether to keep the data and cache directories timeout_ms: Expected timeout for pushing and installing. Returns: The pm uninstall output. """ cmd = ['pm uninstall'] if keep_data: cmd.append('-k') cmd.append('"%s"' % package_name) return self.Shell(' '.join(cmd), timeout_ms=timeout_ms)
[ "def", "Uninstall", "(", "self", ",", "package_name", ",", "keep_data", "=", "False", ",", "timeout_ms", "=", "None", ")", ":", "cmd", "=", "[", "'pm uninstall'", "]", "if", "keep_data", ":", "cmd", ".", "append", "(", "'-k'", ")", "cmd", ".", "append"...
Removes a package from the device. Args: package_name: Package name of target package. keep_data: whether to keep the data and cache directories timeout_ms: Expected timeout for pushing and installing. Returns: The pm uninstall output.
[ "Removes", "a", "package", "from", "the", "device", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L232-L248
train
216,792
google/python-adb
adb/adb_commands.py
AdbCommands.Push
def Push(self, source_file, device_filename, mtime='0', timeout_ms=None, progress_callback=None, st_mode=None): """Push a file or directory to the device. Args: source_file: Either a filename, a directory or file-like object to push to the device. device_filename: Destination on the device to write to. mtime: Optional, modification time to set on the file. timeout_ms: Expected timeout for any part of the push. st_mode: stat mode for filename progress_callback: callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects """ if isinstance(source_file, str): if os.path.isdir(source_file): self.Shell("mkdir " + device_filename) for f in os.listdir(source_file): self.Push(os.path.join(source_file, f), device_filename + '/' + f, progress_callback=progress_callback) return source_file = open(source_file, "rb") with source_file: connection = self.protocol_handler.Open( self._handle, destination=b'sync:', timeout_ms=timeout_ms) kwargs={} if st_mode is not None: kwargs['st_mode'] = st_mode self.filesync_handler.Push(connection, source_file, device_filename, mtime=int(mtime), progress_callback=progress_callback, **kwargs) connection.Close()
python
def Push(self, source_file, device_filename, mtime='0', timeout_ms=None, progress_callback=None, st_mode=None): """Push a file or directory to the device. Args: source_file: Either a filename, a directory or file-like object to push to the device. device_filename: Destination on the device to write to. mtime: Optional, modification time to set on the file. timeout_ms: Expected timeout for any part of the push. st_mode: stat mode for filename progress_callback: callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects """ if isinstance(source_file, str): if os.path.isdir(source_file): self.Shell("mkdir " + device_filename) for f in os.listdir(source_file): self.Push(os.path.join(source_file, f), device_filename + '/' + f, progress_callback=progress_callback) return source_file = open(source_file, "rb") with source_file: connection = self.protocol_handler.Open( self._handle, destination=b'sync:', timeout_ms=timeout_ms) kwargs={} if st_mode is not None: kwargs['st_mode'] = st_mode self.filesync_handler.Push(connection, source_file, device_filename, mtime=int(mtime), progress_callback=progress_callback, **kwargs) connection.Close()
[ "def", "Push", "(", "self", ",", "source_file", ",", "device_filename", ",", "mtime", "=", "'0'", ",", "timeout_ms", "=", "None", ",", "progress_callback", "=", "None", ",", "st_mode", "=", "None", ")", ":", "if", "isinstance", "(", "source_file", ",", "...
Push a file or directory to the device. Args: source_file: Either a filename, a directory or file-like object to push to the device. device_filename: Destination on the device to write to. mtime: Optional, modification time to set on the file. timeout_ms: Expected timeout for any part of the push. st_mode: stat mode for filename progress_callback: callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects
[ "Push", "a", "file", "or", "directory", "to", "the", "device", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L250-L281
train
216,793
google/python-adb
adb/adb_commands.py
AdbCommands.Pull
def Pull(self, device_filename, dest_file=None, timeout_ms=None, progress_callback=None): """Pull a file from the device. Args: device_filename: Filename on the device to pull. dest_file: If set, a filename or writable file-like object. timeout_ms: Expected timeout for any part of the pull. progress_callback: callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects Returns: The file data if dest_file is not set. Otherwise, True if the destination file exists """ if not dest_file: dest_file = io.BytesIO() elif isinstance(dest_file, str): dest_file = open(dest_file, 'wb') elif isinstance(dest_file, file): pass else: raise ValueError("destfile is of unknown type") conn = self.protocol_handler.Open( self._handle, destination=b'sync:', timeout_ms=timeout_ms) self.filesync_handler.Pull(conn, device_filename, dest_file, progress_callback) conn.Close() if isinstance(dest_file, io.BytesIO): return dest_file.getvalue() else: dest_file.close() if hasattr(dest_file, 'name'): return os.path.exists(dest_file.name) # We don't know what the path is, so we just assume it exists. return True
python
def Pull(self, device_filename, dest_file=None, timeout_ms=None, progress_callback=None): """Pull a file from the device. Args: device_filename: Filename on the device to pull. dest_file: If set, a filename or writable file-like object. timeout_ms: Expected timeout for any part of the pull. progress_callback: callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects Returns: The file data if dest_file is not set. Otherwise, True if the destination file exists """ if not dest_file: dest_file = io.BytesIO() elif isinstance(dest_file, str): dest_file = open(dest_file, 'wb') elif isinstance(dest_file, file): pass else: raise ValueError("destfile is of unknown type") conn = self.protocol_handler.Open( self._handle, destination=b'sync:', timeout_ms=timeout_ms) self.filesync_handler.Pull(conn, device_filename, dest_file, progress_callback) conn.Close() if isinstance(dest_file, io.BytesIO): return dest_file.getvalue() else: dest_file.close() if hasattr(dest_file, 'name'): return os.path.exists(dest_file.name) # We don't know what the path is, so we just assume it exists. return True
[ "def", "Pull", "(", "self", ",", "device_filename", ",", "dest_file", "=", "None", ",", "timeout_ms", "=", "None", ",", "progress_callback", "=", "None", ")", ":", "if", "not", "dest_file", ":", "dest_file", "=", "io", ".", "BytesIO", "(", ")", "elif", ...
Pull a file from the device. Args: device_filename: Filename on the device to pull. dest_file: If set, a filename or writable file-like object. timeout_ms: Expected timeout for any part of the pull. progress_callback: callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects Returns: The file data if dest_file is not set. Otherwise, True if the destination file exists
[ "Pull", "a", "file", "from", "the", "device", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L283-L318
train
216,794
google/python-adb
adb/adb_commands.py
AdbCommands.List
def List(self, device_path): """Return a directory listing of the given path. Args: device_path: Directory to list. """ connection = self.protocol_handler.Open(self._handle, destination=b'sync:') listing = self.filesync_handler.List(connection, device_path) connection.Close() return listing
python
def List(self, device_path): """Return a directory listing of the given path. Args: device_path: Directory to list. """ connection = self.protocol_handler.Open(self._handle, destination=b'sync:') listing = self.filesync_handler.List(connection, device_path) connection.Close() return listing
[ "def", "List", "(", "self", ",", "device_path", ")", ":", "connection", "=", "self", ".", "protocol_handler", ".", "Open", "(", "self", ".", "_handle", ",", "destination", "=", "b'sync:'", ")", "listing", "=", "self", ".", "filesync_handler", ".", "List", ...
Return a directory listing of the given path. Args: device_path: Directory to list.
[ "Return", "a", "directory", "listing", "of", "the", "given", "path", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L328-L337
train
216,795
google/python-adb
adb/adb_commands.py
AdbCommands.Shell
def Shell(self, command, timeout_ms=None): """Run command on the device, returning the output. Args: command: Shell command to run timeout_ms: Maximum time to allow the command to run. """ return self.protocol_handler.Command( self._handle, service=b'shell', command=command, timeout_ms=timeout_ms)
python
def Shell(self, command, timeout_ms=None): """Run command on the device, returning the output. Args: command: Shell command to run timeout_ms: Maximum time to allow the command to run. """ return self.protocol_handler.Command( self._handle, service=b'shell', command=command, timeout_ms=timeout_ms)
[ "def", "Shell", "(", "self", ",", "command", ",", "timeout_ms", "=", "None", ")", ":", "return", "self", ".", "protocol_handler", ".", "Command", "(", "self", ".", "_handle", ",", "service", "=", "b'shell'", ",", "command", "=", "command", ",", "timeout_...
Run command on the device, returning the output. Args: command: Shell command to run timeout_ms: Maximum time to allow the command to run.
[ "Run", "command", "on", "the", "device", "returning", "the", "output", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L367-L376
train
216,796
google/python-adb
adb/adb_commands.py
AdbCommands.StreamingShell
def StreamingShell(self, command, timeout_ms=None): """Run command on the device, yielding each line of output. Args: command: Command to run on the target. timeout_ms: Maximum time to allow the command to run. Yields: The responses from the shell command. """ return self.protocol_handler.StreamingCommand( self._handle, service=b'shell', command=command, timeout_ms=timeout_ms)
python
def StreamingShell(self, command, timeout_ms=None): """Run command on the device, yielding each line of output. Args: command: Command to run on the target. timeout_ms: Maximum time to allow the command to run. Yields: The responses from the shell command. """ return self.protocol_handler.StreamingCommand( self._handle, service=b'shell', command=command, timeout_ms=timeout_ms)
[ "def", "StreamingShell", "(", "self", ",", "command", ",", "timeout_ms", "=", "None", ")", ":", "return", "self", ".", "protocol_handler", ".", "StreamingCommand", "(", "self", ".", "_handle", ",", "service", "=", "b'shell'", ",", "command", "=", "command", ...
Run command on the device, yielding each line of output. Args: command: Command to run on the target. timeout_ms: Maximum time to allow the command to run. Yields: The responses from the shell command.
[ "Run", "command", "on", "the", "device", "yielding", "each", "line", "of", "output", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L378-L390
train
216,797
google/python-adb
adb/adb_commands.py
AdbCommands.InteractiveShell
def InteractiveShell(self, cmd=None, strip_cmd=True, delim=None, strip_delim=True): """Get stdout from the currently open interactive shell and optionally run a command on the device, returning all output. Args: cmd: Optional. Command to run on the target. strip_cmd: Optional (default True). Strip command name from stdout. delim: Optional. Delimiter to look for in the output to know when to stop expecting more output (usually the shell prompt) strip_delim: Optional (default True): Strip the provided delimiter from the output Returns: The stdout from the shell command. """ conn = self._get_service_connection(b'shell:') return self.protocol_handler.InteractiveShellCommand( conn, cmd=cmd, strip_cmd=strip_cmd, delim=delim, strip_delim=strip_delim)
python
def InteractiveShell(self, cmd=None, strip_cmd=True, delim=None, strip_delim=True): """Get stdout from the currently open interactive shell and optionally run a command on the device, returning all output. Args: cmd: Optional. Command to run on the target. strip_cmd: Optional (default True). Strip command name from stdout. delim: Optional. Delimiter to look for in the output to know when to stop expecting more output (usually the shell prompt) strip_delim: Optional (default True): Strip the provided delimiter from the output Returns: The stdout from the shell command. """ conn = self._get_service_connection(b'shell:') return self.protocol_handler.InteractiveShellCommand( conn, cmd=cmd, strip_cmd=strip_cmd, delim=delim, strip_delim=strip_delim)
[ "def", "InteractiveShell", "(", "self", ",", "cmd", "=", "None", ",", "strip_cmd", "=", "True", ",", "delim", "=", "None", ",", "strip_delim", "=", "True", ")", ":", "conn", "=", "self", ".", "_get_service_connection", "(", "b'shell:'", ")", "return", "s...
Get stdout from the currently open interactive shell and optionally run a command on the device, returning all output. Args: cmd: Optional. Command to run on the target. strip_cmd: Optional (default True). Strip command name from stdout. delim: Optional. Delimiter to look for in the output to know when to stop expecting more output (usually the shell prompt) strip_delim: Optional (default True): Strip the provided delimiter from the output Returns: The stdout from the shell command.
[ "Get", "stdout", "from", "the", "currently", "open", "interactive", "shell", "and", "optionally", "run", "a", "command", "on", "the", "device", "returning", "all", "output", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/adb_commands.py#L401-L419
train
216,798
google/python-adb
adb/common.py
InterfaceMatcher
def InterfaceMatcher(clazz, subclass, protocol): """Returns a matcher that returns the setting with the given interface.""" interface = (clazz, subclass, protocol) def Matcher(device): for setting in device.iterSettings(): if GetInterface(setting) == interface: return setting return Matcher
python
def InterfaceMatcher(clazz, subclass, protocol): """Returns a matcher that returns the setting with the given interface.""" interface = (clazz, subclass, protocol) def Matcher(device): for setting in device.iterSettings(): if GetInterface(setting) == interface: return setting return Matcher
[ "def", "InterfaceMatcher", "(", "clazz", ",", "subclass", ",", "protocol", ")", ":", "interface", "=", "(", "clazz", ",", "subclass", ",", "protocol", ")", "def", "Matcher", "(", "device", ")", ":", "for", "setting", "in", "device", ".", "iterSettings", ...
Returns a matcher that returns the setting with the given interface.
[ "Returns", "a", "matcher", "that", "returns", "the", "setting", "with", "the", "given", "interface", "." ]
d9b94b2dda555c14674c19806debb8449c0e9652
https://github.com/google/python-adb/blob/d9b94b2dda555c14674c19806debb8449c0e9652/adb/common.py#L40-L49
train
216,799