code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ActivityStreamCompanyViewSet(BaseActivityStreamViewSet): <NEW_LINE> <INDENT> @decorator_from_middleware(ActivityStreamHawkResponseMiddleware) <NEW_LINE> def list(self, request): <NEW_LINE> <INDENT> after_ts, after_id = self._parse_after(request) <NEW_LINE> companies = list( Company.objects.filter( Q(modified=after_ts, id__gt=after_id) | Q(modified__gt=after_ts), date_published__isnull=False ).order_by('modified', 'id')[:MAX_PER_PAGE] ) <NEW_LINE> return self._generate_response( ActivityStreamCompanySerializer(companies, many=True).data, self._build_after(request, companies[-1].modified, companies[-1].id) if companies else None, ) | View set to list companies for the activity stream | 6259903966673b3332c315a1 |
class ConstraintViolation(WebException): <NEW_LINE> <INDENT> pass | The request violated some constraint or integrity within the data model. | 625990391d351010ab8f4cc7 |
class VatsimClient(LineReceiver): <NEW_LINE> <INDENT> cid = "" <NEW_LINE> password = "" <NEW_LINE> realname = "" <NEW_LINE> callsign = "ZAU_OBS" <NEW_LINE> lat ="41.786111" <NEW_LINE> lon = "-87.7525" <NEW_LINE> def sendRawResponse(self,rawResponse): <NEW_LINE> <INDENT> log.msg(">> %s" % rawResponse) <NEW_LINE> self.sendLine(rawResponse) <NEW_LINE> <DEDENT> def sendResponse(self, controlCode, response): <NEW_LINE> <INDENT> self.sendRawResponse("%s%s:%s"% (controlCode,self.callsign,response)) <NEW_LINE> <DEDENT> def sendDirectResponse(self, controlCode, dest, response): <NEW_LINE> <INDENT> rawResponse = '%s%s:%s:%s' % (controlCode,self.callsign,dest,response) <NEW_LINE> self.sendRawResponse(rawResponse) <NEW_LINE> <DEDENT> def serverResponseBuilder(self, controlCode, response): <NEW_LINE> <INDENT> response = ":".join(response) <NEW_LINE> self.sendDirectResponse(controlCode,"SERVER",response) <NEW_LINE> <DEDENT> def connectionMade(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def lineReceived(self, line): <NEW_LINE> <INDENT> controlCode = line[:3] <NEW_LINE> splitLine = line[3:].split(':') <NEW_LINE> log.msg( "<< %s: %s" % (controlCode, splitLine)) <NEW_LINE> if '$DI' in controlCode: <NEW_LINE> <INDENT> if 'CLIENT' in splitLine[1]: <NEW_LINE> <INDENT> self.vathash = VatHasher(splitLine[3]) <NEW_LINE> log.msg(self.vathash.serverSalt) <NEW_LINE> response = [] <NEW_LINE> response.append("2110") <NEW_LINE> response.append("vSTARS") <NEW_LINE> response.append("1") <NEW_LINE> response.append("0") <NEW_LINE> response.append(self.cid) <NEW_LINE> response.append("462CEBA3") <NEW_LINE> self.serverResponseBuilder("$ID",response) <NEW_LINE> self.sendDirectResponse('#AA','SERVER','%s:%s:%s:1:100' % (self.realname,self.cid,self.password)) <NEW_LINE> self.sendDirectResponse('$CQ','SERVER','$CQZFW_OBS:SERVER:ATC') <NEW_LINE> self.sendDirectResponse('$CQ','SERVER','IP') <NEW_LINE> self.sendRawResponse("%s%s:99998:0:150:1:%s:%s:0"%("%",self.callsign,self.lat,self.lon)) <NEW_LINE> <DEDENT> <DEDENT> elif '#TM' in controlCode: <NEW_LINE> <INDENT> if len(splitLine) > 2: <NEW_LINE> <INDENT> log.msg( "%s: %s" % (splitLine[0],splitLine[2])) <NEW_LINE> <DEDENT> <DEDENT> elif '$CR' in controlCode: <NEW_LINE> <INDENT> if 'IP' in splitLine[2]: <NEW_LINE> <INDENT> self.sendDirectResponse('$CR','SERVER','CAPS:VERSION=1:ATCINFO=1') <NEW_LINE> <DEDENT> <DEDENT> elif '$ZC' in controlCode: <NEW_LINE> <INDENT> response = [] <NEW_LINE> response.append(self.vathash.hash(splitLine[2])) <NEW_LINE> self.serverResponseBuilder('$ZR',response) <NEW_LINE> <DEDENT> elif '#DP' in controlCode: <NEW_LINE> <INDENT> self.sendRawResponse("%s%s:99998:0:150:1:%s:%s:0"%("%",self.callsign,self.lat,self.lon)) <NEW_LINE> <DEDENT> elif '@N' in controlCode: <NEW_LINE> <INDENT> log.msg( "MOVEPACKET:%s" % (":".join(splitLine))) | Vatsim Client protocol | 62599039dc8b845886d54761 |
class MineTest(ModuleCase): <NEW_LINE> <INDENT> def test_get(self): <NEW_LINE> <INDENT> self.assertTrue(self.run_function('mine.update', minion_tgt='minion')) <NEW_LINE> self.assertIsNone( self.run_function( 'mine.update', minion_tgt='sub_minion' ) ) <NEW_LINE> self.assertTrue( self.run_function( 'mine.get', ['minion', 'test.ping'] ) ) <NEW_LINE> <DEDENT> def test_send(self): <NEW_LINE> <INDENT> self.assertFalse( self.run_function( 'mine.send', ['foo.__spam_and_cheese'] ) ) <NEW_LINE> self.assertTrue( self.run_function( 'mine.send', ['grains.items'], minion_tgt='minion', ) ) <NEW_LINE> self.assertTrue( self.run_function( 'mine.send', ['grains.items'], minion_tgt='sub_minion', ) ) <NEW_LINE> ret = self.run_function( 'mine.get', ['sub_minion', 'grains.items'] ) <NEW_LINE> self.assertEqual(ret['sub_minion']['id'], 'sub_minion') <NEW_LINE> ret = self.run_function( 'mine.get', ['minion', 'grains.items'], minion_tgt='sub_minion' ) <NEW_LINE> self.assertEqual(ret['minion']['id'], 'minion') <NEW_LINE> <DEDENT> def test_mine_flush(self): <NEW_LINE> <INDENT> for minion_id in ('minion', 'sub_minion'): <NEW_LINE> <INDENT> self.assertTrue( self.run_function( 'mine.send', ['grains.items'], minion_tgt=minion_id ) ) <NEW_LINE> <DEDENT> time.sleep(1) <NEW_LINE> for minion_id in ('minion', 'sub_minion'): <NEW_LINE> <INDENT> ret = self.run_function( 'mine.get', [minion_id, 'grains.items'], minion_tgt=minion_id ) <NEW_LINE> self.assertEqual(ret[minion_id]['id'], minion_id) <NEW_LINE> <DEDENT> self.assertTrue( self.run_function( 'mine.flush', minion_tgt='minion' ) ) <NEW_LINE> ret_flushed = self.run_function( 'mine.get', ['*', 'grains.items'] ) <NEW_LINE> self.assertEqual(ret_flushed.get('minion', None), None) <NEW_LINE> self.assertEqual(ret_flushed['sub_minion']['id'], 'sub_minion') <NEW_LINE> <DEDENT> def test_mine_delete(self): <NEW_LINE> <INDENT> self.assertTrue( self.run_function( 'mine.send', ['grains.items'] ) ) <NEW_LINE> self.assertTrue( self.run_function( 'mine.send', ['test.echo', 'foo'] ) ) <NEW_LINE> ret_grains = self.run_function( 'mine.get', ['minion', 'grains.items'] ) <NEW_LINE> self.assertEqual(ret_grains['minion']['id'], 'minion') <NEW_LINE> ret_echo = self.run_function( 'mine.get', ['minion', 'test.echo'] ) <NEW_LINE> self.assertEqual(ret_echo['minion'], 'foo') <NEW_LINE> self.assertTrue( self.run_function( 'mine.delete', ['grains.items'] ) ) <NEW_LINE> ret_grains_deleted = self.run_function( 'mine.get', ['minion', 'grains.items'] ) <NEW_LINE> self.assertEqual(ret_grains_deleted.get('minion', None), None) <NEW_LINE> ret_echo_stays = self.run_function( 'mine.get', ['minion', 'test.echo'] ) <NEW_LINE> self.assertEqual(ret_echo_stays['minion'], 'foo') | Test the mine system | 625990390a366e3fb87ddb92 |
class LinodeBinarySensor(BinarySensorEntity): <NEW_LINE> <INDENT> def __init__(self, li, node_id): <NEW_LINE> <INDENT> self._linode = li <NEW_LINE> self._node_id = node_id <NEW_LINE> self._state = None <NEW_LINE> self.data = None <NEW_LINE> self._attrs = {} <NEW_LINE> self._name = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self): <NEW_LINE> <INDENT> return DEFAULT_DEVICE_CLASS <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> return self._attrs <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self._linode.update() <NEW_LINE> if self._linode.data is not None: <NEW_LINE> <INDENT> for node in self._linode.data: <NEW_LINE> <INDENT> if node.id == self._node_id: <NEW_LINE> <INDENT> self.data = node <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.data is not None: <NEW_LINE> <INDENT> self._state = self.data.status == "running" <NEW_LINE> self._attrs = { ATTR_CREATED: self.data.created, ATTR_NODE_ID: self.data.id, ATTR_NODE_NAME: self.data.label, ATTR_IPV4_ADDRESS: self.data.ipv4, ATTR_IPV6_ADDRESS: self.data.ipv6, ATTR_MEMORY: self.data.specs.memory, ATTR_REGION: self.data.region.country, ATTR_VCPUS: self.data.specs.vcpus, } <NEW_LINE> self._name = self.data.label | Representation of a Linode droplet sensor. | 6259903930c21e258be999ba |
class PairwiseSoftplusNeuralNetwork(AbstractNeuralNetworkClassifier): <NEW_LINE> <INDENT> def prepare(self): <NEW_LINE> <INDENT> n1, n2, n3 = self.layers_ <NEW_LINE> A1 = self._create_matrix_parameter('A1', n1, n2) <NEW_LINE> A2 = self._create_matrix_parameter('A2', n1, n2) <NEW_LINE> B = self._create_matrix_parameter('B', n2, n2) <NEW_LINE> def activation(input): <NEW_LINE> <INDENT> first1 = T.nnet.softplus(T.dot(input, A1)) <NEW_LINE> first2 = T.nnet.sigmoid(T.dot(input, A2)) <NEW_LINE> return T.batched_dot(T.dot(first1, B), first2) <NEW_LINE> <DEDENT> return activation | The result is computed as :math:`h1 = softplus(A_1 x)`, :math:`h2 = sigmoid(A_2 x)`,
:math:`output = \sum_{ij} B_{ij} h1_i h2_j)` | 625990398a349b6b436873f0 |
class TestIsValidPrefix(unittest.TestCase): <NEW_LINE> <INDENT> def test_invalid_prefix(self): <NEW_LINE> <INDENT> self.assertFalse(export_utils.is_valid_prefix('prefix#with*special@chars')) <NEW_LINE> <DEDENT> def test_valid_prefix(self): <NEW_LINE> <INDENT> self.assertTrue(export_utils.is_valid_prefix('No-special_chars1')) | Tests that is_valid_prefix only returns true for strings containing alphanumeric characters,
dashes, and underscores. | 6259903950485f2cf55dc12d |
class BlockStructureCache(object): <NEW_LINE> <INDENT> def __init__(self, cache): <NEW_LINE> <INDENT> self._cache = cache <NEW_LINE> <DEDENT> def add(self, block_structure): <NEW_LINE> <INDENT> data_to_cache = ( block_structure._block_relations, block_structure.transformer_data, block_structure._block_data_map, ) <NEW_LINE> zp_data_to_cache = zpickle(data_to_cache) <NEW_LINE> timeout_in_seconds = 60 * 60 * 24 <NEW_LINE> self._cache.set( self._encode_root_cache_key(block_structure.root_block_usage_key), zp_data_to_cache, timeout=timeout_in_seconds, ) <NEW_LINE> logger.info( "Wrote BlockStructure %s to cache, size: %s", block_structure.root_block_usage_key, len(zp_data_to_cache), ) <NEW_LINE> <DEDENT> def get(self, root_block_usage_key): <NEW_LINE> <INDENT> zp_data_from_cache = self._cache.get(self._encode_root_cache_key(root_block_usage_key)) <NEW_LINE> if not zp_data_from_cache: <NEW_LINE> <INDENT> logger.info( "Did not find BlockStructure %r in the cache.", root_block_usage_key, ) <NEW_LINE> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.info( "Read BlockStructure %r from cache, size: %s", root_block_usage_key, len(zp_data_from_cache), ) <NEW_LINE> <DEDENT> block_relations, transformer_data, block_data_map = zunpickle(zp_data_from_cache) <NEW_LINE> block_structure = BlockStructureModulestoreData(root_block_usage_key) <NEW_LINE> block_structure._block_relations = block_relations <NEW_LINE> block_structure.transformer_data = transformer_data <NEW_LINE> block_structure._block_data_map = block_data_map <NEW_LINE> return block_structure <NEW_LINE> <DEDENT> def delete(self, root_block_usage_key): <NEW_LINE> <INDENT> self._cache.delete(self._encode_root_cache_key(root_block_usage_key)) <NEW_LINE> logger.info( "Deleted BlockStructure %r from the cache.", root_block_usage_key, ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _encode_root_cache_key(cls, root_block_usage_key): <NEW_LINE> <INDENT> return "v{version}.root.key.{root_usage_key}".format( version=unicode(BlockStructureBlockData.VERSION), root_usage_key=unicode(root_block_usage_key), ) | Cache for BlockStructure objects. | 62599039a8ecb033258723cc |
class FacebookAppOAuth2(FacebookOAuth2): <NEW_LINE> <INDENT> name = 'facebook-app' <NEW_LINE> def uses_redirect(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def auth_complete(self, *args, **kwargs): <NEW_LINE> <INDENT> access_token = None <NEW_LINE> response = {} <NEW_LINE> if 'signed_request' in self.data: <NEW_LINE> <INDENT> key, secret = self.get_key_and_secret() <NEW_LINE> response = self.load_signed_request(self.data['signed_request']) <NEW_LINE> if not 'user_id' in response and not 'oauth_token' in response: <NEW_LINE> <INDENT> raise AuthException(self) <NEW_LINE> <DEDENT> if response is not None: <NEW_LINE> <INDENT> access_token = response.get('access_token') or response['oauth_token'] or self.data.get('access_token') <NEW_LINE> <DEDENT> <DEDENT> if access_token is None: <NEW_LINE> <INDENT> if self.data.get('error') == 'access_denied': <NEW_LINE> <INDENT> raise AuthCanceled(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AuthException(self) <NEW_LINE> <DEDENT> <DEDENT> return self.do_auth(access_token, response, *args, **kwargs) <NEW_LINE> <DEDENT> def auth_html(self): <NEW_LINE> <INDENT> key, secret = self.get_key_and_secret() <NEW_LINE> namespace = self.setting('NAMESPACE', None) <NEW_LINE> scope = self.setting('SCOPE', '') <NEW_LINE> if scope: <NEW_LINE> <INDENT> scope = self.SCOPE_SEPARATOR.join(scope) <NEW_LINE> <DEDENT> ctx = { 'FACEBOOK_APP_NAMESPACE': namespace or key, 'FACEBOOK_KEY': key, 'FACEBOOK_EXTENDED_PERMISSIONS': scope, 'FACEBOOK_COMPLETE_URI': self.redirect_uri, } <NEW_LINE> tpl = self.setting('LOCAL_HTML', 'facebook.html') <NEW_LINE> return self.strategy.render_html(tpl=tpl, context=ctx) <NEW_LINE> <DEDENT> def load_signed_request(self, signed_request): <NEW_LINE> <INDENT> def base64_url_decode(data): <NEW_LINE> <INDENT> data = data.encode('ascii') <NEW_LINE> data += '=' * (4 - (len(data) % 4)) <NEW_LINE> return base64.urlsafe_b64decode(data) <NEW_LINE> <DEDENT> key, secret = self.get_key_and_secret() <NEW_LINE> try: <NEW_LINE> <INDENT> sig, payload = signed_request.split('.', 1) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sig = base64_url_decode(sig) <NEW_LINE> data = json.loads(base64_url_decode(payload)) <NEW_LINE> expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest() <NEW_LINE> if sig == expected_sig and data['issued_at'] > (time.time() - 86400): <NEW_LINE> <INDENT> return data | Facebook Application Authentication support | 625990398da39b475be0439d |
class TouchSensor(rb.TouchSensor): <NEW_LINE> <INDENT> def __init__(self, port=ev3.INPUT_1): <NEW_LINE> <INDENT> super().__init__(port) <NEW_LINE> <DEDENT> def wait_until_pressed(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> if self.get_value()>0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def wait_until_released(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> if self.get_value()==0: <NEW_LINE> <INDENT> break | Primary author of this class: Yuanning Zuo. | 6259903971ff763f4b5e8948 |
@dataclass() <NEW_LINE> class GeneratedTX: <NEW_LINE> <INDENT> tx_context: TXContext <NEW_LINE> proposal: Proposal <NEW_LINE> signed_proposal: SignedProposal <NEW_LINE> header: Header <NEW_LINE> @property <NEW_LINE> def tx_id(self): <NEW_LINE> <INDENT> return self.tx_context.tx_id | A model to represent a transaction that has been generated but not
yet sent for endorsement | 6259903923e79379d538d6af |
class make_preconditioner(LinearOperator): <NEW_LINE> <INDENT> def __init__(self, A, prm={}): <NEW_LINE> <INDENT> Acsr = A.tocsr() <NEW_LINE> self.P = pyamgcl_ext.make_preconditioner( Acsr.indptr, Acsr.indices, Acsr.data, prm) <NEW_LINE> if [int(v) for v in scipy.__version__.split('.')] < [0, 16, 0]: <NEW_LINE> <INDENT> LinearOperator.__init__(self, A.shape, self.P) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LinearOperator.__init__(self, dtype=numpy.float64, shape=A.shape) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.P.__repr__() <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> return self.P(x.astype(numpy.float64)) <NEW_LINE> <DEDENT> def _matvec(self, x): <NEW_LINE> <INDENT> return self.__call__(x) | Algebraic multigrid hierarchy that may be used as a preconditioner with
scipy iterative solvers. | 62599039507cdc57c63a5f48 |
class TestClassificationPolicy(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testClassificationPolicy(self): <NEW_LINE> <INDENT> model = swagger_client.models.classification_policy.ClassificationPolicy() | ClassificationPolicy unit test stubs | 625990398e05c05ec3f6f732 |
class ValidateUserSchema(UserSchema): <NEW_LINE> <INDENT> age = fields.Number(validate=lambda n: 18 <= n <= 40) | This is a contrived example
You could use marshmallow.validate.Tange instead of an anonymous function here | 62599039cad5886f8bdc5953 |
class NumpyConcatenateOnCustomAxis(NonFittableMixin, BaseStep): <NEW_LINE> <INDENT> def __init__(self, axis): <NEW_LINE> <INDENT> self.axis = axis <NEW_LINE> BaseStep.__init__(self) <NEW_LINE> NonFittableMixin.__init__(self) <NEW_LINE> <DEDENT> def _transform_data_container(self, data_container, context): <NEW_LINE> <INDENT> data_inputs = self.transform([dc.data_inputs for dc in data_container.data_inputs]) <NEW_LINE> data_container = DataContainer(data_inputs=data_inputs, current_ids=data_container.current_ids, expected_outputs=data_container.expected_outputs) <NEW_LINE> data_container.set_data_inputs(data_inputs) <NEW_LINE> return data_container <NEW_LINE> <DEDENT> def transform(self, data_inputs): <NEW_LINE> <INDENT> return self._concat(data_inputs) <NEW_LINE> <DEDENT> def _concat(self, data_inputs): <NEW_LINE> <INDENT> return np.concatenate(data_inputs, axis=self.axis) | Numpy concetenation step where the concatenation is performed along the specified custom axis. | 62599039a4f1c619b294f75e |
class _Layer(object): <NEW_LINE> <INDENT> def __init__( self, num_nodes, input_layer=None, activation=None, aux_der=None ): <NEW_LINE> <INDENT> self.nodes = [] <NEW_LINE> if input_layer is None: <NEW_LINE> <INDENT> for _ in range(num_nodes): <NEW_LINE> <INDENT> self.nodes.append(_Node()) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.activation = activation <NEW_LINE> self.aux_der = aux_der <NEW_LINE> for _ in range(num_nodes): <NEW_LINE> <INDENT> self.nodes.append( _Node(input_layer.nodes) ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def forward(self, xs_=None, ys_=None): <NEW_LINE> <INDENT> if xs_ is not None: <NEW_LINE> <INDENT> if DEBUG_TRAIN: <NEW_LINE> <INDENT> print("forwarding: setting inputs") <NEW_LINE> <DEDENT> assert len(self.nodes) == len(xs_),str(len(self.nodes))+"/="+str(len(xs_)) <NEW_LINE> for node, x__ in zip(self.nodes, xs_): <NEW_LINE> <INDENT> node.state = x__ <NEW_LINE> <DEDENT> <DEDENT> elif ys_ is None: <NEW_LINE> <INDENT> if DEBUG_TRAIN: <NEW_LINE> <INDENT> print("forwarding: to a hidden layer") <NEW_LINE> <DEDENT> for node in self.nodes: <NEW_LINE> <INDENT> node.forward() <NEW_LINE> node.state = self.activation(node.state) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if DEBUG_TRAIN: <NEW_LINE> <INDENT> print("forwarding: to output layer") <NEW_LINE> <DEDENT> for node in self.nodes: <NEW_LINE> <INDENT> node.forward() <NEW_LINE> <DEDENT> activation = partial(self.activation, [node.state for node in self.nodes]) <NEW_LINE> for node in self.nodes: <NEW_LINE> <INDENT> node.state = activation(node.state) <NEW_LINE> <DEDENT> if len(ys_) > 0: <NEW_LINE> <INDENT> for node in self.nodes: <NEW_LINE> <INDENT> node.accum_partials( self.aux_der([node.state for node in self.nodes], ys_) ) <NEW_LINE> <DEDENT> if DEBUG_OUTPUT: <NEW_LINE> <INDENT> print('node states are', [node.state for node in self.nodes],end=" ") <NEW_LINE> print('ys are', ys_,end=" ") <NEW_LINE> print('aux_der is', self.aux_der([node.state for node in self.nodes], ys_)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def backprop(self, mb_adjusted_learning_rate): <NEW_LINE> <INDENT> for node in self.nodes: <NEW_LINE> <INDENT> node.adjust_weights(mb_adjusted_learning_rate) <NEW_LINE> <DEDENT> <DEDENT> def zero_grad(self): <NEW_LINE> <INDENT> for node in self.nodes: <NEW_LINE> <INDENT> node.zero_partials() | A layer in an instance of the Net class.
Args:
num_nodes (int): The number of nodes to create in this layer.
input_layer (:obj:`_Layer`, optional): None or a layer whose nodes will
feed into this layer's nodes.
activation (str, optional): A string determining this layer's activation
function.
Attributes:
nodes (:obj:`list` of :obj:`_Node`): The nodes of this layer.
activation (:obj:`function`, optional) : This layer's activation
function or None if this is the input layer..
aux_der: An auxillary function used when building partials while feeding
forward.
partials (:obj:`list` of :obj:`Number`, optional) : A list for holding the
partial derivatives needed to update the inputsLinks to the nodes of
the layer or None if this is the input layer. | 625990390a366e3fb87ddb94 |
class PhysicsEngine(object): <NEW_LINE> <INDENT> ROBOT_WIDTH = 5 <NEW_LINE> ROBOT_HEIGHT = 4 <NEW_LINE> ROBOT_STARTING_X = 18.5 <NEW_LINE> ROBOT_STARTING_Y = 12 <NEW_LINE> STARTING_ANGLE = 180 <NEW_LINE> JOYSTICKS = [1, 2] <NEW_LINE> def __init__(self, physics_controller): <NEW_LINE> <INDENT> self.physics_controller = physics_controller <NEW_LINE> self.position = 0 <NEW_LINE> self.last_tm = None <NEW_LINE> <DEDENT> def update_sim(self, now, tm_diff): <NEW_LINE> <INDENT> l_motor = wpilib.DigitalModule._pwm[0].Get() <NEW_LINE> r_motor = wpilib.DigitalModule._pwm[1].Get() <NEW_LINE> speed, rotation = drivetrains.two_motor_drivetrain(-l_motor, r_motor, 5) <NEW_LINE> self.physics_controller.drive(speed, rotation, tm_diff) | Simulates a 2-wheel robot using Tank Drive joystick control | 625990390fa83653e46f6089 |
class InitCombatCmdSet(CmdSet): <NEW_LINE> <INDENT> key = 'combat_init_cmdset' <NEW_LINE> priority = 1 <NEW_LINE> mergetype = 'Union' <NEW_LINE> def at_cmdset_creation(self): <NEW_LINE> <INDENT> self.add(CmdInitiateAttack()) | Command set containing combat starting commands | 625990398a43f66fc4bf333c |
class LolStatusApiV3(NamedEndpoint): <NEW_LINE> <INDENT> def __init__(self, base_api: BaseApi): <NEW_LINE> <INDENT> super().__init__(base_api, LolStatusApiV3.__name__) <NEW_LINE> <DEDENT> def shard_data(self, region: str): <NEW_LINE> <INDENT> return self._request_endpoint( self.shard_data.__name__, region, LolStatusApiV3Urls.shard_data ) | This class wraps the LoL-Status-v3 Api calls provided by the Riot API.
See https://developer.riotgames.com/api-methods/#lol-status-v3 for more detailed information | 6259903982261d6c5273079c |
class CumulativePresence(Graph): <NEW_LINE> <INDENT> short_name = 'cumulative_presence' <NEW_LINE> def plot(self, **kwargs): <NEW_LINE> <INDENT> num_of_otus = self.parent.otu_table.shape[1] <NEW_LINE> num_of_samples = self.parent.otu_table.shape[0] <NEW_LINE> samples_index = list(reversed(range(1, num_of_samples+1))) <NEW_LINE> counts = self.parent.otu_table.astype(bool).sum(axis=0).value_counts() <NEW_LINE> for n in samples_index: <NEW_LINE> <INDENT> if n not in counts: <NEW_LINE> <INDENT> counts = counts.set_value(n,0) <NEW_LINE> <DEDENT> <DEDENT> counts = counts.sort_index(ascending=False) <NEW_LINE> self.y = list(counts.cumsum()) <NEW_LINE> self.x = [n/num_of_samples for n in samples_index] <NEW_LINE> fig = pyplot.figure() <NEW_LINE> axes = fig.add_subplot(111) <NEW_LINE> axes.step(self.x, self.y, fillstyle='bottom') <NEW_LINE> axes.set_title('Cumulative graph of OTU presence in samples for %s OTUs' % num_of_otus) <NEW_LINE> axes.set_xlabel('Fraction of samples (100%% equates %i samples)' % num_of_samples) <NEW_LINE> axes.set_ylabel('Number of OTUs that appear in that fraction of samples or more') <NEW_LINE> axes.invert_xaxis() <NEW_LINE> axes.set_xticks([min(self.x) + (max(self.x)-min(self.x))* n / 9 for n in range(10)]) <NEW_LINE> axes.set_yscale('log') <NEW_LINE> axes.xaxis.grid(True) <NEW_LINE> percentage = lambda x, pos: '%1.0f%%' % (x*100.0) <NEW_LINE> axes.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(percentage)) <NEW_LINE> self.save_plot(fig, axes, **kwargs) <NEW_LINE> pyplot.close(fig) | Cumulative graph of cluster presence in samples. This means something such as:
- 0% of OTUs appear in 100% of the samples,
- 10% of OTUs appear in 90% of the samples,
- 90% of OTUs appear in 1% of the samples. | 62599039507cdc57c63a5f4a |
class RobustGlobalPool2dFn(torch.autograd.Function): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def runOptimisation(x, y, method, alpha_scalar): <NEW_LINE> <INDENT> with torch.enable_grad(): <NEW_LINE> <INDENT> opt = torch.optim.LBFGS([y], lr=1, max_iter=100, max_eval=None, tolerance_grad=1e-05, tolerance_change=1e-09, history_size=100, line_search_fn=None ) <NEW_LINE> def reevaluate(): <NEW_LINE> <INDENT> opt.zero_grad() <NEW_LINE> f = method.phi(y.unsqueeze(-1).unsqueeze(-1) - x, alpha=alpha_scalar).sum() <NEW_LINE> f.backward() <NEW_LINE> return f <NEW_LINE> <DEDENT> opt.step(reevaluate) <NEW_LINE> <DEDENT> return y <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def forward(ctx, x, method, alpha): <NEW_LINE> <INDENT> input_size = x.size() <NEW_LINE> assert len(input_size) >= 2, "input must at least 2D (%d < 2)" % len(input_size) <NEW_LINE> alpha_scalar = alpha.item() <NEW_LINE> assert alpha.item() > 0.0, "alpha must be strictly positive (%f <= 0)" % alpha.item() <NEW_LINE> x = x.detach() <NEW_LINE> x = x.flatten(end_dim=-3) if len(input_size) > 2 else x <NEW_LINE> if method.is_convex: <NEW_LINE> <INDENT> y = x.mean([-2, -1]).clone().requires_grad_() <NEW_LINE> y = RobustGlobalPool2dFn.runOptimisation(x, y, method, alpha_scalar) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y_mean = x.mean([-2, -1]).clone().requires_grad_() <NEW_LINE> y_mean = RobustGlobalPool2dFn.runOptimisation(x, y_mean, method, alpha_scalar) <NEW_LINE> y_median = x.flatten(start_dim=-2).median(dim=-1)[0].clone().requires_grad_() <NEW_LINE> y_median = RobustGlobalPool2dFn.runOptimisation(x, y_median, method, alpha_scalar) <NEW_LINE> f_mean = method.phi(y_mean.unsqueeze(-1).unsqueeze(-1) - x, alpha=alpha_scalar).sum(-1).sum(-1) <NEW_LINE> f_median = method.phi(y_median.unsqueeze(-1).unsqueeze(-1) - x, alpha=alpha_scalar).sum(-1).sum(-1) <NEW_LINE> y = torch.where(f_mean <= f_median, y_mean, y_median) <NEW_LINE> <DEDENT> y = y.detach() <NEW_LINE> z = (y.unsqueeze(-1).unsqueeze(-1) - x).clone() <NEW_LINE> ctx.method = method <NEW_LINE> ctx.input_size = input_size <NEW_LINE> ctx.save_for_backward(z, alpha) <NEW_LINE> return y.reshape(input_size[:-2]).clone() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def backward(ctx, grad_output): <NEW_LINE> <INDENT> z, alpha = ctx.saved_tensors <NEW_LINE> input_size = ctx.input_size <NEW_LINE> method = ctx.method <NEW_LINE> grad_input = None <NEW_LINE> if ctx.needs_input_grad[0]: <NEW_LINE> <INDENT> grad_output = grad_output.detach().flatten(end_dim=-1) <NEW_LINE> grad_input = method.Dy(z, alpha) * grad_output.unsqueeze(-1).unsqueeze(-1) <NEW_LINE> grad_input = grad_input.reshape(input_size) <NEW_LINE> <DEDENT> return grad_input, None, None | A function to globally pool a 2D response matrix using a robust penalty function | 6259903926238365f5fadd06 |
class TestSuiteResult(object): <NEW_LINE> <INDENT> def __init__(self, testsuite_name, args_obj): <NEW_LINE> <INDENT> self._testsuite = testsuite_name <NEW_LINE> self._args_obj = args_obj <NEW_LINE> self._testcase_results = [] <NEW_LINE> self._blocked_testcases = {} <NEW_LINE> self._unknown_testcases = [] <NEW_LINE> <DEDENT> def add_test_case_result(self, test_case_result): <NEW_LINE> <INDENT> self._testcase_results.append(test_case_result) <NEW_LINE> <DEDENT> def set_blocked_testcases(self, blocked_testcases): <NEW_LINE> <INDENT> self._blocked_testcases = blocked_testcases <NEW_LINE> <DEDENT> def set_unknown_testcases(self, unknown_testcases): <NEW_LINE> <INDENT> self._unknown_testcases = unknown_testcases <NEW_LINE> <DEDENT> @property <NEW_LINE> def success(self): <NEW_LINE> <INDENT> for result in self._testcase_results: <NEW_LINE> <INDENT> if not result.success: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_testcases(self): <NEW_LINE> <INDENT> return self.num_success + self.num_failure + self.num_blocked + self.num_unknown <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_success(self): <NEW_LINE> <INDENT> retval = 0 <NEW_LINE> for result in self._testcase_results: <NEW_LINE> <INDENT> if result.success: <NEW_LINE> <INDENT> retval += 1 <NEW_LINE> <DEDENT> <DEDENT> return retval <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_failure(self): <NEW_LINE> <INDENT> return len(self._testcase_results) - self.num_success <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_blocked(self): <NEW_LINE> <INDENT> return len(self._blocked_testcases) <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_unknown(self): <NEW_LINE> <INDENT> return len(self._unknown_testcases) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> out = '' <NEW_LINE> out += '{}\n'.format(self._args_obj if self._args_obj else '(no args)') <NEW_LINE> out += ''.join([ str(x) for x in self._testcase_results ]) <NEW_LINE> if self._blocked_testcases: <NEW_LINE> <INDENT> for blocked_test, blocking_list in self._blocked_testcases.items(): <NEW_LINE> <INDENT> out += '{}: blocked by {}\n'.format( blocked_test, sorted(blocking_list)) <NEW_LINE> <DEDENT> <DEDENT> out += '================================================================\n\n' <NEW_LINE> if self.num_success != 0: <NEW_LINE> <INDENT> out += 'SUCCESS: {}\n'.format(self.num_success) <NEW_LINE> <DEDENT> if self.num_failure != 0: <NEW_LINE> <INDENT> out += 'FAILURE: {}\n'.format(self.num_failure) <NEW_LINE> <DEDENT> if self.num_blocked != 0: <NEW_LINE> <INDENT> out += 'BLOCKED: {}\n'.format(self.num_blocked) <NEW_LINE> <DEDENT> if self.num_unknown != 0: <NEW_LINE> <INDENT> out += 'UNKNOWN: {}\n'.format(self.num_unknown) <NEW_LINE> <DEDENT> out += '\n' <NEW_LINE> out += 'PASS\n' if self.success else 'FAIL\n' <NEW_LINE> return out | Container of test results of a test suite.
Attributes:
_testsuite: Full name of the test suite.
_args_obj: The argument object passed to test cases.
_testcase_results: A list of TestCaseResult objects. This list only has
results for test cases that are run - either successfully completed
or failed. Test cases that are not run do not appear in this list.
_blocked_testcases: A dictionary mapping test cases that are directly
blocked by failed test cases to the blocking test cases. Test cases
that are not run, but not directly blocked by a failed test case are
not included here.
_untouched_testcases: A list of test cases that are not run, but not
blocked by any failed test cases.
NOTE: The word 'untouched' also appeared in the scheduler but over
there it means that the task not ready for running. | 6259903930c21e258be999be |
class Choice(models.Model): <NEW_LINE> <INDENT> poll = models.ForeignKey(Poll) <NEW_LINE> choice_text = models.CharField(max_length=200) <NEW_LINE> votes = models.IntegerField(default=0) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.choice_text | Model class of Choice | 62599039d99f1b3c44d06856 |
class Solution: <NEW_LINE> <INDENT> def isIsomorphic(self, s: str, t: str) -> bool: <NEW_LINE> <INDENT> return len(set(s))==len(set(t))==len(set(zip(s,t))) | one liner solution | 6259903950485f2cf55dc131 |
class PacketListField(PacketField): <NEW_LINE> <INDENT> __slots__ = ["count_from", "length_from", "next_cls_cb"] <NEW_LINE> islist = 1 <NEW_LINE> def __init__(self, name, default, cls=None, count_from=None, length_from=None, next_cls_cb=None): <NEW_LINE> <INDENT> if default is None: <NEW_LINE> <INDENT> default = [] <NEW_LINE> <DEDENT> PacketField.__init__(self, name, default, cls) <NEW_LINE> self.count_from = count_from <NEW_LINE> self.length_from = length_from <NEW_LINE> self.next_cls_cb = next_cls_cb <NEW_LINE> <DEDENT> def any2i(self, pkt, x): <NEW_LINE> <INDENT> if not isinstance(x, list): <NEW_LINE> <INDENT> return [x] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> <DEDENT> def i2count(self, pkt, val): <NEW_LINE> <INDENT> if isinstance(val, list): <NEW_LINE> <INDENT> return len(val) <NEW_LINE> <DEDENT> return 1 <NEW_LINE> <DEDENT> def i2len(self, pkt, val): <NEW_LINE> <INDENT> return sum( len(p) for p in val ) <NEW_LINE> <DEDENT> def do_copy(self, x): <NEW_LINE> <INDENT> if x is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [p if isinstance(p, six.string_types) else p.copy() for p in x] <NEW_LINE> <DEDENT> <DEDENT> def getfield(self, pkt, s): <NEW_LINE> <INDENT> c = l = cls = None <NEW_LINE> if self.length_from is not None: <NEW_LINE> <INDENT> l = self.length_from(pkt) <NEW_LINE> <DEDENT> elif self.count_from is not None: <NEW_LINE> <INDENT> c = self.count_from(pkt) <NEW_LINE> <DEDENT> if self.next_cls_cb is not None: <NEW_LINE> <INDENT> cls = self.next_cls_cb(pkt, [], None, s) <NEW_LINE> c = 1 <NEW_LINE> <DEDENT> lst = [] <NEW_LINE> ret = b"" <NEW_LINE> remain = s <NEW_LINE> if l is not None: <NEW_LINE> <INDENT> remain,ret = s[:l],s[l:] <NEW_LINE> <DEDENT> while remain: <NEW_LINE> <INDENT> if c is not None: <NEW_LINE> <INDENT> if c <= 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> c -= 1 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if cls is not None: <NEW_LINE> <INDENT> p = cls(remain) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = self.m2i(pkt, remain) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> if conf.debug_dissector: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> p = conf.raw_layer(load=remain) <NEW_LINE> remain = b"" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if conf.padding_layer in p: <NEW_LINE> <INDENT> pad = p[conf.padding_layer] <NEW_LINE> remain = pad.load <NEW_LINE> del(pad.underlayer.payload) <NEW_LINE> if self.next_cls_cb is not None: <NEW_LINE> <INDENT> cls = self.next_cls_cb(pkt, lst, p, remain) <NEW_LINE> if cls is not None: <NEW_LINE> <INDENT> c += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> remain = b"" <NEW_LINE> <DEDENT> <DEDENT> lst.append(p) <NEW_LINE> <DEDENT> return remain+ret,lst <NEW_LINE> <DEDENT> def addfield(self, pkt, s, val): <NEW_LINE> <INDENT> return s + b"".join(raw(v) for v in val) | PacketListField represents a series of Packet instances that might occur right in the middle of another Packet
field list.
This field type may also be used to indicate that a series of Packet instances have a sibling semantic instead of
a parent/child relationship (i.e. a stack of layers). | 62599039b57a9660fecd2c2c |
class Meta: <NEW_LINE> <INDENT> app_label = 'demo' | Meta settings for MaterialWidgetsDemoModel | 62599039b5575c28eb7135a2 |
class _ExtendedEnum(Enum): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def by_name(cls, name: str) -> "Enum": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return cls.__members__[name.upper()] <NEW_LINE> <DEDENT> except KeyError as exc: <NEW_LINE> <INDENT> raise ValueError( "Unknown value for type {}, available: {}", cls, list(cls.__members__.values()), ) from exc | A custom enum with extended functionality. | 625990391f5feb6acb163da4 |
class MoreData(Singleton): <NEW_LINE> <INDENT> Nothing = 0x00 <NEW_LINE> KeepReading = 0xFF | Represents the more follows condition
.. attribute:: Nothing
This indiates that no more objects are going to be returned.
.. attribute:: KeepReading
This indicates that there are more objects to be returned. | 6259903923e79379d538d6b2 |
class ICMS00(Entidade): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(ICMS00, self).__init__(schema={ 'Orig': { 'type': 'string', 'required': True, 'allowed': [v for v,s in constantes.N06_ORIG]}, 'CST': { 'type': 'string', 'required': True, 'allowed': [v for v,s in constantes.N07_CST_ICMS00]}, 'pICMS': { 'type': 'decimal', 'required': True}, }, **kwargs) <NEW_LINE> <DEDENT> def _construir_elemento_xml(self, *args, **kwargs): <NEW_LINE> <INDENT> icms00 = ET.Element(self.__class__.__name__) <NEW_LINE> ET.SubElement(icms00, 'Orig').text = self.Orig <NEW_LINE> ET.SubElement(icms00, 'CST').text = self.CST <NEW_LINE> ET.SubElement(icms00, 'pICMS').text = '{:n}'.format(self.pICMS) <NEW_LINE> return icms00 | Grupo de tributação do ICMS 00, 20 e 90 (``ICMS00``, grupo ``N02``).
:param str Orig:
:param str CST:
:param Decimal pICMS:
.. sourcecode:: python
>>> icms = ICMS00(Orig='0', CST='00', pICMS=Decimal('18.00'))
>>> ET.tostring(icms._xml())
'<ICMS00><Orig>0</Orig><CST>00</CST><pICMS>18.00</pICMS></ICMS00>' | 62599039e76e3b2f99fd9bbe |
class ReadonlyEditor(TextReadonlyEditor): <NEW_LINE> <INDENT> def _get_str_value(self): <NEW_LINE> <INDENT> if not self.value: <NEW_LINE> <INDENT> return self.factory.message <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.value.strftime(self.factory.strftime) | Use a TextEditor for the view. | 62599039cad5886f8bdc5955 |
class MarkovTransitionMatrix: <NEW_LINE> <INDENT> def __init__( self, transition_matrix_df ): <NEW_LINE> <INDENT> self.transition_matrix_df = transition_matrix_df <NEW_LINE> self.column_names = self.transition_matrix_df.columns.values <NEW_LINE> self.total_column = 'row_total' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '< MarkovTransitionMatrix object ¯\\_(ツ)_/¯ >' <NEW_LINE> <DEDENT> def matrix_at_time_step(self, time_step): <NEW_LINE> <INDENT> ret = self.transition_matrix_df.applymap(lambda x: (x.value_at_time_step(time_step), x.is_remainder)) <NEW_LINE> ret[self.total_column] = ret.apply(self.sum_elements_of_tuples, axis=1) <NEW_LINE> ret[self.column_names] = ret.apply(self.use_remainder_to_create_row, axis=1) <NEW_LINE> return ret[self.column_names] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def sum_elements_of_tuples(row): <NEW_LINE> <INDENT> ret = tuple(map(sum, zip(*row))) <NEW_LINE> if ret[1] > 1: <NEW_LINE> <INDENT> raise ValueError( 'transition matrix row {} contains more than 1 cell claiming to be the remainder'.format(row.name) ) <NEW_LINE> <DEDENT> if ret[0] < 0 or ret[0] > 1: <NEW_LINE> <INDENT> raise ValueError('transition matrix row {} is out of bounds. row total = {}'.format(row.name, ret[0])) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def use_remainder_to_create_row(self, row): <NEW_LINE> <INDENT> ret = [tup[0] if not tup[1] else 1 - row[self.total_column][0] for tup in row[self.column_names]] <NEW_LINE> if round(sum(ret), 6) != 1: <NEW_LINE> <INDENT> raise ValueError('transition matrix row {} does not sum to 1. row total = {}'.format(row.name, sum(ret))) <NEW_LINE> <DEDENT> return pd.Series(ret) | DON'T FORGET YOUR DOCSTRING!
You forgot your docstring, didn't you... | 62599039b57a9660fecd2c2d |
class Users(AbstractUser): <NEW_LINE> <INDENT> display = models.CharField('显示的中文名', max_length=50, default='') <NEW_LINE> ding_user_id = models.CharField('钉钉UserID', max_length=64, blank=True) <NEW_LINE> wx_user_id = models.CharField('企业微信UserID', max_length=64, blank=True) <NEW_LINE> feishu_open_id = models.CharField('飞书OpenID', max_length=64, blank=True) <NEW_LINE> failed_login_count = models.IntegerField('失败计数', default=0) <NEW_LINE> last_login_failed_at = models.DateTimeField('上次失败登录时间', blank=True, null=True) <NEW_LINE> resource_group = models.ManyToManyField(ResourceGroup, verbose_name='资源组', blank=True) <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.failed_login_count = min(127, self.failed_login_count) <NEW_LINE> self.failed_login_count = max(0, self.failed_login_count) <NEW_LINE> super(Users, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.display: <NEW_LINE> <INDENT> return self.display <NEW_LINE> <DEDENT> return self.username <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> managed = True <NEW_LINE> db_table = 'sql_users' <NEW_LINE> verbose_name = u'用户管理' <NEW_LINE> verbose_name_plural = u'用户管理' | 用户信息扩展 | 62599039ec188e330fdf9a4a |
class Request(object): <NEW_LINE> <INDENT> def __init__(self, username=None, pin=None, amount=None, new_pin=None,): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.pin = pin <NEW_LINE> self.amount = amount <NEW_LINE> self.new_pin = new_pin <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.username = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.I16: <NEW_LINE> <INDENT> self.pin = iprot.readI16() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 3: <NEW_LINE> <INDENT> if ftype == TType.I32: <NEW_LINE> <INDENT> self.amount = iprot.readI32() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 4: <NEW_LINE> <INDENT> if ftype == TType.I16: <NEW_LINE> <INDENT> self.new_pin = iprot.readI16() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('Request') <NEW_LINE> if self.username is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('username', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.username.encode('utf-8') if sys.version_info[0] == 2 else self.username) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.pin is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('pin', TType.I16, 2) <NEW_LINE> oprot.writeI16(self.pin) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.amount is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('amount', TType.I32, 3) <NEW_LINE> oprot.writeI32(self.amount) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.new_pin is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('new_pin', TType.I16, 4) <NEW_LINE> oprot.writeI16(self.new_pin) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- username
- pin
- amount
- new_pin | 625990391d351010ab8f4ccd |
class CompositeRequest(WebServiceRequest): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(CompositeRequest, self).__init__() <NEW_LINE> self.operations = [] <NEW_LINE> <DEDENT> def web_service_request_model(self): <NEW_LINE> <INDENT> return idempierewsc.enums.WebServiceRequestModel.CompositeRequest | CompositeRequest. Web Service Request | 6259903973bcbd0ca4bcb43c |
class BrotherPrinterSensor(Entity): <NEW_LINE> <INDENT> def __init__(self, coordinator, kind, device_info): <NEW_LINE> <INDENT> self._name = f"{coordinator.data[ATTR_MODEL]} {SENSOR_TYPES[kind][ATTR_LABEL]}" <NEW_LINE> self._unique_id = f"{coordinator.data[ATTR_SERIAL].lower()}_{kind}" <NEW_LINE> self._device_info = device_info <NEW_LINE> self.coordinator = coordinator <NEW_LINE> self.kind = kind <NEW_LINE> self._attrs = {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self.coordinator.data.get(self.kind) <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> remaining_pages = None <NEW_LINE> drum_counter = None <NEW_LINE> if self.kind == ATTR_DRUM_REMAINING_LIFE: <NEW_LINE> <INDENT> remaining_pages = ATTR_DRUM_REMAINING_PAGES <NEW_LINE> drum_counter = ATTR_DRUM_COUNTER <NEW_LINE> <DEDENT> elif self.kind == ATTR_BLACK_DRUM_REMAINING_LIFE: <NEW_LINE> <INDENT> remaining_pages = ATTR_BLACK_DRUM_REMAINING_PAGES <NEW_LINE> drum_counter = ATTR_BLACK_DRUM_COUNTER <NEW_LINE> <DEDENT> elif self.kind == ATTR_CYAN_DRUM_REMAINING_LIFE: <NEW_LINE> <INDENT> remaining_pages = ATTR_CYAN_DRUM_REMAINING_PAGES <NEW_LINE> drum_counter = ATTR_CYAN_DRUM_COUNTER <NEW_LINE> <DEDENT> elif self.kind == ATTR_MAGENTA_DRUM_REMAINING_LIFE: <NEW_LINE> <INDENT> remaining_pages = ATTR_MAGENTA_DRUM_REMAINING_PAGES <NEW_LINE> drum_counter = ATTR_MAGENTA_DRUM_COUNTER <NEW_LINE> <DEDENT> elif self.kind == ATTR_YELLOW_DRUM_REMAINING_LIFE: <NEW_LINE> <INDENT> remaining_pages = ATTR_YELLOW_DRUM_REMAINING_PAGES <NEW_LINE> drum_counter = ATTR_YELLOW_DRUM_COUNTER <NEW_LINE> <DEDENT> if remaining_pages and drum_counter: <NEW_LINE> <INDENT> self._attrs[ATTR_REMAINING_PAGES] = self.coordinator.data.get( remaining_pages ) <NEW_LINE> self._attrs[ATTR_COUNTER] = self.coordinator.data.get(drum_counter) <NEW_LINE> <DEDENT> return self._attrs <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return SENSOR_TYPES[self.kind][ATTR_ICON] <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return self._unique_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return SENSOR_TYPES[self.kind][ATTR_UNIT] <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> return self.coordinator.last_update_success <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_info(self): <NEW_LINE> <INDENT> return self._device_info <NEW_LINE> <DEDENT> @property <NEW_LINE> def entity_registry_enabled_default(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> self.async_on_remove( self.coordinator.async_add_listener(self.async_write_ha_state) ) <NEW_LINE> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> await self.coordinator.async_request_refresh() | Define an Brother Printer sensor. | 6259903926068e7796d4dafb |
class CameraDriver(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_cameras(camera_controller): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_camera(camera_controller, camera_name): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def set_camera(camera_controller, camera_name, key, value): <NEW_LINE> <INDENT> return False | Spoke driver object. | 6259903923e79379d538d6b3 |
class UserChangeForm(forms.ModelForm): <NEW_LINE> <INDENT> password = ReadOnlyPasswordHashField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Account <NEW_LINE> fields = ( 'email', 'password', 'username', 'is_active', 'is_admin', 'is_superuser', ) <NEW_LINE> <DEDENT> def clean_password(self): <NEW_LINE> <INDENT> return self.initial["password"] | A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field. | 6259903950485f2cf55dc133 |
class Argparser(object): <NEW_LINE> <INDENT> def __init__(self, argv=None, *args, **kwargs): <NEW_LINE> <INDENT> self._argv = argv or sys.argv[1:] <NEW_LINE> self._parser = argparse.ArgumentParser(*args, **kwargs) <NEW_LINE> <DEDENT> def add_config_arg(self, *args, **kwargs): <NEW_LINE> <INDENT> config = kwargs.pop('config', Config()) <NEW_LINE> _action = kwargs.pop('action', None) <NEW_LINE> action = conf_action(config, _action) <NEW_LINE> kwargs['action'] = action <NEW_LINE> return self.add_argument(*args, **kwargs) <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(self._parser, attr) | Argument parser class. Holds the keys to argparse | 625990396fece00bbacccb5f |
class MikrotikControllerMangleSwitch(MikrotikControllerSwitch): <NEW_LINE> <INDENT> def __init__(self, inst, uid, mikrotik_controller, sid_data): <NEW_LINE> <INDENT> super().__init__(inst, uid, mikrotik_controller, sid_data) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> if self._data["comment"]: <NEW_LINE> <INDENT> return f"{self._inst} Mangle {self._data['comment']}" <NEW_LINE> <DEDENT> return f"{self._inst} Mangle {self._data['name']}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self) -> str: <NEW_LINE> <INDENT> return f"{self._inst.lower()}-enable_mangle-{self._data['uniq-id']}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self) -> str: <NEW_LINE> <INDENT> if not self._data["enabled"]: <NEW_LINE> <INDENT> icon = "mdi:bookmark-off-outline" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> icon = "mdi:bookmark-outline" <NEW_LINE> <DEDENT> return icon <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_info(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> info = { "identifiers": { ( DOMAIN, "serial-number", self._ctrl.data["routerboard"]["serial-number"], "switch", "Mangle", ) }, "manufacturer": self._ctrl.data["resource"]["platform"], "model": self._ctrl.data["resource"]["board-name"], "name": f"{self._inst} Mangle", } <NEW_LINE> return info <NEW_LINE> <DEDENT> async def async_turn_on(self) -> None: <NEW_LINE> <INDENT> path = "/ip/firewall/mangle" <NEW_LINE> param = ".id" <NEW_LINE> value = None <NEW_LINE> for uid in self._ctrl.data["mangle"]: <NEW_LINE> <INDENT> if self._ctrl.data["mangle"][uid]["uniq-id"] == ( f"{self._data['chain']},{self._data['action']},{self._data['protocol']}," f"{self._data['src-address']}:{self._data['src-port']}-" f"{self._data['dst-address']}:{self._data['dst-port']}" ): <NEW_LINE> <INDENT> value = self._ctrl.data["mangle"][uid][".id"] <NEW_LINE> <DEDENT> <DEDENT> mod_param = "disabled" <NEW_LINE> mod_value = False <NEW_LINE> self._ctrl.set_value(path, param, value, mod_param, mod_value) <NEW_LINE> await self._ctrl.force_update() <NEW_LINE> <DEDENT> async def async_turn_off(self) -> None: <NEW_LINE> <INDENT> path = "/ip/firewall/mangle" <NEW_LINE> param = ".id" <NEW_LINE> value = None <NEW_LINE> for uid in self._ctrl.data["mangle"]: <NEW_LINE> <INDENT> if self._ctrl.data["mangle"][uid]["uniq-id"] == ( f"{self._data['chain']},{self._data['action']},{self._data['protocol']}," f"{self._data['src-address']}:{self._data['src-port']}-" f"{self._data['dst-address']}:{self._data['dst-port']}" ): <NEW_LINE> <INDENT> value = self._ctrl.data["mangle"][uid][".id"] <NEW_LINE> <DEDENT> <DEDENT> mod_param = "disabled" <NEW_LINE> mod_value = True <NEW_LINE> self._ctrl.set_value(path, param, value, mod_param, mod_value) <NEW_LINE> await self._ctrl.async_update() | Representation of a Mangle switch. | 6259903982261d6c5273079e |
class LeadingPersonAddForm(forms.Form): <NEW_LINE> <INDENT> name = forms.CharField(label="Imię i nazwisko") <NEW_LINE> client = forms.ModelMultipleChoiceField(queryset=Client.objects.all(), label="Klient", widget=forms.CheckboxSelectMultiple) | Formualrz nowych opiekunów Klienta | 62599039d164cc6175822127 |
class AutoRecoverableError( six.with_metaclass(_ErrorsMeta, RecoverableError)): <NEW_LINE> <INDENT> pass | If this exception was rised,
the task should be retried automatically | 62599039d4950a0f3b111719 |
class ExperimentInstance(): <NEW_LINE> <INDENT> def __init__(self, instanceIdx, mlFramework, artifactDir, slurmConfig, model, hyperparameters, dataset, optimizer, modelLabel, hyperparametersLabel, datasetLabel, optimizerLabel): <NEW_LINE> <INDENT> self.instanceIdx = instanceIdx <NEW_LINE> self.mlFramework = mlFramework <NEW_LINE> self.artifactDir = artifactDir.format(instanceIdx = instanceIdx) <NEW_LINE> self.dataset = dataset <NEW_LINE> self.model = model <NEW_LINE> self.hyperparameters = hyperparameters <NEW_LINE> self.optimizer = optimizer <NEW_LINE> self.slurmConfig = slurmConfig <NEW_LINE> self.trainfile = None <NEW_LINE> self.dockerfile = None <NEW_LINE> self.executeFile = None <NEW_LINE> self.outputFile = "instance_{instanceIdx}.out".format(instanceIdx=self.instanceIdx) <NEW_LINE> self.label = "Experiment Instance: {instanceIdx}\nModel: {modelLbl}\nOptimizer: {optimizerLbl}\nHyperparameterSet: {hpLbl}\nDataset: {datasetLbl}\n".format( instanceIdx = instanceIdx, modelLbl = str(modelLabel), hpLbl = str(hyperparametersLabel), datasetLbl = str(datasetLabel), optimizerLbl = str(optimizerLabel)) <NEW_LINE> <DEDENT> def getModel(self): <NEW_LINE> <INDENT> return self.model <NEW_LINE> <DEDENT> def getDataset(self): <NEW_LINE> <INDENT> return self.dataset <NEW_LINE> <DEDENT> def getHyperparameters(self): <NEW_LINE> <INDENT> return self.hyperparameters <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.label | instanceIdx - Unique index assigned to the experiment instance. Experiment label + instanceIdx provide a unique identifier for instance
mlFramework - Name of machine learning framework to use, name must match plugin name exactly
slurmConfig - Dictionary containing the arguments to pass to SLURM when executing this instance as defined in the config JSON folder.
This should not include the "--output" parameter (which will be added in the init)
artifactDir - Directory in which all the training artifacts are generated for the experiment instance
instanceIdx - Unique index assigned to instance. The experiment label + instance index define a unique identifier for each experiment instance
model - python module path containing the model associated with instance
hyperparameters - dictionary containing hyperparameters associated with model
dataset - path to dataset to train model
optimizer - python module path containing the optimizer associated with the instance
modelLabel - Human readable label assigned to the model
hyperparameterLabel - Human readable label assigned to the hyperparameter set
datasetLabel - Human readable label assigned to dataset
optimizerLabel - Human readable label assigned to optimizer | 6259903915baa7234946314e |
class CreateDestroyViewSet(DestroyModelMixin, CreateViewSet): <NEW_LINE> <INDENT> pass | Base view set which permit only create and destroy instances | 62599039596a897236128e52 |
class TupleLike(object): <NEW_LINE> <INDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __contains__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def is_bound(self, name): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def has_key(self, name): <NEW_LINE> <INDENT> return name in self <NEW_LINE> <DEDENT> def exportable_keys(self): <NEW_LINE> <INDENT> pass | Interface for tuple-like objects. | 62599039287bf620b6272d9e |
class ImageLabel: <NEW_LINE> <INDENT> def __init__(self, image, data, format, target_size): <NEW_LINE> <INDENT> self.format = format <NEW_LINE> self.image = cv2.resize(image, target_size) <NEW_LINE> self.target_size = target_size <NEW_LINE> self.orignal_size = (image.shape[1], image.shape[0]) <NEW_LINE> self.labels = self.load(data) <NEW_LINE> <DEDENT> def load(self, data): <NEW_LINE> <INDENT> if self.format == "labelme": <NEW_LINE> <INDENT> return self._load_labelme(data) <NEW_LINE> <DEDENT> if self.format == "plaintext": <NEW_LINE> <INDENT> return self._load_plaintext(data) <NEW_LINE> <DEDENT> raise ValueError("Unknow label type:", self.format) <NEW_LINE> <DEDENT> def _load_labelme(self, data): <NEW_LINE> <INDENT> assert type(data) == list <NEW_LINE> data = "".join(data) <NEW_LINE> image_labels = json.loads(data) <NEW_LINE> shapes = image_labels['shapes'] <NEW_LINE> labels = [] <NEW_LINE> for s in shapes: <NEW_LINE> <INDENT> label = s['label'] <NEW_LINE> points = s['points'] <NEW_LINE> points = util.resize_bboxes(points, original_size=self.orignal_size, target_size=self.target_size) <NEW_LINE> labels.append(Label(label, points)) <NEW_LINE> <DEDENT> return labels <NEW_LINE> <DEDENT> def _load_plaintext(self, data): <NEW_LINE> <INDENT> assert type(data) == list <NEW_LINE> labels = [] <NEW_LINE> for i in range(1, len(data)): <NEW_LINE> <INDENT> line = data[i] <NEW_LINE> line = line.replace(" ", "") <NEW_LINE> line = line.replace("\n", "") <NEW_LINE> line_data = line.split(",") <NEW_LINE> points = line_data[:8] <NEW_LINE> label = line_data[8] <NEW_LINE> if line[-2:]==",,": <NEW_LINE> <INDENT> label = "," <NEW_LINE> <DEDENT> points = [int(p.strip()) for p in points] <NEW_LINE> points = np.array(points) <NEW_LINE> points = np.reshape(points, (4, 2)) <NEW_LINE> points = util.resize_bboxes(points, original_size=self.orignal_size, target_size=self.target_size) <NEW_LINE> labels.append(Label(label, points)) <NEW_LINE> <DEDENT> return labels <NEW_LINE> <DEDENT> @property <NEW_LINE> def bboxes(self): <NEW_LINE> <INDENT> return np.array([l.bbox for l in self.labels]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def label(self): <NEW_LINE> <INDENT> return "".join([l.label for l in self.labels]) | Wrap the image and label data
there are 2 types:
- labelme format: like https://github.com/wkentaro/labelme/blob/master/examples/tutorial/apc2016_obj3.json
- plaintext: like
>>>
你好,世界
11,12,21,22,31,32,41,42,你
...
<<<
more, ImageLabel is in charge of resizing to standard size (64x256). | 625990391f5feb6acb163da6 |
class Account: <NEW_LINE> <INDENT> interest = 0.02 <NEW_LINE> def __init__(self, account_holder): <NEW_LINE> <INDENT> self.holder = account_holder <NEW_LINE> self.balance = 0 <NEW_LINE> <DEDENT> def deposit(self, amount): <NEW_LINE> <INDENT> self.balance = self.balance + amount <NEW_LINE> return self.balance <NEW_LINE> <DEDENT> def withdraw(self, amount): <NEW_LINE> <INDENT> if amount > self.balance: <NEW_LINE> <INDENT> return 'Insufficient funds' <NEW_LINE> <DEDENT> self.balance = self.balance - amount <NEW_LINE> return self.balance <NEW_LINE> <DEDENT> def time_to_retire(self, amount): <NEW_LINE> <INDENT> assert self.balance > 0 and amount > 0 and self.interest > 0 <NEW_LINE> n = log(amount/self.balance)/log(1+self.interest) <NEW_LINE> return math.ceil(n) | An account has a balance and a holder.
>>> a = Account('John')
>>> a.deposit(10)
10
>>> a.balance
10
>>> a.interest
0.02
>>> a.time_to_retire(10.25) # 10 -> 10.2 -> 10.404
2
>>> a.balance # balance should not change
10
>>> a.time_to_retire(11) # 10 -> 10.2 -> ... -> 11.040808032
5
>>> a.time_to_retire(100)
117 | 6259903921bff66bcd723e1c |
class MessagesPerTSTracker(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.req_last_hr_q=deque() <NEW_LINE> self.max_requests_last_hr=[] <NEW_LINE> self.tscounter = Counter() <NEW_LINE> self.hour= timedelta(hours=1) <NEW_LINE> self.fmt = "%d/%b/%Y:%H:%M:%S %z" <NEW_LINE> <DEDENT> def addtoTracker(self, ts, isLast=False): <NEW_LINE> <INDENT> adj = 0 <NEW_LINE> timestamp = None <NEW_LINE> if not isLast: <NEW_LINE> <INDENT> timestamp = datetime.strptime(ts, self.fmt) <NEW_LINE> self.req_last_hr_q.append(timestamp) <NEW_LINE> adj = 1 <NEW_LINE> <DEDENT> if len(self.req_last_hr_q) == 0: return <NEW_LINE> while (timestamp and timestamp - self.req_last_hr_q[0] >= self.hour) or isLast: <NEW_LINE> <INDENT> ts = self.req_last_hr_q.popleft() <NEW_LINE> key = ts.strftime(self.fmt) <NEW_LINE> if not self.tscounter[key]: <NEW_LINE> <INDENT> self.tscounter[key] = len(self.req_last_hr_q) + 1 - adj <NEW_LINE> <DEDENT> if len(self.req_last_hr_q) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> '''Define a function that computes the top number (default=10) of requests''' <NEW_LINE> def max_active(self,topcount=10): <NEW_LINE> <INDENT> self.addtoTracker(ts='',isLast=True) <NEW_LINE> max_requests_last_hr = self.tscounter.most_common(topcount) <NEW_LINE> return max_requests_last_hr | #Class that tracks the maximum requests in any given hour | 62599039ac7a0e7691f7369c |
class IAttributes(INamed, IMapping): <NEW_LINE> <INDENT> taggedValue('contains', 'mixed') | Dictionary of Attributes
| 6259903994891a1f408b9fd1 |
class SearchViewlet(ViewletBase): <NEW_LINE> <INDENT> viewletNamespace ="viewletNamespace result" <NEW_LINE> def update(self): <NEW_LINE> <INDENT> query = self.request.form.get('query') <NEW_LINE> if query: <NEW_LINE> <INDENT> self.results ="""you're query is "%s" """ % query <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.results = "Type in a query" | SearchViewlet | 6259903910dbd63aa1c71d89 |
class Solution: <NEW_LINE> <INDENT> def mergekSortedArrays(self, arrays): <NEW_LINE> <INDENT> heap = [] <NEW_LINE> for index, array in enumerate(arrays): <NEW_LINE> <INDENT> if array != []: <NEW_LINE> <INDENT> heapq.heappush(heap, (array[0], index, 0)) <NEW_LINE> <DEDENT> <DEDENT> new = [] <NEW_LINE> while heap: <NEW_LINE> <INDENT> val, i, j = heapq.heappop(heap) <NEW_LINE> new.append(val) <NEW_LINE> if j < len(arrays[i]) - 1: <NEW_LINE> <INDENT> heapq.heappush(heap, (arrays[i][j + 1], i, j + 1)) <NEW_LINE> <DEDENT> <DEDENT> return new | @param arrays: k sorted integer arrays
@return: a sorted array | 625990398c3a8732951f770a |
class APIAccessor(APIClient): <NEW_LINE> <INDENT> def get_track_archive(self, race_id): <NEW_LINE> <INDENT> url = '/'.join((self.url, 'race', race_id, 'track_archive')) <NEW_LINE> return self._return_page(url) <NEW_LINE> <DEDENT> def get_race_task(self, race_id): <NEW_LINE> <INDENT> url = '/'.join((self.url, 'race', race_id)) <NEW_LINE> return self._return_page(url) <NEW_LINE> <DEDENT> def _return_page(self, url): <NEW_LINE> <INDENT> r = requests.get(url) <NEW_LINE> if not r.status_code == 200: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = r.json() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.err("Error while doing json in APIAccessor for %s: %r" % (r.text, e)) <NEW_LINE> raise e <NEW_LINE> <DEDENT> return result | Implement asynchronous methods for convinient access to JSON api. | 62599039b830903b9686ed53 |
class channelConfiguration(object): <NEW_LINE> <INDENT> def __init__(self, dacChannelNumber, trapElectrodeNumber = None, smaOutNumber = None, name = None, boardVoltageRange = (-10, 10), allowedVoltageRange = (0.0, 10.0)): <NEW_LINE> <INDENT> self.dacChannelNumber = dacChannelNumber <NEW_LINE> self.trapElectrodeNumber = trapElectrodeNumber <NEW_LINE> self.smaOutNumber = smaOutNumber <NEW_LINE> self.boardVoltageRange = boardVoltageRange <NEW_LINE> self.allowedVoltageRange = allowedVoltageRange <NEW_LINE> if (name == None) & (trapElectrodeNumber != None): <NEW_LINE> <INDENT> self.name = str(trapElectrodeNumber).zfill(2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> <DEDENT> def computeDigitalVoltage(self, analogVoltage): <NEW_LINE> <INDENT> return int(round(sum([ self.calibration[n] * analogVoltage ** n for n in range(len(self.calibration)) ]))) | Stores complete information for each DAC channel | 625990398da39b475be043a4 |
class TestVerveResponseFlowFinder(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testVerveResponseFlowFinder(self): <NEW_LINE> <INDENT> model = iengage_client.models.verve_response_flow_finder.VerveResponseFlowFinder() | VerveResponseFlowFinder unit test stubs | 62599039004d5f362081f8bf |
class BinUtils(Package): <NEW_LINE> <INDENT> def __init__(self, version: str, gold=True): <NEW_LINE> <INDENT> self.version = version <NEW_LINE> self.gold = gold <NEW_LINE> <DEDENT> def ident(self): <NEW_LINE> <INDENT> s = 'binutils-' + self.version <NEW_LINE> if self.gold: <NEW_LINE> <INDENT> s += '-gold' <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> def fetch(self, ctx): <NEW_LINE> <INDENT> tarname = 'binutils-%s.tar.bz2' % self.version <NEW_LINE> download(ctx, 'http://ftp.gnu.org/gnu/binutils/' + tarname) <NEW_LINE> run(ctx, ['tar', '-xf', tarname]) <NEW_LINE> shutil.move('binutils-' + self.version, 'src') <NEW_LINE> os.remove(tarname) <NEW_LINE> <DEDENT> def build(self, ctx): <NEW_LINE> <INDENT> os.makedirs('obj', exist_ok=True) <NEW_LINE> os.chdir('obj') <NEW_LINE> if not self._bison_installed(ctx): <NEW_LINE> <INDENT> raise FatalError('bison not found (required to build binutils)') <NEW_LINE> <DEDENT> configure = ['../src/configure', '--enable-gold', '--enable-plugins', '--disable-werror', '--prefix=' + self.path(ctx, 'install')] <NEW_LINE> if run(ctx, ['gcc', '--print-sysroot']).stdout: <NEW_LINE> <INDENT> configure.append('--with-sysroot') <NEW_LINE> <DEDENT> run(ctx, configure) <NEW_LINE> run(ctx, ['make', '-j%d' % ctx.jobs]) <NEW_LINE> if self.gold: <NEW_LINE> <INDENT> run(ctx, ['make', '-j%d' % ctx.jobs, 'all-gold']) <NEW_LINE> <DEDENT> <DEDENT> def install(self, ctx): <NEW_LINE> <INDENT> os.chdir('obj') <NEW_LINE> run(ctx, ['make', 'install']) <NEW_LINE> if self.gold: <NEW_LINE> <INDENT> os.chdir('../install/bin') <NEW_LINE> os.remove('ld') <NEW_LINE> shutil.copy('ld.gold', 'ld') <NEW_LINE> <DEDENT> <DEDENT> def is_fetched(self, ctx): <NEW_LINE> <INDENT> return os.path.exists('src') <NEW_LINE> <DEDENT> def is_built(self, ctx): <NEW_LINE> <INDENT> return os.path.exists('obj/%s/ld-new' % ('gold' if self.gold else 'ld')) <NEW_LINE> <DEDENT> def is_installed(self, ctx): <NEW_LINE> <INDENT> return os.path.exists('install/bin/ld') <NEW_LINE> <DEDENT> def _bison_installed(self, ctx): <NEW_LINE> <INDENT> proc = run(ctx, ['bison', '--version'], allow_error=True, silent=True) <NEW_LINE> return proc and proc.returncode == 0 | :identifier: binutils-<version>[-gold]
:param version: version to download
:param gold: whether to use the gold linker | 6259903982261d6c5273079f |
class CmdDisengage(MuxCommand): <NEW_LINE> <INDENT> key = "disengage" <NEW_LINE> aliases = ["spare"] <NEW_LINE> help_category = "battle" <NEW_LINE> def func(self): <NEW_LINE> <INDENT> cmd_check = rules.cmd_check(self.caller, self.args, "disengage", ['InCombat', 'IsTurn', 'AttacksResolved']) <NEW_LINE> if cmd_check: <NEW_LINE> <INDENT> self.caller.msg(cmd_check) <NEW_LINE> return <NEW_LINE> <DEDENT> if not self.args: <NEW_LINE> <INDENT> message = ("%s seems ready to stop fighting. |222[Disengage]|n" % self.caller) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if "<self>" not in self.args: <NEW_LINE> <INDENT> message = ("%s %s |222[Disengage]|n" % (self.caller, self.args)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> replaced = self.args.replace("<self>", str(self.caller)) <NEW_LINE> message = ("%s |222[Disengage]|n" % replaced) <NEW_LINE> <DEDENT> <DEDENT> self.caller.location.msg_contents(message) <NEW_LINE> self.caller.db.Combat_LastAction = "disengage" <NEW_LINE> self.caller.db.Combat_Actions = 0 <NEW_LINE> self.caller.db.Combat_Moves = 0 <NEW_LINE> if self.caller.db.Combat_Second: <NEW_LINE> <INDENT> del self.caller.db.Combat_Second | Like 'pass', but can end combat. | 62599039baa26c4b54d5045d |
class TestUnversionedListMeta(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testUnversionedListMeta(self): <NEW_LINE> <INDENT> model = k8sclient.models.unversioned_list_meta.UnversionedListMeta() | UnversionedListMeta unit test stubs | 6259903907d97122c4217e52 |
class Pool: <NEW_LINE> <INDENT> def __init__(self, periods_length, initial_balance, spread=0, amortizations=None, recovery_step=None, recovery_rate=None, repayment_rates=None, timing_vector=None): <NEW_LINE> <INDENT> self.balances = np.zeros(periods_length) <NEW_LINE> self.balances[0] = initial_balance <NEW_LINE> self.available_interests = np.zeros(periods_length) <NEW_LINE> self.losses = np.zeros(periods_length) <NEW_LINE> self.delinquencies = np.zeros(periods_length) <NEW_LINE> self.recoveries = np.zeros(periods_length) <NEW_LINE> self.repayments = np.zeros(periods_length) <NEW_LINE> self.spreads = np.empty(periods_length) <NEW_LINE> self.spreads.fill(spread) <NEW_LINE> self.amortizations = amortizations <NEW_LINE> self.recovery_step = recovery_step <NEW_LINE> self.recovery_rate = recovery_rate <NEW_LINE> self.repayment_rates = repayment_rates <NEW_LINE> self.timing_vector = timing_vector <NEW_LINE> <DEDENT> @property <NEW_LINE> def cumulative_losses(self): <NEW_LINE> <INDENT> return self.losses.cumsum() | The `Pool` model represents the pool of assets, it allows to initialize the assets,
to calculate the delinquencies, the recoveries, the available interest rate.
.Delinquencies: to calculate delinquent assets
.Recoveries: to recover delinquent assets
Asset definition:
* id: id the of the asset
* issuer: issuer of the asset (unique identifier)
* value: par value of the asset
* maturity: maturity date of the asset
* rating: Fitch rating of the asset
* dp_multiplier: defaulting probability multiplier of the asset
* industry: Fitch industry of the asset
* country: country of the asset
* seniority: seniority of the asset
* rr_multiplier: recovery rate multiplier of the asset
* fixed_rr: fixed recovery rate of the asset
* spread: spread generate by the asset | 62599039b57a9660fecd2c30 |
class Rectangle(): <NEW_LINE> <INDENT> def __init__(self, left, top, width, height): <NEW_LINE> <INDENT> self.top = top <NEW_LINE> self.left = left <NEW_LINE> self.width = width <NEW_LINE> self.height = height <NEW_LINE> self.right = left+width <NEW_LINE> self.bottom = top + height <NEW_LINE> <DEDENT> def contains(self, rect): <NEW_LINE> <INDENT> if(rect.right >= self.left and rect.left <= self.left+self.width): <NEW_LINE> <INDENT> if(rect.top <= self.top+self.height and rect.bottom >= self.top): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Represents a sprite's location in the game | 62599039be383301e02549cc |
class ConcreteDiscoverRunner(DiscoverRunner): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_results_summary(results): <NEW_LINE> <INDENT> covered_user_stories = [] <NEW_LINE> uncovered_user_stories = [] <NEW_LINE> for user_story_id, user_story in USER_STORIES.iteritems(): <NEW_LINE> <INDENT> for category in results: <NEW_LINE> <INDENT> for result in results[category]: <NEW_LINE> <INDENT> if result['user_story_id'] == user_story_id: <NEW_LINE> <INDENT> covered_user_stories.append(user_story_id) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> for user_story_id, user_story in USER_STORIES.iteritems(): <NEW_LINE> <INDENT> if user_story_id not in covered_user_stories: <NEW_LINE> <INDENT> uncovered_user_stories.append(user_story_id) <NEW_LINE> <DEDENT> <DEDENT> percentage = float(len(set(uncovered_user_stories)))/float(len(USER_STORIES)) * float(100) <NEW_LINE> summary = { 'percentage_covered': percentage, 'covered_user_stories': covered_user_stories, 'uncovered_user_stories': uncovered_user_stories, } <NEW_LINE> return summary <NEW_LINE> <DEDENT> def suite_result(self, suite, result, **kwargs): <NEW_LINE> <INDENT> result.results['results'] = self.get_results_summary(results=result.results) <NEW_LINE> with open(settings.PROJECT_DIR('') + '/test_results.json', 'w') as outfile: <NEW_LINE> <INDENT> json.dump(result.results, outfile, sort_keys=True, indent=4) <NEW_LINE> <DEDENT> t = get_template('test/test_results.html') <NEW_LINE> c = Context(result.results) <NEW_LINE> with open(settings.PROJECT_DIR('') + '/test_results.html', 'w') as outfile: <NEW_LINE> <INDENT> outfile.write(t.render(c)) <NEW_LINE> <DEDENT> super(ConcreteDiscoverRunner, self).suite_result(suite, result, **kwargs) <NEW_LINE> <DEDENT> def run_suite(self, suite, **kwargs): <NEW_LINE> <INDENT> return StoreResultsTestRunner( verbosity=self.verbosity, failfast=self.failfast, ).run(suite) | Django test runner that exports the results to JSON format | 6259903963f4b57ef008664e |
class NumberParam(Parameter): <NEW_LINE> <INDENT> __slots__ = tuple() <NEW_LINE> def __int__(self): <NEW_LINE> <INDENT> return int(super(NumberParam, self).value()) <NEW_LINE> <DEDENT> def __float__(self): <NEW_LINE> <INDENT> return float(super(NumberParam, self).value()) <NEW_LINE> <DEDENT> def _validate(self, val, context, template=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Schema.str_to_num(val) <NEW_LINE> <DEDENT> except (ValueError, TypeError) as ex: <NEW_LINE> <INDENT> raise exception.StackValidationFailed(message=six.text_type(ex)) <NEW_LINE> <DEDENT> self.schema.validate_value(val, context=context, template=template) <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return Schema.str_to_num(super(NumberParam, self).value()) | A template parameter of type "Number". | 62599039b5575c28eb7135a4 |
class PrettyDict: <NEW_LINE> <INDENT> pretty_name = None <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> attributes = ', '.join('{}={!r}'.format(k, _fmt_value(v)) for k, v in self.items()) <NEW_LINE> return '{}({})'.format(self.__class__.__name__, attributes) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> attributes = ', '.join('{}={!s}'.format(k, _fmt_value(v)) for k, v in self.items()) <NEW_LINE> return '{}({})'.format(self.pretty_name or self.__class__.__name__, attributes) | Mixin for pretty user-defined dictionary printing | 625990391f5feb6acb163da8 |
class TestV1beta1Event(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testV1beta1Event(self): <NEW_LINE> <INDENT> pass | V1beta1Event unit test stubs | 625990390fa83653e46f6090 |
class VertexError(Error): <NEW_LINE> <INDENT> def __init__(self, vertexNumber, message): <NEW_LINE> <INDENT> self.vertexNumber = vertexNumber <NEW_LINE> self.message = "VertexError: Vertex number = %s, Message = %s" % (vertexNumber,message) | Represents a VertexError exception. It handles different types of graph vertex related exceptions
\ingroup Exceptions | 6259903921bff66bcd723e1e |
class IOEngine: <NEW_LINE> <INDENT> def read(self, info, time_ranges, fields=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def write(self, info, measurements): <NEW_LINE> <INDENT> raise NotImplementedError | This is the base class for reading and writing time-ordered data.
In the read and write functions below, "info" is a dict that
addresses some chunk of data somehow. It might simply contain a
filename, or it might contain filename and group name within an
HDF archive. | 62599039ac7a0e7691f7369e |
class ExportMonitor(EveryN): <NEW_LINE> <INDENT> @deprecated_arg_values( "2016-09-23", "The signature of the input_fn accepted by export is changing to be " "consistent with what's used by tf.Learn Estimator's train/evaluate. " "input_fn and input_feature_key will both become required args.", input_fn=None, input_feature_key=None) <NEW_LINE> def __init__(self, every_n_steps, export_dir, input_fn=None, input_feature_key=None, exports_to_keep=5, signature_fn=None, default_batch_size=1): <NEW_LINE> <INDENT> if (input_fn is None) != (input_feature_key is None): <NEW_LINE> <INDENT> raise ValueError( "input_fn and input_feature_key must both be defined or both be " "None. Not passing in input_fn and input_feature_key is also " "deprecated, so you should go with the former.") <NEW_LINE> <DEDENT> super(ExportMonitor, self).__init__(every_n_steps=every_n_steps) <NEW_LINE> self._export_dir = export_dir <NEW_LINE> self._input_fn = input_fn <NEW_LINE> self._input_feature_key = input_feature_key <NEW_LINE> self._use_deprecated_input_fn = input_fn is None <NEW_LINE> self._exports_to_keep = exports_to_keep <NEW_LINE> self._signature_fn = signature_fn <NEW_LINE> self._default_batch_size = default_batch_size <NEW_LINE> self._last_export_dir = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def export_dir(self): <NEW_LINE> <INDENT> return self._export_dir <NEW_LINE> <DEDENT> @property <NEW_LINE> def exports_to_keep(self): <NEW_LINE> <INDENT> return self._exports_to_keep <NEW_LINE> <DEDENT> @property <NEW_LINE> def signature_fn(self): <NEW_LINE> <INDENT> return self._signature_fn <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_export_dir(self): <NEW_LINE> <INDENT> return self._last_export_dir <NEW_LINE> <DEDENT> def every_n_step_end(self, step, outputs): <NEW_LINE> <INDENT> super(ExportMonitor, self).every_n_step_end(step, outputs) <NEW_LINE> try: <NEW_LINE> <INDENT> self._last_export_dir = self._estimator.export( self.export_dir, exports_to_keep=self.exports_to_keep, signature_fn=self.signature_fn, input_fn=self._input_fn, default_batch_size=self._default_batch_size, input_feature_key=self._input_feature_key, use_deprecated_input_fn=self._use_deprecated_input_fn) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> logging.info("Skipping exporting for the same step. " "Consider exporting less frequently.") <NEW_LINE> <DEDENT> <DEDENT> def end(self, session=None): <NEW_LINE> <INDENT> super(ExportMonitor, self).end(session=session) <NEW_LINE> latest_path = saver_lib.latest_checkpoint(self._estimator.model_dir) <NEW_LINE> if latest_path is None: <NEW_LINE> <INDENT> logging.info("Skipping export at the end since model has not been saved " "yet.") <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._last_export_dir = self._estimator.export( self.export_dir, exports_to_keep=self.exports_to_keep, signature_fn=self.signature_fn, input_fn=self._input_fn, default_batch_size=self._default_batch_size, input_feature_key=self._input_feature_key, use_deprecated_input_fn=self._use_deprecated_input_fn) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT> logging.info("Skipping exporting for the same step.") | Monitor that exports Estimator every N steps. | 625990398c3a8732951f770c |
class IssuesClosed(Stats): <NEW_LINE> <INDENT> def fetch(self): <NEW_LINE> <INDENT> log.info("Searching for issues closed by {0}".format(self.user)) <NEW_LINE> query = "search/issues?q=assignee:{0}+closed:{1}..{2}".format( self.user.login, self.options.since, self.options.until) <NEW_LINE> query += "+type:issue" <NEW_LINE> self.stats = [ Issue(issue) for issue in self.parent.github.search(query)] | Issues closed | 6259903966673b3332c315ab |
class UserRoleAssociation(Resource): <NEW_LINE> <INDENT> hints = { 'contract_attributes': ['id', 'role_id', 'user_id', 'tenant_id'], 'types': [('user_id', basestring), ('tenant_id', basestring)], 'maps': {'userId': 'user_id', 'roleId': 'role_id', 'tenantId': 'tenant_id'} } <NEW_LINE> def __init__(self, user_id=None, role_id=None, tenant_id=None, *args, **kw): <NEW_LINE> <INDENT> super(UserRoleAssociation, self).__init__(user_id=user_id, role_id=role_id, tenant_id=tenant_id, *args, **kw) <NEW_LINE> if isinstance(self.user_id, int): <NEW_LINE> <INDENT> self.user_id = str(self.user_id) <NEW_LINE> <DEDENT> if isinstance(self.tenant_id, int): <NEW_LINE> <INDENT> self.tenant_id = str(self.tenant_id) <NEW_LINE> <DEDENT> <DEDENT> def to_json(self, hints=None, model_name=None): <NEW_LINE> <INDENT> if model_name is None: <NEW_LINE> <INDENT> model_name = "role" <NEW_LINE> <DEDENT> return super(UserRoleAssociation, self).to_json(hints=hints, model_name=model_name) <NEW_LINE> <DEDENT> def to_xml(self, hints=None, model_name=None): <NEW_LINE> <INDENT> if model_name is None: <NEW_LINE> <INDENT> model_name = "role" <NEW_LINE> <DEDENT> return super(UserRoleAssociation, self).to_xml(hints=hints, model_name=model_name) | Role Grant model | 62599039e76e3b2f99fd9bc2 |
class EventDay(models.Model): <NEW_LINE> <INDENT> _name='event.day' <NEW_LINE> _order="event_date" <NEW_LINE> event_date = fields.Date('Date', required=True) <NEW_LINE> event_period = fields.Selection([('precamp', 'Pre Camp'), ('maincamp', 'Main Camp'), ('postcamp', 'Post Camp')], default='maincamp', string='Period') <NEW_LINE> event_id = fields.Many2one('event.event', 'Event day', required=True) <NEW_LINE> @api.multi <NEW_LINE> @api.depends('event_day', 'event_period') <NEW_LINE> def name_get(self): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for ed in self: <NEW_LINE> <INDENT> result.append((ed.id, '%s %s-%s' % (dict(self.fields_get(allfields=['event_period'])['event_period']['selection'])[ed.event_period], ed.event_date[8:], ed.event_date[5:7]))) <NEW_LINE> <DEDENT> return result | An Event day | 62599039b830903b9686ed54 |
class Location(object): <NEW_LINE> <INDENT> def __init__(self, location_data): <NEW_LINE> <INDENT> self.location_data = location_data <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s.%s(%s, %s)" % ( self.__module__, self.__class__.__name__, self.latitude, self.longitude) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.place_name: <NEW_LINE> <INDENT> return self.place_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "%s, %s" % (self.latitude, self.longitude) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def latitude(self): <NEW_LINE> <INDENT> return self.location_data.get('Latitude', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def longitude(self): <NEW_LINE> <INDENT> return self.location_data.get('Longitude', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def place_name(self): <NEW_LINE> <INDENT> return self.location_data.get('Place Name', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def foursquare_id(self): <NEW_LINE> <INDENT> return self.location_data.get('Foursquare ID', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def locality(self): <NEW_LINE> <INDENT> return self.location_data.get('Locality', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def administrative_area(self): <NEW_LINE> <INDENT> return self.location_data.get('Administrative Area', None) <NEW_LINE> <DEDENT> @property <NEW_LINE> def country(self): <NEW_LINE> <INDENT> return self.location_data.get('Country', None) | Location data in an entry. | 6259903930c21e258be999c4 |
class DynamicAddressException(Exception): <NEW_LINE> <INDENT> def __init__(self, msg=""): <NEW_LINE> <INDENT> super(DynamicAddressException, self).__init__(msg) <NEW_LINE> self.msg = msg | Throw this if you try to get an address object from a dhcp interface | 6259903973bcbd0ca4bcb43f |
class WorkItemDeleteUpdate(Model): <NEW_LINE> <INDENT> _attribute_map = { 'is_deleted': {'key': 'isDeleted', 'type': 'bool'} } <NEW_LINE> def __init__(self, is_deleted=None): <NEW_LINE> <INDENT> super(WorkItemDeleteUpdate, self).__init__() <NEW_LINE> self.is_deleted = is_deleted | WorkItemDeleteUpdate.
:param is_deleted:
:type is_deleted: bool | 6259903976d4e153a661db4e |
class CompletedServerScan(object): <NEW_LINE> <INDENT> def __init__(self, server_info, plugin_result_list): <NEW_LINE> <INDENT> self.server_info = server_info <NEW_LINE> self.plugin_result_list = plugin_result_list | The results of a successful SSLyze scan on a single server.
| 62599039d53ae8145f91961c |
class Expense(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.Text) <NEW_LINE> budget = db.Column(db.Float) <NEW_LINE> spent = db.Column(db.Float, default=0) <NEW_LINE> fund_id = db.Column(db.Integer, db.ForeignKey('fund.id'), nullable=False) <NEW_LINE> fund = db.relationship('Fund', backref='expenses', lazy=True) <NEW_LINE> legislation_file = db.Column(db.Text, default=None) <NEW_LINE> legislation_number = db.Column(db.Text, default=None) <NEW_LINE> def __init__(self, name, fund, budget): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.fund = fund <NEW_LINE> self.budget = budget <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Expense %r>' % self.name | A single Expense to be deducted from the UC budget | 6259903950485f2cf55dc138 |
class SyntaxData(syndata.SyntaxDataBase): <NEW_LINE> <INDENT> def __init__(self, langid): <NEW_LINE> <INDENT> syndata.SyntaxDataBase.__init__(self, langid) <NEW_LINE> self.SetLexer(stc.STC_LEX_PYTHON) <NEW_LINE> <DEDENT> def GetKeywords(self): <NEW_LINE> <INDENT> return [BOO_KW] <NEW_LINE> <DEDENT> def GetSyntaxSpec(self): <NEW_LINE> <INDENT> return SYNTAX_ITEMS <NEW_LINE> <DEDENT> def GetProperties(self): <NEW_LINE> <INDENT> return [FOLD, TIMMY] <NEW_LINE> <DEDENT> def GetCommentPattern(self): <NEW_LINE> <INDENT> return [u'#'] | SyntaxData object for Boo
@todo: needs custom highlighting handler | 62599039711fe17d825e1577 |
class TestMakeIdUrl(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self._compiler = cece.compiler.Compiler(None, None) <NEW_LINE> <DEDENT> def testNoBackslash(self): <NEW_LINE> <INDENT> result = self._compiler._make_id_url("test/one") <NEW_LINE> self.assertEqual(result, "/test/one/") <NEW_LINE> <DEDENT> def testBackslash(self): <NEW_LINE> <INDENT> result = self._compiler._make_id_url("test\\one") <NEW_LINE> self.assertEqual(result, "/test/one/") | Test ``cece.compiler.Compiler._make_id_url`` | 62599039baa26c4b54d5045f |
class Pooling: <NEW_LINE> <INDENT> def __init__(self, pool_h, pool_w, stride=1, pad=0): <NEW_LINE> <INDENT> self.pool_h = pool_h <NEW_LINE> self.pool_w = pool_w <NEW_LINE> self.stride = stride <NEW_LINE> self.pad = pad <NEW_LINE> self.x = None <NEW_LINE> self.arg_max = None <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> N, C, H, W = x.shape <NEW_LINE> out_h = (H - self.pool_h) // self.stride + 1 <NEW_LINE> out_w = (W - self.pool_w) // self.stride + 1 <NEW_LINE> col = im2col(x, self.pool_h, self.pool_w, self.stride, self.pad) <NEW_LINE> col = col.reshape(-1, self.pool_h * self.pool_w) <NEW_LINE> arg_max = np.argmax(col, axis=1) <NEW_LINE> out = np.max(col, axis=1) <NEW_LINE> out = out.reshape(N, out_h, out_w, C).transpose((0, 3, 1, 2)) <NEW_LINE> self.x = x <NEW_LINE> self.arg_max = arg_max <NEW_LINE> return out <NEW_LINE> <DEDENT> def backward(self, dout): <NEW_LINE> <INDENT> dout = dout.transpose((0, 2, 3, 1)) <NEW_LINE> pool_size = self.pool_h * self.pool_w <NEW_LINE> dmax = np.zeros((dout.size, pool_size)) <NEW_LINE> dmax[np.arange(self.arg_max.size), self.arg_max.flatten()] = dout.flatten() <NEW_LINE> dmax = dmax.reshape(dout.shape + (pool_size,)) <NEW_LINE> dcol = dmax.reshape(dmax.shape[0] * dmax.shape[1] * dmax.shape[2], -1) <NEW_LINE> dx = col2im(dcol, self.x.shape, self.pool_h, self.pool_w, self.stride, self.pad) <NEW_LINE> return dx | 最大池化层 | 625990393eb6a72ae038b820 |
class Vector(object): <NEW_LINE> <INDENT> def __init__(self, x=None, y=None, z=None): <NEW_LINE> <INDENT> self.x, self.y, self.z = x, y, z | 3-space vector of *x*, *y*, *z* | 62599039b5575c28eb7135a5 |
class JsonPipeline(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.f = open('detail.json','wb') <NEW_LINE> self.exporter = JsonItemExporter(self.f,encoding='utf-8') <NEW_LINE> self.exporter.start_exporting() <NEW_LINE> <DEDENT> def process_item(self, item, spider): <NEW_LINE> <INDENT> self.exporter.export_item(item) <NEW_LINE> return item <NEW_LINE> <DEDENT> def close_spider(self, spider): <NEW_LINE> <INDENT> self.exporter.finish_exporting() | 使用自带方法 | 62599039d10714528d69ef67 |
class AddFileForm(forms.Form): <NEW_LINE> <INDENT> file = forms.FileField() <NEW_LINE> tags = forms.CharField(label="Теги", widget=forms.Textarea, required=False) | Add file form | 625990391f5feb6acb163daa |
class TestMath: <NEW_LINE> <INDENT> def test_calc_degrees_north_from_coords_due_north(cls): <NEW_LINE> <INDENT> assert calc_degrees_north_from_coords((0, 0), (-1, 0)) == 0 <NEW_LINE> <DEDENT> def test_calc_degrees_north_from_coords_due_east(cls): <NEW_LINE> <INDENT> assert calc_degrees_north_from_coords((0, 0), (0, -1)) == 90 <NEW_LINE> <DEDENT> def test_calc_degrees_north_from_coords_due_south(cls): <NEW_LINE> <INDENT> assert calc_degrees_north_from_coords((0, 0), (1, 0)) == 180 <NEW_LINE> <DEDENT> def test_calc_degrees_north_from_coords_due_west(cls): <NEW_LINE> <INDENT> assert calc_degrees_north_from_coords((52, 5), (52, 5.1)) == 270 <NEW_LINE> <DEDENT> def test_calc_degrees_north_from_coords_northeast(cls): <NEW_LINE> <INDENT> assert calc_degrees_north_from_coords((0, 0), (-5.196, -3)) == 30 <NEW_LINE> assert calc_degrees_north_from_coords((1, 1), (-1, -1)) == 45 <NEW_LINE> assert calc_degrees_north_from_coords((0, 0), (-3, -5.196)) == 60 <NEW_LINE> <DEDENT> def test_calc_degrees_north_from_coords_southeast(cls): <NEW_LINE> <INDENT> assert calc_degrees_north_from_coords((0, 0), (3, -5.196)) == 120 <NEW_LINE> assert calc_degrees_north_from_coords((0, 0), (5, -5)) == 135 <NEW_LINE> assert calc_degrees_north_from_coords((0, 0), (5.196, -3)) == 150 <NEW_LINE> <DEDENT> def test_calc_degrees_north_from_coords_southwest(cls): <NEW_LINE> <INDENT> assert calc_degrees_north_from_coords((10, 10), (15, 15)) == 225 <NEW_LINE> assert calc_degrees_north_from_coords((10, 10), (13, 15.196)) == 240 <NEW_LINE> <DEDENT> def test_calc_degrees_north_from_coords_northwest(cls): <NEW_LINE> <INDENT> assert calc_degrees_north_from_coords((0, 0), (-5, 5)) == 315 <NEW_LINE> <DEDENT> def test_calc_difference_between_vectors(cls): <NEW_LINE> <INDENT> assert calc_difference_between_vectors(90, 90) == 0 <NEW_LINE> assert calc_difference_between_vectors(90, 45) == 45 <NEW_LINE> assert calc_difference_between_vectors(90, 0) == 90 <NEW_LINE> assert calc_difference_between_vectors(45, 315) == 90 <NEW_LINE> assert calc_difference_between_vectors(180, 90) == 90 <NEW_LINE> assert calc_difference_between_vectors(270, 0) == 90 <NEW_LINE> assert calc_difference_between_vectors(90, 180) == 90 <NEW_LINE> assert calc_difference_between_vectors(90, 270) == 180 <NEW_LINE> assert calc_difference_between_vectors(0, 180) == 180 <NEW_LINE> assert calc_difference_between_vectors(3, 183) == 180 <NEW_LINE> assert calc_difference_between_vectors(357, 177) == 180 | Reminder: coords are (lat, lon), which correspond to (y, x) | 6259903923e79379d538d6b8 |
class MessageSerializerTests(TestCase): <NEW_LINE> <INDENT> def test_noMultipleFields(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, _MessageSerializer, [Field("akey", identity, ""), Field("akey", identity, ""), Field("message_type", identity, "")]) <NEW_LINE> <DEDENT> def test_noBothTypeFields(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, _MessageSerializer, [Field("message_type", identity, ""), Field("action_type", identity, "")]) <NEW_LINE> <DEDENT> def test_missingTypeField(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, _MessageSerializer, []) <NEW_LINE> <DEDENT> def test_noTaskLevel(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, _MessageSerializer, [Field("message_type", identity, ""), Field("task_level", identity, "")]) <NEW_LINE> <DEDENT> def test_noTaskUuid(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, _MessageSerializer, [Field("message_type", identity, ""), Field("task_uuid", identity, "")]) <NEW_LINE> <DEDENT> def test_noTimestamp(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, _MessageSerializer, [Field("message_type", identity, ""), Field("timestamp", identity, "")]) <NEW_LINE> <DEDENT> def test_noUnderscoreStart(self): <NEW_LINE> <INDENT> self.assertRaises(ValueError, _MessageSerializer, [Field("message_type", identity, ""), Field("_key", identity, "")]) <NEW_LINE> <DEDENT> def test_serialize(self): <NEW_LINE> <INDENT> serializer = _MessageSerializer( [Field.forValue("message_type", "mymessage", u"The type"), Field("length", len, "The length of a thing"), ]) <NEW_LINE> message = {"message_type": "mymessage", "length": "thething"} <NEW_LINE> serializer.serialize(message) <NEW_LINE> self.assertEqual(message, {"message_type": "mymessage", "length": 8}) <NEW_LINE> <DEDENT> def test_missingSerializer(self): <NEW_LINE> <INDENT> serializer = _MessageSerializer( [Field.forValue("message_type", "mymessage", u"The type"), Field("length", len, "The length of a thing"), ]) <NEW_LINE> message = {"message_type": "mymessage", "length": "thething", "extra": 123} <NEW_LINE> serializer.serialize(message) <NEW_LINE> self.assertEqual(message, {"message_type": "mymessage", "length": 8, "extra": 123}) <NEW_LINE> <DEDENT> def test_fieldInstances(self): <NEW_LINE> <INDENT> a_field = Field('a_key', identity) <NEW_LINE> arg = object() <NEW_LINE> with self.assertRaises(TypeError) as cm: <NEW_LINE> <INDENT> _MessageSerializer([a_field, arg]) <NEW_LINE> <DEDENT> self.assertEqual( (u'Expected a Field instance but got', arg), cm.exception.args) | Tests for L{_MessageSerializer}. | 62599039b830903b9686ed55 |
class TestMessageTrailer(unittest.TestCase): <NEW_LINE> <INDENT> def test_message_trailer_to_edifact(self): <NEW_LINE> <INDENT> msg_trl = MessageTrailer(number_of_segments=5, sequence_number="00001").to_edifact() <NEW_LINE> self.assertEqual(msg_trl, "UNT+5+00001'") | Test the generating of a message trailer | 6259903950485f2cf55dc139 |
class QualityRecordAdd(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.qr = QualityRecord() <NEW_LINE> self.qwo = QualityWorkOrder() <NEW_LINE> self.qualityWorkOrder_data = { "smBusiUnitGid": "7e2c4ba1d1f64ad7b214a233c7ebb0fb", "code": pm.create_code(), "mdMaterialGid": params.MaterielSJGid, "shouldCheckQty": 10 } <NEW_LINE> resp1 = self.qwo.qualityWorkOrder_create(self.qualityWorkOrder_data) <NEW_LINE> self.qualityRecord_data = { "code":"", "qcInspectionQty": 5, "imeQcQacGid":resp1.pop("data") } <NEW_LINE> <DEDENT> def test_qualityRecordAdd(self): <NEW_LINE> <INDENT> resp2 = self.qr.qualityRecord_add(self.qualityRecord_data) <NEW_LINE> print(resp2) <NEW_LINE> self.assertEqual(True,resp2.pop("success")) <NEW_LINE> self.reportRecord_data = { "qualifiedQty":1, "unQualifiedQty":1, "imeQcQualityGradeGid":"", "qcHandleWay":"", "gid":resp2.pop("data") } <NEW_LINE> resp3 = self.qr.reportRecord(self.reportRecord_data) <NEW_LINE> print(resp3) <NEW_LINE> self.assertEqual(True, resp3.pop("success")) | 报检单 | 62599039d99f1b3c44d0685e |
class RunnableGenericConfig(RunnableConfig): <NEW_LINE> <INDENT> def __init__(self, suite, parent, arch): <NEW_LINE> <INDENT> super(RunnableGenericConfig, self).__init__(suite, parent, arch) <NEW_LINE> <DEDENT> def Run(self, runner, trybot): <NEW_LINE> <INDENT> stdout, stdout_secondary = Unzip(runner()) <NEW_LINE> return ( AccumulateGenericResults(self.graphs, self.units, stdout), AccumulateGenericResults(self.graphs, self.units, stdout_secondary), ) | Represents a runnable suite definition with generic traces. | 62599039dc8b845886d5476d |
class PrimaryCapsules(nn.Module): <NEW_LINE> <INDENT> def __init__(self,num_capsules=10,in_channels=32,out_channels=32): <NEW_LINE> <INDENT> super(PrimaryCapsules, self).__init__() <NEW_LINE> self.num_capsules = num_capsules <NEW_LINE> self.out_channels = out_channels <NEW_LINE> self.capsules = nn.Sequential( P4ConvP4(in_channels,out_channels*num_capsules,3), nn.BatchNorm3d(out_channels*num_capsules), nn.SELU(), ) <NEW_LINE> <DEDENT> def squash(self,x,dim): <NEW_LINE> <INDENT> norm_squared = (x ** 2).sum(dim, keepdim=True) <NEW_LINE> part1 = norm_squared / (1 + norm_squared) <NEW_LINE> part2 = x / torch.sqrt(norm_squared+ 1e-16) <NEW_LINE> output = part1 * part2 <NEW_LINE> return output <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> output = self.capsules(x) <NEW_LINE> H, W = output.size(-2), output.size(-1) <NEW_LINE> output = output.view(-1,self.num_capsules,self.out_channels,4,H,W) <NEW_LINE> output = self.squash(output,dim=2) <NEW_LINE> return output | Use 2d convolution to extract capsules | 625990398a349b6b436873fc |
class RemoveOldWorkspaceInvitations(UpgradeStep): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> annotations = IAnnotations(api.portal.get()) <NEW_LINE> if ANNOTATIONS_DATA_KEY in annotations: <NEW_LINE> <INDENT> del annotations[ANNOTATIONS_DATA_KEY] | Remove old workspace invitations.
| 625990398da39b475be043a8 |
class Food(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> slug = models.SlugField() <NEW_LINE> category = models.ForeignKey('Category') <NEW_LINE> restaurant = models.ForeignKey('Restaurant') <NEW_LINE> price = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) <NEW_LINE> picture = models.FileField(upload_to='uploaded_files/food_pics', blank=True, null=True) <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.slug = slugify(self.name) <NEW_LINE> super(Food, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return '/food/' + str(self.slug) + '/' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name | Defines the state and behavior of a Food object. | 6259903930c21e258be999c7 |
class Child(models.Model): <NEW_LINE> <INDENT> first_name = models.CharField(max_length=50) <NEW_LINE> middle_name = models.CharField(max_length=50, blank=True, null=True) <NEW_LINE> last_name = models.CharField(max_length=50, blank=True, null=True) <NEW_LINE> uid = models.CharField(max_length=100, blank=True, null=True) <NEW_LINE> dob = models.DateField(max_length=20) <NEW_LINE> gender = models.CharField(max_length=10, choices=Gender, default='male') <NEW_LINE> mt = models.ForeignKey(Moi_Type, default='kannada') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['first_name', 'middle_name', 'last_name'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return '%s' % self.first_name <NEW_LINE> <DEDENT> def getRelations(self): <NEW_LINE> <INDENT> return Relations.objects.filter(child__id=self.id) <NEW_LINE> <DEDENT> def getFather(self): <NEW_LINE> <INDENT> return Relations.objects.get(relation_type='Father', child__id=self.id) <NEW_LINE> <DEDENT> def getMother(self): <NEW_LINE> <INDENT> return Relations.objects.get(relation_type='Mother', child__id=self.id) <NEW_LINE> <DEDENT> def getStudent(self): <NEW_LINE> <INDENT> return Student.objects.get(child__id=self.id) <NEW_LINE> <DEDENT> def get_view_url(self): <NEW_LINE> <INDENT> return '/child/%s/view/' % self.id <NEW_LINE> <DEDENT> def get_update_url(self): <NEW_LINE> <INDENT> return '/child/%d/update/' % self.id <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> from django.db import connection <NEW_LINE> connection.features.can_return_id_from_insert = False <NEW_LINE> self.full_clean() <NEW_LINE> super(Child, self).save(*args, **kwargs) | This class stores the personnel information of the childrens | 625990390a366e3fb87ddb9e |
class UnBindEIPRequestSchema(schema.RequestSchema): <NEW_LINE> <INDENT> fields = { "EIPID": fields.Str(required=True, dump_to="EIPID"), "Region": fields.Str(required=True, dump_to="Region"), "ResourceID": fields.Str(required=True, dump_to="ResourceID"), "ResourceType": fields.Str(required=True, dump_to="ResourceType"), "Zone": fields.Str(required=True, dump_to="Zone"), } | UnBindEIP - 解绑外网IP | 62599039d164cc617582212d |
class Red(Indicator): <NEW_LINE> <INDENT> def __call__(self, target: abjad.LogicalTie): <NEW_LINE> <INDENT> for leaf in abjad.iterate.leaves(target, pitched=True): <NEW_LINE> <INDENT> if isinstance(leaf, abjad.Chord): <NEW_LINE> <INDENT> for note_head in leaf.note_heads: <NEW_LINE> <INDENT> abjad.tweak(note_head).color = "#red" <NEW_LINE> <DEDENT> <DEDENT> if isinstance(leaf, abjad.Note): <NEW_LINE> <INDENT> abjad.tweak(leaf.note_head).color = "#red" | Encoding and attaching the color red.
.. container:: example
>>> template = pang.make_single_staff_score_template()
>>> maker = pang.SegmentMaker(
... score_template=template,
... )
>>> instances = [0, 1, 2, 3]
>>> durations = [1, 1, 0.5, 0.5]
>>> pitches = [0, 0, (0, 12), 0]
>>> sound_points_generator = pang.ManualSoundPointsGenerator(
... instances=instances,
... durations=durations,
... pitches=pitches,
... )
>>> sequence = pang.Sequence(
... sound_points_generator=sound_points_generator,
... )
>>> for event in sequence:
... event.attach(pang.Red())
...
>>> command = pang.QuantizeSequenceCommand(sequence)
>>> scope = pang.Scope(voice_name="Voice")
>>> maker(scope, command)
>>> lilypond_file = maker.run(environment="docs")
>>> abjad.show(lilypond_file) # doctest: +SKIP
.. docs::
>>> string = abjad.lilypond(lilypond_file)
>>> print(string)
\version "2.20.0"
\language "english"
<BLANKLINE>
#(ly:set-option 'relative-includes #t)
<BLANKLINE>
\include "source/_stylesheets/single-voice-staff.ily"
<BLANKLINE>
\context Score = "Score"
<<
\context Staff = "Staff"
<<
\context Voice = "Voice"
{
{
\tempo 4=60
\time 4/4
\tweak color #red
c'4
\tweak color #red
c'4
<
\tweak color #red
c'
\tweak color #red
c''
>8
r8
\tweak color #red
c'8
r8
}
}
>>
>> | 625990393c8af77a43b68818 |
class UserViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.all() <NEW_LINE> serializer_class = UserSerializers <NEW_LINE> permission_classes = (UserViewSetPermission,) <NEW_LINE> @list_route(methods=['post'], permission_classes=(), ) <NEW_LINE> def login(self, request): <NEW_LINE> <INDENT> email = request.data.get('email', None) <NEW_LINE> password = request.data.get('password', None) <NEW_LINE> if email is None and password is None: <NEW_LINE> <INDENT> LOGGER.error("Either email or password not matched.") <NEW_LINE> return Response( data="Please enter a valid email address and password", status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> data = {'email': email, 'password': password} <NEW_LINE> resp = requests.post(url=TOKEN_GET_ENDPOINT, data=data) <NEW_LINE> if resp.status_code != 200: <NEW_LINE> <INDENT> LOGGER.error("Invalid credentials, Login failed!.") <NEW_LINE> return Response(data="Invalid Credentials", status=status.HTTP_401_UNAUTHORIZED) <NEW_LINE> <DEDENT> LOGGER.debug("Login successful.") <NEW_LINE> user_type = {'user_type': User.objects.get(email=email).user_type} <NEW_LINE> response = json.loads(resp.text) <NEW_LINE> response.update(user_type) <NEW_LINE> return Response(json.dumps(response), status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> def create(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if request.data.get('user_type', None) == "CANDIDATE": <NEW_LINE> <INDENT> test_id = request.data.get('test', None) <NEW_LINE> if test_id is not None: <NEW_LINE> <INDENT> resp = super(UserViewSet, self).create(request, *args, **kwargs) <NEW_LINE> user_id = resp.data.get('id', None) <NEW_LINE> user_instance = User.objects.get(id=user_id) <NEW_LINE> test_instance = Test.objects.get(id=test_id) <NEW_LINE> _ = CandidateTestMapping.objects.create( candidate=user_instance, test=test_instance, schedule=request.data.get('schedule', None), is_accepted=request.data.get('is_accepted', False)) <NEW_LINE> LOGGER.debug("Candidate created successfully, associated " "with Test ID %s", test_id) <NEW_LINE> return resp <NEW_LINE> <DEDENT> return super(UserViewSet, self).create(request, *args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resp = super(UserViewSet, self).create(request, *args, **kwargs) <NEW_LINE> LOGGER.debug("Interviewer created successfully.") <NEW_LINE> return resp <NEW_LINE> <DEDENT> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> if self.request.data.get('user_type', None) == 'CANDIDATE': <NEW_LINE> <INDENT> serializer.save(is_staff=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> serializer.save() | User view set to create, login, retrieve, update and delete the question
object. | 62599039d4950a0f3b11171c |
class EmployeeContactListSerializer(AbstractBaseSerializer): <NEW_LINE> <INDENT> contact_type_name = serializers.StringRelatedField(source=CONTACT_TYPE, read_only=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> list_serializer_class = FilteredListSerializer <NEW_LINE> model = EmployeeContact <NEW_LINE> fields = [ 'id', 'contact_type', 'contact_type_name', 'contact_value', 'deleted_status' ] | Serializer for listing Employee Contact only | 6259903991af0d3eaad3afec |
class RunAlreadyActive(ErrorDetails): <NEW_LINE> <INDENT> id: Literal["RunAlreadyActive"] = "RunAlreadyActive" <NEW_LINE> title: str = "Run Already Active" | An error if one tries to create a new run while one is already active. | 625990391d351010ab8f4cd4 |
class User(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> login = db.Column(db.String(80), unique=True) <NEW_LINE> password = db.Column(db.String(64)) <NEW_LINE> country = db.Column(db.String(32)) <NEW_LINE> location = db.Column(db.String(32)) <NEW_LINE> coordinates = db.Column(db.String(32)) <NEW_LINE> is_finish_setup = db.Column(db.Boolean, nullable=False) <NEW_LINE> def is_authenticated(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def is_active(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def is_anonymous(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> return self.id <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.username | Create user model. For simplicity, it will store passwords
in plain text. | 62599039287bf620b6272da4 |
class TestSecondaryArchComposeBranchedImageStart(Base): <NEW_LINE> <INDENT> nodoc = True <NEW_LINE> expected_title = "compose.branched.image.start" <NEW_LINE> expected_subti = "Started building other images for Fedora 18 (arm) compose" <NEW_LINE> expected_objects = set(['branched/arm']) <NEW_LINE> msg = { "i": 1, "timestamp": 1344447839.891876, "topic": "org.fedoraproject.prod.compose.branched.image.start", "msg": { "log": "start", "branch": "18", "arch": "arm", }, } | The `release engineering
<https://fedoraproject.org/wiki/ReleaseEngineering>`_ "compose" scripts
used to produce these messages when they had
**started building live, cloud and disk images for**
a secondary arch compose for a Branched release. Since the Pungi 4
migration, all arches are included in the same compose process. | 625990396e29344779b0180b |
class HasXCoordinateSelector(HasCoordinateSelector): <NEW_LINE> <INDENT> def __init__(self, coords=None, min_points=1, tolerance=0.1): <NEW_LINE> <INDENT> super().__init__(coords=coords, min_points=min_points, tolerance=tolerance) <NEW_LINE> <DEDENT> def filter(self, objectList): <NEW_LINE> <INDENT> r = [] <NEW_LINE> for o, vertices in object_vertices(objectList): <NEW_LINE> <INDENT> if self.count_matching_vertices(vertices, "X") >= self.min_points: <NEW_LINE> <INDENT> r.append(o) <NEW_LINE> <DEDENT> <DEDENT> return r | A CQ Selector class which filters edges which have specified values
for their X coordinate | 6259903994891a1f408b9fd4 |
class Bleasdale(Component): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Component.__init__(self, ('a', 'b', 'c')) <NEW_LINE> self.c.value = 1.0 <NEW_LINE> <DEDENT> def function(self, x): <NEW_LINE> <INDENT> a = self.a.value <NEW_LINE> b = self.b.value <NEW_LINE> c = self.c.value <NEW_LINE> abx = (a + b * x) <NEW_LINE> return np.where(abx > 0., abx ** (-1 / c), 0.) <NEW_LINE> <DEDENT> def grad_a(self, x): <NEW_LINE> <INDENT> a = self.a.value <NEW_LINE> b = self.b.value <NEW_LINE> c = self.c.value <NEW_LINE> return -(b * x + a) ** (-1. / c - 1.) / c <NEW_LINE> <DEDENT> def grad_b(self, x): <NEW_LINE> <INDENT> a = self.a.value <NEW_LINE> b = self.b.value <NEW_LINE> c = self.c.value <NEW_LINE> return -(x * (b * x + a) ** (-1 / c - 1)) / c <NEW_LINE> <DEDENT> def grad_c(self, x): <NEW_LINE> <INDENT> a = self.a.value <NEW_LINE> b = self.b.value <NEW_LINE> c = self.c.value <NEW_LINE> return np.log(b * x + a) / (c ** 2. * (b * x + a) ** (1. / c)) | Bleasdale function component.
f(x) = (a+b*x)^(-1/c)
Attributes
----------
a : Float
b : Float
c : Float | 625990398e05c05ec3f6f738 |
class TestQueryEvent(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testQueryEvent(self): <NEW_LINE> <INDENT> pass | QueryEvent unit test stubs | 6259903930dc7b76659a09ed |
class CalculatedFieldValidator(BaseValidator): <NEW_LINE> <INDENT> def __init__(self, prop): <NEW_LINE> <INDENT> super(CalculatedFieldValidator, self).__init__(prop) <NEW_LINE> <DEDENT> @property <NEW_LINE> def allowed_arguments(self): <NEW_LINE> <INDENT> self._allowed_args.clear() <NEW_LINE> self._allowed_args["max_digits"] = "int" <NEW_LINE> self._allowed_args["decimal_places"] = "int" <NEW_LINE> self._allowed_args["unique"] = ("", True, False) <NEW_LINE> self._allowed_args["calc"] = "" <NEW_LINE> return self._allowed_args <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> super(CalculatedFieldValidator, self).validate() <NEW_LINE> max_digits_exits = False <NEW_LINE> dec_places_exits = False <NEW_LINE> for arg in self.prop.arguments: <NEW_LINE> <INDENT> if arg.name == "max_digits": <NEW_LINE> <INDENT> max_digits_exits = True <NEW_LINE> <DEDENT> elif arg.name == "decimal_places": <NEW_LINE> <INDENT> dec_places_exits = True <NEW_LINE> <DEDENT> <DEDENT> if max_digits_exits and not dec_places_exits: <NEW_LINE> <INDENT> raise DecimalArgsException(_type="calculated_field") | Validator for the calculated field | 62599039287bf620b6272da5 |
class SocketClosedRemote (NetworkError): <NEW_LINE> <INDENT> pass | This indicates that the socket was closed on the remote end. | 6259903976d4e153a661db50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.