code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class ContactTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.mailinglist_1 = MailingList.objects.create(name='Test MailingList') <NEW_LINE> self.mailinglist_2 = MailingList.objects.create(name='Test MailingList 2') <NEW_LINE> <DEDENT> def test_unique(self): <NEW_LINE> <INDENT> contact = Contact(email='test@domain.com').save() <NEW_LINE> self.assertRaises(IntegrityError, Contact(email='test@domain.com').save) <NEW_LINE> <DEDENT> def test_mail_format(self): <NEW_LINE> <INDENT> contact = Contact(email='test@domain.com') <NEW_LINE> self.assertEquals(contact.mail_format(), 'test@domain.com') <NEW_LINE> contact = Contact(email='test@domain.com', first_name='Toto') <NEW_LINE> self.assertEquals(contact.mail_format(), 'test@domain.com') <NEW_LINE> contact = Contact(email='test@domain.com', first_name='Toto', last_name='Titi') <NEW_LINE> self.assertEquals(contact.mail_format(), 'Titi Toto <test@domain.com>') <NEW_LINE> <DEDENT> def test_vcard_format(self): <NEW_LINE> <INDENT> contact = Contact(email='test@domain.com', first_name='Toto', last_name='Titi') <NEW_LINE> self.assertEquals(contact.vcard_format(), 'BEGIN:VCARD\r\nVERSION:3.0\r\n' 'EMAIL;TYPE=INTERNET:test@domain.com\r\nFN:Toto Titi\r\n' 'N:Titi;Toto;;;\r\nEND:VCARD\r\n') <NEW_LINE> <DEDENT> def test_subscriptions(self): <NEW_LINE> <INDENT> contact = Contact.objects.create(email='test@domain.com') <NEW_LINE> self.assertEquals(len(contact.subscriptions()), 0) <NEW_LINE> self.mailinglist_1.subscribers.add(contact) <NEW_LINE> self.assertEquals(len(contact.subscriptions()), 1) <NEW_LINE> self.mailinglist_2.subscribers.add(contact) <NEW_LINE> self.assertEquals(len(contact.subscriptions()), 2) <NEW_LINE> <DEDENT> def test_unsubscriptions(self): <NEW_LINE> <INDENT> contact = Contact.objects.create(email='test@domain.com') <NEW_LINE> self.assertEquals(len(contact.unsubscriptions()), 0) <NEW_LINE> self.mailinglist_1.unsubscribers.add(contact) <NEW_LINE> self.assertEquals(len(contact.unsubscriptions()), 1) <NEW_LINE> self.mailinglist_2.unsubscribers.add(contact) <NEW_LINE> self.assertEquals(len(contact.unsubscriptions()), 2) | Tests for the Contact model | 62598fbb236d856c2adc9516 |
class TestBaseModel(TestCase): <NEW_LINE> <INDENT> def test_createModel(self): <NEW_LINE> <INDENT> my_model = BaseModel() <NEW_LINE> <DEDENT> def test_BaseModelAssignment(self): <NEW_LINE> <INDENT> my_model = BaseModel() <NEW_LINE> my_model.aString = "a string" <NEW_LINE> my_model.aNumber = 98 <NEW_LINE> <DEDENT> def test_BaseModelCreatedAt(self): <NEW_LINE> <INDENT> my_model = BaseModel() <NEW_LINE> self.assertEqual(type(datetime.now()), type(my_model.created_at)) <NEW_LINE> <DEDENT> def test_BaseModelJSON(self): <NEW_LINE> <INDENT> my_model = BaseModel() <NEW_LINE> my_jsondict = my_model.__dict__ <NEW_LINE> my_jsondict['__class__'] = my_model.__class__.__name__ <NEW_LINE> my_model_json = my_model.to_json() <NEW_LINE> for key, value in my_model_json.items(): <NEW_LINE> <INDENT> self.assertEqual(my_jsondict[key], value) <NEW_LINE> <DEDENT> <DEDENT> def test_BaseModelPrint(self): <NEW_LINE> <INDENT> my_model = BaseModel() <NEW_LINE> expected_print = "[{}] ({}) {}\n".format(my_model.__class__.__name__, my_model.id, my_model.__dict__) <NEW_LINE> with patch('sys.stdout', new=StringIO()) as fake_out: <NEW_LINE> <INDENT> print(my_model) <NEW_LINE> self.assertEqual(fake_out.getvalue(), expected_print) | Testing base model | 62598fbbaad79263cf42e981 |
class getitem: <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> self.c = Collection() <NEW_LINE> <DEDENT> def finds_own_tasks_by_name(self): <NEW_LINE> <INDENT> self.c.add_task(_mytask, "foo") <NEW_LINE> assert self.c["foo"] == _mytask <NEW_LINE> <DEDENT> def finds_subcollection_tasks_by_dotted_name(self): <NEW_LINE> <INDENT> sub = Collection("sub") <NEW_LINE> sub.add_task(_mytask) <NEW_LINE> self.c.add_collection(sub) <NEW_LINE> assert self.c["sub._mytask"] == _mytask <NEW_LINE> <DEDENT> def honors_aliases_in_own_tasks(self): <NEW_LINE> <INDENT> t = Task(_func, aliases=["bar"]) <NEW_LINE> self.c.add_task(t, "foo") <NEW_LINE> assert self.c["bar"] == t <NEW_LINE> <DEDENT> def honors_subcollection_task_aliases(self): <NEW_LINE> <INDENT> self.c.add_collection(load("decorators")) <NEW_LINE> assert "decorators.bar" in self.c <NEW_LINE> <DEDENT> def honors_own_default_task_with_no_args(self): <NEW_LINE> <INDENT> t = Task(_func, default=True) <NEW_LINE> self.c.add_task(t) <NEW_LINE> assert self.c[""] == t <NEW_LINE> <DEDENT> def honors_subcollection_default_tasks_on_subcollection_name(self): <NEW_LINE> <INDENT> sub = Collection.from_module(load("decorators")) <NEW_LINE> self.c.add_collection(sub) <NEW_LINE> assert self.c["decorators.biz"] is sub["biz"] <NEW_LINE> assert self.c["decorators"] is self.c["decorators.biz"] <NEW_LINE> <DEDENT> def raises_ValueError_for_no_name_and_no_default(self): <NEW_LINE> <INDENT> with raises(ValueError): <NEW_LINE> <INDENT> self.c[""] <NEW_LINE> <DEDENT> <DEDENT> def ValueError_for_empty_subcol_task_name_and_no_default(self): <NEW_LINE> <INDENT> self.c.add_collection(Collection("whatever")) <NEW_LINE> with raises(ValueError): <NEW_LINE> <INDENT> self.c["whatever"] | __getitem__ | 62598fbbcc40096d6161a2af |
class TestTrialBalance(a_t_f_c.AbstractTestForeignCurrency): <NEW_LINE> <INDENT> def _getReportModel(self): <NEW_LINE> <INDENT> return self.env['report_trial_balance'] <NEW_LINE> <DEDENT> def _getQwebReportName(self): <NEW_LINE> <INDENT> return 'account_financial_report.report_trial_balance_qweb' <NEW_LINE> <DEDENT> def _getXlsxReportName(self): <NEW_LINE> <INDENT> return 'a_f_r.report_trial_balance_xlsx' <NEW_LINE> <DEDENT> def _getXlsxReportActionName(self): <NEW_LINE> <INDENT> return 'account_financial_report.action_report_trial_balance_xlsx' <NEW_LINE> <DEDENT> def _getReportTitle(self): <NEW_LINE> <INDENT> return 'Odoo' <NEW_LINE> <DEDENT> def _getBaseFilters(self): <NEW_LINE> <INDENT> return { 'date_from': date(date.today().year, 1, 1), 'date_to': date(date.today().year, 12, 31), 'company_id': self.company.id, 'fy_start_date': date(date.today().year, 1, 1), 'foreign_currency': True, 'show_partner_details': True, } <NEW_LINE> <DEDENT> def _getAdditionalFiltersToBeTested(self): <NEW_LINE> <INDENT> return [ {'only_posted_moves': True}, {'hide_account_at_0': True}, {'show_partner_details': True}, {'hierarchy_on': 'computed'}, {'hierarchy_on': 'relation'}, {'only_posted_moves': True, 'hide_account_at_0': True, 'hierarchy_on': 'computed'}, {'only_posted_moves': True, 'hide_account_at_0': True, 'hierarchy_on': 'relation'}, {'only_posted_moves': True, 'hide_account_at_0': True}, {'only_posted_moves': True, 'show_partner_details': True}, {'hide_account_at_0': True, 'show_partner_details': True}, { 'only_posted_moves': True, 'hide_account_at_0': True, 'show_partner_details': True }, ] <NEW_LINE> <DEDENT> def _partner_test_is_possible(self, filters): <NEW_LINE> <INDENT> return 'show_partner_details' in filters | Technical tests for Trial Balance Report. | 62598fbb956e5f7376df5754 |
class Transformer(nn.Module): <NEW_LINE> <INDENT> def __init__(self, hidden_size, nlayers, ntokens, nhead=8, dropout=0.1, dropatt=0.1, relative_bias=True, pos_emb=False, pad=0): <NEW_LINE> <INDENT> super(Transformer, self).__init__() <NEW_LINE> self.drop = nn.Dropout(dropout) <NEW_LINE> self.emb = nn.Embedding(ntokens, hidden_size) <NEW_LINE> if pos_emb: <NEW_LINE> <INDENT> self.pos_emb = nn.Embedding(500, hidden_size) <NEW_LINE> <DEDENT> self.layers = nn.ModuleList([ layers.TransformerLayer(hidden_size, nhead, hidden_size * 4, dropout, dropatt=dropatt, relative_bias=relative_bias) for _ in range(nlayers)]) <NEW_LINE> self.norm = nn.LayerNorm(hidden_size) <NEW_LINE> self.output_layer = nn.Linear(hidden_size, ntokens) <NEW_LINE> self.output_layer.weight = self.emb.weight <NEW_LINE> self.init_weights() <NEW_LINE> self.nlayers = nlayers <NEW_LINE> self.nhead = nhead <NEW_LINE> self.ntokens = ntokens <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.pad = pad <NEW_LINE> <DEDENT> def init_weights(self): <NEW_LINE> <INDENT> initrange = 0.1 <NEW_LINE> self.emb.weight.data.uniform_(-initrange, initrange) <NEW_LINE> if hasattr(self, 'pos_emb'): <NEW_LINE> <INDENT> self.pos_emb.weight.data.uniform_(-initrange, initrange) <NEW_LINE> <DEDENT> self.output_layer.bias.data.fill_(0) <NEW_LINE> <DEDENT> def visibility(self, x, device): <NEW_LINE> <INDENT> visibility = (x != self.pad).float() <NEW_LINE> visibility = visibility[:, None, :].expand(-1, x.size(1), -1) <NEW_LINE> visibility = torch.repeat_interleave(visibility, self.nhead, dim=0) <NEW_LINE> return visibility.log() <NEW_LINE> <DEDENT> def encode(self, x, pos): <NEW_LINE> <INDENT> h = self.emb(x) <NEW_LINE> if hasattr(self, 'pos_emb'): <NEW_LINE> <INDENT> h = h + self.pos_emb(pos) <NEW_LINE> <DEDENT> h_list = [] <NEW_LINE> visibility = self.visibility(x, x.device) <NEW_LINE> for i in range(self.nlayers): <NEW_LINE> <INDENT> h_list.append(h) <NEW_LINE> h = self.layers[i]( h.transpose(0, 1), key_padding_mask=visibility).transpose(0, 1) <NEW_LINE> <DEDENT> output = h <NEW_LINE> h_array = torch.stack(h_list, dim=2) <NEW_LINE> return output, h_array <NEW_LINE> <DEDENT> def forward(self, x, pos): <NEW_LINE> <INDENT> batch_size, length = x.size() <NEW_LINE> raw_output, _ = self.encode(x, pos) <NEW_LINE> raw_output = self.norm(raw_output) <NEW_LINE> raw_output = self.drop(raw_output) <NEW_LINE> output = self.output_layer(raw_output) <NEW_LINE> return output.view(batch_size * length, -1), {'raw_output': raw_output,} | Transformer model. | 62598fbb2c8b7c6e89bd3972 |
class RegressionForestTest(SerializationTestMixin, unittest.TestCase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> import forpy <NEW_LINE> self.FOREST_CLASS = forpy.RegressionForest <NEW_LINE> self.FPNAME_END = ".fpf" <NEW_LINE> super(RegressionForestTest, self).__init__(*args, **kwargs) | Test the Regression Forest serialization. | 62598fbbad47b63b2c5a7a01 |
class RunCommandDocument(RunCommandDocumentBase): <NEW_LINE> <INDENT> _validation = { 'schema': {'required': True}, 'id': {'required': True}, 'os_type': {'required': True}, 'label': {'required': True}, 'description': {'required': True}, 'script': {'required': True}, } <NEW_LINE> _attribute_map = { 'schema': {'key': '$schema', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'os_type': {'key': 'osType', 'type': 'str'}, 'label': {'key': 'label', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, 'script': {'key': 'script', 'type': '[str]'}, 'parameters': {'key': 'parameters', 'type': '[RunCommandParameterDefinition]'}, } <NEW_LINE> def __init__( self, *, schema: str, id: str, os_type: Union[str, "OperatingSystemTypes"], label: str, description: str, script: List[str], parameters: Optional[List["RunCommandParameterDefinition"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(RunCommandDocument, self).__init__(schema=schema, id=id, os_type=os_type, label=label, description=description, **kwargs) <NEW_LINE> self.script = script <NEW_LINE> self.parameters = parameters | Describes the properties of a Run Command.
All required parameters must be populated in order to send to Azure.
:ivar schema: Required. The VM run command schema.
:vartype schema: str
:ivar id: Required. The VM run command id.
:vartype id: str
:ivar os_type: Required. The Operating System type. Possible values include: "Windows",
"Linux".
:vartype os_type: str or ~azure.mgmt.compute.v2021_07_01.models.OperatingSystemTypes
:ivar label: Required. The VM run command label.
:vartype label: str
:ivar description: Required. The VM run command description.
:vartype description: str
:ivar script: Required. The script to be executed.
:vartype script: list[str]
:ivar parameters: The parameters used by the script.
:vartype parameters: list[~azure.mgmt.compute.v2021_07_01.models.RunCommandParameterDefinition] | 62598fbb56b00c62f0fb2a68 |
class Int(CliType): <NEW_LINE> <INDENT> def get_help_str(self): <NEW_LINE> <INDENT> if self.help_str: <NEW_LINE> <INDENT> return super(Int, self).get_help_str() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Enter a number' <NEW_LINE> <DEDENT> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(value) <NEW_LINE> return True, '' <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False, 'Value is not an integer' <NEW_LINE> <DEDENT> <DEDENT> def get_the_value(self, value): <NEW_LINE> <INDENT> return int(value) <NEW_LINE> <DEDENT> def type(self): <NEW_LINE> <INDENT> return int | Int class is the class for any integer argument.
| 62598fbb97e22403b383b0b4 |
class ListZones(CLIRunnable): <NEW_LINE> <INDENT> action = 'list' <NEW_LINE> def execute(self, args): <NEW_LINE> <INDENT> if args['<zone>']: <NEW_LINE> <INDENT> return self.list_zone(args) <NEW_LINE> <DEDENT> return self.list_all_zones() <NEW_LINE> <DEDENT> def list_zone(self, args): <NEW_LINE> <INDENT> manager = DNSManager(self.client) <NEW_LINE> table = Table(['id', 'record', 'type', 'ttl', 'value']) <NEW_LINE> table.align['ttl'] = 'l' <NEW_LINE> table.align['record'] = 'r' <NEW_LINE> table.align['value'] = 'l' <NEW_LINE> zone_id = resolve_id(manager.resolve_ids, args['<zone>'], name='zone') <NEW_LINE> records = manager.get_records( zone_id, record_type=args.get('--type'), host=args.get('--record'), ttl=args.get('--ttl'), data=args.get('--data'), ) <NEW_LINE> for record in records: <NEW_LINE> <INDENT> table.add_row([ record['id'], record['host'], record['type'].upper(), record['ttl'], record['data'] ]) <NEW_LINE> <DEDENT> return table <NEW_LINE> <DEDENT> def list_all_zones(self): <NEW_LINE> <INDENT> manager = DNSManager(self.client) <NEW_LINE> zones = manager.list_zones() <NEW_LINE> table = Table(['id', 'zone', 'serial', 'updated']) <NEW_LINE> table.align['serial'] = 'c' <NEW_LINE> table.align['updated'] = 'c' <NEW_LINE> for zone in zones: <NEW_LINE> <INDENT> table.add_row([ zone['id'], zone['name'], zone['serial'], zone['updateDate'], ]) <NEW_LINE> <DEDENT> return table | usage: sl dns list [<zone>] [options]
List zones and optionally, records
Filters:
--data=DATA Record data, such as an IP address
--record=HOST Host record, such as www
--ttl=TTL TTL value in seconds, such as 86400
--type=TYPE Record type, such as A or CNAME | 62598fbb4527f215b58ea081 |
class GetEditLockResponse: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'result': 'GetEditLockResult', 'status': 'str', 'error_message': 'str' } <NEW_LINE> self.result = None <NEW_LINE> self.status = None <NEW_LINE> self.error_message = None | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fbb3317a56b869be625 |
class RandomRotate(object): <NEW_LINE> <INDENT> def __init__(self, degrees, axes=[0, 1, 2]): <NEW_LINE> <INDENT> if isinstance(degrees, numbers.Number): <NEW_LINE> <INDENT> degrees = (-abs(degrees), abs(degrees)) <NEW_LINE> <DEDENT> assert isinstance(degrees, (tuple, list)) and len(degrees) == 2 <NEW_LINE> self.degrees = degrees <NEW_LINE> self.axes = axes <NEW_LINE> <DEDENT> def __call__(self, data): <NEW_LINE> <INDENT> if data.pos.size(-1) == 2: <NEW_LINE> <INDENT> degree = math.pi * random.uniform(*self.degrees) / 180.0 <NEW_LINE> sin, cos = math.sin(degree), math.cos(degree) <NEW_LINE> matrix = [[cos, sin], [-sin, cos]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> m1, m2, m3 = torch.eye(3), torch.eye(3), torch.eye(3) <NEW_LINE> if 0 in self.axes: <NEW_LINE> <INDENT> degree = math.pi * random.uniform(*self.degrees) / 180.0 <NEW_LINE> sin, cos = math.sin(degree), math.cos(degree) <NEW_LINE> m1 = torch.tensor([[1, 0, 0], [0, cos, sin], [0, -sin, cos]]) <NEW_LINE> <DEDENT> if 1 in self.axes: <NEW_LINE> <INDENT> degree = math.pi * random.uniform(*self.degrees) / 180.0 <NEW_LINE> sin, cos = math.sin(degree), math.cos(degree) <NEW_LINE> m2 = torch.tensor([[cos, 0, -sin], [0, 1, 0], [sin, 0, cos]]) <NEW_LINE> <DEDENT> if 2 in self.axes: <NEW_LINE> <INDENT> degree = math.pi * random.uniform(*self.degrees) / 180.0 <NEW_LINE> sin, cos = math.sin(degree), math.cos(degree) <NEW_LINE> m3 = torch.tensor([[cos, sin, 0], [-sin, cos, 0], [0, 0, 1]]) <NEW_LINE> <DEDENT> matrix = torch.mm(torch.mm(m1, m2), m3) <NEW_LINE> <DEDENT> data_rotated = LinearTransformation(matrix)(data) <NEW_LINE> if hasattr(data_rotated, "cell"): <NEW_LINE> <INDENT> data_rotated.cell = torch.matmul(data_rotated.cell, matrix) <NEW_LINE> <DEDENT> return ( data_rotated, matrix, torch.inverse(matrix), ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}({}, axis={})".format( self.__class__.__name__, self.degrees, self.axis ) | Rotates node positions around a specific axis by a randomly sampled
factor within a given interval.
Args:
degrees (tuple or float): Rotation interval from which the rotation
angle is sampled. If `degrees` is a number instead of a
tuple, the interval is given by :math:`[-\mathrm{degrees},
\mathrm{degrees}]`.
axes (int, optional): The rotation axes. (default: `[0, 1, 2]`) | 62598fbbd7e4931a7ef3c241 |
class BUIClients: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.clientsobj = Clients <NEW_LINE> self.clients = self.clientsobj.get_clients() <NEW_LINE> <DEDENT> def translate_clients_stats(self): <NEW_LINE> <INDENT> clients_list_api = TranslateBurpuiAPI(clients=self.clients) <NEW_LINE> clients_reports = clients_list_api.translate_clients() <NEW_LINE> return clients_reports | "
Get data from burp ui clients | 62598fbb4f6381625f199599 |
class Bewerking(Codelijst): <NEW_LINE> <INDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"Bewerking({self.id}, '{self.naam}', '{self.definitie}')" | An edit. | 62598fbb4c3428357761a469 |
class MessagesMixin(object): <NEW_LINE> <INDENT> def _get_messages_from_response_cookies(self, response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return messages.storage.cookie.CookieStorage(response)._decode(response.cookies['messages'].value) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _assert_request_message(self, request_message, expected_message_tags, expected_message_text): <NEW_LINE> <INDENT> self.assertEqual(request_message.tags, expected_message_tags) <NEW_LINE> self.assertEqual(request_message.message, expected_message_text) <NEW_LINE> <DEDENT> def _assert_django_test_client_messages(self, test_client_response, expected_log_messages): <NEW_LINE> <INDENT> response_messages = [ (msg.level, msg.message) for msg in test_client_response.context['messages'] ] <NEW_LINE> assert response_messages == expected_log_messages | Mixin for testing expected Django messages. | 62598fbba05bb46b3848aa19 |
class DatabaseError(RedsError): <NEW_LINE> <INDENT> pass | Raised if there was an error regarding the access control database. | 62598fbb5fcc89381b266223 |
class ADMMParameters: <NEW_LINE> <INDENT> def __init__( self, rho_initial: float = 10000, factor_c: float = 100000, beta: float = 1000, maxiter: int = 10, tol: float = 1.0e-4, max_time: float = np.inf, three_block: bool = True, vary_rho: int = UPDATE_RHO_BY_TEN_PERCENT, tau_incr: float = 2, tau_decr: float = 2, mu_res: float = 10, mu_merit: float = 1000, warm_start: bool = False, ) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.mu_merit = mu_merit <NEW_LINE> self.mu_res = mu_res <NEW_LINE> self.tau_decr = tau_decr <NEW_LINE> self.tau_incr = tau_incr <NEW_LINE> self.vary_rho = vary_rho <NEW_LINE> self.three_block = three_block <NEW_LINE> self.max_time = max_time <NEW_LINE> self.tol = tol <NEW_LINE> self.maxiter = maxiter <NEW_LINE> self.factor_c = factor_c <NEW_LINE> self.beta = beta <NEW_LINE> self.rho_initial = rho_initial <NEW_LINE> self.warm_start = warm_start <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> props = ", ".join([f"{key}={value}" for (key, value) in vars(self).items()]) <NEW_LINE> return f"{type(self).__name__}({props})" | Defines a set of parameters for ADMM optimizer. | 62598fbb3539df3088ecc45a |
class OperationFailed (Exception): <NEW_LINE> <INDENT> def __init__(self, op, message=None): <NEW_LINE> <INDENT> Exception.__init__(self, message) <NEW_LINE> self.op = op <NEW_LINE> self.clab_message = 'The requested operation failed: (%s) # DETAILS: %s'%(op, message) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.clab_message) | Exception indicating that the operation requested failed in its execution
Encapsulates orm.api.ResponseStatusError and uses its message to provide information
about the failure | 62598fbb44b2445a339b6a4c |
class Json: <NEW_LINE> <INDENT> def __init__(self, obj, encode=None): <NEW_LINE> <INDENT> self.obj = obj <NEW_LINE> self.encode = encode or jsonencode <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> obj = self.obj <NEW_LINE> if isinstance(obj, basestring): <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> return self.encode(obj) | Construct a wrapper for holding an object serializable to JSON. | 62598fbb8a349b6b436863ea |
class PortScannerAsync(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._process = None <NEW_LINE> self._nm = PortScanner() <NEW_LINE> return <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self._process is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self._process.is_alive(): <NEW_LINE> <INDENT> self._process.terminate() <NEW_LINE> <DEDENT> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self._process = None <NEW_LINE> return <NEW_LINE> <DEDENT> def scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', callback=None, sudo=False): <NEW_LINE> <INDENT> if sys.version_info[0] == 2: <NEW_LINE> <INDENT> assert type(hosts) in (str, unicode), 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts)) <NEW_LINE> assert type(ports) in (str, unicode, type(None)), 'Wrong type for [ports], should be a string [was {0}]'.format(type(ports)) <NEW_LINE> assert type(arguments) in (str, unicode), 'Wrong type for [arguments], should be a string [was {0}]'.format(type(arguments)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert type(hosts) is str, 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts)) <NEW_LINE> assert type(ports) in (str, type(None)), 'Wrong type for [ports], should be a string [was {0}]'.format(type(ports)) <NEW_LINE> assert type(arguments) is str, 'Wrong type for [arguments], should be a string [was {0}]'.format(type(arguments)) <NEW_LINE> <DEDENT> assert callable(callback) or callback is None, 'The [callback] {0} should be callable or None.'.format(str(callback)) <NEW_LINE> for redirecting_output in ['-oX', '-oA']: <NEW_LINE> <INDENT> assert not redirecting_output in arguments, 'Xml output can\'t be redirected from command line.\nYou can access it after a scan using:\nnmap.nm.get_nmap_last_output()' <NEW_LINE> <DEDENT> self._process = Process( target=__scan_progressive__, args=(self, hosts, ports, arguments, callback, sudo) ) <NEW_LINE> self._process.daemon = True <NEW_LINE> self._process.start() <NEW_LINE> return <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if self._process is not None: <NEW_LINE> <INDENT> self._process.terminate() <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def wait(self, timeout=None): <NEW_LINE> <INDENT> assert type(timeout) in (int, type(None)), 'Wrong type for [timeout], should be an int or None [was {0}]'.format(type(timeout)) <NEW_LINE> self._process.join(timeout) <NEW_LINE> return <NEW_LINE> <DEDENT> def still_scanning(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._process.is_alive() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False | PortScannerAsync allows to use nmap from python asynchronously
for each host scanned, callback is called with scan result for the host | 62598fbb656771135c48981c |
class PatternHostTaskWebSocket(BaseWebSocket): <NEW_LINE> <INDENT> def open(self, callback_timeout=500): <NEW_LINE> <INDENT> super().open(callback_timeout=callback_timeout) <NEW_LINE> self.limit = 10 <NEW_LINE> self.offset = 0 <NEW_LINE> self.pattern_task_status = [] <NEW_LINE> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> super().on_message(message) <NEW_LINE> try: <NEW_LINE> <INDENT> message = json.loads(message) <NEW_LINE> self.message = message <NEW_LINE> self.callback() <NEW_LINE> <DEDENT> except JSONDecodeError: <NEW_LINE> <INDENT> self.render_json_response(code=400, msg='Request arguments format error', res=message) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.render_json_response(code=400, msg='Unknown error on message', res=message) <NEW_LINE> <DEDENT> <DEDENT> def callback(self): <NEW_LINE> <INDENT> if self.message is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> result = { 'publish_task': [], 'publish_pattern_task': [] } <NEW_LINE> publish_tasks = [] <NEW_LINE> publish_pattern_host_id = self.message['publish_pattern_host_id'] <NEW_LINE> with session_scope() as ss: <NEW_LINE> <INDENT> q = ss.query(PublishTask).join( PublishPatternTask, PublishPatternTask.id == PublishTask.publish_pattern_task_id).filter( PublishPatternTask.publish_pattern_host_id == publish_pattern_host_id) <NEW_LINE> db_res = q.limit(self.limit).offset(self.offset).all() <NEW_LINE> pattern_tasks = ss.query(PublishPatternTask).filter_by( publish_pattern_host_id=publish_pattern_host_id).all() <NEW_LINE> publish_pattern_task = [t.to_dict() for t in pattern_tasks] <NEW_LINE> new_task_status = [t['status'] for t in publish_pattern_task] <NEW_LINE> if db_res: <NEW_LINE> <INDENT> for t in db_res: <NEW_LINE> <INDENT> if t.status in ('SUCCESS', 'FAILED'): <NEW_LINE> <INDENT> publish_tasks.append(t.to_dict()) <NEW_LINE> <DEDENT> <DEDENT> result['publish_task'] = publish_tasks <NEW_LINE> self.offset += len(publish_tasks) <NEW_LINE> <DEDENT> if publish_tasks or new_task_status != self.pattern_task_status: <NEW_LINE> <INDENT> self.pattern_task_status = new_task_status <NEW_LINE> result['publish_pattern_task'] = publish_pattern_task <NEW_LINE> self.render_json_response(res=result) | request arguments:
{
"publish_pattern_host_id": 0
}
response:
{
"code": 200,
"msg": "",
"res": {
'publish_task': [],
'publish_pattern_task': []
},
} | 62598fbb7d847024c075c56a |
class NodeSelector(_kuber_definitions.Definition): <NEW_LINE> <INDENT> def __init__( self, node_selector_terms: typing.List["NodeSelectorTerm"] = None, ): <NEW_LINE> <INDENT> super(NodeSelector, self).__init__(api_version="core/v1", kind="NodeSelector") <NEW_LINE> self._properties = { "nodeSelectorTerms": node_selector_terms if node_selector_terms is not None else [], } <NEW_LINE> self._types = { "nodeSelectorTerms": (list, NodeSelectorTerm), } <NEW_LINE> <DEDENT> @property <NEW_LINE> def node_selector_terms(self) -> typing.List["NodeSelectorTerm"]: <NEW_LINE> <INDENT> return typing.cast( typing.List["NodeSelectorTerm"], self._properties.get("nodeSelectorTerms"), ) <NEW_LINE> <DEDENT> @node_selector_terms.setter <NEW_LINE> def node_selector_terms( self, value: typing.Union[typing.List["NodeSelectorTerm"], typing.List[dict]] ): <NEW_LINE> <INDENT> cleaned: typing.List[NodeSelectorTerm] = [] <NEW_LINE> for item in value: <NEW_LINE> <INDENT> if isinstance(item, dict): <NEW_LINE> <INDENT> item = typing.cast( NodeSelectorTerm, NodeSelectorTerm().from_dict(item), ) <NEW_LINE> <DEDENT> cleaned.append(typing.cast(NodeSelectorTerm, item)) <NEW_LINE> <DEDENT> self._properties["nodeSelectorTerms"] = cleaned <NEW_LINE> <DEDENT> def __enter__(self) -> "NodeSelector": <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> return False | A node selector represents the union of the results of one
or more label queries over a set of nodes; that is, it
represents the OR of the selectors represented by the node
selector terms. | 62598fbb97e22403b383b0b5 |
class TestExternalPower(unittest.TestCase): <NEW_LINE> <INDENT> @patch('ups_lite.UPS.__init__', return_value=None) <NEW_LINE> @patch('RPi.GPIO.input', return_value=GPIO.HIGH) <NEW_LINE> def test_external_power_on(self, gpio_mock, ups_mock): <NEW_LINE> <INDENT> ups = ups_lite.UPS() <NEW_LINE> self.assertTrue(ups.external_power(), msg='Expect power on when GPIO ' 'pin 4 is HIGH') <NEW_LINE> gpio_mock.assert_called_with(4) <NEW_LINE> <DEDENT> @patch('ups_lite.UPS.__init__', return_value=None) <NEW_LINE> @patch('RPi.GPIO.input', return_value=GPIO.LOW) <NEW_LINE> def test_external_power_off(self, gpio_mock, ups_mock): <NEW_LINE> <INDENT> ups = ups_lite.UPS() <NEW_LINE> self.assertTrue(not ups.external_power(), msg='Expect power off when ' 'GPIO pin 4 is LOW') <NEW_LINE> gpio_mock.assert_called_with(4) | Test cases for external_power. | 62598fbcadb09d7d5dc0a72b |
class PWMError(IOError): <NEW_LINE> <INDENT> pass | Base class for PWM errors. | 62598fbc7d43ff24874274db |
class InvalidInput(RuntimeError): <NEW_LINE> <INDENT> pass | Signify that the input to the API was invalid. | 62598fbcaad79263cf42e983 |
class Triggers: <NEW_LINE> <INDENT> trigger_list = [] | Playing an animation trigger causes the game engine play an animation of a particular type.
The engine may pick one of a number of actual animations to play based on
Cozmo's mood or emotion, or with random weighting. Thus playing the same
trigger twice may not result in the exact same underlying animation playing
twice.
To play an exact animation, use play_anim with a named animation.
This class holds the set of defined animations triggers to pass to play_anim_trigger. | 62598fbcd268445f26639c5b |
class Operation(object): <NEW_LINE> <INDENT> def __init__(self, message=None, op_dict=None): <NEW_LINE> <INDENT> self.type = None <NEW_LINE> self.id = None <NEW_LINE> self.plugin = None <NEW_LINE> self.data = None <NEW_LINE> self.result = None <NEW_LINE> if message: <NEW_LINE> <INDENT> self._load_message(message) <NEW_LINE> <DEDENT> elif op_dict: <NEW_LINE> <INDENT> self.__dict__ = dict(self.__dict__.items() + op_dict.items()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.id = self._self_assigned_id() <NEW_LINE> <DEDENT> <DEDENT> def _self_assigned_id(self): <NEW_LINE> <INDENT> return misc.generate_uuid() + gvars.SELF_GENERATED_OP_ID <NEW_LINE> <DEDENT> def _load_message(self, message): <NEW_LINE> <INDENT> json_message = json.loads(message) <NEW_LINE> self.type = json_message.get(MessageKey.OPERATION) <NEW_LINE> self.id = json_message.get( MessageKey.OPERATION_ID, self._self_assigned_id() ) <NEW_LINE> self.plugin = json_message.get(MessageKey.PLUGIN) <NEW_LINE> self.data = json_message.get(MessageKey.DATA, {}) <NEW_LINE> <DEDENT> def is_savable(self): <NEW_LINE> <INDENT> savable = [] <NEW_LINE> return self.type in savable <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> def log_print(self): <NEW_LINE> <INDENT> return "({0}, {1})".format(self.type, self.id) | Represents an operation to be run by the agent. | 62598fbc23849d37ff851262 |
class MediaDefiningClass(type): <NEW_LINE> <INDENT> def __new__(mcs, name, bases, attrs): <NEW_LINE> <INDENT> new_class = super(MediaDefiningClass, mcs).__new__(mcs, name, bases, attrs) <NEW_LINE> if 'media' not in attrs: <NEW_LINE> <INDENT> new_class.media = media_property(new_class) <NEW_LINE> <DEDENT> return new_class | 元类:媒体定义。 | 62598fbcbe7bc26dc9251f33 |
class Walker(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.visitors = list() <NEW_LINE> <DEDENT> def accept(self, node, **kwargs): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for v in self.visitors: v.enter(node) <NEW_LINE> name = 'accept_' + node.__class__.__name__ <NEW_LINE> fn = getattr(self, name, self.default_accept) <NEW_LINE> r = fn(node, **kwargs) <NEW_LINE> for v in self.visitors: v.leave(node) <NEW_LINE> return r <NEW_LINE> <DEDENT> def default_accept(self, node, **kwargs): <NEW_LINE> <INDENT> for child in filter(None, node.children): <NEW_LINE> <INDENT> self.accept(child, **kwargs) | A walker may be used to walk a tree. | 62598fbc377c676e912f6e48 |
class Help(click.Command): <NEW_LINE> <INDENT> def parse_args(self, ctx, args): <NEW_LINE> <INDENT> return [] | Do not parse any arguments, allow any args past the `help` command,
always return the help output | 62598fbc97e22403b383b0b6 |
class TradeOrderBookQueueHandler(QueueHandler): <NEW_LINE> <INDENT> def __init__(self, queue): <NEW_LINE> <INDENT> QueueHandler.__init__(self,queue) <NEW_LINE> <DEDENT> def prepare(self, record): <NEW_LINE> <INDENT> record.args = None <NEW_LINE> record.exc_info = None <NEW_LINE> return record | We ant to avoid doing any text transform of the record object
we with format in the other thread as above in prepare
This is operating in the main thread | 62598fbc5166f23b2e24358d |
class Extension(extensions.Extension): <NEW_LINE> <INDENT> _action_collection_class = actions.Actions <NEW_LINE> _panel_widget_class = widget.Widget <NEW_LINE> _panel_dock_area = Qt.LeftDockWidgetArea <NEW_LINE> _config_widget_class = config.Config <NEW_LINE> _settings_config = { 'show': True, 'message': _("Initial extension message") } <NEW_LINE> def __init__(self, parent, name): <NEW_LINE> <INDENT> super(Extension, self).__init__(parent, name) <NEW_LINE> <DEDENT> def app_settings_changed(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def settings_changed(self, key, old, new): <NEW_LINE> <INDENT> if key == 'show': <NEW_LINE> <INDENT> self.action_collection().generic_action.setEnabled(new) | Boilerplate extension "My Extension".
This is a minimal, working Frescobaldi extension providing
stubs for all relevant functions. | 62598fbc1f5feb6acb162dcf |
class XAccelRedirectResponse(HttpResponse): <NEW_LINE> <INDENT> def __init__(self, redirect_url, content_type, basename=None, expires=None, with_buffering=None, limit_rate=None, attachment=True): <NEW_LINE> <INDENT> super(XAccelRedirectResponse, self).__init__(content_type=content_type) <NEW_LINE> if attachment: <NEW_LINE> <INDENT> self.basename = basename or redirect_url.split('/')[-1] <NEW_LINE> self['Content-Disposition'] = 'attachment; filename={name}'.format( name=self.basename) <NEW_LINE> <DEDENT> self['X-Accel-Redirect'] = redirect_url <NEW_LINE> self['X-Accel-Charset'] = content_type_to_charset(content_type) <NEW_LINE> if with_buffering is not None: <NEW_LINE> <INDENT> self['X-Accel-Buffering'] = with_buffering and 'yes' or 'no' <NEW_LINE> <DEDENT> if expires: <NEW_LINE> <INDENT> expire_seconds = timedelta(expires - datetime.now()).seconds <NEW_LINE> self['X-Accel-Expires'] = expire_seconds <NEW_LINE> <DEDENT> elif expires is not None: <NEW_LINE> <INDENT> self['X-Accel-Expires'] = 'off' <NEW_LINE> <DEDENT> if limit_rate is not None: <NEW_LINE> <INDENT> self['X-Accel-Limit-Rate'] = (limit_rate and '%d' % limit_rate or 'off') | Http response that delegates serving file to Nginx. | 62598fbc67a9b606de54617c |
class LoudDict(dict): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> dict.__init__(self, *args, **kwargs) <NEW_LINE> self.callback = lambda x: None <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if key in self and self.__getitem__(key) == value: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> dict.__setitem__(self, key, value) <NEW_LINE> self.callback(key) <NEW_LINE> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) > 1: <NEW_LINE> <INDENT> raise TypeError("update expected at most 1 arguments, got %d" % len(args)) <NEW_LINE> <DEDENT> other = dict(*args, **kwargs) <NEW_LINE> for key in other: <NEW_LINE> <INDENT> self[key] = other[key] <NEW_LINE> <DEDENT> <DEDENT> def set_change_callback(self, callback): <NEW_LINE> <INDENT> self.callback = callback | A Dictionary with a callback for
item changes. | 62598fbc796e427e5384e945 |
class Ice(Data): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Ice, self).__init__() <NEW_LINE> <DEDENT> def load(self, filename, build_hkl=True, load_instrument=False): <NEW_LINE> <INDENT> with open(filename) as f: <NEW_LINE> <INDENT> file_header = [] <NEW_LINE> for line in f: <NEW_LINE> <INDENT> if 'Columns' in line: <NEW_LINE> <INDENT> args = line.split() <NEW_LINE> col_headers = [head for head in args[1:]] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> args = np.genfromtxt(filename, usecols=(0, 1, 2, 3, 4, 5, 6, 7, 8), unpack=True, comments="#", dtype=np.float64) <NEW_LINE> data = OrderedDict() <NEW_LINE> for head, col in zip(col_headers, args): <NEW_LINE> <INDENT> data[head] = col <NEW_LINE> <DEDENT> self._data = data <NEW_LINE> self.data_keys = {'detector': 'Detector', 'monitor': 'Monitor', 'time': 'Time'} <NEW_LINE> self._file_header = file_header <NEW_LINE> if build_hkl: <NEW_LINE> <INDENT> self.Q_keys = {'h': 'QX', 'k': 'QY', 'l': 'QZ', 'e': 'E', 'temp': 'Temp'} <NEW_LINE> <DEDENT> if load_instrument: <NEW_LINE> <INDENT> instrument = Instrument() <NEW_LINE> self.instrument = instrument | Loads ICE (NCNR) format ascii data file.
| 62598fbc498bea3a75a57cd4 |
class Rectangle: <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.__width = width <NEW_LINE> self.__height = height <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> string = "" <NEW_LINE> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(self.height): <NEW_LINE> <INDENT> for j in range(self.width): <NEW_LINE> <INDENT> string += '#' <NEW_LINE> <DEDENT> if i != self.height - 1: <NEW_LINE> <INDENT> string += '\n' <NEW_LINE> <DEDENT> <DEDENT> return string <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Rectangle({}, {})".format(self.width, self.height) <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__width = value <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__height = value <NEW_LINE> <DEDENT> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.width * self.height <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.width + self.height) * 2 | create a rectangle class | 62598fbc5fdd1c0f98e5e141 |
class TestUrlSsrfResponseBatch(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testUrlSsrfResponseBatch(self): <NEW_LINE> <INDENT> pass | UrlSsrfResponseBatch unit test stubs | 62598fbca8370b77170f058f |
class Solution(object): <NEW_LINE> <INDENT> def nthUglyNumber(self, n): <NEW_LINE> <INDENT> heap = [1] <NEW_LINE> visited = {1: True} <NEW_LINE> while 1: <NEW_LINE> <INDENT> min_num = heappop(heap) <NEW_LINE> n -= 1 <NEW_LINE> if n == 0: <NEW_LINE> <INDENT> return min_num <NEW_LINE> <DEDENT> for num in [min_num*2, min_num*3, min_num*5]: <NEW_LINE> <INDENT> if num in visited: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> visited[num] = True <NEW_LINE> heappush(heap, num) | Heap. TODO: DP. | 62598fbcaad79263cf42e984 |
class ValidationWarning(object): <NEW_LINE> <INDENT> def __init__(self, key, details): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.details = details | Tracks job data configuration warnings during validation that may not prevent the job from working. | 62598fbc851cf427c66b8466 |
class PolynomialBase(ParametricModel): <NEW_LINE> <INDENT> _param_names = [] <NEW_LINE> linear = True <NEW_LINE> col_fit_deriv = False <NEW_LINE> @lazyproperty <NEW_LINE> def param_names(self): <NEW_LINE> <INDENT> return self._param_names <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> if self._param_names and attr in self._param_names: <NEW_LINE> <INDENT> return Parameter(attr, default=0.0, model=self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(PolynomialBase, self).__getattr__(attr) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, attr, value): <NEW_LINE> <INDENT> if attr[0] != '_' and self._param_names and attr in self._param_names: <NEW_LINE> <INDENT> param = Parameter(attr, default=0.0, model=self) <NEW_LINE> param.__set__(self, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(PolynomialBase, self).__setattr__(attr, value) <NEW_LINE> <DEDENT> <DEDENT> def _deriv_with_constraints(self, params=None, x=None, y=None): <NEW_LINE> <INDENT> if y is None: <NEW_LINE> <INDENT> d = np.array(self.fit_deriv(x=x)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d = np.array(self.fit_deriv(x=x, y=y)) <NEW_LINE> <DEDENT> if self.col_fit_deriv: <NEW_LINE> <INDENT> return d[self._fit_param_indices] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return d[:, self._fit_param_indices] | Base class for all polynomial-like models with an arbitrary number of
parameters in the form of coeffecients.
In this case Parameter instances are returned through the class's
``__getattr__`` rather than through class descriptors. | 62598fbc7d43ff24874274dc |
class EnumSpace(Generic[T], GymSpace[T], EnumerableSpace[T]): <NEW_LINE> <INDENT> def __init__(self, enum_class: EnumMeta) -> None: <NEW_LINE> <INDENT> self._enum_class = enum_class <NEW_LINE> self._list_enum = list(enum_class) <NEW_LINE> gym_space = gym_spaces.Discrete(len(enum_class)) <NEW_LINE> super().__init__(gym_space) <NEW_LINE> <DEDENT> def contains(self, x: T) -> bool: <NEW_LINE> <INDENT> return isinstance(x, self._enum_class) <NEW_LINE> <DEDENT> def get_elements(self) -> Iterable[T]: <NEW_LINE> <INDENT> return self._list_enum <NEW_LINE> <DEDENT> def sample(self) -> T: <NEW_LINE> <INDENT> return self._list_enum[super().sample()] <NEW_LINE> <DEDENT> def to_jsonable(self, sample_n: Iterable[T]) -> Sequence: <NEW_LINE> <INDENT> return [sample.name for sample in sample_n] <NEW_LINE> <DEDENT> def from_jsonable(self, sample_n: Sequence) -> Iterable[T]: <NEW_LINE> <INDENT> return [self._enum_class[sample] for sample in sample_n] <NEW_LINE> <DEDENT> def unwrapped(self) -> gym_spaces.Discrete: <NEW_LINE> <INDENT> return super().unwrapped() <NEW_LINE> <DEDENT> def to_unwrapped(self, sample_n: Iterable[T]) -> Iterable[int]: <NEW_LINE> <INDENT> return [self._list_enum.index(sample) for sample in sample_n] <NEW_LINE> <DEDENT> def from_unwrapped(self, sample_n: Iterable[int]) -> Iterable[T]: <NEW_LINE> <INDENT> return [self._list_enum[sample] for sample in sample_n] | This class creates an OpenAI Gym Discrete space (gym.spaces.Discrete) from an enumeration and wraps it as a
scikit-decide enumerable space.
!!! warning
Using this class requires OpenAI Gym to be installed. | 62598fbcaad79263cf42e985 |
class NegateOperator(Node): <NEW_LINE> <INDENT> def __init__(self, expr): <NEW_LINE> <INDENT> self.left = expr <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return "not operator at %s" % (self.position) <NEW_LINE> <DEDENT> @failure_info <NEW_LINE> def eval(self, ctx): <NEW_LINE> <INDENT> return not self.left.eval(ctx) <NEW_LINE> <DEDENT> def failure_info(self, ctx): <NEW_LINE> <INDENT> err = self.name() + " failed because sub-expression %s is true" % self.left.name() <NEW_LINE> ctx.failed.append(err) | Used to negate a result | 62598fbc9f28863672818953 |
class W16(VOSIWarning, XMLWarning): <NEW_LINE> <INDENT> message_template = ( "The element table is not a valid root element in VOSI below v1.1") | The table element is not a valid root element in VOSI before version 1.1 | 62598fbc2c8b7c6e89bd3976 |
class InvalidObjectId(BadRequest): <NEW_LINE> <INDENT> def __init__(self, description=None, response=None): <NEW_LINE> <INDENT> desc = {'description': 'Resource ID is not a valid monogdb ObjectId'} <NEW_LINE> if description is not None: <NEW_LINE> <INDENT> desc.update(description) <NEW_LINE> <DEDENT> super().__init__(description=desc, response=None) | *400* `Bad Request`
Raise if the browser sends something to the application the application
or server cannot handle. | 62598fbc56ac1b37e630239e |
class InstructHelper(object): <NEW_LINE> <INDENT> proxy_process = 'iproxy' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.subprocessHandle = [] <NEW_LINE> reg_cleanup(self.teardown) <NEW_LINE> <DEDENT> @on_method_ready('start') <NEW_LINE> def get_ready(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def teardown(self): <NEW_LINE> <INDENT> for sub_proc in self.subprocessHandle: <NEW_LINE> <INDENT> sub_proc.kill() <NEW_LINE> <DEDENT> <DEDENT> @retries(3) <NEW_LINE> def setup_proxy(self, remote_port): <NEW_LINE> <INDENT> local_port = random.randint(11111, 20000) <NEW_LINE> self.do_proxy(local_port, remote_port) <NEW_LINE> return local_port, remote_port <NEW_LINE> <DEDENT> def do_proxy(self, local_port, remote_port): <NEW_LINE> <INDENT> cmds = [self.proxy_process, str(local_port), str(remote_port)] <NEW_LINE> proc = subprocess.Popen( cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) <NEW_LINE> time.sleep(0.5) <NEW_LINE> if proc.poll() is not None: <NEW_LINE> <INDENT> stdout, stderr = proc.communicate() <NEW_LINE> stdout = stdout.decode(get_std_encoding(sys.stdout)) <NEW_LINE> stderr = stderr.decode(get_std_encoding(sys.stderr)) <NEW_LINE> raise DevalError((stdout, stderr)) <NEW_LINE> <DEDENT> self.subprocessHandle.append(proc) | ForwardHelper class
or help run other Instruction | 62598fbc55399d3f056266c5 |
class HttpInvalidRequestLine(_BaseTest): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(self.__class__, self).__init__(b"http_invalid_request_line") | OONI's http-invalid-request-line test | 62598fbc5166f23b2e24358f |
class IndicatorTypeListAPIView(ListAPIView): <NEW_LINE> <INDENT> queryset = IndicatorType.objects.all() <NEW_LINE> serializer_class = indicator_type_serializer['IndicatorTypeListSerializer'] <NEW_LINE> filter_backends = (DjangoFilterBackend,) <NEW_LINE> filter_class = IndicatorTypeListFilter <NEW_LINE> pagination_class = APILimitOffsetPagination | API list view. Gets all records API. | 62598fbcdc8b845886d5376a |
class log_save(object): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> if value is not None and isinstance(value, LoggedException): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value.save() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> log.exception('Got double exception while trying to ' 'save a LoggedException') | with-statement addition that makes sure that if the exception
seen is of type 'LoggedException' it will be saved. This *will*
propagate the exception upwards and not stop it. | 62598fbc7047854f4633f586 |
class ItemUsefulnessSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> item = AsymetricRelatedField.from_serializer( ItemSerializer, kwargs={'required': True}) <NEW_LINE> usefulness = AsymetricRelatedField.from_serializer( UsefulnessSerializer, kwargs={'required': True}) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = ItemUsefulnessModel <NEW_LINE> fields = '__all__' | Common serializer for all ItemUsefulness actions | 62598fbc4f6381625f19959b |
class VersionException(ApiException): <NEW_LINE> <INDENT> def __init__(self, expected_version, received_version): <NEW_LINE> <INDENT> ApiException.__init__(self) <NEW_LINE> self.expected_version = expected_version <NEW_LINE> self.received_version = received_version <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Incompatible API version '{0}' specified; " "expected: '{1}'.".format(self.received_version, self.expected_version) | Exception used to indicate that the client's requested api version
is not supported. | 62598fbc3d592f4c4edbb06f |
class is_title(Predicate): <NEW_LINE> <INDENT> def __call__(self, token): <NEW_LINE> <INDENT> return token.value.istitle() | str.istitle
>>> predicate = is_title()
>>> a, b = tokenize('XXX Xxx')
>>> predicate(a)
False
>>> predicate(b)
True | 62598fbc0fa83653e46f5095 |
class DescribeTagRetentionExecutionTaskResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RetentionTaskList = None <NEW_LINE> self.TotalCount = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("RetentionTaskList") is not None: <NEW_LINE> <INDENT> self.RetentionTaskList = [] <NEW_LINE> for item in params.get("RetentionTaskList"): <NEW_LINE> <INDENT> obj = RetentionTask() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.RetentionTaskList.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> self.RequestId = params.get("RequestId") | DescribeTagRetentionExecutionTask返回参数结构体
| 62598fbc7c178a314d78d651 |
class PollEvents(threading.Thread): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(PollEvents, self).__init__() <NEW_LINE> self.alive = True <NEW_LINE> self._callback = {} <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.alive = False <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def stop(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.alive = False <NEW_LINE> self.join(self.sleep_time) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> while self.alive: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not self.poll_server(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> log(traceback.format_exc()) <NEW_LINE> self.alive = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def poll_server(self): <NEW_LINE> <INDENT> if not self._callback: <NEW_LINE> <INDENT> time.sleep(self.sleep_time) <NEW_LINE> return True <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> event = poll_events() <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> log(traceback.format_exc()) <NEW_LINE> return False <NEW_LINE> <DEDENT> if not event: <NEW_LINE> <INDENT> time.sleep(self.sleep_time) <NEW_LINE> return True <NEW_LINE> <DEDENT> event = event.split('-', 1) <NEW_LINE> data = event[1] <NEW_LINE> event_type = event[0] <NEW_LINE> for name in self._callback: <NEW_LINE> <INDENT> if (event_type == "onwindowcreate" and re.match(glob_trans(name), data, re.M | re.U | re.L)) or (event_type != "onwindowcreate" and self._callback[name][0] == event_type) or event_type == 'kbevent': <NEW_LINE> <INDENT> if event_type == 'kbevent': <NEW_LINE> <INDENT> keys, modifiers = data.split('-') <NEW_LINE> fname = 'kbevent%s%s' % (keys, modifiers) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fname = name <NEW_LINE> <DEDENT> callback = self._callback[fname][1] <NEW_LINE> if not callable(callback): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> args = self._callback[fname][2] <NEW_LINE> try: <NEW_LINE> <INDENT> if len(args) and args[0]: <NEW_LINE> <INDENT> _t = threading.Thread(target=callback, args=args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _t = threading.Thread(target=callback, args=()) <NEW_LINE> <DEDENT> _t.start() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> log(traceback.format_exc()) <NEW_LINE> pass <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> <DEDENT> return True | Class to poll callback events, NOTE: *NOT* for external use | 62598fbc656771135c489820 |
class _PlecostBase(object, metaclass=ABCMeta): <NEW_LINE> <INDENT> def __init__(self, ver1, ver2): <NEW_LINE> <INDENT> if ver1 is None or ver1 is None: <NEW_LINE> <INDENT> self._outdated = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not isinstance(ver1, str): <NEW_LINE> <INDENT> raise TypeError("Expected basestring, got '%s' instead" % type(ver1)) <NEW_LINE> <DEDENT> if not isinstance(ver2, str): <NEW_LINE> <INDENT> raise TypeError("Expected basestring, got '%s' instead" % type(ver2)) <NEW_LINE> <DEDENT> if self.__version_cmp(ver1, ver2) == -1: <NEW_LINE> <INDENT> self._outdated = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._outdated = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __version_cmp(self, version1, version2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tup = lambda x: [int(y) for y in (x+'.0.0.0.0').split('.')][:4] <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if version1.lower() == "trunk": <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif version2.lower() == "trunk": <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not re.search("([\\d]\\.[\\d]\\.*[\\d]*)", version1) or not re.search("([\\d]\\.[\\d]\\.*[\\d]*)", version2): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if tup(version1) > tup(version2): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif tup(version1) < tup(version2): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def is_outdated(self): <NEW_LINE> <INDENT> return self._outdated | Abstract class for all Plecost types | 62598fbca8370b77170f0591 |
class Genre(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return unicode(self.name) <NEW_LINE> <DEDENT> def from_dict(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.save() | Жанр фильмов | 62598fbc97e22403b383b0b9 |
class GeneratorConditionNumberTask(EvalTask): <NEW_LINE> <INDENT> _CONDITION_NUMBER_COUNT = "log_condition_number_count" <NEW_LINE> _CONDITION_NUMBER_MEAN = "log_condition_number_mean" <NEW_LINE> _CONDITION_NUMBER_STD = "log_condition_number_std" <NEW_LINE> def MetricsList(self): <NEW_LINE> <INDENT> return frozenset([ self._CONDITION_NUMBER_COUNT, self._CONDITION_NUMBER_MEAN, self._CONDITION_NUMBER_STD ]) <NEW_LINE> <DEDENT> def RunInSession(self, options, sess, gan, real_images): <NEW_LINE> <INDENT> del real_images <NEW_LINE> result_dict = {} <NEW_LINE> if options.get("compute_generator_condition_number", False): <NEW_LINE> <INDENT> result = ComputeGeneratorConditionNumber(sess, gan) <NEW_LINE> result_dict[self._CONDITION_NUMBER_COUNT] = len(result) <NEW_LINE> result_dict[self._CONDITION_NUMBER_MEAN] = np.mean(result) <NEW_LINE> result_dict[self._CONDITION_NUMBER_STD] = np.std(result) <NEW_LINE> <DEDENT> return result_dict | Computes the generator condition number.
Computes the condition number for metric Tensor of the generator Jacobian.
This condition number is computed locally for each z sample in a minibatch.
Returns the mean log condition number and standard deviation across the
minibatch.
Follows the methods in https://arxiv.org/abs/1802.08768. | 62598fbc091ae35668704dd5 |
class Order_Truck(Order): <NEW_LINE> <INDENT> def __init__(self,count_car,speed=80,distance_max=400,weight_min=1000,weight_max=9000,size_min=60,size_max=180, cost=4000,price=7 ,profit=9): <NEW_LINE> <INDENT> super().__init__(count_car,speed,distance_max,weight_min,weight_max,size_min,size_max, cost,price) | грузові автомобілі | 62598fbcaad79263cf42e986 |
class PyCRYPTHASH(object): <NEW_LINE> <INDENT> def __new__(cls): <NEW_LINE> <INDENT> raise Exception('This class just for typing, can not be instanced!') <NEW_LINE> <DEDENT> def CryptDestroyHash(self,) -> 'None': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CryptDuplicateHash(self,Flags:'Any'=0) -> 'PyCRYPTHASH': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CryptHashData(self,Data:'str',Flags:'Any'=0) -> 'None': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CryptHashSessionKey(self,Key:'PyCRYPTKEY',Flags:'Any'=0) -> 'None': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CryptSignHash(self,KeySpec:'Any',Flags:'Any'=0) -> 'str': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CryptVerifySignature(self,Signature:'str',PubKey:'PyCRYPTKEY',Flags:'Any'=0) -> 'None': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def CryptGetHashParam(self,Param:'Any',Flags:'Any'=0) -> 'Union[Any]': <NEW_LINE> <INDENT> pass | Handle to a cryptographic hash | 62598fbcaad79263cf42e987 |
class StringMultichoice(Choice): <NEW_LINE> <INDENT> paramType = 'string-enumeration-multiple' <NEW_LINE> multiple = True | Define a multichose string parameter type.
Values of this type are iterable sequences of strings
all of which must be an element of a predefined set.
>>> @argument('people', types.StringMultichoice, choices=('alice', 'bob', 'charlie'))
... def func(people=('alice', 'bob')):
... pass | 62598fbc71ff763f4b5e792c |
class GetTransactionStatusInputSet(InputSet): <NEW_LINE> <INDENT> def set_AWSAccessKeyId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSAccessKeyId', value) <NEW_LINE> <DEDENT> def set_AWSSecretKeyId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AWSSecretKeyId', value) <NEW_LINE> <DEDENT> def set_Endpoint(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Endpoint', value) <NEW_LINE> <DEDENT> def set_TransactionId(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'TransactionId', value) | An InputSet with methods appropriate for specifying the inputs to the GetTransactionStatus
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62598fbcbe7bc26dc9251f35 |
class Stack(): <NEW_LINE> <INDENT> def __init__(self, d=None): <NEW_LINE> <INDENT> if d is None: <NEW_LINE> <INDENT> d = [] <NEW_LINE> <DEDENT> self.d = d <NEW_LINE> <DEDENT> def dump(self): <NEW_LINE> <INDENT> return self.d <NEW_LINE> <DEDENT> def peek(self): <NEW_LINE> <INDENT> return self.d[-1] if len(self) != 0 else None <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> return self.d.pop() if len(self) != 0 else None <NEW_LINE> <DEDENT> def push(self, val): <NEW_LINE> <INDENT> if val is not None: <NEW_LINE> <INDENT> self.d.append(val) <NEW_LINE> <DEDENT> <DEDENT> def reverse(self): <NEW_LINE> <INDENT> self.d = self.d[::-1] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.d) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.d) | Stack implementation wrapping Python Lists | 62598fbc2c8b7c6e89bd3978 |
class TD_IPSO_3302_04(CoAPTestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> @typecheck <NEW_LINE> def get_stimulis(cls) -> list_of(Value): <NEW_LINE> <INDENT> return [CoAP(type='con', code='put')] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.match('server', CoAP(type='con', code='put', opt=self.uri('/3302/0')), 'fail') <NEW_LINE> self.match('server', CoAP(pl=Not(b'')), 'fail') <NEW_LINE> self.match('server', CoAP(opt=Opt(CoAPOptionContentFormat('11543'))), 'fail') <NEW_LINE> self.next() <NEW_LINE> self.match('client', CoAP(code=Any(65, 68)), 'fail') <NEW_LINE> self.match('client', CoAP(pl=(b'')), 'fail') | testcase_id: TD_IPSO_3302_04
uri: http://openmobilealliance.org/iot/lightweight-m2m-lwm2m
configuration: LWM2M_CFG_01
objective:
- Setting the writable resources of object 3302 (Presence) Instance 0 using JSON data format (11543)
- This test has to be run for the following resources
- - Busy to Clear delay
- - Clear to Busy delay
pre_conditions:
- Device is registred with the Server
- The current values of the Server Object (ID:1) Instance 0, are saved on the Server
- The Client supports the Configuration C.3 (A superset of C.1 where server objects implements {Default Minimum PEriod, Default Maximum Period, Disable Timeout} additional resources)
- - LWM2M Server Object (ID = 1) Instance 0 with mandatory resources and Short Server ID = 1
- - LWM2M Security Object (ID = 0) Instance 0 with mandatory resources and Bootstrap Server = False
- - LWM2M Device Object (ID = 3) Instance 0 with mandatory resources.
- The Client supports IPSO Presence object (ID:3302) with mandatory resources.
sequence:
- step_id: 'TD_IPSO_3302_04_step_01'
type: stimuli
node: lwm2m_server
description:
- 'LwM2M server sends a WRITE request (CoAP PUT) on Presence object instance'
- - Type = 0 (CON)
- Code = 3 (PUT)
- step_id: 'TD_IPSO_3302_04_step_02'
type: check
description:
- 'Sent PUT request contains'
- - Type=0 and Code=3
- Non-empty payload = A serialized representation of Presentation object instance
- content-format=application/vnd.oma.lwm2m+json
- URI-Path option= 3302/0
- step_id: 'TD_IPSO_3302_04_step_03'
type: check
description:
- 'LwM2M client sends response containing'
- - Code = 2.04 (Changed)
- content-format=application/vnd.oma.lwm2m+json
- empty payload
- step_id: 'TD_IPSO_3302_04_step_04'
type: verify
node: lwm2m_server
description:
- 'LwM2M server indicates successful operation'
| 62598fbc56b00c62f0fb2a6e |
class LogisticRegression(object): <NEW_LINE> <INDENT> def __init__(self, rng, input, n_in, n_out): <NEW_LINE> <INDENT> W_values = numpy.asarray( rng.uniform( low=-numpy.sqrt(6. / (n_in + n_out)), high=numpy.sqrt(6. / (n_in + n_out)), size=(n_in, n_out) ), dtype=theano.config.floatX ) <NEW_LINE> self.W = theano.shared( value= W_values, name='W', borrow=True ) <NEW_LINE> self.b = theano.shared( value=numpy.zeros( (n_out,), dtype=theano.config.floatX ), name='b', borrow=True ) <NEW_LINE> self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b) + 0.0000001 <NEW_LINE> self.y_pred = T.argmax(self.p_y_given_x, axis=1) <NEW_LINE> self.params = [self.W, self.b] <NEW_LINE> self.input = input <NEW_LINE> <DEDENT> def negative_log_likelihood(self, y): <NEW_LINE> <INDENT> return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y]) <NEW_LINE> <DEDENT> def errors(self, y): <NEW_LINE> <INDENT> if y.ndim != self.y_pred.ndim: <NEW_LINE> <INDENT> raise TypeError( 'y should have the same shape as self.y_pred', ('y', y.type, 'y_pred', self.y_pred.type) ) <NEW_LINE> <DEDENT> if y.dtype.startswith('int'): <NEW_LINE> <INDENT> return T.mean(T.neq(self.y_pred, y)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError() | Multi-class Logistic Regression Class
The logistic regression is fully described by a weight matrix :math:`W`
and bias vector :math:`b`. Classification is done by projecting data
points onto a set of hyperplanes, the distance to which is used to
determine a class membership probability. | 62598fbc56ac1b37e63023a0 |
class ErrorNonDict(Exception): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return u'Аргумент функции должен быть словарём.' | Исключение - аргумент функции не словарь | 62598fbc5166f23b2e243591 |
class hybrid_ann_consistency_diagnoser(a_star_frame): <NEW_LINE> <INDENT> def __init__(self, alpha=0.95): <NEW_LINE> <INDENT> super(hybrid_ann_consistency_diagnoser, self).__init__() <NEW_LINE> self.res_set = [] <NEW_LINE> self.res_values = [] <NEW_LINE> self.alpha = alpha <NEW_LINE> <DEDENT> def set_res_set(self, res_set): <NEW_LINE> <INDENT> self.res_set = res_set <NEW_LINE> <DEDENT> def set_res_values(self, res_values): <NEW_LINE> <INDENT> self.res_values = res_values <NEW_LINE> <DEDENT> def __solve_conflict(self, candidate, conf): <NEW_LINE> <INDENT> candi = np.array([-1]*len(self.order)) <NEW_LINE> for i in range(len(candidate)): <NEW_LINE> <INDENT> id = self.order[i] <NEW_LINE> candi[id] = candidate[i] <NEW_LINE> <DEDENT> for i in range(len(conf)): <NEW_LINE> <INDENT> if (conf[i] == 1) and (candi[i] != 0): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def __conflict_cost(self, candidate): <NEW_LINE> <INDENT> cost = 0 <NEW_LINE> for i in range(len(self.res_set)): <NEW_LINE> <INDENT> if not self.res_values[i]: <NEW_LINE> <INDENT> conf = self.res_set[i] <NEW_LINE> cost_c = -log(self.alpha) if self.__solve_conflict(candidate, conf) else -log(1 - self.alpha) <NEW_LINE> cost = cost + cost_c <NEW_LINE> <DEDENT> <DEDENT> return cost <NEW_LINE> <DEDENT> def __hold_consistency(self, candidate, consis): <NEW_LINE> <INDENT> candi = np.array([-1]*len(self.order)) <NEW_LINE> for i in range(len(candidate)): <NEW_LINE> <INDENT> id = self.order[i] <NEW_LINE> candi[id] = candidate[i] <NEW_LINE> <DEDENT> for i in range(len(consis)): <NEW_LINE> <INDENT> if (consis[i] == 1) and (candi[i] == 1): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def __consistency_cost(self, candidate): <NEW_LINE> <INDENT> alpha = 0.1 <NEW_LINE> beta = (1 - 2*alpha) * self.alpha + alpha <NEW_LINE> cost = 0 <NEW_LINE> for i in range(len(self.res_set)): <NEW_LINE> <INDENT> if self.res_values[i]: <NEW_LINE> <INDENT> consis = self.res_set[i] <NEW_LINE> cost_c = -log(beta) if self.__hold_consistency(candidate, consis) else -log(1 - beta) <NEW_LINE> cost = cost + cost_c <NEW_LINE> <DEDENT> <DEDENT> return cost <NEW_LINE> <DEDENT> def __likelihood_cost(self, candidate): <NEW_LINE> <INDENT> cost_conf = self.__conflict_cost(candidate) <NEW_LINE> cost_consis = self.__consistency_cost(candidate) <NEW_LINE> cost = cost_conf + cost_consis <NEW_LINE> return cost <NEW_LINE> <DEDENT> def _cost(self, candidate): <NEW_LINE> <INDENT> alpha = 1e-3 <NEW_LINE> cost = 0 <NEW_LINE> for c, i in zip(candidate, range(len(candidate))): <NEW_LINE> <INDENT> id = self.order[i] <NEW_LINE> value = c <NEW_LINE> p_c = self.priori[id][value] <NEW_LINE> p_c = (1 - 2*alpha) * p_c + alpha <NEW_LINE> cost_c = -log(p_c) <NEW_LINE> cost = cost + cost_c <NEW_LINE> <DEDENT> cost = cost + self.__likelihood_cost(candidate) <NEW_LINE> return cost | the hybrid diagnoser just based on hybrid ann diagnoser | 62598fbc3539df3088ecc460 |
class ForbiddenTest(RuleTest): <NEW_LINE> <INDENT> def _do_test(self): <NEW_LINE> <INDENT> self.assertTrue(len(self.rv) != 0, "Rule '%s' failed. Example '%s' should fail, but passed" % (self.c.name, self.tv)) | Tests forbidden constructs.
The rule checker should find errors in the example code. | 62598fbc796e427e5384e949 |
class _EagerContext(threading.local): <NEW_LINE> <INDENT> def __init__(self, config=None): <NEW_LINE> <INDENT> super(_EagerContext, self).__init__() <NEW_LINE> self.device_spec = _starting_device_spec <NEW_LINE> self.device_name = "" <NEW_LINE> self.mode = default_execution_mode <NEW_LINE> self.is_eager = default_execution_mode == EAGER_MODE <NEW_LINE> self.scope_name = "" <NEW_LINE> self.recording_summaries = False <NEW_LINE> self.summary_writer_resource = None <NEW_LINE> self.scalar_cache = {} <NEW_LINE> self._ones_rank_cache = None <NEW_LINE> self._zeros_cache = None <NEW_LINE> self.execution_mode = None <NEW_LINE> self._config = config <NEW_LINE> self._function_call_options = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def function_call_options(self): <NEW_LINE> <INDENT> if self._function_call_options is None: <NEW_LINE> <INDENT> base_config = config_pb2.ConfigProto() <NEW_LINE> if self._config is not None: <NEW_LINE> <INDENT> base_config.MergeFrom(self._config) <NEW_LINE> <DEDENT> self._config = None <NEW_LINE> self._function_call_options = FunctionCallOptions( config_proto=base_config) <NEW_LINE> <DEDENT> return self._function_call_options <NEW_LINE> <DEDENT> @function_call_options.setter <NEW_LINE> def function_call_options(self, function_call_options): <NEW_LINE> <INDENT> self._function_call_options = function_call_options <NEW_LINE> self._config = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def ones_rank_cache(self): <NEW_LINE> <INDENT> if not self._ones_rank_cache: <NEW_LINE> <INDENT> self._ones_rank_cache = _EagerTensorCache() <NEW_LINE> <DEDENT> return self._ones_rank_cache <NEW_LINE> <DEDENT> @property <NEW_LINE> def zeros_cache(self): <NEW_LINE> <INDENT> if not self._zeros_cache: <NEW_LINE> <INDENT> self._zeros_cache = _EagerTensorCache() <NEW_LINE> <DEDENT> return self._zeros_cache | Thread local eager context. | 62598fbc26068e7796d4cb0e |
class Teams(View): <NEW_LINE> <INDENT> @method_decorator(require_login) <NEW_LINE> def dispatch(self, *args, **kwargs): <NEW_LINE> <INDENT> return super(Teams, self).dispatch(*args, **kwargs) <NEW_LINE> <DEDENT> def get(self, request): <NEW_LINE> <INDENT> users = User.objects.all() <NEW_LINE> teams = [] <NEW_LINE> for user in users: <NEW_LINE> <INDENT> if not user.is_superuser: <NEW_LINE> <INDENT> teams.append(team_proto(user)) <NEW_LINE> <DEDENT> <DEDENT> return HttpResponse(json.dumps(teams, cls=ProtoJsonEncoder), content_type="application/json") | Gets a list of all teams. | 62598fbc44b2445a339b6a4f |
@attr.s <NEW_LINE> class MutationAcquisition(AcquisitionStrategy): <NEW_LINE> <INDENT> breadth: int = attr.ib() <NEW_LINE> breadth.validator(Validator.is_posint) <NEW_LINE> @staticmethod <NEW_LINE> @yaml_constructor('!MutationAcquisition', safe=True) <NEW_LINE> def from_yaml(loader, node) -> 'MutationAcquisition': <NEW_LINE> <INDENT> return MutationAcquisition(**loader.construct_mapping(node)) <NEW_LINE> <DEDENT> def acquire( self, population: IterableIndividuals, *, model: SurrogateModel, relscale: np.ndarray, rng: RandomState, fmin: float, space: Space, ): <NEW_LINE> <INDENT> for parent in population: <NEW_LINE> <INDENT> parent_sample_transformed = space.into_transformed(parent.sample) <NEW_LINE> candidate_samples = [ space.mutate_transformed( parent_sample_transformed, relscale=relscale, rng=rng) for _ in range(self.breadth)] <NEW_LINE> candidate_mean, candidate_std = model.predict_transformed_a( candidate_samples) <NEW_LINE> candidate_ei = expected_improvement( candidate_mean, candidate_std, fmin) <NEW_LINE> i = np.argmax(candidate_ei) <NEW_LINE> yield Individual( space.from_transformed(candidate_samples[i]), prediction=candidate_mean[i], expected_improvement=candidate_ei[i]) | Randomly mutate each parent to create new samples in their neighborhood.
| 62598fbca8370b77170f0593 |
class FirstReducer(Reducer): <NEW_LINE> <INDENT> def __call__(self, group_key: tp.Tuple[str, ...], rows: TRowsIterable) -> TRowsGenerator: <NEW_LINE> <INDENT> for row in rows: <NEW_LINE> <INDENT> yield row <NEW_LINE> break | Yield only first row from passed ones | 62598fbcfff4ab517ebcd998 |
class BoxTagTests(TagTest): <NEW_LINE> <INDENT> def test_plain(self): <NEW_LINE> <INDENT> t = Template('{% load djblets_deco %}' '{% box %}content{% endbox %}') <NEW_LINE> self.assertHTMLEqual( t.render(Context({})), '<div class="box-container"><div class="box">' '<div class="box-inner">\ncontent\n ' '</div></div></div>') <NEW_LINE> <DEDENT> def test_with_class(self): <NEW_LINE> <INDENT> t = Template('{% load djblets_deco %}' '{% box "class" %}content{% endbox %}') <NEW_LINE> self.assertHTMLEqual( t.render(Context({})), '<div class="box-container"><div class="box class">' '<div class="box-inner">\ncontent\n ' '</div></div></div>') <NEW_LINE> <DEDENT> def test_with_extra_arg_error(self): <NEW_LINE> <INDENT> with self.assertRaises(TemplateSyntaxError): <NEW_LINE> <INDENT> Template('{% load djblets_deco %}' '{% box "class" "foo" %}content{% endbox %}') | Unit tests for the {% box %} template tag. | 62598fbc442bda511e95c610 |
class TestIpamsvcCreateServerResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testIpamsvcCreateServerResponse(self): <NEW_LINE> <INDENT> pass | IpamsvcCreateServerResponse unit test stubs | 62598fbc099cdd3c636754bc |
class Controller(object): <NEW_LINE> <INDENT> klass = None <NEW_LINE> @classmethod <NEW_LINE> def get(cls, id): <NEW_LINE> <INDENT> return DB.get(cls.klass).get(id) | Main controller object to subclass other controllers from. Contains
some common logic.
TODO: De-dupe the create methods - requires a factory of sorts to create the
model objects | 62598fbcec188e330fdf8a46 |
class SQLGraph_Test(Mapping_Test): <NEW_LINE> <INDENT> dbname = 'test.dumbo_foo_test' <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> if not testutil.mysql_enabled(): <NEW_LINE> <INDENT> raise SkipTest("no MySQL") <NEW_LINE> <DEDENT> createOpts = dict(source_id='int', target_id='int', edge_id='int') <NEW_LINE> self.datagraph = sqlgraph.SQLGraph(self.dbname, dropIfExists=True, createTable=createOpts) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.datagraph.cursor.execute('drop table if exists %s' % self.dbname) | Runs the same tests on mapping.SQLGraph class | 62598fbcd486a94d0ba2c183 |
class Filesystem(ICanonicalSource): <NEW_LINE> <INDENT> def __init__(self, base_path: str) -> None: <NEW_LINE> <INDENT> self._base_path = base_path <NEW_LINE> <DEDENT> def _make_path(self, uri: D.URI) -> str: <NEW_LINE> <INDENT> return os.path.abspath(uri.path) <NEW_LINE> <DEDENT> def can_resolve(self, uri: D.URI) -> bool: <NEW_LINE> <INDENT> return uri.is_file and self._base_path in os.path.abspath(uri.path) <NEW_LINE> <DEDENT> def load(self, uri: D.URI) -> IO[bytes]: <NEW_LINE> <INDENT> if not self.can_resolve(uri): <NEW_LINE> <INDENT> raise RuntimeError(f'Cannot resolve this URI: {uri}') <NEW_LINE> <DEDENT> return open(self._make_path(uri), 'rb') | Retrieves content from a filesystem (outside the canonical record). | 62598fbc3617ad0b5ee062fb |
class AddReplicationInstanceResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TaskId = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TaskId = params.get("TaskId") <NEW_LINE> self.RequestId = params.get("RequestId") | AddReplicationInstance返回参数结构体
| 62598fbc4527f215b58ea089 |
class VideoFileInvalid(BadRequest): <NEW_LINE> <INDENT> ID = "VIDEO_FILE_INVALID" <NEW_LINE> MESSAGE = __doc__ | The video file is invalid | 62598fbc3317a56b869be629 |
class ApplicationSecurityGroupListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[ApplicationSecurityGroup]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["ApplicationSecurityGroup"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationSecurityGroupListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | A list of application security groups.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of application security groups.
:type value: list[~azure.mgmt.network.v2018_07_01.models.ApplicationSecurityGroup]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str | 62598fbc5fcc89381b266227 |
class UpdateQuery(_BaseSQLQuery): <NEW_LINE> <INDENT> def __init__(self, model, query=None, query_kwargs=None, raw_values=None, values=None, where_str=None): <NEW_LINE> <INDENT> if query is None: <NEW_LINE> <INDENT> query = 'UPDATE %s' % model.__table__ <NEW_LINE> <DEDENT> super(UpdateQuery, self).__init__(model, query, query_kwargs) <NEW_LINE> if where_str is None: <NEW_LINE> <INDENT> where_str = '' <NEW_LINE> <DEDENT> if raw_values is None: <NEW_LINE> <INDENT> raw_values = {} <NEW_LINE> <DEDENT> if values is None: <NEW_LINE> <INDENT> values = {} <NEW_LINE> <DEDENT> self.where_str = where_str <NEW_LINE> self.values_dict = values <NEW_LINE> self.raw_values_dict = raw_values <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> query = self.__class__(self.model, query=self.query, query_kwargs=self.query_kwargs.copy(), raw_values=self.raw_values_dict.copy(), values=self.values_dict.copy(), where_str=self.where_str) <NEW_LINE> return query <NEW_LINE> <DEDENT> def raw_values(self, **raw_values_kwargs): <NEW_LINE> <INDENT> return self._add_raw_values(raw_values_kwargs) <NEW_LINE> <DEDENT> def values(self, *values, **values_kwargs): <NEW_LINE> <INDENT> return self._add_values(values, values_kwargs) <NEW_LINE> <DEDENT> def _form_query(self): <NEW_LINE> <INDENT> query, kwargs = self._get_set_info(self.query, self.query_kwargs.copy()) <NEW_LINE> if self.where_str: <NEW_LINE> <INDENT> query += ' ' + self.where_str <NEW_LINE> <DEDENT> return query, kwargs <NEW_LINE> <DEDENT> def where(self, where_str, **where_kwargs): <NEW_LINE> <INDENT> return self._add_where(where_str, where_kwargs) <NEW_LINE> <DEDENT> def update(self, conn): <NEW_LINE> <INDENT> if not self.values_dict: <NEW_LINE> <INDENT> raise Exception('No values specified for UPDATE') <NEW_LINE> <DEDENT> query, kwargs = self._form_query() <NEW_LINE> cursor = self._execute(conn, query, kwargs) <NEW_LINE> return cursor.rowcount | UPDATE query. Be care with raw_values. See each method doc string
below. | 62598fbce5267d203ee6bab5 |
class PreCompFirstOrder(Base, SparseRWGraph): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> Base.__init__(self, *args, **kwargs) <NEW_LINE> self.alias_j = self.alias_q = None <NEW_LINE> <DEDENT> def get_move_forward(self): <NEW_LINE> <INDENT> indices = self.indices <NEW_LINE> indptr = self.indptr <NEW_LINE> alias_j = self.alias_j <NEW_LINE> alias_q = self.alias_q <NEW_LINE> @njit(nogil=True) <NEW_LINE> def move_forward(cur_idx, prev_idx=None): <NEW_LINE> <INDENT> start, end = indptr[cur_idx], indptr[cur_idx + 1] <NEW_LINE> choice = alias_draw(alias_j[start:end], alias_q[start:end]) <NEW_LINE> return indices[indptr[cur_idx] + choice] <NEW_LINE> <DEDENT> return move_forward <NEW_LINE> <DEDENT> def preprocess_transition_probs(self): <NEW_LINE> <INDENT> data = self.data <NEW_LINE> indices = self.indices <NEW_LINE> indptr = self.indptr <NEW_LINE> get_normalized_probs = self.get_normalized_probs_first_order <NEW_LINE> n_nodes = indptr.size - 1 <NEW_LINE> n_probs = indptr[-1] <NEW_LINE> @njit(parallel=True, nogil=True) <NEW_LINE> def compute_all_transition_probs(): <NEW_LINE> <INDENT> alias_j = np.zeros(n_probs, dtype=np.uint32) <NEW_LINE> alias_q = np.zeros(n_probs, dtype=np.float32) <NEW_LINE> for idx in range(n_nodes): <NEW_LINE> <INDENT> start, end = indptr[idx], indptr[idx + 1] <NEW_LINE> probs = get_normalized_probs(data, indices, indptr, idx) <NEW_LINE> alias_j[start:end], alias_q[start:end] = alias_setup(probs) <NEW_LINE> <DEDENT> return alias_j, alias_q <NEW_LINE> <DEDENT> self.alias_j, self.alias_q = compute_all_transition_probs() | Precompute transition probabilities for first order random walks. | 62598fbc9c8ee8231304024f |
class MachineSpiNNakerLinkVertex(MachineVertex, AbstractSpiNNakerLinkVertex): <NEW_LINE> <INDENT> __slots__ = ( "_spinnaker_link_id", "_board_address", "_virtual_chip_x", "_virtual_chip_y" ) <NEW_LINE> def __init__( self, spinnaker_link_id, board_address=None, label=None, constraints=None): <NEW_LINE> <INDENT> MachineVertex.__init__( self, ResourceContainer( dtcm=DTCMResource(0), sdram=SDRAMResource(0), cpu_cycles=CPUCyclesPerTickResource(0)), label=label, constraints=constraints) <NEW_LINE> self._spinnaker_link_id = spinnaker_link_id <NEW_LINE> self._board_address = board_address <NEW_LINE> self._virtual_chip_x = None <NEW_LINE> self._virtual_chip_y = None <NEW_LINE> <DEDENT> @property <NEW_LINE> @overrides(AbstractSpiNNakerLinkVertex.spinnaker_link_id) <NEW_LINE> def spinnaker_link_id(self): <NEW_LINE> <INDENT> return self._spinnaker_link_id <NEW_LINE> <DEDENT> @property <NEW_LINE> @overrides(AbstractSpiNNakerLinkVertex.board_address) <NEW_LINE> def board_address(self): <NEW_LINE> <INDENT> return self._board_address <NEW_LINE> <DEDENT> @property <NEW_LINE> @overrides(AbstractSpiNNakerLinkVertex.virtual_chip_x) <NEW_LINE> def virtual_chip_x(self): <NEW_LINE> <INDENT> return self._virtual_chip_x <NEW_LINE> <DEDENT> @property <NEW_LINE> @overrides(AbstractSpiNNakerLinkVertex.virtual_chip_y) <NEW_LINE> def virtual_chip_y(self): <NEW_LINE> <INDENT> return self._virtual_chip_y <NEW_LINE> <DEDENT> @overrides(AbstractSpiNNakerLinkVertex.set_virtual_chip_coordinates) <NEW_LINE> def set_virtual_chip_coordinates(self, virtual_chip_x, virtual_chip_y): <NEW_LINE> <INDENT> self._virtual_chip_x = virtual_chip_x <NEW_LINE> self._virtual_chip_y = virtual_chip_y | A virtual vertex on a SpiNNaker Link
| 62598fbc8a349b6b436863f2 |
class Launcher(DesktopEntry): <NEW_LINE> <INDENT> defaultGroup = 'GinfoTweaks Entry' <NEW_LINE> def parse(self, file): <NEW_LINE> <INDENT> IniFile.parse(self, file, allowedGroups) <NEW_LINE> <DEDENT> def launch(self): <NEW_LINE> <INDENT> exe = self.getExec() <NEW_LINE> command = [x for x in exe.split() if not '%' in x] <NEW_LINE> command = list2cmdline(command) <NEW_LINE> sp = Popen(command, shell=True) <NEW_LINE> return True <NEW_LINE> <DEDENT> def getAuthor(self): <NEW_LINE> <INDENT> return self.get('Author', locale=True) | Launcher class | 62598fbc7b180e01f3e4912a |
class Port(PortMixin,db.Model): <NEW_LINE> <INDENT> __tablename__ = 'ports' <NEW_LINE> __table_args__ = {'implicit_returning':False} <NEW_LINE> node_id = db.Column(db.Integer, db.ForeignKey('nodes.id')) | Port | 62598fbcaad79263cf42e98a |
class Mcp3002(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.device_no = 0 <NEW_LINE> self.speed = 1200000 <NEW_LINE> self.Vdd = 3.3 <NEW_LINE> self.step = 1023 <NEW_LINE> self.mode = 1 <NEW_LINE> self.msbf = 1 <NEW_LINE> self.extbus = Spi(spi_ch=0,mode=self.mode,speed=self.speed,bits_word=8) <NEW_LINE> <DEDENT> def transfer(self,adc_ch=0): <NEW_LINE> <INDENT> startbit = 1<<6 <NEW_LINE> mode= self.mode<<5 <NEW_LINE> msbf= self.msbf<<3 <NEW_LINE> send_data = 0x00 <NEW_LINE> send_data |= (startbit + mode + adc_ch + msbf) <NEW_LINE> dummy_data = 0xff <NEW_LINE> send_data = [send_data,dummy_data] <NEW_LINE> recv_data = [0,0] <NEW_LINE> recv_data = self.extbus.transfer(send_data,2) <NEW_LINE> val_ad= (((recv_data[0] & 0x03)<< 8) + recv_data[1]) <NEW_LINE> return val_ad <NEW_LINE> <DEDENT> def getVin(self,data): <NEW_LINE> <INDENT> voltage = (data * self.Vdd) / self.step <NEW_LINE> voltage -= 512 <NEW_LINE> return voltage <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> self.extbus.close() | mode :0 CPOL:0 CPHA:0
mode :1 CPOL:0 CPHA:1
mode :2 CPOL:1 CPHA:0
mode :3 CPOL:1 CPHA:1 | 62598fbcff9c53063f51a804 |
class TrelloActionData(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def board_name(self): <NEW_LINE> <INDENT> return self.data['board']['name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def card_name(self): <NEW_LINE> <INDENT> return self.data['card']['name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def list_name(self): <NEW_LINE> <INDENT> return self.data['list']['name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def list_before_name(self): <NEW_LINE> <INDENT> return self.data['listBefore']['name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def list_after_name(self): <NEW_LINE> <INDENT> return self.data['listAfter']['name'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self.data['text'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def card_permalink(self): <NEW_LINE> <INDENT> return TRELLO_PERMALINK_CARD.format( self.data['board']['id'], self.data['card']['idShort'] ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def check_item_name(self): <NEW_LINE> <INDENT> return self.data['checkItem']['name'] <NEW_LINE> <DEDENT> def check_item_state(self): <NEW_LINE> <INDENT> return self.data['checkItem']['state'] | Provide simple attribute access to action data. | 62598fbc7d43ff24874274df |
class _AxisMasking: <NEW_LINE> <INDENT> def __init__( self, max_len: int, min_num: int = 0, max_num: int = 1, mask_value: float = 0, deterministic: bool = False, start_index: int = 0): <NEW_LINE> <INDENT> self.max_len = max_len <NEW_LINE> self.min_num = min_num <NEW_LINE> self.max_num = max_num <NEW_LINE> self.mask_value = mask_value <NEW_LINE> self.deterministic = deterministic <NEW_LINE> self.start_index = start_index <NEW_LINE> <DEDENT> def __call__( self, signal: torch.Tensor, axis: int, return_mask_params: bool = False) -> torch.Tensor: <NEW_LINE> <INDENT> if not self.deterministic: <NEW_LINE> <INDENT> num_masks = random.randint(self.min_num, self.max_num) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> num_masks = 1 <NEW_LINE> <DEDENT> mask_params = [] <NEW_LINE> size = signal.shape[axis] <NEW_LINE> if size <= self.max_len: <NEW_LINE> <INDENT> return signal <NEW_LINE> <DEDENT> for _ in range(num_masks): <NEW_LINE> <INDENT> if not self.deterministic: <NEW_LINE> <INDENT> mask_len = random.randint(1, self.max_len) <NEW_LINE> start_index = random.randint(0, size - mask_len) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mask_len = self.max_len <NEW_LINE> start_index = self.start_index <NEW_LINE> <DEDENT> if axis == 0: <NEW_LINE> <INDENT> signal[start_index: start_index + mask_len] = self.mask_value <NEW_LINE> <DEDENT> elif axis == 1: <NEW_LINE> <INDENT> signal[:, start_index: start_index + mask_len] = self.mask_value <NEW_LINE> <DEDENT> elif axis == 2: <NEW_LINE> <INDENT> signal[:, :, start_index: start_index + mask_len] = self.mask_value <NEW_LINE> <DEDENT> mask_params.append([start_index, mask_len]) <NEW_LINE> <DEDENT> if return_mask_params: <NEW_LINE> <INDENT> return signal, mask_params <NEW_LINE> <DEDENT> return signal | Applies masking along a given axis with option for overlapping masks
:param max_len: maximum length for a single mask; mask length would be
sampled from [0, max_len]
:type max_len: int
:param min_num: minimum number of masks to apply; defaults to 0
:type min_num: int
:param max_num: maximum number of masks to apply; number of masks would be
sampled from [min_num, max_num]; can lead to overlapping masks,
defaults to 1
:type max_num: int
:param mask_value: value to be used as mask, defaults to 0
:type mask_value: float
:param deterministic: whether the mask is deterministic; if True,
`start_index` is mandatory, `num_masks` is not used and `max_len` is
considered the mask length, defaults to False
:type deterministic: bool
:param start_index: index at which to start masking; only used for
`deterministic=True`; defaults to 0
:type start_index: int | 62598fbccc40096d6161a2b4 |
class TimingDiagram: <NEW_LINE> <INDENT> def __init__(self, width = 800, height = 600, margin = 20, font_size = 12, font_family = 'Times New Roman', background = 0xffffff, foreground = 0x000000, start = 0, end = 100, step = None, delay = 10, signals = None): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> if margin > width / 2 or margin > height / 2: <NEW_LINE> <INDENT> raise ValueError('The diagram margin must be less than half the width or ' 'half the height of the diagram (whichever is less).') <NEW_LINE> <DEDENT> self.margin = margin <NEW_LINE> self.font_size = font_size <NEW_LINE> self.font_family = font_family <NEW_LINE> self.background = background <NEW_LINE> self.foreground = foreground <NEW_LINE> self.start = start <NEW_LINE> self.end = end <NEW_LINE> self.step = step <NEW_LINE> self.delay = delay <NEW_LINE> self.signals = signals or [] | The main timing diagram struct.
Holds global style and timing information, as well as a list of signals (each
a Clock, Bus or Line).
Style properties are self-explantory, while the timing properties are as
follows:
start: The minimum time value displayed in the chart. For example, if start
is set to 20, and a signal changes at time 10, it will not be shown in the
diagram. This can be a negative value.
end: The maximum time value displayed in the chart. For example, if end is
set to 20, and a signal changes at time 30, it will not be shown in the
diagram.
step: If not None, the diagram is split into columns, each step time units
wide, labeled with T#, where # is the column number.
delay: The length of time it takes each signal to complete a value change. | 62598fbc63b5f9789fe85326 |
class HelloSerializer(serializers.Serializer): <NEW_LINE> <INDENT> name = serializers.CharField(max_length=10) | serializes a name field for testing our APIView | 62598fbc23849d37ff85126a |
class DragAndDropTests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> Timings.defaults() <NEW_LINE> self.app = Application() <NEW_LINE> self.app.start(os.path.join(mfc_samples_folder, u"CmnCtrl1.exe")) <NEW_LINE> self.dlg = self.app.Common_Controls_Sample <NEW_LINE> self.ctrl = self.dlg.TreeView.wrapper_object() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.app.kill() <NEW_LINE> <DEDENT> def testDragMouseInput(self): <NEW_LINE> <INDENT> birds = self.ctrl.get_item(r'\Birds') <NEW_LINE> dogs = self.ctrl.get_item(r'\Dogs') <NEW_LINE> birds.click_input() <NEW_LINE> time.sleep(5) <NEW_LINE> self.ctrl.drag_mouse_input(dst=dogs.client_rect().mid_point(), src=birds.client_rect().mid_point(), absolute=False) <NEW_LINE> dogs = self.ctrl.get_item(r'\Dogs') <NEW_LINE> self.assertEqual([child.text() for child in dogs.children()], [u'Birds', u'Dalmatian', u'German Shepherd', u'Great Dane']) | Unit tests for mouse actions like drag-n-drop | 62598fbc4c3428357761a473 |
class ParameterOptions: <NEW_LINE> <INDENT> def __init__(self): pass | Empty class to assemble related settings | 62598fbc4f6381625f19959e |
class PrivateKeyJwt(ClientSecretJwt): <NEW_LINE> <INDENT> def verify_assertion(self, param): <NEW_LINE> <INDENT> return False | Clients that have registered a public key sign a JWT using that key.
The Client authenticates in accordance
with JSON Web Token (JWT) Profile for
OAuth 2.0 Client Authentication and
Authorization Grants [OAuth.JWT] and
Assertion Framework for OAuth 2.0 Client Authentication and
Authorization Grants [OAuth.Assertions]. | 62598fbc796e427e5384e94d |
class FUNCtion(SCPINode, SCPIQuery, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "FUNCtion" <NEW_LINE> args = ["GAUSsian", "NOISe", "RAMP", "SINusoid", "SQUare", "TRIangle", "UNIForm"] <NEW_LINE> class NOISe(SCPINode, SCPIQuery, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "NOISe" <NEW_LINE> args = ["GAUSsian", "UNIForm"] <NEW_LINE> <DEDENT> NOISe = NOISe() <NEW_LINE> class SHAPe(SCPINode, SCPIQuery, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "SHAPe" <NEW_LINE> args = ["SINE", "SQUare"] <NEW_LINE> <DEDENT> SHAPe = SHAPe() | SOURce:PM:INTernal:FUNCtion
Arguments: GAUSsian, NOISe, RAMP, SINusoid, SQUare, TRIangle, UNIForm | 62598fbce5267d203ee6bab7 |
class CleanUpFile(object): <NEW_LINE> <INDENT> def __init__(self, fpath): <NEW_LINE> <INDENT> self._fpath = fpath <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> if os.path.exists(self._fpath): <NEW_LINE> <INDENT> os.remove(self._fpath) | Context utility for ensuring that a given file is always removed after a test is run | 62598fbc8a349b6b436863f4 |
class Token: <NEW_LINE> <INDENT> def __init__(self, type, val): <NEW_LINE> <INDENT> self.type = type; <NEW_LINE> self.val = val; <NEW_LINE> <DEDENT> def un_op(self): <NEW_LINE> <INDENT> return calcapi.uop_bind[self.val] <NEW_LINE> <DEDENT> def bin_op(self): <NEW_LINE> <INDENT> return calcapi.bop_bind[self.val] | Represents a token placed in the expression
Tokens represent separated entities in a mathematical expression
which include operators and numbers. | 62598fbc7d847024c075c574 |
class CommentView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def get(self, request, order_id): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> if not order_id: <NEW_LINE> <INDENT> return redirect(reverse('user:userorder')) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> order = OrderInfo.objects.get(order_id=order_id, user=user) <NEW_LINE> <DEDENT> except OrderInfo.DoesNotExist: <NEW_LINE> <INDENT> return redirect(reverse('user:userorder')) <NEW_LINE> <DEDENT> order.status_name = OrderInfo.ORDER_STATUS[order.order_status] <NEW_LINE> order_skus = OrderGoods.objects.filter(order_id=order_id) <NEW_LINE> for order_sku in order_skus: <NEW_LINE> <INDENT> amount = order_sku.price * order_sku.count <NEW_LINE> order_sku.amount = amount <NEW_LINE> <DEDENT> order.order_skus = order_skus <NEW_LINE> return render(request, 'order_comment.html', {'order':order}) <NEW_LINE> <DEDENT> def post(self, request, order_id): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> if not order_id: <NEW_LINE> <INDENT> return redirect(reverse('user:userorder')) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> order = OrderInfo.objects.get(order_id=order_id, user=user) <NEW_LINE> <DEDENT> except OrderInfo.DoesNotExist: <NEW_LINE> <INDENT> return redirect(reverse('user:userorder')) <NEW_LINE> <DEDENT> total_count = request.POST.get('total_count') <NEW_LINE> total_count = int(total_count) <NEW_LINE> for i in range(1, total_count+1): <NEW_LINE> <INDENT> sku_id = request.POST.get('sku_%d'% i) <NEW_LINE> content = request.POST.get('content_%d'% i, '') <NEW_LINE> try: <NEW_LINE> <INDENT> order_goods = OrderGoods.objects.get(order=order, sku_id=sku_id) <NEW_LINE> <DEDENT> except OrderGoods.DoesNotExist: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> order_goods.comment = content <NEW_LINE> order_goods.save() <NEW_LINE> <DEDENT> order.order_status = 5 <NEW_LINE> order.save() <NEW_LINE> return redirect(reverse('user:userorder', kwargs={'page':1})) | 订单评论 | 62598fbc099cdd3c636754be |
@unittest.skip("The tests fail because the status of a MockPayment is NULL when saving, triggering an integrity error") <NEW_LINE> class PaymentMockTests(BluebottleTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(PaymentMockTests, self).setUp() <NEW_LINE> self.order_payment = OrderPaymentFactory.create(status=StatusDefinition.CREATED, amount=100, payment_method='mock') <NEW_LINE> self.user1 = BlueBottleUserFactory.create() <NEW_LINE> self.user1_token = "JWT {0}".format(self.user1.get_jwt_token()) <NEW_LINE> <DEDENT> def api_status(self, status): <NEW_LINE> <INDENT> self.assertEqual(self.order_payment.status, 'created') <NEW_LINE> self.assertEqual(OrderPayment.objects.count(), 1) <NEW_LINE> data = {'order_payment_id': self.order_payment.id, 'status': status} <NEW_LINE> response = self.client.post(reverse('payment-service-provider-status-update'), data) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> order_payment = OrderPayment.objects.get(id=self.order_payment.id) <NEW_LINE> self.assertEquals(order_payment.status, status) <NEW_LINE> self.assertEquals(OrderPayment.objects.count(), 1) <NEW_LINE> <DEDENT> def test_status_started_update(self): <NEW_LINE> <INDENT> self.api_status('started') <NEW_LINE> <DEDENT> def test_status_authorized_update(self): <NEW_LINE> <INDENT> self.api_status('authorized') <NEW_LINE> <DEDENT> def test_status_settled_update(self): <NEW_LINE> <INDENT> self.api_status('settled') <NEW_LINE> <DEDENT> def test_status_failed_update(self): <NEW_LINE> <INDENT> self.api_status('failed') <NEW_LINE> <DEDENT> def test_status_cancelled_update(self): <NEW_LINE> <INDENT> self.api_status('cancelled') <NEW_LINE> <DEDENT> def test_status_charged_back_update(self): <NEW_LINE> <INDENT> self.api_status('charged_back') <NEW_LINE> <DEDENT> def test_status_refunded_update(self): <NEW_LINE> <INDENT> self.api_status('refunded') <NEW_LINE> <DEDENT> def test_status_unknown_update(self): <NEW_LINE> <INDENT> self.api_status('unknown') <NEW_LINE> <DEDENT> def test_status_unknown_status(self): <NEW_LINE> <INDENT> self.assertEqual(self.order_payment.status, 'created') <NEW_LINE> data = {'order_payment_id': self.order_payment.id, 'status': 'very_obscure_unknown_status'} <NEW_LINE> response = self.client.post(reverse('payment-service-provider-status-update'), data) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> order_payment = OrderPayment.objects.get(id=self.order_payment.id) <NEW_LINE> self.assertEquals(order_payment.status, 'unknown') <NEW_LINE> <DEDENT> def test_update_status_nonexisting_order_payment(self): <NEW_LINE> <INDENT> self.assertEqual(self.order_payment.status, 'created') <NEW_LINE> data = {'order_payment_id': 5, 'status': 'very_obscure_unknown_status'} <NEW_LINE> response = self.client.post(reverse('payment-service-provider-status-update'), data) <NEW_LINE> self.assertEqual(response.status_code, 404) <NEW_LINE> order_payment = OrderPayment.objects.get(id=self.order_payment.id) <NEW_LINE> self.assertEquals(order_payment.status, 'created') | Tests for updating and order payment via mock PSP listener. The listener calls the service to fetch the
appropriate adapter and update the OrderPayment status. It sets the status of the order payment to | 62598fbcaad79263cf42e98c |
class UnbindDevicesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.GatewayProductId = None <NEW_LINE> self.GatewayDeviceName = None <NEW_LINE> self.ProductId = None <NEW_LINE> self.DeviceNames = None <NEW_LINE> self.Skey = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.GatewayProductId = params.get("GatewayProductId") <NEW_LINE> self.GatewayDeviceName = params.get("GatewayDeviceName") <NEW_LINE> self.ProductId = params.get("ProductId") <NEW_LINE> self.DeviceNames = params.get("DeviceNames") <NEW_LINE> self.Skey = params.get("Skey") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | UnbindDevices请求参数结构体
| 62598fbc7d43ff24874274e0 |
class BooleanField(BaseField): <NEW_LINE> <INDENT> def process(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.value = bool(value) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.error = "Not a valid bool value" <NEW_LINE> return False <NEW_LINE> <DEDENT> return True | You should process and validate bool value with this field. | 62598fbc956e5f7376df575a |
class InExpression(FieldExpression): <NEW_LINE> <INDENT> def __init__(self, field: Field, right: Iterable): <NEW_LINE> <INDENT> super().__init__(field) <NEW_LINE> self.right = right <NEW_LINE> <DEDENT> def get_operator_expression(self): <NEW_LINE> <INDENT> return {'$in': list(self.right)} | Matches any of values specified in an array | 62598fbc4f6381625f19959f |
class FileType(object): <NEW_LINE> <INDENT> def __init__(self, extension, change_name, force_thumb, thumbnail): <NEW_LINE> <INDENT> self.extension = extension <NEW_LINE> self.change_name = change_name <NEW_LINE> self.force_thumb = force_thumb <NEW_LINE> self.thumbnail = thumbnail | File type information. This class is pretty mundane.
'thumbnail' here is used if force_thumb is enabled or if the image thumbnailer failed. | 62598fbc0fa83653e46f509d |
class LowLightEnhance(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Type = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Type = params.get("Type") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | 低光照增强参数
| 62598fbc4527f215b58ea08d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.