code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class FileSizeSpinButton(Gtk.Box): <NEW_LINE> <INDENT> __gsignals__ = { 'value-changed': (GObject.SIGNAL_RUN_FIRST, None, (int, )) } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> Gtk.Box.__init__(self, orientation=Gtk.Orientation.HORIZONTAL) <NEW_LINE> self._last_val, self._curr_exp = 1, 1 <NEW_LINE> self._units = MultipleChoiceButton( [label for label, _ in SORTED_KEYS], 'MB', 'MB' ) <NEW_LINE> self._entry = Gtk.SpinButton.new_with_range(1, 1023, 1) <NEW_LINE> self._entry.set_wrap(True) <NEW_LINE> self.get_style_context().add_class( Gtk.STYLE_CLASS_LINKED ) <NEW_LINE> self._entry.set_hexpand(True) <NEW_LINE> self.pack_start(self._entry, True, True, 0) <NEW_LINE> self.pack_start(self._units, False, False, 0) <NEW_LINE> self._entry.connect('value-changed', self.on_value_changed) <NEW_LINE> self._units.connect('row-selected', self.on_unit_changed) <NEW_LINE> <DEDENT> def get_bytes(self): <NEW_LINE> <INDENT> return self._last_val * (1024 ** self._curr_exp) <NEW_LINE> <DEDENT> def set_bytes(self, size): <NEW_LINE> <INDENT> if size is 0: <NEW_LINE> <INDENT> exponent = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exponent = math.floor(math.log(size, 1024)) <NEW_LINE> <DEDENT> display_size = size / (1024 ** exponent) <NEW_LINE> self._entry.set_value(display_size) <NEW_LINE> self._set_exponent(exponent) <NEW_LINE> self._last_val = display_size <NEW_LINE> <DEDENT> def _set_exponent(self, exponent): <NEW_LINE> <INDENT> key, value = None, None <NEW_LINE> for key, value in EXPONENTS.items(): <NEW_LINE> <INDENT> if value == exponent: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> self._units.set_selected_choice(key) <NEW_LINE> self._curr_exp = value <NEW_LINE> <DEDENT> def on_value_changed(self, spbtn): <NEW_LINE> <INDENT> curr = spbtn.get_value_as_int() <NEW_LINE> if curr == 1023 and self._last_val == 1: <NEW_LINE> <INDENT> self._set_exponent(self._curr_exp - 1) <NEW_LINE> <DEDENT> if curr == 1 and self._last_val == 1023: <NEW_LINE> <INDENT> self._set_exponent(self._curr_exp + 1) <NEW_LINE> <DEDENT> self._last_val = curr <NEW_LINE> self.emit('value-changed', curr) <NEW_LINE> <DEDENT> def on_unit_changed(self, _): <NEW_LINE> <INDENT> label = self._units.get_selected_choice() <NEW_LINE> exponent = EXPONENTS.get(label, MAX_EXPONENT) <NEW_LINE> self._set_exponent(exponent) <NEW_LINE> self.emit('value-changed', self.get_bytes())
Widget to choose a file size in the usual units. Works mostly like a GtkSpinButon (and consists of one).
62598fb163d6d428bbee27f8
class Users(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'users' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(250)) <NEW_LINE> email = db.Column(db.String(250), unique=True) <NEW_LINE> _password = db.Column(db.LargeBinary(128)) <NEW_LINE> _salt = db.Column(db.String(128)) <NEW_LINE> @hybrid_property <NEW_LINE> def password(self): <NEW_LINE> <INDENT> return self._password <NEW_LINE> <DEDENT> @password.setter <NEW_LINE> def password(self, value): <NEW_LINE> <INDENT> if self._salt is None: <NEW_LINE> <INDENT> self._salt = os.urandom(128) <NEW_LINE> <DEDENT> self._password = self._hash_password(value) <NEW_LINE> <DEDENT> def is_valid_password(self, password): <NEW_LINE> <INDENT> new_hash = self._hash_password(password) <NEW_LINE> return hmac.compare_digest(new_hash, self._password) <NEW_LINE> <DEDENT> def _hash_password(self, password): <NEW_LINE> <INDENT> pwd = password.encode("utf-8") <NEW_LINE> salt = bytes(self._salt) <NEW_LINE> buff = hashlib.pbkdf2_hmac("sha512", pwd, salt, iterations=100000) <NEW_LINE> return bytes(buff) <NEW_LINE> <DEDENT> def generate_auth_token(self, expiration=600): <NEW_LINE> <INDENT> from app import app <NEW_LINE> s = TimedJSONWebSignatureSerializer(app.config['SECRET_KEY'], expires_in=expiration) <NEW_LINE> return s.dumps({'id': self.id}) <NEW_LINE> <DEDENT> def as_dict(self): <NEW_LINE> <INDENT> user_dict = {c.name: getattr(self, c.name) for c in self.__table__.columns} <NEW_LINE> user_dict.pop('_password') <NEW_LINE> user_dict.pop('_salt') <NEW_LINE> return user_dict <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def verify_auth_token(token, session): <NEW_LINE> <INDENT> from app import app <NEW_LINE> s = TimedJSONWebSignatureSerializer(app.config['SECRET_KEY'], expires_in=600) <NEW_LINE> try: <NEW_LINE> <INDENT> data = s.loads(token) <NEW_LINE> <DEDENT> except SignatureExpired: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> except BadSignature: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> user = session.query(Users).filter_by(Users.id == data['id']).count() > 0 <NEW_LINE> return user <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def email_is_unique(user_email, ignore_id): <NEW_LINE> <INDENT> if not ignore_id: <NEW_LINE> <INDENT> unique_filter = Users.email == user_email <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unique_filter = and_(Users.email == user_email, Users.id != ignore_id) <NEW_LINE> <DEDENT> return db.session.query(Users).filter(unique_filter).count() == 0 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def name_is_unique(user_name, ignore_id): <NEW_LINE> <INDENT> if not ignore_id: <NEW_LINE> <INDENT> unique_filter = Users.name == user_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> unique_filter = and_(Users.name == user_name, Users.id != ignore_id) <NEW_LINE> <DEDENT> return db.session.query(Users).filter(unique_filter).count() == 0
Represents a user of the system. The user is linked to objects that they own and can view.
62598fb1091ae35668704c6c
class MessageMeIfLabel(db.Model): <NEW_LINE> <INDENT> __tablename__ = "messagemeiflabels" <NEW_LINE> messagemeiflabel_id = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> message_me_if_label = db.Column(db.Integer) <NEW_LINE> feature = db.Column(db.Text)
Features for message-me-if labels
62598fb1236d856c2adc9464
class SLPResponse(NamedTuple): <NEW_LINE> <INDENT> packet_id: VarInt <NEW_LINE> json: dict <NEW_LINE> def __bytes__(self): <NEW_LINE> <INDENT> json = dumps(self).encode('latin-1') <NEW_LINE> json_size = len(json) <NEW_LINE> json_size = VarInt(json_size) <NEW_LINE> json_size = bytes(json_size) <NEW_LINE> payload = json_size + json <NEW_LINE> payload = bytes(self.packet_id) + payload <NEW_LINE> payload_size = len(payload) <NEW_LINE> payload_size = VarInt(payload_size) <NEW_LINE> payload_size = bytes(payload_size) <NEW_LINE> return payload_size + payload <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def read(cls, file: IO) -> SLPResponse: <NEW_LINE> <INDENT> total_size = VarInt.read(file) <NEW_LINE> LOGGER.debug('Read total size: %s', total_size) <NEW_LINE> packet_id = VarInt.read(file) <NEW_LINE> LOGGER.debug('Read packet ID: %s', packet_id) <NEW_LINE> json_size = VarInt.read(file) <NEW_LINE> LOGGER.debug('Read JSON size: %s', json_size) <NEW_LINE> json_bytes = file.read(json_size) <NEW_LINE> LOGGER.debug('Read JSON bytes: %s', json_bytes) <NEW_LINE> string = json_bytes.decode('latin-1') <NEW_LINE> json = loads(string) <NEW_LINE> return cls(packet_id, json)
A server list ping response.
62598fb1aad79263cf42e820
class Child(Parent): <NEW_LINE> <INDENT> def __init__(self, name, age, sex): <NEW_LINE> <INDENT> super(Child, self).__init__(name, age) <NEW_LINE> self.sex = sex <NEW_LINE> self.dig = Test(self.age) <NEW_LINE> <DEDENT> def play(self): <NEW_LINE> <INDENT> if self.sex == "Male": <NEW_LINE> <INDENT> self.kid = "boy" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.kid = "girl" <NEW_LINE> <DEDENT> print("There is a %d years old %s who named %s is playing." % (self.age, self.kid, self.name)) <NEW_LINE> self.dig.dig()
This is a class of Child
62598fb126068e7796d4c9a2
class loss(tnn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(loss, self).__init__() <NEW_LINE> self.loss_rating = tnn.BCEWithLogitsLoss() <NEW_LINE> self.loss_category = tnn.CrossEntropyLoss() <NEW_LINE> <DEDENT> def forward(self, ratingOutput, categoryOutput, ratingTarget, categoryTarget): <NEW_LINE> <INDENT> ratingL = self.loss_rating(ratingOutput, ratingTarget.float()) <NEW_LINE> categoryL = self.loss_category(categoryOutput, categoryTarget) <NEW_LINE> total_loss = 0.3*ratingL + 0.7*categoryL <NEW_LINE> return total_loss
Class for creating the loss function. The labels and outputs from your network will be passed to the forward method during training.
62598fb19c8ee82313040198
class Command(BaseCommand): <NEW_LINE> <INDENT> help = 'Export all courses from mongo to the specified data directory' <NEW_LINE> def handle(self, *args, **options): <NEW_LINE> <INDENT> if len(args) != 1: <NEW_LINE> <INDENT> raise CommandError("export requires one argument: <output path>") <NEW_LINE> <DEDENT> output_path = args[0] <NEW_LINE> cs = contentstore() <NEW_LINE> ms = modulestore('direct') <NEW_LINE> root_dir = output_path <NEW_LINE> courses = ms.get_courses() <NEW_LINE> print("%d courses to export:" % len(courses)) <NEW_LINE> cids = [x.id for x in courses] <NEW_LINE> print(cids) <NEW_LINE> for course_id in cids: <NEW_LINE> <INDENT> print("-"*77) <NEW_LINE> print("Exporting course id = {0} to {1}".format(course_id, output_path)) <NEW_LINE> if 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> course_dir = course_id.to_deprecated_string().replace('/', '...') <NEW_LINE> export_to_xml(ms, cs, course_id, root_dir, course_dir, modulestore()) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print("="*30 + "> Oops, failed to export %s" % course_id) <NEW_LINE> print("Error:") <NEW_LINE> print(err)
Export all courses from mongo to the specified data directory
62598fb14e4d562566372473
class PickleStorage(BaseStorage): <NEW_LINE> <INDENT> def _load(self, file_path): <NEW_LINE> <INDENT> with open(enc.syspath(file_path), 'rb') as fh: <NEW_LINE> <INDENT> return pickle.load(fh, encoding='bytes') <NEW_LINE> <DEDENT> <DEDENT> def _dump(self, value, file_path): <NEW_LINE> <INDENT> with open(enc.syspath(file_path), 'wb') as fh: <NEW_LINE> <INDENT> pickle.dump(value, fh, pickle.HIGHEST_PROTOCOL)
Implementation using a very simple standard library serialization module.
62598fb14c3428357761a306
class SignalsTestCase(TestCase): <NEW_LINE> <INDENT> def test_disable_for_loaddata(self): <NEW_LINE> <INDENT> self.top = 0 <NEW_LINE> @disable_for_loaddata <NEW_LINE> def make_top(): <NEW_LINE> <INDENT> self.top += 1 <NEW_LINE> <DEDENT> def call(): <NEW_LINE> <INDENT> return make_top() <NEW_LINE> <DEDENT> call() <NEW_LINE> self.assertEqual(self.top, 1) <NEW_LINE> <DEDENT> def test_ping_directories_handler(self): <NEW_LINE> <INDENT> self.top = 0 <NEW_LINE> def fake_pinger(*ka, **kw): <NEW_LINE> <INDENT> self.top += 1 <NEW_LINE> <DEDENT> import zinnia.ping <NEW_LINE> from zinnia import settings <NEW_LINE> self.original_pinger = zinnia.ping.DirectoryPinger <NEW_LINE> zinnia.ping.DirectoryPinger = fake_pinger <NEW_LINE> params = {'title': 'My entry', 'content': 'My content', 'status': PUBLISHED, 'slug': 'my-entry'} <NEW_LINE> entry = Entry.objects.create(**params) <NEW_LINE> self.assertEqual(entry.is_visible, True) <NEW_LINE> settings.PING_DIRECTORIES = () <NEW_LINE> ping_directories_handler('sender', **{'instance': entry}) <NEW_LINE> self.assertEqual(self.top, 0) <NEW_LINE> settings.PING_DIRECTORIES = ('toto',) <NEW_LINE> settings.SAVE_PING_DIRECTORIES = True <NEW_LINE> ping_directories_handler('sender', **{'instance': entry}) <NEW_LINE> self.assertEqual(self.top, 1) <NEW_LINE> entry.status = DRAFT <NEW_LINE> ping_directories_handler('sender', **{'instance': entry}) <NEW_LINE> self.assertEqual(self.top, 1) <NEW_LINE> zinnia.ping.DirectoryPinger = self.original_pinger <NEW_LINE> <DEDENT> def test_ping_external_urls_handler(self): <NEW_LINE> <INDENT> self.top = 0 <NEW_LINE> def fake_pinger(*ka, **kw): <NEW_LINE> <INDENT> self.top += 1 <NEW_LINE> <DEDENT> import zinnia.ping <NEW_LINE> from zinnia import settings <NEW_LINE> self.original_pinger = zinnia.ping.ExternalUrlsPinger <NEW_LINE> zinnia.ping.ExternalUrlsPinger = fake_pinger <NEW_LINE> params = {'title': 'My entry', 'content': 'My content', 'status': PUBLISHED, 'slug': 'my-entry'} <NEW_LINE> entry = Entry.objects.create(**params) <NEW_LINE> self.assertEqual(entry.is_visible, True) <NEW_LINE> settings.SAVE_PING_EXTERNAL_URLS = False <NEW_LINE> ping_external_urls_handler('sender', **{'instance': entry}) <NEW_LINE> self.assertEqual(self.top, 0) <NEW_LINE> settings.SAVE_PING_EXTERNAL_URLS = True <NEW_LINE> ping_external_urls_handler('sender', **{'instance': entry}) <NEW_LINE> self.assertEqual(self.top, 1) <NEW_LINE> entry.status = 0 <NEW_LINE> ping_external_urls_handler('sender', **{'instance': entry}) <NEW_LINE> self.assertEqual(self.top, 1) <NEW_LINE> zinnia.ping.ExternalUrlsPinger = self.original_pinger
Test cases for signals
62598fb130bbd7224646999f
class Timeout: <NEW_LINE> <INDENT> default = TimeoutDefault() <NEW_LINE> forever = None <NEW_LINE> maximum = float(2**20) <NEW_LINE> def __init__(self, timeout=default): <NEW_LINE> <INDENT> self._stop = 0 <NEW_LINE> self.timeout = self._get_timeout_seconds(timeout) <NEW_LINE> <DEDENT> @property <NEW_LINE> def timeout(self): <NEW_LINE> <INDENT> timeout = self._timeout <NEW_LINE> stop = self._stop <NEW_LINE> if not stop: <NEW_LINE> <INDENT> return timeout <NEW_LINE> <DEDENT> return max(stop - time.time(), 0) <NEW_LINE> <DEDENT> @timeout.setter <NEW_LINE> def timeout(self, value): <NEW_LINE> <INDENT> assert not self._stop <NEW_LINE> self._timeout = self._get_timeout_seconds(value) <NEW_LINE> self.timeout_change() <NEW_LINE> <DEDENT> def _get_timeout_seconds(self, value): <NEW_LINE> <INDENT> if value is self.default: <NEW_LINE> <INDENT> value = pwnlib.context.context.timeout <NEW_LINE> <DEDENT> elif value is self.forever: <NEW_LINE> <INDENT> value = self.maximum <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = float(value) <NEW_LINE> if value is value < 0: <NEW_LINE> <INDENT> raise AttributeError("timeout: Timeout cannot be negative") <NEW_LINE> <DEDENT> if value > self.maximum: <NEW_LINE> <INDENT> value = self.maximum <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def countdown_active(self): <NEW_LINE> <INDENT> return self._stop == 0 or self._stop > time.time() <NEW_LINE> <DEDENT> def timeout_change(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def countdown(self, timeout=default): <NEW_LINE> <INDENT> if timeout is self.maximum: <NEW_LINE> <INDENT> return _DummyContext <NEW_LINE> <DEDENT> if timeout is self.default and self.timeout is self.maximum: <NEW_LINE> <INDENT> return _DummyContext <NEW_LINE> <DEDENT> if timeout is self.default: <NEW_LINE> <INDENT> timeout = self._timeout <NEW_LINE> <DEDENT> return _countdown_handler(self, timeout) <NEW_LINE> <DEDENT> def local(self, timeout): <NEW_LINE> <INDENT> if timeout is self.default or timeout == self.timeout: <NEW_LINE> <INDENT> return _DummyContext <NEW_LINE> <DEDENT> return _local_handler(self, timeout)
Implements a basic class which has a timeout, and support for scoped timeout countdowns. Valid timeout values are: - ``Timeout.default`` use the global default value (``context.default``) - ``Timeout.forever`` or ``None`` never time out - Any positive float, indicates timeouts in seconds Example: >>> context.timeout = 30 >>> t = Timeout() >>> t.timeout == 30 True >>> t = Timeout(5) >>> t.timeout == 5 True >>> i = 0 >>> with t.countdown(): ... print(4 <= t.timeout <= 5) ... True >>> with t.countdown(0.5): ... while t.timeout: ... print(round(t.timeout, 1)) ... time.sleep(0.1) 0.5 0.4 0.3 0.2 0.1 >>> print(t.timeout) 5.0 >>> with t.local(0.5): ... for i in range(5): ... print(round(t.timeout, 1)) ... time.sleep(0.1) 0.5 0.5 0.5 0.5 0.5 >>> print(t.timeout) 5.0
62598fb14f88993c371f0531
class RelatedObjectInstanceMixin(object): <NEW_LINE> <INDENT> related_object = None <NEW_LINE> related_object_id = None <NEW_LINE> related_object_model_class = None <NEW_LINE> related_object_base_model_class = None <NEW_LINE> def __init__(self, model_admin, instance_pk, related_object_id): <NEW_LINE> <INDENT> super(RelatedObjectInstanceMixin, self).__init__(model_admin, instance_pk) <NEW_LINE> self.related_object_id = related_object_id <NEW_LINE> <DEDENT> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> base_instance = get_object_or_404(self.related_object_base_model_class, pk=self.related_object_id) <NEW_LINE> self.related_object = base_instance.specific <NEW_LINE> self.related_object_model_class = self.related_object.__class__ <NEW_LINE> if self.related_object.object_id != self.instance.pk: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> return super(RelatedObjectInstanceMixin, self).dispatch(request, *args, **kwargs)
Mixin class for working with persisted form field instances
62598fb1d486a94d0ba2c01c
class Department(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=100) <NEW_LINE> budget = models.IntegerField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
author: Harper Frankstone purpose: defines properties associated with the Departments properties: departmentName = builds the department name column in the department table, departmentBudget = builds the department budget column for the the department table, the __str__ method makes the departmentName available to be used in a later foreign key constraint
62598fb155399d3f05626572
class AbstractQueryParameter(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_api_repr(cls, resource): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def to_api_repr(self): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for named / positional query parameters.
62598fb197e22403b383af5b
class DatabaseService(service_filter.ServiceFilter): <NEW_LINE> <INDENT> valid_versions = [service_filter.ValidVersion('v1')] <NEW_LINE> def __init__(self, version=None): <NEW_LINE> <INDENT> super(DatabaseService, self).__init__(service_type='database', version=version)
The database service.
62598fb110dbd63aa1c70c01
class StaClrNginx(StatusLog): <NEW_LINE> <INDENT> def serialization(self): <NEW_LINE> <INDENT> lines = self.status_log <NEW_LINE> data = self.data <NEW_LINE> if_n = True <NEW_LINE> for i in lines: <NEW_LINE> <INDENT> if i.startswith("nginx"): <NEW_LINE> <INDENT> if "latest" in i: <NEW_LINE> <INDENT> start = lines.index(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> while if_n: <NEW_LINE> <INDENT> for i in lines[start:]: <NEW_LINE> <INDENT> if i == '\n': <NEW_LINE> <INDENT> if_n = False <NEW_LINE> end = lines[start:].index(i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for i in lines[start:end + start]: <NEW_LINE> <INDENT> if i.startswith("clearlinux/nginx"): <NEW_LINE> <INDENT> if "latest" in i: <NEW_LINE> <INDENT> num = re.findall("\d+\.?\d*", i) <NEW_LINE> self.exception_to_response(num, "status_Clr_nginx:Total") <NEW_LINE> data.get("status_Clr").get("nginx").update( {"Total": num[-1] + "MB"} ) <NEW_LINE> <DEDENT> <DEDENT> if i.startswith("clearlinux base layer Size:"): <NEW_LINE> <INDENT> num = re.findall("\d+\.?\d*", i) <NEW_LINE> self.exception_to_response(num, "status_Clr_nginx:Base_Layer") <NEW_LINE> data.get("status_Clr").get("nginx").update( {"Base_Layer": num[0]} ) <NEW_LINE> <DEDENT> if i.startswith("clearlinux microservice added layer Size:"): <NEW_LINE> <INDENT> num = re.findall("\d+\.?\d*", i) <NEW_LINE> self.exception_to_response(num, "status_Clr_nginx:MicroService_layer") <NEW_LINE> data.get("status_Clr").get("nginx").update( {"MicroService_layer": num[0]} )
default test_status_nginx long analysis
62598fb1d268445f26639baa
class Router: <NEW_LINE> <INDENT> routing_table = {} <NEW_LINE> @staticmethod <NEW_LINE> def extract_data(packets): <NEW_LINE> <INDENT> data_extracted = {} <NEW_LINE> for packet in packets: <NEW_LINE> <INDENT> downlink_format = Router.__get_downlink_format(packet) <NEW_LINE> if downlink_format in Router.routing_table: <NEW_LINE> <INDENT> packet_decoded = Router.routing_table[downlink_format](packet) <NEW_LINE> if packet_decoded: <NEW_LINE> <INDENT> icao = Router.__get_icao(packet) <NEW_LINE> if icao in data_extracted: <NEW_LINE> <INDENT> data_extracted[icao].update(packet_decoded) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data_extracted[icao] = packet_decoded <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return data_extracted <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __get_downlink_format(packet): <NEW_LINE> <INDENT> return bin2int(packet[0:5]) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __get_icao(packet): <NEW_LINE> <INDENT> return bin2hex(packet[8:32])
This class is responsible for taking a list of binary packets and passing them to the correct Downlink Format handler. When using this class, the routing_table must be populated, mapping Downlink Format numbers to the correct handlers
62598fb1aad79263cf42e821
class Box(Sdf): <NEW_LINE> <INDENT> r <NEW_LINE> def __init__(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def at(): <NEW_LINE> <INDENT> pass
Box aligned with axes
62598fb14e4d562566372474
@base.ReleaseTracks(base.ReleaseTrack.ALPHA) <NEW_LINE> class ExportAlpha(ExportBeta): <NEW_LINE> <INDENT> pass
Export a Google Compute Engine image for Alpha release track.
62598fb191f36d47f2230ece
class LivingSpaceAllocations(dec_base): <NEW_LINE> <INDENT> __tablename__ = 'tb_living_space_allocations' <NEW_LINE> allocation_id = Column(Integer, primary_key=True, autoincrement=True) <NEW_LINE> room_name = Column(String(32), nullable=False) <NEW_LINE> members = Column(String(255)) <NEW_LINE> member_ids = Column(String(255))
Create the rooms table
62598fb144b2445a339b6998
class secp256k1(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.P = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f <NEW_LINE> self.a = 0 <NEW_LINE> self.b = 7 <NEW_LINE> self.N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 <NEW_LINE> self.Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 <NEW_LINE> self.Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 <NEW_LINE> self.G = (self.Gx, self.Gy) <NEW_LINE> self.H = 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def base_point(self): <NEW_LINE> <INDENT> return JacobianPoint(self, self.Gx, self.Gy) <NEW_LINE> <DEDENT> def inverse(self, N): <NEW_LINE> <INDENT> if N == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> lm, hm = 1, 0 <NEW_LINE> low, high = N % self.P, self.P <NEW_LINE> while low > 1: <NEW_LINE> <INDENT> r = high//low <NEW_LINE> nm, new = hm - lm * r, high - low * r <NEW_LINE> lm, low, hm, high = nm, new, lm, low <NEW_LINE> <DEDENT> return lm % self.P <NEW_LINE> <DEDENT> def is_on_curve(self, point): <NEW_LINE> <INDENT> X, Y = point.X, point.Y <NEW_LINE> return ( pow(Y, 2, self.P) - pow(X, 3, self.P) - self.a * X - self.b ) % self.P == 0
Elliptic curve with Secp256k1 standard parameters See https://en.bitcoin.it/wiki/Secp256k1 This is the curve E: y^2 = x^3 + ax + b over Fp P is the characteristic of the finite field G is the base (or generator) point N is a prime number, called the order (number of points in E(Fp)) H is the cofactor
62598fb1cc40096d6161a200
class AaaUserEp(ManagedObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> ManagedObject.__init__(self, "AaaUserEp") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def class_id(): <NEW_LINE> <INDENT> return "aaaUserEp" <NEW_LINE> <DEDENT> DN = "Dn" <NEW_LINE> RN = "Rn" <NEW_LINE> STATUS = "Status"
This class contains the relevant properties and constant supported by this MO.
62598fb1f7d966606f748033
class Frame(amqp_object.AMQPObject): <NEW_LINE> <INDENT> NAME = 'Frame' <NEW_LINE> def __init__(self, frame_type, channel_number): <NEW_LINE> <INDENT> self.frame_type = frame_type <NEW_LINE> self.channel_number = channel_number <NEW_LINE> <DEDENT> def _marshal(self, pieces): <NEW_LINE> <INDENT> payload = ''.join(pieces) <NEW_LINE> return struct.pack('>BHI', self.frame_type, self.channel_number, len(payload)) + payload + chr(spec.FRAME_END) <NEW_LINE> <DEDENT> def marshal(self): <NEW_LINE> <INDENT> raise NotImplementedError
Base Frame object mapping. Defines a behavior for all child classes for assignment of core attributes and implementation of the a core _marshal method which child classes use to create the binary AMQP frame.
62598fb17047854f4633f429
class Permutations_set(Permutations): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def __classcall_private__(cls, s): <NEW_LINE> <INDENT> return super(Permutations_set, cls).__classcall__(cls, tuple(s)) <NEW_LINE> <DEDENT> def __init__(self, s): <NEW_LINE> <INDENT> Permutations.__init__(self, category=FiniteEnumeratedSets()) <NEW_LINE> self._set = s <NEW_LINE> <DEDENT> def __contains__(self, x): <NEW_LINE> <INDENT> s = list(self._set) <NEW_LINE> if len(x) != len(s): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for i in x: <NEW_LINE> <INDENT> if i in s: <NEW_LINE> <INDENT> s.remove(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Permutations of the set %s"%list(self._set) <NEW_LINE> <DEDENT> class Element(ClonableArray): <NEW_LINE> <INDENT> def check(self): <NEW_LINE> <INDENT> if self not in self.parent(): <NEW_LINE> <INDENT> raise ValueError("Invalid permutation") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for p in itertools.permutations(self._set, len(self._set)): <NEW_LINE> <INDENT> yield self.element_class(self, p) <NEW_LINE> <DEDENT> <DEDENT> def cardinality(self): <NEW_LINE> <INDENT> return factorial(len(self._set)) <NEW_LINE> <DEDENT> def random_element(self): <NEW_LINE> <INDENT> return sample(self._set, len(self._set))
Permutations of an arbitrary given finite set. Here, a "permutation of a finite set `S`" means a list of the elements of `S` in which every element of `S` occurs exactly once. This is not to be confused with bijections from `S` to `S`, which are also often called permutations in literature.
62598fb166656f66f7d5a43e
class CardKeyProviderCsv(CardKeyProvider): <NEW_LINE> <INDENT> csv_file = None <NEW_LINE> filename = None <NEW_LINE> def __init__(self, filename: str): <NEW_LINE> <INDENT> self.csv_file = open(filename, 'r') <NEW_LINE> if not self.csv_file: <NEW_LINE> <INDENT> raise RuntimeError("Could not open CSV file '%s'" % filename) <NEW_LINE> <DEDENT> self.filename = filename <NEW_LINE> <DEDENT> def get(self, fields: List[str], key: str, value: str) -> Dict[str, str]: <NEW_LINE> <INDENT> super()._verify_get_data(fields, key, value) <NEW_LINE> self.csv_file.seek(0) <NEW_LINE> cr = csv.DictReader(self.csv_file) <NEW_LINE> if not cr: <NEW_LINE> <INDENT> raise RuntimeError( "Could not open DictReader for CSV-File '%s'" % self.filename) <NEW_LINE> <DEDENT> cr.fieldnames = [field.upper() for field in cr.fieldnames] <NEW_LINE> rc = {} <NEW_LINE> for row in cr: <NEW_LINE> <INDENT> if row[key] == value: <NEW_LINE> <INDENT> for f in fields: <NEW_LINE> <INDENT> if f in row: <NEW_LINE> <INDENT> rc.update({f: row[f]}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError("CSV-File '%s' lacks column '%s'" % (self.filename, f)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return rc
Card key provider implementation that allows to query against a specified CSV file
62598fb1167d2b6e312b6fc0
class RenderParameters(object): <NEW_LINE> <INDENT> def __init__(*args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> baseColor = None <NEW_LINE> showAlphaMask = None <NEW_LINE> unfiltered = None <NEW_LINE> __new__ = None
Provides information on how to render the image.
62598fb15166f23b2e243428
class Sinusoidal(_Transform): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def _get_params(N): <NEW_LINE> <INDENT> A = np.random.uniform(0, 1, N) <NEW_LINE> W = np.random.uniform(0, 0.5, N) <NEW_LINE> F = np.random.uniform(0, np.pi, N) <NEW_LINE> return A, W, F <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _func(A, w, f, X): <NEW_LINE> <INDENT> return A * np.sin(2 * np.pi * w * X + f) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def transform(cls, X): <NEW_LINE> <INDENT> _N = X.shape[0] <NEW_LINE> return np.array(list(map(cls._func, *(cls._get_params(_N) + (X,)))))
Sinusoidal series transformation.
62598fb1627d3e7fe0e06efd
class EventHooks(object): <NEW_LINE> <INDENT> def __init__(self, resource: str, EventType=Event) -> None: <NEW_LINE> <INDENT> self.EventType = EventType <NEW_LINE> self.resource = resource <NEW_LINE> self.events = [] <NEW_LINE> <DEDENT> def _make_and_append(self, event: str, func: EventFuncType) -> None: <NEW_LINE> <INDENT> self.events.append( self.EventType(event, self.resource, func) ) <NEW_LINE> <DEDENT> def event(self, event: Any, func: Optional[EventFuncType]=None ) -> Optional[EventFuncType]: <NEW_LINE> <INDENT> def inner(func: EventFuncType) -> EventFuncType: <NEW_LINE> <INDENT> self._make_and_append(event, func) <NEW_LINE> return func <NEW_LINE> <DEDENT> if isinstance(event, str): <NEW_LINE> <INDENT> return inner if func is None else inner(func) <NEW_LINE> <DEDENT> if isinstance(event, self.EventType): <NEW_LINE> <INDENT> if event.resource != self.resource: <NEW_LINE> <INDENT> raise ValueError('event resource does not match.') <NEW_LINE> <DEDENT> return self.events.append(event) <NEW_LINE> <DEDENT> raise TypeError('{} should be string or {}'.format( event, self.EventType.__name__) ) <NEW_LINE> <DEDENT> def multi_event(self, *events, func: Optional[EventFuncType]=None ) -> Optional[EventFuncType]: <NEW_LINE> <INDENT> def inner(func: EventFuncType) -> EventFuncType: <NEW_LINE> <INDENT> for event in events: <NEW_LINE> <INDENT> self.event(event, func) <NEW_LINE> <DEDENT> return func <NEW_LINE> <DEDENT> return inner(func) if func is not None else inner <NEW_LINE> <DEDENT> def init_api(self, api: Eve) -> None: <NEW_LINE> <INDENT> if not isinstance(api, Eve): <NEW_LINE> <INDENT> raise TypeError(api) <NEW_LINE> <DEDENT> for event in self: <NEW_LINE> <INDENT> event.register(api) <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self) -> Iterable[Any]: <NEW_LINE> <INDENT> return iter(self.events) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "{n}('{r}', EventType={e})".format( n=self.__class__.__name__, r=self.resource, e=self.EventType ) <NEW_LINE> <DEDENT> def __call__(self, *events, func: Optional[EventFuncType]=None) -> Any: <NEW_LINE> <INDENT> def inner(func: EventFuncType): <NEW_LINE> <INDENT> if len(events) == 1: <NEW_LINE> <INDENT> return self.event(events[0], func=func) <NEW_LINE> <DEDENT> return self.multi_event(*events, func=func) <NEW_LINE> <DEDENT> return inner(func) if func is not None else inner
An :class:`Event` container that holds events for a domain resource. :param resource: The domain resource :param EventType: The :class:`Event` class or function for the events of this class.
62598fb1a79ad1619776a0b7
class ResCityZip(models.Model): <NEW_LINE> <INDENT> _name = "res.city.zip" <NEW_LINE> _description = __doc__ <NEW_LINE> _order = "name asc" <NEW_LINE> _rec_name = "display_name" <NEW_LINE> name = fields.Char("ZIP", required=True) <NEW_LINE> city_id = fields.Many2one( "res.city", "City", required=True, auto_join=True, ondelete="cascade", index=True, ) <NEW_LINE> display_name = fields.Char( compute="_compute_new_display_name", store=True, index=True ) <NEW_LINE> _sql_constraints = [ ( "name_city_uniq", "UNIQUE(name, city_id)", "You already have a zip with that code in the same city. " "The zip code must be unique within it's city", ) ] <NEW_LINE> @api.depends("name", "city_id") <NEW_LINE> def _compute_new_display_name(self): <NEW_LINE> <INDENT> for rec in self: <NEW_LINE> <INDENT> name = [rec.name, rec.city_id.name] <NEW_LINE> if rec.city_id.state_id: <NEW_LINE> <INDENT> name.append(rec.city_id.state_id.name) <NEW_LINE> <DEDENT> if rec.city_id.country_id: <NEW_LINE> <INDENT> name.append(rec.city_id.country_id.name) <NEW_LINE> <DEDENT> rec.display_name = ", ".join(name)
City/locations completion object
62598fb1a8370b77170f042b
class NaiveHermiteSpline(HermiteSpline): <NEW_LINE> <INDENT> def __init__(self, knots, values, extrapolation_left='constant', extrapolation_right='constant'): <NEW_LINE> <INDENT> derivatives = np.gradient(values, knots) <NEW_LINE> HermiteSpline.__init__(self, knots, values, derivatives, extrapolation_left, extrapolation_right)
Implements a naive Hermite spline which derivatives the knots are not given but calculated using numpy.gradient.
62598fb155399d3f05626574
class MissingDataError(Exception): <NEW_LINE> <INDENT> pass
Error to be raised if any images are missing key data, like energy or forces.
62598fb1498bea3a75a57b6f
class DescribleL7RulesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Business = None <NEW_LINE> self.Id = None <NEW_LINE> self.RuleIdList = None <NEW_LINE> self.Limit = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Domain = None <NEW_LINE> self.ProtocolList = None <NEW_LINE> self.StatusList = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Business = params.get("Business") <NEW_LINE> self.Id = params.get("Id") <NEW_LINE> self.RuleIdList = params.get("RuleIdList") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> self.Offset = params.get("Offset") <NEW_LINE> self.Domain = params.get("Domain") <NEW_LINE> self.ProtocolList = params.get("ProtocolList") <NEW_LINE> self.StatusList = params.get("StatusList") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
DescribleL7Rules请求参数结构体
62598fb1e1aae11d1e7ce84b
class LMDBDataPointIndexed(MapData): <NEW_LINE> <INDENT> def __init__(self, ds, index=1): <NEW_LINE> <INDENT> def f(dp): <NEW_LINE> <INDENT> dp[index-1:index+1] = loads(dp[index]) <NEW_LINE> return dp <NEW_LINE> <DEDENT> super(LMDBDataPointIndexed, self).__init__(ds, f)
Read a LMDB file and produce deserialized values. This can work with :func:`tensorpack.dataflow.dftools.dump_dataflow_to_lmdb`. The input DS can be processed already (with join, shuffle, etc), so the index of key and val are specified. Further more, there could be multiple LMDB data fused together before local shuffle.
62598fb156b00c62f0fb2905
class StoringException(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.message
Exception raised when storing file
62598fb157b8e32f52508143
class CheckResult(structs_rdf.RDFProtoStruct): <NEW_LINE> <INDENT> protobuf = checks_pb2.CheckResult <NEW_LINE> def __nonzero__(self): <NEW_LINE> <INDENT> return bool(self.anomaly) <NEW_LINE> <DEDENT> def ExtendAnomalies(self, other): <NEW_LINE> <INDENT> for o in other: <NEW_LINE> <INDENT> if o is not None: <NEW_LINE> <INDENT> self.anomaly.Extend(list(o.anomaly))
Results of a single check performed on a host.
62598fb171ff763f4b5e77c1
class WorkThread(QThread): <NEW_LINE> <INDENT> trigger = pyqtSignal() <NEW_LINE> def __int__(self): <NEW_LINE> <INDENT> super(WorkThread, self).__init__() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> os.system( "gnome-terminal -x bash -c 'source ~/catkin_ws/devel/setup.bash; roslaunch ros_car_py car_running.launch'" ) <NEW_LINE> self.trigger.emit()
使用 pyqtsignalo函数创建信号时,信号可以传递多个参数,并指定信号传递参 数的类型,参数类型是标准的 Python数据类型(字符串、日期、布尔类型、数字、 列表、元组和字典)
62598fb17c178a314d78d4ec
class Post(models.Model): <NEW_LINE> <INDENT> comment = models.CharField(max_length=255) <NEW_LINE> latitude = models.CharField(max_length=100) <NEW_LINE> longitude = models.CharField(max_length=100) <NEW_LINE> traffic = models.IntegerField() <NEW_LINE> capacity = models.IntegerField() <NEW_LINE> busline = models.ForeignKey(Busline) <NEW_LINE> date = models.DateField(auto_now=True) <NEW_LINE> time = models.TimeField(auto_now=True) <NEW_LINE> user = models.ForeignKey(BusinemeUser) <NEW_LINE> serialize_fields = ['comment', 'latitude', 'longitude', 'traffic', 'capacity', 'busline', 'date', 'time', 'user'] <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return 'id: %s date: %s %s busline_id: %s' % (self.id, str(self.date), str(self.time), self.busline_id) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def api_all(cls): <NEW_LINE> <INDENT> objects = cls.objects.all() <NEW_LINE> return objects <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def api_filter_contains(cls, busline, limit=None): <NEW_LINE> <INDENT> objects = Post.objects.filter(busline__id=busline.id).order_by( '-date', '-time')[:limit] <NEW_LINE> return objects <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def api_get(cls, post_id): <NEW_LINE> <INDENT> post = cls.objects.get(id=post_id) <NEW_LINE> return post
Post Model.
62598fb1f548e778e596b5f3
class Shuffle: <NEW_LINE> <INDENT> def __init__(self, schema: Schema): <NEW_LINE> <INDENT> self.schema = schema <NEW_LINE> <DEDENT> def _shuffle_within_keyed_list(self, to_shuffle: Dict, path: List) -> Dict: <NEW_LINE> <INDENT> ret: Dict[str, Dict] = OrderedDict() <NEW_LINE> for key, value in to_shuffle.items(): <NEW_LINE> <INDENT> ret[key] = self._shuffle_within_folder(value, path) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def _shuffle_within_list(self, to_shuffle: List, path: List) -> List: <NEW_LINE> <INDENT> ret: List = [None] * len(to_shuffle) <NEW_LINE> for i, child in enumerate(to_shuffle): <NEW_LINE> <INDENT> ret[i] = self._shuffle_within_folder(child, path) <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def _shuffle_within_folder(self, to_shuffle: Optional[Dict], path: List) -> Optional[Dict]: <NEW_LINE> <INDENT> if to_shuffle is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> ret: OrderedDict = OrderedDict() <NEW_LINE> keys: List[str] = list(to_shuffle.keys()) <NEW_LINE> random.shuffle(keys) <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> value: Optional[Any] = to_shuffle[key] <NEW_LINE> key_path = path + [key] <NEW_LINE> var: Optional[Variable] = self.schema.lookup(key_path) <NEW_LINE> if var is None: <NEW_LINE> <INDENT> ret[key] = value <NEW_LINE> <DEDENT> elif value is not None and var.data_type == "Folder": <NEW_LINE> <INDENT> ret[key] = self._shuffle_within_folder(value, key_path) <NEW_LINE> <DEDENT> elif value is not None and var.data_type == "List": <NEW_LINE> <INDENT> ret[key] = self._shuffle_within_list(value, key_path) <NEW_LINE> <DEDENT> elif value is not None and var.data_type == "KeyedList": <NEW_LINE> <INDENT> ret[key] = self._shuffle_within_keyed_list(value, key_path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret[key] = value <NEW_LINE> <DEDENT> <DEDENT> return ret <NEW_LINE> <DEDENT> def __call__(self, to_shuffle: Dict) -> Dict: <NEW_LINE> <INDENT> ret = OrderedDict() <NEW_LINE> keys: List[str] = list(to_shuffle.keys()) <NEW_LINE> random.shuffle(keys) <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> ret[key] = self._shuffle_within_folder(to_shuffle[key], []) <NEW_LINE> <DEDENT> return ret
Inverse of sort -- completely randomize all structure to be sorted
62598fb1d268445f26639bab
class TestLyapunov(object): <NEW_LINE> <INDENT> def test_safe_set_init(self): <NEW_LINE> <INDENT> with tf.Session(): <NEW_LINE> <INDENT> discretization = GridWorld([[0, 1], [0, 1]], 3) <NEW_LINE> lyap_fun = lambda x: tf.reduce_sum(tf.square(x), axis=1) <NEW_LINE> dynamics = LinearSystem(np.array([[1, 0.01], [0., 1.]])) <NEW_LINE> lf = 0.4 <NEW_LINE> lv = 0.3 <NEW_LINE> eps = 0.5 <NEW_LINE> policy = lambda x: 0. * x <NEW_LINE> lyap = Lyapunov(discretization, lyap_fun, dynamics, lf, lv, eps, policy) <NEW_LINE> initial_set = [1, 3] <NEW_LINE> lyap = Lyapunov(discretization, lyap_fun, dynamics, lf, lv, eps, policy, initial_set=initial_set) <NEW_LINE> initial_set = np.array([False, True, False, True, False, False, False, False, False]) <NEW_LINE> assert_equal(initial_set, lyap.safe_set) <NEW_LINE> <DEDENT> <DEDENT> def test_update(self): <NEW_LINE> <INDENT> with tf.Session(): <NEW_LINE> <INDENT> discretization = GridWorld([[-1, 1]], 3) <NEW_LINE> lyap_fun = lambda x: tf.reduce_sum(tf.square(x), axis=1, keep_dims=True) <NEW_LINE> policy = lambda x: -.1 * x <NEW_LINE> dynamics = LinearSystem(np.array([[1, 1.]])) <NEW_LINE> lf = 0.4 <NEW_LINE> lv = 0.3 <NEW_LINE> eps = .5 <NEW_LINE> initial_set = [1] <NEW_LINE> lyap = Lyapunov(discretization, lyap_fun, dynamics, lf, lv, eps, policy, initial_set=initial_set) <NEW_LINE> lyap.update_safe_set() <NEW_LINE> assert_equal(lyap.safe_set, np.array([False, True, False])) <NEW_LINE> eps = 0. <NEW_LINE> lyap = Lyapunov(discretization, lyap_fun, dynamics, lf, lv, eps, policy, initial_set=initial_set) <NEW_LINE> lyap.update_safe_set() <NEW_LINE> assert_equal(lyap.safe_set, np.ones(3, dtype=np.bool))
Test the Lyapunov base class.
62598fb13539df3088ecc302
class Event: <NEW_LINE> <INDENT> def __init__(self, raw): <NEW_LINE> <INDENT> self._raw = raw <NEW_LINE> <DEDENT> @property <NEW_LINE> def raw(self): <NEW_LINE> <INDENT> return self._raw <NEW_LINE> <DEDENT> @property <NEW_LINE> def type_id(self): <NEW_LINE> <INDENT> return self.raw["eventId"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def type_name(self): <NEW_LINE> <INDENT> return EVENT_IDS_TO_TYPES.get(self.type_id, "unknown"), <NEW_LINE> <DEDENT> @property <NEW_LINE> def partition_id(self): <NEW_LINE> <INDENT> partition_id = self.raw["partAssociationCSV"] <NEW_LINE> if partition_id is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return int(partition_id) <NEW_LINE> <DEDENT> @property <NEW_LINE> def time(self): <NEW_LINE> <INDENT> return self.raw["logTime"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> return self.raw["eventText"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.raw["eventName"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def category_id(self): <NEW_LINE> <INDENT> return self.raw["group"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def category_name(self): <NEW_LINE> <INDENT> return self.raw["groupName"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def zone_id(self): <NEW_LINE> <INDENT> if self.raw["sourceType"] == 1: <NEW_LINE> <INDENT> return self.raw["sourceID"] - 1 <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def user_id(self): <NEW_LINE> <INDENT> if self.raw["sourceType"] == 2: <NEW_LINE> <INDENT> return self.raw["sourceID"] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def group(self): <NEW_LINE> <INDENT> if self.type_id in range(118, 122): <NEW_LINE> <INDENT> return GROUP_ID_TO_NAME[self.type_id - 118] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def priority(self): <NEW_LINE> <INDENT> return self.raw["priority"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def source_id(self): <NEW_LINE> <INDENT> return self._source_id
A representation of a Risco event.
62598fb1a8370b77170f042c
@register <NEW_LINE> class StepBackArguments(BaseSchema): <NEW_LINE> <INDENT> __props__ = { "threadId": { "type": "integer", "description": "Execute 'stepBack' for this thread." } } <NEW_LINE> __refs__ = set() <NEW_LINE> __slots__ = list(__props__.keys()) + ['kwargs'] <NEW_LINE> def __init__(self, threadId, update_ids_from_dap=False, **kwargs): <NEW_LINE> <INDENT> self.threadId = threadId <NEW_LINE> if update_ids_from_dap: <NEW_LINE> <INDENT> self.threadId = self._translate_id_from_dap(self.threadId) <NEW_LINE> <DEDENT> self.kwargs = kwargs <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def update_dict_ids_from_dap(cls, dct): <NEW_LINE> <INDENT> if 'threadId' in dct: <NEW_LINE> <INDENT> dct['threadId'] = cls._translate_id_from_dap(dct['threadId']) <NEW_LINE> <DEDENT> return dct <NEW_LINE> <DEDENT> def to_dict(self, update_ids_to_dap=False): <NEW_LINE> <INDENT> threadId = self.threadId <NEW_LINE> if update_ids_to_dap: <NEW_LINE> <INDENT> if threadId is not None: <NEW_LINE> <INDENT> threadId = self._translate_id_to_dap(threadId) <NEW_LINE> <DEDENT> <DEDENT> dct = { 'threadId': threadId, } <NEW_LINE> dct.update(self.kwargs) <NEW_LINE> return dct <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def update_dict_ids_to_dap(cls, dct): <NEW_LINE> <INDENT> if 'threadId' in dct: <NEW_LINE> <INDENT> dct['threadId'] = cls._translate_id_to_dap(dct['threadId']) <NEW_LINE> <DEDENT> return dct
Arguments for 'stepBack' request. Note: automatically generated code. Do not edit manually.
62598fb1cc0a2c111447b062
class Subscription(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.subscribers = [] <NEW_LINE> self.new_data = None <NEW_LINE> self.old_data = None <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.subscribers) <NEW_LINE> <DEDENT> def __getitem__(self, subscriber_number: int): <NEW_LINE> <INDENT> return self.subscribers[subscriber_number] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return (f'Subscribers: {self.subscribers}, New data: {self.new_data},' f' Old data: {self.old_data}') <NEW_LINE> <DEDENT> def subscribe(self, subscriber: KQMLPerformative): <NEW_LINE> <INDENT> self.subscribers.append(subscriber) <NEW_LINE> <DEDENT> def update(self, data: Any): <NEW_LINE> <INDENT> if self.old_data != data: <NEW_LINE> <INDENT> self.new_data = data <NEW_LINE> <DEDENT> <DEDENT> def retire_data(self): <NEW_LINE> <INDENT> self.old_data = self.new_data <NEW_LINE> self.new_data = None
A simple class to handle subscriptions to a pattern, and updating the data associated with it. Attributes: new_data (Any): new data to be used in updating the subscription query pattern (passed along to response_to_query). old_data (Any): copy of the new data after it has been retired, used for only updating new if it differs from the last value. subscribers (list): list of subscription messages to reply to when there is new data
62598fb1a05bb46b3848a8bb
class OrganisationMixin(object): <NEW_LINE> <INDENT> def find_organisations(self): <NEW_LINE> <INDENT> organisations = {} <NEW_LINE> current_user = User.objects.with_id(self.current_user.id) <NEW_LINE> for organisation in self.current_user.organisations: <NEW_LINE> <INDENT> all_projects = Project.objects(organisation=organisation).all() <NEW_LINE> projects = [ project for project in all_projects for team in project.acl if current_user in team.team.members ] <NEW_LINE> organisations[organisation] = projects <NEW_LINE> <DEDENT> return organisations <NEW_LINE> <DEDENT> def find_projects(self, organisation): <NEW_LINE> <INDENT> projects = {} <NEW_LINE> current_user = User.objects.with_id(self.current_user.id) <NEW_LINE> all_projects = Project.objects(organisation=organisation).all() <NEW_LINE> user_projects = [ project for project in all_projects for team in project.acl if current_user in team.team.members ] <NEW_LINE> for project in user_projects: <NEW_LINE> <INDENT> projects[project] = TaskList.objects(project=project).all() <NEW_LINE> <DEDENT> return projects <NEW_LINE> <DEDENT> def find_tasklists(self, organisation, project_slug): <NEW_LINE> <INDENT> tasklists = {} <NEW_LINE> project = Project.objects( organisation=organisation, slug=project_slug ).first() <NEW_LINE> user_tasklists = TaskList.objects(project=project).all() <NEW_LINE> for tasklist in user_tasklists: <NEW_LINE> <INDENT> tasklists[tasklist] = Task.objects(task_list=tasklist).all() <NEW_LINE> <DEDENT> return tasklists <NEW_LINE> <DEDENT> def security_check(self, organisation_slug): <NEW_LINE> <INDENT> for organisation in self.current_user.organisations: <NEW_LINE> <INDENT> if organisation.slug == organisation_slug: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise tornado.web.HTTPError(404) <NEW_LINE> <DEDENT> return organisation
A mixin class
62598fb138b623060ffa90ec
class StoppableThread(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(StoppableThread, self).__init__(*args, **kwargs) <NEW_LINE> self._stop = threading.Event() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self._stop.set() <NEW_LINE> <DEDENT> def stopped(self): <NEW_LINE> <INDENT> self._stop.isSet()
A thread that exposes a stop command to halt execution.
62598fb160cbc95b063643a0
class TestVoltageMap(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 VoltageMap( name = '0', experiment = 'xenonnt', detector = 'tpc', voltages = [ xepmts_staging.models.voltage_map_voltages.VoltageMap_voltages( voltage = 1.337, pmt_index = 56, ) ], created_by = '0', comments = '0', date = '0', id = '0' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return VoltageMap( name = '0', experiment = 'xenonnt', detector = 'tpc', ) <NEW_LINE> <DEDENT> <DEDENT> def testVoltageMap(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)
VoltageMap unit test stubs
62598fb13317a56b869be573
class TestShowVolumeCapability(volume_fakes.TestVolume): <NEW_LINE> <INDENT> capability = volume_fakes.FakeCapability.create_one_capability() <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(TestShowVolumeCapability, self).setUp() <NEW_LINE> self.capability_mock = self.app.client_manager.volume.capabilities <NEW_LINE> self.capability_mock.get.return_value = self.capability <NEW_LINE> self.cmd = volume_backend.ShowCapability(self.app, None) <NEW_LINE> <DEDENT> def test_capability_show(self): <NEW_LINE> <INDENT> arglist = [ 'fake', ] <NEW_LINE> verifylist = [ ('host', 'fake'), ] <NEW_LINE> parsed_args = self.check_parser(self.cmd, arglist, verifylist) <NEW_LINE> columns, data = self.cmd.take_action(parsed_args) <NEW_LINE> expected_columns = [ 'Title', 'Key', 'Type', 'Description', ] <NEW_LINE> self.assertEqual(expected_columns, columns) <NEW_LINE> capabilities = [ 'Compression', 'Replication', 'QoS', 'Thin Provisioning', ] <NEW_LINE> for cap in data: <NEW_LINE> <INDENT> self.assertTrue(cap[0] in capabilities) <NEW_LINE> <DEDENT> self.capability_mock.get.assert_called_with( 'fake', )
Test backend capability functionality.
62598fb15fcc89381b266174
class DriverOutput(object): <NEW_LINE> <INDENT> strip_patterns = [] <NEW_LINE> strip_patterns.append((re.compile('at \(-?[0-9]+,-?[0-9]+\) *'), '')) <NEW_LINE> strip_patterns.append((re.compile('size -?[0-9]+x-?[0-9]+ *'), '')) <NEW_LINE> strip_patterns.append((re.compile('text run width -?[0-9]+: '), '')) <NEW_LINE> strip_patterns.append((re.compile('text run width -?[0-9]+ [a-zA-Z ]+: '), '')) <NEW_LINE> strip_patterns.append((re.compile('RenderButton {BUTTON} .*'), 'RenderButton {BUTTON}')) <NEW_LINE> strip_patterns.append((re.compile('RenderImage {INPUT} .*'), 'RenderImage {INPUT}')) <NEW_LINE> strip_patterns.append((re.compile('RenderBlock {INPUT} .*'), 'RenderBlock {INPUT}')) <NEW_LINE> strip_patterns.append((re.compile('RenderTextControl {INPUT} .*'), 'RenderTextControl {INPUT}')) <NEW_LINE> strip_patterns.append((re.compile('\([0-9]+px'), 'px')) <NEW_LINE> strip_patterns.append((re.compile(' *" *\n +" *'), ' ')) <NEW_LINE> strip_patterns.append((re.compile('" +$'), '"')) <NEW_LINE> strip_patterns.append((re.compile('- '), '-')) <NEW_LINE> strip_patterns.append((re.compile('\s+"\n'), '"\n')) <NEW_LINE> strip_patterns.append((re.compile('scrollWidth [0-9]+'), 'scrollWidth')) <NEW_LINE> strip_patterns.append((re.compile('scrollHeight [0-9]+'), 'scrollHeight')) <NEW_LINE> def __init__(self, text, image, image_hash, audio, crash=False, test_time=0, timeout=False, error='', crashed_process_name='??', crashed_pid=None, crash_log=None): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.image = image <NEW_LINE> self.image_hash = image_hash <NEW_LINE> self.image_diff = None <NEW_LINE> self.audio = audio <NEW_LINE> self.crash = crash <NEW_LINE> self.crashed_process_name = crashed_process_name <NEW_LINE> self.crashed_pid = crashed_pid <NEW_LINE> self.crash_log = crash_log <NEW_LINE> self.test_time = test_time <NEW_LINE> self.timeout = timeout <NEW_LINE> self.error = error <NEW_LINE> <DEDENT> def has_stderr(self): <NEW_LINE> <INDENT> return bool(self.error) <NEW_LINE> <DEDENT> def strip_metrics(self): <NEW_LINE> <INDENT> if not self.text: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for pattern in self.strip_patterns: <NEW_LINE> <INDENT> self.text = re.sub(pattern[0], pattern[1], self.text)
Groups information about a output from driver for easy passing and post-processing of data.
62598fb1dd821e528d6d8f85
class UserSignupSchema(UserSchema): <NEW_LINE> <INDENT> password = SchemaNode( String(), validator=Length(max=30))
Schema definition for user signup.
62598fb166656f66f7d5a440
class MACCORExtractor(BatteryDataExtractor): <NEW_LINE> <INDENT> def group(self, files: Union[str, List[str]], directories: List[str] = None, context: dict = None) -> Iterator[Tuple[str, ...]]: <NEW_LINE> <INDENT> for file in files: <NEW_LINE> <INDENT> if file[-3:].isdigit(): <NEW_LINE> <INDENT> yield file <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def generate_dataframe(self, file: str, file_number: int = 0, start_cycle: int = 0, start_time: int = 0) -> pd.DataFrame: <NEW_LINE> <INDENT> df = pd.read_csv(file, skiprows=1, engine='python', sep='\t') <NEW_LINE> df = df.rename(columns={'DateTime': 'test_time'}) <NEW_LINE> df_out = pd.DataFrame() <NEW_LINE> df_out['cycle_number'] = df['Cyc#'] + start_cycle - df['Cyc#'].min() <NEW_LINE> df_out['cycle_number'] = df_out['cycle_number'].astype('int64') <NEW_LINE> df_out['file_number'] = file_number <NEW_LINE> df_out['test_time'] = df['Test (Min)'] * 60 - df['Test (Min)'][0] * 60 + start_time <NEW_LINE> df_out['state'] = df['State'] <NEW_LINE> df_out['current'] = df['Amps'] <NEW_LINE> df_out['current'] = np.where(df['State'] == 'D', -1 * df_out['current'], df_out['current']) <NEW_LINE> df_out['state'].loc[df_out['state'] == 'R'] = ChargingState.hold <NEW_LINE> df_out['state'].loc[df_out['state'] == 'C'] = ChargingState.charging <NEW_LINE> df_out['state'].loc[df_out['state'] == 'D'] = ChargingState.discharging <NEW_LINE> df_out['state'].loc[df_out['state'] == 'O'] = ChargingState.unknown <NEW_LINE> df_out['state'].loc[df_out['state'] == 'S'] = ChargingState.unknown <NEW_LINE> df_out['voltage'] = df['Volts'] <NEW_LINE> df_out = drop_cycles(df_out) <NEW_LINE> add_steps(df_out) <NEW_LINE> add_method(df_out) <NEW_LINE> add_substeps(df_out) <NEW_LINE> return df_out <NEW_LINE> <DEDENT> def implementors(self) -> List[str]: <NEW_LINE> <INDENT> return ['Kubal, Joesph <kubal@anl.gov>', 'Ward, Logan <lward@anl.gov>'] <NEW_LINE> <DEDENT> def version(self) -> str: <NEW_LINE> <INDENT> return '0.0.1'
Parser for reading from Arbin-format files Expects the files to be in .### format to be an ASCII file
62598fb126068e7796d4c9a6
class SplitLists(Enrich): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> def enrich(self, columns): <NEW_LINE> <INDENT> for column in columns: <NEW_LINE> <INDENT> if column not in self.data.columns: <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> <DEDENT> first_column = list(self.data[columns[0]]) <NEW_LINE> count = 0 <NEW_LINE> append_df = pandas.DataFrame() <NEW_LINE> for cell in first_column: <NEW_LINE> <INDENT> if len(cell) >= 1: <NEW_LINE> <INDENT> df = pandas.DataFrame() <NEW_LINE> for column in columns: <NEW_LINE> <INDENT> df[column] = self.data.loc[count, column] <NEW_LINE> <DEDENT> extra_df = pandas.DataFrame([self.data.loc[count]] * len(df)) <NEW_LINE> for column in columns: <NEW_LINE> <INDENT> extra_df[column] = list(df[column]) <NEW_LINE> <DEDENT> append_df = append_df.append(extra_df, ignore_index=True) <NEW_LINE> extra_df = pandas.DataFrame() <NEW_LINE> <DEDENT> count = count + 1 <NEW_LINE> <DEDENT> self.data = self.data.append(append_df, ignore_index=True) <NEW_LINE> return self.data
This class looks for lists in the given columns and append at the end of the dataframe a row for each entry in those lists.
62598fb1167d2b6e312b6fc2
class newBriquetteTest(MyTest): <NEW_LINE> <INDENT> def briquette_verify(self): <NEW_LINE> <INDENT> LoginPage(self.driver).login('13733333333', '88888888') <NEW_LINE> briquette(self.driver).new_briquette() <NEW_LINE> <DEDENT> def test_newBriquette1(self): <NEW_LINE> <INDENT> self.briquette_verify() <NEW_LINE> time.sleep(1) <NEW_LINE> screen_image(self.driver, '试块送检')
试块送检
62598fb15fdd1c0f98e5dfdd
class PrepareOutputDir(luigi.Task): <NEW_LINE> <INDENT> def output(self): <NEW_LINE> <INDENT> return luigi.LocalTarget("tmp/test.txt")
If invoked, it cleans up existing files. Also, creates required directories.
62598fb13539df3088ecc303
class VirtualNetworkListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[VirtualNetwork]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["VirtualNetwork"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(VirtualNetworkListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link
Response for the ListVirtualNetworks API service call. :param value: Gets a list of VirtualNetwork resources in a resource group. :type value: list[~azure.mgmt.network.v2018_12_01.models.VirtualNetwork] :param next_link: The URL to get the next set of results. :type next_link: str
62598fb1a79ad1619776a0b9
class Object(object): <NEW_LINE> <INDENT> def type(self): <NEW_LINE> <INDENT> affirm(False, u".type isn't overloaded") <NEW_LINE> <DEDENT> @jit.unroll_safe <NEW_LINE> def invoke(self, args): <NEW_LINE> <INDENT> import pixie.vm.stdlib as stdlib <NEW_LINE> return stdlib.invoke_other(self, args) <NEW_LINE> <DEDENT> def int_val(self): <NEW_LINE> <INDENT> affirm(False, u"Expected Number") <NEW_LINE> return 0 <NEW_LINE> <DEDENT> def r_uint_val(self): <NEW_LINE> <INDENT> affirm(False, u"Expected Number") <NEW_LINE> return 0 <NEW_LINE> <DEDENT> def promote(self): <NEW_LINE> <INDENT> return self
Base Object for all VM objects
62598fb14527f215b58e9f26
class WebLiveBackend(object): <NEW_LINE> <INDENT> client = None <NEW_LINE> URL = os.environ.get('SOFTWARE_CENTER_WEBLIVE_HOST', 'https://weblive.stgraber.org/weblive/json') <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.weblive = WebLive(self.URL, True) <NEW_LINE> self.available_servers = [] <NEW_LINE> for client in (WebLiveClientX2GO, WebLiveClientQTNX): <NEW_LINE> <INDENT> if client.is_supported(): <NEW_LINE> <INDENT> self.client = client() <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> self._ready = Event() <NEW_LINE> <DEDENT> @property <NEW_LINE> def ready(self): <NEW_LINE> <INDENT> return self.client and self._ready.is_set() <NEW_LINE> <DEDENT> def query_available(self): <NEW_LINE> <INDENT> self._ready.clear() <NEW_LINE> servers = self.weblive.list_everything() <NEW_LINE> self._ready.set() <NEW_LINE> return servers <NEW_LINE> <DEDENT> def query_available_async(self): <NEW_LINE> <INDENT> def _query_available_helper(): <NEW_LINE> <INDENT> self.available_servers = self.query_available() <NEW_LINE> <DEDENT> p = Thread(target=_query_available_helper) <NEW_LINE> p.start() <NEW_LINE> <DEDENT> def is_pkgname_available_on_server(self, pkgname, serverid=None): <NEW_LINE> <INDENT> for server in self.available_servers: <NEW_LINE> <INDENT> if not serverid or server.name == serverid: <NEW_LINE> <INDENT> for pkg in server.packages: <NEW_LINE> <INDENT> if pkg.pkgname == pkgname: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def get_servers_for_pkgname(self, pkgname): <NEW_LINE> <INDENT> servers = [] <NEW_LINE> for server in self.available_servers: <NEW_LINE> <INDENT> if server.current_users >= server.userlimit: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for pkg in server.packages: <NEW_LINE> <INDENT> if pkg.pkgname == pkgname: <NEW_LINE> <INDENT> servers.append(server) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return servers <NEW_LINE> <DEDENT> def create_automatic_user_and_run_session(self, serverid, session="desktop", wait=False): <NEW_LINE> <INDENT> if os.path.exists('/proc/sys/kernel/random/boot_id'): <NEW_LINE> <INDENT> uuid = open('/proc/sys/kernel/random/boot_id', 'r').read().strip().replace('-', '') <NEW_LINE> random.seed(uuid) <NEW_LINE> <DEDENT> identifier = ''.join(random.choice(string.ascii_lowercase) for x in range(20)) <NEW_LINE> fullname = str(os.environ.get('USER', 'WebLive user')) <NEW_LINE> if not re.match("^[A-Za-z0-9 ]*$", fullname) or len(fullname) == 0: <NEW_LINE> <INDENT> fullname = 'WebLive user' <NEW_LINE> <DEDENT> locale = os.environ.get("LANG", "None").replace("UTF-8", "utf8") <NEW_LINE> connection = self.weblive.create_user(serverid, identifier, fullname, identifier, session, locale) <NEW_LINE> if (self.client): <NEW_LINE> <INDENT> self.client.start_session(connection[0], connection[1], session, identifier, identifier, wait) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise IOError("No remote desktop client available.")
Backend for interacting with the WebLive service
62598fb192d797404e388b8c
class MulledDockerContainerResolver(CliContainerResolver): <NEW_LINE> <INDENT> resolver_type = "mulled" <NEW_LINE> shell = '/bin/bash' <NEW_LINE> protocol: Optional[str] = None <NEW_LINE> def __init__(self, app_info=None, namespace="biocontainers", hash_func="v2", auto_install=True, **kwds): <NEW_LINE> <INDENT> super().__init__(app_info=app_info, **kwds) <NEW_LINE> self.namespace = namespace <NEW_LINE> self.hash_func = hash_func <NEW_LINE> self.auto_install = string_as_bool(auto_install) <NEW_LINE> <DEDENT> def cached_container_description(self, targets, namespace, hash_func, resolution_cache): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return docker_cached_container_description(targets, namespace, hash_func, resolution_cache) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError: <NEW_LINE> <INDENT> log.exception('An error occured while listing cached docker image. Docker daemon may need to be restarted.') <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> def pull(self, container): <NEW_LINE> <INDENT> if self.cli_available: <NEW_LINE> <INDENT> command = container.build_pull_command() <NEW_LINE> shell(command) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def can_list_containers(self): <NEW_LINE> <INDENT> return self.cli_available <NEW_LINE> <DEDENT> def resolve(self, enabled_container_types, tool_info, install=False, session=None, **kwds): <NEW_LINE> <INDENT> resolution_cache = kwds.get("resolution_cache") <NEW_LINE> if tool_info.requires_galaxy_python_environment or self.container_type not in enabled_container_types: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> targets = mulled_targets(tool_info) <NEW_LINE> log.debug(f"Image name for tool {tool_info.tool_id}: {image_name(targets, self.hash_func)}") <NEW_LINE> if len(targets) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> name = targets_to_mulled_name(targets=targets, hash_func=self.hash_func, namespace=self.namespace, resolution_cache=resolution_cache, session=session) <NEW_LINE> if name: <NEW_LINE> <INDENT> container_id = f"quay.io/{self.namespace}/{name}" <NEW_LINE> if self.protocol: <NEW_LINE> <INDENT> container_id = f"{self.protocol}{container_id}" <NEW_LINE> <DEDENT> container_description = ContainerDescription( container_id, type=self.container_type, shell=self.shell, ) <NEW_LINE> if self.can_list_containers: <NEW_LINE> <INDENT> if install and not self.cached_container_description( targets, namespace=self.namespace, hash_func=self.hash_func, resolution_cache=resolution_cache, ): <NEW_LINE> <INDENT> destination_info = {} <NEW_LINE> destination_for_container_type = kwds.get('destination_for_container_type') <NEW_LINE> if destination_for_container_type: <NEW_LINE> <INDENT> destination_info = destination_for_container_type(self.container_type) <NEW_LINE> <DEDENT> container = CONTAINER_CLASSES[self.container_type](container_description.identifier, self.app_info, tool_info, destination_info, {}, container_description) <NEW_LINE> self.pull(container) <NEW_LINE> <DEDENT> if not self.auto_install: <NEW_LINE> <INDENT> container_description = self.cached_container_description( targets, namespace=self.namespace, hash_func=self.hash_func, resolution_cache=resolution_cache, ) or container_description <NEW_LINE> <DEDENT> <DEDENT> return container_description <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"MulledDockerContainerResolver[namespace={self.namespace}]"
Look for mulled images matching tool dependencies.
62598fb1cc0a2c111447b063
class ConfigurationService: <NEW_LINE> <INDENT> def __init__(self, repository, configuration_changed_event): <NEW_LINE> <INDENT> self.repository = repository <NEW_LINE> self.event = configuration_changed_event <NEW_LINE> <DEDENT> def change_path(self, path): <NEW_LINE> <INDENT> self.repository.change_path(path) <NEW_LINE> self.event.publish(path) <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> return self.repository.path
Handle configuration rules
62598fb171ff763f4b5e77c3
class Loader(object): <NEW_LINE> <INDENT> def __init__(self, config_path=None): <NEW_LINE> <INDENT> self.config_path = None <NEW_LINE> config_path = config_path or CONF.api_paste_config <NEW_LINE> if not os.path.isabs(config_path): <NEW_LINE> <INDENT> self.config_path = CONF.find_file(config_path) <NEW_LINE> <DEDENT> elif os.path.exists(config_path): <NEW_LINE> <INDENT> self.config_path = config_path <NEW_LINE> <DEDENT> if not self.config_path: <NEW_LINE> <INDENT> raise exception.ConfigNotFound(path=config_path) <NEW_LINE> <DEDENT> <DEDENT> def load_app(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> LOG.debug(_("Loading app %(name)s from %(path)s") % {'name': name, 'path': self.config_path}) <NEW_LINE> return deploy.loadapp("config:%s" % self.config_path, name=name) <NEW_LINE> <DEDENT> except LookupError as err: <NEW_LINE> <INDENT> LOG.error(err) <NEW_LINE> raise exception.PasteAppNotFound(name=name, path=self.config_path)
Used to load WSGI applications from paste configurations.
62598fb156ac1b37e630223c
class CausalLinearAttention(Module): <NEW_LINE> <INDENT> def __init__(self, query_dimensions, feature_map=None, eps=1e-6, event_dispatcher=""): <NEW_LINE> <INDENT> super(CausalLinearAttention, self).__init__() <NEW_LINE> self.feature_map = ( feature_map(query_dimensions) if feature_map else elu_feature_map(query_dimensions) ) <NEW_LINE> self.eps = eps <NEW_LINE> self.event_dispatcher = EventDispatcher.get(event_dispatcher) <NEW_LINE> <DEDENT> def _make_sizes_compatible(self, Q, K): <NEW_LINE> <INDENT> N, L, H, E = Q.shape <NEW_LINE> _, S, _, _ = K.shape <NEW_LINE> if L == S: <NEW_LINE> <INDENT> return Q, K <NEW_LINE> <DEDENT> if L < S: <NEW_LINE> <INDENT> return Q, K[:, :L, :, :] <NEW_LINE> <DEDENT> if L > S: <NEW_LINE> <INDENT> return Q, torch.cat([K, K.new_zeros(N, L-S, H, E)], dim=1) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, queries, keys, values, attn_mask, query_lengths, key_lengths): <NEW_LINE> <INDENT> self.feature_map.new_feature_map(queries.device) <NEW_LINE> Q = self.feature_map.forward_queries(queries) <NEW_LINE> K = self.feature_map.forward_keys(keys) <NEW_LINE> if not attn_mask.lower_triangular: <NEW_LINE> <INDENT> raise RuntimeError(("CausalLinearAttention only supports full " "lower triangular masks")) <NEW_LINE> <DEDENT> K = K * key_lengths.float_matrix[:, :, None, None] <NEW_LINE> Q, K = self._make_sizes_compatible(Q, K) <NEW_LINE> Z = 1/(torch.einsum("nlhi,nlhi->nlh", Q, K.cumsum(1)) + self.eps) <NEW_LINE> V = causal_linear( Q, K, values ) <NEW_LINE> return V * Z[:, :, :, None]
Implement causally masked attention using dot product of feature maps in O(N D^2) complexity. See fast_transformers.attention.linear_attention.LinearAttention for the general concept of replacing the softmax with feature maps. In addition to that, we also make use of the fact that causal masking is a triangular mask which allows us to apply the masking and still compute the attention in O(N D^2) complexity. Arguments --------- feature_map: callable, a callable that applies the feature map to the last dimension of a tensor (default: elu(x)+1) eps: float, a small number to ensure the numerical stability of the denominator (default: 1e-6) event_dispatcher: str or EventDispatcher instance to be used by this module for dispatching events (default: the default global dispatcher)
62598fb1d7e4931a7ef3c0e6
class TestCMovAverage(TestCase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> TestCase.__init__(self, *args, **kwds) <NEW_LINE> self.data = np.arange(25) <NEW_LINE> self.maskeddata = ma.array(self.data) <NEW_LINE> self.maskeddata[10] = masked <NEW_LINE> <DEDENT> def test_onregulararray(self): <NEW_LINE> <INDENT> data = self.data <NEW_LINE> for width in [3, 5, 7]: <NEW_LINE> <INDENT> k = (width-1)/2 <NEW_LINE> ravg = mf.cmov_average(data, width) <NEW_LINE> self.failUnless(isinstance(ravg, MaskedArray)) <NEW_LINE> assert_equal(ravg, data) <NEW_LINE> assert_equal(ravg._mask, [1]*k+[0]*(len(data)-2*k)+[1]*k) <NEW_LINE> <DEDENT> <DEDENT> def test_onmaskedarray(self): <NEW_LINE> <INDENT> data = self.maskeddata <NEW_LINE> for width in [3, 5, 7]: <NEW_LINE> <INDENT> k = (width-1)/2 <NEW_LINE> ravg = mf.cmov_average(data, width) <NEW_LINE> self.failUnless(isinstance(ravg, MaskedArray)) <NEW_LINE> assert_equal(ravg, data) <NEW_LINE> m = np.zeros(len(data), bool) <NEW_LINE> m[:k] = m[-k:] = m[10-k:10+k+1] = True <NEW_LINE> assert_equal(ravg._mask, m) <NEW_LINE> <DEDENT> <DEDENT> def test_ontimeseries(self): <NEW_LINE> <INDENT> data = ts.time_series(self.maskeddata, start_date=ts.now('D')) <NEW_LINE> for width in [3, 5, 7]: <NEW_LINE> <INDENT> k = (width-1)/2 <NEW_LINE> ravg = mf.cmov_average(data, width) <NEW_LINE> self.failUnless(isinstance(ravg, MaskedArray)) <NEW_LINE> assert_equal(ravg, data) <NEW_LINE> m = np.zeros(len(data), bool) <NEW_LINE> m[:k] = m[-k:] = m[10-k:10+k+1] = True <NEW_LINE> assert_equal(ravg._mask, m) <NEW_LINE> assert_equal(ravg._dates, data._dates) <NEW_LINE> <DEDENT> <DEDENT> def tests_onmultitimeseries(self): <NEW_LINE> <INDENT> maskeddata = MaskedArray(np.random.random(75).reshape(25, 3)) <NEW_LINE> maskeddata[10] = masked <NEW_LINE> data = ts.time_series(maskeddata, start_date=ts.now('D')) <NEW_LINE> for width in [3, 5, 7]: <NEW_LINE> <INDENT> k = (width-1)/2 <NEW_LINE> ravg = mf.cmov_average(data, width) <NEW_LINE> self.failUnless(isinstance(ravg, MaskedArray)) <NEW_LINE> assert_almost_equal(ravg[18].squeeze(), data[18-k:18+k+1]._series.mean(0)) <NEW_LINE> m = np.zeros(data.shape, bool) <NEW_LINE> m[:k] = m[-k:] = m[10-k:10+k+1] = True <NEW_LINE> assert_equal(ravg._mask, m) <NEW_LINE> assert_equal(ravg._dates, data._dates)
Testing Centered Moving Average
62598fb1adb09d7d5dc0a5dc
class Circle: <NEW_LINE> <INDENT> pass
Represents a circle. attributes: center (a Point object), radius.
62598fb1d58c6744b42dc301
class SlideLayouts(ParentedElementProxy): <NEW_LINE> <INDENT> __slots__ = ("_sldLayoutIdLst",) <NEW_LINE> def __init__(self, sldLayoutIdLst, parent): <NEW_LINE> <INDENT> super(SlideLayouts, self).__init__(sldLayoutIdLst, parent) <NEW_LINE> self._sldLayoutIdLst = sldLayoutIdLst <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sldLayoutId = self._sldLayoutIdLst[idx] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise IndexError("slide layout index out of range") <NEW_LINE> <DEDENT> return self.part.related_slide_layout(sldLayoutId.rId) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for sldLayoutId in self._sldLayoutIdLst: <NEW_LINE> <INDENT> yield self.part.related_slide_layout(sldLayoutId.rId) <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._sldLayoutIdLst) <NEW_LINE> <DEDENT> def get_by_name(self, name, default=None): <NEW_LINE> <INDENT> for slide_layout in self: <NEW_LINE> <INDENT> if slide_layout.name == name: <NEW_LINE> <INDENT> return slide_layout <NEW_LINE> <DEDENT> <DEDENT> return default <NEW_LINE> <DEDENT> def index(self, slide_layout): <NEW_LINE> <INDENT> for idx, this_layout in enumerate(self): <NEW_LINE> <INDENT> if slide_layout == this_layout: <NEW_LINE> <INDENT> return idx <NEW_LINE> <DEDENT> <DEDENT> raise ValueError("layout not in this SlideLayouts collection") <NEW_LINE> <DEDENT> def remove(self, slide_layout): <NEW_LINE> <INDENT> if slide_layout.used_by_slides: <NEW_LINE> <INDENT> raise ValueError("cannot remove slide-layout in use by one or more slides") <NEW_LINE> <DEDENT> target_idx = self.index(slide_layout) <NEW_LINE> target_sldLayoutId = self._sldLayoutIdLst.sldLayoutId_lst[target_idx] <NEW_LINE> self._sldLayoutIdLst.remove(target_sldLayoutId) <NEW_LINE> slide_layout.slide_master.part.drop_rel(target_sldLayoutId.rId)
Sequence of slide layouts belonging to a slide-master. Supports indexed access, len(), iteration, index() and remove().
62598fb15fdd1c0f98e5dfde
class TestEsiToken(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 testEsiToken(self): <NEW_LINE> <INDENT> pass
EsiToken unit test stubs
62598fb1cc0a2c111447b064
class LoadBalancerNetworkInterfacesOperations(object): <NEW_LINE> <INDENT> models = _models <NEW_LINE> def __init__(self, client, config, serializer, deserializer): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> self._serialize = serializer <NEW_LINE> self._deserialize = deserializer <NEW_LINE> self._config = config <NEW_LINE> <DEDENT> def list( self, resource_group_name, load_balancer_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2020-07-01" <NEW_LINE> accept = "application/json" <NEW_LINE> def prepare_request(next_link=None): <NEW_LINE> <INDENT> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> if not next_link: <NEW_LINE> <INDENT> url = self.list.metadata['url'] <NEW_LINE> path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> url = next_link <NEW_LINE> query_parameters = {} <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> <DEDENT> return request <NEW_LINE> <DEDENT> def extract_data(pipeline_response): <NEW_LINE> <INDENT> deserialized = self._deserialize('NetworkInterfaceListResult', pipeline_response) <NEW_LINE> list_of_elem = deserialized.value <NEW_LINE> if cls: <NEW_LINE> <INDENT> list_of_elem = cls(list_of_elem) <NEW_LINE> <DEDENT> return deserialized.next_link or None, iter(list_of_elem) <NEW_LINE> <DEDENT> def get_next(next_link=None): <NEW_LINE> <INDENT> request = prepare_request(next_link) <NEW_LINE> pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> raise HttpResponseError(response=response, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> return pipeline_response <NEW_LINE> <DEDENT> return ItemPaged( get_next, extract_data ) <NEW_LINE> <DEDENT> list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/networkInterfaces'}
LoadBalancerNetworkInterfacesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2020_07_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer.
62598fb1f9cc0f698b1c52f3
class WikiThumbAction (BaseAction): <NEW_LINE> <INDENT> stringId = u"WikiThumbnail" <NEW_LINE> def __init__(self, application): <NEW_LINE> <INDENT> self._application = application <NEW_LINE> <DEDENT> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return _(u"Thumbnail") <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return _(u"Insert thumbnail") <NEW_LINE> <DEDENT> def run(self, params): <NEW_LINE> <INDENT> codeEditor = self._application.mainWindow.pagePanel.pageView.codeEditor <NEW_LINE> dlgController = ThumbDialogController(self._application.mainWindow, self._application.selectedPage, codeEditor.GetSelectedText()) <NEW_LINE> if dlgController.showDialog() == wx.ID_OK: <NEW_LINE> <INDENT> codeEditor.replaceText(dlgController.result)
Вставка миниатюры
62598fb144b2445a339b699a
class HybridVisMModes(FreqContainer, MContainer): <NEW_LINE> <INDENT> _axes = ("pol", "ew", "el") <NEW_LINE> _dataset_spec = { "vis": { "axes": ["m", "msign", "pol", "freq", "ew", "el"], "dtype": np.complex64, "initialise": True, "distributed": True, "distributed_axis": "freq", }, "vis_weight": { "axes": ["m", "msign", "pol", "freq", "ew"], "dtype": np.float32, "initialise": True, "distributed": True, "distributed_axis": "freq", }, } <NEW_LINE> @property <NEW_LINE> def vis(self): <NEW_LINE> <INDENT> return self.datasets["vis"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def weight(self): <NEW_LINE> <INDENT> return self.datasets["vis_weight"]
Visibilities beamformed in the NS direction and m-mode transformed in RA. This container has visibilities beam formed only in the NS direction to give a grid in elevation.
62598fb1be383301e025384c
class Language(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.iso3 = None <NEW_LINE> self.wals_code = None <NEW_LINE> self.iso1 = None <NEW_LINE> self.wikicode = None <NEW_LINE> self.wikiname = None <NEW_LINE> self.wikisize = None <NEW_LINE> self.wals_vec = None <NEW_LINE> self.phoible_set = set() <NEW_LINE> self.charfreqs = None <NEW_LINE> self.name = None <NEW_LINE> self.alternate_names = set() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "L:[" + " ".join(map(lambda i: str(i), [self.iso3, self.wals_code, self.wikicode, self.wikiname])) + "]"
Language class. Each language has: * ISO639-1 code (e.g. tr) * ISO639-3 code (e.g. cmn) * wikipedia code (e.g. fr) * wikipedia name (e.g. Waray-Waray) * phoible data * wals data * script data * character frequency data * wikipedia file size
62598fb10c0af96317c563ce
class YearReport(AbstractReport): <NEW_LINE> <INDENT> def __init__(self, year, month_queryset, customer=None): <NEW_LINE> <INDENT> self.settings = ProfileSettings.get_solo() <NEW_LINE> self.customer = customer <NEW_LINE> self.year = year <NEW_LINE> self.months = self.create_months_from_queryset(month_queryset) <NEW_LINE> self.quarters = self.create_quarters() <NEW_LINE> self.currency = self.settings.currency <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def create_months_from_queryset(self, month_queryset): <NEW_LINE> <INDENT> months = {i: MonthReport(month=i, year=self.year, hours=0, fee=Decimal(0.00)) for i in range(1, 13)} <NEW_LINE> for month_report in month_queryset: <NEW_LINE> <INDENT> if self.customer: <NEW_LINE> <INDENT> months[month_report.month] = month_report <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> months[month_report.month] += month_report <NEW_LINE> <DEDENT> <DEDENT> return [y for _, y in months.items()] <NEW_LINE> <DEDENT> def calculate_values(self): <NEW_LINE> <INDENT> for quarter in self.quarters: <NEW_LINE> <INDENT> self.sum_values(quarter) <NEW_LINE> <DEDENT> filled_quarters = self.get_filled_quarters() <NEW_LINE> self.fee = round(self.fee/filled_quarters, 2) <NEW_LINE> <DEDENT> def get_filled_quarters(self): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for quarter in self.quarters: <NEW_LINE> <INDENT> count += 1 if quarter.fee > 0 else 0 <NEW_LINE> <DEDENT> return count if count > 0 else 1 <NEW_LINE> <DEDENT> def create_quarters(self): <NEW_LINE> <INDENT> quarters = [] <NEW_LINE> for i in range(1, 5): <NEW_LINE> <INDENT> quarters.append(self.QuarterReport(i, self.months)) <NEW_LINE> <DEDENT> return quarters <NEW_LINE> <DEDENT> class QuarterReport(AbstractReport): <NEW_LINE> <INDENT> def __init__(self, quarter_number, months): <NEW_LINE> <INDENT> if quarter_number < 1 or quarter_number > 4: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> self.quarter_number = quarter_number <NEW_LINE> self.months = self.filter_quarter(months) <NEW_LINE> super().__init__() <NEW_LINE> <DEDENT> def filter_quarter(self, months): <NEW_LINE> <INDENT> return months[3*self.quarter_number-3:3*self.quarter_number] <NEW_LINE> <DEDENT> def calculate_values(self): <NEW_LINE> <INDENT> for month in self.months: <NEW_LINE> <INDENT> self.sum_values(month) <NEW_LINE> <DEDENT> filled_months = self.get_filled_months() <NEW_LINE> self.fee = round(self.fee/filled_months, 2) <NEW_LINE> <DEDENT> def get_filled_months(self): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for month in self.months: <NEW_LINE> <INDENT> count += 1 if month.fee > 0 else 0 <NEW_LINE> <DEDENT> return count if count > 0 else 1 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{}. {}'.format(self.quarter_number, _('Quarter'))
This class represents a report for one year. It holds the summed up month and quarter values and also the total amount.
62598fb17047854f4633f42d
class MultiWidgetButtons(object): <NEW_LINE> <INDENT> def __init__(self, parent, label, buttons): <NEW_LINE> <INDENT> self.box = gtk.HBox(False, 0) <NEW_LINE> parent.pack_start(self.box, False, False, 0) <NEW_LINE> if label: <NEW_LINE> <INDENT> label = gtk.Label('%s:' % label) <NEW_LINE> label.set_alignment(0, 0.5) <NEW_LINE> self.box.pack_start(label, True, True, 0) <NEW_LINE> <DEDENT> gutils.margin(self.box, 20, 1) <NEW_LINE> for properties in reversed(buttons): <NEW_LINE> <INDENT> icon, tooltip, callback = properties <NEW_LINE> button = gtk.Button() <NEW_LINE> button.set_image(gtk.image_new_from_icon_name(icon, 1)) <NEW_LINE> button.set_relief(gtk.RELIEF_NONE) <NEW_LINE> button.set_tooltip_text(tooltip) <NEW_LINE> button.connect('clicked', lambda x,y=callback: y()) <NEW_LINE> self.box.pack_end(button, False)
Display label and multiple toggle image buttons.
62598fb14e4d562566372478
class login(Page): <NEW_LINE> <INDENT> url= '/' <NEW_LINE> def selectLoginMethod(self): <NEW_LINE> <INDENT> ele0 = self.driver.find_element_by_id('lbNormal') <NEW_LINE> ActionChains(self.driver).move_to_element(ele0).perform() <NEW_LINE> <DEDENT> def switchToFrame(self): <NEW_LINE> <INDENT> self.driver.switch_to.frame('x-URS-iframe') <NEW_LINE> <DEDENT> login_username_loc = (By.NAME, 'email') <NEW_LINE> login_password_loc = (By.NAME, 'password') <NEW_LINE> login_button_loc = (By.ID, 'dologin') <NEW_LINE> def login_username(self, username): <NEW_LINE> <INDENT> self.find_element(*self.login_username_loc).clear() <NEW_LINE> self.find_element(*self.login_username_loc).send_keys(username) <NEW_LINE> <DEDENT> def login_password(self, password): <NEW_LINE> <INDENT> self.find_element(*self.login_password_loc).clear() <NEW_LINE> self.find_element(*self.login_password_loc).send_keys(password) <NEW_LINE> <DEDENT> def login_button(self): <NEW_LINE> <INDENT> self.find_element(*self.login_button_loc).click() <NEW_LINE> <DEDENT> def user_login(self, username = 'username', password = '1111'): <NEW_LINE> <INDENT> self.open() <NEW_LINE> sleep(2) <NEW_LINE> self.switchToFrame() <NEW_LINE> self.login_username(username) <NEW_LINE> self.login_password(password) <NEW_LINE> self.login_button() <NEW_LINE> sleep(4) <NEW_LINE> <DEDENT> def user_login_success(self): <NEW_LINE> <INDENT> ele2 = self.driver.find_element_by_class_name('nui-faceEdit-tips') <NEW_LINE> ActionChains(self.driver).move_to_element(ele2).perform() <NEW_LINE> sleep(2) <NEW_LINE> return (self.driver.find_element_by_class_name('nui-faceEdit-tips').text + '登录成功')
用户登录页面
62598fb132920d7e50bc60a6
class Solver(BasicSolver): <NEW_LINE> <INDENT> def __init__(self, state, **kwargs): <NEW_LINE> <INDENT> self.moves = [] <NEW_LINE> super().__init__(state, **kwargs) <NEW_LINE> <DEDENT> def apply(self, move): <NEW_LINE> <INDENT> self.moves.append(move) <NEW_LINE> super().apply(move) <NEW_LINE> <DEDENT> @property <NEW_LINE> def move_tree(self): <NEW_LINE> <INDENT> moves = self.moves <NEW_LINE> guess_stack = [] <NEW_LINE> pos = 0 <NEW_LINE> while pos < len(moves): <NEW_LINE> <INDENT> if isinstance(moves[pos], Guess): <NEW_LINE> <INDENT> guess_stack.append(pos) <NEW_LINE> <DEDENT> elif isinstance(moves[pos], Backtrack): <NEW_LINE> <INDENT> g = guess_stack.pop() <NEW_LINE> branch = moves[g:pos+1] <NEW_LINE> moves = moves[:g] + [branch] + moves[pos+1:] <NEW_LINE> pos -= len(branch) <NEW_LINE> <DEDENT> pos += 1 <NEW_LINE> <DEDENT> return moves
Keep track of the moves that are applied to the state.
62598fb17b25080760ed7503
class ServicesRolloutsService(base_api.BaseApiService): <NEW_LINE> <INDENT> _NAME = u'services_rollouts' <NEW_LINE> def __init__(self, client): <NEW_LINE> <INDENT> super(ServicemanagementV1.ServicesRolloutsService, self).__init__(client) <NEW_LINE> self._upload_configs = { } <NEW_LINE> <DEDENT> def Create(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Create') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) <NEW_LINE> <DEDENT> Create.method_config = lambda: base_api.ApiMethodInfo( http_method=u'POST', method_id=u'servicemanagement.services.rollouts.create', ordered_params=[u'serviceName'], path_params=[u'serviceName'], query_params=[], relative_path=u'v1/services/{serviceName}/rollouts', request_field='<request>', request_type_name=u'Rollout', response_type_name=u'Operation', supports_download=False, ) <NEW_LINE> def Get(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('Get') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) <NEW_LINE> <DEDENT> Get.method_config = lambda: base_api.ApiMethodInfo( http_method=u'GET', method_id=u'servicemanagement.services.rollouts.get', ordered_params=[u'serviceName', u'rolloutId'], path_params=[u'rolloutId', u'serviceName'], query_params=[], relative_path=u'v1/services/{serviceName}/rollouts/{rolloutId}', request_field='', request_type_name=u'ServicemanagementServicesRolloutsGetRequest', response_type_name=u'Rollout', supports_download=False, ) <NEW_LINE> def List(self, request, global_params=None): <NEW_LINE> <INDENT> config = self.GetMethodConfig('List') <NEW_LINE> return self._RunMethod( config, request, global_params=global_params) <NEW_LINE> <DEDENT> List.method_config = lambda: base_api.ApiMethodInfo( http_method=u'GET', method_id=u'servicemanagement.services.rollouts.list', ordered_params=[u'serviceName'], path_params=[u'serviceName'], query_params=[u'filter', u'pageSize', u'pageToken'], relative_path=u'v1/services/{serviceName}/rollouts', request_field='', request_type_name=u'ServicemanagementServicesRolloutsListRequest', response_type_name=u'ListServiceRolloutsResponse', supports_download=False, )
Service class for the services_rollouts resource.
62598fb1091ae35668704c72
class TestInterpolateRepeats(unittest.TestCase): <NEW_LINE> <INDENT> def test_monotonic(self): <NEW_LINE> <INDENT> repeats = np.array([ 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, ], dtype=np.float32) <NEW_LINE> expected = np.array([ 1., 1.33333333, 1.66666667, 2., 2.5, 3., 3.33333333, 3.66666667, 4., 4.5, 5., 5.25, 5.5, 5.75, 6., 6.25, ], dtype=np.float32) <NEW_LINE> interpolated = _interpolate_repeats(repeats) <NEW_LINE> np.testing.assert_allclose(interpolated, expected) <NEW_LINE> <DEDENT> def test_non_monotonic(self): <NEW_LINE> <INDENT> repeats = np.array([ 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 2, 2, 1, 1, 1, 6, ], dtype=np.float32) <NEW_LINE> expected = np.array([ 1., 1.33333333, 1.66666667, 2., 2.5, 3., 3.33333333, 3.66666667, 4., 3., 2., 1.5, 1., 2.66666667, 4.33333333, 6., ], dtype=np.float32) <NEW_LINE> interpolated = _interpolate_repeats(repeats) <NEW_LINE> np.testing.assert_allclose(interpolated, expected) <NEW_LINE> <DEDENT> def test_with_nans(self): <NEW_LINE> <INDENT> repeats = np.array([ 1, 1, 1, 2, nan, 4, 4, 7, 7, 7, nan, nan, nan, 4, 4, ], dtype=np.float32) <NEW_LINE> expected = np.array([ 1., 1.33333333, 1.66666667, 2., 3., 4., 5.5, 7., 6.5, 6., 5.5, 5., 4.5, 4., 3.5, ], dtype=np.float32) <NEW_LINE> interpolated = _interpolate_repeats(repeats) <NEW_LINE> np.testing.assert_allclose(interpolated, expected) <NEW_LINE> <DEDENT> def test_with_nans_at_start(self): <NEW_LINE> <INDENT> repeats = np.array([ nan, nan, nan, 1, 1, 1, 7, ], dtype=np.float32) <NEW_LINE> expected = np.array([ 1, 2, 3, 4, 5, 6, 7, ], dtype=np.float32) <NEW_LINE> interpolated = _interpolate_repeats(repeats) <NEW_LINE> np.testing.assert_allclose(interpolated, expected) <NEW_LINE> <DEDENT> def test_with_nans_at_end(self): <NEW_LINE> <INDENT> repeats = np.array([ 1, 1, 1, 4, nan, nan, nan, ], dtype=np.float32) <NEW_LINE> expected = np.array([ 1, 2, 3, 4, 5, 6, 7, ], dtype=np.float32) <NEW_LINE> interpolated = _interpolate_repeats(repeats) <NEW_LINE> np.testing.assert_allclose(interpolated, expected)
Test _interpolate_repeats helper function
62598fb1167d2b6e312b6fc4
class Address(BaseModel): <NEW_LINE> <INDENT> user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='addresses', verbose_name='用户') <NEW_LINE> province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_addresses', verbose_name='省') <NEW_LINE> city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_addresses', verbose_name='市') <NEW_LINE> district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_addresses', verbose_name='区') <NEW_LINE> title = models.CharField(max_length=20, verbose_name='地址名称') <NEW_LINE> receiver = models.CharField(max_length=20, verbose_name='收货人') <NEW_LINE> place = models.CharField(max_length=50, verbose_name='地址') <NEW_LINE> mobile = models.CharField(max_length=11, verbose_name='手机') <NEW_LINE> tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话') <NEW_LINE> email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱') <NEW_LINE> is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'tb_address' <NEW_LINE> verbose_name = '用户地址' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> ordering = ['-update_time']
用户地址模型类
62598fb1a79ad1619776a0bb
class VocabularyType(Model): <NEW_LINE> <INDENT> def __init__(self, id: str=None, name: str=None, description: str=None, tags: Dict[str, str]=None): <NEW_LINE> <INDENT> self.openapi_types = { 'id': str, 'name': str, 'description': str, 'tags': Dict[str, str] } <NEW_LINE> self.attribute_map = { 'id': 'id', 'name': 'name', 'description': 'description', 'tags': 'tags' } <NEW_LINE> self._id = id <NEW_LINE> self._name = name <NEW_LINE> self._description = description <NEW_LINE> self._tags = tags <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt: dict) -> 'VocabularyType': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `id`, must not be `None`") <NEW_LINE> <DEDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `name`, must not be `None`") <NEW_LINE> <DEDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._description <NEW_LINE> <DEDENT> @description.setter <NEW_LINE> def description(self, description): <NEW_LINE> <INDENT> if description is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `description`, must not be `None`") <NEW_LINE> <DEDENT> self._description = description <NEW_LINE> <DEDENT> @property <NEW_LINE> def tags(self): <NEW_LINE> <INDENT> return self._tags <NEW_LINE> <DEDENT> @tags.setter <NEW_LINE> def tags(self, tags): <NEW_LINE> <INDENT> self._tags = tags
NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually.
62598fb12c8b7c6e89bd3818
class RepeatSumLayer(lasagne.layers.MergeLayer): <NEW_LINE> <INDENT> def __init__(self, incomings, axis=1, **kwargs): <NEW_LINE> <INDENT> super(RepeatSumLayer, self).__init__(incomings, **kwargs) <NEW_LINE> self.axis = axis <NEW_LINE> <DEDENT> def get_output_shape_for(self, input_shapes): <NEW_LINE> <INDENT> output_shape = [None if None in sizes else max(sizes) for sizes in zip(*input_shapes)] <NEW_LINE> def match(shape1, shape2): <NEW_LINE> <INDENT> axis = self.axis if self.axis >= 0 else len(shape1) + self.axis <NEW_LINE> return (len(shape1) == len(shape2) and all(i == axis or s1 is None or s2 is None or s1 == s2 or s1 == 1 or s2 == 1 for i, (s1, s2) in enumerate(zip(shape1, shape2)))) <NEW_LINE> <DEDENT> if not all(match(shape, output_shape) for shape in input_shapes): <NEW_LINE> <INDENT> raise ValueError("Mismatch: input shapes must be the same except " "for the concatenation axis to be broadcasted.") <NEW_LINE> <DEDENT> return tuple(output_shape) <NEW_LINE> <DEDENT> def get_output_for(self, inputs, **kwargs): <NEW_LINE> <INDENT> output_shape = reduce(T.maximum, (input.shape for input in inputs), inputs[0].shape) <NEW_LINE> def align(input, dim): <NEW_LINE> <INDENT> should_repeat = T.gt(output_shape[dim], input.shape[dim]) <NEW_LINE> repeats = T.switch(should_repeat, output_shape[dim], 1) <NEW_LINE> repeats = T.switch(T.neq(dim, self.axis), repeats, 1) <NEW_LINE> return T.extra_ops.repeat(input, repeats, axis=dim) <NEW_LINE> <DEDENT> aligned = [reduce(align, range(input.ndim), input) for input in inputs] <NEW_LINE> return T.sum(aligned, axis=self.axis)
Sums up multiple inputs along the specified axis. Inputs should have the same shape. Additionally, if a dimension has size 1 it gets broadcasted automatically to the size of the other layers. Parameters ---------- incomings : a list of :class:`Layer` instances or tuples The layers feeding into this layer, or expected input shapes axis : int Axis which inputs are summed up over **kwargs Any additional keyword arguments are passed to the :class:`Layer` superclass.
62598fb13539df3088ecc305
class MovementSpecs(Specs): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def specs_factory(cls): <NEW_LINE> <INDENT> csv_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'feature_metadata', 'movement_features.csv') <NEW_LINE> return super(MovementSpecs, cls).specs_factory(csv_path, MovementSpecs) <NEW_LINE> <DEDENT> def get_data(self, worm_features): <NEW_LINE> <INDENT> data = super(MovementSpecs, self).get_data(worm_features) <NEW_LINE> if self.index is not None and data is not None: <NEW_LINE> <INDENT> data = data[self.index, :] <NEW_LINE> <DEDENT> return data
This class specifies how to treat each movement-related feature when doing histogram processing. Attributes ---------- feature_field : old_feature_field : index : feature_category : is_time_series : bin_width : is_zero_bin : is_signed : name : short_name : units : Notes ---------------- From Matlab comments: TODO: - might need to incorporate seg_worm.w.stats.wormStatsInfo - remove is_time_series entry ...
62598fb18da39b475be03239
class DataMessage(AsyncMessage): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> AsyncMessage.__init__(self) <NEW_LINE> self.identity = None <NEW_LINE> self.operation = None
I am used to transport an operation that occured on a managed object or collection. This class of message is transmitted between clients subscribed to a remote destination as well as between server nodes within a cluster. The payload of this message describes all of the relevant details of the operation. This information is used to replicate updates and detect conflicts. @see: U{DataMessage on Livedocs<http:// livedocs.adobe.com/flex/201/langref/mx/data/messages/DataMessage.html>}
62598fb1009cb60464d01574
class DTIFit(FSLCommand): <NEW_LINE> <INDENT> _cmd = 'dtifit' <NEW_LINE> input_spec = DTIFitInputSpec <NEW_LINE> output_spec = DTIFitOutputSpec <NEW_LINE> def _list_outputs(self): <NEW_LINE> <INDENT> outputs = self.output_spec().get() <NEW_LINE> for k in list(outputs.keys()): <NEW_LINE> <INDENT> if k not in ('outputtype', 'environ', 'args'): <NEW_LINE> <INDENT> if k != 'tensor' or (isdefined(self.inputs.save_tensor) and self.inputs.save_tensor): <NEW_LINE> <INDENT> outputs[k] = self._gen_fname( self.inputs.base_name, suffix='_' + k) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return outputs
Use FSL dtifit command for fitting a diffusion tensor model at each voxel Example ------- >>> from nipype.interfaces import fsl >>> dti = fsl.DTIFit() >>> dti.inputs.dwi = 'diffusion.nii' >>> dti.inputs.bvecs = 'bvecs' >>> dti.inputs.bvals = 'bvals' >>> dti.inputs.base_name = 'TP' >>> dti.inputs.mask = 'mask.nii' >>> dti.cmdline # doctest: +ALLOW_UNICODE 'dtifit -k diffusion.nii -o TP -m mask.nii -r bvecs -b bvals'
62598fb171ff763f4b5e77c5
class AdminUserChangeForm(forms.ModelForm): <NEW_LINE> <INDENT> password = ReadOnlyPasswordHashField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Account <NEW_LINE> fields = ('username', 'email', 'password', 'name', 'is_active', 'is_staff', 'is_admin') <NEW_LINE> <DEDENT> def clean_password(self): <NEW_LINE> <INDENT> return self.initial["password"]
A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field.
62598fb156b00c62f0fb2909
class Producto(models.Model): <NEW_LINE> <INDENT> marca=models.CharField(max_length=50) <NEW_LINE> nombre=models.CharField(max_length=50) <NEW_LINE> foto=models.ImageField(upload_to='foto/') <NEW_LINE> precio=models.IntegerField() <NEW_LINE> caracteristica = models.CharField(max_length=200, blank=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.nombre <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('producto-list')
Producto
62598fb1e1aae11d1e7ce84d
class GpibInstrument(Instrument): <NEW_LINE> <INDENT> def __init__(self, gpib_identifier, board_number=0, **keyw): <NEW_LINE> <INDENT> warn_for_invalid_kwargs(keyw, Instrument.ALL_KWARGS.keys()) <NEW_LINE> if isinstance(gpib_identifier, int): <NEW_LINE> <INDENT> resource_name = "GPIB%d::%d" % (board_number, gpib_identifier) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resource_name = gpib_identifier <NEW_LINE> <DEDENT> super(GpibInstrument, self).__init__(resource_name, **keyw) <NEW_LINE> if self.interface_type != VI_INTF_GPIB: <NEW_LINE> <INDENT> raise ValueError("device is not a GPIB instrument") <NEW_LINE> <DEDENT> self.visalib.enable_event(self.session, VI_EVENT_SERVICE_REQ, VI_QUEUE) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self.session is not None: <NEW_LINE> <INDENT> self.__switch_events_off() <NEW_LINE> super(GpibInstrument, self).__del__() <NEW_LINE> <DEDENT> <DEDENT> def __switch_events_off(self): <NEW_LINE> <INDENT> self.visalib.disable_event(self.session, VI_ALL_ENABLED_EVENTS, VI_ALL_MECH) <NEW_LINE> self.visalib.vpp43.discard_events(self.session, VI_ALL_ENABLED_EVENTS, VI_ALL_MECH) <NEW_LINE> <DEDENT> def wait_for_srq(self, timeout=25): <NEW_LINE> <INDENT> lib = self.visalib <NEW_LINE> lib.enable_event(self.session, VI_EVENT_SERVICE_REQ, VI_QUEUE) <NEW_LINE> if timeout and not(0 <= timeout <= 4294967): <NEW_LINE> <INDENT> raise ValueError("timeout value is invalid") <NEW_LINE> <DEDENT> starting_time = time.clock() <NEW_LINE> while True: <NEW_LINE> <INDENT> if timeout is None: <NEW_LINE> <INDENT> adjusted_timeout = VI_TMO_INFINITE <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> adjusted_timeout = int((starting_time + timeout - time.clock()) * 1000) <NEW_LINE> if adjusted_timeout < 0: <NEW_LINE> <INDENT> adjusted_timeout = 0 <NEW_LINE> <DEDENT> <DEDENT> event_type, context = lib.wait_on_event(self.session, VI_EVENT_SERVICE_REQ, adjusted_timeout) <NEW_LINE> lib.close(context) <NEW_LINE> if self.stb & 0x40: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> lib.discard_events(self.session, VI_EVENT_SERVICE_REQ, VI_QUEUE) <NEW_LINE> <DEDENT> @property <NEW_LINE> def stb(self): <NEW_LINE> <INDENT> return self.visalib.read_stb(self.session)
Class for GPIB instruments. This class extents the Instrument class with special operations and properties of GPIB instruments. :param gpib_identifier: strings are interpreted as instrument's VISA resource name. Numbers are interpreted as GPIB number. :param board_number: the number of the GPIB bus. Further keyword arguments are passed to the constructor of class Instrument.
62598fb17c178a314d78d4f0
class TouchSS(IMP.ScoreState): <NEW_LINE> <INDENT> def __init__(self, m, pi, k): <NEW_LINE> <INDENT> IMP.ScoreState.__init__(self, m, "TouchSS") <NEW_LINE> self.pi = pi <NEW_LINE> self.k = k <NEW_LINE> <DEDENT> def do_before_evaluate(self): <NEW_LINE> <INDENT> self.get_model().set_attribute(self.k, self.pi, 1) <NEW_LINE> <DEDENT> def get_type_name(self): <NEW_LINE> <INDENT> return "TouchSS" <NEW_LINE> <DEDENT> def do_after_evaluate(self, accum): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_version_info(self): <NEW_LINE> <INDENT> return IMP.get_module_version_info() <NEW_LINE> <DEDENT> def do_get_inputs(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def do_get_outputs(self): <NEW_LINE> <INDENT> return [self.get_model().get_particle(self.pi)]
ScoreState that logs all calls
62598fb185dfad0860cbfa9d
class DeviceAPI(API): <NEW_LINE> <INDENT> device: Device <NEW_LINE> def __init__(self, db_factory: Callable, pin_spec: PinSpec) -> None: <NEW_LINE> <INDENT> super().__init__(db_factory) <NEW_LINE> self.device = Device(pin_spec) <NEW_LINE> <DEDENT> async def _feed_fish(self, db: Database, feeding): <NEW_LINE> <INDENT> tasks = (self.device.pulse_led(), self.device.turn_motor(db.get_feed_angle())) <NEW_LINE> await asyncio.gather(*tasks) <NEW_LINE> super()._feed_fish(db, feeding)
An API implementation tied to the fish feeder hardware. Attributes: device: A Device instance to control the hardware
62598fb1f548e778e596b5f7
class DeleteCcnResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.RequestId = params.get("RequestId")
DeleteCcn返回参数结构体
62598fb13317a56b869be575
class Conducteur(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'conducteurs' <NEW_LINE> telephone = db.Column(db.String, primary_key=True) <NEW_LINE> email = db.Column(db.String, unique=True) <NEW_LINE> prenom = db.Column(db.String) <NEW_LINE> nom = db.Column(db.String) <NEW_LINE> libre = db.Column(db.Boolean) <NEW_LINE> station = db.Column(db.String, db.ForeignKey('stations.nom')) <NEW_LINE> position = db.Column(Geometry('POINT')) <NEW_LINE> adresse = db.Column(db.Integer, db.ForeignKey('adresses.identifiant')) <NEW_LINE> inscription = db.Column(db.DateTime)
Un conducteur de taxi.
62598fb15fdd1c0f98e5dfe0
class OrganizationOnboardingTask(Model): <NEW_LINE> <INDENT> __core__ = False <NEW_LINE> TASK_CHOICES = ( (OnboardingTask.FIRST_EVENT, 'First event'), (OnboardingTask.INVITE_MEMBER, 'Invite member'), (OnboardingTask.ISSUE_TRACKER, 'Issue tracker'), (OnboardingTask.NOTIFICATION_SERVICE, 'Notification services'), (OnboardingTask.SECOND_PLATFORM, 'Second platform'), (OnboardingTask.USER_CONTEXT, 'User context'), (OnboardingTask.SOURCEMAPS, 'Upload sourcemaps'), (OnboardingTask.RELEASE_TRACKING, 'Release tracking'), (OnboardingTask.USER_REPORTS, 'User reports'), ) <NEW_LINE> STATUS_CHOICES = ( (OnboardingTaskStatus.COMPLETE, 'Complete'), (OnboardingTaskStatus.PENDING, 'Pending'), (OnboardingTaskStatus.SKIPPED, 'Skipped'), ) <NEW_LINE> organization = FlexibleForeignKey('sentry.Organization') <NEW_LINE> user = FlexibleForeignKey(settings.AUTH_USER_MODEL, null=True) <NEW_LINE> task = BoundedPositiveIntegerField(choices=TASK_CHOICES) <NEW_LINE> status = BoundedPositiveIntegerField(choices=STATUS_CHOICES) <NEW_LINE> date_completed = models.DateTimeField(default=timezone.now) <NEW_LINE> project_id = BoundedBigIntegerField(blank=True, null=True) <NEW_LINE> data = JSONField() <NEW_LINE> objects = OrganizationOnboardingTaskManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> app_label = 'sentry' <NEW_LINE> db_table = 'sentry_organizationonboardingtask' <NEW_LINE> unique_together = (('organization', 'task'), ) <NEW_LINE> <DEDENT> __repr__ = sane_repr('organization', 'task')
Onboarding tasks walk new Sentry orgs through basic features of Sentry. data field options (not all tasks have data fields): FIRST_EVENT: { 'platform': 'flask', } INVITE_MEMBER: { 'invited_member': user.id, 'teams': [team.id] } ISSUE_TRACKER | NOTIFICATION_SERVICE: { 'plugin': 'plugin_name' } ISSUE_ASSIGNMENT: { 'assigned_member': user.id } SECOND_PLATFORM: { 'platform': 'javascript' }
62598fb12ae34c7f260ab136
class MediaWikiSignature(Component): <NEW_LINE> <INDENT> _description = cleandoc(__doc__) <NEW_LINE> implements(IWikiPageManipulator) <NEW_LINE> def prepare_wiki_page(self, req, page, fields): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _count_characters(self, text, character): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> max = len(text) <NEW_LINE> while count < max and text[count] == character: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> return count <NEW_LINE> <DEDENT> def validate_wiki_page(self, req, page): <NEW_LINE> <INDENT> startpos = page.text.find('~~~') <NEW_LINE> if startpos >= 0: <NEW_LINE> <INDENT> donetext = page.text[:startpos] <NEW_LINE> searchtext = page.text[startpos:] <NEW_LINE> fullname = req.session.get('name') <NEW_LINE> username = get_reporter_id(req) <NEW_LINE> tzinfo = getattr(req, 'tz', None) <NEW_LINE> now = datetime.now(tzinfo or localtz) <NEW_LINE> today = format_datetime(now, 'iso8601', tzinfo) <NEW_LINE> signatures = {} <NEW_LINE> signatures[3] = ''.join(["-- ", '[[Signature(', username, ', , ', fullname or '', ')]]']) <NEW_LINE> signatures[4] = ''.join(["-- ", '[[Signature(', username, ', ', today, ', ', fullname or '', ')]]']) <NEW_LINE> signatures[5] = ''.join(["-- ", '[[Signature(,', today, ')]]']) <NEW_LINE> sigstart = searchtext.find('~~~') <NEW_LINE> while sigstart >= 0: <NEW_LINE> <INDENT> count = self._count_characters(searchtext[sigstart:], '~') <NEW_LINE> macroCode = signatures.get(count, None) <NEW_LINE> if macroCode: <NEW_LINE> <INDENT> donetext += searchtext[:sigstart] <NEW_LINE> donetext += macroCode <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> donetext += searchtext[:sigstart + count] <NEW_LINE> <DEDENT> searchtext = searchtext[sigstart + count:] <NEW_LINE> sigstart = searchtext.find('~~~') <NEW_LINE> <DEDENT> donetext += searchtext <NEW_LINE> page.text = donetext <NEW_LINE> <DEDENT> return []
[required] Provides the functionality that MediaWiki signatures (`~~~~`) can be used when editing Wiki pages. During the saving of the Wiki page the !MediaWiki signature is replaced by the username and/or the timestamp of the edit. Three different variants are possible: * The `~~~` will be replaced by the username only * The `~~~~` will be replaced by the username and timestamp * The `~~~~~` will be replaced by the timestamp only With all these variants also a separating `--` prefix will automatically be included. The actual showing of the signature is handled by the `[[Signature(...)]]` macro, to be able to show a pretty formatted username and timestamp.
62598fb1be383301e025384e
class MultiProviderNetworks(model_base.BASEV2): <NEW_LINE> <INDENT> __tablename__ = 'nvp_multi_provider_networks' <NEW_LINE> network_id = Column(String(36), ForeignKey('networks.id', ondelete="CASCADE"), primary_key=True) <NEW_LINE> def __init__(self, network_id): <NEW_LINE> <INDENT> self.network_id = network_id
Networks that were provision through multiprovider extension.
62598fb144b2445a339b699b
class PackagePluginManager(PluginManager): <NEW_LINE> <INDENT> PLUGIN_MANIFEST = 'plugins.py' <NEW_LINE> plugin_path = List(Directory) <NEW_LINE> @on_trait_change('plugin_path[]') <NEW_LINE> def _plugin_path_changed(self, obj, trait_name, removed, added): <NEW_LINE> <INDENT> self._update_sys_dot_path(removed, added) <NEW_LINE> self.reset_traits(['_plugins']) <NEW_LINE> <DEDENT> def __plugins_default(self): <NEW_LINE> <INDENT> plugins = [ plugin for plugin in self._harvest_plugins_in_packages() if self._include_plugin(plugin.id) ] <NEW_LINE> logger.debug('package plugin manager found plugins <%s>', plugins) <NEW_LINE> return plugins <NEW_LINE> <DEDENT> def _get_plugins_module(self, package_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> module = __import__( package_name + '.plugins', fromlist=['plugins']) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> module = None <NEW_LINE> <DEDENT> return module <NEW_LINE> <DEDENT> def _harvest_plugins_in_package(self, package_name, package_dirname): <NEW_LINE> <INDENT> plugins_module = self._get_plugins_module(package_name) <NEW_LINE> if plugins_module is not None: <NEW_LINE> <INDENT> factory = getattr(plugins_module, 'get_plugins', None) <NEW_LINE> if factory is not None: <NEW_LINE> <INDENT> plugins = factory() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> plugins = [] <NEW_LINE> logger.debug('Looking for plugins in %s' % package_dirname) <NEW_LINE> for child in File(package_dirname).children or []: <NEW_LINE> <INDENT> if child.ext == '.py' and child.name.endswith('_plugin'): <NEW_LINE> <INDENT> module = __import__( package_name + '.' + child.name, fromlist=[child.name]) <NEW_LINE> atoms = child.name.split('_') <NEW_LINE> capitalized = [atom.capitalize() for atom in atoms] <NEW_LINE> factory_name = ''.join(capitalized) <NEW_LINE> factory = getattr(module, factory_name, None) <NEW_LINE> if factory is not None: <NEW_LINE> <INDENT> plugins.append(factory()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return plugins <NEW_LINE> <DEDENT> def _harvest_plugins_in_packages(self): <NEW_LINE> <INDENT> plugins = [] <NEW_LINE> for dirname in self.plugin_path: <NEW_LINE> <INDENT> for child in File(dirname).children or []: <NEW_LINE> <INDENT> if child.is_package: <NEW_LINE> <INDENT> plugins.extend( self._harvest_plugins_in_package(child.name, child.path)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return plugins <NEW_LINE> <DEDENT> def _update_sys_dot_path(self, removed, added): <NEW_LINE> <INDENT> for dirname in removed: <NEW_LINE> <INDENT> if dirname in sys.path: <NEW_LINE> <INDENT> sys.path.remove(dirname) <NEW_LINE> <DEDENT> <DEDENT> for dirname in added: <NEW_LINE> <INDENT> if dirname not in sys.path: <NEW_LINE> <INDENT> sys.path.append(dirname)
A plugin manager that finds plugins in packages on the 'plugin_path'. All items in 'plugin_path' are directory names and they are all added to 'sys.path' (if not already present). Each directory is then searched for plugins as follows:- a) If the package contains a 'plugins.py' module, then we import it and look for a callable 'get_plugins' that takes no arguments and returns a list of plugins (i.e. instances that implement 'IPlugin'!). b) If the package contains any modules named in the form 'xxx_plugin.py' then the module is imported and if it contains a callable 'XXXPlugin' it is called with no arguments and it must return a single plugin.
62598fb1cc40096d6161a203
class ActionSend(RouteAction): <NEW_LINE> <INDENT> name = 'send' <NEW_LINE> def __init__(self, data, *, crnl: bool = False): <NEW_LINE> <INDENT> if crnl: <NEW_LINE> <INDENT> self.name = 'send-crnl' <NEW_LINE> <DEDENT> super().__init__(data)
Extremely advanced (and dangerous) function allowing you to add raw data to the response.
62598fb163d6d428bbee2800
class Speak: <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> print("{} addon loaded.".format(self.__class__.__name__)) <NEW_LINE> <DEDENT> @commands.has_permissions(manage_messages=True) <NEW_LINE> @commands.command(pass_context=True) <NEW_LINE> async def speak(self, ctx, destination, *, message): <NEW_LINE> <INDENT> await self.bot.delete_message(ctx.message) <NEW_LINE> if len(ctx.message.channel_mentions) > 0: <NEW_LINE> <INDENT> channel = ctx.message.channel_mentions[0] <NEW_LINE> await self.bot.send_message(channel, message)
Give the bot a voice
62598fb1091ae35668704c74
class SubnetListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[Subnet]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["Subnet"]] = None, next_link: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(SubnetListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = next_link
Response for ListSubnets API service callRetrieves all subnet that belongs to a virtual network. :param value: The subnets in a virtual network. :type value: list[~azure.mgmt.network.v2017_06_01.models.Subnet] :param next_link: The URL to get the next set of results. :type next_link: str
62598fb15fcc89381b266176
class GenericResource(Resource): <NEW_LINE> <INDENT> def __init__(self, properties): <NEW_LINE> <INDENT> super(GenericResource, self).__init__("testResource", "testPartition", **properties) <NEW_LINE> for key, value in list(properties.items()): <NEW_LINE> <INDENT> self._data[key] = value <NEW_LINE> <DEDENT> <DEDENT> def scrub_data(self, include_metadata = False): <NEW_LINE> <INDENT> data = copy.deepcopy(self._data) <NEW_LINE> if include_metadata: <NEW_LINE> <INDENT> del data['metadata'] <NEW_LINE> <DEDENT> del data['name'] <NEW_LINE> del data['partition'] <NEW_LINE> return data <NEW_LINE> <DEDENT> def replace_data(self, data): <NEW_LINE> <INDENT> metadata = self._data['metadata'] <NEW_LINE> name = self._data['name'] <NEW_LINE> partition = self._data['partition'] <NEW_LINE> self._data = copy.deepcopy(data) <NEW_LINE> self._data['metadata'] = metadata <NEW_LINE> self._data['name'] = name <NEW_LINE> self._data['partition'] = partition
Mock resource
62598fb1e5267d203ee6b95c
class BaseTAXIIServer: <NEW_LINE> <INDENT> PERSISTENCE_MANAGER_CLASS: ClassVar[Type[BasePersistenceManager]] <NEW_LINE> app: Flask <NEW_LINE> config: dict <NEW_LINE> def __init__(self, config: dict): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.persistence = self.PERSISTENCE_MANAGER_CLASS( server=self, api=initialize_api(config["persistence_api"]) ) <NEW_LINE> <DEDENT> def init_app(self, app: Flask): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.persistence.api.init_app(app) <NEW_LINE> <DEDENT> def get_domain(self, service_id): <NEW_LINE> <INDENT> dynamic_domain = self.persistence.get_domain(service_id) <NEW_LINE> domain = dynamic_domain or self.config.get("domain") <NEW_LINE> return domain <NEW_LINE> <DEDENT> def get_endpoint(self, relative_path: str) -> Optional[Callable[[], Response]]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def handle_internal_error(self, error): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def handle_status_exception(self, error): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def raise_unauthorized(self): <NEW_LINE> <INDENT> raise UnauthorizedException()
Base class for common functionality in taxii* servers.
62598fb1283ffb24f3cf38e1
class XSvbremss(XSAdditiveModel): <NEW_LINE> <INDENT> __function__ = "xsbrmv" <NEW_LINE> def __init__(self, name='vbremss'): <NEW_LINE> <INDENT> self.kT = Parameter(name, 'kT', 3.0, 1.e-2, 100., 0.0, hugeval, 'keV') <NEW_LINE> self.HeovrH = Parameter(name, 'HeovrH', 1.0, 0., 100., 0.0, hugeval, aliases=["HeH"]) <NEW_LINE> self.norm = Parameter(name, 'norm', 1.0, 0.0, 1.0e24, 0.0, hugeval) <NEW_LINE> XSAdditiveModel.__init__(self, name, (self.kT, self.HeovrH, self.norm))
The XSPEC vbremss model: thermal bremsstrahlung. The model is described at [1]_. .. note:: Deprecated in Sherpa 4.10.0 The ``HeH`` parameter has been renamed ``HeovrH`` to match the XSPEC definition. The name ``HeH`` can still be used to access the parameter, but this name will be removed in a future release. Attributes ---------- kT The plasma temperature in keV. HeovrH The ratio n(He) / n(H). norm The normalization of the model: see [1]_ for an explanation of the units. See Also -------- XSbremss, XSzbremss References ---------- .. [1] https://heasarc.gsfc.nasa.gov/xanadu/xspec/manual/XSmodelBremss.html
62598fb1097d151d1a2c1080
class OutputView(webkit.WebView): <NEW_LINE> <INDENT> def __init__(self, theme, source, target, target_display, source_img, target_img): <NEW_LINE> <INDENT> webkit.WebView.__init__(self) <NEW_LINE> self.theme = theme <NEW_LINE> self.last_incoming = None <NEW_LINE> self.ready = False <NEW_LINE> self.pending = [] <NEW_LINE> self.connect('load-finished', self._loading_finished_cb) <NEW_LINE> self.connect('populate-popup', self.on_populate_popup) <NEW_LINE> <DEDENT> def _loading_finished_cb(self, *args): <NEW_LINE> <INDENT> self.ready = True <NEW_LINE> for function in self.pending: <NEW_LINE> <INDENT> self.execute_script(function) <NEW_LINE> <DEDENT> self.execute_script("scrollToBottom()") <NEW_LINE> self.pending = [] <NEW_LINE> <DEDENT> def clear(self, source="", target="", target_display="", source_img="", target_img=""): <NEW_LINE> <INDENT> body = self.theme.get_body(source, target, target_display, source_img, target_img) <NEW_LINE> self.load_string(body, "text/html", "utf-8", "file://" + self.theme.path) <NEW_LINE> self.pending = [] <NEW_LINE> self.ready = False <NEW_LINE> <DEDENT> def add_message(self, msg): <NEW_LINE> <INDENT> if msg.incoming: <NEW_LINE> <INDENT> if self.last_incoming is None: <NEW_LINE> <INDENT> self.last_incoming = False <NEW_LINE> <DEDENT> msg.first = not self.last_incoming <NEW_LINE> html = self.theme.format_incoming(msg) <NEW_LINE> self.last_incoming = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.last_incoming is None: <NEW_LINE> <INDENT> self.last_incoming = True <NEW_LINE> <DEDENT> msg.first = self.last_incoming <NEW_LINE> html = self.theme.format_outgoing(msg) <NEW_LINE> self.last_incoming = False <NEW_LINE> <DEDENT> if msg.first: <NEW_LINE> <INDENT> function = "appendMessage('" + html + "')" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> function = "appendNextMessage('" + html + "')" <NEW_LINE> <DEDENT> self.append(function) <NEW_LINE> <DEDENT> def append(self, function): <NEW_LINE> <INDENT> if self.ready: <NEW_LINE> <INDENT> self.execute_script(function) <NEW_LINE> self.execute_script("scrollToBottom()") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pending.append(function) <NEW_LINE> <DEDENT> <DEDENT> def _set_text(self, text): <NEW_LINE> <INDENT> self._textbox.load_string(text, "text/html", "utf-8", "") <NEW_LINE> self.pending = [] <NEW_LINE> self.ready = False <NEW_LINE> <DEDENT> def _get_text(self): <NEW_LINE> <INDENT> self._textbox.execute_script('oldtitle=document.title;document.title=document.documentElement.innerHTML;') <NEW_LINE> html = self._textbox.get_main_frame().get_title() <NEW_LINE> self._textbox.execute_script('document.title=oldtitle;') <NEW_LINE> return html <NEW_LINE> <DEDENT> text = property(fget=_get_text, fset=_set_text) <NEW_LINE> def on_populate_popup(self, view, menu): <NEW_LINE> <INDENT> for child in menu.get_children(): <NEW_LINE> <INDENT> menu.remove(child)
a class that represents the output widget of a conversation
62598fb166656f66f7d5a444
class BaseParser(LogsterParser): <NEW_LINE> <INDENT> def __init__(self, option_string=None): <NEW_LINE> <INDENT> self.metric = 0 <NEW_LINE> self.reg_compiled = re.compile(self.reg) <NEW_LINE> <DEDENT> def parse_line(self, line): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.reg_compiled.match(line): <NEW_LINE> <INDENT> self.metric += 1 <NEW_LINE> <DEDENT> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise(LogsterParsingException(str(e))) <NEW_LINE> <DEDENT> <DEDENT> def get_state(self, duration): <NEW_LINE> <INDENT> return [ MetricObject("%s.%s" % (socket.gethostname(), self.name), self.metric, self.description), ]
This class is intended to be inherited from. self.reg, self.name, and self.description must be provided by the child class.
62598fb12ae34c7f260ab137
class Test_cfg(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'test_cfg' <NEW_LINE> id = Column(Integer, unique=True, primary_key=True) <NEW_LINE> cfg = Column(String) <NEW_LINE> def __init__(self, cfg): <NEW_LINE> <INDENT> self.cfg = cfg
Test configuration, can be used multiple times.
62598fb1be8e80087fbbf0bb
class language(MessageFilter): <NEW_LINE> <INDENT> def __init__(self, lang: SLT[str]): <NEW_LINE> <INDENT> if isinstance(lang, str): <NEW_LINE> <INDENT> lang = cast(str, lang) <NEW_LINE> self.lang = [lang] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lang = cast(List[str], lang) <NEW_LINE> self.lang = lang <NEW_LINE> <DEDENT> self.name = 'Filters.language({})'.format(self.lang) <NEW_LINE> <DEDENT> def filter(self, message: Message) -> bool: <NEW_LINE> <INDENT> return bool( message.from_user.language_code and any([message.from_user.language_code.startswith(x) for x in self.lang]) )
Filters messages to only allow those which are from users with a certain language code. Note: According to official Telegram API documentation, not every single user has the `language_code` attribute. Do not count on this filter working on all users. Examples: ``MessageHandler(Filters.language("en"), callback_method)`` Args: lang (:class:`telegram.utils.types.SLT[str]`): Which language code(s) to allow through. This will be matched using ``.startswith`` meaning that 'en' will match both 'en_US' and 'en_GB'.
62598fb110dbd63aa1c70c09
class CredentialInputSourceAccess(BaseAccess): <NEW_LINE> <INDENT> model = CredentialInputSource <NEW_LINE> select_related = ('target_credential', 'source_credential') <NEW_LINE> def filtered_queryset(self): <NEW_LINE> <INDENT> return CredentialInputSource.objects.filter( target_credential__in=Credential.accessible_pk_qs(self.user, 'read_role')) <NEW_LINE> <DEDENT> @check_superuser <NEW_LINE> def can_add(self, data): <NEW_LINE> <INDENT> return ( self.check_related('target_credential', Credential, data, role_field='admin_role') and self.check_related('source_credential', Credential, data, role_field='use_role') ) <NEW_LINE> <DEDENT> @check_superuser <NEW_LINE> def can_change(self, obj, data): <NEW_LINE> <INDENT> if self.can_add(data) is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return ( self.user in obj.target_credential.admin_role and self.user in obj.source_credential.use_role ) <NEW_LINE> <DEDENT> @check_superuser <NEW_LINE> def can_delete(self, obj): <NEW_LINE> <INDENT> return self.user in obj.target_credential.admin_role
I can see a CredentialInputSource when: - I can see the associated target_credential I can create/change a CredentialInputSource when: - I'm an admin of the associated target_credential - I have use access to the associated source credential I can delete a CredentialInputSource when: - I'm an admin of the associated target_credential
62598fb13317a56b869be576