code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class TestModel(DBTest): <NEW_LINE> <INDENT> model = model | The base class for testing models in you TG project. | 62598fb2bd1bec0571e15100 |
class CosineProximity(LossFunction): <NEW_LINE> <INDENT> def __init__(self, bigdl_type="float"): <NEW_LINE> <INDENT> super(CosineProximity, self).__init__(None, bigdl_type) | The negative of the mean cosine proximity between predictions and targets.
The cosine proximity is defined as below:
x'(i) = x(i) / sqrt(max(sum(x(i)^2), 1e-12))
y'(i) = y(i) / sqrt(max(sum(x(i)^2), 1e-12))
cosine_proximity(x, y) = mean(-1 * x'(i) * y'(i))
>>> metrics = CosineProximity()
creating: createZooKerasCosineProximity | 62598fb28a43f66fc4bf21f5 |
class Fingerprint(object): <NEW_LINE> <INDENT> def __init__(self, fingerprint): <NEW_LINE> <INDENT> self.fp = fingerprint <NEW_LINE> <DEDENT> def __or__(self, other): <NEW_LINE> <INDENT> return ob.OBFingerprint.Tanimoto(self.fp, other.fp) <NEW_LINE> <DEDENT> @property <NEW_LINE> def bits(self): <NEW_LINE> <INDENT> return _findbits(self.fp, ob.OBFingerprint.Getbitsperint()) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> fp = self.fp <NEW_LINE> if sys.platform[:4] == "java": <NEW_LINE> <INDENT> fp = [self.fp.get(i) for i in range(self.fp.size())] <NEW_LINE> <DEDENT> return ", ".join([str(x) for x in fp]) | A Molecular Fingerprint.
Required parameters:
fingerprint -- a vector calculated by OBFingerprint.FindFingerprint()
Attributes:
fp -- the underlying fingerprint object
bits -- a list of bits set in the Fingerprint
Methods:
The "|" operator can be used to calculate the Tanimoto coeff. For example,
given two Fingerprints 'a', and 'b', the Tanimoto coefficient is given by:
tanimoto = a | b | 62598fb2d486a94d0ba2c04b |
class CpuAcctStat: <NEW_LINE> <INDENT> cpuacctPath = '/sys/fs/cgroup/cpuacct/docker/' <NEW_LINE> def __init__(self, containerId, containerName): <NEW_LINE> <INDENT> self.containerId = containerId <NEW_LINE> self.containerName = containerName <NEW_LINE> self.time = datetime.datetime.now() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(CpuAcctStat.cpuacctPath + self.containerId + "/cpuacct.stat", "r") as cpuacct: <NEW_LINE> <INDENT> for line in cpuacct: <NEW_LINE> <INDENT> fields = line.split() <NEW_LINE> if (fields[0].find('user')): <NEW_LINE> <INDENT> self.userJiffies = fields[1] <NEW_LINE> <DEDENT> if (fields[0].find('system')): <NEW_LINE> <INDENT> self.systemJiffies = fields[1] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except IOError as err: <NEW_LINE> <INDENT> if err.errno == ENOENT: <NEW_LINE> <INDENT> print("No cpuacct.stat found for {0}".format(self.containerName)) <NEW_LINE> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{0} @{1}. User={2} System={3} (in jiffies)".format(self.containerName, self.time, self.userJiffies, self.systemJiffies) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"{0} @{1}. User={2} System={3} (in jiffies)".format(self.containerName, self.time, self.userJiffies, self.systemJiffies) | Class for cpu metric for a docker container | 62598fb285dfad0860cbfab1 |
class Toolchain(Bundle): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def extra_options(extra_vars=None): <NEW_LINE> <INDENT> if extra_vars is None: <NEW_LINE> <INDENT> extra_vars = {} <NEW_LINE> <DEDENT> extra_vars.update({ 'set_env_external_modules': [False, "Include setenv statements for toolchain components that use " "an external module, based on available metadata", CUSTOM], }) <NEW_LINE> return Bundle.extra_options(extra_vars=extra_vars) <NEW_LINE> <DEDENT> def make_module_extra(self): <NEW_LINE> <INDENT> txt = super(Toolchain, self).make_module_extra() <NEW_LINE> if self.cfg.get('set_env_external_modules', False): <NEW_LINE> <INDENT> for dep in [d for d in self.cfg['dependencies'] if d['external_module']]: <NEW_LINE> <INDENT> mod_name = dep['full_mod_name'] <NEW_LINE> metadata = dep['external_module_metadata'] <NEW_LINE> names, versions = metadata.get('name', []), metadata.get('version') <NEW_LINE> if versions is None: <NEW_LINE> <INDENT> versions = [None] * len(names) <NEW_LINE> <DEDENT> if names: <NEW_LINE> <INDENT> self.log.info("Adding environment variables for %s provided by external module %s", names, mod_name) <NEW_LINE> for name, version in zip(names, versions): <NEW_LINE> <INDENT> env_vars = env_vars_external_module(name, version, metadata) <NEW_LINE> for key in env_vars: <NEW_LINE> <INDENT> self.log.info("Defining $%s for external module %s: %s", key, mod_name, env_vars[key]) <NEW_LINE> txt += self.module_generator.set_environment(key, env_vars[key]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return txt | Compiler toolchain easyblock: nothing to install, just generate module file. | 62598fb24527f215b58e9f50 |
class VersionPlistCommandDependency (CommandDependency): <NEW_LINE> <INDENT> def __init__(self, key='CFBundleShortVersionString', **kwargs): <NEW_LINE> <INDENT> super(VersionPlistCommandDependency, self).__init__(**kwargs) <NEW_LINE> self.key = key <NEW_LINE> <DEDENT> def _get_command_version_stream(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _get_version_stream(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_parent(root, element): <NEW_LINE> <INDENT> for node in root.iter(): <NEW_LINE> <INDENT> if element in node: <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> <DEDENT> raise ValueError((root, element)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_next(cls, root, element): <NEW_LINE> <INDENT> parent = cls._get_parent(root=root, element=element) <NEW_LINE> siblings = iter(parent) <NEW_LINE> for node in siblings: <NEW_LINE> <INDENT> if node == element: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return next(siblings) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def _get_version_from_plist(self, path): <NEW_LINE> <INDENT> tree = _element_tree.parse(source=path) <NEW_LINE> data = {} <NEW_LINE> for key in tree.findall('.//key'): <NEW_LINE> <INDENT> value = self._get_next(root=tree, element=key) <NEW_LINE> if value.tag != 'string': <NEW_LINE> <INDENT> raise ValueError((tree, key, value)) <NEW_LINE> <DEDENT> data[key.text] = value.text <NEW_LINE> <DEDENT> return data[self.key] <NEW_LINE> <DEDENT> def _get_version(self): <NEW_LINE> <INDENT> for path in self.paths: <NEW_LINE> <INDENT> if _os.path.exists(path): <NEW_LINE> <INDENT> return self._get_version_from_plist(path=path) <NEW_LINE> <DEDENT> <DEDENT> raise DependencyError( checker=self, message=( 'nothing exists at any of the expected paths for {0}:\n {1}' ).format( self.full_name(), '\n '.join(p for p in self.paths))) | A command that doesn't support --version or equivalent options
On OS X, a command's executable may be hard to find, or not exist
in the PATH. Work around that by looking up the version
information in the package's version.plist file. | 62598fb2796e427e5384e80f |
class AvroUtils(object): <NEW_LINE> <INDENT> REQUEST_SCHEMA = {} <NEW_LINE> REQUEST_AVSC = 'hq_sample.avrc' <NEW_LINE> @classmethod <NEW_LINE> def init_schma(self, request_file=''): <NEW_LINE> <INDENT> request_file = request_file or self.REQUEST_AVSC <NEW_LINE> with open(request_file, 'r') as fileOpen: <NEW_LINE> <INDENT> self.REQUEST_SCHEMA = avro.schema.Parse(fileOpen.read()) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def avro_encode(self, json_data, schema=None): <NEW_LINE> <INDENT> bio = BytesIO() <NEW_LINE> binary_encoder = BinaryEncoder(bio) <NEW_LINE> dw = DatumWriter(writer_schema=schema or self.REQUEST_SCHEMA) <NEW_LINE> dw.write(json_data, binary_encoder) <NEW_LINE> return bio.getvalue() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def avro_decode(cls, binary_data, schema=None): <NEW_LINE> <INDENT> bio = BytesIO(binary_data) <NEW_LINE> binary_decoder = BinaryDecoder(bio) <NEW_LINE> return DatumReader(writer_schema=schema or self.REQUEST_SCHEMA).read(binary_decoder) | avro序列化接口
| 62598fb260cbc95b063643c7 |
class SelectCommand(CAPDU): <NEW_LINE> <INDENT> name = "Select" <NEW_LINE> def __init__(self, file_path=None, file_identifier=None, next_occurrence=False): <NEW_LINE> <INDENT> if file_path is not None: <NEW_LINE> <INDENT> if isinstance(file_path, str): <NEW_LINE> <INDENT> self.data = [ord(c) for c in file_path] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data = file_path <NEW_LINE> <DEDENT> self.p1 = 0x04 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data = file_identifier <NEW_LINE> self.p1 = 0x00 <NEW_LINE> <DEDENT> if next_occurrence: <NEW_LINE> <INDENT> self.p2 = 0x02 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.p2 = 0x00 <NEW_LINE> <DEDENT> self.le = 0x00 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> data = " ".join(["%02x" % i for i in self.data]) <NEW_LINE> return "<Command[%s] P1: %02x, P2: %02x, File name: %s, Le: %02x>" % ( self.name, self.p1, self.p2, data.upper(), self.le or 0, ) | Select an application or file on the card.
Defined in: EMV 4.3 Book 1 section 11.3 | 62598fb23317a56b869be589 |
class Sink(Model): <NEW_LINE> <INDENT> def __init__(self, sim): <NEW_LINE> <INDENT> super().__init__(sim) <NEW_LINE> self.departures = Intervals() <NEW_LINE> self.departures.record(self.sim.stime) <NEW_LINE> <DEDENT> def receive_packet(self): <NEW_LINE> <INDENT> self.departures.record(self.sim.stime) | Sink module represents the traffic sink and counts arrived packets.
Methods:
- receive_packet(): called when the server finishes serving packet. | 62598fb263b5f9789fe851e5 |
class MultiHeadedSelfAttentionModule(nn.Module): <NEW_LINE> <INDENT> def __init__(self, d_model: int, num_heads: int, dropout_p: float = 0.1, device: torch.device = 'cuda'): <NEW_LINE> <INDENT> super(MultiHeadedSelfAttentionModule, self).__init__() <NEW_LINE> self.positional_encoding = PositionalEncoding(d_model) <NEW_LINE> self.layer_norm = LayerNorm(d_model) <NEW_LINE> self.attention = RelativeMultiHeadAttention(d_model, num_heads, dropout_p) <NEW_LINE> self.dropout = nn.Dropout(p=dropout_p) <NEW_LINE> self.device = device <NEW_LINE> <DEDENT> def forward(self, inputs: Tensor, mask: Optional[Tensor] = None): <NEW_LINE> <INDENT> batch_size, seq_length, _ = inputs.size() <NEW_LINE> pos_embedding = self.positional_encoding(seq_length).to(self.device) <NEW_LINE> pos_embedding = pos_embedding.repeat(batch_size, 1, 1) <NEW_LINE> inputs = self.layer_norm(inputs) <NEW_LINE> outputs = self.attention(inputs, inputs, inputs, pos_embedding=pos_embedding, mask=mask) <NEW_LINE> return self.dropout(outputs) | Conformer employ multi-headed self-attention (MHSA) while integrating an important technique from Transformer-XL,
the relative sinusoidal positional encoding scheme. The relative positional encoding allows the self-attention
module to generalize better on different input length and the resulting encoder is more robust to the variance of
the utterance length. Conformer use prenorm residual units with dropout which helps training
and regularizing deeper models.
Args:
d_model (int): The dimension of model
num_heads (int): The number of attention heads.
dropout_p (float): probability of dropout
device (torch.device): torch device (cuda or cpu)
Inputs: inputs, mask
- **inputs** (batch, time, dim): Tensor containing input vector
- **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked
Returns:
- **outputs** (batch, time, dim): Tensor produces by relative multi headed self attention module. | 62598fb255399d3f05626596 |
class ProctoredExamStudentAttemptFilter(BaseDataApiFilter): <NEW_LINE> <INDENT> site = django_filters.CharFilter(field_name="user__usersignupsource__site", lookup_expr='iexact') <NEW_LINE> course_id = django_filters.CharFilter(field_name="proctored_exam__course_id", lookup_expr='iexact') <NEW_LINE> exam_name = django_filters.CharFilter(field_name="proctored_exam__exam_name", lookup_expr='iexact') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = ProctoredExamStudentAttempt <NEW_LINE> fields = [ 'id', 'site', 'course_id', 'exam_name' ] | TODO: add me | 62598fb24428ac0f6e65859e |
class Mushroom(Veggies): <NEW_LINE> <INDENT> pass | マッシュルーム | 62598fb263d6d428bbee2828 |
class ListContactView(ListView): <NEW_LINE> <INDENT> model = Contact <NEW_LINE> form_class = SearchContactForm <NEW_LINE> template_name = 'caesar/contact_list.html' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = Contact.objects.all() <NEW_LINE> if self.request.GET.get('receiver'): <NEW_LINE> <INDENT> queryset = queryset.filter(subject__icontains=self.request.GET.get('receiver')) <NEW_LINE> <DEDENT> if self.request.GET.get('sender'): <NEW_LINE> <INDENT> queryset = queryset.filter(subject__icontains=self.request.GET.get('sender')) <NEW_LINE> <DEDENT> if self.request.GET.get('content'): <NEW_LINE> <INDENT> queryset = queryset.filter(content__icontains=self.request.GET.get('content')) <NEW_LINE> <DEDENT> if self.request.GET.get('subject'): <NEW_LINE> <INDENT> queryset = queryset.filter(content__icontains=self.request.GET.get('subject')) <NEW_LINE> <DEDENT> return queryset <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(ListContactView, self).get_context_data(**kwargs) <NEW_LINE> context['form'] = self.form_class( data={ 'subject': self.request.GET.get('subject'), 'content': self.request.GET.get('content'), 'sender': self.request.GET.get('sender') }) <NEW_LINE> get_copy = self.request.GET.copy() <NEW_LINE> parameters = get_copy.pop('page', True) and get_copy.urlencode() <NEW_LINE> context['parameters'] = parameters <NEW_LINE> return context | Displays the list of all contacts created for all visitors;
which means that no login and no permissions are required. | 62598fb2a8370b77170f0458 |
class VirtualboxProviderPlugin(ProviderPlugin): <NEW_LINE> <INDENT> NAME = 'virtualbox' <NEW_LINE> DESCRIPTION = 'a virtualbox provider' <NEW_LINE> APPLIANCE = VirtualboxAppliance <NEW_LINE> MACHINE = VirtualboxMachineNode <NEW_LINE> NETWORK = VirtualboxNetworkNode <NEW_LINE> INTERFACE = VirtualboxInterfaceNode <NEW_LINE> SHARED = VirtualboxSharedNode <NEW_LINE> COMMUNICATORS = None | A provider
| 62598fb2be383301e0253876 |
class ZookeeperDiscoverySpi(DiscoverySpi): <NEW_LINE> <INDENT> def __init__(self, zoo_service, root_path): <NEW_LINE> <INDENT> self.connection_string = zoo_service.connection_string() <NEW_LINE> self.port = zoo_service.settings.client_port <NEW_LINE> self.root_path = root_path <NEW_LINE> self.session_timeout = zoo_service.settings.min_session_timeout <NEW_LINE> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return "ZOOKEEPER" <NEW_LINE> <DEDENT> def prepare_on_start(self, **kwargs): <NEW_LINE> <INDENT> pass | ZookeeperDiscoverySpi. | 62598fb2aad79263cf42e84f |
class DeviotUpgradePioCommand(WindowCommand): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> self.window.run_command("deviot_update_pio") | Search for platformIO updates
Extends: sublime_plugin.WindowCommand | 62598fb24e4d5625663724a3 |
class Solution: <NEW_LINE> <INDENT> def strStr(self, source, target): <NEW_LINE> <INDENT> len_source = len(source) <NEW_LINE> len_target = len(target) <NEW_LINE> if len_source <= 0 and source == target: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> for start_ind in range(len_source): <NEW_LINE> <INDENT> sub = source[start_ind : start_ind + len_target] <NEW_LINE> if sub == target: <NEW_LINE> <INDENT> return start_ind <NEW_LINE> <DEDENT> <DEDENT> return -1 | @param source:
@param target:
@return: return the index | 62598fb2be7bc26dc9251e9a |
class UnsupportedFlavor(CreateError): <NEW_LINE> <INDENT> pass | Unsupported create action for given flavor name. | 62598fb2a8370b77170f0459 |
class FlowControlVisitor(BaseVisitor): <NEW_LINE> <INDENT> def __init__(self, main_visitor_method): <NEW_LINE> <INDENT> super(FlowControlVisitor, self).__init__(main_visitor_method) <NEW_LINE> <DEDENT> def should_visit(self, nodety, node, state): <NEW_LINE> <INDENT> return nodety in (phpast.Block, phpast.If, phpast.Else, phpast.ElseIf, phpast.While, phpast.DoWhile, phpast.For, phpast.Foreach) <NEW_LINE> <DEDENT> def visit(self, node, state): <NEW_LINE> <INDENT> nodety = type(node) <NEW_LINE> parentscope = self.locate_scope(node, state) <NEW_LINE> if nodety in (phpast.Else, phpast.ElseIf): <NEW_LINE> <INDENT> parentscope = parentscope._parent_scope <NEW_LINE> <DEDENT> newscope = Scope(node, parent_scope=parentscope) <NEW_LINE> state.scopes.append(newscope) <NEW_LINE> return None, False | Create new Scopes | 62598fb2009cb60464d0159e |
class SampleDict(UserDict): <NEW_LINE> <INDENT> def __init__(self, name=None): <NEW_LINE> <INDENT> UserDict.__init__(self) <NEW_LINE> self['name'] = name | Class with ancestor class | 62598fb226068e7796d4c9d2 |
class OptionsPoints(_BaseElementOptions): <NEW_LINE> <INDENT> size = properties.Instance( 'Default point size on the element', OptionsSize, default=OptionsSize, ) <NEW_LINE> shape = properties.StringChoice( 'Points are displayed as squares or spheres', default='square', choices=['square', 'sphere'], ) | PointSet visualization options | 62598fb267a9b606de54604b |
class TensorSpec(object): <NEW_LINE> <INDENT> __slots__ = ["_shape", "_shape_tuple", "_dtype", "_name"] <NEW_LINE> def __init__(self, shape, dtype, name=None): <NEW_LINE> <INDENT> self._shape = tensor_shape.TensorShape(shape) <NEW_LINE> try: <NEW_LINE> <INDENT> self._shape_tuple = tuple(self.shape.as_list()) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self._shape_tuple = None <NEW_LINE> <DEDENT> self._dtype = dtypes.as_dtype(dtype) <NEW_LINE> self._name = name <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_spec(cls, spec, name=None): <NEW_LINE> <INDENT> return cls(spec.shape, spec.dtype, name or spec.name) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_tensor(cls, tensor, name=None): <NEW_LINE> <INDENT> if isinstance(tensor, ops.EagerTensor): <NEW_LINE> <INDENT> return TensorSpec(tensor.shape, tensor.dtype, name) <NEW_LINE> <DEDENT> elif isinstance(tensor, ops.Tensor): <NEW_LINE> <INDENT> return TensorSpec(tensor.shape, tensor.dtype, name or tensor.op.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("`tensor` should be a tf.Tensor") <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def is_bounded(cls): <NEW_LINE> <INDENT> del cls <NEW_LINE> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def shape(self): <NEW_LINE> <INDENT> return self._shape <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return self._dtype <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_discrete(self): <NEW_LINE> <INDENT> return self.dtype.is_integer <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_continuous(self): <NEW_LINE> <INDENT> return self.dtype.is_floating <NEW_LINE> <DEDENT> def is_compatible_with(self, spec_or_tensor): <NEW_LINE> <INDENT> return (self._dtype.is_compatible_with(spec_or_tensor.dtype) and self._shape.is_compatible_with(spec_or_tensor.shape)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "TensorSpec(shape={}, dtype={}, name={})".format( self.shape, repr(self.dtype), repr(self.name)) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self._shape_tuple, self.dtype)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.shape == other.shape and self.dtype == other.dtype <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return TensorSpec, (self._shape, self._dtype, self._name) | Describes a tf.Tensor.
A TensorSpec allows an API to describe the Tensors that it accepts or
returns, before that Tensor exists. This allows dynamic and flexible graph
construction and configuration. | 62598fb24a966d76dd5eef54 |
class TestReadFileassertNotEqual(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.results = (None) <NEW_LINE> self.test_data = (123) <NEW_LINE> <DEDENT> def test_function(self): <NEW_LINE> <INDENT> assertNotEqual(self.results, read_file(self.test_data)) | Unittest | 62598fb27c178a314d78d519 |
class MovieView(GenreYear, ListView): <NEW_LINE> <INDENT> model = Movie <NEW_LINE> queryset = Movie.objects.filter(draft=False) <NEW_LINE> template_name = "movies/movie_list.html" <NEW_LINE> paginate_by = 2 | Список фильмов | 62598fb232920d7e50bc60d1 |
class TestOptimization(unittest.TestCase): <NEW_LINE> <INDENT> def test_readme_basic_example(self): <NEW_LINE> <INDENT> def my_process(x, y): <NEW_LINE> <INDENT> val = np.sin(x)*x + np.sin(y)*y <NEW_LINE> return {'val': val} <NEW_LINE> <DEDENT> builder = BlueprintBuilder() <NEW_LINE> builder.add_float_gene(name='x', domain=(0, 12*np.pi)) <NEW_LINE> builder.add_float_gene(name='y', domain=(0, 12*np.pi)) <NEW_LINE> blueprint = builder.get_blueprint() <NEW_LINE> popdet = blueprint.populate.deterministic(n=20) <NEW_LINE> poprnd = blueprint.populate.random(n=600) <NEW_LINE> pop = popdet + poprnd <NEW_LINE> opt = Optimizer(pop, my_process) <NEW_LINE> opt.config.multithread = False <NEW_LINE> opt.simulate.single_criteria(output='val', objective='max') <NEW_LINE> print(opt.datasets.get_best_criature(outputs='val', objectives='max')) <NEW_LINE> self.assertIsInstance(opt, Optimizer) <NEW_LINE> self.assertIsInstance(opt.population, Population) <NEW_LINE> <DEDENT> def test_readme_salesman_example(self): <NEW_LINE> <INDENT> builder = BlueprintBuilder() <NEW_LINE> def process_deco(travel_salesman): <NEW_LINE> <INDENT> def wrapper(route): <NEW_LINE> <INDENT> return {'distance': travel_salesman.get_route_distance(route)} <NEW_LINE> <DEDENT> return wrapper <NEW_LINE> <DEDENT> number_of_cities = 20 <NEW_LINE> cities = tuple(range(number_of_cities)) <NEW_LINE> builder.add_set_gene(name='route', domain=cities, length=number_of_cities) <NEW_LINE> blueprint = builder.get_blueprint() <NEW_LINE> pop = blueprint.populate.random(n=5000) <NEW_LINE> trav_salesman = TravelSalesman(number_of_cities, seed=123) <NEW_LINE> process = process_deco(trav_salesman) <NEW_LINE> opt = Optimizer(population=pop, process=process) <NEW_LINE> opt.config.multithread = True <NEW_LINE> opt.simulate.single_criteria(output='distance', objective='min') <NEW_LINE> print(opt.datasets.get_best_criature()) <NEW_LINE> self.assertIsInstance(opt, Optimizer) <NEW_LINE> self.assertIsInstance(opt.population, Population) | E2E tests for the Lamarck Optimizer. | 62598fb24f6381625f1994fe |
class RedirectResponseSchema(colander.MappingSchema): <NEW_LINE> <INDENT> headers = RedirectHeadersSchema() | Redirect response schema. | 62598fb285dfad0860cbfab2 |
class Controller(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._log = _logger(self.__class__) <NEW_LINE> <DEDENT> @property <NEW_LINE> def position(self): <NEW_LINE> <INDENT> return self._position_get() <NEW_LINE> <DEDENT> @position.setter <NEW_LINE> def position(self, pos): <NEW_LINE> <INDENT> self._position_set(pos) <NEW_LINE> <DEDENT> def scroll(self, dx, dy): <NEW_LINE> <INDENT> self._scroll(dx, dy) <NEW_LINE> <DEDENT> def press(self, button): <NEW_LINE> <INDENT> self._press(button) <NEW_LINE> <DEDENT> def release(self, button): <NEW_LINE> <INDENT> self._release(button) <NEW_LINE> <DEDENT> def move(self, dx, dy): <NEW_LINE> <INDENT> self.position = tuple(sum(i) for i in zip(self.position, (dx, dy))) <NEW_LINE> <DEDENT> def click(self, button, count=1): <NEW_LINE> <INDENT> with self as controller: <NEW_LINE> <INDENT> for _ in range(count): <NEW_LINE> <INDENT> controller.press(button) <NEW_LINE> controller.release(button) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, value, traceback): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _position_get(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _position_set(self, pos): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _scroll(self, dx, dy): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _press(self, button): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _release(self, button): <NEW_LINE> <INDENT> raise NotImplementedError() | A controller for sending virtual mouse events to the system.
| 62598fb25fc7496912d482bc |
class View(object): <NEW_LINE> <INDENT> def __init__(self, *values, **kargs): <NEW_LINE> <INDENT> self.content = values <NEW_LINE> self.layout = kargs.get("layout", "|") <NEW_LINE> self.label=kargs.get("label", "") | Describes the layout of widget.
<Long description of the class functionality.> | 62598fb201c39578d7f12df6 |
class Unauthorized(ClientError): <NEW_LINE> <INDENT> def __init__(self, msg=None): <NEW_LINE> <INDENT> ClientError.__init__(self, 401, msg) | 401 Unauthorized | 62598fb24527f215b58e9f51 |
class PrimeFreq(): <NEW_LINE> <INDENT> def __init__(self, listlistinningnos): <NEW_LINE> <INDENT> self.listprime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43] <NEW_LINE> self.dictPrimeFreq = collections.defaultdict(int) <NEW_LINE> self.listlistFreqPrime = [] <NEW_LINE> self.totalprime = 0 <NEW_LINE> self.listInningPrimeCount = [0, 0, 0, 0, 0, 0, 0] <NEW_LINE> for listinningnos in listlistinningnos : <NEW_LINE> <INDENT> InningPrimeCount = 0 <NEW_LINE> for no in listinningnos[1:] : <NEW_LINE> <INDENT> if no in self.listprime : <NEW_LINE> <INDENT> self.dictPrimeFreq[no] += 1 <NEW_LINE> self.totalprime += 1 <NEW_LINE> InningPrimeCount += 1 <NEW_LINE> <DEDENT> <DEDENT> self.listInningPrimeCount[InningPrimeCount] += 1 <NEW_LINE> <DEDENT> totalinning = len(listlistinningnos) <NEW_LINE> self.listInningPrimeCount = [ aa / totalinning for aa in self.listInningPrimeCount ] <NEW_LINE> for prime, freq in self.dictPrimeFreq.items() : <NEW_LINE> <INDENT> self.listlistFreqPrime.append([freq, prime]) <NEW_LINE> <DEDENT> self.listlistFreqPrime = sorted(self.listlistFreqPrime, key=lambda listfreqprime: listfreqprime[0], reverse=True) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> outstring = "" <NEW_LINE> for listFreqPrime in self.listlistFreqPrime : <NEW_LINE> <INDENT> outstring += str(listFreqPrime) + ",\n" <NEW_LINE> <DEDENT> return outstring <NEW_LINE> <DEDENT> def get_listlistFreqPrime(self): <NEW_LINE> <INDENT> return self.listlistFreqPrime <NEW_LINE> <DEDENT> def getPrimeProbability(self, prime): <NEW_LINE> <INDENT> if not prime in self.listprime : <NEW_LINE> <INDENT> return 0 ; <NEW_LINE> <DEDENT> count = self.dictPrimeFreq[prime] <NEW_LINE> return count / self.totalprime <NEW_LINE> <DEDENT> def getPrime6Probability(self, listnos): <NEW_LINE> <INDENT> return sum([self.getPrimeProbability(aa) for aa in listnos]) <NEW_LINE> <DEDENT> def getPrimeCountPatternProbability(self, listnos): <NEW_LINE> <INDENT> primecount = [ aa in self.listprime for aa in listnos].count(True) <NEW_LINE> return self.listInningPrimeCount[primecount] <NEW_LINE> <DEDENT> def get_listInningPrimeCount(self): <NEW_LINE> <INDENT> return self.listInningPrimeCount | 소수(prime number)에 대해 그 빈도수를 구하고, 확률를 구한다. | 62598fb23d592f4c4edbaf3e |
class AuiToolBarEvent(CommandToolBarEvent): <NEW_LINE> <INDENT> def __init__(self, command_type=None, win_id=0): <NEW_LINE> <INDENT> CommandToolBarEvent.__init__(self, command_type, win_id) <NEW_LINE> if type(command_type) in six.integer_types: <NEW_LINE> <INDENT> self.notify = wx.NotifyEvent(command_type, win_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.notify = wx.NotifyEvent(command_type.GetEventType(), command_type.GetId()) <NEW_LINE> <DEDENT> <DEDENT> def GetNotifyEvent(self): <NEW_LINE> <INDENT> return self.notify <NEW_LINE> <DEDENT> def IsAllowed(self): <NEW_LINE> <INDENT> return self.notify.IsAllowed() <NEW_LINE> <DEDENT> def Veto(self): <NEW_LINE> <INDENT> self.notify.Veto() <NEW_LINE> <DEDENT> def Allow(self): <NEW_LINE> <INDENT> self.notify.Allow() | A specialized command event class for events sent by :class:`AuiToolBar`. | 62598fb256ac1b37e6302268 |
class TASRTestCase(unittest.TestCase): <NEW_LINE> <INDENT> test_dir = TEST_DIR <NEW_LINE> src_dir = SRC_DIR <NEW_LINE> fix_dir = FIX_DIR <NEW_LINE> @staticmethod <NEW_LINE> def get_fixture_file(rel_path, mode): <NEW_LINE> <INDENT> path = '%s/%s' % (TASRTestCase.fix_dir, rel_path) <NEW_LINE> return open(path, mode) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_schema_permutation(schema_str, field_name=None, field_type=None): <NEW_LINE> <INDENT> jd = json.loads(schema_str) <NEW_LINE> field_name = "extra" if not field_name else field_name <NEW_LINE> field_type = "string" if not field_type else field_type <NEW_LINE> jd['fields'].append({"name": field_name, "type": ["null", field_type], "default": None}) <NEW_LINE> return json.dumps(jd) | These tests check that the TASR S+V REST API, expected by the Avro-1124
repo code. This does not check the TASR native API calls. | 62598fb255399d3f05626597 |
class JobMember(models.Model): <NEW_LINE> <INDENT> objects = ProcessManager() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if self.committee_member_confirmed: <NEW_LINE> <INDENT> return '%s is a confirmed %s for rating decision %s' % ( self.member, self.role, self.rating_decision ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '%s is a %s for rating decision %s' % ( self.member, self.role, self.rating_decision ) <NEW_LINE> <DEDENT> <DEDENT> rating_decision = models.ForeignKey( RatingDecision, on_delete=models.PROTECT ) <NEW_LINE> member = models.ForeignKey( User, on_delete=models.PROTECT, related_name="committee_member_committee_member", null=True, blank=True ) <NEW_LINE> role = models.ForeignKey( Role, on_delete=models.PROTECT, null=False, blank=False ) <NEW_LINE> group = models.ForeignKey( Group, on_delete=models.PROTECT, null=False, blank=False ) <NEW_LINE> committee_member_confirmed = models.BooleanField( db_index=True, default=False ) | Describe the attributes of a committee member
for a specific decision. | 62598fb230bbd722464699b7 |
class TestOrganisationGroupsApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = ChronoSheetsClientLibApi.organisation_groups_api.OrganisationGroupsApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_organisation_groups_create_organisation_group(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_organisation_groups_delete_organisation_group(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_organisation_groups_get_organisation_group(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_organisation_groups_get_organisation_groups(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_organisation_groups_get_organisation_groups_for_job(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_organisation_groups_get_organisation_groups_for_vehicle(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_organisation_groups_update_organisation_group(self): <NEW_LINE> <INDENT> pass | OrganisationGroupsApi unit test stubs | 62598fb2baa26c4b54d4f333 |
class PartyMemberSupportedBillFeature(BooleanFeature): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Feature.__init__(self, "Party member supported the Bill") <NEW_LINE> <DEDENT> def Extract(self, party, bill): <NEW_LINE> <INDENT> return bool(set(bill.joining_members.all()).intersection( set(party.member_set.all()))) | Feature is True if a party member was supporting the bill. | 62598fb2236d856c2adc947d |
class GameStartEvent(GameEvent): <NEW_LINE> <INDENT> name = 'GameStartEvent' <NEW_LINE> def __init__(self, frame, pid, data): <NEW_LINE> <INDENT> super(GameStartEvent, self).__init__(frame, pid) | Recorded when the game starts and the frames start to roll. This is a global non-player
event. | 62598fb22ae34c7f260ab160 |
class ConvertImageDtype(torch.nn.Module): <NEW_LINE> <INDENT> def __init__(self, dtype: torch.dtype) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.dtype = dtype <NEW_LINE> <DEDENT> def forward(self, image): <NEW_LINE> <INDENT> return F.convert_image_dtype(image, self.dtype) | Convert a tensor image to the given ``dtype`` and scale the values accordingly
This function does not support PIL Image and Numpy NDArray.
Args:
dtype (torch.dtype): Desired data type of the output
.. note::
When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly.
If converted back and forth, this mismatch has no effect.
Raises:
RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as
well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to
overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range
of the integer ``dtype``. | 62598fb24a966d76dd5eef55 |
class AwsResourceCollector(): <NEW_LINE> <INDENT> instance_table = None <NEW_LINE> region_list = [] <NEW_LINE> keyname_list = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if os.path.exists('./resource_keeper.yaml'): <NEW_LINE> <INDENT> config_file = './resource_keeper.yaml' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config_file = os.path.expanduser('~/.resource_keeper.yaml') <NEW_LINE> <DEDENT> with open(config_file, 'r') as f: <NEW_LINE> <INDENT> yaml_dict = yaml.full_load(f) <NEW_LINE> <DEDENT> if self.__class__.__name__ in yaml_dict: <NEW_LINE> <INDENT> user_config = yaml_dict[self.__class__.__name__] <NEW_LINE> if 'RegionList' in user_config: <NEW_LINE> <INDENT> self.region_list = user_config['RegionList'] <NEW_LINE> <DEDENT> if 'KeynameList' in user_config: <NEW_LINE> <INDENT> self.keyname_list = user_config['KeynameList'] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print('ERROR: error while parsing "%s".' % (config_file)) <NEW_LINE> print(err) <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> <DEDENT> def _get_available_regions(self): <NEW_LINE> <INDENT> session = boto3.session.Session() <NEW_LINE> available_regions = session.get_available_regions('ec2') <NEW_LINE> return available_regions <NEW_LINE> <DEDENT> def scan_all(self): <NEW_LINE> <INDENT> if not self.region_list: <NEW_LINE> <INDENT> self.region_list = self._get_available_regions() <NEW_LINE> <DEDENT> for region in self.region_list: <NEW_LINE> <INDENT> self.scan_instance(region=region) <NEW_LINE> <DEDENT> <DEDENT> def scan_instance(self, region='us-west-2'): <NEW_LINE> <INDENT> instance_list = [] <NEW_LINE> print('NOTE: Scan running instance in region "%s".' % region) <NEW_LINE> ec2_resource = boto3.resource('ec2', region_name=region) <NEW_LINE> running_instances = ec2_resource.instances.filter( Filters=[{ 'Name': 'instance-state-name', 'Values': ['running'] }]) <NEW_LINE> for instance in running_instances: <NEW_LINE> <INDENT> if not self.keyname_list or instance.key_name in self.keyname_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name = [x for x in instance.tags if x['Key'] == 'Name'][0]['Value'] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> name = 'n/a' <NEW_LINE> <DEDENT> instance_list.append( (region, name, instance.id, instance.instance_type, instance.key_name)) <NEW_LINE> <DEDENT> <DEDENT> if instance_list: <NEW_LINE> <INDENT> if self.instance_table is None: <NEW_LINE> <INDENT> self.instance_table = prettytable.PrettyTable([ 'Region', 'tag:Name', 'InstanceId', 'InstanceType', 'KeyName' ]) <NEW_LINE> self.instance_table.align = 'l' <NEW_LINE> <DEDENT> for item in instance_list: <NEW_LINE> <INDENT> self.instance_table.add_row(item) <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def get_instance_table(self, format='string'): <NEW_LINE> <INDENT> if type(self.instance_table) is not prettytable.PrettyTable: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if format == 'string': <NEW_LINE> <INDENT> return self.instance_table.get_string() <NEW_LINE> <DEDENT> elif format == 'html': <NEW_LINE> <INDENT> return self.instance_table.get_html_string() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.instance_table | Collect unused resources for AWS. | 62598fb25fcc89381b26618b |
class MAVLink_mission_write_partial_list_message(MAVLink_message): <NEW_LINE> <INDENT> def __init__(self, target_system, target_component, start_index, end_index): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLINK_MSG_ID_MISSION_WRITE_PARTIAL_LIST, 'MISSION_WRITE_PARTIAL_LIST') <NEW_LINE> self._fieldnames = ['target_system', 'target_component', 'start_index', 'end_index'] <NEW_LINE> self.target_system = target_system <NEW_LINE> self.target_component = target_component <NEW_LINE> self.start_index = start_index <NEW_LINE> self.end_index = end_index <NEW_LINE> <DEDENT> def pack(self, mav): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 123, struct.pack('>BBhh', self.target_system, self.target_component, self.start_index, self.end_index)) | This message is sent to the MAV to write a partial list. If
start index == end index, only one item will be transmitted /
updated. If the start index is NOT 0 and above the current
list size, this request should be REJECTED! | 62598fb24e4d5625663724a4 |
class FunctionEnvelopeCollection(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[FunctionEnvelope]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: List["FunctionEnvelope"], **kwargs ): <NEW_LINE> <INDENT> super(FunctionEnvelopeCollection, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | Collection of Kudu function information elements.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar value: Required. Collection of resources.
:vartype value: list[~azure.mgmt.web.v2020_06_01.models.FunctionEnvelope]
:ivar next_link: Link to next page of resources.
:vartype next_link: str | 62598fb27d847024c075c440 |
class BufferedParallelTestResult(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.buffered_result = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def test(self): <NEW_LINE> <INDENT> return self.buffered_result.test <NEW_LINE> <DEDENT> def updateResult(self, result): <NEW_LINE> <INDENT> result.startTest(self.test) <NEW_LINE> self.buffered_result.updateResult(result) <NEW_LINE> result.stopTest(self.test) <NEW_LINE> <DEDENT> def startTest(self, test): <NEW_LINE> <INDENT> self.start_time = time.perf_counter() <NEW_LINE> <DEDENT> def stopTest(self, test): <NEW_LINE> <INDENT> if hasattr(time, 'perf_counter'): <NEW_LINE> <INDENT> self.buffered_result.duration = time.perf_counter() - self.start_time <NEW_LINE> <DEDENT> <DEDENT> def addSuccess(self, test): <NEW_LINE> <INDENT> if hasattr(time, 'perf_counter'): <NEW_LINE> <INDENT> print(test, '... ok (%.2fs)' % (time.perf_counter() - self.start_time), file=sys.stderr) <NEW_LINE> <DEDENT> self.buffered_result = BufferedTestSuccess(test) <NEW_LINE> <DEDENT> def addExpectedFailure(self, test, err): <NEW_LINE> <INDENT> if hasattr(time, 'perf_counter'): <NEW_LINE> <INDENT> print(test, '... expected failure (%.2fs)' % (time.perf_counter() - self.start_time), file=sys.stderr) <NEW_LINE> <DEDENT> self.buffered_result = BufferedTestExpectedFailure(test, err) <NEW_LINE> <DEDENT> def addUnexpectedSuccess(self, test): <NEW_LINE> <INDENT> if hasattr(time, 'perf_counter'): <NEW_LINE> <INDENT> print(test, '... unexpected success (%.2fs)' % (time.perf_counter() - self.start_time), file=sys.stderr) <NEW_LINE> <DEDENT> self.buffered_result = BufferedTestUnexpectedSuccess(test) <NEW_LINE> <DEDENT> def addSkip(self, test, reason): <NEW_LINE> <INDENT> print(test, "... skipped '%s'" % reason, file=sys.stderr) <NEW_LINE> self.buffered_result = BufferedTestSkip(test, reason) <NEW_LINE> <DEDENT> def addFailure(self, test, err): <NEW_LINE> <INDENT> print(test, '... FAIL', file=sys.stderr) <NEW_LINE> self.buffered_result = BufferedTestFailure(test, err) <NEW_LINE> <DEDENT> def addError(self, test, err): <NEW_LINE> <INDENT> print(test, '... ERROR', file=sys.stderr) <NEW_LINE> self.buffered_result = BufferedTestError(test, err) | A picklable struct used to communicate test results across processes
Fulfills the interface for unittest.TestResult | 62598fb267a9b606de54604c |
class ClientCollector(StateMachine): <NEW_LINE> <INDENT> tasks: List[Task] <NEW_LINE> bundle: List[bytes] <NEW_LINE> queue: QueueClient <NEW_LINE> local: Queue[Optional[Task]] <NEW_LINE> bundlesize: int <NEW_LINE> bundlewait: int <NEW_LINE> previous_send: datetime <NEW_LINE> state = CollectorState.START <NEW_LINE> states = CollectorState <NEW_LINE> def __init__(self, queue: QueueClient, local: Queue[Optional[Task]], bundlesize: int = DEFAULT_BUNDLESIZE, bundlewait: int = DEFAULT_BUNDLEWAIT) -> None: <NEW_LINE> <INDENT> self.tasks = [] <NEW_LINE> self.bundle = [] <NEW_LINE> self.local = local <NEW_LINE> self.queue = queue <NEW_LINE> self.bundlesize = bundlesize <NEW_LINE> self.bundlewait = bundlewait <NEW_LINE> <DEDENT> @functools.cached_property <NEW_LINE> def actions(self) -> Dict[CollectorState, Callable[[], CollectorState]]: <NEW_LINE> <INDENT> return { CollectorState.START: self.start, CollectorState.GET_LOCAL: self.get_local, CollectorState.CHECK_BUNDLE: self.check_bundle, CollectorState.PACK_BUNDLE: self.pack_bundle, CollectorState.PUT_REMOTE: self.put_remote, CollectorState.FINAL: self.finalize, } <NEW_LINE> <DEDENT> def start(self) -> CollectorState: <NEW_LINE> <INDENT> log.debug('Started (collector)') <NEW_LINE> self.previous_send = datetime.now() <NEW_LINE> return CollectorState.GET_LOCAL <NEW_LINE> <DEDENT> def get_local(self) -> CollectorState: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> task = self.local.get(timeout=1) <NEW_LINE> self.local.task_done() <NEW_LINE> if task: <NEW_LINE> <INDENT> self.tasks.append(task) <NEW_LINE> return CollectorState.CHECK_BUNDLE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return CollectorState.FINAL <NEW_LINE> <DEDENT> <DEDENT> except QueueEmpty: <NEW_LINE> <INDENT> return CollectorState.CHECK_BUNDLE <NEW_LINE> <DEDENT> <DEDENT> def check_bundle(self) -> CollectorState: <NEW_LINE> <INDENT> wait_time = (datetime.now() - self.previous_send) <NEW_LINE> since_last = wait_time.total_seconds() <NEW_LINE> if len(self.tasks) >= self.bundlesize: <NEW_LINE> <INDENT> log.trace(f'Bundle size ({len(self.tasks)}) reached') <NEW_LINE> return CollectorState.PACK_BUNDLE <NEW_LINE> <DEDENT> elif since_last >= self.bundlewait: <NEW_LINE> <INDENT> log.trace(f'Wait time exceeded ({wait_time})') <NEW_LINE> return CollectorState.PACK_BUNDLE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return CollectorState.GET_LOCAL <NEW_LINE> <DEDENT> <DEDENT> def pack_bundle(self) -> CollectorState: <NEW_LINE> <INDENT> self.bundle = [task.pack() for task in self.tasks] <NEW_LINE> return CollectorState.PUT_REMOTE <NEW_LINE> <DEDENT> def put_remote(self) -> CollectorState: <NEW_LINE> <INDENT> if self.bundle: <NEW_LINE> <INDENT> self.queue.completed.put(self.bundle) <NEW_LINE> log.trace(f'Returned bundle of {len(self.bundle)} task(s)') <NEW_LINE> self.tasks.clear() <NEW_LINE> self.bundle.clear() <NEW_LINE> self.previous_send = datetime.now() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.trace('No local tasks to return') <NEW_LINE> <DEDENT> return CollectorState.GET_LOCAL <NEW_LINE> <DEDENT> def finalize(self) -> CollectorState: <NEW_LINE> <INDENT> self.put_remote() <NEW_LINE> log.debug('Done (collector)') <NEW_LINE> return CollectorState.HALT | Collect finished tasks and bundle for outgoing queue. | 62598fb299cbb53fe6830f52 |
class GitterAPI(object): <NEW_LINE> <INDENT> def __init__(self, token): <NEW_LINE> <INDENT> self.token = token <NEW_LINE> self.room_id_dict = self.get_room_id_dict() <NEW_LINE> <DEDENT> def get_rooms(self): <NEW_LINE> <INDENT> headers = { 'Accept': 'application/json', 'Authorization': 'Bearer {0}'.format(self.token), } <NEW_LINE> r = requests.get('https://api.gitter.im/v1/rooms', headers=headers) <NEW_LINE> return r.json() <NEW_LINE> <DEDENT> def get_room_id_dict(self): <NEW_LINE> <INDENT> room_id_dict = {} <NEW_LINE> for room in self.get_rooms(): <NEW_LINE> <INDENT> if room['githubType'] != 'ONETOONE': <NEW_LINE> <INDENT> room_id_dict[room['uri']] = room['id'] <NEW_LINE> <DEDENT> <DEDENT> return room_id_dict <NEW_LINE> <DEDENT> def send_message(self, room, text): <NEW_LINE> <INDENT> headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer {0}'.format(self.token), } <NEW_LINE> room_id = self.room_id_dict.get(room) <NEW_LINE> url = 'https://api.gitter.im/v1/rooms/{room_id}/chatMessages' <NEW_LINE> url = url.format(room_id=room_id) <NEW_LINE> payload = {'text': text} <NEW_LINE> r = requests.post(url, data=json.dumps(payload), headers=headers) <NEW_LINE> return r | Gitter API wrapper
URL: https://developer.gitter.im/docs/welcome | 62598fb27c178a314d78d51b |
class Extended(object): <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return memoryview(self) == memoryview(other) <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return memoryview(self) != memoryview(other) | Used to add extended capability to structures | 62598fb2d486a94d0ba2c04f |
class ShutterContact(IPShutterContact, HelperSabotage): <NEW_LINE> <INDENT> pass | Door / Window contact that emits its open/closed state. | 62598fb257b8e32f5250815b |
class ForRecursion(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def change_status(cls, artifact, status): <NEW_LINE> <INDENT> for a in artifact.children: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a.visibility = status <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print("failed aid: %d, status %s" % (artifact.id, status)) <NEW_LINE> return <NEW_LINE> <DEDENT> cls.change_status(a, status) | for some strange reason, my guess is how we are executing the patches
recursion doesn't work directly so decided to use a class to make it
work | 62598fb2b7558d58954636aa |
class Meta: <NEW_LINE> <INDENT> model = ChartData <NEW_LINE> fields = ( 'ticker', 'date', 'open_value', 'close_value', 'high_value', 'low_value', 'volume', 'adj_close' ) | Meta class. | 62598fb2a17c0f6771d5c2b4 |
class USPSSelect(Select): <NEW_LINE> <INDENT> def __init__(self, attrs=None): <NEW_LINE> <INDENT> from my_django.contrib.localflavor.us.us_states import USPS_CHOICES <NEW_LINE> super(USPSSelect, self).__init__(attrs, choices=USPS_CHOICES) | A Select widget that uses a list of US Postal Service codes as its
choices. | 62598fb24c3428357761a338 |
class Group(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.have_comments = False <NEW_LINE> self.header = [] <NEW_LINE> self.m = numpy.identity(4) <NEW_LINE> self.n_parts = 0 <NEW_LINE> self.n_primitives = 0 <NEW_LINE> self.parts_list = [] <NEW_LINE> <DEDENT> def addComment(self, comment): <NEW_LINE> <INDENT> self.have_comments = True <NEW_LINE> self.parts_list.append(comment) <NEW_LINE> <DEDENT> def addPart(self, part, is_primitive): <NEW_LINE> <INDENT> if is_primitive: <NEW_LINE> <INDENT> self.n_primitives += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.n_parts += 1 <NEW_LINE> <DEDENT> self.parts_list.append(part) <NEW_LINE> <DEDENT> def getNParts(self): <NEW_LINE> <INDENT> return self.n_parts <NEW_LINE> <DEDENT> def getNPrimitives(self): <NEW_LINE> <INDENT> return self.n_primitives <NEW_LINE> <DEDENT> def getParts(self): <NEW_LINE> <INDENT> if self.have_comments: <NEW_LINE> <INDENT> return self.parts_list <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return sorted(self.parts_list, key = lambda part: part.step) <NEW_LINE> <DEDENT> <DEDENT> def matrix(self): <NEW_LINE> <INDENT> return self.m <NEW_LINE> <DEDENT> def setMatrix(self, m): <NEW_LINE> <INDENT> self.m = m | A group of parts. | 62598fb21f5feb6acb162c9e |
class FileRequestDeadline(object): <NEW_LINE> <INDENT> __slots__ = [ '_deadline_value', '_deadline_present', '_allow_late_uploads_value', '_allow_late_uploads_present', ] <NEW_LINE> _has_required_fields = True <NEW_LINE> def __init__(self, deadline=None, allow_late_uploads=None): <NEW_LINE> <INDENT> self._deadline_value = None <NEW_LINE> self._deadline_present = False <NEW_LINE> self._allow_late_uploads_value = None <NEW_LINE> self._allow_late_uploads_present = False <NEW_LINE> if deadline is not None: <NEW_LINE> <INDENT> self.deadline = deadline <NEW_LINE> <DEDENT> if allow_late_uploads is not None: <NEW_LINE> <INDENT> self.allow_late_uploads = allow_late_uploads <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def deadline(self): <NEW_LINE> <INDENT> if self._deadline_present: <NEW_LINE> <INDENT> return self._deadline_value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError("missing required field 'deadline'") <NEW_LINE> <DEDENT> <DEDENT> @deadline.setter <NEW_LINE> def deadline(self, val): <NEW_LINE> <INDENT> val = self._deadline_validator.validate(val) <NEW_LINE> self._deadline_value = val <NEW_LINE> self._deadline_present = True <NEW_LINE> <DEDENT> @deadline.deleter <NEW_LINE> def deadline(self): <NEW_LINE> <INDENT> self._deadline_value = None <NEW_LINE> self._deadline_present = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def allow_late_uploads(self): <NEW_LINE> <INDENT> if self._allow_late_uploads_present: <NEW_LINE> <INDENT> return self._allow_late_uploads_value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @allow_late_uploads.setter <NEW_LINE> def allow_late_uploads(self, val): <NEW_LINE> <INDENT> if val is None: <NEW_LINE> <INDENT> del self.allow_late_uploads <NEW_LINE> return <NEW_LINE> <DEDENT> self._allow_late_uploads_validator.validate_type_only(val) <NEW_LINE> self._allow_late_uploads_value = val <NEW_LINE> self._allow_late_uploads_present = True <NEW_LINE> <DEDENT> @allow_late_uploads.deleter <NEW_LINE> def allow_late_uploads(self): <NEW_LINE> <INDENT> self._allow_late_uploads_value = None <NEW_LINE> self._allow_late_uploads_present = False <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'FileRequestDeadline(deadline={!r}, allow_late_uploads={!r})'.format( self._deadline_value, self._allow_late_uploads_value, ) | :ivar deadline: The deadline for this file request.
:ivar allow_late_uploads: If set, allow uploads after the deadline has
passed. These uploads will be marked overdue. | 62598fb255399d3f0562659a |
class JustNodesStats(NodesStats): <NEW_LINE> <INDENT> def getData(self): <NEW_LINE> <INDENT> self.options[self.TRANSFORM_PARAM] = self.TRANSFORM_VALUE_NESTED <NEW_LINE> return NodesStats.getData(self) <NEW_LINE> <DEDENT> def printData(self, data): <NEW_LINE> <INDENT> if 'nodes' in data: <NEW_LINE> <INDENT> for node in data['nodes']: <NEW_LINE> <INDENT> if self.TIMESTAMP_KEY in data: <NEW_LINE> <INDENT> node[self.TIMESTAMP_KEY] = data[self.TIMESTAMP_KEY] <NEW_LINE> <DEDENT> NodesStats.printData(self, node) | Get "just" nodes stats | 62598fb2a79ad1619776a0e8 |
class BundleDataJSONEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, FileInfo): <NEW_LINE> <INDENT> return [o.public, o.size, o.hash_digest.hex()] <NEW_LINE> <DEDENT> elif isinstance(o, UUID): <NEW_LINE> <INDENT> return str(o) <NEW_LINE> <DEDENT> elif isinstance(o, datetime): <NEW_LINE> <INDENT> return o.isoformat() <NEW_LINE> <DEDENT> elif isinstance(o, Snapshot): <NEW_LINE> <INDENT> return { 'bundle_uuid': o.bundle_uuid, 'hash_digest': o.hash_digest.hex(), 'files': o.files, 'links': o.links, 'created_at': o.created_at, '_type': 'snapshot', '_version': 1, } <NEW_LINE> <DEDENT> elif isinstance(o, StagedDraft): <NEW_LINE> <INDENT> if o.base_snapshot is None: <NEW_LINE> <INDENT> base_snapshot = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> base_snapshot = o.base_snapshot.hash_digest.hex() <NEW_LINE> <DEDENT> return { 'uuid': o.uuid, 'bundle_uuid': o.bundle_uuid, 'name': o.name, 'base_snapshot': base_snapshot, 'files_to_overwrite': o.files_to_overwrite, 'links_to_overwrite': o.links_to_overwrite, 'created_at': o.created_at, 'updated_at': o.updated_at, '_type': 'draft', '_version': 1, } <NEW_LINE> <DEDENT> elif isinstance(o, LinkCollection): <NEW_LINE> <INDENT> return { link.name: { "direct": link.direct_dependency, "indirect": link.indirect_dependencies } for link in o } <NEW_LINE> <DEDENT> elif isinstance(o, LinkChangeSet): <NEW_LINE> <INDENT> change_set_dict = { link.name: { "direct": link.direct_dependency, "indirect": link.indirect_dependencies } for link in o.puts } <NEW_LINE> for name in o.deletes: <NEW_LINE> <INDENT> change_set_dict[name] = None <NEW_LINE> <DEDENT> return change_set_dict <NEW_LINE> <DEDENT> elif isinstance(o, Link): <NEW_LINE> <INDENT> return { "name": o.name, "direct": o.direct_dependency, "indirect": o.indirect_dependencies, } <NEW_LINE> <DEDENT> elif isinstance(o, Dependency): <NEW_LINE> <INDENT> return { "bundle_uuid": o.bundle_uuid, "version": o.version, "snapshot_digest": o.snapshot_digest.hex(), } <NEW_LINE> <DEDENT> return json.JSONEncoder.default(self, o) | Default JSON serialization. | 62598fb2a05bb46b3848a8eb |
class confPostgis: <NEW_LINE> <INDENT> def __init__(self,extent): <NEW_LINE> <INDENT> self.host = 'localhost' <NEW_LINE> self.dbname = 'DBNAME' <NEW_LINE> self.user = 'USERNAME' <NEW_LINE> self.password = 'PASSWORD' <NEW_LINE> self.prefixTable = 'PREFIX' <NEW_LINE> self.geomColumn = 'way' <NEW_LINE> self.srid = '4326' <NEW_LINE> self.extentStr = str((extent.minx-1)) + ',' + str((extent.miny-1)) + ',' + str((extent.maxx+1)) + ',' +str((extent.maxy+1)) <NEW_LINE> <DEDENT> def lineConn(self): <NEW_LINE> <INDENT> query = '%s_line where way && !bbox! ORDER BY st_LENGTH(%s) ASC' % (self.prefixTable, self.geomColumn) <NEW_LINE> datasource_line = PostGIS(host = self.host, dbname = self.dbname, user = self.user, password = self.password, table = query, srid = self.srid, geometry_field = self.geomColumn, extent = self.extentStr) <NEW_LINE> return datasource_line <NEW_LINE> <DEDENT> def pointConn(self): <NEW_LINE> <INDENT> datasource_point = PostGIS(host = self.host, dbname = self.dbname, user = self.user, password = self.password, table=self.prefixTable + '_point') <NEW_LINE> return datasource_point <NEW_LINE> <DEDENT> def polygonConn(self): <NEW_LINE> <INDENT> datasource_polygon = PostGIS(host = self.host, dbname = self.dbname, user = self.user, password = self.password, table=self.prefixTable + '_polygon') <NEW_LINE> return datasource_polygon | Class to create the connections to postgis database
IMPORTANT: you must change the values for your connections | 62598fb2498bea3a75a57b9f |
class VideoSource(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=200) <NEW_LINE> home = models.URLField() <NEW_LINE> embed_template = models.URLField() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name | An encapsulation for "embed template". | 62598fb23346ee7daa337687 |
class Encoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self, input_dim, hidden_dim, dim_h1, categorical_dim): <NEW_LINE> <INDENT> super(Encoder, self).__init__() <NEW_LINE> self.input_dim = input_dim <NEW_LINE> self.hidden_dim = hidden_dim <NEW_LINE> self.dim_h1 = dim_h1 <NEW_LINE> self.categorical_dim = categorical_dim <NEW_LINE> self.transform = nn.Sequential(nn.Linear(input_dim, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU()) <NEW_LINE> self.to_hiddden = nn.Linear(256, dim_h1*categorical_dim) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> out = self.transform(x) <NEW_LINE> out = self.to_hiddden(out) <NEW_LINE> out = out.view(out.size()[0],out.size()[1],self.dim_h1, self.categorical_dim) <NEW_LINE> return out | encoder | 62598fb2aad79263cf42e853 |
class CourseCommentsAdmin(object): <NEW_LINE> <INDENT> list_display = ['user', 'course', 'comments', 'add_time'] <NEW_LINE> search_fields = ['user', 'course', 'comments'] <NEW_LINE> list_filter = ['user', 'course', 'comments', 'add_time'] | 用户评论后台管理器 | 62598fb2cc0a2c111447b092 |
class Subscriber: <NEW_LINE> <INDENT> def __init__(self, _id, func, calls): <NEW_LINE> <INDENT> self.__id = _id <NEW_LINE> self.__func = func <NEW_LINE> self.__calls = calls <NEW_LINE> self.__total_calls = 0 <NEW_LINE> <DEDENT> def call(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__func(*args, **kwargs) <NEW_LINE> if self.__calls and self.__calls > 0: <NEW_LINE> <INDENT> self.__total_calls += 1 <NEW_LINE> if self.__calls == self.__total_calls: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> return self.__id <NEW_LINE> <DEDENT> def is_func(self, func): <NEW_LINE> <INDENT> return self.__func == func | Contains subscriber data | 62598fb23539df3088ecc332 |
class TestGetQuestions(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.app = app.test_client() <NEW_LINE> <DEDENT> def test_if_all_successfuly_returned_all_questions(self): <NEW_LINE> <INDENT> response = self.app.post('/api/v1/questions', content_type='application/json', data={ 'id': 1, 'title': 'testing', 'body': 'answer test' }) <NEW_LINE> response = self.app.get('/api/v1/questions', follow_redirects = True) <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> <DEDENT> def test_returns_not_found_if_question_doesnot_exist(self): <NEW_LINE> <INDENT> response = self.app.get('/api/v1/questions/7') <NEW_LINE> self.assertEquals(response.status_code, 404) <NEW_LINE> self.assertTrue('There is no question that matches the id you specified' in response.get_data(as_text = True)) <NEW_LINE> <DEDENT> def test_pass_if_question_is_found_in_the_database(self): <NEW_LINE> <INDENT> response = self.app.post('/api/v1/questions', content_type='application/json', data=json.dumps({ 'id': 1, 'title': 'testing', 'body': 'answer test' })) <NEW_LINE> response = self.app.get('/api/v1/questions/1') <NEW_LINE> self.assertEquals(response.status_code, 200) <NEW_LINE> data = json.loads(response.data) <NEW_LINE> self.assertEquals(data['question'], { 'id': 1, 'title': 'testing', 'body': 'answer test' }) | This Test class is meant to test all the routes with a GET method | 62598fb2be7bc26dc9251e9c |
class RevocationEndpoint(BaseEndpoint): <NEW_LINE> <INDENT> valid_token_types = ('access_token', 'refresh_token') <NEW_LINE> def __init__(self, request_validator, supported_token_types=None, enable_jsonp=False): <NEW_LINE> <INDENT> BaseEndpoint.__init__(self) <NEW_LINE> self.request_validator = request_validator <NEW_LINE> self.supported_token_types = ( supported_token_types or self.valid_token_types) <NEW_LINE> self.enable_jsonp = enable_jsonp <NEW_LINE> <DEDENT> @catch_errors_and_unavailability <NEW_LINE> def create_revocation_response(self, uri, http_method='POST', body=None, headers=None): <NEW_LINE> <INDENT> resp_headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'Pragma': 'no-cache', } <NEW_LINE> request = Request( uri, http_method=http_method, body=body, headers=headers) <NEW_LINE> try: <NEW_LINE> <INDENT> self.validate_revocation_request(request) <NEW_LINE> log.debug('Token revocation valid for %r.', request) <NEW_LINE> <DEDENT> except OAuth2Error as e: <NEW_LINE> <INDENT> log.debug('Client error during validation of %r. %r.', request, e) <NEW_LINE> response_body = e.json <NEW_LINE> if self.enable_jsonp and request.callback: <NEW_LINE> <INDENT> response_body = '%s(%s);' % (request.callback, response_body) <NEW_LINE> <DEDENT> resp_headers.update(e.headers) <NEW_LINE> return resp_headers, response_body, e.status_code <NEW_LINE> <DEDENT> self.request_validator.revoke_token(request.token, request.token_type_hint, request) <NEW_LINE> response_body = '' <NEW_LINE> if self.enable_jsonp and request.callback: <NEW_LINE> <INDENT> response_body = request.callback + '();' <NEW_LINE> <DEDENT> return {}, response_body, 200 <NEW_LINE> <DEDENT> def validate_revocation_request(self, request): <NEW_LINE> <INDENT> self._raise_on_missing_token(request) <NEW_LINE> self._raise_on_invalid_client(request) <NEW_LINE> self._raise_on_unsupported_token(request) | Token revocation endpoint.
Endpoint used by authenticated clients to revoke access and refresh tokens.
Commonly this will be part of the Authorization Endpoint. | 62598fb2009cb60464d015a2 |
class OAIHarvester(object): <NEW_LINE> <INDENT> def __init__(self, mdRegistry): <NEW_LINE> <INDENT> self._mdRegistry = mdRegistry <NEW_LINE> <DEDENT> def _listRecords(self, baseUrl, metadataPrefix="oai_dc", **kwargs): <NEW_LINE> <INDENT> kwargs['metadataPrefix'] = metadataPrefix <NEW_LINE> client = Client(baseUrl, metadata_registry) <NEW_LINE> client.updateGranularity() <NEW_LINE> for record in client.listRecords(**kwargs): <NEW_LINE> <INDENT> yield record <NEW_LINE> <DEDENT> <DEDENT> def harvest(self, baseUrl, metadataPrefix, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError("{0.__class__.__name__} must be sub-classed") | Abstract Base Class for an OAI-PMH Harvester.
Should be sub-classed in order to do useful things with the harvested
records (e.g. put them in a directory, VCS repository, local database etc. | 62598fb267a9b606de54604e |
class AmbienceDevice(): <NEW_LINE> <INDENT> group = None <NEW_LINE> kind = None <NEW_LINE> def get_label(self) -> str: <NEW_LINE> <INDENT> raise AmbienceDeviceException <NEW_LINE> <DEDENT> def set_label(self, label): <NEW_LINE> <INDENT> raise AmbienceDeviceException <NEW_LINE> <DEDENT> def get_online(self) -> bool: <NEW_LINE> <INDENT> raise AmbienceDeviceException <NEW_LINE> <DEDENT> def get_power(self) -> bool: <NEW_LINE> <INDENT> raise AmbienceDeviceException <NEW_LINE> <DEDENT> def set_power(self, power): <NEW_LINE> <INDENT> raise AmbienceDeviceException <NEW_LINE> <DEDENT> def get_info(self) -> dict: <NEW_LINE> <INDENT> raise AmbienceDeviceException <NEW_LINE> <DEDENT> def write_config(self) -> dict: <NEW_LINE> <INDENT> raise AmbienceDeviceException <NEW_LINE> <DEDENT> def set_group(self, group): <NEW_LINE> <INDENT> self.group = group <NEW_LINE> <DEDENT> def get_group(self) -> AmbienceGroup: <NEW_LINE> <INDENT> return self.group | Template class to be extended by other template classes that want to
represent a unique kind of device. (i.e. light) | 62598fb2167d2b6e312b6ff3 |
class Miss(Wake): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return '/' | A piece representing a square that had been unsuccessfully shot. (Wake)
Overridden Methods:
__str__ | 62598fb266656f66f7d5a470 |
class ISEOConfigSiteMapXMLSchema(Interface): <NEW_LINE> <INDENT> not_included_types = schema.Tuple( title=_("label_included_types", default=u"Types of content included in the XML Site Map"), description=_("help_included_types", default=u"The content types that should be included in the sitemap.xml.gz."), required=False, value_type=schema.Choice( vocabulary="collective.perseo.vocabularies.ReallyUserFriendlyTypes") ) <NEW_LINE> ping_google = schema.Bool( title=_("label_ping_google", default=u"Ping Google"), description=_("help_ping", default=u"Ping site automatically when the Site Map is updated."), default=False, required=False) <NEW_LINE> ping_bing = schema.Bool( title=_("label_ping_bing", default=u"Ping Bing"), description=_("help_ping", default=u"Ping site automatically when the Site Map is updated."), default=False, required=False) <NEW_LINE> ping_ask = schema.Bool( title=_("label_ping_ask", default=u"Ping Ask"), description=_("help_ping", default=u"Ping site automatically when the Site Map is updated."), default=False, required=False) | Schema for Site Map XML Tools | 62598fb226068e7796d4c9d6 |
class ReaderSHP(ReaderBaseClass): <NEW_LINE> <INDENT> def __init__(self, path, **kwargs): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self._shp_reader = fiona.open(path, 'r') <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for row in self._shp_reader: <NEW_LINE> <INDENT> flat_dict = row['properties'] <NEW_LINE> flat_dict['geometry'] = row['geometry'] <NEW_LINE> flat_dict['fiona_id'] = row['id'] <NEW_LINE> flat_dict['fiona_type'] = row['type'] <NEW_LINE> yield flat_dict <NEW_LINE> <DEDENT> <DEDENT> def __del__(self, exc_type=None, exc_val=None, exc_tb=None): <NEW_LINE> <INDENT> if self._shp_reader: <NEW_LINE> <INDENT> self._shp_reader.close() <NEW_LINE> <DEDENT> if exc_type is not None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Reader class implementation for SHP files using Fiona.
Returns a flattened Fiona record. See: http://toblerity.org/fiona/manual.html#records
Fiona generated dictionary keys id and type are transformed into key names,
fiona_id and fiona_type.
Required Config Parameters:
:param path: Attribute containing the actual file path.
Example configuration file entry::
"NaturalEarthLakes": {
"type": "ReaderSHP",
"path": "/Users/matt/Projects/dataplunger/tests/test_data/50m_lakes_utf8.shp"
} | 62598fb2d486a94d0ba2c050 |
class PrintfFormatSourceValidator(BaseValidator): <NEW_LINE> <INDENT> printf_re = re.compile( '%((?:(?P<ord>\d+)\$|\((?P<key>\w+)\))?(?P<fullvar>[+#-]*(?:\d+)?' '(?:\.\d+)?(hh\|h\|l\|ll)?(?P<type>[\w%])))' ) <NEW_LINE> def validate(self, source_trans, target_trans): <NEW_LINE> <INDENT> source_trans = unescape(source_trans) <NEW_LINE> target_trans = unescape(target_trans) <NEW_LINE> source_matches = list(self.printf_re.finditer(source_trans)) <NEW_LINE> target_matches = list(self.printf_re.finditer(target_trans)) <NEW_LINE> target_specifiers = [pat.group('type') for pat in target_matches] <NEW_LINE> target_keys = [pattern.group('key') for pattern in target_matches] <NEW_LINE> for pattern in source_matches: <NEW_LINE> <INDENT> key = pattern.group('key') <NEW_LINE> if key not in target_keys: <NEW_LINE> <INDENT> msg = "The expression '%s' is not present in the translation." <NEW_LINE> raise ValidationError( _(msg % pattern.group(0))) <NEW_LINE> <DEDENT> conversion_specifier = pattern.group('type') <NEW_LINE> try: <NEW_LINE> <INDENT> target_specifiers.remove(conversion_specifier) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> msg = "The expression '%s' is not present in the translation." <NEW_LINE> raise ValidationError( _(msg % pattern.group(0))) | Validator that checks printf-format specifiers in the source string
are preserved in the translation. | 62598fb2e5267d203ee6b985 |
class Actor: <NEW_LINE> <INDENT> def __init__(self, fp_radius=0.3): <NEW_LINE> <INDENT> self.x = 0.0 <NEW_LINE> self.y = 0.0 <NEW_LINE> self.th = 0.0 <NEW_LINE> self.path = None <NEW_LINE> self.flag_follow_traj = True <NEW_LINE> self.t_curr = 0.0 <NEW_LINE> self.counter = 0 <NEW_LINE> self.len_traj = 0 <NEW_LINE> self.fp_radius = fp_radius <NEW_LINE> self.footprint = None <NEW_LINE> self.fp_orientation = None <NEW_LINE> <DEDENT> def __set_pose__(self, new_pose): <NEW_LINE> <INDENT> self.x, self.y, self.th = new_pose <NEW_LINE> <DEDENT> def load_trajectory(self, traj=None, file_path=None): <NEW_LINE> <INDENT> if traj is None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.path = traj <NEW_LINE> self.len_traj = traj.shape[0] <NEW_LINE> self.__set_pose__(traj[0][1:]) <NEW_LINE> <DEDENT> <DEDENT> def set_follow_trajectory(self, flag_follow_traj): <NEW_LINE> <INDENT> self.flag_follow_traj = flag_follow_traj <NEW_LINE> <DEDENT> def reset(self, t_reset=0.0): <NEW_LINE> <INDENT> if t_reset < 0.0: <NEW_LINE> <INDENT> raise Exception("Can't set to time < 0!") <NEW_LINE> <DEDENT> self.counter = 0 <NEW_LINE> self.t_curr = t_reset <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def update(self, dt=0.0): <NEW_LINE> <INDENT> self.t_curr += dt <NEW_LINE> if self.path is None: <NEW_LINE> <INDENT> raise Exception("No path set yet!") <NEW_LINE> <DEDENT> while self.counter < self.len_traj and self.path[self.counter, 0] <= self.t_curr: <NEW_LINE> <INDENT> self.counter += 1 <NEW_LINE> <DEDENT> if self.counter < self.len_traj: <NEW_LINE> <INDENT> self.__set_pose__(interp_path_2d(self.path, self.counter, self.t_curr)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__set_pose__(self.path[-1, 1:]) <NEW_LINE> <DEDENT> <DEDENT> def get_pose(self): <NEW_LINE> <INDENT> return self.x, self.y, self.th <NEW_LINE> <DEDENT> def plot(self, ax): <NEW_LINE> <INDENT> if self.footprint is None: <NEW_LINE> <INDENT> self.footprint = ax.add_patch( patches.Circle( (self.x, self.y), self.fp_radius, facecolor="red", alpha=0.5 ) ) <NEW_LINE> x_plot = np.array([self.x, self.x + self.fp_radius * np.cos(self.th)]) <NEW_LINE> y_plot = np.array([self.y, self.y + self.fp_radius * np.sin(self.th)]) <NEW_LINE> self.fp_orientation = ax.plot(x_plot, y_plot, lw=2, ls='-') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.footprint.center = (self.x, self.y) <NEW_LINE> x_plot = np.array([self.x, self.x + self.fp_radius * np.cos(self.th)]) <NEW_LINE> y_plot = np.array([self.y, self.y + self.fp_radius * np.sin(self.th)]) <NEW_LINE> self.fp_orientation[0].set_xdata(x_plot) <NEW_LINE> self.fp_orientation[0].set_ydata(y_plot) <NEW_LINE> <DEDENT> <DEDENT> def plot_traj(self, ax): <NEW_LINE> <INDENT> if self.path is None: <NEW_LINE> <INDENT> raise Exception("No path set yet!") <NEW_LINE> <DEDENT> ax.plot(self.path[:, 1], self.path[:, 2], 'b-', lw=2) | A base class, defines an actor that can follow a given path in 2D
Assuming a holonomic actor, i.e. can move in all directions | 62598fb25fdd1c0f98e5e00d |
class Cola: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._frente = None <NEW_LINE> self._ultimo = None <NEW_LINE> <DEDENT> def encolar(self, dato): <NEW_LINE> <INDENT> nodo = _Nodo(dato) <NEW_LINE> if self.esta_vacia(): <NEW_LINE> <INDENT> self._frente = nodo <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ultimo.prox = nodo <NEW_LINE> <DEDENT> self._ultimo = nodo <NEW_LINE> <DEDENT> def desencolar(self): <NEW_LINE> <INDENT> if self.esta_vacia(): <NEW_LINE> <INDENT> raise ValueError("Cola vacía") <NEW_LINE> <DEDENT> dato = self._frente.dato <NEW_LINE> self._frente = self._frente.prox <NEW_LINE> if self._frente is None: <NEW_LINE> <INDENT> self._ultimo = None <NEW_LINE> <DEDENT> return dato <NEW_LINE> <DEDENT> def ver_frente(self): <NEW_LINE> <INDENT> if self.esta_vacia(): <NEW_LINE> <INDENT> raise ValueError("Cola vacía") <NEW_LINE> <DEDENT> return self._frente.dato <NEW_LINE> <DEDENT> def esta_vacia(self): <NEW_LINE> <INDENT> return self._frente is None | Representa a una cola, con operaciones de encolar y
desencolar. El primero en ser encolado es también el primero
en ser desencolado. | 62598fb2460517430c43209e |
class Routine: <NEW_LINE> <INDENT> DeployLoopRoutineID = 0xE200 <NEW_LINE> EraseMemory = 0xFF00 <NEW_LINE> CheckProgrammingDependencies = 0xFF01 <NEW_LINE> EraseMirrorMemoryDTCs = 0xFF02 <NEW_LINE> @classmethod <NEW_LINE> def name_from_id(cls, routine_id): <NEW_LINE> <INDENT> if not isinstance(routine_id, int) or routine_id < 0 or routine_id > 0xFFFF: <NEW_LINE> <INDENT> raise ValueError('Routine ID must be a valid integer between 0 and 0xFFFF') <NEW_LINE> <DEDENT> if routine_id >= 0x0000 and routine_id <= 0x00FF: <NEW_LINE> <INDENT> return 'ISOSAEReserved' <NEW_LINE> <DEDENT> if routine_id >= 0x0100 and routine_id <= 0x01FF: <NEW_LINE> <INDENT> return 'TachographTestIds' <NEW_LINE> <DEDENT> if routine_id >= 0x0200 and routine_id <= 0xDFFF: <NEW_LINE> <INDENT> return 'VehicleManufacturerSpecific' <NEW_LINE> <DEDENT> if routine_id >= 0xE000 and routine_id <= 0xE1FF: <NEW_LINE> <INDENT> return 'OBDTestIds' <NEW_LINE> <DEDENT> if routine_id == 0xE200: <NEW_LINE> <INDENT> return 'DeployLoopRoutineID' <NEW_LINE> <DEDENT> if routine_id >= 0xE201 and routine_id <= 0xE2FF: <NEW_LINE> <INDENT> return 'SafetySystemRoutineIDs' <NEW_LINE> <DEDENT> if routine_id >= 0xE300 and routine_id <= 0xEFFF: <NEW_LINE> <INDENT> return 'ISOSAEReserved' <NEW_LINE> <DEDENT> if routine_id >= 0xF000 and routine_id <= 0xFEFF: <NEW_LINE> <INDENT> return 'SystemSupplierSpecific' <NEW_LINE> <DEDENT> if routine_id == 0xFF00: <NEW_LINE> <INDENT> return 'EraseMemory' <NEW_LINE> <DEDENT> if routine_id == 0xFF01: <NEW_LINE> <INDENT> return 'CheckProgrammingDependencies' <NEW_LINE> <DEDENT> if routine_id == 0xFF02: <NEW_LINE> <INDENT> return 'EraseMirrorMemoryDTCs' <NEW_LINE> <DEDENT> if routine_id >= 0xFF03 and routine_id <= 0xFFFF: <NEW_LINE> <INDENT> return 'ISOSAEReserved' | Defines a list of constants that are routine identifiers defined by the UDS standard.
This class provides no functionality apart from defining these constants | 62598fb2baa26c4b54d4f336 |
class SupportFunctionsTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_get_version(self): <NEW_LINE> <INDENT> version = pyluksde.get_version() | Tests the support functions. | 62598fb2e5267d203ee6b986 |
class PingBench: <NEW_LINE> <INDENT> def __init__(self, ip, interval=1): <NEW_LINE> <INDENT> self.ip = ip <NEW_LINE> self.interval = interval <NEW_LINE> self.ping_cmd = 'ping -i ' + str(self.interval) + ' -w 5 ' + self.ip <NEW_LINE> self.process = pexpect.spawn(self.ping_cmd) <NEW_LINE> self.process.timeout = 50 <NEW_LINE> self.process.readline() <NEW_LINE> self.latency = [] <NEW_LINE> self.timeout = 0 <NEW_LINE> self.print_status = False <NEW_LINE> <DEDENT> def ping(self, n_sample=10): <NEW_LINE> <INDENT> for i in range(n_sample): <NEW_LINE> <INDENT> p = str(self.process.readline()) <NEW_LINE> try: <NEW_LINE> <INDENT> ping_time = float(p[p.find('time=') + 5:p.find(' ms')]) <NEW_LINE> self.latency.append(ping_time / 1000.0) <NEW_LINE> if self.print_status: <NEW_LINE> <INDENT> print("Ping: " + str(i + 1) + '/' + str(n_sample) + " --- latency: " + str(ping_time) + 'ms') <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.timeout = self.timeout + 1 <NEW_LINE> <DEDENT> <DEDENT> self.timeout = self.timeout / float(n_sample) <NEW_LINE> self.latency = numpy.array(self.latency) <NEW_LINE> <DEDENT> def get_results(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> if self.latency.size: <NEW_LINE> <INDENT> result['mean'] = numpy.mean(self.latency) <NEW_LINE> result['std'] = numpy.std(self.latency) <NEW_LINE> result['median'] = numpy.median(self.latency) <NEW_LINE> <DEDENT> return result | Ping target IP
Adapted from https://github.com/matthieu-lapeyre/network-benchmark
/blob/master/network_test.py | 62598fb244b2445a339b69b2 |
class LogMetricTrigger(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'threshold_operator': {'key': 'thresholdOperator', 'type': 'str'}, 'threshold': {'key': 'threshold', 'type': 'float'}, 'metric_trigger_type': {'key': 'metricTriggerType', 'type': 'str'}, 'metric_column': {'key': 'metricColumn', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(LogMetricTrigger, self).__init__(**kwargs) <NEW_LINE> self.threshold_operator = kwargs.get('threshold_operator', "GreaterThanOrEqual") <NEW_LINE> self.threshold = kwargs.get('threshold', None) <NEW_LINE> self.metric_trigger_type = kwargs.get('metric_trigger_type', "Consecutive") <NEW_LINE> self.metric_column = kwargs.get('metric_column', None) | A log metrics trigger descriptor.
:param threshold_operator: Evaluation operation for Metric -'GreaterThan' or 'LessThan' or
'Equal'. Possible values include: "GreaterThanOrEqual", "LessThanOrEqual", "GreaterThan",
"LessThan", "Equal". Default value: "GreaterThanOrEqual".
:type threshold_operator: str or
~$(python-base-namespace).v2018_04_16.models.ConditionalOperator
:param threshold: The threshold of the metric trigger.
:type threshold: float
:param metric_trigger_type: Metric Trigger Type - 'Consecutive' or 'Total'. Possible values
include: "Consecutive", "Total". Default value: "Consecutive".
:type metric_trigger_type: str or
~$(python-base-namespace).v2018_04_16.models.MetricTriggerType
:param metric_column: Evaluation of metric on a particular column.
:type metric_column: str | 62598fb28e7ae83300ee9125 |
class ErrataToolUnauthorizedException(Exception): <NEW_LINE> <INDENT> pass | You were not authorized to make a request to the Errata Tool API | 62598fb216aa5153ce400585 |
class CacheNameInvalid(Error): <NEW_LINE> <INDENT> pass | Name is not a valid cache name. | 62598fb2097d151d1a2c10af |
class PagerDutyPrinter(Printer): <NEW_LINE> <INDENT> def format(self, result): <NEW_LINE> <INDENT> if not result.check.pagerduty_service: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> url = "%s://%s/explore/?q=%s" % (settings.PRODUCTSTATUS_PROTOCOL, settings.PRODUCTSTATUS_HOST, result.check.product.id) <NEW_LINE> payload = { 'client': 'Productstatus', 'client_url': url, 'description': 'Integrity check failed', 'details': result.messages(), 'event_type': 'trigger', 'incident_key': result.check.pagerduty_incident, 'service_key': result.check.pagerduty_service, } <NEW_LINE> if result.get_code() == productstatus.check.OK: <NEW_LINE> <INDENT> if not result.check.pagerduty_incident: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> payload['event_type'] = 'resolve' <NEW_LINE> <DEDENT> return payload <NEW_LINE> <DEDENT> def print(self, result): <NEW_LINE> <INDENT> payload = self.format(result) <NEW_LINE> if payload is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> pagerduty_session = requests.Session() <NEW_LINE> pagerduty_session.headers.update({ 'Authorization': 'Token token=' + settings.PAGERDUTY_API_KEY, 'Accept': 'application/vnd.pagerduty+json;version=2' }) <NEW_LINE> r = pagerduty_session.post('https://events.pagerduty.com/generic/2010-04-15/create_event.json', data=json.dumps(payload)) <NEW_LINE> response = r.json() <NEW_LINE> if r.status_code < 200 or r.status_code >= 300: <NEW_LINE> <INDENT> raise Exception(response) <NEW_LINE> <DEDENT> if payload['event_type'] == 'trigger': <NEW_LINE> <INDENT> if 'incident_key' not in response: <NEW_LINE> <INDENT> raise Exception('Did not get incident key in response from PagerDuty.') <NEW_LINE> <DEDENT> result.check.pagerduty_incident = response['incident_key'] <NEW_LINE> <DEDENT> elif payload['event_type'] == 'resolve': <NEW_LINE> <INDENT> result.check.pagerduty_incident = None <NEW_LINE> <DEDENT> result.check.save() <NEW_LINE> return 1 | Submit a check result to PagerDuty. | 62598fb22ae34c7f260ab164 |
class GooglePlacesApiQueryLimitError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, *args): <NEW_LINE> <INDENT> super(GooglePlacesApiQueryLimitError, self).__init__(message, *args) | Exception raised when the query limit in the Google Places API has been
reached. | 62598fb2fff4ab517ebcd867 |
class DummyTileContents(object): <NEW_LINE> <INDENT> def __init__(self, tile_type_id, tile_footprint, band_stack): <NEW_LINE> <INDENT> self.tile_type_id = tile_type_id <NEW_LINE> self.tile_footprint = tile_footprint <NEW_LINE> self.band_stack = band_stack <NEW_LINE> self.reprojected = False <NEW_LINE> self.removed = False <NEW_LINE> assert band_stack.vrt_built, "Expected band_stack to have had a vrt built." <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ("[TileContents %s %s %s]" % (self.tile_type_id, self.tile_footprint, self.band_stack)) <NEW_LINE> <DEDENT> def reproject(self): <NEW_LINE> <INDENT> LOGGER.info("%s: reproject", self) <NEW_LINE> self.reprojected = True <NEW_LINE> <DEDENT> def has_data(self): <NEW_LINE> <INDENT> LOGGER.info("%s: has_data", self) <NEW_LINE> assert not self.removed, "%s: has been removed." % self <NEW_LINE> result = bool(not re.match(r'^empty', self.tile_footprint)) <NEW_LINE> LOGGER.info(" returning: %s", result) <NEW_LINE> return result <NEW_LINE> <DEDENT> def remove(self): <NEW_LINE> <INDENT> LOGGER.info("%s: remove", self) <NEW_LINE> self.removed = True | Dummy tile contents class for testing. | 62598fb27047854f4633f45c |
class DiGraph(Graph): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def is_directed(cls): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def dag(cls): <NEW_LINE> <INDENT> graph = cls(6) <NEW_LINE> graph.add_edge(5, 0) <NEW_LINE> graph.add_edge(5, 2) <NEW_LINE> graph.add_edge(4, 0) <NEW_LINE> graph.add_edge(4, 1) <NEW_LINE> graph.add_edge(2, 3) <NEW_LINE> graph.add_edge(3, 1) <NEW_LINE> return graph | directed graph | 62598fb263d6d428bbee282e |
class AnonymousOutbox(Outbox): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AnonymousOutbox, self).__init__('', '', *args, **kwargs) <NEW_LINE> <DEDENT> def authenticate(self, smtp): <NEW_LINE> <INDENT> pass | Outbox subclass suitable for SMTP servers that do not (or will not)
perform authentication. | 62598fb2091ae35668704c9f |
class BaseKwargsUpdatedField: <NEW_LINE> <INDENT> initial_options = None <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.update(self.initial_options) <NEW_LINE> super().__init__(*args, **kwargs) | Abstract base class made to conform the DRY principle.
The initial_options is overridden by the dict in the subclasses and then
automatically passed to kwargs in the FormField.__init__() method. | 62598fb2090684286d59371e |
class ValidateNameTest(TestCase): <NEW_LINE> <INDENT> def test_invalid_char(self): <NEW_LINE> <INDENT> with self.assertRaises(BundleError): <NEW_LINE> <INDENT> users.User.validate_name(MagicMock(), "bundle wrap") <NEW_LINE> <DEDENT> <DEDENT> def test_ends_in_dash(self): <NEW_LINE> <INDENT> with self.assertRaises(BundleError): <NEW_LINE> <INDENT> users.User.validate_name(MagicMock(), "bundlewrap-") <NEW_LINE> <DEDENT> <DEDENT> def test_too_long(self): <NEW_LINE> <INDENT> with self.assertRaises(BundleError): <NEW_LINE> <INDENT> users.User.validate_name(MagicMock(), "bundlewrapbundlewrapbundlewrapbundlewrap") <NEW_LINE> <DEDENT> <DEDENT> def test_valid(self): <NEW_LINE> <INDENT> users.User.validate_name(MagicMock(), "bundlewrap") | Tests bundlewrap.items.users.User.validate_name. | 62598fb2d7e4931a7ef3c116 |
class DependencyStrategy(Strategy): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("dependency strategy") <NEW_LINE> <DEDENT> def constraints(self, solver, vars, model): <NEW_LINE> <INDENT> for _, task in model.tasks.items(): <NEW_LINE> <INDENT> if len(task.dependencies) == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for dtask in task.dependencies: <NEW_LINE> <INDENT> _task_start = vars["{}_start".format(task.name)] <NEW_LINE> _dtask_start = vars["{}_start".format(dtask.name)] <NEW_LINE> _dtask_length = dtask.length <NEW_LINE> solver.add(_task_start >= _dtask_start + _dtask_length) | dependency strategy class | 62598fb23539df3088ecc334 |
class AskPrimeHandler(CommonHandler): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _number(expr, assumptions): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> i = int(expr.round()) <NEW_LINE> if not (expr - i).equals(0): <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return isprime(i) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def Basic(expr, assumptions): <NEW_LINE> <INDENT> if expr.is_number: <NEW_LINE> <INDENT> return AskPrimeHandler._number(expr, assumptions) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def Mul(expr, assumptions): <NEW_LINE> <INDENT> if expr.is_number: <NEW_LINE> <INDENT> return AskPrimeHandler._number(expr, assumptions) <NEW_LINE> <DEDENT> for arg in expr.args: <NEW_LINE> <INDENT> if ask(Q.integer(arg), assumptions): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def Pow(expr, assumptions): <NEW_LINE> <INDENT> if expr.is_number: <NEW_LINE> <INDENT> return AskPrimeHandler._number(expr, assumptions) <NEW_LINE> <DEDENT> if ask(Q.integer(expr.exp), assumptions) and ask(Q.integer(expr.base), assumptions): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def Integer(expr, assumptions): <NEW_LINE> <INDENT> return isprime(expr) <NEW_LINE> <DEDENT> Rational, Infinity, NegativeInfinity, ImaginaryUnit = [staticmethod(CommonHandler.AlwaysFalse)]*4 <NEW_LINE> @staticmethod <NEW_LINE> def Float(expr, assumptions): <NEW_LINE> <INDENT> return AskPrimeHandler._number(expr, assumptions) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def NumberSymbol(expr, assumptions): <NEW_LINE> <INDENT> return AskPrimeHandler._number(expr, assumptions) | Handler for key 'prime'
Test that an expression represents a prime number. When the
expression is a number the result, when True, is subject to
the limitations of isprime() which is used to return the result. | 62598fb22c8b7c6e89bd3847 |
class CinderKeystoneContext(base_wsgi.Middleware): <NEW_LINE> <INDENT> @webob.dec.wsgify(RequestClass=base_wsgi.Request) <NEW_LINE> def __call__(self, req): <NEW_LINE> <INDENT> user_id = req.headers.get('X_USER') <NEW_LINE> user_id = req.headers.get('X_USER_ID', user_id) <NEW_LINE> if user_id is None: <NEW_LINE> <INDENT> LOG.debug("Neither X_USER_ID nor X_USER found in request") <NEW_LINE> return webob.exc.HTTPUnauthorized() <NEW_LINE> <DEDENT> roles = [r.strip() for r in req.headers.get('X_ROLE', '').split(',')] <NEW_LINE> if 'X_TENANT_ID' in req.headers: <NEW_LINE> <INDENT> project_id = req.headers['X_TENANT_ID'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> project_id = req.headers['X_TENANT'] <NEW_LINE> <DEDENT> auth_token = req.headers.get('X_AUTH_TOKEN', req.headers.get('X_STORAGE_TOKEN')) <NEW_LINE> remote_address = req.remote_addr <NEW_LINE> if FLAGS.use_forwarded_for: <NEW_LINE> <INDENT> remote_address = req.headers.get('X-Forwarded-For', remote_address) <NEW_LINE> <DEDENT> ctx = context.RequestContext(user_id, project_id, roles=roles, auth_token=auth_token, remote_address=remote_address) <NEW_LINE> req.environ['cinder.context'] = ctx <NEW_LINE> return self.application | Make a request context from keystone headers | 62598fb2d486a94d0ba2c052 |
@dataclass <NEW_LINE> class TFXLNetForMultipleChoiceOutput(ModelOutput): <NEW_LINE> <INDENT> loss: Optional[tf.Tensor] = None <NEW_LINE> logits: tf.Tensor = None <NEW_LINE> mems: Optional[List[tf.Tensor]] = None <NEW_LINE> hidden_states: Optional[Tuple[tf.Tensor]] = None <NEW_LINE> attentions: Optional[Tuple[tf.Tensor]] = None | Output type of :class:`~transformers.TFXLNetForMultipleChoice`.
Args:
loss (:obj:`tf.Tensor` of shape `(1,)`, `optional`, returned when :obj:`labels` is provided):
Classification loss.
logits (:obj:`tf.Tensor` of shape :obj:`(batch_size, num_choices)`):
`num_choices` is the second dimension of the input tensors. (see `input_ids` above).
Classification scores (before SoftMax).
mems (:obj:`List[tf.Tensor]` of length :obj:`config.n_layers`):
Contains pre-computed hidden-states. Can be used (see :obj:`mems` input) to speed up sequential decoding.
The token ids which have their past given to this model should not be passed as :obj:`input_ids` as they
have already been computed.
hidden_states (:obj:`tuple(tf.Tensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`tf.Tensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(tf.Tensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`tf.Tensor` (one for each layer) of shape
:obj:`(batch_size, num_heads, sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads. | 62598fb2460517430c43209f |
class PartnerAddress(object): <NEW_LINE> <INDENT> def __init__(self, partner): <NEW_LINE> <INDENT> super(PartnerAddress, self).__init__() <NEW_LINE> self.id = partner.id <NEW_LINE> self.name = partner.name <NEW_LINE> self.street = partner.street <NEW_LINE> self.street2 = partner.street2 <NEW_LINE> self.city = partner.city <NEW_LINE> self.state = partner.state_id.name <NEW_LINE> self.state_id = partner.state_id.id <NEW_LINE> self.zip = partner.zip <NEW_LINE> self.country = partner.country_id.name <NEW_LINE> self.country_id = partner.country_id.id | Object representing a partner address for use in qweb | 62598fb267a9b606de546051 |
class C01_Read(SetupMixin, unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> SetupMixin.setUp(self) <NEW_LINE> self.m_api = hue_device.Api(self.m_pyhouse_obj) <NEW_LINE> self.m_device = HueInformation() <NEW_LINE> <DEDENT> def test_01_Init(self): <NEW_LINE> <INDENT> pass | This section tests the reading and writing of XML used by node_local.
| 62598fb24a966d76dd5eef5a |
class RyanteckRobot(Robot): <NEW_LINE> <INDENT> def __init__(self, pwm=True, pin_factory=None): <NEW_LINE> <INDENT> super(RyanteckRobot, self).__init__( left=(17, 18), right=(22, 23), pwm=pwm, pin_factory=pin_factory ) | Extends :class:`Robot` for the `Ryanteck motor controller board`_.
The Ryanteck MCB pins are fixed and therefore there's no need to specify
them when constructing this class. The following example drives the robot
forward::
from gpiozero import RyanteckRobot
robot = RyanteckRobot()
robot.forward()
:param bool pwm:
If :data:`True` (the default), construct :class:`PWMOutputDevice`
instances for the motor controller pins, allowing both direction and
variable speed control. If :data:`False`, construct
:class:`DigitalOutputDevice` instances, allowing only direction
control.
:type pin_factory: Factory or None
:param pin_factory:
See :doc:`api_pins` for more information (this is an advanced feature
which most users can ignore).
.. _Ryanteck motor controller board: https://ryanteck.uk/add-ons/6-ryanteck-rpi-motor-controller-board-0635648607160.html | 62598fb285dfad0860cbfab5 |
class S3: <NEW_LINE> <INDENT> def __init__(self, region, role, bucket): <NEW_LINE> <INDENT> self.region = region <NEW_LINE> self.client = role.client('s3', region_name=region) <NEW_LINE> self.resource = role.resource('s3', region_name=region) <NEW_LINE> self.bucket = bucket <NEW_LINE> <DEDENT> def put_object(self, key, file_path): <NEW_LINE> <INDENT> self.resource.Object(self.bucket, key).put(Body=open(file_path, 'rb')) <NEW_LINE> if self.region == 'us-east-1': <NEW_LINE> <INDENT> return "https://s3.amazonaws.com/{bucket}/{key}".format( bucket=self.bucket, key=key ) <NEW_LINE> <DEDENT> return "https://s3-{region}.amazonaws.com/{bucket}/{key}".format( region=self.region, bucket=self.bucket, key=key ) <NEW_LINE> <DEDENT> def read_object(self, key): <NEW_LINE> <INDENT> s3_object = self.resource.Object(self.bucket, key) <NEW_LINE> return s3_object.get()['Body'].read().decode('utf-8') <NEW_LINE> <DEDENT> def fetch_s3_url(self, key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s3_object = self.resource.Object(self.bucket, key) <NEW_LINE> s3_object.get() <NEW_LINE> LOGGER.info('Found Template at: %s', s3_object.key) <NEW_LINE> if self.region == 'us-east-1': <NEW_LINE> <INDENT> return "https://s3.amazonaws.com/{bucket}/{key}".format( bucket=self.bucket, key=key ) <NEW_LINE> <DEDENT> return "https://s3-{region}.amazonaws.com/{bucket}/{key}".format( region=self.region, bucket=self.bucket, key=key ) <NEW_LINE> <DEDENT> except self.client.exceptions.NoSuchKey: <NEW_LINE> <INDENT> key_level_up = key.split('/') <NEW_LINE> if len(key_level_up) == 1: <NEW_LINE> <INDENT> LOGGER.info( 'Nothing could be found for %s when traversing the bucket', key) <NEW_LINE> return [] <NEW_LINE> <DEDENT> LOGGER.info( 'Unable to find the specified Key: %s - looking one level up', key) <NEW_LINE> del key_level_up[-2] <NEW_LINE> next_level_up_key = '/'.join(key_level_up) <NEW_LINE> return self.fetch_s3_url(next_level_up_key) | Class used for modeling S3
| 62598fb292d797404e388ba5 |
class CSIMultipleChoiceField(forms.MultipleChoiceField): <NEW_LINE> <INDENT> def to_python(self, value): <NEW_LINE> <INDENT> return ','.join(value) <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> value = value.split(',') <NEW_LINE> <DEDENT> super(CSIMultipleChoiceField, self).validate(value) | Modified MultipleChoiceField for CommaSeparatedIntegerField | 62598fb255399d3f0562659d |
class User(AbstractUser): <NEW_LINE> <INDENT> username = models.CharField(max_length=30, primary_key=True) <NEW_LINE> USERNAME_FIELD = 'username' <NEW_LINE> hangman_points = models.IntegerField(default=0) | A class that extends basic user fields. It makes the username
field the id. It also stores the amount of points the user has
won from playing hangman. | 62598fb28e7ae83300ee9126 |
class Action(Editeur): <NEW_LINE> <INDENT> nom = "editeur:base:action" <NEW_LINE> def __init__(self, pere, objet=None, attribut=None, callback=None, methode=None, *arguments): <NEW_LINE> <INDENT> Editeur.__init__(self, pere, objet, attribut) <NEW_LINE> self.callback = callback <NEW_LINE> self.methode = methode <NEW_LINE> self.arguments = arguments <NEW_LINE> <DEDENT> def entrer(self): <NEW_LINE> <INDENT> self.fermer() <NEW_LINE> callback = self.callback <NEW_LINE> methode = self.methode <NEW_LINE> arguments = self.arguments <NEW_LINE> if callback and methode: <NEW_LINE> <INDENT> getattr(callback, methode)(self, *arguments) | Contexte-éditeur action.
Ce contexte sert à faire une action particulière, appelle une
méthode avec les paramètres indiqués. | 62598fb21f5feb6acb162ca2 |
class BertEncoderExtended(nn.Module): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> super(BertEncoderExtended, self).__init__() <NEW_LINE> self.output_attentions = config.output_attentions <NEW_LINE> self.output_hidden_states = config.output_hidden_states <NEW_LINE> self.layer = nn.ModuleList([mb.BertLayer(config) for _ in range(config.num_hidden_layers - 1)]) <NEW_LINE> self.last_layer = BertLayerExtended(config) <NEW_LINE> <DEDENT> def forward(self, hidden_states, attention_mask, head_mask=None): <NEW_LINE> <INDENT> all_hidden_states = () <NEW_LINE> all_attentions = () <NEW_LINE> for i, layer_module in enumerate(self.layer): <NEW_LINE> <INDENT> if self.output_hidden_states: <NEW_LINE> <INDENT> all_hidden_states = all_hidden_states + (hidden_states,) <NEW_LINE> <DEDENT> layer_outputs = layer_module(hidden_states, attention_mask, head_mask[i]) <NEW_LINE> hidden_states = layer_outputs[0] <NEW_LINE> if self.output_attentions: <NEW_LINE> <INDENT> all_attentions = all_attentions + (layer_outputs[1],) <NEW_LINE> <DEDENT> <DEDENT> if self.output_hidden_states: <NEW_LINE> <INDENT> all_hidden_states = all_hidden_states + (hidden_states,) <NEW_LINE> <DEDENT> layer_outputs = self.last_layer(hidden_states, attention_mask, head_mask[-1]) <NEW_LINE> layer_outputs_keys = layer_outputs[0] <NEW_LINE> layer_outputs_queries = layer_outputs[1] <NEW_LINE> layer_outputs_values = layer_outputs[2] <NEW_LINE> layer_outputs_attention = layer_outputs[3] <NEW_LINE> hidden_states = layer_outputs_values <NEW_LINE> if self.output_attentions: <NEW_LINE> <INDENT> all_attentions = all_attentions + (layer_outputs_attention,) <NEW_LINE> <DEDENT> if self.output_hidden_states: <NEW_LINE> <INDENT> all_hidden_states = all_hidden_states + (hidden_states,) <NEW_LINE> <DEDENT> outputs = ((layer_outputs_keys, layer_outputs_queries, layer_outputs_values),) <NEW_LINE> if self.output_hidden_states: <NEW_LINE> <INDENT> outputs = outputs + (all_hidden_states,) <NEW_LINE> <DEDENT> if self.output_attentions: <NEW_LINE> <INDENT> outputs = outputs + (all_attentions,) <NEW_LINE> <DEDENT> return outputs | Small modification from mb.BertEncoder to return three outputs in the last layer, instead of one. These three
values represent "queries", "keys" and "values" to use for the pointing, mimicking the self-attention the model has
inside. | 62598fb291f36d47f2230ee9 |
class ProxyResponse(CasResponseBase): <NEW_LINE> <INDENT> def render_content(self, context): <NEW_LINE> <INDENT> ticket = context.get('ticket') <NEW_LINE> error = context.get('error') <NEW_LINE> service_response = etree.Element(self.ns('serviceResponse')) <NEW_LINE> if ticket: <NEW_LINE> <INDENT> proxy_success = etree.SubElement(service_response, self.ns('proxySuccess')) <NEW_LINE> proxy_ticket = etree.SubElement(proxy_success, self.ns('proxyTicket')) <NEW_LINE> proxy_ticket.text = ticket.ticket <NEW_LINE> <DEDENT> elif error: <NEW_LINE> <INDENT> proxy_failure = etree.SubElement(service_response, self.ns('proxyFailure')) <NEW_LINE> proxy_failure.set('code', error.code) <NEW_LINE> proxy_failure.text = str(error) <NEW_LINE> <DEDENT> return etree.tostring(service_response, encoding='UTF-8') | (2.7.2) Render an XML format CAS service response for a proxy
request success or failure.
On request success:
<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
<cas:proxySuccess>
<cas:proxyTicket>PT-1856392-b98xZrQN4p90ASrw96c8</cas:proxyTicket>
</cas:proxySuccess>
</cas:serviceResponse>
On request failure:
<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
<cas:proxyFailure code="INVALID_REQUEST">
'pgt' and 'targetService' parameters are both required
</cas:proxyFailure>
</cas:serviceResponse> | 62598fb2f548e778e596b627 |
class World: <NEW_LINE> <INDENT> def __init__(self, size): <NEW_LINE> <INDENT> self.size = size <NEW_LINE> self.things = {} <NEW_LINE> self.effects = {} <NEW_LINE> self.t = 0 <NEW_LINE> <DEDENT> def spawn(self, thing, position): <NEW_LINE> <INDENT> if not inside_map(position, self.size): <NEW_LINE> <INDENT> message = "Can't spawn things outside the map {}".format(position) <NEW_LINE> raise Exception(message) <NEW_LINE> <DEDENT> other = self.things.get(position) <NEW_LINE> if other is None: <NEW_LINE> <INDENT> self.things[position] = thing <NEW_LINE> thing.position = position <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = "Can't place {} in a position occupied by {}." <NEW_LINE> raise Exception(message.format(thing, other)) <NEW_LINE> <DEDENT> <DEDENT> def destroy(self, thing): <NEW_LINE> <INDENT> del self.things[thing.position] <NEW_LINE> thing.position = None <NEW_LINE> <DEDENT> def import_map(self, map_text): <NEW_LINE> <INDENT> for row_index, line in enumerate(map_text.split('\n')): <NEW_LINE> <INDENT> for col_index, char in enumerate(line): <NEW_LINE> <INDENT> position = (col_index, row_index) <NEW_LINE> if char == 'T': <NEW_LINE> <INDENT> self.spawn(Tree(), position) <NEW_LINE> <DEDENT> elif char == 'r': <NEW_LINE> <INDENT> self.spawn(Tower(settings.TEAM_RADIANT), position) <NEW_LINE> <DEDENT> elif char == 'd': <NEW_LINE> <INDENT> self.spawn(Tower(settings.TEAM_DIRE), position) <NEW_LINE> <DEDENT> elif char == 'R': <NEW_LINE> <INDENT> self.spawn(Ancient(settings.TEAM_RADIANT), position) <NEW_LINE> <DEDENT> elif char == 'D': <NEW_LINE> <INDENT> self.spawn(Ancient(settings.TEAM_DIRE), position) | World where to play the game. | 62598fb216aa5153ce400587 |
class ExtensionManager(object): <NEW_LINE> <INDENT> def is_loaded(self, alias): <NEW_LINE> <INDENT> return alias in self.extensions <NEW_LINE> <DEDENT> def register(self, ext): <NEW_LINE> <INDENT> if not self._check_extension(ext): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> alias = ext.alias <NEW_LINE> LOG.audit(_('Loaded extension: %s'), alias) <NEW_LINE> if alias in self.extensions: <NEW_LINE> <INDENT> raise exception.NovaException("Found duplicate extension: %s" % alias) <NEW_LINE> <DEDENT> self.extensions[alias] = ext <NEW_LINE> <DEDENT> def get_resources(self): <NEW_LINE> <INDENT> resources = [] <NEW_LINE> resources.append(ResourceExtension('extensions', ExtensionsResource(self))) <NEW_LINE> for ext in self.extensions.values(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resources.extend(ext.get_resources()) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return resources <NEW_LINE> <DEDENT> def get_controller_extensions(self): <NEW_LINE> <INDENT> controller_exts = [] <NEW_LINE> for ext in self.extensions.values(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> controller_exts.extend(ext.get_controller_extensions()) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return controller_exts <NEW_LINE> <DEDENT> def _check_extension(self, extension): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> LOG.debug(_('Ext name: %s'), extension.name) <NEW_LINE> LOG.debug(_('Ext alias: %s'), extension.alias) <NEW_LINE> LOG.debug(_('Ext description: %s'), ' '.join(extension.__doc__.strip().split())) <NEW_LINE> LOG.debug(_('Ext namespace: %s'), extension.namespace) <NEW_LINE> LOG.debug(_('Ext updated: %s'), extension.updated) <NEW_LINE> <DEDENT> except AttributeError as ex: <NEW_LINE> <INDENT> LOG.exception(_("Exception loading extension: %s"), unicode(ex)) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> def load_extension(self, ext_factory): <NEW_LINE> <INDENT> LOG.debug(_("Loading extension %s"), ext_factory) <NEW_LINE> if isinstance(ext_factory, basestring): <NEW_LINE> <INDENT> factory = importutils.import_class(ext_factory) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> factory = ext_factory <NEW_LINE> <DEDENT> LOG.debug(_("Calling extension factory %s"), ext_factory) <NEW_LINE> factory(self) <NEW_LINE> <DEDENT> def _load_extensions(self): <NEW_LINE> <INDENT> extensions = list(self.cls_list) <NEW_LINE> for ext_factory in extensions: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.load_extension(ext_factory) <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> LOG.warn(_('Failed to load extension %(ext_factory)s: ' '%(exc)s') % locals()) | Load extensions from the configured extension path.
See nova/tests/api/openstack/volume/extensions/foxinsocks.py or an
example extension implementation. | 62598fb24428ac0f6e6585a4 |
class AlphaBetaAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> legalActions = gameState.getLegalActions(0) <NEW_LINE> numAgents = gameState.getNumAgents() <NEW_LINE> bestAction = None <NEW_LINE> maxi = -999999 <NEW_LINE> a = -999999 <NEW_LINE> b = 999999 <NEW_LINE> for action in legalActions: <NEW_LINE> <INDENT> currDepth = 0 <NEW_LINE> currMax = self.min_value(gameState.generateSuccessor(0, action), currDepth, 1, numAgents, a, b) <NEW_LINE> if currMax > maxi: <NEW_LINE> <INDENT> maxi = currMax <NEW_LINE> bestAction = action <NEW_LINE> <DEDENT> if currMax > b: <NEW_LINE> <INDENT> return bestAction <NEW_LINE> <DEDENT> a = max([currMax, a]) <NEW_LINE> <DEDENT> return bestAction <NEW_LINE> <DEDENT> def min_value(self, state, currDepth, agentIndex, numAgents, a, b): <NEW_LINE> <INDENT> if state.isWin() or state.isLose(): <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LINE> <DEDENT> v = 999999 <NEW_LINE> for action in state.getLegalActions(agentIndex): <NEW_LINE> <INDENT> newAgentIndex = (agentIndex + 1) % numAgents <NEW_LINE> if agentIndex == state.getNumAgents() - 1: <NEW_LINE> <INDENT> v = min([v, self.max_value(state.generateSuccessor(agentIndex, action), currDepth, newAgentIndex, numAgents, a, b)]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = min([v, self.min_value(state.generateSuccessor(agentIndex, action), currDepth, newAgentIndex, numAgents, a, b)]) <NEW_LINE> <DEDENT> if v < a: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> b = min([v, b]) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> def max_value(self, state, currDepth, agentIndex, numAgents, a, b): <NEW_LINE> <INDENT> currDepth += 1 <NEW_LINE> if state.isWin() or state.isLose(): <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LINE> <DEDENT> elif currDepth == self.depth: <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LINE> <DEDENT> v = -999999 <NEW_LINE> for action in state.getLegalActions(agentIndex): <NEW_LINE> <INDENT> newAgentIndex = (agentIndex + 1) % numAgents <NEW_LINE> v = max([v, self.min_value(state.generateSuccessor(agentIndex, action), currDepth, newAgentIndex, numAgents, a, b)]) <NEW_LINE> if v > b: <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> a = max([v, a]) <NEW_LINE> <DEDENT> return v | Your minimax agent with alpha-beta pruning (question 3) | 62598fb266673b3332c30450 |
class Bullet(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, ship): <NEW_LINE> <INDENT> super(Bullet, self).__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) <NEW_LINE> self.rect.centerx = ship.rect.centerx <NEW_LINE> self.rect.top = ship.rect.top <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.color = ai_settings.bullet_color <NEW_LINE> self.speed_factor = ai_settings.bullet_speed_factor <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.y -= self.speed_factor <NEW_LINE> self.rect.y = self.y <NEW_LINE> <DEDENT> def draw_bullet(self): <NEW_LINE> <INDENT> pygame.draw.rect(self.screen, self.color, self.rect) | A class to manage bullets fired from the ship | 62598fb2aad79263cf42e857 |
class CaptionDriver(SerialDriver): <NEW_LINE> <INDENT> def _tool_name(self): <NEW_LINE> <INDENT> return "captioncompiler" <NEW_LINE> <DEDENT> def precompile(self, context: AssetBuildContext, asset: Asset) -> List[str]: <NEW_LINE> <INDENT> asset.outpath = asset.path.with_suffix(".dat") <NEW_LINE> return PrecompileResult([asset.path], [asset.outpath]) <NEW_LINE> <DEDENT> def compile(self, context: AssetBuildContext, asset: Asset) -> bool: <NEW_LINE> <INDENT> args = [str(self.tool), str(asset.path)] <NEW_LINE> returncode = self.env.run_tool(args, source=True) <NEW_LINE> return returncode == 0 | Driver that handles compiling closed captions | 62598fb2090684286d59371f |
class QuerySetSequenceModel(object): <NEW_LINE> <INDENT> class DoesNotExist(ObjectDoesNotExist): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class MultipleObjectsReturned(MultipleObjectsReturned): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class _meta: <NEW_LINE> <INDENT> object_name = 'QuerySetSequenceModel' | A fake Model that is used to throw DoesNotExist exceptions for
QuerySetSequence. | 62598fb29c8ee823130401b4 |
class BackupRestoration(core_models.UuidMixin, TimeStampedModel): <NEW_LINE> <INDENT> backup = models.ForeignKey(Backup, related_name='restorations') <NEW_LINE> instance = models.OneToOneField(Instance, related_name='+') <NEW_LINE> flavor = models.ForeignKey(Flavor, related_name='+', null=True, blank=True, on_delete=models.SET_NULL) <NEW_LINE> class Permissions(object): <NEW_LINE> <INDENT> customer_path = 'backup__service_project_link__project__customer' <NEW_LINE> project_path = 'backup__service_project_link__project' | This model corresponds to instance restoration from backup. | 62598fb27b180e01f3e49092 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.