code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class CliPrinter(object): <NEW_LINE> <INDENT> _prntr = None <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> if not CliPrinter._prntr: <NEW_LINE> <INDENT> CliPrinter.init() <NEW_LINE> <DEDENT> <DEDENT> def __getattribute__(self, name): <NEW_LINE> <INDENT> return getattr(CliPrinter._prntr, name) <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> return setattr(CliPrinter._prntr, name, value) <NEW_LINE> <DEDENT> def __dir__(self): <NEW_LINE> <INDENT> return dir(self._prntr) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_printer(cls): <NEW_LINE> <INDENT> return CliPrinter() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def init(cls, *args, **kwargs): <NEW_LINE> <INDENT> if kwargs.get('quiet'): <NEW_LINE> <INDENT> cls._prntr = DummyPrinter() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if 'quiet' in kwargs: <NEW_LINE> <INDENT> del(kwargs['quiet']) <NEW_LINE> <DEDENT> cls._prntr = CliPrinterImpl(*args, **kwargs)
Singleton-style factory class The python magic methods below forward dir/get/set calls onto the underlying _prntr object (as Python's Logger class).
62598faae5267d203ee6b887
class DomesticMelonOrder(AbstractMelonOrder): <NEW_LINE> <INDENT> def __init__(self, species, qty, tax=0.08): <NEW_LINE> <INDENT> self.tax = tax <NEW_LINE> return super(DomesticMelonOrder, self).__init__(species, qty, 'domestic')
A melon order within the USA.
62598faae5267d203ee6b888
class IncidentReportJSONType(Enum): <NEW_LINE> <INDENT> event = Event <NEW_LINE> number = int <NEW_LINE> created = DateTime <NEW_LINE> summary = Optional[str] <NEW_LINE> incidentNumber = Optional[int] <NEW_LINE> reportEntries = list[ReportEntry]
Incident report attribute types
62598faa435de62698e9bd74
class FreeSpiritPresentation(WithSpecialProps): <NEW_LINE> <INDENT> presenter = StrProp('Name of presenter') <NEW_LINE> favorite_color = ColorProp('Favorite color of presenter') <NEW_LINE> def summarize(self): <NEW_LINE> <INDENT> print('{name} loves {topic}.'.format( name=self.presenter, topic=self.favorite_color ))
class FreeSpiritPresentation This class contains info about basic free-spirit presentations
62598faa796e427e5384e711
class NoProjectConfigurationError(FailFastError, ExpectedError): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__("No project configuration file found. " "Please create a ddb.yml file in your project directory. " "It can be empty.") <NEW_LINE> <DEDENT> def log_error(self): <NEW_LINE> <INDENT> context.log.error(str(self))
Error that should be raised when a project configuration file is required for the command.
62598faa656771135c4895ff
class MaterialNode(ArmLogicVariableNodeMixin, ArmLogicTreeNode): <NEW_LINE> <INDENT> bl_idname = 'LNMaterialNode' <NEW_LINE> bl_label = 'Material' <NEW_LINE> arm_version = 1 <NEW_LINE> @property <NEW_LINE> def property0_get(self): <NEW_LINE> <INDENT> if self.property0 == None: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> if self.property0.name not in bpy.data.materials: <NEW_LINE> <INDENT> return self.property0.name <NEW_LINE> <DEDENT> return arm.utils.asset_name(bpy.data.materials[self.property0.name]) <NEW_LINE> <DEDENT> property0: HaxePointerProperty('property0', name='', type=bpy.types.Material) <NEW_LINE> def arm_init(self, context): <NEW_LINE> <INDENT> self.add_output('ArmDynamicSocket', 'Material', is_var=True) <NEW_LINE> <DEDENT> def draw_content(self, context, layout): <NEW_LINE> <INDENT> layout.prop_search(self, 'property0', bpy.data, 'materials', icon='NONE', text='') <NEW_LINE> <DEDENT> def synchronize_from_master(self, master_node: ArmLogicVariableNodeMixin): <NEW_LINE> <INDENT> self.property0 = master_node.property0
Stores the given material as a variable.
62598faa851cf427c66b823b
class HarmonicRestraintBondForce(HarmonicRestraintForceMixIn, RadiallySymmetricBondRestraintForce): <NEW_LINE> <INDENT> pass
Impose a single harmonic restraint between two atoms. This is a version of ``HarmonicRestraintForce`` that can be used with OpenCL 32-bit platforms. It supports atom groups with only a single atom. Parameters ---------- spring_constant : openmm.unit.Quantity The spring constant K (see energy expression above) in units compatible with joule/nanometer**2/mole. restrained_atom_index1 : int The index of the first atom to restrain. restrained_atom_index2 : int The index of the second atom to restrain. controlling_parameter_name : str, optional The name of the global parameter controlling the energy function. The default value is 'lambda_restraints'. Attributes ---------- spring_constant restrained_atom_indices1 restrained_atom_indices2 restraint_parameters controlling_parameter_name
62598faa5fdd1c0f98e5df14
class User(): <NEW_LINE> <INDENT> def __init__(self, first, last, dob, address): <NEW_LINE> <INDENT> self.first = first <NEW_LINE> self.last = last <NEW_LINE> self.dob = dob <NEW_LINE> self.address = address <NEW_LINE> self.uid = uid_gen() <NEW_LINE> self.fpass = passwordgen() <NEW_LINE> self.password = '' <NEW_LINE> if en: <NEW_LINE> <INDENT> print('\nWelcome, {firstname}! Your USER ID is {uid}.'.format( firstname=self.first, uid=colored(self.uid, 'red', 'on_white', attrs=['blink', 'bold'])), '\nYour one-time password is {passw}.'.format(passw=colored( self.fpass, 'green', 'on_white', attrs=['blink', 'bold']) ), "\nDon't forget to change it.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('\nWillkommen, {firstname}! Deine USER ID ist {uid}.'.format( firstname=self.first, uid=colored(self.uid, 'red', 'on_white', attrs=['blink', 'bold'])), '\nDein Startpasswort lautet {passw}.'.format(passw=colored( self.fpass, 'green', 'on_white', attrs=['blink', 'bold']) ), '\nVergiss nicht es zu ändern.')
The User Class instantiates an object for each user that is created.
62598faa1f037a2d8b9e406b
class CodeRedirectsTest(APITestCase): <NEW_LINE> <INDENT> def testBouwblokCode(self): <NEW_LINE> <INDENT> bbk = factories.BouwblokFactory.create(code='AN34') <NEW_LINE> res = self.client.get('/gebieden/bouwblok/AN34/') <NEW_LINE> bb_id = res.data['bouwblokidentificatie'] <NEW_LINE> self.assertEqual(bb_id, bbk.id) <NEW_LINE> <DEDENT> def testBouwblokCodeFilter(self): <NEW_LINE> <INDENT> bbk = factories.BouwblokFactory.create(code='AN34') <NEW_LINE> res = self.client.get('/gebieden/bouwblok/?code=AN34') <NEW_LINE> bb_id = res.data['results'][0]['id'] <NEW_LINE> self.assertEqual(bb_id, bbk.id) <NEW_LINE> <DEDENT> def testStadsdeelCode(self): <NEW_LINE> <INDENT> sdl = factories.StadsdeelFactory.create(code='X') <NEW_LINE> res = self.client.get('/gebieden/stadsdeel/X/') <NEW_LINE> sd_id = res.data['stadsdeelidentificatie'] <NEW_LINE> self.assertEqual(sd_id, sdl.id) <NEW_LINE> <DEDENT> def testStadsdeelCodeFilter(self): <NEW_LINE> <INDENT> sdl = factories.StadsdeelFactory.create(code='X') <NEW_LINE> res = self.client.get('/gebieden/stadsdeel/?code=X') <NEW_LINE> sd = res.data['results'][0] <NEW_LINE> self.assertEqual(sd['code'], sdl.code)
Use code to find object
62598faad7e4931a7ef3c013
class SimpleRenderer: <NEW_LINE> <INDENT> def __init__(self, composer, show_bounds: bool = False): <NEW_LINE> <INDENT> self.dataset = QuickDrawDataset.words() <NEW_LINE> self.composer = composer <NEW_LINE> self.show_bounds = show_bounds <NEW_LINE> <DEDENT> def render(self, scene: 'drawtomat.model.scenegraph.Scene', show: bool = False, output: str = "drawing.png") -> None: <NEW_LINE> <INDENT> composition = self.composer.compose(scene) <NEW_LINE> im_w, im_h = 600, 600 <NEW_LINE> im = Image.new("RGB", (im_w, im_h), "white") <NEW_LINE> draw = ImageDraw.Draw(im) <NEW_LINE> min_x = None <NEW_LINE> max_x = None <NEW_LINE> min_y = None <NEW_LINE> max_y = None <NEW_LINE> for obj in composition: <NEW_LINE> <INDENT> for stroke in obj.strokes: <NEW_LINE> <INDENT> mx = min(stroke[0]) + obj.x <NEW_LINE> my = min(stroke[1]) + obj.y <NEW_LINE> if min_x is None or min_x > mx: <NEW_LINE> <INDENT> min_x = mx <NEW_LINE> <DEDENT> if min_y is None or min_y > my: <NEW_LINE> <INDENT> min_y = my <NEW_LINE> <DEDENT> mx = max(stroke[0]) + obj.x <NEW_LINE> my = max(stroke[1]) + obj.y <NEW_LINE> if max_x is None or max_x < mx: <NEW_LINE> <INDENT> max_x = mx <NEW_LINE> <DEDENT> if max_y is None or min_y < my: <NEW_LINE> <INDENT> max_y = my <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if composition: <NEW_LINE> <INDENT> width = max_x - min_x + 50 <NEW_LINE> height = max_y - min_y + 50 <NEW_LINE> q = min(im_w / width / 2, im_h / height / 2) <NEW_LINE> <DEDENT> for obj in composition: <NEW_LINE> <INDENT> px, py = (obj.x - min_x + width / 2) * q, (obj.y - min_y + height / 2) * q <NEW_LINE> for stroke in obj.strokes: <NEW_LINE> <INDENT> if len(stroke[2]) < 2: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> points = [(px + x * q, py + y * q) for (x, y) in zip(stroke[0], stroke[1])] <NEW_LINE> draw.line(points, fill="black") <NEW_LINE> <DEDENT> if self.show_bounds: <NEW_LINE> <INDENT> draw.rectangle([px, py, px + obj.get_width() * q, py + obj.get_height() * q], outline="#ff00ff") <NEW_LINE> draw.text([px + 4, py + 4], text=obj.entity.word, anchor="nw", fill="#ff00ff", font=("Courier", 10)) <NEW_LINE> draw.line([px - 4, py, px + 4, py], fill="#ff00ff") <NEW_LINE> draw.line([px, py - 4, px, py + 4], fill="#ff00ff") <NEW_LINE> <DEDENT> <DEDENT> im.save(output) <NEW_LINE> if show: <NEW_LINE> <INDENT> im.show()
A simple image renderer. Renders the scene using Pillow. Attributes ---------- composer composer which will be used during the rendering. show_bounds : bool if true, a bounding box will be rendered around each object.
62598faa4428ac0f6e6584a2
class Operation(object): <NEW_LINE> <INDENT> def __init__(self, uri, operation, http_client, models): <NEW_LINE> <INDENT> self._uri = uri <NEW_LINE> self._json = operation <NEW_LINE> self._http_client = http_client <NEW_LINE> self._models = models <NEW_LINE> self.__doc__ = create_operation_docstring(operation) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return u"%s(%s)" % (self.__class__.__name__, self._json[u'nickname']) <NEW_LINE> <DEDENT> def _construct_request(self, **kwargs): <NEW_LINE> <INDENT> _request_options = kwargs.pop('_request_options', {}) or {} <NEW_LINE> request = {} <NEW_LINE> request['method'] = self._json[u'method'].encode('utf8') <NEW_LINE> request['url'] = self._uri <NEW_LINE> request['params'] = {} <NEW_LINE> request['headers'] = _request_options.get('headers', {}) or {} <NEW_LINE> for param in self._json.get(u'parameters', []): <NEW_LINE> <INDENT> value = kwargs.pop(param[u'name'], param.get('defaultValue')) <NEW_LINE> validate_and_add_params_to_request(param, value, request, self._models) <NEW_LINE> <DEDENT> if kwargs: <NEW_LINE> <INDENT> raise TypeError(u"'%s' does not have parameters %r" % ( self._json[u'nickname'], kwargs.keys())) <NEW_LINE> <DEDENT> return request <NEW_LINE> <DEDENT> def __call__(self, **kwargs): <NEW_LINE> <INDENT> log.debug(u"%s?%r" % ( self._json[u'nickname'], urllib_utf8.urlencode(kwargs))) <NEW_LINE> request = self._construct_request(**kwargs) <NEW_LINE> def response_future(response, **kwargs): <NEW_LINE> <INDENT> if not response.text: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return post_receive( response.json(), swagger_type.get_swagger_type(self._json), self._models, **kwargs) <NEW_LINE> <DEDENT> return HTTPFuture(self._http_client, request, response_future)
Perform a request by taking the kwargs passed to the call and constructing an HTTP request.
62598faabaa26c4b54d4f230
class CustomThumbnailNode(ThumbnailNode): <NEW_LINE> <INDENT> error_message = ('Please enter sizes defined in settings') <NEW_LINE> def __init__(self, parser, token): <NEW_LINE> <INDENT> ThumbnailNode.__init__(self, parser, token) <NEW_LINE> bits = token.split_contents() <NEW_LINE> if len(bits) < 5 or bits[-2] != 'as': <NEW_LINE> <INDENT> raise TemplateSyntaxError(self.error_msg) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> thumbnail_settings = get_thumbnail_options_from_dict(settings.OPTIONS_DICT) <NEW_LINE> thumbnail_options = thumbnail_settings[bits[2]] <NEW_LINE> thumbnail_options = thumbnail_options.split() <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise TemplateSyntaxError(self.error_message) <NEW_LINE> <DEDENT> self.geometry = parser.compile_filter("'%s'" % thumbnail_options[0]) <NEW_LINE> self.options = [] <NEW_LINE> try: <NEW_LINE> <INDENT> m = kw_pat.match(thumbnail_options[1]) <NEW_LINE> key = smart_str(m.group('key')) <NEW_LINE> expr = parser.compile_filter('"%s"' % m.group('value')) <NEW_LINE> self.options.append((key, expr)) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.as_var = bits[-1]
Extends ThumbnailNode to use thumbnail sizes from settings
62598faa2c8b7c6e89bd3744
class BaseDummyConverter(Converter): <NEW_LINE> <INDENT> TABLE = {} <NEW_LINE> def inner_convert_string(self, string): <NEW_LINE> <INDENT> for old, new in self.TABLE.items(): <NEW_LINE> <INDENT> string = string.replace(old, new) <NEW_LINE> <DEDENT> return self.pad(string) <NEW_LINE> <DEDENT> def pad(self, string): <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> def convert_msg(self, msg): <NEW_LINE> <INDENT> source = msg.msgid <NEW_LINE> if not source: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> plural = msg.msgid_plural <NEW_LINE> if plural: <NEW_LINE> <INDENT> foreign_single = self.convert(source) <NEW_LINE> foreign_plural = self.convert(plural) <NEW_LINE> plural = { '0': self.final_newline(source, foreign_single), '1': self.final_newline(plural, foreign_plural), } <NEW_LINE> msg.msgstr_plural = plural <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> foreign = self.convert(source) <NEW_LINE> msg.msgstr = self.final_newline(source, foreign) <NEW_LINE> <DEDENT> <DEDENT> def final_newline(self, original, translated): <NEW_LINE> <INDENT> if original: <NEW_LINE> <INDENT> if original[-1] == '\n' and translated[-1] != '\n': <NEW_LINE> <INDENT> translated += '\n' <NEW_LINE> <DEDENT> <DEDENT> return translated
Base class for dummy converters. String conversion goes through a character map, then gets padded.
62598faa1b99ca400228f4ef
class Processor: <NEW_LINE> <INDENT> def __init__(self, text): <NEW_LINE> <INDENT> if type(text) is not str: <NEW_LINE> <INDENT> raise TextProcError("Processors require strings") <NEW_LINE> <DEDENT> self.text = text <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.text) <NEW_LINE> <DEDENT> def count(self): <NEW_LINE> <INDENT> return len(self) <NEW_LINE> <DEDENT> def count_alpha(self): <NEW_LINE> <INDENT> alpha = re.compile(r'[a-z]') <NEW_LINE> return len(alpha.findall(self.text)) <NEW_LINE> <DEDENT> def count_numeric(self): <NEW_LINE> <INDENT> alpha = re.compile(r'[1-9]') <NEW_LINE> return len(alpha.findall(self.text)) <NEW_LINE> <DEDENT> def count_vowels(self): <NEW_LINE> <INDENT> vowels = re.compile(r'[aeou]', re.IGNORECASE) <NEW_LINE> return len(vowels.findall(self.text)) <NEW_LINE> <DEDENT> def is_phonenumber(self): <NEW_LINE> <INDENT> phonenum = re.compile(r'^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$') <NEW_LINE> if phonenum.match(self.text) is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
Class for Processing Strings
62598faad6c5a102081e20c6
class GoodsImage(BaseModel): <NEW_LINE> <INDENT> sku = models.ForeignKey('GoodsSKU', on_delete=models.CASCADE, verbose_name='商品') <NEW_LINE> image = models.ImageField(upload_to='goods', verbose_name='图片路径') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'df_goods_image' <NEW_LINE> verbose_name = '商品图片' <NEW_LINE> verbose_name_plural = verbose_name
商品图片模型
62598faa01c39578d7f12cfe
class EditSubForm(FlaskForm): <NEW_LINE> <INDENT> title = StringField(_l('Title'), validators=[DataRequired(), Length(min=2, max=128)]) <NEW_LINE> nsfw = BooleanField(_l('Sub is NSFW')) <NEW_LINE> restricted = BooleanField(_l('Only mods can post')) <NEW_LINE> usercanflair = BooleanField(_l('Allow users to flair their own posts')) <NEW_LINE> user_can_flair_self = BooleanField(_l('Allow users to set their own user flairs')) <NEW_LINE> freeform_user_flairs = BooleanField(_l('Allow free-form user flairs (disables pre-defined flairs)')) <NEW_LINE> allow_text_posts = BooleanField(_l('Enable text posts')) <NEW_LINE> allow_link_posts = BooleanField(_l('Enable link posts')) <NEW_LINE> allow_upload_posts = BooleanField(_l('Enable upload posts')) <NEW_LINE> allow_polls = BooleanField(_l('Enable polls')) <NEW_LINE> subsort = RadioField(_l('Default sub page post sorting'), choices=[('v', _l('Hot')), ('v_two', _l('New')), ('v_three', _l('Top'))], validators=[Optional()]) <NEW_LINE> sidebar = TextAreaField(_l('Sidebar text'), validators=[Length(max=8000)]) <NEW_LINE> sublogprivate = BooleanField(_l('Make the sub log private')) <NEW_LINE> subbannedusersprivate = BooleanField(_l('Make the list of banned users on this sub private'))
Edit sub form.
62598faa0a50d4780f70535c
class AppEngineInstance(resource_class_factory('appengine_instance', 'name', hash_key=True)): <NEW_LINE> <INDENT> pass
The Resource implementation for AppEngine Instance.
62598faa44b2445a339b692f
class GetSampleInfo(object): <NEW_LINE> <INDENT> def on_post(self, req, resp): <NEW_LINE> <INDENT> data = req.params <NEW_LINE> samplename = data["sampleName"] <NEW_LINE> db = Mysql(table_name="GLORIA_MYSQL") <NEW_LINE> sql = """select * from sample_mx where S_MCODE = \"%s\";""" % samplename <NEW_LINE> data = db.fetch_all(sql) <NEW_LINE> resp.status = falcon.HTTP_200 <NEW_LINE> resp._headers["Access-Control-Allow-Origin"] = "*" <NEW_LINE> if data: <NEW_LINE> <INDENT> result = '{"success":true, "info": "样本存在!" }' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = '{"success":false, "info": "样本不存在!" }' <NEW_LINE> <DEDENT> resp.body = result
根据样本的编写获得样本的其他信息
62598faa7d847024c075c342
class TaskOrderError(DependencyError): <NEW_LINE> <INDENT> pass
Indicates a task depends on data produced by another task in the same phase that is scheduled to runs after it.
62598faa97e22403b383ae8b
class Boolean(SchemaType): <NEW_LINE> <INDENT> def serialize(self, node, appstruct): <NEW_LINE> <INDENT> if appstruct is null: <NEW_LINE> <INDENT> return null <NEW_LINE> <DEDENT> return appstruct and 'true' or 'false' <NEW_LINE> <DEDENT> def deserialize(self, node, cstruct): <NEW_LINE> <INDENT> if cstruct is null: <NEW_LINE> <INDENT> return null <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result = str(cstruct) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise Invalid(node, _('${val} is not a string', mapping={'val':cstruct}) ) <NEW_LINE> <DEDENT> result = result.lower() <NEW_LINE> if result in ('false', '0'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
A type representing a boolean object. During deserialization, a value in the set (``false``, ``0``) will be considered ``False``. Anything else is considered ``True``. Case is ignored. Serialization will produce ``true`` or ``false`` based on the value. If the :attr:`colander.null` value is passed to the serialize method of this class, the :attr:`colander.null` value will be returned. The subnodes of the :class:`colander.SchemaNode` that wraps this type are ignored.
62598faaaad79263cf42e752
class CpwvcmplsexpbitsmodeEnum(Enum): <NEW_LINE> <INDENT> outerTunnel = 1 <NEW_LINE> specifiedValue = 2 <NEW_LINE> serviceDependant = 3 <NEW_LINE> @staticmethod <NEW_LINE> def _meta_info(): <NEW_LINE> <INDENT> from ydk.models.cisco_ios_xe._meta import _CISCO_IETF_PW_MPLS_MIB as meta <NEW_LINE> return meta._meta_table['CiscoIetfPwMplsMib.Cpwvcmplstable.Cpwvcmplsentry.CpwvcmplsexpbitsmodeEnum']
CpwvcmplsexpbitsmodeEnum Set by the operator to indicate the way the VC shim label EXP bits are to be determined. The value of outerTunnel(1) is used where there is an outer tunnel \- cpwVcMplsMplsType is mplsTe or mplsNonTe. Note that in this case there is no need to mark the VC label with the EXP bits since the VC label is not visible to the intermediate nodes. If there is no outer tunnel, specifiedValue(2) indicate that the value is specified by cpwVcMplsExpBits, and serviceDependant(3) indicate that the EXP bits are setup based on a rule specified in the emulated service specific tables, for example when the EXP bits are a function of 802.1p marking for Ethernet emulated service. .. data:: outerTunnel = 1 .. data:: specifiedValue = 2 .. data:: serviceDependant = 3
62598faa38b623060ffa9017
@add_slots <NEW_LINE> @dataclass(frozen=True) <NEW_LINE> class Divide(BaseBinaryOp, _BaseOneTokenOp): <NEW_LINE> <INDENT> whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") <NEW_LINE> whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") <NEW_LINE> def _get_token(self) -> str: <NEW_LINE> <INDENT> return "/"
A binary operator that can be used in a :class:`BinaryOperation` expression.
62598faa236d856c2adc93fc
class Rotation(models.Model): <NEW_LINE> <INDENT> name = models.CharField( unique=True, max_length=255, help_text='The rotation\'s name.' ) <NEW_LINE> description = models.TextField( help_text='A description of the rotation\'s purpose.' ) <NEW_LINE> message = models.TextField( help_text='A reminder message sent to members of the rotation.' ) <NEW_LINE> members = SortedManyToManyField(Member, related_name='rotations') <NEW_LINE> watchers = SortedManyToManyField(Member, related_name='watching') <NEW_LINE> on_call = models.ForeignKey( Member, on_delete=models.CASCADE, help_text='Member currently on call.' ) <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> modified = models.DateTimeField(auto_now=True) <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> ordering = ['-modified'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def advance(self): <NEW_LINE> <INDENT> members = list(self.members.all()) <NEW_LINE> member_count = len(members) <NEW_LINE> try: <NEW_LINE> <INDENT> current_index = members.index(self.on_call) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> logger.warning( 'Failed to find %s in the %s rotation\'s members list.', self.on_call.name, self.name, ) <NEW_LINE> current_index = 0 <NEW_LINE> <DEDENT> on_call_index = (current_index + 1) % member_count <NEW_LINE> on_call_member = members[on_call_index] <NEW_LINE> next_index = (current_index + 2) % member_count <NEW_LINE> next_member = members[next_index] <NEW_LINE> logger.info( 'Advancing the %s rotation. %s was on call. %s is now on call. %s is up next.', self.name, self.on_call.name, on_call_member.name, next_member.name, ) <NEW_LINE> self.on_call = on_call_member <NEW_LINE> self.save() <NEW_LINE> return next_member
Representation of a rotation.
62598faaeab8aa0e5d30bd0a
class Meta: <NEW_LINE> <INDENT> model = Subject <NEW_LINE> fields = ('id', 'title', 'slug')
Klasa Meta pozwala na wskazanie modelu przeznaczonego do serializacji, a także kolumn, które mają być uwzględnione w trakcie tego procesu.
62598faa5fc7496912d48242
class Schedule(models.Model): <NEW_LINE> <INDENT> summary = models.CharField('練習', max_length=1, default= '入力してください' ) <NEW_LINE> description = models.TextField('詳細な説明', blank=True) <NEW_LINE> start_time = models.TimeField('開始時間', default=datetime.time(7, 0, 0)) <NEW_LINE> end_time = models.TimeField('終了時間', default=datetime.time(7, 0, 0)) <NEW_LINE> date = models.DateField('日付') <NEW_LINE> created_at = models.DateTimeField('作成日', default=timezone.now) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.summary
スケジュール
62598faa7047854f4633f358
class Vocabulary(object): <NEW_LINE> <INDENT> def __init__(self, fname): <NEW_LINE> <INDENT> with open(fname) as f: <NEW_LINE> <INDENT> lines = f.readlines() <NEW_LINE> <DEDENT> self._set = set() <NEW_LINE> self._list = ['' for i in range(len(lines))] <NEW_LINE> for l in lines: <NEW_LINE> <INDENT> if l: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> index, word = l.split(' ') <NEW_LINE> index = int(index) <NEW_LINE> word = word.strip() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self._list[index - 1] = word <NEW_LINE> self._set.add(word) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._list) <NEW_LINE> <DEDENT> def __contains__(self, word): <NEW_LINE> <INDENT> return word in self._set <NEW_LINE> <DEDENT> def get(self, i): <NEW_LINE> <INDENT> return self._list[i - 1]
Vocabulary.
62598faa32920d7e50bc5fd4
class TicketServicePayload(object): <NEW_LINE> <INDENT> def update_ticket_payload(self, ticket_status="Accepted", update_description="Required one"): <NEW_LINE> <INDENT> payload = { "ticket_status": ticket_status, "update_description": update_description } <NEW_LINE> return payload
Class for Ticket Service Payloads
62598faae5267d203ee6b889
class CcDateDelegate(QStyledItemDelegate, UpdateEditorGeometry): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> QStyledItemDelegate.__init__(self, parent) <NEW_LINE> self.table_widget = parent <NEW_LINE> <DEDENT> def set_format(self, format): <NEW_LINE> <INDENT> if not format: <NEW_LINE> <INDENT> self.format = 'dd MMM yyyy' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.format = format <NEW_LINE> <DEDENT> <DEDENT> def displayText(self, val, locale): <NEW_LINE> <INDENT> d = qt_to_dt(val) <NEW_LINE> if is_date_undefined(d): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> return format_date(d, self.format) <NEW_LINE> <DEDENT> def createEditor(self, parent, option, index): <NEW_LINE> <INDENT> return DateTimeEdit(parent, self.format) <NEW_LINE> <DEDENT> def setEditorData(self, editor, index): <NEW_LINE> <INDENT> if check_key_modifier(Qt.ControlModifier): <NEW_LINE> <INDENT> val = UNDEFINED_QDATETIME <NEW_LINE> <DEDENT> elif check_key_modifier(Qt.ShiftModifier + Qt.ControlModifier): <NEW_LINE> <INDENT> val = now() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = index.data(Qt.EditRole) <NEW_LINE> if is_date_undefined(val): <NEW_LINE> <INDENT> val = now() <NEW_LINE> <DEDENT> <DEDENT> editor.setDateTime(val) <NEW_LINE> <DEDENT> def setModelData(self, editor, model, index): <NEW_LINE> <INDENT> val = editor.dateTime() <NEW_LINE> if is_date_undefined(val): <NEW_LINE> <INDENT> val = None <NEW_LINE> <DEDENT> model.setData(index, (val), Qt.EditRole)
Delegate for custom columns dates. Because this delegate stores the format as an instance variable, a new instance must be created for each column. This differs from all the other delegates.
62598faa7d847024c075c343
class JoinStrands_GraphicsMode( BreakOrJoinstrands_GraphicsMode ): <NEW_LINE> <INDENT> exit_command_on_leftUp = False <NEW_LINE> def leftDouble(self, event): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def leftUp(self, event): <NEW_LINE> <INDENT> _superclass_for_GM.leftUp(self, event) <NEW_LINE> if self.exit_command_on_leftUp: <NEW_LINE> <INDENT> self.exit_command_on_leftUp = False <NEW_LINE> self.command.command_Done() <NEW_LINE> <DEDENT> <DEDENT> def deposit_from_MMKit(self, atom_or_pos): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> _GLOBAL_TO_LOCAL_PREFS_KEYS = { arrowsOnThreePrimeEnds_prefs_key: joinStrandsCommand_arrowsOnThreePrimeEnds_prefs_key, arrowsOnFivePrimeEnds_prefs_key: joinStrandsCommand_arrowsOnFivePrimeEnds_prefs_key, useCustomColorForThreePrimeArrowheads_prefs_key: joinStrandsCommand_useCustomColorForThreePrimeArrowheads_prefs_key, useCustomColorForFivePrimeArrowheads_prefs_key: joinStrandsCommand_useCustomColorForFivePrimeArrowheads_prefs_key, dnaStrandThreePrimeArrowheadsCustomColor_prefs_key: joinStrandsCommand_dnaStrandThreePrimeArrowheadsCustomColor_prefs_key, dnaStrandFivePrimeArrowheadsCustomColor_prefs_key: joinStrandsCommand_dnaStrandFivePrimeArrowheadsCustomColor_prefs_key, } <NEW_LINE> def get_prefs_value(self, prefs_key): <NEW_LINE> <INDENT> prefs_key = self._GLOBAL_TO_LOCAL_PREFS_KEYS.get( prefs_key, prefs_key) <NEW_LINE> return _superclass_for_GM.get_prefs_value( self, prefs_key)
Graphics mode for Join strands command
62598faa435de62698e9bd75
class cancelActivityApply_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.I32, 'postId', None, None, ), ) <NEW_LINE> def __init__(self, postId=None,): <NEW_LINE> <INDENT> self.postId = postId <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.I32: <NEW_LINE> <INDENT> self.postId = iprot.readI32(); <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('cancelActivityApply_args') <NEW_LINE> if self.postId is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('postId', TType.I32, 1) <NEW_LINE> oprot.writeI32(self.postId) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.postId) <NEW_LINE> return value <NEW_LINE> <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: - postId
62598faaadb09d7d5dc0a50a
class TwiMasterSend(Request): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def compile(cls, addr, data, stop): <NEW_LINE> <INDENT> cls.assert_true(addr >= 0 and addr < 128, "slave address value must be in range [0..127]") <NEW_LINE> cls.assert_true(len(data) < 250, "data length can't be greater than 250 bytes") <NEW_LINE> return super(TwiMasterSend, cls).compile( [stop & 0xff, addr & 0xff] + data )
@brief TWI Master Send request packet compiler @see PATO_BRIDGE_CMD_TWI_MASTER_SEND
62598faa56b00c62f0fb2834
class MultiSchemaStorageManagerPg(multischema.MultiSchemaStorageManagerDB): <NEW_LINE> <INDENT> databaseclass = pypgsql.PyPgDatabase <NEW_LINE> def __init__(self, allOptions={}): <NEW_LINE> <INDENT> for atom in allOptions['connections.Connect'].split(" "): <NEW_LINE> <INDENT> k, v = atom.split("=", 1) <NEW_LINE> if k == "dbname": <NEW_LINE> <INDENT> allOptions['name'] = v <NEW_LINE> <DEDENT> <DEDENT> multischema.MultiSchemaStorageManagerDB.__init__(self, allOptions)
StoreManager to save and retrieve multiple schemas via pyPgSQL.
62598faaa79ad16197769fe5
class Grid(object): <NEW_LINE> <INDENT> def __str__(self, *args, **kwargs): <NEW_LINE> <INDENT> retVal = "" <NEW_LINE> for row in range(1,10): <NEW_LINE> <INDENT> for column in range(1,10): <NEW_LINE> <INDENT> cell = self.getCell(row, column) <NEW_LINE> retVal = retVal + str(cell) + " : " <NEW_LINE> <DEDENT> retVal = retVal + "\n" <NEW_LINE> <DEDENT> return retVal <NEW_LINE> <DEDENT> def __eq__(self, grid): <NEW_LINE> <INDENT> if isinstance(grid, Grid): <NEW_LINE> <INDENT> for row in range(1,10): <NEW_LINE> <INDENT> for column in range(1,10): <NEW_LINE> <INDENT> if not self.getCell(row, column) == grid.getCell(row,column): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def CopyGrid(self): <NEW_LINE> <INDENT> dst = Grid() <NEW_LINE> for row in range(1,10): <NEW_LINE> <INDENT> for column in range(1,10): <NEW_LINE> <INDENT> thisCell = self.getCell(row,column) <NEW_LINE> if thisCell is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> dst.setCell(row,column,thisCell.CopyCell()) <NEW_LINE> <DEDENT> <DEDENT> return dst <NEW_LINE> <DEDENT> def isSolved(self): <NEW_LINE> <INDENT> for column in range(0,9): <NEW_LINE> <INDENT> for row in range(0,9): <NEW_LINE> <INDENT> if len(self.gridList[column][row].values) != 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def getCell(self,row,column): <NEW_LINE> <INDENT> if row < 10 and column < 10: <NEW_LINE> <INDENT> return self.gridList[row-1][column-1] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def setCell(self,row, column, cell): <NEW_LINE> <INDENT> if row > 10 and column > 10: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.gridList[row-1][column-1] = cell <NEW_LINE> <DEDENT> def getColumn(self, column): <NEW_LINE> <INDENT> newList= list() <NEW_LINE> if column > 10: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for i in range(0,9): <NEW_LINE> <INDENT> newList.append(self.gridList[i][column-1]) <NEW_LINE> <DEDENT> return newList <NEW_LINE> <DEDENT> def getRow(self,row): <NEW_LINE> <INDENT> return self.gridList[row-1] <NEW_LINE> <DEDENT> def setQueue(self,msgQueue): <NEW_LINE> <INDENT> for row in range(1,10): <NEW_LINE> <INDENT> for column in range(1,10): <NEW_LINE> <INDENT> cell = self.getCell(row,column) <NEW_LINE> cell.setQueue(msgQueue) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def getLocalGrid(self,row,column): <NEW_LINE> <INDENT> localGridRow = int((row-1)/3) <NEW_LINE> localGridColumn = int((column-1)/3) <NEW_LINE> newList = list() <NEW_LINE> rowRange = range(localGridRow*3, (localGridRow*3)+3) <NEW_LINE> columnRange = range(localGridColumn*3, (localGridColumn*3)+3) <NEW_LINE> for localRow in rowRange: <NEW_LINE> <INDENT> for localColumn in columnRange: <NEW_LINE> <INDENT> newList.append(self.gridList[localRow][localColumn]) <NEW_LINE> <DEDENT> <DEDENT> return newList <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.gridList = list() <NEW_LINE> for rowIndex in range(1,10): <NEW_LINE> <INDENT> row = list() <NEW_LINE> for column in range(1,10): <NEW_LINE> <INDENT> cell = Cell(rowIndex,column) <NEW_LINE> row.append(cell) <NEW_LINE> <DEDENT> self.gridList.append(row)
classdocs
62598faa6e29344779b005dc
class FrontToBackPacket( collections.namedtuple( 'FrontToBackPacket', ['operation_id', 'sequence_number', 'kind', 'name', 'subscription', 'trace_id', 'payload', 'timeout'])): <NEW_LINE> <INDENT> @enum.unique <NEW_LINE> class Kind(enum.Enum): <NEW_LINE> <INDENT> COMMENCEMENT = 'commencement' <NEW_LINE> CONTINUATION = 'continuation' <NEW_LINE> COMPLETION = 'completion' <NEW_LINE> ENTIRE = 'entire' <NEW_LINE> CANCELLATION = 'cancellation' <NEW_LINE> EXPIRATION = 'expiration' <NEW_LINE> SERVICER_FAILURE = 'servicer failure' <NEW_LINE> SERVICED_FAILURE = 'serviced failure' <NEW_LINE> RECEPTION_FAILURE = 'reception failure' <NEW_LINE> TRANSMISSION_FAILURE = 'transmission failure'
A sum type for all values sent from a front to a back. Attributes: operation_id: A unique-with-respect-to-equality hashable object identifying a particular operation. sequence_number: A zero-indexed integer sequence number identifying the packet's place among all the packets sent from front to back for this particular operation. Must be zero if kind is Kind.COMMENCEMENT or Kind.ENTIRE. Must be positive for any other kind. kind: A Kind value describing the overall kind of ticket. name: The name of an operation. Must be present if kind is Kind.COMMENCEMENT or Kind.ENTIRE. Must be None for any other kind. subscription: An interfaces.ServicedSubscription.Kind value describing the interest the front has in packets sent from the back. Must be present if kind is Kind.COMMENCEMENT or Kind.ENTIRE. Must be None for any other kind. trace_id: A uuid.UUID identifying a set of related operations to which this operation belongs. May be None. payload: A customer payload object. Must be present if kind is Kind.CONTINUATION. Must be None if kind is Kind.CANCELLATION. May be None for any other kind. timeout: An optional length of time (measured from the beginning of the operation) to allow for the entire operation. If None, a default value on the back will be used. If present and excessively large, the back may limit the operation to a smaller duration of its choice. May be present for any ticket kind; setting a value on a later ticket allows fronts to request time extensions (or even time reductions!) on in-progress operations.
62598faadd821e528d6d8eb5
class Projectile(Arme): <NEW_LINE> <INDENT> nom_type = "projectile" <NEW_LINE> def __init__(self, cle=""): <NEW_LINE> <INDENT> Arme.__init__(self, cle) <NEW_LINE> self.peut_depecer = False <NEW_LINE> self.emplacement = "" <NEW_LINE> self.positions = () <NEW_LINE> <DEDENT> def etendre_script(self): <NEW_LINE> <INDENT> evt_atteint = self.script.creer_evenement("atteint") <NEW_LINE> evt_atteint.aide_courte = "le projectile atteint une cible" <NEW_LINE> evt_atteint.aide_longue = "Cet évènement est appelé quand le projectile vient " "d'atteindre une cible (juste après les messages informant " "des dégâts éventuels). Il peut être utile pour par " "exemple placer une affection sur la cible." <NEW_LINE> var_auteur = evt_atteint.ajouter_variable("auteur", "Personnage") <NEW_LINE> var_auteur.aide = "le personnage à l'auteur du tir" <NEW_LINE> var_cible = evt_atteint.ajouter_variable("cible", "Personnage") <NEW_LINE> var_cible.aide = "la cible atteinte par le projectile" <NEW_LINE> var_arme = evt_atteint.ajouter_variable("arme", "Objet") <NEW_LINE> var_arme.aide = "l'arme de jet à l'origine du tir" <NEW_LINE> var_projectile = evt_atteint.ajouter_variable("projectile", "Objet") <NEW_LINE> var_projectile.aide = "le projectile qui atteint la cible"
Type d'objet: projectile.
62598faa26068e7796d4c8d4
class ExampleSprite(RewardSprite): <NEW_LINE> <INDENT> def __init__(self, corner, position, character, index, n_unique): <NEW_LINE> <INDENT> super(ExampleEnvironment.ExampleSprite, self).__init__(corner, position, character, index, n_unique) <NEW_LINE> <DEDENT> def update(self, actions, board, layers, backdrop, things, the_plot): <NEW_LINE> <INDENT> action = self.my_action(actions) <NEW_LINE> if action == Actions.LEFT: <NEW_LINE> <INDENT> self._west(board, the_plot) <NEW_LINE> <DEDENT> elif action == Actions.RIGHT: <NEW_LINE> <INDENT> self._east(board, the_plot) <NEW_LINE> <DEDENT> if self.index == 1: <NEW_LINE> <INDENT> if self.position[1] == 1: <NEW_LINE> <INDENT> self.reward(the_plot, 1) <NEW_LINE> the_plot.terminate_episode() <NEW_LINE> <DEDENT> elif self.position[1] == (self.corner[1] - 2): <NEW_LINE> <INDENT> self.reward(the_plot, 100) <NEW_LINE> the_plot.terminate_episode()
Sprite representing player for Pycolab
62598faabaa26c4b54d4f232
class Solution: <NEW_LINE> <INDENT> def numDistinct(self, S, T): <NEW_LINE> <INDENT> nums_pre = [1 for x in range(len(S) + 1)] <NEW_LINE> nums = nums_pre.copy() <NEW_LINE> nums[0] = 0 <NEW_LINE> for i in range(len(T)): <NEW_LINE> <INDENT> for j in range(len(S)): <NEW_LINE> <INDENT> if T[i] == S[j]: <NEW_LINE> <INDENT> nums[j + 1] = nums[j] + nums_pre[j] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nums[j + 1] = nums[j] <NEW_LINE> <DEDENT> <DEDENT> nums_pre = nums.copy() <NEW_LINE> <DEDENT> return nums[-1]
@param: : A string @param: : A string @return: Count the number of distinct subsequences
62598faa67a9b606de545f4c
class XfieldNotFoundError(Exception): <NEW_LINE> <INDENT> pass
raise when xfield is not defined
62598faa090684286d59369c
class TaggedContentAdminMixin(object): <NEW_LINE> <INDENT> form = TaggedContentItemForm
When this is the first in the list of base classes for the admin class of a model that has tags it will ensure your 'tags' are filtered.
62598faa32920d7e50bc5fd5
class CollectionError(Exception): <NEW_LINE> <INDENT> def __init__(self,msg): <NEW_LINE> <INDENT> Exception.__init__(self,msg)
exception when Collection does not exist
62598faa097d151d1a2c0fa9
class FixedClass(type): <NEW_LINE> <INDENT> def __setattr__(cls, key, value): <NEW_LINE> <INDENT> if cls.fixed: <NEW_LINE> <INDENT> for line in traceback.format_stack()[:-2]: <NEW_LINE> <INDENT> print(line, end='') <NEW_LINE> <DEDENT> raise SystemExit('{cls}.{key} may not be changed'.format(cls=cls.__name__, key=key)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> type.__setattr__(cls, key, value)
Metaclass: after the class variable fixed is set to True, all class variables become immutable
62598faa0c0af96317c56303
class IBNResNeXtBottleneck(nn.Layer): <NEW_LINE> <INDENT> def __init__(self, in_channels, out_channels, strides, cardinality, bottleneck_width, conv1_ibn, data_format="channels_last", **kwargs): <NEW_LINE> <INDENT> super(IBNResNeXtBottleneck, self).__init__(**kwargs) <NEW_LINE> mid_channels = out_channels // 4 <NEW_LINE> D = int(math.floor(mid_channels * (bottleneck_width / 64.0))) <NEW_LINE> group_width = cardinality * D <NEW_LINE> self.conv1 = ibn_conv1x1_block( in_channels=in_channels, out_channels=group_width, use_ibn=conv1_ibn, data_format=data_format, name="conv1") <NEW_LINE> self.conv2 = conv3x3_block( in_channels=group_width, out_channels=group_width, strides=strides, groups=cardinality, data_format=data_format, name="conv2") <NEW_LINE> self.conv3 = conv1x1_block( in_channels=group_width, out_channels=out_channels, activation=None, data_format=data_format, name="conv3") <NEW_LINE> <DEDENT> def call(self, x, training=None): <NEW_LINE> <INDENT> x = self.conv1(x, training=training) <NEW_LINE> x = self.conv2(x, training=training) <NEW_LINE> x = self.conv3(x, training=training) <NEW_LINE> return x
IBN-ResNeXt bottleneck block for residual path in IBN-ResNeXt unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. strides : int or tuple/list of 2 int Strides of the convolution. cardinality: int Number of groups. bottleneck_width: int Width of bottleneck block. conv1_ibn : bool Whether to use IBN normalization in the first convolution layer of the block. data_format : str, default 'channels_last' The ordering of the dimensions in tensors.
62598faa76e4537e8c3ef52d
class AESCipher: <NEW_LINE> <INDENT> def __init__(self, key): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> <DEDENT> def encrypt(self, raw, iv): <NEW_LINE> <INDENT> raw = pad(raw) <NEW_LINE> cipher = AES.new(self.key, AES.MODE_CBC, iv) <NEW_LINE> return cipher.encrypt(raw) <NEW_LINE> <DEDENT> def decrypt(self, enc, iv): <NEW_LINE> <INDENT> cipher = AES.new(self.key, AES.MODE_CBC, iv) <NEW_LINE> return unpad(cipher.decrypt(enc[16:]))
Usage: c = AESCipher('password').encrypt('message') m = AESCipher('password').decrypt(c) Tested under Python 3 and PyCrypto 2.6.1.
62598faa627d3e7fe0e06e2d
class Node(object): <NEW_LINE> <INDENT> default = 'DEFAULT' <NEW_LINE> def __init__(self, children=None, connector=None, negated=False): <NEW_LINE> <INDENT> self.children = children and children[:] or [] <NEW_LINE> self.connector = connector or self.default <NEW_LINE> self.negated = negated <NEW_LINE> <DEDENT> def _new_instance(cls, children=None, connector=None, negated=False): <NEW_LINE> <INDENT> obj = Node(children, connector, negated) <NEW_LINE> obj.__class__ = cls <NEW_LINE> return obj <NEW_LINE> <DEDENT> _new_instance = classmethod(_new_instance) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if self.negated: <NEW_LINE> <INDENT> return '(NOT (%s: %s))' % (self.connector, ', '.join([str(c) for c in self.children])) <NEW_LINE> <DEDENT> return '(%s: %s)' % (self.connector, ', '.join([str(c) for c in self.children])) <NEW_LINE> <DEDENT> def __deepcopy__(self, memodict): <NEW_LINE> <INDENT> obj = Node(connector=self.connector, negated=self.negated) <NEW_LINE> obj.__class__ = self.__class__ <NEW_LINE> obj.children = copy.deepcopy(self.children, memodict) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.children) <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return bool(self.children) <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return type(self).__bool__(self) <NEW_LINE> <DEDENT> def __contains__(self, other): <NEW_LINE> <INDENT> return other in self.children <NEW_LINE> <DEDENT> def _prepare_data(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def add(self, data, conn_type, squash=True): <NEW_LINE> <INDENT> if data in self.children: <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> data = self._prepare_data(data) <NEW_LINE> if not squash: <NEW_LINE> <INDENT> self.children.append(data) <NEW_LINE> return data <NEW_LINE> <DEDENT> if self.connector == conn_type: <NEW_LINE> <INDENT> if (isinstance(data, Node) and not data.negated and (data.connector == conn_type or len(data) == 1)): <NEW_LINE> <INDENT> self.children.extend(data.children) <NEW_LINE> return self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.children.append(data) <NEW_LINE> return data <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> obj = self._new_instance(self.children, self.connector, self.negated) <NEW_LINE> self.connector = conn_type <NEW_LINE> self.children = [obj, data] <NEW_LINE> return data <NEW_LINE> <DEDENT> <DEDENT> def negate(self): <NEW_LINE> <INDENT> self.negated = not self.negated
A single internal node in the tree graph. A Node should be viewed as a connection (the root) with the children being either leaf nodes or other Node instances.
62598faafff4ab517ebcd765
class Shape(): <NEW_LINE> <INDENT> ERASED = 0 <NEW_LINE> DRAWN = 1 <NEW_LINE> def __init__(self, xpos = 0, ypos = 0, ): <NEW_LINE> <INDENT> self.set_xpos(xpos) <NEW_LINE> self.set_ypos(ypos) <NEW_LINE> self._gstate = Shape.ERASED <NEW_LINE> <DEDENT> def draw(self): <NEW_LINE> <INDENT> if self._gstate != Shape.DRAWN: <NEW_LINE> <INDENT> self._gstate = Shape.DRAWN <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def erase(self): <NEW_LINE> <INDENT> if self._gstate != Shape.ERASED: <NEW_LINE> <INDENT> self._gstate = Shape.ERASED <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def move_by(self, delta_x, delta_y): <NEW_LINE> <INDENT> if agentsim.debug.get(4): <NEW_LINE> <INDENT> print("Shape:move_by", delta_x, delta_y) <NEW_LINE> <DEDENT> self.set_xpos(self.get_xpos() + delta_x) <NEW_LINE> self.set_ypos(self.get_ypos() + delta_y) <NEW_LINE> return self <NEW_LINE> <DEDENT> def get_xpos(self): <NEW_LINE> <INDENT> return self._xpos <NEW_LINE> <DEDENT> def get_ypos(self): <NEW_LINE> <INDENT> return self._ypos <NEW_LINE> <DEDENT> def set_xpos(self, x): <NEW_LINE> <INDENT> self._xpos = agentsim.gui.clip_x(x) <NEW_LINE> return self._xpos <NEW_LINE> <DEDENT> def set_ypos(self, y): <NEW_LINE> <INDENT> self._ypos = agentsim.gui.clip_y(y) <NEW_LINE> return self._ypos
Shape base class for simulation framework The visualization of the simulation uses shapes moving about on the canvas panel. Each shape is a collection of artifacts on the graphics canvas that are manipulated as a whole. The canvas has the coordinate system of the top right quadrant of the Cartesian plane. (0,0) is the lower left corner. Each Shape has a position which must lie inside the dimensions of the canvas. Some parts of the shape can extend outside the canvas area, and are clipped. get_xpos, set_xpos, get_xpos, set_ypos are accessors to the position. Set will clip the position to lie within the canvas dimensions. Each shape has a graphics _gstate: DRAWN means that the components of the shape have been rendered on the canvas and are visible ERASED means that the components of the shape have been deleted from the canvas. We do not yet support HIDDEN which would be DRAWN but not visible The Shape base class implements the following operations on Shape s: s.draw() - render the graphics artifacts associated with the shape onto the canvas and set the state to DRAWN. s.erase() - remove all graphics artifacts from the canvas and set state to ERASED s.move_by(delta_x, delta_y) - move the position of the shape on the canvas by relative amounts delta_x, delta_y The base class move_by makes sure that positions are updated and properly clipped. The derived class move_by needs to do the actual action on the drawn graphic object.
62598faa4e4d5625663723a6
class ParameterBehaviour(Function.Param.Behaviour): <NEW_LINE> <INDENT> class ParameterUsageInfo: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.params_used: List[Function.Param] = [] <NEW_LINE> self.pre_decl_scopes: List = [] <NEW_LINE> self.post_decl_scopes: List = [] <NEW_LINE> self.pools = [] <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return bool(self.params_used or self.pre_decl_scopes or self.post_decl_scopes or self.pools) <NEW_LINE> <DEDENT> <DEDENT> def wrap(self, rule, param) -> ParameterUsageInfo: <NEW_LINE> <INDENT> ret = self.ParameterUsageInfo() <NEW_LINE> if param: <NEW_LINE> <INDENT> ret.params_used.append(param) <NEW_LINE> <DEDENT> return ret
Trigger for a function parameter NOTE: unlike regular behaviours, this behaviour returns a ParameterUsageInfo. ParameterBehaviour object should not be used as a regular behaviour, since ParameterUsageInfo is not a Swimporting.
62598faa236d856c2adc93fd
class Runner(RunnerClient): <NEW_LINE> <INDENT> def _print_docs(self): <NEW_LINE> <INDENT> ret = super(Runner, self).get_docs() <NEW_LINE> for fun in sorted(ret): <NEW_LINE> <INDENT> print("{0}:\n{1}\n".format(fun, ret[fun])) <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> if self.opts.get('doc', False): <NEW_LINE> <INDENT> self._print_docs() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(Runner, self).cmd( self.opts['fun'], self.opts['arg']) <NEW_LINE> <DEDENT> except salt.exceptions.SaltException as exc: <NEW_LINE> <INDENT> sys.stderr.write('{0}\n'.format(exc)) <NEW_LINE> sys.exit(1)
Execute the salt runner interface
62598faa7b25080760ed742e
class TheHiveSearchCaseObservableRequestCallback(TheHiveApiRequestCallback): <NEW_LINE> <INDENT> def on_request(self, request): <NEW_LINE> <INDENT> super(TheHiveSearchCaseObservableRequestCallback, self).on_request(request) <NEW_LINE> self._thehive_client.post(request, "/api/case/artifact/_search")
Request callback used to invoke TheHive REST API for case/observable/search DXL requests.
62598faae76e3b2f99fd89b7
class AlexaEntity: <NEW_LINE> <INDENT> def __init__(self, hass, config, entity): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.config = config <NEW_LINE> self.entity = entity <NEW_LINE> self.entity_conf = config.entity_config.get(entity.entity_id, {}) <NEW_LINE> <DEDENT> @property <NEW_LINE> def entity_id(self): <NEW_LINE> <INDENT> return self.entity.entity_id <NEW_LINE> <DEDENT> def friendly_name(self): <NEW_LINE> <INDENT> return self.entity_conf.get(CONF_NAME, self.entity.name).translate( TRANSLATION_TABLE ) <NEW_LINE> <DEDENT> def description(self): <NEW_LINE> <INDENT> description = self.entity_conf.get(CONF_DESCRIPTION) or self.entity_id <NEW_LINE> return f"{description} via Home Assistant".translate(TRANSLATION_TABLE) <NEW_LINE> <DEDENT> def alexa_id(self): <NEW_LINE> <INDENT> return self.entity.entity_id.replace(".", "#").translate(TRANSLATION_TABLE) <NEW_LINE> <DEDENT> def display_categories(self): <NEW_LINE> <INDENT> entity_conf = self.config.entity_config.get(self.entity.entity_id, {}) <NEW_LINE> if CONF_DISPLAY_CATEGORIES in entity_conf: <NEW_LINE> <INDENT> return [entity_conf[CONF_DISPLAY_CATEGORIES]] <NEW_LINE> <DEDENT> return self.default_display_categories() <NEW_LINE> <DEDENT> def default_display_categories(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_interface(self, capability): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def interfaces(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def serialize_properties(self): <NEW_LINE> <INDENT> for interface in self.interfaces(): <NEW_LINE> <INDENT> for prop in interface.serialize_properties(): <NEW_LINE> <INDENT> yield prop <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def serialize_discovery(self): <NEW_LINE> <INDENT> return { "displayCategories": self.display_categories(), "cookie": {}, "endpointId": self.alexa_id(), "friendlyName": self.friendly_name(), "description": self.description(), "manufacturerName": "Home Assistant", "capabilities": [i.serialize_discovery() for i in self.interfaces()], }
An adaptation of an entity, expressed in Alexa's terms. The API handlers should manipulate entities only through this interface.
62598faa4428ac0f6e6584a5
class SVN(source.SVN): <NEW_LINE> <INDENT> def __init__(self, reponame, allow_patch=True, *args, **kwargs): <NEW_LINE> <INDENT> source.SVN.__init__(self, *args, **kwargs) <NEW_LINE> self.reponame = reponame <NEW_LINE> self.allow_patch = allow_patch <NEW_LINE> <DEDENT> def describe(self, done=False): <NEW_LINE> <INDENT> s = source.SVN.describe(self, done) <NEW_LINE> s.insert(1, self.reponame) <NEW_LINE> return s <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> s = self.build.getSourceStamp() <NEW_LINE> backup_patch = s.patch <NEW_LINE> backup_revision = s.revision <NEW_LINE> backup_alwaysUseLatest = self.alwaysUseLatest <NEW_LINE> if s.patch: <NEW_LINE> <INDENT> if self.allow_patch: <NEW_LINE> <INDENT> self.alwaysUseLatest = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s.patch = None <NEW_LINE> s.revision = None <NEW_LINE> <DEDENT> <DEDENT> source.SVN.start(self) <NEW_LINE> s.patch = backup_patch <NEW_LINE> s.revision = backup_revision <NEW_LINE> self.alwaysUseLatest = backup_alwaysUseLatest
An SVN source that ties changes directory with the configured repository name for use with RepoChangeScheduler and our SVNPoller.
62598faa5fc7496912d48243
class InotifyDiskCollectorThread(ExceptionalThread, FileSystemEventHandler): <NEW_LINE> <INDENT> INTERESTING_EVENTS = (FileCreatedEvent, FileDeletedEvent, FileModifiedEvent, FileMovedEvent) <NEW_LINE> COLLECTION_INTERVAL = Amount(5, Time.SECONDS) <NEW_LINE> def __init__(self, path): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> self._files = {} <NEW_LINE> self._queue = Queue() <NEW_LINE> self._observer = WatchdogObserver() <NEW_LINE> super(InotifyDiskCollectorThread, self).__init__() <NEW_LINE> self.daemon = True <NEW_LINE> <DEDENT> def dispatch(self, event): <NEW_LINE> <INDENT> if isinstance(event, self.INTERESTING_EVENTS): <NEW_LINE> <INDENT> self._queue.put(event) <NEW_LINE> <DEDENT> <DEDENT> def _initialize(self): <NEW_LINE> <INDENT> log.debug("Starting watchdog observer to collect events...") <NEW_LINE> self._observer.schedule(self, path=self._path, recursive=True) <NEW_LINE> self._observer.start() <NEW_LINE> log.debug("Collecting initial disk usage sample...") <NEW_LINE> for root, _, files in os.walk(self._path): <NEW_LINE> <INDENT> for filename in files: <NEW_LINE> <INDENT> f = os.path.join(root, filename) <NEW_LINE> self._files[f] = safe_bsize(f) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _process_events(self): <NEW_LINE> <INDENT> file_ops = {} <NEW_LINE> def remove_file(path): <NEW_LINE> <INDENT> self._files.pop(path, None) <NEW_LINE> <DEDENT> def stat_file(path): <NEW_LINE> <INDENT> self._files[path] = safe_bsize(path) <NEW_LINE> <DEDENT> while not self._to_process.empty(): <NEW_LINE> <INDENT> event = self._to_process.get() <NEW_LINE> if isinstance(event, (FileCreatedEvent, FileModifiedEvent)): <NEW_LINE> <INDENT> file_ops[event.src_path] = lambda: stat_file(event.src_path) <NEW_LINE> <DEDENT> elif isinstance(event, FileDeletedEvent): <NEW_LINE> <INDENT> file_ops[event.src_path] = lambda: remove_file(event.src_path) <NEW_LINE> <DEDENT> elif isinstance(event, FileMovedEvent): <NEW_LINE> <INDENT> file_ops[event.src_path] = lambda: remove_file(event.src_path) <NEW_LINE> file_ops[event.dest_path] = lambda: stat_file(event.dest_path) <NEW_LINE> <DEDENT> <DEDENT> for op in file_ops.values(): <NEW_LINE> <INDENT> op() <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> self._initialize() <NEW_LINE> log.debug("Initialization complete. Moving to handling events.") <NEW_LINE> while True: <NEW_LINE> <INDENT> next = time.time() + self.COLLECTION_INTERVAL.as_(Time.SECONDS) <NEW_LINE> if not self._queue.empty(): <NEW_LINE> <INDENT> self._to_process, self._queue = self._queue, Queue() <NEW_LINE> self._process_events() <NEW_LINE> <DEDENT> time.sleep(max(0, next - time.time())) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return sum(self._files.itervalues())
Thread to calculate aggregate disk usage under a given path Note that while this thread uses inotify (through the watchdog module) to monitor disk events in "real time", the actual processing of events is only performed periodically (configured via COLLECTION_INTERVAL)
62598faacb5e8a47e493c139
class unique(GeneralFunction): <NEW_LINE> <INDENT> def __init__(self,col): <NEW_LINE> <INDENT> self.fargs = [col]
Return only the unique values from a scalar.
62598faa7c178a314d78d41e
class PortConnectionError(Exception): <NEW_LINE> <INDENT> pass
Raised in case of attemp of connecting two output ports
62598faa3317a56b869be50b
class SufficientError(Exception): <NEW_LINE> <INDENT> pass
Stop when we've reached the test point
62598faa4f6381625f19947f
class View: <NEW_LINE> <INDENT> def __init__(self, controller): <NEW_LINE> <INDENT> self._controller = controller <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> raise NotImplementedError()
Abstract class representing the view of a puzzle game. Responsible for displaying state to the user and interpreting user input.
62598faae5267d203ee6b88c
class LogGaussian(Prior): <NEW_LINE> <INDENT> def __init__(self, mean: ndarray, cov: ndarray): <NEW_LINE> <INDENT> self.mean = mean <NEW_LINE> self.covariance = cov <NEW_LINE> self.precision = np.linalg.inv(cov) <NEW_LINE> self._dimensions = np.size(mean) <NEW_LINE> self._multivariate_normal = scipy.stats.multivariate_normal(mean=mean, cov=cov) <NEW_LINE> <DEDENT> def sample(self) -> ndarray: <NEW_LINE> <INDENT> return np.atleast_1d(np.exp(self._multivariate_normal.rvs())) <NEW_LINE> <DEDENT> def gradient(self, x: ndarray) -> Tuple[ndarray, ndarray]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __call__(self, x: ndarray) -> ndarray: <NEW_LINE> <INDENT> validate_dimensions(x, self._dimensions) <NEW_LINE> return np.atleast_1d(np.exp(self._multivariate_normal._pdf_point_est(x))) <NEW_LINE> <DEDENT> def eval(self, *x): <NEW_LINE> <INDENT> pass
Multivariate Log-Gaussian Prior Addition by Xingchen Wan | 2018
62598faa7d847024c075c345
class ISpeciesFolder(IIngestableFolder): <NEW_LINE> <INDENT> pass
Folder containing species.
62598faa435de62698e9bd77
class WTimeoutError(TimeoutError): <NEW_LINE> <INDENT> pass
Raised when a database operation times out (i.e. wtimeout expires) before replication completes. With newer versions of MongoDB the `error_document` attribute may include write concern fields like 'n', 'updatedExisting', or 'writtenTo'. .. versionadded:: 2.7
62598faa5fdd1c0f98e5df18
class FuncionesVitalesForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = FuncionesVitales <NEW_LINE> exclude = ('consulta',) <NEW_LINE> widgets = { 'frecuencia_cardiaca': forms.TextInput(attrs={'class': 'form-control', 'required':'true', 'placeholder': 'Ingrese frecuencia cardiaca'}), 'frecuencia_respiratoria': forms.TextInput(attrs={'class': 'form-control', 'required':'true', 'placeholder': 'Ingrese frecuencia respiratoria'}), 'presion_arterial': forms.TextInput(attrs={'class': 'form-control', 'required':'true', 'placeholder': 'Ingrese presion arterial'}), 'temperatura': forms.TextInput(attrs={'class': 'form-control', 'required':'true', 'placeholder': 'Ingrese temperatura'}), 'peso': forms.TextInput(attrs={'class': 'form-control', 'required':'true', 'placeholder': 'Ingrese peso'}), 'talla': forms.TextInput(attrs={'class': 'form-control', 'required':'true', 'placeholder': 'Ingrese talla'}), 'masa_corporal': forms.TextInput(attrs={'class': 'form-control', 'required':'true', 'placeholder': 'Ingrese masa corporal'}), 'diagnostico_mc': forms.TextInput(attrs={'class': 'form-control', 'required':'true'}) }
Class FuncionesVitalesForm.
62598faa91af0d3eaad39d92
class HelixProtocol: <NEW_LINE> <INDENT> def __init__(self, con, user, password): <NEW_LINE> <INDENT> self.con = con <NEW_LINE> self.user = user <NEW_LINE> self.password = password <NEW_LINE> self.state = None <NEW_LINE> self.state = HandshakeAwaitingState(None, self) <NEW_LINE> <DEDENT> def on_receive(self, msg): <NEW_LINE> <INDENT> require_field(msg, "type") <NEW_LINE> require_field(msg, "body") <NEW_LINE> if not self.state.on_receive(msg): <NEW_LINE> <INDENT> raise HelixProtocolError("Unexpected Message " + msg["type"] + " during " + self.state.name) <NEW_LINE> log.error("Unexpected Message {0}", msg["type"]) <NEW_LINE> <DEDENT> <DEDENT> def transition(self, state): <NEW_LINE> <INDENT> self.state = state
Simple state machine for protocol to IoT Control Center adapter. States and messages: handshake_awaiting =================================================== <-- connection_request handshake_responded =================================================== --> connection_response <-- connection_verified handshake_verified =================================================== for all output resource kinds simultaneously do --> create_resource_kind_request <-- create_resource_kind_response steady =================================================== for all objects simultaneously do while uuid not available do --> create_or_find_resource_request <-- create_or_find_resource_response // Create relationship to gateway --> create_relationship_request <-- create_relationship_response loop forever if output <-- action if input --> add_stats
62598faaa79ad16197769fe7
class V1HTTPGetAction(object): <NEW_LINE> <INDENT> def __init__(self, path=None, http_headers=None, host=None, scheme=None, port=None): <NEW_LINE> <INDENT> self.swagger_types = { 'path': 'str', 'http_headers': 'list[V1HTTPHeader]', 'host': 'str', 'scheme': 'str', 'port': 'str' } <NEW_LINE> self.attribute_map = { 'path': 'path', 'http_headers': 'httpHeaders', 'host': 'host', 'scheme': 'scheme', 'port': 'port' } <NEW_LINE> self._path = path <NEW_LINE> self._http_headers = http_headers <NEW_LINE> self._host = host <NEW_LINE> self._scheme = scheme <NEW_LINE> self._port = port <NEW_LINE> <DEDENT> @property <NEW_LINE> def path(self): <NEW_LINE> <INDENT> return self._path <NEW_LINE> <DEDENT> @path.setter <NEW_LINE> def path(self, path): <NEW_LINE> <INDENT> self._path = path <NEW_LINE> <DEDENT> @property <NEW_LINE> def http_headers(self): <NEW_LINE> <INDENT> return self._http_headers <NEW_LINE> <DEDENT> @http_headers.setter <NEW_LINE> def http_headers(self, http_headers): <NEW_LINE> <INDENT> self._http_headers = http_headers <NEW_LINE> <DEDENT> @property <NEW_LINE> def host(self): <NEW_LINE> <INDENT> return self._host <NEW_LINE> <DEDENT> @host.setter <NEW_LINE> def host(self, host): <NEW_LINE> <INDENT> self._host = host <NEW_LINE> <DEDENT> @property <NEW_LINE> def scheme(self): <NEW_LINE> <INDENT> return self._scheme <NEW_LINE> <DEDENT> @scheme.setter <NEW_LINE> def scheme(self, scheme): <NEW_LINE> <INDENT> self._scheme = scheme <NEW_LINE> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> return self._port <NEW_LINE> <DEDENT> @port.setter <NEW_LINE> def port(self, port): <NEW_LINE> <INDENT> self._port = port <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598faabe383301e025377b
class RecipeSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> ingredients = serializers.PrimaryKeyRelatedField( many=True, queryset=Ingredient.objects.all() ) <NEW_LINE> tags = serializers.PrimaryKeyRelatedField( many=True, queryset=Tag.objects.all() ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Recipe <NEW_LINE> fields = ('id', 'title', 'ingredients', 'tags', 'time_minutes', 'price', 'link') <NEW_LINE> read_only_fields = ('id',)
"Serialize a recipe
62598faa1f037a2d8b9e406f
class FileSystemTarget(Target): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> <DEDENT> @abc.abstractproperty <NEW_LINE> def fs(self): <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def open(self, mode): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def exists(self): <NEW_LINE> <INDENT> path = self.path <NEW_LINE> if '*' in path or '?' in path or '[' in path or '{' in path: <NEW_LINE> <INDENT> logger.warning("Using wildcards in path %s might lead to processing of an incomplete dataset; " "override exists() to suppress the warning.", path) <NEW_LINE> <DEDENT> return self.fs.exists(path) <NEW_LINE> <DEDENT> def remove(self): <NEW_LINE> <INDENT> self.fs.remove(self.path)
Base class for FileSystem Targets like :class:`~luigi.file.LocalTarget` and :class:`~luigi.hdfs.HdfsTarget`. A FileSystemTarget has an associated :py:class:`FileSystem` to which certain operations can be delegated. By default, :py:meth:`exists` and :py:meth:`remove` are delegated to the :py:class:`FileSystem`, which is determined by the :py:meth:`fs` property. Methods of FileSystemTarget raise :py:class:`FileSystemException` if there is a problem completing the operation.
62598faab7558d58954635ab
class LinuxARMThumbStack(LinuxARMThumb): <NEW_LINE> <INDENT> data_finalizer = _stack_data_finalizer
An environment that targets a 32-bit Linux ARM machine using the Thumb instruction set that allocates the required data on the stack.
62598faabaa26c4b54d4f234
class AgentEvent(BaseEnum): <NEW_LINE> <INDENT> GO_POWER_UP = 'AGENT_EVENT_GO_POWER_DOWN' <NEW_LINE> GO_POWER_DOWN = 'AGENT_EVENT_GO_POWER_UP' <NEW_LINE> INITIALIZE = 'AGENT_EVENT_INITIALIZE' <NEW_LINE> RESET = 'AGENT_EVENT_RESET' <NEW_LINE> GO_ACTIVE = 'AGENT_EVENT_GO_ACTIVE' <NEW_LINE> GO_INACTIVE = 'AGENT_EVENT_GO_INACTIVE' <NEW_LINE> CLEAR = 'AGENT_EVENT_CLEAR' <NEW_LINE> RESUME = 'AGENT_EVENT_RESUME' <NEW_LINE> RUN = 'AGENT_EVENT_RUN' <NEW_LINE> PAUSE = 'AGENT_EVENT_PAUSE' <NEW_LINE> GO_OBSERVATORY_MODE = 'AGENT_EVENT_GO_OBSERVATORY_MODE' <NEW_LINE> GO_DIRECT_ACCESS_MODE = 'AGENT_EVENT_GO_DIRECT_ACCESS_MODE' <NEW_LINE> ENTER = 'AGENT_EVENT_ENTER' <NEW_LINE> EXIT = 'AGENT_EVENT_EXIT'
Common agent event enum.
62598faaa8370b77170f035d
class RegistrationManager(models.Manager): <NEW_LINE> <INDENT> def activate_user(self, activation_key): <NEW_LINE> <INDENT> if SHA1_RE.search(activation_key): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> profile = self.get(activation_key=activation_key) <NEW_LINE> <DEDENT> except self.model.DoesNotExist: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not profile.activation_key_expired(): <NEW_LINE> <INDENT> user = profile.user <NEW_LINE> user.is_active = True <NEW_LINE> user.save() <NEW_LINE> profile.activation_key = self.model.ACTIVATED <NEW_LINE> profile.save() <NEW_LINE> return user <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def create_inactive_user(self, username, email, password, site, send_email=True): <NEW_LINE> <INDENT> new_user = User.objects.create_user(username, email, password) <NEW_LINE> new_user.is_active = False <NEW_LINE> new_user.save() <NEW_LINE> registration_profile = self.create_profile(new_user) <NEW_LINE> if send_email: <NEW_LINE> <INDENT> registration_profile.send_activation_email(site) <NEW_LINE> <DEDENT> return new_user <NEW_LINE> <DEDENT> create_inactive_user = transaction.commit_on_success(create_inactive_user) <NEW_LINE> def create_profile(self, user): <NEW_LINE> <INDENT> salt = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5] <NEW_LINE> salted_username = salt + user.username <NEW_LINE> activation_key = hashlib.sha1(salted_username.encode('utf-8')).hexdigest() <NEW_LINE> return self.create(user=user, activation_key=activation_key) <NEW_LINE> <DEDENT> def delete_expired_users(self): <NEW_LINE> <INDENT> for profile in self.all(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if profile.activation_key_expired(): <NEW_LINE> <INDENT> user = profile.user <NEW_LINE> if not user.is_active: <NEW_LINE> <INDENT> user.delete() <NEW_LINE> profile.delete() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> profile.delete()
Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts.
62598faa57b8e32f525080dc
class CustomerCertificateParameters(SecretParameters): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, 'secret_source': {'required': True}, } <NEW_LINE> _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'secret_source': {'key': 'secretSource', 'type': 'ResourceReference'}, 'secret_version': {'key': 'secretVersion', 'type': 'str'}, 'certificate_authority': {'key': 'certificateAuthority', 'type': 'str'}, 'use_latest_version': {'key': 'useLatestVersion', 'type': 'bool'}, 'subject_alternative_names': {'key': 'subjectAlternativeNames', 'type': '[str]'}, } <NEW_LINE> def __init__( self, *, secret_source: "ResourceReference", secret_version: Optional[str] = None, certificate_authority: Optional[str] = None, use_latest_version: Optional[bool] = None, subject_alternative_names: Optional[List[str]] = None, **kwargs ): <NEW_LINE> <INDENT> super(CustomerCertificateParameters, self).__init__(**kwargs) <NEW_LINE> self.type = 'CustomerCertificate' <NEW_LINE> self.secret_source = secret_source <NEW_LINE> self.secret_version = secret_version <NEW_LINE> self.certificate_authority = certificate_authority <NEW_LINE> self.use_latest_version = use_latest_version <NEW_LINE> self.subject_alternative_names = subject_alternative_names
Customer Certificate used for https. All required parameters must be populated in order to send to Azure. :param type: Required. The type of the Secret to create.Constant filled by server. Possible values include: "UrlSigningKey", "CustomerCertificate", "ManagedCertificate". :type type: str or ~azure.mgmt.cdn.models.SecretType :param secret_source: Required. Resource reference to the KV secret. :type secret_source: ~azure.mgmt.cdn.models.ResourceReference :param secret_version: Version of the secret to be used. :type secret_version: str :param certificate_authority: Certificate issuing authority. :type certificate_authority: str :param use_latest_version: Whether to use the latest version for the certificate. :type use_latest_version: bool :param subject_alternative_names: The list of SANs. :type subject_alternative_names: list[str]
62598faa5166f23b2e24335a
class Value(models.Model): <NEW_LINE> <INDENT> attribute = models.ForeignKey( Attribute, related_name='values', db_index=True, on_delete=models.PROTECT ) <NEW_LINE> value = models.CharField( max_length=255, null=False, blank=True, db_index=True ) <NEW_LINE> resource = models.ForeignKey( 'Resource', related_name='attributes', db_index=True, blank=True ) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return u'%r %s=%s' % (self.resource, self.name, self.value) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('attribute', 'value', 'resource') <NEW_LINE> index_together = unique_together <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.attribute.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def resource_name(self): <NEW_LINE> <INDENT> return self.attribute.resource_name <NEW_LINE> <DEDENT> def clean_fields(self, exclude=None): <NEW_LINE> <INDENT> log.debug('cleaning %s', self.name) <NEW_LINE> if self.resource_name != self.resource._resource_name: <NEW_LINE> <INDENT> raise exc.ValidationError({ 'attribute': 'Invalid attribute type for this resource.' }) <NEW_LINE> <DEDENT> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.full_clean() <NEW_LINE> super(Value, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'name': self.name, 'value': self.value, 'attribute': self.attribute.to_dict(), 'resource_name': self.resource_name, 'resource': self.resource.to_dict(), }
Represents a value for an attribute attached to a Resource.
62598faa01c39578d7f12d02
class WorkspaceLookupError(ProKnowError): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super(WorkspaceLookupError, self).__init__(message) <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'WorkspaceLookupError({!r})'.format(self.message) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self)
Indicates that there was a problem looking up the workspace by the given identifier. Attributes: message (str): An explanation of the error.
62598faa627d3e7fe0e06e2f
class LSTMSequenceEncoder(PyTextSeq2SeqModule): <NEW_LINE> <INDENT> class Config(ConfigBase): <NEW_LINE> <INDENT> embed_dim: int = 512 <NEW_LINE> hidden_dim: int = 512 <NEW_LINE> num_layers: int = 1 <NEW_LINE> dropout_in: float = 0.1 <NEW_LINE> dropout_out: float = 0.1 <NEW_LINE> bidirectional: bool = False <NEW_LINE> <DEDENT> def __init__( self, embed_dim, hidden_dim, num_layers, dropout_in, dropout_out, bidirectional ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.dropout_in = dropout_in <NEW_LINE> self.dropout_out = dropout_out <NEW_LINE> self.hidden_dim = hidden_dim <NEW_LINE> self.bidirectional = bidirectional <NEW_LINE> self.num_layers: int = num_layers <NEW_LINE> self.word_dim = embed_dim <NEW_LINE> self.bilstm = BiLSTM( num_layers=num_layers, bidirectional=bidirectional, embed_dim=embed_dim, hidden_dim=hidden_dim, dropout=dropout_out, ) <NEW_LINE> log_class_usage(__class__) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_config(cls, config): <NEW_LINE> <INDENT> return cls(**config._asdict()) <NEW_LINE> <DEDENT> def forward( self, src_tokens: torch.Tensor, embeddings: torch.Tensor, src_lengths ) -> Dict[str, torch.Tensor]: <NEW_LINE> <INDENT> x = F.dropout(embeddings, p=self.dropout_in, training=self.training) <NEW_LINE> x = x.transpose(0, 1) <NEW_LINE> unpacked_output, final_hiddens, final_cells = self.bilstm( embeddings=x, lengths=src_lengths ) <NEW_LINE> return { "unpacked_output": unpacked_output, "final_hiddens": final_hiddens, "final_cells": final_cells, "src_lengths": src_lengths, "src_tokens": src_tokens, "embeddings": embeddings, } <NEW_LINE> <DEDENT> def max_positions(self): <NEW_LINE> <INDENT> return int(1e5) <NEW_LINE> <DEDENT> def tile_encoder_out( self, beam_size: int, encoder_out: Dict[str, torch.Tensor] ) -> Dict[str, torch.Tensor]: <NEW_LINE> <INDENT> tiled_encoder_out = encoder_out["unpacked_output"].expand(-1, beam_size, -1) <NEW_LINE> hiddens = encoder_out["final_hiddens"] <NEW_LINE> tiled_hiddens: List[torch.Tensor] = [] <NEW_LINE> for i in range(self.num_layers): <NEW_LINE> <INDENT> tiled_hiddens.append(hiddens[i].expand(beam_size, -1)) <NEW_LINE> <DEDENT> cells = encoder_out["final_cells"] <NEW_LINE> tiled_cells: List[torch.Tensor] = [] <NEW_LINE> for i in range(self.num_layers): <NEW_LINE> <INDENT> tiled_cells.append(cells[i].expand(beam_size, -1)) <NEW_LINE> <DEDENT> return { "unpacked_output": tiled_encoder_out, "final_hiddens": torch.stack(tiled_hiddens, dim=0), "final_cells": torch.stack(tiled_cells, dim=0), "src_lengths": encoder_out["src_lengths"], "src_tokens": encoder_out["src_tokens"], }
RNN encoder using nn.LSTM for cuDNN support / ONNX exportability.
62598faafff4ab517ebcd767
class Resource(Model): <NEW_LINE> <INDENT> def __init__(self, resource_id, project_id, first_sample_timestamp, last_sample_timestamp, source, user_id, metadata, meter): <NEW_LINE> <INDENT> Model.__init__(self, resource_id=resource_id, first_sample_timestamp=first_sample_timestamp, last_sample_timestamp=last_sample_timestamp, project_id=project_id, source=source, user_id=user_id, metadata=metadata, meter=meter, )
Something for which sample data has been collected.
62598faa379a373c97d98f95
class GameObject(ABC): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._pos_x = 0 <NEW_LINE> self._pos_y = 0 <NEW_LINE> self._width = 1 <NEW_LINE> self._height = 1 <NEW_LINE> self.housekeeping = GameObjectHouseKeeping() <NEW_LINE> <DEDENT> @property <NEW_LINE> def size(self): <NEW_LINE> <INDENT> return self._width, self._height <NEW_LINE> <DEDENT> @size.setter <NEW_LINE> def size(self, value): <NEW_LINE> <INDENT> w, h = value <NEW_LINE> if w != self._width or h != self._height: <NEW_LINE> <INDENT> self.housekeeping.resized = True <NEW_LINE> self._width = w <NEW_LINE> self._height = h <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def position(self): <NEW_LINE> <INDENT> return self._pos_x, self._pos_y <NEW_LINE> <DEDENT> @position.setter <NEW_LINE> def position(self, value): <NEW_LINE> <INDENT> x, y = value <NEW_LINE> if x != self._pos_x or y != self._pos_y: <NEW_LINE> <INDENT> self.housekeeping.mooved = True <NEW_LINE> self._pos_x = x <NEW_LINE> self._pos_y = y <NEW_LINE> <DEDENT> <DEDENT> @abstractmethod <NEW_LINE> def get_child_objects(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def process_event(self, event): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def update(self, delta_time): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def render(self, pad): <NEW_LINE> <INDENT> raise NotImplementedError()
Represents one "thing" in a game.
62598faa92d797404e388b26
class OpportunityViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> renderer_classes = ( rest_framework.renderers.JSONRenderer, rest_framework.renderers.BrowsableAPIRenderer, PaginatedCSVRenderer, ) <NEW_LINE> pagination_class = LargeResultsSetPagination <NEW_LINE> queryset = Opportunity.objects.all().filter(published=True) <NEW_LINE> serializer_class = OpportunitySerializer <NEW_LINE> filter_backends = (filters.DjangoFilterBackend,) <NEW_LINE> filter_class = OpportunityFilter
API endpoint that allows users to be viewed or edited.
62598faad486a94d0ba2bf51
class PISOutr(models.AbstractModel): <NEW_LINE> <INDENT> _description = textwrap.dedent(" %s" % (__doc__,)) <NEW_LINE> _name = 'nfe.40.pisoutr' <NEW_LINE> _inherit = 'spec.mixin.nfe' <NEW_LINE> _generateds_type = 'PISOutrType' <NEW_LINE> _concrete_rec_name = 'nfe40_CST' <NEW_LINE> nfe40_choice13 = fields.Selection([ ('nfe40_vBC', 'vBC'), ('nfe40_pPIS', 'pPIS'), ('nfe40_qBCProd', 'qBCProd'), ('nfe40_vAliqProd', 'vAliqProd')], "vBC/pPIS/qBCProd/vAliqProd") <NEW_LINE> nfe40_CST = fields.Selection( CST_PISOUTR, string="Código de Situação Tributária do PIS", xsd=True, xsd_required=True, help="Código de Situação Tributária do PIS." "\n99 - Outras Operações.") <NEW_LINE> nfe40_vBC = fields.Monetary( currency_field="brl_currency_id", digits=2, choice='13', string="Valor da BC do PIS", xsd=True, xsd_required=True) <NEW_LINE> nfe40_pPIS = fields.Monetary( currency_field="brl_currency_id", digits=2, choice='13', string="Alíquota do PIS (em percentual)", xsd=True, xsd_required=True) <NEW_LINE> nfe40_qBCProd = fields.Monetary( currency_field="brl_currency_id", digits=4, choice='13', string="Quantidade Vendida (NT2011/004)", xsd=True, xsd_required=True) <NEW_LINE> nfe40_vAliqProd = fields.Monetary( currency_field="brl_currency_id", digits=4, choice='13', string="Alíquota do PIS", xsd=True, xsd_required=True, help="Alíquota do PIS (em reais) (NT2011/004)") <NEW_LINE> nfe40_vPIS = fields.Monetary( currency_field="brl_currency_id", digits=2, string="Valor do PIS", xsd=True, xsd_required=True)
Código de Situação Tributária do PIS. 99 - Outras Operações.
62598faa460517430c43201e
class MountPoint(NamedObject): <NEW_LINE> <INDENT> def __init__(self, parent, name): <NEW_LINE> <INDENT> super().__init__(parent, FwObt.MountPoint, name) <NEW_LINE> <DEDENT> def pathsep(self): <NEW_LINE> <INDENT> return '/'
Mount point object
62598faaaad79263cf42e757
class RetinaNetLoss(tf.losses.Loss): <NEW_LINE> <INDENT> def __init__(self, num_classes=80, alpha=0.25, gamma=2.0, delta=1.0): <NEW_LINE> <INDENT> super(RetinaNetLoss, self).__init__(reduction="auto", name="RetinaNetLoss") <NEW_LINE> self._clf_loss = RetinaNetClassificationLoss(alpha, gamma) <NEW_LINE> self._box_loss = RetinaNetBoxLoss(delta) <NEW_LINE> self._num_classes = num_classes <NEW_LINE> <DEDENT> def call(self, y_true, y_pred): <NEW_LINE> <INDENT> y_pred = tf.cast(y_pred, dtype=tf.float32) <NEW_LINE> box_labels = y_true[:, :, :4] <NEW_LINE> box_predictions = y_pred[:, :, :4] <NEW_LINE> cls_labels = tf.one_hot( tf.cast(y_true[:, :, 4], dtype=tf.int32), depth=self._num_classes, dtype=tf.float32, ) <NEW_LINE> cls_predictions = y_pred[:, :, 4:] <NEW_LINE> positive_mask = tf.cast(tf.greater(y_true[:, :, 4], -1.0), dtype=tf.float32) <NEW_LINE> ignore_mask = tf.cast(tf.equal(y_true[:, :, 4], -2.0), dtype=tf.float32) <NEW_LINE> clf_loss = self._clf_loss(cls_labels, cls_predictions) <NEW_LINE> box_loss = self._box_loss(box_labels, box_predictions) <NEW_LINE> clf_loss = tf.where(tf.equal(ignore_mask, 1.0), 0.0, clf_loss) <NEW_LINE> box_loss = tf.where(tf.equal(positive_mask, 1.0), box_loss, 0.0) <NEW_LINE> normalizer = tf.reduce_sum(positive_mask, axis=-1) <NEW_LINE> clf_loss = tf.math.divide_no_nan(tf.reduce_sum(clf_loss, axis=-1), normalizer) <NEW_LINE> box_loss = tf.math.divide_no_nan(tf.reduce_sum(box_loss, axis=-1), normalizer) <NEW_LINE> loss = clf_loss + box_loss <NEW_LINE> return loss
Wrapper to combine both the losses
62598faa2ae34c7f260ab065
class MultipartWriter(object): <NEW_LINE> <INDENT> part_writer_cls = BodyPartWriter <NEW_LINE> def __init__(self, subtype='mixed', boundary=None): <NEW_LINE> <INDENT> boundary = boundary if boundary is not None else uuid.uuid4().hex <NEW_LINE> try: <NEW_LINE> <INDENT> boundary.encode('us-ascii') <NEW_LINE> <DEDENT> except UnicodeEncodeError: <NEW_LINE> <INDENT> raise ValueError('boundary should contains ASCII only chars') <NEW_LINE> <DEDENT> self.headers = CIMultiDict() <NEW_LINE> self.headers[CONTENT_TYPE] = 'multipart/{}; boundary="{}"'.format( subtype, boundary ) <NEW_LINE> self.parts = [] <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.parts) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.parts) <NEW_LINE> <DEDENT> @property <NEW_LINE> def boundary(self): <NEW_LINE> <INDENT> *_, params = parse_mimetype(self.headers.get(CONTENT_TYPE)) <NEW_LINE> return params['boundary'].encode('us-ascii') <NEW_LINE> <DEDENT> def append(self, obj, headers=None): <NEW_LINE> <INDENT> if isinstance(obj, self.part_writer_cls): <NEW_LINE> <INDENT> if headers: <NEW_LINE> <INDENT> obj.headers.update(headers) <NEW_LINE> <DEDENT> self.parts.append(obj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not headers: <NEW_LINE> <INDENT> headers = CIMultiDict() <NEW_LINE> <DEDENT> self.parts.append(self.part_writer_cls(obj, headers)) <NEW_LINE> <DEDENT> return self.parts[-1] <NEW_LINE> <DEDENT> def append_json(self, obj, headers=None): <NEW_LINE> <INDENT> if not headers: <NEW_LINE> <INDENT> headers = CIMultiDict() <NEW_LINE> <DEDENT> headers[CONTENT_TYPE] = 'application/json' <NEW_LINE> return self.append(obj, headers) <NEW_LINE> <DEDENT> def append_form(self, obj, headers=None): <NEW_LINE> <INDENT> if not headers: <NEW_LINE> <INDENT> headers = CIMultiDict() <NEW_LINE> <DEDENT> headers[CONTENT_TYPE] = 'application/x-www-form-urlencoded' <NEW_LINE> assert isinstance(obj, (Sequence, Mapping)) <NEW_LINE> return self.append(obj, headers) <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> if not self.parts: <NEW_LINE> <INDENT> yield b'' <NEW_LINE> return <NEW_LINE> <DEDENT> for part in self.parts: <NEW_LINE> <INDENT> yield b'--' + self.boundary + b'\r\n' <NEW_LINE> yield from part.serialize() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield b'--' + self.boundary + b'--\r\n' <NEW_LINE> <DEDENT> yield b''
Multipart body writer.
62598faa21bff66bcd722bea
@register_task("nli-alt", rel_path="NLI-Prob/") <NEW_LINE> class NLITypeProbingAltTask(NLITypeProbingTask): <NEW_LINE> <INDENT> def __init__(self, path, max_seq_len, name, probe_path="", **kw): <NEW_LINE> <INDENT> super(NLITypeProbingAltTask, self).__init__( name=name, path=path, max_seq_len=max_seq_len, **kw ) <NEW_LINE> self.path = path <NEW_LINE> self.max_seq_len = max_seq_len <NEW_LINE> self.probe_path = probe_path <NEW_LINE> self.train_data_text = None <NEW_LINE> self.val_data_text = None <NEW_LINE> self.test_data_text = None <NEW_LINE> <DEDENT> def load_data(self): <NEW_LINE> <INDENT> targ_map = {"0": 0, "1": 1, "2": 2} <NEW_LINE> prob_data = load_tsv( data_file=os.path.join(self.path, self.probe_path), max_seq_len=self.max_seq_len, s1_idx=9, s2_idx=10, label_idx=1, label_fn=targ_map.__getitem__, skip_rows=1, return_indices=True, tokenizer_name=self._tokenizer_name, ) <NEW_LINE> self.train_data_text = self.val_data_text = self.test_data_text = prob_data <NEW_LINE> self.sentences = self.val_data_text[0] + self.val_data_text[1] <NEW_LINE> log.info("\tFinished loading NLI-alt probing data.")
Task class for Alt Probing Task (NLI-type), NLITypeProbingTask with different indices
62598faae5267d203ee6b88e
class ProtoService(ProtoNode): <NEW_LINE> <INDENT> def __init__(self, name: str): <NEW_LINE> <INDENT> super().__init__(name) <NEW_LINE> self._methods: List['ProtoServiceMethod'] = [] <NEW_LINE> <DEDENT> def type(self) -> ProtoNode.Type: <NEW_LINE> <INDENT> return ProtoNode.Type.SERVICE <NEW_LINE> <DEDENT> def methods(self) -> List['ProtoServiceMethod']: <NEW_LINE> <INDENT> return list(self._methods) <NEW_LINE> <DEDENT> def add_method(self, method: 'ProtoServiceMethod') -> None: <NEW_LINE> <INDENT> self._methods.append(method) <NEW_LINE> <DEDENT> def _supports_child(self, child: ProtoNode) -> bool: <NEW_LINE> <INDENT> return False
Representation of a service in a .proto file.
62598faaadb09d7d5dc0a50e
class Params(object): <NEW_LINE> <INDENT> def __init__(self, params): <NEW_LINE> <INDENT> if isinstance(params, dict): <NEW_LINE> <INDENT> params = [params] <NEW_LINE> <DEDENT> self.params = params <NEW_LINE> <DEDENT> def names(self): <NEW_LINE> <INDENT> return [p['name'].encode('ascii') for p in self.params] <NEW_LINE> <DEDENT> def values(self, names=None): <NEW_LINE> <INDENT> if names is None: <NEW_LINE> <INDENT> names = self.names() <NEW_LINE> <DEDENT> elif not isinstance(names, list): <NEW_LINE> <INDENT> names = [names] <NEW_LINE> <DEDENT> out = [] <NEW_LINE> for p in self.params: <NEW_LINE> <INDENT> if p['name'] in names: <NEW_LINE> <INDENT> out.append(p['value']) <NEW_LINE> <DEDENT> <DEDENT> if len(out) < len(names): <NEW_LINE> <INDENT> raise KeyError("Only found values for %g of %g named parameters" % (len(out), len(names))) <NEW_LINE> <DEDENT> return asarray(out).squeeze()
Store simple parameters or lists of parameters. Assumes parameters are either a dictionary or a list of dictionaries, where each dictionary has a "name" field with a string, a "value" field, and potentially other optional fields. Attributes ---------- params : list of dicts List of dictionaries each containing a parameter, where each parameter has at least a "name" field and a "value" field
62598faa7d847024c075c347
class ServiceTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_service_trait_type(self): <NEW_LINE> <INDENT> class Foo(HasTraits): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class PluginA(Plugin): <NEW_LINE> <INDENT> id = "A" <NEW_LINE> foo = Instance(Foo, (), service=True) <NEW_LINE> <DEDENT> class PluginB(Plugin): <NEW_LINE> <INDENT> id = "B" <NEW_LINE> foo = Service(Foo) <NEW_LINE> <DEDENT> a = PluginA() <NEW_LINE> b = PluginB() <NEW_LINE> application = TestApplication(plugins=[a, b]) <NEW_LINE> application.start() <NEW_LINE> self.assertEqual(a.foo, b.foo) <NEW_LINE> application.stop() <NEW_LINE> self.assertEqual(None, b.foo) <NEW_LINE> with self.assertRaises(SystemError): <NEW_LINE> <INDENT> setattr(b, "foo", "bogus") <NEW_LINE> <DEDENT> <DEDENT> def test_service_trait_type_with_no_service_registry(self): <NEW_LINE> <INDENT> class Foo(HasTraits): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class Bar(HasTraits): <NEW_LINE> <INDENT> foo = Service(Foo) <NEW_LINE> <DEDENT> b = Bar() <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> getattr(b, "foo") <NEW_LINE> <DEDENT> <DEDENT> def test_service_str_representation(self): <NEW_LINE> <INDENT> class Foo(HasTraits): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> service_repr = "Service(protocol={!r})" <NEW_LINE> service = Service(Foo) <NEW_LINE> self.assertEqual(service_repr.format(Foo), str(service)) <NEW_LINE> self.assertEqual(service_repr.format(Foo), repr(service))
Tests for the 'Service' trait type.
62598faa435de62698e9bd7a
class RocAucEvaluation(Callback): <NEW_LINE> <INDENT> def __init__(self, validation_data=(), interval=1, model_path=None, config_path=None, frozen=False, was_frozen=True, get_embeddings=None, do_prime=False): <NEW_LINE> <INDENT> super(Callback, self).__init__() <NEW_LINE> print('validation_data=%s interval=%s, model_path=%s, config_path=%s ' 'frozen=%s was_frozen=%s get_embeddings=%s, do_prime=%s' % ( len(validation_data), interval, model_path, config_path, frozen, was_frozen, get_embeddings, do_prime)) <NEW_LINE> self.interval = interval <NEW_LINE> self.X_val, self.y_val = validation_data <NEW_LINE> self.model_path = model_path <NEW_LINE> self.config_path = config_path <NEW_LINE> self.frozen = frozen <NEW_LINE> self.best_auc = 0.0 <NEW_LINE> self.best_epoch = -1 <NEW_LINE> self.top_weights = None <NEW_LINE> self.t0 = time.clock() <NEW_LINE> if do_prime: <NEW_LINE> <INDENT> model = load_model(model_path, config_path, was_frozen, get_embeddings) <NEW_LINE> y_pred = model.predict(self.X_val, verbose=0) <NEW_LINE> auc = roc_auc_score(self.y_val, y_pred) <NEW_LINE> xprint('\nROC-AUC - epoch: {:d} - score: {:.6f}'.format(0, auc)) <NEW_LINE> self.best_auc = auc <NEW_LINE> del model <NEW_LINE> <DEDENT> <DEDENT> def on_epoch_end(self, epoch, logs={}): <NEW_LINE> <INDENT> if epoch % self.interval == 0: <NEW_LINE> <INDENT> y_pred = self.model.predict(self.X_val, verbose=0) <NEW_LINE> auc = roc_auc_score(self.y_val, y_pred) <NEW_LINE> xprint('\nROC-AUC - epoch: {:d} - score: {:.6f}'.format(epoch + 1, auc)) <NEW_LINE> logs['val_auc'] = auc <NEW_LINE> dt = time.clock() - self.t0 <NEW_LINE> self.t0 = time.clock() <NEW_LINE> if auc >= self.best_auc + AUC_DELTA: <NEW_LINE> <INDENT> xprint('RocAucEvaluation.fit: auc=%.3f > best_auc=%.3f dt=%.1f sec' % (auc, self.best_auc, dt)) <NEW_LINE> self.best_auc = auc <NEW_LINE> self.best_epoch = epoch <NEW_LINE> weights = self.model.get_weights() <NEW_LINE> self.top_weights = weights[1:] <NEW_LINE> save_model(self.model, self.model_path, self.config_path, self.frozen) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xprint('RocAucEvaluation.fit: No improvement best_epoch=%d best_auc=%.3f dt=%.1f sec' % (self.best_epoch + 1, self.best_auc, dt))
ROC AUC for CV in Keras see for details: https://gist.github.com/smly/d29d079100f8d81b905e
62598faa851cf427c66b8240
class Card_infos(): <NEW_LINE> <INDENT> def __init__(self, name, family, description, type, effect, image_path): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.family = family <NEW_LINE> self.description = description <NEW_LINE> self.type = type <NEW_LINE> self.effect = effect <NEW_LINE> self.image_path = image_path <NEW_LINE> self.color = 0x000000ff <NEW_LINE> if (self.type == "creature"): <NEW_LINE> <INDENT> self.color = 0xffff0020 <NEW_LINE> <DEDENT> elif (self.type == "Magic"): <NEW_LINE> <INDENT> self.color = 0x0000ff20 <NEW_LINE> <DEDENT> elif (self.type == "trap"): <NEW_LINE> <INDENT> self.color = 0xff000020 <NEW_LINE> <DEDENT> elif (self.type == "action"): <NEW_LINE> <INDENT> self.color = 0x00ff0020
Standard of basic informations about a card.
62598faa85dfad0860cbfa36
class fio(test.test): <NEW_LINE> <INDENT> version = 3 <NEW_LINE> def initialize(self): <NEW_LINE> <INDENT> self.job.require_gcc() <NEW_LINE> <DEDENT> def setup(self, tarball='fio-2.99.tar.bz2'): <NEW_LINE> <INDENT> tarball = utils.unmap_url(self.bindir, tarball, self.tmpdir) <NEW_LINE> utils.extract_tarball_to_dir(tarball, self.srcdir) <NEW_LINE> self.job.setup_dep(['libaio']) <NEW_LINE> ldflags = '-L' + self.autodir + '/deps/libaio/lib' <NEW_LINE> cflags = '-I' + self.autodir + '/deps/libaio/include' <NEW_LINE> var_ldflags = 'LDFLAGS="' + ldflags + '"' <NEW_LINE> var_cflags = 'CFLAGS="' + cflags + '"' <NEW_LINE> os.chdir(self.srcdir) <NEW_LINE> utils.system('%s %s make' % (var_ldflags, var_cflags)) <NEW_LINE> <DEDENT> def run_once(self, opts=None, job=None, user='root'): <NEW_LINE> <INDENT> log = os.path.join(self.resultsdir, 'fio-mixed.log') <NEW_LINE> _opts = '--output %s ' % (log) <NEW_LINE> if opts: <NEW_LINE> <INDENT> _opts += opts <NEW_LINE> <DEDENT> arch = platform.machine() <NEW_LINE> if "ppc" in arch: <NEW_LINE> <INDENT> job_cfg_file = 'fio-mixed-ppc.job' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> job_cfg_file = 'fio-mixed.job' <NEW_LINE> <DEDENT> if job is None: <NEW_LINE> <INDENT> job = os.path.join(self.bindir, job_cfg_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not os.path.isabs(job): <NEW_LINE> <INDENT> job = os.path.join(self.bindir, job) <NEW_LINE> <DEDENT> <DEDENT> _opts += ' %s' % (job) <NEW_LINE> os.chdir(self.srcdir) <NEW_LINE> env_vars = 'LD_LIBRARY_PATH="' + self.autodir + '/deps/libaio/lib"' <NEW_LINE> utils.system(env_vars + ' ./fio ' + _opts)
fio is an I/O tool mean for benchmark and stress/hardware verification. @see: http://freecode.com/projects/fio
62598faa4428ac0f6e6584a8
class IsCreator(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, object): <NEW_LINE> <INDENT> return request.user.pk == object.creator.pk
Object-level permission fo only allow creators of an object to operate on it.
62598faa45492302aabfc455
class BDDDescriptor(object): <NEW_LINE> <INDENT> def __init__(self, wrapped): <NEW_LINE> <INDENT> self.wrapped = wrapped <NEW_LINE> <DEDENT> def __get__(self, instance, owner): <NEW_LINE> <INDENT> if not instance: <NEW_LINE> <INDENT> return self.__class__ <NEW_LINE> <DEDENT> self.instance = instance <NEW_LINE> self.owner = owner <NEW_LINE> update_wrapper(self, self.wrapped) <NEW_LINE> return self <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.wrapped.__get__(self.instance, self.owner)(*args, **kwargs) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__class__ == other.__class__ and self.wrapped == other.wrapped
base for @given, @when, @then, @should, and any other stages of testing
62598faa167d2b6e312b6ef5
class FileStorage(): <NEW_LINE> <INDENT> __file_path = "file.json" <NEW_LINE> __objects = {} <NEW_LINE> def all(self): <NEW_LINE> <INDENT> return (self.__objects) <NEW_LINE> <DEDENT> def new(self, obj): <NEW_LINE> <INDENT> if obj: <NEW_LINE> <INDENT> var_id = "{}.{}".format(type(obj).__name__, obj.id) <NEW_LINE> self.__objects[var_id] = obj <NEW_LINE> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> s_dict = {} <NEW_LINE> for var_id, var_obj in self.__objects.items(): <NEW_LINE> <INDENT> s_dict[var_id] = var_obj.to_dict() <NEW_LINE> <DEDENT> with open(self.__file_path, mode='w', encoding='utf-8') as f: <NEW_LINE> <INDENT> json.dump(s_dict, f) <NEW_LINE> <DEDENT> <DEDENT> def reload(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.__file_path, mode='r', encoding='utf-8') as f: <NEW_LINE> <INDENT> obj = json.load(f) <NEW_LINE> <DEDENT> for key, value in obj.items(): <NEW_LINE> <INDENT> name = models.ourclasses[value['__class__']](**value) <NEW_LINE> self.__objects[key] = name <NEW_LINE> <DEDENT> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> pass
FileStorage Class
62598faad268445f26639b45
class GeographicViewServiceStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.GetGeographicView = channel.unary_unary( '/google.ads.googleads.v2.services.GeographicViewService/GetGeographicView', request_serializer=google_dot_ads_dot_googleads__v2_dot_proto_dot_services_dot_geographic__view__service__pb2.GetGeographicViewRequest.SerializeToString, response_deserializer=google_dot_ads_dot_googleads__v2_dot_proto_dot_resources_dot_geographic__view__pb2.GeographicView.FromString, )
Proto file describing the GeographicViewService. Service to manage geographic views.
62598faa10dbd63aa1c70b37
class ServerError(ReppyException): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.status = kwargs.get('status') <NEW_LINE> if self.status is None and len(args) >= 2: <NEW_LINE> <INDENT> self.status = args[1] <NEW_LINE> <DEDENT> ReppyException.__init__(self, *args, **kwargs)
When the remote server returns an error
62598faa66673b3332c3034f
class RegressionConvergenceRate(GlobalConvergenceRate): <NEW_LINE> <INDENT> label = "{var}: p={slope:4.3f}, cor={rvalue:4.3f}" <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(RegressionConvergenceRate, self).__init__(*args, **kwargs) <NEW_LINE> self.fits = {} <NEW_LINE> for varname in self.norms.datasets[0].errors: <NEW_LINE> <INDENT> self.fits[varname] = scipy.stats.linregress( numpy.log(numpy.array(self.norms.study_parameters)), numpy.log(numpy.array([dataset.errors[varname] for dataset in self.norms.datasets])) ) <NEW_LINE> <DEDENT> <DEDENT> def plot_fit(self, var, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['label'] = kwargs.get('label', self.label) .format(var=var, slope=self.fits[var][0], intercept=self.fits[var][1], rvalue=self.fits[var][2], pvalue=self.fits[var][3], stderr=self.fits[var][4]) <NEW_LINE> plt.plot(self.norms.study_parameters, math.exp(self.fits[var][1]) * self.norms.study_parameters**self.fits[var][0], *args, **kwargs) <NEW_LINE> plt.legend() <NEW_LINE> <DEDENT> def p(self, var): <NEW_LINE> <INDENT> return self.fits[var][0] <NEW_LINE> <DEDENT> def goodness(self, var): <NEW_LINE> <INDENT> return self.fits[var][2] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> separator = 16*'='+" "+4*"=" <NEW_LINE> lines = [separator, "{:16s} {:4s}".format("Variable", "p"), separator] <NEW_LINE> lines.extend( ["{:16s} {:4.2g}".format(varname, self.fits[varname][0]) for varname in self.fits ]) <NEW_LINE> lines.append(separator) <NEW_LINE> return "\n".join(lines)
A class which performs a convergence analysis using linear regression. When initialized with a :class:`Study` instance, the :class:`RegressionConvergenceRate` performs a convergence analysis based on the error ansatz .. math:: \epsilon = A h^p by applying linear regression to the logarithm of the errors and deltas.
62598faa7d847024c075c348
class MultipleSession(Unauthorized): <NEW_LINE> <INDENT> pass
[401] Unauthorized (ut) - multiple session.
62598faa379a373c97d98f97
class TrayPower(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'tray_id': 'int', 'number_of_power_supplies': 'int', 'input_power': 'list[int]' } <NEW_LINE> self.attribute_map = { 'tray_id': 'trayID', 'number_of_power_supplies': 'numberOfPowerSupplies', 'input_power': 'inputPower' } <NEW_LINE> self._tray_id = None <NEW_LINE> self._number_of_power_supplies = None <NEW_LINE> self._input_power = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def tray_id(self): <NEW_LINE> <INDENT> return self._tray_id <NEW_LINE> <DEDENT> @tray_id.setter <NEW_LINE> def tray_id(self, tray_id): <NEW_LINE> <INDENT> self._tray_id = tray_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def number_of_power_supplies(self): <NEW_LINE> <INDENT> return self._number_of_power_supplies <NEW_LINE> <DEDENT> @number_of_power_supplies.setter <NEW_LINE> def number_of_power_supplies(self, number_of_power_supplies): <NEW_LINE> <INDENT> self._number_of_power_supplies = number_of_power_supplies <NEW_LINE> <DEDENT> @property <NEW_LINE> def input_power(self): <NEW_LINE> <INDENT> return self._input_power <NEW_LINE> <DEDENT> @input_power.setter <NEW_LINE> def input_power(self, input_power): <NEW_LINE> <INDENT> self._input_power = input_power <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if self is None or other is None: <NEW_LINE> <INDENT> return None <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.
62598faaaad79263cf42e758
class WeblinkCheckerRobot(SingleSiteBot, ExistingPageBot): <NEW_LINE> <INDENT> killing = False <NEW_LINE> def __init__(self, generator, HTTPignore=None, day=7, site=True): <NEW_LINE> <INDENT> super(WeblinkCheckerRobot, self).__init__( generator=generator, site=site) <NEW_LINE> if config.report_dead_links_on_talk: <NEW_LINE> <INDENT> pywikibot.log("Starting talk page thread") <NEW_LINE> reportThread = DeadLinkReportThread() <NEW_LINE> reportThread.start() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> reportThread = None <NEW_LINE> <DEDENT> self.history = History(reportThread, site=self.site) <NEW_LINE> if HTTPignore is None: <NEW_LINE> <INDENT> self.HTTPignore = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.HTTPignore = HTTPignore <NEW_LINE> <DEDENT> self.day = day <NEW_LINE> <DEDENT> def treat_page(self): <NEW_LINE> <INDENT> page = self.current_page <NEW_LINE> text = page.get() <NEW_LINE> """report page.title and time""" <NEW_LINE> try: <NEW_LINE> <INDENT> pywikibot.output(u'P:%s >>>%s' % (page.title(), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> for url in weblinksIn(text): <NEW_LINE> <INDENT> ignoreUrl = False <NEW_LINE> for ignoreR in ignorelist: <NEW_LINE> <INDENT> if ignoreR.match(url): <NEW_LINE> <INDENT> ignoreUrl = True <NEW_LINE> <DEDENT> <DEDENT> if not ignoreUrl: <NEW_LINE> <INDENT> pywikibot.output(u'STARTING thread #%i' % threading.activeCount()) <NEW_LINE> while threading.activeCount() >= config.max_external_links: <NEW_LINE> <INDENT> pywikibot.output(u'WAIT %s for thread #%i' % (config.retry_wait,threading.activeCount())) <NEW_LINE> time.sleep(config.retry_wait) <NEW_LINE> <DEDENT> thread = LinkCheckThread(page, url, self.history, self.HTTPignore, self.day) <NEW_LINE> thread.setDaemon(True) <NEW_LINE> try: <NEW_LINE> <INDENT> thread.start() <NEW_LINE> <DEDENT> except (threading.ThreadError,thread.error): <NEW_LINE> <INDENT> pywikibot.warning( "Can't start a new thread.\nPlease decrease " "max_external_links in your user-config.py or use\n" "'-max_external_links:' option with a smaller value. " "Default is 50.") <NEW_LINE> raise <NEW_LINE> <DEDENT> except request.data: <NEW_LINE> <INDENT> pywikibot.warning('*** NO DATA received') <NEW_LINE> pywikibot.output('*** NO DATA received') <NEW_LINE> raise <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> pywikibot.output(u'Finally: thread error...') <NEW_LINE> if not self.killing: <NEW_LINE> <INDENT> pywikibot.output(u'Saving history on thread error...') <NEW_LINE> self.killing = True <NEW_LINE> <DEDENT> return
Bot which will search for dead weblinks. It uses several LinkCheckThreads at once to process pages from generator.
62598faa236d856c2adc93ff
class MessageTypes(object): <NEW_LINE> <INDENT> RCON_AUTHENTICATE = 3 <NEW_LINE> RCON_AUTH_RESPONSE = 2 <NEW_LINE> RCON_EXEC_COMMAND = 2 <NEW_LINE> RCON_EXEC_RESPONSE = 0
Message types used by the RCON API. Only used when sending data at the moment, but could be used to verify the types of incoming data.
62598faa4e4d5625663723aa
class CustomUser(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> username = models.CharField(_('username'), max_length=254, unique=True) <NEW_LINE> email = models.EmailField(_('email field'), max_length=254) <NEW_LINE> first_name = models.CharField(_('first name'), max_length=30, blank=True) <NEW_LINE> last_name = models.CharField(_('last name'), max_length=30, blank=True) <NEW_LINE> is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) <NEW_LINE> is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) <NEW_LINE> date_joined = models.DateTimeField(_('date joined'), default=timezone.now) <NEW_LINE> last_visit = models.DateTimeField(_('last visit'), default=timezone.now) <NEW_LINE> type_choices = ( ('B', 'Beheerder'), ('SB', 'Syntrus Beheerder'), ('SOG', 'Syntrus Projectmanager'), ('SD', 'Syntrus Derden'), ) <NEW_LINE> type_user = models.CharField(max_length=3, choices=type_choices, default='SD') <NEW_LINE> belegger = models.ForeignKey(Belegger, on_delete=models.CASCADE, null=True) <NEW_LINE> organisatie = models.ForeignKey(Organisatie, on_delete=models.CASCADE, null=True) <NEW_LINE> objects = CustomUserManager() <NEW_LINE> USERNAME_FIELD = 'username' <NEW_LINE> REQUIRED_FIELDS = [] <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('user') <NEW_LINE> verbose_name_plural = _('users') <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return "/users/%s/" % urlquote(self.username) <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> full_name = '%s %s' % (self.first_name, self.last_name) <NEW_LINE> return full_name.strip() <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.first_name <NEW_LINE> <DEDENT> def email_user(self, subject, message, from_email=None): <NEW_LINE> <INDENT> send_mail(subject, message, from_email, [self.email])
A fully featured User model with admin-compliant permissions that uses a full-length email field as the username. Email and password are required. Other fields are optional.
62598faacc0a2c111447af95
class Group(object): <NEW_LINE> <INDENT> def __init__(self, name, alias=DEFAULT_CHANNEL_BACKEND, channel_backend=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> if channel_backend: <NEW_LINE> <INDENT> self.channel_backend = channel_backend <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.channel_backend = channel_backends[alias] <NEW_LINE> <DEDENT> <DEDENT> def add(self, channel): <NEW_LINE> <INDENT> if isinstance(channel, Channel): <NEW_LINE> <INDENT> channel = channel.name <NEW_LINE> <DEDENT> self.channel_backend.group_add(self.name, channel) <NEW_LINE> <DEDENT> def discard(self, channel): <NEW_LINE> <INDENT> if isinstance(channel, Channel): <NEW_LINE> <INDENT> channel = channel.name <NEW_LINE> <DEDENT> self.channel_backend.group_discard(self.name, channel) <NEW_LINE> <DEDENT> def channels(self): <NEW_LINE> <INDENT> return self.channel_backend.group_channels(self.name) <NEW_LINE> <DEDENT> def send(self, content): <NEW_LINE> <INDENT> if not isinstance(content, dict): <NEW_LINE> <INDENT> raise ValueError("You can only send dicts as content on channels.") <NEW_LINE> <DEDENT> self.channel_backend.send_group(self.name, content)
A group of channels that can be messaged at once, and that expire out of the group after an expiry time (keep re-adding to keep them in).
62598faae76e3b2f99fd89bb
class TestUpdateUserRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testUpdateUserRequest(self): <NEW_LINE> <INDENT> pass
UpdateUserRequest unit test stubs
62598faa4428ac0f6e6584a9
@parsleyfy <NEW_LINE> class MessageCreation(models.ModelForm): <NEW_LINE> <INDENT> model = Message <NEW_LINE> title = fields.CharField(min_length=1) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(MessageCreation, self).__init__(*args, **kwargs) <NEW_LINE> self.helper = FormHelper() <NEW_LINE> self.helper.form_class = 'form-horizontal hn-form messsage' <NEW_LINE> self.helper.form_method = 'POST' <NEW_LINE> self.helper.label_class = 'col-lg-8' <NEW_LINE> self.helper.field_class = 'col-lg-8' <NEW_LINE> self.helper.layout = Layout( Fieldset('New Message', Div( Div('receiver', css_class='col-lg-3'), css_class='row', ), Div( Div('title', css_class='message-row'), css_class='row', ), Div( Div('content', css_class='message-row'), css_class='row', ), ) ) <NEW_LINE> self.fields['title'].widget.attrs['size'] = 30 <NEW_LINE> self.fields['title'].widget.attrs['style'] = "" <NEW_LINE> self.fields['content'].widget.attrs['min-length'] = 0 <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Message <NEW_LINE> fields = 'receiver', 'content', 'title'
Name: MessageCreation Message Creation form based on the model Message
62598faacb5e8a47e493c13b
class RemoteFunctionCallError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, child_exception=None): <NEW_LINE> <INDENT> super().__init__(message) <NEW_LINE> if child_exception is not None: <NEW_LINE> <INDENT> if issubclass(child_exception.__class__, Exception): <NEW_LINE> <INDENT> from ._function import exception_to_safe_exception as _exception_to_safe_exception <NEW_LINE> self._child_exception = _exception_to_safe_exception( child_exception) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.args = ("%s : %s" % (message, str(child_exception)), ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def unpack_and_raise(self): <NEW_LINE> <INDENT> if self._child_exception is None: <NEW_LINE> <INDENT> raise self <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> import traceback as _traceback <NEW_LINE> tb_lines = _traceback.format_exception( self.__class__, self, self.__traceback__) <NEW_LINE> self._child_exception.args = ( "%s\n=== Local Traceback ===\n%s" % (self._child_exception.args[0], "".join(tb_lines)), ) <NEW_LINE> if isinstance(self._child_exception, RemoteFunctionCallError): <NEW_LINE> <INDENT> self._child_exception.unpack_and_raise() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise self._child_exception
This exception is called if there is a remote function call error that could not be auto-converted to anything else. If a child exception occurred remotely, then this is packaged safely into this exception
62598faa8e71fb1e983bba38
class Comparison(models.Model): <NEW_LINE> <INDENT> submission_a = models.ForeignKey(Submission, on_delete=models.CASCADE, related_name="+") <NEW_LINE> submission_b = models.ForeignKey(Submission, on_delete=models.CASCADE, related_name="+", blank=True, null=True) <NEW_LINE> similarity = models.FloatField(default=None, null=True, help_text="Similarity score resulting from the comparison of two submissions.") <NEW_LINE> matches_json = models.TextField(blank=True, null=True, default=None, help_text="JSON-serialized array of 3-element arrays, containing the index mappings and lengths of matches. E.g. [[i, j, n], ... ] where n is the match length, i starting index of the match in submission_a, and j in submission_b.") <NEW_LINE> review = models.IntegerField(choices=settings.REVIEW_CHOICES, default=0) <NEW_LINE> objects = ComparisonManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ("submission_a", "submission_b") <NEW_LINE> ordering = ["-similarity", ] <NEW_LINE> <DEDENT> @property <NEW_LINE> def review_options(self): <NEW_LINE> <INDENT> return settings.REVIEWS <NEW_LINE> <DEDENT> @property <NEW_LINE> def review_name(self): <NEW_LINE> <INDENT> return choice_name(settings.REVIEW_CHOICES, self.review) <NEW_LINE> <DEDENT> @property <NEW_LINE> def review_class(self): <NEW_LINE> <INDENT> return next((m["class"] for m in settings.REVIEWS if m["value"] == self.review), "unknown") <NEW_LINE> <DEDENT> def update_review(self, review): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = int(review) <NEW_LINE> if choice_name(settings.REVIEW_CHOICES, r) != "unknown": <NEW_LINE> <INDENT> self.review = r <NEW_LINE> self.save() <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> c = "template" if self.submission_b is None else "vs %s" % (self.submission_b.student.key) <NEW_LINE> return "%s/%s: %s %s similarity %.2f" % (self.submission_a.exercise.course.name, self.submission_a.exercise.name, self.submission_a.student.key, c, self.similarity)
Comparison of two submissions, with a resulting similarity score. When submission_b is null, the Comparison contains the result from comparison submission_a to an exercise template.
62598faa7047854f4633f35f