code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class Saplings(TreeMaker): <NEW_LINE> <INDENT> __version__ = '0.0.2' <NEW_LINE> extra_branches = ['peaks.left','peaks.hit_time_mean','peaks.top_hitpattern_spread','peaks.area_fraction_top'] <NEW_LINE> def extract_data(self, event): <NEW_LINE> <INDENT> result = dict() <NEW_LINE> if not len(event.interactions): <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> interaction = event.interactions[0] <NEW_LINE> s1 = event.peaks[interaction.s1] <NEW_LINE> s2 = event.peaks[interaction.s2] <NEW_LINE> largest_other_indices = get_largest_indices(event.peaks, exclude_indices=(interaction.s1, interaction.s2)) <NEW_LINE> result['sum_s2s_before_main_s1'] = sum([p.area for p in event.peaks if p.type == 's2' and p.detector == 'tpc' and p.left < s1.left]) <NEW_LINE> result['s1_hit_time_mean'] = s1.hit_time_mean <NEW_LINE> result['largest_other_s2_area_fraction_top'] = float('nan') <NEW_LINE> largest_other_s2_index = largest_other_indices.get('s2', -1) <NEW_LINE> if largest_other_s2_index != -1: <NEW_LINE> <INDENT> pk = event.peaks[largest_other_s2_index] <NEW_LINE> result['largest_other_s2_area_fraction_top'] = pk.area_fraction_top <NEW_LINE> <DEDENT> return result | sum_s2s_before_main_s1: Sum up all the s2 peaks before main s1 peak
s1_hit_time_mean: Hit time mena of main s1 peak
largest_other_s2_area_fraction_top: Area fraction top of largest other s2 | 6259904615baa723494632f5 |
class CommandError(RuntimeError): <NEW_LINE> <INDENT> def __init__(self, message, data=None, status=1, code=None) -> None: <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.message = message <NEW_LINE> self.data = data <NEW_LINE> self.success = False <NEW_LINE> self.status = status <NEW_LINE> self.code = code <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.message | raised if an error occurred while executing a command | 62599046d53ae8145f9197c3 |
class ExceptionContextImpl(ExceptionContext): <NEW_LINE> <INDENT> def __init__(self, exception, sqlalchemy_exception, connection, cursor, statement, parameters, context, is_disconnect): <NEW_LINE> <INDENT> self.connection = connection <NEW_LINE> self.sqlalchemy_exception = sqlalchemy_exception <NEW_LINE> self.original_exception = exception <NEW_LINE> self.execution_context = context <NEW_LINE> self.statement = statement <NEW_LINE> self.parameters = parameters <NEW_LINE> self.is_disconnect = is_disconnect | Implement the :class:`.ExceptionContext` interface. | 6259904671ff763f4b5e8b07 |
class SelectHierarchy(Operator): <NEW_LINE> <INDENT> bl_idname = "object.select_hierarchy" <NEW_LINE> bl_label = "Select Hierarchy" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> direction = EnumProperty( items=(('PARENT', "Parent", ""), ('CHILD', "Child", ""), ), name="Direction", description="Direction to select in the hierarchy", default='PARENT') <NEW_LINE> extend = BoolProperty( name="Extend", description="Extend the existing selection", default=False, ) <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return context.object <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> select_new = [] <NEW_LINE> act_new = None <NEW_LINE> selected_objects = context.selected_objects <NEW_LINE> obj_act = context.object <NEW_LINE> if context.object not in selected_objects: <NEW_LINE> <INDENT> selected_objects.append(context.object) <NEW_LINE> <DEDENT> if self.direction == 'PARENT': <NEW_LINE> <INDENT> for obj in selected_objects: <NEW_LINE> <INDENT> parent = obj.parent <NEW_LINE> if parent: <NEW_LINE> <INDENT> if obj_act == obj: <NEW_LINE> <INDENT> act_new = parent <NEW_LINE> <DEDENT> select_new.append(parent) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for obj in selected_objects: <NEW_LINE> <INDENT> select_new.extend(obj.children) <NEW_LINE> <DEDENT> if select_new: <NEW_LINE> <INDENT> select_new.sort(key=lambda obj_iter: obj_iter.name) <NEW_LINE> act_new = select_new[0] <NEW_LINE> <DEDENT> <DEDENT> if select_new: <NEW_LINE> <INDENT> if not self.extend: <NEW_LINE> <INDENT> bpy.ops.object.select_all(action='DESELECT') <NEW_LINE> <DEDENT> for obj in select_new: <NEW_LINE> <INDENT> obj.select = True <NEW_LINE> <DEDENT> context.scene.objects.active = act_new <NEW_LINE> return {'FINISHED'} <NEW_LINE> <DEDENT> return {'CANCELLED'} | Select object relative to the active object's positionin the hierarchy | 62599046596a897236128f61 |
@attr.s(auto_attribs=True) <NEW_LINE> class Widget: <NEW_LINE> <INDENT> widget: QSignaledWidget = attr.ib(factory=QSignaledWidget) <NEW_LINE> increment: QtWidgets.QPushButton = attr.ib(factory=QtWidgets.QPushButton) <NEW_LINE> decrement: QtWidgets.QPushButton = attr.ib(factory=QtWidgets.QPushButton) <NEW_LINE> label: QtWidgets.QLabel = attr.ib(factory=QtWidgets.QLabel) <NEW_LINE> layout: QtWidgets.QHBoxLayout = attr.ib(factory=QtWidgets.QHBoxLayout) <NEW_LINE> count: int = 0 <NEW_LINE> serving_event: trio.Event = attr.ib(factory=trio.Event) <NEW_LINE> def setup(self, title: str, parent: typing.Optional[QtWidgets.QWidget]) -> None: <NEW_LINE> <INDENT> self.widget.setParent(parent) <NEW_LINE> self.widget.setWindowTitle(title) <NEW_LINE> self.widget.setLayout(self.layout) <NEW_LINE> self.increment.setText("+") <NEW_LINE> self.decrement.setText("-") <NEW_LINE> self.label.setText(str(self.count)) <NEW_LINE> self.layout.addWidget(self.decrement) <NEW_LINE> self.layout.addWidget(self.label) <NEW_LINE> self.layout.addWidget(self.increment) <NEW_LINE> <DEDENT> def increment_count(self) -> None: <NEW_LINE> <INDENT> self.count += 1 <NEW_LINE> self.label.setText(str(self.count)) <NEW_LINE> <DEDENT> def decrement_count(self) -> None: <NEW_LINE> <INDENT> self.count -= 1 <NEW_LINE> self.label.setText(str(self.count)) <NEW_LINE> <DEDENT> async def show(self) -> None: <NEW_LINE> <INDENT> self.widget.show() <NEW_LINE> <DEDENT> async def serve( self, *, task_status: trio_typing.TaskStatus[None] = trio.TASK_STATUS_IGNORED, ) -> None: <NEW_LINE> <INDENT> signals = [ self.decrement.clicked, self.increment.clicked, self.widget.closed, ] <NEW_LINE> async with qtrio.enter_emissions_channel(signals=signals) as emissions: <NEW_LINE> <INDENT> await self.show() <NEW_LINE> task_status.started() <NEW_LINE> self.serving_event.set() <NEW_LINE> async for emission in emissions.channel: <NEW_LINE> <INDENT> if emission.is_from(self.decrement.clicked): <NEW_LINE> <INDENT> self.decrement_count() <NEW_LINE> <DEDENT> elif emission.is_from(self.increment.clicked): <NEW_LINE> <INDENT> self.increment_count() <NEW_LINE> <DEDENT> elif emission.is_from(self.widget.closed): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise qtrio.QTrioException(f"Unexpected emission: {emission}") | A manager for a simple window with increment and decrement buttons to change a
counter which is displayed via a widget in the center. | 6259904607f4c71912bb0796 |
class ContrailRouteTableTest(rbac_base.BaseContrailTest): <NEW_LINE> <INDENT> def _delete_route_table(self, route_id): <NEW_LINE> <INDENT> self.route_client.delete_route_table(route_id) <NEW_LINE> <DEDENT> def _create_route_tables(self): <NEW_LINE> <INDENT> parent_type = 'project' <NEW_LINE> fq_name = ['default-domain', self.tenant_name, data_utils.rand_name('Route')] <NEW_LINE> route_table = self.route_client.create_route_tables( fq_name=fq_name, parent_type=parent_type)['route-table'] <NEW_LINE> self.addCleanup(self._try_delete_resource, self._delete_route_table, route_table['uuid']) <NEW_LINE> return route_table <NEW_LINE> <DEDENT> @rbac_rule_validation.action(service="Contrail", rules=["list_route_tables"]) <NEW_LINE> @decorators.idempotent_id('ca5a5d42-6e49-40e4-a5ac-de07b397b775') <NEW_LINE> def test_list_route_tables(self): <NEW_LINE> <INDENT> self._create_route_tables() <NEW_LINE> with self.override_role(): <NEW_LINE> <INDENT> self.route_client.list_route_tables() <NEW_LINE> <DEDENT> <DEDENT> @rbac_rule_validation.action(service="Contrail", rules=["show_route_table"]) <NEW_LINE> @decorators.idempotent_id('084a2759-991a-4ae2-bde4-8f9915966f6e') <NEW_LINE> def test_show_route_table(self): <NEW_LINE> <INDENT> route_table = self._create_route_tables() <NEW_LINE> with self.override_role(): <NEW_LINE> <INDENT> self.route_client.show_route_table(route_table['uuid']) <NEW_LINE> <DEDENT> <DEDENT> @rbac_rule_validation.action(service="Contrail", rules=["create_route_tables"]) <NEW_LINE> @decorators.idempotent_id('3fab8105-c0be-4c9e-be5f-d2dce4deb921') <NEW_LINE> def test_create_route_tables(self): <NEW_LINE> <INDENT> with self.override_role(): <NEW_LINE> <INDENT> self._create_route_tables() <NEW_LINE> <DEDENT> <DEDENT> @rbac_rule_validation.action(service="Contrail", rules=["update_route_table"]) <NEW_LINE> @decorators.idempotent_id('2acee7ad-843e-40b0-b8f8-a6d90a51c6c8') <NEW_LINE> def test_update_route_table(self): <NEW_LINE> <INDENT> route_table = self._create_route_tables() <NEW_LINE> display_name = data_utils.rand_name('RouteNew') <NEW_LINE> with self.override_role(): <NEW_LINE> <INDENT> self.route_client.update_route_table( route_id=route_table['uuid'], display_name=display_name) <NEW_LINE> <DEDENT> <DEDENT> @rbac_rule_validation.action(service="Contrail", rules=["delete_route_table"]) <NEW_LINE> @decorators.idempotent_id('20a5086c-ec9a-43e0-ae2c-4161c0f4b280') <NEW_LINE> def test_delete_route_table(self): <NEW_LINE> <INDENT> route_table = self._create_route_tables() <NEW_LINE> with self.override_role(): <NEW_LINE> <INDENT> self._delete_route_table(route_table['uuid']) | Test class to test route objects using RBAC roles | 62599046d99f1b3c44d06a04 |
class Gridding(Linop): <NEW_LINE> <INDENT> def __init__(self, oshape, coord, kernel='spline', width=2, param=1): <NEW_LINE> <INDENT> ndim = coord.shape[-1] <NEW_LINE> ishape = list(oshape[:-ndim]) + list(coord.shape[:-1]) <NEW_LINE> self.coord = coord <NEW_LINE> self.kernel = kernel <NEW_LINE> self.width = width <NEW_LINE> self.param = param <NEW_LINE> super().__init__(oshape, ishape) <NEW_LINE> <DEDENT> def _apply(self, input): <NEW_LINE> <INDENT> device = backend.get_device(input) <NEW_LINE> with device: <NEW_LINE> <INDENT> coord = backend.to_device(self.coord, device) <NEW_LINE> return interp.gridding(input, coord, self.oshape, kernel=self.kernel, width=self.width, param=self.param) <NEW_LINE> <DEDENT> <DEDENT> def _adjoint_linop(self): <NEW_LINE> <INDENT> return Interpolate(self.oshape, self.coord, kernel=self.kernel, width=self.width, param=self.param) | Gridding linear operator.
Args:
oshape (tuple of ints): Output shape = batch_shape + pts_shape
ishape (tuple of ints): Input shape = batch_shape + grd_shape
coord (array): Coordinates, values from - nx / 2 to nx / 2 - 1.
ndim can only be 1, 2 or 3. of shape pts_shape + [ndim]
width (float): Width of interp. kernel in grid size.
kernel (str): Interpolation kernel, {'spline', 'kaiser_bessel'}.
param (float): Kernel parameter.
See Also:
:func:`sigpy.gridding` | 62599046d4950a0f3b1117f4 |
class ArgumentParser(object): <NEW_LINE> <INDENT> def start(self): <NEW_LINE> <INDENT> print ('sys.argv') <NEW_LINE> print (sys.argv) <NEW_LINE> parser = argparse.ArgumentParser() <NEW_LINE> parser.add_argument('--level', help='logging level') <NEW_LINE> args = parser.parse_args() <NEW_LINE> if args.level: <NEW_LINE> <INDENT> print('arg: logging level: ' + args.level) <NEW_LINE> <DEDENT> return args.level | Parses input arguments | 6259904663b5f9789fe864d1 |
class Fichier(object): <NEW_LINE> <INDENT> def __init__(self, dossier_source): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fichier_reader = dossier_source.reader(self.nom_fichier) <NEW_LINE> donnees_csv = [] <NEW_LINE> for ligne in fichier_reader: <NEW_LINE> <INDENT> donnees_ligne = self.extraction_ligne(ligne) <NEW_LINE> if donnees_ligne == -1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> donnees_csv.append(donnees_ligne) <NEW_LINE> <DEDENT> self.donnees = donnees_csv <NEW_LINE> self.verifie_date = 0 <NEW_LINE> self.verifie_coherence = 0 <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> Outils.fatal(e, "impossible d'ouvrir le fichier : "+self.nom_fichier) <NEW_LINE> <DEDENT> <DEDENT> def extraction_ligne(self, ligne): <NEW_LINE> <INDENT> num = len(self.cles) <NEW_LINE> if len(ligne) != num: <NEW_LINE> <INDENT> info = self.libelle + ": nombre de colonnes incorrect : " + str(len(ligne)) + ", attendu : " + str(num) <NEW_LINE> Outils.affiche_message(info) <NEW_LINE> sys.exit("Erreur de consistance") <NEW_LINE> <DEDENT> donnees_ligne = {} <NEW_LINE> for xx in range(0, num): <NEW_LINE> <INDENT> donnees_ligne[self.cles[xx]] = ligne[xx] <NEW_LINE> <DEDENT> return donnees_ligne <NEW_LINE> <DEDENT> def verification_date(self, annee, mois): <NEW_LINE> <INDENT> if self.verifie_date == 1: <NEW_LINE> <INDENT> print(self.libelle + ": date déjà vérifiée") <NEW_LINE> return 0 <NEW_LINE> <DEDENT> msg = "" <NEW_LINE> position = 1 <NEW_LINE> for donnee in self.donnees: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if (int(donnee['mois']) != mois) or (int(donnee['annee']) != annee): <NEW_LINE> <INDENT> msg += "date incorrect ligne " + str(position) + "\n" <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> msg += "année ou mois n'est pas valable" + str(position) + "\n" <NEW_LINE> <DEDENT> position += 1 <NEW_LINE> <DEDENT> del self.donnees[0] <NEW_LINE> self.verifie_date = 1 <NEW_LINE> if msg != "": <NEW_LINE> <INDENT> msg = self.libelle + "\n" + msg <NEW_LINE> Outils.affiche_message(msg) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> return 0 | Classe de base des classes d'importation de données
Attributs de classe (à définir dans les sous-classes) :
nom_fichier Le nom relatif du fichier à charger
libelle Un intitulé pour les messages d'erreur
cles La liste des colonnes à charger | 62599046d6c5a102081e3481 |
class DQN(Model): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.original = Network() <NEW_LINE> self.target = Network() <NEW_LINE> <DEDENT> def call(self, x): <NEW_LINE> <INDENT> return self.original(x) <NEW_LINE> <DEDENT> def q_original(self, x): <NEW_LINE> <INDENT> return self.call(x) <NEW_LINE> <DEDENT> def q_target(self, x): <NEW_LINE> <INDENT> return self.target(x) <NEW_LINE> <DEDENT> def copy_original(self): <NEW_LINE> <INDENT> self.target = copy.deepcopy(self.original) | Simple Deep Q-Network for CartPole | 62599046d99f1b3c44d06a05 |
class Verbatim(models.Model): <NEW_LINE> <INDENT> verbatim = models.CharField(max_length=300) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s" % self.verbatim | MODEL
instances of verbatims and associated status | 625990468a43f66fc4bf34fa |
class Vector(Epetra.Vector): <NEW_LINE> <INDENT> def __neg__(self): <NEW_LINE> <INDENT> v = Vector(self) <NEW_LINE> v.Scale(-1.0) <NEW_LINE> return v <NEW_LINE> <DEDENT> def __truediv__(self, scal): <NEW_LINE> <INDENT> v = Vector(self) <NEW_LINE> v.Scale(1.0 / scal) <NEW_LINE> return v <NEW_LINE> <DEDENT> def dot(self, other): <NEW_LINE> <INDENT> return self.Dot(other)[0] <NEW_LINE> <DEDENT> def gather(self): <NEW_LINE> <INDENT> local_elements = [] <NEW_LINE> if self.Comm().MyPID() == 0: <NEW_LINE> <INDENT> local_elements = range(self.Map().NumGlobalElements()) <NEW_LINE> <DEDENT> local_map = Epetra.Map(-1, local_elements, 0, self.Comm()) <NEW_LINE> importer = Epetra.Import(local_map, self.Map()) <NEW_LINE> out = Epetra.Vector(local_map) <NEW_LINE> out.Import(self, importer, Epetra.Insert) <NEW_LINE> return out <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_array(m, x): <NEW_LINE> <INDENT> local_elements = [] <NEW_LINE> if m.Comm().MyPID() == 0: <NEW_LINE> <INDENT> local_elements = range(m.NumGlobalElements()) <NEW_LINE> <DEDENT> local_map = Epetra.Map(-1, local_elements, 0, m.Comm()) <NEW_LINE> importer = Epetra.Import(m, local_map) <NEW_LINE> x_local = Vector(Epetra.Copy, local_map, x) <NEW_LINE> out = Vector(m) <NEW_LINE> out.Import(x_local, importer, Epetra.Insert) <NEW_LINE> return out <NEW_LINE> <DEDENT> size = property(Epetra.Vector.GlobalLength) | Distributed Epetra_Vector with some extra methods added to it for convenience. | 6259904621a7993f00c672cf |
class EventsPublisher(object): <NEW_LINE> <INDENT> def __init__(self, connection_url, routing_key=None): <NEW_LINE> <INDENT> self.connection_url = connection_url <NEW_LINE> self.connection = None <NEW_LINE> self.producer = None <NEW_LINE> self.default_routing_key = routing_key <NEW_LINE> self.exchange = Exchange("events", type="topic") <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.connection = Connection(self.connection_url) <NEW_LINE> self.exchange = self.exchange(self.connection.channel) <NEW_LINE> <DEDENT> def disconnect(self): <NEW_LINE> <INDENT> if self.connection: <NEW_LINE> <INDENT> self.connection.release() <NEW_LINE> self.connection = None <NEW_LINE> self.producer = None <NEW_LINE> <DEDENT> <DEDENT> def log(self, message): <NEW_LINE> <INDENT> logger.info("{0}".format(message)) <NEW_LINE> <DEDENT> def publish(self, message, routing_key=None): <NEW_LINE> <INDENT> if not self.connection: <NEW_LINE> <INDENT> self.connect() <NEW_LINE> <DEDENT> if not self.producer: <NEW_LINE> <INDENT> self.producer = Producer(self.connection, self.exchange) <NEW_LINE> <DEDENT> routing_key = routing_key or self.default_routing_key <NEW_LINE> if not routing_key: <NEW_LINE> <INDENT> raise Exception("Routing key not specified") <NEW_LINE> <DEDENT> self.log("Publishing to exchange {0} with routing key {1}".format( self.exchange, routing_key )) <NEW_LINE> self.producer.publish(message, exchange=self.exchange, routing_key=routing_key) | Generic publisher class that specific publishers inherit from. | 625990466fece00bbacccd1b |
class ProfileAwareConfigLoader(PyFileConfigLoader): <NEW_LINE> <INDENT> def load_subconfig(self, fname, path=None, profile=None): <NEW_LINE> <INDENT> if profile is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), profile, ) <NEW_LINE> <DEDENT> except ProfileDirError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> path = profile_dir.location <NEW_LINE> <DEDENT> return super(ProfileAwareConfigLoader, self).load_subconfig(fname, path=path) | A Python file config loader that is aware of IPython profiles. | 6259904673bcbd0ca4bcb5f3 |
class FakeUnbindPortContext(FakePortContext): <NEW_LINE> <INDENT> @property <NEW_LINE> def top_bound_segment(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def bottom_bound_segment(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def original_top_bound_segment(self): <NEW_LINE> <INDENT> return self._segment <NEW_LINE> <DEDENT> @property <NEW_LINE> def original_bottom_bound_segment(self): <NEW_LINE> <INDENT> return self._bottom_segment | Port context used during migration to unbind port. | 62599046287bf620b6272f4f |
class Display: <NEW_LINE> <INDENT> def __init__(self, initializers: Tuple[str, str] = ("", "")) -> None: <NEW_LINE> <INDENT> self._lcd = LCD.Adafruit_CharLCDPlate() <NEW_LINE> self._log = list(initializers) <NEW_LINE> self._cur_index = 1 <NEW_LINE> self._cur_side_index = 0 <NEW_LINE> self.clear() <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def clear(self) -> None: <NEW_LINE> <INDENT> self._lcd.clear() <NEW_LINE> <DEDENT> def get_on_screen(self) -> Tuple[str, str]: <NEW_LINE> <INDENT> return (self._log[self._cur_index - 1].rstrip(), self._log[self._cur_index].rstrip()) <NEW_LINE> <DEDENT> def _put(self, line1: str, line2: str) -> None: <NEW_LINE> <INDENT> self._lcd.message(line1 + "\n" + line2) <NEW_LINE> <DEDENT> def show(self) -> None: <NEW_LINE> <INDENT> self.clear() <NEW_LINE> line1 = self._log[self._cur_index - 1] <NEW_LINE> line2 = self._log[self._cur_index] <NEW_LINE> self._put(line1[self._cur_side_index:] + line1[:self._cur_side_index], line2[self._cur_side_index:] + line2[:self._cur_side_index]) <NEW_LINE> <DEDENT> def write(self, message: str) -> None: <NEW_LINE> <INDENT> message_parts = [] <NEW_LINE> num_message_parts = (len(message) // 39) + 1 <NEW_LINE> part_length = len(message) // num_message_parts <NEW_LINE> for i in range(num_message_parts): <NEW_LINE> <INDENT> if i == num_message_parts - 1: <NEW_LINE> <INDENT> message_parts.append(message[i * part_length:]) <NEW_LINE> break <NEW_LINE> <DEDENT> message_parts.append(message[i * part_length:(i + 1) * part_length]) <NEW_LINE> <DEDENT> for message_part in message_parts: <NEW_LINE> <INDENT> while len(message_part) < 16: <NEW_LINE> <INDENT> message_part += " " <NEW_LINE> <DEDENT> message_part += " " <NEW_LINE> self._log.append(message_part) <NEW_LINE> self._cur_index += 1 <NEW_LINE> <DEDENT> self.show() <NEW_LINE> <DEDENT> def scroll(self, displacement: int) -> None: <NEW_LINE> <INDENT> self._cur_index = (displacement + self._cur_index) % len(self._log) <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def side_scroll(self, displacement: int) -> None: <NEW_LINE> <INDENT> _len = max(len(self._log[self._cur_index - 1]), len(self._log[self._cur_index])) <NEW_LINE> self._cur_side_index = (displacement + self._cur_side_index) % _len <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def set_default(self) -> None: <NEW_LINE> <INDENT> self._cur_index = len(self._log) - 1 <NEW_LINE> self._cur_side_index = 0 <NEW_LINE> self.show() <NEW_LINE> <DEDENT> def check_pressed(self) -> str: <NEW_LINE> <INDENT> buttons = ((LCD.SELECT, "select"), (LCD.LEFT, "left" ), (LCD.UP, "up" ), (LCD.DOWN, "down" ), (LCD.RIGHT, "right" )) <NEW_LINE> for button in buttons: <NEW_LINE> <INDENT> if self._lcd.is_pressed(button[0]): <NEW_LINE> <INDENT> return button[1] <NEW_LINE> <DEDENT> <DEDENT> return "" | Manages all display functionality regarding the 16x2 LCD display.
| 62599046507cdc57c63a6104 |
class AppAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ("id", "name", "is_active", "access_key", "secret_key", "created_on", "modified_on") <NEW_LINE> search_fields = ("name", "is_active", "access_key") | 第三方应用的后台管理页面 | 6259904763b5f9789fe864d3 |
class User: <NEW_LINE> <INDENT> alarms = {} <NEW_LINE> next_alarm = None <NEW_LINE> current_alarm = None <NEW_LINE> snooze = None <NEW_LINE> alarm_sound = 'alarm.wav' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def refresh(self): <NEW_LINE> <INDENT> if bool(self.alarms): <NEW_LINE> <INDENT> current_week_minute = utils.datetime_to_week_minute() <NEW_LINE> try: <NEW_LINE> <INDENT> self.next_alarm = min(filter(lambda x: x > current_week_minute,self.alarms.keys())) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.next_alarm = min(self.alarms.keys()) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.next_alarm = None <NEW_LINE> <DEDENT> <DEDENT> def trigger(self): <NEW_LINE> <INDENT> self.current_alarm = self.alarms[self.next_alarm] <NEW_LINE> sound = self.alarms[self.current_alarm].get('sound',default=self.alarm_sound) <NEW_LINE> utils.play_sound(sound) <NEW_LINE> self.refresh() <NEW_LINE> <DEDENT> def silence(self): <NEW_LINE> <INDENT> self.remove_one_time_alarm(self.current_alarm) <NEW_LINE> self.current_alarm = None <NEW_LINE> utils.stop_sound() <NEW_LINE> <DEDENT> def snooze_alarm(self): <NEW_LINE> <INDENT> snooze = self.alarms[self.current_alarm].get('snooze',default=self.snooze) <NEW_LINE> if snooze: <NEW_LINE> <INDENT> snoozed_week_minute = utils.datetime_to_week_minute() + snooze <NEW_LINE> if snoozed_week_minute > utils.MAX_WEEK_MINUTE: <NEW_LINE> <INDENT> snoozed_week_minute -= utils.MAX_WEEK_MINUTE <NEW_LINE> <DEDENT> attributes = self.alarms[self.current_alarm] <NEW_LINE> self.add_alarm(self.current_alarm,**attributes) <NEW_LINE> self.silence() <NEW_LINE> self.refresh() <NEW_LINE> <DEDENT> <DEDENT> def add_alarm(self, week_minute, **kwargs): <NEW_LINE> <INDENT> self.alarms[week_minute] = kwargs <NEW_LINE> self.refresh() <NEW_LINE> <DEDENT> def remove_one_time_alarm(self, week_minute): <NEW_LINE> <INDENT> if not self.alarms[week_minute].get('repeat',default=True): <NEW_LINE> <INDENT> self.remove_alarm(week_minute) <NEW_LINE> <DEDENT> <DEDENT> def remove_alarm(self, week_minute): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> del self.alarms[week_minute] <NEW_LINE> self.refresh() <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def set_alarm_sound(self,sound_file): <NEW_LINE> <INDENT> self.alarm_sound = sound_file <NEW_LINE> <DEDENT> def set_snooze(self,snooze_minutes): <NEW_LINE> <INDENT> self.snooze = snooze_minutes | A regular user of the alarm clock | 6259904745492302aabfd839 |
class Component(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def destroy(self): <NEW_LINE> <INDENT> attr_list = list(self.__dict__.keys()) <NEW_LINE> for attr_name in attr_list: <NEW_LINE> <INDENT> attr = getattr(self, attr_name) <NEW_LINE> if hasattr(attr, 'destroy'): <NEW_LINE> <INDENT> attr.destroy() <NEW_LINE> <DEDENT> delattr(self, attr_name) <NEW_LINE> <DEDENT> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> from deeppavlov.core.models.serializable import Serializable <NEW_LINE> if isinstance(self, Serializable): <NEW_LINE> <INDENT> log.warning(f'Method for {self.__class__.__name__} serialization is not implemented!' f' Will not be able to load without using load_path') <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def deserialize(self, data): <NEW_LINE> <INDENT> from deeppavlov.core.models.serializable import Serializable <NEW_LINE> if isinstance(self, Serializable): <NEW_LINE> <INDENT> log.warning(f'Method for {self.__class__.__name__} deserialization is not implemented!' f' Please, use traditional load_path for this component') <NEW_LINE> <DEDENT> pass | Abstract class for all callables that could be used in Chainer's pipe. | 62599047d6c5a102081e3483 |
class alpha_PriceSwingDiv(alpha): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(alpha_PriceSwingDiv, self).__init__(*args, **kwargs) <NEW_LINE> self.prev_n = 10 <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> super(alpha_PriceSwingDiv, self).initialize() <NEW_LINE> if 'prev_n' in self.params: <NEW_LINE> <INDENT> self.prev_n = int(self.params['prev_n']) <NEW_LINE> <DEDENT> <DEDENT> def generate(self, alaph_vec, data, di): <NEW_LINE> <INDENT> ix = np.logical_and(data['universe'][di-1, :] == 1, data['tradable'][di-1, :] == 1) <NEW_LINE> for i in range(alaph_vec.shape[0]): <NEW_LINE> <INDENT> if ix[i]: <NEW_LINE> <INDENT> if data['universe'][di-self.delay, i] == 1 and data['tradable'][di-self.delay, i]: <NEW_LINE> <INDENT> alaph_vec[i] = -1 * pearsonr(data['essentials']['high'][di-self.prev_n:di,i] / data['essentials']['low'][di-self.prev_n:di,i], data['essentials']['volume'][di-self.prev_n:di,i])[0] | description of class | 62599047009cb60464d0289c |
class UsageEvent(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'dimension_id': {'key': 'dimensionId', 'type': 'str'}, 'dimension_name': {'key': 'dimensionName', 'type': 'str'}, 'measure_unit': {'key': 'measureUnit', 'type': 'str'}, 'amount_billed': {'key': 'amountBilled', 'type': 'float'}, 'amount_consumed': {'key': 'amountConsumed', 'type': 'float'}, 'unit_price': {'key': 'unitPrice', 'type': 'float'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(UsageEvent, self).__init__(**kwargs) <NEW_LINE> self.dimension_id = kwargs.get('dimension_id', None) <NEW_LINE> self.dimension_name = kwargs.get('dimension_name', None) <NEW_LINE> self.measure_unit = kwargs.get('measure_unit', None) <NEW_LINE> self.amount_billed = kwargs.get('amount_billed', None) <NEW_LINE> self.amount_consumed = kwargs.get('amount_consumed', None) <NEW_LINE> self.unit_price = kwargs.get('unit_price', None) | Usage event details.
:ivar dimension_id: The dimension id.
:vartype dimension_id: str
:ivar dimension_name: The dimension name.
:vartype dimension_name: str
:ivar measure_unit: The unit of measure.
:vartype measure_unit: str
:ivar amount_billed: The amount billed.
:vartype amount_billed: float
:ivar amount_consumed: The amount consumed.
:vartype amount_consumed: float
:ivar unit_price: The unit price.
:vartype unit_price: float | 6259904750485f2cf55dc2ef |
class Language(TableBase): <NEW_LINE> <INDENT> __tablename__ = 'languages' <NEW_LINE> __singlename__ = 'language' <NEW_LINE> id = Column(Integer, primary_key=True, nullable=False, doc=u"A numeric ID") <NEW_LINE> iso639 = Column(Unicode(79), nullable=False, doc=u"The two-letter code of the language. Note that it is not unique.", info=dict(format='identifier')) <NEW_LINE> iso3166 = Column(Unicode(79), nullable=False, doc=u"The two-letter code of the country where this language is spoken. Note that it is not unique.", info=dict(format='identifier')) <NEW_LINE> identifier = Column(Unicode(79), nullable=False, doc=u"An identifier", info=dict(format='identifier')) <NEW_LINE> official = Column(Boolean, nullable=False, index=True, doc=u"True iff games are produced in the language.") <NEW_LINE> order = Column(Integer, nullable=True, doc=u"Order for sorting in foreign name lists.") | A language the Pokémon games have been translated into. | 6259904771ff763f4b5e8b0b |
class LivestockPigCycle(ProduModel): <NEW_LINE> <INDENT> production_livestock = models.ForeignKey( "producer.ProductionLivestock", related_name="livestock_pig_cycle", on_delete=models.CASCADE ) <NEW_LINE> up_three_months = models.PositiveIntegerField(default=0) <NEW_LINE> three_eight_months = models.PositiveIntegerField(default=0) <NEW_LINE> males_older_eight_months = models.PositiveIntegerField(default=0) <NEW_LINE> females_older_eight_months = models.PositiveIntegerField(default=0) <NEW_LINE> number_pigs = models.PositiveIntegerField(default=0) <NEW_LINE> number_stallions = models.PositiveIntegerField(default=0) | Ciclo de cerdos relacionado
con la actividad productiva | 62599047462c4b4f79dbcd66 |
class TestAnalysisEvent(BaseTest): <NEW_LINE> <INDENT> SKETCH_ID = 1 <NEW_LINE> def test_event(self): <NEW_LINE> <INDENT> sketch = interface.Sketch(sketch_id=self.SKETCH_ID) <NEW_LINE> datastore = MockDataStore('127.0.0.1', 4711) <NEW_LINE> valid_event = dict( _id='1', _type='test', _index='test', _source={'__ts_timeline_id': 1, 'test': True}) <NEW_LINE> invalid_event = dict(_id='1') <NEW_LINE> event = interface.Event(valid_event, datastore, sketch=None) <NEW_LINE> sketch_event = interface.Event(valid_event, datastore, sketch=sketch) <NEW_LINE> self.assertIsInstance(event.datastore, MockDataStore) <NEW_LINE> self.assertIsNone(event.sketch) <NEW_LINE> self.assertIsInstance(sketch_event.sketch, interface.Sketch) <NEW_LINE> self.assertRaises(KeyError, interface.Event, invalid_event, datastore) | Tests for the functionality of the Event class. | 6259904730dc7b76659a0b9a |
class RadiusAttr_WLAN_Reason_Code(_RadiusAttrIntValue): <NEW_LINE> <INDENT> val = 185 | RFC 7268 | 625990476fece00bbacccd1d |
class Post(AbstractTranslatableEntry, ExcerptImageEntryMixin): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _("Blog post") <NEW_LINE> verbose_name_plural = _("Blog posts") <NEW_LINE> ordering = ('-publication_date',) | Custom blog entry model with an excerpt text. | 6259904707d97122c421800a |
@register_relay_node <NEW_LINE> class Function(Expr): <NEW_LINE> <INDENT> def __init__(self, params, ret_type, body, type_params=None): <NEW_LINE> <INDENT> if type_params is None: <NEW_LINE> <INDENT> type_params = convert([]) <NEW_LINE> <DEDENT> self.__init_handle_by_constructor__( _make.Function, params, ret_type, body, type_params) | A function declaration expression.
Parameters
----------
params: List[tvm.relay.Var]
List of input parameters to the function.
ret_type: tvm.relay.Type
The return type annotation of the function.
body: tvm.relay.Expr
The body of the function.
type_params: Optional[List[tvm.relay.TypeParam]]
The additional type parameters, this is only
used in advanced usecase of template functions. | 625990478da39b475be04558 |
class ReptorResource: <NEW_LINE> <INDENT> def __init__(self, ): <NEW_LINE> <INDENT> self._reputation_service = Reptor() <NEW_LINE> <DEDENT> @jsonschema.validate(get_json_schema) <NEW_LINE> def on_get(self, req:falcon.Request, resp:falcon.Response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rep_name = req.media['reputee'] <NEW_LINE> scores = self._reputation_service.calc_scores(rep_name) <NEW_LINE> resp.status = falcon.HTTP_200 <NEW_LINE> resp.media = scores <NEW_LINE> <DEDENT> except exceptions.ReputeeNotFoundError: <NEW_LINE> <INDENT> raise falcon.HTTPError(falcon.HTTP_422, 'Reputee not found.') <NEW_LINE> <DEDENT> <DEDENT> @jsonschema.validate(post_json_schema) <NEW_LINE> def on_post(self, req:falcon.Request, resp: falcon.Response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._reputation_service.update(req.media) <NEW_LINE> resp.status = falcon.HTTP_202 <NEW_LINE> <DEDENT> except exceptions.RidDuplicateError: <NEW_LINE> <INDENT> raise falcon.HTTPError(falcon.HTTP_422, 'Rejected due to duplicate identifier') | Falcon application for reputation. It only tries to work with things that are directly web-related.
It does not include the rules or algorithms for data handling once the JSON is digested. | 62599047287bf620b6272f51 |
class DataIngestionBot(pywikibot.Bot): <NEW_LINE> <INDENT> def __init__(self, reader, titlefmt, pagefmt, site=pywikibot.Site(u'commons', u'commons')): <NEW_LINE> <INDENT> super(DataIngestionBot, self).__init__(generator=reader) <NEW_LINE> self.reader = reader <NEW_LINE> self.titlefmt = titlefmt <NEW_LINE> self.pagefmt = pagefmt <NEW_LINE> if site: <NEW_LINE> <INDENT> self.site = site <NEW_LINE> <DEDENT> <DEDENT> def treat(self, photo): <NEW_LINE> <INDENT> duplicates = photo.findDuplicateImages() <NEW_LINE> if duplicates: <NEW_LINE> <INDENT> pywikibot.output(u"Skipping duplicate of %r" % duplicates) <NEW_LINE> return duplicates[0] <NEW_LINE> <DEDENT> title = photo.getTitle(self.titlefmt) <NEW_LINE> description = photo.getDescription(self.pagefmt) <NEW_LINE> bot = upload.UploadRobot(url=photo.URL, description=description, useFilename=title, keepFilename=True, verifyDescription=False, targetSite=self.site) <NEW_LINE> bot._contents = photo.downloadPhoto().getvalue() <NEW_LINE> bot._retrieved = True <NEW_LINE> bot.run() <NEW_LINE> return title <NEW_LINE> <DEDENT> @deprecated("treat()") <NEW_LINE> def doSingle(self): <NEW_LINE> <INDENT> return self.treat(next(self.reader)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parseConfigurationPage(cls, configurationPage): <NEW_LINE> <INDENT> configuration = {} <NEW_LINE> configuration['csvDialect'] = u'excel' <NEW_LINE> configuration['csvDelimiter'] = ';' <NEW_LINE> configuration['csvEncoding'] = u'Windows-1252' <NEW_LINE> templates = configurationPage.templatesWithParams() <NEW_LINE> for (template, params) in templates: <NEW_LINE> <INDENT> if template.title(withNamespace=False) == u'Data ingestion': <NEW_LINE> <INDENT> for param in params: <NEW_LINE> <INDENT> (field, sep, value) = param.partition(u'=') <NEW_LINE> field = field.strip() <NEW_LINE> value = value.strip() <NEW_LINE> if not value: <NEW_LINE> <INDENT> value = None <NEW_LINE> <DEDENT> configuration[field] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return configuration | Data ingestion bot. | 6259904724f1403a92686281 |
class _MMSchemaMeta(mm.schema.SchemaMeta, abc_schema.abc.ABCMeta): <NEW_LINE> <INDENT> ... | Combined meta class from Marshmallow and abc.ABCMeta, so we can inherit from both | 6259904723849d37ff852425 |
class MemoryDAO(dao.DAO): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> dao.DAO.register(MemoryDAO) <NEW_LINE> self._stack = {} <NEW_LINE> <DEDENT> def cls(self, obj): <NEW_LINE> <INDENT> return obj.__class__.__name__ <NEW_LINE> <DEDENT> def create(self, obj): <NEW_LINE> <INDENT> self._stack[obj.reg_id] = deepcopy(obj) <NEW_LINE> <DEDENT> def retrieve(self, reg_id): <NEW_LINE> <INDENT> if reg_id not in self._stack.keys(): <NEW_LINE> <INDENT> raise FileNotFoundError <NEW_LINE> <DEDENT> obj = self._stack[reg_id] <NEW_LINE> return deepcopy(obj) <NEW_LINE> <DEDENT> def retrieve_all(self): <NEW_LINE> <INDENT> return [deepcopy(self._stack[i]) for i in self._stack] <NEW_LINE> <DEDENT> def update(self, obj): <NEW_LINE> <INDENT> if obj.reg_id in self._stack.keys(): <NEW_LINE> <INDENT> self._stack[obj.reg_id] = deepcopy(obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise FileNotFoundError <NEW_LINE> <DEDENT> <DEDENT> def delete(self, obj): <NEW_LINE> <INDENT> del self._stack[obj.reg_id] <NEW_LINE> <DEDENT> def find_by(self, attributes: dict): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if len(self._stack) == 0: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> sample = list(self._stack.items())[0][1] <NEW_LINE> intersect_keys = set(attributes).intersection(set(sample.__dict__)) <NEW_LINE> for k, reg in self._stack.items(): <NEW_LINE> <INDENT> for key in intersect_keys: <NEW_LINE> <INDENT> stack_item = reg.__dict__ <NEW_LINE> if stack_item[key] == attributes[key]: <NEW_LINE> <INDENT> result.append(deepcopy(reg)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if len(result) < 1: <NEW_LINE> <INDENT> raise FileNotFoundError <NEW_LINE> <DEDENT> return result | Store values in memory instead of any persistence
Usually used in tests as a test fixture to raise coverage | 62599047c432627299fa42b7 |
class Notification(QtWidgets.QWidget): <NEW_LINE> <INDENT> _type = None <NEW_LINE> def __init__( self, event=None, date=None, parent=None ): <NEW_LINE> <INDENT> super(Notification, self).__init__(parent=parent) <NEW_LINE> self.horizontalLayout = QtWidgets.QHBoxLayout() <NEW_LINE> verticalLayout = QtWidgets.QVBoxLayout() <NEW_LINE> self.setLayout(self.horizontalLayout) <NEW_LINE> self.horizontalLayout.addLayout(verticalLayout, stretch=1) <NEW_LINE> self.textLabel = QtWidgets.QLabel() <NEW_LINE> verticalLayout.addWidget(self.textLabel) <NEW_LINE> self.dateLabel = QtWidgets.QLabel() <NEW_LINE> verticalLayout.addWidget(self.dateLabel) <NEW_LINE> self.setDate(event['created_at']) <NEW_LINE> self.setEvent(event) <NEW_LINE> <DEDENT> def _load(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def value(self): <NEW_LINE> <INDENT> return { 'text': self.textLabel.text(), 'type': self._type } <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> self._load() <NEW_LINE> <DEDENT> def setEvent(self, event): <NEW_LINE> <INDENT> self._event = event <NEW_LINE> self.load() <NEW_LINE> <DEDENT> def setText(self, text): <NEW_LINE> <INDENT> self.textLabel.setText(text) <NEW_LINE> <DEDENT> def setDate(self, date): <NEW_LINE> <INDENT> self._date = arrow.get( date.datetime, 'local' ) <NEW_LINE> self.dateLabel.setText( self._date.humanize() ) <NEW_LINE> <DEDENT> def _onButtonClicked(self): <NEW_LINE> <INDENT> ftrack.EVENT_HUB.publish( ftrack.Event( 'ftrack.crew.notification.{0._type}'.format(self), data=self.value() ), synchronous=True ) | Represent a notification. | 62599047d4950a0f3b1117f6 |
class Market(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('latitude', 'longitude') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s' % (self.market_name) <NEW_LINE> <DEDENT> market_id = models.AutoField(primary_key=True) <NEW_LINE> market_name = models.TextField(max_length=80, unique=True) <NEW_LINE> region = models.TextField(max_length=60) <NEW_LINE> state = models.CharField(max_length=2, choices=STATE_CHOICES) <NEW_LINE> latitude = models.DecimalField(max_digits=11, decimal_places=8) <NEW_LINE> longitude = models.DecimalField(max_digits=11, decimal_places=8) <NEW_LINE> moderator = models.ForeignKey(User) | Market details, it consists of just Indian states | 6259904745492302aabfd83a |
class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod): <NEW_LINE> <INDENT> name = 'PLAINTEXT' <NEW_LINE> @property <NEW_LINE> def signature(self): <NEW_LINE> <INDENT> return self.base_secrets | Implements the PLAINTEXT signature logic.
http://oauth.net/core/1.0/#rfc.section.9.4 | 6259904763b5f9789fe864d5 |
class SSCModule(object): <NEW_LINE> <INDENT> def __init__(self, mod_name): <NEW_LINE> <INDENT> mod_name = bytes(mod_name, "utf-8") <NEW_LINE> self._module = _LIB.ssc_module_create(mod_name) <NEW_LINE> <DEDENT> def _module_data(self): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> info = _LIB.ssc_module_var_info(self._module, i) <NEW_LINE> if info == ffi.NULL: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> var_type = _LIB.ssc_info_var_type(info) <NEW_LINE> name = _LIB.ssc_info_name(info) <NEW_LINE> yield var_type, ffi.string(name) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def inputs(self): <NEW_LINE> <INDENT> inputs_ = [] <NEW_LINE> for var_type, name in self._module_data(): <NEW_LINE> <INDENT> if var_type in (_LIB.SSC_INPUT, _LIB.SSC_INOUT): <NEW_LINE> <INDENT> inputs_.append(name) <NEW_LINE> <DEDENT> <DEDENT> return inputs_ <NEW_LINE> <DEDENT> @property <NEW_LINE> def outputs(self): <NEW_LINE> <INDENT> outputs_ = [] <NEW_LINE> for var_type, name in self._module_data(): <NEW_LINE> <INDENT> if var_type in (_LIB.SSC_OUTPUT, _LIB.SSC_INOUT): <NEW_LINE> <INDENT> outputs_.append(name) <NEW_LINE> <DEDENT> <DEDENT> return outputs_ <NEW_LINE> <DEDENT> def execute(self, data): <NEW_LINE> <INDENT> success = _LIB.ssc_module_exec(self._module, data._data) <NEW_LINE> if not success: <NEW_LINE> <INDENT> raise ModuleRunError <NEW_LINE> <DEDENT> return data | Generic base class for SSC modules | 62599047e64d504609df9d85 |
class CarsDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, mat_anno, data_dir, car_names, cleaned=None, transform=None): <NEW_LINE> <INDENT> self.full_data_set = scipy.io.loadmat(mat_anno) <NEW_LINE> self.car_annotations = self.full_data_set['annotations'] <NEW_LINE> self.car_annotations = self.car_annotations[0] <NEW_LINE> if cleaned is not None: <NEW_LINE> <INDENT> cleaned_annos = [] <NEW_LINE> print("Cleaning up data set (only take pics with rgb chans)...") <NEW_LINE> clean_files = np.loadtxt(cleaned, dtype=str) <NEW_LINE> for c in self.car_annotations: <NEW_LINE> <INDENT> if c[-1][0] in clean_files: <NEW_LINE> <INDENT> cleaned_annos.append(c) <NEW_LINE> <DEDENT> <DEDENT> self.car_annotations = cleaned_annos <NEW_LINE> <DEDENT> self.car_names = scipy.io.loadmat(car_names)['class_names'] <NEW_LINE> self.car_names = np.array(self.car_names[0]) <NEW_LINE> self.data_dir = data_dir <NEW_LINE> self.transform = transform <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.car_annotations) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> img_name = os.path.join(self.data_dir, self.car_annotations[idx][-1][0]) <NEW_LINE> image = Image.open(img_name) <NEW_LINE> car_class = self.car_annotations[idx][-2][0][0] <NEW_LINE> if self.transform: <NEW_LINE> <INDENT> image = self.transform(image) <NEW_LINE> <DEDENT> return image, car_class <NEW_LINE> <DEDENT> def map_class(self, id): <NEW_LINE> <INDENT> id = np.ravel(id) <NEW_LINE> ret = self.car_names[id - 1][0][0] <NEW_LINE> return ret <NEW_LINE> <DEDENT> def show_batch(self, img_batch, class_batch): <NEW_LINE> <INDENT> for i in range(img_batch.shape[0]): <NEW_LINE> <INDENT> ax = plt.subplot(1, img_batch.shape[0], i + 1) <NEW_LINE> title_str = self.map_class(int(class_batch[i])) <NEW_LINE> img = np.transpose(img_batch[i, ...], (1, 2, 0)) <NEW_LINE> ax.imshow(img) <NEW_LINE> ax.set_title(title_str.__str__(), {'fontsize': 5}) <NEW_LINE> plt.tight_layout() | Face Landmarks dataset. | 6259904750485f2cf55dc2f1 |
class TaskPriority: <NEW_LINE> <INDENT> SHOWSTOPPER = 0 <NEW_LINE> CRITICAL = 1 <NEW_LINE> HIGH = 2 <NEW_LINE> MEDIUM = 3 <NEW_LINE> LOW = 4 | Task Priorities | 625990471f5feb6acb163f5f |
class StoreJobIntermediateResultsBody(Model): <NEW_LINE> <INDENT> def __init__(self, gas_payer: str = None, gas_payer_private: str = None, address: str = None, rep_oracle_pub: str = None, results_url: str = None): <NEW_LINE> <INDENT> self.swagger_types = { 'gas_payer': str, 'gas_payer_private': str, 'address': str, 'rep_oracle_pub': str, 'results_url': str, } <NEW_LINE> self.attribute_map = { 'gas_payer': 'gasPayer', 'gas_payer_private': 'gasPayerPrivate', 'address': 'address', 'rep_oracle_pub': 'repOraclePub', 'results_url': 'resultsUrl', } <NEW_LINE> self._gas_payer = gas_payer <NEW_LINE> self._gas_payer_private = gas_payer_private <NEW_LINE> self._address = address <NEW_LINE> self._rep_oracle_pub = rep_oracle_pub <NEW_LINE> self._results_url = results_url <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'StoreJobIntermediateResultsBody': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def gas_payer(self) -> str: <NEW_LINE> <INDENT> return self._gas_payer <NEW_LINE> <DEDENT> @gas_payer.setter <NEW_LINE> def gas_payer(self, gas_payer: str): <NEW_LINE> <INDENT> self._gas_payer = gas_payer <NEW_LINE> <DEDENT> @property <NEW_LINE> def gas_payer_private(self) -> str: <NEW_LINE> <INDENT> return self._gas_payer_private <NEW_LINE> <DEDENT> @gas_payer_private.setter <NEW_LINE> def gas_payer_private(self, gas_payer_private: str): <NEW_LINE> <INDENT> self._gas_payer_private = gas_payer_private <NEW_LINE> <DEDENT> @property <NEW_LINE> def address(self) -> str: <NEW_LINE> <INDENT> return self._address <NEW_LINE> <DEDENT> @address.setter <NEW_LINE> def address(self, address: str): <NEW_LINE> <INDENT> self._address = address <NEW_LINE> <DEDENT> @property <NEW_LINE> def rep_oracle_pub(self) -> str: <NEW_LINE> <INDENT> return self._rep_oracle_pub <NEW_LINE> <DEDENT> @rep_oracle_pub.setter <NEW_LINE> def rep_oracle_pub(self, rep_oracle_pub: str): <NEW_LINE> <INDENT> self._rep_oracle_pub = rep_oracle_pub <NEW_LINE> <DEDENT> @property <NEW_LINE> def results_url(self) -> str: <NEW_LINE> <INDENT> return self._results_url <NEW_LINE> <DEDENT> @results_url.setter <NEW_LINE> def results_url(self, results_url: str): <NEW_LINE> <INDENT> self._results_url = results_url | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259904782261d6c5273087a |
class Action71(Action): <NEW_LINE> <INDENT> def execute(self, instance): <NEW_LINE> <INDENT> instance.objectPlayer.set_hyperlink_color(get_text_color(5)) | Set Hyperlink color->Text of item selected in a control
Parameters:
0: ((unknown 25072)) | 625990476fece00bbacccd1f |
class GCSFileScheme(FileScheme): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("gcp", fstype=FileScheme.FileSchemeType.gcs) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def check_if_has_gcp(): <NEW_LINE> <INDENT> if has_google_cloud: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> raise ImportError( "You've tried to use the Google Cloud storage (GCS) filesystem, but don't have the 'google-cloud-storage' " "library. This can be installed with 'pip install janis-pipelines.runner[gcs]'." ) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_valid_prefix(prefix: str): <NEW_LINE> <INDENT> return prefix.lower().startswith("gs://") <NEW_LINE> <DEDENT> def get_file_size(self, path) -> Optional[int]: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_public_client(self): <NEW_LINE> <INDENT> from google.cloud.storage import Client <NEW_LINE> return Client.create_anonymous_client() <NEW_LINE> <DEDENT> def get_blob_from_link(self, link): <NEW_LINE> <INDENT> bucket, blob = self.parse_gcs_link(link) <NEW_LINE> storage_client = self.get_public_client() <NEW_LINE> bucket = storage_client.bucket(bucket) <NEW_LINE> blob = bucket.get_blob(blob) <NEW_LINE> if not blob: <NEW_LINE> <INDENT> raise Exception(f"Couldn't find GCS link: {link}") <NEW_LINE> <DEDENT> return blob <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse_gcs_link(gcs_link: str): <NEW_LINE> <INDENT> import re <NEW_LINE> gcs_locator = re.compile("gs:\/\/([A-z0-9-]+)\/(.*)") <NEW_LINE> match = gcs_locator.match(gcs_link) <NEW_LINE> if match is None: <NEW_LINE> <INDENT> raise Exception( f"Janis was unable to validate your GCS link '{gcs_link}', as it couldn't determine the BUCKET, " f"and FILE COMPONENT. Please raise an issue for more information." ) <NEW_LINE> <DEDENT> bucket, blob = match.groups() <NEW_LINE> return bucket, blob <NEW_LINE> <DEDENT> def exists(self, path): <NEW_LINE> <INDENT> blob = self.get_blob_from_link(path) <NEW_LINE> return blob.exists() <NEW_LINE> <DEDENT> def cp_from( self, source, dest, force=False, report_progress: Optional[Callable[[float], None]] = None, ): <NEW_LINE> <INDENT> self.check_if_has_gcp() <NEW_LINE> blob = self.get_blob_from_link(source) <NEW_LINE> size_mb = blob.size // (1024 * 1024) <NEW_LINE> Logger.debug(f"Downloading {source} -> {dest} ({size_mb} MB)") <NEW_LINE> blob.download_to_filename(dest) <NEW_LINE> print( "Downloaded public blob {} from bucket {} to {}.".format( blob.name, blob.bucket.name, dest ) ) <NEW_LINE> <DEDENT> def cp_to( self, source, dest, force=False, report_progress: Optional[Callable[[float], None]] = None, ): <NEW_LINE> <INDENT> raise Exception("Janis doesn't support copying files TO google cloud storage.") <NEW_LINE> <DEDENT> def mkdirs(self, directory): <NEW_LINE> <INDENT> raise NotImplementedError("Cannot make directories through GCS filescheme") <NEW_LINE> <DEDENT> def rm_dir(self, directory): <NEW_LINE> <INDENT> raise NotImplementedError("Cannot remove directories through GCS filescheme") | Placeholder for GCS File schema, almost for sure going to need the 'gsutil' package,
probably a credentials file to access the files. Should call the report_progress param on cp | 62599047435de62698e9d16f |
class Lookup(_Rule): <NEW_LINE> <INDENT> def _configure(self, table=None, icase=False): <NEW_LINE> <INDENT> self.table = table or dict() <NEW_LINE> self.icase = icase <NEW_LINE> if icase: <NEW_LINE> <INDENT> self.table = {k.lower(): v for k, v in table.items()} <NEW_LINE> <DEDENT> <DEDENT> @_Rule.track_changes <NEW_LINE> def apply(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fieldval = str(data[self.fieldname]) <NEW_LINE> if self.icase: <NEW_LINE> <INDENT> fieldval = fieldval.lower() <NEW_LINE> <DEDENT> data[self.fieldname] = self.table[fieldval] <NEW_LINE> <DEDENT> except KeyError as err: <NEW_LINE> <INDENT> log.debug("Lookup: fieldname '%s' not in data, ignoring", err) <NEW_LINE> return | Implements a dead-simple lookup table which perform case sensitive
(default) or insensitive (icase=True) lookups. | 62599047be383301e0254b83 |
class TorConfigType(object): <NEW_LINE> <INDENT> def parse(self, s): <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> def validate(self, s, instance, name): <NEW_LINE> <INDENT> return s | Base class for all configuration types, which function as parsers
and un-parsers. | 6259904726068e7796d4dcb1 |
class MHSMPrivateEndpointConnectionsListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[MHSMPrivateEndpointConnection]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(MHSMPrivateEndpointConnectionsListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) <NEW_LINE> self.next_link = kwargs.get('next_link', None) | List of private endpoint connections associated with a managed HSM Pools.
:param value: The private endpoint connection associated with a managed HSM Pools.
:type value:
list[~azure.mgmt.keyvault.v2021_04_01_preview.models.MHSMPrivateEndpointConnection]
:param next_link: The URL to get the next set of managed HSM Pools.
:type next_link: str | 62599047507cdc57c63a6108 |
class EthernetDstAddress(base_tests.SimpleDataPlane): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> logging.info("Running Ethernet Dst Address test") <NEW_LINE> of_ports = config["port_map"].keys() <NEW_LINE> of_ports.sort() <NEW_LINE> self.assertTrue(len(of_ports) > 1, "Not enough ports for test") <NEW_LINE> rv = delete_all_flows(self.controller) <NEW_LINE> self.assertEqual(rv, 0, "Failed to delete all flows") <NEW_LINE> egress_port=of_ports[1] <NEW_LINE> no_ports=set(of_ports).difference([egress_port]) <NEW_LINE> yes_ports = of_ports[1] <NEW_LINE> logging.info("Inserting a flow with match on Ethernet Destination Address ") <NEW_LINE> logging.info("Sending matching and non-matching ethernet packets") <NEW_LINE> logging.info("Verifying only matching packets implements the action specified in the flow") <NEW_LINE> (pkt,match) = match_ethernet_dst_address(self,of_ports) <NEW_LINE> self.dataplane.send(of_ports[0], str(pkt)) <NEW_LINE> receive_pkt_check(self.dataplane,pkt,[yes_ports],no_ports,self) <NEW_LINE> pkt2 = simple_eth_packet(dl_dst='00:01:01:01:01:02'); <NEW_LINE> self.dataplane.send(of_ports[0], str(pkt2)) <NEW_LINE> (response, raw) = self.controller.poll(ofp.OFPT_PACKET_IN,timeout=4) <NEW_LINE> self.assertTrue(response is not None, "PacketIn not received for non matching packet") | Verify match on single Header Field Field -- Ethernet Dst Address | 62599047d6c5a102081e3486 |
class BaiduPipeline(object): <NEW_LINE> <INDENT> def process_item(self, item, spider): <NEW_LINE> <INDENT> if isinstance(spider, BaiduSpider): <NEW_LINE> <INDENT> print("这是百度爬虫管道的数据") <NEW_LINE> <DEDENT> return item | 由此来判断item是属于哪个爬虫的对象 | 62599047379a373c97d9a395 |
class SketchCurvePoint(SketchBase): <NEW_LINE> <INDENT> CLASS = 'curvePoint' <NEW_LINE> ATTRS = { 'do_objectID': (asId, None), 'cornerRadius': (asNumber, 0), 'curveFrom': (SketchPositionString, POINT_ORIGIN), 'curveMode': (asInt, 1), 'curveTo': (SketchPositionString, POINT_ORIGIN), 'hasCurveFrom': (asBool, False), 'hasCurveTo': (asBool, False), 'point': (SketchPositionString, POINT_ORIGIN), } | type SketchCurvePoint = {
_class: 'curvePoint',
do_objectID: UUID,
cornerRadius: number,
curveFrom: SketchPositionString, --> SketchPoint
curveMode: number,
curveTo: SketchPositionString, --> SketchPoint
hasCurveFrom: bool,
hasCurveTo: bool,
point: SketchPositionString --> Point | 6259904763b5f9789fe864d7 |
class User(object): <NEW_LINE> <INDENT> def __init__(self, name, spotify_ids): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.spotify_ids = spotify_ids | A Spotify User | 62599047711fe17d825e1653 |
class mail_message(osv.Model): <NEW_LINE> <INDENT> _inherit = 'mail.message' <NEW_LINE> _columns = { 'email_to':fields.text('Email To'), 'email_cc':fields.char('Email cc', size=240), } <NEW_LINE> def _notify(self, cr, uid, newid, context=None): <NEW_LINE> <INDENT> notification_obj = self.pool.get('mail.notification') <NEW_LINE> message = self.browse(cr, uid, newid, context=context) <NEW_LINE> partners_to_notify = set([]) <NEW_LINE> if not message.subtype_id: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if message.model and message.res_id: <NEW_LINE> <INDENT> fol_obj = self.pool.get("mail.followers") <NEW_LINE> fol_ids = fol_obj.search(cr, SUPERUSER_ID, [ ('res_model', '=', message.model), ('res_id', '=', message.res_id), ('subtype_ids', 'in', message.subtype_id.id) ], context=context) <NEW_LINE> partners_to_notify |= set(fo.partner_id for fo in fol_obj.browse(cr, SUPERUSER_ID, fol_ids, context=context)) <NEW_LINE> <DEDENT> if message.author_id and message.model == "res.partner" and message.res_id == message.author_id.id: <NEW_LINE> <INDENT> partners_to_notify |= set([message.author_id]) <NEW_LINE> <DEDENT> elif message.author_id: <NEW_LINE> <INDENT> partners_to_notify -= set([message.author_id]) <NEW_LINE> <DEDENT> if message.partner_ids: <NEW_LINE> <INDENT> partners_to_notify |= set(message.partner_ids) <NEW_LINE> <DEDENT> notification_obj._notify(cr, uid, newid, partners_to_notify=[p.id for p in partners_to_notify], context=context) <NEW_LINE> message.refresh() <NEW_LINE> if message.parent_id: <NEW_LINE> <INDENT> partners_to_parent_notify = set(message.notified_partner_ids).difference(message.parent_id.notified_partner_ids) <NEW_LINE> for partner in partners_to_parent_notify: <NEW_LINE> <INDENT> notification_obj.create(cr, uid, { 'message_id': message.parent_id.id, 'partner_id': partner.id, 'read': True, }, context=context) | Messages model: system notification (replacing res.log notifications),
comments (OpenChatter discussion) and incoming emails. | 62599047d6c5a102081e3487 |
class Addresses2(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(Addresses2, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, Addresses2): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62599047498bea3a75a58e8a |
class CapabilityUpdate(ManagedObject): <NEW_LINE> <INDENT> consts = CapabilityUpdateConsts() <NEW_LINE> naming_props = set(['version']) <NEW_LINE> mo_meta = MoMeta("CapabilityUpdate", "capabilityUpdate", "update-[version]", VersionMeta.Version131c, "InputOutput", 0x3f, [], ["admin"], ['capabilityEp'], [], ["Get"]) <NEW_LINE> prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version131c, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "image_name": MoPropertyMeta("image_name", "imageName", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, None, 1, 64, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302c, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version131c, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), "update_ts": MoPropertyMeta("update_ts", "updateTs", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, None, None, None, r"""([0-9]){4}-([0-9]){2}-([0-9]){2}T([0-9]){2}:([0-9]){2}:([0-9]){2}((\.([0-9]){3})){0,1}""", [], []), "version": MoPropertyMeta("version", "version", "string", VersionMeta.Version131c, MoPropertyMeta.NAMING, 0x20, 1, 510, None, [], []), } <NEW_LINE> prop_map = { "childAction": "child_action", "dn": "dn", "imageName": "image_name", "rn": "rn", "sacl": "sacl", "status": "status", "updateTs": "update_ts", "version": "version", } <NEW_LINE> def __init__(self, parent_mo_or_dn, version, **kwargs): <NEW_LINE> <INDENT> self._dirty_mask = 0 <NEW_LINE> self.version = version <NEW_LINE> self.child_action = None <NEW_LINE> self.image_name = None <NEW_LINE> self.sacl = None <NEW_LINE> self.status = None <NEW_LINE> self.update_ts = None <NEW_LINE> ManagedObject.__init__(self, "CapabilityUpdate", parent_mo_or_dn, **kwargs) | This is CapabilityUpdate class. | 6259904782261d6c5273087b |
class GMPYRationalField(RationalField): <NEW_LINE> <INDENT> dtype = GMPYRational <NEW_LINE> zero = dtype(0) <NEW_LINE> one = dtype(1) <NEW_LINE> alias = 'QQ_gmpy' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def to_sympy(self, a): <NEW_LINE> <INDENT> return SymPyRational(int(gmpy_numer(a)), int(gmpy_denom(a))) <NEW_LINE> <DEDENT> def from_sympy(self, a): <NEW_LINE> <INDENT> if a.is_Rational: <NEW_LINE> <INDENT> return GMPYRational(a.p, a.q) <NEW_LINE> <DEDENT> elif a.is_Float: <NEW_LINE> <INDENT> from sympy.polys.domains import RR <NEW_LINE> return GMPYRational(*RR.as_integer_ratio(a)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise CoercionFailed("expected `Rational` object, got %s" % a) <NEW_LINE> <DEDENT> <DEDENT> def from_ZZ_python(K1, a, K0): <NEW_LINE> <INDENT> return GMPYRational(a) <NEW_LINE> <DEDENT> def from_QQ_python(K1, a, K0): <NEW_LINE> <INDENT> return GMPYRational(a.numerator, a.denominator) <NEW_LINE> <DEDENT> def from_ZZ_gmpy(K1, a, K0): <NEW_LINE> <INDENT> return GMPYRational(a) <NEW_LINE> <DEDENT> def from_QQ_gmpy(K1, a, K0): <NEW_LINE> <INDENT> return a <NEW_LINE> <DEDENT> def from_RR_mpmath(K1, a, K0): <NEW_LINE> <INDENT> return GMPYRational(*K0.as_integer_ratio(a)) <NEW_LINE> <DEDENT> def exquo(self, a, b): <NEW_LINE> <INDENT> return GMPYRational(gmpy_qdiv(a, b)) <NEW_LINE> <DEDENT> def quo(self, a, b): <NEW_LINE> <INDENT> return GMPYRational(gmpy_qdiv(a, b)) <NEW_LINE> <DEDENT> def rem(self, a, b): <NEW_LINE> <INDENT> return self.zero <NEW_LINE> <DEDENT> def div(self, a, b): <NEW_LINE> <INDENT> return GMPYRational(gmpy_qdiv(a, b)), self.zero <NEW_LINE> <DEDENT> def numer(self, a): <NEW_LINE> <INDENT> return a.numerator <NEW_LINE> <DEDENT> def denom(self, a): <NEW_LINE> <INDENT> return a.denominator <NEW_LINE> <DEDENT> def factorial(self, a): <NEW_LINE> <INDENT> return GMPYRational(gmpy_factorial(int(a))) | Rational field based on GMPY mpq class. | 62599047d10714528d69f043 |
class _CustomTexts(Model): <NEW_LINE> <INDENT> __tablename__ = 'customtexts' <NEW_LINE> id = Column(UnicodeText(36), primary_key=True, default=uuid4) <NEW_LINE> tid = Column(Integer, default=1, nullable=False) <NEW_LINE> lang = Column(UnicodeText(5), primary_key=True) <NEW_LINE> texts = Column(JSON, default=dict, nullable=False) <NEW_LINE> unicode_keys = ['lang'] <NEW_LINE> json_keys = ['texts'] <NEW_LINE> @declared_attr <NEW_LINE> def __table_args__(self): <NEW_LINE> <INDENT> return (ForeignKeyConstraint(['tid'], ['tenant.id'], ondelete='CASCADE', deferrable=True, initially='DEFERRED'),) | Class used to implement custom texts | 6259904710dbd63aa1c71f46 |
class GeoManager(Manager): <NEW_LINE> <INDENT> def get_query_set(self): <NEW_LINE> <INDENT> return GeoQuerySet(model=self.model) <NEW_LINE> <DEDENT> def area(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().area(*args, **kwargs) <NEW_LINE> <DEDENT> def centroid(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().centroid(*args, **kwargs) <NEW_LINE> <DEDENT> def difference(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().difference(*args, **kwargs) <NEW_LINE> <DEDENT> def distance(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().distance(*args, **kwargs) <NEW_LINE> <DEDENT> def envelope(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().envelope(*args, **kwargs) <NEW_LINE> <DEDENT> def extent(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().extent(*args, **kwargs) <NEW_LINE> <DEDENT> def gml(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().gml(*args, **kwargs) <NEW_LINE> <DEDENT> def intersection(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().intersection(*args, **kwargs) <NEW_LINE> <DEDENT> def kml(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().kml(*args, **kwargs) <NEW_LINE> <DEDENT> def length(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().length(*args, **kwargs) <NEW_LINE> <DEDENT> def make_line(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().make_line(*args, **kwargs) <NEW_LINE> <DEDENT> def mem_size(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().mem_size(*args, **kwargs) <NEW_LINE> <DEDENT> def num_geom(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().num_geom(*args, **kwargs) <NEW_LINE> <DEDENT> def num_points(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().num_points(*args, **kwargs) <NEW_LINE> <DEDENT> def perimeter(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().perimeter(*args, **kwargs) <NEW_LINE> <DEDENT> def point_on_surface(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().point_on_surface(*args, **kwargs) <NEW_LINE> <DEDENT> def scale(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().scale(*args, **kwargs) <NEW_LINE> <DEDENT> def svg(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().svg(*args, **kwargs) <NEW_LINE> <DEDENT> def sym_difference(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().sym_difference(*args, **kwargs) <NEW_LINE> <DEDENT> def transform(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().transform(*args, **kwargs) <NEW_LINE> <DEDENT> def translate(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().translate(*args, **kwargs) <NEW_LINE> <DEDENT> def union(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().union(*args, **kwargs) <NEW_LINE> <DEDENT> def unionagg(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.get_query_set().unionagg(*args, **kwargs) | Overrides Manager to return Geographic QuerySets. | 6259904726068e7796d4dcb3 |
class ParsingCheckError(ParsingError): <NEW_LINE> <INDENT> pass | Exception raised when a builtin check_*() function fails. | 6259904716aa5153ce40185a |
class DatasetDeflateCompression(DatasetCompression): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, } <NEW_LINE> _attribute_map = { 'additional_properties': {'key': '', 'type': '{object}'}, 'type': {'key': 'type', 'type': 'str'}, 'level': {'key': 'level', 'type': 'str'}, } <NEW_LINE> def __init__(self, additional_properties=None, level=None): <NEW_LINE> <INDENT> super(DatasetDeflateCompression, self).__init__(additional_properties=additional_properties) <NEW_LINE> self.level = level <NEW_LINE> self.type = 'Deflate' | The Deflate compression method used on a dataset.
:param additional_properties: Unmatched properties from the message are
deserialized this collection
:type additional_properties: dict[str, object]
:param type: Constant filled by server.
:type type: str
:param level: The Deflate compression level. Possible values include:
'Optimal', 'Fastest'
:type level: str or ~azure.mgmt.datafactory.models.DatasetCompressionLevel | 6259904745492302aabfd83e |
class MarkForumsReadView(TemplateView): <NEW_LINE> <INDENT> success_message = _('Forums have been marked read.') <NEW_LINE> template_name = 'forum_tracking/mark_forums_read.html' <NEW_LINE> @method_decorator(login_required) <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return super(MarkForumsReadView, self).dispatch(request, *args, **kwargs) <NEW_LINE> <DEDENT> def get(self, request, pk=None): <NEW_LINE> <INDENT> self.top_level_forum = get_object_or_404(Forum, pk=pk) if pk else None <NEW_LINE> return super(MarkForumsReadView, self).get(request, pk) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(MarkForumsReadView, self).get_context_data(**kwargs) <NEW_LINE> context['top_level_forum'] = self.top_level_forum <NEW_LINE> context['top_level_forum_url'] = self.get_top_level_forum_url() <NEW_LINE> return context <NEW_LINE> <DEDENT> def get_top_level_forum_url(self): <NEW_LINE> <INDENT> return reverse('forum:index') if self.top_level_forum is None else reverse('forum:forum', kwargs={'slug': self.top_level_forum.slug, 'pk': self.kwargs['pk']}) <NEW_LINE> <DEDENT> def mark_as_read(self, request, pk): <NEW_LINE> <INDENT> if self.top_level_forum is not None: <NEW_LINE> <INDENT> forums = request.forum_permission_handler.forum_list_filter( self.top_level_forum.get_descendants(include_self=True), request.user) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> forums = request.forum_permission_handler.forum_list_filter( Forum.objects.all(), request.user) <NEW_LINE> <DEDENT> track_handler.mark_forums_read(forums, request.user) <NEW_LINE> if len(forums): <NEW_LINE> <INDENT> messages.success(request, self.success_message) <NEW_LINE> <DEDENT> return HttpResponseRedirect(self.get_top_level_forum_url()) <NEW_LINE> <DEDENT> def post(self, request, pk=None): <NEW_LINE> <INDENT> self.top_level_forum = get_object_or_404(Forum, pk=pk) if pk else None <NEW_LINE> return self.mark_as_read(request, pk) | Marks a set of forums as read. | 62599047379a373c97d9a397 |
class LaberintoADT: <NEW_LINE> <INDENT> def __init__(self, rens, cols, pasillos): <NEW_LINE> <INDENT> self.__laberinto = Array2D(rens, cols, '1') <NEW_LINE> for a in pasillos: <NEW_LINE> <INDENT> self.__laberinto.set_item(a[0], a[1], '0') <NEW_LINE> <DEDENT> <DEDENT> def to_string(self): <NEW_LINE> <INDENT> self.__laberinto.to_string() | 0 Pasillo, 1 Pared, S Salida y E entrada
pasillos es una tupla con coordenadas | 62599047711fe17d825e1654 |
class Rectangle: <NEW_LINE> <INDENT> number_of_instances = 0 <NEW_LINE> print_symbol = '#' <NEW_LINE> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> if type(height) != int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if height < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> if type(width) != int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if width < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__height = height <NEW_LINE> self.__width = width <NEW_LINE> Rectangle.number_of_instances += 1 <NEW_LINE> <DEDENT> """Getting the private __height variable""" <NEW_LINE> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> """Setting the private __height variable""" <NEW_LINE> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) != int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> """Getting the private __width variable""" <NEW_LINE> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> """Setting the private __width variable""" <NEW_LINE> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) != int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> """Calculate the area of the rectangle""" <NEW_LINE> def area(self): <NEW_LINE> <INDENT> return self.__height * self.__width <NEW_LINE> <DEDENT> """Calculate the perimiter of the rectangle""" <NEW_LINE> def perimeter(self): <NEW_LINE> <INDENT> if self.__height == 0 or self.__width == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (self.__height + self.__height) + (self.__width + self.__width) <NEW_LINE> <DEDENT> """String Representation of rectangle class""" <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if self.__height == 0 or self.__width == 0: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> symb = (str(self.print_symbol) * self.__width) <NEW_LINE> rect_r = (symb + '\n') * (self.__height - 1) <NEW_LINE> return rect_r + symb <NEW_LINE> <DEDENT> """Representation of rectangle class""" <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return "Rectangle({:d}, {:d})".format(self.__width, self.__height) <NEW_LINE> <DEDENT> """Prititing message when instance of class is deleted""" <NEW_LINE> def __del__(self): <NEW_LINE> <INDENT> print("Bye rectangle...") <NEW_LINE> Rectangle.number_of_instances -= 1 | Initializing the Rectangle class
| 6259904723e79379d538d86b |
class DawgBuilder(object): <NEW_LINE> <INDENT> def __init__(self, reduced=True, field_root=False): <NEW_LINE> <INDENT> self._reduced = reduced <NEW_LINE> self._field_root = field_root <NEW_LINE> self.lastword = None <NEW_LINE> self.unchecked = [] <NEW_LINE> self.minimized = {} <NEW_LINE> self.root = BuildNode() <NEW_LINE> <DEDENT> def insert(self, word): <NEW_LINE> <INDENT> lw = self.lastword <NEW_LINE> prefixlen = 0 <NEW_LINE> if lw: <NEW_LINE> <INDENT> if self._field_root and lw[0] != word[0]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif word < lw: <NEW_LINE> <INDENT> raise Exception("Out of order %r..%r." % (self.lastword, word)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in xrange(min(len(word), len(lw))): <NEW_LINE> <INDENT> if word[i] != lw[i]: break <NEW_LINE> prefixlen += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._minimize(prefixlen) <NEW_LINE> if not self.unchecked: <NEW_LINE> <INDENT> node = self.root <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> node = self.unchecked[-1][2] <NEW_LINE> <DEDENT> for letter in word[prefixlen:]: <NEW_LINE> <INDENT> nextnode = BuildNode() <NEW_LINE> node.put(letter, nextnode) <NEW_LINE> self.unchecked.append((node, letter, nextnode)) <NEW_LINE> node = nextnode <NEW_LINE> <DEDENT> node.final = True <NEW_LINE> self.lastword = word <NEW_LINE> <DEDENT> def _minimize(self, downto): <NEW_LINE> <INDENT> for i in xrange(len(self.unchecked) - 1, downto - 1, -1): <NEW_LINE> <INDENT> (parent, letter, child) = self.unchecked[i]; <NEW_LINE> if child in self.minimized: <NEW_LINE> <INDENT> parent.put(letter, self.minimized[child]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.minimized[child] = child; <NEW_LINE> <DEDENT> self.unchecked.pop() <NEW_LINE> <DEDENT> <DEDENT> def finish(self): <NEW_LINE> <INDENT> self._minimize(0) <NEW_LINE> if self._reduced: <NEW_LINE> <INDENT> self.reduce(self.root, self._field_root) <NEW_LINE> <DEDENT> <DEDENT> def write(self, dbfile): <NEW_LINE> <INDENT> self.finish() <NEW_LINE> DawgWriter(dbfile).write(self.root) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def reduce(root, field_root=False): <NEW_LINE> <INDENT> if not field_root: <NEW_LINE> <INDENT> reduce(root) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for key in root: <NEW_LINE> <INDENT> v = root.edge(key) <NEW_LINE> reduce(v) | Class for building a graph from scratch.
>>> db = DawgBuilder()
>>> db.insert(u"alfa")
>>> db.insert(u"bravo")
>>> db.write(dbfile)
This class does not have the cleanest API, because it was cobbled together
to support the spelling correction system. | 625990470a366e3fb87ddd53 |
class GenericArrayCoderImpl(FieldCoderImpl): <NEW_LINE> <INDENT> def __init__(self, elem_coder: FieldCoderImpl): <NEW_LINE> <INDENT> self._elem_coder = elem_coder <NEW_LINE> <DEDENT> def encode_to_stream(self, value, out_stream): <NEW_LINE> <INDENT> out_stream.write_int32(len(value)) <NEW_LINE> for elem in value: <NEW_LINE> <INDENT> if elem is None: <NEW_LINE> <INDENT> out_stream.write_byte(False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out_stream.write_byte(True) <NEW_LINE> self._elem_coder.encode_to_stream(elem, out_stream) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def decode_from_stream(self, in_stream, length=0): <NEW_LINE> <INDENT> size = in_stream.read_int32() <NEW_LINE> elements = [self._elem_coder.decode_from_stream(in_stream) if in_stream.read_byte() else None for _ in range(size)] <NEW_LINE> return elements <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'GenericArrayCoderImpl[%s]' % repr(self._elem_coder) | A coder for object array value (the element of array could be any kind of Python object). | 62599047004d5f362081f99d |
class DataprocProjectsLocationsAutoscalingPoliciesDeleteRequest(_messages.Message): <NEW_LINE> <INDENT> name = _messages.StringField(1, required=True) | A DataprocProjectsLocationsAutoscalingPoliciesDeleteRequest object.
Fields:
name: Required. The "resource name" of the autoscaling policy, as
described in https://cloud.google.com/apis/design/resource_names of the
form
projects/{project_id}/regions/{region}/autoscalingPolicies/{policy_id}. | 62599047d53ae8145f9197cd |
class IptablesAuth(models.Model): <NEW_LINE> <INDENT> user = models.CharField(u'用户名', unique=True, max_length=32) <NEW_LINE> ip = models.CharField(u'ip地址', max_length=32) <NEW_LINE> p_key = models.CharField(u'私钥', max_length=32) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "iptables用户验证" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.user | iptables登陆验证 | 62599047462c4b4f79dbcd6c |
@implementer(IBodyProducer) <NEW_LINE> class BytesProducer(object): <NEW_LINE> <INDENT> def __init__(self, body): <NEW_LINE> <INDENT> self.body = body if body != None else b"" <NEW_LINE> self.length = len(self.body) <NEW_LINE> <DEDENT> def startProducing(self, consumer): <NEW_LINE> <INDENT> consumer.write(self.body) <NEW_LINE> return succeed(None) <NEW_LINE> <DEDENT> def pauseProducing(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def stopProducing(self): <NEW_LINE> <INDENT> pass | 生成http请求的body部分 | 625990473eb6a72ae038b9c8 |
class vernier(pya.PCellDeclarationHelper): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(vernier, self).__init__() <NEW_LINE> self.param("layer", self.TypeLayer, "Layer", default = pya.LayerInfo(1, 0)) <NEW_LINE> self.param("width", self.TypeDouble, "Width [um]", default = 4) <NEW_LINE> self.param("length", self.TypeDouble, "Length [um]", default = 40) <NEW_LINE> self.param("pitch", self.TypeDouble, "Pitch [um]", default = 8) <NEW_LINE> self.param("invert", self.TypeBoolean, "Hole", default = False) <NEW_LINE> self.param("border", self.TypeDouble, " Border Width [um]", default = 10) <NEW_LINE> <DEDENT> def display_text_impl(self): <NEW_LINE> <INDENT> return "Vernier Pattern\n" + "Pitch [um] = " + str('%.3f' % self.pitch) + "\n" + "Width [um] = " + str('%.3f' % self.width) <NEW_LINE> <DEDENT> def coerce_parameters_impl(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def can_create_from_shape_impl(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def parameters_from_shape_impl(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def transformation_from_shape_impl(self): <NEW_LINE> <INDENT> return pya.Trans(pya.Point(0,0)) <NEW_LINE> <DEDENT> def produce_impl(self): <NEW_LINE> <INDENT> dbu = self.layout.dbu <NEW_LINE> w = self.width / dbu <NEW_LINE> l = self.length / dbu <NEW_LINE> p = self.pitch / dbu <NEW_LINE> b = self.border / dbu <NEW_LINE> s = shape() <NEW_LINE> region = s.vernier(w,l,p) <NEW_LINE> if (self.invert): <NEW_LINE> <INDENT> region = s.invert(region,b) <NEW_LINE> <DEDENT> self.cell.shapes(self.layer_layer).insert(region) | Generates a vernier scale pattern
Parameters
---------
layer : from interface
The layer and datatype for the patterns
width : from interface
The width of each tick mark
length : from interface
The length of the central tick mark
pitch : from interface
The distance between neighboring tick marks
invert : from interface
Invert the pattern?
border : from interface
The space between the bounding box and the inverted pattern
Description
---------
A pair of vernier scale can be used to measure misalignment by eye.
In photolithography the wafer will contain one vernier pattern (width = 4, length = 40, pitch = 8, units = micron)
and the mask will contain a second vernier pattern (pitch = 8.2) providing an alignment measurement resolution of 0.2 micron. | 6259904773bcbd0ca4bcb5fb |
class FeaturedSpeakerForm(messages.Message): <NEW_LINE> <INDENT> name = messages.StringField(1) <NEW_LINE> sessions = messages.StringField(2, repeated=True) | outbound Form containing fields for Speaker name
and corresponding Session names | 625990478da39b475be0455e |
class CDMIContainer(object): <NEW_LINE> <INDENT> def __init__(self, drastic_container, api_root): <NEW_LINE> <INDENT> self.collection = drastic_container <NEW_LINE> self.api_root = api_root <NEW_LINE> <DEDENT> def get_capabilitiesURI(self): <NEW_LINE> <INDENT> return (u'{0}/cdmi_capabilities/container{1}' ''.format(self.api_root, self.collection.path) ) <NEW_LINE> <DEDENT> def get_children(self, range=None): <NEW_LINE> <INDENT> child_c , child_r = self.collection.get_child() <NEW_LINE> child_c = [ u"{}/".format(c) for c in child_c ] <NEW_LINE> res = child_c + child_r <NEW_LINE> if range: <NEW_LINE> <INDENT> start, stop = ( int(el) for el in range.split("-", 1)) <NEW_LINE> stop += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start = 0 <NEW_LINE> stop = len(res) <NEW_LINE> <DEDENT> return res[start:stop] <NEW_LINE> <DEDENT> def get_childrenrange(self): <NEW_LINE> <INDENT> child_container , child_dataobject = self.collection.get_child() <NEW_LINE> nb_child = len(child_container) + len(child_dataobject) <NEW_LINE> if nb_child != 0: <NEW_LINE> <INDENT> return "{}-{}".format(0, nb_child-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "0-0" <NEW_LINE> <DEDENT> <DEDENT> def get_completionStatus(self): <NEW_LINE> <INDENT> val = self.collection.get_metadata_key("cdmi_completionStatus") <NEW_LINE> if not val: <NEW_LINE> <INDENT> val = "Complete" <NEW_LINE> <DEDENT> return val <NEW_LINE> <DEDENT> def get_domainURI(self): <NEW_LINE> <INDENT> return ('{0}/cdmi_domains/drastic/'.format(self.api_root)) <NEW_LINE> <DEDENT> def get_metadata(self): <NEW_LINE> <INDENT> md = self.collection.get_cdmi_metadata() <NEW_LINE> md.update(self.collection.get_acl_metadata()) <NEW_LINE> return md <NEW_LINE> <DEDENT> def get_objectID(self): <NEW_LINE> <INDENT> return self.collection.uuid <NEW_LINE> <DEDENT> def get_objectName(self): <NEW_LINE> <INDENT> return self.collection.name <NEW_LINE> <DEDENT> def get_objectType(self): <NEW_LINE> <INDENT> return "application/cdmi-container" <NEW_LINE> <DEDENT> def get_parentID(self): <NEW_LINE> <INDENT> parent_path = self.collection.container <NEW_LINE> if self.collection.is_root: <NEW_LINE> <INDENT> parent_path = u"/" <NEW_LINE> <DEDENT> parent = Collection.find(parent_path) <NEW_LINE> return parent.uuid <NEW_LINE> <DEDENT> def get_parentURI(self): <NEW_LINE> <INDENT> parent_path = self.collection.container <NEW_LINE> if parent_path != '/' and parent_path != "null": <NEW_LINE> <INDENT> parent_path = u"{}/".format(parent_path) <NEW_LINE> <DEDENT> return u"{}".format(parent_path) <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> return self.collection.path <NEW_LINE> <DEDENT> def get_percentComplete(self): <NEW_LINE> <INDENT> val = self.collection.get_metadata_key("cdmi_percentComplete") <NEW_LINE> if not val: <NEW_LINE> <INDENT> val = "100" <NEW_LINE> <DEDENT> return val | Wrapper to return CDMI fields from a Drastic Collection | 62599047379a373c97d9a399 |
class TreeDragWidget(QtGui.QTreeWidget): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super(TreeDragWidget, self).__init__(parent) <NEW_LINE> self.setDragEnabled(True) <NEW_LINE> self.setDropIndicatorShown(True) <NEW_LINE> self.setDragDropMode(QtGui.QAbstractItemView.DragOnly) <NEW_LINE> <DEDENT> def mimeTypes(self): <NEW_LINE> <INDENT> return ['function/plain'] <NEW_LINE> <DEDENT> def mimeData(self, items): <NEW_LINE> <INDENT> tree_item = items[0] <NEW_LINE> if tree_item.childCount() == 0: <NEW_LINE> <INDENT> data = tree_item.data(0, QtCore.Qt.UserRole) <NEW_LINE> self._mime_data = QtCore.QMimeData() <NEW_LINE> self._mime_data.setData('function/plain', data.encode('utf8')) <NEW_LINE> return self._mime_data | Extends QtGui.QTreeWidget and lets it use drag and drop. | 62599047e76e3b2f99fd9d7a |
class SkillsField(ArrayField): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.setdefault('base_field', models.CharField(max_length=30, blank=False)) <NEW_LINE> kwargs.setdefault('blank', True) <NEW_LINE> kwargs.setdefault('default', list) <NEW_LINE> super().__init__(*args, **kwargs) | ArrayField subclass to be used for saving skills under Seeker. Requires Postgres database. | 6259904729b78933be26aa7a |
class Square(Marker): <NEW_LINE> <INDENT> __example__ = "tests/glyphs/Square.py" | Render a square marker, optionally rotated. | 6259904723e79379d538d86d |
class IndexType(IntEnum): <NEW_LINE> <INDENT> VARIABLE = 1 <NEW_LINE> FORCED_INPUT = 2 <NEW_LINE> NONE = 3 | Represents the type of an index, can be either a index to state variables,
forced inputs or no index. | 6259904782261d6c5273087d |
class CatalogClass: <NEW_LINE> <INDENT> x1 = 'x1' <NEW_LINE> x2 = 'x2' <NEW_LINE> def __init__(self, param): <NEW_LINE> <INDENT> if param in self._class_method_choices: <NEW_LINE> <INDENT> self.param = param <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(f'Invalid Value for Param: {param}') <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def _class_method_1(cls): <NEW_LINE> <INDENT> print(f'Value {cls.x1}') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _class_method_2(cls): <NEW_LINE> <INDENT> print(f'Value {cls.x2}') <NEW_LINE> <DEDENT> _class_method_choices = { 'p1': _class_method_1, 'p2': _class_method_2, } <NEW_LINE> def main_method(self): <NEW_LINE> <INDENT> self._class_method_choices[self.param].__get__(None, self.__class__)() | 第三种: 调用时更麻烦一点, 而且还要 @classmethod 修饰 | 625990478a43f66fc4bf3504 |
class GrossShippingMethodPriceCalculator(ShippingMethodPriceCalculator): <NEW_LINE> <INDENT> def get_price_net(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.shipping_method.price / ((100 + self.shipping_method.tax.rate) / 100) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return self.shipping_method.price <NEW_LINE> <DEDENT> <DEDENT> def get_price_gross(self): <NEW_LINE> <INDENT> return self.shipping_method.price | ShippingMethodPriceCalculator which considers the entered price as gross
price.
See lfs.plugins.ShippingMethodPriceCalculator | 625990470fa83653e46f624c |
class Content(models.Model): <NEW_LINE> <INDENT> code = models.CharField(max_length=30, ) <NEW_LINE> name = models.CharField(max_length=70, blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Matière' <NEW_LINE> ordering = ['code', 'name'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return ('%s : %s') % (self.code, self.name) | Matières d'enseignement | 625990476fece00bbacccd25 |
class SphinxDocsBuilder: <NEW_LINE> <INDENT> def __init__(self, html_output_dir, is_release=True): <NEW_LINE> <INDENT> self.documented_modules = self._get_module_names_from_index_rst() <NEW_LINE> self.python_api_output_dir = "python_api" <NEW_LINE> self.html_output_dir = html_output_dir <NEW_LINE> self.is_release = is_release <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _get_module_names_from_index_rst(): <NEW_LINE> <INDENT> module_names = [] <NEW_LINE> with open('index.rst', 'r') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> m = re.match( '\s*MAKE_DOCS/python_api/([^\s]*)\s*(.*)\s*$', line) <NEW_LINE> if m: <NEW_LINE> <INDENT> module_names.append((m.group(1), m.group(2))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return module_names <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self._gen_python_api_docs() <NEW_LINE> self._run_sphinx() <NEW_LINE> <DEDENT> def _gen_python_api_docs(self): <NEW_LINE> <INDENT> pd = PyAPIDocsBuilder(self.python_api_output_dir, self.documented_modules) <NEW_LINE> pd.generate_rst() <NEW_LINE> <DEDENT> def _run_sphinx(self): <NEW_LINE> <INDENT> build_dir = os.path.join(self.html_output_dir, "html") <NEW_LINE> if self.is_release: <NEW_LINE> <INDENT> version_list = [ line.rstrip('\n').split(' ')[1] for line in open('../src/version.txt') ] <NEW_LINE> release_version = '.'.join(version_list[:3]) <NEW_LINE> print("Building docs for release:", release_version) <NEW_LINE> cmd = [ "sphinx-build", "-b", "html", "-D", "version=" + release_version, "-D", "release=" + release_version, "-j", str(multiprocessing.cpu_count()), ".", build_dir, ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cmd = [ "sphinx-build", "-b", "html", "-j", str(multiprocessing.cpu_count()), ".", build_dir, ] <NEW_LINE> <DEDENT> print('Calling: "%s"' % " ".join(cmd)) <NEW_LINE> subprocess.check_call(cmd, stdout=sys.stdout, stderr=sys.stderr) | SphinxDocsBuilder calls Python api docs generation and then calls
sphinx-build:
(1) The user call `make *` (e.g. `make html`) gets forwarded to make.py
(2) Calls PyAPIDocsBuilder to generate Python api docs rst files
(3) Calls `sphinx-build` with the user argument | 62599047cad5886f8bdc5a36 |
class SignupForm(UserCreationForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = get_user_model() <NEW_LINE> fields = ('username', 'email') <NEW_LINE> <DEDENT> def clean_username(self): <NEW_LINE> <INDENT> username = self.cleaned_data.get('username') <NEW_LINE> if not username: <NEW_LINE> <INDENT> raise forms.ValidationError(_("USERNAME IS REQUIRED"), code='invalid') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> get_user_model().objects.get(username=username) <NEW_LINE> raise forms.ValidationError(_("THAT USERNAME IS ALREADY USED"), code='invalid') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return username <NEW_LINE> <DEDENT> <DEDENT> def clean_email(self): <NEW_LINE> <INDENT> email = self.cleaned_data.get("email") <NEW_LINE> if not email: <NEW_LINE> <INDENT> raise forms.ValidationError(_("E-MAIL IS REQUIRED"), code='invalid') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> get_user_model().objects.get(email=email) <NEW_LINE> raise forms.ValidationError(_("THAT E-MAIL IS ALREADY USED"), code='invalid') <NEW_LINE> <DEDENT> except get_user_model().DoesNotExist: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> EmailValidation.objects.get(email=email) <NEW_LINE> raise forms.ValidationError(_("THAT E-MAIL IS ALREADY CONFIRMED"), code='invalid') <NEW_LINE> <DEDENT> except EmailValidation.DoesNotExist: <NEW_LINE> <INDENT> return email <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def clean_password1(self): <NEW_LINE> <INDENT> password1 = self.cleaned_data.get('password1') <NEW_LINE> if not password1: <NEW_LINE> <INDENT> raise forms.ValidationError(_("PASSWORD IS REQUIRED"), code='invalid') <NEW_LINE> <DEDENT> return password1 <NEW_LINE> <DEDENT> def clean_password2(self): <NEW_LINE> <INDENT> password2 = self.cleaned_data.get('password2') <NEW_LINE> if not password2: <NEW_LINE> <INDENT> raise forms.ValidationError(_("PASSWORD IS REQUIRED"), code='invalid') <NEW_LINE> <DEDENT> if not password2 == self.cleaned_data.get('password1'): <NEW_LINE> <INDENT> raise forms.ValidationError(_("PASSWORDS ARE MISMATCH"), code='invalid') <NEW_LINE> <DEDENT> return password2 | Form for registering a new user userprofile. | 625990478e71fb1e983bce3f |
class TestSubmission(models.Model): <NEW_LINE> <INDENT> id = models.AutoField(primary_key=True) <NEW_LINE> right_answers_number = models.IntegerField(null=True) <NEW_LINE> date_submission = models.DateTimeField(null=False) <NEW_LINE> test = models.ForeignKey(Test, on_delete=models.CASCADE, null=False, related_name="test") <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, related_name="user") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['-id'] <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.pk: <NEW_LINE> <INDENT> if not self.date_submission: <NEW_LINE> <INDENT> self.date_submission = localtime() <NEW_LINE> <DEDENT> <DEDENT> super().save(*args, **kwargs) | Passed test model class. | 6259904726238365f5fadecc |
class BinHumanBytes(HumanBytes): <NEW_LINE> <INDENT> def __init__(self,formatter=None): <NEW_LINE> <INDENT> super(self.__class__,self).__init__(1024,( 'B','KB','MB','GB','TB','PB','EB','ZB','YB' ),formatter=formatter) <NEW_LINE> <DEDENT> def format(self,val,formatter=None): <NEW_LINE> <INDENT> if formatter==None: <NEW_LINE> <INDENT> formatter=self.formatter <NEW_LINE> <DEDENT> val,units=self._findUnits(val) <NEW_LINE> return "{0} {1}".format(formatter(val),units) | BinHumanBytes instances use a divisor of 10**3 to express a given
number of bytes in a form easy for humans to interpret. These are the
available units:
B
KB
MB
GB
TB
PB
EB
ZB
YB | 6259904707f4c71912bb07a3 |
class Authentication(object): <NEW_LINE> <INDENT> def is_authenticated(self, request): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def challenge_headers(self): <NEW_LINE> <INDENT> raise NotImplementedError | Authentication interface | 6259904715baa72349463301 |
class IFunction(object): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'name', None, None, ), (2, TType.STRING, 'code', None, None, ), ) <NEW_LINE> def __init__(self, name=None, code=None,): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.code = code <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.name = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.code = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('IFunction') <NEW_LINE> if self.name != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('name', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.name) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.code != None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('code', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.code) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- name
- code | 6259904723849d37ff85242d |
class _xSEEntryPLGN(_ChunkEntry, _Dumpable, _Remappable): <NEW_LINE> <INDENT> __slots__ = ('mod_index', 'light_index', 'mod_name') <NEW_LINE> def __init__(self, ins): <NEW_LINE> <INDENT> self.mod_index = unpack_byte(ins) <NEW_LINE> if self.mod_index == 0xFE: <NEW_LINE> <INDENT> self.light_index = unpack_short(ins) <NEW_LINE> <DEDENT> self.mod_name = _unpack_cosave_str16(ins) <NEW_LINE> <DEDENT> def write_entry(self, out): <NEW_LINE> <INDENT> pack_byte(out, self.mod_index) <NEW_LINE> if self.mod_index == 0xFE: <NEW_LINE> <INDENT> pack_short(out, self.light_index) <NEW_LINE> <DEDENT> _pack_cosave_str16(out, self.mod_name) <NEW_LINE> <DEDENT> def entry_length(self): <NEW_LINE> <INDENT> total_len = 5 if self.mod_index == 0xFE else 3 <NEW_LINE> return total_len + len(self.mod_name) <NEW_LINE> <DEDENT> def dump_to_log(self, log, save_masters_): <NEW_LINE> <INDENT> if self.mod_index != 0xFE: <NEW_LINE> <INDENT> log(f' {self.mod_index:02X} - ' f'{self.mod_name}') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log(f' {self.mod_index:02X} {self.light_index:04X} ' f' {self.mod_name}') <NEW_LINE> <DEDENT> <DEDENT> def remap_plugins(self, plugin_renames): <NEW_LINE> <INDENT> self.mod_name = plugin_renames.get(self.mod_name, self.mod_name) | A single PLGN entry. A PLGN chunk contains several of these. | 62599047d4950a0f3b1117fa |
class Deck: <NEW_LINE> <INDENT> def __init__(self, dead_cards: Iterable=None): <NEW_LINE> <INDENT> self.cards = [Card(rank, suit) for rank in range(2, 15) for suit in range(1, 5)] <NEW_LINE> if dead_cards: <NEW_LINE> <INDENT> self.remove_cards(dead_cards) <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self.cards[item] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.cards) <NEW_LINE> <DEDENT> def remove_cards(self, cards: Iterable): <NEW_LINE> <INDENT> for card in cards: <NEW_LINE> <INDENT> self.cards.remove(card) | Class representing a standard deck | 6259904745492302aabfd842 |
class User(Base): <NEW_LINE> <INDENT> __tablename__ = 'user' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String(80), nullable=False) <NEW_LINE> email = Column(String(250), nullable=False) <NEW_LINE> picture = Column(String(250)) <NEW_LINE> @property <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'name': self.name, 'email': self.email, 'picture': self.picture, } | Logged in users information will be stored in user table in db | 6259904716aa5153ce40185e |
class AESCipher(object): <NEW_LINE> <INDENT> def __init__(self, key,bs): <NEW_LINE> <INDENT> self.bs = bs <NEW_LINE> self.key = key <NEW_LINE> <DEDENT> def encrypt(self, raw): <NEW_LINE> <INDENT> raw = self._pad(raw) <NEW_LINE> iv = Random.new().read(AES.block_size) <NEW_LINE> cipher = AES.new(self.key, AES.MODE_CBC, iv) <NEW_LINE> return base64.b64encode(iv + cipher.encrypt(raw)) <NEW_LINE> <DEDENT> def decrypt(self, enc): <NEW_LINE> <INDENT> enc = base64.b64decode(enc) <NEW_LINE> iv = enc[:AES.block_size] <NEW_LINE> cipher = AES.new(self.key, AES.MODE_CBC, iv) <NEW_LINE> return self._unpad(cipher.decrypt(enc[AES.block_size:])) <NEW_LINE> <DEDENT> def _pad(self, s): <NEW_LINE> <INDENT> return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) <NEW_LINE> <DEDENT> def _unpad(self,s): <NEW_LINE> <INDENT> return s[:-ord(s[len(s)-1:])] | - AESCipher is responsible for the management and initilization of the AES encryption process.
- It contains methods to perform encryption decryption as well as padding.
- key management to be done | 6259904730c21e258be99b77 |
class x_wmi_authentication (x_wmi): <NEW_LINE> <INDENT> pass | Raised when an invalid combination of authentication properties is attempted when connecting | 62599047ec188e330fdf9c0d |
class LabPair(Tkinter.Frame): <NEW_LINE> <INDENT> def __init__(self, master, deflist, name, **kw): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.default = kw.get('default') <NEW_LINE> self.hide = kw.get('hide') <NEW_LINE> label = kw.get('label', string.upper(name[:1]) + name[1:]) <NEW_LINE> self.label = Tkinter.Label(master, name="label", text=label, width=7, anchor='ne') <NEW_LINE> self.label.pack(side='top', expand=1, fill='both') <NEW_LINE> self.value = Tkinter.Label(master, name="value", anchor='ne') <NEW_LINE> self.value.pack(side='top', expand=1, fill='both') <NEW_LINE> try: <NEW_LINE> <INDENT> self.value.bind('<Button-1>', (lambda e, c=kw['command'], n=name: c(n))) <NEW_LINE> bindLabel(self.value) <NEW_LINE> <DEDENT> except KeyError: pass <NEW_LINE> self.value.bind('<Control-1>', (lambda e, self=self: viewer.cen.EditField(self.name))) <NEW_LINE> deflist[name] = self.update <NEW_LINE> <DEDENT> def update(self, val, db): <NEW_LINE> <INDENT> if callable(self.default): <NEW_LINE> <INDENT> val = self.default(val, db) <NEW_LINE> <DEDENT> elif val == self.default: <NEW_LINE> <INDENT> val = "" <NEW_LINE> <DEDENT> if ((callable(self.hide) and self.hide(val, db)) or val == self.hide): <NEW_LINE> <INDENT> self.label.pack_forget() <NEW_LINE> self.value.pack_forget() <NEW_LINE> <DEDENT> elif ((callable(self.hide) and self.hide(self.value['text'])) or self.value['text'] == str(self.hide)): <NEW_LINE> <INDENT> self.label.pack(expand=1, fill='both') <NEW_LINE> self.value.pack(expand=1, fill='both') <NEW_LINE> <DEDENT> self.value['text'] = val | Create a label/value pair for HDL with description LABEL. | 625990478e05c05ec3f6f813 |
class SeverityLevel(object): <NEW_LINE> <INDENT> verbose = 0 <NEW_LINE> information = 1 <NEW_LINE> warning = 2 <NEW_LINE> error = 3 <NEW_LINE> critical = 4 | Data contract class for type SeverityLevel. | 62599047dc8b845886d5492c |
class ViewsTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_page_redirects_when_not_logged_in(self): <NEW_LINE> <INDENT> with shoppinglister.app.test_request_context(): <NEW_LINE> <INDENT> self.assertEqual( shoppinglister.views.shopping_list().status_code, 302) <NEW_LINE> self.assertEqual(shoppinglister.views.shopping_list().location, url_for('lister.login')) <NEW_LINE> <DEDENT> <DEDENT> def test_logout(self): <NEW_LINE> <INDENT> with shoppinglister.app.test_request_context(): <NEW_LINE> <INDENT> self.assertEqual(shoppinglister.views.logout().status_code, 302) <NEW_LINE> self.assertEqual(shoppinglister.views.logout().location, url_for('lister.signup')) | Contains tests for the views | 62599047e64d504609df9d89 |
class TreeViewCustomGui(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def IsFocusItem(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def MakeVisible(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Refresh(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def SetFocusItem(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def SetHeaderText(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def SetLayout(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def SetRoot(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ShowObject(self, *args, **kwargs): <NEW_LINE> <INDENT> pass | TreeView gadget - Dialog element. | 6259904771ff763f4b5e8b15 |
class LCDCheckBox(urwid.CheckBox): <NEW_LINE> <INDENT> states = { True: urwid.SelectableIcon('\xd0'), False: urwid.SelectableIcon('\x05'), } <NEW_LINE> reserve_columns = 1 | A check box+label that uses only one character for the check box,
including custom CGRAM character | 625990471f5feb6acb163f67 |
class SKU(BaseModel): <NEW_LINE> <INDENT> name = models.CharField(max_length=50, verbose_name='名称') <NEW_LINE> caption = models.CharField(max_length=100, verbose_name='副标题') <NEW_LINE> spu = models.ForeignKey(SPU, related_name='skus', on_delete=models.CASCADE, verbose_name='商品') <NEW_LINE> category = models.ForeignKey(GoodsCategory, on_delete=models.PROTECT, verbose_name='从属类别') <NEW_LINE> price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='单价') <NEW_LINE> cost_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='进价') <NEW_LINE> market_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='市场价') <NEW_LINE> stock = models.IntegerField(default=0, verbose_name='库存') <NEW_LINE> sales = models.IntegerField(default=0, verbose_name='销量') <NEW_LINE> comments = models.IntegerField(default=0, verbose_name='评价数') <NEW_LINE> is_launched = models.BooleanField(default=True, verbose_name='是否上架销售') <NEW_LINE> default_image = models.ImageField(max_length=200, default='', null=True, blank=True, verbose_name='默认图片') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'tb_sku' <NEW_LINE> verbose_name = '商品SKU' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s: %s' % (self.id, self.name) | 商品SKU | 625990476fece00bbacccd27 |
class ZkRenumberHeadingsCommand(sublime_plugin.TextCommand): <NEW_LINE> <INDENT> def run(self, edit): <NEW_LINE> <INDENT> current_level = 0 <NEW_LINE> levels = [0] * 6 <NEW_LINE> regions_to_skip = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> h_regions = self.view.find_by_selector('markup.heading.markdown') <NEW_LINE> h_regions = h_regions[regions_to_skip:] <NEW_LINE> if not h_regions: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> regions_to_skip += 1 <NEW_LINE> h_region = h_regions[0] <NEW_LINE> heading = self.view.substr(h_region) <NEW_LINE> match = re.match('(\s*)(#+)(\s*[1-9.]*\s)(.*)', heading) <NEW_LINE> spaces, hashes, old_numbering, title = match.groups() <NEW_LINE> level = len(hashes) - 1 <NEW_LINE> levels[level] += 1 <NEW_LINE> if level < current_level: <NEW_LINE> <INDENT> levels[:current_level] + [0] * (6 - level) <NEW_LINE> <DEDENT> numbering = ' ' + '.'.join([str(l) for l in levels[:level+1]]) + ' ' <NEW_LINE> h_region.a += len(spaces) + len(hashes) <NEW_LINE> if old_numbering.strip(): <NEW_LINE> <INDENT> h_region.b = h_region.a + len(old_numbering) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> h_region.b = h_region.a <NEW_LINE> <DEDENT> self.view.replace(edit, h_region, numbering) | Re-number headings of the current note. | 6259904715baa72349463302 |
class OraSegment(OraObject): <NEW_LINE> <INDENT> def getTablespace(self, db): <NEW_LINE> <INDENT> raise PysqlNotImplemented() | Father of tables and indexes | 62599047596a897236128f68 |
class PageEditSerializer(serializers.HyperlinkedModelSerializer): <NEW_LINE> <INDENT> raw = serializers.CharField() <NEW_LINE> message = serializers.CharField(write_only=True) <NEW_LINE> extra_data = serializers.SerializerMethodField() <NEW_LINE> def get_extra_data(self, page): <NEW_LINE> <INDENT> form_extra_data = {} <NEW_LINE> receivers_responses = page_preedit.send(sender=views.edit, page=page) <NEW_LINE> for r in receivers_responses: <NEW_LINE> <INDENT> if isinstance(r[1], dict) and 'form_extra_data' in r[1]: <NEW_LINE> <INDENT> form_extra_data.update(r[1]['form_extra_data']) <NEW_LINE> <DEDENT> <DEDENT> return json.dumps(form_extra_data) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> mutable = self.context['request'].POST._mutable <NEW_LINE> self.context['request'].POST._mutable = True <NEW_LINE> kwargs['slug'] = self.instance.slug <NEW_LINE> page = Page.objects.filter(slug=kwargs['slug'])[0] <NEW_LINE> new_title = self.context['request'].POST.get('title', page.title) <NEW_LINE> self.context['request'].POST['title'] = page.title <NEW_LINE> self.context['request'].POST['markup'] = WALIKI_DEFAULT_MARKUP <NEW_LINE> self.context['request'].POST._mutable = mutable <NEW_LINE> if not self.context['request'].POST.get('extra_data', False): <NEW_LINE> <INDENT> mutable = self.context['request'].POST._mutable <NEW_LINE> self.context['request'].POST._mutable = True <NEW_LINE> self.context['request'].POST['extra_data'] = self.get_extra_data(self.instance) <NEW_LINE> self.context['request'].POST._mutable = mutable <NEW_LINE> <DEDENT> response = views.edit(self.context['request'],*args, **kwargs) <NEW_LINE> commit = json.loads(self.get_extra_data(self.instance))['parent'] <NEW_LINE> page_request.send( sender=Request, new_title=new_title, page=page, commit=commit, author=self.context['request'].user, message=self.context['request'].POST['message']) <NEW_LINE> if self.context['request'].user.has_perm( 'wiki.can_approve_request' ): <NEW_LINE> <INDENT> request = Request.objects.filter(commit=commit)[0] <NEW_LINE> request.approve_request(self.context['request'].user) <NEW_LINE> <DEDENT> <DEDENT> class Meta(): <NEW_LINE> <INDENT> model = Page <NEW_LINE> fields = ('id', 'title', 'slug', 'raw', 'markup' ,'message', 'extra_data', ) <NEW_LINE> read_only_fields = ('id', 'slug', ) | Serializer Class to edit a Page. | 62599047a8ecb03325872583 |
class PyPickleshare(PythonPackage): <NEW_LINE> <INDENT> pypi = "pickleshare/pickleshare-0.7.4.tar.gz" <NEW_LINE> version('0.7.5', sha256='87683d47965c1da65cdacaf31c8441d12b8044cdec9aca500cd78fc2c683afca') <NEW_LINE> version('0.7.4', sha256='84a9257227dfdd6fe1b4be1319096c20eb85ff1e82c7932f36efccfe1b09737b') <NEW_LINE> depends_on('[email protected]:2.8,3:', type=('build', 'run')) <NEW_LINE> depends_on('py-setuptools', type='build') <NEW_LINE> depends_on('py-pathlib2', type=('build', 'run'), when='^[email protected]:2.8,3.2:3.3') | Tiny 'shelve'-like database with concurrency support | 62599047435de62698e9d177 |
class TestRemovePermissions(unittest.TestCase): <NEW_LINE> <INDENT> layer = FTW_PERMISSIONMGR_INTEGRATION_TESTING <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> portal = self.layer['portal'] <NEW_LINE> portal.portal_membership.setLocalRoles( obj=portal.folder1, member_ids=[TEST_USER_ID], member_role="Contributor", reindex=True) <NEW_LINE> portal.folder1.reindexObjectSecurity() <NEW_LINE> <DEDENT> def test_has_manager_role(self): <NEW_LINE> <INDENT> portal = self.layer['portal'] <NEW_LINE> view = SharingView(portal.folder1, portal.folder1.REQUEST) <NEW_LINE> self.assertTrue(view.has_manage_portal()) <NEW_LINE> <DEDENT> def test_has_local_role(self): <NEW_LINE> <INDENT> portal = self.layer['portal'] <NEW_LINE> view = SharingView(portal.folder1, portal.folder1.REQUEST) <NEW_LINE> self.assertTrue(view.has_local_role()) <NEW_LINE> logout() <NEW_LINE> login(portal, TEST_USER_ID_2) <NEW_LINE> self.assertFalse(view.has_local_role()) <NEW_LINE> logout() <NEW_LINE> login(portal, TEST_USER_NAME) <NEW_LINE> <DEDENT> def test_role_settings(self): <NEW_LINE> <INDENT> portal = self.layer['portal'] <NEW_LINE> view = SharingView(portal.folder1, portal.folder1.REQUEST) <NEW_LINE> for entry in view.role_settings(): <NEW_LINE> <INDENT> if entry['id'] == TEST_USER_ID: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> self.assertTrue(entry['roles']['Contributor']) | Sharing is well tested by Plone, so just our customized methods | 6259904707f4c71912bb07a5 |
class CPWWigglesByArea: <NEW_LINE> <INDENT> def __init__(self, structure, length, width, start_up=True, radius=None, pinw=None, gapw=None): <NEW_LINE> <INDENT> s = structure <NEW_LINE> if pinw is None: <NEW_LINE> <INDENT> pinw = s.__dict__['pinw'] <NEW_LINE> <DEDENT> if gapw is None: <NEW_LINE> <INDENT> gapw = s.__dict__['gapw'] <NEW_LINE> <DEDENT> if radius is None: <NEW_LINE> <INDENT> radius = s.__dict__['radius'] <NEW_LINE> <DEDENT> num_wiggles = int(floor(length / (2 * radius) - 1)) <NEW_LINE> padding = length - 2 * (num_wiggles + 1) * radius <NEW_LINE> vlength = (width - 4 * radius) / 2. <NEW_LINE> total_length = (1 + num_wiggles) * (pi * radius) + 2 * num_wiggles * vlength + 2 * (num_wiggles - 1) * radius <NEW_LINE> self.num_wiggles = num_wiggles <NEW_LINE> self.padding = padding <NEW_LINE> self.vlength = vlength <NEW_LINE> self.total_length = total_length <NEW_LINE> self.properties = {'num_wiggles': num_wiggles, 'padding': padding, 'vlength': vlength, 'total_length': total_length} <NEW_LINE> CPWStraight(s, padding / 2., pinw, gapw) <NEW_LINE> CPWWiggles(s, num_wiggles, total_length, start_up, radius, pinw, gapw) <NEW_LINE> CPWStraight(s, padding / 2., pinw, gapw) | CPW Wiggles which fill an area specified by (length,width) | 6259904791af0d3eaad3b197 |
class DistanceMap: <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self._map = data <NEW_LINE> <DEDENT> def get_distance(self, start_city, end_city): <NEW_LINE> <INDENT> return self._map.get((start_city, end_city)) | store the distances between cities present in the map data file
=== private attribues ===
@type _map: {(str,str),int}
Map the start city and end city to the distance from start city to end city
=== repersation invariants ===
the data must contain atleast two cities | 6259904745492302aabfd844 |
class RequestTypeViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = RequestType.objects.all().order_by('id') <NEW_LINE> serializer_class = RequestTypeSerializer | API для типов заявки | 6259904730c21e258be99b79 |
class Solution: <NEW_LINE> <INDENT> def isInterleave(self, s1, s2, s3): <NEW_LINE> <INDENT> if len(s1) + len(s2) != len(s3): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> i1 = 0 <NEW_LINE> i2 = 0 <NEW_LINE> i = 0 <NEW_LINE> while i < len(s3): <NEW_LINE> <INDENT> ch = s3[i] <NEW_LINE> if i1 < len(s1) and i2 < len(s2) and s1[i1] == ch and s2[i2] == ch: <NEW_LINE> <INDENT> t1 = i1 + 1 <NEW_LINE> t2 = i2 + 1 <NEW_LINE> ti = i + 1 <NEW_LINE> while ti < len(s3): <NEW_LINE> <INDENT> tch = s3[ti] <NEW_LINE> if t1 < len(s1) and t2 < len(s2) and s1[t1] == tch and s2[t2] == tch: <NEW_LINE> <INDENT> t1 += 1 <NEW_LINE> t2 += 1 <NEW_LINE> <DEDENT> elif t1 < len(s1) and s1[t1] == tch: <NEW_LINE> <INDENT> i1 += 1 <NEW_LINE> break <NEW_LINE> <DEDENT> elif t2 < len(s2) and s2[t2] == tch: <NEW_LINE> <INDENT> i2 += 1 <NEW_LINE> break <NEW_LINE> <DEDENT> ti += 1 <NEW_LINE> <DEDENT> if ti == len(s3): <NEW_LINE> <INDENT> i1 += 1 <NEW_LINE> <DEDENT> <DEDENT> elif i1 < len(s1) and s1[i1] == ch: <NEW_LINE> <INDENT> i1 += 1 <NEW_LINE> <DEDENT> elif i2 < len(s2) and s2[i2] == ch: <NEW_LINE> <INDENT> i2 += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> return True | @params s1, s2, s3: Three strings as description.
@return: return True if s3 is formed by the interleaving of
s1 and s2 or False if not.
@hint: you can use [[True] * m for i in range (n)] to allocate a n*m matrix. | 62599047e76e3b2f99fd9d7e |
class LluviaField(ConPerfilMixin, serializers.Field): <NEW_LINE> <INDENT> def to_representation(self, value): <NEW_LINE> <INDENT> return lluvia_para_api(self.perfil, value) <NEW_LINE> <DEDENT> def to_internal_value(self, data): <NEW_LINE> <INDENT> return lluvia_desde_api(self.perfil, data) | Campo para el manejo de los datos de lluvia | 6259904745492302aabfd845 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.