code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class EZCoinTestNet(EZCoin): <NEW_LINE> <INDENT> name = 'test-ezcoin' <NEW_LINE> seeds = ("testseed1.ezcoin.org", ) <NEW_LINE> port = 17955 <NEW_LINE> message_start = b'\xf2\xc5\xa7\xde' <NEW_LINE> base58_prefixes = { 'PUBKEY_ADDR': 44, 'SCRIPT_ADDR': 196, 'SECRET_KEY': 172 }
Class with all the necessary EZCoin testing network information based on https://github.com/ezcoin/ezcoin/blob/master/src/net.cpp (date of access: 02/14/2018)
62598f9c0a50d4780f70519b
class PacketLayerError(CPacketBuildException): <NEW_LINE> <INDENT> def __init__(self, name, message=''): <NEW_LINE> <INDENT> self._default_message = "The given packet layer name ({0}) does not exists.".format(name) <NEW_LINE> self.message = message or self._default_message <NEW_LINE> super(CTRexPktBuilder.PacketLayerError, self).__init__(-13, self.message)
This exception is used to indicate an error caused by operation performed on an non-exists layer of the packet.
62598f9c56ac1b37e6301fac
class RegistroM220(Registro): <NEW_LINE> <INDENT> campos = [ CampoFixo(1, 'REG', 'M220'), Campo(2, 'IND_AJ', obrigatorio=True), CampoNumerico(3, 'VL_AJ', obrigatorio=True), Campo(4, 'COD_AJ', obrigatorio=True), CampoNumerico(5, 'NUM_DOC'), Campo(6, 'DESCR_AJ'), CampoData(7, 'DT_REF'), ] <NEW_LINE> nivel = 4
Ajustes da Contribuição para o PIS/PASEP Apurada
62598f9c009cb60464d012e7
class Session(object): <NEW_LINE> <INDENT> def __init__(self, request_obj): <NEW_LINE> <INDENT> self._request_handler = request_obj <NEW_LINE> self._session_id = request_obj.get_argument("utoken", None) <NEW_LINE> if not self._session_id: <NEW_LINE> <INDENT> self._session_id = uuid.uuid4().hex <NEW_LINE> self.data = {} <NEW_LINE> request_obj.set_secure_cookie("session_id", self._session_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> jsondata = request_obj.redis.get("session_id:%s" % (self._session_id) ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> raise e <NEW_LINE> <DEDENT> if not jsondata: <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data = json.loads(jsondata) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> json_str = json.dumps(self.data) <NEW_LINE> try: <NEW_LINE> <INDENT> self._request_handler.redis.set("session_id:%s" % self._session_id, json_str, SESSION_EXPIRE_TIME) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> raise e <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._request_handler.redis.delete("session_id:%s" % self._session_id) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> raise e <NEW_LINE> <DEDENT> self._request_handler.clear_cookie("session_id") <NEW_LINE> <DEDENT> def clear_session(self, session_id, userid): <NEW_LINE> <INDENT> if not isinstance(session_id, bytes): <NEW_LINE> <INDENT> raise TypeError("session_id 不正确") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> logging.debug("session_id:%s" % session_id.decode('utf8')) <NEW_LINE> self._request_handler.redis.delete("session_id:%s" % session_id.decode('utf8')) <NEW_LINE> logging.debug("tb_users uid:%s" % userid) <NEW_LINE> self._request_handler.redis.hdel("tb_users", "uid:%d" % userid) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> raise e
存储用户session 数据缓存在redis
62598f9c462c4b4f79dbb7cd
class Tutorial (object): <NEW_LINE> <INDENT> def __init__ (self, connection): <NEW_LINE> <INDENT> self.connection = connection <NEW_LINE> connection.addListeners(self) <NEW_LINE> self.mac_to_port = {} <NEW_LINE> <DEDENT> def resend_packet (self, packet_in, out_port): <NEW_LINE> <INDENT> msg = of.ofp_packet_out() <NEW_LINE> msg.data = packet_in <NEW_LINE> action = of.ofp_action_output(port = out_port) <NEW_LINE> msg.actions.append(action) <NEW_LINE> self.connection.send(msg) <NEW_LINE> <DEDENT> def act_like_hub (self, packet, packet_in): <NEW_LINE> <INDENT> self.resend_packet(packet_in, of.OFPP_ALL) <NEW_LINE> <DEDENT> def act_like_switch (self, packet, packet_in,port): <NEW_LINE> <INDENT> self.mac_to_port[packet.src] = port <NEW_LINE> if packet.dst in self.mac_to_port: <NEW_LINE> <INDENT> self.resend_packet(packet_in, mac_to_port[packet.dst]) <NEW_LINE> log.debug("Installing flow...") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.resend_packet(packet_in, of.OFPP_ALL) <NEW_LINE> <DEDENT> <DEDENT> def _handle_PacketIn (self, event): <NEW_LINE> <INDENT> packet = event.parsed <NEW_LINE> if not packet.parsed: <NEW_LINE> <INDENT> log.warning("Ignoring incomplete packet") <NEW_LINE> return <NEW_LINE> <DEDENT> packet_in = event.ofp <NEW_LINE> self.act_like_switch(packet, packet_in,event.port)
A Tutorial object is created for each switch that connects. A Connection object for that switch is passed to the __init__ function.
62598f9c32920d7e50bc5e18
class Channel(BaseNode): <NEW_LINE> <INDENT> location_code = String.T(xmlstyle='attribute') <NEW_LINE> external_reference_list = List.T( ExternalReference.T(xmltagname='ExternalReference')) <NEW_LINE> latitude = Latitude.T(xmltagname='Latitude') <NEW_LINE> longitude = Longitude.T(xmltagname='Longitude') <NEW_LINE> elevation = Distance.T(xmltagname='Elevation') <NEW_LINE> depth = Distance.T(xmltagname='Depth') <NEW_LINE> azimuth = Azimuth.T(optional=True, xmltagname='Azimuth') <NEW_LINE> dip = Dip.T(optional=True, xmltagname='Dip') <NEW_LINE> type_list = List.T(Type.T(xmltagname='Type')) <NEW_LINE> sample_rate = SampleRate.T(optional=True, xmltagname='SampleRate') <NEW_LINE> sample_rate_ratio = SampleRateRatio.T(optional=True, xmltagname='SampleRateRatio') <NEW_LINE> storage_format = String.T(optional=True, xmltagname='StorageFormat') <NEW_LINE> clock_drift = ClockDrift.T(optional=True, xmltagname='ClockDrift') <NEW_LINE> calibration_units = Units.T(optional=True, xmltagname='CalibrationUnits') <NEW_LINE> sensor = Equipment.T(optional=True, xmltagname='Sensor') <NEW_LINE> pre_amplifier = Equipment.T(optional=True, xmltagname='PreAmplifier') <NEW_LINE> data_logger = Equipment.T(optional=True, xmltagname='DataLogger') <NEW_LINE> equipment = Equipment.T(optional=True, xmltagname='Equipment') <NEW_LINE> response = Response.T(optional=True, xmltagname='Response') <NEW_LINE> @property <NEW_LINE> def position_values(self): <NEW_LINE> <INDENT> lat = self.latitude.value <NEW_LINE> lon = self.longitude.value <NEW_LINE> elevation = value_or_none(self.elevation) <NEW_LINE> depth = value_or_none(self.depth) <NEW_LINE> return lat, lon, elevation, depth
Equivalent to SEED blockette 52 and parent element for the related the response blockettes.
62598f9da8370b77170f01a5
class StatusCodeCount(luigi.Task): <NEW_LINE> <INDENT> input_file = luigi.Parameter() <NEW_LINE> def requires(self): <NEW_LINE> <INDENT> return InputFile(self.input_file) <NEW_LINE> <DEDENT> def output(self): <NEW_LINE> <INDENT> return luigi.LocalTarget('aggregate_api.json') <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> data = {} <NEW_LINE> for line in self.input().open().read().strip().split("\n"): <NEW_LINE> <INDENT> j_line = json.loads(line)['_source'] <NEW_LINE> if j_line.get('api_key', None) and j_line.get('status', None): <NEW_LINE> <INDENT> if data.get(j_line.get('api_key'), None): <NEW_LINE> <INDENT> if data[j_line.get('api_key')]['status_codes'].get(j_line.get('status')): <NEW_LINE> <INDENT> data[j_line.get('api_key')]['status_codes'][j_line.get('status')] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data[j_line.get('api_key')]['status_codes'].setdefault(j_line.get('status'), 1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> data.setdefault(j_line.get('api_key'), {'status_codes': {j_line.get('status'): 1}}) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with self.output().open('w') as fout: <NEW_LINE> <INDENT> fout.write(json.dumps(data))
This class parses the previous json file and collects the code count for each status
62598f9d1f5feb6acb1629e4
@python_2_unicode_compatible <NEW_LINE> class SysUserManager(BaseUserManager): <NEW_LINE> <INDENT> def create_user(self, email, cell_no, password=None): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError('email은 필수 입력입니다.') <NEW_LINE> <DEDENT> if not cell_no: <NEW_LINE> <INDENT> raise ValueError('휴대폰번호는 필수 입력입니다.') <NEW_LINE> <DEDENT> user = self.model( email = self.nomalize_email(email), ) <NEW_LINE> user.is_admin = False <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using = self._db) <NEW_LINE> return User <NEW_LINE> <DEDENT> def create_superuser(self, email, cell_no, password): <NEW_LINE> <INDENT> user = self.create_user( email, password = password, ) <NEW_LINE> user.is_admin = True <NEW_LINE> user.save(using = self._db) <NEW_LINE> return user
시스템 사용자 관리 매니저
62598f9dbe383301e02535b7
class CoinGateBaseOrder: <NEW_LINE> <INDENT> fields_translation = dict() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if self.coingate_id is not None: <NEW_LINE> <INDENT> return "<CoinGate Order {} ({})>".format(self.order_id, self.coingate_id) <NEW_LINE> <DEDENT> return "<CoinGate Order {}>".format(self.order_id) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_response_data(cls, rdata): <NEW_LINE> <INDENT> args = {} <NEW_LINE> for fname, f in cls.fields_translation.items(): <NEW_LINE> <INDENT> if f.get('required', False) and fname not in rdata: <NEW_LINE> <INDENT> raise CoinGateClientException('Field {} is required and missing'.format(fname)) <NEW_LINE> <DEDENT> if fname in rdata: <NEW_LINE> <INDENT> if (f.get('validate', None) is not None) and (not f['validate'](rdata[fname])): <NEW_LINE> <INDENT> raise CoinGateClientException('Field {} has invalid value'.format(fname)) <NEW_LINE> <DEDENT> args[f.get('property_name', fname)] = f.get('casting', str)(rdata[fname]) <NEW_LINE> <DEDENT> <DEDENT> return cls(**args)
Base class for CoinGate orders the fields_translation dictionary contains dictionaries that indicates how fields returned by CoinGate's API relate to properties of the class. Most of them have default arguments. Here are the keys and their possible values : - The name of the field in Coingate's schema is given by the key - "property_name": The corresponding property on the model. If not set, defaults to the value of field_name - "casting": function to be called to cast the value of the field. defaults to str. - "required": if set to True, will raise an exception if the field is missing. Defaults to False. - "validate": Function used to validate the data, should return a Boolean (True if valid, False if invalid). No validation will occur if this is set to None. Defaults to None. Children classes are expected to have coingate_id and order_id properties
62598f9d3cc13d1c6d46552e
class RulesetView(CreateAPIView): <NEW_LINE> <INDENT> serializer_class = YaraRuleSerializer <NEW_LINE> permission_classes = [IsGroupAdminOrMemberAddMethod]
Create new rule.
62598f9d7d43ff24874272e3
class CustomerPremission(permissions.DjangoModelPermissions): <NEW_LINE> <INDENT> message = 'No Permission to Access.' <NEW_LINE> def has_permission(self, request, view): <NEW_LINE> <INDENT> patch_map = 'patch' <NEW_LINE> deletel_map = 'deletel' <NEW_LINE> post_map = 'post' <NEW_LINE> need_perms = '' <NEW_LINE> module_perms = view.module_perms <NEW_LINE> if (ENVIRONMENT == 'dev'): <NEW_LINE> <INDENT> if ((module_perms in ENVIRONMENT_LIST) and (request.method not in SAFE_METHODS)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user_perms = init_permissions(request.user,'perms') <NEW_LINE> if (request.user.is_superuser): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (request.method in SAFE_METHODS): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (request.method == 'PATCH'): <NEW_LINE> <INDENT> need_perms = module_perms[0] + ':' + patch_map <NEW_LINE> <DEDENT> elif (request.method == 'POST'): <NEW_LINE> <INDENT> need_perms = module_perms[0] + ':' + post_map <NEW_LINE> <DEDENT> elif (request.method == 'DELETE'): <NEW_LINE> <INDENT> need_perms = module_perms[0] + ':' + deletel_map <NEW_LINE> <DEDENT> if (need_perms in user_perms): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> elif (ENVIRONMENT == 'prd'): <NEW_LINE> <INDENT> user_perms = init_permissions(request.user,'perms') <NEW_LINE> if (request.user.is_superuser): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (request.method in SAFE_METHODS): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if (request.method == 'PATCH'): <NEW_LINE> <INDENT> need_perms = module_perms[0] + ':' + patch_map <NEW_LINE> <DEDENT> elif (request.method == 'POST'): <NEW_LINE> <INDENT> need_perms = module_perms[0] + ':' + post_map <NEW_LINE> <DEDENT> elif (request.method == 'DELETE'): <NEW_LINE> <INDENT> need_perms = module_perms[0] + ':' + deletel_map <NEW_LINE> <DEDENT> if (need_perms in user_perms): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
自定义权限
62598f9d07f4c71912baf20d
class Station(models.Model): <NEW_LINE> <INDENT> station_name = models.CharField(max_length=100) <NEW_LINE> station_code = models.CharField(max_length=11) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.station_name
Train station
62598f9d67a9b606de545d8c
class Initialize(object): <NEW_LINE> <INDENT> def __init__(self, blacklist, dnsservers, ip, port): <NEW_LINE> <INDENT> self.blacklist = blacklist <NEW_LINE> self.dnsservers = dnsservers <NEW_LINE> self.ip = ip <NEW_LINE> self.port = port <NEW_LINE> <DEDENT> def main(self): <NEW_LINE> <INDENT> resolver = client.createResolver(self.dnsservers) <NEW_LINE> http_client = Agent(reactor) <NEW_LINE> factory = ProxyFactory(self.blacklist, resolver, http_client) <NEW_LINE> endpoint = serverFromString( reactor, "tcp:%d:interface=%s" % (self.port, self.ip)) <NEW_LINE> endpoint.listen(factory) <NEW_LINE> reactor.run()
This class initialises the proxy based on the configuration specified
62598f9d3d592f4c4edbac91
class FileBank(object): <NEW_LINE> <INDENT> def __init__(self, default_file_name=None): <NEW_LINE> <INDENT> self.file_dict = dict() <NEW_LINE> self.default_file_name = default_file_name <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> for key, file in self.file_dict.items(): <NEW_LINE> <INDENT> file.close() <NEW_LINE> <DEDENT> <DEDENT> def get(self, name, default_file_name=None, default_file_mod='wt'): <NEW_LINE> <INDENT> if name not in self.file_dict: <NEW_LINE> <INDENT> if default_file_name is None: <NEW_LINE> <INDENT> if self.default_file_name is None: <NEW_LINE> <INDENT> raise TypeError('please input a valid file name!') <NEW_LINE> <DEDENT> default_file_name = self.default_file_name + '.' + name <NEW_LINE> <DEDENT> self.file_dict[name] = open(default_file_name, default_file_mod) <NEW_LINE> <DEDENT> return self.file_dict[name]
A set of files can be used to dynamically open and automatically closed
62598f9d76e4537e8c3ef378
class AbsoluteEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> return { 'type': 'absolute', 'name': obj.place_name }
Encodes a Absolute location.
62598f9d45492302aabfc29b
class VocabularyResource(ResourceBase): <NEW_LINE> <INDENT> def __init__(self, *args, transformer=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._transformer = str.lower <NEW_LINE> if transformer is not None: <NEW_LINE> <INDENT> self._transformer = transformer <NEW_LINE> <DEDENT> <DEDENT> def update_object(self, obj): <NEW_LINE> <INDENT> if not isinstance(obj, set): <NEW_LINE> <INDENT> raise TypeError("Expected 'set' type but instead '{}' was given.".format(type(obj))) <NEW_LINE> <DEDENT> super(VocabularyResource, self).update_object(obj) <NEW_LINE> <DEDENT> def _load_object_impl(self, opener): <NEW_LINE> <INDENT> with opener(mode='r', encoding='utf-8') as f: <NEW_LINE> <INDENT> return set(filter(None, (self._transformer(word).strip() for word in f if word))) <NEW_LINE> <DEDENT> <DEDENT> def _dump_object_impl(self, obj, opener): <NEW_LINE> <INDENT> with opener(mode='w', encoding='utf-8') as f: <NEW_LINE> <INDENT> for entry in obj: <NEW_LINE> <INDENT> print(entry.lower().strip(), file=f)
Resource handler for vocabularies. A vocabulary is a set of unique entities stored per line in a text file.
62598f9dd58c6744b42dc1b3
class DocLinkModel(BaseContentModel): <NEW_LINE> <INDENT> trunk_ref = db.ReferenceProperty(TrunkModel) <NEW_LINE> default_title = db.StringProperty() <NEW_LINE> doc_ref = db.ReferenceProperty(DocModel) <NEW_LINE> from_trunk_ref = db.ReferenceProperty(TrunkModel, collection_name='from_link') <NEW_LINE> from_doc_ref = db.ReferenceProperty(DocModel, collection_name='from_link') <NEW_LINE> def get_score(self, user): <NEW_LINE> <INDENT> if not self.doc_ref: <NEW_LINE> <INDENT> raise InvalidDocumentError('Document referred could not be found.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.doc_ref.get_score(user) <NEW_LINE> <DEDENT> <DEDENT> def ident(self): <NEW_LINE> <INDENT> return str(self.doc_ref.key()) <NEW_LINE> <DEDENT> def get_title(self): <NEW_LINE> <INDENT> if self.trunk_ref: <NEW_LINE> <INDENT> doc = db.get(self.trunk_ref.head) <NEW_LINE> if doc and doc.title: <NEW_LINE> <INDENT> return doc.title <NEW_LINE> <DEDENT> <DEDENT> if self.doc_ref: <NEW_LINE> <INDENT> return self.doc_ref.title <NEW_LINE> <DEDENT> return self.default_title
Link to another document in the datastore. Stores trunk_ref, doc_ref to the document it's pointing to and also for the document containing the link (i.e source of the link). Attributes: trunk_ref: Reference to a trunk containing the document. doc_ref: Reference to a document (used to point at a specific version of a document). from_trunk_ref: Reference to the trunk containing this link. from_doc_ref: Reference to the doc containing this link. default_title: Default title for the link (useful for docs which do not exists yet).
62598f9d8e7ae83300ee8e62
class AjaxItem(Item): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.detail.pop('article_json_rule')
condition 1,需要通过索引页拿到相关json数据,然后构造文章URL再去拿内容
62598f9d3617ad0b5ee05f13
class SearchField(QLineEdit): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(SearchField, self).__init__() <NEW_LINE> self.__focus = False <NEW_LINE> <DEDENT> def focusInEvent(self, focusevent): <NEW_LINE> <INDENT> self.__focus = True <NEW_LINE> super(SearchField, self).focusInEvent(focusevent) <NEW_LINE> <DEDENT> def focusOutEvent(self, focusevent): <NEW_LINE> <INDENT> self.__focus = False <NEW_LINE> super(SearchField, self).focusInEvent(focusevent) <NEW_LINE> <DEDENT> def isFocused(self): <NEW_LINE> <INDENT> return self.__focus
This is a docstring
62598f9d91f36d47f2230d81
class Image(TimeStampedModel): <NEW_LINE> <INDENT> file = models.ImageField() <NEW_LINE> location = models.CharField(max_length=140) <NEW_LINE> caption = models.TextField() <NEW_LINE> creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name='images', null=True ) <NEW_LINE> tags = TaggableManager() <NEW_LINE> @property <NEW_LINE> def like_count(self): <NEW_LINE> <INDENT> return self.likes.all().count() <NEW_LINE> <DEDENT> @property <NEW_LINE> def comment_count(self): <NEW_LINE> <INDENT> return self.comments.all().count() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'{self.location} - {self.caption}' <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['-created_at']
Image Model
62598f9dd6c5a102081e1f08
class MasterRep(object): <NEW_LINE> <INDENT> def __init__(self, gtid_mode, exe_gtid, filename, pos): <NEW_LINE> <INDENT> self.gtid_mode = gtid_mode <NEW_LINE> self.exe_gtid = exe_gtid <NEW_LINE> self.file = filename <NEW_LINE> self.pos = pos
Class: MasterRep Description: Class stub holder for mysql_class.MasterRep class. Methods: __init__ -> Class initialization.
62598f9d30bbd72246469858
class CouchDBKit(object): <NEW_LINE> <INDENT> def __init__(self, app=None): <NEW_LINE> <INDENT> _include_couchdbkit(self) <NEW_LINE> if app is not None: <NEW_LINE> <INDENT> self.init_app(app) <NEW_LINE> <DEDENT> <DEDENT> def init_app(self, app): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.app.config.setdefault('COUCHDB_SERVER', 'http://localhost:5984/') <NEW_LINE> self.app.config.setdefault('COUCHDB_DATABASE', None) <NEW_LINE> self.app.config.setdefault('COUCHDB_KEEPALIVE', None) <NEW_LINE> self.app.config.setdefault('COUCHDB_VIEWS', '_design') <NEW_LINE> server_uri = app.config.get('COUCHDB_SERVER') <NEW_LINE> pool_keepalive = app.config.get('COUCHDB_KEEPALIVE') <NEW_LINE> if pool_keepalive is not None: <NEW_LINE> <INDENT> mgr = Manager(max_conn=pool_keepalive) <NEW_LINE> server = Server(server_uri, manager=mgr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> server = Server(server_uri) <NEW_LINE> <DEDENT> self.server = server <NEW_LINE> self.init_db() <NEW_LINE> <DEDENT> def init_db(self): <NEW_LINE> <INDENT> dbname = self.app.config.get('COUCHDB_DATABASE') <NEW_LINE> self.db = self.server.get_or_create_db(dbname) <NEW_LINE> self.Document._db = self.db <NEW_LINE> <DEDENT> def sync(self): <NEW_LINE> <INDENT> local_path = self.app.config.get('COUCHDB_VIEWS') <NEW_LINE> design_path = os.path.join(self.app.root_path, local_path) <NEW_LINE> loader = FileSystemDocsLoader(design_path) <NEW_LINE> loader.sync(self.db)
This class is used to control CouchDB integration to a Flask application. :param app: The application to which this CouchDBKit should be bound. If an app is not provided at initialization time, it may be provided later by calling `init_app` manually.
62598f9df7d966606f747dab
class PerformanceIncident(BaseIncident): <NEW_LINE> <INDENT> type = models.ForeignKey( PerformanceIncidentType, on_delete=models.CASCADE ) <NEW_LINE> performance = models.ForeignKey( Performance, on_delete=models.CASCADE ) <NEW_LINE> predicted = models.BooleanField(default=False) <NEW_LINE> def should_tweet(self): <NEW_LINE> <INDENT> return self.predicted == False and self.performance.occurred == False <NEW_LINE> <DEDENT> def get_incident_text(self): <NEW_LINE> <INDENT> if self.type.tweet: <NEW_LINE> <INDENT> text = self.type.tweet <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text ='%s - %s' % (self.type.title, self.type.description) <NEW_LINE> <DEDENT> return '%s! %s' % (self.type.get_penalty_display(), text) <NEW_LINE> <DEDENT> def get_context_hashtag(self): <NEW_LINE> <INDENT> return '#%s' % self.performance.song.country.hashtag <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> predicted='' <NEW_LINE> if self.predicted: <NEW_LINE> <INDENT> predicted=' (predicted)' <NEW_LINE> <DEDENT> return '%s%s during %s' % ( self.type.title, predicted, self.performance, )
An instance of a PerformanceIncidentType that has occurred during a specific Performance.
62598f9d07f4c71912baf20e
class TestX265SAONonDeblock(unittest.TestCase): <NEW_LINE> <INDENT> def test_x265_sao_non_deblock(self): <NEW_LINE> <INDENT> x265 = X265() <NEW_LINE> self._test_sao_non_deblock_normal_values(x265) <NEW_LINE> self._test_sao_non_deblock_abormal_values(x265) <NEW_LINE> <DEDENT> def _test_sao_non_deblock_normal_values(self, x265): <NEW_LINE> <INDENT> x265.sao_non_deblock = True <NEW_LINE> self.assertTrue(x265.sao_non_deblock) <NEW_LINE> x265.sao_non_deblock = False <NEW_LINE> self.assertFalse(x265.sao_non_deblock) <NEW_LINE> <DEDENT> def _test_sao_non_deblock_abormal_values(self, x265): <NEW_LINE> <INDENT> x265.sao_non_deblock = 1 <NEW_LINE> self.assertTrue(x265.sao_non_deblock) <NEW_LINE> x265.sao_non_deblock = 10 <NEW_LINE> self.assertTrue(x265.sao_non_deblock) <NEW_LINE> x265.sao_non_deblock = -1 <NEW_LINE> self.assertTrue(x265.sao_non_deblock) <NEW_LINE> x265.sao_non_deblock = -10 <NEW_LINE> self.assertTrue(x265.sao_non_deblock) <NEW_LINE> x265.sao_non_deblock = 'Hello, World!' <NEW_LINE> self.assertTrue(x265.sao_non_deblock) <NEW_LINE> x265.sao_non_deblock = 0 <NEW_LINE> self.assertFalse(x265.sao_non_deblock) <NEW_LINE> x265.sao_non_deblock = None <NEW_LINE> self.assertFalse(x265.sao_non_deblock) <NEW_LINE> x265.sao_non_deblock = '' <NEW_LINE> self.assertFalse(x265.sao_non_deblock)
Tests all SAO Non-Deblock option values for the x265 codec.
62598f9d3539df3088ecc079
class JobAPIStub(object): <NEW_LINE> <INDENT> def __init__(self, channel): <NEW_LINE> <INDENT> self.CreateJob = channel.unary_unary( '/descarteslabs.workflows.JobAPI/CreateJob', request_serializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.CreateJobRequest.SerializeToString, response_deserializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.Job.FromString, ) <NEW_LINE> self.ListJobs = channel.unary_stream( '/descarteslabs.workflows.JobAPI/ListJobs', request_serializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.ListJobsRequest.SerializeToString, response_deserializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.Job.FromString, ) <NEW_LINE> self.GetJob = channel.unary_unary( '/descarteslabs.workflows.JobAPI/GetJob', request_serializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.GetJobRequest.SerializeToString, response_deserializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.Job.FromString, ) <NEW_LINE> self.CancelJob = channel.unary_unary( '/descarteslabs.workflows.JobAPI/CancelJob', request_serializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.CancelJobRequest.SerializeToString, response_deserializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.CancelJobResponse.FromString, ) <NEW_LINE> self.WatchJob = channel.unary_stream( '/descarteslabs.workflows.JobAPI/WatchJob', request_serializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.WatchJobRequest.SerializeToString, response_deserializer=descarteslabs_dot_common_dot_proto_dot_job_dot_job__pb2.Job.State.FromString, )
Missing associated documentation comment in .proto file.
62598f9d3eb6a72ae038a404
class Builder: <NEW_LINE> <INDENT> __self_sql = '' <NEW_LINE> def sql(self, sql_str): <NEW_LINE> <INDENT> self.__self_sql = sql_str <NEW_LINE> <DEDENT> def build(self): <NEW_LINE> <INDENT> return self.__self_sql
数据库条件构造器
62598f9db5575c28eb712baf
class JavaScriptEngine(Engine): <NEW_LINE> <INDENT> _interpreter = JavaScriptInterpreter
The default JavaScript engine.
62598f9d0a50d4780f70519d
class Datetest(object): <NEW_LINE> <INDENT> defaultData = datetime(2013, 4, 15, 14, 4, 11), datetime(2013, 10, 25, 10, 50, 13), datetime(2014, 1, 1, 2, 0, 0) <NEW_LINE> def __init__(self, case=None, expected=None, data=None): <NEW_LINE> <INDENT> self.case = case <NEW_LINE> self.expected = expected if expected!=None else case <NEW_LINE> if data: <NEW_LINE> <INDENT> self.data = data <NEW_LINE> <DEDENT> elif case: <NEW_LINE> <INDENT> self.data = Datetest.gendata(Datetest.defaultData, case) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data = None <NEW_LINE> <DEDENT> self.options = None <NEW_LINE> self.formatstr = None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def gendata(dates, dateformat): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for date in dates: <NEW_LINE> <INDENT> datestr = datetime.strftime(date, dateformat) <NEW_LINE> data.append(datestr) <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.options = DateSense.detect_format(self.data) <NEW_LINE> self.formatstr = self.options.get_format_string() <NEW_LINE> success = (self.formatstr == self.expected) <NEW_LINE> if success: <NEW_LINE> <INDENT> casestr = " From: '" + (self.case if self.case else str(self.data)) + "'" <NEW_LINE> print("GOOD: Got: '" + self.formatstr + "'" + casestr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("FAIL: Got: '" + self.formatstr + "' Expected: '" + self.expected + "'") <NEW_LINE> print(self.options.get_long_debug_string()) <NEW_LINE> <DEDENT> return success
Class for testing various formats
62598f9d925a0f43d25e7e01
class Firm(Base): <NEW_LINE> <INDENT> __tablename__ = 'firm' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(String) <NEW_LINE> addr = Column(String) <NEW_LINE> longitude = Column(String) <NEW_LINE> latitude = Column(String) <NEW_LINE> last_updated = Column(DateTime) <NEW_LINE> lawyers = relationship('Lawyer', backref=backref('firm'))
classdocs
62598f9da79ad16197769e28
class ConstantOp(Op): <NEW_LINE> <INDENT> def __init__(self, value, name="Constant"): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> self.name = name <NEW_LINE> self.graph = graph.get_default_graph() <NEW_LINE> self.graph.add_to_graph(self) <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def forward(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def grad(self, partial_derivative_opname=None): <NEW_LINE> <INDENT> return 0
The constant operation which contains one initialized value.
62598f9d24f1403a92685794
class ProcesserManagerInitError(Exception): <NEW_LINE> <INDENT> def __init__(self, module, class_name, reason): <NEW_LINE> <INDENT> self.msg = "Can not Init class_name [%s] of module [%s] because of [%s]" % (class_name, module, reason) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.msg
init error
62598f9d99cbb53fe6830c96
class WinkToggleDevice(ToggleEntity): <NEW_LINE> <INDENT> def __init__(self, wink): <NEW_LINE> <INDENT> self.wink = wink <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return "{}.{}".format(self.__class__, self.wink.device_id()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.wink.name() <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self.wink.state() <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> self.wink.set_state(True) <NEW_LINE> <DEDENT> def turn_off(self): <NEW_LINE> <INDENT> self.wink.set_state(False) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.wink.update_state()
Represents a Wink toogle (switch) device.
62598f9d379a373c97d98dd9
class EletricCar(Car): <NEW_LINE> <INDENT> def __init__(self,make,model,year): <NEW_LINE> <INDENT> super().__init__(make,model,year) <NEW_LINE> self.battery_size = 70 <NEW_LINE> <DEDENT> def descript_battery(self): <NEW_LINE> <INDENT> print("这辆车拥有一个"+str(self.battery_size)+"kw/h的电池") <NEW_LINE> <DEDENT> def get_range(self): <NEW_LINE> <INDENT> if self.battery_size == 70: <NEW_LINE> <INDENT> range = 240 <NEW_LINE> <DEDENT> elif self.battery_size == 85: <NEW_LINE> <INDENT> range = 270 <NEW_LINE> <DEDENT> message = "这辆车的续航里程为:" + str(range) + "公里" <NEW_LINE> print(message)
定义电动车的不同之处
62598f9dcc0a2c111447add0
class MAC_INDUSTRY_AREA_ESTATE_INVEST_MONTH(Base): <NEW_LINE> <INDENT> __tablename__ = "MAC_INDUSTRY_AREA_ESTATE_INVEST_MONTH" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> stat_month = Column(String(20), nullable=False) <NEW_LINE> area_code = Column(String(20), nullable=False) <NEW_LINE> area_name = Column(String(100), nullable=False) <NEW_LINE> invest = Column(DECIMAL(20, 4)) <NEW_LINE> invest_yoy = Column(DECIMAL(10, 4)) <NEW_LINE> resident = Column(DECIMAL(20, 4)) <NEW_LINE> resident_yoy = Column(DECIMAL(10, 4)) <NEW_LINE> status = Column(TINYINT(display_width=4), default=0) <NEW_LINE> addtime = Column(TIMESTAMP, default=datetime.datetime.now) <NEW_LINE> modtime = Column(TIMESTAMP)
分地区房地产开发投资情况表(月度累计)
62598f9d851cf427c66b808c
class CreateNetworkForm(forms.Form): <NEW_LINE> <INDENT> network = forms.CharField(label='Network name', widget=forms.TextInput(attrs={'required':'required'})) <NEW_LINE> action = '' <NEW_LINE> back_link = '' <NEW_LINE> back_text = '' <NEW_LINE> submit = ''
description of class
62598f9d507cdc57c63a4b5a
class SimpleSpellController(BaseTextStylingController): <NEW_LINE> <INDENT> def getColorizingThread(self, page, params, runEvent): <NEW_LINE> <INDENT> return threading.Thread( None, self._colorizeThreadFunc, args=(params.text, params.editor, params.enableSpellChecking) ) <NEW_LINE> <DEDENT> def _colorizeThreadFunc(self, text, editor, enableSpellChecking): <NEW_LINE> <INDENT> if not enableSpellChecking: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> spellStatusFlags = [True] * len(text) <NEW_LINE> for start, end in self._splitText(text): <NEW_LINE> <INDENT> if not self._runColorizingEvent.is_set(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._checkSpell(editor, text, start, end, spellStatusFlags) <NEW_LINE> <DEDENT> wx.CallAfter(editor.markSpellErrors, spellStatusFlags) <NEW_LINE> <DEDENT> def _checkSpell(self, editor, text, start, end, spellStatusFlags): <NEW_LINE> <INDENT> spellChecker = editor.getSpellChecker() <NEW_LINE> errors = spellChecker.findErrors(text[start: end]) <NEW_LINE> for _word, err_start, err_end in errors: <NEW_LINE> <INDENT> spellStatusFlags[err_start + start: err_end + start] = [False] * (err_end - err_start) <NEW_LINE> <DEDENT> <DEDENT> def _splitText(self, text): <NEW_LINE> <INDENT> portion = 8000 <NEW_LINE> position = 0 <NEW_LINE> length = len(text) <NEW_LINE> while position < length: <NEW_LINE> <INDENT> newposition = text.rfind(' ', position, position + portion) <NEW_LINE> if newposition != -1: <NEW_LINE> <INDENT> yield (position, newposition) <NEW_LINE> position = newposition + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield (position, len(text)) <NEW_LINE> break
Base class for styling controller which spell check only
62598f9d01c39578d7f12b42
class ImagingXMLRPCClient(Pulse2Api): <NEW_LINE> <INDENT> name = "ImagingXMLRPCClient"
Imaging API XML-RPC client to connect to the MMC agent.
62598f9df8510a7c17d7e05a
@python_2_unicode_compatible <NEW_LINE> class AbstractResourceType(models.Model): <NEW_LINE> <INDENT> organisation = models.ForeignKey(Model['Organisation'], on_delete=models.CASCADE, verbose_name=_("organisation"), related_name='resource_types') <NEW_LINE> name = models.CharField(_("name"), max_length=255) <NEW_LINE> deleted = models.BooleanField(_("deleted"), default=False) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> verbose_name = _("resource type") <NEW_LINE> verbose_name_plural = _("resource types") <NEW_LINE> unique_together = ('organisation', 'name') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @transaction.atomic <NEW_LINE> def add_resource(self, name, stock=1): <NEW_LINE> <INDENT> resource = Model.Resource(name=name, stock=stock) <NEW_LINE> resource.resource_type = self <NEW_LINE> resource.full_clean() <NEW_LINE> resource.save(force_insert=True) <NEW_LINE> return resource
Représente un type de ressource.
62598f9d21bff66bcd722a29
class ActivityBase(QtWidgets.QWidget): <NEW_LINE> <INDENT> def __init__(self, name, parentwidget): <NEW_LINE> <INDENT> super(ActivityBase, self).__init__(parentwidget) <NEW_LINE> self._parent = parentwidget <NEW_LINE> self._mainmenubutton = None <NEW_LINE> self._write_to_status_bar('Loading ' + name + '...') <NEW_LINE> self.setObjectName(name) <NEW_LINE> self._create_content() <NEW_LINE> self._write_to_status_bar('') <NEW_LINE> <DEDENT> def set_main_menu_button(self, button): <NEW_LINE> <INDENT> self._mainmenubutton = button <NEW_LINE> <DEDENT> def get_main_menu_button(self): <NEW_LINE> <INDENT> return self._mainmenubutton <NEW_LINE> <DEDENT> def show_in_main_window(self): <NEW_LINE> <INDENT> self._parent.showActivity(self) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _create_content(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _create_scrollable_content(self): <NEW_LINE> <INDENT> content = QtWidgets.QWidget() <NEW_LINE> mainscroll = QtWidgets.QScrollArea() <NEW_LINE> mainscroll.setWidget(content) <NEW_LINE> mainscroll.setWidgetResizable(True) <NEW_LINE> mainlayout = QtWidgets.QVBoxLayout() <NEW_LINE> mainlayout.setContentsMargins(0, 0, 0, 0) <NEW_LINE> mainlayout.setSpacing(0) <NEW_LINE> mainlayout.addWidget(mainscroll) <NEW_LINE> self.setLayout(mainlayout) <NEW_LINE> return content <NEW_LINE> <DEDENT> def _write_to_status_bar(self, message): <NEW_LINE> <INDENT> self._parent.statusBar().showMessage(message) <NEW_LINE> <DEDENT> def _write_to_log(self, message): <NEW_LINE> <INDENT> self._parent.write_to_log(message)
Abstract base class for activities.
62598f9df7d966606f747dac
class EnrichrAPIError(APIError): <NEW_LINE> <INDENT> pass
Exception raised for errors communicating with the Enrichr API.
62598f9d0a50d4780f70519e
class JsonDict(dict): <NEW_LINE> <INDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[attr] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr) <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, attr, value): <NEW_LINE> <INDENT> self[attr] = value
general json object that allows attributes to be bound to and also behaves like a dict
62598f9d1b99ca400228f410
class OutputSplitter(object): <NEW_LINE> <INDENT> def __init__(self, nextFile, max_file_size=0, compress=True): <NEW_LINE> <INDENT> self.nextFile = nextFile <NEW_LINE> self.compress = compress <NEW_LINE> self.max_file_size = max_file_size <NEW_LINE> self.file = self.open(self.nextFile.next()) <NEW_LINE> <DEDENT> def reserve(self, size): <NEW_LINE> <INDENT> if self.file.tell() + size > self.max_file_size: <NEW_LINE> <INDENT> self.close() <NEW_LINE> self.file = self.open(self.nextFile.next()) <NEW_LINE> <DEDENT> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> self.reserve(len(data)) <NEW_LINE> self.file.write(data) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.file.close() <NEW_LINE> <DEDENT> def open(self, filename): <NEW_LINE> <INDENT> if self.compress: <NEW_LINE> <INDENT> return bz2.BZ2File(filename + '.bz2', 'w') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return open(filename, 'w')
File-like object, that splits output to multiple files of a given max size.
62598f9df7d966606f747dad
class BadCharReplacer: <NEW_LINE> <INDENT> def __init__(self, f, charmap=None): <NEW_LINE> <INDENT> self.reader = f <NEW_LINE> self.charmap = charmap <NEW_LINE> if self.charmap is None: <NEW_LINE> <INDENT> self.charmap = { '\xc2\x85' : '...', } <NEW_LINE> <DEDENT> self.pattern = '(' + '|'.join(self.charmap.keys()) + ')' <NEW_LINE> self.rx = re.compile(self.pattern) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> val = self.reader.next() <NEW_LINE> def replace_chars(match): <NEW_LINE> <INDENT> char = match.group(0) <NEW_LINE> return self.charmap[char] <NEW_LINE> <DEDENT> if self.rx.search(val) is not None: <NEW_LINE> <INDENT> return self.rx.sub(replace_chars, val) <NEW_LINE> <DEDENT> return val
Iterator that reads an encoded stream and replaces Bad Characters! The underlying reader MUST be returning UTF-8 encoded unicode strings
62598f9d45492302aabfc29e
class DataLoadError(Exception): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> message = 'Invalid file' <NEW_LINE> Exception.__init__(self, message)
Loading data error
62598f9dcb5e8a47e493c057
class LuksClient(base_client.CauliflowerVestClient): <NEW_LINE> <INDENT> ESCROW_PATH = '/luks' <NEW_LINE> REQUIRED_METADATA = base_settings.LUKS_REQUIRED_PROPERTIES <NEW_LINE> def UploadPassphrase(self, volume_uuid, passphrase, metadata): <NEW_LINE> <INDENT> self._metadata = metadata <NEW_LINE> super(LuksClient, self).UploadPassphrase(volume_uuid, passphrase)
Client to perform Luks operations.
62598f9d8e7ae83300ee8e65
class Driver: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.current_focus = False <NEW_LINE> <DEDENT> def focus(self, newFocus): <NEW_LINE> <INDENT> if(self.current_focus): <NEW_LINE> <INDENT> self.blur() <NEW_LINE> <DEDENT> self.current_focus = newFocus <NEW_LINE> if(self.current_focus): <NEW_LINE> <INDENT> self.current_focus.focused() <NEW_LINE> <DEDENT> <DEDENT> def blur(self): <NEW_LINE> <INDENT> if(self.current_focus): <NEW_LINE> <INDENT> self.current_focus.blurred() <NEW_LINE> <DEDENT> self.current_focus = False <NEW_LINE> <DEDENT> def focused(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def blurred(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def command(self, which): <NEW_LINE> <INDENT> if(not self.current_focus): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.current_focus.command(which) <NEW_LINE> <DEDENT> def display(self, screen, *args): <NEW_LINE> <INDENT> if(not self.current_focus): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.current_focus.display(screen, *args)
Driver is a class which represents any structure for handling client input and output. display and command are the main methods provided for override by subclasses. Both methods, by default, invoke the same method on their current_focus. Both should return True to indicate they are "blocking". For example, a sub-driver might wish to indicate that it has handled player keyboard input, and no further handling should be performed by the parent.
62598f9d7d847024c075c197
class OperationNodeStructure(NodeStructure): <NEW_LINE> <INDENT> def __init__(self, operation_gid): <NEW_LINE> <INDENT> NodeStructure.__init__(self, operation_gid, "") <NEW_LINE> operation = dao.get_operation_by_gid(operation_gid) <NEW_LINE> algo = dao.get_algorithm_by_id(operation.fk_from_algo) <NEW_LINE> node_data = NodeData(MAX_SHAPE_SIZE, OPERATION_SHAPE_COLOR, OPERATION_SHAPE, NODE_OPERATION_TYPE, operation.id, str(operation.start_date)) <NEW_LINE> self.name = algo.name <NEW_LINE> self.data = node_data
This class knows how to create a NodeStructure for a given Operation.
62598f9d67a9b606de545d8f
class _ContextConfig(object): <NEW_LINE> <INDENT> def __init__(self, logger): <NEW_LINE> <INDENT> self.logger = logger <NEW_LINE> self.use_client_certificate = config.getbool('Credentials', 'use_client_certificate') <NEW_LINE> self.client_cert_path = None <NEW_LINE> if not self.use_client_certificate: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> atexit.register(self._unprovision_client_cert) <NEW_LINE> self.client_cert_path = os.path.join(gslib.GSUTIL_DIR, 'caa_cert.pem') <NEW_LINE> try: <NEW_LINE> <INDENT> self._provision_client_cert(self.client_cert_path) <NEW_LINE> <DEDENT> except CertProvisionError as e: <NEW_LINE> <INDENT> self.logger.error('Failed to provision client certificate: %s' % e) <NEW_LINE> <DEDENT> <DEDENT> def _provision_client_cert(self, cert_path): <NEW_LINE> <INDENT> cert_command_string = config.get('Credentials', 'cert_provider_command', None) <NEW_LINE> if cert_command_string: <NEW_LINE> <INDENT> cert_command = cert_command_string.split(' ') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cert_command = _default_command() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> command_stdout_string, _ = execution_util.ExecuteExternalCommand( cert_command) <NEW_LINE> sections = _split_pem_into_sections(command_stdout_string, self.logger) <NEW_LINE> with open(cert_path, 'w+') as f: <NEW_LINE> <INDENT> f.write(sections['CERTIFICATE']) <NEW_LINE> f.write(sections['ENCRYPTED PRIVATE KEY']) <NEW_LINE> <DEDENT> self.client_cert_password = sections['PASSPHRASE'].splitlines()[1] <NEW_LINE> <DEDENT> except (exception.ExternalBinaryError, OSError) as e: <NEW_LINE> <INDENT> raise CertProvisionError(e) <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> raise CertProvisionError( 'Invalid output format from certificate provider, no %s' % e) <NEW_LINE> <DEDENT> <DEDENT> def _unprovision_client_cert(self): <NEW_LINE> <INDENT> if self.client_cert_path is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(self.client_cert_path) <NEW_LINE> self.logger.debug('Unprovisioned client cert: %s' % self.client_cert_path) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> self.logger.error('Failed to remove client certificate: %s' % e)
Represents the configurations associated with context aware access. Only one instance of Config can be created for the program.
62598f9d097d151d1a2c0ded
class V1beta1QueuingConfiguration(object): <NEW_LINE> <INDENT> openapi_types = { 'hand_size': 'int', 'queue_length_limit': 'int', 'queues': 'int' } <NEW_LINE> attribute_map = { 'hand_size': 'handSize', 'queue_length_limit': 'queueLengthLimit', 'queues': 'queues' } <NEW_LINE> def __init__(self, hand_size=None, queue_length_limit=None, queues=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration.get_default_copy() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._hand_size = None <NEW_LINE> self._queue_length_limit = None <NEW_LINE> self._queues = None <NEW_LINE> self.discriminator = None <NEW_LINE> if hand_size is not None: <NEW_LINE> <INDENT> self.hand_size = hand_size <NEW_LINE> <DEDENT> if queue_length_limit is not None: <NEW_LINE> <INDENT> self.queue_length_limit = queue_length_limit <NEW_LINE> <DEDENT> if queues is not None: <NEW_LINE> <INDENT> self.queues = queues <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def hand_size(self): <NEW_LINE> <INDENT> return self._hand_size <NEW_LINE> <DEDENT> @hand_size.setter <NEW_LINE> def hand_size(self, hand_size): <NEW_LINE> <INDENT> self._hand_size = hand_size <NEW_LINE> <DEDENT> @property <NEW_LINE> def queue_length_limit(self): <NEW_LINE> <INDENT> return self._queue_length_limit <NEW_LINE> <DEDENT> @queue_length_limit.setter <NEW_LINE> def queue_length_limit(self, queue_length_limit): <NEW_LINE> <INDENT> self._queue_length_limit = queue_length_limit <NEW_LINE> <DEDENT> @property <NEW_LINE> def queues(self): <NEW_LINE> <INDENT> return self._queues <NEW_LINE> <DEDENT> @queues.setter <NEW_LINE> def queues(self, queues): <NEW_LINE> <INDENT> self._queues = queues <NEW_LINE> <DEDENT> def to_dict(self, serialize=False): <NEW_LINE> <INDENT> result = {} <NEW_LINE> def convert(x): <NEW_LINE> <INDENT> if hasattr(x, "to_dict"): <NEW_LINE> <INDENT> args = getfullargspec(x.to_dict).args <NEW_LINE> if len(args) == 1: <NEW_LINE> <INDENT> return x.to_dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x.to_dict(serialize) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> <DEDENT> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> attr = self.attribute_map.get(attr, attr) if serialize else attr <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: convert(x), value )) <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], convert(item[1])), value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = convert(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, V1beta1QueuingConfiguration): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1beta1QueuingConfiguration): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598f9d32920d7e50bc5e1c
class lvars_info_t(abyss_filter_t): <NEW_LINE> <INDENT> def maturity_ev(self, cfunc, new_maturity): <NEW_LINE> <INDENT> if new_maturity == ida_hexrays.CMAT_FINAL: <NEW_LINE> <INDENT> lvars = cfunc.get_lvars() <NEW_LINE> for lvar in lvars: <NEW_LINE> <INDENT> if lvar.has_nice_name and not lvar.has_user_name: <NEW_LINE> <INDENT> vtype = "s" if lvar.is_stk_var() else "r" if lvar.is_reg_var() else "u" <NEW_LINE> suffix = "_%s%d" % (vtype, lvar.width) <NEW_LINE> lvar.name += ida_lines.COLSTR(suffix, ida_lines.SCOLOR_AUTOCMT) <NEW_LINE> lvar.set_user_name() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return 0
appends a postfix to local variables that indicates each variable's type (*r*egister or *s*tack) and its size in bytes.
62598f9d99cbb53fe6830c98
class DocumentAnalysisError(object): <NEW_LINE> <INDENT> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> self.code = kwargs.get('code', None) <NEW_LINE> self.message = kwargs.get('message', None) <NEW_LINE> self.target = kwargs.get('target', None) <NEW_LINE> self.details = kwargs.get('details', None) <NEW_LINE> self.innererror = kwargs.get('innererror', None) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ( "DocumentAnalysisError(code={}, message={}, target={}, details={}, innererror={})".format( self.code, self.message, self.target, repr(self.details), repr(self.innererror) ) ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _from_generated(cls, err): <NEW_LINE> <INDENT> return cls( code=err.code, message=err.message, target=err.target, details=[DocumentAnalysisError._from_generated(e) for e in err.details] if err.details else [], innererror=DocumentAnalysisInnerError._from_generated(err.innererror) if err.innererror else None ) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return { "code": self.code, "message": self.message, "target": self.target, "details": [detail.to_dict() for detail in self.details] if self.details else [], "innererror": self.innererror.to_dict() if self.innererror else None } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, data): <NEW_LINE> <INDENT> return cls( code=data.get("code", None), message=data.get("message", None), target=data.get("target", None), details=[DocumentAnalysisError.from_dict(e) for e in data.get("details")] if data.get("details") else [], innererror=DocumentAnalysisInnerError.from_dict(data.get("innererror")) if data.get("innererror") else None )
DocumentAnalysisError contains the details of the error returned by the service. :ivar code: Error code. :vartype code: str :ivar message: Error message. :vartype message: str :ivar target: Target of the error. :vartype target: str :ivar details: List of detailed errors. :vartype details: list[~azure.ai.formrecognizer.DocumentAnalysisError] :ivar innererror: Detailed error. :vartype innererror: ~azure.ai.formrecognizer.DocumentAnalysisInnerError
62598f9d1f5feb6acb1629e8
class RealValueVectorOrg(object): <NEW_LINE> <INDENT> def __init__(self, genotype=None): <NEW_LINE> <INDENT> if genotype is None: <NEW_LINE> <INDENT> genotype = _create_random_genotype() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> genotype = np.asarray(genotype, dtype=np.float64) <NEW_LINE> <DEDENT> self.genotype = genotype <NEW_LINE> self._fitness_cache = None <NEW_LINE> <DEDENT> def fitness(self, environment): <NEW_LINE> <INDENT> if self._fitness_cache is None: <NEW_LINE> <INDENT> self._fitness_cache = {} <NEW_LINE> self._fitness_cache[environment] = environment(self.genotype) <NEW_LINE> <DEDENT> elif environment not in self._fitness_cache: <NEW_LINE> <INDENT> self._fitness_cache[environment] = environment(self.genotype) <NEW_LINE> <DEDENT> return self._fitness_cache[environment] <NEW_LINE> <DEDENT> def reset_fitness_cache(self): <NEW_LINE> <INDENT> self._fitness_cache = None <NEW_LINE> <DEDENT> def get_mutant(self): <NEW_LINE> <INDENT> return RealValueVectorOrg(_get_mutated_genotype(self.genotype, MUTATION_EFFECT_SIZE)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.genotype == other.genotype <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "RealValueVectorOrg({})".format(self.genotype) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def is_better_than(self, other, environment): <NEW_LINE> <INDENT> return self.fitness(environment) < other.fitness(environment) <NEW_LINE> <DEDENT> def distance(self, other, environment): <NEW_LINE> <INDENT> dist = 0.0 <NEW_LINE> for i in range(self.genotype.shape[0]): <NEW_LINE> <INDENT> dist += (self.genotype[i] - other.genotype[i])**2 <NEW_LINE> <DEDENT> return sqrt(dist)
this is a class that represents organisms as a real value array fitness is determined by calling the fitness fuction the length is determined at object creation
62598f9d3539df3088ecc07c
class EditDialogMixin(object): <NEW_LINE> <INDENT> def __init__(self, orig_data): <NEW_LINE> <INDENT> bb = self.get_action_area() <NEW_LINE> self.refresh = Gtk.Button(Gtk.STOCK_REFRESH) <NEW_LINE> self.refresh.set_use_stock(True) <NEW_LINE> self.refresh.connect("clicked", lambda w: self.from_tuple(orig_data)) <NEW_LINE> bb.add(self.refresh) <NEW_LINE> bb.set_child_secondary(self.refresh, True) <NEW_LINE> self.refresh.clicked() <NEW_LINE> self.delete = Gtk.Button(stock=Gtk.STOCK_DELETE) <NEW_LINE> bb.add(self.delete) <NEW_LINE> <DEDENT> def delete_confirmation(self, deleter): <NEW_LINE> <INDENT> return deleter
Mix-in class to convert initial-data-entry dialogs to edit dialogs.
62598f9da17c0f6771d5c001
class FTP_TLS(FTP): <NEW_LINE> <INDENT> def __init__(self, host=None, ssl_ctx=None): <NEW_LINE> <INDENT> if ssl_ctx is not None: <NEW_LINE> <INDENT> self.ssl_ctx = ssl_ctx <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ssl_ctx = SSL.Context(DEFAULT_PROTOCOL) <NEW_LINE> <DEDENT> FTP.__init__(self, host) <NEW_LINE> self.prot = 0 <NEW_LINE> <DEDENT> def auth_tls(self): <NEW_LINE> <INDENT> self.voidcmd('AUTH TLS') <NEW_LINE> s = SSL.Connection(self.ssl_ctx, self.sock) <NEW_LINE> s.setup_ssl() <NEW_LINE> s.set_connect_state() <NEW_LINE> s.connect_ssl() <NEW_LINE> self.sock = s <NEW_LINE> self.file = self.sock.makefile() <NEW_LINE> <DEDENT> def auth_ssl(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def prot_p(self): <NEW_LINE> <INDENT> self.voidcmd('PBSZ 0') <NEW_LINE> self.voidcmd('PROT P') <NEW_LINE> self.prot = 1 <NEW_LINE> <DEDENT> def prot_c(self): <NEW_LINE> <INDENT> self.voidcmd('PROT C') <NEW_LINE> self.prot = 0 <NEW_LINE> <DEDENT> def ntransfercmd(self, cmd, rest=None): <NEW_LINE> <INDENT> conn, size = FTP.ntransfercmd(self, cmd, rest) <NEW_LINE> if self.prot: <NEW_LINE> <INDENT> conn = SSL.Connection(self.ssl_ctx, conn) <NEW_LINE> conn.setup_ssl() <NEW_LINE> conn.set_connect_state() <NEW_LINE> conn.set_session(self.sock.get_session()) <NEW_LINE> conn.connect_ssl() <NEW_LINE> <DEDENT> return conn, size
Python OO interface to client-side FTP/TLS.
62598f9d851cf427c66b808e
class Loader(object): <NEW_LINE> <INDENT> def __init__(*args, **kwargs): pass <NEW_LINE> def load(self): pass
Base loader class for :class:`LoadedDataStruct`
62598f9d67a9b606de545d90
class Payment(BaseModel): <NEW_LINE> <INDENT> order = models.ForeignKey(OrderInfo, on_delete=models.CASCADE, verbose_name="订单") <NEW_LINE> trade_id = models.CharField(max_length=100, unique=True, null=True, blank=True, verbose_name="支付编号") <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = "tb_paymnet" <NEW_LINE> verbose_name = "支付信息" <NEW_LINE> verbose_name_plural = verbose_name
支付信息
62598f9d55399d3f056262e8
class WebviewTests(DemoDatabaseTestCase): <NEW_LINE> <INDENT> def test_any_records_use_group_true(self) -> None: <NEW_LINE> <INDENT> self.announce("test_any_records_use_group_true") <NEW_LINE> self.assertTrue(any_records_use_group(self.req, self.group)) <NEW_LINE> <DEDENT> def test_any_records_use_group_false(self) -> None: <NEW_LINE> <INDENT> self.announce("test_any_records_use_group_false") <NEW_LINE> group = Group() <NEW_LINE> self.dbsession.add(self.group) <NEW_LINE> self.dbsession.commit() <NEW_LINE> self.assertFalse(any_records_use_group(self.req, group)) <NEW_LINE> <DEDENT> def test_webview_constant_validators(self) -> None: <NEW_LINE> <INDENT> self.announce("test_webview_constant_validators") <NEW_LINE> for x in class_attribute_names(ViewArg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> validate_alphanum_underscore(x, self.req) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> self.fail(f"Operations.{x} fails validate_alphanum_underscore")
Unit tests.
62598f9d5f7d997b871f92c2
class HelloHandler(RosieDiscoService): <NEW_LINE> <INDENT> HELLO = "Hello %s\n" <NEW_LINE> def get(self, *args): <NEW_LINE> <INDENT> format_arg = self.get_query_argument("format", default=None) <NEW_LINE> data = self.HELLO % pwd.getpwuid(os.getuid()).pw_name <NEW_LINE> if format_arg == "json": <NEW_LINE> <INDENT> self.write(json.dumps(data)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.write(data)
Writes a 'Hello' message to the current logged-in user, else 'user'.
62598f9d38b623060ffa8e58
class CandidateSearch(object): <NEW_LINE> <INDENT> swagger_types = { 'id': 'str', 'name': 'str', 'office_sought': 'str' } <NEW_LINE> attribute_map = { 'id': 'id', 'name': 'name', 'office_sought': 'office_sought' } <NEW_LINE> def __init__(self, id=None, name=None, office_sought=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._name = None <NEW_LINE> self._office_sought = None <NEW_LINE> self.discriminator = None <NEW_LINE> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> if name is not None: <NEW_LINE> <INDENT> self.name = name <NEW_LINE> <DEDENT> if office_sought is not None: <NEW_LINE> <INDENT> self.office_sought = office_sought <NEW_LINE> <DEDENT> <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 name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def office_sought(self): <NEW_LINE> <INDENT> return self._office_sought <NEW_LINE> <DEDENT> @office_sought.setter <NEW_LINE> def office_sought(self, office_sought): <NEW_LINE> <INDENT> self._office_sought = office_sought <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(CandidateSearch, 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, CandidateSearch): <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.
62598f9d0c0af96317c56149
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class Decoder(object): <NEW_LINE> <INDENT> @property <NEW_LINE> def batch_size(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_size(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_dtype(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def initialize(self, name=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def step(self, time, inputs, state, name=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def finalize(self, outputs, final_state, sequence_lengths): <NEW_LINE> <INDENT> raise NotImplementedError
An RNN Decoder abstract interface object. Concepts used by this interface: - `inputs`: (structure of) tensors and TensorArrays that is passed as input to the RNNCell composing the decoder, at each time step. - `state`: (structure of) tensors and TensorArrays that is passed to the RNNCell instance as the state. - `finished`: boolean tensor telling whether each sequence in the batch is finished. - `outputs`: Instance of BasicDecoderOutput. Result of the decoding, at each time step.
62598f9d3d592f4c4edbac95
class CommonAvgRef(PreprocPipe): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self = self <NEW_LINE> <DEDENT> def _pipe_as_flow(self, signal_packet): <NEW_LINE> <INDENT> hkey = signal_packet.keys()[0] <NEW_LINE> data = signal_packet[hkey]['data'] <NEW_LINE> data = (data.T - data.mean(axis=1)).T <NEW_LINE> signal_packet[hkey]['data'] = data <NEW_LINE> return signal_packet
CommonAvgRef pipe for removing the common-average from the signal
62598f9d10dbd63aa1c7097d
class Rectangle: <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) is not int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.height * self.width <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return (2 * self.height) + (2 * self.width) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.width == 0 or self.height == 0: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> Rect = "" <NEW_LINE> for i in range(self.height): <NEW_LINE> <INDENT> Rect += "#" * self.width <NEW_LINE> Rect += "\n" <NEW_LINE> <DEDENT> return Rect[:-1]
Show the attribute of rectangle
62598f9d60cbc95b06364114
class ZMQDisplayPublisher(DisplayPublisher): <NEW_LINE> <INDENT> session = Instance(Session) <NEW_LINE> pub_socket = Instance('zmq.Socket') <NEW_LINE> parent_header = Dict({}) <NEW_LINE> topic = CBytes(b'displaypub') <NEW_LINE> def set_parent(self, parent): <NEW_LINE> <INDENT> self.parent_header = extract_header(parent) <NEW_LINE> <DEDENT> def _flush_streams(self): <NEW_LINE> <INDENT> sys.stdout.flush() <NEW_LINE> sys.stderr.flush() <NEW_LINE> <DEDENT> def publish(self, source, data, metadata=None): <NEW_LINE> <INDENT> self._flush_streams() <NEW_LINE> if metadata is None: <NEW_LINE> <INDENT> metadata = {} <NEW_LINE> <DEDENT> self._validate_data(source, data, metadata) <NEW_LINE> content = {} <NEW_LINE> content['source'] = source <NEW_LINE> _encode_binary(data) <NEW_LINE> content['data'] = data <NEW_LINE> content['metadata'] = metadata <NEW_LINE> self.session.send( self.pub_socket, u'display_data', json_clean(content), parent=self.parent_header, ident=self.topic, ) <NEW_LINE> <DEDENT> def clear_output(self, stdout=True, stderr=True, other=True): <NEW_LINE> <INDENT> content = dict(stdout=stdout, stderr=stderr, other=other) <NEW_LINE> if stdout: <NEW_LINE> <INDENT> print('\r', file=sys.stdout, end='') <NEW_LINE> <DEDENT> if stderr: <NEW_LINE> <INDENT> print('\r', file=sys.stderr, end='') <NEW_LINE> <DEDENT> self._flush_streams() <NEW_LINE> self.session.send( self.pub_socket, u'clear_output', content, parent=self.parent_header, ident=self.topic, )
A display publisher that publishes data using a ZeroMQ PUB socket.
62598f9d435de62698e9bbbb
class TfvcItemRequestData(Model): <NEW_LINE> <INDENT> _attribute_map = { 'include_content_metadata': {'key': 'includeContentMetadata', 'type': 'bool'}, 'include_links': {'key': 'includeLinks', 'type': 'bool'}, 'item_descriptors': {'key': 'itemDescriptors', 'type': '[TfvcItemDescriptor]'} } <NEW_LINE> def __init__(self, include_content_metadata=None, include_links=None, item_descriptors=None): <NEW_LINE> <INDENT> super(TfvcItemRequestData, self).__init__() <NEW_LINE> self.include_content_metadata = include_content_metadata <NEW_LINE> self.include_links = include_links <NEW_LINE> self.item_descriptors = item_descriptors
TfvcItemRequestData. :param include_content_metadata: If true, include metadata about the file type :type include_content_metadata: bool :param include_links: Whether to include the _links field on the shallow references :type include_links: bool :param item_descriptors: :type item_descriptors: list of :class:`TfvcItemDescriptor <tfvc.v4_0.models.TfvcItemDescriptor>`
62598f9d8e71fb1e983bb87d
class JobStages(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'stage_name': {'readonly': True}, 'display_name': {'readonly': True}, 'stage_status': {'readonly': True}, 'stage_time': {'readonly': True}, 'job_stage_details': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'stage_name': {'key': 'stageName', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'stage_status': {'key': 'stageStatus', 'type': 'str'}, 'stage_time': {'key': 'stageTime', 'type': 'iso-8601'}, 'job_stage_details': {'key': 'jobStageDetails', 'type': 'object'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(JobStages, self).__init__(**kwargs) <NEW_LINE> self.stage_name = None <NEW_LINE> self.display_name = None <NEW_LINE> self.stage_status = None <NEW_LINE> self.stage_time = None <NEW_LINE> self.job_stage_details = None
Job stages. Variables are only populated by the server, and will be ignored when sending a request. :ivar stage_name: Name of the job stage. Possible values include: "DeviceOrdered", "DevicePrepared", "Dispatched", "Delivered", "PickedUp", "AtAzureDC", "DataCopy", "Completed", "CompletedWithErrors", "Cancelled", "Failed_IssueReportedAtCustomer", "Failed_IssueDetectedAtAzureDC", "Aborted", "CompletedWithWarnings", "ReadyToDispatchFromAzureDC", "ReadyToReceiveAtAzureDC". :vartype stage_name: str or ~azure.mgmt.databox.models.StageName :ivar display_name: Display name of the job stage. :vartype display_name: str :ivar stage_status: Status of the job stage. Possible values include: "None", "InProgress", "Succeeded", "Failed", "Cancelled", "Cancelling", "SucceededWithErrors", "WaitingForCustomerAction", "SucceededWithWarnings". :vartype stage_status: str or ~azure.mgmt.databox.models.StageStatus :ivar stage_time: Time for the job stage in UTC ISO 8601 format. :vartype stage_time: ~datetime.datetime :ivar job_stage_details: Job Stage Details. :vartype job_stage_details: object
62598f9d07f4c71912baf212
class TestInlineResponse20027Schedules(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testInlineResponse20027Schedules(self): <NEW_LINE> <INDENT> pass
InlineResponse20027Schedules unit test stubs
62598f9d56b00c62f0fb2678
class Cekit(object): <NEW_LINE> <INDENT> def __init__(self, params): <NEW_LINE> <INDENT> self.params = params <NEW_LINE> <DEDENT> def init(self): <NEW_LINE> <INDENT> if self.params.nocolor: <NEW_LINE> <INDENT> setup_logging(False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> setup_logging() <NEW_LINE> <DEDENT> if self.params.verbose: <NEW_LINE> <INDENT> LOGGER.setLevel(logging.DEBUG) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOGGER.setLevel(logging.INFO) <NEW_LINE> <DEDENT> LOGGER.debug("Running version {}".format(__version__)) <NEW_LINE> if 'dev' in __version__ or 'rc' in __version__: <NEW_LINE> <INDENT> LOGGER.warning("You are running unreleased development version of CEKit, " "use it only at your own risk!") <NEW_LINE> <DEDENT> <DEDENT> def configure(self): <NEW_LINE> <INDENT> LOGGER.debug("Configuring CEKit...") <NEW_LINE> CONFIG.configure(self.params.config, { 'redhat': self.params.redhat, 'work_dir': self.params.work_dir }) <NEW_LINE> <DEDENT> def cleanup(self): <NEW_LINE> <INDENT> directories_to_clean = [os.path.join(self.params.target, 'image', 'modules'), os.path.join(self.params.target, 'image', 'repos'), os.path.join(self.params.target, 'repo')] <NEW_LINE> for directory in directories_to_clean: <NEW_LINE> <INDENT> if os.path.exists(directory): <NEW_LINE> <INDENT> LOGGER.debug("Removing dirty directory: '{}'".format(directory)) <NEW_LINE> try: <NEW_LINE> <INDENT> shutil.rmtree(directory) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise CekitError("Unable to clean directory '{}'".format(directory)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def run(self, clazz): <NEW_LINE> <INDENT> self.init() <NEW_LINE> self.configure() <NEW_LINE> self.cleanup() <NEW_LINE> command = clazz(self.params) <NEW_LINE> try: <NEW_LINE> <INDENT> command.execute() <NEW_LINE> LOGGER.info("Finished!") <NEW_LINE> sys.exit(0) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except CekitError as ex: <NEW_LINE> <INDENT> if self.params.verbose: <NEW_LINE> <INDENT> LOGGER.exception(ex) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOGGER.error(ex.message) <NEW_LINE> <DEDENT> sys.exit(1)
Main application
62598f9dbe8e80087fbbee26
class TestDeleteSessionByToken(DatabaseTestCase): <NEW_LINE> <INDENT> def test_deletes_session_when_session_exists(self): <NEW_LINE> <INDENT> user = User( username='username', password='password', salt='salt', ).save() <NEW_LINE> Session( user=user, token='token', ).save() <NEW_LINE> session = Session.objects.get(token='token') <NEW_LINE> assert session is not None <NEW_LINE> result = SessionService.delete_session_by_token('token') <NEW_LINE> assert result is True <NEW_LINE> with pytest.raises(Session.DoesNotExist): <NEW_LINE> <INDENT> Session.objects.get(token='token') <NEW_LINE> <DEDENT> <DEDENT> def test_fails_silently_when_session_does_not_exist(self): <NEW_LINE> <INDENT> result = SessionService.delete_session_by_token('token') <NEW_LINE> assert result is False <NEW_LINE> with pytest.raises(Session.DoesNotExist): <NEW_LINE> <INDENT> Session.objects.get(token='token')
Test for the delete_session_by_token function.
62598f9d91af0d3eaad39bd2
class PocketAPI: <NEW_LINE> <INDENT> def __init__(self, consumer_key=None, access_token=None): <NEW_LINE> <INDENT> self.consumer_key = consumer_key <NEW_LINE> self.access_token = access_token <NEW_LINE> <DEDENT> def get_request_token(self): <NEW_LINE> <INDENT> headers = { 'content-type': 'application/json; charset=UTF-8', 'x-accept': 'application/json' } <NEW_LINE> data = { 'consumer_key': self.consumer_key, 'redirect_uri': 'https://getpocket.com/v3/oauth/authorize' } <NEW_LINE> pocket_api = requests.post( 'https://getpocket.com/v3/oauth/request', data=json.dumps(data), headers=headers ) <NEW_LINE> r = json.loads(pocket_api.text) <NEW_LINE> return r['code'] <NEW_LINE> <DEDENT> def get_access_token(self, request_token): <NEW_LINE> <INDENT> headers = { 'content-type': 'application/json; charset=UTF-8', 'x-accept': 'application/json' } <NEW_LINE> data = { 'consumer_key': self.consumer_key, 'code': request_token } <NEW_LINE> pocket_api = requests.post( 'https://getpocket.com/v3/oauth/authorize', data=json.dumps(data), headers=headers ) <NEW_LINE> r = json.loads(pocket_api.text) <NEW_LINE> return r['access_token'] <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> if not self.access_token: <NEW_LINE> <INDENT> self.request_token = self.get_request_token() <NEW_LINE> print("[*] Request token: %s" % self.request_token) <NEW_LINE> print("Now you need to authorize this app to access your getpocket list.") <NEW_LINE> print("Open this URL in your browser: https://getpocket.com/auth/authorize?request_token=%s&redirect_uri=https://getpocket.com" % self.request_token) <NEW_LINE> input("Press Enter to continue...") <NEW_LINE> self.access_token = self.get_access_token(self.request_token) <NEW_LINE> print("[*] Access token: %s" % self.access_token) <NEW_LINE> <DEDENT> self.p = Pocket( consumer_key=self.consumer_key, access_token=self.access_token ) <NEW_LINE> <DEDENT> def get(self, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.p.retrieve(**kwargs) <NEW_LINE> <DEDENT> except PocketException as e: <NEW_LINE> <INDENT> print(e.message) <NEW_LINE> return None
Wrapper around https://pypi.python.org/pypi/pocket-api/
62598f9db7558d58954633f6
class Distributor(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def metadata(cls): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def validate_config(self, repo, config, related_repos): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def distributor_added(self, repo, config): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def distributor_removed(self, repo, config): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def publish_repo(self, repo, publish_conduit, config): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def cancel_publish_repo(self, call_request, call_report): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def create_consumer_payload(self, repo, config, binding_config): <NEW_LINE> <INDENT> return {}
Base class for Pulp content distributors for a single repository. Distributors must subclass this class in order for Pulp to identify it as a valid distributor during discovery.
62598f9d236d856c2adc931d
class TreeLSTM(nn.Module): <NEW_LINE> <INDENT> def __init__(self, in_features, hidden_size): <NEW_LINE> <INDENT> super(TreeLSTM, self).__init__() <NEW_LINE> self.in_features = in_features <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.cell = TreeLSTMCell(in_features, hidden_size) <NEW_LINE> <DEDENT> def forward(self, input, tree): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> is_cuda = next(self.cell.parameters()).is_cuda <NEW_LINE> states = [] <NEW_LINE> right_bracket_token = tree[0, -1] <NEW_LINE> if is_cuda: <NEW_LINE> <INDENT> FloatTensor = torch.cuda.FloatTensor <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> FloatTensor = torch.FloatTensor <NEW_LINE> <DEDENT> for node, val in zip(tree.permute(1, 0), input.permute(1, 0, 2)): <NEW_LINE> <INDENT> if (node != right_bracket_token).all(): <NEW_LINE> <INDENT> init_left_state = [Variable(torch.zeros(self.hidden_size).type(FloatTensor), requires_grad=False) for _ in range(2)] <NEW_LINE> init_right_state = [Variable(torch.zeros(self.hidden_size).type(FloatTensor), requires_grad=False) for _ in range(2)] <NEW_LINE> node_state = self.cell(val, init_left_state, init_right_state) <NEW_LINE> stack.append(node_state) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> right_state = stack.pop() <NEW_LINE> left_state = stack.pop() <NEW_LINE> node_state = self.cell(val, left_state, right_state) <NEW_LINE> stack.append(node_state) <NEW_LINE> <DEDENT> states.append(node_state[0]) <NEW_LINE> <DEDENT> states = torch.cat(states).unsqueeze(0) <NEW_LINE> assert len(stack) == 1 <NEW_LINE> return stack[0][0], states
A binary tree LSTM that unfortunately does not support batching Args: in_features: size of each input at each time step hidden_size: size of hidden states of LSTM Shape: - Input: input: a list containing embeddings, transfored from the bracketed form of tree representations tree: a list of idx and <-REDUCE-> tokens, used to guide how the network computes along the tree. - Output: final hidden state at root node
62598f9d7d847024c075c199
class IBookingHole(Interface): <NEW_LINE> <INDENT> pass
BBB: backward compatibility.
62598f9ddd821e528d6d8cfc
class QDViewerDialogTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_icon_png(self): <NEW_LINE> <INDENT> path = ':/plugins/QDViewer/icon.png' <NEW_LINE> icon = QIcon(path) <NEW_LINE> self.assertFalse(icon.isNull())
Test rerources work.
62598f9d67a9b606de545d91
class EvtObjectConnected(event.Event): <NEW_LINE> <INDENT> obj = 'The object that is connected' <NEW_LINE> connected = 'True if the object connected, False if it disconnected'
Triggered when the engine reports that an object is connected (i.e. exists). This will usually occur at the start of the program in response to the SDK sending RequestConnectedObjects to the engine.
62598f9d462c4b4f79dbb7d3
class RoomDetail(DetailView): <NEW_LINE> <INDENT> model = models.Room <NEW_LINE> pk_url_kwarg = "potato"
DetailView Definition
62598f9d379a373c97d98ddc
class JoystickHatMove(object): <NEW_LINE> <INDENT> def __init__(self, js_name, js_id, hat, x, y): <NEW_LINE> <INDENT> self.js_name = js_name <NEW_LINE> self.js_id = js_id <NEW_LINE> self.hat = hat <NEW_LINE> self.x = x <NEW_LINE> self.y = y
This input event represents a joystick hat moving. .. attribute:: js_name The name of the joystick. .. attribute:: js_id The number of the joystick, where ``0`` is the first joystick. .. attribute:: hat The number of the hat that moved, where ``0`` is the first axis on the joystick. .. attribute:: x The horizontal position of the hat, where ``0`` is centered, ``-1`` is left, and ``1`` is right. .. attribute:: y The vertical position of the hat, where ``0`` is centered, ``-1`` is up, and ``1`` is down.
62598f9d30dc7b766599f615
class ObjectJsonDictifiable(ObjectDictifiable): <NEW_LINE> <INDENT> zope.interface.implements(IO.JsonDictIO) <NEW_LINE> _json_model = None <NEW_LINE> def marshall_json_dict(self, **options): <NEW_LINE> <INDENT> d = self.marshall_dict() <NEW_LINE> return self._json_model(d).serialize() <NEW_LINE> <DEDENT> def unmarshall_json_dict(self, document, **options): <NEW_LINE> <INDENT> valid_doc = self._json_model(document) <NEW_LINE> try: <NEW_LINE> <INDENT> valid_doc.validate() <NEW_LINE> <DEDENT> except Exception as exc: <NEW_LINE> <INDENT> log.warn("document validation failed with error {}".format(exc)) <NEW_LINE> raise exc <NEW_LINE> <DEDENT> self.unmarshall_dict(document, **options)
Object can marshall/unmarshall to/from python json compatible dict A json compatible dict is a dict with only 4 value types : str num bool None We rely on schematics to do the job from our object's 'public' attributes
62598f9d796e427e5384e55b
class HouseName(externals.atom.core.XmlElement): <NEW_LINE> <INDENT> _qname = GDATA_TEMPLATE % 'housename'
The gd:housename element. Used in places where houses or buildings have names (and not necessarily numbers), eg. "The Pillars".
62598f9d925a0f43d25e7e05
class OneOfWebhookActivityEntryAttributes(object): <NEW_LINE> <INDENT> swagger_types = { } <NEW_LINE> attribute_map = { } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.discriminator = None <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(OneOfWebhookActivityEntryAttributes, 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, OneOfWebhookActivityEntryAttributes): <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.
62598f9d097d151d1a2c0def
class Tag(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(30), unique=True, nullable=False) <NEW_LINE> users = db.relationship('UserTag', back_populates='tag') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Representation of a tag.
62598f9da79ad16197769e2c
class LinkedIntegrationRuntimeProperties(Model): <NEW_LINE> <INDENT> _validation = { 'authorization_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'authorization_type': {'key': 'authorizationType', 'type': 'str'}, } <NEW_LINE> _subtype_map = { 'authorization_type': {'RBAC': 'LinkedIntegrationRuntimeRbac', 'Key': 'LinkedIntegrationRuntimeKey'} } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(LinkedIntegrationRuntimeProperties, self).__init__() <NEW_LINE> self.authorization_type = None
The base definition of a secret type. You probably want to use the sub-classes and not this class directly. Known sub-classes are: LinkedIntegrationRuntimeRbac, LinkedIntegrationRuntimeKey :param authorization_type: Constant filled by server. :type authorization_type: str
62598f9d1f5feb6acb1629ea
class _JsonEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, Decimal): <NEW_LINE> <INDENT> return { "_type": "decimal", "v": str(o), } <NEW_LINE> <DEDENT> elif isinstance(o, date): <NEW_LINE> <INDENT> return { "_type": "date", "y": o.year, "m": o.month, "d": o.day, } <NEW_LINE> <DEDENT> return super(_JsonEncoder, self).default(o)
JsonEncoder allowing serialising `Decimal` and `datetime.date` objects.
62598f9dcc0a2c111447add4
class Error(Exception): <NEW_LINE> <INDENT> __module__ = "psycopg" <NEW_LINE> sqlstate: Optional[str] = None <NEW_LINE> def __init__( self, *args: Sequence[Any], info: ErrorInfo = None, encoding: str = "utf-8" ): <NEW_LINE> <INDENT> super().__init__(*args) <NEW_LINE> self._info = info <NEW_LINE> self._encoding = encoding <NEW_LINE> <DEDENT> @property <NEW_LINE> def diag(self) -> "Diagnostic": <NEW_LINE> <INDENT> return Diagnostic(self._info, encoding=self._encoding) <NEW_LINE> <DEDENT> def __reduce__(self) -> Union[str, Tuple[Any, ...]]: <NEW_LINE> <INDENT> res = super().__reduce__() <NEW_LINE> if isinstance(res, tuple) and len(res) >= 3: <NEW_LINE> <INDENT> res[2]["_info"] = self._info_to_dict(self._info) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _info_to_dict(cls, info: ErrorInfo) -> ErrorInfo: <NEW_LINE> <INDENT> if hasattr(info, "error_field"): <NEW_LINE> <INDENT> info = cast(PGresult, info) <NEW_LINE> return {v: info.error_field(v) for v in DiagnosticField} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return info
Base exception for all the errors psycopg will raise. Exception that is the base class of all other error exceptions. You can use this to catch all errors with one single `!except` statement. This exception is guaranteed to be picklable.
62598f9dfff4ab517ebcd5b6
class DataSet(list): <NEW_LINE> <INDENT> def __init__(self, raw_xml): <NEW_LINE> <INDENT> list.__init__(self) <NEW_LINE> self.raw_xml = raw_xml <NEW_LINE> xml_tree = ElementTree.fromstring(self.raw_xml) <NEW_LINE> self.id = xml_tree.find('{http://www.w3.org/2005/Atom}id').text <NEW_LINE> self.title = xml_tree.find('{http://www.w3.org/2005/Atom}title').text <NEW_LINE> self.totalResults = int(xml_tree.find('{http://a9.com/-/spec/opensearchrss/1.0/}totalResults').text) <NEW_LINE> self.startIndex = int(xml_tree.find('{http://a9.com/-/spec/opensearchrss/1.0/}startIndex').text) <NEW_LINE> self.itemsPerPage = int(xml_tree.find('{http://a9.com/-/spec/opensearchrss/1.0/}itemsPerPage').text) <NEW_LINE> endDate = xml_tree.find('{http://schemas.google.com/analytics/2009}endDate').text <NEW_LINE> self.endDate = datetime.date.fromtimestamp(time.mktime(time.strptime(endDate, '%Y-%m-%d'))) <NEW_LINE> startDate = xml_tree.find('{http://schemas.google.com/analytics/2009}startDate').text <NEW_LINE> self.startDate = datetime.date.fromtimestamp(time.mktime(time.strptime(startDate, '%Y-%m-%d'))) <NEW_LINE> aggregates = xml_tree.find('{http://schemas.google.com/analytics/2009}aggregates') <NEW_LINE> aggregate_metrics = aggregates.findall('{http://schemas.google.com/analytics/2009}metric') <NEW_LINE> self.aggregates = [] <NEW_LINE> for m in aggregate_metrics: <NEW_LINE> <INDENT> metric = Metric(**m.attrib) <NEW_LINE> setattr(self, metric.name, metric) <NEW_LINE> self.aggregates.append(metric) <NEW_LINE> <DEDENT> dataSource = xml_tree.find('{http://schemas.google.com/analytics/2009}dataSource') <NEW_LINE> self.tableId = dataSource.find('{http://schemas.google.com/analytics/2009}tableId').text <NEW_LINE> self.tableName = dataSource.find('{http://schemas.google.com/analytics/2009}tableName').text <NEW_LINE> properties = dataSource.findall('{http://schemas.google.com/analytics/2009}property') <NEW_LINE> for property in properties: <NEW_LINE> <INDENT> setattr(self, property.attrib['name'].replace('ga:', ''), property.attrib['value']) <NEW_LINE> <DEDENT> entries = xml_tree.getiterator('{http://www.w3.org/2005/Atom}entry') <NEW_LINE> for entry in entries: <NEW_LINE> <INDENT> dp = DataPoint(entry) <NEW_LINE> self.append(dp) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def list(self): <NEW_LINE> <INDENT> return [[[d.value for d in dp.dimensions], [m.value for m in dp.metrics]] for dp in self] <NEW_LINE> <DEDENT> @property <NEW_LINE> def tuple(self): <NEW_LINE> <INDENT> return tuple(map(tuple, self.list))
docstring for DataSet
62598f9dbe383301e02535bd
class TestKnapsack(QiskitOptimizationTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.values = [10, 40, 30, 50] <NEW_LINE> self.weights = [5, 4, 6, 3] <NEW_LINE> self.max_weight = 10 <NEW_LINE> op = QuadraticProgram() <NEW_LINE> for _ in range(4): <NEW_LINE> <INDENT> op.binary_var() <NEW_LINE> <DEDENT> self.result = OptimizationResult( x=[0, 1, 0, 1], fval=90, variables=op.variables, status=OptimizationResultStatus.SUCCESS, ) <NEW_LINE> <DEDENT> def test_to_quadratic_program(self): <NEW_LINE> <INDENT> knapsack = Knapsack(values=self.values, weights=self.weights, max_weight=self.max_weight) <NEW_LINE> op = knapsack.to_quadratic_program() <NEW_LINE> self.assertEqual(op.name, "Knapsack") <NEW_LINE> self.assertEqual(op.get_num_vars(), 4) <NEW_LINE> for var in op.variables: <NEW_LINE> <INDENT> self.assertEqual(var.vartype, VarType.BINARY) <NEW_LINE> <DEDENT> obj = op.objective <NEW_LINE> self.assertEqual(obj.sense, QuadraticObjective.Sense.MAXIMIZE) <NEW_LINE> self.assertEqual(obj.constant, 0) <NEW_LINE> self.assertDictEqual(obj.linear.to_dict(), {0: 10, 1: 40, 2: 30, 3: 50}) <NEW_LINE> self.assertEqual(obj.quadratic.to_dict(), {}) <NEW_LINE> lin = op.linear_constraints <NEW_LINE> self.assertEqual(len(lin), 1) <NEW_LINE> self.assertEqual(lin[0].sense, Constraint.Sense.LE) <NEW_LINE> self.assertEqual(lin[0].rhs, self.max_weight) <NEW_LINE> self.assertEqual(lin[0].linear.to_dict(), dict(enumerate(self.weights))) <NEW_LINE> <DEDENT> def test_interpret(self): <NEW_LINE> <INDENT> knapsack = Knapsack(values=self.values, weights=self.weights, max_weight=self.max_weight) <NEW_LINE> self.assertEqual(knapsack.interpret(self.result), [1, 3]) <NEW_LINE> <DEDENT> def test_max_weight(self): <NEW_LINE> <INDENT> knapsack = Knapsack(values=self.values, weights=self.weights, max_weight=self.max_weight) <NEW_LINE> knapsack.max_weight = 5 <NEW_LINE> self.assertEqual(knapsack.max_weight, 5)
Test Knapsack class
62598f9d851cf427c66b8090
class UnderscoreTemplateLinter(BaseLinter): <NEW_LINE> <INDENT> ruleset = RuleSet( underscore_not_escaped='underscore-not-escaped', ) <NEW_LINE> def __init__(self, skip_dirs=None): <NEW_LINE> <INDENT> super(UnderscoreTemplateLinter, self).__init__() <NEW_LINE> self._skip_underscore_dirs = skip_dirs or () <NEW_LINE> <DEDENT> def process_file(self, directory, file_name): <NEW_LINE> <INDENT> full_path = os.path.normpath(directory + '/' + file_name) <NEW_LINE> results = FileResults(full_path) <NEW_LINE> if not self._is_valid_directory(self._skip_underscore_dirs, directory): <NEW_LINE> <INDENT> return results <NEW_LINE> <DEDENT> if not file_name.lower().endswith('.underscore'): <NEW_LINE> <INDENT> return results <NEW_LINE> <DEDENT> return self._load_and_check_file_is_safe(full_path, self.check_underscore_file_is_safe, results) <NEW_LINE> <DEDENT> def check_underscore_file_is_safe(self, underscore_template, results): <NEW_LINE> <INDENT> self._check_underscore_expressions(underscore_template, results) <NEW_LINE> results.prepare_results(underscore_template) <NEW_LINE> <DEDENT> def _check_underscore_expressions(self, underscore_template, results): <NEW_LINE> <INDENT> expressions = self._find_unescaped_expressions(underscore_template) <NEW_LINE> for expression in expressions: <NEW_LINE> <INDENT> if not self._is_safe_unescaped_expression(expression): <NEW_LINE> <INDENT> results.violations.append(ExpressionRuleViolation( self.ruleset.underscore_not_escaped, expression )) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _is_safe_unescaped_expression(self, expression): <NEW_LINE> <INDENT> if expression.expression_inner.startswith('HtmlUtils.'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if expression.expression_inner.startswith('_.escape('): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def _find_unescaped_expressions(self, underscore_template): <NEW_LINE> <INDENT> unescaped_expression_regex = re.compile("<%=.*?%>", re.DOTALL) <NEW_LINE> expressions = [] <NEW_LINE> for match in unescaped_expression_regex.finditer(underscore_template): <NEW_LINE> <INDENT> expression = Expression( match.start(), match.end(), template=underscore_template, start_delim="<%=", end_delim="%>" ) <NEW_LINE> expressions.append(expression) <NEW_LINE> <DEDENT> return expressions
The linter for Underscore.js template files.
62598f9d656771135c48944b
class AddProjectToImage(command.ShowOne): <NEW_LINE> <INDENT> def get_parser(self, prog_name): <NEW_LINE> <INDENT> parser = super(AddProjectToImage, self).get_parser(prog_name) <NEW_LINE> parser.add_argument( "image", metavar="<image>", help="Image to share (name or ID)", ) <NEW_LINE> parser.add_argument( "project", metavar="<project>", help="Project to associate with image (name or ID)", ) <NEW_LINE> common.add_project_domain_option_to_parser(parser) <NEW_LINE> return parser <NEW_LINE> <DEDENT> def take_action(self, parsed_args): <NEW_LINE> <INDENT> image_client = self.app.client_manager.image <NEW_LINE> identity_client = self.app.client_manager.identity <NEW_LINE> project_id = common.find_project(identity_client, parsed_args.project, parsed_args.project_domain).id <NEW_LINE> image_id = utils.find_resource( image_client.images, parsed_args.image).id <NEW_LINE> image_member = image_client.image_members.create( image_id, project_id, ) <NEW_LINE> return zip(*sorted(six.iteritems(image_member)))
Associate project with image
62598f9dfbf16365ca793e81
class VoterBallotSaved(models.Model): <NEW_LINE> <INDENT> voter_id = models.IntegerField(verbose_name="the voter unique id", default=0, null=False, blank=False) <NEW_LINE> google_civic_election_id = models.PositiveIntegerField( verbose_name="google civic election id", default=0, null=False) <NEW_LINE> state_code = models.CharField(verbose_name="state the ballot item is related to", max_length=2, null=True) <NEW_LINE> election_description_text = models.CharField(max_length=255, blank=False, null=False, verbose_name='text label for this election') <NEW_LINE> election_date = models.DateField(verbose_name='election start date', null=True, auto_now=False) <NEW_LINE> original_text_for_map_search = models.CharField(max_length=255, blank=False, null=False, verbose_name='address as entered') <NEW_LINE> original_text_city = models.CharField(max_length=255, null=True) <NEW_LINE> original_text_state = models.CharField(max_length=255, null=True) <NEW_LINE> original_text_zip = models.CharField(max_length=255, null=True) <NEW_LINE> substituted_address_city = models.CharField(max_length=255, null=True) <NEW_LINE> substituted_address_state = models.CharField(max_length=255, null=True) <NEW_LINE> substituted_address_zip = models.CharField(max_length=255, null=True) <NEW_LINE> substituted_address_nearby = models.CharField(max_length=255, blank=False, null=False, verbose_name='address from nearby ballot_returned') <NEW_LINE> is_from_substituted_address = models.BooleanField(default=False) <NEW_LINE> is_from_test_ballot = models.BooleanField(default=False) <NEW_LINE> polling_location_we_vote_id_source = models.CharField( verbose_name="we vote permanent id of the map point this was copied from", max_length=255, default=None, null=True, blank=True, unique=False) <NEW_LINE> ballot_returned_we_vote_id = models.CharField( verbose_name="ballot_returned we_vote_id this was copied from", max_length=255, default=None, null=True, blank=True, unique=False) <NEW_LINE> ballot_location_display_name = models.CharField( verbose_name="the name of the ballot the voter is looking at", max_length=255, default=None, null=True, blank=True, unique=False) <NEW_LINE> ballot_location_shortcut = models.CharField( verbose_name="the url string used to find specific ballot", max_length=255, default=None, null=True, blank=True, unique=False) <NEW_LINE> def election_day_text(self): <NEW_LINE> <INDENT> if isinstance(self.election_date, date): <NEW_LINE> <INDENT> return self.election_date.strftime('%Y-%m-%d') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> <DEDENT> def ballot_caveat(self): <NEW_LINE> <INDENT> message = '' <NEW_LINE> if self.is_from_substituted_address: <NEW_LINE> <INDENT> message += "Ballot displayed is from a nearby address: '{substituted_address_nearby}'." "".format(substituted_address_nearby=self.substituted_address_nearby) <NEW_LINE> <DEDENT> if self.is_from_test_ballot: <NEW_LINE> <INDENT> message += "Ballot displayed is a TEST ballot, and is for demonstration purposes only." <NEW_LINE> <DEDENT> return message
This is a table with a meta data about a voter's various elections they have looked at and might return to
62598f9df8510a7c17d7e05c
class OpendatasoftCore: <NEW_LINE> <INDENT> def __init__( self, base_url: str, session: requests.Session, resource: str = 'catalog', ) -> None: <NEW_LINE> <INDENT> self.base_url = base_url <NEW_LINE> self.session = session <NEW_LINE> self.resource = resource <NEW_LINE> <DEDENT> @property <NEW_LINE> def api_url(self) -> str: <NEW_LINE> <INDENT> return f'{self.base_url}/api/v2/{self.resource}' <NEW_LINE> <DEDENT> def build_querystring(self, **kwargs: Any) -> str: <NEW_LINE> <INDENT> parameters = { key: value for key, value in kwargs.items() if value is not None } <NEW_LINE> return f'?{urllib.parse.urlencode(parameters, doseq=True)}' <NEW_LINE> <DEDENT> def build_url(self, *args: str) -> str: <NEW_LINE> <INDENT> return '/'.join([self.api_url, *args]) <NEW_LINE> <DEDENT> def get(self, url: str) -> requests.Response: <NEW_LINE> <INDENT> response = self.session.get(url) <NEW_LINE> logger.info(f'GET {urllib.parse.unquote_plus(url)} {response.status_code}') <NEW_LINE> return response.json()
Core API interface
62598f9d5f7d997b871f92c3
class SingletonMeta(type): <NEW_LINE> <INDENT> _instances = {} <NEW_LINE> def __call__(cls): <NEW_LINE> <INDENT> if cls not in cls._instances: <NEW_LINE> <INDENT> instance = super().__call__() <NEW_LINE> cls._instances[cls] = instance <NEW_LINE> <DEDENT> return cls._instances[cls]
Mixin for create Singleton pattern that restricts the instantiation of a class to one "single" instance
62598f9da219f33f346c65e2
class subdirmatcher(basematcher): <NEW_LINE> <INDENT> def __init__(self, path, matcher): <NEW_LINE> <INDENT> super(subdirmatcher, self).__init__(matcher._root, matcher._cwd) <NEW_LINE> self._path = path <NEW_LINE> self._matcher = matcher <NEW_LINE> self._always = matcher.always() <NEW_LINE> self._files = [f[len(path) + 1:] for f in matcher._files if f.startswith(path + "/")] <NEW_LINE> if matcher.prefix(): <NEW_LINE> <INDENT> self._always = any(f == path for f in matcher._files) <NEW_LINE> <DEDENT> <DEDENT> def bad(self, f, msg): <NEW_LINE> <INDENT> self._matcher.bad(self._path + "/" + f, msg) <NEW_LINE> <DEDENT> def abs(self, f): <NEW_LINE> <INDENT> return self._matcher.abs(self._path + "/" + f) <NEW_LINE> <DEDENT> def rel(self, f): <NEW_LINE> <INDENT> return self._matcher.rel(self._path + "/" + f) <NEW_LINE> <DEDENT> def uipath(self, f): <NEW_LINE> <INDENT> return self._matcher.uipath(self._path + "/" + f) <NEW_LINE> <DEDENT> def matchfn(self, f): <NEW_LINE> <INDENT> return self._matcher.matchfn(self._path + "/" + f) <NEW_LINE> <DEDENT> def visitdir(self, dir): <NEW_LINE> <INDENT> if dir == '.': <NEW_LINE> <INDENT> dir = self._path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dir = self._path + "/" + dir <NEW_LINE> <DEDENT> return self._matcher.visitdir(dir) <NEW_LINE> <DEDENT> def always(self): <NEW_LINE> <INDENT> return self._always <NEW_LINE> <DEDENT> def prefix(self): <NEW_LINE> <INDENT> return self._matcher.prefix() and not self._always <NEW_LINE> <DEDENT> @encoding.strmethod <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return ('<subdirmatcher path=%r, matcher=%r>' % (self._path, self._matcher))
Adapt a matcher to work on a subdirectory only. The paths are remapped to remove/insert the path as needed: >>> from . import pycompat >>> m1 = match(b'root', b'', [b'a.txt', b'sub/b.txt']) >>> m2 = subdirmatcher(b'sub', m1) >>> bool(m2(b'a.txt')) False >>> bool(m2(b'b.txt')) True >>> bool(m2.matchfn(b'a.txt')) False >>> bool(m2.matchfn(b'b.txt')) True >>> m2.files() ['b.txt'] >>> m2.exact(b'b.txt') True >>> util.pconvert(m2.rel(b'b.txt')) 'sub/b.txt' >>> def bad(f, msg): ... print(pycompat.sysstr(b"%s: %s" % (f, msg))) >>> m1.bad = bad >>> m2.bad(b'x.txt', b'No such file') sub/x.txt: No such file >>> m2.abs(b'c.txt') 'sub/c.txt'
62598f9d0c0af96317c5614b
class CyclingIterator: <NEW_LINE> <INDENT> def __init__(self, n: int, generator_fn, start_epoch=0): <NEW_LINE> <INDENT> self._n = n <NEW_LINE> self._epoch = start_epoch <NEW_LINE> self._generator_fn = generator_fn <NEW_LINE> self._iter = generator_fn(self._epoch) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return next(self._iter) <NEW_LINE> <DEDENT> except StopIteration as eod: <NEW_LINE> <INDENT> if self._epoch < self._n - 1: <NEW_LINE> <INDENT> self._epoch += 1 <NEW_LINE> self._iter = self._generator_fn(self._epoch) <NEW_LINE> return self.__next__() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise eod
An iterator decorator that cycles through the underlying iterator "n" times. Useful to "unroll" the dataset across multiple training epochs. The generator function is called as ``generator_fn(epoch)`` to obtain the underlying iterator, where ``epoch`` is a number less than or equal to ``n`` representing the ``k``th cycle For example if ``generator_fn`` always returns ``[1,2,3]`` then ``CyclingIterator(n=2, generator_fn)`` will iterate through ``[1,2,3,1,2,3]``
62598f9d45492302aabfc2a1
class ComputeVpnTunnelsDeleteRequest(messages.Message): <NEW_LINE> <INDENT> project = messages.StringField(1, required=True) <NEW_LINE> region = messages.StringField(2, required=True) <NEW_LINE> vpnTunnel = messages.StringField(3, required=True)
A ComputeVpnTunnelsDeleteRequest object. Fields: project: Project ID for this request. region: The name of the region for this request. vpnTunnel: Name of the VpnTunnel resource to delete.
62598f9d3617ad0b5ee05f19
class DetailsView(generics.RetrieveUpdateDestroyAPIView): <NEW_LINE> <INDENT> queryset = BucketList.objects.all() <NEW_LINE> serializer_class = BucketListSerializer <NEW_LINE> permission_classes = ( permissions.IsAuthenticated, IsOwner)
This class handles the http GET, PUT and DELETE requests.
62598f9df548e778e596b375
class filter_set: <NEW_LINE> <INDENT> alias = { "Bessell-U": ("U", 'bessell-u'), "Harris-R": ("R", "harris-r"), "Harris-V": ("V","harris-v" ), "Arizona-I": ("I",), "Harris-B": ("B",), "Schott-8612": ("Schott",), "Open": ("Open", "open", "OPEN", "Clear", "CLEAR", "clear") } <NEW_LINE> def __init__( self, filters=None, prx=None ): <NEW_LINE> <INDENT> if filters is None: <NEW_LINE> <INDENT> if prx is None: <NEW_LINE> <INDENT> self._filter_list = rts2_wwwapi.rts2comm().get_filters() <NEW_LINE> <DEDENT> <DEDENT> elif type(filters) == list: <NEW_LINE> <INDENT> self._filter_list = filters <NEW_LINE> <DEDENT> elif type(filters) == dict: <NEW_LINE> <INDENT> raise TypeError("Filters are should not be a dict, it probably should be None") <NEW_LINE> <DEDENT> elif type(filters) == str or type(filters) == unicode: <NEW_LINE> <INDENT> self._filter_list = str(filters).split() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Unexpected filter type {}, type must be string, unicode, list or dict".format(type(filters))) <NEW_LINE> <DEDENT> <DEDENT> def check_alias( self, alias ): <NEW_LINE> <INDENT> for name, aliases in self.alias.items(): <NEW_LINE> <INDENT> if alias == name: <NEW_LINE> <INDENT> return alias <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for al in aliases: <NEW_LINE> <INDENT> if al == alias: <NEW_LINE> <INDENT> return name <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<filter_set: "+str(self._filter_list)+">" <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if type(key) == int: <NEW_LINE> <INDENT> return self._filter_list[key] <NEW_LINE> <DEDENT> elif type(key) == str or type(key) == unicode: <NEW_LINE> <INDENT> realname = self.check_alias(key) <NEW_LINE> if realname is not None: <NEW_LINE> <INDENT> return self._filter_list.index(realname) <NEW_LINE> <DEDENT> <DEDENT> raise ValueError( "cannot find filter {}".format(key) ) <NEW_LINE> <DEDENT> def __contains__(self, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val=self.__getitem__(item) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Class to simplify look up of filter by name and number uses the python [] operator to lookup filter number or name. If you give it the name it will return the number and vice versa. it also uses aliases for the lookup. RTS2 and the Galil like to use long names like "Harris-U" observers like short names like "U" either format is acceptable as long as the alias is in the dictionary below.
62598f9dd6c5a102081e1f0e
class FastReadWrite: <NEW_LINE> <INDENT> def __init__( self, path, func, n_cpu=2, chunk_size=1024 * 1024, header=False, *args, **kwargs ): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> self.size = getsize(path) <NEW_LINE> self.n_cpu = n_cpu <NEW_LINE> self.func = func <NEW_LINE> self.args = args <NEW_LINE> self.kwargs = kwargs <NEW_LINE> self.chunk_size = chunk_size <NEW_LINE> self.splits = [i * self.size // self.n_cpu for i in range(self.n_cpu)] <NEW_LINE> for index, split in enumerate(self.splits): <NEW_LINE> <INDENT> with open(self.path, "r") as infile: <NEW_LINE> <INDENT> infile.seek(split) <NEW_LINE> infile.readline() <NEW_LINE> self.splits[index] = infile.tell() <NEW_LINE> <DEDENT> <DEDENT> if not header: <NEW_LINE> <INDENT> self.splits[0] = 0 <NEW_LINE> <DEDENT> self.splits.append(self.size) <NEW_LINE> self.split_files = [uuid.uuid4().hex + str(i) for i in range(self.n_cpu)] <NEW_LINE> self.chunk_content = {cpu: None for cpu in range(self.n_cpu)} <NEW_LINE> self.chunk_start = deepcopy(self.chunk_content) <NEW_LINE> pool = mp.Pool(n_cpu) <NEW_LINE> pool.map(self.spawn_consumer, range(self.n_cpu)) <NEW_LINE> <DEDENT> def spawn_consumer(self, cpu_id): <NEW_LINE> <INDENT> print(self.splits) <NEW_LINE> self.chunk_start[cpu_id], end = self.splits[cpu_id : cpu_id + 2] <NEW_LINE> n_chunk = 0 <NEW_LINE> self.read_chunk(cpu_id) <NEW_LINE> while self.chunk_start[cpu_id] < end: <NEW_LINE> <INDENT> print("START IS : ", self.chunk_start[cpu_id]) <NEW_LINE> present_chunk = self.chunk_content[cpu_id] <NEW_LINE> io_thread = Thread(target=self.read_chunk, args=(cpu_id,)) <NEW_LINE> cpu_thread = Thread(target=self.consume_chunk, args=(present_chunk,)) <NEW_LINE> io_thread.start() <NEW_LINE> cpu_thread.start() <NEW_LINE> io_thread.join() <NEW_LINE> cpu_thread.join() <NEW_LINE> n_chunk += 1 <NEW_LINE> print("CPU {0} has processed {1} chunks".format(cpu_id, n_chunk)) <NEW_LINE> <DEDENT> <DEDENT> def read_chunk(self, cpu_id): <NEW_LINE> <INDENT> with open(self.path, "r") as sf: <NEW_LINE> <INDENT> sf.seek(self.chunk_start[cpu_id]) <NEW_LINE> self.chunk_content[cpu_id] = sf.read(self.chunk_size) <NEW_LINE> self.chunk_content[cpu_id] += sf.readline() <NEW_LINE> self.chunk_start[cpu_id] = sf.tell() <NEW_LINE> <DEDENT> <DEDENT> def consume_chunk(self, chunk): <NEW_LINE> <INDENT> out = [] <NEW_LINE> done = False <NEW_LINE> for line in chunk.splitlines(): <NEW_LINE> <INDENT> if not done: <NEW_LINE> <INDENT> print("FIRST LINE IS : ", line) <NEW_LINE> done = True <NEW_LINE> <DEDENT> out.append(self.func(line, *self.args, **self.kwargs)) <NEW_LINE> <DEDENT> print("LAST LINE IS : ", line) <NEW_LINE> return out <NEW_LINE> <DEDENT> def write_chunk(chunk_out, split_file): <NEW_LINE> <INDENT> with open(split_file, "w") as sf: <NEW_LINE> <INDENT> sf.writelines(chunk_out) <NEW_LINE> <DEDENT> <DEDENT> def merge_splits(self, merged_out): <NEW_LINE> <INDENT> with open(merged_out, "wb") as out: <NEW_LINE> <INDENT> for split_file in self.split_files: <NEW_LINE> <INDENT> shutil.copyfileobj(open(split_file, "rb"), out)
Handles parallelisation of file processing + I/O.
62598f9d460517430c431f3f
class Level(): <NEW_LINE> <INDENT> def __init__(self,g,E,number): <NEW_LINE> <INDENT> self.g = g <NEW_LINE> self.E = E <NEW_LINE> self.number = number <NEW_LINE> <DEDENT> def LTE_level_pop(self,Z,T): <NEW_LINE> <INDENT> return self.g*np.exp(-self.E/(constants.k*T))/Z
Represents an atomic/molecular energy level Attributes: ------------ - g: float statistical weight - E: float energy in [J] - number: int the level number (0 for the lowest level)
62598f9dcc0a2c111447add5
class UserImageUploadView(generics.RetrieveUpdateAPIView): <NEW_LINE> <INDENT> serializer_class = UserImageSerializer <NEW_LINE> authentication_classes = (authentication.TokenAuthentication,) <NEW_LINE> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> def get_object(self): <NEW_LINE> <INDENT> return self.request.user <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> user = self.get_object() <NEW_LINE> serializer = self.serializer_class(user, data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response( serializer.data, status=status.HTTP_200_OK ) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Manage adding images to users
62598f9dbe8e80087fbbee28
class matplotlib(FigureCanvasQTAgg): <NEW_LINE> <INDENT> def __init__(self, dim=2, parent=None): <NEW_LINE> <INDENT> self.fig = Figure(figsize=(10, 10), dpi=100) <NEW_LINE> self.dim = dim <NEW_LINE> FigureCanvasQTAgg.__init__(self, self.fig) <NEW_LINE> FigureCanvasQTAgg.setSizePolicy( self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) <NEW_LINE> FigureCanvasQTAgg.updateGeometry(self) <NEW_LINE> self.setParent(parent) <NEW_LINE> if dim == 2: <NEW_LINE> <INDENT> self.ax = self.fig.add_subplot(111) <NEW_LINE> self.ax.figure.subplots_adjust( left=0.08, right=0.98, bottom=0.08, top=0.92) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ax = Axes3D(self.fig) <NEW_LINE> self.ax.mouse_init(rotate_btn=1, zoom_btn=2) <NEW_LINE> <DEDENT> <DEDENT> def plot_3D(self, labels, xdata, ydata, zdata, config=None): <NEW_LINE> <INDENT> self.ax.clear() <NEW_LINE> self.data = {"x": xdata[0], "y": ydata[:, 0], "z": zdata} <NEW_LINE> if config and config.getboolean("MEOS", "surface"): <NEW_LINE> <INDENT> self.ax.plot_surface(xdata, ydata, zdata, rstride=1, cstride=1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ax.plot_wireframe(xdata, ydata, zdata, rstride=1, cstride=1) <NEW_LINE> <DEDENT> self.ax.set_xlabel(labels[0]) <NEW_LINE> self.ax.set_ylabel(labels[1]) <NEW_LINE> self.ax.set_zlabel(labels[2]) <NEW_LINE> self.ax.mouse_init(rotate_btn=1, zoom_btn=2)
Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).
62598f9d3539df3088ecc07f
class VisualSplitDateTimeWidget(forms.SplitDateTimeWidget): <NEW_LINE> <INDENT> class Media(object): <NEW_LINE> <INDENT> css = {'all': ('css/libs/jquery.timepicker.css',)} <NEW_LINE> js = ('js/visual_datetime.js', 'js/libs/jquery.timepicker.min.js') <NEW_LINE> <DEDENT> def __init__(self, time_format='%I:%M%p', *args, **kwargs): <NEW_LINE> <INDENT> super(VisualSplitDateTimeWidget, self).__init__( *args, time_format=time_format, **kwargs) <NEW_LINE> self.widgets[0].attrs['class'] = 'vDateField' <NEW_LINE> self.widgets[1].attrs['class'] = 'vTimeField'
Extend the SplitDateTimeWidget but tie in the appropriate JavaScript. To be used by the VisualSplitDateTimeField below.
62598f9d627d3e7fe0e06c74