code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class ModelDoesNotExistError(Exception): <NEW_LINE> <INDENT> pass
Model does not exists
62598fa1be8e80087fbbeebd
class TaskData(_NodeData): <NEW_LINE> <INDENT> input: AbinitInput = Field(..., description="Abinit input object") <NEW_LINE> num_warnings: int = Field(..., description="Number of warnings found the in log file") <NEW_LINE> num_errors: int = Field(..., description="Number of errors") <NEW_LINE> num_comments: int = Field(..., description="Number of comments found in the log file") <NEW_LINE> num_restarts: int = Field(..., description="Number of restarts performed by AbiPy") <NEW_LINE> num_corrections: int = Field(..., description="Number of correction performed by AbiPy") <NEW_LINE> report: EventReport = Field(..., description="Number of warnings") <NEW_LINE> mpi_procs: int = Field(..., description="Number of MPI processes used by the Task") <NEW_LINE> omp_threads: int = Field(..., description="Number of OpenMP threads. -1 if not used.") <NEW_LINE> out_gfsd: GfsFileDesc = Field(None, description="Metadata needed to retrieve the output file from GridFS.") <NEW_LINE> log_gfsd: GfsFileDesc = Field(None, description="Metadata needed to retrieve the log file from GridFS.") <NEW_LINE> @classmethod <NEW_LINE> def from_task(cls, task: Task, mng_connector: MongoConnector, with_out: bool, with_log: bool) -> TaskData: <NEW_LINE> <INDENT> data = cls.get_data_for_node(task) <NEW_LINE> data["input"] = task.input <NEW_LINE> report = task.get_event_report() <NEW_LINE> data["report"] = report <NEW_LINE> for a in ("num_errors", "num_comments", "num_warnings"): <NEW_LINE> <INDENT> data[a] = getattr(report, a) <NEW_LINE> <DEDENT> data.update(dict( num_restarts=task.num_restarts, num_corrections=task.num_corrections, mpi_procs=task.mpi_procs, omp_threads=task.omp_threads, )) <NEW_LINE> if with_out: <NEW_LINE> <INDENT> data["out_gfsd"] = mng_connector.gfs_put_filepath(task.output_file.path) <NEW_LINE> <DEDENT> if with_log: <NEW_LINE> <INDENT> data["log_gfsd"] = mng_connector.gfs_put_filepath(task.log_file.path) <NEW_LINE> <DEDENT> return cls(**data)
Data Model associated to an AbiPy |Task|.
62598fa1627d3e7fe0e06d09
class ShapemaskLoss(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._binary_crossentropy = tf.keras.losses.BinaryCrossentropy( reduction=tf.keras.losses.Reduction.SUM, from_logits=True) <NEW_LINE> <DEDENT> def __call__(self, logits, labels, valid_mask): <NEW_LINE> <INDENT> with tf.name_scope('shapemask_loss'): <NEW_LINE> <INDENT> batch_size, num_instances = valid_mask.get_shape().as_list()[:2] <NEW_LINE> labels = tf.cast(labels, tf.float32) <NEW_LINE> logits = tf.cast(logits, tf.float32) <NEW_LINE> loss = self._binary_crossentropy(labels, logits) <NEW_LINE> loss *= tf.cast(tf.reshape( valid_mask, [batch_size, num_instances, 1, 1]), loss.dtype) <NEW_LINE> loss = tf.reduce_sum(loss) / (tf.reduce_sum(labels) + 0.001) <NEW_LINE> <DEDENT> return loss
ShapeMask mask loss function wrapper.
62598fa121bff66bcd722ac2
class DataFloat(_object): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, DataFloat, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, DataFloat, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> __swig_setmethods__["content_id"] = _moduleconnectorwrapper.DataFloat_content_id_set <NEW_LINE> __swig_getmethods__["content_id"] = _moduleconnectorwrapper.DataFloat_content_id_get <NEW_LINE> if _newclass: <NEW_LINE> <INDENT> content_id = _swig_property(_moduleconnectorwrapper.DataFloat_content_id_get, _moduleconnectorwrapper.DataFloat_content_id_set) <NEW_LINE> <DEDENT> __swig_setmethods__["info"] = _moduleconnectorwrapper.DataFloat_info_set <NEW_LINE> __swig_getmethods__["info"] = _moduleconnectorwrapper.DataFloat_info_get <NEW_LINE> if _newclass: <NEW_LINE> <INDENT> info = _swig_property(_moduleconnectorwrapper.DataFloat_info_get, _moduleconnectorwrapper.DataFloat_info_set) <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return _moduleconnectorwrapper.DataFloat_get_data(self) <NEW_LINE> <DEDENT> def get_copy(self): <NEW_LINE> <INDENT> return _moduleconnectorwrapper.DataFloat_get_copy(self) <NEW_LINE> <DEDENT> __swig_setmethods__["data"] = _moduleconnectorwrapper.DataFloat_data_set <NEW_LINE> __swig_getmethods__["data"] = _moduleconnectorwrapper.DataFloat_data_get <NEW_LINE> if _newclass: <NEW_LINE> <INDENT> data = _swig_property(_moduleconnectorwrapper.DataFloat_data_get, _moduleconnectorwrapper.DataFloat_data_set) <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> this = _moduleconnectorwrapper.new_DataFloat() <NEW_LINE> try: <NEW_LINE> <INDENT> self.this.append(this) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.this = this <NEW_LINE> <DEDENT> <DEDENT> __swig_destroy__ = _moduleconnectorwrapper.delete_DataFloat <NEW_LINE> __del__ = lambda self: None
Encapulates a vector of float elements, for example baseband data. This package can be retrieved from the module with the use of read_message_data_float in the XEP interface. Python warning: Accessing vectors directly can cause memory corruption if the parent object goes out of scope and is garbage collected. Use accessor methods for a workaround. Parameters ---------- * `content_id` : id that tells what the content is. * `info` : this might be some generic information, but usually it is the frame counter value. * `data` : the vector of float elements. Attributes ---------- * `content_id` : `uint32_t` * `info` : `uint32_t` * `data` : `std::vector< float >` C++ includes: Data.hpp
62598fa1851cf427c66b8126
class TestGatherTree(test.TestCase): <NEW_LINE> <INDENT> def test_gather_tree(self): <NEW_LINE> <INDENT> predicted_ids = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[2, 3, 4], [5, 6, 7], [8, 9, 10]]]).transpose([1, 0, 2]) <NEW_LINE> parent_ids = np.array([ [[0, 0, 0], [0, 1, 1], [2, 1, 2]], [[0, 0, 0], [1, 2, 0], [2, 1, 1]], ]).transpose([1, 0, 2]) <NEW_LINE> expected_result = np.array([[[2, 2, 2], [6, 5, 6], [7, 8, 9]], [[2, 4, 4], [7, 6, 6], [8, 9, 10]]]).transpose([1, 0, 2]) <NEW_LINE> res = beam_search_decoder._gather_tree( ops.convert_to_tensor(predicted_ids), ops.convert_to_tensor(parent_ids)) <NEW_LINE> with self.test_session() as sess: <NEW_LINE> <INDENT> res_ = sess.run(res) <NEW_LINE> <DEDENT> np.testing.assert_array_equal(expected_result, res_)
Tests the gather_tree function.
62598fa1442bda511e95c2b9
class BaseGrammarTest(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(BaseGrammarTest, self).__init__(*args, **kwargs) <NEW_LINE> self.parser = ConvertibleParser(self.grammar) <NEW_LINE> <DEDENT> def test_expressions(self): <NEW_LINE> <INDENT> for expression, expected_node in self.expressions.items(): <NEW_LINE> <INDENT> def check(): <NEW_LINE> <INDENT> tree = self.parser(expression) <NEW_LINE> expected_node.check_equivalence(tree.root_node) <NEW_LINE> <DEDENT> check.description = 'Operation "%s" should yield "%s"' % (expression, expected_node) <NEW_LINE> yield check <NEW_LINE> <DEDENT> <DEDENT> def test_badformed_expressions(self): <NEW_LINE> <INDENT> for expression in self.badformed_expressions: <NEW_LINE> <INDENT> @raises(ParseException) <NEW_LINE> def check(): <NEW_LINE> <INDENT> self.parser(expression) <NEW_LINE> <DEDENT> check.description = "'%s' is an invalid expression" % expression <NEW_LINE> yield check <NEW_LINE> <DEDENT> <DEDENT> def test_single_operands(self): <NEW_LINE> <INDENT> operand_parser = self.parser.define_operand().parseString <NEW_LINE> for expression, expected_operand in self.single_operands.items(): <NEW_LINE> <INDENT> def check(): <NEW_LINE> <INDENT> node = operand_parser(expression, parseAll=True) <NEW_LINE> eq_(1, len(node)) <NEW_LINE> expected_operand.check_equivalence(node[0]) <NEW_LINE> <DEDENT> check.description = ('Single operand "%s" should return %s' % (expression, expected_operand)) <NEW_LINE> yield check <NEW_LINE> <DEDENT> <DEDENT> def test_invalid_operands(self): <NEW_LINE> <INDENT> operand_parser = self.parser.define_operand().parseString <NEW_LINE> for expression in self.invalid_operands: <NEW_LINE> <INDENT> @raises(ParseException) <NEW_LINE> def check(): <NEW_LINE> <INDENT> operand_parser(expression, parseAll=True) <NEW_LINE> <DEDENT> check.description = ('"%s" is an invalid operand' % expression) <NEW_LINE> yield check
Base test case for a grammar and the expressions its parser could handle. Subclasses must define all the following attributes for the test case to work. .. attribute:: grammar An instance of the grammar to be tested. **This attribute must be set in the subclasses**, like this:: from booleano.parser import Grammar class TestMyGrammar(BaseGrammarTest): grammar = Grammar(ne="<>") :type: :class:`booleano.parser.Grammar` .. attribute:: expressions A dictionary with all the valid expressions recognized by the grammar, where each key is the expression itself and its item is the mock representation of the operation. :type: dict .. attribute:: badformed_expressions A list of expressions that are bad-formed in the :attr:`grammar`. :type: list .. attribute:: single_operands A dictionary where the key is an expression that contains a single operand (i.e., no operator) and the item is the :term:`root node` of the expected :term:`parse tree`. :type: dict .. attribute:: invalid_operands A list of expressions which contain a single operand and it is invalid. :type: list
62598fa18e7ae83300ee8efe
class StoogeSort(SortAlgorithm): <NEW_LINE> <INDENT> def sort(self): <NEW_LINE> <INDENT> for x in self.stoogeSort(0, len(self.items.items) - 1): <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> <DEDENT> def stoogeSort(self, left, right): <NEW_LINE> <INDENT> leftMarker = self.markers.addMarker(True, left, (0, 0, 255)) <NEW_LINE> rightMarker = self.markers.addMarker(True, right+1, (0, 0, 255)) <NEW_LINE> yield <NEW_LINE> if self.cmp.gtI(left, right): <NEW_LINE> <INDENT> self.items.swap(left, right) <NEW_LINE> <DEDENT> yield <NEW_LINE> if self.cmp.gt(right - left, 1): <NEW_LINE> <INDENT> third = (right - left + 1) // 3 <NEW_LINE> for x in self.stoogeSort(left, right - third): <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> for x in self.stoogeSort(left + third, right): <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> for x in self.stoogeSort(left, right - third): <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> <DEDENT> self.markers.removeMarker(leftMarker) <NEW_LINE> self.markers.removeMarker(rightMarker)
Implements Stooge sort O(n^(lg 3 / lg 1.5)), ?-stable, in-place http://en.wikipedia.org/wiki/Stooge_sort
62598fa1fbf16365ca793f19
class LcBuilder(object): <NEW_LINE> <INDENT> def __init__(self,pions,kaons,protons,config): <NEW_LINE> <INDENT> self.pions = pions <NEW_LINE> self.kaons = kaons <NEW_LINE> self.protons = protons <NEW_LINE> self.config = config <NEW_LINE> self.pkpi = [self._makeLc2pKpi()] <NEW_LINE> <DEDENT> def _makeLc2pKpi(self): <NEW_LINE> <INDENT> dm,units = LoKiCuts.cutValue(self.config['MASS_WINDOW']) <NEW_LINE> comboCuts = [LoKiCuts(['ASUMPT'],self.config).code(), "(ADAMASS('Lambda_c+') < %s*%s) " % (dm+10,units), hasTopoChild()] <NEW_LINE> comboCuts.append(LoKiCuts(['AMAXDOCA'],self.config).code()) <NEW_LINE> comboCuts = LoKiCuts.combine(comboCuts) <NEW_LINE> momCuts = ["(ADMASS('Lambda_c+') < %s*%s) " % (dm,units), LoKiCuts(['VCHI2DOF','BPVVDCHI2','BPVDIRA'], self.config).code()] <NEW_LINE> momCuts = LoKiCuts.combine(momCuts) <NEW_LINE> cp = CombineParticles(CombinationCut=comboCuts,MotherCut=momCuts, DecayDescriptors=["[Lambda_c+ -> p+ K- pi+]cc"]) <NEW_LINE> return Selection('Lc2PKPiBeauty2Charm',Algorithm=cp, RequiredSelections=[self.pions,self.kaons, self.protons])
Produces all Lambda_c baryons for the Beauty2Charm module.
62598fa1a17c0f6771d5c098
class GazeNet(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(GazeNet, self).__init__() <NEW_LINE> self.face_net = resnext50(4,32) <NEW_LINE> self.eye_net = resnext50(4,32) <NEW_LINE> <DEDENT> def calc_gaze_lola(self,head,eye): <NEW_LINE> <INDENT> head_lo = head[:,0] <NEW_LINE> head_la = head[:,1] <NEW_LINE> eye_lo = eye[:,0] <NEW_LINE> eye_la = eye[:,1] <NEW_LINE> cA = torch.cos(head_lo/180*np.pi) <NEW_LINE> sA = torch.sin(head_lo/180*np.pi) <NEW_LINE> cB = torch.cos(head_la/180*np.pi) <NEW_LINE> sB = torch.sin(head_la/180*np.pi) <NEW_LINE> cC = torch.cos(eye_lo/180*np.pi) <NEW_LINE> sC = torch.sin(eye_lo/180*np.pi) <NEW_LINE> cD = torch.cos(eye_la/180*np.pi) <NEW_LINE> sD = torch.sin(eye_la/180*np.pi) <NEW_LINE> g_x = - cA * sC * cD + sA * sB * sD - sA * cB * cC * cD <NEW_LINE> g_y = cB * sD + sB * cC * cD <NEW_LINE> g_z = sA * sC * cD + cA * sB * sD - cA * cB * cC * cD <NEW_LINE> gaze_lo = torch.atan2(-g_x,-g_z)*180.0/np.pi <NEW_LINE> gaze_la = -torch.asin(g_y)*180.0/np.pi <NEW_LINE> gaze_lo = gaze_lo.unsqueeze(1) <NEW_LINE> gaze_la = gaze_la.unsqueeze(1) <NEW_LINE> gaze_lola = torch.cat((gaze_lo,gaze_la),1) <NEW_LINE> return gaze_lola <NEW_LINE> <DEDENT> def forward(self,img_face,img_leye,img_reye): <NEW_LINE> <INDENT> return_dict = {} <NEW_LINE> head = self.face_net(img_face) <NEW_LINE> leye = self.eye_net(img_leye) <NEW_LINE> reye = self.eye_net(img_reye) <NEW_LINE> eye = (leye + reye) / 2 <NEW_LINE> gaze_lola = self.calc_gaze_lola(head,eye) <NEW_LINE> head = (head + 90)/180 <NEW_LINE> eye = (eye + 90)/180 <NEW_LINE> gaze_lola = (gaze_lola + 90)/180 <NEW_LINE> return_dict['head'] = head <NEW_LINE> return_dict['eye'] = eye <NEW_LINE> return_dict['gaze'] = gaze_lola <NEW_LINE> return return_dict
The end_to_end model of Gaze Prediction Training
62598fa18da39b475be0303d
class Document(object): <NEW_LINE> <INDENT> def __init__(self, content, identifier, metadata): <NEW_LINE> <INDENT> self.metadata = metadata <NEW_LINE> self.identifier = identifier <NEW_LINE> self.tokens, _ = tokenize(content) <NEW_LINE> self.raw_tokens = list( filter(lambda x: x not in stopwords, self.tokens)) <NEW_LINE> self.freq_map = Counter(self.raw_tokens) <NEW_LINE> self.freq_map_max = max(self.freq_map.values()) <NEW_LINE> self.tokens = set(self.raw_tokens) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Document identifier="{}" metadata="{}" tokens="{}">'.format( self.identifier, self.metadata, self.tokens)
a container object for properties of a given document
62598fa1e76e3b2f99fd8896
class Save2eEsPipeline(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.es = EsObject(index_name=settings.INDEX_NAME, index_type=settings.INDEX_TYPE, host=settings.ES_HOST, port=settings.ES_PORT) <NEW_LINE> <DEDENT> def process_item(self, item, spider): <NEW_LINE> <INDENT> if item: <NEW_LINE> <INDENT> _id = item['ws_pc_id'] <NEW_LINE> res1 = self.es.get_data_by_id(_id) <NEW_LINE> if res1.get('found') == True: <NEW_LINE> <INDENT> logger.debug("该数据已存在%s" % _id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.es.insert_data(dict(item), _id) <NEW_LINE> logger.debug("----------抓取成功,开始插入数据%s" % _id) <NEW_LINE> return item
存储elasticsearch
62598fa17047854f4633f236
class LogsView(BrowserView): <NEW_LINE> <INDENT> @property <NEW_LINE> def logs(self): <NEW_LINE> <INDENT> return sorted(self.context._logs, key=operator.itemgetter(1), reverse=True)
Display logs
62598fa10c0af96317c561e1
@error('xbr.network.error.username_already_exists') <NEW_LINE> class UsernameAlreadyExists(ApplicationError): <NEW_LINE> <INDENT> def __init__(self, username, alt_username=None): <NEW_LINE> <INDENT> if alt_username: <NEW_LINE> <INDENT> msg = 'username "{}" already exists. alternative available username "{}"'.format(username, alt_username) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = 'username "{}" already exists'.format(username) <NEW_LINE> <DEDENT> super().__init__('xbr.network.error.username_already_exists', msg, alt_username=alt_username)
An action could not be performed because the chosen username already exists.
62598fa1be383301e0253655
class Position(_Position): <NEW_LINE> <INDENT> def __add__(self, other): <NEW_LINE> <INDENT> x, y = other <NEW_LINE> return Position(x=self.x + x, y=self.y + y) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> x, y = other <NEW_LINE> return self.__add__((-x, -y))
Represents screen positions.
62598fa13d592f4c4edbad2c
class ClearBladeModbusProxyServerContext(ModbusServerContext): <NEW_LINE> <INDENT> def __init__(self, cb_system, cb_auth, cb_slaves_config, cb_data, **kwargs): <NEW_LINE> <INDENT> super(ClearBladeModbusProxyServerContext, self).__init__(single=kwargs.get('single', False)) <NEW_LINE> if is_logger(kwargs.get('log', None)): <NEW_LINE> <INDENT> self.log = kwargs.get('log') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log = get_wrapping_logger(name='ClearBladeModbusServerContext', debug=True if kwargs.get('debug', None) else False) <NEW_LINE> <DEDENT> self.cb_system = cb_system <NEW_LINE> self.cb_auth = cb_auth <NEW_LINE> self.ip_address = kwargs.get('ip_address', None) <NEW_LINE> self.cb_slaves = cb_slaves_config <NEW_LINE> self.cb_data = cb_data <NEW_LINE> self._initialize_slaves() <NEW_LINE> <DEDENT> def _initialize_slaves(self): <NEW_LINE> <INDENT> slaves = [] <NEW_LINE> collection = self.cb_system.Collection(self.cb_auth, collectionName=self.cb_slaves) <NEW_LINE> query = Query() <NEW_LINE> if self.ip_address is not None: <NEW_LINE> <INDENT> self.log.debug("Querying ClearBlade based on ip_address: {}".format(self.ip_address)) <NEW_LINE> query.equalTo(COL_PROXY_IP_ADDRESS, self.ip_address) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log.debug("No ip_address found in ClearBlade, querying based on non-empty slave_id") <NEW_LINE> query.notEqualTo(COL_SLAVE_ID, '') <NEW_LINE> <DEDENT> rows = collection.getItems(query) <NEW_LINE> self.log.debug("Found {} rows in ClearBlade adapter config".format(len(rows))) <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> slave_id = int(row[COL_SLAVE_ID]) <NEW_LINE> if slave_id not in slaves: <NEW_LINE> <INDENT> slaves.append(slave_id) <NEW_LINE> self[slave_id] = ClearBladeModbusProxySlaveContext(server_context=self, config=row, log=self.log) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log.warning("Duplicate slave_id {} found in RTUs collection - only 1 RTU per server context" .format(slave_id))
A Modbus server context, initialized by reading a ClearBlade collection defining Slave configurations / templates
62598fa15f7d997b871f930f
class Genre(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Model representing a book genre.
62598fa185dfad0860cbf9a4
class Nfs(Deployment): <NEW_LINE> <INDENT> compatibility = 1 <NEW_LINE> def __init__(self, parent, parameters): <NEW_LINE> <INDENT> super(Nfs, self).__init__(parent) <NEW_LINE> self.action = NfsAction() <NEW_LINE> self.action.section = self.action_type <NEW_LINE> self.action.job = self.job <NEW_LINE> parent.add_action(self.action, parameters) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def accepts(cls, device, parameters): <NEW_LINE> <INDENT> if not nfs_accept(device, parameters): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if 'nfs' in device['actions']['deploy']['methods']: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
Strategy class for a NFS deployment. Downloads rootfs and deploys to NFS server on dispatcher
62598fa1ac7a0e7691f7236a
class SettingValue: <NEW_LINE> <INDENT> def __init__(self, typ, default=None): <NEW_LINE> <INDENT> self.typ = typ <NEW_LINE> self.values = collections.OrderedDict.fromkeys( ['temp', 'conf', 'default']) <NEW_LINE> self.values['default'] = default <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.value() <NEW_LINE> <DEDENT> def default(self): <NEW_LINE> <INDENT> return self.values['default'] <NEW_LINE> <DEDENT> def getlayers(self, startlayer): <NEW_LINE> <INDENT> idx = list(self.values.keys()).index(startlayer) <NEW_LINE> d = collections.OrderedDict(list(self.values.items())[idx:]) <NEW_LINE> return d <NEW_LINE> <DEDENT> def value(self, startlayer=None): <NEW_LINE> <INDENT> if startlayer is None: <NEW_LINE> <INDENT> d = self.values <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d = self.getlayers(startlayer) <NEW_LINE> <DEDENT> for val in d.values(): <NEW_LINE> <INDENT> if val is not None: <NEW_LINE> <INDENT> return val <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("No valid config value found!") <NEW_LINE> <DEDENT> <DEDENT> def transformed(self): <NEW_LINE> <INDENT> return self.typ.transform(self.value()) <NEW_LINE> <DEDENT> def setv(self, layer, value, interpolated): <NEW_LINE> <INDENT> self.typ.validate(interpolated) <NEW_LINE> self.values[layer] = value
Base class for setting values. Intended to be subclassed by config value "types". Attributes: typ: A BaseType subclass instance. value: (readonly property) The currently valid, most important value. values: An OrderedDict with the values on different layers, with the most significant layer first.
62598fa12c8b7c6e89bd3626
class AllowTrustResult: <NEW_LINE> <INDENT> def __init__( self, code: AllowTrustResultCode, ) -> None: <NEW_LINE> <INDENT> self.code = code <NEW_LINE> <DEDENT> def pack(self, packer: Packer) -> None: <NEW_LINE> <INDENT> self.code.pack(packer) <NEW_LINE> if self.code == AllowTrustResultCode.ALLOW_TRUST_SUCCESS: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def unpack(cls, unpacker: Unpacker) -> "AllowTrustResult": <NEW_LINE> <INDENT> code = AllowTrustResultCode.unpack(unpacker) <NEW_LINE> if code == AllowTrustResultCode.ALLOW_TRUST_SUCCESS: <NEW_LINE> <INDENT> return cls(code) <NEW_LINE> <DEDENT> return cls(code) <NEW_LINE> <DEDENT> def to_xdr_bytes(self) -> bytes: <NEW_LINE> <INDENT> packer = Packer() <NEW_LINE> self.pack(packer) <NEW_LINE> return packer.get_buffer() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_xdr_bytes(cls, xdr: bytes) -> "AllowTrustResult": <NEW_LINE> <INDENT> unpacker = Unpacker(xdr) <NEW_LINE> return cls.unpack(unpacker) <NEW_LINE> <DEDENT> def to_xdr(self) -> str: <NEW_LINE> <INDENT> xdr_bytes = self.to_xdr_bytes() <NEW_LINE> return base64.b64encode(xdr_bytes).decode() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_xdr(cls, xdr: str) -> "AllowTrustResult": <NEW_LINE> <INDENT> xdr_bytes = base64.b64decode(xdr.encode()) <NEW_LINE> return cls.from_xdr_bytes(xdr_bytes) <NEW_LINE> <DEDENT> def __eq__(self, other: object): <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return self.code == other.code <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> out = [] <NEW_LINE> out.append(f"code={self.code}") <NEW_LINE> return f"<AllowTrustResult {[', '.join(out)]}>"
XDR Source Code ---------------------------------------------------------------- union AllowTrustResult switch (AllowTrustResultCode code) { case ALLOW_TRUST_SUCCESS: void; default: void; }; ----------------------------------------------------------------
62598fa1379a373c97d98e76
class Action: <NEW_LINE> <INDENT> HARDWARE = None <NEW_LINE> @staticmethod <NEW_LINE> def hw(): <NEW_LINE> <INDENT> return Action.HARDWARE <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def nothing(): <NEW_LINE> <INDENT> None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def do_power_payload(): <NEW_LINE> <INDENT> hw = Action.hw() <NEW_LINE> hw.power_cpm(True) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def do_power_cameras(): <NEW_LINE> <INDENT> hw = Action.hw() <NEW_LINE> hw.power_cameras(True) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def do_exit_iss_safety_zone(): <NEW_LINE> <INDENT> None
All actions associated with state transitions.
62598fa1f7d966606f747e42
class DummyAuth(object): <NEW_LINE> <INDENT> def __init__(self, **kw): <NEW_LINE> <INDENT> self._users = {} <NEW_LINE> <DEDENT> def create_user(self, user_name, password, email): <NEW_LINE> <INDENT> if user_name in self._users: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> id_ = random.randint(1, 2000) <NEW_LINE> ids = self._users.values() <NEW_LINE> while id_ in ids: <NEW_LINE> <INDENT> id_ = random.randint(1, 2000) <NEW_LINE> <DEDENT> self._users[user_name] = id_ <NEW_LINE> return True <NEW_LINE> <DEDENT> def get_user_id(self, user_name): <NEW_LINE> <INDENT> if user_name in self._users: <NEW_LINE> <INDENT> return self._users[user_name] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def authenticate_user(self, user_name, password): <NEW_LINE> <INDENT> if user_name not in self._users: <NEW_LINE> <INDENT> self.create_user(user_name, password, '') <NEW_LINE> <DEDENT> return self._users[user_name] <NEW_LINE> <DEDENT> def generate_reset_code(self, user_id, overwrite=False): <NEW_LINE> <INDENT> return 'XXXX-XXXX-XXXX-XXXX' <NEW_LINE> <DEDENT> def verify_reset_code(self, user_id, code): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def clear_reset_code(self, user_id): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def get_user_info(self, user_id): <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> def update_email(self, user_id, email): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def delete_user(self, user_id, password=None): <NEW_LINE> <INDENT> for name, id_ in tuple(self._users.items()): <NEW_LINE> <INDENT> if id_ == user_id: <NEW_LINE> <INDENT> del self._users[name] <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def get_total_size(self, user_id): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def get_user_node(self, user_id, assign=True): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def update_password(self, user_id, new_password, old_password): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def admin_update_password(self, user_id, new_password, key): <NEW_LINE> <INDENT> return True
Dummy authentication. Will store the user ids in memory
62598fa13c8af77a43b67e70
class MnliProcessor(DataProcessor): <NEW_LINE> <INDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched") <NEW_LINE> <DEDENT> def get_test_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples( self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test") <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> return ["contradiction", "entailment", "neutral"] <NEW_LINE> <DEDENT> def get_examples_num(self): <NEW_LINE> <INDENT> return 392702 <NEW_LINE> <DEDENT> def _create_examples(self, lines, set_type): <NEW_LINE> <INDENT> examples = [] <NEW_LINE> for (i, line) in enumerate(lines): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> guid = "%s-%s" % (set_type, tokenization.convert_to_unicode(line[0])) <NEW_LINE> text_a = tokenization.convert_to_unicode(line[8]) <NEW_LINE> text_b = tokenization.convert_to_unicode(line[9]) <NEW_LINE> if set_type == "test": <NEW_LINE> <INDENT> label = "contradiction" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label = tokenization.convert_to_unicode(line[-1]) <NEW_LINE> <DEDENT> examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <NEW_LINE> <DEDENT> return examples
Processor for the MultiNLI data set (GLUE version).
62598fa145492302aabfc331
class RaceConditionException(Exception): <NEW_LINE> <INDENT> pass
Raised when an object could not be saved in X attempts
62598fa1d268445f26639ab3
class Card: <NEW_LINE> <INDENT> card_size = (50, 70) <NEW_LINE> def __init__(self, num: int): <NEW_LINE> <INDENT> self.num = num <NEW_LINE> self.active = False <NEW_LINE> self.pos = [0, 0] <NEW_LINE> <DEDENT> def load_graphic(self): <NEW_LINE> <INDENT> self.img = pygame.image.load(folder+str(self.num)+".png") <NEW_LINE> self.img = pygame.transform.scale(self.img, self.card_size) <NEW_LINE> <DEDENT> def click(self): <NEW_LINE> <INDENT> if not self.active: <NEW_LINE> <INDENT> self.active = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.active = False <NEW_LINE> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.active = False <NEW_LINE> <DEDENT> def set_pos(self, pos): <NEW_LINE> <INDENT> self.pos = pos <NEW_LINE> self.x, self.y = self.pos <NEW_LINE> <DEDENT> def draw(self, *args): <NEW_LINE> <INDENT> self.load_graphic() <NEW_LINE> if args: <NEW_LINE> <INDENT> self.x, self.y = args <NEW_LINE> <DEDENT> card = self.img.get_rect().move(self.x, self.y) <NEW_LINE> screen.blit(self.img, (self.x, self.y)) <NEW_LINE> self.rect = card <NEW_LINE> <DEDENT> def collidepoint(self, x, y): <NEW_LINE> <INDENT> return self.rect.collidepoint(x, y) <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.num < other.num <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f'Card {self.num}, active {self.active}' <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{0}'.format(self.num)
Describes Card entity - load image from folder if requested - store description - identify by number (num)
62598fa1d6c5a102081e1fa7
class TestHelpLinksInterface(Interface): <NEW_LINE> <INDENT> nickname = Text(title=u'nickname') <NEW_LINE> displayname = Text(title=u'displayname')
Test interface for the view below.
62598fa1dd821e528d6d8d95
@_register_parser <NEW_LINE> @_set_msg_type(ofproto.OFPT_PORT_STATUS) <NEW_LINE> class OFPPortStatus(MsgBase): <NEW_LINE> <INDENT> def __init__(self, datapath, reason=None, desc=None): <NEW_LINE> <INDENT> super(OFPPortStatus, self).__init__(datapath) <NEW_LINE> self.reason = reason <NEW_LINE> self.desc = desc <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parser(cls, datapath, version, msg_type, msg_len, xid, buf): <NEW_LINE> <INDENT> msg = super(OFPPortStatus, cls).parser(datapath, version, msg_type, msg_len, xid, buf) <NEW_LINE> msg.reason = struct.unpack_from( ofproto.OFP_PORT_STATUS_PACK_STR, msg.buf, ofproto.OFP_HEADER_SIZE)[0] <NEW_LINE> msg.desc = OFPPhyPort.parser(msg.buf, ofproto.OFP_PORT_STATUS_DESC_OFFSET) <NEW_LINE> return msg
Port status message The switch notifies controller of change of ports. ================ ====================================================== Attribute Description ================ ====================================================== reason One of the following values. | OFPPR_ADD | OFPPR_DELETE | OFPPR_MODIFY desc instance of ``OFPPhyPort`` ================ ====================================================== Example:: @set_ev_cls(ofp_event.EventOFPPortStatus, MAIN_DISPATCHER) def port_status_handler(self, ev): msg = ev.msg dp = msg.datapath ofp = dp.ofproto if msg.reason == ofp.OFPPR_ADD: reason = 'ADD' elif msg.reason == ofp.OFPPR_DELETE: reason = 'DELETE' elif msg.reason == ofp.OFPPR_MODIFY: reason = 'MODIFY' else: reason = 'unknown' self.logger.debug('OFPPortStatus received: reason=%s desc=%s', reason, msg.desc)
62598fa163b5f9789fe84fd5
class Email(Module): <NEW_LINE> <INDENT> MAILGUN = 'MAILGUN' <NEW_LINE> __default_config__ = { 'type': MAILGUN } <NEW_LINE> logger = logging.getLogger('wing_database') <NEW_LINE> def init(self, config): <NEW_LINE> <INDENT> self.app.context.modules.email = self <NEW_LINE> self._type = config.get('type') <NEW_LINE> if self._type == self.MAILGUN: <NEW_LINE> <INDENT> from .backends._mailgun import services <NEW_LINE> self.services = services <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.error('Unknown mailer type!') <NEW_LINE> raise NotImplementedError <NEW_LINE> <DEDENT> services.MailerServiceBase.init(module=self) <NEW_LINE> <DEDENT> def send_mail(self, from_email, to_email=[], cc=[], bcc=[], subject='', text='', html=None, attachments=[]): <NEW_LINE> <INDENT> print('Sending email...') <NEW_LINE> self.services.SendEmailService( from_email=from_email, to_email=to_email, cc=cc, bcc=bcc, subject=subject, text=text, html=html, attachments=attachments ).call() <NEW_LINE> print('Sent!')
Drongo module for sending emails
62598fa10a50d4780f70523b
class StatusWidetUpdateWorker(QtCore.QRunnable): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(StatusWidetUpdateWorker, self).__init__() <NEW_LINE> self.signal = StatusWidetUpdateWorkerSignals() <NEW_LINE> <DEDENT> @QtCore.pyqtSlot() <NEW_LINE> def run(self): <NEW_LINE> <INDENT> api = get_ckan_api() <NEW_LINE> if not api.is_available(): <NEW_LINE> <INDENT> text = "No connection" <NEW_LINE> tip = f"Can you access {api.server} via a browser?" <NEW_LINE> icon = "hourglass" <NEW_LINE> <DEDENT> elif not api.is_available(with_correct_version=True): <NEW_LINE> <INDENT> text = "Server out of date" <NEW_LINE> tip = "Please downgrade DCOR-Aid" <NEW_LINE> icon = "ban" <NEW_LINE> <DEDENT> elif not api.api_key: <NEW_LINE> <INDENT> text = "Anonymous" <NEW_LINE> tip = "Click here to enter your API key." <NEW_LINE> icon = "user" <NEW_LINE> <DEDENT> elif not api.is_available(with_api_key=True): <NEW_LINE> <INDENT> text = "API token incorrect" <NEW_LINE> tip = "Click here to update your API key." <NEW_LINE> icon = "user-times" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_data = api.get_user_dict() <NEW_LINE> <DEDENT> except ConnectionTimeoutErrors: <NEW_LINE> <INDENT> text = "Connection timeout" <NEW_LINE> tip = f"Can you access {api.server} via a browser?" <NEW_LINE> icon = "hourglass" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fullname = user_data["fullname"] <NEW_LINE> name = user_data["name"] <NEW_LINE> if not fullname: <NEW_LINE> <INDENT> fullname = name <NEW_LINE> <DEDENT> text = "{}".format(fullname) <NEW_LINE> tip = "user '{}'".format(name) <NEW_LINE> icon = "user-lock" <NEW_LINE> <DEDENT> <DEDENT> self.signal.state_signal.emit(text, tip, icon, api.server)
Worker for updating the current API situation
62598fa1c432627299fa2e3b
class DropDownItem(Widget, _MixinTextualWidget): <NEW_LINE> <INDENT> def __init__(self, text, *args, **kwargs): <NEW_LINE> <INDENT> super(DropDownItem, self).__init__(*args, **kwargs) <NEW_LINE> self.type = 'option' <NEW_LINE> self.set_text(text) <NEW_LINE> <DEDENT> def set_value(self, text): <NEW_LINE> <INDENT> return self.set_text(text) <NEW_LINE> <DEDENT> def get_value(self): <NEW_LINE> <INDENT> return self.get_text()
item widget for the DropDown
62598fa18e7ae83300ee8f01
class NormalItem(Item, ItemProps): <NEW_LINE> <INDENT> def __init__(self, name, sell_in, quality): <NEW_LINE> <INDENT> super().__init__(name, sell_in, quality) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return super().__repr__() <NEW_LINE> <DEDENT> def update(self) -> None: <NEW_LINE> <INDENT> if self.is_expired(): <NEW_LINE> <INDENT> self.quality -= self._quality_down_speed * 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.quality -= self._quality_down_speed <NEW_LINE> <DEDENT> self.constraints() <NEW_LINE> self.sell_in -= 1 <NEW_LINE> <DEDENT> def is_expired(self) -> bool: <NEW_LINE> <INDENT> if self.sell_in < 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def constraints(self) -> None: <NEW_LINE> <INDENT> if self.quality < self._quality_min: <NEW_LINE> <INDENT> self.quality = self._quality_min <NEW_LINE> <DEDENT> if self.quality > self._quality_max: <NEW_LINE> <INDENT> self.quality = self._quality_max
Item común y corriente de la tienda
62598fa156b00c62f0fb2711
class Storage: <NEW_LINE> <INDENT> def __init__(self, root_directory): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__root_path = Path(root_directory) <NEW_LINE> self.__root_path.mkdir(parents=True, exist_ok=True) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise IOError("Impossible d'initialiser le stockage.") <NEW_LINE> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shutil.rmtree(self.__root_path) <NEW_LINE> self.__root_path.mkdir(parents=True, exist_ok=True) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise IOError("Impossible d'effacer le stockage.") <NEW_LINE> <DEDENT> <DEDENT> def read_api_bundle(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filepath = self.__root_path.joinpath(API_BUNDLE_FILE) <NEW_LINE> data = filepath.read_bytes() <NEW_LINE> bundle = APIBundle() <NEW_LINE> bundle.ParseFromString(data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise IOError("Impossible de lire l'API Bundle du stockage.") <NEW_LINE> <DEDENT> return bundle <NEW_LINE> <DEDENT> def write_api_bundle(self, api_bundle): <NEW_LINE> <INDENT> if not isinstance(api_bundle, APIBundle): <NEW_LINE> <INDENT> raise ValueError("L'API Bundle à écrire est invalide.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> filepath = self.__root_path.joinpath(API_BUNDLE_FILE) <NEW_LINE> data = api_bundle.SerializeToString() <NEW_LINE> filepath.write_bytes(data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise IOError("Impossible d'écrire l'API Bundle dans le stockage.") <NEW_LINE> <DEDENT> <DEDENT> def read_schedule(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filepath = self.__root_path.joinpath(PLANNING_FILE) <NEW_LINE> data = filepath.read_bytes() <NEW_LINE> bundle = Schedule() <NEW_LINE> bundle.ParseFromString(data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise IOError("Impossible de lire le planning du stockage.") <NEW_LINE> <DEDENT> return bundle <NEW_LINE> <DEDENT> def write_schedule(self, schedule): <NEW_LINE> <INDENT> if not isinstance(schedule, Schedule): <NEW_LINE> <INDENT> raise ValueError("Le planning à écrire est invalide.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> filepath = self.__root_path.joinpath(PLANNING_FILE) <NEW_LINE> data = schedule.SerializeToString() <NEW_LINE> filepath.write_bytes(data) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise IOError("Impossible d'écrire le planning dans le stockage.")
Parser for user input (intents).
62598fa1cc0a2c111447ae6f
class TestCharField(FieldValues): <NEW_LINE> <INDENT> valid_inputs = { 1: '1', 'abc': 'abc' } <NEW_LINE> invalid_inputs = { '': ['This field may not be blank.'] } <NEW_LINE> outputs = { 1: '1', 'abc': 'abc' } <NEW_LINE> field = serializers.CharField() <NEW_LINE> def test_trim_whitespace_default(self): <NEW_LINE> <INDENT> field = serializers.CharField() <NEW_LINE> assert field.to_internal_value(' abc ') == 'abc' <NEW_LINE> <DEDENT> def test_trim_whitespace_disabled(self): <NEW_LINE> <INDENT> field = serializers.CharField(trim_whitespace=False) <NEW_LINE> assert field.to_internal_value(' abc ') == ' abc ' <NEW_LINE> <DEDENT> def test_disallow_blank_with_trim_whitespace(self): <NEW_LINE> <INDENT> field = serializers.CharField(allow_blank=False, trim_whitespace=True) <NEW_LINE> with pytest.raises(serializers.ValidationError) as exc_info: <NEW_LINE> <INDENT> field.run_validation(' ') <NEW_LINE> <DEDENT> assert exc_info.value.detail == ['This field may not be blank.']
Valid and invalid values for `CharField`.
62598fa1462c4b4f79dbb86d
class ExceptionStackContext(object): <NEW_LINE> <INDENT> def __init__(self, exception_handler): <NEW_LINE> <INDENT> self.exception_handler = exception_handler <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.old_contexts = _state.contexts <NEW_LINE> _state.contexts = (self.old_contexts + ((ExceptionStackContext, self.exception_handler),)) <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if type is not None: <NEW_LINE> <INDENT> return self.exception_handler(type, value, traceback) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> _state.contexts = self.old_contexts
Specialization of StackContext for exception handling. The supplied exception_handler function will be called in the event of an uncaught exception in this context. The semantics are similar to a try/finally clause, and intended use cases are to log an error, close a socket, or similar cleanup actions. The exc_info triple (type, value, traceback) will be passed to the exception_handler function. If the exception handler returns true, the exception will be consumed and will not be propagated to other exception handlers.
62598fa199fddb7c1ca62d18
class BookLevel: <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self.soccer, self.tennis, self.hockey, self.basket, self.volley = ([] for i in range(5)) <NEW_LINE> <DEDENT> def attrs_dict(self) -> dict: <NEW_LINE> <INDENT> return {attr: val for attr, val in self.__dict__.items() if isinstance(val, list)} <NEW_LINE> <DEDENT> def _del_empty(self) -> None: <NEW_LINE> <INDENT> for attr, val in self.attrs_dict().items(): <NEW_LINE> <INDENT> new_val = [event for event in val if _exist_not_empty(event)] <NEW_LINE> setattr(self, attr, new_val) <NEW_LINE> <DEDENT> <DEDENT> def _format(self) -> None: <NEW_LINE> <INDENT> for sport in self.attrs_dict().values(): <NEW_LINE> <INDENT> for event in sport: <NEW_LINE> <INDENT> event._format() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def format(self) -> None: <NEW_LINE> <INDENT> self._del_empty() <NEW_LINE> self._format()
Represent level of bookmaker, on which bookmaker has 5 types of sports.
62598fa15fdd1c0f98e5ddf9
@unittest.skip("option not available") <NEW_LINE> class InsiderAuctionComplaintResourceTest(BaseInsiderAuctionWebTest, AuctionComplaintResourceTestMixin): <NEW_LINE> <INDENT> pass
Test Case for Auction Complaint resource
62598fa1e64d504609df92e9
class URDFObject(object): <NEW_LINE> <INDENT> def __init__(self, urdf_path, sensor_pos_vector3): <NEW_LINE> <INDENT> if len(sensor_pos_vector3) == 3: <NEW_LINE> <INDENT> self._obj = p.loadURDF(urdf_path, sensor_pos_vector3) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("use a 3 length sensor_pos_vector3 list as argument") <NEW_LINE> <DEDENT> <DEDENT> def get_sensor_obj(self): <NEW_LINE> <INDENT> return self._obj
class to process all the URDF references usually inherited by other object creator classes
62598fa14f6381625f1993ed
class HIBC: <NEW_LINE> <INDENT> def __init__(self, _hibc_n): <NEW_LINE> <INDENT> self.hibc = _hibc_n <NEW_LINE> self.primary, self.secondary = None, None <NEW_LINE> self.lic = None <NEW_LINE> self.units = None <NEW_LINE> self.expire_date = None <NEW_LINE> self.edi_number = None <NEW_LINE> self.lot_number = None <NEW_LINE> self.manufactured_date = None <NEW_LINE> <DEDENT> def parse(self): <NEW_LINE> <INDENT> return self.__parse_hibc(self.hibc) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __jd_to_dt(cls, jd): <NEW_LINE> <INDENT> return datetime.strptime(jd, '%y%j').date() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __verify(cls, _hibc): <NEW_LINE> <INDENT> if match(r'(^[+])\w(\d{3})([\w\d]*)/(\d{6})(\d*)([\w\d_+$\-.\s%]*)$', _hibc): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __verify_concat_hibc(cls, hibc, check_digit): <NEW_LINE> <INDENT> chr_list = list(hibc[:-1]) <NEW_LINE> if sum([HIBC_TABLE[c] for c in chr_list]) % 43 == HIBC_TABLE[check_digit]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __parse_manufactured_date(cls, key): <NEW_LINE> <INDENT> date = ''.join([str(HIBC_TABLE[x]) for x in list(key)]) <NEW_LINE> year = '20' + date[2:] <NEW_LINE> month = str(int(date[1]) + 1) <NEW_LINE> day = date[0] <NEW_LINE> _date = '{}-{}-{}'.format(year, month, day) <NEW_LINE> n_date = ''.join(('0' if len(x) < 2 else '')+x for x in _date.split('-')) <NEW_LINE> return datetime.strptime(n_date, '%Y%m%d').date() <NEW_LINE> <DEDENT> def __parse_hibc(self, hibc): <NEW_LINE> <INDENT> if not self.__verify(hibc): <NEW_LINE> <INDENT> raise ValueError("Not a valid Barcode [{}].".format(hibc)) <NEW_LINE> <DEDENT> if not self.__verify_concat_hibc(hibc, hibc[-1:]): <NEW_LINE> <INDENT> raise ValueError("Not a valid Barcode [{}]. Primary and " "Secondary Barcode's do not match.".format(hibc)) <NEW_LINE> <DEDENT> s_hibc = hibc.split(r'/') <NEW_LINE> self.primary, self.secondary = s_hibc[0], s_hibc[1] <NEW_LINE> self.lic = self.primary[1:5] <NEW_LINE> self.units = self.primary[-1:] <NEW_LINE> self.expire_date = self.__jd_to_dt(self.secondary[:5]) if self.secondary[0] != '%' else 'None' <NEW_LINE> self.edi_number = self.primary[5:-1] <NEW_LINE> self.lot_number = self.secondary[5:-4] <NEW_LINE> self.manufactured_date = self.__parse_manufactured_date(self.secondary[-4:-1]) <NEW_LINE> return OrderedDict({"barcode": hibc, "lic": self.lic, "units": self.units, "edi_number": self.edi_number, "lot_number": self.lot_number, "expiration_date": self.expire_date, "manufactured_date": self.manufactured_date})
Barcode Parser
62598fa1f548e778e596b40f
class MonitorServer(XmlRpcBaseServer): <NEW_LINE> <INDENT> server_name = "monitor" <NEW_LINE> method_names = XmlRpcBaseServer.method_names + [ 'startRecord', 'stopRecord', 'getResult', 'getXmlResult', 'getMonitorsConfig'] <NEW_LINE> def __init__(self, argv=None): <NEW_LINE> <INDENT> self.interval = None <NEW_LINE> self.records = [] <NEW_LINE> self._keys = {} <NEW_LINE> XmlRpcBaseServer.__init__(self, argv) <NEW_LINE> self.plugins=MonitorPlugins(self._conf) <NEW_LINE> self.plugins.registerPlugins() <NEW_LINE> self._monitor = MonitorThread(self.records, self.plugins, self.host, self.interval) <NEW_LINE> self._monitor.start() <NEW_LINE> <DEDENT> def _init_cb(self, conf, options): <NEW_LINE> <INDENT> self.interval = conf.getfloat('server', 'interval') <NEW_LINE> self._conf=conf <NEW_LINE> <DEDENT> def startRecord(self, key): <NEW_LINE> <INDENT> self.logd('startRecord %s' % key) <NEW_LINE> if key not in self._keys or self._keys[key][1] is not None: <NEW_LINE> <INDENT> self._monitor.startRecord() <NEW_LINE> <DEDENT> self._keys[key] = [len(self.records), None] <NEW_LINE> return 1 <NEW_LINE> <DEDENT> def stopRecord(self, key): <NEW_LINE> <INDENT> self.logd('stopRecord %s' % key) <NEW_LINE> if key not in self._keys or self._keys[key][1] is not None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> self._keys[key] = [self._keys[key][0], len(self.records)] <NEW_LINE> self._monitor.stopRecord() <NEW_LINE> return 1 <NEW_LINE> <DEDENT> def getResult(self, key): <NEW_LINE> <INDENT> self.logd('getResult %s' % key) <NEW_LINE> if key not in self._keys.keys(): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> ret = self.records[self._keys[key][0]:self._keys[key][1]] <NEW_LINE> return ret <NEW_LINE> <DEDENT> def getMonitorsConfig(self): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> for plugin in (self.plugins.MONITORS.values()): <NEW_LINE> <INDENT> conf = plugin.getConfig() <NEW_LINE> if conf: <NEW_LINE> <INDENT> ret[plugin.name] = conf <NEW_LINE> <DEDENT> <DEDENT> return ret <NEW_LINE> <DEDENT> def getXmlResult(self, key): <NEW_LINE> <INDENT> self.logd('getXmlResult %s' % key) <NEW_LINE> ret = self.getResult(key) <NEW_LINE> ret = [stat.__repr__(key) for stat in ret] <NEW_LINE> return '\n'.join(ret) <NEW_LINE> <DEDENT> def test(self): <NEW_LINE> <INDENT> key = 'internal_test_monitor' <NEW_LINE> self.startRecord(key) <NEW_LINE> sleep(3) <NEW_LINE> self.stopRecord(key) <NEW_LINE> self.log(self.records) <NEW_LINE> self.log(self.getXmlResult(key)) <NEW_LINE> return 1
The XML RPC monitor server.
62598fa12ae34c7f260aaf41
class InjectSink(Sink): <NEW_LINE> <INDENT> def __init__(self, iface=None, name=None): <NEW_LINE> <INDENT> Sink.__init__(self, name=name) <NEW_LINE> if iface == None: <NEW_LINE> <INDENT> iface = conf.iface <NEW_LINE> <DEDENT> self.iface = iface <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.s = conf.L2socket(iface=self.iface) <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> self.s.close() <NEW_LINE> <DEDENT> def push(self, msg): <NEW_LINE> <INDENT> self.s.send(msg)
Packets received on low input are injected to an interface +-----------+ >>-| |->> | | >-|--[iface] |-> +-----------+
62598fa16e29344779b004bd
class PendingCertificateSigningRequestResult(Model): <NEW_LINE> <INDENT> _validation = { 'value': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': 'str'}, } <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.value = None
The pending certificate signing request result. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: The pending certificate signing request as Base64 encoded string. :vartype value: str
62598fa11b99ca400228f45f
class SparkSqlToDF(AbstractSqlToDF): <NEW_LINE> <INDENT> __spark_context = None <NEW_LINE> __hive_context = None <NEW_LINE> def __init__(self, *args,**kwargs): <NEW_LINE> <INDENT> super(SparkSqlToDF, self).__init__() <NEW_LINE> if SparkSqlToDF.__spark_context: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not os.environ.has_key('SPARK_HOME'): <NEW_LINE> <INDENT> raise SqlToDFException("Environment variable SPARK_HOME must be set " + "to the root directory of the SPARK installation") <NEW_LINE> <DEDENT> spark_home_py = os.path.expandvars("$SPARK_HOME/python") <NEW_LINE> sys.path.append(spark_home_py) <NEW_LINE> file_list = glob.glob(spark_home_py + "/lib/py4j*.zip") <NEW_LINE> if file_list is None: <NEW_LINE> <INDENT> raise SqlToDFException("p4j*.zip not found - this needs to be on the PYTHONPATH") <NEW_LINE> <DEDENT> sys.path.append(file_list[0]) <NEW_LINE> try: <NEW_LINE> <INDENT> from pyspark import SparkContext, SparkConf <NEW_LINE> from pyspark.sql import HiveContext <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise SqlToDFException("Required pyspark modules cannot be found") <NEW_LINE> <DEDENT> if cfg.SPARK.has_key('spark.driver.memory'): <NEW_LINE> <INDENT> memory = cfg.SPARK['spark.driver.memory'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> memory = '1g' <NEW_LINE> <DEDENT> pyspark_submit_args = ' --driver-memory ' + memory + ' pyspark-shell' <NEW_LINE> os.environ["PYSPARK_SUBMIT_ARGS"] = pyspark_submit_args <NEW_LINE> SparkSqlToDF.__spark_context = SparkContext(conf = self._sparkconfig(SparkConf())) <NEW_LINE> SparkSqlToDF.__spark_context.setLogLevel('INFO') <NEW_LINE> SparkSqlToDF.__hive_context = HiveContext(SparkSqlToDF.__spark_context) <NEW_LINE> <DEDENT> def _sparkconfig(self,sparkc): <NEW_LINE> <INDENT> sparkc.setMaster(cfg.SPARK_MODE).setAppName(cfg.APP_NAME) <NEW_LINE> for k in cfg.SPARK: <NEW_LINE> <INDENT> sparkc.set(k,cfg.SPARK[k]) <NEW_LINE> <DEDENT> return sparkc <NEW_LINE> <DEDENT> def dumpconfig(self): <NEW_LINE> <INDENT> for itm in self.__spark_context.getConf().getAll(): <NEW_LINE> <INDENT> print(itm) <NEW_LINE> <DEDENT> <DEDENT> def SqlToPandas(self,sql,*args,**kwargs): <NEW_LINE> <INDENT> spark_df = SparkSqlToDF.__hive_context.sql(sql) <NEW_LINE> pandas_df = spark_df.toPandas() <NEW_LINE> spark_df.unpersist() <NEW_LINE> return pandas_df
Conversion of Hive SQL resultset to Panda's dataframe.
62598fa132920d7e50bc5eb7
class Sets(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=40, help_text="Enter a name of an item") <NEW_LINE> summary = models.TextField(max_length=1000, help_text="Enter a brief description of an item") <NEW_LINE> image = models.ImageField(blank=True, null=True, upload_to="sets_images") <NEW_LINE> price = models.IntegerField(default=0, null=True, blank=True, help_text="Entrer a price here") <NEW_LINE> weight = models.CharField(max_length=4, null=True, blank=True, help_text="Enter a weight in grams here") <NEW_LINE> candy_item = models.ManyToManyField('Candy', blank=True, help_text='Select a candy for this set') <NEW_LINE> ITEM_STATUS = ( ('a', 'Available'), ('d', 'Under development'), ('o', 'Out of stock'), ('i', 'In production'), ) <NEW_LINE> status = models.CharField(max_length=1, choices=ITEM_STATUS, default='d', blank=True, help_text='Item availability') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def image_tag(self): <NEW_LINE> <INDENT> return mark_safe('<img src=/media/{0} width="40" height="40">'.format(self.image)) <NEW_LINE> <DEDENT> image_tag.short_description = 'Image' <NEW_LINE> image_tag.allow_tags = True <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('set-detail', args=[str(self.id)]) <NEW_LINE> <DEDENT> def display_candy(self): <NEW_LINE> <INDENT> pass
Model representing a set (box with candies)
62598fa1baa26c4b54d4f111
class CrestList(list): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def fromlist(listt): <NEW_LINE> <INDENT> new = CrestList() <NEW_LINE> new.extend(listt) <NEW_LINE> return new
a special class that's produced when using an annotation with several states (transitions, updates)
62598fa1a219f33f346c667b
class TerminalBackendInterface: <NEW_LINE> <INDENT> def __init__(self, token, base_url): <NEW_LINE> <INDENT> self.token = token <NEW_LINE> self.base_url = base_url <NEW_LINE> self._auth_header = {'Authorization': 'Token '+self.token} <NEW_LINE> self._info = self.api_get('/terminals/myself') <NEW_LINE> <DEDENT> def api_get(self, api_path): <NEW_LINE> <INDENT> url = api_path if self.base_url in api_path else self.base_url+api_path <NEW_LINE> r = requests.get(url, headers=self._auth_header) <NEW_LINE> return r.json() <NEW_LINE> <DEDENT> def identify_user(self, id_type, id_str): <NEW_LINE> <INDENT> user = [p for p in self.api_get('/profiles/')['results'] if p['id_type'] == id_type and p['id_string'] == id_str] <NEW_LINE> if user: <NEW_LINE> <INDENT> return user[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def check_permission(self, user_id, dev_shortname): <NEW_LINE> <INDENT> dev = self.api_get('/devices/'+dev_shortname) <NEW_LINE> perm = [p for p in self.api_get('/permissions/')['results'] if p['granted_to_id'] == user_id and p['permission_group'] == dev['required_permission_group']] <NEW_LINE> if perm: <NEW_LINE> <INDENT> return perm[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def api_devicestatus_change(self, shortname, in_operation, authorization, reason=None, start_time=None): <NEW_LINE> <INDENT> data = {'in_operation': in_operation, 'authorization': authorization} <NEW_LINE> if start_time: <NEW_LINE> <INDENT> data['start_time'] = start_time <NEW_LINE> <DEDENT> if reason: <NEW_LINE> <INDENT> data['reason'] = reason <NEW_LINE> <DEDENT> url = self.base_url+'/device/'+shortname+'/status' <NEW_LINE> request.put(url, data=data, header=self._auth_header) <NEW_LINE> <DEDENT> def get_devices(self): <NEW_LINE> <INDENT> devices = [] <NEW_LINE> for dev_url in self._info['devices']: <NEW_LINE> <INDENT> dev_info = self.api_get(dev_url) <NEW_LINE> dev = DeviceInterfaceDummy(**dev_info) <NEW_LINE> devices.append(dev) <NEW_LINE> <DEDENT> return devices
Interface from terminal to backend server
62598fa12ae34c7f260aaf42
class ToolAction: <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def execute(self, tool, trans, incoming=None, set_output_hid=True, **kwargs): <NEW_LINE> <INDENT> pass
The actions to be taken when a tool is run (after parameters have been converted and validated).
62598fa11f5feb6acb162a84
class SimplePatient(object): <NEW_LINE> <INDENT> def __init__(self, viruses, maxPop): <NEW_LINE> <INDENT> self.viruses = viruses <NEW_LINE> self.maxPop = maxPop <NEW_LINE> <DEDENT> def getTotalPop(self): <NEW_LINE> <INDENT> return len(self.viruses) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> viruses = [] <NEW_LINE> for virus in self.viruses: <NEW_LINE> <INDENT> if not virus.doesClear(): <NEW_LINE> <INDENT> viruses.append(virus) <NEW_LINE> <DEDENT> <DEDENT> self.viruses = viruses <NEW_LINE> popDensity = len(viruses)/float(self.maxPop) <NEW_LINE> childViruses = [] <NEW_LINE> for virus in self.viruses: <NEW_LINE> <INDENT> childViruses.append(virus) <NEW_LINE> try: <NEW_LINE> <INDENT> newVirus = virus.reproduce(popDensity) <NEW_LINE> childViruses.append(newVirus) <NEW_LINE> <DEDENT> except NoChildException: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> self.viruses = childViruses <NEW_LINE> return self.getTotalPop()
Representation of a simplified patient. The patient does not take any drugs and his/her virus populations have no drug resistance.
62598fa191f36d47f2230dd2
class LimiterBuilder(object): <NEW_LINE> <INDENT> def __init__(self, test, requestsPerSocket=3, socketCount=2): <NEW_LINE> <INDENT> self.requestsPerSocket = requestsPerSocket <NEW_LINE> self.socketCount = socketCount <NEW_LINE> self.limiter = ConnectionLimiter( 2, maxRequests=requestsPerSocket * socketCount ) <NEW_LINE> self.dispatcher = self.limiter.dispatcher <NEW_LINE> self.dispatcher.reactor = ReaderAdder() <NEW_LINE> self.service = Service() <NEW_LINE> self.limiter.addPortService("TCP", 4321, "127.0.0.1", 5, self.serverServiceMakerMaker(self.service)) <NEW_LINE> for ignored in xrange(socketCount): <NEW_LINE> <INDENT> subskt = self.dispatcher.addSocket() <NEW_LINE> subskt.start() <NEW_LINE> subskt.restarted() <NEW_LINE> <DEDENT> self.limiter.startService() <NEW_LINE> self.port = self.service.myPort <NEW_LINE> <DEDENT> def highestLoad(self): <NEW_LINE> <INDENT> return max( skt.status.effective() for skt in self.limiter.dispatcher._subprocessSockets ) <NEW_LINE> <DEDENT> def serverServiceMakerMaker(self, s): <NEW_LINE> <INDENT> class NotAPort(object): <NEW_LINE> <INDENT> def startReading(self): <NEW_LINE> <INDENT> self.reading = True <NEW_LINE> <DEDENT> def stopReading(self): <NEW_LINE> <INDENT> self.reading = False <NEW_LINE> <DEDENT> <DEDENT> def serverServiceMaker(port, factory, *a, **k): <NEW_LINE> <INDENT> s.factory = factory <NEW_LINE> s.myPort = NotAPort() <NEW_LINE> s.myPort.startReading() <NEW_LINE> factory.myServer = s <NEW_LINE> return s <NEW_LINE> <DEDENT> return serverServiceMaker <NEW_LINE> <DEDENT> def fillUp(self, acknowledged=True, count=0): <NEW_LINE> <INDENT> for _ignore_x in range(count or self.limiter.maxRequests): <NEW_LINE> <INDENT> self.dispatcher.sendFileDescriptor(None, "SSL") <NEW_LINE> if acknowledged: <NEW_LINE> <INDENT> self.dispatcher.statusMessage( self.dispatcher._subprocessSockets[0], "+" ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def processRestart(self): <NEW_LINE> <INDENT> self.dispatcher._subprocessSockets[0].stop() <NEW_LINE> self.dispatcher._subprocessSockets[0].start() <NEW_LINE> self.dispatcher.statusMessage( self.dispatcher._subprocessSockets[0], "0" ) <NEW_LINE> <DEDENT> def loadDown(self): <NEW_LINE> <INDENT> self.dispatcher.statusMessage( self.dispatcher._subprocessSockets[0], "-" )
A L{LimiterBuilder} can build a L{ConnectionLimiter} and associated objects for a given unit test.
62598fa19c8ee8231304009f
class DeviotRebuildBoardsCommand(WindowCommand): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> PioBridge().save_boards_list_async()
Rebuild the boards.json file who is used to list the boards in the quick menu Extends: sublime_plugin.WindowCommand
62598fa116aa5153ce400362
class ModifyTos(base_tests.SimpleDataPlane): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> logging.info("Running Modify_Tos test") <NEW_LINE> of_ports = config["port_map"].keys() <NEW_LINE> of_ports.sort() <NEW_LINE> self.assertTrue(len(of_ports) > 1, "Not enough ports for test") <NEW_LINE> rv = delete_all_flows(self.controller) <NEW_LINE> self.assertEqual(rv, 0, "Failed to delete all flows") <NEW_LINE> logging.info("Verify if switch supports the action -- modify_tos, if not skip the test") <NEW_LINE> logging.info("Insert a flow with action -- set type of service ") <NEW_LINE> logging.info("Send packet matching the flow, verify recieved packet has TOS rewritten ") <NEW_LINE> sup_acts = sw_supported_actions(self,use_cache="true") <NEW_LINE> if not (sup_acts & 1 << ofp.OFPAT_SET_NW_TOS): <NEW_LINE> <INDENT> skip_message_emit(self, "ModifyTOS test") <NEW_LINE> return <NEW_LINE> <DEDENT> (pkt, exp_pkt, acts) = pkt_action_setup(self, mod_fields=['ip_tos'], check_test_params=True) <NEW_LINE> flow_match_test(self, config["port_map"], pkt=pkt, exp_pkt=exp_pkt, action_list=acts, max_test=2, egr_count=-1)
ModifyTOS :Modify the IP type of service of an IP packet
62598fa1097d151d1a2c0e8c
class BoltzmannTransform(Transform): <NEW_LINE> <INDENT> domain = constraints.real <NEW_LINE> codomain = constraints.simplex <NEW_LINE> event_dim = 1 <NEW_LINE> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, BoltzmannTransform) <NEW_LINE> <DEDENT> def _call(self, x): <NEW_LINE> <INDENT> logprobs = x <NEW_LINE> probs = (logprobs - logprobs.max(-1, True)[0]).exp() <NEW_LINE> probs /= probs.sum(-1, True) <NEW_LINE> return probs <NEW_LINE> <DEDENT> def _inverse(self, y): <NEW_LINE> <INDENT> probs = y <NEW_LINE> return probs.log()
Transform from unconstrained space to the simplex via `y = exp(x)` then normalizing. This is not bijective and cannot be used for HMC. However this acts mostly coordinate-wise (except for the final normalization), and thus is appropriate for coordinate-wise optimization algorithms.
62598fa1b7558d5895463490
class VMtranslator(object): <NEW_LINE> <INDENT> def __init__(self, file): <NEW_LINE> <INDENT> if file.endswith('.vm') and os.path.isfile(file): <NEW_LINE> <INDENT> self.__infilelist = [file] <NEW_LINE> self.__outfilename = file[:-2] + 'asm' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not os.path.isdir(file): <NEW_LINE> <INDENT> print('input should be a ".vm" file or a directory') <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> self.__infilelist = glob.glob(os.path.join(file, '*.vm')) <NEW_LINE> self.__outfilename = os.path.join(file, os.path.basename(os.path.abspath(file)) + '.asm') <NEW_LINE> if self.__infilelist == []: <NEW_LINE> <INDENT> print('no ".vm" file found in the given directory') <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> <DEDENT> self.__code = CodeWriter(self.__outfilename) <NEW_LINE> <DEDENT> def gen(self): <NEW_LINE> <INDENT> if len(self.__infilelist) > 1: <NEW_LINE> <INDENT> self.__code.writeInit() <NEW_LINE> <DEDENT> for infile in self.__infilelist: <NEW_LINE> <INDENT> parser = Parser(infile) <NEW_LINE> while parser.hasnext(): <NEW_LINE> <INDENT> command = parser.next() <NEW_LINE> self.__code.parse(command) <NEW_LINE> <DEDENT> <DEDENT> self.__code.close()
translator .vm file to .asm file if more than one .vm file is given, bootstrap code will be written at the beginning of .asm file method: gen()
62598fa14527f215b58e9d45
class Variable: <NEW_LINE> <INDENT> def __init__(self, name, domain, value=None): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._domain = domain[:] <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return Variable(self._name, self._domain, self._value) <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def reduce_domain(self, value): <NEW_LINE> <INDENT> self._domain.remove(value) <NEW_LINE> <DEDENT> def domain_size(self): <NEW_LINE> <INDENT> return len(self._domain) <NEW_LINE> <DEDENT> def get_domain(self): <NEW_LINE> <INDENT> return self._domain[:] <NEW_LINE> <DEDENT> def is_assigned(self): <NEW_LINE> <INDENT> return self._value is not None <NEW_LINE> <DEDENT> def get_assigned_value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> def set_value(self, value): <NEW_LINE> <INDENT> self._value = value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> buf = "%s(%s)" %(self._name, self._domain) <NEW_LINE> if self._value is not None: <NEW_LINE> <INDENT> buf += ": %s" %(self._value) <NEW_LINE> <DEDENT> return buf
Representation of a discrete variable with a finite domain. As used in our VD table. A variable can be in the assigned state, in which v.is_assigned() will return true.
62598fa1a79ad16197769ec1
class MincutResult (Result): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = pyxb.namespace.ExpandedName(Namespace, 'MincutResult') <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/ore-common/xsd/backendResult.xsd', 26, 2) <NEW_LINE> _ElementMap = Result._ElementMap.copy() <NEW_LINE> _AttributeMap = Result._AttributeMap.copy() <NEW_LINE> __nodeid = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(None, 'nodeid'), 'nodeid', '__httpwww_fuzzed_orgbackendResults_MincutResult_nodeid', True, pyxb.utils.utility.Location('/ore-common/xsd/backendResult.xsd', 30, 10), ) <NEW_LINE> nodeid = property(__nodeid.value, __nodeid.set, None, None) <NEW_LINE> _ElementMap.update({ __nodeid.name() : __nodeid }) <NEW_LINE> _AttributeMap.update({ })
Complex type {http://www.fuzzed.org/backendResults}MincutResult with content type ELEMENT_ONLY
62598fa130bbd722464698a8
class OpenBound(_Bound): <NEW_LINE> <INDENT> name = 'open' <NEW_LINE> def larger(self, other): <NEW_LINE> <INDENT> return self > other <NEW_LINE> <DEDENT> def smaller(self, other): <NEW_LINE> <INDENT> return self < other
Sets larger and smaller functions to be `>` and `<`, respectively.
62598fa1fbf16365ca793f1d
class Subinterface(Interface): <NEW_LINE> <INDENT> _BASE_INTERFACE_NAME = 'entry BASE_INTERFACE_NAME' <NEW_LINE> _BASE_INTERFACE_TYPE = 'var BASE_INTERFACE_TYPE' <NEW_LINE> def set_name(self): <NEW_LINE> <INDENT> if '.' not in self.name: <NEW_LINE> <INDENT> self.name = '{0}.{1}'.format(self.name, self.tag) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def XPATH(self): <NEW_LINE> <INDENT> path = super(Subinterface, self).XPATH <NEW_LINE> if self._BASE_INTERFACE_TYPE in path: <NEW_LINE> <INDENT> if self.uid.startswith('ae'): <NEW_LINE> <INDENT> rep = 'aggregate-ethernet' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rep = 'ethernet' <NEW_LINE> <DEDENT> path = path.replace(self._BASE_INTERFACE_TYPE, rep) <NEW_LINE> <DEDENT> if self._BASE_INTERFACE_NAME in path: <NEW_LINE> <INDENT> base = self.uid.split('.')[0] <NEW_LINE> path = path.replace(self._BASE_INTERFACE_NAME, "entry[@name='{0}']".format(base)) <NEW_LINE> <DEDENT> return path
Subinterface class Do not instantiate this object. Use a subclass.
62598fa101c39578d7f12be1
class NumericReference ( HasPrivateTraits ): <NEW_LINE> <INDENT> context = Instance( 'enthought.model.numeric_context.a_numeric_context.' 'ANumericContext' ) <NEW_LINE> name = Str <NEW_LINE> value = Property <NEW_LINE> def _get_value ( self ): <NEW_LINE> <INDENT> return self.context[ self.name ] <NEW_LINE> <DEDENT> def _set_value ( self, value ): <NEW_LINE> <INDENT> self.context[ self.name ] = value <NEW_LINE> <DEDENT> def _context_modified_changed_for_context ( self, event ): <NEW_LINE> <INDENT> if ((event.reset and (self.name in self.context.context_names)) or (self.name in event.modified)): <NEW_LINE> <INDENT> self.trait_property_changed( 'value', None, self.value )
A named reference to a single numeric context array value.
62598fa1a17c0f6771d5c09d
class GramMatrix(array.LabeledMatrix): <NEW_LINE> <INDENT> @chk.check(dict(data=chk.accept_any(chk.has_reals, chk.has_complex), beam_idx=beamforming.is_beam_index)) <NEW_LINE> def __init__(self, data, beam_idx): <NEW_LINE> <INDENT> data = np.array(data, copy=False) <NEW_LINE> N_beam = len(beam_idx) <NEW_LINE> if not chk.has_shape((N_beam, N_beam))(data): <NEW_LINE> <INDENT> raise ValueError('Parameters[data, beam_idx] are not consistent.') <NEW_LINE> <DEDENT> if not np.allclose(data, data.conj().T): <NEW_LINE> <INDENT> raise ValueError('Parameter[data] must be hermitian symmetric.') <NEW_LINE> <DEDENT> super().__init__(data, beam_idx, beam_idx)
Gram coefficients. Examples -------- .. testsetup:: import numpy as np import pandas as pd from pypeline.phased_array.util.gram import GramMatrix .. doctest:: >>> N_beam = 5 >>> beam_idx = pd.Index(range(N_beam), name='BEAM_ID') >>> G = GramMatrix(np.eye(N_beam), beam_idx) >>> G.data array([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.]])
62598fa1dd821e528d6d8d97
class itkImageFileReaderVIUS3(itkImageSourcePython.itkImageSourceVIUS3): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetFileName(self, *args): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_SetFileName(self, *args) <NEW_LINE> <DEDENT> def GetFileName(self): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_GetFileName(self) <NEW_LINE> <DEDENT> def SetImageIO(self, *args): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_SetImageIO(self, *args) <NEW_LINE> <DEDENT> def GetImageIO(self): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_GetImageIO(self) <NEW_LINE> <DEDENT> def GenerateOutputInformation(self): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_GenerateOutputInformation(self) <NEW_LINE> <DEDENT> def SetUseStreaming(self, *args): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_SetUseStreaming(self, *args) <NEW_LINE> <DEDENT> def GetUseStreaming(self): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_GetUseStreaming(self) <NEW_LINE> <DEDENT> def UseStreamingOn(self): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_UseStreamingOn(self) <NEW_LINE> <DEDENT> def UseStreamingOff(self): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_UseStreamingOff(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkImageFileReaderPython.delete_itkImageFileReaderVIUS3 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkImageFileReaderPython.itkImageFileReaderVIUS3_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkImageFileReaderVIUS3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkImageFileReaderVIUS3 class
62598fa13539df3088ecc117
class travel_rental_service(orm.Model): <NEW_LINE> <INDENT> _name = 'travel.rental.service' <NEW_LINE> _description = _(__doc__) <NEW_LINE> @staticmethod <NEW_LINE> def _check_dep_arr_dates(start, end): <NEW_LINE> <INDENT> return not start or not end or start <= end <NEW_LINE> <DEDENT> def on_change_times(self, cr, uid, ids, start, end, context=None): <NEW_LINE> <INDENT> if self._check_dep_arr_dates(start, end): <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> return { 'value': { 'end': False, }, 'warning': { 'title': 'Arrival after Departure', 'message': ('End of rental (%s) cannot be before Start (%s).' % (start, end)), }, } <NEW_LINE> <DEDENT> def check_date(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> if not ids: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> rental = self.browse(cr, uid, ids[0], context=context) <NEW_LINE> return self._check_dep_arr_dates(rental.start, rental.end) <NEW_LINE> <DEDENT> _columns = { 'location': fields.many2one('res.partner', 'Location', required=True, help='Location of rental supplier.'), 'city_id': fields.many2one('res.better.zip', 'City', required='True', help='City of rental.'), 'start': fields.datetime('Start', required=True, help='Start date and time of rental.'), 'end': fields.datetime('End', required=True, help='End date and time of rental.'), 'capacity': fields.integer('Capacity', help='Maximum capacity of people in room.'), 'equipment': fields.text('Desired equipment'), 'services': fields.text('Desired services'), 'passenger_id': fields.many2one( 'travel.passenger', 'Passenger', required=True, help='Passenger of this rental.'), } <NEW_LINE> _constraints = [ (check_date, _('End date cannot be after Start date for service rental.'), ['start', 'end']), ]
Service rentals for travel
62598fa10a50d4780f70523d
class GmyUnstructuredGridReader(vtk.vtkProgrammableSource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.SetExecuteMethod(self._Execute) <NEW_LINE> self.GetUnstructuredGridOutput() <NEW_LINE> self.FileName = "" <NEW_LINE> return <NEW_LINE> <DEDENT> def GetOutputPort(self, index=3): <NEW_LINE> <INDENT> return vtk.vtkAlgorithm.GetOutputPort(self, index) <NEW_LINE> <DEDENT> def SetFileName(self, name): <NEW_LINE> <INDENT> self.FileName = name <NEW_LINE> self.Modified() <NEW_LINE> return <NEW_LINE> <DEDENT> def GetFileName(self): <NEW_LINE> <INDENT> return self.FileName <NEW_LINE> <DEDENT> def _Execute(self): <NEW_LINE> <INDENT> output = self.GetUnstructuredGridOutput() <NEW_LINE> loader = GeneratingLoader(self.FileName) <NEW_LINE> loader.Load() <NEW_LINE> output.ShallowCopy(loader.Grid) <NEW_LINE> return
VTK-style reader for HemeLB Geometry files (.gmy). When run, it will create a VTK data structure with the same geometry as the file. The vtkUnstructuredGrid that is the output will have one cell for every fluid site in the geometry file. The cell will be a cube or voxel (in VTK terminology a cell with type VTK_VOXEL or, when accessed through the GetCell() API, an instance of vtkVoxel) with its centre on the lattice point and its corners half a lattice unit away in each of the eight <1,1,1> type directions. The output units are metres and the object has no cell data or point data.
62598fa138b623060ffa8ef6
class MigrationValidationResult(Model): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'migration_id': {'readonly': True}, 'status': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'migration_id': {'key': 'migrationId', 'type': 'str'}, 'summary_results': {'key': 'summaryResults', 'type': '{MigrationValidationDatabaseSummaryResult}'}, 'status': {'key': 'status', 'type': 'str'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(MigrationValidationResult, self).__init__(**kwargs) <NEW_LINE> self.id = None <NEW_LINE> self.migration_id = None <NEW_LINE> self.summary_results = kwargs.get('summary_results', None) <NEW_LINE> self.status = None
Migration Validation Result. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Migration validation result identifier :vartype id: str :ivar migration_id: Migration Identifier :vartype migration_id: str :param summary_results: Validation summary results for each database :type summary_results: dict[str, ~azure.mgmt.datamigration.models.MigrationValidationDatabaseSummaryResult] :ivar status: Current status of validation at the migration level. Status from the database validation result status will be aggregated here. Possible values include: 'Default', 'NotStarted', 'Initialized', 'InProgress', 'Completed', 'CompletedWithIssues', 'Stopped', 'Failed' :vartype status: str or ~azure.mgmt.datamigration.models.ValidationStatus
62598fa1462c4b4f79dbb86f
class AccountManager: <NEW_LINE> <INDENT> def __init__(self, capital_base=100000, name="", currency=Currency("USD"), leverage=1): <NEW_LINE> <INDENT> self.__capital_base = capital_base <NEW_LINE> self.__name = name <NEW_LINE> self.__currency = currency <NEW_LINE> self.__leverage = leverage <NEW_LINE> self.initialize() <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> self.__capital_net = self.__capital_base <NEW_LINE> self.__capital_cash = self.__capital_base <NEW_LINE> self.__records = [] <NEW_LINE> <DEDENT> def set_capital_base(self, capital_base): <NEW_LINE> <INDENT> if isinstance(capital_base, int) and capital_base > 0: <NEW_LINE> <INDENT> self.__capital_base = capital_base <NEW_LINE> self.initialize <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise(ValueError("不合法的base值%s"%capital_base)) <NEW_LINE> <DEDENT> <DEDENT> def is_margin_enough(self, price): <NEW_LINE> <INDENT> return(self.__capital_cash * self.__leverage >= price) <NEW_LINE> <DEDENT> def update_deal(self, deal): <NEW_LINE> <INDENT> if not deal.profit: return <NEW_LINE> self.__capital_cash += deal.profit <NEW_LINE> self.__records.append({'x':deal.time+deal.time_msc/(10**6),'y':float('%.2f'%((self.__capital_cash/self.__capital_base-1)*100))}) <NEW_LINE> <DEDENT> def get_profit_records(self): <NEW_LINE> <INDENT> return(self.__records)
交易账户对象
62598fa199fddb7c1ca62d19
class Permissions(UserDict): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.data = {}
Overridden instance of dictionary with some functions to simplify access and searching through data. Attributes: data: Underlying dictionary containing hierarchical data.
62598fa10c0af96317c561e5
class Adjustment(): <NEW_LINE> <INDENT> def __init__(self, mask_type, output_size, predicted_available, configfile=None, config=None): <NEW_LINE> <INDENT> logger.debug("Initializing %s: (arguments: '%s', output_size: %s, " "predicted_available: %s, configfile: %s, config: %s)", self.__class__.__name__, mask_type, output_size, predicted_available, configfile, config) <NEW_LINE> self.config = self.set_config(configfile, config) <NEW_LINE> logger.debug("config: %s", self.config) <NEW_LINE> self.mask_type = self.get_mask_type(mask_type, predicted_available) <NEW_LINE> self.dummy = np.zeros((output_size, output_size, 3), dtype='float32') <NEW_LINE> self.skip = self.config.get("type", None) is None <NEW_LINE> logger.debug("Initialized %s", self.__class__.__name__) <NEW_LINE> <DEDENT> def set_config(self, configfile, config): <NEW_LINE> <INDENT> section = ".".join(self.__module__.split(".")[-2:]) <NEW_LINE> if config is None: <NEW_LINE> <INDENT> retval = get_config(section, configfile=configfile) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config.section = section <NEW_LINE> retval = config.config_dict <NEW_LINE> config.section = None <NEW_LINE> <DEDENT> logger.debug("Config: %s", retval) <NEW_LINE> return retval <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_mask_type(mask_type, predicted_available): <NEW_LINE> <INDENT> logger.debug("Requested mask_type: %s", mask_type) <NEW_LINE> if mask_type == "predicted" and not predicted_available: <NEW_LINE> <INDENT> mask_type = model_masks.get_default_mask() <NEW_LINE> logger.warning("Predicted selected, but the model was not trained with a mask. " "Switching to '%s'", mask_type) <NEW_LINE> <DEDENT> logger.debug("Returning mask_type: %s", mask_type) <NEW_LINE> return mask_type <NEW_LINE> <DEDENT> def process(self, *args, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def run(self, *args, **kwargs): <NEW_LINE> <INDENT> logger.trace("Performing mask adjustment: (plugin: %s, args: %s, kwargs: %s", self.__module__, args, kwargs) <NEW_LINE> retval = self.process(*args, **kwargs) <NEW_LINE> return retval
Parent class for adjustments
62598fa144b2445a339b689f
class ZipFilesystem(NodeFilesystem): <NEW_LINE> <INDENT> def __init__(self, path: pathlib.Path) -> None: <NEW_LINE> <INDENT> node = zipfile.Path(path) <NEW_LINE> self.root = ZipFilesystemNode(node)
ZIP filesystem.
62598fa1e5267d203ee6b770
@Key.filter_registry.register('key-rotation-status') <NEW_LINE> class KeyRotationStatus(ValueFilter): <NEW_LINE> <INDENT> schema = type_schema('key-rotation-status', rinherit=ValueFilter.schema) <NEW_LINE> schema_alias = False <NEW_LINE> permissions = ('kms:GetKeyRotationStatus',) <NEW_LINE> def process(self, resources, event=None): <NEW_LINE> <INDENT> client = local_session(self.manager.session_factory).client('kms') <NEW_LINE> def _key_rotation_status(resource): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> resource['KeyRotationEnabled'] = client.get_key_rotation_status( KeyId=resource['KeyId']) <NEW_LINE> <DEDENT> except ClientError as e: <NEW_LINE> <INDENT> if e.response['Error']['Code'] == 'AccessDeniedException': <NEW_LINE> <INDENT> self.log.warning( "Access denied when getting rotation status on key:%s", resource.get('KeyArn')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> with self.executor_factory(max_workers=2) as w: <NEW_LINE> <INDENT> query_resources = [ r for r in resources if 'KeyRotationEnabled' not in r] <NEW_LINE> self.log.debug( "Querying %d kms-keys' rotation status" % len(query_resources)) <NEW_LINE> list(w.map(_key_rotation_status, query_resources)) <NEW_LINE> <DEDENT> return [r for r in resources if self.match( r.get('KeyRotationEnabled', {}))]
Filters KMS keys by the rotation status :example: .. code-block:: yaml policies: - name: kms-key-disabled-rotation resource: kms-key filters: - type: key-rotation-status key: KeyRotationEnabled value: false
62598fa13d592f4c4edbad30
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class Bridge(tf.keras.layers.Layer): <NEW_LINE> <INDENT> def __call__(self, encoder_state, decoder_zero_state): <NEW_LINE> <INDENT> inputs = [encoder_state, decoder_zero_state] <NEW_LINE> if compat.is_tf2(): <NEW_LINE> <INDENT> return super(Bridge, self).__call__(inputs) <NEW_LINE> <DEDENT> if not compat.reuse(): <NEW_LINE> <INDENT> self.build(compat.nest.map_structure(lambda x: x.shape, inputs)) <NEW_LINE> <DEDENT> return self.call(inputs) <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def call(self, states): <NEW_LINE> <INDENT> raise NotImplementedError()
Base class for bridges.
62598fa197e22403b383ad6f
class Sentinel(enum.Enum): <NEW_LINE> <INDENT> sentinel = object()
A type-safe sentinel class
62598fa12ae34c7f260aaf43
class CheckFieldDefaultMixin(object): <NEW_LINE> <INDENT> _default_hint = ('<valid default>', '<invalid default>') <NEW_LINE> def _check_default(self): <NEW_LINE> <INDENT> if self.has_default() and self.default is not None and not callable(self.default): <NEW_LINE> <INDENT> return [ checks.Warning( '%s default should be a callable instead of an instance so that it\'s not shared between all field ' 'instances.' % (self.__class__.__name__,), hint='Use a callable instead, e.g., use `%s` instead of `%s`.' % self._default_hint, obj=self, id='postgres.E003', ) ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> def check(self, **kwargs): <NEW_LINE> <INDENT> errors = super(CheckFieldDefaultMixin, self).check(**kwargs) <NEW_LINE> errors.extend(self._check_default()) <NEW_LINE> return errors
This was copied from https://github.com/django/django/commit/f6e1789654e82bac08cead5a2d2a9132f6403f52 More info: https://code.djangoproject.com/ticket/28577
62598fa16e29344779b004bf
class CellCrawler(object): <NEW_LINE> <INDENT> BASE_URL = 'http://www.cell.com/' <NEW_LINE> PREV_NEXT = '"/(issue\?pii[^"]+)' <NEW_LINE> FULL_TEXT = '"/(fulltext/[^"]+)' <NEW_LINE> PDF = 'href="(http://download.cell.com/pdf/[^"]+.pdf)"' <NEW_LINE> DATE = '<title>.*, (.*)</title>' <NEW_LINE> SWITCH_TIME = dt(2005, 5, 6, 0, 0) <NEW_LINE> def __init__(self, out=sys.stdout): <NEW_LINE> <INDENT> self.out = out <NEW_LINE> self.decoy = BrowserDecoy() <NEW_LINE> self.visited = set([]) <NEW_LINE> <DEDENT> def start( self, url = "current", headers = {'Host': 'www.cell.com'}, verbose = True): <NEW_LINE> <INDENT> full_url = self.BASE_URL + url <NEW_LINE> self.decoy.connect(full_url, headers) <NEW_LINE> if verbose: <NEW_LINE> <INDENT> sys.stderr.write('started at %s\n' % full_url) <NEW_LINE> <DEDENT> to_previous_issue = re.findall(self.PREV_NEXT, self.decoy.read()) <NEW_LINE> headers.update({'Referer': full_url}) <NEW_LINE> headers.update(self.decoy.get_cookie_items()) <NEW_LINE> self.visited.add(full_url) <NEW_LINE> self.crawl( url_list = to_previous_issue, headers = headers, verbose = verbose ) <NEW_LINE> <DEDENT> def crawl(self, url_list, headers, verbose=True): <NEW_LINE> <INDENT> urls_to_visit = set(url_list).difference(self.visited) <NEW_LINE> for url in urls_to_visit: <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDENT> sys.stderr.write(self.BASE_URL + url + '\n') <NEW_LINE> <DEDENT> retries = 0 <NEW_LINE> while retries < 3: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.decoy.connect(self.BASE_URL + url, headers) <NEW_LINE> content = remove_JS(self.decoy.read()) <NEW_LINE> date_match = re.search(self.DATE, content).groups() <NEW_LINE> date = dt.strptime(date_match[0], '%d %B %Y') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> retries += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if date > self.SWITCH_TIME: <NEW_LINE> <INDENT> BS = BeautifulSoup(content) <NEW_LINE> article_tags = BS.findAll(attrs={'class': 'article'}) <NEW_LINE> articles = '\n'.join([str(tag) for tag in article_tags]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> articles = content <NEW_LINE> <DEDENT> to_prev_next = re.findall(self.PREV_NEXT, content) <NEW_LINE> to_pdf = re.findall(self.PDF, articles) <NEW_LINE> to_full = re.findall(self.FULL_TEXT, articles) <NEW_LINE> self.out.write('"%s": ' % url) <NEW_LINE> json.dump([to_pdf, to_full], self.out) <NEW_LINE> self.out.write(',\n') <NEW_LINE> self.visited.add(url) <NEW_LINE> headers['Referer'] = url <NEW_LINE> self.crawl( url_list = to_prev_next, headers = headers )
A crawler to retrive the links to the articles of Cell.
62598fa1460517430c431f8c
class EndpointQuery: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.redis_connection = RedisProxy() <NEW_LINE> self.handle_data = HandleData() <NEW_LINE> self.connection = self.redis_connection.get_connection() <NEW_LINE> self._data = self.handle_data <NEW_LINE> <DEDENT> def get_allEndpoints(self, query): <NEW_LINE> <INDENT> get_data = self.connection.execute_command( 'GRAPH.QUERY', 'apigraph', "MATCH (p:classes) RETURN p") + self.connection.execute_command( 'GRAPH.QUERY', 'apigraph', "MATCH (p:collection) RETURN p") <NEW_LINE> print("classEndpoints + CollectionEndpoints") <NEW_LINE> return self._data.show_data(get_data) <NEW_LINE> <DEDENT> def get_classEndpoints(self, query): <NEW_LINE> <INDENT> get_data = self.connection.execute_command( 'GRAPH.QUERY', 'apigraph', "MATCH (p:classes) RETURN p") <NEW_LINE> print("classEndpoints") <NEW_LINE> return self._data.show_data(get_data) <NEW_LINE> <DEDENT> def get_collectionEndpoints(self, query): <NEW_LINE> <INDENT> get_data = self.connection.execute_command( 'GRAPH.QUERY', 'apigraph', "MATCH (p:collection) RETURN p") <NEW_LINE> print("collectoinEndpoints") <NEW_LINE> return self._data.show_data(get_data)
EndpointQuery is used for get the endpoints from the Redis.
62598fa11b99ca400228f460
class ParentsTagger(BaseOperator): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _simuPOP_muop.ParentsTagger_swiginit(self, _simuPOP_muop.new_ParentsTagger(*args, **kwargs)) <NEW_LINE> <DEDENT> __swig_destroy__ = _simuPOP_muop.delete_ParentsTagger
Details: This tagging operator records the indexes of parents (relative to the parental generation) of each offspring in specified information fields ( default to father_idx and mother_idx). Only one information field should be specified if an asexsual mating scheme is used so there is one parent for each offspring. Information recorded by this operator is intended to be used to look up parents of each individual in multi-generational Population.
62598fa1498bea3a75a57985
class AudioTrack(Track): <NEW_LINE> <INDENT> def __init__(self, sampling_frequency=None, channels=None, output_sampling_frequency=None, bit_depth=None, **kwargs): <NEW_LINE> <INDENT> super(AudioTrack, self).__init__(**kwargs) <NEW_LINE> self.sampling_frequency = sampling_frequency <NEW_LINE> self.channels = channels <NEW_LINE> self.output_sampling_frequency = output_sampling_frequency <NEW_LINE> self.bit_depth = bit_depth <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromelement(cls, element): <NEW_LINE> <INDENT> audiotrack = super(AudioTrack, cls).fromelement(element) <NEW_LINE> audiotrack.sampling_frequency = element['Audio'].get('SamplingFrequency', 8000.0) <NEW_LINE> audiotrack.channels = element['Audio'].get('Channels', 1) <NEW_LINE> audiotrack.output_sampling_frequency = element['Audio'].get('OutputSamplingFrequency') <NEW_LINE> audiotrack.bit_depth = element['Audio'].get('BitDepth') <NEW_LINE> return audiotrack <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s [%d, %d channel(s), %.0fHz, %s, name=%r, language=%s]>' % (self.__class__.__name__, self.number, self.channels, self.sampling_frequency, self.codec_id, self.name, self.language)
Object for the Tracks EBML element with :data:`AUDIO_TRACK` TrackType
62598fa10a50d4780f70523e
class Validator(): <NEW_LINE> <INDENT> def __init__(self, predicate): <NEW_LINE> <INDENT> self.predicate = predicate <NEW_LINE> <DEDENT> def __call__(self, input): <NEW_LINE> <INDENT> if not self.predicate(input): <NEW_LINE> <INDENT> raise ValueError(f'{input} is invalid') <NEW_LINE> <DEDENT> return input
Creates a validator callable from a predicate.
62598fa14e4d562566372287
class LaTeX(Task): <NEW_LINE> <INDENT> __platforms__ = ["linux", "osx"] <NEW_LINE> __osx_deps__ = ["Homebrew"] <NEW_LINE> __osx_genfiles__ = [ "/Library/TeX/Distributions/.DefaultTeX/Contents/Programs/texbin/pdflatex", "/Applications/texstudio.app", "/Applications/texstudio.app/Contents/Resources/en_GB.ign", ] <NEW_LINE> def install_osx(self): <NEW_LINE> <INDENT> Homebrew().install_cask("mactex") <NEW_LINE> Homebrew().install_cask("texstudio") <NEW_LINE> Homebrew().install_package("poppler") <NEW_LINE> self.install() <NEW_LINE> symlink( os.path.join(PRIVATE, "texstudio", "en_GB.ign"), "/Applications/texstudio.app/Contents/Resources/en_GB.ign", ) <NEW_LINE> <DEDENT> def install_linux(self): <NEW_LINE> <INDENT> Apt().install_package("texlive-full") <NEW_LINE> Apt().install_package("biber") <NEW_LINE> <DEDENT> def upgrade_osx(self): <NEW_LINE> <INDENT> Homebrew().upgrade_cask("mactex") <NEW_LINE> Homebrew().upgrade_cask("texstudio")
latex compiler and libraries
62598fa1be8e80087fbbeec3
class Member(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey( 'core.User', verbose_name='Usuário', blank=True, related_name='user_organization_member', on_delete=models.DO_NOTHING ) <NEW_LINE> position = models.CharField( verbose_name='Atividade/Cargo', help_text='Atividades que o membro realiza.', max_length=150, blank=False ) <NEW_LINE> be_since = models.DateField( verbose_name='Membro Desde', blank=False, ) <NEW_LINE> social_networks = models.ManyToManyField( 'core.SocialNetwork', verbose_name='Redes Sociais', blank=True ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['be_since', 'user'] <NEW_LINE> verbose_name = 'Membro da Organização' <NEW_LINE> verbose_name_plural = 'Membros das Organizações' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.user
Organizations Member model definitions
62598fa1b7558d5895463491
class Ripple25(Benchmark): <NEW_LINE> <INDENT> def __init__(self, dimensions=2): <NEW_LINE> <INDENT> Benchmark.__init__(self, dimensions) <NEW_LINE> self.bounds = list(zip([0.0] * self.dimensions, [1.0] * self.dimensions)) <NEW_LINE> self.global_optimum = [0.1] * self.dimensions <NEW_LINE> self.fglob = -2.0 <NEW_LINE> <DEDENT> def evaluator(self, x, *args): <NEW_LINE> <INDENT> self.fun_evals += 1 <NEW_LINE> return sum(-exp(-2.0*log(2.0)*((x - 0.1)/0.8)**2.0)*(sin(5.0*pi*x)**6.0))
Ripple 25 test objective function. This class defines the Ripple 25 global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Ripple25}}(\mathbf{x}) = \sum_{i=1}^2 -e^{-2 \log 2 (\frac{x_i-0.1}{0.8})^2} \left[\sin^6(5 \pi x_i) \right] Here, :math:`n` represents the number of dimensions and :math:`x_i \in [0, 1]` for :math:`i=1,...,n`. .. figure:: figures/Ripple25.png :alt: Ripple 25 function :align: center **Two-dimensional Ripple 25 function** *Global optimum*: :math:`f(x_i) = -2` for :math:`x_i = 0.1` for :math:`i=1,2`
62598fa2796e427e5384e5f7
class FreqDist(Counter): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def load(klass, stream): <NEW_LINE> <INDENT> data = json.load(stream) <NEW_LINE> dist = klass() <NEW_LINE> for sample, count in data.items(): <NEW_LINE> <INDENT> dist[sample] = count <NEW_LINE> <DEDENT> return dist <NEW_LINE> <DEDENT> def N(self): <NEW_LINE> <INDENT> return sum(self.values()) <NEW_LINE> <DEDENT> def B(self): <NEW_LINE> <INDENT> return len(self) <NEW_LINE> <DEDENT> def freq(self, key): <NEW_LINE> <INDENT> if self.N() == 0: return 0 <NEW_LINE> return float(self[key]) / self.N() <NEW_LINE> <DEDENT> def ratio(self, a, b): <NEW_LINE> <INDENT> if b not in self: return 0 <NEW_LINE> return float(self[a]) / float(self[b]) <NEW_LINE> <DEDENT> def max(self): <NEW_LINE> <INDENT> if len(self) == 0: return None <NEW_LINE> return self.most_common(1)[0][0] <NEW_LINE> <DEDENT> def plot(self, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import pylab <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise ValueError("The plot function requires matplotlib.") <NEW_LINE> <DEDENT> if len(args) == 0: <NEW_LINE> <INDENT> args = [len(self)] <NEW_LINE> <DEDENT> samples = list(islice(self, *args)) <NEW_LINE> freqs = [self[sample] for sample in samples] <NEW_LINE> ylabel = "Counts" <NEW_LINE> pylab.grid(True, color="silver") <NEW_LINE> if not "linewidth" in kwargs: <NEW_LINE> <INDENT> kwargs["linewidth"] = 2 <NEW_LINE> <DEDENT> if "title" in kwargs: <NEW_LINE> <INDENT> pylab.title(kwargs["title"]) <NEW_LINE> del kwargs["title"] <NEW_LINE> <DEDENT> pylab.plot(freqs, **kwargs) <NEW_LINE> pylab.xticks(range(len(samples)), [str(s) for s in samples], rotation=90) <NEW_LINE> pylab.xlabel("Samples") <NEW_LINE> pylab.ylabel(ylabel) <NEW_LINE> pylab.show() <NEW_LINE> <DEDENT> def dump(self, stream): <NEW_LINE> <INDENT> json.dump(self, stream) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.pprint() <NEW_LINE> <DEDENT> def pprint(self, maxlen=10): <NEW_LINE> <INDENT> items = ['{0!r}: {1!r}'.format(*item) for item in self.most_common(maxlen)] <NEW_LINE> if len(self) > maxlen: <NEW_LINE> <INDENT> items.append('...') <NEW_LINE> <DEDENT> return 'FreqDist({{{0}}})'.format(', '.join(items)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<FreqDist with %i samples and %i outcomes>" % (self.B(), self.N())
Based off of NLTK's FreqDist - this records the number of times each outcome of an experiment has occured. Useful for tracking metrics.
62598fa28c0ade5d55dc35c1
class PlaceHolder(object): <NEW_LINE> <INDENT> def __init__(self, dim): <NEW_LINE> <INDENT> self.out_dim = dim <NEW_LINE> <DEDENT> def load(self, data=None): <NEW_LINE> <INDENT> self.output = data
placeholders for training and test data they only have output fields, wont take inputs
62598fa2442bda511e95c2bf
class YelpReview(Item): <NEW_LINE> <INDENT> review_id = Field() <NEW_LINE> text = Field() <NEW_LINE> rating = Field() <NEW_LINE> date = Field() <NEW_LINE> reviewer_location = Field() <NEW_LINE> restaurant_id = Field()
Yelp container (dictionary-like object) for scraped data
62598fa28da39b475be03043
class BaseWriter(Generic[T]): <NEW_LINE> <INDENT> def __init__(self, ltsvfile, formatter): <NEW_LINE> <INDENT> self._ltsvfile = ltsvfile <NEW_LINE> self._formatter = formatter <NEW_LINE> return <NEW_LINE> <DEDENT> def writerow(self, row): <NEW_LINE> <INDENT> line = self._formatter.format(row) <NEW_LINE> n = self._ltsvfile.write(line) <NEW_LINE> if n is None: <NEW_LINE> <INDENT> n = len(line) <NEW_LINE> <DEDENT> return n <NEW_LINE> <DEDENT> def writerows(self, rows): <NEW_LINE> <INDENT> total = 0 <NEW_LINE> for row in rows: <NEW_LINE> <INDENT> total += self.writerow(row) <NEW_LINE> <DEDENT> return total
Base LTSV writer.
62598fa2d6c5a102081e1fab
class Store(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> address = models.ManyToManyField("Address") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Store attributes
62598fa245492302aabfc335
class GpNextPointsConstantLiar(GpNextPointsPrettyView): <NEW_LINE> <INDENT> _route_name = GP_NEXT_POINTS_CONSTANT_LIAR_ROUTE_NAME <NEW_LINE> _pretty_route_name = GP_NEXT_POINTS_CONSTANT_LIAR_PRETTY_ROUTE_NAME <NEW_LINE> request_schema = GpNextPointsConstantLiarRequest() <NEW_LINE> _pretty_default_request = GpNextPointsPrettyView._pretty_default_request.copy() <NEW_LINE> _pretty_default_request['lie_method'] = DEFAULT_CONSTANT_LIAR_METHOD <NEW_LINE> @view_config(route_name=_pretty_route_name, renderer=PRETTY_RENDERER) <NEW_LINE> def pretty_view(self): <NEW_LINE> <INDENT> return self.pretty_response() <NEW_LINE> <DEDENT> def get_lie_value(self, params): <NEW_LINE> <INDENT> if params.get('lie_value') is not None: <NEW_LINE> <INDENT> return params.get('lie_value') <NEW_LINE> <DEDENT> gaussian_process = _make_gp_from_params(params) <NEW_LINE> points_sampled_values = gaussian_process._historical_data._points_sampled_value.tolist() <NEW_LINE> if params.get('lie_method') == CONSTANT_LIAR_MIN: <NEW_LINE> <INDENT> return numpy.amin(points_sampled_values) <NEW_LINE> <DEDENT> elif params.get('lie_method') == CONSTANT_LIAR_MAX: <NEW_LINE> <INDENT> return numpy.amax(points_sampled_values) <NEW_LINE> <DEDENT> elif params.get('lie_method') == CONSTANT_LIAR_MEAN: <NEW_LINE> <INDENT> return numpy.mean(points_sampled_values) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise(NotImplementedError, '{0} is not implemented'.format(params.get('lie_method'))) <NEW_LINE> <DEDENT> <DEDENT> @view_config(route_name=_route_name, renderer='json', request_method='POST') <NEW_LINE> def gp_next_points_constant_liar_view(self): <NEW_LINE> <INDENT> params = self.get_params_from_request() <NEW_LINE> return self.compute_next_points_to_sample_response( params, GP_NEXT_POINTS_CONSTANT_LIAR_OPTIMIZER_METHOD_NAME, self._route_name, self.get_lie_value(params), lie_noise_variance=params.get('lie_noise_variance'), )
Views for gp_next_points_constant_liar endpoints.
62598fa2a17c0f6771d5c09e
class PWrap(Pattern): <NEW_LINE> <INDENT> def __init__(self, pattern, min=40, max=80): <NEW_LINE> <INDENT> self.pattern = pattern <NEW_LINE> self.min = min <NEW_LINE> self.max = max <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> value = next(self.pattern) <NEW_LINE> while value < self.min: <NEW_LINE> <INDENT> value += self.max - self.min <NEW_LINE> <DEDENT> while value >= self.max: <NEW_LINE> <INDENT> value -= self.max - self.min <NEW_LINE> <DEDENT> return value
PWrap: Wrap input note values within <min>, <max>. >>> p = PWrap(PSeries(5, 3), 0, 10) >>> p.nextn(16) [5, 8, 1, 4, 7, 0, 3, 6, 9, 2, 5, 8, 1, 4, 7, 0]
62598fa266673b3332c3022b
class YamlSerialize(AbstractSerializer): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def load(path_to_file): <NEW_LINE> <INDENT> return YamlSerialize .base_load('y-' + path_to_file, yaml.load, '.yaml', 'r') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def save(path_to_file, lst): <NEW_LINE> <INDENT> YamlSerialize .base_save('y-' + path_to_file, lst, yaml.dump, '.yaml', 'w')
Yaml serializer class
62598fa2d53ae8145f9182f0
class CompositeBase(FunctionBase): <NEW_LINE> <INDENT> abstract = True <NEW_LINE> def __call__(self, args, **kwargs): <NEW_LINE> <INDENT> import dynts <NEW_LINE> expression = dynts.parse(self.composite) <NEW_LINE> if args: <NEW_LINE> <INDENT> data = dict((('X{0}'.format(n+1),ts) for n,ts in enumerate(args))) <NEW_LINE> backend = args[0].type <NEW_LINE> return expression.unwind(data, backend, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError
Base class for a timeseries function implementation. The only member function to implement is the ``__call__`` method. .. function:: __call__(args, **kwargs) where *args* is a list of arguments (timeseries or other objects) and *kwargs* is a dictionary of input parameters. For example, the rolling-standard deviation is defined as:: std(expression,window=20)
62598fa2a17c0f6771d5c09f
class Events(object): <NEW_LINE> <INDENT> exposed = True <NEW_LINE> _cp_config = dict(LowDataAdapter._cp_config, **{ 'response.stream': True, 'tools.encode.encoding': 'utf-8', 'tools.salt_token.on': True, 'tools.salt_auth.on': False, 'tools.hypermedia_in.on': False, 'tools.hypermedia_out.on': False, }) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.opts = cherrypy.config['saltopts'] <NEW_LINE> self.auth = salt.auth.LoadAuth(self.opts) <NEW_LINE> <DEDENT> def GET(self, token=None): <NEW_LINE> <INDENT> if token: <NEW_LINE> <INDENT> orig_sesion, _ = cherrypy.session.cache.get(token, ({}, None)) <NEW_LINE> salt_token = orig_sesion.get('token') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> salt_token = cherrypy.session.get('token') <NEW_LINE> <DEDENT> if not salt_token or not self.auth.get_tok(salt_token): <NEW_LINE> <INDENT> raise cherrypy.InternalRedirect('/login') <NEW_LINE> <DEDENT> cherrypy.session.release_lock() <NEW_LINE> cherrypy.response.headers['Content-Type'] = 'text/event-stream' <NEW_LINE> cherrypy.response.headers['Cache-Control'] = 'no-cache' <NEW_LINE> cherrypy.response.headers['Connection'] = 'keep-alive' <NEW_LINE> def listen(): <NEW_LINE> <INDENT> event = salt.utils.event.SaltEvent('master', self.opts['sock_dir']) <NEW_LINE> stream = event.iter_events(full=True) <NEW_LINE> yield u'retry: {0}\n'.format(400) <NEW_LINE> while True: <NEW_LINE> <INDENT> data = stream.next() <NEW_LINE> yield u'tag: {0}\n'.format(data.get('tag', '')) <NEW_LINE> yield u'data: {0}\n\n'.format(json.dumps(data)) <NEW_LINE> <DEDENT> <DEDENT> return listen()
The event bus on the Salt master exposes a large variety of things, notably when executions are started on the master and also when minions ultimately return their results. This URL provides a real-time window into a running Salt infrastructure.
62598fa207f4c71912baf2a8
class TeamMembershipType(bb.Union): <NEW_LINE> <INDENT> _catch_all = None <NEW_LINE> full = None <NEW_LINE> limited = None <NEW_LINE> def is_full(self): <NEW_LINE> <INDENT> return self._tag == 'full' <NEW_LINE> <DEDENT> def is_limited(self): <NEW_LINE> <INDENT> return self._tag == 'limited' <NEW_LINE> <DEDENT> def _process_custom_annotations(self, annotation_type, processor): <NEW_LINE> <INDENT> super(TeamMembershipType, self)._process_custom_annotations(annotation_type, processor) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return 'TeamMembershipType(%r, %r)' % (self._tag, self._value)
This class acts as a tagged union. Only one of the ``is_*`` methods will return true. To get the associated value of a tag (if one exists), use the corresponding ``get_*`` method. :ivar full: User uses a license and has full access to team resources like the shared quota. :ivar limited: User does not have access to the shared quota and team admins have restricted administrative control.
62598fa2009cb60464d0138a
class BaseLobheader(object): <NEW_LINE> <INDENT> BLOB_TYPE = 1 <NEW_LINE> CLOB_TYPE = 2 <NEW_LINE> NCLOB_TYPE = 3 <NEW_LINE> LOB_TYPES = {type_codes.BLOB: BLOB_TYPE, type_codes.CLOB: CLOB_TYPE, type_codes.NCLOB: NCLOB_TYPE} <NEW_LINE> LOB_OPTION_ISNULL = 0x01 <NEW_LINE> LOB_OPTION_DATAINCLUDED = 0x02 <NEW_LINE> LOB_OPTION_LASTDATA = 0x04 <NEW_LINE> OPTIONS_STR = { LOB_OPTION_ISNULL: 'isnull', LOB_OPTION_DATAINCLUDED: 'data_included', LOB_OPTION_LASTDATA: 'last_data' }
Base LobHeader class
62598fa299cbb53fe6830d38
class MySeasonCalendar(Calendar): <NEW_LINE> <INDENT> def __init__(self, date=None, days=7): <NEW_LINE> <INDENT> self.url = 'calendars/my/shows/premieres' <NEW_LINE> super(MySeasonCalendar, self).__init__(date=date, days=days)
Personalized TraktTV TV Show Season Premiere
62598fa24428ac0f6e658390
class ParameterError(Exception): <NEW_LINE> <INDENT> pass
Custom errors for Parameters class
62598fa256b00c62f0fb2715
class RemovedInReviewBot50Warning(BaseRemovedInReviewBotVersionWarning): <NEW_LINE> <INDENT> pass
Deprecations for features removed in Review Bot 5.0. Note that this class will itself be removed in Review Bot 5.0. If you need to check against Review Bot deprecation warnings, please see :py:class:`BaseRemovedInReviewBotVersionWarning`. Alternatively, you can use the alias for this class, :py:data:`RemovedInNextReviewBotVersionWarning`.
62598fa20c0af96317c561e7
class DataFilterValueRange(TypedDict): <NEW_LINE> <INDENT> dataFilter: DataFilter <NEW_LINE> majorDimension: Dimension <NEW_LINE> values: List[List[Any]]
A range of values whose location is specified by a DataFilter.
62598fa22c8b7c6e89bd362b
class Collector: <NEW_LINE> <INDENT> PARSER: t.Optional[parsers.Parser] = None <NEW_LINE> def __init__( self, session_factory: t.Optional[sessionmaker] = None, shutdown: t.Optional[threading.Event] = None, ): <NEW_LINE> <INDENT> self.session_factory: t.Optional[sessionmaker] = session_factory <NEW_LINE> self.shutdown: t.Optional[threading.Event] = shutdown <NEW_LINE> <DEDENT> def _session(self, **kwargs) -> t.ContextManager[Session]: <NEW_LINE> <INDENT> return db.managed_session(self.session_factory, **kwargs) <NEW_LINE> <DEDENT> def collect( self, profile: Profile, investigation: db.Investigation, previous: t.Optional[db.Investigation] = None, ) -> pa.DataFrame: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def configure(self, config: Config) -> Config: <NEW_LINE> <INDENT> return config.parse(self.PARSER) if self.PARSER else config <NEW_LINE> <DEDENT> def _get_first_event( self, profile: db.Profile, **kwargs, ) -> t.Optional[db.Event]: <NEW_LINE> <INDENT> logger.debug("Retrieving first event of profile '%s'", profile.name) <NEW_LINE> backoff = ExponentialBackoff(initialize=True, **kwargs) <NEW_LINE> while not self.shutdown.wait(backoff.timeout): <NEW_LINE> <INDENT> with self._session(expire_on_commit=False) as session: <NEW_LINE> <INDENT> first_event = session.query(db.Event).join( (db.Actor, db.Event.actor), (db.Profile, db.Actor.profile), ).filter( db.Profile.id == profile.id, ).order_by(db.Event.created_at.asc()).first() <NEW_LINE> if first_event: <NEW_LINE> <INDENT> return first_event <NEW_LINE> <DEDENT> logger.info( "First event not found trying again in %.2f seconds", backoff.next(), )
Base class used to collect anomalies to analyze. Subclasses should implement the `collect` method. Parameters ---------- session_factory: Optional[sessionmaker] SQLAlchemy session factory. shutdown: threading.Event Threading event that indicates a shutdown occurred. Attributes ---------- session_factory: Optional[sessionmaker] SQLAlchemy session factory. shutdown: threading.Event Threading event that indicates a shutdown occurred.
62598fa25f7d997b871f9312
class LMTP(SMTP): <NEW_LINE> <INDENT> ehlo_msg = "lhlo" <NEW_LINE> def __init__(self, host='', port=LMTP_PORT, local_hostname=None, source_address=None): <NEW_LINE> <INDENT> SMTP.__init__(self, host, port, local_hostname=local_hostname, source_address=source_address) <NEW_LINE> <DEDENT> def connect(self, host='localhost', port=0, source_address=None): <NEW_LINE> <INDENT> if host[0] != '/': <NEW_LINE> <INDENT> return SMTP.connect(self, host, port, source_address=source_address) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) <NEW_LINE> self.file = None <NEW_LINE> self.sock.connect(host) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> if self.debuglevel > 0: <NEW_LINE> <INDENT> self._print_debug('connect fail:', host) <NEW_LINE> <DEDENT> if self.sock: <NEW_LINE> <INDENT> self.sock.close() <NEW_LINE> <DEDENT> self.sock = None <NEW_LINE> raise <NEW_LINE> <DEDENT> (code, msg) = self.getreply() <NEW_LINE> if self.debuglevel > 0: <NEW_LINE> <INDENT> self._print_debug('connect:', msg) <NEW_LINE> <DEDENT> return (code, msg)
LMTP - Local Mail Transfer Protocol The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It's common to use Unix sockets for LMTP, so our connect() method must support that as well as a regular host:port server. local_hostname and source_address have the same meaning as they do in the SMTP class. To specify a Unix socket, you must use an absolute path as the host, starting with a '/'. Authentication is supported, using the regular SMTP mechanism. When using a Unix socket, LMTP generally don't support or require any authentication, but your mileage might vary.
62598fa2e64d504609df92eb
class AnnealedSplitMergeKernel(AbstractSplitMergKernel): <NEW_LINE> <INDENT> def copy_particle(self, particle): <NEW_LINE> <INDENT> return AnnealedSplitMergeParticle( particle.block_idx, tuple([x.copy() for x in particle.block_params]), particle.generation, particle.log_annealing_correction, particle.log_w, particle.parent_particle ) <NEW_LINE> <DEDENT> def get_log_q(self, data_point, parent_particle): <NEW_LINE> <INDENT> if parent_particle is None: <NEW_LINE> <INDENT> block_params = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> block_params = parent_particle.block_params <NEW_LINE> <DEDENT> log_q = {} <NEW_LINE> if self.can_add_block(parent_particle): <NEW_LINE> <INDENT> for block_idx, _ in enumerate(block_params): <NEW_LINE> <INDENT> log_q[block_idx] = 0 <NEW_LINE> <DEDENT> block_idx = len(block_params) <NEW_LINE> log_q[block_idx] = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for block_idx, params in enumerate(block_params): <NEW_LINE> <INDENT> log_q[block_idx] = parent_particle.log_annealing_correction <NEW_LINE> log_q[block_idx] += self.partition_prior.log_tau_2_diff(params.N) <NEW_LINE> log_q[block_idx] += self.dist.log_predictive_likelihood(data_point, params) <NEW_LINE> <DEDENT> <DEDENT> return log_q <NEW_LINE> <DEDENT> def _create_particle(self, block_idx, block_params, data_point, log_q, log_q_norm, parent_particle): <NEW_LINE> <INDENT> generation = self._get_generation(parent_particle) <NEW_LINE> if generation < self.num_anchors: <NEW_LINE> <INDENT> log_annealing_correction = None <NEW_LINE> <DEDENT> elif generation == self.num_anchors: <NEW_LINE> <INDENT> n = self.num_generations <NEW_LINE> s = self.num_anchors <NEW_LINE> if n == s: <NEW_LINE> <INDENT> log_annealing_correction = None <NEW_LINE> log_q_norm = self.log_target_density(block_params) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log_annealing_correction = (1 / (n - s)) * self.log_target_density(block_params) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> log_annealing_correction = parent_particle.log_annealing_correction <NEW_LINE> <DEDENT> return AnnealedSplitMergeParticle( block_idx=block_idx, block_params=tuple(block_params), generation=generation, log_annealing_correction=log_annealing_correction, log_w=log_q_norm, parent_particle=parent_particle )
Propose next state uniformly until all anchors are added then use fully adapted proposal.
62598fa28a43f66fc4bf1fe1
class Command(RunserverCommand): <NEW_LINE> <INDENT> help = 'Starts a lightweight Web server for development with LiveReload.' <NEW_LINE> def add_arguments(self, parser): <NEW_LINE> <INDENT> super(Command, self).add_arguments(parser) <NEW_LINE> parser.add_argument('--nolivereload', action='store_false', dest='use_livereload', default=True, help='Tells Django to NOT use LiveReload.') <NEW_LINE> parser.add_argument('--livereload-port', action='store', dest='livereload_port', default='35729', help='Port where LiveReload listen.') <NEW_LINE> <DEDENT> def message(self, message, verbosity=1, style=None): <NEW_LINE> <INDENT> if verbosity: <NEW_LINE> <INDENT> if style: <NEW_LINE> <INDENT> message = style(message) <NEW_LINE> <DEDENT> self.stdout.write(message) <NEW_LINE> <DEDENT> <DEDENT> def livereload_request(self, **options): <NEW_LINE> <INDENT> style = color_style() <NEW_LINE> verbosity = int(options['verbosity']) <NEW_LINE> host = 'localhost:%s' % options['livereload_port'] <NEW_LINE> try: <NEW_LINE> <INDENT> urlopen('http://%s/changed?files=.' % host) <NEW_LINE> self.message('LiveReload request emitted.\n', verbosity, style.HTTP_INFO) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def get_handler(self, *args, **options): <NEW_LINE> <INDENT> handler = super(Command, self).get_handler(*args, **options) <NEW_LINE> if options['use_livereload']: <NEW_LINE> <INDENT> self.livereload_request(**options) <NEW_LINE> <DEDENT> return handler
Command for running the development server with LiveReload.
62598fa22ae34c7f260aaf45
class CourseTeamSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> id = serializers.CharField(source='team_id', read_only=True) <NEW_LINE> membership = UserMembershipSerializer(many=True, read_only=True) <NEW_LINE> class Meta(object): <NEW_LINE> <INDENT> model = CourseTeam <NEW_LINE> fields = ( "id", "discussion_topic_id", "name", "is_active", "course_id", "topic_id", "date_created", "description", "country", "language", "last_activity_at", "membership", ) <NEW_LINE> read_only_fields = ("course_id", "date_created", "discussion_topic_id", "last_activity_at")
Serializes a CourseTeam with membership information.
62598fa23617ad0b5ee05fb7
class Train: <NEW_LINE> <INDENT> def __init__(self, id, route, name, period, lateness=None): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.route = route <NEW_LINE> self.name = name <NEW_LINE> self.period = period <NEW_LINE> if lateness is None: <NEW_LINE> <INDENT> self.lateness = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.lateness=lateness
id route name lateness []
62598fa2f7d966606f747e48
class DataCitePreconditionError(DataCiteRequestError): <NEW_LINE> <INDENT> pass
Metadata must be uploaded first.
62598fa257b8e32f5250804f