code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Stripped(Adapter): <NEW_LINE> <INDENT> def __init__(self, subcon, pad=None): <NEW_LINE> <INDENT> super(Stripped, self).__init__(subcon) <NEW_LINE> self.pad = pad <NEW_LINE> <DEDENT> def _decode(self, obj, context, path): <NEW_LINE> <INDENT> pad = self.pad <NEW_LINE> if pad is None: <NEW_LINE> <INDENT> pad = u'\0' if isinstance(obj, unicodestringtype) else b'\x00' <NEW_LINE> <DEDENT> if not isinstance(pad, type(obj)): <NEW_LINE> <INDENT> raise PaddingError("NullStripped pad must be of the same type: {} vs {}".format(type(pad), type(obj))) <NEW_LINE> <DEDENT> unit = len(pad) <NEW_LINE> if unit < 1: <NEW_LINE> <INDENT> raise PaddingError("NullStripped pad must be at least 1 byte") <NEW_LINE> <DEDENT> obj = obj <NEW_LINE> if unit == 1: <NEW_LINE> <INDENT> obj = obj.rstrip(pad) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tailunit = len(obj) % unit <NEW_LINE> end = len(obj) <NEW_LINE> if tailunit and obj[-tailunit:] == pad[:tailunit]: <NEW_LINE> <INDENT> end -= tailunit <NEW_LINE> <DEDENT> while end-unit >= 0 and obj[end-unit:end] == pad: <NEW_LINE> <INDENT> end -= unit <NEW_LINE> <DEDENT> obj = obj[:end] <NEW_LINE> <DEDENT> return obj <NEW_LINE> <DEDENT> def _encode(self, obj, context, path): <NEW_LINE> <INDENT> pad = self.pad <NEW_LINE> if pad is None: <NEW_LINE> <INDENT> pad = u'\0' if isinstance(self.subcon, StringEncoded) else b'\x00' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> size = self.subcon._sizeof(context, path) <NEW_LINE> <DEDENT> except SizeofError: <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> unit = len(pad) <NEW_LINE> if unit == 1: <NEW_LINE> <INDENT> obj = obj.ljust(size, pad) <NEW_LINE> <DEDENT> elif (size - len(obj)) % unit == 0: <NEW_LINE> <INDENT> obj = (obj + (pad * (size - len(obj))))[:size] <NEW_LINE> <DEDENT> return obj
An adapter that strips characters/bytes from the right of the parsed results. NOTE: While this may look similar to Padded() this is different because this doesn't take a length and instead strips out the nulls from within the already parsed subconstruct. :param subcon: The sub-construct to wrap. :param pad: The character/bytes to use for stripping. Defaults to null character. >>> Stripped(GreedyBytes).parse(b'hello\x00\x00\x00') 'hello' >>> Stripped(Bytes(10)).parse(b'hello\x00\x00\x00\x00\x00') 'hello' >>> Stripped(Bytes(14), pad=b'PAD').parse(b'helloPADPADPAD') 'hello' >>> Stripped(Bytes(14), pad=b'PAD').build(b'hello') 'helloPADPADPAD' >>> Stripped(CString(), pad=u'PAD').parse(b'helloPADPAD\x00') u'hello' >>> Stripped(String(14), pad=u'PAD').parse(b'helloPADPAD\x00\x00\x00') u'hello' # WARNING: If padding doesn't fit in the perscribed data it will not strip it! >>> Stripped(Bytes(13), pad=b'PAD').parse(b'helloPADPADPA') 'helloPADPADPA' >>> Stripped(Bytes(13), pad=b'PAD').build(b'hello') Traceback (most recent call last): ... StreamError: bytes object of wrong length, expected 13, found 5 # If the wrapped subconstruct's size can't be determine, if defaults to not providing a pad. >>> Stripped(CString(), pad=u'PAD').build(u'hello') 'hello\x00'
62598fbfdc8b845886d537ca
class EquipmentViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = Equipment.objects.all() <NEW_LINE> serializer_class = EquipmentSerializer <NEW_LINE> ordering_fields = '__all__' <NEW_LINE> filter_fields = ('name',)
API endpoint for equipment objects
62598fbff548e778e596b7b6
class UTC(datetime.tzinfo): <NEW_LINE> <INDENT> __getattribute__ = lambda self, attr: ( (lambda *_: self.__class__.__name__) if attr in ('tzname',) else (lambda *_: datetime.timedelta(0)))
UTC tzinfo object used in datetime as tzinfo keyword argument: (usage) datetime.datetime(1970, 1, 1, tzinfo=UTC()) ----- oneliner ----- # UTC = type( # 'UTC', # (datetime.tzinfo,), # {'utcoffset': lambda *_: datetime.timedelta(0)}) ----- (almost) proper OO ----- # utcoffset = lambda *args: datetime.timedelta(0) # tzname = lambda *args: "UTC" # dst = utcoffset
62598fbfe1aae11d1e7ce92d
class IPStrategysStatus(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TotalCount = None <NEW_LINE> self.StrategySet = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TotalCount = params.get("TotalCount") <NEW_LINE> if params.get("StrategySet") is not None: <NEW_LINE> <INDENT> self.StrategySet = [] <NEW_LINE> for item in params.get("StrategySet"): <NEW_LINE> <INDENT> obj = IPStrategy() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.StrategySet.append(obj) <NEW_LINE> <DEDENT> <DEDENT> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
策略列表
62598fbff548e778e596b7b7
class User(Model): <NEW_LINE> <INDENT> def __init__(self, username, email, manager): <NEW_LINE> <INDENT> super(User, self).__init__(manager) <NEW_LINE> self.username = username <NEW_LINE> self.email = email <NEW_LINE> <DEDENT> def sync(self): <NEW_LINE> <INDENT> self = self.manager.get(username=self.username) <NEW_LINE> return self <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.username
Base model for a user. Attributes: username (str): The user's username. email (str): The user's email. manager (:class:`saltant.models.user.UserManager`): The manager which spawned this user instance.
62598fbfcc40096d6161a2e1
class Expression18(Expression): <NEW_LINE> <INDENT> def get(self, instance): <NEW_LINE> <INDENT> raise NotImplementedError('%s not implemented' % ( str(self)))
System->BEEP music !->A# frequency Return type: Int
62598fbf7b180e01f3e49158
class IOSCfgLine(BaseCfgLine): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(IOSCfgLine, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def is_object_for(cls, line="", re=re): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_intf(self): <NEW_LINE> <INDENT> if self.text[0:10]=='interface ' and self.text[10]!=' ': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_subintf(self): <NEW_LINE> <INDENT> intf_regex = r'^interface\s+(\S+?\.\d+)' <NEW_LINE> if self.re_match(intf_regex): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> _VIRTUAL_INTF_REGEX_STR = r"""^interface\s+(Loopback|Tunnel|Dialer|Virtual-Template|Port-[Cc]hannel)""" <NEW_LINE> _VIRTUAL_INTF_REGEX = re.compile(_VIRTUAL_INTF_REGEX_STR) <NEW_LINE> @property <NEW_LINE> def is_virtual_intf(self): <NEW_LINE> <INDENT> if self.re_match(self._VIRTUAL_INTF_REGEX): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_loopback_intf(self): <NEW_LINE> <INDENT> intf_regex = r'^interface\s+(\Soopback)' <NEW_LINE> if self.re_match(intf_regex): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_ethernet_intf(self): <NEW_LINE> <INDENT> intf_regex = r'^interface\s+(.*?\Sthernet)' <NEW_LINE> if self.re_match(intf_regex): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
An object for a parsed IOS-style configuration line. :class:`~models_cisco.IOSCfgLine` objects contain references to other parent and child :class:`~models_cisco.IOSCfgLine` objects. .. note:: Originally, :class:`~models_cisco.IOSCfgLine` objects were only intended for advanced ciscoconfparse users. As of ciscoconfparse version 0.9.10, *all users* are strongly encouraged to prefer the methods directly on :class:`~models_cisco.IOSCfgLine` objects. Ultimately, if you write scripts which call methods on :class:`~models_cisco.IOSCfgLine` objects, your scripts will be much more efficient than if you stick strictly to the classic :class:`~ciscoconfparse.CiscoConfParse` methods. Args: - text (str): A string containing a text copy of the IOS configuration line. :class:`~ciscoconfparse.CiscoConfParse` will automatically identify the parent and children (if any) when it parses the configuration. - comment_delimiter (str): A string which is considered a comment for the configuration format. Since this is for Cisco IOS-style configurations, it defaults to ``!``. Attributes: - text (str): A string containing the parsed IOS configuration statement - linenum (int): The line number of this configuration statement in the original config; default is -1 when first initialized. - parent (:class:`~models_cisco.IOSCfgLine()`): The parent of this object; defaults to ``self``. - children (list): A list of ``IOSCfgLine()`` objects which are children of this object. - child_indent (int): An integer with the indentation of this object's children - indent (int): An integer with the indentation of this object's ``text`` oldest_ancestor (bool): A boolean indicating whether this is the oldest ancestor in a family - is_comment (bool): A boolean indicating whether this is a comment Returns: - An instance of :class:`~models_cisco.IOSCfgLine`.
62598fbf442bda511e95c66f
class AdvertiserCreationForm(forms.ModelForm): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.user_profile = kwargs.pop("user_profile", None) <NEW_LINE> super().__init__(*args, **kwargs) <NEW_LINE> self.helper = FormHelper(self) <NEW_LINE> self.helper.layout = Layout() <NEW_LINE> for field_name, field in list(self.fields.items()): <NEW_LINE> <INDENT> self.helper.layout.append( Div( Field( field_name, placeholder=field.label, css_class="form-control", ), css_class="form-group mb-3", ) ) <NEW_LINE> <DEDENT> self.helper.form_show_labels = False <NEW_LINE> self.helper.form_tag = False <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = Advertiser <NEW_LINE> fields = [ "email", "stripe_id", ] <NEW_LINE> <DEDENT> def save(self, commit=True): <NEW_LINE> <INDENT> instance = super().save(commit=False) <NEW_LINE> instance.user_profile = self.user_profile <NEW_LINE> instance.stripe_id = self.stripe_id <NEW_LINE> if commit: <NEW_LINE> <INDENT> instance.save() <NEW_LINE> <DEDENT> return instance
A form that creates an advertiser with credit card info
62598fbf76e4537e8c3ef7b7
class AtariVisionModel(TFSeparableModel): <NEW_LINE> <INDENT> def __init__(self, k, statedim=(42,42,1), actiondim=(18,1)): <NEW_LINE> <INDENT> super(AtariVisionModel, self).__init__(statedim, actiondim, k, [0,1],'chain') <NEW_LINE> <DEDENT> def createPolicyNetwork(self): <NEW_LINE> <INDENT> return conv2a3c(self.statedim, self.actiondim[0]) <NEW_LINE> <DEDENT> def createTransitionNetwork(self): <NEW_LINE> <INDENT> return conv2a3c(self.statedim, 2)
This class defines the abstract class for a tensorflow model for the primitives.
62598fbf283ffb24f3cf3a94
class ChoicesContractor(object): <NEW_LINE> <INDENT> def __iter__(self): <NEW_LINE> <INDENT> from project.models import Contractor <NEW_LINE> for i in Contractor.query.order_by(Contractor.name.asc()).all(): <NEW_LINE> <INDENT> yield (i.id, i.name)
this method ensure a dynamic choice_list for selectField
62598fbf23849d37ff8512c5
class AvroResponder(Responder): <NEW_LINE> <INDENT> def __init__(self, protocol, impl=None): <NEW_LINE> <INDENT> super().__init__(local_protocol=protocol) <NEW_LINE> self._impl = impl or self <NEW_LINE> <DEDENT> def invoke(self, message, request, context=None): <NEW_LINE> <INDENT> logging.debug("Processing message %r (%s) with request %r", message.name, message, request) <NEW_LINE> try: <NEW_LINE> <INDENT> message_handler = getattr(self._impl, message.name) <NEW_LINE> return message_handler( context=context, request=request, ) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logging.error("Error processing message %r:\n%s", message.name, traceback.format_exc()) <NEW_LINE> raise
Generic Avro responder that delegates to an implementation using reflection.
62598fbf099cdd3c636754eb
class MessageViewTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.client = app.test_client() <NEW_LINE> self.testuser = User.signup(username="testuser", email="test@test.com", password="testuser", image_url=None) <NEW_LINE> db.session.commit() <NEW_LINE> self.new_message = Message( text="Hello I am a message.", user_id=self.testuser.id) <NEW_LINE> db.session.add(self.new_message) <NEW_LINE> db.session.commit() <NEW_LINE> self.new_message_id = self.new_message.id <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> db.session.rollback() <NEW_LINE> User.query.delete() <NEW_LINE> Message.query.delete() <NEW_LINE> <DEDENT> def test_add_message(self): <NEW_LINE> <INDENT> with self.client as c: <NEW_LINE> <INDENT> with c.session_transaction() as sess: <NEW_LINE> <INDENT> sess[CURR_USER_KEY] = self.testuser.id <NEW_LINE> <DEDENT> resp = c.post("/messages/new", data={"text": "Hello"}) <NEW_LINE> self.assertEqual(resp.status_code, 302) <NEW_LINE> msg = Message.query.order_by(Message.id.desc()).first() <NEW_LINE> self.assertEqual(len(User.query.one().messages), 2) <NEW_LINE> self.assertEqual(msg.text, "Hello") <NEW_LINE> <DEDENT> <DEDENT> def test_add_message_view_restricted(self): <NEW_LINE> <INDENT> with self.client as c: <NEW_LINE> <INDENT> resp = c.post('/messages/new') <NEW_LINE> self.assertEqual(resp.status_code, 302) <NEW_LINE> <DEDENT> <DEDENT> def test_show_message(self): <NEW_LINE> <INDENT> with self.client as c: <NEW_LINE> <INDENT> with c.session_transaction() as sess: <NEW_LINE> <INDENT> sess[CURR_USER_KEY] = self.testuser.id <NEW_LINE> <DEDENT> with c.session_transaction() as sess: <NEW_LINE> <INDENT> del sess[CURR_USER_KEY] <NEW_LINE> <DEDENT> resp = c.get(f'/messages/{self.new_message_id}') <NEW_LINE> self.assertEqual(resp.status_code, 200) <NEW_LINE> html = resp.get_data(as_text=True) <NEW_LINE> self.assertIn("Hello I am a message.", html) <NEW_LINE> <DEDENT> <DEDENT> def test_delete_message(self): <NEW_LINE> <INDENT> with self.client as c: <NEW_LINE> <INDENT> with c.session_transaction() as sess: <NEW_LINE> <INDENT> sess[CURR_USER_KEY] = self.testuser.id <NEW_LINE> <DEDENT> resp = c.post(f'/messages/{self.new_message_id}/delete') <NEW_LINE> self.assertEqual(resp.status_code, 302) <NEW_LINE> msgs = Message.query.all() <NEW_LINE> self.assertEqual(len(msgs), 0)
Test views for messages.
62598fbfec188e330fdf8aa4
class ReadGroupProgram(_messages.Message): <NEW_LINE> <INDENT> commandLine = _messages.StringField(1) <NEW_LINE> id = _messages.StringField(2) <NEW_LINE> name = _messages.StringField(3) <NEW_LINE> prevProgramId = _messages.StringField(4) <NEW_LINE> version = _messages.StringField(5)
A ReadGroupProgram object. Fields: commandLine: The command line used to run this program. id: The user specified locally unique ID of the program. Used along with prevProgramId to define an ordering between programs. name: The name of the program. prevProgramId: The ID of the program run before this one. version: The version of the program run.
62598fbf3d592f4c4edbb0ce
class VideoSearchForm(forms.Form): <NEW_LINE> <INDENT> exclude_fields = ( 'approved', 'active_broadcast', 'video_url', 'description', 'handout', 'presentation', ) <NEW_LINE> test_equal = set(( 'video_type', 'subject', )) <NEW_LINE> field_order_priority = ( 'name', ) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(VideoSearchForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields.update(dict( (field_name, form_field) for field_name, form_field in fields_for_model(Video).iteritems() if field_name not in self.exclude_fields)) <NEW_LINE> for name, field in self.fields.iteritems(): <NEW_LINE> <INDENT> field.required = False <NEW_LINE> <DEDENT> self._set_field_ordering() <NEW_LINE> <DEDENT> def _set_field_ordering(self): <NEW_LINE> <INDENT> for field in reversed(self.field_order_priority): <NEW_LINE> <INDENT> self.fields.keyOrder.remove(field) <NEW_LINE> self.fields.keyOrder.insert(0, field) <NEW_LINE> <DEDENT> <DEDENT> def get_query_set(self): <NEW_LINE> <INDENT> qs = Video.objects.all() <NEW_LINE> for name, data in self.cleaned_data.iteritems(): <NEW_LINE> <INDENT> if name == 'q': continue <NEW_LINE> if name in self.test_equal: <NEW_LINE> <INDENT> if data: <NEW_LINE> <INDENT> qs = qs.filter(**{name: data}) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for part in data.split(): <NEW_LINE> <INDENT> qs = qs.filter(**{name + '__icontains': part}) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return qs
A form class which allows the user to get search results based on form fields for a particular model. It is also possible to add extra fields for custom processing. Following the YAGNI prinicple, it is only implemented for the Video model, instead of being an overly generic solution for all models. If the need for a different search appears, it can be refactored to have a greater level of abstraction.
62598fbf3d592f4c4edbb0cf
class Sequence(object): <NEW_LINE> <INDENT> _revcomp_trans = string.maketrans('acgt', 'tgca') <NEW_LINE> def __init__(self, seq): <NEW_LINE> <INDENT> self.seq = seq.lower() <NEW_LINE> if not re.match(r'^[acgtn]*$', self.seq): <NEW_LINE> <INDENT> raise ValueError('illegal characters in sequence, ' 'currently only supports DNA sequences') <NEW_LINE> <DEDENT> <DEDENT> def revcomp(self): <NEW_LINE> <INDENT> return Sequence(self.seq.translate(Sequence._revcomp_trans)[::-1]) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return Sequence(self.seq[key]) <NEW_LINE> <DEDENT> def __eq__(self, seq2): <NEW_LINE> <INDENT> if isinstance(seq2, basestring): <NEW_LINE> <INDENT> return self.seq == seq2 <NEW_LINE> <DEDENT> return self.seq == seq2.seq <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.seq) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.seq <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Sequence: {0}...>'.format(self.seq[:5])
Represent a DNA sequence. :param seq: a string representing a DNA sequence. Bases A, C, G, T and N are allowed. :raises: ValuError if the sequence contains illegal characters.
62598fbfd486a94d0ba2c1e2
class Pip(): <NEW_LINE> <INDENT> def __init__(self, node0, node1, directional): <NEW_LINE> <INDENT> self.node0 = node0 <NEW_LINE> self.node1 = node1 <NEW_LINE> self.directional = directional <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Pip({}, {}, {})".format( repr(self.node0), repr(self.node1), repr(self.directional)) <NEW_LINE> <DEDENT> def site_wires(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def nodes(self): <NEW_LINE> <INDENT> return [self.node0, self.node1] <NEW_LINE> <DEDENT> def is_connected(self, other_object): <NEW_LINE> <INDENT> if other_object.is_node_connected(self.node0): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return other_object.is_node_connected(self.node1) <NEW_LINE> <DEDENT> <DEDENT> def is_site_pin_for(self, site, bel_pin_index): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def can_connect_via_site_wire(self, other_site_index, other_site_wire_index, other_direction): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def is_bel_pin(self, site, bel_pin_index): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def is_node_connected(self, node): <NEW_LINE> <INDENT> return node in [self.node0, self.node1] <NEW_LINE> <DEDENT> def is_root(self): <NEW_LINE> <INDENT> return False
Pip device resource object.
62598fbf4f88993c371f0612
class RandomAgent(Agent): <NEW_LINE> <INDENT> def __init__( self, states_spec, actions_spec, device=None, session_config=None, scope='random', saver_spec=None, summary_spec=None, distributed_spec=None, discount=0.99, variable_noise=None, states_preprocessing_spec=None, explorations_spec=None, reward_preprocessing_spec=None, batched_observe=1000 ): <NEW_LINE> <INDENT> self.optimizer = None <NEW_LINE> self.device = device <NEW_LINE> self.session_config = session_config <NEW_LINE> self.scope = scope <NEW_LINE> self.saver_spec = saver_spec <NEW_LINE> self.summary_spec = summary_spec <NEW_LINE> self.distributed_spec = distributed_spec <NEW_LINE> self.discount = discount <NEW_LINE> self.variable_noise = variable_noise <NEW_LINE> self.states_preprocessing_spec = states_preprocessing_spec <NEW_LINE> self.explorations_spec = explorations_spec <NEW_LINE> self.reward_preprocessing_spec = reward_preprocessing_spec <NEW_LINE> super(RandomAgent, self).__init__( states_spec=states_spec, actions_spec=actions_spec, batched_observe=batched_observe ) <NEW_LINE> <DEDENT> def initialize_model(self): <NEW_LINE> <INDENT> return RandomModel( states_spec=self.states_spec, actions_spec=self.actions_spec, device=self.device, session_config=self.session_config, scope=self.scope, saver_spec=self.saver_spec, summary_spec=self.summary_spec, distributed_spec=self.distributed_spec, optimizer=self.optimizer, discount=self.discount, variable_noise=self.variable_noise, states_preprocessing_spec=self.states_preprocessing_spec, explorations_spec=self.explorations_spec, reward_preprocessing_spec=self.reward_preprocessing_spec )
Random agent, useful as a baseline and sanity check.
62598fbf4527f215b58ea0e0
class User(TwitterModel): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.param_defaults = { 'contributors_enabled': None, 'created_at': None, 'default_profile': None, 'default_profile_image': None, 'description': None, 'email': None, 'favourites_count': None, 'followers_count': None, 'following': None, 'friends_count': None, 'geo_enabled': None, 'id': None, 'lang': None, 'listed_count': None, 'location': None, 'name': None, 'notifications': None, 'profile_background_color': None, 'profile_background_image_url': None, 'profile_background_tile': None, 'profile_banner_url': None, 'profile_image_url': None, 'profile_link_color': None, 'profile_sidebar_fill_color': None, 'profile_text_color': None, 'protected': None, 'screen_name': None, 'status': None, 'statuses_count': None, 'time_zone': None, 'url': None, 'utc_offset': None, 'verified': None, } <NEW_LINE> for (param, default) in self.param_defaults.items(): <NEW_LINE> <INDENT> setattr(self, param, kwargs.get(param, default)) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "User(ID={uid}, ScreenName={sn})".format( uid=self.id, sn=self.screen_name) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def NewFromJsonDict(cls, data, **kwargs): <NEW_LINE> <INDENT> if data.get('status', None): <NEW_LINE> <INDENT> status = Status.NewFromJsonDict(data.get('status')) <NEW_LINE> return super(cls, cls).NewFromJsonDict(data=data, status=status) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(cls, cls).NewFromJsonDict(data=data)
A class representing the User structure.
62598fbfd268445f26639c8d
class UserStyleSheet(File): <NEW_LINE> <INDENT> typestr = 'user-stylesheet' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__(none_ok=True) <NEW_LINE> <DEDENT> def transform(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> path = super().transform(value) <NEW_LINE> if os.path.exists(path): <NEW_LINE> <INDENT> return QUrl.fromLocalFile(path) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = base64.b64encode(value.encode('utf-8')).decode('ascii') <NEW_LINE> return QUrl("data:text/css;charset=utf-8;base64,{}".format(data)) <NEW_LINE> <DEDENT> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> if self._none_ok: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise configexc.ValidationError(value, "may not be empty!") <NEW_LINE> <DEDENT> <DEDENT> value = os.path.expandvars(value) <NEW_LINE> value = os.path.expanduser(value) <NEW_LINE> try: <NEW_LINE> <INDENT> super().validate(value) <NEW_LINE> <DEDENT> except configexc.ValidationError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not os.path.isabs(value): <NEW_LINE> <INDENT> value.encode('utf-8') <NEW_LINE> <DEDENT> <DEDENT> except UnicodeEncodeError as e: <NEW_LINE> <INDENT> raise configexc.ValidationError(value, str(e))
QWebSettings UserStyleSheet.
62598fbff548e778e596b7b9
class Color(models.Model): <NEW_LINE> <INDENT> html = models.CharField(max_length = 7, unique = True) <NEW_LINE> hex = models.CharField(max_length = 8, unique = True) <NEW_LINE> rgb_r = models.IntegerField() <NEW_LINE> rgb_g = models.IntegerField() <NEW_LINE> rgb_b = models.IntegerField() <NEW_LINE> l = models.FloatField() <NEW_LINE> a = models.FloatField() <NEW_LINE> b = models.FloatField() <NEW_LINE> objects = GetOrNoneManager() <NEW_LINE> @classmethod <NEW_LINE> def create(cls, color): <NEW_LINE> <INDENT> crgb = cu._2rgb(color) <NEW_LINE> chtml = cu.rgb2html(crgb) <NEW_LINE> R, G, B = crgb <NEW_LINE> chex = cu.rgb2hex(crgb) <NEW_LINE> l, a, b = (cu._2lab(crgb)).get_value_tuple() <NEW_LINE> return cls(html = chtml, hex = chex, rgb_r = R, rgb_g = G, rgb_b = B, l = l, a = a, b = b) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.html <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> unique_together = ('rgb_r', 'rgb_g', 'rgb_b')
Color representations. **Fields:** | html (CharField): html style color definition | hex (CharField): hex style color definition | rgb_r (IntegerField): red value of the rgb-color space | rgb_g (IntegerField): green value of the rgb-color space | rgb_b (IntegerField): blue value of the rgb-color space | l (FloatField): lightness value of the Lab-color space | a (FloatField): a color-opponent value of the Lab-color space | b (FloatField): b color-opponent value of the Lab-color space
62598fbfad47b63b2c5a7a68
class CreateTable: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Connect_DB(): <NEW_LINE> <INDENT> con = sqlite3.connect("mydatabase.db") <NEW_LINE> return con <NEW_LINE> <DEDENT> def create_table(self): <NEW_LINE> <INDENT> cursor_obj = CreateTable.Connect_DB().cursor() <NEW_LINE> cursor_obj.execute("CREATE TABLE PDBs(id INTEGER PRIMARY KEY,pdb_name text, protein_name text, species text, hi_resolution float, Rwork float, Rfree float, space_group text, sequence text)") <NEW_LINE> CreateTable.Connect_DB().commit()
Constructing database tables. This should only be run at the beginning of a project.
62598fbf4f6381625f1995cb
class QMultiInputDialog(QDialog): <NEW_LINE> <INDENT> def __init__(self, parent=None, title=None, text=None, fields=[''], values={}, f=0): <NEW_LINE> <INDENT> super().__init__(parent, f) <NEW_LINE> self.setWindowTitle(title) <NEW_LINE> layout = QVBoxLayout(self) <NEW_LINE> layout.addWidget(QLabel(text)) <NEW_LINE> inputGrid = QGridLayout() <NEW_LINE> layout.addLayout(inputGrid) <NEW_LINE> self.inputs = {f: QLineEdit(self) for f in fields} <NEW_LINE> for idx, field in enumerate(fields): <NEW_LINE> <INDENT> if field in values: <NEW_LINE> <INDENT> self.inputs[field].setText(values[field]) <NEW_LINE> self.inputs[field].setEnabled(False) <NEW_LINE> <DEDENT> inputGrid.addWidget(QLabel(field), idx, 0) <NEW_LINE> inputGrid.addWidget(self.inputs[field], idx, 1) <NEW_LINE> <DEDENT> buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) <NEW_LINE> buttons.accepted.connect(self.accept) <NEW_LINE> buttons.rejected.connect(self.reject) <NEW_LINE> layout.addWidget(buttons) <NEW_LINE> <DEDENT> def getValues(self): <NEW_LINE> <INDENT> return {key: line.text() for key, line in self.inputs.items()} <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getInputs(parent=None, title=None, text=None, fields=[], values={}, f=0): <NEW_LINE> <INDENT> dialog = QMultiInputDialog(parent, title, text, fields, values, f) <NEW_LINE> result = dialog.exec_() <NEW_LINE> values = dialog.getValues() <NEW_LINE> return (values, result == QDialog.Accepted)
Get several inputs in one dialog.
62598fbf63b5f9789fe85384
class Ui: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def renderBaseMenuOptions(self, discard = "X"): <NEW_LINE> <INDENT> if discard != "B" and discard != "b": <NEW_LINE> <INDENT> print("\t(B)inario") <NEW_LINE> <DEDENT> if discard != "O" and discard != "o": <NEW_LINE> <INDENT> print("\t(O)ctal") <NEW_LINE> <DEDENT> if discard != "D" and discard != "d": <NEW_LINE> <INDENT> print("\t(D)ecimal") <NEW_LINE> <DEDENT> if discard != "H" and discard != "h": <NEW_LINE> <INDENT> print("\t(H)exadecimal") <NEW_LINE> <DEDENT> print("\t-------------") <NEW_LINE> if discard != "X": <NEW_LINE> <INDENT> print("\t(R)egresar") <NEW_LINE> <DEDENT> print("\t(S)alir\n") <NEW_LINE> opt = getChar() <NEW_LINE> if opt == "S" or opt == "s": <NEW_LINE> <INDENT> exit() <NEW_LINE> <DEDENT> if opt == "R" or opt == "r": <NEW_LINE> <INDENT> main() <NEW_LINE> <DEDENT> return opt <NEW_LINE> <DEDENT> def renderBaseMenu(self): <NEW_LINE> <INDENT> clear() <NEW_LINE> print("BaseConverter es una herramienta para convertir números entre distintas bases de sistemas numéricos." + "\n\nSeleccione el sistema numérico base del número que desea convertir (origen): \n") <NEW_LINE> origin = self.renderBaseMenuOptions() <NEW_LINE> print("\n\nSeleccione la base del sistema numérico al que desea convertir el número (destino): \n") <NEW_LINE> destination = self.renderBaseMenuOptions(origin) <NEW_LINE> number = input("\n\tIngrese el número a cambiar de base: ") <NEW_LINE> return {'origin': origin, 'destination': destination, 'number': number}
Capa de Interfaz
62598fbf7047854f4633f5e7
class JoinPieceTextOutputProcessor(OutputProcessor, Serializable): <NEW_LINE> <INDENT> yaml_tag = "!JoinPieceTextOutputProcessor" <NEW_LINE> @serializable_init <NEW_LINE> def __init__(self, space_token: str = "\u2581") -> None: <NEW_LINE> <INDENT> self.space_token = space_token <NEW_LINE> <DEDENT> def process(self, s: str) -> str: <NEW_LINE> <INDENT> return s.replace(" ", "").replace(self.space_token, " ").strip()
Assumes a sentence-piece vocabulary and joins them to form words. Space_token could be the starting character of a piece per default, the u'▁' indicates spaces
62598fbf283ffb24f3cf3a96
class TestBase(unittest.TestCase): <NEW_LINE> <INDENT> def test_base_parameters(self): <NEW_LINE> <INDENT> b = Base(1) <NEW_LINE> self.assertIsNotNone(id(b)) <NEW_LINE> <DEDENT> def test_instance(self): <NEW_LINE> <INDENT> b = Base(10) <NEW_LINE> self.assertIsInstance(b, Base) <NEW_LINE> <DEDENT> def test_to_json_string(self): <NEW_LINE> <INDENT> b = Base(32) <NEW_LINE> self.assertEqual(b.to_json_string([]), '[]') <NEW_LINE> self.assertEqual(b.to_json_string(None), '[]') <NEW_LINE> dict = {'x': 1, 'y': 9, 'id': 1, 'height': 2, 'width': 10} <NEW_LINE> d2 = b.to_json_string(dict) <NEW_LINE> self.assertTrue(type(d2) is str) <NEW_LINE> self.assertTrue(len(d2) > 0) <NEW_LINE> <DEDENT> def test_from_json(self): <NEW_LINE> <INDENT> b = Base(50) <NEW_LINE> self.assertEqual(b.from_json_string('[]'), []) <NEW_LINE> self.assertEqual(b.from_json_string(None), [])
Tests for base
62598fbf7c178a314d78d6b2
class Field(dict): <NEW_LINE> <INDENT> def __init__(self, name, type, size, default, desc, start_pos): <NEW_LINE> <INDENT> logging.debug("Creating field") <NEW_LINE> self["name"] = name <NEW_LINE> self["type"] = type <NEW_LINE> self["size"] = size <NEW_LINE> self["start"] = start_pos <NEW_LINE> self["end"] = start_pos + size - 1 <NEW_LINE> self["default"] = default <NEW_LINE> self["desc"] = desc
Common base class for all rtlog fields
62598fbfec188e330fdf8aa6
class CRPixelPrinter(object): <NEW_LINE> <INDENT> def __init__(self, val): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> <DEDENT> def to_string(self): <NEW_LINE> <INDENT> return "{id=%d (%d, %d)}" % (self.val["id"], self.val["col"], self.val["row"])
Print a CRPixel
62598fbf5fcc89381b266256
class FabricV1Network(FabricNetwork): <NEW_LINE> <INDENT> def __init__(self, name, network_id, network_type): <NEW_LINE> <INDENT> super(FabricV1Network, self).__init__(name, network_id, network_type) <NEW_LINE> <DEDENT> def set_config(self): <NEW_LINE> <INDENT> self.config = FabricV1NetworkConfig()
FabricV1Network represents a Hyperledger Fabric v1.0 network.
62598fbf92d797404e388c6c
class Moneda(models.Model): <NEW_LINE> <INDENT> moneda = models.CharField(max_length=5, unique=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.moneda <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "Moneda" <NEW_LINE> verbose_name_plural = "Monedas"
docstring for Moneda
62598fbf9f28863672818985
class GroupMembership(BaseObject): <NEW_LINE> <INDENT> def __init__(self, api=None, created_at=None, default=None, group_id=None, id=None, updated_at=None, url=None, user_id=None, **kwargs): <NEW_LINE> <INDENT> self.api = api <NEW_LINE> self.created_at = created_at <NEW_LINE> self.default = default <NEW_LINE> self.group_id = group_id <NEW_LINE> self.id = id <NEW_LINE> self.updated_at = updated_at <NEW_LINE> self.url = url <NEW_LINE> self.user_id = user_id <NEW_LINE> for key, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> for key in self.to_dict(): <NEW_LINE> <INDENT> if getattr(self, key) is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._dirty_attributes.remove(key) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def created(self): <NEW_LINE> <INDENT> if self.created_at: <NEW_LINE> <INDENT> return dateutil.parser.parse(self.created_at) <NEW_LINE> <DEDENT> <DEDENT> @created.setter <NEW_LINE> def created(self, created): <NEW_LINE> <INDENT> if created: <NEW_LINE> <INDENT> self.created_at = created <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def group(self): <NEW_LINE> <INDENT> if self.api and self.group_id: <NEW_LINE> <INDENT> return self.api._get_group(self.group_id) <NEW_LINE> <DEDENT> <DEDENT> @group.setter <NEW_LINE> def group(self, group): <NEW_LINE> <INDENT> if group: <NEW_LINE> <INDENT> self.group_id = group.id <NEW_LINE> self._group = group <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def updated(self): <NEW_LINE> <INDENT> if self.updated_at: <NEW_LINE> <INDENT> return dateutil.parser.parse(self.updated_at) <NEW_LINE> <DEDENT> <DEDENT> @updated.setter <NEW_LINE> def updated(self, updated): <NEW_LINE> <INDENT> if updated: <NEW_LINE> <INDENT> self.updated_at = updated <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def user(self): <NEW_LINE> <INDENT> if self.api and self.user_id: <NEW_LINE> <INDENT> return self.api._get_user(self.user_id) <NEW_LINE> <DEDENT> <DEDENT> @user.setter <NEW_LINE> def user(self, user): <NEW_LINE> <INDENT> if user: <NEW_LINE> <INDENT> self.user_id = user.id <NEW_LINE> self._user = user
###################################################################### # Do not modify, this class is autogenerated by gen_classes.py # ######################################################################
62598fbf8a349b6b43686451
class TestResults(object): <NEW_LINE> <INDENT> def __init__(self, session_context, cluster): <NEW_LINE> <INDENT> self._results = [] <NEW_LINE> self.session_context = session_context <NEW_LINE> self.cluster = cluster <NEW_LINE> self.start_time = -1 <NEW_LINE> self.stop_time = -1 <NEW_LINE> <DEDENT> def append(self, obj): <NEW_LINE> <INDENT> return self._results.append(obj) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._results) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self._results) <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_passed(self): <NEW_LINE> <INDENT> return len([r for r in self._results if r.test_status == PASS]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_failed(self): <NEW_LINE> <INDENT> return len([r for r in self._results if r.test_status == FAIL]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_ignored(self): <NEW_LINE> <INDENT> return len([r for r in self._results if r.test_status == IGNORE]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def run_time_seconds(self): <NEW_LINE> <INDENT> if self.start_time < 0: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if self.stop_time < 0: <NEW_LINE> <INDENT> self.stop_time = time.time() <NEW_LINE> <DEDENT> return self.stop_time - self.start_time <NEW_LINE> <DEDENT> def get_aggregate_success(self): <NEW_LINE> <INDENT> for result in self._results: <NEW_LINE> <INDENT> if result.test_status == FAIL: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def _stats(self, num_list): <NEW_LINE> <INDENT> if len(num_list) == 0: <NEW_LINE> <INDENT> return { "mean": None, "min": None, "max": None } <NEW_LINE> <DEDENT> return { "mean": sum(num_list) / float(len(num_list)), "min": min(num_list), "max": max(num_list) } <NEW_LINE> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> if self.run_time_seconds == 0 or len(self.cluster) == 0: <NEW_LINE> <INDENT> cluster_utilization = 0 <NEW_LINE> parallelism = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cluster_utilization = (1.0 / len(self.cluster)) * (1.0 / self.run_time_seconds) * sum([r.nodes_used * r.run_time_seconds for r in self]) <NEW_LINE> parallelism = sum([r.run_time_seconds for r in self._results]) / self.run_time_seconds <NEW_LINE> <DEDENT> return { "ducktape_version": ducktape_version(), "session_context": self.session_context, "run_time_seconds": self.run_time_seconds, "start_time": self.start_time, "stop_time": self.stop_time, "run_time_statistics": self._stats([r.run_time_seconds for r in self]), "cluster_nodes_used": self._stats([r.nodes_used for r in self]), "cluster_nodes_allocated": self._stats([r.nodes_allocated for r in self]), "cluster_utilization": cluster_utilization, "cluster_num_nodes": len(self.cluster), "num_passed": self.num_passed, "num_failed": self.num_failed, "num_ignored": self.num_ignored, "parallelism": parallelism, "results": [r for r in self._results] }
Class used to aggregate individual TestResult objects from many tests.
62598fbf0fa83653e46f50f9
class MainMenu(tk.Menu): <NEW_LINE> <INDENT> def __init__(self, root, *args, **kwargs): <NEW_LINE> <INDENT> tk.Menu.__init__(self, root, *args, **kwargs) <NEW_LINE> file_menu = FileMenu(self, tearoff= 0) <NEW_LINE> self.add_cascade(label="File", menu=file_menu) <NEW_LINE> root.config(menu=self)
Creates Main Menu.
62598fbf7c178a314d78d6b4
class ExplorationCompleteEventHandler(base.BaseHandler): <NEW_LINE> <INDENT> REQUIRE_PAYLOAD_CSRF_CHECK = False <NEW_LINE> @require_playable <NEW_LINE> def post(self, exploration_id): <NEW_LINE> <INDENT> event_services.CompleteExplorationEventHandler.record( exploration_id, self.payload.get('version'), self.payload.get('state_name'), self.payload.get('session_id'), self.payload.get('client_time_spent_in_secs'), self.payload.get('params'), feconf.PLAY_TYPE_NORMAL)
Tracks a learner completing an exploration. The state name recorded should be a state with a terminal interaction.
62598fbf7cff6e4e811b5c38
class SimpleXMethodMatcher(XMethodMatcher): <NEW_LINE> <INDENT> class SimpleXMethodWorker(XMethodWorker): <NEW_LINE> <INDENT> def __init__(self, method_function, arg_types): <NEW_LINE> <INDENT> self._arg_types = arg_types <NEW_LINE> self._method_function = method_function <NEW_LINE> <DEDENT> def get_arg_types(self): <NEW_LINE> <INDENT> return self._arg_types <NEW_LINE> <DEDENT> def __call__(self, *args): <NEW_LINE> <INDENT> return self._method_function(*args) <NEW_LINE> <DEDENT> <DEDENT> def __init__( self, name, class_matcher, method_matcher, method_function, *arg_types ): <NEW_LINE> <INDENT> XMethodMatcher.__init__(self, name) <NEW_LINE> assert callable(method_function), ( "The 'method_function' argument to 'SimpleXMethodMatcher' " "__init__ method should be a callable." ) <NEW_LINE> self._method_function = method_function <NEW_LINE> self._class_matcher = class_matcher <NEW_LINE> self._method_matcher = method_matcher <NEW_LINE> self._arg_types = arg_types <NEW_LINE> <DEDENT> def match(self, class_type, method_name): <NEW_LINE> <INDENT> cm = re.match(self._class_matcher, str(class_type.unqualified().tag)) <NEW_LINE> mm = re.match(self._method_matcher, method_name) <NEW_LINE> if cm and mm: <NEW_LINE> <INDENT> return SimpleXMethodMatcher.SimpleXMethodWorker( self._method_function, self._arg_types )
A utility class to implement simple xmethod mathers and workers. See the __init__ method below for information on how instances of this class can be used. For simple classes and methods, one can choose to use this class. For complex xmethods, which need to replace/implement template methods on possibly template classes, one should implement their own xmethod matchers and workers. See py-xmethods.py in testsuite/gdb.python directory of the GDB source tree for examples.
62598fbf956e5f7376df5789
class ServerAuthViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = models.ServerAuthRule.objects.all() <NEW_LINE> serializer_class = serializers.ServerAuthRuleSerializer <NEW_LINE> permission_classes = (permissions.AllowAny,)
主机授权规则
62598fbf091ae35668704e3b
class RGB(object): <NEW_LINE> <INDENT> __slots__=['r', 'g', 'b'] <NEW_LINE> def __init__(self, r=0, g=0, b=0): <NEW_LINE> <INDENT> self.r=r <NEW_LINE> self.g=g <NEW_LINE> self.b=b <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<%f %f %f>" % (self.r, self.g, self.b) <NEW_LINE> <DEDENT> def __eq__(self, rhs): <NEW_LINE> <INDENT> return self.r==rhs.r and self.g==rhs.g and self.b==rhs.b <NEW_LINE> <DEDENT> def __ne__(self, rhs): <NEW_LINE> <INDENT> return not self.__eq__(rhs) <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if key==0: <NEW_LINE> <INDENT> return self.r <NEW_LINE> <DEDENT> elif key==1: <NEW_LINE> <INDENT> return self.g <NEW_LINE> <DEDENT> elif key==2: <NEW_LINE> <INDENT> return self.b <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert(False)
material color
62598fbf2c8b7c6e89bd39d6
class DecodeProtoFailTest(test_case.ProtoOpTestCase): <NEW_LINE> <INDENT> def _TestCorruptProtobuf(self, sanitize): <NEW_LINE> <INDENT> corrupt_proto = 'This is not a binary protobuf' <NEW_LINE> batch = np.array(corrupt_proto, dtype=object) <NEW_LINE> msg_type = 'tensorflow.contrib.proto.TestCase' <NEW_LINE> field_names = ['sizes'] <NEW_LINE> field_types = [dtypes.int32] <NEW_LINE> with self.test_session() as sess: <NEW_LINE> <INDENT> ctensor, vtensor = decode_proto_op.decode_proto( batch, message_type=msg_type, field_names=field_names, output_types=field_types, sanitize=sanitize) <NEW_LINE> with self.assertRaisesRegexp(errors.DataLossError, 'Unable to parse binary protobuf' '|Failed to consume entire buffer'): <NEW_LINE> <INDENT> _ = sess.run([ctensor] + vtensor) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def testCorrupt(self): <NEW_LINE> <INDENT> self._TestCorruptProtobuf(sanitize=False) <NEW_LINE> <DEDENT> def testSanitizerCorrupt(self): <NEW_LINE> <INDENT> self._TestCorruptProtobuf(sanitize=True)
Test failure cases for DecodeToProto.
62598fbf4f88993c371f0614
class InputPeerChat(TLObject): <NEW_LINE> <INDENT> __slots__ = ["chat_id"] <NEW_LINE> ID = 0x179be863 <NEW_LINE> QUALNAME = "types.InputPeerChat" <NEW_LINE> def __init__(self, *, chat_id: int): <NEW_LINE> <INDENT> self.chat_id = chat_id <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "InputPeerChat": <NEW_LINE> <INDENT> chat_id = Int.read(b) <NEW_LINE> return InputPeerChat(chat_id=chat_id) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> b.write(Int(self.chat_id)) <NEW_LINE> return b.getvalue()
Attributes: LAYER: ``112`` Attributes: ID: ``0x179be863`` Parameters: chat_id: ``int`` ``32-bit``
62598fbfdc8b845886d537d0
class ApiPortalResource(ProxyResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'system_data': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, 'properties': {'key': 'properties', 'type': 'ApiPortalProperties'}, 'sku': {'key': 'sku', 'type': 'Sku'}, } <NEW_LINE> def __init__( self, *, properties: Optional["ApiPortalProperties"] = None, sku: Optional["Sku"] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApiPortalResource, self).__init__(**kwargs) <NEW_LINE> self.properties = properties <NEW_LINE> self.sku = sku
API portal resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. :vartype type: str :ivar system_data: Metadata pertaining to creation and last modification of the resource. :vartype system_data: ~azure.mgmt.appplatform.v2022_01_01_preview.models.SystemData :ivar properties: API portal properties payload. :vartype properties: ~azure.mgmt.appplatform.v2022_01_01_preview.models.ApiPortalProperties :ivar sku: Sku of the API portal resource. :vartype sku: ~azure.mgmt.appplatform.v2022_01_01_preview.models.Sku
62598fbff548e778e596b7bc
class SolidMembrane(SolidModelBase): <NEW_LINE> <INDENT> def __init__(self, solution, traction, n, dt, bcs, params, tol=1E-8): <NEW_LINE> <INDENT> V = solution.function_space() <NEW_LINE> u = TrialFunction(V) <NEW_LINE> w = TestFunction(V) <NEW_LINE> rho_s = Constant(params.rho_s) <NEW_LINE> E = Constant(params.E) <NEW_LINE> nu = Constant(params.nu) <NEW_LINE> k = Constant(params.kk) <NEW_LINE> h_s = Constant(params.h) <NEW_LINE> u0 = Function(V) <NEW_LINE> u0.assign(solution) <NEW_LINE> u1 = Function(V) <NEW_LINE> form = rho_s*h_s*inner((u-2*u0+u1)/dt**2, w)*dx+ h_s*inner(stress(u, n, E, nu, k), strain(w, n))*dx+ inner(traction, w)*dx <NEW_LINE> a, L = lhs(form), rhs(form) <NEW_LINE> bcs = [DirichletBC(V, value, bdry, tag) for (value, bdry, tag) in bcs] <NEW_LINE> A, b = PETScMatrix(), PETScVector() <NEW_LINE> solver = PETScKrylovSolver('gmres', 'hypre_euclid') <NEW_LINE> self.uh, self.u0, self.u1 = solution, u0, u1 <NEW_LINE> self.a, self.L = a, L <NEW_LINE> self.A, self.b = A, b <NEW_LINE> self.solver = solver <NEW_LINE> self.bcs = bcs <NEW_LINE> <DEDENT> def solve(self): <NEW_LINE> <INDENT> assemble(self.a, tensor=self.A) <NEW_LINE> assemble(self.L, tensor=self.b) <NEW_LINE> for bc in self.bcs: bc.apply(self.A, self.b) <NEW_LINE> niters = self.solver.solve(self.A, self.uh.vector(), self.b) <NEW_LINE> self.u1.assign(self.u0) <NEW_LINE> self.u0.assign(self.uh) <NEW_LINE> return niters
Elastic membrane from A coupled momentum method for modelling blood flow in 3d deformable arteries.
62598fbf0fa83653e46f50fc
class ArgsValidator(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def validate(cls, args): <NEW_LINE> <INDENT> if len(args) == 1: <NEW_LINE> <INDENT> sys_exit('Please enter site url as second argument!') <NEW_LINE> <DEDENT> url = args[1] <NEW_LINE> url_checker = UrlValidator(url=url) <NEW_LINE> url_checker.validate() <NEW_LINE> return url
Валидатор входных параметров
62598fbf63b5f9789fe85388
class DelayPreds(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self, delay=1000, skip=100, two_dim=False): <NEW_LINE> <INDENT> self.delay = delay <NEW_LINE> self.skip = skip <NEW_LINE> self.two_dim = two_dim <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, X, y=None): <NEW_LINE> <INDENT> if self.two_dim: <NEW_LINE> <INDENT> return delay_preds_2d(X, delay=self.delay, skip=self.skip) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return delay_preds(X, delay=self.delay, skip=self.skip) <NEW_LINE> <DEDENT> <DEDENT> def update_subsample(self, old_sub, new_sub): <NEW_LINE> <INDENT> ratio = old_sub / new_sub <NEW_LINE> self.delay = int(self.delay * ratio) <NEW_LINE> self.skip = int(self.skip * ratio)
Delayed prediction tranformer Mixin.
62598fbf4c3428357761a4d3
class Category(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'category' <NEW_LINE> ordering = ['name'] <NEW_LINE> <DEDENT> category_id = models.AutoField(primary_key=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> icon = models.ImageField( upload_to='icons', null=True, blank=True, help_text=( 'It is expected that the icon came from http://mapicons.mapsmarker.com/ and that it ' 'has a transparent background with a white foreground' ) ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
A container for species.
62598fbf67a9b606de5461e2
class Solution: <NEW_LINE> <INDENT> def searchMatrix(self, matrix, target): <NEW_LINE> <INDENT> if target is None or matrix is None or not len(matrix) or not len(matrix[0]): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> sentinels = [] <NEW_LINE> for i in range(len(matrix)): <NEW_LINE> <INDENT> sentinels.append(matrix[i][0]) <NEW_LINE> <DEDENT> if len(matrix[i]) > 1: <NEW_LINE> <INDENT> sentinels.append(matrix[i][len(matrix[i]) - 1]) <NEW_LINE> <DEDENT> start, end, found = self.do_binary_search(sentinels, target) <NEW_LINE> if found: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if sentinels[start] == target or sentinels[end] == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> row_ind = 0 <NEW_LINE> if sentinels[start] > target: <NEW_LINE> <INDENT> row_ind = start - 1 <NEW_LINE> <DEDENT> elif sentinels[end] > target: <NEW_LINE> <INDENT> row_ind = start <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> row_ind = end <NEW_LINE> <DEDENT> if row_ind < 0 or row_ind >= len(matrix): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> row_to_inspect = matrix[row_ind] <NEW_LINE> start, end, found = self.do_binary_search(row_to_inspect, target) <NEW_LINE> if found: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return row_to_inspect[start] == target or row_to_inspect[end] == target <NEW_LINE> <DEDENT> def do_binary_search(self, list_to_search, target): <NEW_LINE> <INDENT> start, end = 0, len(list_to_search) - 1 <NEW_LINE> while start + 1 < end: <NEW_LINE> <INDENT> mid = (start + end) // 2 <NEW_LINE> if list_to_search[mid] > target: <NEW_LINE> <INDENT> end = mid <NEW_LINE> <DEDENT> elif list_to_search[mid] == target: <NEW_LINE> <INDENT> return start, end, True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> start = mid <NEW_LINE> <DEDENT> <DEDENT> return start, end, False
@param matrix: matrix, a list of lists of integers @param target: An integer @return: a boolean, indicate whether matrix contains target
62598fbf97e22403b383b120
class LapPrinter(Printer): <NEW_LINE> <INDENT> def common_entry(self, row): <NEW_LINE> <INDENT> row_print = list(row) <NEW_LINE> if 'Lap Times' in self.fields: <NEW_LINE> <INDENT> idx_lap = self.fields.index('Lap Times') <NEW_LINE> lap_times = row[idx_lap] <NEW_LINE> row_print[idx_lap] = lap_times[0] <NEW_LINE> <DEDENT> entry = self.row_delim.join(row_print) <NEW_LINE> if 'Lap Times' in self.fields: <NEW_LINE> <INDENT> for i in range(1, len(lap_times)): <NEW_LINE> <INDENT> entry += self.row_end + self.row_start + self.row_delim <NEW_LINE> row_print = ['' for j in range(len(row))] <NEW_LINE> row_print[idx_lap] = str(lap_times[i]) <NEW_LINE> entry += self.row_delim.join(row_print) <NEW_LINE> <DEDENT> <DEDENT> return entry
Printer class for multi lap races
62598fbfaad79263cf42e9ec
class IsTripOwnerOrNothing(permissions.BasePermission): <NEW_LINE> <INDENT> def has_object_permission(self, request, view, obj): <NEW_LINE> <INDENT> return obj.trip.user == request.user
Custom permission to only allow owners of an object to edit it.
62598fbf3d592f4c4edbb0d4
class Address(Model): <NEW_LINE> <INDENT> def __init__(self, json): <NEW_LINE> <INDENT> self.parking_instructions = json.get("parking_instructions") <NEW_LINE> self.city = json.get("city") <NEW_LINE> self.address_city = json.get("address_city") <NEW_LINE> self.contact_preference = json.get("contact_preference") <NEW_LINE> self.name = json.get("name") <NEW_LINE> self.zip = json.get("zip") <NEW_LINE> self.apt_number = json.get("apt_number") <NEW_LINE> self.floor_number = json.get("floor_number") <NEW_LINE> self.state = json.get("state") <NEW_LINE> self.buzzer_code = json.get("buzzer_code") <NEW_LINE> self.confirmed = json.get("confirmed", False) <NEW_LINE> self.id = json.get("id") <NEW_LINE> self.street_address = json.get("street_address") <NEW_LINE> self.instructions = json.get("instructions") <NEW_LINE> self.latitude = json.get("latitude") <NEW_LINE> self.longitude = json.get("longitude") <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name
User's delivery address information.
62598fbf99fddb7c1ca62ef8
class ObfuscatedUrlInfo(Model): <NEW_LINE> <INDENT> content = models.ForeignKey(Content) <NEW_LINE> create_date = models.DateTimeField() <NEW_LINE> expire_date = models.DateTimeField() <NEW_LINE> url_uuid = models.CharField(max_length=32, unique=True, editable=False) <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> self.url_uuid = str(uuid.uuid4()).replace("-", "") <NEW_LINE> <DEDENT> super(ObfuscatedUrlInfo, self).save(*args, **kwargs)
Stores info used for obfuscated urls of unpublished content.
62598fbf956e5f7376df578a
class StoragePoolOperationListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'required': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[StoragePoolRPOperation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(StoragePoolOperationListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs['value'] <NEW_LINE> self.next_link = kwargs.get('next_link', None)
List of operations supported by the RP. All required parameters must be populated in order to send to Azure. :param value: Required. An array of operations supported by the StoragePool RP. :type value: list[~storage_pool_management.models.StoragePoolRPOperation] :param next_link: URI to fetch the next section of the paginated response. :type next_link: str
62598fbf57b8e32f52508229
class IDeserializeFromJson(Interface): <NEW_LINE> <INDENT> pass
An adapter to deserialize a JSON object into an object in Plone.
62598fbf4f88993c371f0615
class StaffGradingTab(StaffTab, GradingTab): <NEW_LINE> <INDENT> type = 'staff_grading' <NEW_LINE> def __init__(self, tab=None): <NEW_LINE> <INDENT> super(StaffGradingTab, self).__init__( name=_("Staff grading"), tab_id=self.type, link_func=link_reverse_func(self.type), )
A tab for staff grading.
62598fbfdc8b845886d537d2
class GetTypeInfo_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.STRUCT, 'success', (TGetTypeInfoResp, TGetTypeInfoResp.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <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 == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = TGetTypeInfoResp() <NEW_LINE> self.success.read(iprot) <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('GetTypeInfo_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <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.success) <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: - success
62598fbffff4ab517ebcd9fd
class Layer(object): <NEW_LINE> <INDENT> __bases__ = () <NEW_LINE> __name__ = 'Layer' <NEW_LINE> @classmethod <NEW_LINE> def get_app(cls): <NEW_LINE> <INDENT> return _APP_UNDER_TEST <NEW_LINE> <DEDENT> def make_wsgi_app(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def cooperative_super(self, method_name): <NEW_LINE> <INDENT> method = getattr(super(Layer, self), method_name, None) <NEW_LINE> if method is not None: <NEW_LINE> <INDENT> method() <NEW_LINE> <DEDENT> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.cooperative_super('setUp') <NEW_LINE> global _APP_UNDER_TEST <NEW_LINE> if _APP_UNDER_TEST is not None: <NEW_LINE> <INDENT> raise AssertionError("Already Setup") <NEW_LINE> <DEDENT> _APP_UNDER_TEST = self.make_wsgi_app() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> global _APP_UNDER_TEST <NEW_LINE> _APP_UNDER_TEST = None <NEW_LINE> self.cooperative_super('tearDown')
Test layer which sets up WSGI app for use with WebTest/testbrowser. Inherit from this layer and overwrite `make_wsgi_app` for setup. Composing multiple layers into one is supported using plone.testing.Layer.
62598fbfe1aae11d1e7ce931
class FESolver(object): <NEW_LINE> <INDENT> def displace(self, load, x, ke, penal): <NEW_LINE> <INDENT> freedofs = np.array(load.freedofs()) <NEW_LINE> nely, nelx = x.shape <NEW_LINE> f_free = load.force()[freedofs] <NEW_LINE> k_free = self.gk_freedofs(load, x, ke, penal) <NEW_LINE> u = np.zeros(load.dim*(nely+1)*(nelx+1)) <NEW_LINE> u[freedofs] = spsolve(k_free, f_free) <NEW_LINE> return u <NEW_LINE> <DEDENT> def gk_freedofs(self, load, x, ke, penal): <NEW_LINE> <INDENT> freedofs = np.array(load.freedofs()) <NEW_LINE> nelx = load.nelx <NEW_LINE> nely = load.nely <NEW_LINE> edof, x_list, y_list = load.edof() <NEW_LINE> factor = x.T.reshape(nelx*nely, 1, 1) ** penal <NEW_LINE> value_list = (np.tile(ke, (nelx*nely, 1, 1))*factor).flatten() <NEW_LINE> dof = load.dim*(nelx+1)*(nely+1) <NEW_LINE> k = coo_matrix((value_list, (y_list, x_list)), shape=(dof, dof)).tocsc() <NEW_LINE> k = k[freedofs, :][:, freedofs] <NEW_LINE> return k
The parent FESolver is used for constructing the global stiffness matrix.
62598fbfcc40096d6161a2e5
class AbstractLocationFeed(EbpubFeed): <NEW_LINE> <INDENT> title_template = 'feeds/streets_title.html' <NEW_LINE> description_template = 'feeds/streets_description.html' <NEW_LINE> def items(self, obj): <NEW_LINE> <INDENT> today_value = today() <NEW_LINE> start_date = today_value - datetime.timedelta(days=5) <NEW_LINE> end_date = today_value + datetime.timedelta(days=5) <NEW_LINE> qs = NewsItem.objects.select_related().by_request(self.request).filter( item_date__gte=start_date, item_date__lte=end_date).order_by('-item_date', 'schema__id', 'id') <NEW_LINE> if 'ignore' in self.request.GET: <NEW_LINE> <INDENT> schema_slugs = self.request.GET['ignore'].split(',') <NEW_LINE> qs = qs.exclude(schema__slug__in=schema_slugs) <NEW_LINE> <DEDENT> if 'only' in self.request.GET: <NEW_LINE> <INDENT> schema_slugs = self.request.GET['only'].split(',') <NEW_LINE> qs = qs.filter(schema__slug__in=schema_slugs) <NEW_LINE> <DEDENT> block_radius = self.request.GET.get('radius', BLOCK_RADIUS_DEFAULT) <NEW_LINE> if block_radius not in BLOCK_RADIUS_CHOICES: <NEW_LINE> <INDENT> raise Http404('Invalid radius') <NEW_LINE> <DEDENT> ni_list = list(self.newsitems_for_obj(obj, qs, block_radius)) <NEW_LINE> schema_list = list(set([ni.schema for ni in ni_list])) <NEW_LINE> populate_attributes_if_needed(ni_list, schema_list) <NEW_LINE> is_block = isinstance(obj, Block) <NEW_LINE> for schema_group in bunch_by_date_and_schema(ni_list, today_value): <NEW_LINE> <INDENT> schema = schema_group[0].schema <NEW_LINE> if schema.can_collapse: <NEW_LINE> <INDENT> yield ('newsitem', obj, schema, schema_group, is_block, block_radius) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for newsitem in schema_group: <NEW_LINE> <INDENT> yield ('newsitem', obj, schema, newsitem, is_block, block_radius) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def item_pubdate(self, item): <NEW_LINE> <INDENT> if item[0] == 'newsitem': <NEW_LINE> <INDENT> if item[2].can_collapse: <NEW_LINE> <INDENT> return item[3][0].pub_date <NEW_LINE> <DEDENT> return item[3].pub_date <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> <DEDENT> def item_link(self, item): <NEW_LINE> <INDENT> if item[0] == 'newsitem': <NEW_LINE> <INDENT> if item[2].can_collapse: <NEW_LINE> <INDENT> return item[1].url() + '#%s-%s' % (item[3][0].schema.slug, item[3][0].item_date.strftime('%Y%m%d')) <NEW_LINE> <DEDENT> return item[3].item_url_with_domain() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> <DEDENT> def newsitems_for_obj(self, obj, qs, block_radius): <NEW_LINE> <INDENT> raise NotImplementedError('Subclasses must implement this.')
Abstract base class for :py:class:`ebpub.db.models.Location`-aware RSS feeds.
62598fbf55399d3f0562672f
class RequestTicket(Base): <NEW_LINE> <INDENT> __tablename__ = 'request_ticket' <NEW_LINE> id = Column(Integer, unique=True, primary_key=True, autoincrement=True) <NEW_LINE> title = Column(String(50)) <NEW_LINE> description = Column(String(200)) <NEW_LINE> client = Column(Enum('Client A', 'Client B', 'Client C')) <NEW_LINE> client_priority = Column(Integer) <NEW_LINE> target_date = Column(DateTime) <NEW_LINE> ticket_url = Column(String(100)) <NEW_LINE> product_area = Column(Enum('Policies', 'Billing', 'Claims', 'Reports')) <NEW_LINE> user_id = Column(Integer, ForeignKey('user.id')) <NEW_LINE> def __init__(self, ind, title, description, client, client_priority, target_date, ticket_url, product_area, user_id): <NEW_LINE> <INDENT> self.id = ind <NEW_LINE> self.title = str(title) <NEW_LINE> self.description = str(description) <NEW_LINE> self.client = client <NEW_LINE> self.client_priority = int(client_priority) <NEW_LINE> self.target_date = target_date <NEW_LINE> self.ticket_url = ticket_url <NEW_LINE> self.product_area = product_area <NEW_LINE> self.user_id = user_id <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self.serialize, indent=4) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return json.dumps(self.serialize) <NEW_LINE> <DEDENT> @property <NEW_LINE> def serialize(self): <NEW_LINE> <INDENT> return {u"id": self.id, u"title": self.title, u"description": self.description, u"client": self.client, u"client_priority": self.client_priority, u"target_date": str(self.target_date), u"ticket_url": str(self.ticket_url), u"product_area": self.product_area, u"user_id": self.user_id}
Schema to declare table of requests
62598fbf97e22403b383b121
class Histogram(object): <NEW_LINE> <INDENT> def __init__(self, training_instances, names, granularity=(1, 1, 1), use_progress=False): <NEW_LINE> <INDENT> self.names = names <NEW_LINE> self.buckets = defaultdict(Counter) <NEW_LINE> self.bucket_counts = defaultdict(int) <NEW_LINE> self.granularity = granularity <NEW_LINE> self.bucket_sizes = (360 // granularity[0], 100 // granularity[1], 100 // granularity[2]) <NEW_LINE> self.use_progress = use_progress <NEW_LINE> self.add_data(training_instances) <NEW_LINE> <DEDENT> def add_data(self, training_instances): <NEW_LINE> <INDENT> if self.use_progress: <NEW_LINE> <INDENT> progress.start_task('Example', len(training_instances)) <NEW_LINE> <DEDENT> for i, inst in enumerate(training_instances): <NEW_LINE> <INDENT> if self.use_progress: <NEW_LINE> <INDENT> progress.progress(i) <NEW_LINE> <DEDENT> bucket = self.get_bucket(inst.input) <NEW_LINE> self.buckets[bucket][inst.output] += 1 <NEW_LINE> self.bucket_counts[bucket] += 1 <NEW_LINE> <DEDENT> if self.use_progress: <NEW_LINE> <INDENT> progress.end_task() <NEW_LINE> <DEDENT> <DEDENT> def get_bucket(self, color): <NEW_LINE> <INDENT> return tuple( s * min(int(d // s), g - 1) for d, s, g in zip(color, self.bucket_sizes, self.granularity) ) <NEW_LINE> <DEDENT> def get_probs(self, color): <NEW_LINE> <INDENT> bucket = self.get_bucket(color) <NEW_LINE> counter = self.buckets[bucket] <NEW_LINE> bucket_size = self.bucket_counts[bucket] <NEW_LINE> probs = [] <NEW_LINE> for name in self.names: <NEW_LINE> <INDENT> prob = ((counter[name] * 1.0 / bucket_size) if bucket_size != 0 else (1.0 / len(self.names))) <NEW_LINE> probs.append(prob) <NEW_LINE> <DEDENT> return probs <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_params(self): <NEW_LINE> <INDENT> return sum(len(counter) for _name, counter in self.buckets.items()) <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> state = dict(self.__dict__) <NEW_LINE> for name in ('buckets', 'bucket_counts'): <NEW_LINE> <INDENT> state[name] = dict(state[name]) <NEW_LINE> <DEDENT> return state <NEW_LINE> <DEDENT> def __setstate__(self, state): <NEW_LINE> <INDENT> self.__dict__.update(state) <NEW_LINE> self.buckets = defaultdict(Counter, self.buckets) <NEW_LINE> self.bucket_counts = defaultdict(int, self.bucket_counts)
>>> from stanza.research.instance import Instance as I >>> data = [I((0.0, 100.0, 49.0), 'red'), ... I((0.0, 100.0, 45.0), 'dark red'), ... I((240.0, 100.0, 49.0), 'blue')] >>> h = Histogram(data, names=['red', 'dark red', 'blue'], ... granularity=(4, 10, 10)) >>> h.get_probs((1.0, 91.0, 48.0)) [0.5, 0.5, 0.0] >>> h.get_probs((240.0, 100.0, 40.0)) [0.0, 0.0, 1.0]
62598fbf7c178a314d78d6b8
class Edge(object): <NEW_LINE> <INDENT> def __init__(self, nodes=None, edges=None, **attr): <NEW_LINE> <INDENT> self.nodes = nodes <NEW_LINE> self.edges = edges <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.graph.get('name', '') <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, s): <NEW_LINE> <INDENT> self.graph['name'] = s <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.node) <NEW_LINE> <DEDENT> def __contains__(self, n): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return n in self.node <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.node) <NEW_LINE> <DEDENT> def __getitem__(self, n): <NEW_LINE> <INDENT> return self.adj[n]
Base class for undirected graphs. A Graph stores nodes and edges with optional data, or attributes. Graphs hold undirected edges. Self loops are allowed but multiple (parallel) edges are not. Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. Edges are represented as links between nodes with optional key/value attributes. Parameters ---------- data : input graph Data to initialize graph. If data=None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph. attr : keyword arguments, optional (default= no attributes) Attributes to add to graph as key=value pairs. See Also -------- DiGraph MultiGraph MultiDiGraph Examples -------- Create an empty graph structure (a "null graph") with no nodes and no edges. >>> G = Graph() G can be grown in several ways. **Nodes:** Add one node at a time: >>> G.add_node(1) Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph). >>> G.add_nodes_from([2,3]) >>> G.add_nodes_from(range(100,110)) >>> H=nx.Graph() >>> H.add_path([0,1,2,3,4,5,6,7,8,9]) >>> G.add_nodes_from(H)
62598fbf3317a56b869be65c
class sgd_momentum(object): <NEW_LINE> <INDENT> def __init__(self, model, loss_func, learning_rate=1e-4, **kwargs): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.loss_func = loss_func <NEW_LINE> self.lr = learning_rate <NEW_LINE> self.grads = None <NEW_LINE> self.optim_config = kwargs.pop('optim_config', {}) <NEW_LINE> self._reset() <NEW_LINE> <DEDENT> def _reset(self): <NEW_LINE> <INDENT> self.optim_configs = {} <NEW_LINE> for p in self.model.params: <NEW_LINE> <INDENT> d = {k: v for k, v in self.optim_configs.items()} <NEW_LINE> self.optim_configs[p] = d <NEW_LINE> <DEDENT> <DEDENT> def backward(self, y_pred, y_true): <NEW_LINE> <INDENT> dout = self.loss_func.backward(y_pred, y_true) <NEW_LINE> self.model.backward(dout) <NEW_LINE> <DEDENT> def _update(self, w, dw, config, lr): <NEW_LINE> <INDENT> if config is None: <NEW_LINE> <INDENT> config = {} <NEW_LINE> <DEDENT> config.setdefault('momentum', 0.9) <NEW_LINE> v = config.get('velocity', np.zeros_like(w)) <NEW_LINE> next_w = None <NEW_LINE> mu = config['momentum'] <NEW_LINE> learning_rate = lr <NEW_LINE> v = mu * v - learning_rate * dw <NEW_LINE> next_w = w + v <NEW_LINE> config['velocity'] = v <NEW_LINE> return next_w, config <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> for name in self.model.grads.keys(): <NEW_LINE> <INDENT> w = self.model.params[name] <NEW_LINE> dw = self.model.grads[name] <NEW_LINE> config = self.optim_configs[name] <NEW_LINE> w_updated, config = self._update(w, dw, config, lr=self.lr) <NEW_LINE> self.model.params[name] = w_updated <NEW_LINE> self.optim_configs[name] = config <NEW_LINE> self.model.grads[name] = 0.0
Performs stochastic gradient descent with momentum. config format: - momentum: Scalar between 0 and 1 giving the momentum value. Setting momentum = 0 reduces to sgd. - velocity: A numpy array of the same shape as w and dw used to store a moving average of the gradients.
62598fbf26068e7796d4cb75
class ConfigBase: <NEW_LINE> <INDENT> def __init__(self, dictionary: Dict = None): <NEW_LINE> <INDENT> if dictionary is not None: <NEW_LINE> <INDENT> self.__dict__ = dictionary <NEW_LINE> <DEDENT> self._pipework = None <NEW_LINE> self._auxiliaryFlags = {} <NEW_LINE> <DEDENT> def peek(self, name: str): <NEW_LINE> <INDENT> self._throw_if_doesnt_exist(name) <NEW_LINE> return object.__getattribute__(self, name) <NEW_LINE> <DEDENT> def has(self, paramName: str) -> bool: <NEW_LINE> <INDENT> return paramName in self.__dict__ <NEW_LINE> <DEDENT> def mark_auxiliary(self, params: List[str]): <NEW_LINE> <INDENT> for name in params: <NEW_LINE> <INDENT> self._throw_if_doesnt_exist(name) <NEW_LINE> self._auxiliaryFlags[name] = True <NEW_LINE> <DEDENT> <DEDENT> def is_auxiliary(self, name: str) -> bool: <NEW_LINE> <INDENT> return name in self._auxiliaryFlags and self._auxiliaryFlags[name] <NEW_LINE> <DEDENT> def _getattribute_method(self, name: str): <NEW_LINE> <INDENT> if name.startswith('_') or name in ['peek', 'has', 'mark_auxiliary', 'is_auxiliary']: <NEW_LINE> <INDENT> return object.__getattribute__(self, name) <NEW_LINE> <DEDENT> self._throw_if_doesnt_exist(name) <NEW_LINE> if not self.is_auxiliary(name) and self._pipework is not None: <NEW_LINE> <INDENT> self._pipework.register_config_param(name) <NEW_LINE> <DEDENT> return object.__getattribute__(self, name) <NEW_LINE> <DEDENT> def _setattr_method(self, name, value): <NEW_LINE> <INDENT> if not name.startswith('_') and self._pipework is not None: <NEW_LINE> <INDENT> raise RuntimeError("Editing configs from reactors is not allowed. " "(Tried to change the '{}' parameter.)".format(name)) <NEW_LINE> <DEDENT> object.__setattr__(self, name, value) <NEW_LINE> <DEDENT> def _clone_with_pipe(self, pipe: 'Pipework') -> 'ConfigBase': <NEW_LINE> <INDENT> clone = copy.copy(self) <NEW_LINE> clone._pipework = pipe <NEW_LINE> return clone <NEW_LINE> <DEDENT> def _throw_if_doesnt_exist(self, name): <NEW_LINE> <INDENT> if name not in self.__dict__: <NEW_LINE> <INDENT> raise AttributeError("The config parameter '{}' does not exist.".format(name))
A base class for config objects that should be used with the Plant. Tracks the access to the config parameters and registers corresponding reactor dependencies. Provides an alternative (better) way of handling configuration, since IDE features for editing
62598fbf8a349b6b43686457
class Node(JsonObject): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ip = kwargs.get('ip', None) <NEW_LINE> self.mac = kwargs.get('mac', None) <NEW_LINE> self.vid = kwargs.get('vid', None) <NEW_LINE> self.dpid = kwargs.get('dpid', None) <NEW_LINE> self.port = kwargs.get('port', None)
Node (JsonObject) Una representación de python del objeto Node
62598fbfdc8b845886d537d4
class LC400Motor(Motor): <NEW_LINE> <INDENT> def __init__(self, device, axis, **kwargs): <NEW_LINE> <INDENT> super(LC400Motor, self).__init__(**kwargs) <NEW_LINE> assert axis in (1, 2, 3) <NEW_LINE> self.proxy = PyTango.DeviceProxy(device) <NEW_LINE> self.proxy.set_source(PyTango.DevSource.DEV) <NEW_LINE> self.axis = axis <NEW_LINE> self._format = '%.3f' <NEW_LINE> <DEDENT> @property <NEW_LINE> def dial_position(self): <NEW_LINE> <INDENT> if self.axis == 1: <NEW_LINE> <INDENT> val = self.proxy.axis1_position <NEW_LINE> <DEDENT> elif self.axis == 2: <NEW_LINE> <INDENT> val = self.proxy.axis2_position <NEW_LINE> <DEDENT> elif self.axis == 3: <NEW_LINE> <INDENT> val = self.proxy.axis3_position <NEW_LINE> <DEDENT> return val <NEW_LINE> <DEDENT> @dial_position.setter <NEW_LINE> def dial_position(self, pos): <NEW_LINE> <INDENT> if self.axis == 1: <NEW_LINE> <INDENT> self.proxy.axis1_position = pos <NEW_LINE> <DEDENT> elif self.axis == 2: <NEW_LINE> <INDENT> self.proxy.axis2_position = pos <NEW_LINE> <DEDENT> elif self.axis == 3: <NEW_LINE> <INDENT> self.proxy.axis3_position = pos <NEW_LINE> <DEDENT> <DEDENT> def busy(self): <NEW_LINE> <INDENT> attribute = 'axis%d_position_on_target' % self.axis <NEW_LINE> on_target = self.proxy.read_attribute(attribute).value <NEW_LINE> return not on_target <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.proxy.stop_waveform() <NEW_LINE> self.proxy.stop_recording()
Single axis on the LC400.
62598fbf97e22403b383b123
class Output: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.description = kwargs.get('description') <NEW_LINE> self.key = kwargs.get('output_key') <NEW_LINE> self.value = kwargs.get('output_value')
SNAPS domain object for an output defined by a heat template
62598fbf4c3428357761a4d7
class BaseConnection(object): <NEW_LINE> <INDENT> def __init__(self, hostname=None, port=None, path=None, username=None, password=None): <NEW_LINE> <INDENT> if hostname is None: <NEW_LINE> <INDENT> hostname = arc.config.get_default().get_server_host() <NEW_LINE> <DEDENT> self.hostname = hostname <NEW_LINE> if port is None: <NEW_LINE> <INDENT> port = arc.config.get_default().get_server_port() <NEW_LINE> <DEDENT> self.port = port <NEW_LINE> if path is None: <NEW_LINE> <INDENT> path = arc.shared.rpc.DEFAULT_PATH <NEW_LINE> <DEDENT> if username is None: <NEW_LINE> <INDENT> username = arc.config.get_default().get_username() <NEW_LINE> <DEDENT> self.username = username <NEW_LINE> if password is None: <NEW_LINE> <INDENT> password = arc.config.get_default().get_password() <NEW_LINE> <DEDENT> self.password = password <NEW_LINE> self.services = {} <NEW_LINE> self.service_proxies = {} <NEW_LINE> self.service_interface_versions = {} <NEW_LINE> try: <NEW_LINE> <INDENT> self.proxy = self._connect(path, self.username) <NEW_LINE> <DEDENT> except RpcAuthError: <NEW_LINE> <INDENT> raise AuthError <NEW_LINE> <DEDENT> <DEDENT> def _connect(self, path, username): <NEW_LINE> <INDENT> rpc_uri = "http://%s:%s/%s" % (self.hostname, self.port, path) <NEW_LINE> base64string = base64.encodestring('%s:%s' % (self.username, self.password))[:-1] <NEW_LINE> headers = {'AUTHORIZATION': 'Basic %s' % base64string} <NEW_LINE> return arc.proxy.Proxy(rpc_uri, headers) <NEW_LINE> <DEDENT> def run(self, service, operation, *args, **data): <NEW_LINE> <INDENT> proxy = self.service_proxies.get(service, None) <NEW_LINE> if proxy is None: <NEW_LINE> <INDENT> raise InvalidProxyError <NEW_LINE> <DEDENT> function = getattr(proxy, operation) <NEW_LINE> result = function(*args, **data) <NEW_LINE> return result <NEW_LINE> <DEDENT> def add_service(self, name, path): <NEW_LINE> <INDENT> self.services[name] = path <NEW_LINE> self.service_proxies[name] = self._connect(path, self.username) <NEW_LINE> try: <NEW_LINE> <INDENT> api_version = tuple(self.run(name, "get_interface_version")) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> api_version = None <NEW_LINE> <DEDENT> self.service_interface_versions[name] = api_version <NEW_LINE> if not self.check_min_rpc_interface_version(name): <NEW_LINE> <INDENT> raise InvalidServiceVersionError <NEW_LINE> <DEDENT> <DEDENT> def check_min_rpc_interface_version(self, service_name): <NEW_LINE> <INDENT> min_version = MIN_REQUIRED_VERSION.get(service_name, None) <NEW_LINE> if min_version is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> current_version = self.service_interface_versions.get(service_name, None) <NEW_LINE> if current_version is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return current_version >= min_version <NEW_LINE> <DEDENT> def ping(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.run(arc.shared.frontend.AFE_SERVICE_NAME, "get_server_time") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Base RPC connection
62598fbff9cc0f698b1c53dd
class StreamServerEndpointService(service.Service, object): <NEW_LINE> <INDENT> _raiseSynchronously = None <NEW_LINE> def __init__(self, endpoint, factory): <NEW_LINE> <INDENT> self.endpoint = endpoint <NEW_LINE> self.factory = factory <NEW_LINE> self._waitingForPort = None <NEW_LINE> <DEDENT> def privilegedStartService(self): <NEW_LINE> <INDENT> service.Service.privilegedStartService(self) <NEW_LINE> self._waitingForPort = self.endpoint.listen(self.factory) <NEW_LINE> raisedNow = [] <NEW_LINE> def handleIt(err): <NEW_LINE> <INDENT> if self._raiseSynchronously: <NEW_LINE> <INDENT> raisedNow.append(err) <NEW_LINE> <DEDENT> elif not err.check(CancelledError): <NEW_LINE> <INDENT> log.err(err) <NEW_LINE> <DEDENT> <DEDENT> self._waitingForPort.addErrback(handleIt) <NEW_LINE> if raisedNow: <NEW_LINE> <INDENT> raisedNow[0].raiseException() <NEW_LINE> <DEDENT> <DEDENT> def startService(self): <NEW_LINE> <INDENT> service.Service.startService(self) <NEW_LINE> if self._waitingForPort is None: <NEW_LINE> <INDENT> self.privilegedStartService() <NEW_LINE> <DEDENT> <DEDENT> def stopService(self): <NEW_LINE> <INDENT> self._waitingForPort.cancel() <NEW_LINE> def stopIt(port): <NEW_LINE> <INDENT> if port is not None: <NEW_LINE> <INDENT> return port.stopListening() <NEW_LINE> <DEDENT> <DEDENT> d = self._waitingForPort.addCallback(stopIt) <NEW_LINE> def stop(passthrough): <NEW_LINE> <INDENT> self.running = False <NEW_LINE> return passthrough <NEW_LINE> <DEDENT> d.addBoth(stop) <NEW_LINE> return d
A L{StreamServerEndpointService} is an L{IService} which runs a server on a listening port described by an L{IStreamServerEndpoint <twisted.internet.interfaces.IStreamServerEndpoint>}. @ivar factory: A server factory which will be used to listen on the endpoint. @ivar endpoint: An L{IStreamServerEndpoint <twisted.internet.interfaces.IStreamServerEndpoint>} provider which will be used to listen when the service starts. @ivar _waitingForPort: a Deferred, if C{listen} has yet been invoked on the endpoint, otherwise None. @ivar _raiseSynchronously: Defines error-handling behavior for the case where C{listen(...)} raises an exception before C{startService} or C{privilegedStartService} have completed. @type _raiseSynchronously: C{bool} @since: 10.2
62598fbf44b2445a339b6a84
class RawDataField(serializers.WritableField): <NEW_LINE> <INDENT> def field_to_native(self, obj, field_name): <NEW_LINE> <INDENT> params = self.context['request'].QUERY_PARAMS <NEW_LINE> order = None <NEW_LINE> new_sort = [] <NEW_LINE> if params.get('sort'): <NEW_LINE> <INDENT> sort = params.get('sort') <NEW_LINE> if sort[:1] == '-': <NEW_LINE> <INDENT> order = 'desc' <NEW_LINE> sort = sort[1:] <NEW_LINE> <DEDENT> sort = sort.split(',') <NEW_LINE> for s in sort: <NEW_LINE> <INDENT> if s == 'from': <NEW_LINE> <INDENT> new_sort.append('from_date') <NEW_LINE> <DEDENT> elif s == 'to': <NEW_LINE> <INDENT> new_sort.append('to_date') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_sort.append(s) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> filter = {} <NEW_LINE> for p in params: <NEW_LINE> <INDENT> if p not in ['sort','format']: <NEW_LINE> <INDENT> value_list = params.get(p).split(',') <NEW_LINE> if p == 'from': <NEW_LINE> <INDENT> filter['from_date'] = value_list <NEW_LINE> <DEDENT> elif p == 'to': <NEW_LINE> <INDENT> filter['to_date'] = value_list <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filter[p] = value_list <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return get_rawdata_for_metric(obj, sort=new_sort, order=order, filter=filter) <NEW_LINE> <DEDENT> def from_native(self, value): <NEW_LINE> <INDENT> if not type(value) is dict: <NEW_LINE> <INDENT> raise ValidationError("Wrong datatype") <NEW_LINE> <DEDENT> if not 'table' in value: <NEW_LINE> <INDENT> raise ValidationError("No key table in data") <NEW_LINE> <DEDENT> if not 'extra_columns' in value: <NEW_LINE> <INDENT> raise ValidationError("No key extra_columns in data") <NEW_LINE> <DEDENT> if not type(value['table']) is list: <NEW_LINE> <INDENT> raise ValidationError("Table property is not a list") <NEW_LINE> <DEDENT> if not type(value['extra_columns']) is list: <NEW_LINE> <INDENT> raise ValidationError("Extra Columns property is not a list") <NEW_LINE> <DEDENT> for e in value['extra_columns']: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> RawDataCategory.objects.get(title=e) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> raise ValidationError("Invalid Extra Column") <NEW_LINE> <DEDENT> <DEDENT> required_fields = ["to", "from", "value"] + value['extra_columns'] <NEW_LINE> for r in value['table']: <NEW_LINE> <INDENT> if not type(r) is dict: <NEW_LINE> <INDENT> raise ValidationError("Table Dict is malformed") <NEW_LINE> <DEDENT> if not all(k in r for k in required_fields): <NEW_LINE> <INDENT> raise ValidationError("Table Dict is malformed, some keys are missing") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> datetime.datetime.strptime(r['from'], '%Y-%m-%d') <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValidationError("Wrong Date Format") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> datetime.datetime.strptime(r['to'], '%Y-%m-%d') <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValidationError("Wrong Date Format") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> float(r['value']) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise ValidationError("At least one value is not a float") <NEW_LINE> <DEDENT> <DEDENT> return value <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> pass
Field for handling the serialization and deserialization of the raw data of a metric.
62598fbfa219f33f346c6a22
class LearningAgent(Agent): <NEW_LINE> <INDENT> def __init__(self, env, learning=False, epsilon=1.0, alpha=0.5): <NEW_LINE> <INDENT> super(LearningAgent, self).__init__(env) <NEW_LINE> self.planner = RoutePlanner(self.env, self) <NEW_LINE> self.valid_actions = self.env.valid_actions <NEW_LINE> self.learning = learning <NEW_LINE> self.Q = dict() <NEW_LINE> self.epsilon = epsilon <NEW_LINE> self.alpha = alpha <NEW_LINE> self.num_trials = 0 <NEW_LINE> <DEDENT> def reset(self, destination=None, testing=False): <NEW_LINE> <INDENT> self.planner.route_to(destination) <NEW_LINE> self.num_trials += 1 <NEW_LINE> self.c = 0.030 <NEW_LINE> if testing == True: <NEW_LINE> <INDENT> self.epsilon = 0.0 <NEW_LINE> self.alpha = 0.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.epsilon = float(1) / math.exp(float(self.c * self.num_trials)) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def build_state(self): <NEW_LINE> <INDENT> waypoint = self.planner.next_waypoint() <NEW_LINE> inputs = self.env.sense(self) <NEW_LINE> deadline = self.env.get_deadline(self) <NEW_LINE> state = (waypoint, inputs['light'], inputs['left'], inputs['oncoming']) <NEW_LINE> return state <NEW_LINE> <DEDENT> def get_maxQ(self, state): <NEW_LINE> <INDENT> maxQ = [key for key, val in self.Q[state].items() if val == max(self.Q[state].values())] <NEW_LINE> return maxQ <NEW_LINE> <DEDENT> def createQ(self, state): <NEW_LINE> <INDENT> if self.learning == True: <NEW_LINE> <INDENT> if state not in self.Q.keys(): <NEW_LINE> <INDENT> self.Q[state] = dict((action, 0.0) for action in self.valid_actions) <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> def choose_action(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> action = None <NEW_LINE> random_num = random.uniform(0, 1) <NEW_LINE> if self.learning == True: <NEW_LINE> <INDENT> highest_q_value = self.get_maxQ(state) <NEW_LINE> if random_num <= (1 - self.epsilon): <NEW_LINE> <INDENT> action = random.choice(highest_q_value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = highest_q_value[0] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> action = random.choice(self.valid_actions) <NEW_LINE> <DEDENT> return action <NEW_LINE> <DEDENT> def learn(self, state, action, reward): <NEW_LINE> <INDENT> if self.learning == True: <NEW_LINE> <INDENT> self.Q[self.state][action] = self.alpha * (reward) + (1 - self.alpha) * self.Q[self.state][action] <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> state = self.build_state() <NEW_LINE> self.createQ(state) <NEW_LINE> action = self.choose_action(state) <NEW_LINE> reward = self.env.act(self, action) <NEW_LINE> self.learn(state, action, reward) <NEW_LINE> return
An agent that learns to drive in the Smartcab world. This is the object you will be modifying.
62598fbf4428ac0f6e65873f
class Aliases(MutableMapping): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self._raw = {} <NEW_LINE> self.update(*args, **kwargs) <NEW_LINE> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> val = self._raw.get(key) <NEW_LINE> if val is None: <NEW_LINE> <INDENT> return default <NEW_LINE> <DEDENT> elif isinstance(val, Iterable) or callable(val): <NEW_LINE> <INDENT> return self.eval_alias(val, seen_tokens={key}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = 'alias of {!r} has an inappropriate type: {!r}' <NEW_LINE> raise TypeError(msg.format(key, val)) <NEW_LINE> <DEDENT> <DEDENT> def eval_alias(self, value, seen_tokens, acc_args=[]): <NEW_LINE> <INDENT> if callable(value): <NEW_LINE> <INDENT> if acc_args: <NEW_LINE> <INDENT> return lambda args, stdin=None: value(acc_args + args, stdin=stdin) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> token, *rest = value <NEW_LINE> if token in seen_tokens or token not in self._raw: <NEW_LINE> <INDENT> return value + acc_args <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.eval_alias(self._raw[token], seen_tokens | {token}, rest + acc_args) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self._raw[key] <NEW_LINE> <DEDENT> def __setitem__(self, key, val): <NEW_LINE> <INDENT> if isinstance(val, string_types): <NEW_LINE> <INDENT> self._raw[key] = shlex.split(val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._raw[key] = val <NEW_LINE> <DEDENT> <DEDENT> def __delitem__(self, key): <NEW_LINE> <INDENT> del self._raw[key] <NEW_LINE> <DEDENT> def update(self, *args, **kwargs): <NEW_LINE> <INDENT> for key, val in dict(*args, **kwargs).items(): <NEW_LINE> <INDENT> self[key] = val <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> yield from self._raw <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._raw) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self._raw) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{0}.{1}({2})'.format(self.__class__.__module__, self.__class__.__name__, self._raw) <NEW_LINE> <DEDENT> def _repr_pretty_(self, p, cycle): <NEW_LINE> <INDENT> name = '{0}.{1}'.format(self.__class__.__module__, self.__class__.__name__) <NEW_LINE> with p.group(0, name + '(', ')'): <NEW_LINE> <INDENT> if cycle: <NEW_LINE> <INDENT> p.text('...') <NEW_LINE> <DEDENT> elif len(self): <NEW_LINE> <INDENT> p.break_() <NEW_LINE> p.pretty(dict(self))
Represents a location to hold and look up aliases.
62598fbf50812a4eaa620cf7
class SearchOrIdFilterTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.filter = filters.SearchOrIdFilter() <NEW_LINE> <DEDENT> def test_filter_queryset_with_search(self): <NEW_LINE> <INDENT> user1 = User.objects.create(first_name="john", username="foo") <NEW_LINE> User.objects.create(first_name="larry", username="bar") <NEW_LINE> queryset = User.objects.all() <NEW_LINE> self.assertEquals(len(queryset), 2) <NEW_LINE> view = Mock() <NEW_LINE> view.search_fields = ("first_name",) <NEW_LINE> request = Mock() <NEW_LINE> request.query_params = {"search": user1.first_name} <NEW_LINE> filtered = self.filter.filter_queryset(request, queryset, view) <NEW_LINE> self.assertEquals(len(filtered), 1) <NEW_LINE> self.assertEquals(filtered[0], user1) <NEW_LINE> <DEDENT> def test_filter_queryset_with_id(self): <NEW_LINE> <INDENT> user1 = User.objects.create(first_name="john", username="foo") <NEW_LINE> User.objects.create(first_name="larry", username="bar") <NEW_LINE> queryset = User.objects.all() <NEW_LINE> self.assertEquals(len(queryset), 2) <NEW_LINE> view = Mock() <NEW_LINE> view.search_fields = ("first_name",) <NEW_LINE> request = Mock() <NEW_LINE> request.query_params = {"id": user1.pk} <NEW_LINE> filtered = self.filter.filter_queryset(request, queryset, view) <NEW_LINE> self.assertEquals(len(filtered), 1) <NEW_LINE> self.assertEquals(filtered[0], user1) <NEW_LINE> <DEDENT> def test_filter_queryset_with_id_and_search(self): <NEW_LINE> <INDENT> user1 = User.objects.create(first_name="john", username="foo") <NEW_LINE> User.objects.create(first_name="larry", username="bar") <NEW_LINE> queryset = User.objects.all() <NEW_LINE> self.assertEquals(len(queryset), 2) <NEW_LINE> view = Mock() <NEW_LINE> view.search_fields = ("first_name",) <NEW_LINE> request = Mock() <NEW_LINE> request.query_params = {"search": user1.first_name, "id": user1.pk} <NEW_LINE> filtered = self.filter.filter_queryset(request, queryset, view) <NEW_LINE> self.assertEquals(len(filtered), 1) <NEW_LINE> self.assertEquals(filtered[0], user1) <NEW_LINE> <DEDENT> def test_filter_queryset_with_id_and_search_different(self): <NEW_LINE> <INDENT> user1 = User.objects.create(first_name="john", username="foo") <NEW_LINE> user2 = User.objects.create(first_name="larry", username="bar") <NEW_LINE> queryset = User.objects.all() <NEW_LINE> self.assertEquals(len(queryset), 2) <NEW_LINE> view = Mock() <NEW_LINE> view.search_fields = ("first_name",) <NEW_LINE> request = Mock() <NEW_LINE> request.query_params = {"search": user2.first_name, "id": user1.pk} <NEW_LINE> filtered = self.filter.filter_queryset(request, queryset, view) <NEW_LINE> self.assertEquals(len(filtered), 2) <NEW_LINE> self.assertIn(user1, filtered) <NEW_LINE> self.assertIn(user2, filtered)
Tests for the joulia.filters.SearchOrIdFilter.
62598fbf7cff6e4e811b5c3e
class Employee: <NEW_LINE> <INDENT> def __init__(self, first_name, last_name, salary): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.salary = salary <NEW_LINE> <DEDENT> @property <NEW_LINE> def fullname_of_employee(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @fullname_of_employee.setter <NEW_LINE> def fullname_of_employee(self, new_fullname_of_employee): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @fullname_of_employee.deleter <NEW_LINE> def fullname_of_employee(self): <NEW_LINE> <INDENT> pass
A class used to represent an Employee ... Attributes ---------- first_name : str a first name of employee last_name : str a last name of employee salary : int a salary of employee
62598fbf8a349b6b43686459
class StorageAccountTypes(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> STANDARD_LRS = "Standard_LRS" <NEW_LINE> PREMIUM_LRS = "Premium_LRS"
Specifies the storage account type for the managed disk. Possible values are: Standard_LRS or Premium_LRS.
62598fbf796e427e5384e9b1
class NamedPackage: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def installAs(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def forRequirements(self, versions): <NEW_LINE> <INDENT> return "{0}=={1}".format(versions.getProperName(self.name), versions[self.name])
Represents a package specified by Name
62598fbff548e778e596b7c3
class DbTypeTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_type_is_always_array(self): <NEW_LINE> <INDENT> f = ArrayField() <NEW_LINE> setattr(f, '_type', 'int') <NEW_LINE> self.assertIn('[]', f.db_type(None)) <NEW_LINE> <DEDENT> def test_respects_type_of_class(self): <NEW_LINE> <INDENT> custom_type = 'int' <NEW_LINE> f = ArrayField() <NEW_LINE> setattr(f, '_type', custom_type) <NEW_LINE> self.assertIn(custom_type, f.db_type(None))
Tests for the db_type.
62598fbfaad79263cf42e9f1
class StunThrower(ThrowerAnt): <NEW_LINE> <INDENT> name = 'Stun' <NEW_LINE> implemented = False <NEW_LINE> food_cost = 6 <NEW_LINE> damage = 0 <NEW_LINE> def throw_at(self, target): <NEW_LINE> <INDENT> if target: <NEW_LINE> <INDENT> apply_effect(make_stun, target, 1)
ThrowerAnt that causes Stun on Bees.
62598fbf0fa83653e46f5101
class Aircraft: <NEW_LINE> <INDENT> def __init__(self, registration): <NEW_LINE> <INDENT> self._registration = registration <NEW_LINE> <DEDENT> def registration(self): <NEW_LINE> <INDENT> return self._registration <NEW_LINE> <DEDENT> def num_seats(self): <NEW_LINE> <INDENT> rows, row_seats = self.seating_plan() <NEW_LINE> return len(rows) * len(row_seats)
Aircraft base class
62598fbf4a966d76dd5ef0f1
class S3MainMenu(default.S3MainMenu): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def menu(cls): <NEW_LINE> <INDENT> main_menu = MM()( cls.menu_modules(), cls.menu_help(right=True), cls.menu_auth(right=True), cls.menu_lang(right=True), cls.menu_admin(right=True), cls.menu_gis(right=True) ) <NEW_LINE> return main_menu <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def menu_modules(cls): <NEW_LINE> <INDENT> return [ homepage(), homepage("project"), homepage("req", f="req")( MM("Fulfill Requests", f="req"), MM("Request Supplies", f="req", m="create", vars={"type": 1}), MM("Request People", f="req", m="create", vars={"type": 3}) ), MM("Locations", c="gis")( MM("Facilities", c="org", f="facility"), MM("Create a Facility", c="org", f="facility", m="create") ), MM("Contacts", c="hrm", f="staff")( MM("Staff", c="hrm", f="staff"), MM("Groups", c="hrm", f="group"), MM("Organizations", c="org", f="organisation"), MM("Networks", c="org", f="group"), ), MM("Resources", url="http://occupysandy.net/resources/coordination/")( MM("Assets", c="asset", f="asset", m="search"), MM("Inventory", c="inv", f="inv_item"), MM("Stock Counts", c="inv", f="adj"), MM("Shipments", c="inv", f="send") ), MM("Cases", c="assess", f="building")( MM("Building Assessments", f="building"), MM("Canvass", f="canvass"), ), MM("Survey", c="survey")( MM("Templates", f="template"), MM("Assessments", f="series"), MM("Import Templates", f="question_list", m="import"), ), ]
Custom Application Main Menu: The main menu consists of several sub-menus, each of which can be customized separately as a method of this class. The overall composition of the menu is defined in the menu() method, which can be customized as well: Function Sub-Menu Access to (standard) menu_modules() the modules menu the Eden modules menu_gis() the GIS menu GIS configurations menu_admin() the Admin menu System/User Administration menu_lang() the Language menu Selection of the GUI locale menu_auth() the User menu Login, Logout, User Profile menu_help() the Help menu Contact page, About page The standard uses the MM layout class for main menu items - but you can of course use a custom layout class which you define in layouts.py. Additional sub-menus can simply be defined as additional functions in this class, and then be included in the menu() method. Each sub-menu function returns a list of menu items, only the menu() function must return a layout class instance.
62598fbf283ffb24f3cf3aa1
class Xweathersensor(): <NEW_LINE> <INDENT> def __init__(self,drec,updateint,xid): <NEW_LINE> <INDENT> self.HEADER = 'time\ttemp\thumidity\tpressure\n' <NEW_LINE> self.sid = drec['sid'] <NEW_LINE> self.updateint = updateint <NEW_LINE> self.tdinit = time.strftime('%H%M%S_%d%m%Y') <NEW_LINE> self.outfname = '%s_%s_%d.xls' % (xid.split('.')[0],self.sid,self.updateint) <NEW_LINE> logging.debug('## using outfname = %s' % self.outfname) <NEW_LINE> fdat = drec['data'] <NEW_LINE> v,t,h,p = fdat['voltage'],fdat['temperature'],fdat['humidity'],fdat['pressure'] <NEW_LINE> if os.path.isfile(self.outfname): <NEW_LINE> <INDENT> self.fout = open(self.outfname,'a') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fout = open(self.outfname,'w') <NEW_LINE> self.fout.write(self.HEADER) <NEW_LINE> self.fout.flush() <NEW_LINE> <DEDENT> self.started = time.time() <NEW_LINE> <DEDENT> def writedat(self,jdat,dat): <NEW_LINE> <INDENT> v = jdat['voltage']/1000.0 <NEW_LINE> t = int(jdat['temperature'])/100.0 <NEW_LINE> h = int(jdat['humidity'])/100.0 <NEW_LINE> p = int(jdat['pressure'])/100.0 <NEW_LINE> dt = time.strftime('%Y%m%d_%H%M%S') <NEW_LINE> s = '%s\t%.1f\t%.1f\t%.1f\n' % (dt,t,h,p) <NEW_LINE> self.fout.write(s) <NEW_LINE> self.fout.flush()
class for xiaomi weather sensors - temp/hum/baro instantiate when detected methods to get latest data and write to a file example from detection: INFO:root:{'model': 'weather.v1', 'proto': '1.0.9', 'sid': '158d0002273666', 'short_id': 52719, 'data': {'voltage': 2905, 'temperature': '1815', 'humidity': '5888', 'pressure': '102190'}, 'raw_data': {'cmd': 'read_ack', 'model': 'weather.v1', 'sid': '158d0002273666', 'short_id': 52719, 'data': '{"voltage":2905,"temperature":"1815","humidity":"5888","pressure":"102190"}'}}
62598fbf60cbc95b0636455a
class PGdevice: <NEW_LINE> <INDENT> def __init__(self, device): <NEW_LINE> <INDENT> self.device = device <NEW_LINE> self.devid = pgopen(device) <NEW_LINE> if self.devid == 0: <NEW_LINE> <INDENT> raise Exception('Failed to open',device) <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.devid > 0: <NEW_LINE> <INDENT> pgslct(self.devid) <NEW_LINE> pgclos() <NEW_LINE> self.devid = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> warnings.warn('the plot device "{:s}" is already closed'.format(self.device)) <NEW_LINE> <DEDENT> <DEDENT> def select(self): <NEW_LINE> <INDENT> if self.devid > 0: <NEW_LINE> <INDENT> pgslct(self.devid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> warnings.warn('the plot device "{:s}" cannot be selected at it has been closed'.format(self.device)) <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self.devid > 0: <NEW_LINE> <INDENT> pgslct(self.devid) <NEW_LINE> pgclos()
Class to open a PGPLOT device which automatically closes it on exit from a program, when ctrl-C is hit or when deleted using its destructor. It also keeps tabs on the ID of the device making it easy to switch between multiple plots. Use of this class is optional. If you do want to use it, then rather than starting and ending a plot with: pgopen('/xs') . . . pgclos() say, you would write dev = PGdevice('/xs') . . . dev.close() although the explicit close can be left off as one will be issued automatically as soon as 'dev' goes out of scope. If you are plotting to multiple devices then 'select' as in 'dev.select()' makes it easy to direct plotting to a particular device. Attributes:: devid : (int) the integer identifier returned by pgopen. This is used to select the device when it is closed and on destruction. device : (string) the name used to open the device.
62598fbfa05bb46b3848aa89
@DataFrame.register_api(staticmethod, "from_periodic") <NEW_LINE> class PeriodicDataFrame(DataFrame): <NEW_LINE> <INDENT> def __init__(self, datafn=random_datablock, interval='500ms', dask=False, start=True, **kwargs): <NEW_LINE> <INDENT> if dask: <NEW_LINE> <INDENT> from streamz.dask import DaskStream <NEW_LINE> source = DaskStream() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> source = Source() <NEW_LINE> <DEDENT> self.loop = source.loop <NEW_LINE> self.interval = pd.Timedelta(interval).total_seconds() <NEW_LINE> self.source = source <NEW_LINE> self.continue_ = [False] <NEW_LINE> self.kwargs = kwargs <NEW_LINE> stream = self.source.map(lambda x: datafn(**x, **kwargs)) <NEW_LINE> example = datafn(last=pd.Timestamp.now(), now=pd.Timestamp.now(), **kwargs) <NEW_LINE> super(PeriodicDataFrame, self).__init__(stream, example) <NEW_LINE> if start: <NEW_LINE> <INDENT> self.start() <NEW_LINE> <DEDENT> <DEDENT> def start(self): <NEW_LINE> <INDENT> if not self.continue_[0]: <NEW_LINE> <INDENT> self.continue_[0] = True <NEW_LINE> self.loop.add_callback(self._cb, self.interval, self.source, self.continue_) <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.continue_[0] = False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> async def _cb(interval, source, continue_): <NEW_LINE> <INDENT> last = pd.Timestamp.now() <NEW_LINE> while continue_[0]: <NEW_LINE> <INDENT> await gen.sleep(interval) <NEW_LINE> now = pd.Timestamp.now() <NEW_LINE> await asyncio.gather(*source._emit(dict(last=last, now=now))) <NEW_LINE> last = now
A streaming dataframe using the asyncio ioloop to poll a callback fn Parameters ---------- datafn: callable Callback function accepting **kwargs and returning a pd.DataFrame. kwargs will include at least 'last' (pd.Timestamp.now() when datafn was last invoked), and 'now' (current pd.Timestamp.now()). interval: timedelta The time interval between new dataframes. dask: boolean If true, uses a DaskStream instead of a regular Source. **kwargs: Optional keyword arguments to be passed into the callback function. By default, returns a three-column random pd.DataFrame generated by the 'random_datablock' function. Example ------- >>> df = PeriodicDataFrame(interval='1s', datafn=random_datapoint) # doctest: +SKIP
62598fbf377c676e912f6e81
class MediaAndroid(test.Test): <NEW_LINE> <INDENT> test = media.Media <NEW_LINE> tag = 'android' <NEW_LINE> page_set = 'page_sets/tough_video_cases.json' <NEW_LINE> options = { 'page_label_filter_exclude': '4k,50fps'}
Obtains media metrics for key user scenarios on Android.
62598fbf7cff6e4e811b5c41
class ShortURI(ndb.Model): <NEW_LINE> <INDENT> uri = ndb.StringProperty() <NEW_LINE> create_date = ndb.DateProperty() <NEW_LINE> last_use_datetime = ndb.DateTimeProperty()
ShortURI
62598fbfdc8b845886d537d8
class FeatureSpecificCloudWatchLoggingTestRunner(CloudWatchLoggingTestRunner): <NEW_LINE> <INDENT> def _verify_log_stream_data(self, logs_state, expected_stream_index, stream): <NEW_LINE> <INDENT> if stream.get("logStreamName") not in expected_stream_index: <NEW_LINE> <INDENT> LOGGER.info("Skipping validation of %s's log stream data.", stream.get("logStreamName")) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOGGER.info("Validating %s log stream data.", stream.get("logStreamName")) <NEW_LINE> super()._verify_log_stream_data(logs_state, expected_stream_index, stream) <NEW_LINE> <DEDENT> <DEDENT> def verify_log_streams_exist(self, logs_state, expected_stream_index, observed_streams): <NEW_LINE> <INDENT> observed_stream_names = [stream.get("logStreamName") for stream in observed_streams] <NEW_LINE> assert_that(observed_stream_names).contains(*expected_stream_index) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def run_tests_for_feature(cls, cluster, scheduler, os, feature_key, region, shared_dir=DEFAULT_SHARED_DIR): <NEW_LINE> <INDENT> environ["AWS_DEFAULT_REGION"] = region <NEW_LINE> cluster_logs_state = CloudWatchLoggingClusterState( scheduler, os, cluster, feature_key, shared_dir ).get_logs_state() <NEW_LINE> test_runner = cls(_get_log_group_name_for_cluster(cluster.name)) <NEW_LINE> test_runner.run_tests(cluster_logs_state)
This class enables running CloudWatch logging tests for only logs specific to a certain feature.
62598fbf796e427e5384e9b3
class Docs(RSSSingleElement): <NEW_LINE> <INDENT> pass
A URL that points to the documentation for the format used in the RSS file Example: Docs('http://blogs.law.harvard.edu/tech/rss')
62598fbff548e778e596b7c4
class JitCore_Tcc(jitcore.JitCore): <NEW_LINE> <INDENT> def __init__(self, ir_arch, bs=None): <NEW_LINE> <INDENT> super(JitCore_Tcc, self).__init__(ir_arch, bs) <NEW_LINE> self.resolver = resolver() <NEW_LINE> self.exec_wrapper = Jittcc.tcc_exec_bloc <NEW_LINE> self.tcc_states =[] <NEW_LINE> self.ir_arch = ir_arch <NEW_LINE> <DEDENT> def load(self): <NEW_LINE> <INDENT> lib_dir = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> libs = [] <NEW_LINE> libs.append(os.path.join(lib_dir, 'arch/JitCore_%s.so' % (self.ir_arch.arch.name))) <NEW_LINE> libs = ';'.join(libs) <NEW_LINE> jittcc_path = Jittcc.__file__ <NEW_LINE> include_dir = os.path.dirname(jittcc_path) <NEW_LINE> include_dir += ";" + os.path.join(include_dir, "arch") <NEW_LINE> p = Popen(["cc", "-Wp,-v", "-E", "-"], stdout=PIPE, stderr=PIPE, stdin=PIPE) <NEW_LINE> p.stdin.close() <NEW_LINE> include_files = p.stderr.read().split('\n') <NEW_LINE> include_files = [x[1:] for x in include_files if x.startswith(' /usr/include')] <NEW_LINE> include_files += [include_dir, get_python_inc()] <NEW_LINE> include_files = ";".join(include_files) <NEW_LINE> Jittcc.tcc_set_emul_lib_path(include_files, libs) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> for tcc_state in self.tcc_states: <NEW_LINE> <INDENT> Jittcc.tcc_end(tcc_state) <NEW_LINE> <DEDENT> <DEDENT> def jitirblocs(self, label, irblocs): <NEW_LINE> <INDENT> f_name = "bloc_%s" % label.name <NEW_LINE> f_declaration = 'void %s(block_id * BlockDst, vm_cpu_t* vmcpu, vm_mngr_t* vm_mngr)' % f_name <NEW_LINE> out = irblocs2C(self.ir_arch, self.resolver, label, irblocs, gen_exception_code=True, log_mn=self.log_mn, log_regs=self.log_regs) <NEW_LINE> out = [f_declaration + '{'] + out + ['}\n'] <NEW_LINE> c_code = out <NEW_LINE> func_code = gen_C_source(self.ir_arch, c_code) <NEW_LINE> self.jitcount += 1 <NEW_LINE> tcc_state, mcode = jit_tcc_compil(f_name, func_code) <NEW_LINE> self.tcc_states.append(tcc_state) <NEW_LINE> jcode = jit_tcc_code(mcode) <NEW_LINE> self.lbl2jitbloc[label.offset] = mcode <NEW_LINE> self.addr2obj[label.offset] = jcode <NEW_LINE> self.addr2objref[label.offset] = objref(jcode)
JiT management, using LibTCC as backend
62598fbf5fdd1c0f98e5e1b0
class Event: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.time = 0.0 <NEW_LINE> self._cuda = torch.cuda.is_available() <NEW_LINE> self._event_start: torch.cuda.Event | datetime <NEW_LINE> <DEDENT> def __enter__(self) -> Event: <NEW_LINE> <INDENT> if self._cuda: <NEW_LINE> <INDENT> self._event_start = torch.cuda.Event(enable_timing=True) <NEW_LINE> self._event_start.record() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._event_start = datetime.now() <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, *args: Any) -> None: <NEW_LINE> <INDENT> if self._cuda: <NEW_LINE> <INDENT> event_end = torch.cuda.Event(enable_timing=True) <NEW_LINE> event_end.record(stream=torch.cuda.current_stream()) <NEW_LINE> torch.cuda.synchronize() <NEW_LINE> assert isinstance(self._event_start, torch.cuda.Event) <NEW_LINE> self.time = self._event_start.elapsed_time(event_end) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert isinstance(self._event_start, datetime) <NEW_LINE> self.time = datetime.now().microsecond - self._event_start.microsecond <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return f"Event of duration: {self.time}"
Emulates torch.cuda.Event, but supports running on a CPU too. :example: >>> from ranzen.torch import Event >>> with Event() as event: >>> y = some_nn_module(x) >>> print(event.time)
62598fbf167d2b6e312b7194
class CaliperThreadTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_thread(self): <NEW_LINE> <INDENT> target_cmd = [ './ci_test_thread' ] <NEW_LINE> query_cmd = [ '../../src/tools/cali-query/cali-query', '-e' ] <NEW_LINE> caliper_config = { 'CALI_CONFIG_PROFILE' : 'thread-trace', 'CALI_RECORDER_FILENAME' : 'stdout', 'CALI_LOG_VERBOSITY' : '0' } <NEW_LINE> query_output = calitest.run_test_with_query(target_cmd, query_cmd, caliper_config) <NEW_LINE> snapshots = calitest.get_snapshots_from_text(query_output) <NEW_LINE> self.assertTrue(len(snapshots) >= 20) <NEW_LINE> self.assertTrue(calitest.has_snapshot_with_keys( snapshots, {'local', 'global', 'function'})) <NEW_LINE> self.assertTrue(calitest.has_snapshot_with_keys( snapshots, {'pthread.id', 'my_thread_id', 'global', 'event.end#function'})) <NEW_LINE> self.assertTrue(calitest.has_snapshot_with_attributes( snapshots, {'my_thread_id' : '49', 'function' : 'thread_proc', 'global' : '999' })) <NEW_LINE> self.assertTrue(calitest.has_snapshot_with_attributes( snapshots, { 'function' : 'main', 'local' : '99' }))
Caliper thread test case
62598fbf4c3428357761a4db
class DenseGCNBlock(Module): <NEW_LINE> <INDENT> def __init__(self, in_features, out_features, nbaselayer, withbn=True, withloop=True, activation=F.relu, dropout=True, aggrmethod="concat", dense=True): <NEW_LINE> <INDENT> super(DenseGCNBlock, self).__init__() <NEW_LINE> self.model = GraphBaseBlock(in_features=in_features, out_features=out_features, nbaselayer=nbaselayer, withbn=withbn, withloop=withloop, activation=activation, dropout=dropout, dense=True, aggrmethod=aggrmethod) <NEW_LINE> <DEDENT> def forward(self, input, adj): <NEW_LINE> <INDENT> return self.model.forward(input, adj) <NEW_LINE> <DEDENT> def get_outdim(self): <NEW_LINE> <INDENT> return self.model.get_outdim() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s %s (%d - [%d:%d] > %d)" % (self.__class__.__name__, self.aggrmethod, self.model.in_features, self.model.hiddendim, self.model.nhiddenlayer, self.model.out_features)
The multiple layer GCN with dense connection block.
62598fbf283ffb24f3cf3aa2
class RemoteTarget(luigi.target.FileSystemTarget): <NEW_LINE> <INDENT> def __init__( self, path, host, format=None, username=None, password=None, port=None, mtime=None, tls=False, timeout=60, sftp=False, pysftp_conn_kwargs=None ): <NEW_LINE> <INDENT> if format is None: <NEW_LINE> <INDENT> format = luigi.format.get_default_format() <NEW_LINE> <DEDENT> self.path = path <NEW_LINE> self.mtime = mtime <NEW_LINE> self.format = format <NEW_LINE> self.tls = tls <NEW_LINE> self.timeout = timeout <NEW_LINE> self.sftp = sftp <NEW_LINE> self._fs = RemoteFileSystem(host, username, password, port, tls, timeout, sftp, pysftp_conn_kwargs) <NEW_LINE> <DEDENT> @property <NEW_LINE> def fs(self): <NEW_LINE> <INDENT> return self._fs <NEW_LINE> <DEDENT> def open(self, mode): <NEW_LINE> <INDENT> if mode == 'w': <NEW_LINE> <INDENT> return self.format.pipe_writer(AtomicFtpFile(self._fs, self.path)) <NEW_LINE> <DEDENT> elif mode == 'r': <NEW_LINE> <INDENT> temp_dir = os.path.join(tempfile.gettempdir(), 'luigi-contrib-ftp') <NEW_LINE> self.__tmp_path = temp_dir + '/' + self.path.lstrip('/') + '-luigi-tmp-%09d' % random.randrange(0, 1e10) <NEW_LINE> self._fs.get(self.path, self.__tmp_path) <NEW_LINE> return self.format.pipe_reader( FileWrapper(io.BufferedReader(io.FileIO(self.__tmp_path, 'r'))) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception("mode must be 'r' or 'w' (got: %s)" % mode) <NEW_LINE> <DEDENT> <DEDENT> def exists(self): <NEW_LINE> <INDENT> return self.fs.exists(self.path, self.mtime) <NEW_LINE> <DEDENT> def put(self, local_path, atomic=True): <NEW_LINE> <INDENT> self.fs.put(local_path, self.path, atomic) <NEW_LINE> <DEDENT> def get(self, local_path): <NEW_LINE> <INDENT> self.fs.get(self.path, local_path)
Target used for reading from remote files. The target is implemented using ssh commands streaming data over the network.
62598fbf56ac1b37e630240c
class Base(object): <NEW_LINE> <INDENT> def __init__(self, pull, fret, **metadata): <NEW_LINE> <INDENT> self.fec = pull <NEW_LINE> self.fret = fret <NEW_LINE> self.metadata = pull.metadata <NEW_LINE> if fret: <NEW_LINE> <INDENT> self.metadata.update(fret.metadata) <NEW_LINE> <DEDENT> self.metadata.update(metadata) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if hasattr(self,'filename'): <NEW_LINE> <INDENT> return "<Experiment.%s from '%s'>" % (self.__class__.__name__, self.filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(Base,self).__repr__() <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() <NEW_LINE> <DEDENT> def plot(self): <NEW_LINE> <INDENT> raise NotImplementedError
.fret .f .ext and other meta-data (sample rate, pull speeds, )
62598fbf1f5feb6acb162e3f
class MainMustBuy(Main): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'axf_mustbuy'
首页必买:axf_mustbuy(img,name,trackid)
62598fbfa219f33f346c6a26
class credentials: <NEW_LINE> <INDENT> credentials_list = [] <NEW_LINE> def __init__(self,name,username,password): <NEW_LINE> <INDENT> self.platform_name = name <NEW_LINE> self.user_name = username <NEW_LINE> self.user_email = email <NEW_LINE> self.password = password <NEW_LINE> <DEDENT> def save_credentials(self): <NEW_LINE> <INDENT> credentials.credentials_list.append(self) <NEW_LINE> <DEDENT> def delete_credentials(self): <NEW_LINE> <INDENT> credentials.credentials_list.remove(self) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def find_credentials_by_platform_name(cls,username): <NEW_LINE> <INDENT> for credential in cls.credentials_list: <NEW_LINE> <INDENT> if credential.username == username: <NEW_LINE> <INDENT> return credential <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def credential_exists(cls,username): <NEW_LINE> <INDENT> for credential in cls.credentials_list: <NEW_LINE> <INDENT> if credential.username == username: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def display_all_credentials(cls): <NEW_LINE> <INDENT> return cls.credentials_list
class to save the user class information
62598fbf67a9b606de5461ea
class OBJECT_OT_export_dwn(Operator, ExportHelper): <NEW_LINE> <INDENT> bl_idname = "object.export_dwn" <NEW_LINE> bl_label = "Dawn Toolbox Export" <NEW_LINE> bl_options = {"REGISTER", "UNDO"} <NEW_LINE> filename_ext = ".dwn" <NEW_LINE> filter_glob: bpy.props.StringProperty( default="*.dwn", options={"HIDDEN"}, maxlen=255) <NEW_LINE> should_export_selected_only: bpy.props.BoolProperty( name="Selected only", description="Export selected mesh items only", default=True) <NEW_LINE> def execute(self, context: BpyContext): <NEW_LINE> <INDENT> if bpy.ops.object.mode_set.poll(): <NEW_LINE> <INDENT> bpy.ops.object.mode_set(mode="OBJECT") <NEW_LINE> <DEDENT> objects = (context.selected_objects if self.should_export_selected_only else context.scene.objects) <NEW_LINE> save_dwn(objects, self.filepath) <NEW_LINE> return {"FINISHED"}
.dwn file export addon
62598fbf63d6d428bbee29d1
class RegisterException(DefaultPyshellException): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> DefaultPyshellException.__init__(self, value, USER_ERROR)
This exception is used in every methods the user can use to register element in an addon. It can also be used in any method used to parameterize a loader in an addon.
62598fbf3d592f4c4edbb0dc
@zope.interface.implementer(interfaces.ITerms) <NEW_LINE> class CollectionTermsSource(SourceTerms): <NEW_LINE> <INDENT> zope.component.adapts( zope.interface.Interface, interfaces.IFormLayer, zope.interface.Interface, zope.schema.interfaces.ICollection, zope.schema.interfaces.IIterableSource, interfaces.IWidget)
ITerms adapter for zope.schema.ICollection based implementations using source.
62598fbf2c8b7c6e89bd39e0
class Week: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.days: List[WorkDay] = [WorkDay(i) for i in range(7)]
每周
62598fbfa8370b77170f0601
class CatalogHandler(BaseHandler): <NEW_LINE> <INDENT> def get(self, key=None): <NEW_LINE> <INDENT> if not key: <NEW_LINE> <INDENT> self.params['catalog'] = Category.dump_cat() <NEW_LINE> logging.info(self.params['catalog']) <NEW_LINE> self.render('catalog.html', **self.params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = ndb.Key(urlsafe=key) <NEW_LINE> try: <NEW_LINE> <INDENT> prod = p.get() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.abort(404) <NEW_LINE> <DEDENT> self.params.update(prod.to_dict()) <NEW_LINE> self.render('listing.html', **self.params)
Create addresses
62598fbf23849d37ff8512d3
class LibShrink(Package): <NEW_LINE> <INDENT> git_url = 'https://github.com/vusec/libshrink.git' <NEW_LINE> def __init__(self, addrspace_bits: int, commit = 'master', debug = False): <NEW_LINE> <INDENT> self.addrspace_bits = addrspace_bits <NEW_LINE> self.commit = commit <NEW_LINE> self.debug = debug <NEW_LINE> <DEDENT> def ident(self): <NEW_LINE> <INDENT> return 'libshrink-%d' % self.addrspace_bits <NEW_LINE> <DEDENT> def dependencies(self): <NEW_LINE> <INDENT> yield Prelink('209') <NEW_LINE> yield PatchElf('0.9') <NEW_LINE> yield PyElfTools('0.24', '2.7') <NEW_LINE> <DEDENT> def fetch(self, ctx): <NEW_LINE> <INDENT> run(ctx, ['git', 'clone', self.git_url, 'src']) <NEW_LINE> os.chdir('src') <NEW_LINE> run(ctx, ['git', 'checkout', self.commit]) <NEW_LINE> <DEDENT> def build(self, ctx): <NEW_LINE> <INDENT> os.chdir('src') <NEW_LINE> run(ctx, ['make', '-j%d' % ctx.jobs, 'OBJDIR=' + self.path(ctx, 'obj'), 'DEBUG=' + ('1' if self.debug else '0')]) <NEW_LINE> <DEDENT> def install(self, ctx): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def is_fetched(self, ctx): <NEW_LINE> <INDENT> return os.path.exists('src') <NEW_LINE> <DEDENT> def is_built(self, ctx): <NEW_LINE> <INDENT> return os.path.exists('obj/libshrink-static.a') and os.path.exists('obj/libshrink-preload.so') <NEW_LINE> <DEDENT> def is_installed(self, ctx): <NEW_LINE> <INDENT> return self.is_built(ctx) <NEW_LINE> <DEDENT> def configure(self, ctx: Namespace, static=True): <NEW_LINE> <INDENT> if static: <NEW_LINE> <INDENT> ctx.ldflags += [ '-L' + self.path(ctx, 'obj'), '-Wl,-whole-archive', '-lshrink-static', '-Wl,-no-whole-archive', '-ldl' ] <NEW_LINE> ctx.hooks.post_build += [self._prelink_binary, self._fix_preinit] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError('libshrink does not have dynamic library support') <NEW_LINE> <DEDENT> <DEDENT> def _prelink_binary(self, ctx, binary): <NEW_LINE> <INDENT> libpath = ctx.runenv.join_paths().get('LD_LIBRARY_PATH', '') <NEW_LINE> run(ctx, [ self.path(ctx, 'src/prelink_binary.py'), '--set-rpath', '--in-place', '--static-lib', '--out-dir', 'prelink-' + os.path.basename(binary), '--library-path', libpath, '--addrspace-bits', self.addrspace_bits, binary ]) <NEW_LINE> <DEDENT> def _fix_preinit(self, ctx, binary): <NEW_LINE> <INDENT> run(ctx, [ self.path(ctx, 'src/fix_preinit.py'), '--preinit-name', '__shrinkaddrspace_preinit', binary ]) <NEW_LINE> <DEDENT> def run_wrapper(self, ctx: Namespace) -> str: <NEW_LINE> <INDENT> return self.path(ctx, 'src/rpath_wrapper.sh')
Dependency package for `libshrink <https://github.com/vusec/libshrink>`_. Libshrink shrinks the application address space to a maximum number of bits. It moves the stack and TLS to a memory region that is within the allowed bitrange, and prelinks all shared libraries as well so that they do not exceed the address space limitations. It also defines a :func:`run_wrapper` that should be put in ``ctx.target_run_wrapper`` by an instance that uses libshrink. :identifier: libshrink-<addrspace_bits> :param addrspace_bits: maximum number of nonzero bits in any pointer :param commit: branch or commit to clone :param debug: whether to compile with debug symbols
62598fbf099cdd3c636754f2
class Filter(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.conversation_id = None <NEW_LINE> self.sender = None <NEW_LINE> self.performative = None <NEW_LINE> self.protocol = None <NEW_LINE> <DEDENT> def set_sender(self, aid): <NEW_LINE> <INDENT> self.sender = aid <NEW_LINE> <DEDENT> def set_performative(self, performative): <NEW_LINE> <INDENT> self.performative = performative <NEW_LINE> <DEDENT> def set_conversation_id(self, conversation_id): <NEW_LINE> <INDENT> self.conversation_id = conversation_id <NEW_LINE> <DEDENT> def set_protocol(self, protocol): <NEW_LINE> <INDENT> self.protocol = protocol <NEW_LINE> <DEDENT> def filter(self, message): <NEW_LINE> <INDENT> state = True <NEW_LINE> if self.conversation_id != None and self.conversation_id != message.conversation_id: <NEW_LINE> <INDENT> state = False <NEW_LINE> <DEDENT> if self.sender != None and self.sender != message.sender: <NEW_LINE> <INDENT> state = False <NEW_LINE> <DEDENT> if self.performative != None and self.performative != message.performative: <NEW_LINE> <INDENT> state = False <NEW_LINE> <DEDENT> if self.protocol != None and self.protocol != message.protocol: <NEW_LINE> <INDENT> state = False <NEW_LINE> <DEDENT> return state
This class instantiates a filter object. The filter has the purpose of selecting messages with pre established attributes in the filter object
62598fbf66673b3332c305f3
class Report(object): <NEW_LINE> <INDENT> def __init__(self, jpush, zone = None): <NEW_LINE> <INDENT> self._jpush = jpush <NEW_LINE> self.zone = zone or jpush.zone <NEW_LINE> <DEDENT> def send(self, method, url, body = None, content_type=None, version=3, params = None): <NEW_LINE> <INDENT> response = self._jpush._request(method, body,url,content_type,version=3, params = params) <NEW_LINE> return ReportResponse(response) <NEW_LINE> <DEDENT> def get_received(self,msg_ids): <NEW_LINE> <INDENT> url = common.get_url('report', self.zone) + 'received' <NEW_LINE> params = { 'msg_ids': msg_ids } <NEW_LINE> received = self.send("GET", url, params = params) <NEW_LINE> return received <NEW_LINE> <DEDENT> def get_messages(self, msg_ids): <NEW_LINE> <INDENT> url = common.get_url('report', self.zone) + 'messages' <NEW_LINE> params = { 'msg_ids': msg_ids } <NEW_LINE> messages = self.send("GET", url, params = params) <NEW_LINE> return messages <NEW_LINE> <DEDENT> def get_users(self, time_unit,start,duration): <NEW_LINE> <INDENT> url = common.get_url('report', self.zone) + 'users' <NEW_LINE> params = { 'time_unit': time_unit, 'start': start, 'duration': duration } <NEW_LINE> users = self.send("GET", url, params = params) <NEW_LINE> return users
JPush Report API V3
62598fbfa219f33f346c6a28
class CustomIndexDashboard(Dashboard): <NEW_LINE> <INDENT> def init_with_context(self, context): <NEW_LINE> <INDENT> site_name = get_admin_site_name(context) <NEW_LINE> self.children.append(modules.AppList( _('AppList: Applications'), collapsible=True, column=1, css_classes=('collapse closed',), exclude=('django.contrib.*',), )) <NEW_LINE> self.children.append(modules.ModelList( _('ModelList: Administration'), column=1, collapsible=True, models=('django.contrib.*',), )) <NEW_LINE> self.children.append(modules.LinkList( _('Scraping Management'), column=2, children=[ { 'title': _('Scrape Legislative Periods'), 'url': '/admin/scrape/llp', 'external': False, }, { 'title': _('Scrape Persons'), 'url': '/admin/scrape/persons', 'external': False, }, { 'title': _('Scrape Persons/Administrations'), 'url': '/admin/scrape/administrations', 'external': False, }, { 'title': _('Scrape Persons/Audit Office Presidents'), 'url': '/admin/scrape/auditors', 'external': False, }, { 'title': _('Scrape Pre-Laws'), 'url': '/admin/scrape/pre_laws', 'external': False, }, { 'title': _('Scrape Laws'), 'url': '/admin/scrape/laws', 'external': False, }, { 'title': _('Scrape Inquiries'), 'url': '/admin/scrape/inquiries', 'external': False, }, { 'title': _('Scrape Petitions'), 'url': '/admin/scrape/petitions', 'external': False, }, { 'title': _('Scrape Debates/Statements'), 'url': '/admin/scrape/debates', 'external': False, }, ] )) <NEW_LINE> self.children.append(modules.LinkList( _('ElasticSearch'), column=2, children=[ { 'title': _('Update ElasticSearch Index'), 'url': '/admin/elastic/update', 'external': False, }, ] )) <NEW_LINE> self.children.append(modules.RecentActions( _('Recent Actions'), limit=5, collapsible=True, column=2, ))
Custom index dashboard for www.
62598fbf851cf427c66b84d7