code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Open: <NEW_LINE> <INDENT> def __init__(self, search_strategy): <NEW_LINE> <INDENT> if search_strategy == _DEPTH_FIRST: <NEW_LINE> <INDENT> self.open = [] <NEW_LINE> self.insert = self.open.append <NEW_LINE> self.extract = self.open.pop <NEW_LINE> <DEDENT> elif search_strategy == _BREADTH_FIRST: <NEW_LINE> <INDENT> self.open = deque() <NEW_LINE> self.insert = self.open.append <NEW_LINE> self.extract = self.open.popleft <NEW_LINE> <DEDENT> elif search_strategy == _BEST_FIRST: <NEW_LINE> <INDENT> self.open = [] <NEW_LINE> sNode.lt_type = _H <NEW_LINE> self.insert = lambda node: heapq.heappush(self.open, node) <NEW_LINE> self.extract = lambda: heapq.heappop(self.open) <NEW_LINE> <DEDENT> elif search_strategy == _ASTAR: <NEW_LINE> <INDENT> self.open = [] <NEW_LINE> sNode.lt_type = _SUM_HG <NEW_LINE> self.insert = lambda node: heapq.heappush(self.open, node) <NEW_LINE> self.extract = lambda: heapq.heappop(self.open) <NEW_LINE> <DEDENT> <DEDENT> def empty(self): return not self.open <NEW_LINE> def print_open(self): <NEW_LINE> <INDENT> print("{", end="") <NEW_LINE> if len(self.open) == 1: <NEW_LINE> <INDENT> print(" <S{}:{}:{}, g={}, h={}, f=g+h={}>".format(self.open[0].state.index, self.open[0].state.action, self.open[0].state.hashable_state(), self.open[0].gval, self.open[0].hval, self.open[0].gval+self.open[0].hval), end="") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for nd in self.open: <NEW_LINE> <INDENT> print(" <S{}:{}:{}, g={}, h={}, f=g+h={}>".format(nd.state.index, nd.state.action, nd.state.hashable_state(), nd.gval, nd.hval, nd.gval+nd.hval), end="") <NEW_LINE> <DEDENT> <DEDENT> print("}") <NEW_LINE> <DEDENT> def get_length(self): <NEW_LINE> <INDENT> return len(self.open)
Open objects hold the search frontier---the set of unexpanded nodes. Depending on the search strategy used we want to extract nodes from this set in different orders, so set up the object's functions to operate as needed by the particular search strategy
625990448da39b475be04514
class IntrinsicPredictor(nn.Module): <NEW_LINE> <INDENT> def __init__(self, d_model, action_dim, dropout=0.0): <NEW_LINE> <INDENT> super(IntrinsicPredictor, self).__init__() <NEW_LINE> self.dropout = nn.Dropout(dropout) <NEW_LINE> self.intrinsic_predict_FFN1 = nn.Linear(d_model+action_dim, d_model) <NEW_LINE> self.intrinsic_predict_FFN2 = nn.Linear(d_model, d_model) <NEW_LINE> self.mse = nn.MSELoss() <NEW_LINE> self.reconstruct_action_FFN1 = nn.Linear(d_model*2, d_model) <NEW_LINE> self.reconstruct_action_FFN2 = nn.Linear(d_model, action_dim) <NEW_LINE> self._reset_parameters() <NEW_LINE> <DEDENT> def _reset_paramters(self): <NEW_LINE> <INDENT> my_init.default_init(self.intrinsic_predict_FFN1.weight) <NEW_LINE> my_init.default_init(self.intrinsic_predict_FFN2.weight) <NEW_LINE> my_init.default_init(self.reconstruct_action_FFN1.weight) <NEW_LINE> my_init.default_init(self.reconstruct_action_FFN2.weight) <NEW_LINE> <DEDENT> def forward(self, rephrase_feature, next_rephrase_feature, action, beta=0.2): <NEW_LINE> <INDENT> predicted_feature = torch.cat([rephrase_feature, action], dim=-1) <NEW_LINE> predicted_feature = F.relu(self.intrinsic_predict_FFN1(predicted_feature)) <NEW_LINE> predicted_feature = self.intrinsic_predict_FFN2(predicted_feature) <NEW_LINE> predict_loss = self.mse(predicted_feature, next_rephrase_feature) <NEW_LINE> reconstructed_action = torch.cat([rephrase_feature, next_rephrase_feature], dim=-1) <NEW_LINE> reconstructed_action = F.relu(self.reconstruct_action_FFN1(reconstructed_action)) <NEW_LINE> reconstructed_action = self.reconstruct_action_FFN2(reconstructed_action) <NEW_LINE> reconstruct_loss = self.mse(reconstructed_action, action) <NEW_LINE> loss = beta * predict_loss + (1-beta) * reconstruct_loss <NEW_LINE> return loss <NEW_LINE> <DEDENT> def get_surprise_bonus(self, rephrase_feature, next_rephrase_feature, action): <NEW_LINE> <INDENT> predicted_feature = torch.cat([rephrase_feature, action], dim=-1) <NEW_LINE> predicted_feature = F.relu(self.intrinsic_predict_FFN1(predicted_feature)) <NEW_LINE> predicted_feature = self.intrinsic_predict_FFN2(predicted_feature) <NEW_LINE> surprise_bonus = (0.5*(predicted_feature - next_rephrase_feature)**2).mean(dim=-1, keepdims=True) <NEW_LINE> return surprise_bonus
the intrinsic predictor provides intrinsic rewards **in the agent** (a multi-task modeling). the predictor is also a self-supervised module.
62599045d4950a0f3b1117d4
class Log(BaseAPIObject): <NEW_LINE> <INDENT> IDNAME = 'log_id' <NEW_LINE> PATH = ['job', 'log'] <NEW_LINE> SUBPATH = ['log'] <NEW_LINE> id = None <NEW_LINE> name = None <NEW_LINE> type = None <NEW_LINE> format = None <NEW_LINE> content = None
The 'Log' object from the API
62599045baa26c4b54d505cf
class _Comparison: <NEW_LINE> <INDENT> default_message = __("Comparison failed") <NEW_LINE> def __init__(self, fieldname: str, message: str = None) -> None: <NEW_LINE> <INDENT> self.fieldname = fieldname <NEW_LINE> self.message = message or self.default_message <NEW_LINE> <DEDENT> def __call__(self, form, field) -> None: <NEW_LINE> <INDENT> other = form[self.fieldname] <NEW_LINE> if not self.compare(field.data, other.data): <NEW_LINE> <INDENT> d = { 'other_label': hasattr(other, 'label') and other.label.text or self.fieldname, 'other_name': self.fieldname, } <NEW_LINE> raise ValidationError(self.message.format(**d)) <NEW_LINE> <DEDENT> <DEDENT> def compare(self, value, other) -> bool: <NEW_LINE> <INDENT> raise NotImplementedError(_("Subclasses must define ``compare``"))
Base class for validators that compare this field's value with another field.
6259904510dbd63aa1c71eff
class MyTopo( Topo ): <NEW_LINE> <INDENT> def __init__( self ): <NEW_LINE> <INDENT> Topo.__init__( self ) <NEW_LINE> sw1 = self.addSwitch( 's1' ) <NEW_LINE> h1 = self.addHost( 'h1', ip='100.0.0.10/24' ) <NEW_LINE> h2 = self.addHost( 'h2', ip='100.0.0.11/24' ) <NEW_LINE> fw1 = self.addSwitch( 's2' ) <NEW_LINE> sw2 = self.addSwitch( 's3' ) <NEW_LINE> lb1 = self.addSwitch( 's4' ) <NEW_LINE> sw3 = self.addSwitch( 's5' ) <NEW_LINE> ids = self.addSwitch( 's6' ) <NEW_LINE> insp = self.addHost( 'h11', ip='100.0.0.30/24' ) <NEW_LINE> lb2 = self.addSwitch( 's7' ) <NEW_LINE> sw4 = self.addSwitch( 's8' ) <NEW_LINE> ds1 = self.addHost( 'h5', ip='100.0.0.20/24' ) <NEW_LINE> ds2 = self.addHost( 'h6', ip='100.0.0.21/24' ) <NEW_LINE> ds3 = self.addHost( 'h7', ip='100.0.0.22/24' ) <NEW_LINE> ws1 = self.addHost( 'h8', ip='100.0.0.40/24' ) <NEW_LINE> ws2 = self.addHost( 'h9', ip='100.0.0.41/24' ) <NEW_LINE> ws3 = self.addHost( 'h10', ip='100.0.0.42/24' ) <NEW_LINE> fw2 = self.addSwitch( 's9' ) <NEW_LINE> napt = self.addSwitch( 's10' ) <NEW_LINE> sw5 = self.addSwitch( 's11' ) <NEW_LINE> h3 = self.addHost( 'h3', ip='10.0.0.50/24' ) <NEW_LINE> h4 = self.addHost( 'h4', ip='10.0.0.51/24' ) <NEW_LINE> self.addLink( h1, sw1 ) <NEW_LINE> self.addLink( h2, sw1 ) <NEW_LINE> self.addLink( fw1, sw1 ) <NEW_LINE> self.addLink( fw1, sw2 ) <NEW_LINE> self.addLink( sw2, lb1 ) <NEW_LINE> self.addLink( sw3, lb1 ) <NEW_LINE> self.addLink( sw2, ids ) <NEW_LINE> self.addLink( ids, lb2 ) <NEW_LINE> self.addLink( ids, insp ) <NEW_LINE> self.addLink( lb2, sw4 ) <NEW_LINE> self.addLink( sw3, ds1 ) <NEW_LINE> self.addLink( sw3, ds2 ) <NEW_LINE> self.addLink( sw3, ds3 ) <NEW_LINE> self.addLink( sw4, ws1 ) <NEW_LINE> self.addLink( sw4, ws2 ) <NEW_LINE> self.addLink( sw4, ws3 ) <NEW_LINE> self.addLink( sw2, fw2 ) <NEW_LINE> self.addLink( fw2, napt ) <NEW_LINE> self.addLink( napt, sw5 ) <NEW_LINE> self.addLink( sw5, h3 ) <NEW_LINE> self.addLink( sw5, h4 )
Simple topology example.
62599045d7e4931a7ef3d39d
class IRating(zope.interface.Interface): <NEW_LINE> <INDENT> id = zope.schema.TextLine( title=u'Id', description=u'The id of the rating used.', required=True) <NEW_LINE> value = zope.schema.Object( title=u'Value', description=u'A scoresystem-valid score that represents the rating.', schema=zope.interface.Interface, required=True) <NEW_LINE> user = zope.schema.TextLine( title=u'User', description=u'The id of the entity having made the rating.', required=True) <NEW_LINE> timestamp = zope.schema.Datetime( title=u'Timestamp', description=u'The time the rating was given.')
A single rating for a definition and user.
6259904526068e7796d4dc6c
class ObjectMmap(test_mmap.test_mmap): <NEW_LINE> <INDENT> def __init__(self, fileno=-1, length=1024, access=test_mmap.ACCESS_WRITE, tagname='share_mmap'): <NEW_LINE> <INDENT> super(ObjectMmap, self).__init__(self, fileno, length, access=access, tagname=tagname) <NEW_LINE> self.length = length <NEW_LINE> self.access = access <NEW_LINE> self.tagname = tagname <NEW_LINE> <DEDENT> def jsonwrite(self, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.obj = obj <NEW_LINE> self.seek(0) <NEW_LINE> obj_str = json.dumps(obj) <NEW_LINE> obj_len = len(obj_str) <NEW_LINE> content = str(obj_len) + ":" + obj_str <NEW_LINE> self.write(content) <NEW_LINE> self.contentbegin = len(str(obj_len)) + 1 <NEW_LINE> self.contentend = self.tell() <NEW_LINE> self.contentlength = self.contentend - self.contentbegin <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def jsonread_master(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.seek(self.contentbegin) <NEW_LINE> content = self.read(self.contentlength) <NEW_LINE> obj = json.loads(content) <NEW_LINE> self.obj = obj <NEW_LINE> return obj <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if self.obj: <NEW_LINE> <INDENT> return self.obj <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def jsonread_follower(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.seek(0) <NEW_LINE> index = self.find(":") <NEW_LINE> if index != -1: <NEW_LINE> <INDENT> head = self.read(index + 1) <NEW_LINE> contentlength = int(head[:-1]) <NEW_LINE> content = self.read(contentlength) <NEW_LINE> obj = json.loads(content) <NEW_LINE> self.obj = obj <NEW_LINE> return obj <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if self.obj: <NEW_LINE> <INDENT> return self.obj <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None
:param fileno: the file handle :param length: memory size :param access: :param tagname:
6259904523e79379d538d824
class TestValidator(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.config = configurator.Config() <NEW_LINE> self.test = validator.Validator() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.config.__init__() <NEW_LINE> <DEDENT> def test_check_values_true(self): <NEW_LINE> <INDENT> actual = self.test.check_values() <NEW_LINE> expected = True <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_check_values_false(self): <NEW_LINE> <INDENT> with open(strings.get_config_path(), "w") as file: <NEW_LINE> <INDENT> file.write("More nonsense.") <NEW_LINE> <DEDENT> actual = self.test.check_values() <NEW_LINE> expected = False <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_check_keys_true(self): <NEW_LINE> <INDENT> actual = self.test.check_keys() <NEW_LINE> expected = True <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_check_keys_false(self): <NEW_LINE> <INDENT> with open(strings.get_config_path(), "w") as file: <NEW_LINE> <INDENT> file.write("More nonsense.") <NEW_LINE> <DEDENT> actual = self.test.check_keys() <NEW_LINE> expected = False <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_check_config_true(self): <NEW_LINE> <INDENT> actual = self.test.check_config() <NEW_LINE> expected = True <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_check_config_false(self): <NEW_LINE> <INDENT> with open(strings.get_config_path(), "w") as file: <NEW_LINE> <INDENT> file.write("More nonsense.") <NEW_LINE> <DEDENT> actual = self.test.check_config() <NEW_LINE> expected = False <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> os.remove(strings.get_config_path()) <NEW_LINE> actual = self.test.check_config() <NEW_LINE> expected = False <NEW_LINE> self.assertEqual(expected, actual)
Class which contains methods for testing the validator.py module.
625990454e696a045264e7b4
class Kdump(CommandDispatcher): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__('kdump', [VmPhysSeg(), VmFreePages(), VmMapSeg(), PhysMap()])
Examine kernel data structures.
62599045b57a9660fecd2da3
class docker_event(Event): <NEW_LINE> <INDENT> pass
Docker Event
62599045d10714528d69f020
class Literal(Formula): <NEW_LINE> <INDENT> def __init__(self, lit): <NEW_LINE> <INDENT> self.lit = lit <NEW_LINE> <DEDENT> def __str__(self, parens = False): <NEW_LINE> <INDENT> return str(self.lit) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.lit) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, Literal) and self.lit == other.lit <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self.__eq__(other) <NEW_LINE> <DEDENT> def evaluate(self, values): <NEW_LINE> <INDENT> return values[self.lit] <NEW_LINE> <DEDENT> def simplify(self): <NEW_LINE> <INDENT> return self
The class for boolean literals (variables).
62599045462c4b4f79dbcd25
@PRE_PYTEST_SKIP <NEW_LINE> class CloudClientTestCase(CloudTest): <NEW_LINE> <INDENT> PROVIDER = "digitalocean" <NEW_LINE> REQUIRED_PROVIDER_CONFIG_ITEMS = tuple() <NEW_LINE> IMAGE_NAME = "14.04.5 x64" <NEW_LINE> @pytest.mark.expensive_test <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> images = self.run_cloud("--list-images {}".format(self.PROVIDER)) <NEW_LINE> if self.image_name not in [i.strip() for i in images]: <NEW_LINE> <INDENT> self.skipTest( "Image '{}' was not found in image search. Is the {} provider " "configured correctly for this test?".format( self.PROVIDER, self.image_name ) ) <NEW_LINE> <DEDENT> <DEDENT> def test_cloud_client_create_and_delete(self): <NEW_LINE> <INDENT> cloud_client = salt.cloud.CloudClient(self.config_file) <NEW_LINE> ret_val = cloud_client.create( provider=self.PROVIDER, names=[self.instance_name], image=self.IMAGE_NAME, location="sfo1", size="512mb", vm_size="512mb", ) <NEW_LINE> self.assertInstanceExists(ret_val) <NEW_LINE> deleted = cloud_client.destroy(names=[self.instance_name]) <NEW_LINE> self.assertIn(self.instance_name, deleted)
Integration tests for the CloudClient class. Uses DigitalOcean as a salt-cloud provider.
62599045ec188e330fdf9bc2
class PNG(Pixmap): <NEW_LINE> <INDENT> gui = {'menu': 'File|Export to pixmap', 'entry': 'PNG'} <NEW_LINE> key = "PNG"
PNG format writer
62599045d6c5a102081e3443
class RawWebSocketTransport(websocket.SockJSWebSocketHandler, base.BaseTransportMixin): <NEW_LINE> <INDENT> name = 'rawwebsocket' <NEW_LINE> def initialize(self, server): <NEW_LINE> <INDENT> self.server = server <NEW_LINE> self.session = None <NEW_LINE> self.active = True <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> self.server.stats.on_conn_opened() <NEW_LINE> if self.server.settings['disable_nagle']: <NEW_LINE> <INDENT> self.set_nodelay(True) <NEW_LINE> <DEDENT> self.session = RawSession(self.server.get_connection_class(), self.server) <NEW_LINE> self.session.set_handler(self) <NEW_LINE> self.session.verify_state() <NEW_LINE> <DEDENT> def _detach(self): <NEW_LINE> <INDENT> if self.session is not None: <NEW_LINE> <INDENT> self.session.remove_handler(self) <NEW_LINE> self.session = None <NEW_LINE> <DEDENT> <DEDENT> def on_message(self, message): <NEW_LINE> <INDENT> if not message or not self.session: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.session.on_message(message) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception('RawWebSocket') <NEW_LINE> self.abort_connection() <NEW_LINE> <DEDENT> <DEDENT> def on_close(self): <NEW_LINE> <INDENT> if self.session is not None: <NEW_LINE> <INDENT> self.server.stats.on_conn_closed() <NEW_LINE> session = self.session <NEW_LINE> self._detach() <NEW_LINE> session.close() <NEW_LINE> <DEDENT> <DEDENT> def send_pack(self, message, binary=False): <NEW_LINE> <INDENT> if IOLoop.current(False) == self.server.io_loop: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.write_message(message, binary).add_done_callback(self.send_complete) <NEW_LINE> <DEDENT> except (IOError, WebSocketError): <NEW_LINE> <INDENT> self.server.io_loop.add_callback(self.on_close) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.server.io_loop.add_callback(lambda: self.send_pack(message, binary)) <NEW_LINE> <DEDENT> <DEDENT> def session_closed(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.close(*self.session.get_close_reason()) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._detach() <NEW_LINE> <DEDENT> <DEDENT> def allow_draft76(self): <NEW_LINE> <INDENT> return True
Raw Websocket transport
6259904526238365f5fade82
class Header: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.last_checked = datetime.datetime.min <NEW_LINE> self.online_status = False <NEW_LINE> self.title = "" <NEW_LINE> self.game = "" <NEW_LINE> self.online_since = None <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if datetime.datetime.now() - self.last_checked > datetime.timedelta(seconds=wizsite.app.config['HEADER_UPDATE_INTERVAL_SECONDS']): <NEW_LINE> <INDENT> self.last_checked = datetime.datetime.now() <NEW_LINE> headers = {'Client-ID': wizsite.app.config['TWITCH_CLIENT_ID']} <NEW_LINE> stream_status = requests.get('{}streams/?user_login={}'.format(base_url, wizsite.app.config['TWITCH_NAME']), headers=headers).json() <NEW_LINE> if not stream_status['data']: <NEW_LINE> <INDENT> self.online_status = False <NEW_LINE> self.title = "" <NEW_LINE> self.game = "" <NEW_LINE> self.online_since = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.online_status = True <NEW_LINE> self.title = stream_status['data']['title'] <NEW_LINE> self.game = stream_status['data']['game_id'] <NEW_LINE> self.online_since = stream_status['data']['started_at']
Object holding online status. Acts as a cache so we don't ping other servers too much.
625990458e05c05ec3f6f7ee
class Mod_Mysql(BaseModule): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> BaseModule.__init__(self, name) <NEW_LINE> self.conf_file = BASE_DIR + self.path + "\my.ini" <NEW_LINE> self.parse_config_file() <NEW_LINE> self.cfg_ctr = {} <NEW_LINE> <DEDENT> def parse_config_file(self): <NEW_LINE> <INDENT> self.content = open(self.conf_file,'r').read() <NEW_LINE> self.cfg = ConfigObj(self.conf_file) <NEW_LINE> <DEDENT> def set_advt_frame(self, parent): <NEW_LINE> <INDENT> self.setting_panel = wx.Panel(parent) <NEW_LINE> self.setting_panel.SetSizer(self.setting_sizer) <NEW_LINE> self.opt_sizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> self.grid_sizer = wx.FlexGridSizer(rows=15, cols=4) <NEW_LINE> for cfg_name in self.cfg['mysqld'].keys(): <NEW_LINE> <INDENT> lbl = wx.StaticText(self.setting_panel, -1, cfg_name) <NEW_LINE> self.cfg_ctr[cfg_name] = txt = wx.TextCtrl(self.setting_panel, -1, self.cfg['mysqld'][cfg_name], size=(200, 20)) <NEW_LINE> self.grid_sizer.Add(lbl, 0, wx.ALL, 5) <NEW_LINE> self.grid_sizer.Add(txt, 0, wx.ALL, 3) <NEW_LINE> <DEDENT> log_btn = wx.Button(self.setting_panel, -1, Lang().get('open_log_file')) <NEW_LINE> log_btn.Bind(wx.EVT_BUTTON, self.open_log_file) <NEW_LINE> conf_btn = wx.Button(self.setting_panel, -1, Lang().get('mysql_config_file')) <NEW_LINE> conf_btn.Bind(wx.EVT_BUTTON, self.open_config_file) <NEW_LINE> console_btn = wx.Button(self.setting_panel, -1, Lang().get('console')) <NEW_LINE> console_btn.Bind(wx.EVT_BUTTON, self.open_console) <NEW_LINE> save_btn = wx.Button(self.setting_panel, -1, Lang().get('save_config')) <NEW_LINE> save_btn.Bind(wx.EVT_BUTTON, self.save_config) <NEW_LINE> self.handler_sizer = wx.BoxSizer(wx.HORIZONTAL) <NEW_LINE> self.handler_sizer.AddMany([ (log_btn), (conf_btn), (console_btn), (save_btn) ]) <NEW_LINE> self.opt_sizer.Add(self.grid_sizer) <NEW_LINE> self.opt_sizer.Add(self.handler_sizer, 0, wx.TOP, 5) <NEW_LINE> self.setting_sizer.Add(self.opt_sizer, 0, wx.ALL, 5) <NEW_LINE> parent.AddPage(self.setting_panel, self.module_name) <NEW_LINE> <DEDENT> def open_log_file(self, event): <NEW_LINE> <INDENT> open_file(self.cfg['mysqld']['log-error']) <NEW_LINE> <DEDENT> def open_config_file(self, event): <NEW_LINE> <INDENT> open_file(self.conf_file) <NEW_LINE> <DEDENT> def save_config(self, event): <NEW_LINE> <INDENT> for cfg_name, ctr in self.cfg_ctr.items(): <NEW_LINE> <INDENT> self.cfg['mysqld'][cfg_name] = ctr.GetValue() <NEW_LINE> <DEDENT> self.cfg.write() <NEW_LINE> <DEDENT> def open_console(self, event): <NEW_LINE> <INDENT> open_cmd(self.path + '\\bin', 'mysql -u root -p')
Mysql模块类
62599045287bf620b6272f0f
class LLO(SCPINode, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "@LLO" <NEW_LINE> args = []
@LLO Arguments:
6259904550485f2cf55dc2ae
class CheckMoneyAccountView(generics.RetrieveAPIView): <NEW_LINE> <INDENT> permission_classes = [TokenHasReadWriteScope | IsAdminUser] <NEW_LINE> required_scopes = ["can_check_if_exist"] <NEW_LINE> queryset = MoneyAccount.objects.all() <NEW_LINE> lookup_field = "slug" <NEW_LINE> serializer_class = MoneyAccountCheckSerializer
Check if MoneyAccount Bank/Api with this slug exists -- is used to communicate with 3rd aplication
6259904594891a1f408ba08a
class GithubReviewRequestTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.valid_request = { 'action': 'review_requested', 'pull_request': { 'html_url': 'https://www.example.com', }, 'sender': { 'login': 'generic-person', }, } <NEW_LINE> <DEDENT> def test_is_valid_pull_request_good(self): <NEW_LINE> <INDENT> is_valid_request = is_valid_pull_request(self.valid_request) <NEW_LINE> self.assertTrue(is_valid_request) <NEW_LINE> <DEDENT> def test_is_valid_pull_request_missing_action(self): <NEW_LINE> <INDENT> with self.assertRaises(BadRequest): <NEW_LINE> <INDENT> data = self.valid_request.copy() <NEW_LINE> del data['action'] <NEW_LINE> is_valid_pull_request(data) <NEW_LINE> <DEDENT> <DEDENT> def test_is_valid_pull_request_missing_pulL_request(self): <NEW_LINE> <INDENT> with self.assertRaises(BadRequest): <NEW_LINE> <INDENT> data = self.valid_request.copy() <NEW_LINE> del data['pull_request'] <NEW_LINE> is_valid_pull_request(data) <NEW_LINE> <DEDENT> <DEDENT> def test_is_valid_pull_request_missing_html_url(self): <NEW_LINE> <INDENT> with self.assertRaises(BadRequest): <NEW_LINE> <INDENT> data = self.valid_request.copy() <NEW_LINE> data['pull_request'] = {} <NEW_LINE> is_valid_pull_request(data) <NEW_LINE> <DEDENT> <DEDENT> def test_is_valid_pull_request_different_action(self): <NEW_LINE> <INDENT> data = self.valid_request.copy() <NEW_LINE> data['action'] = 'generic_action' <NEW_LINE> is_valid_request = is_valid_pull_request(data) <NEW_LINE> self.assertFalse(is_valid_request) <NEW_LINE> <DEDENT> @patch('app.github.IGNORED_USERS', 'ignoreme') <NEW_LINE> def test_is_valid_pull_request_from_ignored_users(self): <NEW_LINE> <INDENT> data = self.valid_request.copy() <NEW_LINE> data['sender']['login'] = 'ignoreme' <NEW_LINE> is_valid_request = is_valid_pull_request(data) <NEW_LINE> self.assertFalse(is_valid_request)
Test the github review request functions.
6259904507f4c71912bb075a
class PTStepperMotor (PTSimpleGPIO): <NEW_LINE> <INDENT> def __init__ (self, p_pinTuple, p_scaling, p_speed, p_accuracy_level): <NEW_LINE> <INDENT> if len (p_pinTuple) == 2: <NEW_LINE> <INDENT> self.task_ptr = ptStepperMotor.stepperMotorFull (p_pinTuple[0], p_pinTuple[1], p_scaling, p_speed, p_accuracy_level) <NEW_LINE> <DEDENT> elif len (p_pinTuple) == 4: <NEW_LINE> <INDENT> self.task_ptr = ptStepperMotor.stepperMotorHalf (p_pinTuple[0], p_pinTuple[1], p_pinTuple[2], p_pinTuple[3], p_scaling, p_speed, p_accuracy_level) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print ('Pins tuple must contain 2 pins for full step mode, or 4 pins for half step mode.') <NEW_LINE> <DEDENT> <DEDENT> def set_scaling (self, p_scaling): <NEW_LINE> <INDENT> ptStepperMotor.setScaling (self.task_ptr, p_scaling) <NEW_LINE> <DEDENT> def set_speed (self, p_speed): <NEW_LINE> <INDENT> ptStepperMotor.setSpeed (self.task_ptr, p_speed) <NEW_LINE> <DEDENT> def set_zero (self): <NEW_LINE> <INDENT> ptStepperMotor.setZero(self.task_ptr) <NEW_LINE> <DEDENT> def move_rel (self, distance): <NEW_LINE> <INDENT> ptStepperMotor.moveRel (self.task_ptr, distance) <NEW_LINE> <DEDENT> def move_abs (self, position): <NEW_LINE> <INDENT> ptStepperMotor.moveAbs (self.task_ptr, position) <NEW_LINE> <DEDENT> def get_scaling (self): <NEW_LINE> <INDENT> return ptStepperMotor.getScaling (self.task_ptr) <NEW_LINE> <DEDENT> def get_speed (self): <NEW_LINE> <INDENT> return ptStepperMotor.getSpeed (self.task_ptr) <NEW_LINE> <DEDENT> def get_position (self): <NEW_LINE> <INDENT> return ptStepperMotor.getPosition (self.task_ptr) <NEW_LINE> <DEDENT> def is_busy (self): <NEW_LINE> <INDENT> return ptStepperMotor.isBusy(self.task_ptr) <NEW_LINE> <DEDENT> def wait_on_busy (self, timeOutSecs): <NEW_LINE> <INDENT> return ptStepperMotor.waitOnBusy (self.task_ptr, timeOutSecs) <NEW_LINE> <DEDENT> def setHold (self, hold): <NEW_LINE> <INDENT> ptStepperMotor.setHold(self.task_ptr, hold)
:param:p_pinTuple is a tuple containing GPIO pin numbers, 2 for full, 4 for half :param:p_scaling is spatial scaling in steps/unit :param:p_speed is speed in units/sec :param:p_accuracy_level method to use for timing, as defined for PTSimpleGPIO
6259904507d97122c4217fc9
class LineStickerDownloadView(TemplateResponseMixin, View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> context = {} <NEW_LINE> context["pack_url"] = pack_url = request.GET.get("url", "") <NEW_LINE> context["pack_meta"] = pack_meta = LineStickerUtils.get_pack_meta_from_url(pack_url) <NEW_LINE> if pack_url and not pack_meta: <NEW_LINE> <INDENT> messages.warning(request, "Unable to get the LINE sticker package ID. " "Check the format of the URL to be parsed.") <NEW_LINE> <DEDENT> return render_template(self.request, _("LINE Sticker Downloader"), "services/linesticker.html", context)
View of LINE sticker downloader UI.
6259904530dc7b76659a0b5a
class MeasuresLocal(MeasuresBase, LocalTask): <NEW_LINE> <INDENT> pass
Measures on local machine
62599045596a897236128f43
class TaskList(TaskMixIn, base.BaseListCommand): <NEW_LINE> <INDENT> columns = ('id', 'status', 'name', 'cluster', 'result', 'progress')
Show list of all avaliable nodes.
625990458e71fb1e983bcdf8
class dm(_dm): <NEW_LINE> <INDENT> alias = 'DM', 'DirectionalMovement' <NEW_LINE> outputs = 'plusdm', 'minusdm' <NEW_LINE> _plus = True <NEW_LINE> _minus = True <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.o.plusdm = self._pdm <NEW_LINE> self.o.minusdm = self._mdm
Defined by J. Welles Wilder, Jr. in 1978 in his book *"New Concepts in Technical Trading Systems"*. Intended to measure trend strength and directionality Formula: - upmove = high - high(-1) - downmove = low(-1) - low - +dm1 = upmove if upmove > downmove and upmove > 0 else 0 - -dm1 = downmove if downmove > upmove and downmove > 0 else 0 - +dm = SmoothAccum(+dm1, period) - -dm = SmoothAccum(-dm1, period) See also: - https://school.stockcharts.com/doku.php?id=technical_indicators:average_directional_index_adx - https://en.wikipedia.org/wiki/Average_directional_movement_index Note: - Although the original definition from Welles Wilder for DirectionalMove does not imply a period, `ta-lib` defines `plus_dm` (+dm) and `minus_dm` (-dm) with a period over which they are accumulted. The accumulation was defined within the scope of the `DirectionalIndicator` (+di, -di) definition.
6259904507d97122c4217fca
class TestScript(domainresource.DomainResource): <NEW_LINE> <INDENT> resource_type = "TestScript" <NEW_LINE> def __init__(self, jsondict=None, strict=True): <NEW_LINE> <INDENT> self.contact = None <NEW_LINE> self.copyright = None <NEW_LINE> self.date = None <NEW_LINE> self.description = None <NEW_LINE> self.destination = None <NEW_LINE> self.experimental = None <NEW_LINE> self.fixture = None <NEW_LINE> self.identifier = None <NEW_LINE> self.jurisdiction = None <NEW_LINE> self.metadata = None <NEW_LINE> self.name = None <NEW_LINE> self.origin = None <NEW_LINE> self.profile = None <NEW_LINE> self.publisher = None <NEW_LINE> self.purpose = None <NEW_LINE> self.setup = None <NEW_LINE> self.status = None <NEW_LINE> self.teardown = None <NEW_LINE> self.test = None <NEW_LINE> self.title = None <NEW_LINE> self.url = None <NEW_LINE> self.useContext = None <NEW_LINE> self.variable = None <NEW_LINE> self.version = None <NEW_LINE> super(TestScript, self).__init__(jsondict=jsondict, strict=strict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(TestScript, self).elementProperties() <NEW_LINE> js.extend([ ("contact", "contact", contactdetail.ContactDetail, True, None, False), ("copyright", "copyright", str, False, None, False), ("date", "date", fhirdate.FHIRDate, False, None, False), ("description", "description", str, False, None, False), ("destination", "destination", TestScriptDestination, True, None, False), ("experimental", "experimental", bool, False, None, False), ("fixture", "fixture", TestScriptFixture, True, None, False), ("identifier", "identifier", identifier.Identifier, False, None, False), ("jurisdiction", "jurisdiction", codeableconcept.CodeableConcept, True, None, False), ("metadata", "metadata", TestScriptMetadata, False, None, False), ("name", "name", str, False, None, True), ("origin", "origin", TestScriptOrigin, True, None, False), ("profile", "profile", fhirreference.FHIRReference, True, None, False), ("publisher", "publisher", str, False, None, False), ("purpose", "purpose", str, False, None, False), ("setup", "setup", TestScriptSetup, False, None, False), ("status", "status", str, False, None, True), ("teardown", "teardown", TestScriptTeardown, False, None, False), ("test", "test", TestScriptTest, True, None, False), ("title", "title", str, False, None, False), ("url", "url", str, False, None, True), ("useContext", "useContext", usagecontext.UsageContext, True, None, False), ("variable", "variable", TestScriptVariable, True, None, False), ("version", "version", str, False, None, False), ]) <NEW_LINE> return js
Describes a set of tests. A structured set of tests against a FHIR server or client implementation to determine compliance against the FHIR specification.
62599045462c4b4f79dbcd27
class AzureWorkloadSAPHanaPointInTimeRecoveryPoint(AzureWorkloadPointInTimeRecoveryPoint): <NEW_LINE> <INDENT> _validation = { 'object_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'object_type': {'key': 'objectType', 'type': 'str'}, 'recovery_point_time_in_utc': {'key': 'recoveryPointTimeInUTC', 'type': 'iso-8601'}, 'type': {'key': 'type', 'type': 'str'}, 'recovery_point_tier_details': {'key': 'recoveryPointTierDetails', 'type': '[RecoveryPointTierInformationV2]'}, 'recovery_point_move_readiness_info': {'key': 'recoveryPointMoveReadinessInfo', 'type': '{RecoveryPointMoveReadinessInfo}'}, 'time_ranges': {'key': 'timeRanges', 'type': '[PointInTimeRange]'}, } <NEW_LINE> def __init__( self, *, recovery_point_time_in_utc: Optional[datetime.datetime] = None, type: Optional[Union[str, "RestorePointType"]] = None, recovery_point_tier_details: Optional[List["RecoveryPointTierInformationV2"]] = None, recovery_point_move_readiness_info: Optional[Dict[str, "RecoveryPointMoveReadinessInfo"]] = None, time_ranges: Optional[List["PointInTimeRange"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(AzureWorkloadSAPHanaPointInTimeRecoveryPoint, self).__init__(recovery_point_time_in_utc=recovery_point_time_in_utc, type=type, recovery_point_tier_details=recovery_point_tier_details, recovery_point_move_readiness_info=recovery_point_move_readiness_info, time_ranges=time_ranges, **kwargs) <NEW_LINE> self.object_type = 'AzureWorkloadSAPHanaPointInTimeRecoveryPoint'
Recovery point specific to PointInTime in SAPHana. All required parameters must be populated in order to send to Azure. :ivar object_type: Required. This property will be used as the discriminator for deciding the specific types in the polymorphic chain of types.Constant filled by server. :vartype object_type: str :ivar recovery_point_time_in_utc: UTC time at which recovery point was created. :vartype recovery_point_time_in_utc: ~datetime.datetime :ivar type: Type of restore point. Possible values include: "Invalid", "Full", "Log", "Differential", "Incremental". :vartype type: str or ~azure.mgmt.recoveryservicesbackup.activestamp.models.RestorePointType :ivar recovery_point_tier_details: Recovery point tier information. :vartype recovery_point_tier_details: list[~azure.mgmt.recoveryservicesbackup.activestamp.models.RecoveryPointTierInformationV2] :ivar recovery_point_move_readiness_info: Eligibility of RP to be moved to another tier. :vartype recovery_point_move_readiness_info: dict[str, ~azure.mgmt.recoveryservicesbackup.activestamp.models.RecoveryPointMoveReadinessInfo] :ivar time_ranges: List of log ranges. :vartype time_ranges: list[~azure.mgmt.recoveryservicesbackup.activestamp.models.PointInTimeRange]
6259904529b78933be26aa57
class ManagedHsmSku(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'family': {'required': True}, 'name': {'required': True}, } <NEW_LINE> _attribute_map = { 'family': {'key': 'family', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, family: Union[str, "ManagedHsmSkuFamily"] = "B", name: Union[str, "ManagedHsmSkuName"], **kwargs ): <NEW_LINE> <INDENT> super(ManagedHsmSku, self).__init__(**kwargs) <NEW_LINE> self.family = family <NEW_LINE> self.name = name
SKU details. All required parameters must be populated in order to send to Azure. :param family: Required. SKU Family of the managed HSM Pool. Possible values include: "B". :type family: str or ~azure.mgmt.keyvault.v2021_06_01_preview.models.ManagedHsmSkuFamily :param name: Required. SKU of the managed HSM Pool. Possible values include: "Standard_B1", "Custom_B32". :type name: str or ~azure.mgmt.keyvault.v2021_06_01_preview.models.ManagedHsmSkuName
62599045ec188e330fdf9bc4
class GitHubCodeReview(zazu.code_reviewer.CodeReview): <NEW_LINE> <INDENT> def __init__(self, github_pull_request): <NEW_LINE> <INDENT> self._pr = github_pull_request <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._pr.title <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self._pr.state <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._pr.body <NEW_LINE> <DEDENT> @property <NEW_LINE> def assignee(self): <NEW_LINE> <INDENT> return self._pr.assignee.login <NEW_LINE> <DEDENT> @property <NEW_LINE> def head(self): <NEW_LINE> <INDENT> return self._pr.head.ref <NEW_LINE> <DEDENT> @property <NEW_LINE> def base(self): <NEW_LINE> <INDENT> return self._pr.base.ref <NEW_LINE> <DEDENT> @property <NEW_LINE> def browse_url(self): <NEW_LINE> <INDENT> return self._pr.html_url <NEW_LINE> <DEDENT> @property <NEW_LINE> def merged(self): <NEW_LINE> <INDENT> return self._pr.merged <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return str(self._pr.number) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '#{} ({}, {}) {} -> {}'.format(self.id, self.status, 'merged' if self.merged else 'unmerged', self.head, self.base)
Adapts a github pull request object into a zazu CodeReview object.
625990458e05c05ec3f6f7ef
class AddressEncoder(JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, corp.Address): <NEW_LINE> <INDENT> encoded_address = { o.__class__.__name__: True, "uid": o.uid_to_json(), "deleted": o.is_deleted(), "street": o.street, "house_number": o.house_number, "city": o.city, "state": o.state, "zipcode": o.zipcode, "country": o.country, } <NEW_LINE> return encoded_address <NEW_LINE> <DEDENT> return JSONEncoder.default(self, o)
JSON-Encoder for Address objects.
625990450a366e3fb87ddd0f
class AzureFirewallApplicationRuleCollection(SubResource): <NEW_LINE> <INDENT> _validation = { 'etag': {'readonly': True}, 'priority': {'maximum': 65000, 'minimum': 100}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'priority': {'key': 'properties.priority', 'type': 'int'}, 'action': {'key': 'properties.action', 'type': 'AzureFirewallRCAction'}, 'rules': {'key': 'properties.rules', 'type': '[AzureFirewallApplicationRule]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, priority: Optional[int] = None, action: Optional["AzureFirewallRCAction"] = None, rules: Optional[List["AzureFirewallApplicationRule"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(AzureFirewallApplicationRuleCollection, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = None <NEW_LINE> self.priority = priority <NEW_LINE> self.action = action <NEW_LINE> self.rules = rules <NEW_LINE> self.provisioning_state = None
Application rule collection resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param name: The name of the resource that is unique within the Azure firewall. This name can be used to access the resource. :type name: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :param priority: Priority of the application rule collection resource. :type priority: int :param action: The action type of a rule collection. :type action: ~azure.mgmt.network.v2019_09_01.models.AzureFirewallRCAction :param rules: Collection of rules used by a application rule collection. :type rules: list[~azure.mgmt.network.v2019_09_01.models.AzureFirewallApplicationRule] :ivar provisioning_state: The provisioning state of the application rule collection resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed". :vartype provisioning_state: str or ~azure.mgmt.network.v2019_09_01.models.ProvisioningState
62599045baa26c4b54d505d3
class ExpiredCredentials(Exception): <NEW_LINE> <INDENT> pass
Credentials used to assume the role has expired.
62599045b830903b9686ee0f
class DTNotation(object): <NEW_LINE> <INDENT> def __init__(self, code): <NEW_LINE> <INDENT> if isinstance(code, string_types): <NEW_LINE> <INDENT> self._init_from_string(code) <NEW_LINE> <DEDENT> elif isinstance(code, n.ndarray): <NEW_LINE> <INDENT> code = [code] <NEW_LINE> self._dt = code <NEW_LINE> <DEDENT> elif isinstance(code, list): <NEW_LINE> <INDENT> self._dt = code <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Could not parse code as a valid type') <NEW_LINE> <DEDENT> <DEDENT> def _init_from_string(self, code): <NEW_LINE> <INDENT> regex = re.compile('[\n]+') <NEW_LINE> lines = regex.split(code) <NEW_LINE> dt = [] <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> numbers = line.split(' ') <NEW_LINE> dt.append(n.array([int(number) for number in numbers], dtype=n.int)) <NEW_LINE> <DEDENT> self._dt = dt <NEW_LINE> <DEDENT> def gauss_code_string(self): <NEW_LINE> <INDENT> if len(self._dt) > 1: <NEW_LINE> <INDENT> raise ValueError('DTNotation -> GaussCode does not yet ' 'work with links') <NEW_LINE> <DEDENT> dt = self._dt[0] <NEW_LINE> arr = n.zeros((len(dt) * 2, 2), dtype=n.int) <NEW_LINE> for index, even in enumerate(dt, 0): <NEW_LINE> <INDENT> odd = 2*index <NEW_LINE> sign = n.sign(even) <NEW_LINE> even = n.abs(even) - 1 <NEW_LINE> arr[odd, 0] = index + 1 <NEW_LINE> arr[odd, 1] = sign <NEW_LINE> arr[even, 0] = index + 1 <NEW_LINE> arr[even, 1] = -1 * sign <NEW_LINE> <DEDENT> str_entries = ['{}{}'.format(index, '+' if sign > 0 else '-') for index, sign in arr] <NEW_LINE> return ','.join(str_entries) <NEW_LINE> <DEDENT> def representation(self, **kwargs): <NEW_LINE> <INDENT> from pyknotid.representations import Representation <NEW_LINE> return Representation.calculating_orientations( self.gauss_code_string(), **kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if len(self._dt) == 0: <NEW_LINE> <INDENT> return '----' <NEW_LINE> <DEDENT> strings = [' '.join(map(str, l)) for l in self._dt] <NEW_LINE> return '\n'.join(strings)
Class for containing and manipulation DT notation. Parameters ---------- code : str or array-like The DT code. Must be either a string of entries separated by spaces, or an array.
6259904596565a6dacd2d91f
class BaseCompletionModel(QStandardItemModel): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> self.setColumnCount(3) <NEW_LINE> <DEDENT> def new_category(self, name, sort=None): <NEW_LINE> <INDENT> cat = QStandardItem(name) <NEW_LINE> if sort is not None: <NEW_LINE> <INDENT> cat.setData(sort, Role.sort) <NEW_LINE> <DEDENT> self.appendRow(cat) <NEW_LINE> return cat <NEW_LINE> <DEDENT> def new_item(self, cat, name, desc='', misc=None, sort=None): <NEW_LINE> <INDENT> nameitem = QStandardItem(name) <NEW_LINE> descitem = QStandardItem(desc) <NEW_LINE> if misc is None: <NEW_LINE> <INDENT> miscitem = QStandardItem() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> miscitem = QStandardItem(misc) <NEW_LINE> <DEDENT> idx = cat.rowCount() <NEW_LINE> cat.setChild(idx, 0, nameitem) <NEW_LINE> cat.setChild(idx, 1, descitem) <NEW_LINE> cat.setChild(idx, 2, miscitem) <NEW_LINE> if sort is not None: <NEW_LINE> <INDENT> nameitem.setData(sort, Role.sort) <NEW_LINE> <DEDENT> return nameitem, descitem, miscitem <NEW_LINE> <DEDENT> def flags(self, index): <NEW_LINE> <INDENT> qtutils.ensure_valid(index) <NEW_LINE> if index.parent().isValid(): <NEW_LINE> <INDENT> return Qt.ItemIsEnabled | Qt.ItemIsSelectable <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Qt.NoItemFlags <NEW_LINE> <DEDENT> <DEDENT> def sort(self, column, order=Qt.AscendingOrder): <NEW_LINE> <INDENT> raise NotImplementedError
A simple QStandardItemModel adopted for completions. Used for showing completions later in the CompletionView. Supports setting marks and adding new categories/items easily.
6259904594891a1f408ba08b
class SplashScreen(tkinter.Toplevel): <NEW_LINE> <INDENT> def __init__(self, master=None, borderwidth=4, relief=tkinter.RAISED, **kw): <NEW_LINE> <INDENT> tkinter.Toplevel.__init__(self, master, relief=relief, borderwidth=borderwidth, **kw) <NEW_LINE> if self.master.master is not None: <NEW_LINE> <INDENT> self.master.master.withdraw() <NEW_LINE> <DEDENT> self.master.withdraw() <NEW_LINE> self.overrideredirect(1) <NEW_LINE> self.createWidgets() <NEW_LINE> self.after_idle(self.centerOnScreen) <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def centerOnScreen(self): <NEW_LINE> <INDENT> self.update_idletasks() <NEW_LINE> xmax = self.winfo_screenwidth() <NEW_LINE> ymax = self.winfo_screenheight() <NEW_LINE> x0 = (xmax - self.winfo_reqwidth()) // 2 <NEW_LINE> y0 = (ymax - self.winfo_reqheight()) // 2 <NEW_LINE> self.geometry(f"+{x0:d}+{y0:d}") <NEW_LINE> <DEDENT> def createWidgets(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Destroy(self): <NEW_LINE> <INDENT> self.master.update() <NEW_LINE> self.master.deiconify() <NEW_LINE> self.withdraw()
Base class for splash screen Subclass and override createWidgets(). In constructor of main window/application call - S = SplashScreen(main=self) (if caller is Toplevel) - S = SplashScreen(main=self.master) (if caller is Frame) - S.Destroy() after you are done creating your widgets etc. Based closely on news posting by Alexander Schliep, 07 Apr 1999
6259904515baa723494632bd
class Swish(nn.Module): <NEW_LINE> <INDENT> def forward(self, input): <NEW_LINE> <INDENT> return input * torch.sigmoid(input)
Swish 活性化関数
6259904523849d37ff8523e6
class Pipeline(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.expected = 3530599.61 <NEW_LINE> self.infile = os.path.join(data_dir, 'metagenome.fa.gz') <NEW_LINE> self.observed = microbe_census.run_pipeline({'seqfiles':[self.infile]})[0] <NEW_LINE> <DEDENT> def test_ags_estimation(self): <NEW_LINE> <INDENT> estimation_error = abs(self.expected-self.observed)/self.expected <NEW_LINE> self.assertTrue(estimation_error < 0.01)
check whether ags is accurately estimated for test data
625990458a349b6b43687575
class DataMapper(object): <NEW_LINE> <INDENT> content_type = 'text/plain' <NEW_LINE> charset = 'utf-8' <NEW_LINE> def format(self, response): <NEW_LINE> <INDENT> res = self._prepare_response(response) <NEW_LINE> res.content = self._format_data(res.content, self.charset) <NEW_LINE> return self._finalize_response(res) <NEW_LINE> <DEDENT> def parse(self, data, charset=None): <NEW_LINE> <INDENT> charset = charset or self.charset <NEW_LINE> return self._parse_data(data, charset) <NEW_LINE> <DEDENT> def _decode_data(self, data, charset): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return smart_unicode(data, charset) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> raise errors.BadRequest('wrong charset') <NEW_LINE> <DEDENT> <DEDENT> def _encode_data(self, data): <NEW_LINE> <INDENT> return smart_str(data, self.charset) <NEW_LINE> <DEDENT> def _format_data(self, data, charset): <NEW_LINE> <INDENT> return self._encode_data(data) if data else u'' <NEW_LINE> <DEDENT> def _parse_data(self, data, charset): <NEW_LINE> <INDENT> return self._decode_data(data, charset) if data else u'' <NEW_LINE> <DEDENT> def _prepare_response(self, response): <NEW_LINE> <INDENT> if not isinstance(response, Response): <NEW_LINE> <INDENT> return Response(0, response) <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> def _finalize_response(self, response): <NEW_LINE> <INDENT> res = HttpResponse(content=response.content, content_type=self._get_content_type()) <NEW_LINE> res.status_code = response.code <NEW_LINE> return res <NEW_LINE> <DEDENT> def _get_content_type(self): <NEW_LINE> <INDENT> return '%s; charset=%s' % (self.content_type, self.charset)
Base class for all data mappers. This class also implements ``text/plain`` datamapper.
625990451d351010ab8f4e44
class BaseTapeDownloader(abc.ABC): <NEW_LINE> <INDENT> def store_metadata(self, iddir, tapes, period_func=to_decade): <NEW_LINE> <INDENT> n_tapes_added = 0 <NEW_LINE> os.makedirs(iddir, exist_ok=True) <NEW_LINE> periods = sorted(list(set([period_func(t['date']) for t in tapes]))) <NEW_LINE> logger.debug(f"storing metadata {periods}") <NEW_LINE> for period in periods: <NEW_LINE> <INDENT> orig_tapes = [] <NEW_LINE> outpath = os.path.join(iddir, f'ids_{period}.json') <NEW_LINE> if os.path.exists(outpath): <NEW_LINE> <INDENT> orig_tapes = json.load(open(outpath, 'r')) <NEW_LINE> <DEDENT> tapes_from_period = [t for t in tapes if period_func(t['date']) == period] <NEW_LINE> new_ids = [x['identifier'] for x in tapes_from_period] <NEW_LINE> period_tapes = [x for x in orig_tapes if not x['identifier'] in new_ids] + tapes_from_period <NEW_LINE> n_period_tapes_added = len(period_tapes) - len(orig_tapes) <NEW_LINE> n_tapes_added = n_tapes_added + n_period_tapes_added <NEW_LINE> if n_period_tapes_added > 0: <NEW_LINE> <INDENT> logger.info(f"Writing {len(period_tapes)} tapes to {outpath}") <NEW_LINE> try: <NEW_LINE> <INDENT> tmpfile = tempfile.mkstemp('.json')[1] <NEW_LINE> json.dump(period_tapes, open(tmpfile, 'w')) <NEW_LINE> os.rename(tmpfile, outpath) <NEW_LINE> logger.debug(f"renamed {tmpfile} to {outpath}") <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> logger.debug(f"removing {tmpfile}") <NEW_LINE> os.remove(tmpfile) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> logger.info(f'added {n_tapes_added} tapes by period') <NEW_LINE> return n_tapes_added <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def get_all_tapes(self, iddir, min_addeddate=None): <NEW_LINE> <INDENT> pass
Abstract base class for a tape downloader. Use one of the subclasses: IATapeDownloader or PhishinTapeDownloader.
62599045498bea3a75a58e48
class Dog: <NEW_LINE> <INDENT> def speak(self): <NEW_LINE> <INDENT> return 'Woof' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'Dog'
One of the objects to be return
62599045462c4b4f79dbcd29
class ExportPlugin(BasePlugin): <NEW_LINE> <INDENT> to = Unicode("", config=True, help="destination to export to") <NEW_LINE> def export(self, gradebook): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for export plugins.
6259904591af0d3eaad3b14f
class Pyscenarios(Scenarios): <NEW_LINE> <INDENT> def WhenTheGeneratorIsPyscenarios(self): <NEW_LINE> <INDENT> self.output = "py/pyscenarios" <NEW_LINE> self.folder = "py/pyunit_tests" <NEW_LINE> self.ext = "_scenarios.py" <NEW_LINE> self.header = "" <NEW_LINE> self.settings = cornichon.Settings(self.output)
Test class scenario
62599045b57a9660fecd2da8
class EosClearSystemCommand(Switch.CmdInterpreter): <NEW_LINE> <INDENT> def __init__(self, switch): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._switch = switch <NEW_LINE> <DEDENT> def default(self, line): <NEW_LINE> <INDENT> return 'NOTICE: Ignoring unknown command "clear system ' + line + '"' <NEW_LINE> <DEDENT> def do_login(self, line): <NEW_LINE> <INDENT> if not line: <NEW_LINE> <INDENT> return 'ERROR: "clear system login" needs a login name to clear' <NEW_LINE> <DEDENT> if len(line.split()) != 1: <NEW_LINE> <INDENT> return ('NOTICE: Ignoring unknown command "clear system login ' + line + '"') <NEW_LINE> <DEDENT> ret = self._switch.del_user_account(line) <NEW_LINE> if ret is None: <NEW_LINE> <INDENT> return ('WARN: Could not delete non-existing user account "' + line + '"') <NEW_LINE> <DEDENT> return ''
Commands starting with 'clear'.
62599045b5575c28eb71365f
class _TestSFTPServerProperties(_CheckSFTP): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> async def start_server(cls): <NEW_LINE> <INDENT> return await cls.create_server(sftp_factory=_CheckPropSFTPServer) <NEW_LINE> <DEDENT> @asynctest <NEW_LINE> async def test_properties(self): <NEW_LINE> <INDENT> async with self.connect() as conn: <NEW_LINE> <INDENT> async with conn.start_sftp_client(env={'A': 1, 'B': 2}) as sftp: <NEW_LINE> <INDENT> files = await sftp.listdir() <NEW_LINE> self.assertEqual(sorted(files), ['A', 'B'])
Unit test for checking SFTP server properties
6259904573bcbd0ca4bcb5b8
class _lazy_property(object): <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> self.func_name = func.__name__ <NEW_LINE> <DEDENT> def __get__(self, obj, cls): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> value = self.func(obj) <NEW_LINE> setattr(obj, self.func_name, value) <NEW_LINE> return value
meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself.
6259904573bcbd0ca4bcb5b9
class Logger(object): <NEW_LINE> <INDENT> events = "" <NEW_LINE> errors = "" <NEW_LINE> @staticmethod <NEW_LINE> def log(message): <NEW_LINE> <INDENT> Logger.events += "[" + str(datetime.datetime.now()) + "] " + str(message) + "\n" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def log_error(message): <NEW_LINE> <INDENT> Logger.errors += "[" + str(datetime.datetime.now()) + "] ERROR: " + str(message) + "\n" <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def write_log_files(output_directory): <NEW_LINE> <INDENT> datetime_string = datetime.datetime.now().strftime("%m-%d-%Y.%I-%m-%p") <NEW_LINE> stamp = datetime_string + "." + str(os.getpid()) <NEW_LINE> log_filename = os.path.join(output_directory, "crypto.events." + stamp + ".log") <NEW_LINE> error_log_filename = os.path.join(output_directory, "crypto.errors." + stamp + ".log") <NEW_LINE> if Logger.events: <NEW_LINE> <INDENT> with open(log_filename, "w") as log_file: <NEW_LINE> <INDENT> log_file.write(Logger.events) <NEW_LINE> <DEDENT> <DEDENT> if Logger.errors: <NEW_LINE> <INDENT> with open(log_filename, "a") as log_file: <NEW_LINE> <INDENT> log_file.write("\n\nEncountered the following errors:\n\n") <NEW_LINE> log_file.write(Logger.errors)
Class for saving log information and creating a log file
62599045d53ae8145f91978b
class Gpon(models.Model): <NEW_LINE> <INDENT> ap_mac = models.CharField(u'ap_mac',max_length=32,default="",unique = True) <NEW_LINE> gpon_state = models.CharField(u'gpon_state',max_length=64,default="",blank=True) <NEW_LINE> off_reason = models.CharField(u'off_reason',max_length=64,default="",blank=True) <NEW_LINE> gpon_sn = models.CharField(u'gpon_sn',max_length=64,default="",blank=True) <NEW_LINE> gpon_pwd = models.CharField(u'gpon_pwd',max_length=64,default="",blank=True) <NEW_LINE> los_status = models.CharField(u'los_status',max_length=64,default="",blank=True) <NEW_LINE> tx_power = models.CharField(u'tx_power',max_length=64,default="",blank=True) <NEW_LINE> rx_power = models.CharField(u'rx_power',max_length=64,default="",blank=True) <NEW_LINE> temperature = models.CharField(u'temperature',max_length=64,default="",blank=True) <NEW_LINE> supply_voltage = models.CharField(u'supply_voltage',max_length=64,default="",blank=True) <NEW_LINE> txbias_current = models.CharField(u'txbias_current',max_length=64,default="",blank=True) <NEW_LINE> onu_state = models.CharField(u'onu_state',max_length=64,default="",blank=True) <NEW_LINE> phy_status = models.CharField(u'phy_status',max_length=64,default="",blank=True) <NEW_LINE> traffic_status = models.CharField(u'traffic_status',max_length=64,default="",blank=True) <NEW_LINE> manufacturer = models.CharField(u'manufacturer',max_length=64,default="",blank=True) <NEW_LINE> manufacturer_oui = models.CharField(u'manufacturer_oui',max_length=64,default="",blank=True) <NEW_LINE> operator_id = models.CharField(u'operator_id',max_length=64,default="",blank=True) <NEW_LINE> model_name = models.CharField(u'model_name',max_length=64,default="",blank=True) <NEW_LINE> customer_hwversion = models.CharField(u'customer_hwversion',max_length=64,default="",blank=True) <NEW_LINE> customer_swversion = models.CharField(u'customer_swversion',max_length=64,default="",blank=True) <NEW_LINE> update_link = models.CharField(u'update_link',max_length=64,default="",blank=True) <NEW_LINE> update_file = models.CharField(u'update_file',max_length=64,default="",blank=True)
Description: Model Description
62599045004d5f362081f97c
class OrganizationCourseAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ('course_id', 'organization', 'active') <NEW_LINE> def formfield_for_foreignkey(self, db_field, request, **kwargs): <NEW_LINE> <INDENT> if db_field.name == 'organization': <NEW_LINE> <INDENT> kwargs['queryset'] = Organization.objects.filter(active=True) <NEW_LINE> <DEDENT> return super(OrganizationCourseAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
Admin for the CourseOrganization table.
62599045a8ecb0332587253d
class DetalheOportunidadeUpdateValue(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'id': 'int', 'nome_campo': 'str', 'conteudo': 'str' } <NEW_LINE> self.attribute_map = { 'id': 'id', 'nome_campo': 'nomeCampo', 'conteudo': 'conteudo' } <NEW_LINE> self._id = None <NEW_LINE> self._nome_campo = None <NEW_LINE> self._conteudo = None <NEW_LINE> <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> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def nome_campo(self): <NEW_LINE> <INDENT> return self._nome_campo <NEW_LINE> <DEDENT> @nome_campo.setter <NEW_LINE> def nome_campo(self, nome_campo): <NEW_LINE> <INDENT> self._nome_campo = nome_campo <NEW_LINE> <DEDENT> @property <NEW_LINE> def conteudo(self): <NEW_LINE> <INDENT> return self._conteudo <NEW_LINE> <DEDENT> @conteudo.setter <NEW_LINE> def conteudo(self, conteudo): <NEW_LINE> <INDENT> self._conteudo = conteudo <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_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 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> 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 the swagger code generator program. Do not edit the class manually.
6259904530c21e258be99b33
class PetitionStatus(enum.Enum): <NEW_LINE> <INDENT> ongoing = 1 <NEW_LINE> pending = 2 <NEW_LINE> answered = 3 <NEW_LINE> expired = 4 <NEW_LINE> deleted = 5
ongoing : 진행중인 청원 pending : 답변 대기중인 청원 answered : 답변 된 청원 expired : 기한이 지난 청원 deleted : 삭제 된 청원
6259904523e79379d538d82b
class GraphConvolutionMulti(MultiLayer): <NEW_LINE> <INDENT> def __init__(self, input_dim, output_dim, adj_mats, dropout=0., act=tf.nn.relu, **kwargs): <NEW_LINE> <INDENT> super(GraphConvolutionMulti, self).__init__(**kwargs) <NEW_LINE> self.adj_mats = adj_mats <NEW_LINE> self.dropout = dropout <NEW_LINE> self.act = act <NEW_LINE> with tf.variable_scope('%s_vars' % self.name): <NEW_LINE> <INDENT> self.vars['weights'] = weight_variable_glorot(input_dim, output_dim, name='weights') <NEW_LINE> <DEDENT> <DEDENT> def _call(self, inputs): <NEW_LINE> <INDENT> x = inputs <NEW_LINE> x = tf.nn.dropout(x, 1-self.dropout) <NEW_LINE> x = tf.matmul(x, self.vars['weights']) <NEW_LINE> x = tf.sparse_tensor_dense_matmul(self.adj_mats[self.edge_type], x) <NEW_LINE> outputs = self.act(x) <NEW_LINE> return outputs
Basic graph convolution layer for undirected graph without edge labels.
62599045a79ad1619776b3ac
class IPasswordRoleSchema(Interface): <NEW_LINE> <INDENT> pass
Schema used to manage the usernames and passwords
625990453c8af77a43b688d3
class IsPrefixOfModifier(Modifier): <NEW_LINE> <INDENT> def __init__(self, prefix: str | list[Any] | Callable | Types) -> None: <NEW_LINE> <INDENT> self.prefix = prefix <NEW_LINE> <DEDENT> def validate(self, ctx: Ctx) -> None: <NEW_LINE> <INDENT> if isinstance(ctx.val, list): <NEW_LINE> <INDENT> if not self.resolve_param(self.prefix, ctx)[:len(ctx.val)] == ctx.val: <NEW_LINE> <INDENT> ctx.raise_vexc('prefix is not found') <NEW_LINE> <DEDENT> <DEDENT> elif type(ctx.val) is str: <NEW_LINE> <INDENT> if not self.resolve_param(self.prefix, ctx).startswith(ctx.val): <NEW_LINE> <INDENT> ctx.raise_vexc('prefix is not found')
Has prefix modifier for checking if a str is suffix of another str.
62599045cad5886f8bdc5a14
class TeamConfirmAskJoinView(LoginRequiredMixin, PlayerActionMixin, NavBarMixin, DetailView): <NEW_LINE> <INDENT> model = PlayerRequest <NEW_LINE> page_title = _("Itinerary Confirmation")
Confirmation page for person who's asked to join a club
62599045b57a9660fecd2da9
class Main(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def get_template_scope(cls, scope): <NEW_LINE> <INDENT> return scope <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_template_file_scope(cls, file, scope): <NEW_LINE> <INDENT> return scope <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_manifest_scope(cls, scope, web_node, user): <NEW_LINE> <INDENT> return scope <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def stop(cls, *arguments, **keywords): <NEW_LINE> <INDENT> return cls <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def post_template_file_rendering(cls, output_file, file, scope): <NEW_LINE> <INDENT> return output_file <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def initialize(cls): <NEW_LINE> <INDENT> return cls.main.options <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def initialize_model(cls): <NEW_LINE> <INDENT> return cls <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def initialize_model_mockup(cls): <NEW_LINE> <INDENT> return cls <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def launch(cls): <NEW_LINE> <INDENT> return cls <NEW_LINE> <DEDENT> def response(self, web_node, mime_type, cache_control_header): <NEW_LINE> <INDENT> return '', mime_type, cache_control_header, None
Contains the main application specific business logic.
6259904507d97122c4217fce
class Device(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length = 256) <NEW_LINE> begin_time = models.DateTimeField() <NEW_LINE> end_time = models.DateTimeField(default=max_datetime) <NEW_LINE> community = models.CharField(max_length = 128) <NEW_LINE> active = models.BooleanField(default = True) <NEW_LINE> devicetag = models.ManyToManyField(DeviceTag, through = "DeviceTagMap") <NEW_LINE> oidsets = models.ManyToManyField("OIDSet", through = "DeviceOIDSetMap") <NEW_LINE> objects = DeviceManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "device" <NEW_LINE> ordering = ['name'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return dict( begin_time=datetime_to_unixtime(self.begin_time), end_time=datetime_to_unixtime(self.end_time), name=self.name, active=self.active)
A system which is pollable via SNMP. Referred to as a Managed Device in SNMP terminology.
62599045462c4b4f79dbcd2b
class RuleGroupGroup(ModelSQL): <NEW_LINE> <INDENT> __name__ = 'ir.rule.group-res.group' <NEW_LINE> rule_group = fields.Many2One('ir.rule.group', 'Rule Group', ondelete='CASCADE', select=True, required=True) <NEW_LINE> group = fields.Many2One('res.group', 'Group', ondelete='CASCADE', select=True, required=True) <NEW_LINE> @classmethod <NEW_LINE> def __register__(cls, module_name): <NEW_LINE> <INDENT> cursor = Transaction().cursor <NEW_LINE> TableHandler.table_rename(cursor, 'group_rule_group_rel', cls._table) <NEW_LINE> TableHandler.sequence_rename(cursor, 'group_rule_group_rel_id_seq', cls._table + '_id_seq') <NEW_LINE> table = TableHandler(cursor, cls, module_name) <NEW_LINE> table.column_rename('rule_group_id', 'rule_group') <NEW_LINE> table.column_rename('group_id', 'group') <NEW_LINE> super(RuleGroupGroup, cls).__register__(module_name)
Rule Group - Group
6259904526238365f5fade88
class UnexpectedJsonFormatError(Exception): <NEW_LINE> <INDENT> pass
Json is not in expected format, probably service has changed during time.
62599045ec188e330fdf9bc8
@ui.register_ui( item_change_password=ui.UI(By.CSS_SELECTOR, '*[id*="action_change_password"]'), item_toggle_user=ui.UI(By.CSS_SELECTOR, '[id$="action_toggle"]')) <NEW_LINE> class DropdownMenu(_ui.DropdownMenu): <NEW_LINE> <INDENT> pass
Dropdown menu for user row.
625990450a366e3fb87ddd13
class Database(cgtwq.Database): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_shot(cls, shot, default=None): <NEW_LINE> <INDENT> data = cgtwq.PROJECT.select_all().get_fields('code', 'database') <NEW_LINE> for i in data: <NEW_LINE> <INDENT> code, database = i <NEW_LINE> if unicode(shot).startswith(code): <NEW_LINE> <INDENT> return cls(database) <NEW_LINE> <DEDENT> <DEDENT> if default: <NEW_LINE> <INDENT> return cls(default) <NEW_LINE> <DEDENT> raise ValueError( 'Can not determinate database from filename.', shot)
Optimized cgtwq database fro nuke.
6259904510dbd63aa1c71f07
class BankAccount: <NEW_LINE> <INDENT> def __init__(self, name, initial_deposit, password): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.accnum = randint(10000,99999) <NEW_LINE> self.password = password <NEW_LINE> self.balance = int(initial_deposit) <NEW_LINE> self.transactions = {} <NEW_LINE> <DEDENT> def show_balance(self): <NEW_LINE> <INDENT> print("Current Balance: ${:.2f}\n".format(self.balance)) <NEW_LINE> <DEDENT> def deposit(self, amount): <NEW_LINE> <INDENT> if amount < 1: <NEW_LINE> <INDENT> print("Invalid deposit\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Depositing ${:.2f}...".format(amount)) <NEW_LINE> self.balance += int(amount) <NEW_LINE> self.show_balance() <NEW_LINE> self.log_transaction('deposit', amount) <NEW_LINE> <DEDENT> <DEDENT> def withdraw(self, amount): <NEW_LINE> <INDENT> if amount > self.balance: <NEW_LINE> <INDENT> print("Insufficient funds\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Withdrawing ${:.2f}...".format(amount)) <NEW_LINE> self.balance -= amount <NEW_LINE> self.show_balance() <NEW_LINE> self.log_transaction('withdrawal', amount) <NEW_LINE> <DEDENT> <DEDENT> def log_transaction(self, transaction, amount): <NEW_LINE> <INDENT> self.transactions[transaction] = amount <NEW_LINE> self.show_transactions() <NEW_LINE> <DEDENT> def show_transactions(self): <NEW_LINE> <INDENT> print("Transactions: {}\n".format(self.transactions)) <NEW_LINE> <DEDENT> def validate_password(self, password): <NEW_LINE> <INDENT> return True if password == self.password else print("Incorrect password") and False
A bank account class with the following properties: AccNumber: A unique identifier for the bank account Name: A string representing owner of bank account Balance: Bank account balance Transactions: List of transaction under the account
62599045d4950a0f3b1117d8
class BatchTest(integration.ShellCase): <NEW_LINE> <INDENT> def test_batch_run(self): <NEW_LINE> <INDENT> ret = 'Executing run on [\'sub_minion\']' <NEW_LINE> cmd = self.run_salt('\'*\' test.echo \'batch testing\' -b 50%') <NEW_LINE> self.assertIn(ret, cmd) <NEW_LINE> <DEDENT> def test_batch_run_number(self): <NEW_LINE> <INDENT> ret = "Executing run on ['sub_minion', 'minion']" <NEW_LINE> cmd = self.run_salt('\'*\' test.ping --batch-size 2') <NEW_LINE> self.assertIn(ret, cmd) <NEW_LINE> <DEDENT> def test_batch_run_grains_targeting(self): <NEW_LINE> <INDENT> os_grain = '' <NEW_LINE> sub_min_ret = "Executing run on ['sub_minion']" <NEW_LINE> min_ret = "Executing run on ['minion']" <NEW_LINE> for item in self.run_salt('minion grains.get os'): <NEW_LINE> <INDENT> if item != 'minion': <NEW_LINE> <INDENT> os_grain = item <NEW_LINE> <DEDENT> <DEDENT> os_grain = os_grain.strip() <NEW_LINE> cmd = self.run_salt('-G \'os:{0}\' -b 25% test.ping'.format(os_grain)) <NEW_LINE> self.assertIn(sub_min_ret, cmd) <NEW_LINE> self.assertIn(min_ret, cmd) <NEW_LINE> <DEDENT> def test_batch_exit_code(self): <NEW_LINE> <INDENT> cmd = self.run_salt(' "*" state.single test.fail_without_changes name=test_me -b 25%', with_retcode=True) <NEW_LINE> self.assertEqual(cmd[-1], 2)
Integration tests for the salt.cli.batch module
62599045287bf620b6272f15
class PLShift(PBinOp): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return "(%s << %s)" % (self.a, self.b) <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> a = Pattern.value(self.a) <NEW_LINE> b = Pattern.value(self.b) <NEW_LINE> return None if a is None or b is None else a << b
PLShift: Binary left-shift (shorthand: patternA << patternB)
625990453eb6a72ae038b98f
class Index(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> value = models.FloatField() <NEW_LINE> min_value = models.FloatField() <NEW_LINE> max_value = models.FloatField() <NEW_LINE> unit = models.CharField(max_length=20) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name
体检指标
6259904573bcbd0ca4bcb5ba
class Actor(nn.Module): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, seed, fc1_units=200, fc2_units=150): <NEW_LINE> <INDENT> super(Actor, self).__init__() <NEW_LINE> self.seed = torch.manual_seed(seed) <NEW_LINE> self.fc1 = nn.Linear(state_size, fc1_units) <NEW_LINE> self.fc2 = nn.Linear(fc1_units, fc2_units) <NEW_LINE> self.fc3 = nn.Linear(fc2_units, action_size) <NEW_LINE> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> self.fc1.weight.data.uniform_(*hidden_init(self.fc1)) <NEW_LINE> self.fc2.weight.data.uniform_(*hidden_init(self.fc2)) <NEW_LINE> self.fc3.weight.data.uniform_(-3e-3, 3e-3) <NEW_LINE> <DEDENT> def forward(self, state): <NEW_LINE> <INDENT> x = F.relu(self.fc1(state)) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> return F.tanh(self.fc3(x))
Actor (Policy) Model.
6259904515baa723494632c0
@nine <NEW_LINE> class BaseRootResource(object): <NEW_LINE> <INDENT> __name__ = '' <NEW_LINE> __parent__ = None <NEW_LINE> def __init__(self, request): <NEW_LINE> <INDENT> self._request = request <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<{}>'.format(type(self).__name__) <NEW_LINE> <DEDENT> def _make_descendant(self, factory, name): <NEW_LINE> <INDENT> o = factory() <NEW_LINE> o._request = self._request <NEW_LINE> o.__parent__ = self <NEW_LINE> if hasattr(o, 'validate_name'): <NEW_LINE> <INDENT> o.__name__ = o.validate_name(name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> o.__name__ = name <NEW_LINE> <DEDENT> return o <NEW_LINE> <DEDENT> def __getitem__(self, name): <NEW_LINE> <INDENT> if hasattr(self, 'contains_cls'): <NEW_LINE> <INDENT> return self._make_descendant(self.contains_cls, name) <NEW_LINE> <DEDENT> elif hasattr(self, 'factories'): <NEW_LINE> <INDENT> return self._make_descendant(self.factories[name], name) <NEW_LINE> <DEDENT> raise KeyError(name)
Base class for your Root resource.
62599045004d5f362081f97d
class TransformProcessor: <NEW_LINE> <INDENT> def __init__(self, survey, ftp_conn): <NEW_LINE> <INDENT> self._base_url = settings.SDX_TRANSFORM_CS_URL <NEW_LINE> self.survey = survey <NEW_LINE> self.tx_id = "" <NEW_LINE> self.logger = get_logger() <NEW_LINE> self._setup_logger() <NEW_LINE> self.ftp = ftp_conn <NEW_LINE> self._endpoint_name = self._get_transformer_endpoint_name() <NEW_LINE> <DEDENT> def process(self): <NEW_LINE> <INDENT> transformed = self._transform() <NEW_LINE> delivered = self.ftp.unzip_and_deliver(settings.FTP_FOLDER, transformed) <NEW_LINE> if not delivered: <NEW_LINE> <INDENT> self.logger.error("Failed to deliver zip to ftp") <NEW_LINE> raise RetryableError("Failed to deliver zip to ftp") <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def _transform(self): <NEW_LINE> <INDENT> endpoint = self._get_url() <NEW_LINE> self.logger.info("Calling transform", request_url=endpoint) <NEW_LINE> response = remote_call(endpoint, json=self.survey) <NEW_LINE> if response_ok(response) and response.content is not None: <NEW_LINE> <INDENT> self.logger.info(f"{self.__class__.__name__}:Successfully transformed") <NEW_LINE> return response.content <NEW_LINE> <DEDENT> raise QuarantinableError("Response missing content") <NEW_LINE> <DEDENT> def _get_url(self): <NEW_LINE> <INDENT> sequence_no = TransformProcessor._get_sequence_number() <NEW_LINE> return f"{self._base_url}/{self._endpoint_name}/{sequence_no}" <NEW_LINE> <DEDENT> def _setup_logger(self): <NEW_LINE> <INDENT> if self.survey: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> metadata = self.survey['metadata'] <NEW_LINE> self.logger = self.logger.bind(user_id=metadata['user_id'], ru_ref=metadata['ru_ref']) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.logger.error("Failed to get metadata") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _get_sequence_number(): <NEW_LINE> <INDENT> sequence_no = get_sequence_no() <NEW_LINE> if sequence_no is None: <NEW_LINE> <INDENT> raise RetryableError("Failed to get sequence number") <NEW_LINE> <DEDENT> return sequence_no <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_transformer_endpoint_name(): <NEW_LINE> <INDENT> return 'transform'
Transforms and passes results to ftp
6259904523849d37ff8523ea
class SkysparkScramHaystackSession(HaystackSession, evalexpr.EvalOpsMixin): <NEW_LINE> <INDENT> _AUTH_OPERATION = SkysparkScramAuthenticateOperation <NEW_LINE> def __init__(self, uri, username, password, project, **kwargs): <NEW_LINE> <INDENT> super(SkysparkScramHaystackSession, self).__init__(uri, 'api/%s' % project,**kwargs) <NEW_LINE> self._username = username <NEW_LINE> self._password = password <NEW_LINE> self._project = project <NEW_LINE> self._authenticated = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_logged_in(self): <NEW_LINE> <INDENT> return self._authenticated <NEW_LINE> <DEDENT> def _on_authenticate_done(self, operation, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> op_result = operation.result <NEW_LINE> header = op_result['header'] <NEW_LINE> self._authenticated = True <NEW_LINE> self._client.cookies = None <NEW_LINE> self._client.headers = header <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self._authenticated = False <NEW_LINE> self._client.cookies = None <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._auth_op = None
The SkysparkHaystackSession class implements some base support for Skyspark servers.
625990451d351010ab8f4e48
class ValueItem(Item): <NEW_LINE> <INDENT> yaml_tag = '!ValueItem' <NEW_LINE> @classmethod <NEW_LINE> def from_yaml(cls, loader, node): <NEW_LINE> <INDENT> logging.debug('{}:from_yaml(loader={})'.format(cls.__name__, loader)) <NEW_LINE> default, select, value_desc = None, list(), None <NEW_LINE> for elem in node.value: <NEW_LINE> <INDENT> for key, value in elem.value: <NEW_LINE> <INDENT> if key.value == 'VALUE': <NEW_LINE> <INDENT> assert value_desc is None, "VALUE key already set" <NEW_LINE> value_desc = value <NEW_LINE> <DEDENT> if key.value == 'SELECT': <NEW_LINE> <INDENT> select.append(loader.construct_mapping(value)) <NEW_LINE> <DEDENT> if key.value == 'DEFAULT': <NEW_LINE> <INDENT> assert default is None, "DEFAULT key already set" <NEW_LINE> default = loader.construct_object(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if value_desc is None: <NEW_LINE> <INDENT> value_desc = yaml.ScalarNode(tag='!Number', value='{vl.value}') <NEW_LINE> <DEDENT> metrics = loader.collector.items(select) <NEW_LINE> assert len(metrics) < 2, 'Wrong SELECT condition {}, selected {} metrics'.format( select, len(metrics)) <NEW_LINE> if len(metrics) > 0: <NEW_LINE> <INDENT> item = cls.format_node(value_desc, {'vl': metrics[0], 'system': loader.system}) <NEW_LINE> return loader.construct_object(item) <NEW_LINE> <DEDENT> assert default is not None, "No metrics selected by SELECT condition" " {} and DEFAULT key isn't set".format(select) <NEW_LINE> return default
Class to process VlaueItem tag
625990458a43f66fc4bf34c2
class Table(object): <NEW_LINE> <INDENT> def __init__(self, table="", primary="", fields = None, readfields = None, joined = None, suffix=""): <NEW_LINE> <INDENT> self.table = table <NEW_LINE> self.primary = primary <NEW_LINE> if fields is not None: <NEW_LINE> <INDENT> self.fields = fields <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fields = [] <NEW_LINE> <DEDENT> if readfields is not None: <NEW_LINE> <INDENT> self.readfields = readfields <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.readfields = [] <NEW_LINE> <DEDENT> self.joined = joined <NEW_LINE> self.relations = [] <NEW_LINE> self.suffix = suffix <NEW_LINE> <DEDENT> def add_relation(self, tabledata, join_field = None, join_key = None, tag = None): <NEW_LINE> <INDENT> self.relations.append({"data": tabledata, "field": join_field, "key": join_key, "tag": tag})
Datos generales de una Tabla
625990450fa83653e46f620a
class gpio_write(LinuxCommand): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> LinuxCommand.__init__(self) <NEW_LINE> self.add_argument('gpio', metavar='GPIO', help="The gpio to write to") <NEW_LINE> self.add_argument('value', metavar='VALUE', help="The value to set") <NEW_LINE> <DEDENT> def run(self, con, config, args): <NEW_LINE> <INDENT> command = "echo out > /sys/class/gpio/gpio%s/direction"%(args['gpio']) <NEW_LINE> if not con.runcommand(command): <NEW_LINE> <INDENT> return (1, con.output.rstrip()) <NEW_LINE> <DEDENT> command = "echo %s > /sys/class/gpio/gpio%s/value"%(args['value'],args['gpio']) <NEW_LINE> if not con.runcommand(command): <NEW_LINE> <INDENT> return (1, con.output.rstrip()) <NEW_LINE> <DEDENT> return True
gpio_write sets a gpio to output and assigns the value specified
62599045d10714528d69f024
class AmpClientFactory(protocol.ReconnectingClientFactory): <NEW_LINE> <INDENT> initialDelay = 1 <NEW_LINE> factor = 1.5 <NEW_LINE> maxDelay = 1 <NEW_LINE> noisy = False <NEW_LINE> def __init__(self, portal): <NEW_LINE> <INDENT> self.portal = portal <NEW_LINE> self.protocol = AMPProtocol <NEW_LINE> <DEDENT> def startedConnecting(self, connector): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def buildProtocol(self, addr): <NEW_LINE> <INDENT> self.resetDelay() <NEW_LINE> self.portal.amp_protocol = AMPProtocol() <NEW_LINE> self.portal.amp_protocol.factory = self <NEW_LINE> return self.portal.amp_protocol <NEW_LINE> <DEDENT> def clientConnectionLost(self, connector, reason): <NEW_LINE> <INDENT> if hasattr(self, "server_restart_mode"): <NEW_LINE> <INDENT> self.maxDelay = 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.maxDelay = 10 <NEW_LINE> self.portal.sessions.announce_all(" ... Portal lost connection to Server.") <NEW_LINE> <DEDENT> protocol.ReconnectingClientFactory.clientConnectionLost(self, connector, reason) <NEW_LINE> <DEDENT> def clientConnectionFailed(self, connector, reason): <NEW_LINE> <INDENT> if hasattr(self, "server_restart_mode"): <NEW_LINE> <INDENT> self.maxDelay = 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.maxDelay = 10 <NEW_LINE> <DEDENT> self.portal.sessions.announce_all(" ...") <NEW_LINE> protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
This factory creates an instance of the Portal, an AMPProtocol instances to use to connect
62599045462c4b4f79dbcd2d
class ImportMassWorker(QThread): <NEW_LINE> <INDENT> signal = QtCore.Signal(int, int) <NEW_LINE> def __init__(self, window): <NEW_LINE> <INDENT> QThread.__init__(self) <NEW_LINE> self.window = window <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> imp_cnt = 0 <NEW_LINE> fail_cnt = 0 <NEW_LINE> input_dir = self.window.directory_select() <NEW_LINE> for pch in os.listdir(input_dir): <NEW_LINE> <INDENT> if pch.split(".")[1] == "bin": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> save.import_to_backend(os.path.join(input_dir, pch)) <NEW_LINE> imp_cnt += 1 <NEW_LINE> <DEDENT> except errors.SavingError: <NEW_LINE> <INDENT> fail_cnt += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.signal.emit(imp_cnt, fail_cnt)
The ImportMassWorker class runs as a separate thread in the application to prevent application snag. This thread will attempt to import specified binary files into the backend as individual patches.
62599045ec188e330fdf9bca
class UserSignTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.base_url = "http://127.0.0.1:8000/api/user_sign/" <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> print(self.result) <NEW_LINE> <DEDENT> @parameterized.expand([ ("all_null", "", "", 10021, "parameter error"), ("eid_error", 901, 13711001100, 10022, "event id null"), ("status_close", 3, 13711001100, 10023, "event status is not available"), ("time_start", 4, 13711001100, 10024, "event has started"), ("phone_error", 1, 10100001111, 10025, "user phone null"), ("eid_phone_error", 1, 13511001102, 10026, "user did not participate in the conference"), ("has_sign_in", 1, 13511001101, 10027, "user has sign in"), ("success", 1, 13511001100, 200, "sign success"), ]) <NEW_LINE> def test_user_sign(self, name, eid, phone, status, msg): <NEW_LINE> <INDENT> payload = {'eid':eid, 'phone':phone} <NEW_LINE> r = requests.post(self.base_url, data=payload) <NEW_LINE> self.result = r.json() <NEW_LINE> if status == 200: <NEW_LINE> <INDENT> self.assertEqual(self.result['message'], msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertEqual(self.result['status'], status) <NEW_LINE> self.assertEqual(self.result['message'], msg)
用户签到
62599045d6c5a102081e344b
class BooleanType(Type): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(BooleanType, self).__init__("boolean", bool) <NEW_LINE> <DEDENT> VALUES = {"yes":1, "true":1, "on":1, "no":0, "false":0, "off":0} <NEW_LINE> def validate(self, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if isinstance(value, (PY_STRING_TYPE, PY_TEXT_TYPE)): <NEW_LINE> <INDENT> return self.VALUES[value.lower()] <NEW_LINE> <DEDENT> return bool(value) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValidationError("Invalid Boolean value '%r'"%value)
A boolean schema type
6259904576d4e153a661dc0d
class OPT(SCPINode, SCPIQuery): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "*OPT" <NEW_LINE> args = []
*OPT Arguments:
6259904521a7993f00c67299
class HashFunction(): <NEW_LINE> <INDENT> def __init__(self, out_len=0, key_len=0, N=0): <NEW_LINE> <INDENT> self.key_len, self.out_len, self.N = key_len, out_len, N <NEW_LINE> self.hashes = {} <NEW_LINE> self.hashes_int = {} <NEW_LINE> <DEDENT> def hash(self, message, key=None): <NEW_LINE> <INDENT> if (key is not None and len(key) is not self.key_len): <NEW_LINE> <INDENT> raise ValueError("Invalid key length, key length was: " + str(len(key)) + " should be: " + str(self.key_len) + ".") <NEW_LINE> <DEDENT> if self.out_len == 0: <NEW_LINE> <INDENT> raise ValueError("Invalid output length: length must be nonzero") <NEW_LINE> <DEDENT> if not (key, message) in self.hashes: <NEW_LINE> <INDENT> self.hashes[(key, message)] = random_string(self.out_len) <NEW_LINE> <DEDENT> return self.hashes[(key, message)] <NEW_LINE> <DEDENT> def hash_int(self, message): <NEW_LINE> <INDENT> if self.N == 0: <NEW_LINE> <INDENT> raise ValueError("Invalid modulus: modulus must be nonzero") <NEW_LINE> <DEDENT> if not in_Z_N_star(message, self.N): <NEW_LINE> <INDENT> raise ValueError("Invalid message: message not in Z_N^*.") <NEW_LINE> <DEDENT> if not message in self.hashes_int: <NEW_LINE> <INDENT> self.hashes_int[message] = random_Z_N_star(self.N) <NEW_LINE> <DEDENT> return self.hashes_int[message]
This class simulates a hash function. It can emulate a hash function with or without a key and with any key or output length (in bytes). Example Usage: .. testcode:: from playcrypt.ideal.hash_function import HashFunction h = HashFunction(16) h1 = h.hash("Hello World!") h2 = h.hash("H3110 W0r1d!") print str(h1 != h2 and len(h1) == h.out_len and len(h1) == len(h2)) .. testoutput:: True
6259904596565a6dacd2d922
class Config(): <NEW_LINE> <INDENT> def load(cfgpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini'), globals = globals()): <NEW_LINE> <INDENT> cfg = ConfigParser(inline_comment_prefixes=('#'), interpolation=ExtendedInterpolation()) <NEW_LINE> cfg.optionxform = str <NEW_LINE> try: <NEW_LINE> <INDENT> cfg.read(cfgpath) <NEW_LINE> <DEDENT> except MissingSectionHeaderError: <NEW_LINE> <INDENT> raise ValueError('Error in module {__file__}: no sections in config file'.format(**globals)) <NEW_LINE> <DEDENT> if not cfg.sections(): <NEW_LINE> <INDENT> raise ValueError('Error in module {__file__}: config file missing or empty'.format(**globals)) <NEW_LINE> <DEDENT> return cfg
Configuration constants.
62599045d7e4931a7ef3d3a6
class TestInvalidResourceName(BaseTestCase): <NEW_LINE> <INDENT> def test_bad_syntax(self): <NEW_LINE> <INDENT> e = rname.InvalidResourceName.bad_syntax("syntax", "resource") <NEW_LINE> assert str(e) == "Could not parse 'resource'. The syntax is 'syntax'." <NEW_LINE> e = rname.InvalidResourceName.bad_syntax("syntax", "resource", "ex") <NEW_LINE> assert str(e) == "Could not parse 'resource'. The syntax is 'syntax' (ex)." <NEW_LINE> <DEDENT> def test_subclass_notfound(self): <NEW_LINE> <INDENT> e = rname.InvalidResourceName.subclass_notfound("inter") <NEW_LINE> assert str(e) == "Parser not found for: inter." <NEW_LINE> e = rname.InvalidResourceName.subclass_notfound("inter", "resource") <NEW_LINE> assert str(e) == "Could not parse 'resource'. Parser not found for: inter." <NEW_LINE> <DEDENT> def test_rc_notfound(self): <NEW_LINE> <INDENT> e = rname.InvalidResourceName.rc_notfound("inter") <NEW_LINE> assert str(e) == "Resource class for inter not provided and default not found." <NEW_LINE> e = rname.InvalidResourceName.rc_notfound("inter", "resource") <NEW_LINE> assert str(e) == ( "Could not parse 'resource'. " "Resource class for inter not provided and default not found." )
Test the creation of InvalidResourceName errors.
6259904550485f2cf55dc2b7
class OpenStackAction(base.Action): <NEW_LINE> <INDENT> _kwargs_for_run = {} <NEW_LINE> _client_class = None <NEW_LINE> client_method_name = None <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self._kwargs_for_run = kwargs <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def _get_client(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_client_method(cls, client): <NEW_LINE> <INDENT> hierarchy_list = cls.client_method_name.split('.') <NEW_LINE> attribute = client <NEW_LINE> for attr in hierarchy_list: <NEW_LINE> <INDENT> attribute = getattr(attribute, attr) <NEW_LINE> <DEDENT> return attribute <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_fake_client(cls): <NEW_LINE> <INDENT> return cls._client_class() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_fake_client_method(cls): <NEW_LINE> <INDENT> return cls._get_client_method(cls._get_fake_client()) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> method = self._get_client_method(self._get_client()) <NEW_LINE> result = method(**self._kwargs_for_run) <NEW_LINE> if inspect.isgenerator(result): <NEW_LINE> <INDENT> return [v for v in result] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> LOG.warning(traceback.format_exc()) <NEW_LINE> e_str = '%s: %s' % (type(e), e.message) <NEW_LINE> raise exc.ActionException( "%s.%s failed: %s" % (self.__class__.__name__, self.client_method_name, e_str) ) <NEW_LINE> <DEDENT> <DEDENT> def test(self): <NEW_LINE> <INDENT> return dict( zip(self._kwargs_for_run, ['test'] * len(self._kwargs_for_run)) )
OpenStack Action. OpenStack Action is the basis of all OpenStack-specific actions, which are constructed via OpenStack Action generators.
62599045dc8b845886d548ea
class GrayscaleHistograms(Histograms): <NEW_LINE> <INDENT> def __init__(self, image_kwargs, *args, **kwargs): <NEW_LINE> <INDENT> self.kwargs = image_kwargs <NEW_LINE> super(GrayscaleHistograms, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def predict(self, observations): <NEW_LINE> <INDENT> rankings = [] <NEW_LINE> for observation_num, (screen_video, page_video) in enumerate(observations): <NEW_LINE> <INDENT> LOGGER.debug("Processing observation number %d / %d ...", observation_num + 1, len(observations)) <NEW_LINE> screens = screen_video.screens <NEW_LINE> pages = page_video.pages <NEW_LINE> for screen in screens: <NEW_LINE> <INDENT> LOGGER.debug("Processing %s ...", screen) <NEW_LINE> screen_histogram = Image(screen, **self.kwargs).get_histogram()[0] <NEW_LINE> ranking = [] <NEW_LINE> for page in pages: <NEW_LINE> <INDENT> LOGGER.debug("Processing %s ...", page) <NEW_LINE> page_histogram = Image(page, **self.kwargs).get_histogram()[0] <NEW_LINE> score = self._compare_histograms(screen_histogram, page_histogram) <NEW_LINE> ranking.append(score if self.measure in HISTOGRAM_SIMILARITIES else -score) <NEW_LINE> LOGGER.debug("Done processing %s.", page) <NEW_LINE> <DEDENT> rankings.append(ranking) <NEW_LINE> LOGGER.debug("Done processing %s.", screen) <NEW_LINE> <DEDENT> LOGGER.debug("Done processing observation number %d / %d.", observation_num + 1, len(observations)) <NEW_LINE> <DEDENT> return rankings <NEW_LINE> <DEDENT> def _filename(self): <NEW_LINE> <INDENT> return "%s.%s-%s-%s" % (__name__, self.__class__.__name__, sorted(self.kwargs.items()), self.measure) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Grayscale histograms (%s, %s)" % (self.kwargs, self.measure)
This class represents a task 1, subtask A model that ranks pairs of images based on the difference in their grayscale histograms.
625990454e696a045264e7b9
class Corps(): <NEW_LINE> <INDENT> def __init__(self, masse, position, vitesse): <NEW_LINE> <INDENT> self._masse = masse <NEW_LINE> self._position = position <NEW_LINE> self._vitesse = vitesse <NEW_LINE> <DEDENT> @property <NEW_LINE> def masse(self): <NEW_LINE> <INDENT> return self._masse <NEW_LINE> <DEDENT> @masse.setter <NEW_LINE> def masse(self, masse): <NEW_LINE> <INDENT> self._masse = masse <NEW_LINE> <DEDENT> @property <NEW_LINE> def position(self): <NEW_LINE> <INDENT> return self._position <NEW_LINE> <DEDENT> @position.setter <NEW_LINE> def position(self, position): <NEW_LINE> <INDENT> self._position = position <NEW_LINE> <DEDENT> @property <NEW_LINE> def vitesse(self): <NEW_LINE> <INDENT> return self._vitesse <NEW_LINE> <DEDENT> @vitesse.setter <NEW_LINE> def vitesse(self, vitesse): <NEW_LINE> <INDENT> self._vitesse = vitesse
Cette classe est un corps qui a une masse, une position et une vitesse, ceci en 2D.
62599045097d151d1a2c239b
class ECCError(Exception): <NEW_LINE> <INDENT> pass
Indicates that something went wrong during communication with the ECC server.
62599045e64d504609df9d69
class Menubar(tkinter.Menu): <NEW_LINE> <INDENT> def __init__(self, parent, main_window): <NEW_LINE> <INDENT> super().__init__(tearoff=0) <NEW_LINE> self.parent = parent <NEW_LINE> self.main_window = main_window <NEW_LINE> self.file_menu = tkinter.Menu(self, tearoff=0) <NEW_LINE> self.file_menu.add_command(label="New fractal", image=main_window.icons.fractal_new_icon, compound="left", underline=0, accelerator="Ctrl+N", command=self.command_fractal_type_dialog) <NEW_LINE> self.file_menu.add_separator() <NEW_LINE> self.file_menu.add_command(label="Load fractal", image=main_window.icons.file_open_icon, compound="left", underline=0, accelerator="Ctrl+L") <NEW_LINE> self.file_menu.add_command(label="Save fractal", image=main_window.icons.file_save_icon, compound="left", underline=0, accelerator="Ctrl+S") <NEW_LINE> self.file_menu.add_separator() <NEW_LINE> self.file_menu.add_command(label="Quit", image=main_window.icons.exit_icon, compound="left", underline=0, accelerator="Ctrl+Q", command=parent.quit) <NEW_LINE> self.renderer_menu = tkinter.Menu(self, tearoff=0) <NEW_LINE> self.compositor_menu = tkinter.Menu(self, tearoff=0) <NEW_LINE> self.palette_menu = tkinter.Menu(self, tearoff=0) <NEW_LINE> self.palette_menu.add_command(label="Load palette", image=main_window.icons.file_open_icon, compound="left", underline=0) <NEW_LINE> self.palette_menu.add_command(label="Save palette", image=main_window.icons.file_save_icon, compound="left", underline=0) <NEW_LINE> self.palette_menu.add_command(label="Palette editor", image=main_window.icons.edit_icon, compound="left", underline=0) <NEW_LINE> self.help_menu = tkinter.Menu(self, tearoff=0) <NEW_LINE> self.help_menu.add_command(label="Help", image=main_window.icons.help_faq_icon, compound="left", underline=0, accelerator="F1", command=help) <NEW_LINE> self.help_menu.add_separator() <NEW_LINE> self.help_menu.add_command(label="About", image=main_window.icons.help_about_icon, accelerator="F11", compound="left", underline=0, command=about) <NEW_LINE> self.add_cascade(label="File", menu=self.file_menu, underline=0) <NEW_LINE> self.add_cascade(label="Renderer", menu=self.renderer_menu, underline=0) <NEW_LINE> self.add_cascade(label="Compositor", menu=self.compositor_menu, underline=0) <NEW_LINE> self.add_cascade(label="Palette", menu=self.palette_menu, underline=0) <NEW_LINE> self.add_cascade(label="Help", menu=self.help_menu, underline=0) <NEW_LINE> self.parent.bind('<F1>', lambda event: help()) <NEW_LINE> self.parent.bind('<F11>', lambda event: about()) <NEW_LINE> self.parent.bind('<Control-n>', lambda event: self.command_fractal_type_dialog()) <NEW_LINE> <DEDENT> def command_fractal_type_dialog(self): <NEW_LINE> <INDENT> select_fractal_type_dialog()
Menu bar displayed on the main window.
625990458da39b475be04520
class Loader: <NEW_LINE> <INDENT> def __init__(self, config='~/.f2mrc', silent=False): <NEW_LINE> <INDENT> self.silent = silent <NEW_LINE> try: <NEW_LINE> <INDENT> with open(os.path.expanduser(config), 'r') as f: <NEW_LINE> <INDENT> self.config = json.loads(f.read()) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> self.output('WARNING: could not open config "{}"'.format(config)) <NEW_LINE> self.config = {'feeds': {}, 'db': None, 'maildir': None} <NEW_LINE> <DEDENT> <DEDENT> def output(self, arg): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> print(arg)
Loads the config/list of feeds from a file
62599045462c4b4f79dbcd2f
class City: <NEW_LINE> <INDENT> def __init__(self, name, city_height, city_width, tiles): <NEW_LINE> <INDENT> self.name: str = name <NEW_LINE> self.CITY_HEIGHT: int = city_height <NEW_LINE> self.CITY_WIDTH: int = city_width <NEW_LINE> self.__tiles: list = tiles <NEW_LINE> assert len(self.__tiles) == self.CITY_HEIGHT and len(self.__tiles[0]) == self.CITY_WIDTH, "Dimension mismatch!" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> res: str = "" <NEW_LINE> for row in range(self.CITY_HEIGHT): <NEW_LINE> <INDENT> curr: str = "|" <NEW_LINE> for col in range(self.CITY_WIDTH): <NEW_LINE> <INDENT> curr += str(self.__tiles[row][col]) + "|" <NEW_LINE> <DEDENT> res += str(curr) + "\n" <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> def get_tiles(self): <NEW_LINE> <INDENT> return self.__tiles <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> return copy.deepcopy(self)
This class contains attributes of a city in Mithoter Planet.
62599045ec188e330fdf9bcc
class ConnectMongoDB(): <NEW_LINE> <INDENT> def __init__(self, host='localhost', port=27017): <NEW_LINE> <INDENT> self.client = MongoClient(host, port) <NEW_LINE> dbName = 'blog' <NEW_LINE> self.db = self.client[dbName] <NEW_LINE> <DEDENT> def get_collection(self, tableName): <NEW_LINE> <INDENT> return self.db[tableName] <NEW_LINE> <DEDENT> def insert_list(self, collection, list2save): <NEW_LINE> <INDENT> print('向%s中插入数据%s' % (collection.name, list2save)) <NEW_LINE> return collection.insert(list2save) <NEW_LINE> <DEDENT> def update_data(self, collection, condition, newData,upsert=False,multi=False): <NEW_LINE> <INDENT> print('更新%s中数据;条件:%s;新数据:%s' % (collection, condition, newData)) <NEW_LINE> return collection.update(condition, newData,upsert=upsert,multi=multi) <NEW_LINE> <DEDENT> def find_data(self, collection, condition={}): <NEW_LINE> <INDENT> return collection.find(condition) <NEW_LINE> <DEDENT> def find_one_data(self, collection, _id): <NEW_LINE> <INDENT> return collection.find_one({"_id": ObjectId(_id)}) <NEW_LINE> <DEDENT> def remove_all_data(self, collection): <NEW_LINE> <INDENT> print('删除全部数据') <NEW_LINE> return collection.remove() <NEW_LINE> <DEDENT> def remove_one_data(self,collection,condition): <NEW_LINE> <INDENT> print('删除:%s条件:%s' % (collection, condition)) <NEW_LINE> return collection.remove(condition)
连接MongoDB,且提供插入,更新,删除,查询的操作
6259904545492302aabfd80d
@add_common_docstring(**_frame_parameters()) <NEW_LINE> class HeliographicCarrington(BaseHeliographic): <NEW_LINE> <INDENT> name = "heliographic_carrington" <NEW_LINE> _wrap_angle = 360*u.deg <NEW_LINE> observer = ObserverCoordinateAttribute(HeliographicStonyhurst)
A coordinate or frame in the Carrington Heliographic (HGC) system. - The origin is the center of the Sun. - The Z-axis (+90 degrees latitude) is aligned with the Sun's north pole. - The X-axis and Y-axis rotate with a period of 25.38 days. This system differs from Stonyhurst Heliographic (HGS) in its definition of longitude. This longitude is an "apparent" longitude because it takes into account the time it takes for light to travel from the Sun's surface to the observer. Thus, the observer needs to be specified to be able to transform to any other coordinate frame. A new instance can be created using the following signatures (note that if supplied, ``obstime`` and ``observer`` must be a keyword argument):: HeliographicCarrington(lon, lat, obstime=obstime, observer=observer) HeliographicCarrington(lon, lat, radius, obstime=obstime, observer=observer) If you want to define the location in HGC such that the observer for the coordinate frame is the same as that location (e.g., the location of an observatory in its corresponding HGC frame), use ``observer='self'``:: HeliographicCarrington(lon, lat, radius, obstime=obstime, observer='self') Parameters ---------- {data} {lonlat} {radius} {observer} {common} Examples -------- >>> from astropy.coordinates import SkyCoord >>> import sunpy.coordinates >>> import astropy.units as u >>> sc = SkyCoord(1*u.deg, 2*u.deg, 3*u.km, ... frame="heliographic_carrington", ... observer="earth", ... obstime="2010/01/01T00:00:30") >>> sc <SkyCoord (HeliographicCarrington: obstime=2010-01-01T00:00:30.000, observer=<HeliographicStonyhurst Coordinate for 'earth'>): (lon, lat, radius) in (deg, deg, km) (1., 2., 3.)> >>> sc = SkyCoord([1,2,3]*u.deg, [4,5,6]*u.deg, [5,6,7]*u.km, ... obstime="2010/01/01T00:00:45", ... observer="self", ... frame="heliographic_carrington") >>> sc <SkyCoord (HeliographicCarrington: obstime=2010-01-01T00:00:45.000, observer=self): (lon, lat, radius) in (deg, deg, km) [(1., 4., 5.), (2., 5., 6.), (3., 6., 7.)]> >>> sc = SkyCoord(CartesianRepresentation(0*u.km, 45*u.km, 2*u.km), ... obstime="2011/01/05T00:00:50", ... frame="heliographic_carrington") >>> sc <SkyCoord (HeliographicCarrington: obstime=2011-01-05T00:00:50.000, observer=None): (lon, lat, radius) in (deg, deg, km) (90., 2.54480438, 45.04442252)>
62599045d99f1b3c44d069d1
class ApiException(Exception): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_message(errorCode): <NEW_LINE> <INDENT> return ErrorCode.ERROR_MESSAGE.get(errorCode, 2000) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_error_result(errorCode): <NEW_LINE> <INDENT> return { "msg": ApiException.get_message(errorCode), "errorCode": str(errorCode), } <NEW_LINE> <DEDENT> @property <NEW_LINE> def error_result(self): <NEW_LINE> <INDENT> return self.get_error_result(self.errorCode) <NEW_LINE> <DEDENT> def __init__(self, errorCode=None): <NEW_LINE> <INDENT> self.errorCode = errorCode <NEW_LINE> self.message = self.get_message(self.errorCode)
全局错误码exception,搭配ErrorCode使用
625990453eb6a72ae038b994
class NiceAverageCopier(Player): <NEW_LINE> <INDENT> name = 'Nice Average Copier' <NEW_LINE> classifier = { 'memory_depth': float('inf'), 'stochastic': True, 'makes_use_of': set(), 'inspects_source': False, 'manipulates_source': False, 'manipulates_state': False } <NEW_LINE> @staticmethod <NEW_LINE> def strategy(opponent): <NEW_LINE> <INDENT> if len(opponent.history) == 0: <NEW_LINE> <INDENT> return Actions.C <NEW_LINE> <DEDENT> p = opponent.cooperations // len(opponent.history) <NEW_LINE> return random_choice(p)
Same as Average Copier, but always starts by cooperating.
6259904523849d37ff8523ee
class CollisionSystem(system.System): <NEW_LINE> <INDENT> def __init__(self, entity_manager=None, *args, **kwargs): <NEW_LINE> <INDENT> super(CollisionSystem, self).__init__(*args, **kwargs) <NEW_LINE> self.entity_manager = entity_manager <NEW_LINE> <DEDENT> def update(self, dt): <NEW_LINE> <INDENT> col_components, trans_components = self.entity_manager.get_all_components_of_types([Collidable, Transform]) <NEW_LINE> for i in xrange(len(col_components)): <NEW_LINE> <INDENT> for j in xrange(i+1, len(col_components)): <NEW_LINE> <INDENT> collided = self.check_collision((col_components[i], trans_components[i]), (col_components[j], trans_components[j])) <NEW_LINE> if collided: <NEW_LINE> <INDENT> col_components[i].collided = True <NEW_LINE> col_components[j].collided = True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def check_collision(self, i, j): <NEW_LINE> <INDENT> collision_distance = i[0].collision_distance + j[0].collision_distance <NEW_LINE> actual_distance = self.distance((i[1].x, i[1].y), (j[1].x, j[1].y)) <NEW_LINE> return (actual_distance <= collision_distance) <NEW_LINE> <DEDENT> def distance(self, point_1=(0, 0), point_2=(0, 0)): <NEW_LINE> <INDENT> return math.sqrt((point_1[0]-point_2[0])**2+(point_1[1]-point_2[1])**2)
Collision System.
6259904573bcbd0ca4bcb5be
class ProtectedItemOperationResultsOperations(object): <NEW_LINE> <INDENT> models = _models <NEW_LINE> def __init__(self, client, config, serializer, deserializer): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self._config = config <NEW_LINE> <DEDENT> @distributed_trace <NEW_LINE> def get( self, vault_name: str, resource_group_name: str, fabric_name: str, container_name: str, protected_item_name: str, operation_id: str, **kwargs: Any ) -> Optional["_models.ProtectedItemResource"]: <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> request = build_get_request( vault_name=vault_name, resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, fabric_name=fabric_name, container_name=container_name, protected_item_name=protected_item_name, operation_id=operation_id, template_url=self.get.metadata['url'], ) <NEW_LINE> request = _convert_request(request) <NEW_LINE> request.url = self._client.format_url(request.url) <NEW_LINE> pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200, 202, 204]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> raise HttpResponseError(response=response, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> deserialized = None <NEW_LINE> if response.status_code == 200: <NEW_LINE> <INDENT> deserialized = self._deserialize('ProtectedItemResource', pipeline_response) <NEW_LINE> <DEDENT> if cls: <NEW_LINE> <INDENT> return cls(pipeline_response, deserialized, {}) <NEW_LINE> <DEDENT> return deserialized <NEW_LINE> <DEDENT> get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/operationResults/{operationId}'}
ProtectedItemOperationResultsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.recoveryservicesbackup.activestamp.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer.
6259904523e79379d538d831
class DivisionViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = Division.objects.all() <NEW_LINE> serializer_class = DivisionSerializer <NEW_LINE> permission_classes = [permissions.AllowAny]
Division means Class
625990456fece00bbacccce7
class time_tracker(object): <NEW_LINE> <INDENT> def __init__(self, f): <NEW_LINE> <INDENT> self.f = f <NEW_LINE> self.counter = 0 <NEW_LINE> self.total_time = 0 <NEW_LINE> self.__name__ = f.__name__ <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> from time import time, ctime <NEW_LINE> start_time = time() <NEW_LINE> for i in range(REPITITION): <NEW_LINE> <INDENT> result = self.f(*args) <NEW_LINE> <DEDENT> end_time = time() <NEW_LINE> spent_time = (end_time - start_time) * 1000 <NEW_LINE> self.counter += 1 <NEW_LINE> self.total_time += spent_time <NEW_LINE> print(ctime(),'[TIME]Function', '\''+ self.__name__ + '\'', 'called', REPITITION, 'times') <NEW_LINE> print(ctime(),'[TIME]Time spent:,', '{:.2f}'.format(spent_time), 'ms') <NEW_LINE> print(ctime(),'[TIME]Total time spent:', '{:.2f}'.format(self.total_time), 'ms') <NEW_LINE> return result
track number of function calls, cost of time, and total time
6259904573bcbd0ca4bcb5bf
@final <NEW_LINE> class Const(Value): <NEW_LINE> <INDENT> src_loc = None <NEW_LINE> @staticmethod <NEW_LINE> def normalize(value, shape): <NEW_LINE> <INDENT> width, signed = shape <NEW_LINE> mask = (1 << width) - 1 <NEW_LINE> value &= mask <NEW_LINE> if signed and value >> (width - 1): <NEW_LINE> <INDENT> value |= ~mask <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def __init__(self, value, shape=None, *, src_loc_at=0): <NEW_LINE> <INDENT> self.value = int(value) <NEW_LINE> if shape is None: <NEW_LINE> <INDENT> shape = Shape(bits_for(self.value), signed=self.value < 0) <NEW_LINE> <DEDENT> elif isinstance(shape, int): <NEW_LINE> <INDENT> shape = Shape(shape, signed=self.value < 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shape = Shape.cast(shape, src_loc_at=1 + src_loc_at) <NEW_LINE> <DEDENT> self.width, self.signed = shape <NEW_LINE> self.value = self.normalize(self.value, shape) <NEW_LINE> <DEDENT> def shape(self): <NEW_LINE> <INDENT> return Shape(self.width, self.signed) <NEW_LINE> <DEDENT> def _rhs_signals(self): <NEW_LINE> <INDENT> return ValueSet() <NEW_LINE> <DEDENT> def _as_const(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "(const {}'{}d{})".format(self.width, "s" if self.signed else "", self.value)
A constant, literal integer value. Parameters ---------- value : int shape : int or tuple or None Either an integer ``width`` or a tuple ``(width, signed)`` specifying the number of bits in this constant and whether it is signed (can represent negative values). ``shape`` defaults to the minimum possible width and signedness of ``value``. Attributes ---------- width : int signed : bool
62599045462c4b4f79dbcd31
class LsitsParam(Model): <NEW_LINE> <INDENT> def __init__(self, switchtype: str=None, line: str=None, station: str=None, eletype: str=None, swtichstatus: str=None): <NEW_LINE> <INDENT> self.swagger_types = { 'switchtype': str, 'line': str, 'station': str, 'eletype': str, 'swtichstatus': str } <NEW_LINE> self.attribute_map = { 'switchtype': 'switchtype', 'line': 'line', 'station': 'station', 'eletype': 'eletype', 'swtichstatus': 'swtichstatus' } <NEW_LINE> self._switchtype = switchtype <NEW_LINE> self._line = line <NEW_LINE> self._station = station <NEW_LINE> self._eletype = eletype <NEW_LINE> self._swtichstatus = swtichstatus <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'LsitsParam': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def switchtype(self) -> str: <NEW_LINE> <INDENT> return self._switchtype <NEW_LINE> <DEDENT> @switchtype.setter <NEW_LINE> def switchtype(self, switchtype: str): <NEW_LINE> <INDENT> self._switchtype = switchtype <NEW_LINE> <DEDENT> @property <NEW_LINE> def line(self) -> str: <NEW_LINE> <INDENT> return self._line <NEW_LINE> <DEDENT> @line.setter <NEW_LINE> def line(self, line: str): <NEW_LINE> <INDENT> self._line = line <NEW_LINE> <DEDENT> @property <NEW_LINE> def station(self) -> str: <NEW_LINE> <INDENT> return self._station <NEW_LINE> <DEDENT> @station.setter <NEW_LINE> def station(self, station: str): <NEW_LINE> <INDENT> self._station = station <NEW_LINE> <DEDENT> @property <NEW_LINE> def eletype(self) -> str: <NEW_LINE> <INDENT> return self._eletype <NEW_LINE> <DEDENT> @eletype.setter <NEW_LINE> def eletype(self, eletype: str): <NEW_LINE> <INDENT> self._eletype = eletype <NEW_LINE> <DEDENT> @property <NEW_LINE> def swtichstatus(self) -> str: <NEW_LINE> <INDENT> return self._swtichstatus <NEW_LINE> <DEDENT> @swtichstatus.setter <NEW_LINE> def swtichstatus(self, swtichstatus: str): <NEW_LINE> <INDENT> self._swtichstatus = swtichstatus
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259904576d4e153a661dc0f
class CheckingClassifier(ClassifierMixin, BaseEstimator): <NEW_LINE> <INDENT> def __init__(self, check_y=None, check_X=None, foo_param=0, expected_fit_params=None): <NEW_LINE> <INDENT> self.check_y = check_y <NEW_LINE> self.check_X = check_X <NEW_LINE> self.foo_param = foo_param <NEW_LINE> self.expected_fit_params = expected_fit_params <NEW_LINE> <DEDENT> def fit(self, X, y, **fit_params): <NEW_LINE> <INDENT> assert len(X) == len(y) <NEW_LINE> if self.check_X is not None: <NEW_LINE> <INDENT> assert self.check_X(X) <NEW_LINE> <DEDENT> if self.check_y is not None: <NEW_LINE> <INDENT> assert self.check_y(y) <NEW_LINE> <DEDENT> self.classes_ = np.unique(check_array(y, ensure_2d=False, allow_nd=True)) <NEW_LINE> if self.expected_fit_params: <NEW_LINE> <INDENT> missing = set(self.expected_fit_params) - set(fit_params) <NEW_LINE> assert len(missing) == 0, 'Expected fit parameter(s) %s not ' 'seen.' % list(missing) <NEW_LINE> for key, value in fit_params.items(): <NEW_LINE> <INDENT> assert len(value) == len(X), ( 'Fit parameter %s has length %d; ' 'expected %d.' % (key, len(value), len(X))) <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def predict(self, T): <NEW_LINE> <INDENT> if self.check_X is not None: <NEW_LINE> <INDENT> assert self.check_X(T) <NEW_LINE> <DEDENT> return self.classes_[np.zeros(_num_samples(T), dtype=np.int)] <NEW_LINE> <DEDENT> def score(self, X=None, Y=None): <NEW_LINE> <INDENT> if self.foo_param > 1: <NEW_LINE> <INDENT> score = 1. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> score = 0. <NEW_LINE> <DEDENT> return score <NEW_LINE> <DEDENT> def _more_tags(self): <NEW_LINE> <INDENT> return {'_skip_test': True, 'X_types': ['1dlabel']}
Dummy classifier to test pipelining and meta-estimators. Checks some property of X and y in fit / predict. This allows testing whether pipelines / cross-validation or metaestimators changed the input. Parameters ---------- check_y check_X foo_param expected_fit_params Attributes ---------- classes_
62599045287bf620b6272f1b
class PluginMount(type): <NEW_LINE> <INDENT> def __init__(cls, name, bases, attrs): <NEW_LINE> <INDENT> if not hasattr(cls, "plugins"): <NEW_LINE> <INDENT> cls.plugins = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not hasattr(cls, "__omitted__"): <NEW_LINE> <INDENT> cls.plugins.append(cls)
Generic plugin mount point (= entry point) for pydifact plugins. .. note:: Plugins that have an **__omitted__** attriute are not added to the list!
62599045baa26c4b54d505dd
class OutputGadget(Gadget): <NEW_LINE> <INDENT> pass
any gadget that produces some signal to the outside world should inherit this.
62599045d99f1b3c44d069d2
class LeNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(LeNet, self).__init__() <NEW_LINE> self.conv1 = nn.Conv2d(1, 6, 3) <NEW_LINE> self.conv2 = nn.Conv2d(6, 16, 3) <NEW_LINE> self.drop1 = nn.Dropout(p=0.5) <NEW_LINE> self.fc1 = nn.Linear(16 * 6 * 6, 120) <NEW_LINE> self.drop2 = nn.Dropout(p=0.2) <NEW_LINE> self.fc2 = nn.Linear(120, 84) <NEW_LINE> self.fc3 = nn.Linear(84, 2) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = F.max_pool2d(F.relu(self.conv1(x)), 2) <NEW_LINE> x = F.max_pool2d(F.relu(self.conv2(x)), 2) <NEW_LINE> x = self.drop1(x) <NEW_LINE> x = x.view(-1, 16 * 6 * 6) <NEW_LINE> x = F.relu(self.fc1(x)) <NEW_LINE> x = self.drop2(x) <NEW_LINE> x = F.relu(self.fc2(x)) <NEW_LINE> x = F.softmax(self.fc3(x), dim=1) <NEW_LINE> return x
LeNet CNN architecture.
6259904545492302aabfd80f
class DeleteCharactersCharacterIdContactsInternalServerError(object): <NEW_LINE> <INDENT> def __init__(self, error=None): <NEW_LINE> <INDENT> self.swagger_types = { 'error': 'str' } <NEW_LINE> self.attribute_map = { 'error': 'error' } <NEW_LINE> self._error = error <NEW_LINE> <DEDENT> @property <NEW_LINE> def error(self): <NEW_LINE> <INDENT> return self._error <NEW_LINE> <DEDENT> @error.setter <NEW_LINE> def error(self, error): <NEW_LINE> <INDENT> self._error = error <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_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 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, DeleteCharactersCharacterIdContactsInternalServerError): <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 the swagger code generator program. Do not edit the class manually.
6259904550485f2cf55dc2ba