code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Payment(models.Model): <NEW_LINE> <INDENT> from_user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='payments_done') <NEW_LINE> to_user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='payments_recived') <NEW_LINE> group = models.ForeignKey(TelegramGroup, on_delete=models.CASCADE, related_name='payments') <NEW_LINE> amount = models.DecimalField(decimal_places=2, max_digits=256) <NEW_LINE> date = models.DateField() <NEW_LINE> created_date = models.DateTimeField(auto_now=True)
Payment from a user to another user in the same group.
62598fdd50812a4eaa620ee2
class AISEstimator(BaseEstimator): <NEW_LINE> <INDENT> def __init__(self, measure: BaseMeasure) -> None: <NEW_LINE> <INDENT> super().__init__(measure) <NEW_LINE> self._risk_numerator = np.zeros(measure.n_dim_risk, dtype=float) <NEW_LINE> <DEDENT> def update(self, idx: Union[int, ndarray, Iterable], y: Union[int, float, ndarray, Iterable], weight: Union[float, ndarray, Iterable] = 1.0, x: Union[int, float, ndarray, None] = None, proposal: Optional[BaseProposal] = None) -> None: <NEW_LINE> <INDENT> super().update(idx, y, weight, x, proposal) <NEW_LINE> idx, y, weight = np.atleast_1d(idx, y, weight) <NEW_LINE> x = np.atleast_1d(x) if x is not None else x <NEW_LINE> loss = self.measure.loss(idx, y, x) <NEW_LINE> if isinstance(loss, spmatrix): <NEW_LINE> <INDENT> self._risk_numerator += loss.multiply(weight[:, np.newaxis]).sum(axis=0).A1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._risk_numerator += np.add.reduce(loss * weight[:, np.newaxis], axis=0) <NEW_LINE> <DEDENT> self.n_samples += y.shape[0] <NEW_LINE> <DEDENT> def get(self) -> Union[ndarray, float]: <NEW_LINE> <INDENT> super().get() <NEW_LINE> measure = self.measure.g(self._risk_numerator / self.n_samples) <NEW_LINE> try: <NEW_LINE> <INDENT> return measure.item() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return measure <NEW_LINE> <DEDENT> <DEDENT> def reset(self) -> None: <NEW_LINE> <INDENT> super().reset() <NEW_LINE> self._risk_numerator = np.zeros(self.measure.n_dim_risk, dtype=float)
Adaptive Importance Sampling (AIS) Estimator This estimator is suitable for adaptive, biased proposals. It corrects for the bias using simple importance re-weighting. After :math:`J` samples, the estimate for the target measure :math:`G` is given by: .. math:: G^{\mathrm{AIS}} = g(\hat{R}^{\mathrm{AIS}}) \mathrm{where} \quad \hat{R}^{\mathrm{AIS}} = \frac{1}{J} \sum_{j = 1}^{J} w_j \ell(x_j, y_j; f) and :math:`w_j` are the importance weights. Parameters ---------- measure : an instance of activeeval.measures.BaseMeasure A target generalized measure to estimate.
62598fddd8ef3951e32c815e
class AddMemberMessageRTQInputSet(InputSet): <NEW_LINE> <INDENT> def set_Body(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('Body', value) <NEW_LINE> <DEDENT> def set_DisplayToPublic(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('DisplayToPublic', value) <NEW_LINE> <DEDENT> def set_EmailCopyToSender(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('EmailCopyToSender', value) <NEW_LINE> <DEDENT> def set_ItemID(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('ItemID', value) <NEW_LINE> <DEDENT> def set_ParentMessageID(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('ParentMessageID', value) <NEW_LINE> <DEDENT> def set_RecipientID(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('RecipientID', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('ResponseFormat', value) <NEW_LINE> <DEDENT> def set_SandboxMode(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('SandboxMode', value) <NEW_LINE> <DEDENT> def set_SiteID(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('SiteID', value) <NEW_LINE> <DEDENT> def set_UserToken(self, value): <NEW_LINE> <INDENT> super(AddMemberMessageRTQInputSet, self)._set_input('UserToken', value)
An InputSet with methods appropriate for specifying the inputs to the AddMemberMessageRTQ Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598fde3617ad0b5ee06752
class TestCRC16XModem(unittest.TestCase): <NEW_LINE> <INDENT> def doBasics(self, module): <NEW_LINE> <INDENT> self.assertEqual(module.crc16xmodem('123456789'), 0x31c3) <NEW_LINE> self.assertNotEqual(module.crc16xmodem('123456'), 0x31c3) <NEW_LINE> crc = module.crc16xmodem('12345') <NEW_LINE> crc = module.crc16xmodem('6789', crc) <NEW_LINE> self.assertEqual(crc, 0x31C3) <NEW_LINE> self.assertEqual(module.crc16xmodem('AAAAAAAAAAAAAAAAAAAAAA'), 0x92cd) <NEW_LINE> self.assertEqual(module.crc16xmodem('A' * 4096), 0xd694) <NEW_LINE> self.assertEqual(module.crc16xmodem('A' * 39999), 0xcfbb) <NEW_LINE> self.assertEqual(module.crc16xmodem(''), 0) <NEW_LINE> <DEDENT> def test_basics(self): <NEW_LINE> <INDENT> self.doBasics(crc16) <NEW_LINE> <DEDENT> def test_basics_c(self): <NEW_LINE> <INDENT> self.doBasics(_crc16) <NEW_LINE> <DEDENT> def test_basics_pure(self): <NEW_LINE> <INDENT> self.doBasics(crc16pure) <NEW_LINE> <DEDENT> def test_big_chunks(self): <NEW_LINE> <INDENT> self.assertEqual(_crc16.crc16xmodem('A' * 16 * 1024 * 1024), 0xbf75)
Test CRC16 CRC-CCITT (XModem) variant.
62598fdeab23a570cc2d5074
class Topotagcreaterequest(object): <NEW_LINE> <INDENT> openapi_types = { 'name': 'str', 'description': 'str' } <NEW_LINE> attribute_map = { 'name': 'name', 'description': 'description' } <NEW_LINE> def __init__(self, name=None, description=None): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> self._description = None <NEW_LINE> self.discriminator = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if description is not None: <NEW_LINE> <INDENT> self.description = description <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._description <NEW_LINE> <DEDENT> @description.setter <NEW_LINE> def description(self, description): <NEW_LINE> <INDENT> self._description = description <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Topotagcreaterequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fdead47b63b2c5a7e5c
class YouTubeVideoDemographicsAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = [ "youtube_video", "age_range", "gender", "views_percentage", "last_updated", ] <NEW_LINE> list_display_links = ["youtube_video"] <NEW_LINE> list_filter = ["youtube_video__youtube", "age_range", "gender"] <NEW_LINE> search_fields = ["youtube_video__title", "youtube_video__external_id"]
List for choosing existing YouTube video demographics data to edit.
62598fdead47b63b2c5a7e5e
class CMAPSSBinaryClassifier(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(CMAPSSBinaryClassifier, self).__init__() <NEW_LINE> self.fc1 = nn.Linear(26, 16) <NEW_LINE> self.fc2 = nn.Linear(16, 4) <NEW_LINE> self.fc3 = nn.Linear(4, 1) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = torch.relu(self.fc1(x)) <NEW_LINE> x = torch.relu(self.fc2(x)) <NEW_LINE> output = self.fc3(x) <NEW_LINE> return output
This class performs binary classification using a simple fully-connected neural network (i.e. healthy/faulty engines) by assuming first and last x samples belonging to each engine correspond to healthy and faulty states respectively.
62598fdec4546d3d9def758c
class TestMlpContainer(unittest.TestCase): <NEW_LINE> <INDENT> def test_init_where_iterable_is_default(self): <NEW_LINE> <INDENT> container = MlpContainer() <NEW_LINE> self.assertEqual(container, []) <NEW_LINE> <DEDENT> def test_init_where_iterable_is_sequence(self): <NEW_LINE> <INDENT> container = MlpContainer([2, 5, 67]) <NEW_LINE> self.assertEqual(container, [2, 5, 67])
Tests for Container class, currently a list subclass
62598fde099cdd3c636756e6
class TestPlansApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = esp_sdk.apis.plans_api.PlansApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_list(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_show(self): <NEW_LINE> <INDENT> pass
PlansApi unit test stubs
62598fdead47b63b2c5a7e62
class MinterSendCoinTx(MinterTx): <NEW_LINE> <INDENT> TYPE = 1 <NEW_LINE> COMMISSION = 10 <NEW_LINE> def __init__(self, coin, to, value, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.coin = coin.upper() <NEW_LINE> self.to = to <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def _structure_from_instance(self): <NEW_LINE> <INDENT> struct = super()._structure_from_instance() <NEW_LINE> struct.update({ 'type': self.TYPE, 'data': { 'coin': MinterHelper.encode_coin_name(self.coin), 'to': bytes.fromhex(MinterHelper.prefix_remove(self.to)), 'value': MinterHelper.to_pip(self.value) } }) <NEW_LINE> return struct <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _structure_to_kwargs(cls, structure): <NEW_LINE> <INDENT> kwargs = super()._structure_to_kwargs(structure) <NEW_LINE> kwargs['data'].update({ 'coin': MinterHelper.decode_coin_name(kwargs['data']['coin']), 'to': MinterHelper.prefix_add( kwargs['data']['to'].hex(), PREFIX_ADDR ), 'value': MinterHelper.to_bip( int.from_bytes(kwargs['data']['value'], 'big') ) }) <NEW_LINE> kwargs.update(kwargs['data']) <NEW_LINE> return kwargs <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _data_from_raw(cls, raw_data): <NEW_LINE> <INDENT> return { 'coin': raw_data[0], 'to': raw_data[1], 'value': raw_data[2] }
Send coin transaction
62598fdec4546d3d9def7590
class System(): <NEW_LINE> <INDENT> def __init__(self, name=None, source=None, supercell_size=None, structdir=None, folded = True, real_or_complex='Real', mindistance=16): <NEW_LINE> <INDENT> assert isinstance(name, str), error("System settings are wrong") <NEW_LINE> assert isinstance(source, str), error("System settings are wrong") <NEW_LINE> self.structdir = os.path.abspath(structdir + "/" + name + "/" + source + "/") <NEW_LINE> self.scell_size=supercell_size <NEW_LINE> self.inputfile=None <NEW_LINE> self.real_or_complex = real_or_complex <NEW_LINE> self.mindistance = mindistance <NEW_LINE> vaspInput=False <NEW_LINE> for file in os.listdir(self.structdir): <NEW_LINE> <INDENT> if fnmatch.fnmatch(file, '*.vasp'): <NEW_LINE> <INDENT> self.inputfile = os.path.abspath(self.structdir + "/" + file) <NEW_LINE> vaspInput = True <NEW_LINE> <DEDENT> <DEDENT> if self.inputfile is not None: <NEW_LINE> <INDENT> if vaspInput: <NEW_LINE> <INDENT> unit_cell = Vasp.read_poscar(self.inputfile) <NEW_LINE> unit_cell = unit_cell.structure <NEW_LINE> assert isinstance(unit_cell, structure.Structure) <NEW_LINE> self.scell = unit_cell.get_supercell(supercell_size) <NEW_LINE> if real_or_complex == 'Real': <NEW_LINE> <INDENT> unit_cell.kgrid=unit_cell.gen_real_kpts_lattice(self.scell) <NEW_LINE> <DEDENT> if real_or_complex == 'Complex': <NEW_LINE> <INDENT> unit_cell.kgrid=unit_cell.gen_complex_kpts_lattice(self.scell,mindistance) <NEW_LINE> <DEDENT> self.unitcell=unit_cell <NEW_LINE> self.structure = [] <NEW_LINE> if not folded: <NEW_LINE> <INDENT> self.structure=unit_cell.make_scell(self.scell) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.structure=copy.deepcopy(unit_cell) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for file in glob.glob(self.inputfile): <NEW_LINE> <INDENT> self.inputfile = file <NEW_LINE> <DEDENT> self.runpspdir = os.path.abspath( settings.rootdir + '/runs/' + name + '/' + settings.pspname + '/' + "psps") <NEW_LINE> if not os.path.exists(self.runpspdir): <NEW_LINE> <INDENT> os.makedirs(self.runpspdir) <NEW_LINE> <DEDENT> self.rundir = settings.rootdir + '/runs/' + name + '/' + settings.pspname + '/' + source + '/radius.' + str(supercell_size) <NEW_LINE> if not os.path.exists(self.rundir): <NEW_LINE> <INDENT> os.makedirs(self.rundir)
Input file locations
62598fde4c3428357761a8c7
class TestHt(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.ht = ht.Ht() <NEW_LINE> <DEDENT> def testCount(self): <NEW_LINE> <INDENT> self.assertEquals(0, len(self.ht)) <NEW_LINE> for i in range(99, -1, -1): <NEW_LINE> <INDENT> self.ht.insert(i) <NEW_LINE> <DEDENT> self.assertEquals(100, len(self.ht)) <NEW_LINE> <DEDENT> def testClear(self): <NEW_LINE> <INDENT> self.assertEquals(0, len(self.ht)) <NEW_LINE> for i in range(99, -1, -1): <NEW_LINE> <INDENT> self.ht.insert(i) <NEW_LINE> <DEDENT> self.ht.clear() <NEW_LINE> self.assertEquals(0, len(self.ht)) <NEW_LINE> <DEDENT> def testKeyInsertion(self): <NEW_LINE> <INDENT> self.ht.insert(42, "Forty-two") <NEW_LINE> self.assertTrue(42 in self.ht) <NEW_LINE> <DEDENT> def testKeyGetter(self): <NEW_LINE> <INDENT> self.ht.insert(42, "Forty-two") <NEW_LINE> self.assertEquals(self.ht.get(42, "What?!?"), "Forty-two") <NEW_LINE> <DEDENT> def testKeyValueInsertion(self): <NEW_LINE> <INDENT> self.ht.insert(33, "Thirty-three") <NEW_LINE> self.assertTrue(33 in self.ht) <NEW_LINE> self.assertEquals(self.ht[33], "Thirty-three") <NEW_LINE> <DEDENT> def testForwardIterators(self): <NEW_LINE> <INDENT> for i in range(0, 100): <NEW_LINE> <INDENT> self.ht.insert(i, str(i)) <NEW_LINE> <DEDENT> items = iter(self.ht) <NEW_LINE> count = 0 <NEW_LINE> for (i, j) in items: <NEW_LINE> <INDENT> self.assertEquals(str(i), j) <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> self.assertEquals(count, 100)
A test class for the ht module.
62598fdefbf16365ca7946dc
class State(BaseModel): <NEW_LINE> <INDENT> name = ""
A State in the world.
62598fdead47b63b2c5a7e69
class JouvenceDocument: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.title_values = {} <NEW_LINE> self.scenes = [] <NEW_LINE> <DEDENT> def addScene(self, header=None): <NEW_LINE> <INDENT> s = JouvenceScene() <NEW_LINE> if header: <NEW_LINE> <INDENT> s.header = header <NEW_LINE> <DEDENT> self.scenes.append(s) <NEW_LINE> return s <NEW_LINE> <DEDENT> def lastScene(self, auto_create=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.scenes[-1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> if auto_create: <NEW_LINE> <INDENT> s = self.addScene() <NEW_LINE> return s <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def lastParagraph(self): <NEW_LINE> <INDENT> s = self.lastScene(False) <NEW_LINE> if s: <NEW_LINE> <INDENT> return s.lastParagraph() <NEW_LINE> <DEDENT> return None
Represents a Fountain screenplay in a structured way. A screenplay contains: * A title page (optional) with a key/value dictionary of settings. * A list of scenes. * Each scene contains a list of paragraphs of various types.
62598fde26238365f5fad17f
class Destinations(models.Model): <NEW_LINE> <INDENT> destination = models.CharField(max_length=200, default='N/A') <NEW_LINE> url = models.TextField(max_length=1000, default='N/A') <NEW_LINE> site_name = models.CharField(max_length=200, default='N/A') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.site_name
Model representing destinations page.
62598fde4c3428357761a8c9
class DayOfWeekCondition(BaseCronCondition): <NEW_LINE> <INDENT> WEEKDAY_CHOICES = ( (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Sunday'), (7, 'Saturday'), ) <NEW_LINE> weekday = models.PositiveSmallIntegerField( verbose_name='day of the week', choices=WEEKDAY_CHOICES, help_text="Action will occur every week on that day.", ) <NEW_LINE> class Meta(BaseCronCondition.Meta): <NEW_LINE> <INDENT> verbose_name = 'day of week condition' <NEW_LINE> verbose_name_plural = 'day of week conditions' <NEW_LINE> <DEDENT> def is_met(self, *args, **kwargs): <NEW_LINE> <INDENT> today = timezone.now().date() <NEW_LINE> if self.weekday == today.isoweekday() and (not self.last_executed or self.last_executed.date() != today): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Day of week condition (day: {0})'.format(self.get_weekday_display())
Class representation of a day of week condition It allows for date based conditions like 'every Monday'.
62598fdec4546d3d9def7592
class Anewnote(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> desired_caps = { 'platformName' : 'Android', 'platformVersion' : '4.4.2', 'deviceName' : '127.0.0.1:22515', 'appPackage' : 'com.youdao.note', 'appActivity' : '.activity2.SplashActivity', 'unicodeKeyboard' : 'True', 'resetKeyboard' : 'True' } <NEW_LINE> self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps) <NEW_LINE> <DEDENT> def test_newnote(self): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> time.sleep(3) <NEW_LINE> wb = xlrd.open_workbook("E:\\python_workspace\\appium-framework-week4\\data\\data-week4.xls") <NEW_LINE> sh = wb.sheet_by_name("note") <NEW_LINE> r_num = sh.nrows <NEW_LINE> for i in range(1, r_num): <NEW_LINE> <INDENT> title = sh.cell_value(i, 1) <NEW_LINE> content = sh.cell_value(i, 2) <NEW_LINE> expect = sh.cell_value(i, 3) <NEW_LINE> driver.find_element(By.ID, 'com.youdao.note:id/add_note_floater_open').click() <NEW_LINE> driver.find_element(By.NAME, '新建笔记').click() <NEW_LINE> driver.find_element(By.ID, 'com.youdao.note:id/note_title').send_keys(title) <NEW_LINE> driver.find_element(By.XPATH, '//android.widget.LinearLayout[@resource-id=\"com.youdao.note:id/note_content\"]/android.widget.EditText[1]').send_keys(content) <NEW_LINE> driver.find_element(By.ID, 'com.youdao.note:id/actionbar_complete_text').click() <NEW_LINE> if expect == 'ok': <NEW_LINE> <INDENT> if driver.find_element(By.NAME, title) and driver.find_element(By.NAME, content): <NEW_LINE> <INDENT> print('success') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('fail') <NEW_LINE> <DEDENT> <DEDENT> elif title == '': <NEW_LINE> <INDENT> res1 = driver.find_element(By.ID, 'com.youdao.note:id/title').text <NEW_LINE> res2 = driver.find_element(By.ID, 'com.youdao.note:id/summary').text <NEW_LINE> if res1 == res2: <NEW_LINE> <INDENT> print('success') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('fail') <NEW_LINE> <DEDENT> <DEDENT> elif expect == 'tit': <NEW_LINE> <INDENT> if driver.find_element(By.NAME, title): <NEW_LINE> <INDENT> print('success') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('fail') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> exitApp(self)
新建云笔记
62598fde50812a4eaa620eef
class Wheel(BodyPart): <NEW_LINE> <INDENT> def __init__(self, config, robot): <NEW_LINE> <INDENT> dims = get_simulation_settings()['body_part_sizes']['wheel'] <NEW_LINE> super().__init__(config, robot, Dimensions(dims['width'], dims['height']), 'motor', driver_name='lego-ev3-l-motor') <NEW_LINE> <DEDENT> def setup_visuals(self, scale): <NEW_LINE> <INDENT> vis_conf = get_simulation_settings() <NEW_LINE> self.init_sprite(vis_conf['image_paths']['wheel'], scale) <NEW_LINE> <DEDENT> def is_falling(self) -> bool: <NEW_LINE> <INDENT> for obstacle in self.sensible_obstacles: <NEW_LINE> <INDENT> if obstacle.collided_with(self.sprite.center_x, self.sprite.center_y): <NEW_LINE> <INDENT> if isinstance(obstacle, Board): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return self.get_default_value() <NEW_LINE> <DEDENT> def get_default_value(self): <NEW_LINE> <INDENT> return True
Class representing a Wheel of the simulated robot.
62598fdead47b63b2c5a7e6d
class Environment2: <NEW_LINE> <INDENT> def outcome(self, action): <NEW_LINE> <INDENT> if action == 0: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
In Environment 2, action 0 yields outcome 1, action 1 yields outcome 0
62598fde656771135c489c92
class RolesApi(object): <NEW_LINE> <INDENT> def __init__(self, api_client=None): <NEW_LINE> <INDENT> config = Configuration() <NEW_LINE> if api_client: <NEW_LINE> <INDENT> self.api_client = api_client <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not config.api_client: <NEW_LINE> <INDENT> config.api_client = ApiClient() <NEW_LINE> <DEDENT> self.api_client = config.api_client <NEW_LINE> <DEDENT> <DEDENT> def list_roles(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.list_roles_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.list_roles_with_http_info(**kwargs) <NEW_LINE> return data <NEW_LINE> <DEDENT> <DEDENT> def list_roles_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = [] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method list_roles" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> query_params = [] <NEW_LINE> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client. select_header_accept(['application/json']) <NEW_LINE> header_params['Content-Type'] = self.api_client. select_header_content_type(['application/json']) <NEW_LINE> auth_settings = ['AuthTokenHeader'] <NEW_LINE> return self.api_client.call_api('/1.11/roles', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='RoleResponse', auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen
62598fde26238365f5fad183
class Enviroment: <NEW_LINE> <INDENT> stack = Stack() <NEW_LINE> words = { '!': forth_dictionary.ForthWord(primitives.store), '@': forth_dictionary.ForthWord(primitives.fetch), } <NEW_LINE> storage = {} <NEW_LINE> inbuffer = [] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fetch_word(self): <NEW_LINE> <INDENT> if not self.inbuffer: <NEW_LINE> <INDENT> self.inbuffer = input().split() <NEW_LINE> <DEDENT> return self.inbuffer.pop(0) <NEW_LINE> <DEDENT> def execute_word(self): <NEW_LINE> <INDENT> word = self.fetch_word() <NEW_LINE> if word in self.words: <NEW_LINE> <INDENT> self.words[word](self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.stack.push(float(word)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise WordError("Unknown word {}".format(word))
Interpretation enviroment for monkeyforth. Holds all data about the enviroment.
62598fde50812a4eaa620ef1
class Repos(APIView): <NEW_LINE> <INDENT> def get(self, request, format=None): <NEW_LINE> <INDENT> username = request.user.get_username() <NEW_LINE> repo_base = username <NEW_LINE> serializer = RepoSerializer(username, repo_base, request) <NEW_LINE> return Response(serializer.user_accessible_repos())
Repos visible to the logged in user.
62598fdeab23a570cc2d507e
class ToggleColumn(tables.CheckBoxColumn): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> default = kwargs.pop('default', '') <NEW_LINE> visible = kwargs.pop('visible', False) <NEW_LINE> super().__init__(*args, default=default, visible=visible, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def header(self): <NEW_LINE> <INDENT> return mark_safe('<input type="checkbox" class="toggle" title="Toggle all" />')
Extend CheckBoxColumn to add a "toggle all" checkbox in the column header.
62598fde50812a4eaa620ef2
class ExcBase(Model): <NEW_LINE> <INDENT> def __init__(self, system, config): <NEW_LINE> <INDENT> Model.__init__(self, system, config) <NEW_LINE> self.group = 'Exciter' <NEW_LINE> self.flags.tds = True <NEW_LINE> self.VoltComp = BackRef() <NEW_LINE> self.ug = ExtParam(src='u', model='SynGen', indexer=self.syn, tex_name='u_g', info='Generator online status', unit='bool', export=False, ) <NEW_LINE> self.ue = ConstService(v_str='u * ug', info="effective online status", tex_name='u_e', ) <NEW_LINE> self.Sn = ExtParam(src='Sn', model='SynGen', indexer=self.syn, tex_name='S_m', info='Rated power from generator', unit='MVA', export=False, ) <NEW_LINE> self.Vn = ExtParam(src='Vn', model='SynGen', indexer=self.syn, tex_name='V_m', info='Rated voltage from generator', unit='kV', export=False, ) <NEW_LINE> self.vf0 = ExtService(src='vf', model='SynGen', indexer=self.syn, tex_name='v_{f0}', info='Steady state excitation voltage') <NEW_LINE> self.bus = ExtParam(src='bus', model='SynGen', indexer=self.syn, tex_name='bus', info='Bus idx of the generators', export=False, vtype=str, ) <NEW_LINE> self.omega = ExtState(src='omega', model='SynGen', indexer=self.syn, tex_name=r'\omega', info='Generator speed', ) <NEW_LINE> self.vf = ExtAlgeb(src='vf', model='SynGen', indexer=self.syn, tex_name=r'v_f', e_str='ue * (vout - vf0)', info='Excitation field voltage to generator', ename='vf', tex_ename='v_f', ) <NEW_LINE> self.XadIfd = ExtAlgeb(src='XadIfd', model='SynGen', indexer=self.syn, tex_name=r'X_{ad}I_{fd}', info='Armature excitation current', ) <NEW_LINE> self.a = ExtAlgeb(model='Bus', src='a', indexer=self.bus, tex_name=r'\theta', info='Bus voltage phase angle', ) <NEW_LINE> self.vbus = ExtAlgeb(model='Bus', src='v', indexer=self.bus, tex_name='V', info='Bus voltage magnitude', ) <NEW_LINE> self.v = Algeb(info='Input to exciter (bus v or Eterm)', tex_name='E_{term}', v_str='vbus', e_str='vbus - v', v_str_add=True, ) <NEW_LINE> self.vout = Algeb(info='Exciter final output voltage', tex_name='v_{out}', v_str='ue * vf0', diag_eps=True, )
Base model for exciters. Notes ----- As of v1.4.5, the input voltage Eterm (variable ``self.v``) is converted to type ``Algeb``. Since variables are evaluated after services, ``ConstService`` of exciters can no longer depend on ``v``. TODO: programmatically disallow ``ConstService`` use uninitialized variables.
62598fded8ef3951e32c816d
class SqlAlchemyMiddleware(object): <NEW_LINE> <INDENT> def process_response(self, request, response): <NEW_LINE> <INDENT> Session.remove() <NEW_LINE> return response <NEW_LINE> <DEDENT> def process_exception(self, request, exception): <NEW_LINE> <INDENT> Session.remove()
dispose sqlalchemy Session at the end of each request
62598fde26238365f5fad187
class quadNG(object): <NEW_LINE> <INDENT> def __init__(self, xInp, yInp): <NEW_LINE> <INDENT> x = list(map(float, xInp)) <NEW_LINE> y = list(map(float, yInp)) <NEW_LINE> c = list(zip(x,y)) <NEW_LINE> c.sort() <NEW_LINE> x = [] <NEW_LINE> y = [] <NEW_LINE> aLast = None <NEW_LINE> for aa,bb in c: <NEW_LINE> <INDENT> if aa != aLast: <NEW_LINE> <INDENT> x.append(aa) <NEW_LINE> y.append(bb) <NEW_LINE> <DEDENT> aLast = aa <NEW_LINE> <DEDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.a = [] <NEW_LINE> self.b = [] <NEW_LINE> self.c = [] <NEW_LINE> dif1 = [] <NEW_LINE> for i in range( len(x) - 1 ): <NEW_LINE> <INDENT> dif1.append( old_div((y[i+1]-y[i]), (x[i+1]-x[i])) ) <NEW_LINE> <DEDENT> dif2 = [] <NEW_LINE> for i in range( len(x) - 2 ): <NEW_LINE> <INDENT> dif2.append( old_div((dif1[i+1]-dif1[i]), (x[i+2]-x[i])) ) <NEW_LINE> <DEDENT> for i in range( len(x)-2): <NEW_LINE> <INDENT> self.a.append( y[i] ) <NEW_LINE> self.b.append( dif1[i] ) <NEW_LINE> self.c.append( dif2[i] ) <NEW_LINE> <DEDENT> self.iMax = len(self.a) - 1 <NEW_LINE> <DEDENT> def __call__(self, xval=0.0): <NEW_LINE> <INDENT> return self.getValue( xval ) <NEW_LINE> <DEDENT> def getIndex(self, xval=0.0): <NEW_LINE> <INDENT> i = bisect.bisect_left(self.x, xval) - 1 <NEW_LINE> if i<0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif i>self.iMax: <NEW_LINE> <INDENT> return self.iMax <NEW_LINE> <DEDENT> return i <NEW_LINE> <DEDENT> def getValue(self, xval=0.0): <NEW_LINE> <INDENT> xval = float( xval ) <NEW_LINE> if xval > self.x[-1]: <NEW_LINE> <INDENT> return self.y[-1] <NEW_LINE> <DEDENT> if xval < self.x[0]: <NEW_LINE> <INDENT> return self.y[0] <NEW_LINE> <DEDENT> i = self.getIndex(xval) <NEW_LINE> dx = xval - self.x[i] <NEW_LINE> dx2 = xval-self.x[i+1] <NEW_LINE> return self.a[i] + dx*( self.b[i] + dx2*self.c[i] ) <NEW_LINE> <DEDENT> def deriv(self, xval=0.0): <NEW_LINE> <INDENT> xval = float( xval ) <NEW_LINE> i = self.getIndex(xval) <NEW_LINE> dx = xval - self.x[i] <NEW_LINE> dx2 = xval-self.x[i+1] <NEW_LINE> return self.b[i] + self.c[i]*(2.*xval - self.x[i] - self.x[i+1]) <NEW_LINE> <DEDENT> def deriv2nd(self, xval=0.0): <NEW_LINE> <INDENT> xval = float( xval ) <NEW_LINE> i = self.getIndex(xval) <NEW_LINE> return 2.0*self.c[i]
quadratic Newton-Gregory Interpolation assume a formula of: f = a + b(x-x0) + c(x-x0)(x-x1)
62598fdf50812a4eaa620ef4
class DUMPP(TypeKeyword): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("DUMPP", (float,), comment="Dumping period, in sec") <NEW_LINE> <DEDENT> def set(self, dumpp): <NEW_LINE> <INDENT> super().set(dumpp)
Dump interval. When the DUMPTO option is activated, simulation results are written in the output files every DUMPP seconds. This option is useful to check the progress of long simulations. It also allows the program to be run with a long execution time and to be stopped when the required statistical uncertainty has been reached.
62598fdf091ae35668705242
class RGdata(RPackage): <NEW_LINE> <INDENT> homepage = "https://cloud.r-project.org/package=gdata" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/gdata_2.18.0.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/gdata" <NEW_LINE> version('2.18.0', sha256='4b287f59f5bbf5fcbf18db16477852faac4a605b10c5284c46b93fa6e9918d7f') <NEW_LINE> version('2.17.0', sha256='8097ec0e4868f6bf746f821cff7842f696e874bb3a84f1b2aa977ecd961c3e4e') <NEW_LINE> depends_on('r@2.3.0:', type=('build', 'run')) <NEW_LINE> depends_on('r-gtools', type=('build', 'run')) <NEW_LINE> depends_on('perl@5.10.0:')
Various R programming tools for data manipulation, including: - medical unit conversions ('ConvertMedUnits', 'MedUnits'), - combining objects ('bindData', 'cbindX', 'combine', 'interleave'), - character vector operations ('centerText', 'startsWith', 'trim'), - factor manipulation ('levels', 'reorder.factor', 'mapLevels'), - obtaining information about R objects ('object.size', 'elem', 'env', 'humanReadable', 'is.what', 'll', 'keep', 'ls.funs', 'Args','nPairs', 'nobs'), - manipulating MS-Excel formatted files ('read.xls', 'installXLSXsupport', 'sheetCount', 'xlsFormats'), - generating fixed-width format files ('write.fwf'), - extricating components of date & time objects ('getYear', 'getMonth', 'getDay', 'getHour', 'getMin', 'getSec'), - operations on columns of data frames ('matchcols', 'rename.vars'), - matrix operations ('unmatrix', 'upperTriangle', 'lowerTriangle'), - operations on vectors ('case', 'unknownToNA', 'duplicated2', 'trimSum'), - operations on data frames ('frameApply', 'wideByFactor'), - value of last evaluated expression ('ans'), and - wrapper for 'sample' that ensures consistent behavior for both scalar and vector arguments ('resample').
62598fdfab23a570cc2d5081
class EveStatus: <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> self.config = bot.config <NEW_LINE> self.logger = bot.logger <NEW_LINE> <DEDENT> @commands.command(name='status', aliases=["tq", "eve"]) <NEW_LINE> @checks.spam_check() <NEW_LINE> @checks.is_whitelist() <NEW_LINE> async def _status(self, ctx): <NEW_LINE> <INDENT> global status, player_count <NEW_LINE> self.logger.info('EveStatus - {} requested server info.'.format(str(ctx.message.author))) <NEW_LINE> data = await ctx.bot.esi_data.server_info() <NEW_LINE> try: <NEW_LINE> <INDENT> if data.get('start_time'): <NEW_LINE> <INDENT> status = 'Online' <NEW_LINE> player_count = data.get('players') <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> status = 'Offline' <NEW_LINE> player_count = 'N/A' <NEW_LINE> <DEDENT> embed = make_embed(guild=ctx.guild) <NEW_LINE> embed.set_footer(icon_url=ctx.bot.user.avatar_url, text="Provided Via Firetail Bot") <NEW_LINE> embed.set_thumbnail(url="https://image.eveonline.com/Alliance/434243723_64.png") <NEW_LINE> embed.add_field(name="Status", value="Server State:\nPlayer Count:", inline=True) <NEW_LINE> embed.add_field(name="-", value="{}\n{}".format(status, player_count), inline=True) <NEW_LINE> dest = ctx.author if ctx.bot.config.dm_only else ctx <NEW_LINE> await dest.send(embed=embed) <NEW_LINE> if ctx.bot.config.delete_commands: <NEW_LINE> <INDENT> await ctx.message.delete()
This extension handles the status command.
62598fdf099cdd3c636756f1
class TransitionBlock(object): <NEW_LINE> <INDENT> def __init__(self, components, start_time=None): <NEW_LINE> <INDENT> self.start_time = start_time <NEW_LINE> self.components = components <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> orig_repr = object.__repr__(self) <NEW_LINE> comp_info = ', '.join(['{0}: {1}'.format(c, t) for c, t in self.components.items()]) <NEW_LINE> if self.start_time is None or self.end_time is None: <NEW_LINE> <INDENT> return orig_repr.replace('object at', ' ({0}, unscheduled) at'.format(comp_info)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = '({0}, {1} to {2}) at'.format(comp_info, self.start_time, self.end_time) <NEW_LINE> return orig_repr.replace('object at', s) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def end_time(self): <NEW_LINE> <INDENT> return self.start_time + self.duration <NEW_LINE> <DEDENT> @property <NEW_LINE> def components(self): <NEW_LINE> <INDENT> return self._components <NEW_LINE> <DEDENT> @components.setter <NEW_LINE> def components(self, val): <NEW_LINE> <INDENT> duration = 0*u.second <NEW_LINE> for t in val.values(): <NEW_LINE> <INDENT> duration += t <NEW_LINE> <DEDENT> self._components = val <NEW_LINE> self.duration = duration
An object that represents "dead time" between observations, while the telescope is slewing, instrument is reconfiguring, etc. Parameters ---------- components : dict A dictionary mapping the reason for an observation's dead time to `Quantity`s with time units start_time : Quantity with time units
62598fdfd8ef3951e32c816f
class Stack: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._top = None <NEW_LINE> self._bottom = None <NEW_LINE> self._size = 0 <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> iterator = self._top <NEW_LINE> while True: <NEW_LINE> <INDENT> if iterator is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> yield iterator.value <NEW_LINE> iterator = iterator.next <NEW_LINE> <DEDENT> <DEDENT> def empty(self): <NEW_LINE> <INDENT> return self._size == 0 <NEW_LINE> <DEDENT> def push(self, value): <NEW_LINE> <INDENT> new_node = _Node(value) <NEW_LINE> if self.empty(): <NEW_LINE> <INDENT> self._top = new_node <NEW_LINE> self._bottom = new_node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_node.next = self._top <NEW_LINE> self._top = new_node <NEW_LINE> <DEDENT> self._size += 1 <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> if self.empty(): <NEW_LINE> <INDENT> raise IndexError("Empty stack") <NEW_LINE> <DEDENT> pop_value = self._top.value <NEW_LINE> self._top = self._top.next <NEW_LINE> self._size -= 1 <NEW_LINE> return pop_value
Stack data structure.
62598fdf4c3428357761a8d5
class BatchNormalizedMLP(Sequence, Initializable, Feedforward): <NEW_LINE> <INDENT> @lazy(allocation=['dims']) <NEW_LINE> def __init__(self, activations, dims, bn_init=None, **kwargs): <NEW_LINE> <INDENT> if bn_init is None: <NEW_LINE> <INDENT> bn_init = IsotropicGaussian(0.1) <NEW_LINE> <DEDENT> self.bn_init = bn_init <NEW_LINE> self.activations = activations <NEW_LINE> self.batch_normnalizations = [BatchNormalization(name='bn_{}'.format(i), beta_init=bn_init, gamma_init=bn_init) for i in range(len(activations))] <NEW_LINE> self.linear_transformations = [Linear(name='linear_{}'.format(i)) for i in range(len(activations))] <NEW_LINE> application_methods = [] <NEW_LINE> for entity in interleave([self.linear_transformations, self.batch_normnalizations, activations]): <NEW_LINE> <INDENT> if entity is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if isinstance(entity, Brick): <NEW_LINE> <INDENT> application_methods.append(entity.apply) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> application_methods.append(entity) <NEW_LINE> <DEDENT> <DEDENT> if not dims: <NEW_LINE> <INDENT> dims = [None] * (len(activations) + 1) <NEW_LINE> <DEDENT> self.dims = dims <NEW_LINE> super(BatchNormalizedMLP, self).__init__(application_methods, **kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def input_dim(self): <NEW_LINE> <INDENT> return self.dims[0] <NEW_LINE> <DEDENT> @input_dim.setter <NEW_LINE> def input_dim(self, value): <NEW_LINE> <INDENT> self.dims[0] = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_dim(self): <NEW_LINE> <INDENT> return self.dims[-1] <NEW_LINE> <DEDENT> @output_dim.setter <NEW_LINE> def output_dim(self, value): <NEW_LINE> <INDENT> self.dims[-1] = value <NEW_LINE> <DEDENT> def _push_allocation_config(self): <NEW_LINE> <INDENT> if not len(self.dims) - 1 == len(self.linear_transformations): <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> for input_dim, output_dim, layer in equizip(self.dims[:-1], self.dims[1:], self.linear_transformations): <NEW_LINE> <INDENT> layer.input_dim = input_dim <NEW_LINE> layer.output_dim = output_dim <NEW_LINE> layer.use_bias = self.use_bias <NEW_LINE> <DEDENT> for output_dim, bn in equizip(self.dims[1:], self.batch_normnalizations): <NEW_LINE> <INDENT> bn.dim = output_dim
A simple multi-layer perceptron. Parameters ---------- activations : list of :class:`.Brick`, :class:`.BoundApplication`, or ``None`` A list of activations to apply after each linear transformation. Give ``None`` to not apply any activation. It is assumed that the application method to use is ``apply``. Required for :meth:`__init__`. dims : list of ints A list of input dimensions, as well as the output dimension of the last layer. Required for :meth:`~.Brick.allocate`. Notes ----- See :class:`Initializable` for initialization parameters. Note that the ``weights_init``, ``biases_init`` and ``use_bias`` configurations will overwrite those of the layers each time the :class:`MLP` is re-initialized. For more fine-grained control, push the configuration to the child layers manually before initialization.
62598fdf3617ad0b5ee06770
class ParameterizedVariableScope(object): <NEW_LINE> <INDENT> def __init__(self, template, name, parameter=None, *args, **kwargs): <NEW_LINE> <INDENT> assert template.variables is not None <NEW_LINE> self._template = template <NEW_LINE> self._name = name <NEW_LINE> self._variable_scope = tf.variable_scope( name, custom_getter=self._parameterized_variable_getter, reuse=tf.AUTO_REUSE, *args, **kwargs ) <NEW_LINE> with self._variable_scope: <NEW_LINE> <INDENT> if parameter is not None: <NEW_LINE> <INDENT> self._parameter = parameter <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> flattened_variables = [] <NEW_LINE> for v in self._template.variables: <NEW_LINE> <INDENT> flattened_variables.append( tf.reshape(v.variable.initialized_value(), [-1]) ) <NEW_LINE> <DEDENT> self._parameter = tf.Variable( tf.concat(flattened_variables, axis=0), dtype=template.dtype ) <NEW_LINE> <DEDENT> self._parameterized_variables = None <NEW_LINE> <DEDENT> <DEDENT> def _parameterized_variable_getter(self, getter, name, *args, **kwargs): <NEW_LINE> <INDENT> descoped_name = name.split(self.name)[-1][1:] <NEW_LINE> if descoped_name in self.parameterized_variables: <NEW_LINE> <INDENT> return self.parameterized_variables[descoped_name] <NEW_LINE> <DEDENT> return getter(name, *args, **kwargs) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self._variable_scope.__enter__() <NEW_LINE> <DEDENT> def __exit__(self, etype, value, tb): <NEW_LINE> <INDENT> return self._variable_scope.__exit__(etype, value, tb) <NEW_LINE> <DEDENT> @property <NEW_LINE> def parameter(self): <NEW_LINE> <INDENT> return self._parameter <NEW_LINE> <DEDENT> @property <NEW_LINE> def parameterized_variables(self): <NEW_LINE> <INDENT> if self._parameterized_variables is None: <NEW_LINE> <INDENT> self._parameterized_variables = OrderedDict() <NEW_LINE> for v in self._template.variables: <NEW_LINE> <INDENT> self._parameterized_variables[v.name] = tf.reshape( tf.slice(self._parameter, [v.index], [v.size]), v.shape ) <NEW_LINE> <DEDENT> <DEDENT> return self._parameterized_variables <NEW_LINE> <DEDENT> @property <NEW_LINE> def variable_scope(self): <NEW_LINE> <INDENT> return self._variable_scope <NEW_LINE> <DEDENT> @property <NEW_LINE> def template(self): <NEW_LINE> <INDENT> return self._template <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name
Parameterized variable scope from template. Create a variable scope with custom variable getter to get variable from the single parameter vector.
62598fdfadb09d7d5dc0aba3
class ColourSettings(SettingsMenu): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> super().__init__(parent, MenuList) <NEW_LINE> self.parent = parent <NEW_LINE> self.loadTitle(getResourcePath("assets/settings/colourTitle.png")) <NEW_LINE> self.loadWidgets() <NEW_LINE> <DEDENT> def loadWidgets(self): <NEW_LINE> <INDENT> for key, item in maze.tileColours.items(): <NEW_LINE> <INDENT> tileName = key.name.replace("_", " ").title() <NEW_LINE> container = tk.Frame(self, width=200) <NEW_LINE> container.grid(row=key.value + 1, column=0, pady=0) <NEW_LINE> title = ttk.Label(container, style="Header.TLabel", text=tileName) <NEW_LINE> title.grid(row=0, column=0, columnspan=19) <NEW_LINE> fgTitle = ttk.Label(container, style="Subheading.TLabel", text="FG :") <NEW_LINE> fgTitle.grid(row=1, column=0) <NEW_LINE> fgColour = tkColourPicker.ColourPicker(container, 2, 1, key=key, command=self.setColour, index=1) <NEW_LINE> fgColour.grid(row=1, column=1) <NEW_LINE> fgColour.set(maze.tileColours[key][1]) <NEW_LINE> divider = ttk.Label(container, style="Subheading.TLabel", text=" ") <NEW_LINE> divider.grid(row=1, column=3) <NEW_LINE> bgTitle = ttk.Label(container, style="Subheading.TLabel", text="BG :") <NEW_LINE> bgTitle.grid(row=1, column=4) <NEW_LINE> bgColour = tkColourPicker.ColourPicker(container, 2, 1, key=key, command=self.setColour, index=0) <NEW_LINE> bgColour.grid(row=1, column=5) <NEW_LINE> bgColour.set(maze.tileColours[key][0]) <NEW_LINE> <DEDENT> self.reloadButton = ttk.Button(self, style="Settings.TButton", text="Reload Colours", command=self.updateColours) <NEW_LINE> self.reloadButton.grid(row=100, column=0, pady=3) <NEW_LINE> <DEDENT> def setColour(self, key, newColour, index): <NEW_LINE> <INDENT> if newColour is not None: <NEW_LINE> <INDENT> maze.tileColours[key][index] = newColour <NEW_LINE> self.parent.db.updateUserColours(self.parent.userID, key.name.upper(), index, newColour) <NEW_LINE> <DEDENT> <DEDENT> def updateColours(self): <NEW_LINE> <INDENT> for row in self.parent.maze.tiles: <NEW_LINE> <INDENT> for tile in row: <NEW_LINE> <INDENT> tile.updateColour()
Class for the applications Colour Menu
62598fdf656771135c489c9f
class Retrosheet(object): <NEW_LINE> <INDENT> record_types: ClassVar[FrozenSet[Text]] = make_frozen( 'id', 'version', 'info', 'start', 'play', 'sub', 'com', 'data', 'badj', 'padj', ) <NEW_LINE> info_types: ClassVar[FrozenSet[Text]] = make_frozen( 'visteam', 'hometeam', 'date', 'number', 'starttime', 'daynight', 'usedh', 'pitches', 'umphome', 'ump1b', 'ump2b', 'ump3b', 'umplf', 'umprf', 'fieldcond', 'precip', 'sky', 'temp', 'winddir', 'windspeed', 'timeofgame', 'attendance', 'site', 'wp', 'lp', 'save', 'gwrbi', 'edittime', 'howscored', 'inputprogvers', 'inputter', 'inputtime', 'scorer', 'translator', ) <NEW_LINE> pitch_types: ClassVar[FrozenSet[Text]] = make_frozen( 'B', 'C', 'F', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', ) <NEW_LINE> team_s: ClassVar[slice] = slice(3) <NEW_LINE> assert team_s.stop is not None <NEW_LINE> year_s: ClassVar[slice] = slice(team_s.stop, team_s.stop + 4) <NEW_LINE> assert year_s.stop is not None <NEW_LINE> month_s: ClassVar[slice] = slice(year_s.stop, year_s.stop + 2) <NEW_LINE> assert month_s.stop is not None <NEW_LINE> day_s = slice(month_s.stop, month_s.stop + 2) <NEW_LINE> assert day_s.stop is not None <NEW_LINE> eve_base = 'http://www.retrosheet.org/events' <NEW_LINE> years: ClassVar[range] = range(1921, datetime.today().year) <NEW_LINE> @classmethod <NEW_LINE> def event_url(cls, year: int) -> Text: <NEW_LINE> <INDENT> assert year in cls.years <NEW_LINE> return cls.eve_base + '/' + '{0}eve.zip'.format(year)
Constants associated with Retrosheet event file parsing id: id,<team:3><year:3><month:2><day:2><num:1>
62598fdf4c3428357761a8da
class MissingRequiredInstanceGroupsError(EmrError, ParamValidationError): <NEW_LINE> <INDENT> fmt = ('aws: error: Must specify either --instance-groups or ' '--instance-type with --instance-count(optional) to ' 'configure instance groups.')
In create-cluster command, none of --instance-group, --instance-count nor --instance-type were not supplied.
62598fdf656771135c489ca0
class InvalidFileTypeError(OSError): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("This file extension is not supported. " "Supported extension is a enum value in file_handler.FileExtensions")
Exception which will be raised when the file extension of the data file does not match what is in the FileExtension Enum.
62598fdf187af65679d29f0c
class ProductsTestCase(TestCase): <NEW_LINE> <INDENT> def _create_fixture(self): <NEW_LINE> <INDENT> Product.objects.create( name='product 1', active=True, unit_price=42) <NEW_LINE> Product.objects.create( name='product 2', active=True, unit_price=42) <NEW_LINE> Product.objects.create( name='product 3', active=False, unit_price=42) <NEW_LINE> <DEDENT> def test01_should_return_all_active_products(self): <NEW_LINE> <INDENT> self._create_fixture() <NEW_LINE> tag = Products(DummyParser(), DummyTokens()) <NEW_LINE> result = tag.get_context({}, None) <NEW_LINE> self.assertTrue('products' in result) <NEW_LINE> self.assertEqual(len(result['products']), 2) <NEW_LINE> <DEDENT> def test02_should_return_objects_given_as_argument(self): <NEW_LINE> <INDENT> self._create_fixture() <NEW_LINE> tag = Products(DummyParser(), DummyTokens()) <NEW_LINE> arg_objects = Product.objects.filter(active=False) <NEW_LINE> result = tag.get_context({}, arg_objects) <NEW_LINE> self.assertTrue('products' in result) <NEW_LINE> self.assertEqual(len(result['products']), 1) <NEW_LINE> <DEDENT> def test03_should_return_empty_array_if_no_objects_found(self): <NEW_LINE> <INDENT> self._create_fixture() <NEW_LINE> tag = Products(DummyParser(), DummyTokens()) <NEW_LINE> arg_objects = Product.objects.filter(pk=99999) <NEW_LINE> result = tag.get_context({}, arg_objects) <NEW_LINE> self.assertEqual(len(result['products']), 0)
Tests for the Products templatetag.
62598fdf50812a4eaa620ef8
class OfferBadgeCampaign(object): <NEW_LINE> <INDENT> openapi_types = { 'id': 'str', 'name': 'str' } <NEW_LINE> attribute_map = { 'id': 'id', 'name': 'name' } <NEW_LINE> def __init__(self, id=None, name=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._id = None <NEW_LINE> self._name = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.id = id <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `id`, must not be `None`") <NEW_LINE> <DEDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, OfferBadgeCampaign): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, OfferBadgeCampaign): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fdf099cdd3c636756f5
class triByteFlags(treedict.Tree_dict): <NEW_LINE> <INDENT> def __init__(self, flagClass, **kwargs): <NEW_LINE> <INDENT> self.flagClass=flagClass <NEW_LINE> self.curval=self.flagClass.NONE <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def loadByte(self, abyte): <NEW_LINE> <INDENT> self.curval=self.flagClass(abyte) <NEW_LINE> <DEDENT> def testFlag(self, flagbits): <NEW_LINE> <INDENT> return self.curval & flagbits == flagbits
a special version for the status byte returned on every spi transfer - makes it look like another register to the app
62598fdfd8ef3951e32c8173
class AbstractStatEventHandler(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def on_statistics(self, nodes: list, metrics: ParseMetrics, quality: ParseQuality) -> None: <NEW_LINE> <INDENT> pass
Base class for statistics event handlers
62598fdfc4546d3d9def759c
class Employee: <NEW_LINE> <INDENT> def __init__(self, emp_name, emp_salary, emp_type, emp_id): <NEW_LINE> <INDENT> self.emp_name = emp_name <NEW_LINE> self.emp_salary = emp_salary <NEW_LINE> self.emp_type = emp_type <NEW_LINE> self.emp_id = emp_id
object to represent employee
62598fdf50812a4eaa620ef9
class SMSGateway(MethodsMixin, db.Model): <NEW_LINE> <INDENT> __tablename__ = 'smsgateway' <NEW_LINE> __table_args__ = {'mysql_row_format': 'DYNAMIC'} <NEW_LINE> id = db.Column(db.Integer, Sequence("smsgateway_seq"), primary_key=True) <NEW_LINE> identifier = db.Column(db.Unicode(255), nullable=False, unique=True) <NEW_LINE> description = db.Column(db.Unicode(1024), default=u"") <NEW_LINE> providermodule = db.Column(db.Unicode(1024), nullable=False) <NEW_LINE> options = db.relationship('SMSGatewayOption', lazy='dynamic', backref='smsgw') <NEW_LINE> def __init__(self, identifier, providermodule, description=None, options=None, headers=None): <NEW_LINE> <INDENT> options = options or {} <NEW_LINE> headers = headers or {} <NEW_LINE> sql = SMSGateway.query.filter_by(identifier=identifier).first() <NEW_LINE> if sql: <NEW_LINE> <INDENT> self.id = sql.id <NEW_LINE> <DEDENT> self.identifier = identifier <NEW_LINE> self.providermodule = providermodule <NEW_LINE> self.description = description <NEW_LINE> self.save() <NEW_LINE> opts = {"option": options, "header": headers} <NEW_LINE> if sql: <NEW_LINE> <INDENT> sql_opts = {"option": sql.option_dict, "header": sql.header_dict} <NEW_LINE> for typ, vals in opts.items(): <NEW_LINE> <INDENT> for key in sql_opts[typ].keys(): <NEW_LINE> <INDENT> if key not in vals: <NEW_LINE> <INDENT> SMSGatewayOption.query.filter_by(gateway_id=self.id, Key=key, Type=typ).delete() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for typ, vals in opts.items(): <NEW_LINE> <INDENT> for k, v in vals.items(): <NEW_LINE> <INDENT> SMSGatewayOption(gateway_id=self.id, Key=k, Value=v, Type=typ).save() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> if self.id is None: <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> SMSGateway.query.filter_by(id=self.id).update({ "identifier": self.identifier, "providermodule": self.providermodule, "description": self.description }) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> return self.id <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> ret = self.id <NEW_LINE> db.session.query(SMSGatewayOption) .filter(SMSGatewayOption.gateway_id == ret) .delete() <NEW_LINE> db.session.delete(self) <NEW_LINE> db.session.commit() <NEW_LINE> return ret <NEW_LINE> <DEDENT> @property <NEW_LINE> def option_dict(self): <NEW_LINE> <INDENT> res = {} <NEW_LINE> for option in self.options: <NEW_LINE> <INDENT> if option.Type == "option" or not option.Type: <NEW_LINE> <INDENT> res[option.Key] = option.Value <NEW_LINE> <DEDENT> <DEDENT> return res <NEW_LINE> <DEDENT> @property <NEW_LINE> def header_dict(self): <NEW_LINE> <INDENT> res = {} <NEW_LINE> for option in self.options: <NEW_LINE> <INDENT> if option.Type == "header": <NEW_LINE> <INDENT> res[option.Key] = option.Value <NEW_LINE> <DEDENT> <DEDENT> return res <NEW_LINE> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> d = {"id": self.id, "name": self.identifier, "providermodule": self.providermodule, "description": self.description, "options": self.option_dict, "headers": self.header_dict} <NEW_LINE> return d
This table stores the SMS Gateway definitions. See https://github.com/privacyidea/privacyidea/wiki/concept:-Delivery-Gateway It saves the * unique name * a description * the SMS provider module All options and parameters are saved in other tables.
62598fdfd8ef3951e32c8174
class StoreItem(Domain): <NEW_LINE> <INDENT> pass
Object containing store items attributes
62598fdf656771135c489ca4
class SecureCookieSessionInterface(SessionInterface): <NEW_LINE> <INDENT> salt = "cookie-session" <NEW_LINE> digest_method = staticmethod(hashlib.sha1) <NEW_LINE> key_derivation = "hmac" <NEW_LINE> serializer = session_json_serializer <NEW_LINE> session_class = SecureCookieSession <NEW_LINE> def get_signing_serializer(self, app): <NEW_LINE> <INDENT> if not app.secret_key: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> signer_kwargs = dict( key_derivation=self.key_derivation, digest_method=self.digest_method ) <NEW_LINE> return URLSafeTimedSerializer( app.secret_key, salt=self.salt, serializer=self.serializer, signer_kwargs=signer_kwargs, ) <NEW_LINE> <DEDENT> def open_session(self, app, request): <NEW_LINE> <INDENT> s = self.get_signing_serializer(app) <NEW_LINE> if s is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> val = request.cookies.get(self.get_cookie_name(app)) <NEW_LINE> if not val: <NEW_LINE> <INDENT> return self.session_class() <NEW_LINE> <DEDENT> max_age = total_seconds(app.permanent_session_lifetime) <NEW_LINE> try: <NEW_LINE> <INDENT> data = s.loads(val, max_age=max_age) <NEW_LINE> return self.session_class(data) <NEW_LINE> <DEDENT> except BadSignature: <NEW_LINE> <INDENT> return self.session_class() <NEW_LINE> <DEDENT> <DEDENT> def save_session(self, app, session, response): <NEW_LINE> <INDENT> name = self.get_cookie_name(app) <NEW_LINE> domain = self.get_cookie_domain(app) <NEW_LINE> path = self.get_cookie_path(app) <NEW_LINE> if not session: <NEW_LINE> <INDENT> if session.modified: <NEW_LINE> <INDENT> response.delete_cookie(name, domain=domain, path=path) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> if session.accessed: <NEW_LINE> <INDENT> response.vary.add("Cookie") <NEW_LINE> <DEDENT> if not self.should_set_cookie(app, session): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> httponly = self.get_cookie_httponly(app) <NEW_LINE> secure = self.get_cookie_secure(app) <NEW_LINE> samesite = self.get_cookie_samesite(app) <NEW_LINE> expires = self.get_expiration_time(app, session) <NEW_LINE> val = self.get_signing_serializer(app).dumps(dict(session)) <NEW_LINE> response.set_cookie( name, val, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure, samesite=samesite, )
The default session interface that stores sessions in signed cookies through the :mod:`itsdangerous` module.
62598fdf099cdd3c636756f9
class PollPoller(_PollerBase): <NEW_LINE> <INDENT> POLL_TIMEOUT_MULT = 1000 <NEW_LINE> def __init__(self, get_wait_seconds, process_timeouts): <NEW_LINE> <INDENT> self._poll = None <NEW_LINE> super(PollPoller, self).__init__(get_wait_seconds, process_timeouts) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _create_poller(): <NEW_LINE> <INDENT> return select.poll() <NEW_LINE> <DEDENT> def poll(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> events = self._poll.poll(self._get_max_wait()) <NEW_LINE> break <NEW_LINE> <DEDENT> except _SELECT_ERRORS as error: <NEW_LINE> <INDENT> if _is_resumable(error): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> fd_event_map = collections.defaultdict(int) <NEW_LINE> for fileno, event in events: <NEW_LINE> <INDENT> if (event & select.POLLHUP) and rez.vendor.pika.compat.ON_OSX: <NEW_LINE> <INDENT> event |= select.POLLERR <NEW_LINE> <DEDENT> fd_event_map[fileno] |= event <NEW_LINE> <DEDENT> self._dispatch_fd_events(fd_event_map) <NEW_LINE> <DEDENT> def _init_poller(self): <NEW_LINE> <INDENT> assert self._poll is None <NEW_LINE> self._poll = self._create_poller() <NEW_LINE> <DEDENT> def _uninit_poller(self): <NEW_LINE> <INDENT> if self._poll is not None: <NEW_LINE> <INDENT> if hasattr(self._poll, "close"): <NEW_LINE> <INDENT> self._poll.close() <NEW_LINE> <DEDENT> self._poll = None <NEW_LINE> <DEDENT> <DEDENT> def _register_fd(self, fileno, events): <NEW_LINE> <INDENT> if self._poll is not None: <NEW_LINE> <INDENT> self._poll.register(fileno, events) <NEW_LINE> <DEDENT> <DEDENT> def _modify_fd_events(self, fileno, events, events_to_clear, events_to_set): <NEW_LINE> <INDENT> if self._poll is not None: <NEW_LINE> <INDENT> self._poll.modify(fileno, events) <NEW_LINE> <DEDENT> <DEDENT> def _unregister_fd(self, fileno, events_to_clear): <NEW_LINE> <INDENT> if self._poll is not None: <NEW_LINE> <INDENT> self._poll.unregister(fileno)
Poll works on Linux and can have better performance than EPoll in certain scenarios. Both are faster than select.
62598fdf187af65679d29f11
class CourseGraderUpdatesTest(CourseTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(CourseGraderUpdatesTest, self).setUp() <NEW_LINE> self.url = get_url(self.course.id, 'grading_handler') <NEW_LINE> self.starting_graders = CourseGradingModel(self.course).graders <NEW_LINE> <DEDENT> def test_get(self): <NEW_LINE> <INDENT> resp = self.client.get_json(self.url + '/0') <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> obj = json.loads(resp.content) <NEW_LINE> self.assertEqual(self.starting_graders[0], obj) <NEW_LINE> <DEDENT> def test_delete(self): <NEW_LINE> <INDENT> resp = self.client.delete(self.url + '/0', HTTP_ACCEPT="application/json") <NEW_LINE> self.assertEqual(resp.status_code, 204) <NEW_LINE> current_graders = CourseGradingModel.fetch(self.course.id).graders <NEW_LINE> self.assertNotIn(self.starting_graders[0], current_graders) <NEW_LINE> self.assertEqual(len(self.starting_graders) - 1, len(current_graders)) <NEW_LINE> <DEDENT> def test_update(self): <NEW_LINE> <INDENT> grader = { "id": 0, "type": "manual", "min_count": 5, "drop_count": 10, "short_label": "yo momma", "weight": 17.3, } <NEW_LINE> resp = self.client.ajax_post(self.url + '/0', grader) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> obj = json.loads(resp.content) <NEW_LINE> self.assertEqual(obj, grader) <NEW_LINE> current_graders = CourseGradingModel.fetch(self.course.id).graders <NEW_LINE> self.assertEqual(len(self.starting_graders), len(current_graders)) <NEW_LINE> <DEDENT> def test_add(self): <NEW_LINE> <INDENT> grader = { "type": "manual", "min_count": 5, "drop_count": 10, "short_label": "yo momma", "weight": 17.3, } <NEW_LINE> resp = self.client.ajax_post('{}/{}'.format(self.url, len(self.starting_graders) + 1), grader) <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> obj = json.loads(resp.content) <NEW_LINE> self.assertEqual(obj['id'], len(self.starting_graders)) <NEW_LINE> del obj['id'] <NEW_LINE> self.assertEqual(obj, grader) <NEW_LINE> current_graders = CourseGradingModel.fetch(self.course.id).graders <NEW_LINE> self.assertEqual(len(self.starting_graders) + 1, len(current_graders))
Test getting, deleting, adding, & updating graders
62598fdf091ae35668705254
class Solution(object): <NEW_LINE> <INDENT> def solve(self, board): <NEW_LINE> <INDENT> if not board: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> row, column = len(board), len(board[0]) <NEW_LINE> def dfs(x, y): <NEW_LINE> <INDENT> que = [(x, y)] <NEW_LINE> while que: <NEW_LINE> <INDENT> x, y = que.pop() <NEW_LINE> board[x][y] = 'P' <NEW_LINE> for a, b in [(0, 1), (0, -1), (1, 0), (-1, 0)]: <NEW_LINE> <INDENT> if 0 <= x + a < row and 0 <= y + b < column: <NEW_LINE> <INDENT> if board[x + a][y + b] == 'O': <NEW_LINE> <INDENT> que.append((x + a, y + b)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for i in [0, row - 1]: <NEW_LINE> <INDENT> for j in range(column): <NEW_LINE> <INDENT> if board[i][j] == 'O': <NEW_LINE> <INDENT> dfs(i, j) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for i in range(1, row - 1): <NEW_LINE> <INDENT> for j in [0, column - 1]: <NEW_LINE> <INDENT> if board[i][j] == 'O': <NEW_LINE> <INDENT> dfs(i, j) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for i in range(row): <NEW_LINE> <INDENT> for j in range(column): <NEW_LINE> <INDENT> if board[i][j] == 'O': <NEW_LINE> <INDENT> board[i][j] = 'X' <NEW_LINE> <DEDENT> elif board[i][j] == 'P': <NEW_LINE> <INDENT> board[i][j] = 'O' <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return board
给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 示例: X X X X X O O X X X O X X O X X 运行你的函数后,矩阵变为: X X X X X X X X X X X X X O X X 解释: 被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。 如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。 链接:https://leetcode-cn.com/problems/surrounded-regions
62598fdf26238365f5fad19b
class ThreadPool: <NEW_LINE> <INDENT> def __init__(self, threads): <NEW_LINE> <INDENT> self._thread_queues = queue.LifoQueue() <NEW_LINE> for i in range(threads): <NEW_LINE> <INDENT> task = queue.Queue() <NEW_LINE> result = queue.Queue() <NEW_LINE> q = AttrDict( dict(task=task, result=result) ) <NEW_LINE> thread = threading.Thread( target=_request_worker, kwargs=dict(task_queue=q.task, result_queue=q.result), daemon=True ) <NEW_LINE> thread.start() <NEW_LINE> self._thread_queues.put(q) <NEW_LINE> <DEDENT> <DEDENT> def request(self, method, url, body=None, encoding=None, retry=1, headers=None): <NEW_LINE> <INDENT> task = dict(method=method, url=url, body=body, encoding=encoding, retry=retry, headers=headers) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> q = self._thread_queues.get(timeout=1) <NEW_LINE> break <NEW_LINE> <DEDENT> except queue.Empty: <NEW_LINE> <INDENT> if not pool.is_alive(): <NEW_LINE> <INDENT> raise Exception("Connection pool closed") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if q is None: raise Exception("No thread queue found") <NEW_LINE> q.task.put(task) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = q.result.get(timeout=1) <NEW_LINE> q.result.task_done() <NEW_LINE> <DEDENT> except queue.Empty: <NEW_LINE> <INDENT> if not pool.is_alive(): <NEW_LINE> <INDENT> raise Exception("Connection pool closed") <NEW_LINE> <DEDENT> else: continue <NEW_LINE> <DEDENT> self._thread_queues.task_done() <NEW_LINE> self._thread_queues.put(q) <NEW_LINE> if 'exception' in result: raise result['exception'] <NEW_LINE> return result['result']
Pool of threads used to perform connections
62598fdf187af65679d29f13
class CKYParser: <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.grammar = CNFGrammar(path) <NEW_LINE> <DEDENT> def parse(self, sentence): <NEW_LINE> <INDENT> N = len(sentence) <NEW_LINE> self.chart = [(N+1)*[None] for row_label in xrange(N+1)] <NEW_LINE> for j in xrange(1, N+1): <NEW_LINE> <INDENT> token = sentence[j-1] <NEW_LINE> self.chart[j-1][j] = map(lambda preterm: Node(preterm, terminal=token), self.grammar.lhs_for_rhs(token, "lexical")) <NEW_LINE> for i in reversed(xrange(0, j-1)): <NEW_LINE> <INDENT> for k in xrange(i+1, j): <NEW_LINE> <INDENT> lcandidates = self.chart[i][k] <NEW_LINE> rcandidates = self.chart[k][j] <NEW_LINE> if lcandidates and rcandidates: <NEW_LINE> <INDENT> for lnode in lcandidates: <NEW_LINE> <INDENT> lsymbol = lnode.symbol <NEW_LINE> for rnode in rcandidates: <NEW_LINE> <INDENT> rsymbol = rnode.symbol <NEW_LINE> msymbols = self.grammar.lhs_for_rhs([lsymbol, rsymbol], "phrasal") <NEW_LINE> if msymbols and self.chart[i][j] is None: <NEW_LINE> <INDENT> self.chart[i][j] = [] <NEW_LINE> <DEDENT> for msymbol in msymbols: <NEW_LINE> <INDENT> self.chart[i][j].append(Node(msymbol, lnode, rnode)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def parse_to_string(self, node): <NEW_LINE> <INDENT> if node.left and node.right: <NEW_LINE> <INDENT> inside = "{0} {1}".format(self.parse_to_string(node.left), self.parse_to_string(node.right)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> inside = "{0}".format(node.terminal) <NEW_LINE> <DEDENT> return "({0} {1})".format(node.symbol, inside) <NEW_LINE> <DEDENT> def get_parses(self, sentence): <NEW_LINE> <INDENT> self.parse(sentence) <NEW_LINE> N = len(sentence) <NEW_LINE> parse_roots = self.chart[0][N] <NEW_LINE> result = [] <NEW_LINE> if parse_roots: <NEW_LINE> <INDENT> for root in parse_roots: <NEW_LINE> <INDENT> if root.symbol == self.grammar.start: <NEW_LINE> <INDENT> result.append(self.parse_to_string(root)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result
CKY parsing algorithm class
62598fdf4c3428357761a8ea
class EndpointServicesListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[EndpointServiceResult]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(EndpointServicesListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None)
Response for the ListAvailableEndpointServices API service call. :param value: List of available endpoint services in a region. :type value: list[~azure.mgmt.network.v2019_04_01.models.EndpointServiceResult] :param next_link: The URL to get the next set of results. :type next_link: str
62598fdfd8ef3951e32c817a
class ClassName(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> def my_function(self): <NEW_LINE> <INDENT> print(F"Hello my function {self.name}") <NEW_LINE> <DEDENT> def my_function_2(self): <NEW_LINE> <INDENT> print(F"Hello {self.name}")
Class level doc string
62598fdfadb09d7d5dc0abb5
class Meta: <NEW_LINE> <INDENT> app_label: str = "mcadmin" <NEW_LINE> unique_together: List[str] = [ "command", "user", ] <NEW_LINE> verbose_name: str = _("management command permission") <NEW_LINE> verbose_name_plural: str = _("management commands permissions") <NEW_LINE> ordering: List[str] = [ "command", ]
Model settings.
62598fdfd8ef3951e32c817b
class Connectivity(enum.Enum): <NEW_LINE> <INDENT> FOUR=4, <NEW_LINE> SIX=6
Two-dimensional 4-connectivity
62598fdfadb09d7d5dc0abb7
class ExtentTest(shared_test_lib.BaseTestCase): <NEW_LINE> <INDENT> def testInitialize(self): <NEW_LINE> <INDENT> test_extent = extent.Extent() <NEW_LINE> self.assertIsNotNone(test_extent)
Tests the VFS extent.
62598fdfc4546d3d9def75a5
class OvsStub(NetworkmanagerStub): <NEW_LINE> <INDENT> __next_id = 0 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(OvsStub, self).__init__('OvsStub') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __generate_id(cls): <NEW_LINE> <INDENT> cls.__next_id += 1 <NEW_LINE> return cls.__next_id <NEW_LINE> <DEDENT> def _send_message(self, url, method, params=None): <NEW_LINE> <INDENT> id = self.__generate_id() <NEW_LINE> id = 0 <NEW_LINE> headers = {'content-type': 'application/json'} <NEW_LINE> payload = { 'method': method, 'params': params if params is not None else [], 'jsonrpc': '2.0', 'id': id } <NEW_LINE> if general_config['mode'] == 'debug': <NEW_LINE> <INDENT> self._logger.info('I am in debug mode and do not send anything') <NEW_LINE> response = {'result': {'data': 'You are in debug mode'}, 'id': id} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._logger.debug('Request {} on {}'.format(method, url)) <NEW_LINE> response = requests.post(url, data=json.dumps(payload), headers=headers) <NEW_LINE> response.raise_for_status() <NEW_LINE> response = response.json() <NEW_LINE> <DEDENT> assert response['id'] == id, 'Wrong id received in OvsStub._send_message' + 'expected id {} but got {}'.format(id, response['id']) <NEW_LINE> if 'error' in response['result'].keys(): <NEW_LINE> <INDENT> raise RuntimeError(response['result']['error']) <NEW_LINE> <DEDENT> return response['result'] <NEW_LINE> <DEDENT> def set_rate_limit(self, switch_ip, switch_id, interface, ratelimit): <NEW_LINE> <INDENT> url = '{}{}:{}'.format( self._config['rpc_prefix'], switch_ip, self._config['rpc_port'] ) <NEW_LINE> if ratelimit is None: <NEW_LINE> <INDENT> ratelimit = 0 <NEW_LINE> <DEDENT> response = self._send_message( url=url, method='ovshandler.set_interface_ingress_rate_limit', params=['eth{}'.format(interface), ratelimit] ) <NEW_LINE> return response <NEW_LINE> <DEDENT> def set_burst(self, switch_ip, switch_id, interface, burstlimit): <NEW_LINE> <INDENT> url = '{}{}:{}'.format( self._config['rpc_prefix'], switch_ip, self._config['rpc_port'] ) <NEW_LINE> if burstlimit is None: <NEW_LINE> <INDENT> burstlimit = 0 <NEW_LINE> <DEDENT> response = self._send_message( url=url, method='ovshandler.set_interface_ingress_burst_limit', params=['eth{}'.format(interface), burstlimit] ) <NEW_LINE> return response
RPC stub for openvswitch Attributes: logger (logging.Logger): Classes logger object config (dict): Dictionary with configuration entries __next_id (int): currently highest id
62598fdffbf16365ca794703
class GameClient: <NEW_LINE> <INDENT> def __init__(self, server, token, player): <NEW_LINE> <INDENT> path = "ws://{}/galaxy".format(server) <NEW_LINE> self.galaxy = None <NEW_LINE> self.actions = [] <NEW_LINE> self.player = player <NEW_LINE> self.socket = websocket.WebSocketApp(path, header=['token: {}'.format(token)], on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open) <NEW_LINE> <DEDENT> def send_drones(self, src, dest, drones): <NEW_LINE> <INDENT> self.actions.append(ClientAction(src, dest, drones)) <NEW_LINE> <DEDENT> def get_my_planets(self): <NEW_LINE> <INDENT> return list(filter(lambda p: p.owner == self.player, self.galaxy.planets)) <NEW_LINE> <DEDENT> def get_planet_by_id(self, planet_id): <NEW_LINE> <INDENT> planet = list(filter(lambda p: p.id == planet_id, self.galaxy.planets)) <NEW_LINE> return None if len(planet) == 0 else planet <NEW_LINE> <DEDENT> def get_neighbours(self, planet_id): <NEW_LINE> <INDENT> planet = self.get_planet_by_id(planet_id) <NEW_LINE> return [] if not planet else list(filter(lambda p: planet_id in p.neighbours, self.galaxy.planets)) <NEW_LINE> <DEDENT> def get_galaxy(self): <NEW_LINE> <INDENT> return self.galaxy <NEW_LINE> <DEDENT> def run(self, on_turn=None): <NEW_LINE> <INDENT> self.on_turn = on_turn <NEW_LINE> self.socket.run_forever() <NEW_LINE> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> logger.debug("Received command <<< {}".format(message)) <NEW_LINE> self.galaxy = GalaxySnapshot(json.loads(message)) <NEW_LINE> self.actions = [] <NEW_LINE> self.on_turn(self) <NEW_LINE> command = ClientCommand(self.actions) <NEW_LINE> json_command = json.dumps(command.__dict__, cls=ClientCommandEncoder) <NEW_LINE> self.__send(json_command) <NEW_LINE> <DEDENT> def __send(self, msg): <NEW_LINE> <INDENT> logger.debug('Sending command >>> {}'.format(msg)) <NEW_LINE> if self.socket.sock: <NEW_LINE> <INDENT> self.socket.send(msg) <NEW_LINE> <DEDENT> <DEDENT> def on_open(self): <NEW_LINE> <INDENT> logger.info('Connection established') <NEW_LINE> <DEDENT> def on_error(self, error): <NEW_LINE> <INDENT> logger.error("Error: {}".format(error)) <NEW_LINE> <DEDENT> def on_close(self): <NEW_LINE> <INDENT> logger.info("Disconnected")
Основной объект клиента для взаимодействия с сервером.
62598fdf50812a4eaa620f02
class Revision_tag(db.Model): <NEW_LINE> <INDENT> tag_id = db.Column(db.Integer, primary_key = True) <NEW_LINE> name = db.Column(db.String(64)) <NEW_LINE> rev_id = db.Column(db.Integer, db.ForeignKey('revision_type.rev_id'))
Table for storing the revision tag (e.g. Definition) and the relative type of revision
62598fdfd8ef3951e32c817d
class Solution: <NEW_LINE> <INDENT> def fibonacci(self, n): <NEW_LINE> <INDENT> a = [0, 1] <NEW_LINE> for i in range(2, n): <NEW_LINE> <INDENT> a.append(a[i - 2] + a[i - 1]) <NEW_LINE> <DEDENT> return a[n - 1]
@param: n: an integer @return: an ineger f(n)
62598fdf26238365f5fad1a7
class BaseContentSummaryHook(hook.Hook): <NEW_LINE> <INDENT> __regid__ = "frarchives_edition.base_content.toc" <NEW_LINE> __select__ = hook.Hook.__select__ & is_instance("BaseContent") <NEW_LINE> events = ("before_add_entity", "before_update_entity") <NEW_LINE> def __call__(self): <NEW_LINE> <INDENT> entity = self.entity <NEW_LINE> old_content, new_content = entity.cw_edited.oldnewvalue("content") <NEW_LINE> old_policy, new_policy = entity.cw_edited.oldnewvalue("summary_policy") <NEW_LINE> changed_policy = new_policy != old_policy <NEW_LINE> if new_content != old_content or changed_policy: <NEW_LINE> <INDENT> in_summary = self._cw.transaction_data.setdefault("bc-summary", set()) <NEW_LINE> if entity.eid not in in_summary: <NEW_LINE> <INDENT> in_summary.add(entity.eid) <NEW_LINE> BaseContentSummaryOp.get_instance(self._cw).add_data((entity.eid)) <NEW_LINE> if changed_policy: <NEW_LINE> <INDENT> for tr in entity.reverse_translation_of: <NEW_LINE> <INDENT> BaseContentSummaryOp.get_instance(self._cw).add_data((tr.eid))
summary
62598fdf4c3428357761a8f2
class IService(object): <NEW_LINE> <INDENT> pass
An interface for services.
62598fdfd8ef3951e32c817e
class OperatorField(Field): <NEW_LINE> <INDENT> def __init__(self, name, *operators): <NEW_LINE> <INDENT> super(OperatorField, self).__init__(name) <NEW_LINE> self._name_to_op = dict() <NEW_LINE> for op in [op for op in operators]: <NEW_LINE> <INDENT> self._name_to_op[op.get_name()] = op <NEW_LINE> <DEDENT> <DEDENT> def apply(self, query, op_name, *args): <NEW_LINE> <INDENT> return self._name_to_op[op_name].apply(query, *args)
A field that support multiple operators. The first argument to the apply method should always be the operator name.
62598fdfc4546d3d9def75a7
class CORMap(Map): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_properties(cls, header): <NEW_LINE> <INDENT> properties = Map.get_properties(header) <NEW_LINE> properties.update({ "date": parse_time(header.get('date_obs')), "detector": header.get('detector'), "instrument": "SECCHI", "observatory": header.get('obsrvtry'), "measurement": "white-light", "name": "SECCHI %s" % header.get('detector'), "nickname": "%s-%s" % (header.get('detector'), header.get('obsrvtry')[-1]) }) <NEW_LINE> return properties <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_datasource_for(cls, header): <NEW_LINE> <INDENT> return header.get('detector', '').startswith('COR')
COR Image Map definition
62598fe0d8ef3951e32c8181
class RatingReducer(Reducer): <NEW_LINE> <INDENT> def reduce(self, key, values): <NEW_LINE> <INDENT> raise NotImplementedError
Example Reducer that does nothing at the moment. Your task is to implement the reduce method which will return the average film rating.
62598fe0187af65679d29f1b
class KeyValue(CIMXMLTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(KeyValue, self).setUp() <NEW_LINE> self.xml.append(cim_xml.KEYVALUE('dog', 'string')) <NEW_LINE> self.xml.append(cim_xml.KEYVALUE('2', 'numeric')) <NEW_LINE> self.xml.append(cim_xml.KEYVALUE('FALSE', 'boolean')) <NEW_LINE> self.xml.append(cim_xml.KEYVALUE('2', 'numeric', 'uint16')) <NEW_LINE> self.xml.append(cim_xml.KEYVALUE(None))
<!ELEMENT KEYVALUE (#PCDATA)> <!ATTLIST KEYVALUE VALUETYPE (string|boolean|numeric) 'string' %CIMType; #IMPLIED>
62598fe0091ae35668705269
class NurbsSurfaceBilinear: <NEW_LINE> <INDENT> def __init__(self, P00, P01, P10, P11): <NEW_LINE> <INDENT> self.P00 = P00 <NEW_LINE> self.P01 = P01 <NEW_LINE> self.P10 = P10 <NEW_LINE> self.P11 = P11 <NEW_LINE> self.ndim = 3 <NEW_LINE> ndims = [np.shape(P00)[0], np.shape(P01)[0], np.shape(P10)[0], np.shape(P11)[0]] <NEW_LINE> if any([ndim != 3 for ndim in ndims]): <NEW_LINE> <INDENT> raise Exception("The input points must be three-dimensional") <NEW_LINE> <DEDENT> self.NurbsSurface = None <NEW_LINE> self.make_nurbs_surface() <NEW_LINE> <DEDENT> def make_nurbs_surface(self): <NEW_LINE> <INDENT> n_dim, n, m = self.ndim, 2, 2 <NEW_LINE> P = np.zeros((n_dim, n, m)) <NEW_LINE> P[:, 0, 0] = self.P00 <NEW_LINE> P[:, 1, 0] = self.P01 <NEW_LINE> P[:, 0, 1] = self.P10 <NEW_LINE> P[:, 1, 1] = self.P11 <NEW_LINE> self.NurbsSurface = NurbsSurface(control_points=P)
Create a NURBS representation of the bilinear patch defined by corners P00, P01, P10, and P11 Create a NURBS representation of the bilinear patch S(u,v) = (1-v)*[(1-u)*P00 + u*P01] + v*[(1-u)*P10 + u*P11] Note that a bilinear patch is a ruled surface with segments (P00, P01) and (P10, P11) as generating curves S(u,v) = (1-v)*C1(u) + v*C2(u) C1(u) = (1-u)*P00 + u*P01 C2(u) = (1-u)*P10 + u*P11 Parameters ---------- P00, P01, P10, P11 : ndarrays with shape (ndim,) Coordinates of the corner points defining the bilinear surface (ndim=3) References ---------- The NURBS book. Chapter 8.2 L. Piegl and W. Tiller Springer, second edition
62598fe0adb09d7d5dc0abc9
class Media: <NEW_LINE> <INDENT> css = { "all": ("admin/mixing/styles.css",), } <NEW_LINE> js = ("admin/mixing/scripts.js",)
Include our style and script customizations for the Project admin.
62598fe026238365f5fad1b5
class MyDocuments(Documents): <NEW_LINE> <INDENT> search_options = {'Creator': authenticated_member, 'trashed': False} <NEW_LINE> enabled_actions = [ 'zip_selected', 'export_documents', ] <NEW_LINE> major_actions = [] <NEW_LINE> @property <NEW_LINE> def columns(self): <NEW_LINE> <INDENT> remove_columns = ['containing_subdossier'] <NEW_LINE> columns = [] <NEW_LINE> for col in super(MyDocuments, self).columns: <NEW_LINE> <INDENT> if isinstance(col, dict) and col.get('column') in remove_columns: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> columns.append(col) <NEW_LINE> <DEDENT> <DEDENT> return columns <NEW_LINE> <DEDENT> @property <NEW_LINE> def view_name(self): <NEW_LINE> <INDENT> return self.__name__.split('tabbedview_view-')[1]
List the documents created by the current user.
62598fe0d8ef3951e32c8185
class ClothesTweak_MaxWeight(ClothesTweak): <NEW_LINE> <INDENT> def buildPatch(self,patchFile,keep,log): <NEW_LINE> <INDENT> tweakCount = 0 <NEW_LINE> maxWeight = self.choiceValues[self.chosen][0] <NEW_LINE> superWeight = max(10,5*maxWeight) <NEW_LINE> for record in patchFile.CLOT.records: <NEW_LINE> <INDENT> weight = record.weight <NEW_LINE> if self.isMyType(record) and maxWeight < weight < superWeight: <NEW_LINE> <INDENT> record.weight = maxWeight <NEW_LINE> keep(record.fid) <NEW_LINE> tweakCount += 1 <NEW_LINE> <DEDENT> <DEDENT> log(u'* %s: [%4.2f]: %d' % (self.label,maxWeight,tweakCount))
Enforce a max weight for specified clothes.
62598fe0c4546d3d9def75ae
class _RowFormatter(): <NEW_LINE> <INDENT> def __init__(self, mcls: List[int]) -> None: <NEW_LINE> <INDENT> self.colpad = 2 <NEW_LINE> self.mcls = list(map(lambda x: x + self.colpad, mcls)) <NEW_LINE> self.fmts = str() <NEW_LINE> for mcl in self.mcls: <NEW_LINE> <INDENT> self.fmts += f'{{:<{mcl}s}}' <NEW_LINE> <DEDENT> <DEDENT> def format(self, row: 'Table.Row') -> str: <NEW_LINE> <INDENT> res = str() <NEW_LINE> res += self.fmts.format(*row.data) <NEW_LINE> if row.withrule: <NEW_LINE> <INDENT> res += '\n' + ('-' * (sum(self.mcls) - self.colpad)) <NEW_LINE> <DEDENT> return res
Private class used for row formatting.
62598fe0adb09d7d5dc0abcb
class ExpressionCaptcha(object): <NEW_LINE> <INDENT> is_captcha = True <NEW_LINE> def __init__(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.terms = config.get('captcha_expression_terms', 3) <NEW_LINE> self.ceiling = config.get('captcha_expression_ceiling', 10) <NEW_LINE> if self.ceiling > 100: <NEW_LINE> <INDENT> raise ValueError('Numeric captcha can not represent numbers > 100') <NEW_LINE> <DEDENT> <DEDENT> def generate_captcha(self, req): <NEW_LINE> <INDENT> terms = [str(random.randrange(0, self.ceiling)) for i in xrange(self.terms)] <NEW_LINE> operations = [random.choice(operation_names.keys()) for i in xrange(self.terms -1)] <NEW_LINE> expression, human = _humanize_expression(terms, operations) <NEW_LINE> return (expression, html.blockquote(' '.join(map(str, human)))) <NEW_LINE> <DEDENT> def verify_captcha(self, req): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def is_usable(self, req): <NEW_LINE> <INDENT> return True
captcha in the form of a human readable numeric expression Initial implementation by sergeych@tancher.com.
62598fe0fbf16365ca794715
class PAFeedParser(NITFFeedParser): <NEW_LINE> <INDENT> NAME = 'pa_nitf' <NEW_LINE> label = 'PA NITF' <NEW_LINE> def _category_mapping(self, elem): <NEW_LINE> <INDENT> if elem.get('content') is not None: <NEW_LINE> <INDENT> category = elem.get('content')[:1].upper() <NEW_LINE> if category in {'S', 'R', 'F'}: <NEW_LINE> <INDENT> return [{'qcode': 'S'}] <NEW_LINE> <DEDENT> if category == 'Z': <NEW_LINE> <INDENT> return [{'qcode': 'V'}] <NEW_LINE> <DEDENT> if category == 'H': <NEW_LINE> <INDENT> if self.xml.find("head/docdata/doc-scope[@scope='SHOWBIZ']") is not None: <NEW_LINE> <INDENT> return [{'qcode': 'E'}] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return [{'qcode': 'I'}] <NEW_LINE> <DEDENT> def get_content(self, xml): <NEW_LINE> <INDENT> elements = [] <NEW_LINE> for elem in xml.find('body/body.content'): <NEW_LINE> <INDENT> text = etree.tostring(elem, encoding="unicode", method="text") <NEW_LINE> elements.append( '<p>{}</p>\n'.format(html.escape(text))) <NEW_LINE> <DEDENT> content = ''.join(elements) <NEW_LINE> if self.get_anpa_format(xml) == 't': <NEW_LINE> <INDENT> if not content.startswith('<pre>'): <NEW_LINE> <INDENT> content = '<pre>{}</pre>'.format(self.parse_to_preformatted(content)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> content = self.parse_to_preformatted(content) <NEW_LINE> <DEDENT> <DEDENT> return content <NEW_LINE> <DEDENT> def get_headline(self, xml): <NEW_LINE> <INDENT> if xml.find('body/body.head/hedline/hl1') is not None: <NEW_LINE> <INDENT> return xml.find('body/body.head/hedline/hl1').text <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if xml.find('head/title') is not None: <NEW_LINE> <INDENT> return self._get_slugline(xml.find('head/title')) <NEW_LINE> <DEDENT> <DEDENT> raise SkipValue() <NEW_LINE> <DEDENT> def _get_slugline(self, elem): <NEW_LINE> <INDENT> sluglineList = re.sub(r'^[\d.]+\W+', '', elem.text).split(' ') <NEW_LINE> slugline = sluglineList[0].capitalize() <NEW_LINE> if len(sluglineList) > 1: <NEW_LINE> <INDENT> slugline = '{} {}'.format(slugline, ' '.join(sluglineList[1:])) <NEW_LINE> <DEDENT> return slugline <NEW_LINE> <DEDENT> def _get_pubstatus(self, elem): <NEW_LINE> <INDENT> return 'usable' if elem.attrib['management-status'] == 'embargoed' else elem.attrib['management-status'] <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.MAPPING = {'anpa_category': {'xpath': "head/meta/[@name='category']", 'filter': self._category_mapping}, 'slugline': {'xpath': 'head/title', 'filter': self._get_slugline}, 'pubstatus': {'xpath': 'head/docdata', 'filter': self._get_pubstatus}} <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def parse(self, xml, provider=None): <NEW_LINE> <INDENT> self.xml = xml <NEW_LINE> return super().parse(xml, provider=provider)
NITF Parser extension for Press Association, it maps the category meta tag to an anpa category
62598fe026238365f5fad1b7
class StackedCells(object): <NEW_LINE> <INDENT> def __init__(self, input_size, celltype=RNN, layers = [], activation = lambda x:x): <NEW_LINE> <INDENT> self.input_size = input_size <NEW_LINE> self.create_layers(layers, activation, celltype) <NEW_LINE> <DEDENT> def create_layers(self, layer_sizes, activation_type, celltype): <NEW_LINE> <INDENT> self.layers = [] <NEW_LINE> prev_size = self.input_size <NEW_LINE> for k, layer_size in enumerate(layer_sizes): <NEW_LINE> <INDENT> layer = celltype(prev_size, layer_size, activation_type) <NEW_LINE> self.layers.append(layer) <NEW_LINE> prev_size = layer_size <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def params(self): <NEW_LINE> <INDENT> return [param for layer in self.layers for param in layer.params] <NEW_LINE> <DEDENT> def forward(self, x, prev_hiddens = None, dropout = []): <NEW_LINE> <INDENT> if prev_hiddens is None: <NEW_LINE> <INDENT> prev_hiddens = [(T.repeat(T.shape_padleft(layer.initial_hidden_state), x.shape[0], axis=0) if x.ndim > 1 else layer.initial_hidden_state) if hasattr(layer, 'initial_hidden_state') else None for layer in self.layers ] <NEW_LINE> <DEDENT> out = [] <NEW_LINE> layer_input = x <NEW_LINE> for k, layer in enumerate(self.layers): <NEW_LINE> <INDENT> level_out = layer_input <NEW_LINE> if len(dropout) > 0: <NEW_LINE> <INDENT> level_out = apply_dropout(layer_input, dropout[k]) <NEW_LINE> <DEDENT> if layer.is_recursive: <NEW_LINE> <INDENT> level_out = layer.activate(level_out, prev_hiddens[k]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> level_out = layer.activate(level_out) <NEW_LINE> <DEDENT> out.append(level_out) <NEW_LINE> if hasattr(layer, 'postprocess_activation'): <NEW_LINE> <INDENT> if layer.is_recursive: <NEW_LINE> <INDENT> level_out = layer.postprocess_activation(level_out, layer_input, prev_hiddens[k]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> level_out = layer.postprocess_activation(level_out, layer_input) <NEW_LINE> <DEDENT> <DEDENT> layer_input = level_out <NEW_LINE> <DEDENT> return out
Sequentially connect several recurrent layers. celltypes can be RNN or LSTM.
62598fe0c4546d3d9def75af
@dataclass <NEW_LINE> class ResNetModelOutput(ModelOutput): <NEW_LINE> <INDENT> last_hidden_state: torch.FloatTensor = None <NEW_LINE> pooler_output: torch.FloatTensor = None <NEW_LINE> hidden_states: Optional[Tuple[torch.FloatTensor]] = None
ResNet model's output, with potential hidden states. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`torch.FloatTensor` of shape `(batch_size, config.hidden_sizes[-1])`): The pooled last hidden state. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the model at the output of each layer plus the initial embedding outputs.
62598fe0c4546d3d9def75b0
class User(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField( unique=True, error_messages={ 'unique': _("そのEメールアドレスはすでに使用されています"), }, verbose_name='Eメール' ) <NEW_LINE> username_validator = UnicodeUsernameValidator() <NEW_LINE> username = models.CharField( max_length=150, validators=[username_validator], help_text=_('150文字以下。文字と数字と @/./+/-/_ のみ。'), verbose_name='ユーザ名' ) <NEW_LINE> birthday = models.DateField( blank=True, null=True, help_text=_('例:1996-05-31'), verbose_name='生年月日' ) <NEW_LINE> GENDER_CHOICES = ( (1,'男性'), (2,'女性'), ) <NEW_LINE> gender = models.IntegerField(verbose_name='性別', choices=GENDER_CHOICES) <NEW_LINE> place = models.CharField(max_length=100, verbose_name='居住地', null=True) <NEW_LINE> height =models.FloatField(help_text=_('男性は170cm未満のかた限定です。'), verbose_name='身長') <NEW_LINE> date_joined = models.DateTimeField(default=timezone.now, verbose_name='登録日') <NEW_LINE> user_icon = models.ImageField('画像', upload_to = 'images/', blank=True, null=True) <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> super().clean() <NEW_LINE> self.email = self.__class__.objects.normalize_email(self.email) <NEW_LINE> if self.username == 'dst': <NEW_LINE> <INDENT> raise ValidationError("'dstは名前に使えません'") <NEW_LINE> <DEDENT> if self.gender == 1: <NEW_LINE> <INDENT> if self.height < 150.0 or self.height > 169.9: <NEW_LINE> <INDENT> raise ValidationError('身長が170cm以上の男性はご遠慮ください') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> is_active = models.BooleanField( _('active'), default=True, ) <NEW_LINE> is_admin = models.BooleanField(default=False) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserManager() <NEW_LINE> EMAIL_FIELD = 'email' <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['username', 'birthday', 'gender', 'place', 'height'] <NEW_LINE> def email_user(self, subject, message, from_email=None, **kwargs): <NEW_LINE> <INDENT> send_mail(subject, message, from_email, [self.email], **kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email <NEW_LINE> <DEDENT> def has_perm(self, perm, obj=None): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def has_module_perms(self, app_label): <NEW_LINE> <INDENT> return True
An abstract base class implementing a fully featured User model with admin-compliant permissions. Username and password are required. Other fields are optional.
62598fe0187af65679d29f21
class FileVariables(object): <NEW_LINE> <INDENT> _filename = None <NEW_LINE> def __init__(self, filename=None): <NEW_LINE> <INDENT> self._filename = filename <NEW_LINE> self._local_vars = dict() <NEW_LINE> self._load_variables() <NEW_LINE> <DEDENT> def get_value(self, key): <NEW_LINE> <INDENT> return self._local_vars.get(key, None) <NEW_LINE> <DEDENT> def get_variables(self): <NEW_LINE> <INDENT> return self._local_vars <NEW_LINE> <DEDENT> def _load_variables(self): <NEW_LINE> <INDENT> if not self._filename: <NEW_LINE> <INDENT> raise FileVariableError('No filename has been given') <NEW_LINE> <DEDENT> fd = file(self._filename, 'r') <NEW_LINE> lines = [fd.readline(), fd.readline()] <NEW_LINE> fd.close() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._parse_variables(line) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _parse_variables(self, line): <NEW_LINE> <INDENT> paren = '-*-' <NEW_LINE> start = line.find(paren) + len(paren) <NEW_LINE> end = line.rfind(paren) <NEW_LINE> if start == -1 or end == -1: <NEW_LINE> <INDENT> raise ValueError( "%r not a valid local variable declaration" % (line,)) <NEW_LINE> <DEDENT> items = line[start:end].split(';') <NEW_LINE> for item in items: <NEW_LINE> <INDENT> if len(item.strip()) == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> split = item.split(':') <NEW_LINE> if len(split) != 2: <NEW_LINE> <INDENT> raise ValueError("%r contains invalid declaration %r" % (line, item)) <NEW_LINE> <DEDENT> self._local_vars[split[0].strip()] = split[1].strip()
Emacs local variables format parser for Mamba. We don't use twisted self implementation because we need extra stuff.
62598fe0d8ef3951e32c8188
class IconData(IniFile): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> IniFile.__init__(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.getDisplayName() <NEW_LINE> <DEDENT> def parse(self, file): <NEW_LINE> <INDENT> IniFile.parse(self, file, ["Icon Data"]) <NEW_LINE> <DEDENT> def getDisplayName(self): <NEW_LINE> <INDENT> return self.get('DisplayName', locale=True) <NEW_LINE> <DEDENT> def getEmbeddedTextRectangle(self): <NEW_LINE> <INDENT> return self.get('EmbeddedTextRectangle', list=True) <NEW_LINE> <DEDENT> def getAttachPoints(self): <NEW_LINE> <INDENT> return self.get('AttachPoints', type="point", list=True) <NEW_LINE> <DEDENT> def checkExtras(self): <NEW_LINE> <INDENT> if self.fileExtension != ".icon": <NEW_LINE> <INDENT> self.warnings.append('Unknown File extension') <NEW_LINE> <DEDENT> <DEDENT> def checkGroup(self, group): <NEW_LINE> <INDENT> if not (group == self.defaultGroup or (re.match("^\[X-", group) and group.encode("ascii", 'ignore') == group)): <NEW_LINE> <INDENT> self.errors.append("Invalid Group name: %s" % group.encode("ascii", "replace")) <NEW_LINE> <DEDENT> <DEDENT> def checkKey(self, key, value, group): <NEW_LINE> <INDENT> if re.match("^DisplayName"+xdg.Locale.regex+"$", key): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif key == "EmbeddedTextRectangle": <NEW_LINE> <INDENT> self.checkValue(key, value, type="integer", list=True) <NEW_LINE> <DEDENT> elif key == "AttachPoints": <NEW_LINE> <INDENT> self.checkValue(key, value, type="point", list=True) <NEW_LINE> <DEDENT> elif re.match("^X-[a-zA-Z0-9-]+", key): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.errors.append("Invalid key: %s" % key)
Class to parse and validate IconData Files
62598fe050812a4eaa620f0d
class ResidualBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self, inchannel, outchannel, stride=1, shortcut=None): <NEW_LINE> <INDENT> super(ResidualBlock, self).__init__() <NEW_LINE> self.left = nn.Sequential( nn.Conv2d(inchannel, outchannel, 3, stride, 1, bias=False), nn.BatchNorm2d(outchannel), nn.ReLU(inplace=True), nn.Conv2d(outchannel, outchannel, 3, 1,1,bias=False), nn.BatchNorm2d(outchannel) ) <NEW_LINE> self.right = shortcut <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> out = self.left(x) <NEW_LINE> residual = x if self.right is None else self.right(x) <NEW_LINE> out += residual <NEW_LINE> return F.relu(out)
sub module: the residual block
62598fe0d8ef3951e32c8189
class MultiOptionField(Field): <NEW_LINE> <INDENT> def custom_default(self): <NEW_LINE> <INDENT> return self.values[0] <NEW_LINE> <DEDENT> def allowed_types(self): <NEW_LINE> <INDENT> return 'unicode-strings in %s' % self.values <NEW_LINE> <DEDENT> def on_initialized(self, sender, kwargs): <NEW_LINE> <INDENT> self.options = ordereddict() <NEW_LINE> self.values = [] <NEW_LINE> options = kwargs.pop('options') <NEW_LINE> for value, text in options: <NEW_LINE> <INDENT> self.options[text] = value <NEW_LINE> self.values.append(value) <NEW_LINE> <DEDENT> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> if value not in self.values: <NEW_LINE> <INDENT> self.validation_error(value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def conf_to_python(self, value): <NEW_LINE> <INDENT> def _find_value(): <NEW_LINE> <INDENT> for _value in self.values: <NEW_LINE> <INDENT> if str(_value) == value: <NEW_LINE> <INDENT> return _value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> _value = _find_value() <NEW_LINE> if _value is None: <NEW_LINE> <INDENT> self.validation_error(value) <NEW_LINE> <DEDENT> return type(_value)(value) <NEW_LINE> <DEDENT> def python_to_conf(self, value): <NEW_LINE> <INDENT> if type(value)(str(value)) != value: <NEW_LINE> <INDENT> raise InvalidOptionError(self, "%r has an incompatible type (%r)" % (value, type(value))) <NEW_LINE> <DEDENT> return str(value)
A (typically dropdown) selection field. Takes an extra argument ``options`` which is a tuple of two-tuples (or any other iterable datatype in this form) where the first item of the two-tuple holds a value and the second item the label for entry. The value item might be of any type, the label item has to be a string. .. note:: If your backend runs in compatibility mode, values may only be instances of any type convertable from string to that type using ``thattype(somestring)`` (for example, :class:`int`, :class:`float` support that type of conversion). Otherwise, reading values from the backend will fail. Example:: ... = MultiOptionField('My options', options=( ('foo', 'Select me for foo'), ('bar', 'Select me for bar'), (42, 'Select me for the answer to Life, the Universe, and Everything') ))
62598fe0c4546d3d9def75b3
class UserDetailView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> user = get_object_or_404(User, pk=int(request.GET['id'])) <NEW_LINE> users = User.objects.exclude(Q(id=int(request.GET['id'])) | Q(username='admin')) <NEW_LINE> structures = Structure.objects.values() <NEW_LINE> roles = Role.objects.values() <NEW_LINE> user_roles = user.roles.values() <NEW_LINE> ret = { 'user': user, 'structures': structures, 'users': users, 'roles': roles, 'user_roles': user_roles } <NEW_LINE> return render(request, 'system/users/user_detail.html', ret)
用户详情视图
62598fe050812a4eaa620f0f
class Node(object): <NEW_LINE> <INDENT> def __init__(self, value=None): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.next = None <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.value)
Defines a class for Queue Node
62598fe0fbf16365ca79471f
class Repository: <NEW_LINE> <INDENT> def __init__(self, root=None, *args, **kwargs): <NEW_LINE> <INDENT> self.root = root <NEW_LINE> self.config = confutils.ConfigFile() <NEW_LINE> self.actions_config = self.config.section_view('actions') <NEW_LINE> self.files_config = self.config.section_view('files', True) <NEW_LINE> self.categories_config = self.config.section_view('categories', True) <NEW_LINE> self.category_rules = [] <NEW_LINE> self.file_rules = [] <NEW_LINE> self.file_configs = GlobStore() <NEW_LINE> self.rule_lexer = rule_parser.RuleLexer() <NEW_LINE> self.action_lexer = action_parser.ActionLexer() <NEW_LINE> self._read_config() <NEW_LINE> <DEDENT> @property <NEW_LINE> def uconf_dir(self): <NEW_LINE> <INDENT> return os.path.join(self.root, constants.REPO_SUBFOLDER) <NEW_LINE> <DEDENT> @property <NEW_LINE> def config_path(self): <NEW_LINE> <INDENT> return os.path.join(self.uconf_dir, 'config') <NEW_LINE> <DEDENT> def extract(self, initial): <NEW_LINE> <INDENT> view = RepositoryView(self) <NEW_LINE> view.set_initial_categories(initial) <NEW_LINE> return view <NEW_LINE> <DEDENT> def write_config(self, fs): <NEW_LINE> <INDENT> temp_name = '.config-%s.new' % time.strftime('%Y%m%d%H%M%S') <NEW_LINE> temp_path = os.path.join(self.uconf_dir, temp_name) <NEW_LINE> with fs.open(temp_path, 'wt') as f: <NEW_LINE> <INDENT> self.config.write(f) <NEW_LINE> <DEDENT> fs.rename(temp_path, self.config_path) <NEW_LINE> <DEDENT> def _read_config(self): <NEW_LINE> <INDENT> if not self.root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.config.parse_file(self.config_path, skip_unreadable=False) <NEW_LINE> self._read_category_rules(self.categories_config) <NEW_LINE> self._read_file_rules(self.files_config) <NEW_LINE> self._read_file_actions(self.actions_config) <NEW_LINE> <DEDENT> def _read_category_rules(self, rules): <NEW_LINE> <INDENT> for rule_text, extra_categories in rules.items(): <NEW_LINE> <INDENT> rule = self.rule_lexer.get_rule(rule_text) <NEW_LINE> self.category_rules.append((rule, helpers.flatten(extra_categories))) <NEW_LINE> <DEDENT> <DEDENT> def _read_file_rules(self, rules): <NEW_LINE> <INDENT> for rule_text, filenames in rules.items(): <NEW_LINE> <INDENT> rule = self.rule_lexer.get_rule(rule_text) <NEW_LINE> for filename in helpers.flatten(filenames, ' '): <NEW_LINE> <INDENT> self.file_rules.append((rule, filename)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _read_file_actions(self, actions): <NEW_LINE> <INDENT> for filename, action_text in actions.items(): <NEW_LINE> <INDENT> action_parts = action_text.strip().split(' ', 1) <NEW_LINE> action = action_parts.pop(0) <NEW_LINE> if action_parts: <NEW_LINE> <INDENT> option_text = action_parts[0] <NEW_LINE> options = self.action_lexer.get_options(option_text) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> options = {} <NEW_LINE> <DEDENT> self.file_configs[filename] = FileConfig(action, **options)
Holds repository configuration. Attributes: categories (str set): all categories files (str list): all managed files file_actions (dict(str => FileConfig)): actions for files rule_lexer (rule_parser.RuleLexer): lexer to use for rule parsing
62598fe0187af65679d29f25
class PageBlockTable(Object): <NEW_LINE> <INDENT> ID = 0xbf4dea82 <NEW_LINE> def __init__(self, title, rows: list, bordered: bool = None, striped: bool = None): <NEW_LINE> <INDENT> self.bordered = bordered <NEW_LINE> self.striped = striped <NEW_LINE> self.title = title <NEW_LINE> self.rows = rows <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "PageBlockTable": <NEW_LINE> <INDENT> flags = Int.read(b) <NEW_LINE> bordered = True if flags & (1 << 0) else False <NEW_LINE> striped = True if flags & (1 << 1) else False <NEW_LINE> title = Object.read(b) <NEW_LINE> rows = Object.read(b) <NEW_LINE> return PageBlockTable(title, rows, bordered, striped) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> flags = 0 <NEW_LINE> flags |= (1 << 0) if self.bordered is not None else 0 <NEW_LINE> flags |= (1 << 1) if self.striped is not None else 0 <NEW_LINE> b.write(Int(flags)) <NEW_LINE> b.write(self.title.write()) <NEW_LINE> b.write(Vector(self.rows)) <NEW_LINE> return b.getvalue()
Attributes: ID: ``0xbf4dea82`` Args: title: Either :obj:`TextEmpty <pyrogram.api.types.TextEmpty>`, :obj:`TextPlain <pyrogram.api.types.TextPlain>`, :obj:`TextBold <pyrogram.api.types.TextBold>`, :obj:`TextItalic <pyrogram.api.types.TextItalic>`, :obj:`TextUnderline <pyrogram.api.types.TextUnderline>`, :obj:`TextStrike <pyrogram.api.types.TextStrike>`, :obj:`TextFixed <pyrogram.api.types.TextFixed>`, :obj:`TextUrl <pyrogram.api.types.TextUrl>`, :obj:`TextEmail <pyrogram.api.types.TextEmail>`, :obj:`TextConcat <pyrogram.api.types.TextConcat>`, :obj:`TextSubscript <pyrogram.api.types.TextSubscript>`, :obj:`TextSuperscript <pyrogram.api.types.TextSuperscript>`, :obj:`TextMarked <pyrogram.api.types.TextMarked>`, :obj:`TextPhone <pyrogram.api.types.TextPhone>`, :obj:`TextImage <pyrogram.api.types.TextImage>` or :obj:`TextAnchor <pyrogram.api.types.TextAnchor>` rows: List of :obj:`PageTableRow <pyrogram.api.types.PageTableRow>` bordered (optional): ``bool`` striped (optional): ``bool``
62598fe026238365f5fad1c3
class RandomKeyError(PotteryError, RuntimeError): <NEW_LINE> <INDENT> pass
Can't create a random Redis key; all of our attempts already exist.
62598fe0d8ef3951e32c818c
class NonAsciiUnicodeDictationTestCase(ElementTestCase): <NEW_LINE> <INDENT> def _build_element(self): <NEW_LINE> <INDENT> def value_func(node, extras): <NEW_LINE> <INDENT> return text_type(extras["text"]) <NEW_LINE> <DEDENT> return Compound("test <text>", extras=[Dictation(name="text")], value_func=value_func) <NEW_LINE> <DEDENT> input_output = [ (u"test DICTATION", u"dictation"), (u"test TOUCHÉ", u"touché"), (u"test JALAPEÑO", u"jalapeño"), ]
Verify handling of non-ASCII characters in unicode dictation.
62598fe0ab23a570cc2d509f
class UserProfileSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = models.UserProfile <NEW_LINE> fields = ('id','email','name','password') <NEW_LINE> extra_kwargs = { 'password':{ 'write_only' :True, 'style':{'input_type':'password'} } } <NEW_LINE> <DEDENT> def create(self,validated_data): <NEW_LINE> <INDENT> user = models.UserProfile.objects.create_user( email=validated_data['email'], name=validated_data['name'], password=validated_data['password'] ) <NEW_LINE> return user <NEW_LINE> <DEDENT> def update(self,instance,validated_data): <NEW_LINE> <INDENT> if 'password' in validated_data: <NEW_LINE> <INDENT> password = validated_data.pop('password') <NEW_LINE> instance.set_password(password) <NEW_LINE> <DEDENT> return super().update(instance,validated_data)
Serializes a user profile object
62598fe04c3428357761a910
class ContainerRegistryManagementClientConfiguration(Configuration): <NEW_LINE> <INDENT> def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> super(ContainerRegistryManagementClientConfiguration, self).__init__(**kwargs) <NEW_LINE> if credential is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'credential' must not be None.") <NEW_LINE> <DEDENT> if subscription_id is None: <NEW_LINE> <INDENT> raise ValueError("Parameter 'subscription_id' must not be None.") <NEW_LINE> <DEDENT> self.credential = credential <NEW_LINE> self.subscription_id = subscription_id <NEW_LINE> self.api_version = "2021-09-01" <NEW_LINE> self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) <NEW_LINE> kwargs.setdefault('sdk_moniker', 'mgmt-containerregistry/{}'.format(VERSION)) <NEW_LINE> self._configure(**kwargs) <NEW_LINE> <DEDENT> def _configure( self, **kwargs: Any ) -> None: <NEW_LINE> <INDENT> self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) <NEW_LINE> self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) <NEW_LINE> self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) <NEW_LINE> self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) <NEW_LINE> self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs) <NEW_LINE> self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) <NEW_LINE> self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) <NEW_LINE> self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) <NEW_LINE> self.authentication_policy = kwargs.get('authentication_policy') <NEW_LINE> if self.credential and not self.authentication_policy: <NEW_LINE> <INDENT> self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
Configuration for ContainerRegistryManagementClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Microsoft Azure subscription ID. :type subscription_id: str
62598fe0d8ef3951e32c818d
class query_result: <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.LIST, b'success', (TType.STRUCT,(Property, Property.thrift_spec)), None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.success = [] <NEW_LINE> (_etype45, _size42) = iprot.readListBegin() <NEW_LINE> for _i46 in range(_size42): <NEW_LINE> <INDENT> _elem47 = Property() <NEW_LINE> _elem47.read(iprot) <NEW_LINE> self.success.append(_elem47) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin(b'query_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin(b'success', TType.LIST, 0) <NEW_LINE> oprot.writeListBegin(TType.STRUCT, len(self.success)) <NEW_LINE> for iter48 in self.success: <NEW_LINE> <INDENT> iter48.write(oprot) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - success
62598fe0091ae3566870527f
class Address(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def address_factory(addr): <NEW_LINE> <INDENT> split = addr.split(':', 1) <NEW_LINE> if 'pipe' == split[0]: <NEW_LINE> <INDENT> addressObj = _AbstractPipeAddress._factory(addr, split) <NEW_LINE> <DEDENT> elif 'tcp' == split[0]: <NEW_LINE> <INDENT> addressObj = TcpAddress._factory(addr, split) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise UnknownProtocolException(addr, split[0]) <NEW_LINE> <DEDENT> return addressObj <NEW_LINE> <DEDENT> def listen(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for a addressable endpoint. This class can create the underlying sockets as needed based on the communication endpoint type.
62598fe0ad47b63b2c5a7eb3
class EvolinoSubMutation(SimpleMutation): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> SimpleMutation.__init__(self) <NEW_LINE> ap = KWArgsProcessor(self, kwargs) <NEW_LINE> ap.add('mutationVariate', default=CauchyVariate()) <NEW_LINE> self.mutationVariate.alpha = 0.001
Mutation operator for EvolinoSubPopulation objects. Like SimpleMutation, except, that CauchyVariate is used by default.
62598fe04c3428357761a912
class JarRules(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def skip_signatures_and_duplicates_concat_well_known_metadata(cls, default_dup_action=None, additional_rules=None): <NEW_LINE> <INDENT> default_dup_action = Duplicate.validate_action(default_dup_action or Duplicate.SKIP) <NEW_LINE> additional_rules = assert_list(additional_rules, expected_type=(Duplicate, Skip)) <NEW_LINE> rules = [Skip(r'^META-INF/[^/]+\.SF$'), Skip(r'^META-INF/[^/]+\.DSA$'), Skip(r'^META-INF/[^/]+\.RSA$'), Duplicate(r'^META-INF/services/', Duplicate.CONCAT)] <NEW_LINE> return cls(rules=rules + additional_rules, default_dup_action=default_dup_action) <NEW_LINE> <DEDENT> _DEFAULT = None <NEW_LINE> @classmethod <NEW_LINE> def default(cls): <NEW_LINE> <INDENT> if cls._DEFAULT is None: <NEW_LINE> <INDENT> cls._DEFAULT = cls.skip_signatures_and_duplicates_concat_well_known_metadata() <NEW_LINE> <DEDENT> return cls._DEFAULT <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def set_default(cls, rules): <NEW_LINE> <INDENT> if not isinstance(rules, JarRules): <NEW_LINE> <INDENT> raise ValueError('The default rules must be a JarRules instance.') <NEW_LINE> <DEDENT> cls._DEFAULT = rules <NEW_LINE> <DEDENT> def __init__(self, rules=None, default_dup_action=Duplicate.SKIP): <NEW_LINE> <INDENT> self._default_dup_action = Duplicate.validate_action(default_dup_action) <NEW_LINE> self._rules = assert_list(rules, expected_type=JarRule) <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_dup_action(self): <NEW_LINE> <INDENT> return self._default_dup_action <NEW_LINE> <DEDENT> @property <NEW_LINE> def rules(self): <NEW_LINE> <INDENT> return self._rules
A set of rules for packaging up a deploy jar. Deploy jars are executable jars with fully self-contained classpaths and as such, assembling them presents problems given jar semantics. One issue is signed jars that must be included on the classpath. These have a signature that depends on the jar contents and assembly of the deploy jar changes the content of the jar, breaking the signatures. For cases like these the signed jars must be verified and then the signature information thrown away. The :ref:`Skip <bdict_Skip>` rule supports this sort of issue by allowing outright entry exclusion in the final deploy jar. Another issue is duplicate jar entries. Although the underlying zip format supports these, the java jar tool and libraries do not. As such some action must be taken for each duplicate entry such that there are no duplicates in the final deploy jar. The four :ref:`Duplicate <bdict_Duplicate>` rules support resolution of these cases by allowing 1st wins, last wins, concatenation of the duplicate entry contents or raising an exception.
62598fe0d8ef3951e32c818e
class AvailableProducts(enum.IntEnum): <NEW_LINE> <INDENT> JUMPER = 1 <NEW_LINE> T_SHIRT = 2 <NEW_LINE> SOCKS = 3 <NEW_LINE> JEANS = 4
Class of available products.
62598fe0fbf16365ca794727
class Libro(models.Model): <NEW_LINE> <INDENT> nombre = models.CharField(max_length=50) <NEW_LINE> fecha = models.DateField()
docstring for Libro.
62598fe0d8ef3951e32c818f
class Str(Variable): <NEW_LINE> <INDENT> def __init__(self, default_value='', iotype=None, desc=None, **metadata): <NEW_LINE> <INDENT> if not isinstance(default_value, str): <NEW_LINE> <INDENT> raise ValueError("Default value for a Str must be a string") <NEW_LINE> <DEDENT> if iotype is not None: <NEW_LINE> <INDENT> metadata['iotype'] = iotype <NEW_LINE> <DEDENT> if desc is not None: <NEW_LINE> <INDENT> metadata['desc'] = desc <NEW_LINE> <DEDENT> self._validator = Enthought_Str(default_value=default_value, **metadata) <NEW_LINE> super(Str, self).__init__(default_value=default_value, **metadata) <NEW_LINE> <DEDENT> def validate(self, obj, name, value): <NEW_LINE> <INDENT> return self._validator.validate(obj, name, value)
A variable wrapper for a string variable.
62598fe0187af65679d29f29
class ConohaProviderTests(TestCase, IntegrationTestsV2): <NEW_LINE> <INDENT> provider_name = "conoha" <NEW_LINE> domain = "narusejun.com" <NEW_LINE> def _test_parameters_overrides(self): <NEW_LINE> <INDENT> return {"auth_region": "tyo1"} <NEW_LINE> <DEDENT> def _test_fallback_fn(self): <NEW_LINE> <INDENT> return lambda x: None if x in ("priority") else "placeholder_" + x <NEW_LINE> <DEDENT> def _filter_post_data_parameters(self): <NEW_LINE> <INDENT> return ["auth"] <NEW_LINE> <DEDENT> def _filter_headers(self): <NEW_LINE> <INDENT> return ["X-Auth-Token"]
TestCase for Conoha
62598fe1ad47b63b2c5a7eb7
class InputStack(jsl.Document): <NEW_LINE> <INDENT> class Options: <NEW_LINE> <INDENT> description = "Input stack for generating recommendations" <NEW_LINE> definition_id = "input_stack" <NEW_LINE> <DEDENT> appstack_id = jsl.StringField(required=True) <NEW_LINE> uri = jsl.StringField(required=True)
Class with the schema definition based on JSL domain specific language.
62598fe126238365f5fad1cb
class Writer(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> async def flush(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def write_candles(self, candles): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def write_ticks(self, ticks): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def write_order_updates(self, updates, *, order_book): <NEW_LINE> <INDENT> raise NotImplementedError
A write handle to market history data :ivar int newest_timestamp: Number of seconds between the Epoch and the most recent data written.
62598fe1c4546d3d9def75b9
class HcDriverInfoItem(ManagedObject): <NEW_LINE> <INDENT> consts = HcDriverInfoItemConsts() <NEW_LINE> naming_props = set([u'id']) <NEW_LINE> mo_meta = MoMeta("HcDriverInfoItem", "hcDriverInfoItem", "driver-[id]", VersionMeta.Version151a, "InputOutput", 0x1ff, [], ["admin"], [u'hcHolder'], [], [None]) <NEW_LINE> prop_meta = { "adapter_pid": MoPropertyMeta("adapter_pid", "adapterPid", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x2, 0, 510, None, [], []), "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "id": MoPropertyMeta("id", "id", "string", VersionMeta.Version151a, MoPropertyMeta.NAMING, 0x8, 1, 510, None, [], []), "protocol": MoPropertyMeta("protocol", "protocol", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x10, 0, 510, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x20, 0, 256, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x40, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), "vendor": MoPropertyMeta("vendor", "vendor", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x80, 0, 510, None, [], []), "version": MoPropertyMeta("version", "version", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x100, 0, 510, None, [], []), } <NEW_LINE> prop_map = { "adapterPid": "adapter_pid", "childAction": "child_action", "dn": "dn", "id": "id", "protocol": "protocol", "rn": "rn", "status": "status", "vendor": "vendor", "version": "version", } <NEW_LINE> def __init__(self, parent_mo_or_dn, id, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.id = id <NEW_LINE> self.adapter_pid = None <NEW_LINE> self.child_action = None <NEW_LINE> self.protocol = None <NEW_LINE> self.status = None <NEW_LINE> self.vendor = None <NEW_LINE> self.version = None <NEW_LINE> ManagedObject.__init__(self, "HcDriverInfoItem", parent_mo_or_dn, **kwargs)
This is HcDriverInfoItem class.
62598fe150812a4eaa620f15
class Figure: <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def move(figure, point): <NEW_LINE> <INDENT> figure.x = point.x <NEW_LINE> figure.y = point.y <NEW_LINE> <DEDENT> def square(self): <NEW_LINE> <INDENT> pass <NEW_LINE> print('У абстрактной фигуры нет площади')
Документация for Figure
62598fe1fbf16365ca79472c
class ModifyAlert(graphene.Mutation): <NEW_LINE> <INDENT> class Arguments: <NEW_LINE> <INDENT> input_object = ModifyAlertInput( required=True, name='input', description="Input ObjectType for modifying an alert", ) <NEW_LINE> <DEDENT> ok = graphene.Boolean( description="True on success. Otherwise the response contains an error" ) <NEW_LINE> @staticmethod <NEW_LINE> @require_authentication <NEW_LINE> def mutate(_root, info, input_object): <NEW_LINE> <INDENT> gmp = get_gmp(info) <NEW_LINE> if input_object.event_data is not None: <NEW_LINE> <INDENT> event_data = append_alert_event_data( input_object.event, input_object.event_data ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> event_data = None <NEW_LINE> <DEDENT> if input_object.method_data is not None: <NEW_LINE> <INDENT> method_data = append_alert_method_data( input_object.method, input_object.method_data, report_formats=input_object.report_formats, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> method_data = None <NEW_LINE> <DEDENT> if input_object.condition_data is not None: <NEW_LINE> <INDENT> condition_data = append_alert_condition_data( input_object.condition, input_object.condition_data ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> condition_data = None <NEW_LINE> <DEDENT> if input_object.filter_id is not None: <NEW_LINE> <INDENT> filter_id = str(input_object.filter_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filter_id = None <NEW_LINE> <DEDENT> gmp.modify_alert( alert_id=str(input_object.alert_id), name=input_object.name, condition=get_alert_condition_from_string(input_object.condition), event=get_alert_event_from_string(input_object.event), method=get_alert_method_from_string(input_object.method), comment=input_object.comment, method_data=method_data, condition_data=condition_data, event_data=event_data, filter_id=filter_id, ) <NEW_LINE> return ModifyAlert(ok=True)
Modify an alert
62598fe14c3428357761a918