code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class PlacerRadialPlacementFromChipConstraint(AbstractPlacerConstraint): <NEW_LINE> <INDENT> __slots__ = [ "_x", "_y" ] <NEW_LINE> def __init__(self, x, y): <NEW_LINE> <INDENT> self._x = x <NEW_LINE> self._y = y <NEW_LINE> <DEDENT> @property <NEW_LINE> def x(self): <NEW_LINE> <INDENT> return self._x <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> return self._y <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "PlacerRadialPlacementFromChipConstraint(x={}, y={})".format( self._x, self._y) | A constraint that attempts to place a vertex as close to a chip as possible (including on it)
| 62598fafdd821e528d6d8f48 |
class ActionTypeTests(TestCase): <NEW_LINE> <INDENT> def actionType(self): <NEW_LINE> <INDENT> return ActionType("myapp:mysystem:myaction", [], [], "An action type") <NEW_LINE> <DEDENT> def test_call(self): <NEW_LINE> <INDENT> actionType = self.actionType() <NEW_LINE> actionType._startAction = lambda *args, **kwargs: 1234 <NEW_LINE> result = actionType(object()) <NEW_LINE> self.assertEqual(result, 1234) <NEW_LINE> <DEDENT> def test_callArguments(self): <NEW_LINE> <INDENT> called = [] <NEW_LINE> actionType = self.actionType() <NEW_LINE> actionType._startAction = lambda *args, **kwargs: called.append( (args, kwargs)) <NEW_LINE> logger = object() <NEW_LINE> actionType(logger, key=5) <NEW_LINE> self.assertEqual(called, [((logger, "myapp:mysystem:myaction", actionType._serializers), {"key": 5})]) <NEW_LINE> <DEDENT> def test_defaultStartAction(self): <NEW_LINE> <INDENT> self.assertEqual(ActionType._startAction, startAction) <NEW_LINE> <DEDENT> def test_asTask(self): <NEW_LINE> <INDENT> actionType = self.actionType() <NEW_LINE> actionType._startTask = lambda *args, **kwargs: 1234 <NEW_LINE> result = actionType.asTask(object()) <NEW_LINE> self.assertEqual(result, 1234) <NEW_LINE> <DEDENT> def test_asTaskArguments(self): <NEW_LINE> <INDENT> called = [] <NEW_LINE> actionType = self.actionType() <NEW_LINE> actionType._startTask = lambda *args, **kwargs: called.append( (args, kwargs)) <NEW_LINE> logger = object() <NEW_LINE> actionType.asTask(logger, key=5) <NEW_LINE> self.assertEqual(called, [((logger, "myapp:mysystem:myaction", actionType._serializers), {"key": 5})]) <NEW_LINE> <DEDENT> def test_defaultStartTask(self): <NEW_LINE> <INDENT> self.assertEqual(ActionType._startTask, startTask) <NEW_LINE> <DEDENT> def test_description(self): <NEW_LINE> <INDENT> actionType = self.actionType() <NEW_LINE> self.assertEqual(actionType.description, "An action type") <NEW_LINE> <DEDENT> def test_optionalDescription(self): <NEW_LINE> <INDENT> actionType = ActionType("name", [], []) <NEW_LINE> self.assertEqual(actionType.description, "") | General tests for L{ActionType}. | 62598faf8e7ae83300ee90b6 |
class H2(_H): <NEW_LINE> <INDENT> pass | Implement the ``h2`` HTML tag. | 62598faf097d151d1a2c103e |
class MediaGraphSink(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, 'name': {'required': True}, 'inputs': {'required': True}, } <NEW_LINE> _attribute_map = { 'type': {'key': '@type', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'inputs': {'key': 'inputs', 'type': '[MediaGraphNodeInput]'}, } <NEW_LINE> _subtype_map = { 'type': {'#Microsoft.Media.MediaGraphAssetSink': 'MediaGraphAssetSink', '#Microsoft.Media.MediaGraphFileSink': 'MediaGraphFileSink', '#Microsoft.Media.MediaGraphIoTHubMessageSink': 'MediaGraphIoTHubMessageSink'} } <NEW_LINE> def __init__( self, *, name: str, inputs: List["MediaGraphNodeInput"], **kwargs ): <NEW_LINE> <INDENT> super(MediaGraphSink, self).__init__(**kwargs) <NEW_LINE> self.type = None <NEW_LINE> self.name = name <NEW_LINE> self.inputs = inputs | Enables a media graph to write media data to a destination outside of the Live Video Analytics IoT Edge module.
You probably want to use the sub-classes and not this class directly. Known
sub-classes are: MediaGraphAssetSink, MediaGraphFileSink, MediaGraphIoTHubMessageSink.
All required parameters must be populated in order to send to Azure.
:param type: Required. The discriminator for derived types.Constant filled by server.
:type type: str
:param name: Required. The name to be used for the media graph sink.
:type name: str
:param inputs: Required. An array of the names of the other nodes in the media graph, the
outputs of which are used as input for this sink node.
:type inputs: list[~azure.media.analyticsedge.models.MediaGraphNodeInput] | 62598faf99cbb53fe6830eec |
class double_well(overdamped_langevin): <NEW_LINE> <INDENT> def invariant_measure(self,x): <NEW_LINE> <INDENT> return np.exp(-self.U(x)/self['kT']) <NEW_LINE> <DEDENT> def U(self,x,**kw): <NEW_LINE> <INDENT> return (x**2-1.0)**2 <NEW_LINE> <DEDENT> def force(self,x,t,**kw): <NEW_LINE> <INDENT> dU = 4*x*(x**2-1) <NEW_LINE> return -dU/self["friction_coeff"] <NEW_LINE> <DEDENT> def __init__(self, **simulation_args): <NEW_LINE> <INDENT> super(double_well, self).__init__(**simulation_args) <NEW_LINE> self["potential"] = self.U <NEW_LINE> self["SDE_f"] = self.force | Defines a symmetric double well of height 1kT, under a
Langevin overdamped system integrated by Euler-Maruyama.
This sets SDE_f to the gradient of the double well potential.
Parameters
----------
all parameters defined by SDE_euler_maruyama, overdamped_langevin and | 62598faf3346ee7daa337651 |
class MesosClusterRepository: <NEW_LINE> <INDENT> mesos_enabled = False <NEW_LINE> master_address = None <NEW_LINE> master_port = None <NEW_LINE> secret_file = None <NEW_LINE> role = None <NEW_LINE> principal = None <NEW_LINE> default_volumes = () <NEW_LINE> dockercfg_location = None <NEW_LINE> offer_timeout = None <NEW_LINE> secret = None <NEW_LINE> name = "frameworks" <NEW_LINE> clusters = {} <NEW_LINE> state_data = {} <NEW_LINE> state_watcher = None <NEW_LINE> @classmethod <NEW_LINE> def attach(cls, _, observer): <NEW_LINE> <INDENT> cls.state_watcher = observer <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_cluster(cls, master_address=None): <NEW_LINE> <INDENT> if master_address is None: <NEW_LINE> <INDENT> master_address = cls.master_address <NEW_LINE> <DEDENT> if master_address not in cls.clusters: <NEW_LINE> <INDENT> framework_id = cls.state_data.get(master_address) <NEW_LINE> cluster = MesosCluster( mesos_address=master_address, mesos_master_port=cls.master_port, secret=cls.secret, principal=cls.principal, mesos_role=cls.role, framework_id=framework_id, enabled=cls.mesos_enabled, default_volumes=cls.default_volumes, dockercfg_location=cls.dockercfg_location, offer_timeout=cls.offer_timeout, ) <NEW_LINE> cls.clusters[master_address] = cluster <NEW_LINE> <DEDENT> return cls.clusters[master_address] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def shutdown(cls): <NEW_LINE> <INDENT> for cluster in cls.clusters.values(): <NEW_LINE> <INDENT> cluster.stop() <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def configure(cls, mesos_options): <NEW_LINE> <INDENT> cls.master_address = mesos_options.master_address <NEW_LINE> cls.master_port = mesos_options.master_port <NEW_LINE> cls.secret_file = mesos_options.secret_file <NEW_LINE> cls.role = mesos_options.role <NEW_LINE> cls.secret = get_secret_from_file(cls.secret_file) <NEW_LINE> cls.principal = mesos_options.principal <NEW_LINE> cls.mesos_enabled = mesos_options.enabled <NEW_LINE> cls.default_volumes = [vol._asdict() for vol in mesos_options.default_volumes] <NEW_LINE> cls.dockercfg_location = mesos_options.dockercfg_location <NEW_LINE> cls.offer_timeout = mesos_options.offer_timeout <NEW_LINE> for cluster in cls.clusters.values(): <NEW_LINE> <INDENT> cluster.set_enabled(cls.mesos_enabled) <NEW_LINE> cluster.configure_tasks( default_volumes=cls.default_volumes, dockercfg_location=cls.dockercfg_location, offer_timeout=cls.offer_timeout, ) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def restore_state(cls, mesos_state): <NEW_LINE> <INDENT> cls.state_data = mesos_state.get(cls.name, {}) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def save(cls, master_address, framework_id): <NEW_LINE> <INDENT> cls.state_data[master_address] = framework_id <NEW_LINE> cls.state_watcher.handler(cls, None) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def remove(cls, master_address): <NEW_LINE> <INDENT> if master_address in cls.state_data: <NEW_LINE> <INDENT> del cls.state_data[master_address] <NEW_LINE> cls.state_watcher.handler(cls, None) | A class that stores MesosCluster objects and configuration. | 62598faf4f88993c371f0514 |
class TensorType(ResultType): <NEW_LINE> <INDENT> def __init__(self, shape, dtype='float32'): <NEW_LINE> <INDENT> if not isinstance(shape, (tuple, list)): <NEW_LINE> <INDENT> raise TypeError('shape must be a tuple or list: %s' % str(shape)) <NEW_LINE> <DEDENT> self._type_shape = loom.TypeShape(dtype, shape) <NEW_LINE> <DEDENT> def _repr_args(self): <NEW_LINE> <INDENT> return [self.shape, self.dtype] <NEW_LINE> <DEDENT> def __array__(self): <NEW_LINE> <INDENT> return np.zeros(self.shape, self.dtype) <NEW_LINE> <DEDENT> @property <NEW_LINE> def shape(self): <NEW_LINE> <INDENT> return self._type_shape.shape <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return self._type_shape.dtype <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return np.prod(self.shape, dtype=np.int) <NEW_LINE> <DEDENT> @property <NEW_LINE> def ndim(self): <NEW_LINE> <INDENT> return len(self.shape) <NEW_LINE> <DEDENT> def flatten(self, instance): <NEW_LINE> <INDENT> return [instance] | Tensors (which may be numpy or tensorflow) of a particular shape.
Tensor types implement the numpy array protocol, which means that
e.g. `np.ones_like(tensor_type)` will do what you expect it
to. Calling `np.array(tensor_type)` returns a zeroed array. | 62598faf67a9b606de545fe1 |
class DeleteEndpoint(command.Command): <NEW_LINE> <INDENT> log = logging.getLogger(__name__ + '.DeleteEndpoint') <NEW_LINE> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(DeleteEndpoint, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( 'endpoint', metavar='<endpoint-id>', help='Endpoint ID to delete', ) <NEW_LINE> return parser <NEW_LINE> <DEDENT> @utils.log_method(log) <NEW_LINE> def take_action(self, parsed_args): <NEW_LINE> <INDENT> identity_client = self.app.client_manager.identity <NEW_LINE> endpoint_id = utils.find_resource(identity_client.endpoints, parsed_args.endpoint).id <NEW_LINE> identity_client.endpoints.delete(endpoint_id) <NEW_LINE> return | Delete endpoint | 62598faf30dc7b766599f861 |
class CertificateChain: <NEW_LINE> <INDENT> parent = None <NEW_LINE> child = None <NEW_LINE> def __init__(self, cert, path): <NEW_LINE> <INDENT> self.cert = cert <NEW_LINE> self.path = path | Object to store the tree of a certificate chain. | 62598faf99fddb7c1ca62df3 |
class ObjectDetector(ImageModel): <NEW_LINE> <INDENT> def __init__(self, bigdl_type="float"): <NEW_LINE> <INDENT> self.bigdl_type = bigdl_type <NEW_LINE> super(ObjectDetector, self).__init__(None, bigdl_type) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def load_model(path, weight_path=None, bigdl_type="float"): <NEW_LINE> <INDENT> jmodel = callBigDlFunc(bigdl_type, "loadObjectDetector", path, weight_path) <NEW_LINE> model = ImageModel._do_load(jmodel, bigdl_type) <NEW_LINE> model.__class__ = ObjectDetector <NEW_LINE> return model | A pre-trained object detector model.
:param model_path The path containing the pre-trained model | 62598faf7d847024c075c3d7 |
class FormatCBFMiniEigerPhotonFactory(FormatCBFMini): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def understand(image_file): <NEW_LINE> <INDENT> if "ENABLE_PHOTON_FACTORY_TWO_EIGER" in os.environ: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _goniometer(self): <NEW_LINE> <INDENT> return self._goniometer_factory.make_goniometer( (1, 0, 0), (1, 0, 0, 0, 1, 0, 0, 0, 1) ) <NEW_LINE> <DEDENT> def _detector(self): <NEW_LINE> <INDENT> if "_lower_" in self._image_file: <NEW_LINE> <INDENT> detector = self._detector_factory.complex( "PAD", origin=(-79.3767, 2.47119, -169.509), fast=(0.999997, -0.00228845, 0.00127629), slow=(-0.0026197, -0.862841, 0.505469), pixel=(0.075, 0.075), size=(2070, 2167), trusted_range=(-1, 1e7), ) <NEW_LINE> <DEDENT> elif "_upper_" in self._image_file: <NEW_LINE> <INDENT> detector = self._detector_factory.complex( "PAD", origin=(75.1912, 14.1117, -124.34), fast=(-0.999993, 0.00338011, -0.00156153), slow=(0.00213163, 0.863573, 0.504219), pixel=(0.075, 0.075), size=(2070, 2167), trusted_range=(-1, 1e7), ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError("Don't understand image") <NEW_LINE> <DEDENT> return detector <NEW_LINE> <DEDENT> def _beam(self): <NEW_LINE> <INDENT> return self._beam_factory.complex( sample_to_source=(-0.00573979, -0, 0.999984), polarization_fraction=0.999, polarization_plane_normal=(0, 1, 0), wavelength=1.1, ) <NEW_LINE> <DEDENT> def _scan(self): <NEW_LINE> <INDENT> exposure_time = 1 <NEW_LINE> osc_start = float(self._cif_header_dictionary["Start_angle"].split()[0]) <NEW_LINE> osc_range = 0.1 <NEW_LINE> timestamp = 1 <NEW_LINE> return self._scan_factory.single_file( self._image_file, exposure_time, osc_start, osc_range, timestamp ) <NEW_LINE> <DEDENT> def detectorbase_start(self): <NEW_LINE> <INDENT> self.detectorbase = PilatusImage(self._image_file) <NEW_LINE> self.detectorbase.readHeader() <NEW_LINE> self.detectorbase.parameters["SIZE1"] = 2167 <NEW_LINE> self.detectorbase.parameters["SIZE2"] = 2070 <NEW_LINE> <DEDENT> def get_vendortype(self): <NEW_LINE> <INDENT> return gv(self.get_detector()) | A class for reading mini CBF format Eiger images, and correctly
constructing a model for the experiment from this.
Specific for 2-Eiger setup at Photon Factory based on images sent by
Yusuke Yamada. Geometry currently hard-coded as no geometry information in
image headers. Assumes image filenames contain the string '_upper_' or
'_lower_' to distinguish the two detectors.
Only works if environment variable ENABLE_PHOTON_FACTORY_TWO_EIGER is set. | 62598fafcc0a2c111447b026 |
class SuperBaseView(GlobalBaseView): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def validate_sign(cls, sign_: str, params: tuple): <NEW_LINE> <INDENT> def f(func): <NEW_LINE> <INDENT> def wrapper(self, request, args): <NEW_LINE> <INDENT> sign = args.get(sign_) <NEW_LINE> key = SimpleEncrypt.decrypt(sign) <NEW_LINE> key_list = key.split("@") <NEW_LINE> if len(key_list) != len(params): <NEW_LINE> <INDENT> return self.send_error(403, {"error_text": "鉴权失败"}) <NEW_LINE> <DEDENT> for index, v in enumerate(params): <NEW_LINE> <INDENT> if key_list[index] != str(args.get(v)): <NEW_LINE> <INDENT> return self.send_error(403, {"error_text": "鉴权失败"}) <NEW_LINE> <DEDENT> <DEDENT> return func(self, request, args) <NEW_LINE> <DEDENT> return wrapper <NEW_LINE> <DEDENT> return f <NEW_LINE> <DEDENT> def _get_current_user(self, request): <NEW_LINE> <INDENT> jwt = ZhiHaoJWTAuthentication() <NEW_LINE> try: <NEW_LINE> <INDENT> res = jwt.authenticate(request) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> res = None <NEW_LINE> <DEDENT> if res: <NEW_LINE> <INDENT> user = res[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user = None <NEW_LINE> <DEDENT> return user <NEW_LINE> <DEDENT> def _set_current_user( self, user: User, expiration_delta=datetime.timedelta(days=1) ): <NEW_LINE> <INDENT> jwt_payload_handler = jwt_setting.JWT_PAYLOAD_HANDLER <NEW_LINE> jwt_encode_handler = jwt_setting.JWT_ENCODE_HANDLER <NEW_LINE> payload = jwt_payload_handler(user, expiration_delta) <NEW_LINE> token = jwt_encode_handler(payload) <NEW_LINE> refresh_payload = jwt_payload_handler(user, datetime.timedelta(days=1), 'refresh_token') <NEW_LINE> refresh_token = jwt_encode_handler(refresh_payload) <NEW_LINE> return (token, refresh_token) <NEW_LINE> <DEDENT> def _refresh_current_user( self, user: User, expiration_delta=datetime.timedelta(days=1) ): <NEW_LINE> <INDENT> jwt_payload_handler = jwt_setting.JWT_PAYLOAD_HANDLER <NEW_LINE> jwt_encode_handler = jwt_setting.JWT_ENCODE_HANDLER <NEW_LINE> payload = jwt_payload_handler(user, expiration_delta) <NEW_LINE> token = jwt_encode_handler(payload) <NEW_LINE> return token | 对接总后台, 没有登录信息和店铺信息 | 62598fafaad79263cf42e7e8 |
class Port(model_base.HasStandardAttributes, model_base.BASEV2, HasId, HasTenant): <NEW_LINE> <INDENT> name = sa.Column(sa.String(attr.NAME_MAX_LEN)) <NEW_LINE> network_id = sa.Column(sa.String(36), sa.ForeignKey("networks.id"), nullable=False) <NEW_LINE> fixed_ips = orm.relationship(IPAllocation, backref='port', lazy='joined', passive_deletes='all') <NEW_LINE> mac_address = sa.Column(sa.String(32), nullable=False) <NEW_LINE> admin_state_up = sa.Column(sa.Boolean(), nullable=False) <NEW_LINE> status = sa.Column(sa.String(16), nullable=False) <NEW_LINE> device_id = sa.Column(sa.String(attr.DEVICE_ID_MAX_LEN), nullable=False) <NEW_LINE> device_owner = sa.Column(sa.String(attr.DEVICE_OWNER_MAX_LEN), nullable=False) <NEW_LINE> dns_name = sa.Column(sa.String(255), nullable=True) <NEW_LINE> __table_args__ = ( sa.Index( 'ix_ports_network_id_mac_address', 'network_id', 'mac_address'), sa.Index( 'ix_ports_network_id_device_owner', 'network_id', 'device_owner'), sa.UniqueConstraint( network_id, mac_address, name='uniq_ports0network_id0mac_address'), model_base.BASEV2.__table_args__ ) <NEW_LINE> def __init__(self, id=None, tenant_id=None, name=None, network_id=None, mac_address=None, admin_state_up=None, status=None, device_id=None, device_owner=None, fixed_ips=None, dns_name=None): <NEW_LINE> <INDENT> super(Port, self).__init__() <NEW_LINE> self.id = id <NEW_LINE> self.tenant_id = tenant_id <NEW_LINE> self.name = name <NEW_LINE> self.network_id = network_id <NEW_LINE> self.mac_address = mac_address <NEW_LINE> self.admin_state_up = admin_state_up <NEW_LINE> self.device_owner = device_owner <NEW_LINE> self.device_id = device_id <NEW_LINE> self.dns_name = dns_name <NEW_LINE> if fixed_ips: <NEW_LINE> <INDENT> self.fixed_ips = fixed_ips <NEW_LINE> <DEDENT> self.status = status | Represents a port on a Neutron v2 network. | 62598fafcc40096d6161a1e4 |
class WSIdentityGroupAPITest(unittest.TestCase): <NEW_LINE> <INDENT> def test_subscribe(self): <NEW_LINE> <INDENT> api = identity_group.IdentityGroupAPI() <NEW_LINE> self.assertEqual( [('/identity-groups/foo.bar', '*')], api.subscribe({'topic': '/identity-groups', 'identity-group': 'foo.bar'}) ) <NEW_LINE> self.assertEqual( [('/identity-groups/foo.*', '*')], api.subscribe({'topic': '/identity-groups', 'identity-group': 'foo.*'}) ) <NEW_LINE> self.assertEqual( [('/identity-groups/*', '*')], api.subscribe({'topic': '/identity-groups'}) ) <NEW_LINE> with six.assertRaisesRegex( self, jsonschema.exceptions.ValidationError, '\'filter\' was unexpected' ): <NEW_LINE> <INDENT> api.subscribe({'topic': '/identity-groups', 'filter': 'foo!'}) <NEW_LINE> <DEDENT> with six.assertRaisesRegex( self, jsonschema.exceptions.ValidationError, 'None is not of type u?\'string\'' ): <NEW_LINE> <INDENT> api.subscribe({'topic': '/identity-groups', 'identity-group': None}) <NEW_LINE> <DEDENT> <DEDENT> def test_on_event(self): <NEW_LINE> <INDENT> api = identity_group.IdentityGroupAPI() <NEW_LINE> self.assertEqual( {'topic': '/identity-groups', 'identity-group': 'foo.bar', 'identity': 3, 'host': 'xxx.xx.com', 'app': 'foo.bar#123', 'sow': True}, api.on_event( '/identity-groups/foo.bar/3', None, '{"host": "xxx.xx.com", "app": "foo.bar#123"}' ) ) <NEW_LINE> self.assertEqual( {'topic': '/identity-groups', 'identity-group': 'foo.bar', 'identity': 3, 'host': None, 'app': None, 'sow': False}, api.on_event( '/identity-groups/foo.bar/3', 'd', None ) ) | Tests for identity group websocket API. | 62598faf01c39578d7f12d93 |
class MetricsCollections(metaclass=Singleton): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__collections = dict() <NEW_LINE> <DEDENT> @property <NEW_LINE> def collections(self): <NEW_LINE> <INDENT> return self.__collections <NEW_LINE> <DEDENT> @collections.setter <NEW_LINE> def collections(self, value): <NEW_LINE> <INDENT> self.__collections = value <NEW_LINE> <DEDENT> def add_to_collection(self, collection_name, metric_instance): <NEW_LINE> <INDENT> if collection_name not in self.__collections.keys(): <NEW_LINE> <INDENT> self.__collections[collection_name] = dict() <NEW_LINE> <DEDENT> if metric_instance.flavor: <NEW_LINE> <INDENT> self.__collections[collection_name][metric_instance.flavor] = metric_instance <NEW_LINE> self.__collections[collection_name][metric_instance.metric_uuid] = metric_instance <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__collections[collection_name][metric_instance.metric_uuid] = metric_instance <NEW_LINE> <DEDENT> <DEDENT> def get_collection(self, name): <NEW_LINE> <INDENT> collection = self.__collections.get(name, None) <NEW_LINE> result_dict = dict() <NEW_LINE> if collection: <NEW_LINE> <INDENT> for metric in collection.keys(): <NEW_LINE> <INDENT> if isinstance(metric, str): <NEW_LINE> <INDENT> result_dict[metric] = collection[metric] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result_dict <NEW_LINE> <DEDENT> def del_collection(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.__collections[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def get_metric_by_uuid(self, metric_type: str, uuid: str): <NEW_LINE> <INDENT> collection = self.__collections.get(metric_type, None) <NEW_LINE> if collection: <NEW_LINE> <INDENT> return collection.get(uuid, None) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def get_metric_by_flavor(self, metric_type, flavor): <NEW_LINE> <INDENT> collection = self.__collections.get(metric_type, None) <NEW_LINE> if collection: <NEW_LINE> <INDENT> return collection.get(flavor, None) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def remove_metric_by_uuid(self, metric_type, uuid): <NEW_LINE> <INDENT> collection = self.__collections.get(metric_type, None) <NEW_LINE> if collection: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> metric = collection[uuid] <NEW_LINE> try: <NEW_LINE> <INDENT> del collection[metric.flavor] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> del collection[uuid] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def remove_metric_by_flavor(self, metric_type, flavor): <NEW_LINE> <INDENT> collection = self.__collections.get(metric_type, None) <NEW_LINE> if collection: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> metric = collection[flavor] <NEW_LINE> del collection[metric.metric_uuid] <NEW_LINE> del collection[flavor] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def remove_metrics_for_source(self, metric_type, source_name): <NEW_LINE> <INDENT> collection = self.__collections.get(metric_type, None) <NEW_LINE> if collection: <NEW_LINE> <INDENT> uuid_keys = [k for k, v in collection.items() if v.source.lower() == source_name.lower()] <NEW_LINE> for uuid in uuid_keys: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del collection[uuid] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.__collections.clear() | This class represents a Singleton that collects all Metrics instances of different types that had been created | 62598faf5fdd1c0f98e5dfa0 |
class MoveRUMarker(ModelSQL, ModelView): <NEW_LINE> <INDENT> _name = "ekd.account.move.marker" <NEW_LINE> _description=__doc__ <NEW_LINE> company = fields.Many2One('company.company', 'Company', required=True, readonly=True, ondelete="RESTRICT") <NEW_LINE> name = fields.Char('Name', size=None) <NEW_LINE> note = fields.Text('Note') <NEW_LINE> active = fields.Boolean('Active') <NEW_LINE> def default_company(self): <NEW_LINE> <INDENT> return Transaction().context.get('company') or False <NEW_LINE> <DEDENT> def default_active(self): <NEW_LINE> <INDENT> return True | Marker for entries | 62598fafbf627c535bcb14b4 |
class UserMessage(messages.Message): <NEW_LINE> <INDENT> message = messages.StringField(1, required=True) | Outbound: user notification | 62598faf236d856c2adc9448 |
class Subsample(object): <NEW_LINE> <INDENT> sub_sampling_type = 'other' <NEW_LINE> def __init__(self, name, num_models, model_group=None, file=None): <NEW_LINE> <INDENT> self.name, self.num_models = name, num_models <NEW_LINE> self.model_group, self.file = model_group, file <NEW_LINE> <DEDENT> num_models_deposited = property( lambda self: len(self.model_group) if self.model_group else 0, doc="Number of models in this subsample that are in the mmCIF file") | Base class for a subsample within an ensemble.
In some cases the models that make up an :class:`Ensemble` may be
partitioned into subsamples, for example to determine if the
sampling was exhaustive
(see `Viswanath et al. 2017 <https://www.ncbi.nlm.nih.gov/pmc/articles/pmid/29211988/>`_).
This base class can be used to describe the set of models in the
subsample, for example by pointing to an externally-deposited
set of conformations.
Usually a derived class (:class:`RandomSubsample` or
:class:`IndependentSubsample`) is used instead of this class.
Instances are stored in :attr:`Ensemble.subsamples`. All of the
subsamples in a given ensemble must be of the same type.
:param str name: A descriptive name for this sample
:param int num_models: The total number of models in this sample
:param model_group: The set of models in this sample, if applicable.
:type model_group: :class:`ModelGroup`
:param file: A reference to an external file containing coordinates
for the entire sample, for example as a DCD file
(see :class:`DCDWriter`).
:type file: :class:`ihm.location.OutputFileLocation` | 62598faf4527f215b58e9eeb |
class rfid_tag_decoder_f_sptr(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _rfid_swig.new_rfid_tag_decoder_f_sptr(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> def __deref__(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr___deref__(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _rfid_swig.delete_rfid_tag_decoder_f_sptr <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def set_ctrl_out(self, *args, **kwargs): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_set_ctrl_out(self, *args, **kwargs) <NEW_LINE> <DEDENT> def history(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_history(self) <NEW_LINE> <DEDENT> def output_multiple(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_output_multiple(self) <NEW_LINE> <DEDENT> def relative_rate(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_relative_rate(self) <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_start(self) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_stop(self) <NEW_LINE> <DEDENT> def nitems_read(self, *args, **kwargs): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_nitems_read(self, *args, **kwargs) <NEW_LINE> <DEDENT> def nitems_written(self, *args, **kwargs): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_nitems_written(self, *args, **kwargs) <NEW_LINE> <DEDENT> def detail(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_detail(self) <NEW_LINE> <DEDENT> def set_detail(self, *args, **kwargs): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_set_detail(self, *args, **kwargs) <NEW_LINE> <DEDENT> def name(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_name(self) <NEW_LINE> <DEDENT> def input_signature(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_input_signature(self) <NEW_LINE> <DEDENT> def output_signature(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_output_signature(self) <NEW_LINE> <DEDENT> def unique_id(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_unique_id(self) <NEW_LINE> <DEDENT> def to_basic_block(self): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_to_basic_block(self) <NEW_LINE> <DEDENT> def check_topology(self, *args, **kwargs): <NEW_LINE> <INDENT> return _rfid_swig.rfid_tag_decoder_f_sptr_check_topology(self, *args, **kwargs) | Proxy of C++ boost::shared_ptr<(rfid_tag_decoder_f)> class | 62598faf097d151d1a2c1040 |
class IfConfig: <NEW_LINE> <INDENT> def __init__(self, stdout=None, debug=False): <NEW_LINE> <INDENT> if stdout is not None: <NEW_LINE> <INDENT> self.stdout = stdout <NEW_LINE> self.stderr = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env = os.environ.copy() <NEW_LINE> env.update(LANG='C.utf8') <NEW_LINE> p = Popen('ifconfig', stdout=PIPE, stderr=PIPE, env=env, universal_newlines=True) <NEW_LINE> self.stdout, self.stderr = p.communicate() <NEW_LINE> if self.stderr != '': <NEW_LINE> <INDENT> raise ValueError( 'stderr from ifconfig was nonempty:\n%s' % self.stderr) <NEW_LINE> <DEDENT> <DEDENT> if 0: <NEW_LINE> <INDENT> print('self.stdout: %r' % self.stdout) <NEW_LINE> <DEDENT> self.devices = [] <NEW_LINE> curdev = None <NEW_LINE> for line in self.stdout.splitlines(): <NEW_LINE> <INDENT> if 0: <NEW_LINE> <INDENT> print('line: %r' % line) <NEW_LINE> <DEDENT> if line == '': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> m = re.match(r'(\w+): (.+)', line) <NEW_LINE> mo = re.match(r'(\w+)\s+(.+)', line) <NEW_LINE> if m: <NEW_LINE> <INDENT> self.oldFormat = False <NEW_LINE> devname = m.group(1) <NEW_LINE> curdev = Device(devname, debug) <NEW_LINE> self.devices.append(curdev) <NEW_LINE> curdev._parse_rest_of_first_line(m.group(2)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if mo: <NEW_LINE> <INDENT> self.oldFormat = True <NEW_LINE> devname = mo.group(1) <NEW_LINE> curdev = Device(devname, debug) <NEW_LINE> self.devices.append(curdev) <NEW_LINE> curdev._parse_rest_of_first_line_old(mo.group(2)) <NEW_LINE> continue <NEW_LINE> <DEDENT> if curdev is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if self.oldFormat: <NEW_LINE> <INDENT> curdev._parse_line_old(line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> curdev._parse_line(line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_device_by_name(self, devname): <NEW_LINE> <INDENT> for dev in self.devices: <NEW_LINE> <INDENT> if dev.name == devname: <NEW_LINE> <INDENT> return dev <NEW_LINE> <DEDENT> <DEDENT> raise ValueError('device not found: %r' % devname) | Wrapper around a single invocation of "ifconfig" | 62598fafe1aae11d1e7ce82e |
class Guest(db.Model, UserMixin): <NEW_LINE> <INDENT> __tablename__ = 'guests' <NEW_LINE> number = db.Column(db.Integer,primary_key=True) <NEW_LINE> name = db.Column(db.String) <NEW_LINE> availability = db.Column(db.Boolean) <NEW_LINE> rooms = relationship("Room",back_populates="guests") <NEW_LINE> def get_id(self): <NEW_LINE> <INDENT> return self.number | room details. | 62598faf5166f23b2e2433ef |
class IotHubQuotaMetricInfoListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[IotHubQuotaMetricInfo]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["IotHubQuotaMetricInfo"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(IotHubQuotaMetricInfoListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | The JSON-serialized array of IotHubQuotaMetricInfo objects with a next link.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: The array of quota metrics objects.
:vartype value: list[~azure.mgmt.iothub.v2021_03_31.models.IotHubQuotaMetricInfo]
:ivar next_link: The next link.
:vartype next_link: str | 62598fafbe8e80087fbbf07a |
@pytest.mark.usefixtures('class_devices') <NEW_LINE> class DeviceCreateTest(BaseDefaultTest): <NEW_LINE> <INDENT> def test_create_device_with_existent_project(self): <NEW_LINE> <INDENT> to_send = self.serialized_device <NEW_LINE> to_send.update({'name': self.random_string()}) <NEW_LINE> to_send.update(project=self.project.project_id) <NEW_LINE> response = self.client.post( reverse('devices:list-create-devices'), **self.auth_user_headers, data=to_send ) <NEW_LINE> self.assertEqual(response.status_code, 201) <NEW_LINE> res = response.json() <NEW_LINE> for field, value in res.items(): <NEW_LINE> <INDENT> sent_value = to_send.get(field) <NEW_LINE> if sent_value: <NEW_LINE> <INDENT> self.assertEqual(value, str(sent_value)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_create_device_without_project(self): <NEW_LINE> <INDENT> to_send = self.serialized_device <NEW_LINE> to_send.update({'name': self.random_string()}) <NEW_LINE> response = self.client.post( reverse('devices:list-create-devices'), **self.auth_user_headers, data=to_send ) <NEW_LINE> self.assertEqual(response.status_code, 400) | Testing POST 'devices:list-create-devices' | 62598faf63b5f9789fe8517d |
class VotingClassifier(object): <NEW_LINE> <INDENT> def __init__(self, estimators, voting='hard'): <NEW_LINE> <INDENT> self.estimators = estimators <NEW_LINE> if voting == 'hard' or voting == 'soft': <NEW_LINE> <INDENT> self.voting = voting <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError('Invalid \'voting\' argument, \'hard\' and \'soft\' voting available.') <NEW_LINE> <DEDENT> <DEDENT> def fit(self, X, y): <NEW_LINE> <INDENT> for estimator in self.estimators: <NEW_LINE> <INDENT> estimator.fit(X,y) <NEW_LINE> <DEDENT> <DEDENT> def predict(self,X): <NEW_LINE> <INDENT> if self.voting == 'soft': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> preds = [estimator.predict_proba(X) for estimator in self.estimators] <NEW_LINE> preds = sum(preds) <NEW_LINE> return np.argmax(preds) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> print('The list of specified estimators does not support soft voting, set voting to \'hard\' to resolve.') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> preds = [estimator.predict(X) for estimator in self.estimators] <NEW_LINE> preds = np.bincount(preds) <NEW_LINE> return np.argmax(preds) | A VotingClassifier is an ensemble model that aggregates the predictions of
multiple base models and makes a final prediction based on either hard or
soft voting.
Args:
estimators (list): A list storing the base estimators of the ensemble.
voting (str): The voting method to be used.
Attributes:
estimators (list): A list storing the base estimators of the ensemble.
voting (str): The voting method used. | 62598faf7d847024c075c3d9 |
class TimeDictionaryError(Exception): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.message = ('No se ha introducido un diccionario válido.') <NEW_LINE> Exception.__init__(self, self.message) | Error que se produce cuando no se define un diccionario temporal en el
programa principal.
Atributos
---------
message : string
Mensaje de error. | 62598fafa8370b77170f03f1 |
class AesTokenEncryptionTests(FantasticoUnitTestsCase): <NEW_LINE> <INDENT> _aes_iv = None <NEW_LINE> def init(self): <NEW_LINE> <INDENT> self._aes_iv = Random.new().read(AES.block_size) <NEW_LINE> <DEDENT> def test_aes_ok(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> for key_length in [16, 24, 32]: <NEW_LINE> <INDENT> token_key = Random.new().read(key_length) <NEW_LINE> token = Token({"client_id": "test client", "attr1": "test"}) <NEW_LINE> token_encrypted = aes_provider.encrypt_token(token, self._aes_iv, token_key) <NEW_LINE> token_decrypted = aes_provider.decrypt_token(token_encrypted, self._aes_iv, token_key) <NEW_LINE> self.assertIsNotNone(token_decrypted) <NEW_LINE> self.assertEqual(token.client_id, token_decrypted.client_id) <NEW_LINE> self.assertEqual(token.attr1, token_decrypted.attr1) <NEW_LINE> <DEDENT> <DEDENT> def test_aes_encrypt_notoken(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> with self.assertRaises(OAuth2InvalidTokenDescriptorError) as ctx: <NEW_LINE> <INDENT> aes_provider.encrypt_token(None, None, None) <NEW_LINE> <DEDENT> self.assertEqual("token", ctx.exception.attr_name) <NEW_LINE> <DEDENT> def test_aes_encrypt_notokeniv(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> with self.assertRaises(OAuth2InvalidTokenDescriptorError) as ctx: <NEW_LINE> <INDENT> aes_provider.encrypt_token(Token({}), None, None) <NEW_LINE> <DEDENT> self.assertEqual("token_iv", ctx.exception.attr_name) <NEW_LINE> <DEDENT> def test_aes_encrypt_notokenkey(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> with self.assertRaises(OAuth2InvalidTokenDescriptorError) as ctx: <NEW_LINE> <INDENT> aes_provider.encrypt_token(Token({}), "simple key", None) <NEW_LINE> <DEDENT> self.assertEqual("token_key", ctx.exception.attr_name) <NEW_LINE> <DEDENT> def test_aes_encrypt_unexpected_error(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> with self.assertRaises(OAuth2TokenEncryptionError): <NEW_LINE> <INDENT> aes_provider.encrypt_token(Token({}), "Simple IV", "Simple Key") <NEW_LINE> <DEDENT> <DEDENT> def test_aes_decrypt_notoken(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> with self.assertRaises(OAuth2InvalidTokenDescriptorError) as ctx: <NEW_LINE> <INDENT> aes_provider.decrypt_token(None, None, None) <NEW_LINE> <DEDENT> self.assertEqual("encrypted_str", ctx.exception.attr_name) <NEW_LINE> <DEDENT> def test_aes_descrypt_notokeniv(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> with self.assertRaises(OAuth2InvalidTokenDescriptorError) as ctx: <NEW_LINE> <INDENT> aes_provider.decrypt_token(Token({}), None, None) <NEW_LINE> <DEDENT> self.assertEqual("token_iv", ctx.exception.attr_name) <NEW_LINE> <DEDENT> def test_aes_decrypt_notokenkey(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> with self.assertRaises(OAuth2InvalidTokenDescriptorError) as ctx: <NEW_LINE> <INDENT> aes_provider.decrypt_token(Token({}), "simple key", None) <NEW_LINE> <DEDENT> self.assertEqual("token_key", ctx.exception.attr_name) <NEW_LINE> <DEDENT> def test_aes_decrypt_unexpected_error(self): <NEW_LINE> <INDENT> aes_provider = AesTokenEncryption() <NEW_LINE> with self.assertRaises(OAuth2TokenEncryptionError): <NEW_LINE> <INDENT> aes_provider.decrypt_token(Token({}), "Simple IV", "Simple Key") | This class provides tests suite for AES token encryption provider from fantastico. | 62598faf6e29344779b00672 |
class TestCfgManager(base.TestCase): <NEW_LINE> <INDENT> @mock.patch( 'oslo_config.generator._get_raw_opts_loaders', _fake_opt_loader) <NEW_LINE> @mock.patch( 'oslo_config.cfg.open', _file_mock({ "svc.tpl": NAMESPACE_FILE_CONTENT, "svc1.conf": CONF_FILE1_CONTENT, "svc2.conf": CONF_FILE2_CONTENT})) <NEW_LINE> def test_init(self): <NEW_LINE> <INDENT> cfg_manager = agent.ConfigManager( 'host', {"svc": {"svc1.conf": "svc.tpl", "svc2.conf": "svc.tpl"}}) <NEW_LINE> self.assertEqual('host', cfg_manager.host) <NEW_LINE> self.assertEqual(2, len(cfg_manager.configs)) <NEW_LINE> self.assertEqual(2, len(cfg_manager.namespaces)) <NEW_LINE> self.assertEqual(1, len(cfg_manager.templates)) <NEW_LINE> for conf in six.itervalues(cfg_manager.configs): <NEW_LINE> <INDENT> self.assertIsInstance(conf, agent.Config) <NEW_LINE> <DEDENT> for nspc in six.itervalues(cfg_manager.namespaces): <NEW_LINE> <INDENT> self.assertIsInstance(nspc, agent.Namespace) <NEW_LINE> <DEDENT> for tpl in six.itervalues(cfg_manager.templates): <NEW_LINE> <INDENT> self.assertIsInstance(tpl, agent.Template) | Config manager tests | 62598fafa8370b77170f03f2 |
class IMDBProcessor(DataProcessor): <NEW_LINE> <INDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "mini_train.tsv")), "train") <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "mini_train.tsv")), "dev") <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> return ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] <NEW_LINE> <DEDENT> def _create_examples(self, lines, set_type): <NEW_LINE> <INDENT> examples = [] <NEW_LINE> for (i, line) in enumerate(lines): <NEW_LINE> <INDENT> if len(line) != 2: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> guid = "%s-%s" % (set_type, i) <NEW_LINE> text_a = tokenization.convert_to_unicode(line[1].strip()) <NEW_LINE> text_b = None <NEW_LINE> label = tokenization.convert_to_unicode(line[0].strip().lower()) <NEW_LINE> examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <NEW_LINE> <DEDENT> return examples | Processor for the MRPC data set (GLUE version). | 62598faf1b99ca400228f53b |
class TestCASSSingleObjectApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = cass_client.api.cass_single_object_api.CASSSingleObjectApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_competency(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_framework(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_relation(self): <NEW_LINE> <INDENT> pass | CASSSingleObjectApi unit test stubs | 62598fafaad79263cf42e7ea |
class Peer: <NEW_LINE> <INDENT> def __init__( self, hostname: str, valid: datetime, aes_key: bytes, aes_iv: bytes, throttling: Optional[int] = None, ): <NEW_LINE> <INDENT> self._hostname = hostname <NEW_LINE> self._valid = valid <NEW_LINE> self._throttling = throttling <NEW_LINE> self._multiplexer = None <NEW_LINE> self._crypto = CryptoTransport(aes_key, aes_iv) <NEW_LINE> <DEDENT> @property <NEW_LINE> def hostname(self) -> str: <NEW_LINE> <INDENT> return self._hostname <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_connected(self) -> bool: <NEW_LINE> <INDENT> if not self._multiplexer: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._multiplexer.is_connected <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_valid(self) -> bool: <NEW_LINE> <INDENT> return self._valid > datetime.utcnow() <NEW_LINE> <DEDENT> @property <NEW_LINE> def multiplexer(self) -> Optional[Multiplexer]: <NEW_LINE> <INDENT> return self._multiplexer <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_ready(self) -> bool: <NEW_LINE> <INDENT> if self.multiplexer is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self.multiplexer.is_connected: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> async def init_multiplexer_challenge( self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter ) -> None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> token = hashlib.sha256(os.urandom(40)).digest() <NEW_LINE> writer.write(self._crypto.encrypt(token)) <NEW_LINE> async with async_timeout.timeout(10): <NEW_LINE> <INDENT> await writer.drain() <NEW_LINE> data = await reader.readexactly(32) <NEW_LINE> <DEDENT> data = self._crypto.decrypt(data) <NEW_LINE> assert hashlib.sha256(token).digest() == data <NEW_LINE> <DEDENT> except ( asyncio.TimeoutError, asyncio.IncompleteReadError, MultiplexerTransportDecrypt, AssertionError, OSError, ) as err: <NEW_LINE> <INDENT> _LOGGER.warning("Wrong challenge from peer") <NEW_LINE> raise SniTunChallengeError() from err <NEW_LINE> <DEDENT> self._multiplexer = Multiplexer( self._crypto, reader, writer, throttling=self._throttling ) <NEW_LINE> <DEDENT> def wait_disconnect(self) -> Coroutine: <NEW_LINE> <INDENT> if not self._multiplexer: <NEW_LINE> <INDENT> raise RuntimeError("No Transport initialize for peer") <NEW_LINE> <DEDENT> return self._multiplexer.wait() | Representation of a Peer. | 62598faf3539df3088ecc2c9 |
class IntervalWindowCoder(FastCoder): <NEW_LINE> <INDENT> def _create_impl(self): <NEW_LINE> <INDENT> return coder_impl.IntervalWindowCoderImpl() <NEW_LINE> <DEDENT> def is_deterministic(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def as_cloud_object(self, coders_context=None): <NEW_LINE> <INDENT> return { '@type': 'kind:interval_window', } <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return type(self) == type(other) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(type(self)) | Coder for an window defined by a start timestamp and a duration. | 62598faf26068e7796d4c96c |
class Group(UUIDModel): <NEW_LINE> <INDENT> manager: 'models.ForeignKey[Group, Authenticator]' = UnsavedForeignKey( Authenticator, on_delete=models.CASCADE, related_name='groups' ) <NEW_LINE> name = models.CharField(max_length=128, db_index=True) <NEW_LINE> state = models.CharField(max_length=1, default=State.ACTIVE, db_index=True) <NEW_LINE> comments = models.CharField(max_length=256, default='') <NEW_LINE> users = models.ManyToManyField(User, related_name='groups') <NEW_LINE> is_meta = models.BooleanField(default=False, db_index=True) <NEW_LINE> meta_if_any = models.BooleanField(default=False) <NEW_LINE> groups = models.ManyToManyField('self', symmetrical=False) <NEW_LINE> created = models.DateTimeField(default=getSqlDatetime, blank=True) <NEW_LINE> objects: 'models.BaseManager[Group]' <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('name',) <NEW_LINE> app_label = 'uds' <NEW_LINE> constraints = [ models.UniqueConstraint( fields=['manager', 'name'], name='u_grp_manager_name' ) ] <NEW_LINE> <DEDENT> @property <NEW_LINE> def pretty_name(self) -> str: <NEW_LINE> <INDENT> return self.name + '@' + self.manager.name <NEW_LINE> <DEDENT> def getManager(self) -> 'auths.Authenticator': <NEW_LINE> <INDENT> return self.manager.getInstance() <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> if self.is_meta: <NEW_LINE> <INDENT> return "Meta group {}(id:{}) with groups {}".format( self.name, self.id, list(self.groups.all()) ) <NEW_LINE> <DEDENT> return "Group {}(id:{}) from auth {}".format( self.name, self.id, self.manager.name ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def beforeDelete(sender, **kwargs) -> None: <NEW_LINE> <INDENT> toDelete = kwargs['instance'] <NEW_LINE> toDelete.getManager().removeGroup(toDelete.name) <NEW_LINE> log.clearLogs(toDelete) <NEW_LINE> logger.debug('Deleted group %s', toDelete) | This class represents a group, associated with one authenticator | 62598faf627d3e7fe0e06ec4 |
class AboutAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> exclude = ('user',) <NEW_LINE> def save_model(self, request, obj, form, change): <NEW_LINE> <INDENT> if not change: <NEW_LINE> <INDENT> obj.user = request.user <NEW_LINE> <DEDENT> obj.save() | fieldsets = (
('Photo',{'fields':('main_photo',)}),
('What We Do',{'fields':('what_we_do',)}),
('Who We Are',{'fields':('who_we_are',)}),
('How It Works',{'fields':('how_it_works')}),
) | 62598faf44b2445a339b697c |
class Survey(models.Model): <NEW_LINE> <INDENT> event = models.ForeignKey('core.Event', on_delete=models.CASCADE) <NEW_LINE> slug = models.CharField(**NONUNIQUE_SLUG_FIELD_PARAMS) <NEW_LINE> title = models.CharField( max_length=255, verbose_name=_('Title'), help_text=_('Will be displayed at the top of the survey page.'), ) <NEW_LINE> description = models.TextField( verbose_name=_('Description'), help_text=_('Will be displayed at the top of the survey page.'), ) <NEW_LINE> active_from = models.DateTimeField( null=True, blank=True, verbose_name=_('Active from'), ) <NEW_LINE> active_until = models.DateTimeField( null=True, blank=True, verbose_name=_('Active until'), ) <NEW_LINE> form_class_path = models.CharField( max_length=255, verbose_name=_('Form path'), help_text=_('A reference to the form that is used as the survey form.'), ) <NEW_LINE> form_class = code_property('form_class_path') <NEW_LINE> override_does_not_apply_message = models.TextField( default='', verbose_name=_('Message when denied access'), help_text=_( "This message will be shown to the user when they attempt to access a query they don't" "have access to." ), ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_active(self): <NEW_LINE> <INDENT> return is_within_period(self.active_from, self.active_until) <NEW_LINE> <DEDENT> @property <NEW_LINE> def does_not_apply_message(self): <NEW_LINE> <INDENT> if self.override_does_not_apply_message: <NEW_LINE> <INDENT> return self.override_does_not_apply_message <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _('This survey does not apply to you.') <NEW_LINE> <DEDENT> <DEDENT> def admin_is_active(self): <NEW_LINE> <INDENT> return self.is_active <NEW_LINE> <DEDENT> admin_is_active.short_description = _('Active') <NEW_LINE> admin_is_active.boolean = True <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('Survey') <NEW_LINE> verbose_name_plural = _('Surveys') <NEW_LINE> unique_together = [ ('event', 'slug'), ] | The Labour Manager may have their Workers fill in a Survey some time after signing up.
The driving use case for these Surveys is to ask for shift wishes some time before the event.
A Survey requires a Model and a Form. The Model is requested to return an instance via
Model.for_signup(signup) and it is passed to the Form via
initialize_form(Form, request, instance=instance, event=event). | 62598faf4527f215b58e9eed |
class greenhouse_gas_emissions_from_vehicle_travel(Variable): <NEW_LINE> <INDENT> _return_type = "float32" <NEW_LINE> def dependencies(self): <NEW_LINE> <INDENT> return ["psrc.zone.vehicle_miles_traveled"] <NEW_LINE> <DEDENT> def compute(self, dataset_pool): <NEW_LINE> <INDENT> co2_pounds_per_vehicle_mile = .916 <NEW_LINE> vmt = self.get_dataset().get_attribute("vehicle_miles_traveled") <NEW_LINE> return co2_pounds_per_vehicle_mile * vmt | Calculate the total greenhouse gas emissions for a year. | 62598faf3317a56b869be556 |
class DummyFactory(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.callbacks = {} <NEW_LINE> <DEDENT> def addBootstrap(self, event, callback): <NEW_LINE> <INDENT> self.callbacks[event] = callback | Dummy XmlStream factory that only registers bootstrap observers. | 62598faf76e4537e8c3ef5c4 |
class ClusteringProblem: <NEW_LINE> <INDENT> def __init__(self, cities, facilities, metric, facility_cost): <NEW_LINE> <INDENT> self.facilities = facilities <NEW_LINE> self.cities = cities <NEW_LINE> self._metric = metric <NEW_LINE> self._facility_cost = facility_cost <NEW_LINE> <DEDENT> def ScoreCityAssignment(self, city, facility): <NEW_LINE> <INDENT> return self._metric.distance(city, facility) <NEW_LINE> <DEDENT> def ScoreOpenFacility(self, facility): <NEW_LINE> <INDENT> return self._facility_cost[facility.id] | A clustering problem consists of cities, facilities to connect to a
metric cost structure for connection and costs for opening
facilities. | 62598faf5fcc89381b266158 |
class Slot(Builtin): <NEW_LINE> <INDENT> attributes = ("NHoldAll",) <NEW_LINE> rules = { "Slot[]": "Slot[1]", "MakeBoxes[Slot[n_Integer?NonNegative]," " f:StandardForm|TraditionalForm|InputForm|OutputForm]": ( '"#" <> ToString[n]' ), } | <dl>
<dt>'#$n$'
<dd>represents the $n$th argument to a pure function.
<dt>'#'
<dd>is short-hand for '#1'.
<dt>'#0'
<dd>represents the pure function itself.
</dl>
X> #
= #1
Unused arguments are simply ignored:
>> {#1, #2, #3}&[1, 2, 3, 4, 5]
= {1, 2, 3}
Recursive pure functions can be written using '#0':
>> If[#1<=1, 1, #1 #0[#1-1]]& [10]
= 3628800
#> # // InputForm
= #1
#> #0 // InputForm
= #0 | 62598fafd7e4931a7ef3c0ad |
class SocialLink(Model): <NEW_LINE> <INDENT> site = models.CharField( max_length=7, choices=social_links.SOCIAL_SITES, ) <NEW_LINE> url = models.URLField( max_length=255, verbose_name='URL', ) <NEW_LINE> @property <NEW_LINE> def site_name(self): <NEW_LINE> <INDENT> return self.get_site_display() <NEW_LINE> <DEDENT> @property <NEW_LINE> def site_logo(self): <NEW_LINE> <INDENT> return social_links.SOCIAL_SITE_ICONS[self.site] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> site = self.site_name <NEW_LINE> url = self.url <NEW_LINE> return f'{site}: {url}' | This model holds information about one social media link | 62598faf4428ac0f6e65853d |
class ActivityRightsDict(TypedDict): <NEW_LINE> <INDENT> cloned_from: Optional[str] <NEW_LINE> status: str <NEW_LINE> community_owned: bool <NEW_LINE> owner_names: List[str] <NEW_LINE> editor_names: List[str] <NEW_LINE> voice_artist_names: List[str] <NEW_LINE> viewer_names: List[str] <NEW_LINE> viewable_if_private: bool | A dict version of ActivityRights suitable for use by the frontend. | 62598faf097d151d1a2c1042 |
class BookForm(FlaskForm): <NEW_LINE> <INDENT> title = StringField("Title:", validators=[DataRequired(), Length(min=1)]) <NEW_LINE> author_fname = StringField("Author First Name", validators=[DataRequired(), Length(min=1)]) <NEW_LINE> author_lname = StringField("Author Surname", validators=[DataRequired(), Length(min=1)]) <NEW_LINE> category_id = StringField("Category") <NEW_LINE> cover_url = StringField("Cover Link", validators=[DataRequired(), Length(min=2)]) | Form to capture and validate new book to add as well as update book info
up_votes and down_votes and date_added are set within the add_book function | 62598fafd486a94d0ba2bfe7 |
class PluginHelpMixin(HasTraits): <NEW_LINE> <INDENT> _cached_help = HTML <NEW_LINE> def get_help(self): <NEW_LINE> <INDENT> if self._cached_help == "": <NEW_LINE> <INDENT> class_path = pathlib.PurePath(inspect.getfile(self.__class__)) <NEW_LINE> help_file = class_path.parents[1] / 'help' / 'views' / (class_path.stem + '.html') <NEW_LINE> with open(help_file, encoding = 'utf-8') as f: <NEW_LINE> <INDENT> self._cached_help = f.read() <NEW_LINE> <DEDENT> <DEDENT> return self._cached_help | A mixin to get online HTML help for a class. It determines the HTML
path name from the class name. | 62598faf3539df3088ecc2ca |
class UserAPI(APIBase): <NEW_LINE> <INDENT> __class__ = User <NEW_LINE> public_attributes = ('locale', 'name') <NEW_LINE> allowed_attributes = ('name', 'locale', 'fullname', 'created') <NEW_LINE> def _select_attributes(self, user_data): <NEW_LINE> <INDENT> if current_user.is_authenticated() and current_user.admin: <NEW_LINE> <INDENT> tmp = User().to_public_json(user_data) <NEW_LINE> tmp['id'] = user_data['id'] <NEW_LINE> tmp['email_addr'] = user_data['email_addr'] <NEW_LINE> return tmp <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> privacy = self._is_user_private(user_data) <NEW_LINE> for attribute in user_data.keys(): <NEW_LINE> <INDENT> self._remove_attribute_if_private(attribute, user_data, privacy) <NEW_LINE> <DEDENT> return user_data <NEW_LINE> <DEDENT> <DEDENT> def _remove_attribute_if_private(self, attribute, user_data, privacy): <NEW_LINE> <INDENT> if self._is_attribute_private(attribute, privacy): <NEW_LINE> <INDENT> del user_data[attribute] <NEW_LINE> <DEDENT> <DEDENT> def _is_attribute_private(self, attribute, privacy): <NEW_LINE> <INDENT> return (attribute not in self.allowed_attributes or privacy and attribute not in self.public_attributes) <NEW_LINE> <DEDENT> def _is_user_private(self, user): <NEW_LINE> <INDENT> return not self._is_requester_admin() and user['privacy_mode'] <NEW_LINE> <DEDENT> def _is_requester_admin(self): <NEW_LINE> <INDENT> return current_user.is_authenticated() and current_user.admin <NEW_LINE> <DEDENT> def _custom_filter(self, filters): <NEW_LINE> <INDENT> if self._private_attributes_in_request() and not self._is_requester_admin(): <NEW_LINE> <INDENT> filters['privacy_mode'] = False <NEW_LINE> <DEDENT> return filters <NEW_LINE> <DEDENT> def _private_attributes_in_request(self): <NEW_LINE> <INDENT> for attribute in request.args.keys(): <NEW_LINE> <INDENT> if (attribute in self.allowed_attributes and attribute not in self.public_attributes): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @jsonpify <NEW_LINE> @ratelimit(limit=ratelimits.get('LIMIT'), per=ratelimits.get('PER')) <NEW_LINE> def post(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> raise MethodNotAllowed <NEW_LINE> <DEDENT> except MethodNotAllowed as e: <NEW_LINE> <INDENT> return error.format_exception( e, target=self.__class__.__name__.lower(), action='POST') <NEW_LINE> <DEDENT> <DEDENT> @jsonpify <NEW_LINE> @ratelimit(limit=ratelimits.get('LIMIT'), per=ratelimits.get('PER')) <NEW_LINE> def delete(self, oid=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> raise MethodNotAllowed <NEW_LINE> <DEDENT> except MethodNotAllowed as e: <NEW_LINE> <INDENT> return error.format_exception( e, target=self.__class__.__name__.lower(), action='DEL') | Class for the domain object User. | 62598fafdd821e528d6d8f4c |
class CustomBatchNormManualModule(nn.Module): <NEW_LINE> <INDENT> def __init__(self, n_neurons, eps=1e-5): <NEW_LINE> <INDENT> super(CustomBatchNormManualModule, self).__init__() <NEW_LINE> raise NotImplementedError <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> return out | This nn.module implements a custom version of the batch norm operation for MLPs.
In self.forward the functional version CustomBatchNormManualFunction.forward is called.
The automatic differentiation of PyTorch calls the backward method of this function in the backward pass. | 62598faf7d847024c075c3da |
@dataclass <NEW_LINE> class Clf: <NEW_LINE> <INDENT> model: Union[BaseEstimator, Lstm] <NEW_LINE> name: str <NEW_LINE> def __post_init__(self) -> None: <NEW_LINE> <INDENT> self.preds = [] <NEW_LINE> self.probs = [] <NEW_LINE> <DEDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def set_fit(self, X, Y): <NEW_LINE> <INDENT> print(f"Training {self.name} .....") <NEW_LINE> self.model = self.model.fit(X, Y) <NEW_LINE> return self <NEW_LINE> <DEDENT> def set_preds(self, X: List[List[Union[int, float]]]) -> List[List[int]]: <NEW_LINE> <INDENT> self.preds = self.model.predict(X) <NEW_LINE> return self.preds <NEW_LINE> <DEDENT> def set_probs(self, X: List[List[Union[int, float]]]) -> List[List[float]]: <NEW_LINE> <INDENT> self.probs = self.model.predict_proba(X) <NEW_LINE> return self <NEW_LINE> <DEDENT> def save(self, loc: str) -> str: <NEW_LINE> <INDENT> if isinstance(self.model, Lstm): <NEW_LINE> <INDENT> fn = str(self) + ".pt" <NEW_LINE> fp = os.path.join(loc, fn) <NEW_LINE> torch.save(self.model.state_dict(), fp) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fn = str(self) + ".sk" <NEW_LINE> fp = os.path.join(loc, fn) <NEW_LINE> dump(self.model, fp) <NEW_LINE> <DEDENT> return fp | A wrapper for classifiers allowing for abstract usage in evaluation. | 62598fafbd1bec0571e150ce |
class Solution(object): <NEW_LINE> <INDENT> def minCameraCover(self, root): <NEW_LINE> <INDENT> sums = 0 <NEW_LINE> def dfs(root): <NEW_LINE> <INDENT> nonlocal sums <NEW_LINE> if not root: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> left = dfs(root.left) <NEW_LINE> right = dfs(root.right) <NEW_LINE> print(left, right) <NEW_LINE> if left == 0 or right == 0: <NEW_LINE> <INDENT> sums = sums + 1 <NEW_LINE> return 2 <NEW_LINE> <DEDENT> elif left == 2 or right == 2: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> if dfs(root) == 0: <NEW_LINE> <INDENT> sums = sums + 1 <NEW_LINE> <DEDENT> return sums | 读了很多次,真的不知道知道题啥意思,我的火爆脾气呀
明白了其输入的含义,读着题,感觉很难呀
去搜了一下题解,根据贪心法来解决这道问题
和我昨天做的一个左叶子之和有异曲同工之妙
感觉这道题有点找拐点的意思,有一个0就添加一个相机 | 62598fafa8370b77170f03f3 |
class UserForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ( 'first_name', 'last_name', ) <NEW_LINE> labels = { 'first_name':'First Name', 'last_name':'Surname', } | User form for getting user fields for Profile | 62598faf7c178a314d78d4b4 |
class LXD(Plugin, UbuntuPlugin): <NEW_LINE> <INDENT> plugin_name = 'lxd' <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> self.add_copy_spec([ "/var/lib/lxd/lxd.db", "/etc/default/lxc-bridge", ]) <NEW_LINE> self.add_copy_spec_limit("/var/log/lxd*", sizelimit=self.get_option("log_size")) <NEW_LINE> self.add_cmd_output([ "lxc list", "lxc profile list", "lxc image list", ]) <NEW_LINE> self.add_cmd_output([ "find /var/lib/lxd -maxdepth 2 -type d -ls", ], suggest_filename='var-lxd-dirs.txt') | LXD is a containers hypervisor.
| 62598faf851cf427c66b82d4 |
class OptionsManager2ConfigurationAdapter(object): <NEW_LINE> <INDENT> def __init__(self, provider): <NEW_LINE> <INDENT> self.config = provider <NEW_LINE> <DEDENT> def __getattr__(self, key): <NEW_LINE> <INDENT> return getattr(self.config, key) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> provider = self.config._all_options[key] <NEW_LINE> try: <NEW_LINE> <INDENT> return getattr(provider.config, provider.option_name(key)) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise KeyError(key) <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.config.global_set_option(self.config.option_name(key), value) <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> provider = self.config._all_options[key] <NEW_LINE> try: <NEW_LINE> <INDENT> return getattr(provider.config, provider.option_name(key)) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return default | Adapt an option manager to behave like a
`logilab.common.configuration.Configuration` instance | 62598faf6e29344779b00674 |
class ThirstingBlade(Invocation): <NEW_LINE> <INDENT> name = "Thirsting Blade" | You can attack with your pact weapon twice, instead of once, whenever you
take the Attack action on your turn.
**Prerequisite**: 5th Level, Pact of the Blade | 62598fafe5267d203ee6b921 |
class PreprocessorBase(ParamsBaseClass): <NEW_LINE> <INDENT> def __init__(self, params = [], **kwargs): <NEW_LINE> <INDENT> paramsThis = [Param("enabled", True, friendlyName = "Enabled")] <NEW_LINE> ParamsBaseClass.__init__(self, paramsThis + params, **kwargs) <NEW_LINE> <DEDENT> def OptimizeForSeries(self, fseries): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Apply(self, frame): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Baseclass for all preprocessors.
Params:
enabled (bool): is the preprocessor enabled | 62598faf23849d37ff8510cc |
class SRIAgent(Verifier, Issuer): <NEW_LINE> <INDENT> async def process_post(self, form: dict) -> str: <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> logger.debug('SRIAgent.process_post: >>> form: {}'.format(form)) <NEW_LINE> mro = SRIAgent._mro_dispatch() <NEW_LINE> for ResponderClass in mro: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rv = await ResponderClass.process_post(self, form) <NEW_LINE> logger.debug('SRIAgent.process_post: <<< {}'.format(rv)) <NEW_LINE> return rv <NEW_LINE> <DEDENT> except TokenType: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> logger.debug('SRIAgent.process_post: <!< not this form type: {}'.format(form['type'])) <NEW_LINE> raise TokenType('{} does not support token type {}'.format(self.__class__.__name__, form['type'])) | SRI agent is:
* a Verifier for:
* BC Org Book proofs of BC Registrar
* PSPC Org Book proofs of its own SRI registration claims
* an Issuer of its own SRI registration claims | 62598faf7047854f4633f3f3 |
class Product(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=190, db_index=True) <NEW_LINE> slug = models.SlugField(max_length=190, db_index=True) <NEW_LINE> brand = models.CharField(max_length=50) <NEW_LINE> sku = models.CharField(max_length=50) <NEW_LINE> price = models.DecimalField(max_digits=9, decimal_places=2) <NEW_LINE> old_price = models.DecimalField( max_digits=9, decimal_places=2, blank=True, default=0.00) <NEW_LINE> image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) <NEW_LINE> image_caption = models.CharField(max_length=200) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_bestseller = models.BooleanField(default=False) <NEW_LINE> is_featured = models.BooleanField(default=False) <NEW_LINE> is_new = models.BooleanField(default=False) <NEW_LINE> available = models.BooleanField(default=True) <NEW_LINE> quantity = models.PositiveIntegerField() <NEW_LINE> description = models.TextField() <NEW_LINE> meta_description = models.CharField( max_length=255, help_text='Content for description meta tag') <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> categories = models.ManyToManyField(Category) <NEW_LINE> objects = models.Manager() <NEW_LINE> active = ActiveProductManager() <NEW_LINE> featured = FeaturedProductManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'products' <NEW_LINE> ordering = ('-created',) <NEW_LINE> index_together = (('id', 'slug'),) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('products:product_detail', args=[self.id, self.slug]) <NEW_LINE> <DEDENT> def sale_price(self): <NEW_LINE> <INDENT> if self.old_price > self.price: <NEW_LINE> <INDENT> return self.price <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | model class containing information about a product; instances of this class are what the user
adds to their shopping cart and can subsequently purchase | 62598faf63d6d428bbee27c4 |
class Movie(): <NEW_LINE> <INDENT> def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.storyline = movie_storyline <NEW_LINE> self.poster_image_url = poster_image <NEW_LINE> self.trailer_youtube_url = trailer_youtube | This class accepts four arguments for our movie page:
* Movie title
* Storyline
* Poster image
* Yourtube trailer | 62598faf0c0af96317c5639b |
class cmd_domain_dcpromo(Command): <NEW_LINE> <INDENT> synopsis = "%prog <dnsdomain> [DC|RODC] [options]" <NEW_LINE> takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions, "credopts": options.CredentialsOptions, } <NEW_LINE> takes_options = [] <NEW_LINE> takes_options.extend(common_join_options) <NEW_LINE> takes_options.extend(common_provision_join_options) <NEW_LINE> if samba.is_ntvfs_fileserver_built(): <NEW_LINE> <INDENT> takes_options.extend(common_ntvfs_options) <NEW_LINE> <DEDENT> takes_args = ["domain", "role?"] <NEW_LINE> def run(self, domain, role=None, sambaopts=None, credopts=None, versionopts=None, server=None, site=None, targetdir=None, domain_critical_only=False, parent_domain=None, machinepass=None, use_ntvfs=False, dns_backend=None, quiet=False, verbose=False, plaintext_secrets=False, backend_store=None): <NEW_LINE> <INDENT> lp = sambaopts.get_loadparm() <NEW_LINE> creds = credopts.get_credentials(lp) <NEW_LINE> net = Net(creds, lp, server=credopts.ipaddress) <NEW_LINE> logger = self.get_logger() <NEW_LINE> if verbose: <NEW_LINE> <INDENT> logger.setLevel(logging.DEBUG) <NEW_LINE> <DEDENT> elif quiet: <NEW_LINE> <INDENT> logger.setLevel(logging.WARNING) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.setLevel(logging.INFO) <NEW_LINE> <DEDENT> netbios_name = lp.get("netbios name") <NEW_LINE> if role is not None: <NEW_LINE> <INDENT> role = role.upper() <NEW_LINE> <DEDENT> if role == "DC": <NEW_LINE> <INDENT> join_DC(logger=logger, server=server, creds=creds, lp=lp, domain=domain, site=site, netbios_name=netbios_name, targetdir=targetdir, domain_critical_only=domain_critical_only, machinepass=machinepass, use_ntvfs=use_ntvfs, dns_backend=dns_backend, promote_existing=True, plaintext_secrets=plaintext_secrets, backend_store=backend_store) <NEW_LINE> <DEDENT> elif role == "RODC": <NEW_LINE> <INDENT> join_RODC(logger=logger, server=server, creds=creds, lp=lp, domain=domain, site=site, netbios_name=netbios_name, targetdir=targetdir, domain_critical_only=domain_critical_only, machinepass=machinepass, use_ntvfs=use_ntvfs, dns_backend=dns_backend, promote_existing=True, plaintext_secrets=plaintext_secrets, backend_store=backend_store) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise CommandError("Invalid role '%s' (possible values: DC, RODC)" % role) | Promote an existing domain member or NT4 PDC to an AD DC. | 62598faf2c8b7c6e89bd37de |
class V1MongoClusterConfigurationSpecMongoDB(BaseModel): <NEW_LINE> <INDENT> mongo_name = StringField(required=False) <NEW_LINE> storage_name = StringField(required=False) <NEW_LINE> storage_size = StringField(required=False) <NEW_LINE> storage_data_path = StringField(required=False) <NEW_LINE> storage_class_name = StringField(required=False) <NEW_LINE> cpu_limit = StringField(required=False) <NEW_LINE> cpu_request = StringField(required=False) <NEW_LINE> memory_limit = StringField(required=False) <NEW_LINE> memory_request = StringField(required=False) <NEW_LINE> replicas = MongoReplicaCountField(required=True) <NEW_LINE> wired_tiger_cache_size = StringField(required=False) | Model for the `spec.mongodb` field of the V1MongoClusterConfiguration. | 62598faf2ae34c7f260ab0fa |
class Model(Sized, Iterable, Container): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.item_added = Signal() <NEW_LINE> self.item_removed = Signal() <NEW_LINE> self.model_reset = Signal() <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def add(self, item): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def remove(self, item): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def reset(self): <NEW_LINE> <INDENT> pass | A model is a data container that provide signal to observe changes.
The base model do not provide a way to change directly the data,
this to remove useless restrictions to models that will store complex
objects where attribute changes but not objects directly.
Setter methods and signals can be simply implemented in subclass, where
needed.
A model should be as generic as possible in the way its store data, working
like a normal data structure, for more ui-oriented tasks a ModelAdapter
should be used.
__iter__ must provide an iterator over the items
__len__ must return the number of stored items
__contains__ must return True/False if the given item is in/not in the model | 62598faf99cbb53fe6830ef2 |
class Squamata(Reptilia): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.order_name = self.__class__.__name__ <NEW_LINE> super(Squamata, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def order_info(self): <NEW_LINE> <INDENT> pass | Creates a Squamata | 62598faff548e778e596b5be |
@add_metaclass(MetaInstructionCase) <NEW_LINE> class AdcImmWithDecimalTest(unittest.TestCase): <NEW_LINE> <INDENT> asm = 'ADC #10' <NEW_LINE> lex = [('T_INSTRUCTION', 'ADC'), ('T_DECIMAL_NUMBER', '#10')] <NEW_LINE> syn = ['S_IMMEDIATE'] <NEW_LINE> code = [0x69, 0x0A] | Test the arithmetic operation ADC between decimal 10
and the content of the accumulator. | 62598faf796e427e5384e7ae |
class StorageCenterApiHelper(object): <NEW_LINE> <INDENT> def __init__(self, config, active_backend_id, storage_protocol): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.active_backend_id = active_backend_id <NEW_LINE> self.ssn = self.config.dell_sc_ssn <NEW_LINE> self.storage_protocol = storage_protocol <NEW_LINE> self.apiversion = '2.0' <NEW_LINE> <DEDENT> def open_connection(self): <NEW_LINE> <INDENT> connection = None <NEW_LINE> LOG.info(_LI('open_connection to %(ssn)s at %(ip)s'), {'ssn': self.ssn, 'ip': self.config.san_ip}) <NEW_LINE> if self.ssn: <NEW_LINE> <INDENT> connection = StorageCenterApi(self.config.san_ip, self.config.dell_sc_api_port, self.config.san_login, self.config.san_password, self.config.dell_sc_verify_cert, self.apiversion) <NEW_LINE> connection.vfname = self.config.dell_sc_volume_folder <NEW_LINE> connection.sfname = self.config.dell_sc_server_folder <NEW_LINE> if self.storage_protocol == 'FC': <NEW_LINE> <INDENT> connection.protocol = 'FibreChannel' <NEW_LINE> <DEDENT> if self.active_backend_id: <NEW_LINE> <INDENT> connection.ssn = int(self.active_backend_id) <NEW_LINE> connection.failed_over = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> connection.ssn = self.ssn <NEW_LINE> connection.failed_over = False <NEW_LINE> <DEDENT> connection.open_connection() <NEW_LINE> if self.apiversion != connection.apiversion: <NEW_LINE> <INDENT> LOG.info(_LI('open_connection: Updating API version to %s'), connection.apiversion) <NEW_LINE> self.apiversion = connection.apiversion <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise exception.VolumeBackendAPIException( data=_('Configuration error: dell_sc_ssn not set.')) <NEW_LINE> <DEDENT> return connection | StorageCenterApiHelper
Helper class for API access. Handles opening and closing the
connection to the Dell REST API. | 62598fafbd1bec0571e150cf |
@implementer(IDomain) <NEW_LINE> class Domain(Model): <NEW_LINE> <INDENT> id = Int(primary=True) <NEW_LINE> mail_host = Unicode() <NEW_LINE> base_url = Unicode() <NEW_LINE> description = Unicode() <NEW_LINE> contact_address = Unicode() <NEW_LINE> def __init__(self, mail_host, description=None, base_url=None, contact_address=None): <NEW_LINE> <INDENT> self.mail_host = mail_host <NEW_LINE> self.base_url = (base_url if base_url is not None else 'http://' + mail_host) <NEW_LINE> self.description = description <NEW_LINE> self.contact_address = (contact_address if contact_address is not None else 'postmaster@' + mail_host) <NEW_LINE> <DEDENT> @property <NEW_LINE> def url_host(self): <NEW_LINE> <INDENT> return urlparse(self.base_url).netloc <NEW_LINE> <DEDENT> @property <NEW_LINE> def scheme(self): <NEW_LINE> <INDENT> return urlparse(self.base_url).scheme <NEW_LINE> <DEDENT> @property <NEW_LINE> @dbconnection <NEW_LINE> def mailing_lists(self, store): <NEW_LINE> <INDENT> mailing_lists = store.find( MailingList, MailingList.mail_host == self.mail_host) <NEW_LINE> for mlist in mailing_lists: <NEW_LINE> <INDENT> yield mlist <NEW_LINE> <DEDENT> <DEDENT> def confirm_url(self, token=''): <NEW_LINE> <INDENT> return urljoin(self.base_url, 'confirm/' + token) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.description is None: <NEW_LINE> <INDENT> return ('<Domain {0.mail_host}, base_url: {0.base_url}, ' 'contact_address: {0.contact_address}>').format(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ('<Domain {0.mail_host}, {0.description}, ' 'base_url: {0.base_url}, ' 'contact_address: {0.contact_address}>').format(self) | Domains. | 62598faf67a9b606de545fe7 |
class HyperParams(AttrDict): <NEW_LINE> <INDENT> def __init__(self, names=(), **conf): <NEW_LINE> <INDENT> super(HyperParams, self).__init__(*names) <NEW_LINE> self.conf = {} <NEW_LINE> for key, sett in conf.iteritems(): <NEW_LINE> <INDENT> self.conf[key] = dict((k, v) for k, v in sett.iteritems()) <NEW_LINE> <DEDENT> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> return dict((n, self[n].value) for n in self.names) <NEW_LINE> <DEDENT> def as_ordered_dict(self): <NEW_LINE> <INDENT> return OrderedDict((n, self[n].value) for n in self.names) <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return [self[n].value for n in self.names] <NEW_LINE> <DEDENT> def fill_conf(self): <NEW_LINE> <INDENT> self.conf = {} <NEW_LINE> for name in self.names: <NEW_LINE> <INDENT> self.conf[name] = dict((n, self[name].conf[n]) for n in self[name].conf.names) <NEW_LINE> <DEDENT> <DEDENT> def get_conf(self): <NEW_LINE> <INDENT> if not self.conf: <NEW_LINE> <INDENT> self.fill_conf() <NEW_LINE> <DEDENT> return self.conf <NEW_LINE> <DEDENT> def get_conf_ordered(self): <NEW_LINE> <INDENT> conf = OrderedDict() <NEW_LINE> for name in self.names: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conf[name] = OrderedDict((n, self[name].conf[n]) for n in self[name].conf.names) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> conf[name] = self.conf[name] <NEW_LINE> <DEDENT> <DEDENT> return conf <NEW_LINE> <DEDENT> def get_init_values(self, index): <NEW_LINE> <INDENT> return [self.conf[n]['init'][index] for n in self.names] <NEW_LINE> <DEDENT> def set_value(self, name, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> hp = HyperParam(self.conf[name]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> hp.value = value <NEW_LINE> self[name] = hp <NEW_LINE> <DEDENT> def set_values(self, values): <NEW_LINE> <INDENT> if isinstance(values, dict): <NEW_LINE> <INDENT> values = [values[n] for n in self.names] <NEW_LINE> <DEDENT> if len(values) != len(self.names): <NEW_LINE> <INDENT> raise Exception('Number of values (%d) should be equal to the number of names (%d)!' % len(values), len(self.names)) <NEW_LINE> <DEDENT> for i, name in enumerate(self.names): <NEW_LINE> <INDENT> self.set_value(name, values[i]) | Describes collection of hyperparameter, each item of which is
an instance of HyperParam class.
Example of usage:
maxnum_iter_conf = {'max': 20, 'min': 20, 'name': 'maxnum_iter', 'size': 1, 'type': 'int'}
mu_conf = {'max': 0.1, 'min': 0.001, 'name': 'mu', 'size': 1, 'type': 'float'}
maxnum_iter = HyperParam(maxnum_iter_conf)
mu = HyperParam(mu_conf)
Set values:
mu.value = 0.05
maxnum_iter.value = 12
hpr = HyperParams(('maxnum_iter', 'mu'))
hpr.mu = mu
hpr.maxnum_iter = maxnum_iter
# Re-define value (works only if `maxnum_iter` exists):
hpr.maxnum_iter.value = 15
# In other case - this way:
hpr.set_value(maxnum_iter, 15)
Call attributes:
hpr.mu.conf
hpr.as_ordered_dict()
hpr.as_dict() | 62598faf7c178a314d78d4b6 |
class Decoder: <NEW_LINE> <INDENT> def __init__(self, vocab_size, wordvec_size, hidden_size): <NEW_LINE> <INDENT> V, D, H = vocab_size, wordvec_size, hidden_size <NEW_LINE> embed_W = (np.random.randn(V, D) / 100).astype("f") <NEW_LINE> lstm_Wx = (np.random.randn(D, 4 * H) / np.sqrt(D)).astype("f") <NEW_LINE> lstm_Wh = (np.random.randn(H, 4 * H) / np.sqrt(H)).astype("f") <NEW_LINE> lstm_b = np.zeros(4 * H).astype("f") <NEW_LINE> affine_W = (np.random.randn(H, V) / np.sqrt(H)).astype("f") <NEW_LINE> affine_b = np.zeros(V).astype("f") <NEW_LINE> self.embed = TimeEmbedding(embed_W) <NEW_LINE> self.lstm = TimeLSTM(lstm_Wx, lstm_Wh, lstm_b, stateful=True) <NEW_LINE> self.affine = TimeAffine(affine_W, affine_b) <NEW_LINE> self.params, self.grads = [], [] <NEW_LINE> for layer in (self.embed, self.lstm, self.affine): <NEW_LINE> <INDENT> self.params += layer.params <NEW_LINE> self.grads += layer.grads <NEW_LINE> <DEDENT> <DEDENT> def forward(self, xs, h): <NEW_LINE> <INDENT> self.lstm.set_state(h) <NEW_LINE> out = self.embed.forward(xs) <NEW_LINE> out = self.lstm.forward(out) <NEW_LINE> score = self.affine.forward(out) <NEW_LINE> return score <NEW_LINE> <DEDENT> def backward(self, dscore): <NEW_LINE> <INDENT> dout = self.affine.backward(dscore) <NEW_LINE> dout = self.lstm.backward(dout) <NEW_LINE> self.embed.backward(dout) <NEW_LINE> dh = self.lstm.dh <NEW_LINE> return dh <NEW_LINE> <DEDENT> def generate(self, h, start_id, sample_size): <NEW_LINE> <INDENT> sample = [] <NEW_LINE> sample_id = start_id <NEW_LINE> self.lstm.set_state(h) <NEW_LINE> for _ in range(sample_size): <NEW_LINE> <INDENT> x = np.array(sample_id).reshape((1, 1)) <NEW_LINE> out = self.embed.forward(x) <NEW_LINE> out = self.lstm.forward(out) <NEW_LINE> score = self.affine.forward(out) <NEW_LINE> sample_id = np.argmax(score.flatten()) <NEW_LINE> sample.append(int(sample_id)) <NEW_LINE> <DEDENT> return sample | Decoder part (seq2seq)
| 62598faf4e4d562566372440 |
class EventNotFound(Exception): <NEW_LINE> <INDENT> def __init__(self, event): <NEW_LINE> <INDENT> super(EventNotFound, self).__init__("Event '%s' was not found" % event) | Raised if an event was not found | 62598fafa8370b77170f03f6 |
class DNBURLValidator(RegexValidator): <NEW_LINE> <INDENT> regex = re.compile(r'.*(?:d-nb.info?|portal.dnb.de?)/.*(?:gnd/?|nid%3D?)(\w+)') <NEW_LINE> message = "Bitte nur Adressen der DNB eingeben (d-nb.info oder portal.dnb.de)." <NEW_LINE> code = "dnb" | RegexValidator for URLs of the German national library.
This validator captures the GND ID in the first group for a given valid URL. | 62598faf7d43ff248742740f |
class AnchorMode(IntEnum): <NEW_LINE> <INDENT> Parent = 0 <NEW_LINE> Cursor = 1 | An IntEnum defining the various popup anchor modes.
| 62598faf63d6d428bbee27c6 |
class ChrRace(models.Model): <NEW_LINE> <INDENT> id = models.IntegerField(unique=True, primary_key=True) <NEW_LINE> name = models.CharField(max_length=30) <NEW_LINE> short_description = models.TextField(blank=True) <NEW_LINE> description = models.TextField(blank=True) <NEW_LINE> icon_id = models.IntegerField(blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'eve_db' <NEW_LINE> ordering = ['id'] <NEW_LINE> verbose_name = 'Race' <NEW_LINE> verbose_name_plural = 'Races' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__unicode__() | Table lists available races. Races are numbered like bitmask - 1,2,4,8,16...
CCP Table: chrRaces
CCP Primary key: "raceID" tinyint(3) | 62598faf1b99ca400228f53d |
class ComputeAddressesListRequest(_messages.Message): <NEW_LINE> <INDENT> filter = _messages.StringField(1) <NEW_LINE> maxResults = _messages.IntegerField(2, variant=_messages.Variant.UINT32, default=500) <NEW_LINE> orderBy = _messages.StringField(3) <NEW_LINE> pageToken = _messages.StringField(4) <NEW_LINE> project = _messages.StringField(5, required=True) <NEW_LINE> region = _messages.StringField(6, required=True) | A ComputeAddressesListRequest object.
Fields:
filter: Sets a filter {expression} for filtering listed resources. Your
{expression} must be in the format: field_name comparison_string
literal_string. The field_name is the name of the field you want to
compare. Only atomic field types are supported (string, number,
boolean). The comparison_string must be either eq (equals) or ne (not
equals). The literal_string is the string value to filter to. The
literal value must be valid for the type of field you are filtering by
(string, number, boolean). For string fields, the literal value is
interpreted as a regular expression using RE2 syntax. The literal value
must match the entire field. For example, to filter for instances that
do not have a name of example-instance, you would use name ne example-
instance. You can filter on nested fields. For example, you could
filter on instances that have set the scheduling.automaticRestart field
to true. Use filtering on nested fields to take advantage of labels to
organize and search for results based on label values. To filter on
multiple expressions, provide each separate expression within
parentheses. For example, (scheduling.automaticRestart eq true) (zone eq
us-central1-f). Multiple expressions are treated as AND expressions,
meaning that resources must match all expressions to pass the filters.
maxResults: The maximum number of results per page that should be
returned. If the number of available results is larger than maxResults,
Compute Engine returns a nextPageToken that can be used to get the next
page of results in subsequent list requests. Acceptable values are 0 to
500, inclusive. (Default: 500)
orderBy: Sorts list results by a certain order. By default, results are
returned in alphanumerical order based on the resource name. You can
also sort results in descending order based on the creation timestamp
using orderBy="creationTimestamp desc". This sorts results based on the
creationTimestamp field in reverse chronological order (newest result
first). Use this to sort resources like operations so that the newest
operation is returned first. Currently, only sorting by name or
creationTimestamp desc is supported.
pageToken: Specifies a page token to use. Set pageToken to the
nextPageToken returned by a previous list request to get the next page
of results.
project: Project ID for this request.
region: Name of the region for this request. | 62598faf23849d37ff8510ce |
class Application(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def factory(cls, global_config, **local_config): <NEW_LINE> <INDENT> return cls(**local_config) <NEW_LINE> <DEDENT> def __call__(self, environ, start_response): <NEW_LINE> <INDENT> raise NotImplementedError(_('You must implement __call__')) | Base WSGI application wrapper. Subclasses need to implement __call__. | 62598faf442bda511e95c472 |
class LogModules(Base, Dictable): <NEW_LINE> <INDENT> __tablename__ = 'log_modules' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> log_id = Column(Integer, ForeignKey('log_list.log_id')) <NEW_LINE> module_id = Column(Integer) <NEW_LINE> module_name = Column(String(30)) | Liste der Module
| 62598fafadb09d7d5dc0a5a5 |
class Config: <NEW_LINE> <INDENT> SECRET_KEY='@Lb\xf5\xa864L\x8f\xc9\xe8V\x89\xb3\xc7\x8akx\x9b\x0e\x0eJ\xfa\x10' <NEW_LINE> SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://moringa:Access@localhost/pitches' <NEW_LINE> UPLOADED_PHOTOS_DEST ='app/static/photos' <NEW_LINE> SIMPLEMDE_JS_IIFE = True <NEW_LINE> SIMPLEMDE_USE_CDN = True <NEW_LINE> MAIL_SERVER = 'smtp.googlemail.com' <NEW_LINE> MAIL_PORT = 587 <NEW_LINE> MAIL_USE_TLS = True <NEW_LINE> MAIL_USERNAME = os.environ.get("MAIL_USERNAME") <NEW_LINE> MAIL_PASSWORD = os.environ.get("MAIL_PASSWORD") <NEW_LINE> pass | General configuration parent class | 62598fafff9c53063f51a667 |
class ScanState(enum.Enum): <NEW_LINE> <INDENT> notScanning = 0 <NEW_LINE> initialScan = 1 <NEW_LINE> computingHashes = 2 <NEW_LINE> checkModified = 3 <NEW_LINE> realHashOnly = 4 | State of the filesystem scan. Used internally in :class:`Source`. | 62598fafbf627c535bcb14b9 |
class PipelineCallback(object): <NEW_LINE> <INDENT> def __init__(self, entry_point, req, store=None): <NEW_LINE> <INDENT> self.entry_point = entry_point <NEW_LINE> self.plumbing = Plumbing(req.scope_of(entry_point).plumbing.pipeline, "%s-via-%s" % (req.plumbing.id, entry_point)) <NEW_LINE> self.req = req <NEW_LINE> self.store = store <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __deepcopy__(self, memo): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> log.debug("{!s}: called".format(self.plumbing)) <NEW_LINE> t = args[0] <NEW_LINE> if t is None: <NEW_LINE> <INDENT> raise ValueError("PipelineCallback must be called with a parse-tree argument") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> state = kwargs <NEW_LINE> state[self.entry_point] = True <NEW_LINE> log.debug("state: {}".format(repr(state))) <NEW_LINE> return self.plumbing.process(self.req.md, store=self.store, state=state, t=t) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> log.debug(traceback.format_exc()) <NEW_LINE> log.error(ex) <NEW_LINE> raise ex | A delayed pipeline callback used as a post for parse_saml_metadata
| 62598faf4527f215b58e9ef1 |
class BuildTypeMixin(object): <NEW_LINE> <INDENT> def get_build_type(self, build_type): <NEW_LINE> <INDENT> if build_type is None: <NEW_LINE> <INDENT> raise TargetDefinitionException(self, "Target must define a 'build_type' attribute as either " "debug or release") <NEW_LINE> <DEDENT> if build_type.lower() not in ('release', 'debug'): <NEW_LINE> <INDENT> raise TargetDefinitionException(self, "The 'build_type' attribute must be 'debug' " "or 'release' instead of: {0}".format(build_type)) <NEW_LINE> <DEDENT> return build_type | Mixin class to validate and normalize build type input for keystores and android targets. | 62598faf3317a56b869be558 |
class ObjectRegionData(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.region = SkyRegionMap().CATCHALL_REGION_ID <NEW_LINE> self.region_center_dot_product = -1 | Data representing an individual object's position in a region.
We care about the region itself for obvious reasons, but we care about
the dot product with the center because it is a measure of how
close it is to the center of a region. | 62598faff7d966606f748000 |
class LRUpdate(Callback): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.history = {} <NEW_LINE> self.trained_iterations = 0 <NEW_LINE> <DEDENT> def _get_lr(self): <NEW_LINE> <INDENT> return K.get_value(self.model.optimizer.lr) <NEW_LINE> <DEDENT> def on_train_begin(self, logs = None): <NEW_LINE> <INDENT> logs = logs or {} <NEW_LINE> lr_shape = K.get_variable_shape(self.model.optimizer.lr) <NEW_LINE> if len(lr_shape) > 0: <NEW_LINE> <INDENT> self.min_lr = np.full(lr_shape, self._get_lr()) <NEW_LINE> <DEDENT> K.set_value(self.model.optimizer.lr, self.min_lr) <NEW_LINE> <DEDENT> def on_batch_end(self, batch, logs = None): <NEW_LINE> <INDENT> logs = logs or {} <NEW_LINE> self.trained_iterations += 1 <NEW_LINE> K.set_value(self.model.optimizer.lr, self._get_lr()) <NEW_LINE> self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr)) <NEW_LINE> self.history.setdefault('iterations', []).append(self.trained_iterations) <NEW_LINE> for k, v in logs.items(): <NEW_LINE> <INDENT> self.history.setdefault(k, []).append(v) <NEW_LINE> <DEDENT> <DEDENT> def plot_lr(self): <NEW_LINE> <INDENT> plt.xlabel('iterations') <NEW_LINE> plt.ylabel('learning rate') <NEW_LINE> plt.plot(self.history['iterations'], self.history['lr']) | This callback is utilized to log the learning rates for every iteration (batch cycle
i.e. dataset size / batch size). It is not meant to be directly used as a callback
but extended by other callbacks ie. LRFind, LRCycle | 62598faf76e4537e8c3ef5c9 |
class TestWaitForPackage(testing.AsyncTestCase): <NEW_LINE> <INDENT> def setUp(self, *args, **kwargs): <NEW_LINE> <INDENT> super(TestWaitForPackage, self).setUp(*args, **kwargs) <NEW_LINE> packagecloud.TOKEN = "Unittest" <NEW_LINE> packagecloud.ACCOUNT = "Unittest" <NEW_LINE> self.maxDiff = None <NEW_LINE> <DEDENT> @testing.gen_test <NEW_LINE> def test_bad_regex_name(self): <NEW_LINE> <INDENT> with self.assertRaises(exceptions.InvalidOptions): <NEW_LINE> <INDENT> packagecloud.WaitForPackage( "Unit test action", {"name": "[", "version": "1", "repo": "unittest"} ) <NEW_LINE> <DEDENT> <DEDENT> @testing.gen_test <NEW_LINE> def test_bad_regex_version(self): <NEW_LINE> <INDENT> with self.assertRaises(exceptions.InvalidOptions): <NEW_LINE> <INDENT> packagecloud.WaitForPackage( "Unit test action", {"name": "unittest", "version": "[", "repo": "unittest"}, ) <NEW_LINE> <DEDENT> <DEDENT> @testing.gen_test <NEW_LINE> def test_execute(self): <NEW_LINE> <INDENT> actor = packagecloud.WaitForPackage( "Unit test action", {"name": "unittest", "repo": "unittest", "version": "0.2"}, ) <NEW_LINE> actor._packagecloud_client = mock.Mock() <NEW_LINE> actor._packagecloud_client.packages().http_get = mock_tornado( ALL_PACKAGES_MOCK_RESPONSE ) <NEW_LINE> actor._packagecloud_client.delete().http_delete = mock_tornado({}) <NEW_LINE> matched_packages = yield actor._execute() <NEW_LINE> self.assertEqual(matched_packages, None) <NEW_LINE> <DEDENT> @testing.gen_test <NEW_LINE> def test_execute_with_sleep(self): <NEW_LINE> <INDENT> actor = packagecloud.WaitForPackage( "Unit test action", {"name": "not_found", "repo": "unittest", "version": "0.2", "sleep": 1}, ) <NEW_LINE> actor._packagecloud_client = mock.Mock() <NEW_LINE> actor._packagecloud_client.packages().http_get = mock_tornado( ALL_PACKAGES_MOCK_RESPONSE ) <NEW_LINE> actor._search = mock.Mock( side_effect=[tornado_value([]), tornado_value(["something"])] ) <NEW_LINE> yield actor._execute() <NEW_LINE> self.assertEqual(actor._search.call_count, 2) <NEW_LINE> <DEDENT> @testing.gen_test <NEW_LINE> def test_search(self): <NEW_LINE> <INDENT> actor = packagecloud.WaitForPackage( "Unit test action", {"name": "unittest", "repo": "unittest", "version": "0.2"}, ) <NEW_LINE> actor._packagecloud_client = mock.Mock() <NEW_LINE> actor._packagecloud_client.packages().http_get = mock_tornado( ALL_PACKAGES_MOCK_RESPONSE ) <NEW_LINE> matched_packages = yield actor._search( repo="unittest", name="unittest", version="0.2" ) <NEW_LINE> self.assertEqual(matched_packages, [ALL_PACKAGES_MOCK_RESPONSE[0]]) | Unit tests for the packagecloud WaitForPackage actor. | 62598faf67a9b606de545fe8 |
class Onreset(HtmlTagAttribute): <NEW_LINE> <INDENT> belongs_to = ['Form'] | Script to be run when a reset button in a form is clicked. | 62598faf55399d3f0562653f |
class SeqGenerator: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.dict = {} <NEW_LINE> <DEDENT> def get_seq(self, prefix, ts): <NEW_LINE> <INDENT> entry = self.dict.get(prefix) <NEW_LINE> if not entry or entry[0] != ts: <NEW_LINE> <INDENT> self.dict[prefix] = [ts, 1] <NEW_LINE> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> seq = entry[1] <NEW_LINE> entry[1] += 1 <NEW_LINE> return seq | Class that will determine the sequence number of a line required for
updates. | 62598fafd486a94d0ba2bfeb |
class SkiaBuildbotPageSet(page_set_module.PageSet): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SkiaBuildbotPageSet, self).__init__( user_agent_type='desktop', credentials_path = 'data/credentials.json', archive_data_file='data/skia_twitter_desktop.json') <NEW_LINE> urls_list = [ 'http://twitter.com/katyperry', ] <NEW_LINE> for url in urls_list: <NEW_LINE> <INDENT> self.AddPage(SkiaBuildbotDesktopPage(url, self)) | Pages designed to represent the median, not highly optimized web | 62598faf66673b3332c303e8 |
class CreateSubscriptionRequest(BaseRequest): <NEW_LINE> <INDENT> def __init__(self, ts_connection, subscription_subject, content_type, content_id, schedule_id, user_id): <NEW_LINE> <INDENT> super().__init__(ts_connection) <NEW_LINE> self._subscription_subject = subscription_subject <NEW_LINE> self._content_type = content_type.lower() <NEW_LINE> self._content_id = content_id <NEW_LINE> self._schedule_id = schedule_id <NEW_LINE> self._user_id = user_id <NEW_LINE> self._validate_content_type() <NEW_LINE> <DEDENT> @property <NEW_LINE> def valid_content_types(self): <NEW_LINE> <INDENT> return [ 'Workbook', 'View' ] <NEW_LINE> <DEDENT> def _validate_content_type(self): <NEW_LINE> <INDENT> if self._content_type.capitalize() in self.valid_content_types: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._invalid_parameter_exception() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def base_create_subscription_request(self): <NEW_LINE> <INDENT> self._request_body.update({ 'subscription': { 'subject': self._subscription_subject, 'content': { 'type': self._content_type, 'id': self._content_id }, 'schedule': {'id': self._schedule_id}, 'user': {'id': self._user_id} }, }) <NEW_LINE> return self._request_body <NEW_LINE> <DEDENT> def get_request(self): <NEW_LINE> <INDENT> return self.base_create_subscription_request | Create subscription request for generating API request URLs to Tableau Server.
:param ts_connection: The Tableau Server connection object.
:type ts_connection: class
:param subscription_subject: The subject to display to users receiving the subscription.
:type subscription_subject: string
:param content_type: Set this value to 'Workbook' if the subscription is for a workbook;
set this value to 'View' if the subscription is for a view.
:type content_type: string
:param content_id: The ID of the workbook or view the subscription is sourced from.
:type content_id: string
:param schedule_id: The ID of the schedule the subscription runs on.
:type schedule_id: string
:param user_id: The user ID for the user who is being subscribed to the view or workbook.
This user must have an email address defined on Tableau Server.
:type user_id: string | 62598fafa79ad1619776a083 |
class Vampire(Monster): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.mon_mult = {'HersheyKisses': 1, 'SourStraws': 1, 'ChocolateBars': 0, 'NerdBombs': 1} <NEW_LINE> self.__id = 1 <NEW_LINE> super().__init__(random.randint(100, 200), random.randint(10, 20), self.mon_mult) <NEW_LINE> <DEDENT> def get_id(self): <NEW_LINE> <INDENT> return self.__id | Vampire object: A monster type. | 62598faf85dfad0860cbfa81 |
class BaseGenerator(object): <NEW_LINE> <INDENT> def __init__(self, N, batch_size, create_y): <NEW_LINE> <INDENT> self.N = N <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.batch_start = 0 <NEW_LINE> self.create_y = create_y <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> self._advance_batch() <NEW_LINE> if self.batch_start == 0: <NEW_LINE> <INDENT> self.first_batch() <NEW_LINE> <DEDENT> x_batch = self.get_x_batch() <NEW_LINE> if self.create_y: <NEW_LINE> <INDENT> y_batch = self.get_y_batch() <NEW_LINE> result = (x_batch, y_batch) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = x_batch <NEW_LINE> <DEDENT> self.batch_start = self.batch_end % self.N <NEW_LINE> return result <NEW_LINE> <DEDENT> def _advance_batch(self): <NEW_LINE> <INDENT> assert self.batch_start < self.N <NEW_LINE> if self.batch_start + self.batch_size <= self.N: <NEW_LINE> <INDENT> self.batch_end = self.batch_start + self.batch_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.batch_end = self.N <NEW_LINE> <DEDENT> <DEDENT> def first_batch(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_x_batch(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_y_batch(self): <NEW_LINE> <INDENT> pass | A generator that dynamically creates batches from a list of N examples. | 62598faf7d847024c075c3de |
class VectorPrettyPrinter(PrettyPrinter): <NEW_LINE> <INDENT> def _print_Derivative(self, deriv): <NEW_LINE> <INDENT> from sympy.physics.vector.functions import dynamicsymbols <NEW_LINE> t = dynamicsymbols._t <NEW_LINE> dot_i = 0 <NEW_LINE> syms = list(reversed(deriv.variables)) <NEW_LINE> while len(syms) > 0: <NEW_LINE> <INDENT> if syms[-1] == t: <NEW_LINE> <INDENT> syms.pop() <NEW_LINE> dot_i += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super()._print_Derivative(deriv) <NEW_LINE> <DEDENT> <DEDENT> if not (isinstance(type(deriv.expr), UndefinedFunction) and (deriv.expr.args == (t,))): <NEW_LINE> <INDENT> return super()._print_Derivative(deriv) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pform = self._print_Function(deriv.expr) <NEW_LINE> <DEDENT> if len(pform.picture) > 1: <NEW_LINE> <INDENT> return super()._print_Derivative(deriv) <NEW_LINE> <DEDENT> if dot_i >= 5: <NEW_LINE> <INDENT> return super()._print_Derivative(deriv) <NEW_LINE> <DEDENT> dots = {0 : "", 1 : "\N{COMBINING DOT ABOVE}", 2 : "\N{COMBINING DIAERESIS}", 3 : "\N{COMBINING THREE DOTS ABOVE}", 4 : "\N{COMBINING FOUR DOTS ABOVE}"} <NEW_LINE> d = pform.__dict__ <NEW_LINE> if not self._use_unicode: <NEW_LINE> <INDENT> apostrophes = "" <NEW_LINE> for i in range(0, dot_i): <NEW_LINE> <INDENT> apostrophes += "'" <NEW_LINE> <DEDENT> d['picture'][0] += apostrophes + "(t)" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d['picture'] = [center_accent(d['picture'][0], dots[dot_i])] <NEW_LINE> <DEDENT> return pform <NEW_LINE> <DEDENT> def _print_Function(self, e): <NEW_LINE> <INDENT> from sympy.physics.vector.functions import dynamicsymbols <NEW_LINE> t = dynamicsymbols._t <NEW_LINE> func = e.func <NEW_LINE> args = e.args <NEW_LINE> func_name = func.__name__ <NEW_LINE> pform = self._print_Symbol(Symbol(func_name)) <NEW_LINE> if not (isinstance(func, UndefinedFunction) and (args == (t,))): <NEW_LINE> <INDENT> return super()._print_Function(e) <NEW_LINE> <DEDENT> return pform | Pretty Printer for vectorialexpressions. | 62598faf8a43f66fc4bf2196 |
class UniversalHousingExit(DefaultExit): <NEW_LINE> <INDENT> def at_traverse(self, traversing_object, target_location, **kwargs): <NEW_LINE> <INDENT> if target_location: <NEW_LINE> <INDENT> super().at_traverse(traversing_object, target_location, **kwargs) <NEW_LINE> return <NEW_LINE> <DEDENT> owned_rooms = self.objects.filter( db_tags__db_key=traversing_object.dbref, db_tags__db_category="owner") <NEW_LINE> guest_rooms = self.objects.filter( db_tags__db_key=traversing_object.dbref, db_tags__db_category="guest") <NEW_LINE> traversing_object.msg('You cannot access any rooms here.') <NEW_LINE> combined_rooms = owned_rooms + guest_rooms <NEW_LINE> if len(combined_rooms) == 1: <NEW_LINE> <INDENT> super().at_traverse(traversing_object, combined_rooms[0], **kwargs) <NEW_LINE> <DEDENT> evmenu.EvMenu(traversing_object, {"choice_prompt":choice_prompt}, startnode="choice_prompt", cmdset_mergetype="Union", cmd_on_exit=None, callback=self.at_traverse, list1=owned_rooms, list2=guest_rooms) | Allow access to owned houses. | 62598fafbe8e80087fbbf080 |
class PluginSearch(object): <NEW_LINE> <INDENT> schema = { 'type': 'array', 'items': { 'allOf': [ {'$ref': '/schema/plugins?group=search'}, {'maxProperties': 1, 'minProperties': 1} ] } } <NEW_LINE> @plugin.priority(130) <NEW_LINE> def on_task_urlrewrite(self, task, config): <NEW_LINE> <INDENT> if task.manager.unit_test: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> plugins = {} <NEW_LINE> for p in plugin.get_plugins(group='search'): <NEW_LINE> <INDENT> plugins[p.name] = p.instance <NEW_LINE> <DEDENT> for entry in task.accepted: <NEW_LINE> <INDENT> for name in config: <NEW_LINE> <INDENT> search_config = None <NEW_LINE> if isinstance(name, dict): <NEW_LINE> <INDENT> name, search_config = list(name.items())[0] <NEW_LINE> <DEDENT> log.verbose('Searching `%s` from %s' % (entry['title'], name)) <NEW_LINE> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results = plugins[name].search(task=task, entry=entry, config=search_config) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> log.warning('Search plugin %s does not support latest search api.' % name) <NEW_LINE> results = plugins[name].search(entry, search_config) <NEW_LINE> <DEDENT> matcher = SequenceMatcher(a=entry['title']) <NEW_LINE> for result in sorted(results, key=lambda e: e.get('search_sort'), reverse=True): <NEW_LINE> <INDENT> matcher.set_seq2(result['title']) <NEW_LINE> if matcher.ratio() > 0.9: <NEW_LINE> <INDENT> log.debug('Found url: %s', result['url']) <NEW_LINE> entry['url'] = result['url'] <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> except (plugin.PluginError, plugin.PluginWarning) as pw: <NEW_LINE> <INDENT> log.verbose('Failed: %s' % pw.value) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> entry['immortal'] = False <NEW_LINE> entry.reject('search failed') | Search entry from sites. Accepts list of known search plugins, list is in priority order.
Once hit has been found no more searches are performed. Should be used only when
there is no other way to get working download url, ie. when input plugin does not provide
any downloadable urls.
Example::
urlrewrite_search:
- newtorrents
- piratebay
.. note:: Some url rewriters will use search plugins automatically if entry url
points into a search page. | 62598faf283ffb24f3cf38a8 |
@pytest.mark.usefixtures('verify_mock_vuforia') <NEW_LINE> class TestIncorrect: <NEW_LINE> <INDENT> def test_not_integer(self, endpoint: Endpoint) -> None: <NEW_LINE> <INDENT> endpoint_headers = dict(endpoint.prepared_request.headers) <NEW_LINE> if not endpoint_headers.get('Content-Type'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> content_length = '0.4' <NEW_LINE> headers = {**endpoint_headers, 'Content-Length': content_length} <NEW_LINE> endpoint.prepared_request.headers = CaseInsensitiveDict(data=headers) <NEW_LINE> session = requests.Session() <NEW_LINE> response = session.send(request=endpoint.prepared_request) <NEW_LINE> assert response.text == '' <NEW_LINE> assert dict(response.headers) == { 'Content-Length': '0', 'Connection': 'Close', } <NEW_LINE> assert response.status_code == HTTPStatus.BAD_REQUEST <NEW_LINE> <DEDENT> def test_too_large(self, endpoint: Endpoint) -> None: <NEW_LINE> <INDENT> endpoint_headers = dict(endpoint.prepared_request.headers) <NEW_LINE> if not endpoint_headers.get('Content-Type'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> content_length = str(int(endpoint_headers['Content-Length']) + 1) <NEW_LINE> headers = {**endpoint_headers, 'Content-Length': content_length} <NEW_LINE> endpoint.prepared_request.headers = CaseInsensitiveDict(data=headers) <NEW_LINE> session = requests.Session() <NEW_LINE> response = session.send(request=endpoint.prepared_request) <NEW_LINE> assert response.text == '' <NEW_LINE> assert dict(response.headers) == { 'Content-Length': '0', 'Connection': 'keep-alive', } <NEW_LINE> assert response.status_code == HTTPStatus.GATEWAY_TIMEOUT <NEW_LINE> <DEDENT> def test_too_small(self, endpoint: Endpoint) -> None: <NEW_LINE> <INDENT> endpoint_headers = dict(endpoint.prepared_request.headers) <NEW_LINE> if not endpoint_headers.get('Content-Type'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> content_length = str(int(endpoint_headers['Content-Length']) - 1) <NEW_LINE> headers = {**endpoint_headers, 'Content-Length': content_length} <NEW_LINE> endpoint.prepared_request.headers = CaseInsensitiveDict(data=headers) <NEW_LINE> session = requests.Session() <NEW_LINE> response = session.send(request=endpoint.prepared_request) <NEW_LINE> url = str(endpoint.prepared_request.url) <NEW_LINE> netloc = urlparse(url).netloc <NEW_LINE> if netloc == 'cloudreco.vuforia.com': <NEW_LINE> <INDENT> assert_vwq_failure( response=response, status_code=HTTPStatus.UNAUTHORIZED, content_type='application/json', cache_control=None, www_authenticate='VWS', connection='keep-alive', ) <NEW_LINE> return <NEW_LINE> <DEDENT> assert_vws_failure( response=response, status_code=HTTPStatus.UNAUTHORIZED, result_code=ResultCodes.AUTHENTICATION_FAILURE, ) | Tests for the ``Content-Length`` header set incorrectly.
We cannot test what happens if ``Content-Length`` is removed from a
prepared request because ``requests-mock`` behaves differently to
``requests`` - https://github.com/jamielennox/requests-mock/issues/80. | 62598faf7047854f4633f3f6 |
class Layer: <NEW_LINE> <INDENT> def __init__(self, n_outputs=1, **kwargs): <NEW_LINE> <INDENT> self.n_outputs = n_outputs <NEW_LINE> self.kwargs = kwargs <NEW_LINE> self.name = self.__class__.__name__ <NEW_LINE> <DEDENT> def _call(self, nodes): <NEW_LINE> <INDENT> nodes = utils.generic.listify(nodes) <NEW_LINE> if self.n_outputs > 1: <NEW_LINE> <INDENT> out_nodes = [TransformationNode(self, nodes, i) for i in range(self.n_outputs)] <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> node.outbound_nodes += out_nodes <NEW_LINE> <DEDENT> if all(node.output is not None for node in nodes): <NEW_LINE> <INDENT> for out_node in out_nodes: <NEW_LINE> <INDENT> out_node.fit() <NEW_LINE> out_node.transform() <NEW_LINE> <DEDENT> <DEDENT> out = out_nodes <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out_node = TransformationNode(self, nodes) <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> node.outbound_nodes.append(out_node) <NEW_LINE> <DEDENT> if all(node.output is not None for node in nodes): <NEW_LINE> <INDENT> out_node.fit() <NEW_LINE> out_node.transform() <NEW_LINE> <DEDENT> out = out_node <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> def __call__(self, nodes): <NEW_LINE> <INDENT> return self._call(nodes) <NEW_LINE> <DEDENT> def partial_fit(self, *inputs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fit(self, *inputs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def transform(self, *inputs): <NEW_LINE> <INDENT> raise NotImplementedError | Base class of all layers.
Parameters
----------
n_outputs (default: 1)
number of distinct data, and thus nodes, output by the layer's transform.
**kwargs
hyperparameters of the transformation function.
Attributes
----------
n_outputs
number of distinct data, and thus nodes, output by the layer's transform.
kwargs
hyperparameters of the transformation function. | 62598fafa219f33f346c6832 |
class FeffPathNlegList(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> def __get__(self, instance, owner): <NEW_LINE> <INDENT> lst=[] <NEW_LINE> for i in range(instance.wrapper.nleg): <NEW_LINE> <INDENT> x = eval('feffpathwrapper.get_'+self._name+'(instance.wrapper,i)') <NEW_LINE> lst.append(float(x)) <NEW_LINE> <DEDENT> return lst <NEW_LINE> <DEDENT> def __set__(self, instance, val): <NEW_LINE> <INDENT> pass | A descriptor for list-valued FeffPath attributes which have nleg
members and describe the geometry of the path, i.e. ri, beta, and
eta | 62598fafbe383301e0253815 |
class TestVehicleStatsEngineOilPressureKPa(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 make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return VehicleStatsEngineOilPressureKPa( time = '2020-01-27T07:06:25Z', value = 100 ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return VehicleStatsEngineOilPressureKPa( time = '2020-01-27T07:06:25Z', value = 100, ) <NEW_LINE> <DEDENT> <DEDENT> def testVehicleStatsEngineOilPressureKPa(self): <NEW_LINE> <INDENT> inst_req_only = self.make_instance(include_optional=False) <NEW_LINE> inst_req_and_optional = self.make_instance(include_optional=True) | VehicleStatsEngineOilPressureKPa unit test stubs | 62598faf56ac1b37e6302208 |
class ClasseFonction(Fonction): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def init_types(cls): <NEW_LINE> <INDENT> cls.ajouter_types(cls.peut_contenir_objet, "Objet", "Objet") <NEW_LINE> cls.ajouter_types(cls.peut_contenir_proto, "Objet", "str", "Fraction") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def peut_contenir_objet(conteneur, objet): <NEW_LINE> <INDENT> if conteneur.est_de_type("conteneur de potion"): <NEW_LINE> <INDENT> return conteneur.potion is None <NEW_LINE> <DEDENT> if conteneur.est_de_type("conteneur de nourriture"): <NEW_LINE> <INDENT> if sum(o.poids_unitaire for o in conteneur.nourriture) + objet.poids_unitaire > conteneur.poids_max: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> if conteneur.est_de_type("conteneur") or conteneur.est_de_type( "machine") or conteneur.est_de_type("meuble"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conteneur.conteneur.supporter_poids_sup(objet.poids_unitaire, recursif=False) <NEW_LINE> if conteneur.est_de_type("conteneur"): <NEW_LINE> <INDENT> assert conteneur.accepte_type(objet) <NEW_LINE> <DEDENT> <DEDENT> except (AssertionError, SurPoids): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def peut_contenir_proto(conteneur, prototype, nb): <NEW_LINE> <INDENT> nb = int(nb) <NEW_LINE> if not prototype in importeur.objet.prototypes: <NEW_LINE> <INDENT> raise ErreurExecution("prototype {} introuvable".format(prototype)) <NEW_LINE> <DEDENT> prototype = importeur.objet.prototypes[prototype] <NEW_LINE> if conteneur.est_de_type("conteneur de potion"): <NEW_LINE> <INDENT> return conteneur.potion is None and nb <= 1 <NEW_LINE> <DEDENT> if conteneur.est_de_type("conteneur de nourriture"): <NEW_LINE> <INDENT> if sum(o.poids_unitaire for o in conteneur.nourriture) + prototype.poids_unitaire * nb > conteneur.poids_max: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> if conteneur.est_de_type("conteneur") or conteneur.est_de_type( "machine") or conteneur.est_de_type("meuble"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conteneur.conteneur.supporter_poids_sup( prototype.poids_unitaire * nb, recursif=False) <NEW_LINE> if conteneur.est_de_type("conteneur"): <NEW_LINE> <INDENT> assert conteneur.accepte_type(prototype) <NEW_LINE> <DEDENT> <DEDENT> except (AssertionError, SurPoids): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Teste si le conteneur a de la place. | 62598fafe5267d203ee6b926 |
class _ExtensionLinesField(ExtensionField, LinesField): <NEW_LINE> <INDENT> pass | LinesField | 62598faf4527f215b58e9ef2 |
class DSNNWeightedMag(DSNNHeb): <NEW_LINE> <INDENT> def _is_dynamic(self, module): <NEW_LINE> <INDENT> return module.hebbian_prune is not None <NEW_LINE> <DEDENT> def prune(self, module): <NEW_LINE> <INDENT> with torch.no_grad(): <NEW_LINE> <INDENT> weight = module.m.weight.clone().detach() <NEW_LINE> corr = module.get_coactivations() <NEW_LINE> hebbian_prune_perc = module.hebbian_prune <NEW_LINE> active_synapses = weight != 0 <NEW_LINE> if hebbian_prune_perc is not None: <NEW_LINE> <INDENT> weight *= corr <NEW_LINE> keep_mask = self._get_magnitude_mask( weight, active_synapses, hebbian_prune_perc ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> keep_mask = active_synapses.to(self.device) <NEW_LINE> <DEDENT> <DEDENT> return keep_mask <NEW_LINE> <DEDENT> def grow(self, module, num_add): <NEW_LINE> <INDENT> with torch.no_grad(): <NEW_LINE> <INDENT> nonactive_synapses = module.m.weight == 0 <NEW_LINE> add_mask = self._get_random_add_mask(nonactive_synapses, num_add) <NEW_LINE> add_mask = add_mask.to(self.device) <NEW_LINE> <DEDENT> return add_mask | Weight weights using correlation | 62598faf2ae34c7f260ab0fe |
class BaseCompileIT(PantsRunIntegrationTest): <NEW_LINE> <INDENT> _EXTRA_TASK_ARGS=[] <NEW_LINE> @contextmanager <NEW_LINE> def do_test_compile(self, target, expected_files=None, iterations=2, expect_failure=False, extra_args=None, workdir_outside_of_buildroot=False): <NEW_LINE> <INDENT> if not workdir_outside_of_buildroot: <NEW_LINE> <INDENT> workdir_generator = self.temporary_workdir() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> workdir_generator = temporary_dir(suffix='.pants.d') <NEW_LINE> <DEDENT> with workdir_generator as workdir: <NEW_LINE> <INDENT> with self.temporary_cachedir() as cachedir: <NEW_LINE> <INDENT> for i in six.moves.xrange(0, iterations): <NEW_LINE> <INDENT> pants_run = self.run_test_compile(workdir, cachedir, target, clean_all=(i == 0), extra_args=extra_args) <NEW_LINE> if expect_failure: <NEW_LINE> <INDENT> self.assert_failure(pants_run) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assert_success(pants_run) <NEW_LINE> <DEDENT> <DEDENT> found = defaultdict(set) <NEW_LINE> workdir_files = [] <NEW_LINE> if expected_files: <NEW_LINE> <INDENT> to_find = set(expected_files) <NEW_LINE> for root, _, files in os.walk(workdir): <NEW_LINE> <INDENT> for file in files: <NEW_LINE> <INDENT> workdir_files.append(os.path.join(root, file)) <NEW_LINE> if file in to_find: <NEW_LINE> <INDENT> found[file].add(os.path.join(root, file)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> to_find.difference_update(found) <NEW_LINE> if not expect_failure: <NEW_LINE> <INDENT> self.assertEqual(set(), to_find, 'Failed to find the following compiled files: {} in {}'.format( to_find, '\n'.join(sorted(workdir_files)))) <NEW_LINE> <DEDENT> <DEDENT> yield found <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def run_test_compile(self, workdir, cacheurl, target, clean_all=False, extra_args=None, test=False): <NEW_LINE> <INDENT> config = { 'cache': { 'write': True, 'write_to': [cacheurl], }, } <NEW_LINE> task = 'test' if test else 'compile' <NEW_LINE> args = self._EXTRA_TASK_ARGS + [task, target] + (extra_args if extra_args else []) <NEW_LINE> if clean_all: <NEW_LINE> <INDENT> args.insert(0, 'clean-all') <NEW_LINE> <DEDENT> return self.run_pants_with_workdir(args, workdir, config=config) <NEW_LINE> <DEDENT> def get_only(self, found, name): <NEW_LINE> <INDENT> files = found[name] <NEW_LINE> self.assertEqual(1, len(files)) <NEW_LINE> return files.pop() <NEW_LINE> <DEDENT> def do_test_success_and_failure(self, target, success_args, failure_args, shared_args=None): <NEW_LINE> <INDENT> shared_args = shared_args if shared_args else [] <NEW_LINE> with self.do_test_compile(target, extra_args=(shared_args + success_args)): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> with self.do_test_compile(target, extra_args=(shared_args + failure_args), expect_failure=True): <NEW_LINE> <INDENT> pass | :API: public | 62598faf26068e7796d4c972 |
class VirtualScreen2OrderViewset(DynamicModelViewSet): <NEW_LINE> <INDENT> queryset = VirtualScreen2.objects.all() <NEW_LINE> pagination_class = OrdersPagination <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> serializer_class = VirtualScreen2OrderSerializer <NEW_LINE> ordering = ('-add_time',) | 订单管理
list:
获取个人订单 | 62598faffff4ab517ebcd802 |
class MonoQueue: <NEW_LINE> <INDENT> def __init__(self, A, opt): <NEW_LINE> <INDENT> self.q = deque() <NEW_LINE> self.l=self.r=0 <NEW_LINE> self.A = A <NEW_LINE> self.opt = opt <NEW_LINE> <DEDENT> def append(self): <NEW_LINE> <INDENT> while self.q and self.opt(self.A[self.q[-1]], self.A[self.r]): <NEW_LINE> <INDENT> self.q.pop() <NEW_LINE> <DEDENT> self.q.append(self.r) <NEW_LINE> self.r+=1 <NEW_LINE> <DEDENT> def popleft(self): <NEW_LINE> <INDENT> if self.q[0]==self.l: <NEW_LINE> <INDENT> self.q.popleft() <NEW_LINE> <DEDENT> self.l += 1 <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return self.q[0] | des:
monoqueue on an arraylist, store its indices
use it like a sliding window
application:
max queue:
opt=operator.le
if equal, select rightmost
opt=operator.lt
if equal, select leftmost
min queue: opt=operator.ge | 62598faf38b623060ffa90b8 |
class BaseCard(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.card = AdaptiveCard() <NEW_LINE> self.card.add(TextBlock("Self Service Bot", size="ExtraLarge", weight="Bolder")) <NEW_LINE> <DEDENT> async def genMessage(self) -> Activity: <NEW_LINE> <INDENT> cardJsonStr = await self.card.to_json() <NEW_LINE> cardJson = json.loads(cardJsonStr) <NEW_LINE> message = Activity( type = ActivityTypes.message, attachments = [CardFactory.adaptive_card(cardJson)] ) <NEW_LINE> return message | The BaseCard class is used to represent a base adaptive card. | 62598fafbaa26c4b54d4f2d1 |
class DomainOrganisationListFilter(OrganisationListFilter): <NEW_LINE> <INDENT> parameter_name = 'domain_organisation__id__exact' <NEW_LINE> def queryset(self, request, queryset): <NEW_LINE> <INDENT> if self.value(): <NEW_LINE> <INDENT> return queryset.filter(domain__organisation_id=self.value()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return queryset | Limit the List filter to valid options for the user | 62598faf44b2445a339b697f |
class BasicPlot: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def line(self, data: pd.DataFrame, x_axis: str, y_axis: str, color: str) -> plot: <NEW_LINE> <INDENT> line = go.Scatter( x=data[x_axis], y=data[y_axis], mode="lines", marker=dict(color=color) ) <NEW_LINE> return line <NEW_LINE> <DEDENT> def scatter(self, data: pd.DataFrame, x_axis: str, y_axis: str, color: str) -> plot: <NEW_LINE> <INDENT> scatter = go.Scatter( x=data[x_axis], y=data[y_axis], name=x_axis + " vs. " + y_axis, mode="markers", marker=dict(color=color), ) <NEW_LINE> return scatter <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def plot_to_div(plot_obj_list): <NEW_LINE> <INDENT> return plot(plot_obj_list, output_type="div", include_plotlyjs=True) | Plotting 'library' | 62598faf4527f215b58e9ef3 |
class psacct(Plugin, RedHatPlugin): <NEW_LINE> <INDENT> def setup(self): <NEW_LINE> <INDENT> self.addCopySpec("/var/account") | Process accounting related information
| 62598faf5fdd1c0f98e5dfa9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.