code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class po2ini(object): <NEW_LINE> <INDENT> SourceStoreClass = po.pofile <NEW_LINE> TargetStoreClass = ini.inifile <NEW_LINE> TargetUnitClass = ini.iniunit <NEW_LINE> MissingTemplateMessage = "A template INI file must be provided." <NEW_LINE> def __init__(self, input_file, output_file, template_file=None, include_fuzzy=False, output_threshold=None, dialect="default"): <NEW_LINE> <INDENT> import sys <NEW_LINE> if sys.version_info[0] == 3: <NEW_LINE> <INDENT> print("Translate Toolkit doesn't yet support converting to INI in " "Python 3.") <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> if template_file is None: <NEW_LINE> <INDENT> raise ValueError(self.MissingTemplateMessage) <NEW_LINE> <DEDENT> self.source_store = self.SourceStoreClass(input_file) <NEW_LINE> self.should_output_store = convert.should_output_store( self.source_store, output_threshold ) <NEW_LINE> if self.should_output_store: <NEW_LINE> <INDENT> self.include_fuzzy = include_fuzzy <NEW_LINE> self.output_file = output_file <NEW_LINE> self.template_store = self.TargetStoreClass(template_file, dialect=dialect) <NEW_LINE> self.target_store = self.TargetStoreClass(dialect=dialect) <NEW_LINE> <DEDENT> <DEDENT> def merge_stores(self): <NEW_LINE> <INDENT> self.source_store.makeindex() <NEW_LINE> for template_unit in self.template_store.units: <NEW_LINE> <INDENT> for location in template_unit.getlocations(): <NEW_LINE> <INDENT> if location in self.source_store.locationindex: <NEW_LINE> <INDENT> source_unit = self.source_store.locationindex[location] <NEW_LINE> if source_unit.isfuzzy() and not self.include_fuzzy: <NEW_LINE> <INDENT> template_unit.target = template_unit.source <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> template_unit.target = source_unit.target <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> template_unit.target = template_unit.source <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> if not self.should_output_store: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> self.merge_stores() <NEW_LINE> self.template_store.serialize(self.output_file) <NEW_LINE> return 1
Convert a PO file and a template INI file to a INI file.
625990560fa83653e46f6439
class Eigenvectors(Builtin): <NEW_LINE> <INDENT> messages = { 'eigenvecnotimplemented': ( "Eigenvectors is not yet implemented for the matrix `1`."), } <NEW_LINE> def apply(self, m, evaluation): <NEW_LINE> <INDENT> matrix = to_sympy_matrix(m) <NEW_LINE> if matrix is None or matrix.cols != matrix.rows or matrix.cols == 0: <NEW_LINE> <INDENT> return evaluation.message('Eigenvectors', 'matsq', m) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> eigenvects = matrix.eigenvects() <NEW_LINE> <DEDENT> except NotImplementedError: <NEW_LINE> <INDENT> return evaluation.message( 'Eigenvectors', 'eigenvecnotimplemented', m) <NEW_LINE> <DEDENT> eigenvects = sorted(eigenvects, key=lambda val_c_vect: (abs(val_c_vect[0]), -val_c_vect[0]), reverse=True) <NEW_LINE> result = [] <NEW_LINE> for val, count, basis in eigenvects: <NEW_LINE> <INDENT> vects = [from_sympy(list(b)) for b in basis] <NEW_LINE> vects.reverse() <NEW_LINE> result.extend(vects) <NEW_LINE> <DEDENT> result.extend([Expression('List', *( [0] * matrix.rows))] * (matrix.rows - len(result))) <NEW_LINE> return Expression('List', *result)
<dl> <dt>'Eigenvectors[$m$]' <dd>computes the eigenvectors of the matrix $m$. </dl> >> Eigenvectors[{{1, 1, 0}, {1, 0, 1}, {0, 1, 1}}] = {{1, 1, 1}, {1, -2, 1}, {-1, 0, 1}} >> Eigenvectors[{{1, 0, 0}, {0, 1, 0}, {0, 0, 0}}] = {{0, 1, 0}, {1, 0, 0}, {0, 0, 1}} >> Eigenvectors[{{2, 0, 0}, {0, -1, 0}, {0, 0, 0}}] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}} >> Eigenvectors[{{0.1, 0.2}, {0.8, 0.5}}] = {{0.309017, 1.}, {-0.809017, 1.}} #> Eigenvectors[{{-2, 1, -1}, {-3, 2, 1}, {-1, 1, 0}}] = {{1 / 3, 7 / 3, 1}, {1, 1, 0}, {0, 0, 0}}
625990563eb6a72ae038bbb4
@implementer(ILogObserver) <NEW_LINE> class LegacyLogObserverWrapper(object): <NEW_LINE> <INDENT> def __init__(self, legacyObserver): <NEW_LINE> <INDENT> self.legacyObserver = legacyObserver <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ( "{self.__class__.__name__}({self.legacyObserver})" .format(self=self) ) <NEW_LINE> <DEDENT> def __call__(self, event): <NEW_LINE> <INDENT> if "message" not in event: <NEW_LINE> <INDENT> event["message"] = () <NEW_LINE> <DEDENT> if "time" not in event: <NEW_LINE> <INDENT> event["time"] = event["log_time"] <NEW_LINE> <DEDENT> if "system" not in event: <NEW_LINE> <INDENT> event["system"] = event.get("log_system", "-") <NEW_LINE> <DEDENT> if "format" not in event and event.get("log_format", None) is not None: <NEW_LINE> <INDENT> event["format"] = "%(log_legacy)s" <NEW_LINE> event["log_legacy"] = StringifiableFromEvent(event.copy()) <NEW_LINE> <DEDENT> if "log_failure" in event: <NEW_LINE> <INDENT> if "failure" not in event: <NEW_LINE> <INDENT> event["failure"] = event["log_failure"] <NEW_LINE> <DEDENT> if "isError" not in event: <NEW_LINE> <INDENT> event["isError"] = 1 <NEW_LINE> <DEDENT> if "why" not in event: <NEW_LINE> <INDENT> event["why"] = formatEvent(event) <NEW_LINE> <DEDENT> <DEDENT> elif "isError" not in event: <NEW_LINE> <INDENT> event["isError"] = 0 <NEW_LINE> <DEDENT> self.legacyObserver(event)
L{ILogObserver} that wraps an L{twisted.python.log.ILogObserver}. Received (new-style) events are modified prior to forwarding to the legacy observer to ensure compatibility with observers that expect legacy events.
6259905623849d37ff852619
class RequestIDMiddleware(BaseHTTPMiddleware): <NEW_LINE> <INDENT> async def dispatch(self, request: Request, call_next: RequestResponseEndpoint): <NEW_LINE> <INDENT> request = Request(request.scope, request.receive) <NEW_LINE> return await call_next(request)
API Server middleware to include a unique X-Request-ID in incoming requests headers.
62599056b57a9660fecd2fd0
class AzureFirewall(Resource): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'etag': {'key': 'etag', 'type': 'str'}, 'application_rule_collections': {'key': 'properties.applicationRuleCollections', 'type': '[AzureFirewallApplicationRuleCollection]'}, 'network_rule_collections': {'key': 'properties.networkRuleCollections', 'type': '[AzureFirewallNetworkRuleCollection]'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[AzureFirewallIPConfiguration]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AzureFirewall, self).__init__(**kwargs) <NEW_LINE> self.etag = None <NEW_LINE> self.application_rule_collections = kwargs.get('application_rule_collections', None) <NEW_LINE> self.network_rule_collections = kwargs.get('network_rule_collections', None) <NEW_LINE> self.ip_configurations = kwargs.get('ip_configurations', None) <NEW_LINE> self.provisioning_state = kwargs.get('provisioning_state', None)
Azure Firewall resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :ivar etag: Gets a unique read-only string that changes whenever the resource is updated. :vartype etag: str :param application_rule_collections: Collection of application rule collections used by a Azure Firewall. :type application_rule_collections: list[~azure.mgmt.network.v2018_04_01.models.AzureFirewallApplicationRuleCollection] :param network_rule_collections: Collection of network rule collections used by a Azure Firewall. :type network_rule_collections: list[~azure.mgmt.network.v2018_04_01.models.AzureFirewallNetworkRuleCollection] :param ip_configurations: IP configuration of the Azure Firewall resource. :type ip_configurations: list[~azure.mgmt.network.v2018_04_01.models.AzureFirewallIPConfiguration] :param provisioning_state: The provisioning state of the resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed". :type provisioning_state: str or ~azure.mgmt.network.v2018_04_01.models.ProvisioningState
625990568e71fb1e983bd01e
class Contacts(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'contact_list': {'key': 'contacts', 'type': '[Contact]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(Contacts, self).__init__(**kwargs) <NEW_LINE> self.id = None <NEW_LINE> self.contact_list = kwargs.get('contact_list', None)
The contacts for the vault certificates. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Identifier for the contacts collection. :vartype id: str :ivar contact_list: The contact list for the vault certificates. :vartype contact_list: list[~azure.keyvault.v2016_10_01.models.Contact]
62599056baa26c4b54d507f8
class Jogador( Nave ): <NEW_LINE> <INDENT> def __init__( self, posicao, explosao, vidas=10, imagem=None ): <NEW_LINE> <INDENT> Nave.__init__( self, posicao, explosao, vidas, [ 0, 0 ], imagem ) <NEW_LINE> self.set_XP( 0 ) <NEW_LINE> <DEDENT> def update( self, dt ): <NEW_LINE> <INDENT> velocidade_mov = ( self.velocidade[ 0 ] * dt / 16, self.velocidade[ 1 ] * dt / 16) <NEW_LINE> self.rect = self.rect.move( velocidade_mov ) <NEW_LINE> if ( self.rect.right > self.area.right ): <NEW_LINE> <INDENT> self.rect.right = self.area.right <NEW_LINE> <DEDENT> elif ( self.rect.left < 0 ): <NEW_LINE> <INDENT> self.rect.left = 0 <NEW_LINE> <DEDENT> if ( self.rect.bottom > self.area.bottom ): <NEW_LINE> <INDENT> self.rect.bottom = self.area.bottom <NEW_LINE> <DEDENT> elif ( self.rect.top < 0 ): <NEW_LINE> <INDENT> self.rect.top = 0 <NEW_LINE> <DEDENT> <DEDENT> def get_posicao( self ): <NEW_LINE> <INDENT> return ( self.rect.center[ 0 ], self.rect.top ) <NEW_LINE> <DEDENT> def get_XP( self ): <NEW_LINE> <INDENT> return self.XP <NEW_LINE> <DEDENT> def set_XP( self, XP ): <NEW_LINE> <INDENT> self.XP = XP <NEW_LINE> <DEDENT> def tiro( self, lista_tiros, imagem=None ): <NEW_LINE> <INDENT> l = 1 <NEW_LINE> if self.XP > 10: l = 3 <NEW_LINE> if self.XP > 50: l = 5 <NEW_LINE> posicao = self.get_posicao() <NEW_LINE> velocidades = self.get_velocidade_tiro( l ) <NEW_LINE> for velocidade in velocidades: <NEW_LINE> <INDENT> Tiro( posicao, velocidade, imagem, lista_tiros ) <NEW_LINE> <DEDENT> <DEDENT> def get_velocidade_tiro( self, municao ): <NEW_LINE> <INDENT> velocidades = [] <NEW_LINE> if municao <= 0: <NEW_LINE> <INDENT> return velocidades <NEW_LINE> <DEDENT> if municao == 1: <NEW_LINE> <INDENT> velocidades += [ ( 0, -5 ) ] <NEW_LINE> <DEDENT> if municao > 1 and municao <= 3: <NEW_LINE> <INDENT> velocidades += [ ( 0, -5 ) ] <NEW_LINE> velocidades += [ ( -2, -3 ) ] <NEW_LINE> velocidades += [ ( 2, -3 ) ] <NEW_LINE> <DEDENT> if municao > 3 and municao <= 5: <NEW_LINE> <INDENT> velocidades += [ ( 0, -5 ) ] <NEW_LINE> velocidades += [ ( -2, -3 ) ] <NEW_LINE> velocidades += [ ( 2, -3 ) ] <NEW_LINE> velocidades += [ ( -4, -2 ) ] <NEW_LINE> velocidades += [ ( 4, -2 ) ] <NEW_LINE> <DEDENT> return velocidades
A classe Jogador é uma classe derivada da classe GameObject.
625990563539df3088ecd7fb
class _AA1(_GaitPolicy): <NEW_LINE> <INDENT> def __init__(self, gait, param_name): <NEW_LINE> <INDENT> super(_AA1, self).__init__(gait, 1) <NEW_LINE> self.param = param_name <NEW_LINE> <DEDENT> def initial_action(self): <NEW_LINE> <INDENT> value = self.gait.params[self.param][0] <NEW_LINE> return np.atleast_2d([value]).T <NEW_LINE> <DEDENT> def update(self, action): <NEW_LINE> <INDENT> self.gait.params[self.param] = (action[0, 0], action[0, 0], action[0, 0], action[0, 0])
All legs; One parameter
62599056d7e4931a7ef3d5d3
class PicFetchFailedException(Exception): <NEW_LINE> <INDENT> pass
Thrown when a category fails to download an image
62599056baa26c4b54d507f9
class TestLPathConverter(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_LpathParser(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_LpathToSparql(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_LpathChild(self): <NEW_LINE> <INDENT> query = "//time/Ae" <NEW_LINE> p = lpath_parser.parser(query) <NEW_LINE> self.assertEqual(type(p), pyparsing.ParseResults) <NEW_LINE> self.assertEqual(p.exp.connector, "//") <NEW_LINE> self.assertEqual(p.exp.right.left.text, "time") <NEW_LINE> self.assertEqual(p.exp.right.right.text, "Ae") <NEW_LINE> self.assertEqual(p.exp.right.connector, "/") <NEW_LINE> q = lpath_parser.lpathToSparql(query) <NEW_LINE> <DEDENT> def test_LpathSequence(self): <NEW_LINE> <INDENT> query = "//t->Ae" <NEW_LINE> p = lpath_parser.parser(query) <NEW_LINE> self.assertEqual(type(p), pyparsing.ParseResults) <NEW_LINE> self.assertEqual(p.exp.connector, "//") <NEW_LINE> self.assertEqual(p.exp.right.left.text, "t") <NEW_LINE> self.assertEqual(p.exp.right.right.text, "Ae") <NEW_LINE> self.assertEqual(p.exp.right.connector, "->") <NEW_LINE> q = lpath_parser.lpathToSparql(query) <NEW_LINE> <DEDENT> def test_LpathPredicate(self): <NEW_LINE> <INDENT> query = "//time[/Ae]" <NEW_LINE> p = lpath_parser.parser(query) <NEW_LINE> self.assertEqual(type(p), pyparsing.ParseResults) <NEW_LINE> self.assertEqual(p.exp.connector, "//") <NEW_LINE> self.assertEqual(p.exp.right.text, "time") <NEW_LINE> self.assertEqual(p.exp.right.predicate.right.text, "Ae") <NEW_LINE> self.assertEqual(p.exp.right.predicate.connector, "/") <NEW_LINE> q = lpath_parser.lpathToSparql(query) <NEW_LINE> <DEDENT> def test_LpathPredicateNest(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_LpathAttribute(self): <NEW_LINE> <INDENT> query = "//time[@dada:type=maus:orthography]" <NEW_LINE> p = lpath_parser.parser(query) <NEW_LINE> self.assertEqual(type(p), pyparsing.ParseResults) <NEW_LINE> self.assertEqual(p.exp.connector, "//") <NEW_LINE> self.assertEqual(p.exp.right.text, "time") <NEW_LINE> self.assertEqual(p.exp.right.attr_test.attr, "dada:type") <NEW_LINE> self.assertEqual(p.exp.right.attr_test.attr_val, "maus:orthography") <NEW_LINE> q = lpath_parser.lpathToSparql(query) <NEW_LINE> <DEDENT> def test_LpathWildcard(self): <NEW_LINE> <INDENT> query = "//_[/t]" <NEW_LINE> p = lpath_parser.parser(query) <NEW_LINE> self.assertEqual(type(p), pyparsing.ParseResults) <NEW_LINE> self.assertEqual(p.exp.connector, "//") <NEW_LINE> self.assertEqual(p.exp.right.text, "_") <NEW_LINE> self.assertEqual(p.exp.right.predicate.right.text, "t") <NEW_LINE> self.assertEqual(p.exp.right.predicate.connector, "/") <NEW_LINE> q = lpath_parser.lpathToSparql(query) <NEW_LINE> <DEDENT> def test_LpathNot(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_LpathOr(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_LpathAnd(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_LpathFunction(self): <NEW_LINE> <INDENT> pass
LPath+ to SPARQL converter
625990568da39b475be04741
class MessageDataFinder(MetaPathFinder): <NEW_LINE> <INDENT> expr = re.compile(r"message_ix_models\.(?P<name>(model|project)\..*)") <NEW_LINE> @classmethod <NEW_LINE> def find_spec(cls, name, path, target=None): <NEW_LINE> <INDENT> match = cls.expr.match(name) <NEW_LINE> try: <NEW_LINE> <INDENT> new_name = f"message_data.{match.group('name')}" <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> spec = util.find_spec(new_name) <NEW_LINE> if not spec: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> new_spec = ModuleSpec( name=name, loader=SourceFileLoader(fullname=name, path=spec.origin), origin=spec.origin, ) <NEW_LINE> new_spec.submodule_search_locations = spec.submodule_search_locations <NEW_LINE> return new_spec
Load model and project code from :mod:`message_data`.
62599056fff4ab517ebced78
class PublicationsList(ListView): <NEW_LINE> <INDENT> model = Publication <NEW_LINE> template_name = 'news/publications_list.html' <NEW_LINE> context_object_name = 'publications' <NEW_LINE> ordering = ['-published_date'] <NEW_LINE> paginate_by = 5
This class is a child of ListView (declared in django class) Used when View should use a template to show a list of instances of single object (model in this context)
625990564a966d76dd5f0446
class AnnotateCycles(Transformation): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> <DEDENT> def apply(self, model): <NEW_LINE> <INDENT> graph = model.graph <NEW_LINE> for node in graph.node: <NEW_LINE> <INDENT> if _is_fpgadataflow_node(node): <NEW_LINE> <INDENT> op_inst = registry.getCustomOp(node) <NEW_LINE> cycles = op_inst.get_exp_cycles() <NEW_LINE> op_inst.set_nodeattr("cycles_estimate", cycles) <NEW_LINE> <DEDENT> elif node.op_type == "StreamingDataflowPartition": <NEW_LINE> <INDENT> sdp_model_filename = getCustomOp(node).get_nodeattr("model") <NEW_LINE> sdp_model = ModelWrapper(sdp_model_filename) <NEW_LINE> sdp_model = sdp_model.transform(AnnotateCycles()) <NEW_LINE> sdp_model.save(sdp_model_filename) <NEW_LINE> <DEDENT> <DEDENT> return (model, False)
Annotate the estimate of clock cycles per sample taken by each fpgadataflow node as an attribute on the node.
625990568e7ae83300eea5e3
class element(VegaSchema): <NEW_LINE> <INDENT> _schema = {'$ref': '#/refs/element'} <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> super(element, self).__init__(*args)
element schema wrapper string
6259905699cbb53fe6832435
class Pipe: <NEW_LINE> <INDENT> def __init__(self, prumer=50): <NEW_LINE> <INDENT> self.prumer = prumer <NEW_LINE> <DEDENT> def objem(self, delka=1): <NEW_LINE> <INDENT> from math import pi <NEW_LINE> r = (self.prumer / 2) / 100 <NEW_LINE> h = delka * 10 <NEW_LINE> return int(pi * r**2 * h)
Vypocita objem vody v trubce. Zadej __init__(prumer v mm) objem(delka v metrech)
625990564e696a045264e8cd
class ProjectsConfigsOperationsService(base_api.BaseApiService): <NEW_LINE> <INDENT> _NAME = u'projects_configs_operations' <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(RuntimeconfigV1beta1.ProjectsConfigsOperationsService, self).__init__(client) <NEW_LINE> self._method_configs = { 'Get': base_api.ApiMethodInfo( http_method=u'GET', method_id=u'runtimeconfig.projects.configs.operations.get', ordered_params=[u'projectsId', u'configsId', u'operationsId'], path_params=[u'configsId', u'operationsId', u'projectsId'], query_params=[], relative_path=u'v1beta1/projects/{projectsId}/configs/{configsId}/operations/{operationsId}', request_field='', request_type_name=u'RuntimeconfigProjectsConfigsOperationsGetRequest', response_type_name=u'Operation', supports_download=False, ), } <NEW_LINE> self._upload_configs = { } <NEW_LINE> <DEDENT> def Get(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Get') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params)
Service class for the projects_configs_operations resource.
625990564e4d56256637395d
class Column(Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Column, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.type = kwargs.get('type', None)
A table column. A column in a table. :param name: The name of this column. :type name: str :param type: The data type of this column. :type type: str
625990567b25080760ed878a
class Register(Qobj): <NEW_LINE> <INDENT> def __init__(self,N,state=None): <NEW_LINE> <INDENT> if state==None: <NEW_LINE> <INDENT> reg=tensor([basis(2) for k in range(N)]) <NEW_LINE> <DEDENT> if isinstance(state,str): <NEW_LINE> <INDENT> state=_reg_str2array(state,N) <NEW_LINE> reg=tensor([basis(2,state[k]) for k in state]) <NEW_LINE> <DEDENT> Qobj.__init__(self, reg.data, reg.dims, reg.shape, reg.type, reg.isherm, fast=False) <NEW_LINE> <DEDENT> def width(self): <NEW_LINE> <INDENT> return len(self.dims[0]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = "" <NEW_LINE> s += ("Quantum Register: " + ", width = " + str(self.width()) + ", type = " + self.type + "\n") <NEW_LINE> s += "Register data =\n" <NEW_LINE> if all(np.imag(self.data.data) == 0): <NEW_LINE> <INDENT> s += str(np.real(self.full())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s += str(self.full()) <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def apply_hadamard(self, target): <NEW_LINE> <INDENT> target=np.asarray(target) <NEW_LINE> _reg_input_check(target,self.width()) <NEW_LINE> H=1.0 / sqrt(2.0) * (sigmaz()+sigmax()) <NEW_LINE> reg_gate=_single_op_reg_gate(H,target,self.width()) <NEW_LINE> if self.type=='ket': <NEW_LINE> <INDENT> self.data=(reg_gate*self).data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data=(reg_gate*self*reg_gate.dag()).data <NEW_LINE> <DEDENT> <DEDENT> def apply_not(self,target): <NEW_LINE> <INDENT> target=np.asarray(target) <NEW_LINE> _reg_input_check(target,self.width()) <NEW_LINE> reg_gate=_single_op_reg_gate(sigmax(),target,self.width()) <NEW_LINE> self.data=(reg_gate*self).data <NEW_LINE> <DEDENT> def apply_sigmaz(self,target): <NEW_LINE> <INDENT> target=np.asarray(target) <NEW_LINE> _reg_input_check(target,self.width()) <NEW_LINE> reg_gate=_single_op_reg_gate(sigmaz(),target,self.width()) <NEW_LINE> self.data=(reg_gate*self).data <NEW_LINE> <DEDENT> def apply_sigmay(self,target): <NEW_LINE> <INDENT> target=np.asarray(target) <NEW_LINE> _reg_input_check(target,self.width()) <NEW_LINE> reg_gate=_single_op_reg_gate(sigmay(),target,self.width()) <NEW_LINE> self.data=(reg_gate*self).data <NEW_LINE> <DEDENT> def apply_sigmax(self,target): <NEW_LINE> <INDENT> self.apply_not(self,target,self.width()) <NEW_LINE> <DEDENT> def apply_phasegate(self, target, phase=0): <NEW_LINE> <INDENT> target=np.asarray(target) <NEW_LINE> _reg_input_check(target,self.width()) <NEW_LINE> P=fock_dm(2,0)+np.exp(1.0j*phase)*fock_dm(2,1) <NEW_LINE> reg_gate=_single_op_reg_gate(P,target,self.width()) <NEW_LINE> self.data=(reg_gate*self).data
A class for representing quantum registers. Subclass of the quantum object (Qobj) class.
6259905624f1403a9268637a
class _JSONEncoder(_json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, _date): <NEW_LINE> <INDENT> encoded_obj = _toString(obj) <NEW_LINE> <DEDENT> elif isinstance(obj, _cursors.Record): <NEW_LINE> <INDENT> encoded_obj = super(_JSONEncoder, self).default(obj.copy()) <NEW_LINE> <DEDENT> elif hasattr(obj, '_asdict'): <NEW_LINE> <INDENT> encoded_obj = super(_JSONEncoder, self).default(obj._asdict()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> encoded_obj = super(_JSONEncoder, self).default(obj) <NEW_LINE> <DEDENT> return encoded_obj
JSONEncoder that handles dates.
6259905623e79379d538da52
class KerasLayersModelExample(KerasModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> x = Input([1]) <NEW_LINE> y = np.array([[2.0]]) <NEW_LINE> b = np.array([0.0]) <NEW_LINE> mult = Dense(1, weights=(y, b)) <NEW_LINE> z = mult(x) <NEW_LINE> self.x = x <NEW_LINE> self.mult = mult <NEW_LINE> self.z = z <NEW_LINE> <DEDENT> @property <NEW_LINE> def placeholders(self): <NEW_LINE> <INDENT> return [self.x] <NEW_LINE> <DEDENT> def inputs_to_feed_dict(self, batch): <NEW_LINE> <INDENT> return {self.x: np.array([[batch.x]])} <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_tensors(self): <NEW_LINE> <INDENT> return [self.z]
A Model that is defined using Keras layers from beginning to end.
62599056435de62698e9d35a
class MiniSeqKernel(GenericKernelMixin, StationaryKernelMixin, Kernel): <NEW_LINE> <INDENT> def __init__(self, baseline_similarity=0.5, baseline_similarity_bounds=(1e-5, 1)): <NEW_LINE> <INDENT> self.baseline_similarity = baseline_similarity <NEW_LINE> self.baseline_similarity_bounds = baseline_similarity_bounds <NEW_LINE> <DEDENT> @property <NEW_LINE> def hyperparameter_baseline_similarity(self): <NEW_LINE> <INDENT> return Hyperparameter( "baseline_similarity", "numeric", self.baseline_similarity_bounds ) <NEW_LINE> <DEDENT> def _f(self, s1, s2): <NEW_LINE> <INDENT> return sum( [1.0 if c1 == c2 else self.baseline_similarity for c1 in s1 for c2 in s2] ) <NEW_LINE> <DEDENT> def _g(self, s1, s2): <NEW_LINE> <INDENT> return sum([0.0 if c1 == c2 else 1.0 for c1 in s1 for c2 in s2]) <NEW_LINE> <DEDENT> def __call__(self, X, Y=None, eval_gradient=False): <NEW_LINE> <INDENT> if Y is None: <NEW_LINE> <INDENT> Y = X <NEW_LINE> <DEDENT> if eval_gradient: <NEW_LINE> <INDENT> return ( np.array([[self._f(x, y) for y in Y] for x in X]), np.array([[[self._g(x, y)] for y in Y] for x in X]), ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.array([[self._f(x, y) for y in Y] for x in X]) <NEW_LINE> <DEDENT> <DEDENT> def diag(self, X): <NEW_LINE> <INDENT> return np.array([self._f(x, x) for x in X]) <NEW_LINE> <DEDENT> def clone_with_theta(self, theta): <NEW_LINE> <INDENT> cloned = clone(self) <NEW_LINE> cloned.theta = theta <NEW_LINE> return cloned
A minimal (but valid) convolutional kernel for sequences of variable length.
6259905632920d7e50bc759e
class TableDataInsertAllRequest(_messages.Message): <NEW_LINE> <INDENT> class RowsValueListEntry(_messages.Message): <NEW_LINE> <INDENT> insertId = _messages.StringField(1) <NEW_LINE> json = _messages.MessageField('JsonObject', 2) <NEW_LINE> <DEDENT> ignoreUnknownValues = _messages.BooleanField(1) <NEW_LINE> kind = _messages.StringField(2, default=u'bigquery#tableDataInsertAllRequest') <NEW_LINE> rows = _messages.MessageField('RowsValueListEntry', 3, repeated=True) <NEW_LINE> skipInvalidRows = _messages.BooleanField(4)
A TableDataInsertAllRequest object. Messages: RowsValueListEntry: A RowsValueListEntry object. Fields: ignoreUnknownValues: [Optional] Accept rows that contain values that do not match the schema. The unknown values are ignored. Default is false, which treats unknown values as errors. kind: The resource type of the response. rows: The rows to insert. skipInvalidRows: [Optional] Insert all valid rows of a request, even if invalid rows exist. The default value is false, which causes the entire request to fail if any invalid rows exist.
6259905645492302aabfda2e
class TSVCorpusReader(object): <NEW_LINE> <INDENT> def __init__(self, sentence_file, preload=True, file_reader=open): <NEW_LINE> <INDENT> self._open = file_reader <NEW_LINE> self._sentence_file = sentence_file <NEW_LINE> self._sentence_cache = [] <NEW_LINE> if preload: <NEW_LINE> <INDENT> self._sentence_cache = list(self.sents()) <NEW_LINE> <DEDENT> <DEDENT> def _line_iterator(self): <NEW_LINE> <INDENT> with self._open(self._sentence_file) as fd: <NEW_LINE> <INDENT> for line in fd: <NEW_LINE> <INDENT> yield line.strip() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def sents(self): <NEW_LINE> <INDENT> if self._sentence_cache: <NEW_LINE> <INDENT> for sentence in self._sentence_cache: <NEW_LINE> <INDENT> yield sentence <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for line in self._line_iterator(): <NEW_LINE> <INDENT> yield line.split("\t") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def words(self): <NEW_LINE> <INDENT> for sentence in self.sents(): <NEW_LINE> <INDENT> for word in sentence: <NEW_LINE> <INDENT> yield word
Corpus reader for TSV files. Input files are assumed to contain one sentence per line, with tokens separated by tabs: foo[tab]bar[tab]baz span[tab]eggs Would correspond to the two-sentence corpus: ["foo", "bar", "baz"], ["spam", "eggs"]
62599056dd821e528d6da42b
class Category(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=512, null=False) <NEW_LINE> slug = models.SlugField(null=False, unique=True, max_length=255) <NEW_LINE> description = models.TextField(null=True, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "Category: %s" % self.title <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> from django.urls import reverse <NEW_LINE> return reverse('category', kwargs={'slug': str(self.slug)}) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "Categories"
This model represent a category of posts
62599056fff4ab517ebced7a
class Modbus_WriteMultipleCoilsResp(scapy_all.Packet): <NEW_LINE> <INDENT> pass
Layer for wite multiple coils response
625990568e7ae83300eea5e5
class Money: <NEW_LINE> <INDENT> def __init__(self, amount, currency): <NEW_LINE> <INDENT> self.amount = amount <NEW_LINE> self.currency = currency <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.currency.symbol != None: <NEW_LINE> <INDENT> return f"{self.currency.symbol}{self.amount:.{self.currency.digits}f}" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f"{self.currency.code} {self.amount:.{self.currency.digits}f}" <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"<Money {str(self)}>" <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (type(self) == type(other) and self.amount == other.amount and self.currency == other.currency) <NEW_LINE> <DEDENT> def add(self, other): <NEW_LINE> <INDENT> if self.currency.code == other.currency.code: <NEW_LINE> <INDENT> self.amount = self.amount + other.amount <NEW_LINE> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise DifferentCurrencyError() <NEW_LINE> <DEDENT> <DEDENT> def sub(self, other): <NEW_LINE> <INDENT> if self.currency.code == other.currency.code: <NEW_LINE> <INDENT> self.amount = self.amount - other.amount <NEW_LINE> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise DifferentCurrencyError() <NEW_LINE> <DEDENT> <DEDENT> def mul(self, multiplier): <NEW_LINE> <INDENT> self.amount = self.amount * multiplier <NEW_LINE> return self <NEW_LINE> <DEDENT> def div(self, divisor): <NEW_LINE> <INDENT> self.amount = self.amount / divisor <NEW_LINE> return self
Represents an amount of money. Requires an amount and a currency.
62599056a79ad1619776b569
class ToneChatEnums: <NEW_LINE> <INDENT> class ContentLanguage(str, Enum): <NEW_LINE> <INDENT> EN = 'en' <NEW_LINE> FR = 'fr' <NEW_LINE> <DEDENT> class AcceptLanguage(str, Enum): <NEW_LINE> <INDENT> AR = 'ar' <NEW_LINE> DE = 'de' <NEW_LINE> EN = 'en' <NEW_LINE> ES = 'es' <NEW_LINE> FR = 'fr' <NEW_LINE> IT = 'it' <NEW_LINE> JA = 'ja' <NEW_LINE> KO = 'ko' <NEW_LINE> PT_BR = 'pt-br' <NEW_LINE> ZH_CN = 'zh-cn' <NEW_LINE> ZH_TW = 'zh-tw'
Enums for tone_chat parameters.
6259905607f4c71912bb0992
class TestSameTree(unittest.TestCase): <NEW_LINE> <INDENT> def test_same_tree(self): <NEW_LINE> <INDENT> s = Solution() <NEW_LINE> self.assertEqual(True, s.isSameTree(TreeNode.generate([1, 2, 3]), TreeNode.generate([1, 2, 3]))) <NEW_LINE> self.assertEqual(False, s.isSameTree(TreeNode.generate([1, 2]), TreeNode.generate([1, None, 2]))) <NEW_LINE> self.assertEqual(False, s.isSameTree(TreeNode.generate([1, 2, 1]), TreeNode.generate([1, 1, 2])))
Test q100_same_tree.py
625990568a43f66fc4bf36e5
class TypedSequence(MutableSequence): <NEW_LINE> <INDENT> def __init__(self, cls, args, allow_none=True): <NEW_LINE> <INDENT> self.cls = cls <NEW_LINE> self.allowed_types = (cls, type(None)) if allow_none else cls <NEW_LINE> self.list = [] <NEW_LINE> self.extend(args) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.list) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return repr(self.list) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.list) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, TypedSequence): <NEW_LINE> <INDENT> return self.list == other.list and self.cls == other.cls <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.list == other <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> return self.list[i] <NEW_LINE> <DEDENT> def __delitem__(self, i): <NEW_LINE> <INDENT> del self.list[i] <NEW_LINE> <DEDENT> def __setitem__(self, i, v): <NEW_LINE> <INDENT> self._check(v) <NEW_LINE> self.list[i] = v <NEW_LINE> <DEDENT> def insert(self, i, v): <NEW_LINE> <INDENT> self._check(v) <NEW_LINE> self.list.insert(i, v) <NEW_LINE> <DEDENT> def _check(self, v): <NEW_LINE> <INDENT> if not isinstance(v, self.allowed_types): <NEW_LINE> <INDENT> raise TypeError("Invalid value %s (%s != %s)" % (v, type(v), self.cls))
Custom list type that checks the instance type of new values. reference: http://stackoverflow.com/a/3488283
6259905601c39578d7f141e3
class LList: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._len = 0 <NEW_LINE> self._head = None <NEW_LINE> self._tail = None
Linked List class that mostly just is an interface to LLNode
6259905663b5f9789fe866ca
class Podcast: <NEW_LINE> <INDENT> PATH_TO_PODCASTS_YAML = os.path.join(os.path.dirname(__file__), 'podcasts.yaml') <NEW_LINE> def __init__( self, key: str, index: str) -> None: <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.index = index <NEW_LINE> self.name = self.get_name_from_key(key) <NEW_LINE> self.episode = self.get_episode_from_index(key, index) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return '{} - {} - {}'.format( self.episode.index, self.name, self.episode.title) <NEW_LINE> <DEDENT> @property <NEW_LINE> def filename(self) -> str: <NEW_LINE> <INDENT> filename = '{} {} {}'.format( self.episode.index, self.key, self.episode.title) <NEW_LINE> return '{}{}'.format(slugify(filename), '.mp3') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_name_from_key(cls, key: str) -> str: <NEW_LINE> <INDENT> podcasts = read_yaml_file(cls.PATH_TO_PODCASTS_YAML) <NEW_LINE> podcast = podcasts.get(key) <NEW_LINE> return podcast.get('name') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_episode_from_index(cls, key: str, index: str) -> str: <NEW_LINE> <INDENT> podcasts = read_yaml_file(cls.PATH_TO_PODCASTS_YAML) <NEW_LINE> podcast = podcasts.get(key) <NEW_LINE> episodes = podcast.get('episodes') <NEW_LINE> return Episode(**episodes[int(index) - 1]) <NEW_LINE> <DEDENT> def download_remote_media(self) -> None: <NEW_LINE> <INDENT> r = requests.get(self.episode.remote_media_uri) <NEW_LINE> r.raise_for_status() <NEW_LINE> filename = self.filename <NEW_LINE> with open(filename, 'wb') as f: <NEW_LINE> <INDENT> f.write(r.content)
Object representation of a podcast.
6259905621a7993f00c674c5
class PCommand(Mbase_cmd.DebuggerCommand): <NEW_LINE> <INDENT> aliases = ('print', 'pr') <NEW_LINE> category = 'data' <NEW_LINE> min_args = 1 <NEW_LINE> max_args = None <NEW_LINE> name = os.path.basename(__file__).split('.')[0] <NEW_LINE> need_stack = True <NEW_LINE> short_help = 'Print value of expression EXP' <NEW_LINE> complete = Mcomplete.complete_identifier <NEW_LINE> def run(self, args): <NEW_LINE> <INDENT> if len(args) > 2 and '/' == args[1][0]: <NEW_LINE> <INDENT> fmt = args[1] <NEW_LINE> del args[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fmt = None <NEW_LINE> pass <NEW_LINE> <DEDENT> arg = ' '.join(args[1:]) <NEW_LINE> try: <NEW_LINE> <INDENT> val = self.proc.eval(arg) <NEW_LINE> if fmt: <NEW_LINE> <INDENT> val = Mprint.printf(val, fmt) <NEW_LINE> pass <NEW_LINE> <DEDENT> self.msg(self.proc._saferepr(val)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass
**print** *expression* Print the value of the expression. Variables accessible are those of the environment of the selected stack frame, plus globals. The expression may be preceded with */fmt* where *fmt* is one of the format letters 'c', 'x', 'o', 'f', or 's' for chr, hex, oct, float or str respectively. If the length output string large, the first part of the value is shown and `...` indicates it has been truncated. See also: --------- `pp` and `examine` for commands which do more in the way of formatting.
6259905694891a1f408ba1a2
class OleCfPluginTestCase(test_lib.ParserTestCase): <NEW_LINE> <INDENT> def _OpenOleCfFile(self, path, codepage=u'cp1252'): <NEW_LINE> <INDENT> file_entry = self._GetTestFileEntryFromPath([path]) <NEW_LINE> file_object = file_entry.GetFileObject() <NEW_LINE> olecf_file = pyolecf.file() <NEW_LINE> olecf_file.set_ascii_codepage(codepage) <NEW_LINE> olecf_file.open_file_object(file_object) <NEW_LINE> return olecf_file <NEW_LINE> <DEDENT> def _ParseOleCfFileWithPlugin( self, path, plugin_object, knowledge_base_values=None): <NEW_LINE> <INDENT> event_queue = single_process.SingleProcessQueue() <NEW_LINE> event_queue_consumer = test_lib.TestItemQueueConsumer(event_queue) <NEW_LINE> parse_error_queue = single_process.SingleProcessQueue() <NEW_LINE> parser_mediator = self._GetParserMediator( event_queue, parse_error_queue, knowledge_base_values=knowledge_base_values) <NEW_LINE> olecf_file = self._OpenOleCfFile(path) <NEW_LINE> file_entry = self._GetTestFileEntryFromPath([path]) <NEW_LINE> parser_mediator.SetFileEntry(file_entry) <NEW_LINE> root_item = olecf_file.root_item <NEW_LINE> item_names = [item.name for item in root_item.sub_items] <NEW_LINE> plugin_object.Process( parser_mediator, root_item=root_item, item_names=item_names) <NEW_LINE> return event_queue_consumer
The unit test case for OLE CF based plugins.
625990562ae34c7f260ac63f
class TestCalendarCreate(Base): <NEW_LINE> <INDENT> expected_title = "fedocal.calendar.new" <NEW_LINE> expected_subti = 'ralph created a whole new "awesome" calendar' <NEW_LINE> expected_link = "https://apps.fedoraproject.org/calendar/awesome/" <NEW_LINE> expected_icon = ("https://apps.fedoraproject.org/calendar/" "static/calendar.png") <NEW_LINE> expected_secondary_icon = ( "https://seccdn.libravatar.org/avatar/" "9c9f7784935381befc302fe3c814f9136e7a33953d0318761669b8643f4df55c" "?s=64&d=retro") <NEW_LINE> expected_packages = set([]) <NEW_LINE> expected_usernames = set(['ralph']) <NEW_LINE> expected_objects = set(['awesome/new']) <NEW_LINE> msg = { "username": "threebean", "i": 1, "timestamp": 1379638157.759283, "msg_id": "2013-96f9ca0e-c7c6-43f0-9de7-7a268c7f1cef", "topic": "org.fedoraproject.dev.fedocal.calendar.new", "msg": { "calendar": { "calendar_editor_group": "sysadmin-main", "calendar_name": "awesome", "calendar_description": "cool deal", "calendar_admin_group": "sysadmin-badges", "calendar_contact": "[email protected]", "calendar_status": "Enabled" }, "agent": "ralph" } }
These messages are published when someone creates a whole calendar from `fedocal <https://apps.fedoraproject.org/calendar>`_.
625990563eb6a72ae038bbb8
class Token(object): <NEW_LINE> <INDENT> def __init__(self, type, val, pos,lineno): <NEW_LINE> <INDENT> self.type = type <NEW_LINE> self.val = val <NEW_LINE> self.pos = pos <NEW_LINE> self.lineno=lineno <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s(%s) at %s in %s' % (self.type, self.val, self.pos,self.lineno)
A simple Token structure. Token type, value and position.
62599056435de62698e9d35c
class EvergreenProjectConfig(object): <NEW_LINE> <INDENT> def __init__(self, conf): <NEW_LINE> <INDENT> self._conf = conf <NEW_LINE> self.tasks = [Task(task_dict) for task_dict in self._conf["tasks"]] <NEW_LINE> self._tasks_by_name = {task.name: task for task in self.tasks} <NEW_LINE> self.task_groups = [ TaskGroup(task_group_dict) for task_group_dict in self._conf.get("task_groups", []) ] <NEW_LINE> self._task_groups_by_name = {task_group.name: task_group for task_group in self.task_groups} <NEW_LINE> self.variants = [ Variant(variant_dict, self._tasks_by_name, self._task_groups_by_name) for variant_dict in self._conf["buildvariants"] ] <NEW_LINE> self._variants_by_name = {variant.name: variant for variant in self.variants} <NEW_LINE> self.distro_names = set() <NEW_LINE> for variant in self.variants: <NEW_LINE> <INDENT> self.distro_names.update(variant.distro_names) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def task_names(self): <NEW_LINE> <INDENT> return self._tasks_by_name.keys() <NEW_LINE> <DEDENT> def get_task(self, task_name): <NEW_LINE> <INDENT> return self._tasks_by_name.get(task_name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def task_group_names(self): <NEW_LINE> <INDENT> return self._task_groups_by_name.keys() <NEW_LINE> <DEDENT> def get_task_group(self, task_group_name): <NEW_LINE> <INDENT> return self._task_groups_by_name.get(task_group_name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def lifecycle_task_names(self): <NEW_LINE> <INDENT> excluded = self._get_test_lifecycle_excluded_task_names() <NEW_LINE> return [name for name in self.task_names if name not in excluded] <NEW_LINE> <DEDENT> def _get_test_lifecycle_excluded_task_names(self): <NEW_LINE> <INDENT> excluded_patterns = self._conf.get("test_lifecycle_excluded_tasks", []) <NEW_LINE> excluded = [] <NEW_LINE> for pattern in excluded_patterns: <NEW_LINE> <INDENT> excluded.extend(fnmatch.filter(self.task_names, pattern)) <NEW_LINE> <DEDENT> return excluded <NEW_LINE> <DEDENT> @property <NEW_LINE> def variant_names(self): <NEW_LINE> <INDENT> return self._variants_by_name.keys() <NEW_LINE> <DEDENT> def get_variant(self, variant_name): <NEW_LINE> <INDENT> return self._variants_by_name.get(variant_name)
Represent an Evergreen project configuration file.
62599056cb5e8a47e493cc33
class MqttSwitch(MqttEntity, SwitchEntity, RestoreEntity): <NEW_LINE> <INDENT> def __init__(self, hass, config, config_entry, discovery_data): <NEW_LINE> <INDENT> self._state = False <NEW_LINE> self._state_on = None <NEW_LINE> self._state_off = None <NEW_LINE> self._optimistic = None <NEW_LINE> MqttEntity.__init__(self, hass, config, config_entry, discovery_data) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def config_schema(): <NEW_LINE> <INDENT> return PLATFORM_SCHEMA <NEW_LINE> <DEDENT> def _setup_from_config(self, config): <NEW_LINE> <INDENT> state_on = config.get(CONF_STATE_ON) <NEW_LINE> self._state_on = state_on if state_on else config[CONF_PAYLOAD_ON] <NEW_LINE> state_off = config.get(CONF_STATE_OFF) <NEW_LINE> self._state_off = state_off if state_off else config[CONF_PAYLOAD_OFF] <NEW_LINE> self._optimistic = config[CONF_OPTIMISTIC] <NEW_LINE> template = self._config.get(CONF_VALUE_TEMPLATE) <NEW_LINE> if template is not None: <NEW_LINE> <INDENT> template.hass = self.hass <NEW_LINE> <DEDENT> <DEDENT> async def _subscribe_topics(self): <NEW_LINE> <INDENT> @callback <NEW_LINE> @log_messages(self.hass, self.entity_id) <NEW_LINE> def state_message_received(msg): <NEW_LINE> <INDENT> payload = msg.payload <NEW_LINE> template = self._config.get(CONF_VALUE_TEMPLATE) <NEW_LINE> if template is not None: <NEW_LINE> <INDENT> payload = template.async_render_with_possible_json_value(payload) <NEW_LINE> <DEDENT> if payload == self._state_on: <NEW_LINE> <INDENT> self._state = True <NEW_LINE> <DEDENT> elif payload == self._state_off: <NEW_LINE> <INDENT> self._state = False <NEW_LINE> <DEDENT> self.async_write_ha_state() <NEW_LINE> <DEDENT> if self._config.get(CONF_STATE_TOPIC) is None: <NEW_LINE> <INDENT> self._optimistic = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._sub_state = await subscription.async_subscribe_topics( self.hass, self._sub_state, { CONF_STATE_TOPIC: { "topic": self._config.get(CONF_STATE_TOPIC), "msg_callback": state_message_received, "qos": self._config[CONF_QOS], } }, ) <NEW_LINE> <DEDENT> if self._optimistic: <NEW_LINE> <INDENT> last_state = await self.async_get_last_state() <NEW_LINE> if last_state: <NEW_LINE> <INDENT> self._state = last_state.state == STATE_ON <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def assumed_state(self): <NEW_LINE> <INDENT> return self._optimistic <NEW_LINE> <DEDENT> async def async_turn_on(self, **kwargs): <NEW_LINE> <INDENT> mqtt.async_publish( self.hass, self._config[CONF_COMMAND_TOPIC], self._config[CONF_PAYLOAD_ON], self._config[CONF_QOS], self._config[CONF_RETAIN], ) <NEW_LINE> if self._optimistic: <NEW_LINE> <INDENT> self._state = True <NEW_LINE> self.async_write_ha_state() <NEW_LINE> <DEDENT> <DEDENT> async def async_turn_off(self, **kwargs): <NEW_LINE> <INDENT> mqtt.async_publish( self.hass, self._config[CONF_COMMAND_TOPIC], self._config[CONF_PAYLOAD_OFF], self._config[CONF_QOS], self._config[CONF_RETAIN], ) <NEW_LINE> if self._optimistic: <NEW_LINE> <INDENT> self._state = False <NEW_LINE> self.async_write_ha_state()
Representation of a switch that can be toggled using MQTT.
62599056adb09d7d5dc0bac3
class WebsocketJsonRpcProtocol(object): <NEW_LINE> <INDENT> version = '1.0.0' <NEW_LINE> def __init__(self, _type): <NEW_LINE> <INDENT> self._type = _type.lower() <NEW_LINE> if self._type != 'request' and self._type != 'response': <NEW_LINE> <INDENT> raise Exception('Wrong protocol type, "request" or "response" expected. ' 'Got {err_type}.'.format(err_type=self._type)) <NEW_LINE> <DEDENT> if self._type == 'request': <NEW_LINE> <INDENT> self.uid = gen_id() <NEW_LINE> self.pack = self.__request_pack <NEW_LINE> self.unpack = self.__request_unpack <NEW_LINE> <DEDENT> elif self._type == 'response': <NEW_LINE> <INDENT> self.uid = None <NEW_LINE> self.pack = self.__response_pack <NEW_LINE> self.unpack = self.__response_unpack <NEW_LINE> <DEDENT> <DEDENT> @check_args <NEW_LINE> def __request_pack(self, method, params): <NEW_LINE> <INDENT> if not params: <NEW_LINE> <INDENT> params = {} <NEW_LINE> <DEDENT> return json.dumps( { "id": self.uid, "method": method, "params": params } ) <NEW_LINE> <DEDENT> @check_args <NEW_LINE> def __response_pack(self, uid, result, err): <NEW_LINE> <INDENT> return json.dumps( { "id": uid, "result": result, "error": err } ) <NEW_LINE> <DEDENT> @check_recv <NEW_LINE> def __request_unpack(self, recv): <NEW_LINE> <INDENT> return recv['id'], recv['method'], recv['params'] <NEW_LINE> <DEDENT> @check_recv <NEW_LINE> def __response_unpack(self, recv): <NEW_LINE> <INDENT> return recv['id'], recv['result'], recv['error'] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _ver(): <NEW_LINE> <INDENT> return WebsocketJsonRpcProtocol.version
Definition of Json-rpc protocol structure.
62599056e64d504609df9e7c
class EncodedArrayItem : <NEW_LINE> <INDENT> def __init__(self, buff, cm) : <NEW_LINE> <INDENT> self.__CM = cm <NEW_LINE> self.offset = buff.get_idx() <NEW_LINE> self.value = EncodedArray( buff, cm ) <NEW_LINE> <DEDENT> def get_value(self) : <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def set_off(self, off) : <NEW_LINE> <INDENT> self.offset = off <NEW_LINE> <DEDENT> def reload(self) : <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_value(self) : <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def show(self) : <NEW_LINE> <INDENT> bytecode._PrintSubBanner("Encoded Array Item") <NEW_LINE> self.value.show() <NEW_LINE> <DEDENT> def get_obj(self) : <NEW_LINE> <INDENT> return [ self.value ] <NEW_LINE> <DEDENT> def get_raw(self) : <NEW_LINE> <INDENT> return self.value.get_raw() <NEW_LINE> <DEDENT> def get_length(self) : <NEW_LINE> <INDENT> return self.value.get_length() <NEW_LINE> <DEDENT> def get_off(self) : <NEW_LINE> <INDENT> return self.offset
This class can parse an encoded_array_item of a dex file :param buff: a string which represents a Buff object of the encoded_array_item :type buff: Buff object :param cm: a ClassManager object :type cm: :class:`ClassManager`
62599056596a89723612905c
class SymbolTable: <NEW_LINE> <INDENT> from .Node import Node as node <NEW_LINE> from .exceptions import ( NodeError, CircularReferenceError, EmptyExpressionError, ExpressionSyntaxError, EvaluationError, UnresolvedNodeError ) <NEW_LINE> @property <NEW_LINE> def keys(self): <NEW_LINE> <INDENT> return tuple(self._nodes.keys()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def nodes(self): <NEW_LINE> <INDENT> return tuple(self._nodes.values()) <NEW_LINE> <DEDENT> def expression(self, value, **kwds): <NEW_LINE> <INDENT> if isinstance(value, self.node): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if not isinstance(value, str): <NEW_LINE> <INDENT> return self.variable(value=value, **kwds) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> program, operands = self.node.expression.compile(model=self, expression=value) <NEW_LINE> <DEDENT> except self.node.EmptyExpressionError as error: <NEW_LINE> <INDENT> return self.variable(value=error.expression, **kwds) <NEW_LINE> <DEDENT> return self.node.expression( model=self, expression=value, program=program, operands=operands, **kwds) <NEW_LINE> <DEDENT> def interpolation(self, value, **kwds): <NEW_LINE> <INDENT> if isinstance(value, self.node): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if not isinstance(value, str): <NEW_LINE> <INDENT> return self.variable(value=value, **kwds) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> operands = self.node.interpolation.compile(model=self, expression=value) <NEW_LINE> <DEDENT> except self.node.EmptyExpressionError as error: <NEW_LINE> <INDENT> return self.variable(value=error.expression, **kwds) <NEW_LINE> <DEDENT> return self.node.interpolation(model=self, expression=value, operands=operands, **kwds) <NEW_LINE> <DEDENT> def sequence(self, nodes, **kwds): <NEW_LINE> <INDENT> return self.node.sequence(operands=tuple(nodes), **kwds) <NEW_LINE> <DEDENT> def mapping(self, nodes, **kwds): <NEW_LINE> <INDENT> return self.node.mapping(operands=nodes, **kwds) <NEW_LINE> <DEDENT> def variable(self, **kwds): <NEW_LINE> <INDENT> return self.node.variable(**kwds) <NEW_LINE> <DEDENT> def literal(self, **kwds): <NEW_LINE> <INDENT> return self.node.literal(**kwds) <NEW_LINE> <DEDENT> def get(self, name, default=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[name] <NEW_LINE> <DEDENT> except self.UnresolvedNodeError: <NEW_LINE> <INDENT> self[name] = default <NEW_LINE> <DEDENT> return self[name] <NEW_LINE> <DEDENT> def insert(self, name, node): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> old = self._nodes[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> old = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node.replace(old) <NEW_LINE> <DEDENT> self._nodes[name] = node <NEW_LINE> return name, new, old <NEW_LINE> <DEDENT> def retrieve(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> node = self._nodes[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> node = self.node.unresolved(request=name) <NEW_LINE> self._nodes[name] = node <NEW_LINE> <DEDENT> return node <NEW_LINE> <DEDENT> def __init__(self, **kwds): <NEW_LINE> <INDENT> super().__init__(**kwds) <NEW_LINE> self._nodes = {} <NEW_LINE> return <NEW_LINE> <DEDENT> def __contains__(self, name): <NEW_LINE> <INDENT> return name in self._nodes <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._nodes) <NEW_LINE> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> node = self.retrieve(name) <NEW_LINE> return node.value <NEW_LINE> <DEDENT> def __setitem__(self, name, value): <NEW_LINE> <INDENT> new = self.interpolation(value=value) <NEW_LINE> return self.insert(node=new, name=name) <NEW_LINE> <DEDENT> _nodes = None
Storage and naming services for algebraic nodes
625990560a50d4780f70686b
class Node(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Node, self).__init__() <NEW_LINE> <DEDENT> @property <NEW_LINE> def info(self): <NEW_LINE> <INDENT> return node_inf.retrieve_info() <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return node_inf.retrieve_status()
docstring for KongNode
625990568e71fb1e983bd022
@final <NEW_LINE> class ClearVariableAction(EventAction[ClearVariableActionParameters]): <NEW_LINE> <INDENT> name = "clear_variable" <NEW_LINE> param_class = ClearVariableActionParameters <NEW_LINE> def start(self) -> None: <NEW_LINE> <INDENT> player = self.session.player <NEW_LINE> key = self.parameters.variable <NEW_LINE> player.game_variables.pop(key, None)
Clear the value of a variable from the game. Script usage: .. code-block:: clear_variable <variable> Script parameters: variable: The variable to clear.
6259905621bff66bcd7241bd
class ObjectIterator(_BaseIterator): <NEW_LINE> <INDENT> def __init__(self, bucket, prefix='', delimiter='', marker='', max_keys=100, max_retries=defaults.request_retries): <NEW_LINE> <INDENT> super(ObjectIterator, self).__init__(marker, max_retries) <NEW_LINE> self.bucket = bucket <NEW_LINE> self.prefix = prefix <NEW_LINE> self.delimiter = delimiter <NEW_LINE> self.max_keys = max_keys <NEW_LINE> <DEDENT> def _fetch(self): <NEW_LINE> <INDENT> result = self.bucket.list_objects(prefix=self.prefix, delimiter=self.delimiter, marker=self.next_marker, max_keys=self.max_keys) <NEW_LINE> self.entries = result.object_list + [SimplifiedObjectInfo(prefix, None, None, None, None, None) for prefix in result.prefix_list] <NEW_LINE> self.entries.sort(key=lambda obj: obj.key) <NEW_LINE> return result.is_truncated, result.next_marker
遍历Bucket里文件的迭代器。 每次迭代返回的是 :class:`SimplifiedObjectInfo <oss2.models.SimplifiedObjectInfo>` 对象。 当 `SimplifiedObjectInfo.is_prefix()` 返回True时,表明是公共前缀(目录)。 :param bucket: :class:`Bucket <oss2.Bucket>` 对象 :param prefix: 只列举匹配该前缀的文件 :param delimiter: 目录分隔符 :param marker: 分页符 :param max_keys: 每次调用 `list_objects` 时的max_keys参数。注意迭代器返回的数目可能会大于该值。
62599056507cdc57c63a62fe
class ApplicationGatewayBackendHealth(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'backend_address_pools': {'key': 'backendAddressPools', 'type': '[ApplicationGatewayBackendHealthPool]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayBackendHealth, self).__init__(**kwargs) <NEW_LINE> self.backend_address_pools = kwargs.get('backend_address_pools', None)
Response for ApplicationGatewayBackendHealth API service call. :param backend_address_pools: A list of ApplicationGatewayBackendHealthPool resources. :type backend_address_pools: list[~azure.mgmt.network.v2019_04_01.models.ApplicationGatewayBackendHealthPool]
6259905645492302aabfda31
class Box(object): <NEW_LINE> <INDENT> def __init__(self,boxType): <NEW_LINE> <INDENT> self.pos=(0,0,0) <NEW_LINE> self.boxType=boxType <NEW_LINE> self.xzBox=None <NEW_LINE> self.xyBox=None <NEW_LINE> self.yzBox=None <NEW_LINE> <DEDENT> def getType(self): <NEW_LINE> <INDENT> return self.boxType <NEW_LINE> <DEDENT> def setPos(self,x,y,z): <NEW_LINE> <INDENT> self.pos=(x,y,z) <NEW_LINE> <DEDENT> def getPos(self): <NEW_LINE> <INDENT> return self.pos <NEW_LINE> <DEDENT> def getSides(self): <NEW_LINE> <INDENT> ret=[] <NEW_LINE> if self.xz: <NEW_LINE> <INDENT> ret.append(self.xz) <NEW_LINE> <DEDENT> if self.yz: <NEW_LINE> <INDENT> ret.append(self.yz) <NEW_LINE> <DEDENT> if self.xy: <NEW_LINE> <INDENT> ret.append(self.xy) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s at "%(self.boxType)+str(self.pos)+" , xz= "+str(self.xz)+" , yz= "+str(self.yz)+" , xy= "+str(self.xy)+"\n" <NEW_LINE> <DEDENT> def hasColor(self,*colors): <NEW_LINE> <INDENT> ret=True <NEW_LINE> for color in colors: <NEW_LINE> <INDENT> colorFound=False <NEW_LINE> if self.xy is not None and self.xy.color==color.color: <NEW_LINE> <INDENT> colorFound=True <NEW_LINE> <DEDENT> if self.xz is not None and self.xz.color==color.color: <NEW_LINE> <INDENT> colorFound=True <NEW_LINE> <DEDENT> if self.yz is not None and self.yz.color==color.color: <NEW_LINE> <INDENT> colorFound=True <NEW_LINE> <DEDENT> if not colorFound: <NEW_LINE> <INDENT> ret=False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return ret <NEW_LINE> return False
The base class for boxes.
62599056fff4ab517ebced7c
class InputFile(BaseTask): <NEW_LINE> <INDENT> def output(self): <NEW_LINE> <INDENT> return luigi.LocalTarget(self.input_file)
A Task wrapping up a Target object
62599056379a373c97d9a57e
@keras_export('keras.layers.experimental.preprocessing.Resizing') <NEW_LINE> class Resizing(PreprocessingLayer): <NEW_LINE> <INDENT> def __init__(self, height, width, interpolation='bilinear', name=None, **kwargs): <NEW_LINE> <INDENT> self.target_height = height <NEW_LINE> self.target_width = width <NEW_LINE> self.interpolation = interpolation <NEW_LINE> self._interpolation_method = get_interpolation(interpolation) <NEW_LINE> self.input_spec = InputSpec(ndim=4) <NEW_LINE> super(Resizing, self).__init__(name=name, **kwargs) <NEW_LINE> base_preprocessing_layer.keras_kpl_gauge.get_cell('Resizing').set(True) <NEW_LINE> <DEDENT> def call(self, inputs): <NEW_LINE> <INDENT> outputs = image_ops.resize_images_v2( images=inputs, size=[self.target_height, self.target_width], method=self._interpolation_method) <NEW_LINE> return outputs <NEW_LINE> <DEDENT> def compute_output_shape(self, input_shape): <NEW_LINE> <INDENT> input_shape = tensor_shape.TensorShape(input_shape).as_list() <NEW_LINE> return tensor_shape.TensorShape( [input_shape[0], self.target_height, self.target_width, input_shape[3]]) <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = { 'height': self.target_height, 'width': self.target_width, 'interpolation': self.interpolation, } <NEW_LINE> base_config = super(Resizing, self).get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items()))
Image resizing layer. Resize the batched image input to target height and width. The input should be a 4-D tensor in the format of NHWC. Arguments: height: Integer, the height of the output shape. width: Integer, the width of the output shape. interpolation: String, the interpolation method. Defaults to `bilinear`. Supports `bilinear`, `nearest`, `bicubic`, `area`, `lanczos3`, `lanczos5`, `gaussian`, `mitchellcubic` name: A string, the name of the layer.
6259905616aa5153ce401a3d
class Perfect_Paddle: <NEW_LINE> <INDENT> Width = 20 <NEW_LINE> Height = 100 <NEW_LINE> def __init__(self, Width, Height, player): <NEW_LINE> <INDENT> self.screen_Width = Width <NEW_LINE> self.screen_Height = Height <NEW_LINE> self.player = player <NEW_LINE> self.y = self.screen_Width//2 <NEW_LINE> self.vy = 0 <NEW_LINE> <DEDENT> def update(self, screen, bgColor, fgColor, ball, y_last): <NEW_LINE> <INDENT> if self.player == 1: <NEW_LINE> <INDENT> pygame.draw.rect(screen, bgColor, pygame.Rect((0, self.y-self.Height//2, self.Width, self.Height))) <NEW_LINE> <DEDENT> elif self.player == 2: <NEW_LINE> <INDENT> pygame.draw.rect(screen, bgColor, pygame.Rect((self.screen_Width-self.Width, self.y-self.Height//2, self.Width, self.Height))) <NEW_LINE> <DEDENT> self.y = ball.y <NEW_LINE> self.vy = round(self.y - y_last) <NEW_LINE> if self.player == 1: <NEW_LINE> <INDENT> pygame.draw.rect(screen, fgColor, pygame.Rect((0, self.y-self.Height//2, self.Width, self.Height))) <NEW_LINE> <DEDENT> elif self.player == 2: <NEW_LINE> <INDENT> pygame.draw.rect(screen, fgColor, pygame.Rect((self.screen_Width-self.Width, self.y-self.Height//2, self.Width, self.Height)))
Takes ball object as input and sets paddle.y == ball.y
62599056460517430c432afe
@attr.s(slots=True, frozen=True) <NEW_LINE> class UnknownJob(UserError): <NEW_LINE> <INDENT> lead = "Jenkins error" <NEW_LINE> server_url = attr.ib(validator=instance_of(str)) <NEW_LINE> job_name = attr.ib(validator=instance_of(str)) <NEW_LINE> def __attr_post_init__(self): <NEW_LINE> <INDENT> super(UnknownJob, self).__init__(self.format_message()) <NEW_LINE> <DEDENT> def format_message(self): <NEW_LINE> <INDENT> fmt = "No job named {job_name} found at {server_url}" <NEW_LINE> return fmt.format_map(attr.asdict(self))
No job with specified name was found on the server.
6259905601c39578d7f141e4
class SourceFileExtractor(FileExtractor): <NEW_LINE> <INDENT> def get_options(self): <NEW_LINE> <INDENT> return self.default_options().union(self.get_help_list_macro('HELP_SPEC_OPTIONS'))
An abstract extractor for a source file with usage message. This class does not offer a way to set a filename, which is expected to be defined in children classes.
6259905624f1403a9268637c
class Gaussian(Distribution): <NEW_LINE> <INDENT> def __init__(self, mu=0, sigma=1): <NEW_LINE> <INDENT> Distribution.__init__(self, mu, sigma) <NEW_LINE> <DEDENT> def calculate_mean(self): <NEW_LINE> <INDENT> avg = 1.0 * sum(self.data) / len(self.data) <NEW_LINE> self.mean = avg <NEW_LINE> return self.mean <NEW_LINE> <DEDENT> def calculate_stdev(self, sample=True): <NEW_LINE> <INDENT> if sample: <NEW_LINE> <INDENT> n = len(self.data) - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n = len(self.data) <NEW_LINE> <DEDENT> mean = self.calculate_mean() <NEW_LINE> sigma = 0 <NEW_LINE> for d in self.data: <NEW_LINE> <INDENT> sigma += (d - mean) ** 2 <NEW_LINE> <DEDENT> sigma = math.sqrt(sigma / n) <NEW_LINE> self.stdev = sigma <NEW_LINE> return self.stdev <NEW_LINE> <DEDENT> def plot_histogram(self): <NEW_LINE> <INDENT> plt.hist(self.data) <NEW_LINE> plt.title('Histogram of Data') <NEW_LINE> plt.xlabel('data') <NEW_LINE> plt.ylabel('count') <NEW_LINE> <DEDENT> def pdf(self, x): <NEW_LINE> <INDENT> return (1.0 / (self.stdev * math.sqrt(2 * math.pi))) * math.exp(-0.5 * ((x - self.mean) / self.stdev) ** 2) <NEW_LINE> <DEDENT> def plot_histogram_pdf(self, n_spaces=50): <NEW_LINE> <INDENT> mu = self.mean <NEW_LINE> sigma = self.stdev <NEW_LINE> min_range = min(self.data) <NEW_LINE> max_range = max(self.data) <NEW_LINE> interval = 1.0 * (max_range - min_range) / n_spaces <NEW_LINE> x = [] <NEW_LINE> y = [] <NEW_LINE> for i in range(n_spaces): <NEW_LINE> <INDENT> tmp = min_range + interval * i <NEW_LINE> x.append(tmp) <NEW_LINE> y.append(self.pdf(tmp)) <NEW_LINE> <DEDENT> fig, axes = plt.subplots(2, sharex=True) <NEW_LINE> fig.subplots_adjust(hspace=.5) <NEW_LINE> axes[0].hist(self.data, density=True) <NEW_LINE> axes[0].set_title('Normed Histogram of Data') <NEW_LINE> axes[0].set_ylabel('Density') <NEW_LINE> axes[1].plot(x, y) <NEW_LINE> axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') <NEW_LINE> axes[0].set_ylabel('Density') <NEW_LINE> plt.show() <NEW_LINE> return x, y <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> result = Gaussian() <NEW_LINE> result.mean = self.mean + other.mean <NEW_LINE> result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2) <NEW_LINE> return result <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "mean {}, standard deviation {}".format(self.mean, self.stdev)
Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file
625990568da39b475be04746
class GalleryView(object): <NEW_LINE> <INDENT> def __call__(self, environ): <NEW_LINE> <INDENT> html = '' <NEW_LINE> req = Request(environ) <NEW_LINE> filename, ext = os.path.splitext(req.path_info) <NEW_LINE> markdown_file = content + filename + '.md' <NEW_LINE> if os.path.isfile(markdown_file): <NEW_LINE> <INDENT> _buffer = StringIO() <NEW_LINE> md = markdown.markdownFromFile(input=markdown_file, output=_buffer) <NEW_LINE> html = _buffer.getvalue() <NEW_LINE> _buffer.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> html = '<center>Page not found</center>' <NEW_LINE> <DEDENT> renderer = pystache.Renderer(search_dirs=templates) <NEW_LINE> return renderer.render_name('gallery', {'content': html})
Read markdown file and render template.
6259905655399d3f05627a79
class SimpleUploadForm(forms.Form): <NEW_LINE> <INDENT> file = forms.FileField(label=_('File')) <NEW_LINE> method = forms.ChoiceField( label=_('Merge method'), choices=( ('', _('Add as translation')), ('suggest', _('Add as a suggestion')), ('fuzzy', _('Add as fuzzy translation')), ), required=False ) <NEW_LINE> merge_header = forms.BooleanField( label=_('Merge file header'), help_text=_('Merges content of file header into the translation.'), required=False, initial=True, )
Base form for uploading a file.
62599056a219f33f346c7d5f
class Element(ClonableArray): <NEW_LINE> <INDENT> def check(self): <NEW_LINE> <INDENT> if self not in self.parent(): <NEW_LINE> <INDENT> raise ValueError("Invalid permutation")
A length-`k` partial permutation of `[n]`.
625990563eb6a72ae038bbba
class Movement_card(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self, x, y, x_mov, y_mov, color, order): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.image = pygame.Surface((width / 7.5, height / 6.66)) <NEW_LINE> self.color = color <NEW_LINE> self.image.fill(color) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = x <NEW_LINE> self.rect.y = y <NEW_LINE> self.x_mov = x_mov <NEW_LINE> self.y_mov = y_mov <NEW_LINE> self.order = order <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> global selected <NEW_LINE> if self.order in selected: <NEW_LINE> <INDENT> self.rect.y = height / 1.25 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rect.y = height / 1.3 <NEW_LINE> <DEDENT> click = pygame.sprite.spritecollide(self, cursor_group, False) <NEW_LINE> if click: <NEW_LINE> <INDENT> self.image.fill(grey) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image.fill(self.color)
Class for the cards that choose movement
625990566e29344779b01ba5
class registerOrganization_InputForm(messages.Message): <NEW_LINE> <INDENT> orgName = messages.StringField(1) <NEW_LINE> phoneNumber = messages.StringField(2)
OrganizationForm -- Organization outbound form message
6259905615baa723494634ec
class SmartMeter(object): <NEW_LINE> <INDENT> def __init__(self, retries=2, com_method='rtu', baudrate=19200, stopbits=1, parity='N', bytesize=8, timeout=0.1, logfile='sm.log'): <NEW_LINE> <INDENT> self.retries = retries <NEW_LINE> self.com_method = com_method <NEW_LINE> self.baudrate = baudrate <NEW_LINE> self.stopbits = stopbits <NEW_LINE> self.parity = parity <NEW_LINE> self.bytesize = bytesize <NEW_LINE> self.timeout = timeout <NEW_LINE> self.logger = logging.getLogger('smart_meter') <NEW_LINE> self.logger.setLevel(logging.DEBUG) <NEW_LINE> self.fh = logging.FileHandler(logfile) <NEW_LINE> formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') <NEW_LINE> self.fh.setFormatter(formatter) <NEW_LINE> self.logger.addHandler(self.fh) <NEW_LINE> <DEDENT> def connect(self, vendor="", product="", meter_port=None): <NEW_LINE> <INDENT> if meter_port is None: <NEW_LINE> <INDENT> self.vendor = vendor <NEW_LINE> self.product = product <NEW_LINE> self.meter_port = find_tty_usb(vendor, product) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.meter_port = meter_port <NEW_LINE> <DEDENT> self.logger.info('Connecting to port: %s' % self.meter_port) <NEW_LINE> self.client = ModbusClient( retries=self.retries, method=self.com_method, baudrate=self.baudrate, stopbits=self.stopbits, parity=self.parity, bytesize=self.bytesize, timeout=self.timeout, port=self.meter_port) <NEW_LINE> self.logger.info('Connected to port: %s' % self.meter_port) <NEW_LINE> return self.client <NEW_LINE> <DEDENT> def read_from_meter(self, meter_id, base_register, block_size, params_indices): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> binary_data = self.client.read_holding_registers( base_register, block_size, unit=meter_id) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> time.sleep(0.5) <NEW_LINE> self.logger.exception(e) <NEW_LINE> self.logger.info('Will now try to reconnect') <NEW_LINE> self.client = self.connect( vendor=self.vendor, product=self.product) <NEW_LINE> binary_data = self.client.read_holding_registers( base_register, block_size, unit=meter_id) <NEW_LINE> <DEDENT> data = "" <NEW_LINE> for i in range(0, (block_size - 1), 2): <NEW_LINE> <INDENT> for j in params_indices: <NEW_LINE> <INDENT> if(j == i): <NEW_LINE> <INDENT> data = data + "," + convert_to_str( (binary_data.registers[i + 1] << 16) + binary_data.registers[i]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> data = data[:-1] + "\n" <NEW_LINE> data = str(time.time()) + data <NEW_LINE> return data <NEW_LINE> <DEDENT> def write_csv(self, csv_path, data): <NEW_LINE> <INDENT> with open(csv_path, 'a') as f: <NEW_LINE> <INDENT> f.write(data)
1. Sets up a smart meter connection 2. Specifies a serial port to connect to 3. Methods to read and write data (to csv)
625990567cff6e4e811b6f9c
class SNError(Exception): <NEW_LINE> <INDENT> pass
Superclass used for errors in the SNePS module.
62599056baa26c4b54d507fe
class ActionAbstract(models.Model): <NEW_LINE> <INDENT> state_db = models.ForeignKey(State) <NEW_LINE> person = models.ForeignKey(Person) <NEW_LINE> name = models.SlugField(max_length=8) <NEW_LINE> created = models.DateTimeField(editable=False) <NEW_LINE> comment = models.TextField(blank=True, null=True) <NEW_LINE> file = models.FileField(upload_to=generate_upload_filename, blank=True, null=True) <NEW_LINE> merged_file = models.OneToOneField(PoFile, null=True) <NEW_LINE> arg_is_required = False <NEW_LINE> comment_is_required = False <NEW_LINE> file_is_required = False <NEW_LINE> file_is_prohibited = False <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s (%s) - %s" % (self.name, self.description, self.id) <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return dict(ACTION_NAMES).get(self.name, None) <NEW_LINE> <DEDENT> def get_filename(self): <NEW_LINE> <INDENT> if self.file: <NEW_LINE> <INDENT> return os.path.basename(self.file.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def has_po_file(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.file.name[-3:] == ".po" <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get_action_history(cls, state=None, sequence=None): <NEW_LINE> <INDENT> history = [] <NEW_LINE> if state or sequence: <NEW_LINE> <INDENT> file_history = [{'action_id':0, 'title': ugettext("File in repository")}] <NEW_LINE> if not sequence: <NEW_LINE> <INDENT> query = cls.objects.filter(state_db__id=state.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = cls.objects.filter(sequence=sequence) <NEW_LINE> <DEDENT> for action in query.order_by('id'): <NEW_LINE> <INDENT> history.append((action, list(file_history))) <NEW_LINE> if action.file and action.file.path.endswith('.po'): <NEW_LINE> <INDENT> file_history.insert(0, { 'action_id': action.id, 'title': ugettext("Uploaded file by %(name)s on %(date)s") % { 'name': action.person.name, 'date': action.created }, }) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return history
Common model for Action and ActionArchived
62599056dd821e528d6da42d
class DynamicSentenceEndingLabeler(workflow.ExactMatchLabeler): <NEW_LINE> <INDENT> def __init__(self, input_sequence: str, config: Optional[SentenceSegementationConfig]): <NEW_LINE> <INDENT> if config and config.dynamic_endings: <NEW_LINE> <INDENT> self.AC_AUTOMATION = self.build_ac_automation_from_strings(config.dynamic_endings) <NEW_LINE> <DEDENT> super().__init__(input_sequence, config) <NEW_LINE> <DEDENT> def intervals_generator(self) -> workflow.IntervalGeneratorType: <NEW_LINE> <INDENT> def mocker_generator() -> workflow.IntervalGeneratorType: <NEW_LINE> <INDENT> empty_tuple = cast(workflow.IntervalListType, ()) <NEW_LINE> yield from empty_tuple <NEW_LINE> <DEDENT> if self.config: <NEW_LINE> <INDENT> config = cast(SentenceSegementationConfig, self.config) <NEW_LINE> if not config.dynamic_endings: <NEW_LINE> <INDENT> return mocker_generator() <NEW_LINE> <DEDENT> <DEDENT> return super().intervals_generator()
Support dynamic sentence endings that will be built in runtime.
62599056d7e4931a7ef3d5d9
class ConfigurationParser(object): <NEW_LINE> <INDENT> CONFIG_OBJECT = None <NEW_LINE> @classmethod <NEW_LINE> def get_config_object(cls): <NEW_LINE> <INDENT> if not cls.CONFIG_OBJECT: <NEW_LINE> <INDENT> config = ConfigParser.ConfigParser() <NEW_LINE> try: <NEW_LINE> <INDENT> config.read("app_config.properties") <NEW_LINE> <DEDENT> except (IOError, ConfigParser.NoSectionError, ConfigParser.NoOptionError) as err: <NEW_LINE> <INDENT> logging.error("Error in reading configuration file %s" % err) <NEW_LINE> return <NEW_LINE> <DEDENT> cls.CONFIG_OBJECT = config <NEW_LINE> <DEDENT> return cls.CONFIG_OBJECT
Utility class for configuration parser object provider
625990560a50d4780f70686c
class BleachCharField(models.CharField, BleachMixin): <NEW_LINE> <INDENT> def __init__(self, allowed_tags=None, allowed_attributes=None, allowed_styles=None, strip_tags=None, strip_comments=None, *args, **kwargs): <NEW_LINE> <INDENT> super(BleachCharField, self).__init__(*args, **kwargs) <NEW_LINE> self._do_init(allowed_tags=allowed_tags, allowed_attributes=allowed_attributes, allowed_styles=allowed_styles, strip_tags=strip_tags, strip_comments=strip_comments) <NEW_LINE> <DEDENT> def pre_save(self, model_instance, add): <NEW_LINE> <INDENT> return self._do_pre_save(model_instance, add)
Bleach CharField.
62599056379a373c97d9a57f
class NodeAlias(object): <NEW_LINE> <INDENT> def __init__(self, alias): <NEW_LINE> <INDENT> self._alias = int(alias) <NEW_LINE> <DEDENT> def __int__(self): <NEW_LINE> <INDENT> return self._alias <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '0x{0:X}'.format(self._alias) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'NodeAlias(0x{0:X})'.format(self._alias) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return int(self) == other <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return int(self) != other <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return int(self) < other <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return int(self) <= other <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return int(self) > other <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> return int(self) >= other
Utility class for handling node alias * Calling ``int`` on an instance of :py:class:`NodeAlias` will return the integer value. * Calling ``str`` on an instance of :py:class:`NodeAlias` will return a hexidecimal number.
62599056baa26c4b54d507ff
class QSignalBlocker(__sip.simplewrapper): <NEW_LINE> <INDENT> def reblock(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def unblock(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return object() <NEW_LINE> <DEDENT> def __exit__(self, p_object, p_object_1, p_object_2): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, QObject): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None)
QSignalBlocker(QObject)
625990568e71fb1e983bd024
class FunctionType(LittleScribeType): <NEW_LINE> <INDENT> def __init__(self, parameter_types, return_type): <NEW_LINE> <INDENT> self.parameter_types = parameter_types <NEW_LINE> self.parameter_count = len(parameter_types) <NEW_LINE> self.return_type = return_type <NEW_LINE> <DEDENT> def is_super_of(self, other): <NEW_LINE> <INDENT> return (isinstance(other, FunctionType) and self.parameter_count == other.parameter_count and self.return_type.is_super_of(other.return_type) and all(other_pt.is_super_of(self_pt) for (self_pt, other_pt) in zip(self.parameter_types, other.parameter_types))) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def make(parameter_types, return_type): <NEW_LINE> <INDENT> return FunctionType(parameter_types, return_type)
A callable type which runs code and returns a value. All functions are pure (having no side effects) and return exactly one value. This may change in later versions.
62599056be383301e0254d3a
class Command(NoArgsCommand): <NEW_LINE> <INDENT> def handle_noargs(self, **options): <NEW_LINE> <INDENT> addresses = BaseAddress.objects.filter(coordinates__isnull=True) <NEW_LINE> for address in addresses: <NEW_LINE> <INDENT> if address.fetch_coordinates(): <NEW_LINE> <INDENT> address.coordinates = address.fetch_coordinates() <NEW_LINE> self.stdout.write(u'[%s, %s] - %s' % (address.coordinates.x, address.coordinates.y, address)) <NEW_LINE> address.save() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stdout.write(u'pk %s - не удалось получить координаты' % (address.pk))
Поиск адресов без координат и попытка их проставить.
6259905629b78933be26ab72
class FileError(GoghError): <NEW_LINE> <INDENT> pass
'{0}' does not exist.
6259905632920d7e50bc75a2
class TermsOfServiceCheckboxInput(CheckboxInput): <NEW_LINE> <INDENT> def render(self, name, value, attrs=None): <NEW_LINE> <INDENT> final_attrs = self.build_attrs(attrs, type='checkbox', name=name) <NEW_LINE> if self.check_test(value): <NEW_LINE> <INDENT> final_attrs['checked'] = 'checked' <NEW_LINE> <DEDENT> if not (value is True or value is False or value is None or value == ''): <NEW_LINE> <INDENT> final_attrs['value'] = force_text(value) <NEW_LINE> <DEDENT> label = _('I, and my company, accept the {link_start}{platform_name} API Terms of Service{link_end}.').format( platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME), link_start='<a href="{url}" target="_blank">'.format(url=reverse('api_admin:api-tos')), link_end='</a>', ) <NEW_LINE> html = '<input{{}} /> <label class="tos-checkbox-label" for="{id}">{label}</label>'.format( id=final_attrs['id'], label=label ) <NEW_LINE> return format_html(html, flatatt(final_attrs))
Renders a checkbox with a label linking to the terms of service.
62599056e5267d203ee6ce4a
class SettingsDelete(generic.ObjectDeleteView): <NEW_LINE> <INDENT> queryset = Settings.objects.all()
Delete Cisco DNA Center Settings
62599056498bea3a75a59082
class LoggerMixin: <NEW_LINE> <INDENT> @cached_property <NEW_LINE> def full_slug(self): <NEW_LINE> <INDENT> return self.slug <NEW_LINE> <DEDENT> def log_hook(self, level, msg, *args): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def log_debug(self, msg, *args): <NEW_LINE> <INDENT> self.log_hook("DEBUG", msg, *args) <NEW_LINE> return LOGGER.debug(": ".join((self.full_slug, msg)), *args) <NEW_LINE> <DEDENT> def log_info(self, msg, *args): <NEW_LINE> <INDENT> self.log_hook("INFO", msg, *args) <NEW_LINE> return LOGGER.info(": ".join((self.full_slug, msg)), *args) <NEW_LINE> <DEDENT> def log_warning(self, msg, *args): <NEW_LINE> <INDENT> self.log_hook("WARNING", msg, *args) <NEW_LINE> return LOGGER.warning(": ".join((self.full_slug, msg)), *args) <NEW_LINE> <DEDENT> def log_error(self, msg, *args): <NEW_LINE> <INDENT> self.log_hook("ERROR", msg, *args) <NEW_LINE> return LOGGER.error(": ".join((self.full_slug, msg)), *args)
Mixin for models with logging.
62599056097d151d1a2c25c7
class Base64: <NEW_LINE> <INDENT> digits = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.base64_map = dict(zip(Base64.digits, xrange(0, 64))) <NEW_LINE> <DEDENT> def decode(self, base64): <NEW_LINE> <INDENT> value = 0 <NEW_LINE> first = 0 <NEW_LINE> neg = False <NEW_LINE> if base64[0] == '-': <NEW_LINE> <INDENT> neg = True <NEW_LINE> first = 1 <NEW_LINE> <DEDENT> for i in xrange(first, len(base64)): <NEW_LINE> <INDENT> value = value << 6 <NEW_LINE> value += self.base64_map[base64[i]] <NEW_LINE> <DEDENT> return -value if neg else value
Bacula specific implementation of a base64 decoder
625990564e4d562566373963
class InterfaceTypeFixture(TypeFixture): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.gfi = make_type_info('GF', typevars=['T'], is_abstract=True) <NEW_LINE> self.m1i = make_type_info('M1', is_abstract=True, mro=[self.gfi, self.oi], bases=[Instance(self.gfi, [self.a])]) <NEW_LINE> self.gfa = Instance(self.gfi, [self.a]) <NEW_LINE> self.gfb = Instance(self.gfi, [self.b]) <NEW_LINE> self.m1 = Instance(self.m1i, [])
Extension of TypeFixture that contains additional generic interface types.
6259905607d97122c4218207
class MDSEventListener(models.Model): <NEW_LINE> <INDENT> event_name = models.CharField(max_length=50) <NEW_LINE> server = models.CharField(max_length=100) <NEW_LINE> description = models.CharField(max_length = 500, blank=True) <NEW_LINE> h1ds_signal = models.ManyToManyField(H1DSSignal, through='ListenerSignals') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return unicode("%s@%s" %(self.event_name, self.server)) <NEW_LINE> <DEDENT> def start_listener(self): <NEW_LINE> <INDENT> task_name = u'h1ds_mdsplus.tasks.mds_event_listener' <NEW_LINE> signals = {} <NEW_LINE> for signal in self.h1ds_signal.all(): <NEW_LINE> <INDENT> signals[signal.name] = {'active':False, 'class':signal, 'args':u"(u'{}', u'{}', u'{}')".format( self.server, self.event_name, signal.name)} <NEW_LINE> <DEDENT> active_workers = inspect().active() <NEW_LINE> if active_workers != None: <NEW_LINE> <INDENT> for worker in active_workers.keys(): <NEW_LINE> <INDENT> for active_task in active_workers[worker]: <NEW_LINE> <INDENT> for sig in signals.keys(): <NEW_LINE> <INDENT> if (active_task['name'] == task_name and active_task['args'] == signals[sig]['args']): <NEW_LINE> <INDENT> signals[sig]['active'] = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for sig in signals.keys(): <NEW_LINE> <INDENT> if not signals[sig]['active']: <NEW_LINE> <INDENT> self.listener = mds_event_listener.delay(self.server, self.event_name, signals[sig]['class']) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> super(MDSEventListener, self).save(*args, **kwargs) <NEW_LINE> self.start_listener()
Listens for an MDSplus event from a specified server.
62599056d99f1b3c44d06bfc
class Bool(Validator): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._valid_values = [True, False] <NEW_LINE> <DEDENT> def validate(self, value, context=''): <NEW_LINE> <INDENT> if not isinstance(value, bool) and not isinstance(value, np.bool8): <NEW_LINE> <INDENT> raise TypeError( '{} is not Boolean; {}'.format(repr(value), context)) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Boolean>'
requires a boolean
625990564e696a045264e8d0
class Interface(Entity): <NEW_LINE> <INDENT> host = entity_fields.OneToOneField('Host', required=True) <NEW_LINE> mac = entity_fields.MACAddressField(required=True) <NEW_LINE> ip = entity_fields.IPAddressField(required=True) <NEW_LINE> interface_type = entity_fields.StringField(required=True) <NEW_LINE> name = entity_fields.StringField(required=True) <NEW_LINE> subnet = entity_fields.OneToOneField('Subnet', null=True) <NEW_LINE> domain = entity_fields.OneToOneField('Domain', null=True) <NEW_LINE> username = entity_fields.StringField(null=True) <NEW_LINE> password = entity_fields.StringField(null=True) <NEW_LINE> provider = entity_fields.StringField(null=True) <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> api_names = {'interface_type': 'type'} <NEW_LINE> api_path = 'api/v2/hosts/:host_id/interfaces' <NEW_LINE> server_modes = ('sat')
A representation of a Interface entity.
62599056b57a9660fecd2fd8
class Relocation(object): <NEW_LINE> <INDENT> def __init__(self, address, symbol, offset, reltype): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> self.symbol = symbol <NEW_LINE> self.offset = offset <NEW_LINE> self.reltype = reltype <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{:<#10x} {:<10} {:<#4x} {:20} {}'.format(self.address, self.offset, self.reltype, _RELOC_TYPES[self.reltype], self.symbol.name)
Represents a relocation entry in the COFF file.
62599056dc8b845886d54b21
class SemanticRolesResult(): <NEW_LINE> <INDENT> def __init__(self, *, sentence=None, subject=None, action=None, object=None): <NEW_LINE> <INDENT> self.sentence = sentence <NEW_LINE> self.subject = subject <NEW_LINE> self.action = action <NEW_LINE> self.object = object <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_dict(cls, _dict): <NEW_LINE> <INDENT> args = {} <NEW_LINE> valid_keys = ['sentence', 'subject', 'action', 'object'] <NEW_LINE> bad_keys = set(_dict.keys()) - set(valid_keys) <NEW_LINE> if bad_keys: <NEW_LINE> <INDENT> raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesResult: ' + ', '.join(bad_keys)) <NEW_LINE> <DEDENT> if 'sentence' in _dict: <NEW_LINE> <INDENT> args['sentence'] = _dict.get('sentence') <NEW_LINE> <DEDENT> if 'subject' in _dict: <NEW_LINE> <INDENT> args['subject'] = SemanticRolesResultSubject._from_dict( _dict.get('subject')) <NEW_LINE> <DEDENT> if 'action' in _dict: <NEW_LINE> <INDENT> args['action'] = SemanticRolesResultAction._from_dict( _dict.get('action')) <NEW_LINE> <DEDENT> if 'object' in _dict: <NEW_LINE> <INDENT> args['object'] = SemanticRolesResultObject._from_dict( _dict.get('object')) <NEW_LINE> <DEDENT> return cls(**args) <NEW_LINE> <DEDENT> def _to_dict(self): <NEW_LINE> <INDENT> _dict = {} <NEW_LINE> if hasattr(self, 'sentence') and self.sentence is not None: <NEW_LINE> <INDENT> _dict['sentence'] = self.sentence <NEW_LINE> <DEDENT> if hasattr(self, 'subject') and self.subject is not None: <NEW_LINE> <INDENT> _dict['subject'] = self.subject._to_dict() <NEW_LINE> <DEDENT> if hasattr(self, 'action') and self.action is not None: <NEW_LINE> <INDENT> _dict['action'] = self.action._to_dict() <NEW_LINE> <DEDENT> if hasattr(self, 'object') and self.object is not None: <NEW_LINE> <INDENT> _dict['object'] = self.object._to_dict() <NEW_LINE> <DEDENT> return _dict <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self._to_dict(), indent=2) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
The object containing the actions and the objects the actions act upon. :attr str sentence: (optional) Sentence from the source that contains the subject, action, and object. :attr SemanticRolesResultSubject subject: (optional) The extracted subject from the sentence. :attr SemanticRolesResultAction action: (optional) The extracted action from the sentence. :attr SemanticRolesResultObject object: (optional) The extracted object from the sentence.
62599056d7e4931a7ef3d5db
class KernelManagerABC(object, metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @abc.abstractproperty <NEW_LINE> def kernel(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def start_kernel(self, **kw): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def shutdown_kernel(self, now=False, restart=False): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def restart_kernel(self, now=False, **kw): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractproperty <NEW_LINE> def has_kernel(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def interrupt_kernel(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def signal_kernel(self, signum): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def is_alive(self): <NEW_LINE> <INDENT> pass
KernelManager ABC. The docstrings for this class can be found in the base implementation: `jupyter_client.kernelmanager.KernelManager`
62599056dd821e528d6da42e
class Article(Element): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("article")
An HTML article (<article>) element. A self-contained article on a page, like a blog entry or a comment in a blog system.
62599056b5575c28eb71377a
class SchemaError(ValueError): <NEW_LINE> <INDENT> pass
Raised when the validation schema is missing, has the wrong format or contains errors.
625990560c0af96317c5780e
class Model(object): <NEW_LINE> <INDENT> def is_equal(self, field, value): <NEW_LINE> <INDENT> const = getattr(self, field) <NEW_LINE> if const.value == value: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> for key in vars(self): <NEW_LINE> <INDENT> var = getattr(self, key) <NEW_LINE> if isinstance(var.value, set): <NEW_LINE> <INDENT> var.value = list(var.value) <NEW_LINE> <DEDENT> output.update({var.name: var.value}) <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def save(self, path): <NEW_LINE> <INDENT> raise NotImplementedError
The model class represent the final output for each type of data
62599056379a373c97d9a582
class ProjectContextTests: <NEW_LINE> <INDENT> def test_no_filtration(self, samples, project): <NEW_LINE> <INDENT> _assert_samples(samples, project.samples) <NEW_LINE> with ProjectContext(project) as prj: <NEW_LINE> <INDENT> _assert_samples(project.samples, prj.samples) <NEW_LINE> <DEDENT> <DEDENT> @pytest.mark.parametrize( argnames=["selector_include", "expected_names"], argvalues=[ ("ATAC", {"atac-PE"}), (("WGBS", "RRBS"), {WGBS_NAME, RRBS_NAME}), ({"RNA", "CHIP"}, {RNA_NAME, CHIP_NAME}), ], ) <NEW_LINE> def test_inclusion(self, samples, project, selector_include, expected_names): <NEW_LINE> <INDENT> _assert_samples(samples, project.samples) <NEW_LINE> with ProjectContext(project, selector_include=selector_include) as prj: <NEW_LINE> <INDENT> _assert_sample_names(expected_names, observed_samples=prj.samples) <NEW_LINE> <DEDENT> <DEDENT> @pytest.mark.parametrize( argnames=["selector_exclude", "expected_names"], argvalues=[ ({"RNA", "CHIP"}, {ATAC_NAME, WGBS_NAME, RRBS_NAME}), ("ATAC", {CHIP_NAME, RNA_NAME, WGBS_NAME, RRBS_NAME}), ({"WGBS", "RRBS"}, {ATAC_NAME, CHIP_NAME, RNA_NAME}), ], ) <NEW_LINE> def test_exclusion(self, samples, project, selector_exclude, expected_names): <NEW_LINE> <INDENT> _assert_samples(samples, project.samples) <NEW_LINE> with ProjectContext(project, selector_exclude=selector_exclude) as prj: <NEW_LINE> <INDENT> _assert_sample_names(expected_names, observed_samples=prj.samples) <NEW_LINE> <DEDENT> <DEDENT> @pytest.mark.parametrize( argnames=["selection", "selection_type"], argvalues=[ ({"CHIP", "WGBS", "RRBS"}, "selector_exclude"), ({"WGBS", "ATAC"}, "selector_include"), ], ids=lambda proto_seltype_pair: "{}:{}".format(*proto_seltype_pair), ) <NEW_LINE> def test_restoration(self, samples, project, selection, selection_type): <NEW_LINE> <INDENT> _assert_samples(samples, project.samples) <NEW_LINE> with ProjectContext(project, **{selection_type: selection}) as prj: <NEW_LINE> <INDENT> assert {s.name for s in prj.samples} != {s.name for s in samples} <NEW_LINE> <DEDENT> _assert_samples(samples, project.samples) <NEW_LINE> <DEDENT> @pytest.mark.parametrize(argnames="add_project_data", argvalues=[ADD_PROJECT_DATA]) <NEW_LINE> @pytest.mark.parametrize( argnames="attr_name", argvalues=list(ADD_PROJECT_DATA.keys()) ) <NEW_LINE> def test_access_to_project_attributes(self, project, add_project_data, attr_name): <NEW_LINE> <INDENT> with ProjectContext(project) as prj: <NEW_LINE> <INDENT> assert getattr(project, attr_name) is getattr(prj, attr_name) <NEW_LINE> <DEDENT> <DEDENT> @pytest.mark.parametrize( argnames="attr_name", argvalues=["include", "exclude", "prj"] ) <NEW_LINE> def test_access_to_non_project_attributes(self, project, attr_name): <NEW_LINE> <INDENT> with ProjectContext(project) as prj: <NEW_LINE> <INDENT> assert getattr(prj, attr_name) is (project if attr_name == "prj" else None)
Tests for Project context manager wrapper
6259905632920d7e50bc75a4
class scenario_positive_default_role_added_permission_with_filter(APITestCase): <NEW_LINE> <INDENT> @pre_upgrade <NEW_LINE> def test_pre_default_role_added_permission_with_filter(self): <NEW_LINE> <INDENT> defaultrole = entities.Role().search( query={'search': 'name="Default role"'})[0] <NEW_LINE> domainfilter = entities.Filter( permission=entities.Permission( resource_type='Domain').search( filters={'name': 'view_domains'}), unlimited=False, role=defaultrole, search='name ~ a' ).create() <NEW_LINE> self.assertIn( domainfilter.id, [filt.id for filt in defaultrole.read().filters]) <NEW_LINE> <DEDENT> @post_upgrade <NEW_LINE> def test_post_default_role_added_permission_with_filter(self): <NEW_LINE> <INDENT> defaultrole = entities.Role().search( query={'search': 'name="Default role"'})[0] <NEW_LINE> domainfilt = entities.Filter().search(query={ 'search': 'role_id={} and permission="view_domains"'.format( defaultrole.id)}) <NEW_LINE> self.assertTrue(domainfilt) <NEW_LINE> self.assertEqual(domainfilt[0].search, 'name ~ a') <NEW_LINE> domainfilt[0].delete()
Default role extra added permission with filter should be intact post upgrade :id: b287b71c-42fd-4612-a67a-b93d47dbbb33 :steps: 1. In Preupgrade Satellite, Update existing 'Default role' by adding new permission with filter 2. Upgrade the satellite to next/latest version 3. Postupgrade, Verify the permission with filter in existing 'Default role' is intact :expectedresults: The added permission with filter in existing 'Default role' is intact post upgrade
625990567047854f4634091d
class NSNitroNserrConnfailoverService(NSNitroLbErrors): <NEW_LINE> <INDENT> pass
Nitro error code 1290 Connection failover can only be enabled on a virtual server of service type ANY
625990568e71fb1e983bd027
class QLearningAgent(ReinforcementAgent): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> self.qValues = util.Counter() <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> qvalue = self.qValues[(state, action)] <NEW_LINE> if qvalue == None: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> return qvalue <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> maxval = -10000 <NEW_LINE> for action in self.getLegalActions(state): <NEW_LINE> <INDENT> qval = self.getQValue(state, action) <NEW_LINE> if qval > maxval: <NEW_LINE> <INDENT> maxval = qval <NEW_LINE> <DEDENT> <DEDENT> if maxval == -10000: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> return maxval <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> bestaction = None <NEW_LINE> bestvalue = -10000 <NEW_LINE> for action in self.getLegalActions(state): <NEW_LINE> <INDENT> value = self.getQValue(state, action) <NEW_LINE> if value > bestvalue: <NEW_LINE> <INDENT> bestvalue = value <NEW_LINE> bestaction = action <NEW_LINE> <DEDENT> <DEDENT> return bestaction <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> action = None <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> util.raiseNotDefined() <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> oldVal = self.getQValue(state, action) <NEW_LINE> futureval = self.getValue(nextState) <NEW_LINE> self.qValues[(state, action)] = (1 - self.alpha) * oldVal + self.alpha * (reward + self.discount * futureval)
Q-Learning Agent Functions you should fill in: - getQValue - getAction - getValue - getPolicy - update Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.discount (discount rate) Functions you should use - self.getLegalActions(state) which returns legal actions for a state
62599056004d5f362081fa9c
class CmdRestart(ClusterCompleter): <NEW_LINE> <INDENT> names = ['restart', 'reboot'] <NEW_LINE> tag = None <NEW_LINE> def execute(self, args): <NEW_LINE> <INDENT> if not args: <NEW_LINE> <INDENT> self.parser.error("please specify a cluster <tag_name>") <NEW_LINE> <DEDENT> for arg in args: <NEW_LINE> <INDENT> self.cm.restart_cluster(arg)
restart [options] <cluster_tag> Restart an existing cluster Example: $ starcluster restart mynewcluster This command will reboot each node (without terminating), wait for the nodes to come back up, and then reconfigures the cluster without losing any data on the node's local disk
6259905694891a1f408ba1a5
class Encoder(object): <NEW_LINE> <INDENT> def __init__(self, pin_x = 'GP4',pin_y = 'GP5', pin_mode=Pin.PULL_UP, scale=1, min=0, max=100, reverse=False): <NEW_LINE> <INDENT> self.pin_x = (pin_x if isinstance(pin_x, Pin) else Pin(pin_x, mode=Pin.IN, pull=pin_mode)) <NEW_LINE> self.pin_y = (pin_y if isinstance(pin_y, Pin) else Pin(pin_y, mode=Pin.IN, pull=pin_mode)) <NEW_LINE> self.pin_mode = pin_mode <NEW_LINE> self.scale = scale <NEW_LINE> self.min = min <NEW_LINE> self.max = max <NEW_LINE> self.reverse = 1 if reverse else -1 <NEW_LINE> self._pos = -1 <NEW_LINE> self._readings = 0 <NEW_LINE> self._state = 0 <NEW_LINE> self.set_callbacks(self._callback) <NEW_LINE> <DEDENT> def _callback(self, line): <NEW_LINE> <INDENT> self._readings = (self._readings << 2 | self.pin_x.value() << 1 | self.pin_y.value()) & 0x0f <NEW_LINE> self._state = ENC_STATES[self._readings] * self.reverse <NEW_LINE> if self._state: <NEW_LINE> <INDENT> self._pos = min(max(self.min, self._pos + self._state), self.max) <NEW_LINE> <DEDENT> <DEDENT> def set_callbacks(self, callback=None): <NEW_LINE> <INDENT> self.irq_x = self.pin_x.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=callback) <NEW_LINE> self.irq_y = self.pin_y.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=callback) <NEW_LINE> <DEDENT> @property <NEW_LINE> def position(self): <NEW_LINE> <INDENT> return self._pos * self.scale <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._pos = 0
Rotary encoder class
6259905607f4c71912bb0998
class RoomFactory(object): <NEW_LINE> <INDENT> def __init__(self, config, room_manager, server_name_model, map_meta_data_accessor, command_executer, event_subscription_fulfiller, metrics_service): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.room_manager = room_manager <NEW_LINE> self.room_manager.set_factory(self) <NEW_LINE> self.room_bindings = config.get('room_bindings', {}) <NEW_LINE> self.room_types = config.get('room_types', {}) <NEW_LINE> self.server_name_model = server_name_model <NEW_LINE> self.map_meta_data_accessor = map_meta_data_accessor <NEW_LINE> self.command_executer = command_executer <NEW_LINE> self.event_subscription_fulfiller = event_subscription_fulfiller <NEW_LINE> self.metrics_service = metrics_service <NEW_LINE> <DEDENT> def get_room_config(self, name, room_type='default'): <NEW_LINE> <INDENT> room_config = {} <NEW_LINE> room_config.update(self.room_types.get(room_type, {})) <NEW_LINE> room_config.update(self.room_bindings.get(name, {})) <NEW_LINE> return room_config <NEW_LINE> <DEDENT> def build_room(self, name, room_type='default', map_rotation=None): <NEW_LINE> <INDENT> room_config = self.get_room_config(name, room_type) <NEW_LINE> ready_up_controller_factory = ReadyUpControllerFactory(room_config.get('ready_up', {})) <NEW_LINE> if map_rotation is None: <NEW_LINE> <INDENT> map_rotation_data = room_config.get('map_rotation', test_rotation_dict) <NEW_LINE> map_rotation = MapRotation.from_dictionary(map_rotation_data) <NEW_LINE> <DEDENT> demo_recorder = DemoRecorder() <NEW_LINE> maxplayers = room_config.get('maxplayers', 12) <NEW_LINE> room = Room(ready_up_controller_factory=ready_up_controller_factory, room_name=name, room_manager=self.room_manager, server_name_model=self.server_name_model, map_meta_data_accessor=self.map_meta_data_accessor, map_rotation=map_rotation, command_executer=self.command_executer, event_subscription_fulfiller=self.event_subscription_fulfiller, maxplayers=maxplayers, metrics_service=self.metrics_service, demo_recorder=demo_recorder) <NEW_LINE> self.room_manager.add_room(room) <NEW_LINE> return room
Initializes rooms from the config. If a room is in the room bindings section of the config it will be initialized with those settings. If a room type is specified the room will be initialized according to that registered room type if it exists. Otherwise it will be initialized with the default settings.
625990568a43f66fc4bf36eb
class AdminHouseEditHandler(session.SessionHandler, RequestHandler): <NEW_LINE> <INDENT> def get(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.session_obj['admin_is_login'] == 0: <NEW_LINE> <INDENT> self.redirect(r'/admin/login') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id = self.get_argument('id') <NEW_LINE> database_util = Db_Util() <NEW_LINE> params = {'renting_id': id} <NEW_LINE> result = database_util.find_house(**params) <NEW_LINE> if result: <NEW_LINE> <INDENT> renting_id = result[0]['renting_id'] <NEW_LINE> renting_title = result[0]['renting_title'] <NEW_LINE> region = result[0]['region'] <NEW_LINE> user_name = result[0]['user_name'] <NEW_LINE> user_email = result[0]['user_email'] <NEW_LINE> release_time = result[0]['release_time'] <NEW_LINE> renting_detail = result[0]['renting_detail'] <NEW_LINE> self.render(r'../template/admin_pages/houseEdit.html', result = locals()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('没有查到任何信息 ') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def post(self, *args, **kwargs): <NEW_LINE> <INDENT> ret = { 'result': 'ok', 'status': True, 'code': 200 } <NEW_LINE> renting_id = self.get_body_argument('renting_id') <NEW_LINE> renting_title = self.get_body_argument('renting_title') <NEW_LINE> region = self.get_argument('region') <NEW_LINE> print('region', region) <NEW_LINE> renting_detail = self.get_body_argument('renting_detail') <NEW_LINE> param1 = { 'renting_title': renting_title, 'region': region, 'renting_detail': renting_detail } <NEW_LINE> param2 = {'renting_id': renting_id} <NEW_LINE> params = {'param1': param1, 'param2': param2} <NEW_LINE> database_util = Db_Util() <NEW_LINE> result = database_util.update_house(**params) <NEW_LINE> if result == 1: <NEW_LINE> <INDENT> database_util.conn.commit() <NEW_LINE> ret = { 'result': 'ok', 'status': True, 'code': 200 } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> database_util.conn.rollback() <NEW_LINE> ret = { 'result': 'fail', 'status': True, 'code': 200 } <NEW_LINE> <DEDENT> database_util.conn.close() <NEW_LINE> self.write(json_encode(ret))
在房源管理列表中,点击编辑,对编辑的处理,首先跳转到编辑的页面,点击保存,更新数据库
625990560fa83653e46f6443
class IoaSimilarity(RegionSimilarityCalculator): <NEW_LINE> <INDENT> def _compare(self, boxlist1, boxlist2): <NEW_LINE> <INDENT> return box_list_ops.ioa(boxlist1, boxlist2)
Class to compute similarity based on Intersection over Area (IOA) metric. This class computes pairwise similarity between two BoxLists based on their pairwise intersections divided by the areas of second BoxLists.
625990563617ad0b5ee076a7
class Cinema(scrapy.Item): <NEW_LINE> <INDENT> id_mt = Field() <NEW_LINE> id_tb = Field() <NEW_LINE> id_lm = Field() <NEW_LINE> @classmethod <NEW_LINE> def get_table_name(cls): <NEW_LINE> <INDENT> return 'cinema'
汇总各个渠道
625990567d847024c075d939
class OutputError(_RuntimeError): <NEW_LINE> <INDENT> pass
Failure whilst gathering task outputs
6259905645492302aabfda36
class Run(Main): <NEW_LINE> <INDENT> synopsis = "run" <NEW_LINE> callLater = reactor.callLater <NEW_LINE> def postOptions(self): <NEW_LINE> <INDENT> tlog.startLogging(sys.stdout) <NEW_LINE> with createWeb() as webFactory: <NEW_LINE> <INDENT> epWeb = endpoints.serverFromString(reactor, 'tcp:%s' % DEFAULT_PORT) <NEW_LINE> dWeb = epWeb.listen(webFactory) <NEW_LINE> def giveUp(f): <NEW_LINE> <INDENT> f.printTraceback() <NEW_LINE> self.callLater(0, reactor.stop) <NEW_LINE> <DEDENT> dl = defer.DeferredList([dWeb,], fireOnOneErrback=True).addErrback(giveUp) <NEW_LINE> reactor.run() <NEW_LINE> return dl
Command that runs the glyphs server
6259905663b5f9789fe866d1
class _DataServiceDatasetV2(dataset_ops.DatasetSource): <NEW_LINE> <INDENT> def __init__(self, input_dataset, dataset_id, processing_mode, address, protocol, max_outstanding_requests=None, task_refresh_interval_hint_ms=None): <NEW_LINE> <INDENT> if max_outstanding_requests is None: <NEW_LINE> <INDENT> max_outstanding_requests = dataset_ops.AUTOTUNE <NEW_LINE> <DEDENT> if task_refresh_interval_hint_ms is None: <NEW_LINE> <INDENT> task_refresh_interval_hint_ms = dataset_ops.AUTOTUNE <NEW_LINE> <DEDENT> self._element_spec = input_dataset.element_spec <NEW_LINE> variant_tensor = gen_experimental_dataset_ops.data_service_dataset( dataset_id=dataset_id, processing_mode=processing_mode, address=address, protocol=protocol, max_outstanding_requests=max_outstanding_requests, task_refresh_interval_hint_ms=task_refresh_interval_hint_ms, **self._flat_structure) <NEW_LINE> super(_DataServiceDatasetV2, self).__init__(variant_tensor) <NEW_LINE> <DEDENT> @property <NEW_LINE> def element_spec(self): <NEW_LINE> <INDENT> return self._element_spec
A `Dataset` that reads elements from the tf.data service.
6259905621a7993f00c674cb
class Span(object): <NEW_LINE> <INDENT> def __init__(self, trace_context): <NEW_LINE> <INDENT> self.trace_context = trace_context <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> if exc_type: <NEW_LINE> <INDENT> self.error('python.exception', {'type': exc_type, 'val': exc_val, 'tb': exc_tb}) <NEW_LINE> <DEDENT> self.finish() <NEW_LINE> <DEDENT> def start_child(self, operation_name, tags=None): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def finish(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def add_tag(self, key, value): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def add_tags(self, tags): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def info(self, message, *args): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def error(self, message, *args): <NEW_LINE> <INDENT> return self
Span represents a unit of work executed on behalf of a trace. Examples of spans include a remote procedure call, or a in-process method call to a sub-component. A trace is required to have a single, top level "root" span, and zero or more children spans, which in turns can have their own children spans, thus forming a tree structure. Span implements a Context Manager API that allows the following usage: .. code-block:: python span = tracer.start_trace(operation_name='go_fishing') with span: call_some_service() In this case it's not necessary to call span.finish()
62599056009cb60464d02a92
class WssClient(KrakenSocketManager): <NEW_LINE> <INDENT> def __init__(self, key=None, secret=None, nonce_multiplier=1.0): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.key = key <NEW_LINE> self.secret = secret <NEW_LINE> self.nonce_multiplier = nonce_multiplier <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.close() <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> reactor.stop() <NEW_LINE> <DEDENT> <DEDENT> def subscribe_public(self, subscription, callback, **kwargs): <NEW_LINE> <INDENT> self._subscribe(subscription, callback, False, **kwargs) <NEW_LINE> <DEDENT> def subscribe_private(self, subscription, callback, **kwargs): <NEW_LINE> <INDENT> self._subscribe(subscription, callback, True, **kwargs) <NEW_LINE> <DEDENT> def _subscribe(self, subscription, callback, private, **kwargs): <NEW_LINE> <INDENT> if 'pair' in kwargs: <NEW_LINE> <INDENT> id_ = "_".join([subscription['name'], kwargs['pair'][0]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id_ = "_".join([subscription['name']]) <NEW_LINE> <DEDENT> data = { 'event': 'subscribe', 'subscription': subscription, } <NEW_LINE> data.update(**kwargs) <NEW_LINE> payload = json.dumps(data, ensure_ascii=False).encode('utf8') <NEW_LINE> return self._start_socket(id_, payload, callback, private=private) <NEW_LINE> <DEDENT> def request(self, request, callback, **kwargs): <NEW_LINE> <INDENT> id_ = "_".join([request['event'], request['type']]) <NEW_LINE> payload = json.dumps(request, ensure_ascii=False).encode('utf8') <NEW_LINE> return self._start_socket(id_, payload, callback, private=True)
Websocket client for Kraken
62599056adb09d7d5dc0bac9
class Habitatclass(models.Model): <NEW_LINE> <INDENT> site = models.ForeignKey(Site, null=True) <NEW_LINE> habitatcode = models.CharField(max_length=510, blank=True, null=True) <NEW_LINE> percentagecover = models.FloatField(blank=True, null=True) <NEW_LINE> description = models.CharField(max_length=510, blank=True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '{} -- {}'.format(self.habitatcode, self.site.sitecode)
General habitat classes.
6259905621bff66bcd7241c3
class ProcessingException(EnsembleException): <NEW_LINE> <INDENT> pass
For general processing failures
625990560a50d4780f70686e
class BlockREST(REST): <NEW_LINE> <INDENT> grok.baseclass() <NEW_LINE> grok.adapts(PageAPI, IPage) <NEW_LINE> grok.require('silva.ChangeSilvaContent') <NEW_LINE> slot = None <NEW_LINE> slot_id = None <NEW_LINE> slot_validate = True <NEW_LINE> block = None <NEW_LINE> block_id = None <NEW_LINE> block_controller = None <NEW_LINE> @Lazy <NEW_LINE> def manager(self): <NEW_LINE> <INDENT> return getMultiAdapter( (self.context, self.request), IBoundBlockManager) <NEW_LINE> <DEDENT> def publishTraverse(self, request, name): <NEW_LINE> <INDENT> if self.slot_id is None: <NEW_LINE> <INDENT> slot_id = urllib.unquote(name) <NEW_LINE> if self.slot_validate: <NEW_LINE> <INDENT> design = self.context.get_design() <NEW_LINE> if slot_id not in design.slots: <NEW_LINE> <INDENT> raise NotFound('Unknown slot %s' % slot_id) <NEW_LINE> <DEDENT> self.slot = design.slots[slot_id] <NEW_LINE> <DEDENT> self.slot_id = slot_id <NEW_LINE> self.__name__ = '/'.join((self.__name__, name)) <NEW_LINE> return self <NEW_LINE> <DEDENT> if self.slot_id is not None and self.block_id is None: <NEW_LINE> <INDENT> block_id = urllib.unquote(name) <NEW_LINE> block, block_controller = self.manager.get(block_id) <NEW_LINE> if block is not None: <NEW_LINE> <INDENT> self.block = block <NEW_LINE> self.block_id = block_id <NEW_LINE> self.block_controller = block_controller <NEW_LINE> handler = self.publishBlock(name, request) <NEW_LINE> if handler is not None: <NEW_LINE> <INDENT> return handler <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return super(BlockREST, self).publishTraverse(request, name) <NEW_LINE> <DEDENT> def publishBlock(self, name, request): <NEW_LINE> <INDENT> self.__name__ = '/'.join((self.__name__, name)) <NEW_LINE> return self
Traverse to a block on a page.
625990568e7ae83300eea5ec
class OrDefinitionItem(Item): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def is_item(cls, line): <NEW_LINE> <INDENT> return definition_regex.match(line) is not None <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse(cls, lines): <NEW_LINE> <INDENT> header = lines[0].strip() <NEW_LINE> term, classifiers = header_regex.split( header, maxsplit=1) if (' :' in header) else (header, '') <NEW_LINE> classifiers = [ classifier.strip() for classifier in classifiers.split('or')] <NEW_LINE> if classifiers == ['']: <NEW_LINE> <INDENT> classifiers = [] <NEW_LINE> <DEDENT> trimed_lines = trim_indent(lines[1:]) if (len(lines) > 1) else [''] <NEW_LINE> definition = [line.rstrip() for line in trimed_lines] <NEW_LINE> return Item(term.strip(), classifiers, definition)
A docstring definition section item. In this section definition item there are two classifiers that are separated by ``or``. Syntax diagram:: +-------------------------------------------------+ | term [ " : " classifier [ " or " classifier] ] | +--+----------------------------------------------+---+ | definition | | (body elements)+ | +--------------------------------------------------+ Attributes ---------- term : str The term usually reflects the name of a parameter or an attribute. classifiers : list The classifiers of the definition. Commonly used to reflect the type of an argument or the signature of a function. Only two classifiers are accepted. definition : list The list of strings that holds the description the definition item. .. note:: An Or Definition item is based on the item of a section definition list as it defined in restructured text (_http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#sections).
625990562c8b7c6e89bd4d4d