repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_edge_configuration
python
def add_edge_configuration(self, param_name, edge, param_value): if param_name not in self.config['edges']: self.config['edges'][param_name] = {edge: param_value} else: self.config['edges'][param_name][edge] = param_value
Set a parameter for a given edge :param param_name: parameter identifier (as specified by the chosen model) :param edge: edge identifier :param param_value: parameter value
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L95-L106
null
class Configuration(object): """ Configuration Object """ def __init__(self): self.config = { 'nodes': {}, 'edges': {}, 'model': {}, 'status': {} } def get_nodes_configuration(self): """ Nodes configurations ...
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_edge_set_configuration
python
def add_edge_set_configuration(self, param_name, edge_to_value): for edge, val in future.utils.iteritems(edge_to_value): self.add_edge_configuration(param_name, edge, val)
Set Edges parameter :param param_name: parameter identifier (as specified by the chosen model) :param edge_to_value: dictionary mapping each edge a parameter value
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L108-L116
[ "def add_edge_configuration(self, param_name, edge, param_value):\n \"\"\"\n Set a parameter for a given edge\n\n :param param_name: parameter identifier (as specified by the chosen model)\n :param edge: edge identifier\n :param param_value: parameter value\n \"\"\"\n if param_name not in self....
class Configuration(object): """ Configuration Object """ def __init__(self): self.config = { 'nodes': {}, 'edges': {}, 'model': {}, 'status': {} } def get_nodes_configuration(self): """ Nodes configurations ...
GiulioRossetti/ndlib
ndlib/models/opinions/SznajdModel.py
SznajdModel.iteration
python
def iteration(self, node_status=True): # One iteration changes the opinion of several voters using the following procedure: # - select randomly one voter (speaker 1) # - select randomly one of its neighbours (speaker 2) # - if the two voters agree, their neighbours take their opinion ...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/SznajdModel.py#L28-L95
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n", "def status_delt...
class SznajdModel(DiffusionModel): """ """ def __init__(self, graph): """ Model Constructor :param graph: A networkx graph object """ super(self.__class__, self).__init__(graph) self.available_statuses = { "Susceptible": 0, ...
GiulioRossetti/ndlib
ndlib/utils.py
multi_runs
python
def multi_runs(model, execution_number=1, iteration_number=50, infection_sets=None, nprocesses=multiprocessing.cpu_count()): if nprocesses > multiprocessing.cpu_count(): nprocesses = multiprocessing.cpu_count() executions = [] if infection_sets is not None: if len(infection...
Multiple executions of a given model varying the initial set of infected nodes :param model: a configured diffusion model :param execution_number: number of instantiations :param iteration_number: number of iterations per execution :param infection_sets: predefined set of infected nodes sets :param...
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/utils.py#L15-L58
null
import multiprocessing from contextlib import closing import copy import past __author__ = 'Giulio Rossetti' __license__ = "BSD-2-Clause" __email__ = "giulio.rossetti@gmail.com" class InitializationException(Exception): """Initialization Exception""" def __execute(model, iteration_number): """ Execute...
GiulioRossetti/ndlib
ndlib/utils.py
__execute
python
def __execute(model, iteration_number): iterations = model.iteration_bunch(iteration_number, False) trends = model.build_trends(iterations)[0] del iterations del model return trends
Execute a simulation model :param model: a configured diffusion model :param iteration_number: number of iterations :return: computed trends
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/utils.py#L61-L73
null
import multiprocessing from contextlib import closing import copy import past __author__ = 'Giulio Rossetti' __license__ = "BSD-2-Clause" __email__ = "giulio.rossetti@gmail.com" class InitializationException(Exception): """Initialization Exception""" def multi_runs(model, execution_number=1, iteration_number=5...
GiulioRossetti/ndlib
ndlib/models/DynamicCompostiteModel.py
DynamicCompositeModel.iteration
python
def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actual_iteration += 1 delta, node_count, status...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/DynamicCompostiteModel.py#L30-L70
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n", "def status_delt...
class DynamicCompositeModel(DynamicDiffusionModel): def __init__(self, graph): """ Model Constructor :param graph: A networkx graph object """ super(self.__class__, self).__init__(graph) self.available_statuses = {} self.compartment = {} se...
GiulioRossetti/ndlib
ndlib/viz/bokeh/MultiPlot.py
MultiPlot.plot
python
def plot(self, ncols=2): grid = gridplot(self.plots, ncols=ncols) return grid
:param ncols: Number of grid columns :return: a bokeh figure image
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/viz/bokeh/MultiPlot.py#L19-L25
null
class MultiPlot(object): def __init__(self): self.plots = [] def add_plot(self, plot): """ :param plot: The bokeh plot to add to the grid """ self.plots.append(plot)
GiulioRossetti/ndlib
ndlib/models/opinions/MajorityRuleModel.py
MajorityRuleModel.iteration
python
def iteration(self, node_status=True): # One iteration changes the opinion of at most q voters using the following procedure: # - select randomly q voters # - compute majority opinion # - if tie all agents take opinion +1 # - if not tie, all agents take majority opinion ...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/MajorityRuleModel.py#L38-L99
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n", "def status_delt...
class MajorityRuleModel(DiffusionModel): """ """ def __init__(self, graph): """ Model Constructor :param graph: A networkx graph object """ super(self.__class__, self).__init__(graph) self.available_statuses = { "Susceptible": 0, ...
GiulioRossetti/ndlib
ndlib/models/dynamic/DynSIModel.py
DynSIModel.iteration
python
def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} # streaming if self.stream_execution: u, v = list(self.graph.edges())[0] u...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/dynamic/DynSIModel.py#L43-L113
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n", "def status_delt...
class DynSIModel(DynamicDiffusionModel): """ Model Parameters to be specified via ModelConfig :param beta: The infection rate (float value in [0,1]) """ def __init__(self, graph): """ Model Constructor :param graph: A dynetx graph object """ supe...
GiulioRossetti/ndlib
ndlib/models/epidemics/IndependentCascadesModel.py
IndependentCascadesModel.iteration
python
def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actual_iteration += 1 delta, node_count, status...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/epidemics/IndependentCascadesModel.py#L46-L101
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n", "def status_delt...
class IndependentCascadesModel(DiffusionModel): """ Edge Parameters to be specified via ModelConfig :param threshold: The edge threshold. As default a value of 0.1 is assumed for all edges. """ def __init__(self, graph): """ Model Constructor :param graph...
GiulioRossetti/ndlib
ndlib/models/epidemics/KerteszThresholdModel.py
KerteszThresholdModel.iteration
python
def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: if min(actual_status.values()) == 0: number_nod...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/epidemics/KerteszThresholdModel.py#L62-L136
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n", "def status_delt...
class KerteszThresholdModel(DiffusionModel): """ Node/Model Parameters to be specified via ModelConfig :param threshold: The node threshold. As default a value of 0.1 is assumed for all nodes. :param adopter_rate: The probability of spontaneous adoptions. Defaults value 0. :param p...
GiulioRossetti/ndlib
ndlib/models/dynamic/DynProfileThresholdModel.py
DynProfileThresholdModel.iteration
python
def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} # streaming if self.stream_execution: raise ValueError("Streaming network not allowed."...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/dynamic/DynProfileThresholdModel.py#L67-L135
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n", "def status_delt...
class DynProfileThresholdModel(DynamicDiffusionModel): """ Node Parameters to be specified via ModelConfig :param profile: The node profile. As default a value of 0.1 is assumed for all nodes. :param threshold: The node threshold. As default a value of 0.1 is assumed for all nodes. """ ...
GiulioRossetti/ndlib
ndlib/models/opinions/AlgorithmicBiasModel.py
AlgorithmicBiasModel.set_initial_status
python
def set_initial_status(self, configuration=None): super(AlgorithmicBiasModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = np.random.random_sample() self.initial_status = self.status.copy()
Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values.
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/AlgorithmicBiasModel.py#L54-L64
[ "def set_initial_status(self, configuration):\n \"\"\"\n Set the initial model configuration\n\n :param configuration: a ```ndlib.models.ModelConfig.Configuration``` object\n \"\"\"\n\n self.__validate_configuration(configuration)\n\n nodes_cfg = configuration.get_nodes_configuration()\n # Set ...
class AlgorithmicBiasModel(DiffusionModel): """ Model Parameters to be specified via ModelConfig :param epsilon: bounded confidence threshold from the Deffuant model, in [0,1] :param gamma: strength of the algorithmic bias, positive, real Node states are continuous values in [0,1]. The initia...
GiulioRossetti/ndlib
ndlib/models/opinions/AlgorithmicBiasModel.py
AlgorithmicBiasModel.iteration
python
def iteration(self, node_status=True): # One iteration changes the opinion of N agent pairs using the following procedure: # - first one agent is selected # - then a second agent is selected based on a probability that decreases with the distance to the first agent # - if the two agents ...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/AlgorithmicBiasModel.py#L77-L141
[ "def clean_initial_status(self, valid_status=None):\n for n, s in future.utils.iteritems(self.status):\n if s > 1 or s < 0:\n self.status[n] = 0\n", "def status_delta(self, actual_status):\n \"\"\"\n Compute the point-to-point variations for each status w.r.t. the previous system config...
class AlgorithmicBiasModel(DiffusionModel): """ Model Parameters to be specified via ModelConfig :param epsilon: bounded confidence threshold from the Deffuant model, in [0,1] :param gamma: strength of the algorithmic bias, positive, real Node states are continuous values in [0,1]. The initia...
GiulioRossetti/ndlib
ndlib/models/epidemics/ThresholdModel.py
ThresholdModel.iteration
python
def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actual_iteration += 1 delta, node_count, statu...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
train
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/epidemics/ThresholdModel.py#L44-L90
[ "def clean_initial_status(self, valid_status=None):\n \"\"\"\n Check the consistency of initial status\n :param valid_status: valid node configurations\n \"\"\"\n for n, s in future.utils.iteritems(self.status):\n if s not in valid_status:\n self.status[n] = 0\n", "def status_delt...
class ThresholdModel(DiffusionModel): """ Node Parameters to be specified via ModelConfig :param threshold: The node threshold. If not specified otherwise a value of 0.1 is assumed for all nodes. """ def __init__(self, graph): """ Model Constructor :param ...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/bninception.py
bninception
python
def bninception(num_classes=1000, pretrained='imagenet'): r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper. """ model = BNInception(num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['bninception'][pretrained] assert n...
r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper.
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/bninception.py#L497-L511
null
from __future__ import print_function, division, absolute_import import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo import os import sys __all__ = ['BNInception', 'bninception'] pretrained_settings = { 'bninception': { 'imagenet': { # W...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/fbresnet/resnet152_load.py
conv3x3
python
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
3x3 convolution with padding
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L20-L23
null
from __future__ import print_function, division, absolute_import import torch.nn as nn import math import torch.utils.model_zoo as model_zoo __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c10...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/fbresnet/resnet152_load.py
resnet18
python
def resnet18(pretrained=False, **kwargs): model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L160-L169
null
from __future__ import print_function, division, absolute_import import torch.nn as nn import math import torch.utils.model_zoo as model_zoo __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c10...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/fbresnet/resnet152_load.py
resnet50
python
def resnet50(pretrained=False, **kwargs): model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L184-L193
null
from __future__ import print_function, division, absolute_import import torch.nn as nn import math import torch.utils.model_zoo as model_zoo __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c10...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/nasnet_mobile.py
nasnetamobile
python
def nasnetamobile(num_classes=1000, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetamobile'][pretrained] assert num_classes == settings['num_classes'], \ ...
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/nasnet_mobile.py#L618-L652
null
""" NASNet Mobile Thanks to Anastasiia (https://github.com/DagnyT) for the great help, support and motivation! ------------------------------------------------------------------------------------ Architecture | Top-1 Acc | Top-5 Acc | Multiply-Adds | Params (M) ------------------------------------------...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/cafferesnet.py
cafferesnet101
python
def cafferesnet101(num_classes=1000, pretrained='imagenet'): model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['cafferesnet101'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should...
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/cafferesnet.py#L168-L184
null
from __future__ import print_function, division, absolute_import import math import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo pretrained_settings = { 'cafferesnet101': { 'imagenet': { 'url': 'http://data.lip6.fr/cadene/pretrainedmodels...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/fbresnet.py
fbresnet152
python
def fbresnet152(num_classes=1000, pretrained='imagenet'): model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['fbresnet152'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be ...
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet.py#L216-L233
null
from __future__ import print_function, division, absolute_import import torch.nn as nn import torch.nn.functional as F import math import torch.utils.model_zoo as model_zoo __all__ = ['FBResNet', #'fbresnet18', 'fbresnet34', 'fbresnet50', 'fbresnet101', 'fbresnet152'] pretrained_settings = { ...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
alexnet
python
def alexnet(num_classes=1000, pretrained='imagenet'): r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. """ # https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py model = models.alexnet(pretrained=False) if pretrained ...
r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L168-L178
[ "def load_pretrained(model, num_classes, settings):\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n state_dict = model_zoo.load_url(settings['url'])\n state_dict = update_state_dict(state_dict)\n model.lo...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import torchvision.models as models import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import types import re ################################################################# # You can find the definitions ...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
densenet121
python
def densenet121(num_classes=1000, pretrained='imagenet'): r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet121(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet121'][...
r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L205-L214
[ "def load_pretrained(model, num_classes, settings):\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n state_dict = model_zoo.load_url(settings['url'])\n state_dict = update_state_dict(state_dict)\n model.lo...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import torchvision.models as models import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import types import re ################################################################# # You can find the definitions ...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
inceptionv3
python
def inceptionv3(num_classes=1000, pretrained='imagenet'): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. """ model = models.inception_v3(pretrained=False) if pretrained is not None: settings = pretrai...
r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_.
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L252-L309
[ "def load_pretrained(model, num_classes, settings):\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n state_dict = model_zoo.load_url(settings['url'])\n state_dict = update_state_dict(state_dict)\n model.lo...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import torchvision.models as models import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import types import re ################################################################# # You can find the definitions ...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
resnet50
python
def resnet50(num_classes=1000, pretrained='imagenet'): model = models.resnet50(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet50'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_resnets(model) return model
Constructs a ResNet-50 model.
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L368-L376
[ "def load_pretrained(model, num_classes, settings):\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n state_dict = model_zoo.load_url(settings['url'])\n state_dict = update_state_dict(state_dict)\n model.lo...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import torchvision.models as models import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import types import re ################################################################# # You can find the definitions ...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
squeezenet1_0
python
def squeezenet1_0(num_classes=1000, pretrained='imagenet'): r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. """ model = models.squeezenet1_0(pretrained=False) if pretraine...
r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper.
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L428-L438
[ "def load_pretrained(model, num_classes, settings):\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n state_dict = model_zoo.load_url(settings['url'])\n state_dict = update_state_dict(state_dict)\n model.lo...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import torchvision.models as models import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import types import re ################################################################# # You can find the definitions ...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
vgg11
python
def vgg11(num_classes=1000, pretrained='imagenet'): model = models.vgg11(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg11'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
VGG 11-layer model (configuration "A")
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L495-L503
[ "def load_pretrained(model, num_classes, settings):\n assert num_classes == settings['num_classes'], \\\n \"num_classes should be {}, but is {}\".format(settings['num_classes'], num_classes)\n state_dict = model_zoo.load_url(settings['url'])\n state_dict = update_state_dict(state_dict)\n model.lo...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import import torchvision.models as models import torch.utils.model_zoo as model_zoo import torch.nn.functional as F import types import re ################################################################# # You can find the definitions ...
Cadene/pretrained-models.pytorch
examples/imagenet_eval.py
adjust_learning_rate
python
def adjust_learning_rate(optimizer, epoch): lr = args.lr * (0.1 ** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr
Sets the learning rate to the initial LR decayed by 10 every 30 epochs
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/examples/imagenet_eval.py#L280-L284
null
from __future__ import print_function, division, absolute_import import argparse import os import shutil import time import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torchvision.transforms as transforms import torchvision...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/nasnet.py
nasnetalarge
python
def nasnetalarge(num_classes=1001, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetalarge'][pretrained] assert num_classes == settings['num_classes'], \ ...
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/nasnet.py#L608-L635
null
from __future__ import print_function, division, absolute_import import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from torch.autograd import Variable pretrained_settings = { 'nasnetalarge': { 'imagenet': { 'url': 'http://data.lip6.fr/c...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/dpn.py
adaptive_avgmax_pool2d
python
def adaptive_avgmax_pool2d(x, pool_type='avg', padding=0, count_include_pad=False): if pool_type == 'avgmaxc': x = torch.cat([ F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad), F.max_pool2d(x, kernel_size=(x.si...
Selectable global pooling function with dynamic input kernel size
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/dpn.py#L407-L428
null
""" PyTorch implementation of DualPathNetworks Ported to PyTorch by [Ross Wightman](https://github.com/rwightman/pytorch-dpn-pretrained) Based on original MXNet implementation https://github.com/cypw/DPNs with many ideas from another PyTorch implementation https://github.com/oyam/pytorch-DPNs. This implementation is ...
Cadene/pretrained-models.pytorch
pretrainedmodels/datasets/utils.py
download_url
python
def download_url(url, destination=None, progress_bar=True): def my_hook(t): last_b = [0] def inner(b=1, bsize=1, tsize=None): if tsize is not None: t.total = tsize if b > 0: t.update((b - last_b[0]) * bsize) last_b[0] = b ...
Download a URL to a local file. Parameters ---------- url : str The URL to download. destination : str, None The destination of the file. If None is given the file is saved to a temporary directory. progress_bar : bool Whether to show a command-line progress bar while downlo...
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L45-L83
[ "def my_hook(t):\n last_b = [0]\n\n def inner(b=1, bsize=1, tsize=None):\n if tsize is not None:\n t.total = tsize\n if b > 0:\n t.update((b - last_b[0]) * bsize)\n last_b[0] = b\n\n return inner\n" ]
from __future__ import print_function, division, absolute_import import math from six.moves.urllib.request import urlretrieve import torch from PIL import Image from tqdm import tqdm def load_imagenet_classes(path_synsets='data/imagenet_synsets.txt', path_classes='data/imagenet_classes.txt')...
Cadene/pretrained-models.pytorch
pretrainedmodels/datasets/utils.py
AveragePrecisionMeter.add
python
def add(self, output, target): if not torch.is_tensor(output): output = torch.from_numpy(output) if not torch.is_tensor(target): target = torch.from_numpy(target) if output.dim() == 1: output = output.view(-1, 1) else: assert output.dim() ...
Args: output (Tensor): NxK tensor that for each of the N examples indicates the probability of the example belonging to each of the K classes, according to the model. The probabilities should sum to one over all classes target (Tensor): binary NxK ...
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L110-L156
null
class AveragePrecisionMeter(object): """ The APMeter measures the average precision per class. The APMeter is designed to operate on `NxK` Tensors `output` and `target`, and optionally a `Nx1` Tensor weight where (1) the `output` contains model output scores for `N` examples and `K` classes that oug...
Cadene/pretrained-models.pytorch
pretrainedmodels/datasets/utils.py
AveragePrecisionMeter.value
python
def value(self): if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) rg = torch.arange(1, self.scores.size(0)).float() # compute average precision for each class for k in range(self.scores.size(1)): # sort scores score...
Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L158-L177
[ "def average_precision(output, target, difficult_examples=True):\n\n # sort examples\n sorted, indices = torch.sort(output, dim=0, descending=True)\n\n # Computes prec@i\n pos_count = 0.\n total_count = 0.\n precision_at_i = 0.\n for i in indices:\n label = target[i]\n if difficul...
class AveragePrecisionMeter(object): """ The APMeter measures the average precision per class. The APMeter is designed to operate on `NxK` Tensors `output` and `target`, and optionally a `Nx1` Tensor weight where (1) the `output` contains model output scores for `N` examples and `K` classes that oug...
Cadene/pretrained-models.pytorch
pretrainedmodels/models/polynet.py
polynet
python
def polynet(num_classes=1000, pretrained='imagenet'): if pretrained: settings = pretrained_settings['polynet'][pretrained] assert num_classes == settings['num_classes'], \ 'num_classes should be {}, but is {}'.format( settings['num_classes'], num_classes) model = ...
PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725
train
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/polynet.py#L461-L480
null
from __future__ import print_function, division, absolute_import import torch import torch.nn as nn from torch.utils import model_zoo __all__ = ['PolyNet', 'polynet'] pretrained_settings = { 'polynet': { 'imagenet': { 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/polynet-f71d82a5.pth', ...
fmfn/BayesianOptimization
examples/async_optimization.py
BayesianOptimizationHandler.post
python
def post(self): body = tornado.escape.json_decode(self.request.body) try: self._bo.register( params=body["params"], target=body["target"], ) print("BO has registered: {} points.".format(len(self._bo.space)), end="\n\n") except ...
Deal with incoming requests.
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/examples/async_optimization.py#L42-L57
null
class BayesianOptimizationHandler(RequestHandler): """Basic functionality for NLP handlers.""" _bo = BayesianOptimization( f=black_box_function, pbounds={"x": (-4, 4), "y": (-3, 3)} ) _uf = UtilityFunction(kind="ucb", kappa=3, xi=1)
fmfn/BayesianOptimization
bayes_opt/bayesian_optimization.py
BayesianOptimization.register
python
def register(self, params, target): self._space.register(params, target) self.dispatch(Events.OPTMIZATION_STEP)
Expect observation with known target
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/bayesian_optimization.py#L102-L105
[ "def dispatch(self, event):\n for _, callback in self.get_subscribers(event).items():\n callback(event, self)\n", "def register(self, params, target):\n \"\"\"\n Append a point and its target value to the known data.\n\n Parameters\n ----------\n x : ndarray\n a single point, with ...
class BayesianOptimization(Observable): def __init__(self, f, pbounds, random_state=None, verbose=2): """""" self._random_state = ensure_rng(random_state) # Data structure containing the function to be optimized, the bounds of # its domain, and a record of the evaluations we have do...
fmfn/BayesianOptimization
bayes_opt/bayesian_optimization.py
BayesianOptimization.probe
python
def probe(self, params, lazy=True): if lazy: self._queue.add(params) else: self._space.probe(params) self.dispatch(Events.OPTMIZATION_STEP)
Probe target of x
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/bayesian_optimization.py#L107-L113
[ "def add(self, obj):\n \"\"\"Add object to end of queue.\"\"\"\n self._queue.append(obj)\n", "def dispatch(self, event):\n for _, callback in self.get_subscribers(event).items():\n callback(event, self)\n", "def probe(self, params):\n \"\"\"\n Evaulates a single point x, to obtain the valu...
class BayesianOptimization(Observable): def __init__(self, f, pbounds, random_state=None, verbose=2): """""" self._random_state = ensure_rng(random_state) # Data structure containing the function to be optimized, the bounds of # its domain, and a record of the evaluations we have do...
fmfn/BayesianOptimization
bayes_opt/bayesian_optimization.py
BayesianOptimization.suggest
python
def suggest(self, utility_function): if len(self._space) == 0: return self._space.array_to_params(self._space.random_sample()) # Sklearn's GP throws a large number of warnings at times, but # we don't really need to see them here. with warnings.catch_warnings(): ...
Most promissing point to probe next
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/bayesian_optimization.py#L115-L135
[ "def acq_max(ac, gp, y_max, bounds, random_state, n_warmup=100000, n_iter=250):\n \"\"\"\n A function to find the maximum of the acquisition function\n\n It uses a combination of random sampling (cheap) and the 'L-BFGS-B'\n optimization method. First by sampling `n_warmup` (1e5) points at random,\n a...
class BayesianOptimization(Observable): def __init__(self, f, pbounds, random_state=None, verbose=2): """""" self._random_state = ensure_rng(random_state) # Data structure containing the function to be optimized, the bounds of # its domain, and a record of the evaluations we have do...
fmfn/BayesianOptimization
bayes_opt/bayesian_optimization.py
BayesianOptimization._prime_queue
python
def _prime_queue(self, init_points): if self._queue.empty and self._space.empty: init_points = max(init_points, 1) for _ in range(init_points): self._queue.add(self._space.random_sample())
Make sure there's something in the queue at the very beginning.
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/bayesian_optimization.py#L137-L143
[ "def add(self, obj):\n \"\"\"Add object to end of queue.\"\"\"\n self._queue.append(obj)\n", "def random_sample(self):\n \"\"\"\n Creates random points within the bounds of the space.\n\n Returns\n ----------\n data: ndarray\n [num x dim] array points with dimensions corresponding to `...
class BayesianOptimization(Observable): def __init__(self, f, pbounds, random_state=None, verbose=2): """""" self._random_state = ensure_rng(random_state) # Data structure containing the function to be optimized, the bounds of # its domain, and a record of the evaluations we have do...
fmfn/BayesianOptimization
bayes_opt/bayesian_optimization.py
BayesianOptimization.maximize
python
def maximize(self, init_points=5, n_iter=25, acq='ucb', kappa=2.576, xi=0.0, **gp_params): self._prime_subscriptions() self.dispatch(Events.OPTMIZATION_START) self._prime_queue(init_points) ...
Mazimize your function
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/bayesian_optimization.py#L152-L176
[ "def dispatch(self, event):\n for _, callback in self.get_subscribers(event).items():\n callback(event, self)\n", "def probe(self, params, lazy=True):\n \"\"\"Probe target of x\"\"\"\n if lazy:\n self._queue.add(params)\n else:\n self._space.probe(params)\n self.dispatch(Ev...
class BayesianOptimization(Observable): def __init__(self, f, pbounds, random_state=None, verbose=2): """""" self._random_state = ensure_rng(random_state) # Data structure containing the function to be optimized, the bounds of # its domain, and a record of the evaluations we have do...
fmfn/BayesianOptimization
bayes_opt/target_space.py
TargetSpace.register
python
def register(self, params, target): x = self._as_array(params) if x in self: raise KeyError('Data point {} is not unique'.format(x)) # Insert data into unique dictionary self._cache[_hashable(x.ravel())] = target self._params = np.concatenate([self._params, x.reshap...
Append a point and its target value to the known data. Parameters ---------- x : ndarray a single point, with len(x) == self.dim y : float target function value Raises ------ KeyError: if the point is not unique Note...
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/target_space.py#L126-L167
[ "def _hashable(x):\n \"\"\" ensure that an point is hashable by a python dict \"\"\"\n return tuple(map(float, x))\n", "def _as_array(self, x):\n try:\n x = np.asarray(x, dtype=float)\n except TypeError:\n x = self.params_to_array(x)\n\n x = x.ravel()\n try:\n assert x.size ...
class TargetSpace(object): """ Holds the param-space coordinates (X) and target values (Y) Allows for constant-time appends while ensuring no duplicates are added Example ------- >>> def target_func(p1, p2): >>> return p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> spa...
fmfn/BayesianOptimization
bayes_opt/target_space.py
TargetSpace.probe
python
def probe(self, params): x = self._as_array(params) try: target = self._cache[_hashable(x)] except KeyError: params = dict(zip(self._keys, x)) target = self.target_func(**params) self.register(x, target) return target
Evaulates a single point x, to obtain the value y and then records them as observations. Notes ----- If x has been previously seen returns a cached value of y. Parameters ---------- x : ndarray a single point, with len(x) == self.dim Returns...
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/target_space.py#L169-L196
[ "def _hashable(x):\n \"\"\" ensure that an point is hashable by a python dict \"\"\"\n return tuple(map(float, x))\n", "def target_func(**kwargs):\n # arbitrary target func\n return sum(kwargs.values())\n", "def _as_array(self, x):\n try:\n x = np.asarray(x, dtype=float)\n except TypeEr...
class TargetSpace(object): """ Holds the param-space coordinates (X) and target values (Y) Allows for constant-time appends while ensuring no duplicates are added Example ------- >>> def target_func(p1, p2): >>> return p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> spa...
fmfn/BayesianOptimization
bayes_opt/target_space.py
TargetSpace.random_sample
python
def random_sample(self): # TODO: support integer, category, and basic scipy.optimize constraints data = np.empty((1, self.dim)) for col, (lower, upper) in enumerate(self._bounds): data.T[col] = self.random_state.uniform(lower, upper, size=1) return data.ravel()
Creates random points within the bounds of the space. Returns ---------- data: ndarray [num x dim] array points with dimensions corresponding to `self._keys` Example ------- >>> target_func = lambda p1, p2: p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': ...
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/target_space.py#L198-L219
null
class TargetSpace(object): """ Holds the param-space coordinates (X) and target values (Y) Allows for constant-time appends while ensuring no duplicates are added Example ------- >>> def target_func(p1, p2): >>> return p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> spa...
fmfn/BayesianOptimization
bayes_opt/target_space.py
TargetSpace.max
python
def max(self): try: res = { 'target': self.target.max(), 'params': dict( zip(self.keys, self.params[self.target.argmax()]) ) } except ValueError: res = {} return res
Get maximum target value found and corresponding parametes.
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/target_space.py#L221-L232
null
class TargetSpace(object): """ Holds the param-space coordinates (X) and target values (Y) Allows for constant-time appends while ensuring no duplicates are added Example ------- >>> def target_func(p1, p2): >>> return p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> spa...
fmfn/BayesianOptimization
bayes_opt/target_space.py
TargetSpace.res
python
def res(self): params = [dict(zip(self.keys, p)) for p in self.params] return [ {"target": target, "params": param} for target, param in zip(self.target, params) ]
Get all target values found and corresponding parametes.
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/target_space.py#L234-L241
null
class TargetSpace(object): """ Holds the param-space coordinates (X) and target values (Y) Allows for constant-time appends while ensuring no duplicates are added Example ------- >>> def target_func(p1, p2): >>> return p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> spa...
fmfn/BayesianOptimization
bayes_opt/target_space.py
TargetSpace.set_bounds
python
def set_bounds(self, new_bounds): for row, key in enumerate(self.keys): if key in new_bounds: self._bounds[row] = new_bounds[key]
A method that allows changing the lower and upper searching bounds Parameters ---------- new_bounds : dict A dictionary with the parameter name and its new bounds
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/target_space.py#L243-L254
null
class TargetSpace(object): """ Holds the param-space coordinates (X) and target values (Y) Allows for constant-time appends while ensuring no duplicates are added Example ------- >>> def target_func(p1, p2): >>> return p1 + p2 >>> pbounds = {'p1': (0, 1), 'p2': (1, 100)} >>> spa...
fmfn/BayesianOptimization
examples/sklearn_example.py
get_data
python
def get_data(): data, targets = make_classification( n_samples=1000, n_features=45, n_informative=12, n_redundant=7, random_state=134985745, ) return data, targets
Synthetic binary classification dataset.
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/examples/sklearn_example.py#L9-L18
null
from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.svm import SVC from bayes_opt import BayesianOptimization from bayes_opt.util import Colours def svc_cv(C, gamma, data, targets): """SVC cr...
fmfn/BayesianOptimization
examples/sklearn_example.py
svc_cv
python
def svc_cv(C, gamma, data, targets): estimator = SVC(C=C, gamma=gamma, random_state=2) cval = cross_val_score(estimator, data, targets, scoring='roc_auc', cv=4) return cval.mean()
SVC cross validation. This function will instantiate a SVC classifier with parameters C and gamma. Combined with data and targets this will in turn be used to perform cross validation. The result of cross validation is returned. Our goal is to find combinations of C and gamma that maximizes the roc_au...
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/examples/sklearn_example.py#L21-L33
null
from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.svm import SVC from bayes_opt import BayesianOptimization from bayes_opt.util import Colours def get_data(): """Synthetic binary classificati...
fmfn/BayesianOptimization
examples/sklearn_example.py
rfc_cv
python
def rfc_cv(n_estimators, min_samples_split, max_features, data, targets): estimator = RFC( n_estimators=n_estimators, min_samples_split=min_samples_split, max_features=max_features, random_state=2 ) cval = cross_val_score(estimator, data, targets, s...
Random Forest cross validation. This function will instantiate a random forest classifier with parameters n_estimators, min_samples_split, and max_features. Combined with data and targets this will in turn be used to perform cross validation. The result of cross validation is returned. Our goal is...
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/examples/sklearn_example.py#L36-L55
null
from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.svm import SVC from bayes_opt import BayesianOptimization from bayes_opt.util import Colours def get_data(): """Synthetic binary classificati...
fmfn/BayesianOptimization
examples/sklearn_example.py
optimize_svc
python
def optimize_svc(data, targets): def svc_crossval(expC, expGamma): """Wrapper of SVC cross validation. Notice how we transform between regular and log scale. While this is not technically necessary, it greatly improves the performance of the optimizer. """ C = 10 ** ...
Apply Bayesian Optimization to SVC parameters.
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/examples/sklearn_example.py#L58-L79
[ "def maximize(self,\n init_points=5,\n n_iter=25,\n acq='ucb',\n kappa=2.576,\n xi=0.0,\n **gp_params):\n \"\"\"Mazimize your function\"\"\"\n self._prime_subscriptions()\n self.dispatch(Events.OPTMIZATION_START)\n self._prime_queue...
from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.svm import SVC from bayes_opt import BayesianOptimization from bayes_opt.util import Colours def get_data(): """Synthetic binary classificati...
fmfn/BayesianOptimization
examples/sklearn_example.py
optimize_rfc
python
def optimize_rfc(data, targets): def rfc_crossval(n_estimators, min_samples_split, max_features): """Wrapper of RandomForest cross validation. Notice how we ensure n_estimators and min_samples_split are casted to integer before we pass them along. Moreover, to avoid max_features tak...
Apply Bayesian Optimization to Random Forest parameters.
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/examples/sklearn_example.py#L82-L112
[ "def maximize(self,\n init_points=5,\n n_iter=25,\n acq='ucb',\n kappa=2.576,\n xi=0.0,\n **gp_params):\n \"\"\"Mazimize your function\"\"\"\n self._prime_subscriptions()\n self.dispatch(Events.OPTMIZATION_START)\n self._prime_queue...
from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestClassifier as RFC from sklearn.svm import SVC from bayes_opt import BayesianOptimization from bayes_opt.util import Colours def get_data(): """Synthetic binary classificati...
fmfn/BayesianOptimization
bayes_opt/util.py
acq_max
python
def acq_max(ac, gp, y_max, bounds, random_state, n_warmup=100000, n_iter=250): # Warm up with random points x_tries = random_state.uniform(bounds[:, 0], bounds[:, 1], size=(n_warmup, bounds.shape[0])) ys = ac(x_tries, gp=gp, y_max=y_max) x_max = x_tries[ys.argmax()] ...
A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method. First by sampling `n_warmup` (1e5) points at random, and then running L-BFGS-B from `n_iter` (250) random starting points. Parameters ---------- :...
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/util.py#L7-L71
[ "def utility(self, x, gp, y_max):\n if self.kind == 'ucb':\n return self._ucb(x, gp, self.kappa)\n if self.kind == 'ei':\n return self._ei(x, gp, y_max, self.xi)\n if self.kind == 'poi':\n return self._poi(x, gp, y_max, self.xi)\n" ]
import warnings import numpy as np from scipy.stats import norm from scipy.optimize import minimize class UtilityFunction(object): """ An object to compute the acquisition functions. """ def __init__(self, kind, kappa, xi): """ If UCB is to be used, a constant kappa is needed. ...
fmfn/BayesianOptimization
bayes_opt/util.py
load_logs
python
def load_logs(optimizer, logs): import json if isinstance(logs, str): logs = [logs] for log in logs: with open(log, "r") as j: while True: try: iteration = next(j) except StopIteration: break ...
Load previous ...
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/util.py#L130-L156
[ "def register(self, params, target):\n \"\"\"Expect observation with known target\"\"\"\n self._space.register(params, target)\n self.dispatch(Events.OPTMIZATION_STEP)\n" ]
import warnings import numpy as np from scipy.stats import norm from scipy.optimize import minimize def acq_max(ac, gp, y_max, bounds, random_state, n_warmup=100000, n_iter=250): """ A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFG...
fmfn/BayesianOptimization
bayes_opt/util.py
ensure_rng
python
def ensure_rng(random_state=None): if random_state is None: random_state = np.random.RandomState() elif isinstance(random_state, int): random_state = np.random.RandomState(random_state) else: assert isinstance(random_state, np.random.RandomState) return random_state
Creates a random number generator based on an optional seed. This can be an integer or another random state for a seeded rng, or None for an unseeded rng.
train
https://github.com/fmfn/BayesianOptimization/blob/8ce2292895137477963cf1bafa4e71fa20b2ce49/bayes_opt/util.py#L159-L171
null
import warnings import numpy as np from scipy.stats import norm from scipy.optimize import minimize def acq_max(ac, gp, y_max, bounds, random_state, n_warmup=100000, n_iter=250): """ A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFG...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient._get_key_file_path
python
def _get_key_file_path(): if os.getenv(USER_HOME) is not None and os.access(os.getenv(USER_HOME), os.W_OK): return os.path.join(os.getenv(USER_HOME), KEY_FILE_NAME) return os.path.join(os.getcwd(), KEY_FILE_NAME)
Return the key file path.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L39-L45
null
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.load_key_file
python
def load_key_file(self): self.client_key = None if self.key_file_path: key_file_path = self.key_file_path else: key_file_path = self._get_key_file_path() key_dict = {} logger.debug('load keyfile from %s', key_file_path); if os.path.isfile(key_fil...
Try to load the client key for the current ip.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L47-L66
[ "def _get_key_file_path():\n \"\"\"Return the key file path.\"\"\"\n if os.getenv(USER_HOME) is not None and os.access(os.getenv(USER_HOME),\n os.W_OK):\n return os.path.join(os.getenv(USER_HOME), KEY_FILE_NAME)\n\n return os.path.join(os.getcwd()...
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.save_key_file
python
def save_key_file(self): if self.client_key is None: return if self.key_file_path: key_file_path = self.key_file_path else: key_file_path = self._get_key_file_path() logger.debug('save keyfile to %s', key_file_path); with open(key_file_path,...
Save the current client key.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L68-L89
[ "def _get_key_file_path():\n \"\"\"Return the key file path.\"\"\"\n if os.getenv(USER_HOME) is not None and os.access(os.getenv(USER_HOME),\n os.W_OK):\n return os.path.join(os.getenv(USER_HOME), KEY_FILE_NAME)\n\n return os.path.join(os.getcwd()...
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient._send_register_payload
python
def _send_register_payload(self, websocket): file = os.path.join(os.path.dirname(__file__), HANDSHAKE_FILE_NAME) data = codecs.open(file, 'r', 'utf-8') raw_handshake = data.read() handshake = json.loads(raw_handshake) handshake['payload']['client-key'] = self.client_key ...
Send the register payload.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L92-L112
null
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient._register
python
def _register(self): logger.debug('register on %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except: logger.error('register failed to c...
Register wrapper.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L119-L137
null
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.register
python
def register(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self._register())
Pair client with tv.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L139-L143
null
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient._command
python
def _command(self, msg): logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except: logger.debug('command faile...
Send a command to the tv.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L146-L172
null
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.command
python
def command(self, request_type, uri, payload): self.command_count += 1 if payload is None: payload = {} message = { 'id': "{}_{}".format(type, self.command_count), 'type': request_type, 'uri': "ssap://{}".format(uri), 'payload': paylo...
Build and send a command.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L174-L195
null
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.send_message
python
def send_message(self, message, icon_path=None): icon_encoded_string = '' icon_extension = '' if icon_path is not None: icon_extension = os.path.splitext(icon_path)[1][1:] with open(icon_path, 'rb') as icon_file: icon_encoded_string = base64.b64encode(ico...
Show a floating message.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L201-L215
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_apps
python
def get_apps(self): self.request(EP_GET_APPS) return {} if self.last_response is None else self.last_response.get('payload').get('launchPoints')
Return all apps.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L218-L221
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_current_app
python
def get_current_app(self): self.request(EP_GET_CURRENT_APP_INFO) return None if self.last_response is None else self.last_response.get('payload').get('appId')
Get the current app id.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L223-L226
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_services
python
def get_services(self): self.request(EP_GET_SERVICES) return {} if self.last_response is None else self.last_response.get('payload').get('services')
Get all services.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L255-L258
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_software_info
python
def get_software_info(self): self.request(EP_GET_SOFTWARE_INFO) return {} if self.last_response is None else self.last_response.get('payload')
Return the current software status.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L260-L263
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_inputs
python
def get_inputs(self): self.request(EP_GET_INPUTS) return {} if self.last_response is None else self.last_response.get('payload').get('devices')
Get all inputs.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L283-L286
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_audio_status
python
def get_audio_status(self): self.request(EP_GET_AUDIO_STATUS) return {} if self.last_response is None else self.last_response.get('payload')
Get the current audio status
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L299-L302
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_volume
python
def get_volume(self): self.request(EP_GET_VOLUME) return 0 if self.last_response is None else self.last_response.get('payload').get('volume')
Get the current volume.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L314-L317
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.set_volume
python
def set_volume(self, volume): volume = max(0, volume) self.request(EP_SET_VOLUME, { 'volume': volume })
Set volume.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L319-L324
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_channels
python
def get_channels(self): self.request(EP_GET_TV_CHANNELS) return {} if self.last_response is None else self.last_response.get('payload').get('channelList')
Get all tv channels.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L343-L346
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_current_channel
python
def get_current_channel(self): self.request(EP_GET_CURRENT_CHANNEL) return {} if self.last_response is None else self.last_response.get('payload')
Get the current tv channel.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L348-L351
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
TheRealLink/pylgtv
pylgtv/webos_client.py
WebOsClient.get_channel_info
python
def get_channel_info(self): self.request(EP_GET_CHANNEL_INFO) return {} if self.last_response is None else self.last_response.get('payload')
Get the current channel info.
train
https://github.com/TheRealLink/pylgtv/blob/a7d9ad87ce47e77180fe9262da785465219f4ed6/pylgtv/webos_client.py#L353-L356
[ "def request(self, uri, payload=None):\n \"\"\"Send a request.\"\"\"\n self.command('request', uri, payload)\n" ]
class WebOsClient(object): def __init__(self, ip, key_file_path=None, timeout_connect=2): """Initialize the client.""" self.ip = ip self.port = 3000 self.key_file_path = key_file_path self.client_key = None self.web_socket = None self.command_count = 0 ...
Salamek/cron-descriptor
examples/crontabReader.py
CrontabReader.parse_cron_line
python
def parse_cron_line(self, line): stripped = line.strip() if stripped and stripped.startswith('#') is False: rexres = self.rex.search(stripped) if rexres: return ' '.join(rexres.group(1).split()) return None
Parses crontab line and returns only starting time string Args: line: crontab line Returns: Time part of cron line
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/examples/crontabReader.py#L58-L73
null
class CrontabReader(object): """ Simple example reading /etc/contab """ rex = re.compile(r"^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$") def __init__(self, cronfile): """Initialize CrontabReader Args: cronfile: Path to cronfile Returns: No...
Salamek/cron-descriptor
cron_descriptor/ExpressionParser.py
ExpressionParser.parse
python
def parse(self): # Initialize all elements of parsed array to empty strings parsed = ['', '', '', '', '', '', ''] if self._expression is None or len(self._expression) == 0: raise MissingFieldException("ExpressionDescriptor.expression") else: expression_parts_temp...
Parses the cron expression string Returns: A 7 part string array, one part for each component of the cron expression (seconds, minutes, etc.) Raises: MissingFieldException: if _expression is empty or None FormatException: if _expression has wrong format
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionParser.py#L72-L114
[ "def normalize_expression(self, expression_parts):\n \"\"\"Converts cron expression components into consistent, predictable formats.\n Args:\n expression_parts: A 7 part string array, one part for each component of the cron expression\n Returns:\n None\n \"\"\"\n # convert ? to * only f...
class ExpressionParser(object): """ Parses and validates a Cron Expression into list of fixed len() """ _expression = '' _options = None _cron_days = { 0: 'SUN', 1: 'MON', 2: 'TUE', 3: 'WED', 4: 'THU', 5: 'FRI', 6: 'SAT' } _cro...
Salamek/cron-descriptor
cron_descriptor/ExpressionParser.py
ExpressionParser.normalize_expression
python
def normalize_expression(self, expression_parts): # convert ? to * only for DOM and DOW expression_parts[3] = expression_parts[3].replace("?", "*") expression_parts[5] = expression_parts[5].replace("?", "*") # convert 0/, 1/ to */ if expression_parts[0].startswith("0/"): ...
Converts cron expression components into consistent, predictable formats. Args: expression_parts: A 7 part string array, one part for each component of the cron expression Returns: None
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionParser.py#L121-L206
[ "def decrease_days_of_week(self, day_of_week_expression_part):\n dow_chars = list(day_of_week_expression_part)\n for i, dow_char in enumerate(dow_chars):\n if i == 0 or dow_chars[i - 1] != '#' and dow_chars[i - 1] != '/':\n try:\n char_numeric = int(dow_char)\n ...
class ExpressionParser(object): """ Parses and validates a Cron Expression into list of fixed len() """ _expression = '' _options = None _cron_days = { 0: 'SUN', 1: 'MON', 2: 'TUE', 3: 'WED', 4: 'THU', 5: 'FRI', 6: 'SAT' } _cro...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
get_description
python
def get_description(expression, options=None): descripter = ExpressionDescriptor(expression, options) return descripter.get_description(DescriptionTypeEnum.FULL)
Generates a human readable string for the Cron Expression Args: expression: The cron expression string options: Options to control the output description Returns: The cron expression description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L605-L615
[ "def get_description(self, description_type=DescriptionTypeEnum.FULL):\n \"\"\"Generates a human readable string for the Cron Expression\n\n Args:\n description_type: Which part(s) of the expression to describe\n Returns:\n The cron expression description\n Raises:\n Exception: if t...
# The MIT License (MIT) # # Copyright (c) 2016 Adam Schubert # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mod...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_description
python
def get_description(self, description_type=DescriptionTypeEnum.FULL): try: if self._parsed is False: parser = ExpressionParser(self._expression, self._options) self._expression_parts = parser.parse() self._parsed = True choices = { ...
Generates a human readable string for the Cron Expression Args: description_type: Which part(s) of the expression to describe Returns: The cron expression description Raises: Exception: if throw_exception_on_parse_error is True
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L76-L112
[ "def parse(self):\n \"\"\"Parses the cron expression string\n Returns:\n A 7 part string array, one part for each component of the cron expression (seconds, minutes, etc.)\n Raises:\n MissingFieldException: if _expression is empty or None\n FormatException: if _expression has wrong for...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_full_description
python
def get_full_description(self): try: time_segment = self.get_time_of_day_description() day_of_month_desc = self.get_day_of_month_description() month_desc = self.get_month_description() day_of_week_desc = self.get_day_of_week_description() year_desc = ...
Generates the FULL description Returns: The FULL description Raises: FormatException: if formating fails and throw_exception_on_parse_error is True
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L114-L149
[ "def get_time_of_day_description(self):\n \"\"\"Generates a description for only the TIMEOFDAY portion of the expression\n\n Returns:\n The TIMEOFDAY description\n\n \"\"\"\n seconds_expression = self._expression_parts[0]\n minute_expression = self._expression_parts[1]\n hour_expression = s...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_time_of_day_description
python
def get_time_of_day_description(self): seconds_expression = self._expression_parts[0] minute_expression = self._expression_parts[1] hour_expression = self._expression_parts[2] description = StringBuilder() # handle special cases first if any(exp in minute_expression for...
Generates a description for only the TIMEOFDAY portion of the expression Returns: The TIMEOFDAY description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L151-L214
[ "def append(self, string):\n \"\"\"Appends non empty string\n\n Args:\n string: String to append\n Returns:\n None\n \"\"\"\n if string:\n self.string.append(string)\n" ]
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_seconds_description
python
def get_seconds_description(self): return self.get_segment_description( self._expression_parts[0], _("every second"), lambda s: s, lambda s: _("every {0} seconds").format(s), lambda s: _("seconds {0} through {1} past the minute"), lambda s...
Generates a description for only the SECONDS portion of the expression Returns: The SECONDS description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L216-L231
[ "def get_segment_description(\n self,\n expression,\n all_description,\n get_single_item_description,\n get_interval_description_format,\n get_between_description_format,\n get_description_format\n):\n \"\"\"Returns segment description\n Args:\n expression: Segment to descript\n ...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_minutes_description
python
def get_minutes_description(self): return self.get_segment_description( self._expression_parts[1], _("every minute"), lambda s: s, lambda s: _("every {0} minutes").format(s), lambda s: _("minutes {0} through {1} past the hour"), lambda s: ...
Generates a description for only the MINUTE portion of the expression Returns: The MINUTE description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L233-L248
[ "def get_segment_description(\n self,\n expression,\n all_description,\n get_single_item_description,\n get_interval_description_format,\n get_between_description_format,\n get_description_format\n):\n \"\"\"Returns segment description\n Args:\n expression: Segment to descript\n ...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_hours_description
python
def get_hours_description(self): expression = self._expression_parts[2] return self.get_segment_description( expression, _("every hour"), lambda s: self.format_time(s, "0"), lambda s: _("every {0} hours").format(s), lambda s: _("between {0} and...
Generates a description for only the HOUR portion of the expression Returns: The HOUR description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L250-L265
[ "def get_segment_description(\n self,\n expression,\n all_description,\n get_single_item_description,\n get_interval_description_format,\n get_between_description_format,\n get_description_format\n):\n \"\"\"Returns segment description\n Args:\n expression: Segment to descript\n ...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_day_of_week_description
python
def get_day_of_week_description(self): if self._expression_parts[5] == "*" and self._expression_parts[3] != "*": # DOM is specified and DOW is * so to prevent contradiction like "on day 1 of the month, every day" # we will not specified a DOW description. return "" ...
Generates a description for only the DAYOFWEEK portion of the expression Returns: The DAYOFWEEK description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L267-L321
[ "def get_segment_description(\n self,\n expression,\n all_description,\n get_single_item_description,\n get_interval_description_format,\n get_between_description_format,\n get_description_format\n):\n \"\"\"Returns segment description\n Args:\n expression: Segment to descript\n ...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_month_description
python
def get_month_description(self): return self.get_segment_description( self._expression_parts[4], '', lambda s: datetime.date(datetime.date.today().year, int(s), 1).strftime("%B"), lambda s: _(", every {0} months").format(s), lambda s: _(", {0} through ...
Generates a description for only the MONTH portion of the expression Returns: The MONTH description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L323-L337
[ "def get_segment_description(\n self,\n expression,\n all_description,\n get_single_item_description,\n get_interval_description_format,\n get_between_description_format,\n get_description_format\n):\n \"\"\"Returns segment description\n Args:\n expression: Segment to descript\n ...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_day_of_month_description
python
def get_day_of_month_description(self): expression = self._expression_parts[3] expression = expression.replace("?", "*") if expression == "L": description = _(", on the last day of the month") elif expression == "LW" or expression == "WL": description = _(", on t...
Generates a description for only the DAYOFMONTH portion of the expression Returns: The DAYOFMONTH description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L339-L373
[ "def get_segment_description(\n self,\n expression,\n all_description,\n get_single_item_description,\n get_interval_description_format,\n get_between_description_format,\n get_description_format\n):\n \"\"\"Returns segment description\n Args:\n expression: Segment to descript\n ...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_year_description
python
def get_year_description(self): def format_year(s): regex = re.compile(r"^\d+$") if regex.match(s): year_int = int(s) if year_int < 1900: return year_int return datetime.date(year_int, 1, 1).strftime("%Y") e...
Generates a description for only the YEAR portion of the expression Returns: The YEAR description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L375-L400
[ "def get_segment_description(\n self,\n expression,\n all_description,\n get_single_item_description,\n get_interval_description_format,\n get_between_description_format,\n get_description_format\n):\n \"\"\"Returns segment description\n Args:\n expression: Segment to descript\n ...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.get_segment_description
python
def get_segment_description( self, expression, all_description, get_single_item_description, get_interval_description_format, get_between_description_format, get_description_format ): description = None if expression is None or expression == ''...
Returns segment description Args: expression: Segment to descript all_description: * get_single_item_description: 1 get_interval_description_format: 1/2 get_between_description_format: 1-2 get_description_format: format get_single_item_desc...
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L402-L484
[ "def generate_between_segment_description(\n self,\n between_expression,\n get_between_description_format,\n get_single_item_description\n):\n \"\"\"\n Generates the between segment description\n :param between_expression:\n :param get_between_description_format:\n :param ...
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.generate_between_segment_description
python
def generate_between_segment_description( self, between_expression, get_between_description_format, get_single_item_description ): description = "" between_segments = between_expression.split('-') between_segment_1_description = get_single_item...
Generates the between segment description :param between_expression: :param get_between_description_format: :param get_single_item_description: :return: The between segment description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L486-L509
null
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.format_time
python
def format_time( self, hour_expression, minute_expression, second_expression='' ): hour = int(hour_expression) period = '' if self._options.use_24hour_time_format is False: period = " PM" if (hour >= 12) else " AM" if hour > 12: ...
Given time parts, will contruct a formatted time description Args: hour_expression: Hours part minute_expression: Minutes part second_expression: Seconds part Returns: Formatted time description
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L511-L539
null
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.transform_verbosity
python
def transform_verbosity(self, description, use_verbose_format): if use_verbose_format is False: description = description.replace( _(", every minute"), '') description = description.replace(_(", every hour"), '') description = description.replace(_(", every da...
Transforms the verbosity of the expression description by stripping verbosity from original description Args: description: The description to transform use_verbose_format: If True, will leave description as it, if False, will strip verbose parts second_expression: Seconds par...
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L541-L556
null
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.transform_case
python
def transform_case(self, description, case_type): if case_type == CasingTypeEnum.Sentence: description = "{}{}".format( description[0].upper(), description[1:]) elif case_type == CasingTypeEnum.Title: description = description.title() else:...
Transforms the case of the expression description, based on options Args: description: The description to transform case_type: The casing type that controls the output casing second_expression: Seconds part Returns: The transformed description with proper ...
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L558-L576
null
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
Salamek/cron-descriptor
cron_descriptor/ExpressionDescriptor.py
ExpressionDescriptor.number_to_day
python
def number_to_day(self, day_number): return [ calendar.day_name[6], calendar.day_name[0], calendar.day_name[1], calendar.day_name[2], calendar.day_name[3], calendar.day_name[4], calendar.day_name[5] ][day_number]
Returns localized day name by its CRON number Args: day_number: Number of a day Returns: Day corresponding to day_number Raises: IndexError: When day_number is not found
train
https://github.com/Salamek/cron-descriptor/blob/fafe86b33e190caf205836fa1c719d27c7b408c7/cron_descriptor/ExpressionDescriptor.py#L578-L596
null
class ExpressionDescriptor(object): """ Converts a Cron Expression into a human readable string """ _special_characters = ['/', '-', ',', '*'] _expression = '' _options = None _expression_parts = [] _parsed = False def __init__(self, expression, options=None, **kwargs): "...
dnephin/PyStaticConfiguration
staticconf/schema.py
SchemaMeta.build_attributes
python
def build_attributes(cls, attributes, namespace): config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): key = value_def.config_key or config_key return '%s.%s' % (config_path, key) if config_path else key def build_...
Return an attributes dictionary with ValueTokens replaced by a property which returns the config value.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/schema.py#L166-L193
null
class SchemaMeta(type): """Metaclass to construct config schema object.""" def __new__(mcs, name, bases, attributes): namespace = mcs.get_namespace(attributes) attributes = mcs.build_attributes(attributes, namespace) return super(SchemaMeta, mcs).__new__(mcs, name, bases, attributes) ...
dnephin/PyStaticConfiguration
staticconf/proxy.py
cache_as_field
python
def cache_as_field(cache_name): def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: return value ret = func(self, *args, **kwargs) ...
Cache a functions return value as the field 'cache_name'.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/proxy.py#L74-L87
null
""" Proxy a configuration value. Defers the lookup until the value is used, so that values can be read statically at import time. """ import functools import operator from staticconf import errors import six class UndefToken(object): """A token to represent an undefined value, so that None can be used as a d...
dnephin/PyStaticConfiguration
staticconf/proxy.py
extract_value
python
def extract_value(proxy): value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is missing value for: %s" % (proxy.namespace, proxy.config_key)) try: return proxy.validator(value) except errors.ValidationErro...
Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/proxy.py#L90-L103
null
""" Proxy a configuration value. Defers the lookup until the value is used, so that values can be read statically at import time. """ import functools import operator from staticconf import errors import six class UndefToken(object): """A token to represent an undefined value, so that None can be used as a d...
dnephin/PyStaticConfiguration
staticconf/readers.py
build_reader
python
def build_reader(validator, reader_namespace=config.DEFAULT): def reader(config_key, default=UndefToken, namespace=None): config_namespace = config.get_namespace(namespace or reader_namespace) return validator(_read_config(config_key, config_namespace, default)) return reader
A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to the appropriate type. :param reader_namespace: the d...
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/readers.py#L103-L116
null
""" Functions to read values directly from a :class:`staticconf.config.ConfigNamespace`. Values will be validated and cast to the requested type. Examples -------- .. code-block:: python import staticconf # read an int max_cycles = staticconf.read_int('max_cycles') start_id = staticconf.read_int('...
dnephin/PyStaticConfiguration
staticconf/config.py
get_namespaces_from_names
python
def get_namespaces_from_names(name, all_names): names = configuration_namespaces.keys() if all_names else [name] for name in names: yield get_namespace(name)
Return a generator which yields namespace objects.
train
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L181-L185
[ "def get_namespace(name):\n \"\"\"Return a :class:`ConfigNamespace` by name, creating the\n namespace if it does not exist.\n \"\"\"\n if name not in configuration_namespaces:\n configuration_namespaces[name] = ConfigNamespace(name)\n return configuration_namespaces[name]\n" ]
""" Store configuration in :class:`ConfigNamespace` objects and provide tools for reloading, and displaying help messages. Configuration Reloading ----------------------- Configuration reloading is supported using a :class:`ConfigFacade`, which composes a :class:`ConfigurationWatcher` and a :class:`ReloadCallbackCha...