code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@Vows.batch <NEW_LINE> class AlgNoneVerification(Vows.Context): <NEW_LINE> <INDENT> def topic(self): <NEW_LINE> <INDENT> return jwt_alg_none <NEW_LINE> <DEDENT> class VerifyJWTNoPublicKeyNoneAllowed(Vows.Context): <NEW_LINE> <INDENT> def topic(self, topic): <NEW_LINE> <INDENT> return jwt.verify_jwt(topic, None, ['none']) <NEW_LINE> <DEDENT> def token_should_verify(self, r): <NEW_LINE> <INDENT> expect(r).to_be_instance_of(tuple) <NEW_LINE> <DEDENT> <DEDENT> class VerifyJWTPublicKeyNoneAllowed(Vows.Context): <NEW_LINE> <INDENT> @Vows.capture_error <NEW_LINE> def topic(self, topic): <NEW_LINE> <INDENT> return jwt.verify_jwt(topic, JWK(kty='oct', k=base64url_encode('anysecrethere')), ['none']) <NEW_LINE> <DEDENT> def token_should_not_verify(self, r): <NEW_LINE> <INDENT> expect(r).to_be_an_error() <NEW_LINE> expect([ 'Verification failed for all signatures[\'Failed: [InvalidJWSSignature(\\\'Verification failed {InvalidSignature(\\\\\\\'The "none" signature cannot be verified\\\\\\\',)}\\\',)]\']', 'Verification failed for all signatures[\'Failed: [InvalidJWSSignature(\\\'Verification failed {InvalidSignature(\\\\\\\'The "none" signature cannot be verified\\\\\\\')}\\\')]\']', 'Verification failed for all signatures["Failed: [InvalidJWSSignature(\'Verification failed\')]"]', 'Verification failed for all signatures["Failed: [InvalidJWSSignature(\'Verification failed\',)]"]' ]).to_include(str(r)) <NEW_LINE> <DEDENT> <DEDENT> class VerifyJWTPublicKeyNoneNotAllowed(Vows.Context): <NEW_LINE> <INDENT> @Vows.capture_error <NEW_LINE> def topic(self, topic): <NEW_LINE> <INDENT> return jwt.verify_jwt(topic, JWK(kty='oct', k=base64url_encode('anysecrethere'))) <NEW_LINE> <DEDENT> def token_should_fail_to_verify_when_pub_key_specified(self, r): <NEW_LINE> <INDENT> expect(r).to_be_an_error() <NEW_LINE> expect(str(r)).to_equal('algorithm not allowed: none') <NEW_LINE> <DEDENT> <DEDENT> class VerifyJWTNoPublicKeyNoneNotAllowed(Vows.Context): <NEW_LINE> <INDENT> @Vows.capture_error <NEW_LINE> def topic(self, topic): <NEW_LINE> <INDENT> return jwt.verify_jwt(topic) <NEW_LINE> <DEDENT> def token_should_fail_to_verify_when_pub_key_specified(self, r): <NEW_LINE> <INDENT> expect(r).to_be_an_error() <NEW_LINE> expect(str(r)).to_equal('algorithm not allowed: none')
Check we get an error when verifying token that has alg none with a public key
6259906e97e22403b383c76b
class QueueController(RoutingController): <NEW_LINE> <INDENT> _resource_name = 'queue' <NEW_LINE> def __init__(self, shard_catalog): <NEW_LINE> <INDENT> super(QueueController, self).__init__(shard_catalog) <NEW_LINE> self._lookup = self._shard_catalog.lookup <NEW_LINE> <DEDENT> def list(self, project=None, marker=None, limit=storage.DEFAULT_QUEUES_PER_PAGE, detailed=False): <NEW_LINE> <INDENT> def all_pages(): <NEW_LINE> <INDENT> for shard in self._shard_catalog._shards_ctrl.list(limit=0): <NEW_LINE> <INDENT> yield next(self._shard_catalog.get_driver(shard['name']) .queue_controller.list( project=project, marker=marker, limit=limit, detailed=detailed)) <NEW_LINE> <DEDENT> <DEDENT> ls = heapq.merge(*[ utils.keyify('name', page) for page in all_pages() ]) <NEW_LINE> marker_name = {} <NEW_LINE> def it(): <NEW_LINE> <INDENT> for queue_cmp in itertools.islice(ls, limit): <NEW_LINE> <INDENT> marker_name['next'] = queue_cmp.obj['name'] <NEW_LINE> yield queue_cmp.obj <NEW_LINE> <DEDENT> <DEDENT> yield it() <NEW_LINE> yield marker_name['next'] <NEW_LINE> <DEDENT> def create(self, name, project=None): <NEW_LINE> <INDENT> self._shard_catalog.register(name, project) <NEW_LINE> target = self._lookup(name, project) <NEW_LINE> if not target: <NEW_LINE> <INDENT> raise RuntimeError('Failed to register queue') <NEW_LINE> <DEDENT> return target.queue_controller.create(name, project) <NEW_LINE> <DEDENT> def delete(self, name, project=None): <NEW_LINE> <INDENT> target = self._lookup(name, project) <NEW_LINE> if target: <NEW_LINE> <INDENT> control = target.queue_controller <NEW_LINE> self._shard_catalog.deregister(name, project) <NEW_LINE> ret = control.delete(name, project) <NEW_LINE> return ret <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def exists(self, name, project=None, **kwargs): <NEW_LINE> <INDENT> target = self._lookup(name, project) <NEW_LINE> if target: <NEW_LINE> <INDENT> control = target.queue_controller <NEW_LINE> return control.exists(name, project=project) <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def get_metadata(self, name, project=None): <NEW_LINE> <INDENT> target = self._lookup(name, project) <NEW_LINE> if target: <NEW_LINE> <INDENT> control = target.queue_controller <NEW_LINE> return control.get_metadata(name, project=project) <NEW_LINE> <DEDENT> raise errors.QueueDoesNotExist(name, project) <NEW_LINE> <DEDENT> def set_metadata(self, name, metadata, project=None): <NEW_LINE> <INDENT> target = self._lookup(name, project) <NEW_LINE> if target: <NEW_LINE> <INDENT> control = target.queue_controller <NEW_LINE> return control.set_metadata(name, metadata=metadata, project=project) <NEW_LINE> <DEDENT> raise errors.QueueDoesNotExist(name, project) <NEW_LINE> <DEDENT> def stats(self, name, project=None): <NEW_LINE> <INDENT> target = self._lookup(name, project) <NEW_LINE> if target: <NEW_LINE> <INDENT> control = target.queue_controller <NEW_LINE> return control.stats(name, project=project) <NEW_LINE> <DEDENT> raise errors.QueueDoesNotExist(name, project)
Controller to facilitate special processing for queue operations.
6259906e01c39578d7f14368
class intSet(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.vals = [] <NEW_LINE> <DEDENT> def insert(self, e): <NEW_LINE> <INDENT> if not e in self.vals: <NEW_LINE> <INDENT> self.vals.append(e) <NEW_LINE> <DEDENT> <DEDENT> def member(self, e): <NEW_LINE> <INDENT> return e in self.vals <NEW_LINE> <DEDENT> def remove(self, e): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.vals.remove(e) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError(str(e) + ' not found') <NEW_LINE> <DEDENT> <DEDENT> def intersect(self, other): <NEW_LINE> <INDENT> new_intSet = intSet() <NEW_LINE> for x in self.vals: <NEW_LINE> <INDENT> if x in other.vals: <NEW_LINE> <INDENT> new_intSet.insert(x) <NEW_LINE> <DEDENT> <DEDENT> return new_intSet <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.vals) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> self.vals.sort() <NEW_LINE> return '{' + ','.join([str(e) for e in self.vals]) + '}'
An intSet is a set of integers The value is represented by a list of ints, self.vals. Each int in the set occurs in self.vals exactly once.
6259906e1b99ca4002290169
class Node(object): <NEW_LINE> <INDENT> def __init__(self, data, next=None): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.next = next
Linked list node
6259906efff4ab517ebcf082
class Environment: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.things = [] <NEW_LINE> self.agents = [] <NEW_LINE> <DEDENT> def thing_classes(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def percept(self, agent): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def execute_action(self, agent, action): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def default_loction(self, thing): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def exogenous_change(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def is_done(self): <NEW_LINE> <INDENT> return not any(agent.is_alive() for agent in self.agents) <NEW_LINE> <DEDENT> def step(self): <NEW_LINE> <INDENT> if not self.is_done(): <NEW_LINE> <INDENT> actions = [] <NEW_LINE> for agent in self.agents: <NEW_LINE> <INDENT> if agent.alive: <NEW_LINE> <INDENT> actions.append(agent.program(self.percept(agent))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> actions.append("") <NEW_LINE> <DEDENT> for (agent, action) in zip(self.agents, actions): <NEW_LINE> <INDENT> self.execute_action(agent, action) <NEW_LINE> <DEDENT> self.exogenous_change() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def run(self, steps=1000): <NEW_LINE> <INDENT> for step in range(steps): <NEW_LINE> <INDENT> if self.is_done(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.step() <NEW_LINE> <DEDENT> <DEDENT> def list_things_at(self, location, tclass=Thing): <NEW_LINE> <INDENT> return [thing for thing in self.things if thing.location == location and isinstance(thing, tclass)] <NEW_LINE> <DEDENT> def some_things_at(self, location, tclass=Thing): <NEW_LINE> <INDENT> return self.list_things_at(location, tclass) != [] <NEW_LINE> <DEDENT> def add_thing(self, thing, location=None): <NEW_LINE> <INDENT> if not isinstance(thing, Thing): <NEW_LINE> <INDENT> thing = Agent(thing) <NEW_LINE> <DEDENT> if thing in self.things: <NEW_LINE> <INDENT> print("Cann't add the same thing twice") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> thing.location = location if location is not None else self.default_loction( thing) <NEW_LINE> self.things.append(thing) <NEW_LINE> if isinstance(thing, Agent): <NEW_LINE> <INDENT> thing.performance = 0 <NEW_LINE> self.agents.append(thing) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def delete_thing(self, thing): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.things.remove(thing) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> print(" in Environment delete_thing") <NEW_LINE> print(" Thing to be removed: {} at {}".format(thing, thing.loation)) <NEW_LINE> print(" from list:{}".format( [(thing, thing.location) for thing in self.things])) <NEW_LINE> <DEDENT> if thing in self.agents: <NEW_LINE> <INDENT> self.agents.remove(thing)
Abstract class representing an Environment. 'Real' Environment classes inherit from this. Your Environment will typically need to implement: percept: Define the percept that an agent sees. execute_action: Define the effects of executing an action. Also update the agent.performance slot. The environment keeps a list of .things and .agents (which is a subset of .things). Each agent has a .performance slot, initialized to 0. Each thing has a .loation slot, even through some environments may not need this
6259906e76e4537e8c3f0deb
class BillingReport(object): <NEW_LINE> <INDENT> swagger_types = { 'created': 'int', 'id': 'str', 'last_known_failures': 'list[str]', 'statistics': 'dict(str, int)' } <NEW_LINE> attribute_map = { 'created': 'created', 'id': 'id', 'last_known_failures': 'last_known_failures', 'statistics': 'statistics' } <NEW_LINE> def __init__(self, created=None, id=None, last_known_failures=None, statistics=None): <NEW_LINE> <INDENT> self._created = None <NEW_LINE> self._id = None <NEW_LINE> self._last_known_failures = None <NEW_LINE> self._statistics = None <NEW_LINE> self.discriminator = None <NEW_LINE> if created is not None: <NEW_LINE> <INDENT> self.created = created <NEW_LINE> <DEDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> if last_known_failures is not None: <NEW_LINE> <INDENT> self.last_known_failures = last_known_failures <NEW_LINE> <DEDENT> if statistics is not None: <NEW_LINE> <INDENT> self.statistics = statistics <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def created(self): <NEW_LINE> <INDENT> return self._created <NEW_LINE> <DEDENT> @created.setter <NEW_LINE> def created(self, created): <NEW_LINE> <INDENT> self._created = created <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_known_failures(self): <NEW_LINE> <INDENT> return self._last_known_failures <NEW_LINE> <DEDENT> @last_known_failures.setter <NEW_LINE> def last_known_failures(self, last_known_failures): <NEW_LINE> <INDENT> self._last_known_failures = last_known_failures <NEW_LINE> <DEDENT> @property <NEW_LINE> def statistics(self): <NEW_LINE> <INDENT> return self._statistics <NEW_LINE> <DEDENT> @statistics.setter <NEW_LINE> def statistics(self, statistics): <NEW_LINE> <INDENT> self._statistics = statistics <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, BillingReport): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259906eadb09d7d5dc0bdd2
class test_Applogin_class(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> unittest.TestCase.setUp(self) <NEW_LINE> self.url="http://yun.geneedu.cn/passport/login.do" <NEW_LINE> <DEDENT> def test_Applogin(self): <NEW_LINE> <INDENT> self.data={ "appId":1, "deviceType":1, "password":"", "userName":"", "versionNum":9 } <NEW_LINE> self.r=requests.post(url=self.url,data=self.data) <NEW_LINE> print(self.r.text) <NEW_LINE> s=json.loads(self.r.text) <NEW_LINE> print(s['message']) <NEW_LINE> self.assertEqual(s['message'], '用户名和密码不能为空!', '测试用例执行未通过!!!') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> unittest.TestCase.tearDown(self)
测试类
6259906ea17c0f6771d5d7dd
class Team: <NEW_LINE> <INDENT> def __init__(self, team=None): <NEW_LINE> <INDENT> self.__my_team = [None, None, None, None, None, None] <NEW_LINE> if team: <NEW_LINE> <INDENT> i = 0 <NEW_LINE> for member in team: <NEW_LINE> <INDENT> self[i] = member <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self.__my_team[item] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> value = TeamMember(value) <NEW_LINE> <DEDENT> elif isinstance(value, pokedex.Pokemon): <NEW_LINE> <INDENT> value = TeamMember(poke=value) <NEW_LINE> <DEDENT> if isinstance(value, TeamMember): <NEW_LINE> <INDENT> self.__my_team[key] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError('value is not str, Pokemon or TeamMember')
A class that represents a team of pokemon
6259906e1f5feb6acb164458
class WePayClientError(WePayHTTPError): <NEW_LINE> <INDENT> pass
This is a 4xx type error, which, most of the time, carries important error information about the object of interest.
6259906e26068e7796d4e1a3
class CBRWError(Exception): <NEW_LINE> <INDENT> pass
Base exception raised by the CBRW class
6259906ea05bb46b3848bd61
class InRamStore(StoreInterface): <NEW_LINE> <INDENT> def delete(self, key): <NEW_LINE> <INDENT> self.pop(key, None) <NEW_LINE> <DEDENT> def wipe(self): <NEW_LINE> <INDENT> keys = list(self.keys()).copy() <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> self.delete(key)
The InRamStore inherits :class:`graphenestore.interfaces.StoreInterface` and extends it by two further calls for wipe and delete. The store is syntactically equivalent to a regular dictionary. .. warning:: If you are trying to obtain a value for a key that does **not** exist in the store, the library will **NOT** raise but return a ``None`` value. This represents the biggest difference to a regular ``dict`` class.
6259906e7047854f46340c1f
class SubjectLocalityType_(SamlBase): <NEW_LINE> <INDENT> c_tag = 'SubjectLocalityType' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = SamlBase.c_children.copy() <NEW_LINE> c_attributes = SamlBase.c_attributes.copy() <NEW_LINE> c_child_order = SamlBase.c_child_order[:] <NEW_LINE> c_cardinality = SamlBase.c_cardinality.copy() <NEW_LINE> c_attributes['Address'] = ('address', 'string', False) <NEW_LINE> c_attributes['DNSName'] = ('dns_name', 'string', False) <NEW_LINE> def __init__(self, address=None, dns_name=None, text=None, extension_elements=None, extension_attributes=None): <NEW_LINE> <INDENT> SamlBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) <NEW_LINE> self.address = address <NEW_LINE> self.dns_name = dns_name
The urn:oasis:names:tc:SAML:2.0:assertion:SubjectLocalityType element
6259906ebe8e80087fbc08f7
class JumptapRenderer(HtmlDataRenderer): <NEW_LINE> <INDENT> pass
Inheritance Hierarchy: JumptapRenderer => HtmlDataRenderer => BaseHtmlRenderer => BaseCreativeRenderer
6259906ebf627c535bcb2d33
class TestPageDeprecation(DefaultSiteTestCase, DeprecationTestCase): <NEW_LINE> <INDENT> def test_creator(self): <NEW_LINE> <INDENT> mainpage = self.get_mainpage() <NEW_LINE> creator = mainpage.getCreator() <NEW_LINE> self.assertEqual(creator, (mainpage.oldest_revision.user, mainpage.oldest_revision.timestamp.isoformat())) <NEW_LINE> self.assertIsInstance(creator[0], unicode) <NEW_LINE> self.assertIsInstance(creator[1], unicode) <NEW_LINE> self._ignore_unknown_warning_packages = True <NEW_LINE> self.assertDeprecation() <NEW_LINE> self._reset_messages() <NEW_LINE> if MediaWikiVersion(self.site.version()) >= MediaWikiVersion('1.16'): <NEW_LINE> <INDENT> self.assertIsInstance(mainpage.previous_revision_id, int) <NEW_LINE> self.assertEqual(mainpage.previous_revision_id, mainpage.latest_revision.parent_id) <NEW_LINE> self.assertDeprecation()
Test deprecation of Page attributes.
6259906e99cbb53fe6832750
class AbstractSubsystem(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=128, blank=True, db_index=True, unique=True, help_text='no spaces and unique') <NEW_LINE> displayName = models.CharField(max_length=128, blank=True) <NEW_LINE> group = models.ForeignKey(SubsystemGroup, null=True, blank=True, related_name="subsystems") <NEW_LINE> logFileUrl = models.CharField(max_length=512, blank=True) <NEW_LINE> warningThreshold = models.IntegerField(default=5, null=True, blank=True, help_text='in seconds') <NEW_LINE> failureThreshold = models.IntegerField(default=10, null=True, blank=True, help_text='in seconds') <NEW_LINE> refreshRate = models.IntegerField(default=1, null=True, blank=True, help_text='in seconds') <NEW_LINE> constantName = models.CharField(max_length=128, null=True, blank=True, help_text='constant name to look up the hostname') <NEW_LINE> active = models.BooleanField(null=False, blank=True, default=True) <NEW_LINE> def getTitle(self): <NEW_LINE> <INDENT> return self.displayName <NEW_LINE> <DEDENT> def getHostname(self): <NEW_LINE> <INDENT> constant = Constant.objects.get(name = self.constantName) <NEW_LINE> return constant.value <NEW_LINE> <DEDENT> def getStatus(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _cache = caches['default'] <NEW_LINE> result = json.loads(_cache.get(self.name)) <NEW_LINE> return result <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> subsystemStatus = SubsystemStatus(self.name) <NEW_LINE> return subsystemStatus.getStatus() <NEW_LINE> <DEDENT> <DEDENT> def toDict(self): <NEW_LINE> <INDENT> result = modelToDict(self) <NEW_LINE> return result <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = ['displayName']
Data quality, Video, etc. Each individual device.
6259906e9c8ee82313040dbc
class FilterModule(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def filters(): <NEW_LINE> <INDENT> return { 'bit_length_power_of_2': bit_length_power_of_2, 'netloc': get_netloc, 'netloc_no_port': get_netloc_no_port, 'netorigin': get_netorigin, 'string_2_int': string_2_int, 'pip_requirement_names': pip_requirement_names, 'pip_constraint_update': pip_constraint_update, 'splitlines': splitlines, 'filtered_list': filtered_list, 'git_link_parse': git_link_parse, 'git_link_parse_name': git_link_parse_name, 'deprecated': _deprecated }
Ansible jinja2 filters.
6259906e67a9b606de5476d7
class SpriteSheet(object): <NEW_LINE> <INDENT> def __init__(self, file): <NEW_LINE> <INDENT> self.sheet = load_alpha_image(SPRITES_FOLDER + file) <NEW_LINE> self.file = file <NEW_LINE> loaded_sheets.append(self) <NEW_LINE> <DEDENT> def get_image(self, rect): <NEW_LINE> <INDENT> return self.sheet.subsurface(rect) <NEW_LINE> <DEDENT> def get_images(self, rect_list): <NEW_LINE> <INDENT> return [self.get_image(rect) for rect in rect_list] <NEW_LINE> <DEDENT> def get_strip(self, rect, frames): <NEW_LINE> <INDENT> sprites = [ (rect[0] + rect[2] * x, rect[1], rect[2], rect[3]) for x in range(frames) ] <NEW_LINE> return self.get_images(sprites)
Contains the image of a sprite sheet and methods to extract sprites from it.
6259906e0c0af96317c57992
class Malware(Entity): <NEW_LINE> <INDENT> _collection_name = 'entities' <NEW_LINE> type = 'malware' <NEW_LINE> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._stix_object.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._stix_object.description <NEW_LINE> <DEDENT> @property <NEW_LINE> def kill_chain_phases(self): <NEW_LINE> <INDENT> return self._stix_object.kill_chain_phases
Malware Yeti object. Extends the Malware STIX2 definition.
6259906e55399d3f05627d8b
class Product(Operation): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Operation.__init__(self, 'product', 1, 1, leftparenthesis='<', rightparenthesis='>') <NEW_LINE> <DEDENT> def getreturntype(self, args): <NEW_LINE> <INDENT> newargs1 = [] <NEW_LINE> newargs = [] <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> newargs1.append(arg.type.args[1]) <NEW_LINE> <DEDENT> type1 = Application(cartesian_product, newargs1) <NEW_LINE> newargs.append(args[0].type.args[0]) <NEW_LINE> newargs.append(type1) <NEW_LINE> type = Application(functional_type, newargs) <NEW_LINE> return type <NEW_LINE> <DEDENT> def checkapplicationconstraints(self, args): <NEW_LINE> <INDENT> if len(args) < 2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> type = args[0].type.args[0] <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if arg.kind != 'element': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not arg.type.args[0].equals(type): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return True
Represents the product Operation, which can be applied to two or more 'elements'. It yields an 'element'. Note: Product should be thought of as functional product: the 'functions' (or rather: 'elements') to which it is applied should have a common domain. Attributes: See the attributes of the Operation base class.
6259906e56ac1b37e6303917
class Plan(BaseModel): <NEW_LINE> <INDENT> description = models.TextField(blank=True, null=True) <NEW_LINE> status = models.CharField(max_length=1, choices=PLAN_STATUS_TYPES, default='A') <NEW_LINE> date_activated = models.DateTimeField(blank=True, null=True, default=None) <NEW_LINE> date_inactivated = models.DateTimeField(blank=True, null=True, default=None) <NEW_LINE> date_deleted = models.DateTimeField(blank=True, null=True, default=None) <NEW_LINE> max_users = models.IntegerField(default=-1) <NEW_LINE> max_files = models.IntegerField(default=-1) <NEW_LINE> max_shares = models.IntegerField(default=-1) <NEW_LINE> max_file_size = models.IntegerField(default=-1) <NEW_LINE> branding = models.BooleanField(default=False) <NEW_LINE> encryption = models.BooleanField(default=True) <NEW_LINE> support_type = models.CharField(max_length=1, choices=SUPPORT_TYPES, default='0') <NEW_LINE> monthly_fee = models.DecimalField(max_digits=16, decimal_places=2, default=0.00) <NEW_LINE> trial_period = models.IntegerField(default=30) <NEW_LINE> notes = models.TextField(blank=True, null=True) <NEW_LINE> def user_count(self): <NEW_LINE> <INDENT> return self.subscriptions.count()
Define different plans. A plan should never be modified, only new plans added with revised parameters. - Max value of 0 = feature is disabled - Max value of -1 = unlimited
6259906e3539df3088ecdb05
class TranslateBase(compile_rule.CompileBase): <NEW_LINE> <INDENT> def __init__(self, lang=None): <NEW_LINE> <INDENT> self.lang = lang <NEW_LINE> <DEDENT> def translate(infile_name, outfile_lang_moentries_context): <NEW_LINE> <INDENT> raise NotImplementedError('Subclasses must implement translate') <NEW_LINE> <DEDENT> def build_many(self, outfile_infiles_changed_context): <NEW_LINE> <INDENT> infile_map = {} <NEW_LINE> mo_entries_map = {} <NEW_LINE> for (outfile, infiles, _, context) in outfile_infiles_changed_context: <NEW_LINE> <INDENT> assert len(infiles) == 2, infiles <NEW_LINE> if infiles[1] not in mo_entries_map: <NEW_LINE> <INDENT> with open(self.abspath(infiles[1])) as f: <NEW_LINE> <INDENT> mo_entries_map[infiles[1]] = cPickle.load(f) <NEW_LINE> <DEDENT> <DEDENT> lang = self.lang or context['{lang}'] <NEW_LINE> infile_map.setdefault(infiles[0], []).append( (outfile, lang, mo_entries_map[infiles[1]], context)) <NEW_LINE> <DEDENT> for (infile, outfile_lang_moentries_context) in infile_map.iteritems(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.translate(infile, outfile_lang_moentries_context) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> log.exception('FATAL ERROR building %s', outfile_lang_moentries_context[0][0]) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def split_outputs(self, outfile_infiles_changed_context, num_processes): <NEW_LINE> <INDENT> if num_processes == 1: <NEW_LINE> <INDENT> yield outfile_infiles_changed_context <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> infile_map = {} <NEW_LINE> for entry in outfile_infiles_changed_context: <NEW_LINE> <INDENT> infile = entry[1][0] <NEW_LINE> infile_map.setdefault(infile, []).append(entry) <NEW_LINE> <DEDENT> chunk_size = ((len(outfile_infiles_changed_context) - 1) / num_processes + 1) <NEW_LINE> chunk = [] <NEW_LINE> for entries in infile_map.itervalues(): <NEW_LINE> <INDENT> chunk.extend(entries) <NEW_LINE> if len(chunk) >= chunk_size: <NEW_LINE> <INDENT> yield chunk <NEW_LINE> chunk = [] <NEW_LINE> <DEDENT> <DEDENT> if chunk: <NEW_LINE> <INDENT> yield chunk <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _read_input(self, infile_name): <NEW_LINE> <INDENT> with open(self.abspath(infile_name)) as f: <NEW_LINE> <INDENT> return f.read().decode('utf-8') <NEW_LINE> <DEDENT> <DEDENT> def _write_output(self, infile_name, outfile_name, new_content): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(outfile_name) <NEW_LINE> <DEDENT> except (IOError, OSError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if new_content is None: <NEW_LINE> <INDENT> output_dir = os.path.dirname(self.abspath(outfile_name)) <NEW_LINE> symlink = os.path.relpath(self.abspath(infile_name), output_dir) <NEW_LINE> os.symlink(symlink, self.abspath(outfile_name)) <NEW_LINE> log.info("Creating symlink for translation (content unchanged)") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> with open(self.abspath(outfile_name), 'w') as f: <NEW_LINE> <INDENT> f.write(new_content.encode('utf-8'))
A compile rule for translating a file from one language to another. Compile-rules that derive from TranslateBase define a translate() routine rather than a build() or build_many() routine. These rules *must* have the following format for their input files: input[0]: the English file to translate input[1]: the small_mo.pickle file associated with input[0]
6259906eac7a0e7691f73d51
class invalid_capital_gain_exception(Exception): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return 'The input of capital gain is not a valid integer.'
Raise exception when the input of capital gain is not a valid integer.
6259906e4f88993c371f1154
@route("/mps") <NEW_LINE> class IndexHandler(BasicHandler): <NEW_LINE> <INDENT> def check_xsrf_cookie(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_error_html(self, status_code=500, **kwargs): <NEW_LINE> <INDENT> self.set_header("Content-Type", "application/xml;charset=utf-8") <NEW_LINE> if self.touser and self.fromuser: <NEW_LINE> <INDENT> reply = mpsmsg.reply_text(self.touser,self.fromuser,'回复h查看帮助。') <NEW_LINE> self.write(reply) <NEW_LINE> <DEDENT> <DEDENT> def check_signature(self): <NEW_LINE> <INDENT> signature = self.get_argument('signature', '') <NEW_LINE> timestamp = self.get_argument('timestamp', '') <NEW_LINE> nonce = self.get_argument('nonce', '') <NEW_LINE> tmparr = [self.settings['mps_token'], timestamp, nonce] <NEW_LINE> tmparr.sort() <NEW_LINE> tmpstr = ''.join(tmparr) <NEW_LINE> tmpstr = sha1(tmpstr.encode()).hexdigest() <NEW_LINE> return tmpstr == signature <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> echostr = self.get_argument('echostr', '') <NEW_LINE> if self.check_signature(): <NEW_LINE> <INDENT> self.write(echostr) <NEW_LINE> self.logging.info("Signature check success.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logging.warning("Signature check failed.") <NEW_LINE> <DEDENT> <DEDENT> @asynchronous <NEW_LINE> def post(self): <NEW_LINE> <INDENT> if not self.check_signature(): <NEW_LINE> <INDENT> self.logging.warning("Signature check failed.") <NEW_LINE> return <NEW_LINE> <DEDENT> self.set_header("Content-Type", "application/xml;charset=utf-8") <NEW_LINE> body = self.request.body <NEW_LINE> msg = mpsmsg.parse_msg(body) <NEW_LINE> if not msg: <NEW_LINE> <INDENT> self.logging.info('Empty message, ignored') <NEW_LINE> return <NEW_LINE> <DEDENT> self.logging.info('message type %s from %s with %s', msg.type, msg.fromuser, body.decode("utf-8")) <NEW_LINE> reply_msg = MsgProcess(msg, self).process() <NEW_LINE> self.logging.info('Replied to %s with "%s"', msg.fromuser, reply_msg) <NEW_LINE> self.write(reply_msg) <NEW_LINE> self.finish()
微信消息主要处理控制器
6259906ed486a94d0ba2d828
class PageOfAssetPolicy(object): <NEW_LINE> <INDENT> swagger_types = { 'links': 'list[Link]', 'page': 'PageInfo', 'resources': 'list[AssetPolicy]' } <NEW_LINE> attribute_map = { 'links': 'links', 'page': 'page', 'resources': 'resources' } <NEW_LINE> def __init__(self, links=None, page=None, resources=None): <NEW_LINE> <INDENT> self._links = None <NEW_LINE> self._page = None <NEW_LINE> self._resources = None <NEW_LINE> self.discriminator = None <NEW_LINE> if links is not None: <NEW_LINE> <INDENT> self.links = links <NEW_LINE> <DEDENT> if page is not None: <NEW_LINE> <INDENT> self.page = page <NEW_LINE> <DEDENT> if resources is not None: <NEW_LINE> <INDENT> self.resources = resources <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def links(self): <NEW_LINE> <INDENT> return self._links <NEW_LINE> <DEDENT> @links.setter <NEW_LINE> def links(self, links): <NEW_LINE> <INDENT> self._links = links <NEW_LINE> <DEDENT> @property <NEW_LINE> def page(self): <NEW_LINE> <INDENT> return self._page <NEW_LINE> <DEDENT> @page.setter <NEW_LINE> def page(self, page): <NEW_LINE> <INDENT> self._page = page <NEW_LINE> <DEDENT> @property <NEW_LINE> def resources(self): <NEW_LINE> <INDENT> return self._resources <NEW_LINE> <DEDENT> @resources.setter <NEW_LINE> def resources(self, resources): <NEW_LINE> <INDENT> self._resources = resources <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(PageOfAssetPolicy, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, PageOfAssetPolicy): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
6259906eaad79263cf43001e
class FileError(BoltError): <NEW_LINE> <INDENT> def __init__(self, in_name, message): <NEW_LINE> <INDENT> super(FileError, self).__init__(message) <NEW_LINE> self._in_name = (in_name and '%s' % in_name) or 'Unknown File' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self._in_name}: {self.message}'
An error that occurred while handling a file.
6259906efff4ab517ebcf084
class Login(MyScreen): <NEW_LINE> <INDENT> def login(self): <NEW_LINE> <INDENT> app = App.get_running_app() <NEW_LINE> try: <NEW_LINE> <INDENT> app.backend.login(self.ids.email.text, self.ids.password.text) <NEW_LINE> app.show(Home, True) <NEW_LINE> <DEDENT> except BackEndError as e: <NEW_LINE> <INDENT> Alert(title="Login Error", text=e.error) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> Alert(title="Login Error", text="Unexpected error: " + str(e)) <NEW_LINE> <DEDENT> <DEDENT> def register(self): <NEW_LINE> <INDENT> app = App.get_running_app() <NEW_LINE> try: <NEW_LINE> <INDENT> app.backend.register(self.ids.email.text, self.ids.password.text) <NEW_LINE> Alert(title="Register Success", text="Your account is successfully created.") <NEW_LINE> <DEDENT> except BackEndError as e: <NEW_LINE> <INDENT> Alert(title="Register Error", text=e.error) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> Alert(title="Register Error", text="Unexpected error: " + str(e))
Represent the screen to login
6259906eadb09d7d5dc0bdd4
class VariantField(ProtoField): <NEW_LINE> <INDENT> VARIANTS = frozenset([pmessages.Variant.DOUBLE, pmessages.Variant.FLOAT, pmessages.Variant.BOOL, pmessages.Variant.INT64, pmessages.Variant.UINT64, pmessages.Variant.SINT64, pmessages.Variant.INT32, pmessages.Variant.UINT32, pmessages.Variant.SINT32, pmessages.Variant.STRING, pmessages.Variant.BYTES, pmessages.Variant.MESSAGE, pmessages.Variant.ENUM]) <NEW_LINE> DEFAULT_VARIANT = pmessages.Variant.STRING <NEW_LINE> type = (int, long, bool, basestring, dict, pmessages.Message)
Field definition for a completely variant field. Allows containment of any valid Python value supported by Protobuf/ProtoRPC.
6259906ea17c0f6771d5d7de
class TestFieldOverrideSplitPerformance(FieldOverridePerformanceTestCase): <NEW_LINE> <INDENT> MODULESTORE = TEST_DATA_SPLIT_MODULESTORE <NEW_LINE> __test__ = True <NEW_LINE> TEST_DATA = { ('no_overrides', 1, True, False): (23, 4, 9), ('no_overrides', 2, True, False): (68, 19, 54), ('no_overrides', 3, True, False): (263, 84, 215), ('ccx', 1, True, False): (23, 4, 9), ('ccx', 2, True, False): (68, 19, 54), ('ccx', 3, True, False): (263, 84, 215), ('ccx', 1, True, True): (25, 4, 13), ('ccx', 2, True, True): (70, 19, 84), ('ccx', 3, True, True): (265, 84, 335), ('no_overrides', 1, False, False): (23, 4, 9), ('no_overrides', 2, False, False): (68, 19, 54), ('no_overrides', 3, False, False): (263, 84, 215), ('ccx', 1, False, False): (23, 4, 9), ('ccx', 2, False, False): (68, 19, 54), ('ccx', 3, False, False): (263, 84, 215), ('ccx', 1, False, True): (23, 4, 9), ('ccx', 2, False, True): (68, 19, 54), ('ccx', 3, False, True): (263, 84, 215), }
Test cases for instrumenting field overrides against the Split modulestore.
6259906e21bff66bcd7244d1
class SequenceIdentityDenominator(IntEnum): <NEW_LINE> <INDENT> SHORTER_LENGTH = 1 <NEW_LINE> NUM_ALIGNED_WITH_GAPS = 2 <NEW_LINE> NUM_ALIGNED_WITHOUT_GAPS = 3 <NEW_LINE> MEAN_LENGTH = 4 <NEW_LINE> OTHER = 5
The denominator used while calculating the sequence identity. One of these constants can be passed to :class:`SequenceIdentity`.
6259906ecb5e8a47e493cdb7
class CommonColumns(Base): <NEW_LINE> <INDENT> __abstract__ = True <NEW_LINE> _created = Column(DateTime) <NEW_LINE> _updated = Column(DateTime) <NEW_LINE> _etag = Column(String) <NEW_LINE> _id = Column(Integer, primary_key=True) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> h = hashlib.sha1() <NEW_LINE> self._etag = h.hexdigest() <NEW_LINE> super(CommonColumns, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def jsonify(self): <NEW_LINE> <INDENT> relationships = inspect(self.__class__).relationships.keys() <NEW_LINE> mapper = inspect(self) <NEW_LINE> attrs = [a.key for a in mapper.attrs if a.key not in relationships and a.key not in mapper.expired_attributes] <NEW_LINE> return dict([(c, getattr(self, c, None)) for c in attrs])
Master SQLAlchemy Model. All the SQL tables defined for the application should inherit from this class. It provides common columns such as _created, _updated and _id. WARNING: the _id column name does not respect Eve's setting for custom ID_FIELD.
6259906eb7558d5895464b67
class Angel(BasePlayer): <NEW_LINE> <INDENT> color = 'White' <NEW_LINE> def make_move(self, round): <NEW_LINE> <INDENT> return True
Player which always plays nice.
6259906e435de62698e9d670
class ProcLoadavg(SingleLineFile): <NEW_LINE> <INDENT> fields = (("load1", float), ("load5", float), ("load15", float))
Parse :file:`/proc/loadavg`.
6259906e8e7ae83300eea8fb
class SparseBinnedObjects(object): <NEW_LINE> <INDENT> def __init__(self, positioned_objects, gridsize=1): <NEW_LINE> <INDENT> self.gridsize = gridsize <NEW_LINE> self.reciproke = 1/gridsize <NEW_LINE> self.bins = {} <NEW_LINE> for positioned_object in positioned_objects: <NEW_LINE> <INDENT> indices = tuple(numpy.floor(positioned_object.coordinate*self.reciproke).astype(int)) <NEW_LINE> bin = self.bins.get(indices) <NEW_LINE> if bin is None: <NEW_LINE> <INDENT> bin = set() <NEW_LINE> self.bins[indices] = bin <NEW_LINE> <DEDENT> bin.add(positioned_object) <NEW_LINE> <DEDENT> <DEDENT> def yield_surrounding(self, r, deltas): <NEW_LINE> <INDENT> center = numpy.floor(r*self.reciproke).astype(int) <NEW_LINE> for delta in deltas: <NEW_LINE> <INDENT> bin = self.bins.get(tuple(center + delta)) <NEW_LINE> if bin is not None: <NEW_LINE> <INDENT> for positioned_object in bin: <NEW_LINE> <INDENT> yield bin, positioned_object
A SparseBinnedObjects instance divides 3D space into a sparse grid. Each cell in the grid is called a bin. Each bin can contain a set of Positioned objects. This implementation works with sparse bins: A bin is only created in memory when an object is encountered that belongs in that bin. All bins are uniquely defined by their indices i,j,k as defined in __init__.
6259906e55399d3f05627d8d
class FeedNotFoundError(Exception): <NEW_LINE> <INDENT> pass
Raised when page does not exist any feed
6259906e16aa5153ce401d45
class SessionModel(db.Model): <NEW_LINE> <INDENT> pdump = db.BlobProperty()
Contains session data. key_name is the session ID and pdump contains a pickled dictionary which maps session variables to their values.
6259906e99cbb53fe6832753
class DependencyKind(object): <NEW_LINE> <INDENT> undefined = 0 <NEW_LINE> http_only = 1 <NEW_LINE> http_any = 2 <NEW_LINE> sql = 3
Data contract class for type DependencyKind.
6259906e97e22403b383c76f
class DevfreqOutPower(Base): <NEW_LINE> <INDENT> name = "devfreq_out_power" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(DevfreqOutPower, self).__init__( unique_word="thermal_power_devfreq_limit:", ) <NEW_LINE> <DEDENT> def get_all_freqs(self): <NEW_LINE> <INDENT> return pd.DataFrame(self.data_frame["freq"] / 1000000)
Process de devfreq cooling device data regarding power2state in an ftrace dump
6259906e76e4537e8c3f0def
class Normalise(object): <NEW_LINE> <INDENT> def __init__(self, scale, mean, std, depth_scale=1.0): <NEW_LINE> <INDENT> self.scale = scale <NEW_LINE> self.mean = mean <NEW_LINE> self.std = std <NEW_LINE> self.depth_scale = depth_scale <NEW_LINE> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> sample["image"] = (self.scale * sample["image"] - self.mean) / self.std <NEW_LINE> if "depth" in sample: <NEW_LINE> <INDENT> sample["depth"] = sample["depth"] / self.depth_scale <NEW_LINE> <DEDENT> return sample
Normalise a tensor image with mean and standard deviation. Given mean: (R, G, B) and std: (R, G, B), will normalise each channel of the torch.*Tensor, i.e. channel = (scale * channel - mean) / std Args: scale (float): Scaling constant. mean (sequence): Sequence of means for R,G,B channels respecitvely. std (sequence): Sequence of standard deviations for R,G,B channels respecitvely. depth_scale (float): Depth divisor for depth annotations.
6259906ebaa26c4b54d50b15
class RandomColor(Operation): <NEW_LINE> <INDENT> def __init__(self, probability, min_factor, max_factor): <NEW_LINE> <INDENT> Operation.__init__(self, probability) <NEW_LINE> self.min_factor = min_factor <NEW_LINE> self.max_factor = max_factor <NEW_LINE> <DEDENT> def perform_operation(self, images): <NEW_LINE> <INDENT> factor = np.random.uniform(self.min_factor, self.max_factor) <NEW_LINE> def do(image): <NEW_LINE> <INDENT> image_enhancer_color = ImageEnhance.Color(image) <NEW_LINE> return image_enhancer_color.enhance(factor) <NEW_LINE> <DEDENT> return do(images)
This class is used to random change saturation of an image.
6259906e167d2b6e312b81c4
class export_task(): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> self.signature = args <NEW_LINE> <DEDENT> def __call__(self, m): <NEW_LINE> <INDENT> global _export_info_l <NEW_LINE> info = BfmMethodInfo(m, self.signature) <NEW_LINE> info.id = len(_export_info_l) <NEW_LINE> _export_info_l.append(info) <NEW_LINE> return m
Identifies a BFM-class method that can be called from the HDL
6259906e8a43f66fc4bf39ff
class CNN(CNNBase): <NEW_LINE> <INDENT> def __init__(self, mean, std, gpu, channel_list, dc_channel_list, ksize_list, dc_ksize_list, inter_list, last_list, pad_list): <NEW_LINE> <INDENT> super(CNN, self).__init__(mean, std, gpu) <NEW_LINE> if len(ksize_list) > 0 and len(dc_ksize_list) == 0: <NEW_LINE> <INDENT> dc_ksize_list = ksize_list <NEW_LINE> <DEDENT> with self.init_scope(): <NEW_LINE> <INDENT> self.pos_encoder = Encoder(self.nb_inputs, channel_list, ksize_list, pad_list) <NEW_LINE> self.pos_decoder = Decoder(dc_channel_list[-1], dc_channel_list, dc_ksize_list[::-1]) <NEW_LINE> self.inter = Conv_Module(channel_list[-1], dc_channel_list[0], inter_list) <NEW_LINE> self.last = Conv_Module(dc_channel_list[-1], self.nb_inputs, last_list, True) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, inputs): <NEW_LINE> <INDENT> pos_x, pos_y, offset_x, ego_x, ego_y, pose_x, pose_y = self._prepare_input(inputs) <NEW_LINE> batch_size, past_len, _ = pos_x.shape <NEW_LINE> h = self.pos_encoder(pos_x) <NEW_LINE> h = self.inter(h) <NEW_LINE> h = self.pos_decoder(h) <NEW_LINE> pred_y = self.last(h) <NEW_LINE> pred_y = F.swapaxes(pred_y, 1, 2) <NEW_LINE> pred_y = pred_y[:, :pos_y.shape[1], :] <NEW_LINE> loss = F.mean_squared_error(pred_y, pos_y) <NEW_LINE> pred_y = pred_y + F.broadcast_to(F.expand_dims(offset_x, 1), pred_y.shape) <NEW_LINE> pred_y = cuda.to_cpu(pred_y.data) * self._std + self._mean <NEW_LINE> return loss, pred_y, None
Baseline: location only
6259906e4c3428357761bb1f
class echoList_result: <NEW_LINE> <INDENT> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [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 = RecList() <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._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('echoList_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 __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <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
6259906e21bff66bcd7244d3
class Author(models.Model): <NEW_LINE> <INDENT> first_name = models.CharField(max_length=100) <NEW_LINE> last_name = models.CharField(max_length=100) <NEW_LINE> date_of_birth = models.DateField(null=True, blank=True) <NEW_LINE> date_of_death = models.DateField('died', null=True, blank=True) <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('authors', args=[str(self.id)]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s, %s' % (self.last_name, self.first_name)
Model representing an author.
6259906ecb5e8a47e493cdb8
class ConsistentTreesHlistArbor(RockstarArbor): <NEW_LINE> <INDENT> _has_uids = True <NEW_LINE> _field_info_class = ConsistentTreesFieldInfo <NEW_LINE> _data_file_class = ConsistentTreesHlistDataFile <NEW_LINE> def _parse_parameter_file(self): <NEW_LINE> <INDENT> ConsistentTreesArbor._parse_parameter_file( self, ntrees_in_file=False) <NEW_LINE> <DEDENT> def _get_data_files(self): <NEW_LINE> <INDENT> prefix = os.path.join(os.path.dirname(self.filename), "hlist_") <NEW_LINE> suffix = ".list" <NEW_LINE> my_files = glob.glob(f"{prefix}*{suffix}") <NEW_LINE> my_files.sort( key=lambda x: self._get_file_index(x, prefix, suffix), reverse=True) <NEW_LINE> self.data_files = [self._data_file_class(f, self) for f in my_files] <NEW_LINE> <DEDENT> def _get_file_index(self, f, prefix, suffix): <NEW_LINE> <INDENT> return float(f[f.find(prefix)+len(prefix):f.rfind(suffix)]) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _is_valid(self, *args, **kwargs): <NEW_LINE> <INDENT> fn = args[0] <NEW_LINE> if not os.path.basename(fn).startswith("hlist") or not fn.endswith(".list"): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Class for Arbors created from consistent-trees hlist_*.list files. This is a hybrid type with multiple catalog files like the rockstar frontend, but with headers structured like consistent-trees.
6259906e7d847024c075dc4a
class ObjectTypeFlags(Enum): <NEW_LINE> <INDENT> OBJECT = 1 << 0 <NEW_LINE> ITEM = 1 << 1 <NEW_LINE> CONTAINER = 1 << 2 <NEW_LINE> UNIT = 1 << 3 <NEW_LINE> PLAYER = 1 << 4 <NEW_LINE> GAME_OBJECT = 1 << 5 <NEW_LINE> DYNAMIC_OBJECT = 1 << 6 <NEW_LINE> CORPSE = 1 << 7
BaseObject descriptors "flags" (field 0x8).
6259906e99cbb53fe6832754
class TestFixGridOrca025U(NcoDataFixBaseTest): <NEW_LINE> <INDENT> def test_subprocess_called_correctly(self): <NEW_LINE> <INDENT> fix = FixGridOrca025U('uo_1.nc', '/a') <NEW_LINE> fix.apply_fix() <NEW_LINE> calls = [ mock.call( "ncks -h --no_alphabetize -3 /a/uo_1.nc /a/uo_1.nc.temp", stderr=subprocess.STDOUT, shell=True ), mock.call( "ncks -h --no_alphabetize -A -v latitude,longitude," "vertices_latitude,vertices_longitude " "/gws/nopw/j04/primavera1/masks/HadGEM3Ocean_fixes/" "grids/ORCA025/ORCA025_grid-u.nc /a/uo_1.nc.temp", stderr=subprocess.STDOUT, shell=True ), mock.call( "ncks -h --no_alphabetize -7 --deflate=3 /a/uo_1.nc.temp " "/a/uo_1.nc", stderr=subprocess.STDOUT, shell=True ), ] <NEW_LINE> self.mock_subprocess.assert_has_calls(calls)
Test FixGridOrca025U
6259906e44b2445a339b7595
@register_df_node <NEW_LINE> class AttrPattern(DFPattern): <NEW_LINE> <INDENT> def __init__(self, pattern: "DFPattern", attrs: tvm.ir.attrs.Attrs): <NEW_LINE> <INDENT> self.__init_handle_by_constructor__(ffi.AttrPattern, pattern, attrs)
Get match an expression with a certain attributes. Currently only supports Op Attributes, not call Attributes. Parameters ---------- pattern: tvm.relay.dataflow_pattern.DFPattern The input pattern. attrs: tvm.ir.attrs.Attrs The attributes to match.
6259906e97e22403b383c770
class REPL(commands.Cog): <NEW_LINE> <INDENT> def __init__(self, bot): <NEW_LINE> <INDENT> self.bot = bot <NEW_LINE> self._last_result = None <NEW_LINE> self.sessions = set() <NEW_LINE> <DEDENT> async def __local_check(self, ctx): <NEW_LINE> <INDENT> return await self.bot.is_owner(ctx.author) <NEW_LINE> <DEDENT> def cleanup_code(self, content): <NEW_LINE> <INDENT> if content.startswith('```') and content.endswith('```'): <NEW_LINE> <INDENT> return '\n'.join(content.split('\n')[1:-1]) <NEW_LINE> <DEDENT> return content.strip('` \n') <NEW_LINE> <DEDENT> def get_syntax_error(self, e): <NEW_LINE> <INDENT> if e.text is None: <NEW_LINE> <INDENT> return f'```py\n{e.__class__.__name__}: {e}\n```' <NEW_LINE> <DEDENT> return f'```py\n{e.text}{"^":>{e.offset}}\n{e.__class__.__name__}: {e}```' <NEW_LINE> <DEDENT> @commands.command(hidden=True, name='eval') <NEW_LINE> async def _eval(self, ctx, *, body: str): <NEW_LINE> <INDENT> env = { 'bot': self.bot, 'ctx': ctx, 'channel': ctx.channel, 'author': ctx.author, 'guild': ctx.guild, 'message': ctx.message, '_': self._last_result } <NEW_LINE> env.update(globals()) <NEW_LINE> body = self.cleanup_code(body) <NEW_LINE> stdout = io.StringIO() <NEW_LINE> to_compile = f'async def func():\n{textwrap.indent(body, " ")}' <NEW_LINE> try: <NEW_LINE> <INDENT> exec(to_compile, env) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```') <NEW_LINE> <DEDENT> func = env['func'] <NEW_LINE> try: <NEW_LINE> <INDENT> with redirect_stdout(stdout): <NEW_LINE> <INDENT> ret = await func() <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> value = stdout.getvalue() <NEW_LINE> await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = stdout.getvalue() <NEW_LINE> if ret is None: <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> await ctx.send(f'```py\n{value}\n```') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._last_result = ret <NEW_LINE> await ctx.send(f'```py\n{value}{ret}\n```') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @commands.command(hidden=True) <NEW_LINE> async def peval(self, ctx, *, body: str): <NEW_LINE> <INDENT> body = self.cleanup_code(body) <NEW_LINE> await ctx.invoke(self._eval, body=f'print({body})') <NEW_LINE> <DEDENT> @commands.command(hidden=True) <NEW_LINE> async def run(self, ctx, *, command): <NEW_LINE> <INDENT> proc = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) <NEW_LINE> stdout, stderr = (text.decode() for text in await proc.communicate()) <NEW_LINE> res = '' <NEW_LINE> if stdout: <NEW_LINE> <INDENT> res = f'Output:```\n{stdout}```' <NEW_LINE> <DEDENT> if stderr: <NEW_LINE> <INDENT> res += f'Error:```\n{stderr}```' <NEW_LINE> <DEDENT> if not res: <NEW_LINE> <INDENT> res = 'No result.' <NEW_LINE> <DEDENT> await ctx.send(res) <NEW_LINE> <DEDENT> @commands.command(hidden=True) <NEW_LINE> async def restart(self, ctx): <NEW_LINE> <INDENT> await ctx.invoke(self.run, command='sudo systemctl restart soturi.service')
Admin-only commands that make the bot dynamic.
6259906e16aa5153ce401d47
class PeriodSpecTest(unittest.TestCase): <NEW_LINE> <INDENT> @unittest.skip("Period spec not covered") <NEW_LINE> def test_period_spec(self): <NEW_LINE> <INDENT> period = Period(id='0', start=None, duration=None)
from ISO/IEC 23009-1: Overview: A Media Presentation consists of one or more Periods. A Period is defined by a Period element in the MPD element. - Each Period contains one or more Adaptation Sets as described in 5.3.3. - Each Period may contain one or more Subsets that restrict combination of Adaptation Sets for presentation supported attributes for the urn:mpeg:dash:profile:isoff-on-demand:2011 profile: - 'id' (Optional) specifies an identifier for this Period. The identifier shall be unique within the scope of the Media Presentation. If the MPD@type is "dynamic", then this attribute shall be present and shall not change in case the MPD is updated. If not present, no identifier for the Period is provided. - 'start' (Optional) if present, specifies the PeriodStart time of the Period. The PeriodStart time is used as an anchor to determine the MPD start time of each Media Segment as well as to determine the presentation time of each access unit in the Media Presentation timeline. - 'duration' (Optional) if present specifies the duration of the Period to determine the PeriodStart time of the next Period.
6259906e97e22403b383c771
class FoundAttachment(FoundPage): <NEW_LINE> <INDENT> def __init__(self, page_name, attachment, matches=None, page=None, rev=0): <NEW_LINE> <INDENT> self.page_name = page_name <NEW_LINE> self.attachment = attachment <NEW_LINE> self.rev = rev <NEW_LINE> self.page = page <NEW_LINE> if matches is None: <NEW_LINE> <INDENT> matches = [] <NEW_LINE> <DEDENT> self._matches = matches <NEW_LINE> <DEDENT> def weight(self, unique=1): <NEW_LINE> <INDENT> return 1
Represents an attachment in search results
6259906e283ffb24f3cf5116
class RpcZmqEnvelopeEnabledTestCase(_RpcZmqBaseTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(RpcZmqEnvelopeEnabledTestCase, self).setUp() <NEW_LINE> self.stubs.Set(rpc_common, '_SEND_RPC_ENVELOPE', True)
This sends messages with envelopes enabled.
6259906e99fddb7c1ca63a08
class Phantom(Shape): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def draw(self,centroid,color): <NEW_LINE> <INDENT> pass
Dummy
6259906e63b5f9789fe869d0
class ShareForm(ModelForm): <NEW_LINE> <INDENT> url = forms.URLField(label=u'链接',widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': u'链接', 'required': ''})) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Share <NEW_LINE> fields = ('title', 'url') <NEW_LINE> widgets = { 'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': u'标题', 'required': '', 'autofocus': ''}), }
添加分享链接
6259906ecb5e8a47e493cdb9
class SleepInMultiInput(BaseTestClass): <NEW_LINE> <INDENT> def _initialize(self): <NEW_LINE> <INDENT> self.__data = connectors.MultiInputData() <NEW_LINE> <DEDENT> @connectors.MultiInput("get_values", parallelization=connectors.Parallelization.THREAD) <NEW_LINE> def add_value(self, value): <NEW_LINE> <INDENT> time.sleep(1.0) <NEW_LINE> data_id = self.__data.add(value) <NEW_LINE> self._register_call(method_name="add_value", parameters=[value], return_value=data_id) <NEW_LINE> return data_id <NEW_LINE> <DEDENT> @add_value.remove <NEW_LINE> def remove_value(self, data_id): <NEW_LINE> <INDENT> self._register_call(method_name="remove_value", parameters=[data_id], return_value=self) <NEW_LINE> del self.__data[data_id] <NEW_LINE> return self <NEW_LINE> <DEDENT> @add_value.replace <NEW_LINE> def replace_value(self, data_id, value): <NEW_LINE> <INDENT> self._register_call(method_name="replace_value", parameters=[data_id, value], return_value=self) <NEW_LINE> self.__data[data_id] = value <NEW_LINE> return self <NEW_LINE> <DEDENT> @connectors.Output() <NEW_LINE> def get_values(self): <NEW_LINE> <INDENT> result = tuple(self.__data.values()) <NEW_LINE> self._register_call(method_name="get_values", parameters=[], return_value=result) <NEW_LINE> return result
Sleeps one second, when the multi-input connector is executed
6259906e2ae34c7f260ac958
class Populaire(EventMixin, Base): <NEW_LINE> <INDENT> __tablename__ = 'populaires' <NEW_LINE> event_name = Column(Text) <NEW_LINE> short_name = Column(Text, index=True) <NEW_LINE> distance = Column(Text) <NEW_LINE> start_locn = Column(Text) <NEW_LINE> start_map_url = Column(Text) <NEW_LINE> entry_form_url = Column(Text) <NEW_LINE> riders = relationship( 'PopulaireRider', order_by='PopulaireRider.lowercase_last_name', ) <NEW_LINE> def __init__( self, event_name, short_name, distance, date_time, start_locn, organizer_email, registration_end, entry_form_url=None, google_doc_id=None ): <NEW_LINE> <INDENT> self.event_name = event_name <NEW_LINE> self.short_name = short_name <NEW_LINE> self.distance = distance <NEW_LINE> self.date_time = date_time <NEW_LINE> self.start_locn = start_locn <NEW_LINE> self.organizer_email = organizer_email <NEW_LINE> self.registration_end = registration_end <NEW_LINE> self.entry_form_url = ( entry_form_url or DBSession.query(Link) .filter_by(key='entry_form') .one().url) <NEW_LINE> self.start_map_url = ( 'https://maps.google.com/maps?q={}' .format('+'.join(self.start_locn.split()))) <NEW_LINE> self.google_doc_id = google_doc_id <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{.short_name}'.format(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Populaire({})>'.format(self) <NEW_LINE> <DEDENT> @property <NEW_LINE> def uuid(self): <NEW_LINE> <INDENT> return uuid.uuid5( uuid.NAMESPACE_URL, '/randopony/{0.short_name}/{0.date_time:%d%b%Y}'.format(self))
Populaire event.
6259906ebf627c535bcb2d39
class Expr(stmt): <NEW_LINE> <INDENT> _fields = ("value",)
An expression in statement context. The value of expression is discarded. :ivar value: (:class:`expr`) value
6259906e5fc7496912d48ea0
class FacebookFriend(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User, verbose_name=_(u'User')) <NEW_LINE> facebook_id = models.BigIntegerField(_(u'Facebook id')) <NEW_LINE> name = models.CharField(_(u'Name'), max_length=128, blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'facebook_friends' <NEW_LINE> abstract = False if settings.MANIFEST_FACEBOOK_FRIENDS else True <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return 'friends of %s' % self.user.username
Abstract base class for Facebook user profile
6259906e7d43ff2487428049
class TestPNG(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.png = image_png.PngReader <NEW_LINE> self.out = sys.stdout <NEW_LINE> sys.stdout = FakeStdOut() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> sys.stdout = self.out <NEW_LINE> <DEDENT> def test_png_01(self): <NEW_LINE> <INDENT> self.assertRaises( image_png.PNGWrongHeaderError, self.png, 'test_data/sachovnice.jpg' ) <NEW_LINE> <DEDENT> def test_png_02(self): <NEW_LINE> <INDENT> self.assertRaises( image_png.PNGNotImplementedError, self.png, 'test_data/sachovnice_paleta.png' ) <NEW_LINE> <DEDENT> def test_png_03(self): <NEW_LINE> <INDENT> image = self.png('test_data/sachovnice.png') <NEW_LINE> self.assertEqual( image.rgb, [[(255, 0, 0), (0, 255, 0), (0, 0, 255)], [(255, 255, 255), (127, 127, 127), (0, 0, 0)], [(255, 255, 0), (255, 0, 255), (0, 255, 255)]] )
testuje korektní načítání podmnožiny PNG-obrázků
6259906ee5267d203ee6cff4
class TestLinkedList(unittest.TestCase): <NEW_LINE> <INDENT> def test_empty_list(self): <NEW_LINE> <INDENT> ll = LinkedList() <NEW_LINE> self.assertEqual(str(ll), "") <NEW_LINE> <DEDENT> def test_single_node(self): <NEW_LINE> <INDENT> ll = LinkedList(1) <NEW_LINE> self.assertEquals(str(ll), "1") <NEW_LINE> <DEDENT> def test_add_before(self): <NEW_LINE> <INDENT> ll = LinkedList() <NEW_LINE> ll.add_before(4) <NEW_LINE> ll.add_before(3) <NEW_LINE> ll.add_before(2) <NEW_LINE> ll.add_before(1) <NEW_LINE> self.assertEquals(str(ll), "1 2 3 4") <NEW_LINE> <DEDENT> def test_add_after(self): <NEW_LINE> <INDENT> ll = LinkedList() <NEW_LINE> ll.add_after(1) <NEW_LINE> ll.add_after(2) <NEW_LINE> ll.add_after(3) <NEW_LINE> ll.add_after(4) <NEW_LINE> self.assertEquals(str(ll), "1 2 3 4") <NEW_LINE> <DEDENT> def test_reverse(self): <NEW_LINE> <INDENT> ll = LinkedList() <NEW_LINE> ll.add_before(1) <NEW_LINE> ll.add_before(2) <NEW_LINE> ll.add_before(3) <NEW_LINE> ll.add_before(4) <NEW_LINE> ll.reverse() <NEW_LINE> self.assertEllqual(str(ll), "1 2 3 4")
This is the absolute vanilla linked list implementation I can print the list I can add a node to the front of the list I can create a list
6259906ea8370b77170f1c36
class Efm8HidPort(hidport.HidPort): <NEW_LINE> <INDENT> SIZE_IN = 4 <NEW_LINE> SIZE_OUT = 64 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(Efm8HidPort, self).__init__() <NEW_LINE> if sys.platform == 'win32': <NEW_LINE> <INDENT> self.make_report = lambda r: b'\x00' + r <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.make_report = lambda r: r <NEW_LINE> <DEDENT> <DEDENT> def read(self): <NEW_LINE> <INDENT> in_report = self.get_input_report()[-Efm8HidPort.SIZE_IN:] <NEW_LINE> return in_report[0:1] <NEW_LINE> <DEDENT> def write(self, frame): <NEW_LINE> <INDENT> for n in range(0, len(frame), Efm8HidPort.SIZE_OUT): <NEW_LINE> <INDENT> out_report = self.make_report(frame[n:n+Efm8HidPort.SIZE_OUT]) <NEW_LINE> self.set_output_report(out_report)
Class demonstrates how to communicate with EFM8 HID bootloader. This class provides functions for writing a boot frame and for reading the response from the EFM8 HID bootloader. Because the EFM8 HID device only defines one input and one output report, there is no report number. For Windows hosts only, read/write data exchanged with the HID driver is prepended with a dummy report number.
6259906ea8370b77170f1c37
class ArchiveViewlet(ViewletBase): <NEW_LINE> <INDENT> def update(self): <NEW_LINE> <INDENT> info = queryAdapter(self.context, IObjectArchivator) or queryAdapter(self.context, IObjectArchivator, name='annotation_storage_dexterity') <NEW_LINE> rv = NamedVocabulary('eea.workflow.reasons') <NEW_LINE> vocab = rv.getVocabularyDict(self.context) <NEW_LINE> archive_info = dict(initiator=info.initiator, archive_date=info.archive_date, reason=vocab.get(info.reason, "Other"), custom_message=info.custom_message) <NEW_LINE> self.info = archive_info
Viewlet that appears only when the object is archived
6259906e9c8ee82313040dbf
class EmployeeUpdateView(LoginRequiredMixin, UpdateView): <NEW_LINE> <INDENT> model = Employee <NEW_LINE> template_name = 'profiles/employee/update.html' <NEW_LINE> form_class = EmployeeUpdateForm <NEW_LINE> login_url = reverse_lazy('users_app:login') <NEW_LINE> success_url = reverse_lazy('profiles_app:employee-list') <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> usuario = self.request.user <NEW_LINE> if not (usuario.type_user == '4' or usuario.type_user == '1'): <NEW_LINE> <INDENT> return HttpResponseRedirect( reverse( 'users_app:login' ) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.object = self.get_object() <NEW_LINE> context = self.get_context_data(object=self.object) <NEW_LINE> return self.render_to_response(context) <NEW_LINE> <DEDENT> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> form.save() <NEW_LINE> conductor = self.get_object() <NEW_LINE> conductor.user_modified = self.request.user <NEW_LINE> conductor.save() <NEW_LINE> return super(EmployeeUpdateView, self).form_valid(form)
vista para actualizar datos de Empleados
6259906e442bda511e95d98f
class Exists(FunctionalTest): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setup_class(cls): <NEW_LINE> <INDENT> build_address(id=5) <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def teardown_class(cls): <NEW_LINE> <INDENT> delete_addresses() <NEW_LINE> db.session.commit() <NEW_LINE> <DEDENT> def test_exists(self): <NEW_LINE> <INDENT> response = self.put('/addresses/5') <NEW_LINE> assert response.status_code != 404 <NEW_LINE> assert response.status_code != 500
Check if the webservice exists
6259906e0c0af96317c57995
class QtMpl (FigureCanvasQTAgg): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> self.fig = matplotlib.figure.Figure() <NEW_LINE> self.fig.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) <NEW_LINE> self.fig.gca().xaxis.set_major_locator(mdates.DayLocator()) <NEW_LINE> FigureCanvasQTAgg.__init__(self, self.fig) <NEW_LINE> self.setParent(parent) <NEW_LINE> self.subplot = self.fig.add_subplot(111) <NEW_LINE> self.subplot.set_ylabel("Stock Price($)") <NEW_LINE> self.subplot.set_xlabel("Date(MM/DD/YYYY)") <NEW_LINE> self.subplot.set_title("Historical Stock Data Display") <NEW_LINE> self.line = [] <NEW_LINE> FigureCanvasQTAgg.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) <NEW_LINE> FigureCanvasQTAgg.updateGeometry(self) <NEW_LINE> <DEDENT> def addLine(self, x, y, title): <NEW_LINE> <INDENT> self.line.append(self.subplot.plot(x, y, label=title)) <NEW_LINE> self.subplot.legend() <NEW_LINE> self.fig.canvas.draw() <NEW_LINE> self.fig.autofmt_xdate() <NEW_LINE> return
This class will plot a figure on the UI window
6259906e7b25080760ed891a
class Plan(GitHubObject): <NEW_LINE> <INDENT> def __init__(self, plan): <NEW_LINE> <INDENT> super(Plan, self).__init__(plan) <NEW_LINE> self.collaborators = plan.get('collaborators') <NEW_LINE> self.name = plan.get('name') <NEW_LINE> self.private_repos = plan.get('private_repos') <NEW_LINE> self.space = plan.get('space') <NEW_LINE> <DEDENT> def _repr(self): <NEW_LINE> <INDENT> return '<Plan [{0}]>'.format(self.name) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def is_free(self): <NEW_LINE> <INDENT> return self.name == 'free'
The :class:`Plan <Plan>` object. This makes interacting with the plan information about a user easier. Please see GitHub's `Authenticated User <http://developer.github.com/v3/users/#get-the-authenticated-user>`_ documentation for more specifics.
6259906ef548e778e596cdfc
class LibxdoKeyboard(BaseX11Keyboard): <NEW_LINE> <INDENT> _log = logging.getLogger("keyboard") <NEW_LINE> display = Xlib.display.Display() <NEW_LINE> libxdo = xdo.Xdo(os.environ.get('DISPLAY', '')) <NEW_LINE> @classmethod <NEW_LINE> def send_keyboard_events(cls, events): <NEW_LINE> <INDENT> cls._log.debug("Keyboard.send_keyboard_events %r", events) <NEW_LINE> for event in events: <NEW_LINE> <INDENT> (key, down, timeout) = event <NEW_LINE> delay_micros = int(timeout * 1000.0) <NEW_LINE> key = KEY_TRANSLATION.get(key, key) <NEW_LINE> try: <NEW_LINE> <INDENT> if down: <NEW_LINE> <INDENT> cls.libxdo.send_keysequence_window_down(0, key, delay_micros) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cls.libxdo.send_keysequence_window_up(0, key, delay_micros) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> cls._log.exception("Failed to type key code %s: %s", key, e) <NEW_LINE> <DEDENT> if timeout: <NEW_LINE> <INDENT> time.sleep(timeout)
Static class for typing keys with python-libxdo.
6259906ed486a94d0ba2d82e
class IsSuperuser(BasePermission): <NEW_LINE> <INDENT> def has_permission(self, request, view): <NEW_LINE> <INDENT> return is_superuser(request.user)
Only superusers are authorised
6259906efff4ab517ebcf089
class SlicedPepperoni(Pepperoni): <NEW_LINE> <INDENT> pass
薄切りペパロニ
6259906e32920d7e50bc78b6
class itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass(itkInPlaceImageFilterAPython.itkInPlaceImageFilterIRGBAUS3IRGBAUS3): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> InputImage1Dimension = _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_InputImage1Dimension <NEW_LINE> InputImage2Dimension = _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_InputImage2Dimension <NEW_LINE> OutputImageDimension = _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_OutputImageDimension <NEW_LINE> SameDimensionCheck1 = _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_SameDimensionCheck1 <NEW_LINE> SameDimensionCheck2 = _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_SameDimensionCheck2 <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetInput1(self, *args): <NEW_LINE> <INDENT> return _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_SetInput1(self, *args) <NEW_LINE> <DEDENT> def SetInput2(self, *args): <NEW_LINE> <INDENT> return _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_SetInput2(self, *args) <NEW_LINE> <DEDENT> def GetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_GetFunctor(self, *args) <NEW_LINE> <DEDENT> def SetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_SetFunctor(self, *args) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkMaskImageFilterPython.delete_itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkMaskImageFilterPython.itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkMaskImageFilterIRGBAUS3IUC3IRGBAUS3_Superclass class
6259906e1b99ca400229016d
class Action(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> actor = db.Column(db.String(20)) <NEW_LINE> action = db.Column(db.String(500)) <NEW_LINE> status = db.Column(db.String(20)) <NEW_LINE> edited_time = db.Column(db.DateTime, default=datetime.datetime.utcnow)
Class for storing user variant log.
6259906e76e4537e8c3f0df3
class DPTControllerStatus(DPTBase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_knx(cls, raw): <NEW_LINE> <INDENT> cls.test_bytesarray(raw, 1) <NEW_LINE> if raw[0] & 8 > 0: <NEW_LINE> <INDENT> return HVACOperationMode.FROST_PROTECTION <NEW_LINE> <DEDENT> if raw[0] & 4 > 0: <NEW_LINE> <INDENT> return HVACOperationMode.NIGHT <NEW_LINE> <DEDENT> if raw[0] & 2 > 0: <NEW_LINE> <INDENT> return HVACOperationMode.STANDBY <NEW_LINE> <DEDENT> if raw[0] & 1 > 0: <NEW_LINE> <INDENT> return HVACOperationMode.COMFORT <NEW_LINE> <DEDENT> raise CouldNotParseKNXIP("Could not parse HVACOperationMode") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def to_knx(cls, value): <NEW_LINE> <INDENT> if value == HVACOperationMode.AUTO: <NEW_LINE> <INDENT> raise ConversionError("Cant serialize DPTControllerStatus", value=value) <NEW_LINE> <DEDENT> if value == HVACOperationMode.COMFORT: <NEW_LINE> <INDENT> return (0x21,) <NEW_LINE> <DEDENT> if value == HVACOperationMode.STANDBY: <NEW_LINE> <INDENT> return (0x22,) <NEW_LINE> <DEDENT> if value == HVACOperationMode.NIGHT: <NEW_LINE> <INDENT> return (0x24,) <NEW_LINE> <DEDENT> if value == HVACOperationMode.FROST_PROTECTION: <NEW_LINE> <INDENT> return (0x28,) <NEW_LINE> <DEDENT> raise ConversionError("Could not parse DPTControllerStatus", value=value)
Abstraction for KNX HVAC Controller status. Non-standardised DP type (in accordance with KNX AN 097/07 rev 3). Help needed: The values of this type were retrieved by reverse engineering. Any notes on the correct implementation of this type are highly appreciated.
6259906e167d2b6e312b81c6
class WebrootBase(object): <NEW_LINE> <INDENT> exposed = True <NEW_LINE> def __init__(self, templatePath): <NEW_LINE> <INDENT> self.vars = {} <NEW_LINE> self.config = config.getConfig() <NEW_LINE> self._templateDirs = [] <NEW_LINE> self.setTemplatePath(templatePath) <NEW_LINE> <DEDENT> def updateHtmlVars(self, vars): <NEW_LINE> <INDENT> self.vars.update(vars) <NEW_LINE> <DEDENT> def setTemplatePath(self, templatePath): <NEW_LINE> <INDENT> templateDir, templateFilename = os.path.split(templatePath) <NEW_LINE> self._templateDirs.append(templateDir) <NEW_LINE> self.templateFilename = templateFilename <NEW_LINE> self._templateLookup = None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _escapeJavascript(string): <NEW_LINE> <INDENT> return re.sub( r'[^a-zA-Z0-9]', lambda match: '\\u%04X' % ord(match.group()), string ) <NEW_LINE> <DEDENT> def _renderHTML(self): <NEW_LINE> <INDENT> if self._templateLookup is None: <NEW_LINE> <INDENT> self._templateLookup = mako.lookup.TemplateLookup(directories=self._templateDirs) <NEW_LINE> <DEDENT> template = self._templateLookup.get_template(self.templateFilename) <NEW_LINE> return template.render(js=self._escapeJavascript, json=json.dumps, **self.vars) <NEW_LINE> <DEDENT> def GET(self, **params): <NEW_LINE> <INDENT> return self._renderHTML() <NEW_LINE> <DEDENT> def DELETE(self, **params): <NEW_LINE> <INDENT> raise cherrypy.HTTPError(405) <NEW_LINE> <DEDENT> def PATCH(self, **params): <NEW_LINE> <INDENT> raise cherrypy.HTTPError(405) <NEW_LINE> <DEDENT> def POST(self, **params): <NEW_LINE> <INDENT> raise cherrypy.HTTPError(405) <NEW_LINE> <DEDENT> def PUT(self, **params): <NEW_LINE> <INDENT> raise cherrypy.HTTPError(405)
Serves a template file in response to GET requests. This will typically be the base class of any non-API endpoints.
6259906e460517430c432c8e
class Resource: <NEW_LINE> <INDENT> def __init__(self, name, resource_type, resource_id, status, status_reason): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.type = resource_type <NEW_LINE> self.id = resource_id <NEW_LINE> self.status = status <NEW_LINE> self.status_reason = status_reason
SNAPS domain object for a resource created by a heat template
6259906e63b5f9789fe869d2
class AccountSettingsView(LoginRequiredMixin, generic.DetailView): <NEW_LINE> <INDENT> model = User <NEW_LINE> template_name = 'accounts/account_settings.html'
Account settings view. Accessible only to owner. Staff will have access to modify settings here, but through the admin console app.
6259906e5fcc89381b266d8f
class ElementWrapper(object): <NEW_LINE> <INDENT> in_html_document = False <NEW_LINE> def __init__(self, obj): <NEW_LINE> <INDENT> self.object = obj <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self.object.attrib.get('id') <NEW_LINE> <DEDENT> @property <NEW_LINE> def etree_element(self): <NEW_LINE> <INDENT> return self.object <NEW_LINE> <DEDENT> @property <NEW_LINE> def parent(self): <NEW_LINE> <INDENT> par = self.object.getparent() <NEW_LINE> return ElementWrapper(par) if par is not None else None <NEW_LINE> <DEDENT> @property <NEW_LINE> def classes(self): <NEW_LINE> <INDENT> cl = self.object.attrib.get('class') <NEW_LINE> return split_whitespace(cl) if cl is not None else [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def local_name(self): <NEW_LINE> <INDENT> return node_name(self.object) <NEW_LINE> <DEDENT> @property <NEW_LINE> def namespace_url(self): <NEW_LINE> <INDENT> if '}' in self.object.tag: <NEW_LINE> <INDENT> self.object.tag.split('}')[0][1:] <NEW_LINE> <DEDENT> <DEDENT> def iter_ancestors(self): <NEW_LINE> <INDENT> element = self <NEW_LINE> while element.parent is not None: <NEW_LINE> <INDENT> element = element.parent <NEW_LINE> yield element <NEW_LINE> <DEDENT> <DEDENT> def apply_rules(self, rules): <NEW_LINE> <INDENT> matches = rules.match(self) <NEW_LINE> for match in matches: <NEW_LINE> <INDENT> attr_dict = match[3][1] <NEW_LINE> for attr, val in attr_dict.items(): <NEW_LINE> <INDENT> if not attr in self.object.attrib: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.object.attrib[attr] = val <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> self.object.set('__rules_applied', '1')
lxml element wrapper to partially match the API from cssselect2.ElementWrapper so as element can be passed to rules.match().
6259906e26068e7796d4e1ab
class Raja(CMakePackage): <NEW_LINE> <INDENT> homepage = "http://software.llnl.gov/RAJA/" <NEW_LINE> version('develop', git='https://github.com/LLNL/RAJA.git', branch="master", submodules="True") <NEW_LINE> depends_on('[email protected]:', type='build')
RAJA Parallel Framework.
6259906e7d847024c075dc4e
class ExpiredOAuthTokenError(Exception): <NEW_LINE> <INDENT> pass
Raised when an expired L{OAuthAccessToken} or L{OAuthRenewalToken} is used in a request.
6259906eb7558d5895464b6a
class NoNorm(Normalize): <NEW_LINE> <INDENT> def __call__(self, value, clip=None): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> def inverse(self, value): <NEW_LINE> <INDENT> return value
Dummy replacement for `Normalize`, for the case where we want to use indices directly in a `~matplotlib.cm.ScalarMappable`.
6259906e7b180e01f3e49c9c
@attr('UNIT', group='mi') <NEW_LINE> class TestConfig(MiUnitTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> Config().cm.destroy() <NEW_LINE> if not exists(ROOTDIR): <NEW_LINE> <INDENT> makedirs(ROOTDIR) <NEW_LINE> <DEDENT> if exists(self.config_file()): <NEW_LINE> <INDENT> log.debug("remove test dir %s" % self.config_file()) <NEW_LINE> remove(self.config_file()) <NEW_LINE> <DEDENT> self.assertFalse(exists(self.config_file())) <NEW_LINE> <DEDENT> def config_file(self): <NEW_LINE> <INDENT> return "%s/idk.yml" % ROOTDIR <NEW_LINE> <DEDENT> def read_config(self): <NEW_LINE> <INDENT> infile = open(self.config_file(), "r") <NEW_LINE> result = infile.read() <NEW_LINE> infile.close() <NEW_LINE> return result <NEW_LINE> <DEDENT> def write_config(self): <NEW_LINE> <INDENT> outfile = open(self.config_file(), "a") <NEW_LINE> outfile.write(" couchdb: couchdb\n") <NEW_LINE> outfile.write(" start_couch: True\n") <NEW_LINE> outfile.write(" start_rabbit: True\n") <NEW_LINE> outfile.close() <NEW_LINE> <DEDENT> def test_default_config(self): <NEW_LINE> <INDENT> config = Config(ROOTDIR) <NEW_LINE> self.assertTrue(config) <NEW_LINE> expected_string = "idk:\n start_couch: false\n working_repo: %s\n start_rabbit: false\n" % config.get("working_repo") <NEW_LINE> self.assertEqual(expected_string, self.read_config()) <NEW_LINE> self.assertTrue(config.get("working_repo")) <NEW_LINE> self.assertTrue(config.get("template_dir")) <NEW_LINE> self.assertTrue(config.get("couchdb")) <NEW_LINE> self.assertTrue(config.get("rabbitmq")) <NEW_LINE> self.assertTrue(False == config.get("start_rabbit")) <NEW_LINE> self.assertTrue(False == config.get("start_couch")) <NEW_LINE> <DEDENT> def test_overloaded_config(self): <NEW_LINE> <INDENT> config = Config(ROOTDIR) <NEW_LINE> self.write_config() <NEW_LINE> self.assertTrue(config) <NEW_LINE> config.cm.init(ROOTDIR) <NEW_LINE> expected_string = "idk:\n start_couch: false\n working_repo: %s\n start_rabbit: false\n couchdb: %s\n start_couch: True\n start_rabbit: True\n" % (config.get("working_repo"), config.get("couchdb")) <NEW_LINE> self.assertEqual(expected_string, self.read_config()) <NEW_LINE> self.assertEqual(config.get("couchdb"), "couchdb") <NEW_LINE> self.assertTrue(config.get("working_repo")) <NEW_LINE> self.assertTrue(config.get("template_dir")) <NEW_LINE> self.assertTrue(config.get("rabbitmq")) <NEW_LINE> self.assertTrue(True == config.get("start_rabbit")) <NEW_LINE> self.assertTrue(True == config.get("start_couch"))
Test the config object.
6259906e4c3428357761bb23
class Vocabulary(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._token_to_id = {} <NEW_LINE> self._token_to_count = collections.Counter() <NEW_LINE> self._id_to_token = [] <NEW_LINE> self._num_tokens = 0 <NEW_LINE> self._total_count = 0 <NEW_LINE> self._s_id = None <NEW_LINE> self._unk_id = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_tokens(self): <NEW_LINE> <INDENT> return self._num_tokens <NEW_LINE> <DEDENT> @property <NEW_LINE> def unk(self): <NEW_LINE> <INDENT> return "<UNK>" <NEW_LINE> <DEDENT> @property <NEW_LINE> def unk_id(self): <NEW_LINE> <INDENT> return self._unk_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def s(self): <NEW_LINE> <INDENT> return "<S>" <NEW_LINE> <DEDENT> @property <NEW_LINE> def s_id(self): <NEW_LINE> <INDENT> return self._s_id <NEW_LINE> <DEDENT> def add(self, token, count): <NEW_LINE> <INDENT> self._token_to_id[token] = self._num_tokens <NEW_LINE> self._token_to_count[token] = count <NEW_LINE> self._id_to_token.append(token) <NEW_LINE> self._num_tokens += 1 <NEW_LINE> self._total_count += count <NEW_LINE> <DEDENT> def finalize(self): <NEW_LINE> <INDENT> self._s_id = self.get_id(self.s) <NEW_LINE> self._unk_id = self.get_id(self.unk) <NEW_LINE> <DEDENT> def get_id(self, token): <NEW_LINE> <INDENT> return self._token_to_id.get(token, self.unk_id) <NEW_LINE> <DEDENT> def get_token(self, id_): <NEW_LINE> <INDENT> return self._id_to_token[id_] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_file(filename): <NEW_LINE> <INDENT> vocab = Vocabulary() <NEW_LINE> with codecs.open(filename, "r", "utf-8") as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> word, count = line.strip().split() <NEW_LINE> vocab.add(word, int(count)) <NEW_LINE> <DEDENT> <DEDENT> vocab.finalize() <NEW_LINE> return vocab
A dictionary for words. Adapeted from @rafaljozefowicz's implementation.
6259906ea8370b77170f1c38
class TypeQuantity(object): <NEW_LINE> <INDENT> def __init__(self, typeid, quantity): <NEW_LINE> <INDENT> self.typeid = typeid <NEW_LINE> self.quantity = quantity
represents a typed lump of stuff from eve. generated and consumed by jobs and market orders
6259906e3d592f4c4edbc751
class ExecuteWorker(Worker): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ExecuteWorker, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def process_task(self, task): <NEW_LINE> <INDENT> print("-----------------------") <NEW_LINE> print("Working on task: {0}".format(task.id)) <NEW_LINE> dirs = self.create_dirs(task) <NEW_LINE> params_file = os.path.join(dirs['SIMCITY_IN'], 'input.json') <NEW_LINE> dirs['SIMCITY_PARAMS'] = params_file <NEW_LINE> with open(params_file, 'w') as f: <NEW_LINE> <INDENT> json.dump(task.input, f) <NEW_LINE> <DEDENT> for attachment in task.input.get('uploads', []): <NEW_LINE> <INDENT> download_attachment(task, dirs['SIMCITY_IN'], attachment) <NEW_LINE> <DEDENT> command = expandfilename(task['command']) <NEW_LINE> if 'arguments' in task and len(task['arguments']) > 0: <NEW_LINE> <INDENT> command = [command] <NEW_LINE> for arg in task['arguments']: <NEW_LINE> <INDENT> if arg in dirs: <NEW_LINE> <INDENT> command.append(dirs[arg]) <NEW_LINE> <DEDENT> elif arg.startswith('$') and arg[1:] in dirs: <NEW_LINE> <INDENT> command.append(dirs[arg[1:]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> command.append(arg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> dirs.update(os.environ) <NEW_LINE> task['execute_properties'] = {'env': dirs} <NEW_LINE> out_file = os.path.join(dirs['SIMCITY_OUT'], 'stdout.txt') <NEW_LINE> err_file = os.path.join(dirs['SIMCITY_OUT'], 'stderr.txt') <NEW_LINE> try: <NEW_LINE> <INDENT> if self.execute(command, out_file, err_file, dirs) != 0: <NEW_LINE> <INDENT> task.error("Command failed") <NEW_LINE> <DEDENT> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> task.error("Command raised exception", ex) <NEW_LINE> <DEDENT> task.output = {} <NEW_LINE> out_files = listfiles(dirs['SIMCITY_OUT']) <NEW_LINE> for filename in out_files: <NEW_LINE> <INDENT> upload_attachment(task, dirs['SIMCITY_OUT'], filename) <NEW_LINE> <DEDENT> if not task.has_error(): <NEW_LINE> <INDENT> task.done() <NEW_LINE> <DEDENT> print("-----------------------") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def execute(command, out_file, err_file, env): <NEW_LINE> <INDENT> with open(out_file, 'w') as out: <NEW_LINE> <INDENT> with open(err_file, 'w') as err: <NEW_LINE> <INDENT> return call(command, env=env, stdout=out, stderr=err) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def create_dirs(self, task): <NEW_LINE> <INDENT> dir_map = { 'SIMCITY_TMP': 'tmp_dir', 'SIMCITY_IN': 'input_dir', 'SIMCITY_OUT': 'output_dir' } <NEW_LINE> dirs = {} <NEW_LINE> for d, conf in dir_map.items(): <NEW_LINE> <INDENT> super_dir = expandfilename(self.config[conf]) <NEW_LINE> try: <NEW_LINE> <INDENT> os.mkdir(super_dir) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> dirs[d] = os.path.join(super_dir, task.id + '_' + str(task['lock'])) <NEW_LINE> os.mkdir(dirs[d]) <NEW_LINE> <DEDENT> return dirs
Executes a job locally, all tasks provided by its iterator. Tasks are assumed to have input parameters. It creates a new input, output and temporary directory for each tasks, and attaches files that are generated in the output directory to the task when the task is finished. If the command exits with non-zero, the task is assumed to have failed. At the start of a job, it is registered to the job database, when it is finished, it is archived.
6259906e99cbb53fe6832759
class Spine: <NEW_LINE> <INDENT> def __init__(self, parent_axes, transform): <NEW_LINE> <INDENT> self.parent_axes = parent_axes <NEW_LINE> self.transform = transform <NEW_LINE> self.data = None <NEW_LINE> self.pixel = None <NEW_LINE> self.world = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def data(self): <NEW_LINE> <INDENT> return self._data <NEW_LINE> <DEDENT> @data.setter <NEW_LINE> def data(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> self._data = None <NEW_LINE> self._pixel = None <NEW_LINE> self._world = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._data = value <NEW_LINE> self._pixel = self.parent_axes.transData.transform(self._data) <NEW_LINE> self._world = self.transform.transform(self._data) <NEW_LINE> self._update_normal() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def pixel(self): <NEW_LINE> <INDENT> return self._pixel <NEW_LINE> <DEDENT> @pixel.setter <NEW_LINE> def pixel(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> self._data = None <NEW_LINE> self._pixel = None <NEW_LINE> self._world = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._data = self.parent_axes.transData.inverted().transform(self._data) <NEW_LINE> self._pixel = value <NEW_LINE> self._world = self.transform.transform(self._data) <NEW_LINE> self._update_normal() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def world(self): <NEW_LINE> <INDENT> return self._world <NEW_LINE> <DEDENT> @world.setter <NEW_LINE> def world(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> self._data = None <NEW_LINE> self._pixel = None <NEW_LINE> self._world = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._data = self.transform.transform(value) <NEW_LINE> self._pixel = self.parent_axes.transData.transform(self._data) <NEW_LINE> self._world = value <NEW_LINE> self._update_normal() <NEW_LINE> <DEDENT> <DEDENT> def _update_normal(self): <NEW_LINE> <INDENT> dx = self.pixel[1:, 0] - self.pixel[:-1, 0] <NEW_LINE> dy = self.pixel[1:, 1] - self.pixel[:-1, 1] <NEW_LINE> self.normal_angle = np.degrees(np.arctan2(dx, -dy))
A single side of an axes. This does not need to be a straight line, but represents a 'side' when determining which part of the frame to put labels and ticks on.
6259906e55399d3f05627d93
class Interpellation(Act): <NEW_LINE> <INDENT> ANSWER_TYPES = Choices( ('WRITTEN', 'written', _('Written')), ('VERBAL', 'verbal', _('Verbal')), ) <NEW_LINE> FINAL_STATUSES = ( ('ANSWERED', _('answered')), ('NOTANSWERED', _('not answered')), ) <NEW_LINE> STATUS = Choices( ('PRESENTED', 'presented', _('presented')), ('ANSWERED', 'answered', _('answered')), ('NOTANSWERED', 'notanswered', _('not answered')), ) <NEW_LINE> status = StatusField() <NEW_LINE> answer_type = models.CharField(_('answer type'), max_length=8, choices=ANSWER_TYPES) <NEW_LINE> question_motivation = models.TextField(blank=True) <NEW_LINE> answer_text = models.TextField(blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('interpellation') <NEW_LINE> verbose_name_plural = _('interpellations') <NEW_LINE> <DEDENT> @models.permalink <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return 'om_interpellation_detail', (), {'pk': str(self.pk)}
WRITEME
6259906e56ac1b37e630391b
class Field(object, metaclass=FieldBase): <NEW_LINE> <INDENT> def __init__(self, pk=False, required=False, hidden=False): <NEW_LINE> <INDENT> self.pk = pk <NEW_LINE> self.required = required <NEW_LINE> self.hidden = hidden <NEW_LINE> <DEDENT> def consume(self, prev, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def treat(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def show(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def validate(self, data): <NEW_LINE> <INDENT> for v in self.validators: <NEW_LINE> <INDENT> v(self, data) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> @validator <NEW_LINE> def validate_required(self, data): <NEW_LINE> <INDENT> if self.required and data is None: <NEW_LINE> <INDENT> raise FieldRequired() <NEW_LINE> <DEDENT> return data
Field base class. All other fields inherit from this class, so usually you want to use one of the more specialized fields. However, there might be cases where you wanna store an arbitrary value that does not fit well into any other standard field, and in that case you could use Field to store any value.
6259906efff4ab517ebcf08b
class LineReader(object): <NEW_LINE> <INDENT> def __init__(self, src): <NEW_LINE> <INDENT> self.lines = src.readlines() <NEW_LINE> self.line_cnt = 0 <NEW_LINE> <DEDENT> def getline(self): <NEW_LINE> <INDENT> ls = cleanline(self.lines[self.line_cnt]).split() <NEW_LINE> self.line_cnt += 1 <NEW_LINE> return CommandLine(ls[0], ls) <NEW_LINE> <DEDENT> def getattrs(self, to_float=False, split_sym='='): <NEW_LINE> <INDENT> attrs = {} <NEW_LINE> for line in self.lines: <NEW_LINE> <INDENT> ls = cleanline(line).split(split_sym) <NEW_LINE> if to_float: <NEW_LINE> <INDENT> attrs[ls[0]] = float(ls[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> attrs[ls[0]] = ls[1] <NEW_LINE> <DEDENT> <DEDENT> return Attr(attrs) <NEW_LINE> <DEDENT> def eof(self): <NEW_LINE> <INDENT> return self.line_cnt == len(self.lines)
Read linear command from file
6259906e38b623060ffaa48c
class TestPieceWiseConstant(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.particles = HydroParticleCreator(num=2, dim=2) <NEW_LINE> self.recon = PieceWiseConstant() <NEW_LINE> <DEDENT> def test_add_fields(self): <NEW_LINE> <INDENT> particles = CarrayContainer(1, {"wrong_type": "int"}) <NEW_LINE> self.assertRaises(RuntimeError, self.recon.add_fields, particles) <NEW_LINE> <DEDENT> def test_initialize(self): <NEW_LINE> <INDENT> self.assertRaises(RuntimeError, self.recon.initialize) <NEW_LINE> self.recon.add_fields(self.particles) <NEW_LINE> self.recon.initialize() <NEW_LINE> self.assertItemsEqual( self.recon.left_states.carray_named_groups["primitive"], self.particles.carray_named_groups["primitive"]) <NEW_LINE> self.assertItemsEqual( self.recon.left_states.carray_named_groups["velocity"], self.particles.carray_named_groups["velocity"]) <NEW_LINE> self.assertItemsEqual( self.recon.right_states.carray_named_groups["primitive"], self.particles.carray_named_groups["primitive"]) <NEW_LINE> self.assertItemsEqual( self.recon.right_states.carray_named_groups["velocity"], self.particles.carray_named_groups["velocity"]) <NEW_LINE> <DEDENT> def test_compute_states(self): <NEW_LINE> <INDENT> for field in self.particles.carray_named_groups["primitive"]: <NEW_LINE> <INDENT> self.particles[field][:] = 1.0 <NEW_LINE> <DEDENT> self.recon.add_fields(self.particles) <NEW_LINE> self.recon.initialize() <NEW_LINE> domain_manager = DomainManager(0.2) <NEW_LINE> mesh = Mesh() <NEW_LINE> mesh.register_fields(self.particles) <NEW_LINE> mesh.initialize() <NEW_LINE> mesh.faces.resize(1) <NEW_LINE> mesh.faces["pair-i"][0] = 0 <NEW_LINE> mesh.faces["pair-j"][0] = 1 <NEW_LINE> self.recon.compute_states(self.particles, mesh, False, domain_manager, dt=1.0) <NEW_LINE> for field in self.recon.left_states.carrays.keys(): <NEW_LINE> <INDENT> self.assertAlmostEqual(self.recon.left_states[field][0], self.particles[field][0]) <NEW_LINE> self.assertAlmostEqual(self.recon.right_states[field][0], self.particles[field][1])
Tests for the constant reconstruction class.
6259906e1f5feb6acb164462
class CourseBookmarksView(View): <NEW_LINE> <INDENT> @method_decorator(login_required) <NEW_LINE> @method_decorator(ensure_csrf_cookie) <NEW_LINE> @method_decorator(cache_control(no_cache=True, no_store=True, must_revalidate=True)) <NEW_LINE> @method_decorator(ensure_valid_course_key) <NEW_LINE> def get(self, request, course_id): <NEW_LINE> <INDENT> course_key = CourseKey.from_string(course_id) <NEW_LINE> course = get_course_with_access(request.user, 'load', course_key, check_if_enrolled=True) <NEW_LINE> course_url_name = default_course_url_name(course.id) <NEW_LINE> course_url = reverse(course_url_name, kwargs={'course_id': six.text_type(course.id)}) <NEW_LINE> bookmarks_fragment = CourseBookmarksFragmentView().render_to_fragment(request, course_id=course_id) <NEW_LINE> context = { 'csrf': csrf(request)['csrf_token'], 'course': course, 'supports_preview_menu': True, 'course_url': course_url, 'bookmarks_fragment': bookmarks_fragment, 'disable_courseware_js': True, 'uses_pattern_library': True, } <NEW_LINE> return render_to_response('course_bookmarks/course-bookmarks.html', context)
View showing the user's bookmarks for a course.
6259906e56b00c62f0fb413f
class QlearnDeepAgent(QlearnTabularAgent): <NEW_LINE> <INDENT> def __init__(self, env, nb_episodes=1, epsilon=0.1, learning_rate=0.1, discount=1, verbose=False, nb_hidden_1=100, nb_hidden_2=100, activation='relu', optim='SGD'): <NEW_LINE> <INDENT> self.nb_hidden_1 = nb_hidden_1 <NEW_LINE> self.nb_hidden_2 = nb_hidden_2 <NEW_LINE> self.activation = activation <NEW_LINE> self.optim = optim <NEW_LINE> QlearnTabularAgent.__init__(self, env, nb_episodes, epsilon, learning_rate, discount, verbose) <NEW_LINE> self.reset() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> super(QlearnDeepAgent, self).reset() <NEW_LINE> self.model = DeepModel(self.env, self.learning_rate, self.nb_hidden_1, self.nb_hidden_2, self.activation, self.optim)
Q-Learning with a neural network model observation space : continuous action space : discrete
6259906ecb5e8a47e493cdbb
class UserUpdateMe(UserBase): <NEW_LINE> <INDENT> email: Optional[EmailStr] <NEW_LINE> first_name: Optional[str] <NEW_LINE> last_name: Optional[str] <NEW_LINE> password: Optional[str]
Properties to receive via API on update of current user.
6259906e7b180e01f3e49c9d
class IS_UUR(Validator): <NEW_LINE> <INDENT> def __init__(self, error_message="Uur (UU:MM) foutief !"): <NEW_LINE> <INDENT> self.error_message = error_message <NEW_LINE> <DEDENT> def __call__(self, uur): <NEW_LINE> <INDENT> error = None <NEW_LINE> if not self.valideer_lengte(uur): <NEW_LINE> <INDENT> error = self.error_message <NEW_LINE> <DEDENT> uren, scheidingsteken, minuten = self.splits(uur) <NEW_LINE> uren_ok = self.valideer_uren(uren) <NEW_LINE> scheidingsteken_ok = self.valideer_scheidingsteken(scheidingsteken) <NEW_LINE> minuten_ok = self.valideer_minuten(minuten) <NEW_LINE> if uren_ok and minuten_ok and scheidingsteken_ok: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error = self.error_message <NEW_LINE> <DEDENT> return (uur, error) <NEW_LINE> <DEDENT> def valideer_lengte(self, value): <NEW_LINE> <INDENT> return (len(value) == 5) <NEW_LINE> <DEDENT> def valideer_uren(self, uren): <NEW_LINE> <INDENT> return ('00' <= uren <= '23') <NEW_LINE> <DEDENT> def valideer_minuten(self, minuten): <NEW_LINE> <INDENT> return ('00' <= minuten <= '59') <NEW_LINE> <DEDENT> def valideer_scheidingsteken(self, teken): <NEW_LINE> <INDENT> return (teken == ':') <NEW_LINE> <DEDENT> def splits(self, uur): <NEW_LINE> <INDENT> return (uur[0:2], uur[2:3], uur[3:])
Valideer of een uur geldig is. Formaat : UU:MM Geldige waarden : - uren : tussen 00 en 23 - minuten : tussen 00 en 59
6259906ebe8e80087fbc0901
class FailedToCreatePath(AsyncV20Exception): <NEW_LINE> <INDENT> pass
Unable to construct the path for the requested endpoint
6259906e3317a56b869bf17d
class AsyncMsg(object): <NEW_LINE> <INDENT> def __init__(self, element, msgType): <NEW_LINE> <INDENT> self.src_ne = element <NEW_LINE> self.msg_type = msgType <NEW_LINE> <DEDENT> def do_event(self, source): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> OnepAsyncMsgType = enum('ONEP_ASYNC_MESSAGE_TYPE_APICALL', 'ONEP_ASYNC_MESSAGE_TYPE_EVENT')
This abstract class is meant to be implemented by a any class acting as a event object.
6259906e4c3428357761bb25
class ShapeOptimizer(Optimizer): <NEW_LINE> <INDENT> def add_requirements(self, fgraph): <NEW_LINE> <INDENT> fgraph.attach_feature(ShapeFeature()) <NEW_LINE> <DEDENT> def apply(self, fgraph): <NEW_LINE> <INDENT> pass
Optimizer that serves to add ShapeFeature as an fgraph feature.
6259906ea8370b77170f1c3a
class ConfigDirective(Directive): <NEW_LINE> <INDENT> def add_line(self, line: str, source: str, *lineno: int) -> None: <NEW_LINE> <INDENT> self.result.append(line, source, *lineno) <NEW_LINE> <DEDENT> def generate_docs( self, component_name: str, component_index: str, docstring: str, sourcename: str, option_data: List[Dict], more_content: Any, ) -> None: <NEW_LINE> <INDENT> indent = " " <NEW_LINE> self.add_line(".. everett:component:: %s" % component_name, sourcename) <NEW_LINE> self.add_line("", sourcename) <NEW_LINE> if "show-docstring" in self.options and docstring: <NEW_LINE> <INDENT> docstringlines = prepare_docstring(docstring) <NEW_LINE> for i, line in enumerate(docstringlines): <NEW_LINE> <INDENT> self.add_line(indent + line, sourcename, i) <NEW_LINE> <DEDENT> self.add_line("", "") <NEW_LINE> <DEDENT> if more_content: <NEW_LINE> <INDENT> for line, src in zip(more_content.data, more_content.items): <NEW_LINE> <INDENT> self.add_line(indent + line, src[0], src[1]) <NEW_LINE> <DEDENT> self.add_line("", "") <NEW_LINE> <DEDENT> if "show-table" in self.options: <NEW_LINE> <INDENT> self.add_line(indent + "Configuration summary:", sourcename) <NEW_LINE> self.add_line("", sourcename) <NEW_LINE> table: List[List[str]] = [] <NEW_LINE> table.append(["Setting", "Parser", "Required?"]) <NEW_LINE> for option_item in option_data: <NEW_LINE> <INDENT> ref = f"{component_name}.{option_item['key']}" <NEW_LINE> table.append( [ f":everett:option:`{option_item['key']} <{ref}>`", f"*{option_item['parser']}*", "Yes" if option_item["default"] is NO_VALUE else "", ] ) <NEW_LINE> <DEDENT> for line in build_table(table): <NEW_LINE> <INDENT> self.add_line(indent + line, sourcename) <NEW_LINE> <DEDENT> self.add_line("", sourcename) <NEW_LINE> self.add_line(indent + "Configuration options:", sourcename) <NEW_LINE> self.add_line("", sourcename) <NEW_LINE> <DEDENT> if option_data: <NEW_LINE> <INDENT> sourcename = "class definition" <NEW_LINE> for option_item in option_data: <NEW_LINE> <INDENT> key = option_item["key"] <NEW_LINE> self.add_line(f"{indent}.. everett:option:: {key}", sourcename) <NEW_LINE> self.add_line( f"{indent} :parser: {option_item['parser']}", sourcename ) <NEW_LINE> if option_item["default"] is not NO_VALUE: <NEW_LINE> <INDENT> self.add_line( f"{indent} :default: \"{option_item['default']}\"", sourcename ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.add_line(f"{indent} :required:", sourcename) <NEW_LINE> <DEDENT> self.add_line("", sourcename) <NEW_LINE> doc = option_item["doc"] <NEW_LINE> for doc_line in doc.splitlines(): <NEW_LINE> <INDENT> self.add_line(f"{indent} {doc_line}", sourcename) <NEW_LINE> <DEDENT> self.add_line("", sourcename) <NEW_LINE> <DEDENT> <DEDENT> self.add_line("", sourcename)
Base class for generating configuration
6259906e3d592f4c4edbc753
class SSHPower(base.PowerInterface): <NEW_LINE> <INDENT> def validate(self, node): <NEW_LINE> <INDENT> _parse_driver_info(node) <NEW_LINE> <DEDENT> def get_power_state(self, task, node): <NEW_LINE> <INDENT> driver_info = _parse_driver_info(node) <NEW_LINE> driver_info['macs'] = _get_nodes_mac_addresses(task, node) <NEW_LINE> ssh_obj = _get_connection(node) <NEW_LINE> return _get_power_status(ssh_obj, driver_info) <NEW_LINE> <DEDENT> @task_manager.require_exclusive_lock <NEW_LINE> def set_power_state(self, task, node, pstate): <NEW_LINE> <INDENT> driver_info = _parse_driver_info(node) <NEW_LINE> driver_info['macs'] = _get_nodes_mac_addresses(task, node) <NEW_LINE> ssh_obj = _get_connection(node) <NEW_LINE> if pstate == states.POWER_ON: <NEW_LINE> <INDENT> state = _power_on(ssh_obj, driver_info) <NEW_LINE> <DEDENT> elif pstate == states.POWER_OFF: <NEW_LINE> <INDENT> state = _power_off(ssh_obj, driver_info) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise exception.InvalidParameterValue(_("set_power_state called " "with invalid power state %s.") % pstate) <NEW_LINE> <DEDENT> if state != pstate: <NEW_LINE> <INDENT> raise exception.PowerStateFailure(pstate=pstate) <NEW_LINE> <DEDENT> <DEDENT> @task_manager.require_exclusive_lock <NEW_LINE> def reboot(self, task, node): <NEW_LINE> <INDENT> driver_info = _parse_driver_info(node) <NEW_LINE> driver_info['macs'] = _get_nodes_mac_addresses(task, node) <NEW_LINE> ssh_obj = _get_connection(node) <NEW_LINE> current_pstate = _get_power_status(ssh_obj, driver_info) <NEW_LINE> if current_pstate == states.POWER_ON: <NEW_LINE> <INDENT> _power_off(ssh_obj, driver_info) <NEW_LINE> <DEDENT> state = _power_on(ssh_obj, driver_info) <NEW_LINE> if state != states.POWER_ON: <NEW_LINE> <INDENT> raise exception.PowerStateFailure(pstate=states.POWER_ON)
SSH Power Interface. This PowerInterface class provides a mechanism for controlling the power state of virtual machines via SSH. NOTE: This driver supports VirtualBox and Virsh commands. NOTE: This driver does not currently support multi-node operations.
6259906e009cb60464d02da9
class Solution2(object): <NEW_LINE> <INDENT> def isSymmetric(self, root): <NEW_LINE> <INDENT> if root == None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> stack1 = [root.left] <NEW_LINE> stack2 = [root.right] <NEW_LINE> while len(stack1) != 0 and len(stack2) != 0: <NEW_LINE> <INDENT> t1 = stack1.pop(0) <NEW_LINE> t2 = stack2.pop(0) <NEW_LINE> if t1 == None and t2 == None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif t1 != None and t2 != None: <NEW_LINE> <INDENT> if t1.val != t2.val: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> stack1.append(t1.left) <NEW_LINE> stack1.append(t1.right) <NEW_LINE> stack2.append(t2.right) <NEW_LINE> stack2.append(t2.left) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> if len(stack1) != len(stack2): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
use two queues, one for left half tree, other for right half tree. queue 1, enqueue from left to right, queue 2, enqueue from right to left, then two queue should be same.
6259906ef548e778e596cdff
class MsgLauncher2Portal(amp.Command): <NEW_LINE> <INDENT> key = "MsgLauncher2Portal" <NEW_LINE> arguments = [('operation', amp.String()), ('arguments', amp.String())] <NEW_LINE> errors = {Exception: 'EXCEPTION'} <NEW_LINE> response = []
Message Launcher -> Portal
6259906e9c8ee82313040dc1
class ComponentEditFrame(wx.Frame): <NEW_LINE> <INDENT> def __init__(self, parent, title): <NEW_LINE> <INDENT> super(ComponentEditFrame, self).__init__(parent, title=title, size=(600, 400)) <NEW_LINE> self.Centre() <NEW_LINE> self.panel = CompEditPanel(self) <NEW_LINE> self.panel.SetBackgroundColour("gray") <NEW_LINE> self.createStatusBar() <NEW_LINE> <DEDENT> def createStatusBar(self): <NEW_LINE> <INDENT> self.CreateStatusBar()
Platform Component Edit window.
6259906ee1aae11d1e7cf445
class SymbolData: <NEW_LINE> <INDENT> def __init__(self, symbol, macd): <NEW_LINE> <INDENT> self.Symbol = symbol <NEW_LINE> self.MACD = macd
Contains data specific to a symbol required by this model
6259906e71ff763f4b5e901b