code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class LogLevel: <NEW_LINE> <INDENT> FATAL = 'FATAL' <NEW_LINE> ERROR = 'ERROR' <NEW_LINE> WARN = 'WARN' <NEW_LINE> INFO = 'INFO' <NEW_LINE> DEBUG = 'DEBUG' <NEW_LINE> levels = [FATAL, ERROR, WARN, INFO, DEBUG] <NEW_LINE> @staticmethod <NEW_LINE> def normalize(level): <NEW_LINE> <INDENT> if level in LogLevel.levels: <NEW_LINE> <INDENT> return level <NEW_LINE> <DEDENT> for l in LogLevel.levels: <NEW_LINE> <INDENT> if l[0] == level: <NEW_LINE> <INDENT> return l <NEW_LINE> <DEDENT> <DEDENT> raise ValueError('invalid log level')
Represents log levels.
62598fae3539df3088ecc2a0
class TestReviewDocs(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> print('\n\n.................................') <NEW_LINE> print('..... Testing Documentation .....') <NEW_LINE> print('....... Review Class .......') <NEW_LINE> print('.................................\n\n') <NEW_LINE> <DEDENT> def test_doc_file(self): <NEW_LINE> <INDENT> expected = '\nReview Class from Models Module\n' <NEW_LINE> actual = models.review.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_class(self): <NEW_LINE> <INDENT> expected = 'Review class handles all application reviews' <NEW_LINE> actual = Review.__doc__ <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_doc_init(self): <NEW_LINE> <INDENT> expected = 'instantiates a new review' <NEW_LINE> actual = Review.__init__.__doc__ <NEW_LINE> self.assertEqual(expected, actual)
Class for testing BaseModel docs
62598fae7c178a314d78d48b
class ofp_packet_in: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.header = ofp_header() <NEW_LINE> self.header.type = OFPT_PACKET_IN <NEW_LINE> self.buffer_id = 0 <NEW_LINE> self.total_len = 0 <NEW_LINE> self.in_port = 0 <NEW_LINE> self.reason = 0 <NEW_LINE> self.pad = 0 <NEW_LINE> self.data= [] <NEW_LINE> <DEDENT> def __assert(self): <NEW_LINE> <INDENT> if(not isinstance(self.header, ofp_header)): <NEW_LINE> <INDENT> return (False, "self.header is not class ofp_header as expected.") <NEW_LINE> <DEDENT> return (True, None) <NEW_LINE> <DEDENT> def pack(self, assertstruct=True): <NEW_LINE> <INDENT> if(assertstruct): <NEW_LINE> <INDENT> if(not self.__assert()[0]): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> packed = "" <NEW_LINE> packed += self.header.pack() <NEW_LINE> packed += struct.pack("!LHHBB", self.buffer_id, self.total_len, self.in_port, self.reason, self.pad) <NEW_LINE> for i in self.data: <NEW_LINE> <INDENT> packed += struct.pack("!B",i) <NEW_LINE> <DEDENT> return packed <NEW_LINE> <DEDENT> def unpack(self, binaryString): <NEW_LINE> <INDENT> if (len(binaryString) < 18): <NEW_LINE> <INDENT> return binaryString <NEW_LINE> <DEDENT> self.header.unpack(binaryString[0:]) <NEW_LINE> fmt = '!LHHBB' <NEW_LINE> start = 8 <NEW_LINE> end = start + struct.calcsize(fmt) <NEW_LINE> (self.buffer_id, self.total_len, self.in_port, self.reason, self.pad) = struct.unpack(fmt, binaryString[start:end]) <NEW_LINE> return binaryString[18:] <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> l = 18 <NEW_LINE> l += len(self.data)*1 <NEW_LINE> return l <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if type(self) != type(other): return False <NEW_LINE> if self.header != other.header: return False <NEW_LINE> if self.buffer_id != other.buffer_id: return False <NEW_LINE> if self.total_len != other.total_len: return False <NEW_LINE> if self.in_port != other.in_port: return False <NEW_LINE> if self.reason != other.reason: return False <NEW_LINE> if self.pad != other.pad: return False <NEW_LINE> if self.data != other.data: return False <NEW_LINE> return True <NEW_LINE> <DEDENT> def __ne__(self, other): return not self.__eq__(other) <NEW_LINE> def show(self, prefix=''): <NEW_LINE> <INDENT> outstr = '' <NEW_LINE> outstr += prefix + 'header: \n' <NEW_LINE> outstr += self.header.show(prefix + ' ') <NEW_LINE> outstr += prefix + 'buffer_id: ' + str(self.buffer_id) + '\n' <NEW_LINE> outstr += prefix + 'total_len: ' + str(self.total_len) + '\n' <NEW_LINE> outstr += prefix + 'in_port: ' + str(self.in_port) + '\n' <NEW_LINE> outstr += prefix + 'reason: ' + str(self.reason) + '\n' <NEW_LINE> outstr += prefix + 'data: ' + str(self.data) + '\n' <NEW_LINE> return outstr
Automatically generated Python class for ofp_packet_in Date 2011-06-13 Created by pylibopenflow.of.pythonize.pythonizer
62598fae7047854f4633f3c8
class HeaderRule(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> header = models.ForeignKey(HttpHeader) <NEW_LINE> regex = models.CharField(max_length=255) <NEW_LINE> domain = models.CharField(max_length=50, blank=True) <NEW_LINE> extension_list = models.CharField(max_length=50, default="html") <NEW_LINE> context_var = models.CharField(max_length=50, blank=True) <NEW_LINE> order = models.PositiveSmallIntegerField() <NEW_LINE> enabled = models.BooleanField('Enable This Rule') <NEW_LINE> admin_override = models.BooleanField('Enable This Rule for Admins for Testing') <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name
A rule that changes the file extension and/or sets a context variable based on an HTTP header.
62598fae5fdd1c0f98e5df7b
class Article(models.Model): <NEW_LINE> <INDENT> nid = models.AutoField(primary_key=True) <NEW_LINE> title = models.CharField(verbose_name="文章标题",max_length=50) <NEW_LINE> desc = models.CharField(verbose_name="文章描述",max_length=255) <NEW_LINE> create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True) <NEW_LINE> content = models.TextField() <NEW_LINE> comment_count = models.IntegerField(verbose_name="评论数",default=0) <NEW_LINE> up_count = models.IntegerField(verbose_name="点赞数",default=0) <NEW_LINE> down_count = models.IntegerField(verbose_name="踩灭数",default=0) <NEW_LINE> user = models.ForeignKey(verbose_name='作者', to='UserInfo', to_field='nid', on_delete=models.CASCADE) <NEW_LINE> category = models.ForeignKey(to='Category', to_field='nid', null=True, on_delete=models.CASCADE) <NEW_LINE> tags = models.ManyToManyField( to="Tag", through='Article2Tag', ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title
文章
62598fae2c8b7c6e89bd37b4
class uploadBlobChunk_args: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'session', None, None, ), (2, TType.STRING, 'chunk', None, None, ), ) <NEW_LINE> def __init__(self, session=None, chunk=None,): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> self.chunk = chunk <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.session = iprot.readString().decode('utf-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 2: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.chunk = iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('uploadBlobChunk_args') <NEW_LINE> if self.session is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('session', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.session.encode('utf-8')) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.chunk is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('chunk', TType.STRING, 2) <NEW_LINE> oprot.writeString(self.chunk) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.session) <NEW_LINE> value = (value * 31) ^ hash(self.chunk) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - session - chunk
62598fae26068e7796d4c943
class RelAxis2 (MultiEvent): <NEW_LINE> <INDENT> name = 'relaxis2' <NEW_LINE> child = RelAxis <NEW_LINE> multiple = 2 <NEW_LINE> def __init__ (self, *inps): <NEW_LINE> <INDENT> MultiEvent.__init__(self, inps) <NEW_LINE> <DEDENT> def _parse_input (self, i): <NEW_LINE> <INDENT> if isinstance(i, inputs.Input): <NEW_LINE> <INDENT> i = (i,) <NEW_LINE> <DEDENT> if isinstance(i[0], inputs.Input): <NEW_LINE> <INDENT> return MultiEvent._parse_input(self, i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> scale = i[0] <NEW_LINE> i, ecs, ics = MultiEvent._parse_input(self, i[1:]) <NEW_LINE> return ((scale,) + i, ecs, ics) <NEW_LINE> <DEDENT> <DEDENT> def gen_cb_args (self, changed): <NEW_LINE> <INDENT> rel = [0] * self.multiple <NEW_LINE> for evt_i, this_rel in MultiEvent.gen_cb_args(self, changed): <NEW_LINE> <INDENT> rel[evt_i] += this_rel <NEW_LINE> <DEDENT> yield (rel,)
A double :class:`RelAxis`. Callbacks are called every frame with a list of positions for each of the two relative axes.
62598faefff4ab517ebcd7d4
class JSONExporter(BaseExporter): <NEW_LINE> <INDENT> def __init__(self,*args): <NEW_LINE> <INDENT> super(JSONExporter,self).__init__(*args) <NEW_LINE> <DEDENT> def dump(self,out_file): <NEW_LINE> <INDENT> json.dump(self.repr_as_dict(self.pathname),out_file)
Export Directory Structure as JSON
62598fae1b99ca400228f527
class Problem18(Problem): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.rows = list( map(lambda x: list(map(lambda y: int(y), x.split(' '))), [ "75", "95 64", "17 47 82", "18 35 87 10", "20 04 82 47 65", "19 01 23 75 03 34", "88 02 77 73 07 63 67", "99 65 04 28 06 16 70 92", "41 41 26 56 83 40 80 70 33", "41 48 72 33 47 32 37 16 94 29", "53 71 44 65 25 43 91 52 97 51 14", "70 11 33 28 77 73 17 78 39 68 17 57", "91 71 52 38 17 14 91 43 58 50 27 29 48", "63 66 04 68 89 53 67 30 73 16 69 87 40 31", "04 62 98 27 23 09 70 98 73 93 38 53 60 04 23" ])) <NEW_LINE> <DEDENT> def solve(self): <NEW_LINE> <INDENT> e = self.rows[::-1] <NEW_LINE> for i in range(1, len(e)): <NEW_LINE> <INDENT> for j in range(0, len(e[i])): <NEW_LINE> <INDENT> e[i][j] += max([e[i - 1][j], e[i - 1][j + 1]]) <NEW_LINE> <DEDENT> <DEDENT> return self.rows[0][0]
Maximum path sum I Problem 18 By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)
62598fae3346ee7daa33763f
class ScanScanFile(ScanScan): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> super(ScanScanFile, self).__init__() <NEW_LINE> self.filename = filename <NEW_LINE> self.load(filename) <NEW_LINE> <DEDENT> def load(self, filename): <NEW_LINE> <INDENT> with open(filename, "r") as content_file: <NEW_LINE> <INDENT> self.content = content_file.read() <NEW_LINE> <DEDENT> <DEDENT> def apply(self, content_lambda, die_on_not_applied=False): <NEW_LINE> <INDENT> content = content_lambda(self.content) <NEW_LINE> if content is not None: <NEW_LINE> <INDENT> self.content = content <NEW_LINE> <DEDENT> elif die_on_not_applied: <NEW_LINE> <INDENT> raise Exception("Not applied.") <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def contains_xml_comment(self, comment): <NEW_LINE> <INDENT> return re.search(r"\<!--\s*%s\s*--\>" % comment, self.content) is not None <NEW_LINE> <DEDENT> def write(self): <NEW_LINE> <INDENT> with open(self.filename, "w") as content_file: <NEW_LINE> <INDENT> content_file.write(self.content) <NEW_LINE> <DEDENT> return self
Successively apply content transformations to a file.
62598fae66673b3332c303bb
class TextAreaField(StringField): <NEW_LINE> <INDENT> widget = wg.TextArea()
This field represents an HTML ``<textarea>`` and can be used to take multi-line input.
62598fae8da39b475be031d4
class EntryDelegate: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.callback = None <NEW_LINE> <DEDENT> def setCallback(self, callback): <NEW_LINE> <INDENT> self.callback = callback <NEW_LINE> <DEDENT> def onEnter(self, player): <NEW_LINE> <INDENT> player.stopMovingUp() <NEW_LINE> player.stopMovingDown() <NEW_LINE> player.stopMovingLeft() <NEW_LINE> player.stopMovingRight() <NEW_LINE> self.callback(["Entered a tile"])
Represents an action to perform when entering a Tile
62598fae236d856c2adc9435
@register_object("relay.ext.ethos-u.CompilationArtifact") <NEW_LINE> class CompilationArtifact(Object): <NEW_LINE> <INDENT> def __init__( self, function_name: str, command_stream: str, encoded_constants: str, base_addresses: List[BaseAddress], ): <NEW_LINE> <INDENT> self.__init_handle_by_constructor__( _ffi_api.CompilationArtifact, function_name, command_stream, encoded_constants, base_addresses, )
This is a structure to hold binary artifacts for the microNPU.
62598fae99cbb53fe6830ec7
class aws_logger: <NEW_LINE> <INDENT> def __init__(self, aws_operations=None): <NEW_LINE> <INDENT> if aws_operations is not None: <NEW_LINE> <INDENT> self.aws_operations = aws_operations <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.aws_operations = aws_storage_operations() <NEW_LINE> <DEDENT> <DEDENT> def log(self, file_path, log_message): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> date = now.date() <NEW_LINE> current_time = now.strftime('%H:%M:%S') <NEW_LINE> message = str(date) + '/' + str(current_time) + '\t\t' + log_message + '\n' <NEW_LINE> self.aws_operations.append_file(file_path, message) <NEW_LINE> return None <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise e
This class shall be used for handling all the logging operations to the AWS storage. Written By: Prafful Agrawal Version: 1.0 Revisions: None
62598fae091ae35668704c0e
class SupportArtifactTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_support_artifact(self): <NEW_LINE> <INDENT> support_artifact_obj = SupportArtifact() <NEW_LINE> self.assertNotEqual(support_artifact_obj, None)
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fae30bbd72246469970
class Individual: <NEW_LINE> <INDENT> def __init__(self, phenome=None, objective_values=None): <NEW_LINE> <INDENT> self.phenome = phenome <NEW_LINE> self.objective_values = objective_values
A data structure to store objective values together with the solution. Some methods of the problem classes expect objects with the two attributes `phenome` and `objective_values`. The exact type of these objects is irrelevant, but this class would be the obvious fit. The term 'phenome' stems from biology and means the whole set of phenotypic entities, in other words the form of appearance, of an animate being. So, it matches quite well as description of what is evaluated by the objective function.
62598fae9c8ee82313040169
class WorkloadDeploymentRequest(object): <NEW_LINE> <INDENT> def __init__(self, node_name=None): <NEW_LINE> <INDENT> self.swagger_types = { 'node_name': 'str' } <NEW_LINE> self.attribute_map = { 'node_name': 'nodeName' } <NEW_LINE> self._node_name = node_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def node_name(self): <NEW_LINE> <INDENT> return self._node_name <NEW_LINE> <DEDENT> @node_name.setter <NEW_LINE> def node_name(self, node_name): <NEW_LINE> <INDENT> self._node_name = node_name <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, WorkloadDeploymentRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fae7b25080760ed749f
class Frame(wx.Frame, containers.Container): <NEW_LINE> <INDENT> __events__ = { 'Close': wx.EVT_CLOSE, 'Iconize': wx.EVT_ICONIZE, 'Show': wx.EVT_SHOW, 'Activate': wx.EVT_ACTIVATE, 'Idle': wx.EVT_IDLE, 'MenuHighlight': wx.EVT_MENU_HIGHLIGHT, 'MenuOpen': wx.EVT_MENU_OPEN, 'MenuClose': wx.EVT_MENU_CLOSE, } <NEW_LINE> def __init__(self, parent=None, title="", direction="H", size=None, **kwargs): <NEW_LINE> <INDENT> style = 0 <NEW_LINE> style |= self._params(kwargs) <NEW_LINE> style |= styles.window(kwargs) <NEW_LINE> wx.Frame.__init__(self, parent, wx.NewId(), title, size=size or (-1,-1), style=style) <NEW_LINE> self.BindEvents() <NEW_LINE> self._create_sizer(direction) <NEW_LINE> self.SetDefaultFont() <NEW_LINE> styles.properties(self, kwargs) <NEW_LINE> self.Body() <NEW_LINE> <DEDENT> def SetIcon(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, str) or isinstance(obj, unicode): <NEW_LINE> <INDENT> obj = wx.Icon(obj, wx.BITMAP_TYPE_ICO) <NEW_LINE> <DEDENT> wx.Frame.SetIcon(self, obj) <NEW_LINE> <DEDENT> def _params(self, kwargs): <NEW_LINE> <INDENT> flags = wx.DEFAULT_FRAME_STYLE <NEW_LINE> flags &= ~(styles.styleboolexclude('resize', wx.RESIZE_BORDER, kwargs, reverse=1)) <NEW_LINE> flags &= ~(styles.styleboolexclude('close_box', wx.CLOSE_BOX, kwargs, reverse=1)) <NEW_LINE> flags &= ~(styles.styleboolexclude('minimize_box', wx.MINIMIZE_BOX, kwargs, reverse=1)) <NEW_LINE> flags &= ~(styles.styleboolexclude('maximize_box', wx.MAXIMIZE_BOX, kwargs, reverse=1)) <NEW_LINE> flags |= styles.stylebool('shaped', wx.FRAME_SHAPED, kwargs) <NEW_LINE> flags |= styles.stylebool('stayontop', wx.STAY_ON_TOP, kwargs) <NEW_LINE> flags |= styles.stylebool('stay_on_top', wx.STAY_ON_TOP, kwargs) <NEW_LINE> return flags
Top-level frame (window) with built-in sizer.
62598fae8e7ae83300ee9092
class ElasticsearchConnectionManager(object): <NEW_LINE> <INDENT> def __init__(self, fqdn): <NEW_LINE> <INDENT> self.fqdn = fqdn <NEW_LINE> self.connection = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> _es_host = {"host": self.fqdn, "port": 9200} <NEW_LINE> self.connection = Elasticsearch(hosts=[_es_host], use_ssl=False, verify_certs=False, timeout=600) <NEW_LINE> return self.connection <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, exc_traceback): <NEW_LINE> <INDENT> del(self) <NEW_LINE> <DEDENT> def connectToElasticsearch( self, fqdn, port): <NEW_LINE> <INDENT> connection_string = 'https://' + fqdn + ':' + str(port) <NEW_LINE> self.connection = Elasticsearch([connection_string], use_ssl=False, verify_certs=False, timeout=600) <NEW_LINE> return self.connection
This is only a context manager for elasticsearch connection
62598faea05bb46b3848a85b
class TraceFunctionEvent(TraceEvent): <NEW_LINE> <INDENT> function = Any() <NEW_LINE> module_name = Unicode() <NEW_LINE> qual_name = Unicode() <NEW_LINE> atomic = Bool() <NEW_LINE> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.qual_name.split('.')[-1] <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_name(self): <NEW_LINE> <INDENT> return self.module_name + '.' + self.qual_name
Event pertaining to a function call.
62598fae66656f66f7d5a3df
class TestConceptsApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = swagger_client.apis.concepts_api.ConceptsApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_concept_details(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_get_concepts(self): <NEW_LINE> <INDENT> pass
ConceptsApi unit test stubs
62598faef548e778e596b594
class AlkoholhaltigeDrinks(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=55, null=False, blank=False) <NEW_LINE> centiliter = models.DecimalField(max_length=8, max_digits=8, decimal_places=2, default="") <NEW_LINE> beschreibung = models.TextField(blank=True, default='') <NEW_LINE> zusatzstoffe = models.CharField(max_length=55, null=True, blank=True, default="") <NEW_LINE> preis = models.DecimalField(max_length=8, max_digits=8, decimal_places=2, default="") <NEW_LINE> kundeId = models.ForeignKey(Kunde, null=True, on_delete=models.SET_NULL) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f'{self.name}'
Eine Klasse zur Repräsentation eines alkoholfreien Drinks ... Attributes ---------- name : charfield Name des alkoholfreien Drinks liter : decimalfield Füllmenge mit 2 Nachkommastellen in centiliter beschreibung : textfield Beschreibung des alkoholhaltigen Drinks zusatzstoffe : charfield Enthaltene Zusatzstoffe des alkoholhaltigen Drinks preis : decimalfield Preis mit 2 Nachkommastellen kundeId : foreignkey Fremdschlüssel des Kunden Methods ------- __str__(): Gibt den Namen des alkoholhaltigen Drinks aus
62598fae4428ac0f6e658515
class WriteConcern(object): <NEW_LINE> <INDENT> __slots__ = ("__document", "__acknowledged") <NEW_LINE> def __init__(self, w=None, wtimeout=None, j=None, fsync=None): <NEW_LINE> <INDENT> self.__document = {} <NEW_LINE> self.__acknowledged = True <NEW_LINE> if wtimeout is not None: <NEW_LINE> <INDENT> if not isinstance(wtimeout, integer_types): <NEW_LINE> <INDENT> raise TypeError("wtimeout must be an integer") <NEW_LINE> <DEDENT> self.__document["wtimeout"] = wtimeout <NEW_LINE> <DEDENT> if j is not None: <NEW_LINE> <INDENT> if not isinstance(j, bool): <NEW_LINE> <INDENT> raise TypeError("j must be True or False") <NEW_LINE> <DEDENT> self.__document["j"] = j <NEW_LINE> <DEDENT> if fsync is not None: <NEW_LINE> <INDENT> if not isinstance(fsync, bool): <NEW_LINE> <INDENT> raise TypeError("fsync must be True or False") <NEW_LINE> <DEDENT> if j and fsync: <NEW_LINE> <INDENT> raise ConfigurationError("Can't set both j " "and fsync at the same time") <NEW_LINE> <DEDENT> self.__document["fsync"] = fsync <NEW_LINE> <DEDENT> if self.__document and w == 0: <NEW_LINE> <INDENT> raise ConfigurationError("Can not use w value " "of 0 with other options") <NEW_LINE> <DEDENT> if w is not None: <NEW_LINE> <INDENT> if isinstance(w, integer_types): <NEW_LINE> <INDENT> self.__acknowledged = w > 0 <NEW_LINE> <DEDENT> elif not isinstance(w, string_type): <NEW_LINE> <INDENT> raise TypeError("w must be an integer or string") <NEW_LINE> <DEDENT> self.__document["w"] = w <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def document(self): <NEW_LINE> <INDENT> return self.__document.copy() <NEW_LINE> <DEDENT> @property <NEW_LINE> def acknowledged(self): <NEW_LINE> <INDENT> return self.__acknowledged <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ("WriteConcern(%s)" % ( ", ".join("%s=%s" % kvt for kvt in self.document.items()),)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.document == other.document <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return self.document != other.document
WriteConcern :Parameters: - `w`: (integer or string) Used with replication, write operations will block until they have been replicated to the specified number or tagged set of servers. `w=<integer>` always includes the replica set primary (e.g. w=3 means write to the primary and wait until replicated to **two** secondaries). **w=0 disables acknowledgement of write operations and can not be used with other write concern options.** - `wtimeout`: (integer) Used in conjunction with `w`. Specify a value in milliseconds to control how long to wait for write propagation to complete. If replication does not complete in the given timeframe, a timeout exception is raised. - `j`: If ``True`` block until write operations have been committed to the journal. Cannot be used in combination with `fsync`. Prior to MongoDB 2.6 this option was ignored if the server was running without journaling. Starting with MongoDB 2.6 write operations will fail with an exception if this option is used when the server is running without journaling. - `fsync`: If ``True`` and the server is running without journaling, blocks until the server has synced all data files to disk. If the server is running with journaling, this acts the same as the `j` option, blocking until write operations have been committed to the journal. Cannot be used in combination with `j`.
62598fae99cbb53fe6830ec8
class WaitDistanceTimeout(AutoTestTimeoutException): <NEW_LINE> <INDENT> pass
Thrown when fails to attain distance
62598fae498bea3a75a57b0e
@skipUnless(issubclass(JOB_RUNNER_CLASS, LocalJobRunner), 'skip if local runner is not used') <NEW_LINE> class LocalJobRunnerTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(LocalJobRunnerTest, self).setUp() <NEW_LINE> self._job = CommonJob.objects.create() <NEW_LINE> self._runner = LocalJobRunner(self._job) <NEW_LINE> <DEDENT> def testShouldMakeValidMRCommand(self): <NEW_LINE> <INDENT> self.assertTrue(self._runner.create_hadoop_command() .startswith(HADOOP_JOB_CMD)) <NEW_LINE> <DEDENT> def testShouldRunJobWithFailedExitCode(self): <NEW_LINE> <INDENT> self.assertEquals(self._runner.run_job(), 0)
Test Map-Reduce runner.
62598fae16aa5153ce4004f2
class SaAutoCamelSchema(SQLAlchemyAutoSchema): <NEW_LINE> <INDENT> def on_bind_field(self, field_name, field_obj): <NEW_LINE> <INDENT> field_obj.data_key = camelcase(field_obj.data_key or field_name)
For marshmallow schemas that use camelCase for its external representation and snake_case for its internal representation.
62598fae2c8b7c6e89bd37b5
class CardPriorityList(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = CardPriority.objects.all() <NEW_LINE> serializer_class = CardPrioritySerializer
List all cards priority.
62598fae7b180e01f3e49048
class MonoGenericInstPrinter: <NEW_LINE> <INDENT> def __init__(self, val): <NEW_LINE> <INDENT> self.val = val <NEW_LINE> <DEDENT> def to_string(self): <NEW_LINE> <INDENT> if int(self.val.cast (gdb.lookup_type ("guint64"))) == 0: <NEW_LINE> <INDENT> return "0x0" <NEW_LINE> <DEDENT> inst = self.val.dereference () <NEW_LINE> inst_len = inst ["type_argc"] <NEW_LINE> inst_args = inst ["type_argv"] <NEW_LINE> inst_str = "" <NEW_LINE> for i in range(0, inst_len): <NEW_LINE> <INDENT> type_printer = MonoTypePrinter (inst_args [i]) <NEW_LINE> if i > 0: <NEW_LINE> <INDENT> inst_str = inst_str + ", " <NEW_LINE> <DEDENT> inst_str = inst_str + type_printer.to_string () <NEW_LINE> <DEDENT> return inst_str
Print a MonoGenericInst structure
62598fae7c178a314d78d48d
class search_plan(LoginRequiredMixin,View): <NEW_LINE> <INDENT> def get(self,requests): <NEW_LINE> <INDENT> plan_name=requests.GET.get("plan_name") <NEW_LINE> user=requests.user <NEW_LINE> if user.is_superuser: <NEW_LINE> <INDENT> plan_objs=Plan.objects.filter(plant_name=plan_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> plan_objs = Plan.objects.filter(plant_name=plan_name,project__user__user_id=user.user_id) <NEW_LINE> <DEDENT> content={ "plan_objs":plan_objs, "user_obj": user } <NEW_LINE> return render(requests,'apitest/plant_index.html',content)
搜索测试计划试图
62598fae4e4d562566372416
class TestCreateZipUnit: <NEW_LINE> <INDENT> def test__create_zip_defaults(self, two_iterables): <NEW_LINE> <INDENT> zipped = _create_zip(*two_iterables) <NEW_LINE> assert isinstance(zipped, zip) <NEW_LINE> <DEDENT> def test__create_zip_type_longest_false(self, two_iterables): <NEW_LINE> <INDENT> zipped = _create_zip(*two_iterables, type_longest=False) <NEW_LINE> assert isinstance(zipped, zip) <NEW_LINE> <DEDENT> def test__create_zip_type_longest_true(self, two_iterables): <NEW_LINE> <INDENT> zipped = _create_zip(*two_iterables, type_longest=True) <NEW_LINE> assert isinstance(zipped, zip_longest) <NEW_LINE> <DEDENT> def test__create_zip_default_fillvalue_none(self): <NEW_LINE> <INDENT> iterables = (("A", "B", "C"), (1, 2)) <NEW_LINE> zipped = _create_zip(*iterables, type_longest=True) <NEW_LINE> for z in zipped: <NEW_LINE> <INDENT> pairs = z <NEW_LINE> <DEDENT> assert pairs[-1] is None <NEW_LINE> <DEDENT> def test__create_zip_custom_fillvalue(self): <NEW_LINE> <INDENT> iterables = (("A", "B", "C"), (1, 2)) <NEW_LINE> zipped = _create_zip(*iterables, fillvalue=99, type_longest=True) <NEW_LINE> for z in zipped: <NEW_LINE> <INDENT> pairs = z <NEW_LINE> <DEDENT> assert pairs[-1] == 99
Collection for `namedzip.namedzip._create_zip`.
62598faed486a94d0ba2bfbf
class Scoreboard(): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, stats): <NEW_LINE> <INDENT> self.screen = screen <NEW_LINE> self.screen_rect = screen.get_rect() <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.stats = stats <NEW_LINE> self.text_color = (30, 30, 30) <NEW_LINE> self.font = pygame.font.SysFont(None, 48) <NEW_LINE> self.prep_score() <NEW_LINE> self.prep_score() <NEW_LINE> self.prep_high_score() <NEW_LINE> self.prep_level() <NEW_LINE> self.prep_ships() <NEW_LINE> <DEDENT> def prep_score(self): <NEW_LINE> <INDENT> rounded_score = round(self.stats.score, -1) <NEW_LINE> score_str = "{:,}".format(rounded_score) <NEW_LINE> self.score_image = self.font.render(score_str, True, self.text_color, self.ai_settings.bg_color) <NEW_LINE> self.score_rect = self.score_image.get_rect() <NEW_LINE> self.score_rect.right = self.screen_rect.right - 20 <NEW_LINE> self.score_rect.top = 20 <NEW_LINE> <DEDENT> def prep_high_score(self): <NEW_LINE> <INDENT> high_score = round(self.stats.high_score, -1) <NEW_LINE> high_score_str = "{:,}".format(high_score) <NEW_LINE> self.high_score_image = self.font.render(high_score_str, True, self.text_color, self.ai_settings.bg_color) <NEW_LINE> self.high_score_rect = self.high_score_image.get_rect() <NEW_LINE> self.high_score_rect.centerx = self.screen_rect.centerx <NEW_LINE> self.high_score_rect.top = self.score_rect.top <NEW_LINE> <DEDENT> def prep_level(self): <NEW_LINE> <INDENT> self.level_image = self.font.render(str(self.stats.level), True, self.text_color, self.ai_settings.bg_color) <NEW_LINE> self.level_rect = self.level_image.get_rect() <NEW_LINE> self.level_rect.right = self.score_rect.right <NEW_LINE> self.level_rect.top = self.score_rect.bottom + 10 <NEW_LINE> <DEDENT> def prep_ships(self): <NEW_LINE> <INDENT> self.ships = Group() <NEW_LINE> for ship_number in range(self.stats.ships_left): <NEW_LINE> <INDENT> ship = Ship(self.ai_settings, self.screen) <NEW_LINE> ship.rect.x = 10 + ship_number * ship.rect.width <NEW_LINE> ship.rect.y = 10 <NEW_LINE> self.ships.add(ship) <NEW_LINE> <DEDENT> <DEDENT> def show_score(self): <NEW_LINE> <INDENT> self.screen.blit(self.score_image, self.score_rect) <NEW_LINE> self.screen.blit(self.high_score_image, self.high_score_rect) <NEW_LINE> self.screen.blit(self.level_image, self.level_rect) <NEW_LINE> self.ships.draw(self.screen)
显示得分信息的类
62598faebe8e80087fbbf054
class Device(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.connected = False <NEW_LINE> <DEDENT> def wait_for_connection(self, timeout): <NEW_LINE> <INDENT> total_time = 0 <NEW_LINE> while not self.connected and total_time < timeout: <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> total_time += 1 <NEW_LINE> <DEDENT> if not self.connected: <NEW_LINE> <INDENT> raise RuntimeError('Could not connect to MQTT bridge.') <NEW_LINE> <DEDENT> <DEDENT> def on_connect(self, unused_client, unused_userdata, unused_flags, rc): <NEW_LINE> <INDENT> print('on_connect(): Connection Result:', error_str(rc)) <NEW_LINE> self.connected = True <NEW_LINE> <DEDENT> def on_disconnect(self, unused_client, unused_userdata, rc): <NEW_LINE> <INDENT> print('on_disconnect(): Disconnected:', error_str(rc)) <NEW_LINE> self.connected = False <NEW_LINE> <DEDENT> def on_publish(self, unused_client, unused_userdata, unused_mid): <NEW_LINE> <INDENT> print('on_publish(): msg sent.') <NEW_LINE> <DEDENT> def on_subscribe(self, unused_client, unused_userdata, unused_mid, granted_qos): <NEW_LINE> <INDENT> print('on_subscribe(): Subscribed: ', granted_qos) <NEW_LINE> if granted_qos[0] == 128: <NEW_LINE> <INDENT> print('Subscription failed.') <NEW_LINE> <DEDENT> <DEDENT> def on_message(self, unused_client, unused_userdata, message): <NEW_LINE> <INDENT> payload = message.payload <NEW_LINE> print('on_message(): Received message \'{}\' on topic \'{}\' with Qos {}'.format( payload, message.topic, str(message.qos))) <NEW_LINE> if not payload: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> data = json.loads(payload)
Represents the state of a single device.
62598fae2c8b7c6e89bd37b6
class FieldSequenceComparator(Comparator): <NEW_LINE> <INDENT> any = 'any' <NEW_LINE> notany = 'notany'
Comparators for :class:`hypatia.field.FieldIndex` search index. These comparators need to be combined with a sequence of index values.
62598faecb5e8a47e493c171
class DataStream(Base): <NEW_LINE> <INDENT> __tablename__ = "datastream" <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> sensor = Column(Text, ForeignKey('sensor.uuid', ondelete='CASCADE'), unique=True, index=True) <NEW_LINE> owner = Column(Integer, ForeignKey('user.id', ondelete='CASCADE')) <NEW_LINE> min_value = Column(Float) <NEW_LINE> max_value = Column(Float) <NEW_LINE> name = Column(Text) <NEW_LINE> description = Column(Text) <NEW_LINE> paths = relationship("Path") <NEW_LINE> def toDict(self): <NEW_LINE> <INDENT> return { 'id': self.id, 'min_value': self.min_value, 'max_value': self.max_value, 'name': self.name, 'description': self.description, 'owner': self.owner, 'sensor': self.sensor, "paths": [p.path for p in self.paths] }
id : int Unique identifier of this DataStream. sensor : str Used to identify a DataStream to a Sensor. owner : int Identifies the user for the datastream. Currently unused. min_value : float max_value : float name : str User-friendly (human-readable) name. Currently unused. description : str Some information that describes the datastream. Currently unused.
62598fae3346ee7daa337640
class Decorator(object): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self.commands: CmdTable = [] <NEW_LINE> <DEDENT> def __call__( self, name: str, help: Optional[str], aliases: Optional[List[str]] = None ) -> Callable[[Type[Subcmd]], Type[Subcmd]]: <NEW_LINE> <INDENT> return subcmd(name, help, aliases=aliases, cmd_table=self.commands)
decorator() creates a new object that can act as a decorator function to help define Subcmd instances. This decorator object also maintains a list of all commands that have been defined using it. This command list can later be passed to add_subcommands() to register these commands.
62598fae167d2b6e312b6f63
class SecurityDomainObject(Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': 'str'}, } <NEW_LINE> def __init__(self, *, value=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(SecurityDomainObject, self).__init__(**kwargs) <NEW_LINE> self.value = value
:param value: :type value: str
62598fae10dbd63aa1c70ba5
class LineTests(unittest.TestCase): <NEW_LINE> <INDENT> records = [('LN "foo" "http://example.com/"', lncore.LN, "foo", "http://example.com/"), ('NS "foo" "http://example.com/"', lncore.NS, "foo", "http://example.com/"), ('X "foo" "http://example.com/"', lncore.X, "foo", "http://example.com/"), ('PATTERN "foo" "http://example.com/"', lncore.PATTERN, "foo", "http://example.com/"),] <NEW_LINE> lines = [('LN "foo" "http://example.com/"', lncore.Line.RCD), ('# This is a comment."', lncore.Line.CMT), ('', lncore.Line.BLK), ('An error.', lncore.Line.ERR),] <NEW_LINE> def testRecordInterpretation(self): <NEW_LINE> <INDENT> for (line, record_type, key, value) in LineTests.records: <NEW_LINE> <INDENT> line = lncore.Line(line) <NEW_LINE> assert line.record_type == record_type <NEW_LINE> assert line.key == key <NEW_LINE> assert line.value == value <NEW_LINE> <DEDENT> <DEDENT> def testLineInterpretation(self): <NEW_LINE> <INDENT> for (line, line_type) in LineTests.lines: <NEW_LINE> <INDENT> line = lncore.Line(line) <NEW_LINE> assert line.line_type == line_type
Test line recognition. DOC testRecordInterpretation -- test record details testLineInterpretation -- test line types
62598fae5fdd1c0f98e5df7e
class LocalTimezone(tzinfo): <NEW_LINE> <INDENT> def __init__(self, dt): <NEW_LINE> <INDENT> tzinfo.__init__(self) <NEW_LINE> self.__dt = dt <NEW_LINE> self._tzname = self.tzname(dt) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return smart_text(self._tzname) <NEW_LINE> <DEDENT> def __getinitargs__(self): <NEW_LINE> <INDENT> return self.__dt, <NEW_LINE> <DEDENT> def utcoffset(self, dt): <NEW_LINE> <INDENT> if self._isdst(dt): <NEW_LINE> <INDENT> return timedelta(seconds=-time.altzone) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return timedelta(seconds=-time.timezone) <NEW_LINE> <DEDENT> <DEDENT> def dst(self, dt): <NEW_LINE> <INDENT> if self._isdst(dt): <NEW_LINE> <INDENT> return timedelta(seconds=-time.altzone) - timedelta(seconds=-time.timezone) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return timedelta(0) <NEW_LINE> <DEDENT> <DEDENT> def tzname(self, dt): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return smart_unicode(time.tzname[self._isdst(dt)], DEFAULT_LOCALE_ENCODING) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def _isdst(self, dt): <NEW_LINE> <INDENT> tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0) <NEW_LINE> try: <NEW_LINE> <INDENT> stamp = time.mktime(tt) <NEW_LINE> <DEDENT> except (OverflowError, ValueError): <NEW_LINE> <INDENT> tt = (2037,) + tt[1:] <NEW_LINE> stamp = time.mktime(tt) <NEW_LINE> <DEDENT> tt = time.localtime(stamp) <NEW_LINE> return tt.tm_isdst > 0
Proxy timezone information from time module.
62598fae30bbd72246469971
class TestPagedRelatedEvent(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testPagedRelatedEvent(self): <NEW_LINE> <INDENT> pass
PagedRelatedEvent unit test stubs
62598fae67a9b606de545fbe
class VF_OT_value_finder(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "node.vf_value_finder" <NEW_LINE> bl_label = "Value Finder" <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> space = context.space_data <NEW_LINE> return space.type == 'NODE_EDITOR' <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> node_active = context.active_node <NEW_LINE> props = context.scene.value_finder <NEW_LINE> rd = context.scene.render <NEW_LINE> if props.del_files: <NEW_LINE> <INDENT> dir_path = Path(rd.filepath+"_").parent <NEW_LINE> print(dir_path) <NEW_LINE> [f.unlink() for f in dir_path.glob("*") if f.is_file()] <NEW_LINE> <DEDENT> input_socket = node_active.inputs[props.input] <NEW_LINE> original_value = input_socket.default_value <NEW_LINE> original_path = rd.filepath <NEW_LINE> for step in range(props.steps): <NEW_LINE> <INDENT> slope = (props.end_input-props.start_input)/(props.steps-1) <NEW_LINE> value = props.start_input+slope*step <NEW_LINE> input_socket.default_value = value <NEW_LINE> if props.image_info: <NEW_LINE> <INDENT> rd.filepath = f"{original_path}_({input_socket.name}_{step+1:n}={value:.2f})" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rd.filepath = f"{original_path}{step+1:n}" <NEW_LINE> <DEDENT> bpy.ops.render.render(write_still=True) <NEW_LINE> <DEDENT> rd.filepath = original_path <NEW_LINE> input_socket.default_value = original_value <NEW_LINE> self.report({'INFO'}, "Finished Rendering") <NEW_LINE> return {'FINISHED'}
Render the scene for the different values
62598fae090684286d5936d5
class ShowMplsInterfaceSchema(MetaParser): <NEW_LINE> <INDENT> schema = { 'vrf':{ Any():{ 'interfaces': { Any(): { Optional('ip'): str, Optional('tunnel'): str, Optional('bgp'): str, Optional('static'): str, Optional('operational'): str, Optional('type'): str, Optional('session'): str, Optional('ip_labeling_enabled'):{ Any():{ 'ldp': bool, Optional('interface_config'): bool, } }, Optional('lsp_tunnel_labeling_enabled'): bool, Optional('lp_frr_labeling_enabled'): bool, Optional('bgp_labeling_enabled'): bool, Optional('mpls_operational'): bool, Optional('mtu'): int, } } } } }
Schema for show mpls interfaces show mpls interfaces all show mpls interfaces vrf <vrf> show mpls interfaces <interface> show mpls interfaces <interface> detail show mpls interfaces detail
62598fae66656f66f7d5a3e1
class WeChatException(Exception): <NEW_LINE> <INDENT> def __init__(self, errcode, errmsg): <NEW_LINE> <INDENT> self.errcode = errcode <NEW_LINE> self.errmsg = errmsg <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if six.PY2: <NEW_LINE> <INDENT> return to_binary('Error code: {code}, message: {msg}'.format( code=self.errcode, msg=self.errmsg )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return to_text('Error code: {code}, message: {msg}'.format( code=self.errcode, msg=self.errmsg )) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> _repr = '{klass}({code}, {msg}'.format( klass=self.__class__.__name__, code=self.errcode, msg=self.errmsg ) <NEW_LINE> if six.PY2: <NEW_LINE> <INDENT> return to_binary(_repr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return to_text(_repr)
Base exception for wechatpy
62598faef548e778e596b596
class Grid: <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = np.asarray(x) <NEW_LINE> self.y = np.asarray(y) <NEW_LINE> self.significance = np.zeros((len(x), len(y))) <NEW_LINE> self.cls = np.zeros_like(self.significance) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromfile(cls, filename): <NEW_LINE> <INDENT> data = np.load(filename) <NEW_LINE> obj = cls(data['x'], data['y']) <NEW_LINE> obj.significance = data['significance'] <NEW_LINE> obj.cls = data['cls'] <NEW_LINE> return obj <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for iy in range(len(self.y)): <NEW_LINE> <INDENT> for ix in range(len(self.x)): <NEW_LINE> <INDENT> global_index = ix + iy * len(self.x) <NEW_LINE> yield (global_index, self.x[ix], self.y[iy]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def save(self, filename): <NEW_LINE> <INDENT> np.savez(filename, x=self.x, y=self.y, significance=self.significance, cls=self.cls) <NEW_LINE> <DEDENT> def set(self, global_index, significance, cls): <NEW_LINE> <INDENT> ix = global_index % len(self.x) <NEW_LINE> iy = global_index // len(self.x) <NEW_LINE> self.significance[ix, iy] = significance <NEW_LINE> self.cls[ix, iy] = cls
Class to facilitate scanning over a 2D grid. For each node of the grid, the significance and the CLs value can be attached. They are stored in 2D arrays with coordinates in the order (x, y). The grid and values of significance and CLs can be saved in an .npz file and read back from it.
62598fae16aa5153ce4004f4
class FileSystemCompCommand(sublime_plugin.EventListener): <NEW_LINE> <INDENT> def on_query_completions(self, view, prefix, locations): <NEW_LINE> <INDENT> global activated <NEW_LINE> rowcol = view.rowcol(locations[0]) <NEW_LINE> line = view.line(locations[0]) <NEW_LINE> lstr = view.substr(line) <NEW_LINE> lstr = lstr[0:rowcol[1]] <NEW_LINE> guessed_path = scanpath(lstr) <NEW_LINE> if not activated and not isexplicitpath(guessed_path): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> guessed_path = os.path.expanduser(guessed_path) <NEW_LINE> escaped_path = ispathescaped(guessed_path) <NEW_LINE> view_path = getviewcwd(view) <NEW_LINE> fuzzy_path = fuzzypath(guessed_path, view_path) <NEW_LINE> if not fuzzy_path: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> matches = self.get_matches(fuzzy_path, escaped_path) <NEW_LINE> activated = False <NEW_LINE> return (matches, sublime.INHIBIT_WORD_COMPLETIONS) <NEW_LINE> <DEDENT> def get_matches(self, path, escaped_path): <NEW_LINE> <INDENT> if escaped_path: <NEW_LINE> <INDENT> path = remove_escape_spaces(path) <NEW_LINE> <DEDENT> pattern = path + '*' <NEW_LINE> matches = [] <NEW_LINE> for fname in iglob(pattern): <NEW_LINE> <INDENT> completion = os.path.basename(fname) <NEW_LINE> if escaped_path: <NEW_LINE> <INDENT> completion = escape_scapes(completion) <NEW_LINE> <DEDENT> text = '' <NEW_LINE> if os.path.isdir(fname): <NEW_LINE> <INDENT> text = '%s/\tDir' % completion <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> text = '%s\tFile' % completion <NEW_LINE> <DEDENT> lastword = path[path.rfind(sep)+1:] <NEW_LINE> rest = '' <NEW_LINE> if path[-1] != ' ': <NEW_LINE> <INDENT> lastword = lastword[lastword.rfind(' ')+1:] <NEW_LINE> rest = completion[completion.find(lastword):] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rest = completion[completion.find(lastword)+len(lastword):] <NEW_LINE> <DEDENT> if rest.find(' ') != -1: <NEW_LINE> <INDENT> completion = rest <NEW_LINE> <DEDENT> matches.append((text, completion)) <NEW_LINE> <DEDENT> return matches
Enable SublimeText2 to complete filesystem paths a la VIM:
62598fae2c8b7c6e89bd37b7
class AssociateAccessGroupsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.MountPointId = None <NEW_LINE> self.AccessGroupIds = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.MountPointId = params.get("MountPointId") <NEW_LINE> self.AccessGroupIds = params.get("AccessGroupIds")
AssociateAccessGroups请求参数结构体
62598fae7b180e01f3e49049
class StoreLocation(object): <NEW_LINE> <INDENT> def __init__(self, store_specs): <NEW_LINE> <INDENT> self.specs = store_specs <NEW_LINE> if self.specs: <NEW_LINE> <INDENT> self.process_specs() <NEW_LINE> <DEDENT> <DEDENT> def process_specs(self): <NEW_LINE> <INDENT> self.scheme = self.specs.get('scheme', 'scohack') <NEW_LINE> self.volume_id = self.specs.get('volume_id') <NEW_LINE> <DEDENT> def get_uri(self): <NEW_LINE> <INDENT> return "scohack://%s" % self.volume_id <NEW_LINE> <DEDENT> def parse_uri(self, uri): <NEW_LINE> <INDENT> if not uri.startswith('scohack://'): <NEW_LINE> <INDENT> reason = _("URI must start with scohack://") <NEW_LINE> LOG.error(reason) <NEW_LINE> msg = (_("BadStore: uri: >%(uri)s<, reason: >%(reason)s<") % dict(uri=uri, reason=reason)) <NEW_LINE> raise Exception(msg) <NEW_LINE> <DEDENT> self.scheme = 'scohack' <NEW_LINE> self.volume_id = uri[10:]
Class describing a Scohack URI
62598faea8370b77170f03ce
class DeleteGroupInputSet(InputSet): <NEW_LINE> <INDENT> def set_Email(self, value): <NEW_LINE> <INDENT> super(DeleteGroupInputSet, self)._set_input('Email', value) <NEW_LINE> <DEDENT> def set_GroupID(self, value): <NEW_LINE> <INDENT> super(DeleteGroupInputSet, self)._set_input('GroupID', value) <NEW_LINE> <DEDENT> def set_Password(self, value): <NEW_LINE> <INDENT> super(DeleteGroupInputSet, self)._set_input('Password', value) <NEW_LINE> <DEDENT> def set_Server(self, value): <NEW_LINE> <INDENT> super(DeleteGroupInputSet, self)._set_input('Server', value)
An InputSet with methods appropriate for specifying the inputs to the DeleteGroup Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62598faeac7a0e7691f724fb
class PTReader: <NEW_LINE> <INDENT> def __init__(self, path, domain='none', exclude=()): <NEW_LINE> <INDENT> self.domain = domain <NEW_LINE> self.catalogs = {} <NEW_LINE> self.path = path <NEW_LINE> self.exclude = exclude <NEW_LINE> <DEDENT> def read(self): <NEW_LINE> <INDENT> from extract import tal_strings <NEW_LINE> tal = tal_strings(self.path, domain=self.domain, exclude=self.exclude + ('tests', 'docs')) <NEW_LINE> for msgid in tal: <NEW_LINE> <INDENT> msgstr = msgid.default or '' <NEW_LINE> if msgid and msgid != '${DYNAMIC_CONTENT}': <NEW_LINE> <INDENT> self._add_msg(msgid, msgstr, [], [l[0] for l in tal[msgid]], [], self.domain) <NEW_LINE> <DEDENT> <DEDENT> return [] <NEW_LINE> <DEDENT> def _add_msg(self, msgid, msgstr, comments, filename, automatic_comments, domain): <NEW_LINE> <INDENT> if not domain: <NEW_LINE> <INDENT> print >> sys.stderr, 'No domain name for msgid "%s" in %s\n' % (msgid, filename) <NEW_LINE> return <NEW_LINE> <DEDENT> if not domain in self.catalogs: <NEW_LINE> <INDENT> self.catalogs[domain] = MessageCatalog(domain=domain) <NEW_LINE> <DEDENT> self.catalogs[domain].add(msgid, msgstr=msgstr, comments=comments, references=filename, automatic_comments=automatic_comments)
Reads in a list of page templates
62598fae99fddb7c1ca62de2
class GoogleCloudMlV1ListModelsResponse(_messages.Message): <NEW_LINE> <INDENT> models = _messages.MessageField('GoogleCloudMlV1Model', 1, repeated=True) <NEW_LINE> nextPageToken = _messages.StringField(2)
Response message for the ListModels method. Fields: models: The list of models. nextPageToken: Optional. Pass this token as the `page_token` field of the request for a subsequent call.
62598fae21bff66bcd722c59
class NormalizeTree(CythonTransform): <NEW_LINE> <INDENT> def __init__(self, context): <NEW_LINE> <INDENT> super(NormalizeTree, self).__init__(context) <NEW_LINE> self.is_in_statlist = False <NEW_LINE> self.is_in_expr = False <NEW_LINE> <DEDENT> def visit_ModuleNode(self, node): <NEW_LINE> <INDENT> self.visitchildren(node) <NEW_LINE> if not isinstance(node.body, Nodes.StatListNode): <NEW_LINE> <INDENT> node.body = Nodes.StatListNode(pos=node.pos, stats=[node.body]) <NEW_LINE> <DEDENT> return node <NEW_LINE> <DEDENT> def visit_ExprNode(self, node): <NEW_LINE> <INDENT> stacktmp = self.is_in_expr <NEW_LINE> self.is_in_expr = True <NEW_LINE> self.visitchildren(node) <NEW_LINE> self.is_in_expr = stacktmp <NEW_LINE> return node <NEW_LINE> <DEDENT> def visit_StatNode(self, node, is_listcontainer=False): <NEW_LINE> <INDENT> stacktmp = self.is_in_statlist <NEW_LINE> self.is_in_statlist = is_listcontainer <NEW_LINE> self.visitchildren(node) <NEW_LINE> self.is_in_statlist = stacktmp <NEW_LINE> if not self.is_in_statlist and not self.is_in_expr: <NEW_LINE> <INDENT> return Nodes.StatListNode(pos=node.pos, stats=[node]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> <DEDENT> def visit_StatListNode(self, node): <NEW_LINE> <INDENT> self.is_in_statlist = True <NEW_LINE> self.visitchildren(node) <NEW_LINE> self.is_in_statlist = False <NEW_LINE> return node <NEW_LINE> <DEDENT> def visit_ParallelAssignmentNode(self, node): <NEW_LINE> <INDENT> return self.visit_StatNode(node, True) <NEW_LINE> <DEDENT> def visit_CEnumDefNode(self, node): <NEW_LINE> <INDENT> return self.visit_StatNode(node, True) <NEW_LINE> <DEDENT> def visit_CStructOrUnionDefNode(self, node): <NEW_LINE> <INDENT> return self.visit_StatNode(node, True) <NEW_LINE> <DEDENT> def visit_PassStatNode(self, node): <NEW_LINE> <INDENT> if not self.is_in_statlist: <NEW_LINE> <INDENT> return Nodes.StatListNode(pos=node.pos, stats=[]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> def visit_ExprStatNode(self, node): <NEW_LINE> <INDENT> if node.expr.is_string_literal: <NEW_LINE> <INDENT> return self.visit_PassStatNode(node) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.visit_StatNode(node) <NEW_LINE> <DEDENT> <DEDENT> def visit_CDeclaratorNode(self, node): <NEW_LINE> <INDENT> return node
This transform fixes up a few things after parsing in order to make the parse tree more suitable for transforms. a) After parsing, blocks with only one statement will be represented by that statement, not by a StatListNode. When doing transforms this is annoying and inconsistent, as one cannot in general remove a statement in a consistent way and so on. This transform wraps any single statements in a StatListNode containing a single statement. b) The PassStatNode is a noop and serves no purpose beyond plugging such one-statement blocks; i.e., once parsed a ` "pass" can just as well be represented using an empty StatListNode. This means less special cases to worry about in subsequent transforms (one always checks to see if a StatListNode has no children to see if the block is empty).
62598faebe8e80087fbbf056
class ExamplePipeline(object): <NEW_LINE> <INDENT> def process_item(self, item, spider): <NEW_LINE> <INDENT> return item <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.searchIndex.finish_index()
This pipeline class object is designed for ElasticSearch client
62598fae097d151d1a2c101c
class KeyReferenceToPersistent(KeyReferenceToPersistent): <NEW_LINE> <INDENT> implements(IKeyReference) <NEW_LINE> adapts(IPersistent) <NEW_LINE> key_type_id = 'five.intid.keyreference' <NEW_LINE> def __init__(self, wrapped_obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.path = '/'.join(wrapped_obj.getPhysicalPath()) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.path = None <NEW_LINE> <DEDENT> if self.path is not None and self.path.endswith('/'): <NEW_LINE> <INDENT> raise NotYet(wrapped_obj) <NEW_LINE> <DEDENT> self.object = aq_base(wrapped_obj) <NEW_LINE> connection = IConnection(wrapped_obj, None) <NEW_LINE> if not getattr(self.object, '_p_oid', None): <NEW_LINE> <INDENT> if connection is None: <NEW_LINE> <INDENT> raise NotYet(wrapped_obj) <NEW_LINE> <DEDENT> connection.add(self.object) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.root_oid = get_root(wrapped_obj)._p_oid <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.root_oid = get_root(getSite())._p_oid <NEW_LINE> <DEDENT> self.oid = self.object._p_oid <NEW_LINE> self.dbname = connection.db().database_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def root(self): <NEW_LINE> <INDENT> return IConnection(self.object)[self.root_oid] <NEW_LINE> <DEDENT> @property <NEW_LINE> def wrapped_object(self): <NEW_LINE> <INDENT> if self.path is None: <NEW_LINE> <INDENT> return self.object <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> obj = self.root.unrestrictedTraverse(self.path) <NEW_LINE> <DEDENT> except (NotFound, AttributeError,): <NEW_LINE> <INDENT> return self.object <NEW_LINE> <DEDENT> chain = aq_chain(obj) <NEW_LINE> if not len(chain) or not isinstance(chain[-1], RequestContainer): <NEW_LINE> <INDENT> site = getSite() <NEW_LINE> site_chain = aq_chain(site) <NEW_LINE> if len(site_chain) and isinstance(site_chain[-1], RequestContainer): <NEW_LINE> <INDENT> req = site_chain[-1] <NEW_LINE> new_obj = req <NEW_LINE> for item in reversed(chain): <NEW_LINE> <INDENT> new_obj = aq_base(item).__of__(new_obj) <NEW_LINE> <DEDENT> obj = new_obj <NEW_LINE> <DEDENT> <DEDENT> return obj <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return self.wrapped_object <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.dbname, self.object._p_oid, )) <NEW_LINE> <DEDENT> def __cmp__(self, other): <NEW_LINE> <INDENT> if self.key_type_id == other.key_type_id: <NEW_LINE> <INDENT> return cmp((self.dbname,self.oid), (other.dbname, other.oid)) <NEW_LINE> <DEDENT> return cmp(self.key_type_id, other.key_type_id)
a zope2ish implementation of keyreferences that unwraps objects that have Acquisition wrappers These references compare by _p_oids of the objects they reference. @@ cache IConnection as a property and volative attr?
62598faeff9c53063f51a640
class DocumentUpdateError(ArangoRequestError): <NEW_LINE> <INDENT> pass
Failed to update the ArangoDB document(s).
62598fae379a373c97d99006
class GetConfig(BaseService): <NEW_LINE> <INDENT> def __init__(self, connection, context, **kwargs): <NEW_LINE> <INDENT> super().__init__(connection, context, **kwargs) <NEW_LINE> self.start_state = 'enable' <NEW_LINE> self.end_state = 'enable' <NEW_LINE> self.timeout = connection.settings.EXEC_TIMEOUT <NEW_LINE> self.__dict__.update(kwargs) <NEW_LINE> <DEDENT> def pre_service(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def post_service(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def call_service(self, target='active', timeout=None, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.result = self.connection.execute("show running-config", target=target, timeout=timeout) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> raise SubCommandFailure("get_config failed", err) from err
Service return running configuration of the device. Returns: standby running configuration if standby is passed as input. Arguments: target: Service target, by default active Returns: running configuration on Success, raise SubCommandFailure on failure. Example: .. code-block:: python rtr.get_config() rtr.get_config(target='standby')
62598fae442bda511e95c44a
class _ForwardRef(TypingMeta): <NEW_LINE> <INDENT> def __new__(cls, arg): <NEW_LINE> <INDENT> if not isinstance(arg, str): <NEW_LINE> <INDENT> raise TypeError('ForwardRef must be a string -- got %r' % (arg,)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> code = compile(arg, '<string>', 'eval') <NEW_LINE> <DEDENT> except SyntaxError: <NEW_LINE> <INDENT> raise SyntaxError('ForwardRef must be an expression -- got %r' % (arg,)) <NEW_LINE> <DEDENT> self = super().__new__(cls, arg, (), {}, _root=True) <NEW_LINE> self.__forward_arg__ = arg <NEW_LINE> self.__forward_code__ = code <NEW_LINE> self.__forward_evaluated__ = False <NEW_LINE> self.__forward_value__ = None <NEW_LINE> typing_globals = globals() <NEW_LINE> frame = sys._getframe(1) <NEW_LINE> while frame is not None and frame.f_globals is typing_globals: <NEW_LINE> <INDENT> frame = frame.f_back <NEW_LINE> <DEDENT> assert frame is not None <NEW_LINE> self.__forward_frame__ = frame <NEW_LINE> return self <NEW_LINE> <DEDENT> def _eval_type(self, globalns, localns): <NEW_LINE> <INDENT> if not self.__forward_evaluated__: <NEW_LINE> <INDENT> if globalns is None and localns is None: <NEW_LINE> <INDENT> globalns = localns = {} <NEW_LINE> <DEDENT> elif globalns is None: <NEW_LINE> <INDENT> globalns = localns <NEW_LINE> <DEDENT> elif localns is None: <NEW_LINE> <INDENT> localns = globalns <NEW_LINE> <DEDENT> self.__forward_value__ = _type_check( eval(self.__forward_code__, globalns, localns), "Forward references must evaluate to types.") <NEW_LINE> self.__forward_evaluated__ = True <NEW_LINE> <DEDENT> return self.__forward_value__ <NEW_LINE> <DEDENT> def __instancecheck__(self, obj): <NEW_LINE> <INDENT> raise TypeError("Forward references cannot be used with isinstance().") <NEW_LINE> <DEDENT> def __subclasscheck__(self, cls): <NEW_LINE> <INDENT> if not self.__forward_evaluated__: <NEW_LINE> <INDENT> globalns = self.__forward_frame__.f_globals <NEW_LINE> localns = self.__forward_frame__.f_locals <NEW_LINE> try: <NEW_LINE> <INDENT> self._eval_type(globalns, localns) <NEW_LINE> <DEDENT> except NameError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return issubclass(cls, self.__forward_value__) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '_ForwardRef(%r)' % (self.__forward_arg__,)
Wrapper to hold a forward reference.
62598fae63b5f9789fe8515a
class fuzzydict(dict): <NEW_LINE> <INDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if super().__eq__(other): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif not isinstance(other, dict): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> keys_same = set(self).intersection(other) <NEW_LINE> for k in keys_same: <NEW_LINE> <INDENT> if self[k] != other[k]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> keys_diff = set(self).difference(other) <NEW_LINE> for k in keys_diff: <NEW_LINE> <INDENT> sv = self.get(k, fuzzylist()) <NEW_LINE> ov = other.get(k, fuzzylist()) <NEW_LINE> if sv != ov: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f'{type(self).__name__}({super().__repr__()})'
Dictionary that ignores empty `fuzzylist` values when determining equality, e.g. fuzzydict(x=fuzzylist()) == {}
62598fae4527f215b58e9ecf
class LengthBonus(BatchScorerInterface): <NEW_LINE> <INDENT> def __init__(self, n_vocab: int): <NEW_LINE> <INDENT> self.n = n_vocab <NEW_LINE> <DEDENT> def score(self, y, state, x): <NEW_LINE> <INDENT> return torch.tensor([1.0], device=x.device, dtype=x.dtype).expand(self.n), None <NEW_LINE> <DEDENT> def batch_score( self, ys: torch.Tensor, states: List[Any], xs: torch.Tensor ) -> Tuple[torch.Tensor, List[Any]]: <NEW_LINE> <INDENT> return ( torch.tensor([1.0], device=xs.device, dtype=xs.dtype).expand( ys.shape[0], self.n ), None, )
Length bonus in beam search.
62598fae1b99ca400228f529
class const: <NEW_LINE> <INDENT> UNDEFINED = Undefined() <NEW_LINE> literal_types = six.integer_types + (six.text_type, six.binary_type) + (bool, float, complex, object, type(None)) <NEW_LINE> transformed_exceptions = (AssertionError, TypeError, ValueError,) <NEW_LINE> class COMPILED_TYPE: <NEW_LINE> <INDENT> LITERAL = 'literal' <NEW_LINE> TYPE = 'type' <NEW_LINE> SCHEMA = 'schema' <NEW_LINE> ENUM = 'enum' <NEW_LINE> CALLABLE = 'callable' <NEW_LINE> ITERABLE = 'iterable' <NEW_LINE> MAPPING = 'mapping' <NEW_LINE> MARKER = 'marker' <NEW_LINE> <DEDENT> compiled_type_priorities = { COMPILED_TYPE.LITERAL: 100, COMPILED_TYPE.TYPE: 50, COMPILED_TYPE.SCHEMA: 0, COMPILED_TYPE.ENUM: 0, COMPILED_TYPE.CALLABLE: 0, COMPILED_TYPE.ITERABLE: 0, COMPILED_TYPE.MAPPING: 0, COMPILED_TYPE.MARKER: None, }
Misc constants
62598fae4e4d562566372419
class Permutator: <NEW_LINE> <INDENT> def __init__(self, word: str): <NEW_LINE> <INDENT> self._word = word <NEW_LINE> if word is None or len(word) < 1 : <NEW_LINE> <INDENT> raise AppException("Word to permutate is None or 0-length") <NEW_LINE> <DEDENT> self._char_counts = find_repeats(self._word) <NEW_LINE> <DEDENT> def number_of_permutations(self) -> int: <NEW_LINE> <INDENT> perms = math.factorial(len(self._word)) <NEW_LINE> for v in self._char_counts.values(): <NEW_LINE> <INDENT> if v > 1: <NEW_LINE> <INDENT> perms /= math.factorial(v) <NEW_LINE> <DEDENT> <DEDENT> return perms <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def permutations(char_counts: DefaultDict[str, int])->Set[str]: <NEW_LINE> <INDENT> total_char = sum(char_counts.values()) <NEW_LINE> variations = set() <NEW_LINE> if len(char_counts) == 1: <NEW_LINE> <INDENT> word_1 = "" <NEW_LINE> for k, v in char_counts.items(): <NEW_LINE> <INDENT> for i in range(v): <NEW_LINE> <INDENT> word_1 += k <NEW_LINE> <DEDENT> <DEDENT> variations.add(word_1) <NEW_LINE> return variations <NEW_LINE> <DEDENT> elif total_char == 2: <NEW_LINE> <INDENT> word_1 = "".join(char_counts.keys()) <NEW_LINE> word_2 = word_1[::-1] <NEW_LINE> variations.add(word_1) <NEW_LINE> variations.add(word_2) <NEW_LINE> return variations <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for k, v in char_counts.items(): <NEW_LINE> <INDENT> copied_char_counts = char_counts.copy() <NEW_LINE> if v == 1: <NEW_LINE> <INDENT> del copied_char_counts[k] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> copied_char_counts[k] -= 1 <NEW_LINE> <DEDENT> sub_variations = Permutator.permutations(copied_char_counts) <NEW_LINE> for word in sub_variations: <NEW_LINE> <INDENT> variations.add(k + word) <NEW_LINE> <DEDENT> <DEDENT> return variations <NEW_LINE> <DEDENT> <DEDENT> def list_permutations(self): <NEW_LINE> <INDENT> return self.permutations(self._char_counts)
class that finds possible permutations of a word
62598fae99cbb53fe6830ecb
@ui.register_ui( item_release=ui.UI(By.CSS_SELECTOR, '[id$="action_release"]')) <NEW_LINE> class DropdownMenu(_ui.DropdownMenu): <NEW_LINE> <INDENT> pass
Dropdown menu of floating IP.
62598fae10dbd63aa1c70ba7
class GetSellerResponse(object): <NEW_LINE> <INDENT> _names = { "id":'id', "name":'name', "code":'code', "document":'document', "description":'description', "status":'Status', "created_at":'CreatedAt', "updated_at":'UpdatedAt', "address":'Address', "metadata":'Metadata', "deleted_at":'DeletedAt' } <NEW_LINE> def __init__(self, id=None, name=None, code=None, document=None, description=None, status=None, created_at=None, updated_at=None, address=None, metadata=None, deleted_at=None): <NEW_LINE> <INDENT> self.id = id <NEW_LINE> self.name = name <NEW_LINE> self.code = code <NEW_LINE> self.document = document <NEW_LINE> self.description = description <NEW_LINE> self.status = status <NEW_LINE> self.created_at = created_at <NEW_LINE> self.updated_at = updated_at <NEW_LINE> self.address = address <NEW_LINE> self.metadata = metadata <NEW_LINE> self.deleted_at = deleted_at <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dictionary(cls, dictionary): <NEW_LINE> <INDENT> if dictionary is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> id = dictionary.get('id') <NEW_LINE> name = dictionary.get('name') <NEW_LINE> code = dictionary.get('code') <NEW_LINE> document = dictionary.get('document') <NEW_LINE> description = dictionary.get('description') <NEW_LINE> status = dictionary.get('Status') <NEW_LINE> created_at = dictionary.get('CreatedAt') <NEW_LINE> updated_at = dictionary.get('UpdatedAt') <NEW_LINE> address = mundiapi.models.get_address_response.GetAddressResponse.from_dictionary(dictionary.get('Address')) if dictionary.get('Address') else None <NEW_LINE> metadata = dictionary.get('Metadata') <NEW_LINE> deleted_at = dictionary.get('DeletedAt') <NEW_LINE> return cls(id, name, code, document, description, status, created_at, updated_at, address, metadata, deleted_at)
Implementation of the 'GetSellerResponse' model. TODO: type model description here. Attributes: id (string): Identification name (string): TODO: type description here. code (string): TODO: type description here. document (string): TODO: type description here. description (string): Description status (string): Status created_at (string): Creation date updated_at (string): Updated date address (GetAddressResponse): Address metadata (dict<object, string>): Metadata deleted_at (string): Deleted date
62598fae7d847024c075c3b6
class IAssociationSetEvent(IAssociationChangeEvent): <NEW_LINE> <INDENT> pass
An association with [0..1] multiplicity has been changed.
62598fae5fdd1c0f98e5df80
class Population: <NEW_LINE> <INDENT> def __init__(self, id: int, chromosomes: List[Chromosome] = None): <NEW_LINE> <INDENT> if chromosomes is None: <NEW_LINE> <INDENT> chromosomes = [] <NEW_LINE> <DEDENT> self.id = id <NEW_LINE> self.chromosomes = chromosomes <NEW_LINE> self.size = self.chromosomes.__len__() <NEW_LINE> <DEDENT> def len(self) -> int: <NEW_LINE> <INDENT> return self.chromosomes.__len__() <NEW_LINE> <DEDENT> def get_all(self) -> List[Chromosome]: <NEW_LINE> <INDENT> return deepcopy(self.chromosomes) <NEW_LINE> <DEDENT> def add(self, chromosome: Chromosome): <NEW_LINE> <INDENT> self.chromosomes.append(chromosome) <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.chromosomes.clear() <NEW_LINE> <DEDENT> def contains(self, chromosome: Chromosome) -> bool: <NEW_LINE> <INDENT> return self.chromosomes.__contains__(chromosome) <NEW_LINE> <DEDENT> def copy(self) -> List[Chromosome]: <NEW_LINE> <INDENT> return self.chromosomes.copy() <NEW_LINE> <DEDENT> def index(self, chromosome: Chromosome) -> int: <NEW_LINE> <INDENT> return self.chromosomes.index(chromosome) <NEW_LINE> <DEDENT> def insert(self, index: int, chromosome: Chromosome): <NEW_LINE> <INDENT> return self.chromosomes.insert(index, chromosome) <NEW_LINE> <DEDENT> def remove(self, chromosome: Chromosome) -> bool: <NEW_LINE> <INDENT> if self.contains(chromosome): <NEW_LINE> <INDENT> self.chromosomes.remove(chromosome) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def remove_at(self, index: int) -> bool: <NEW_LINE> <INDENT> if index <= self.len(): <NEW_LINE> <INDENT> self.chromosomes.remove(self.chromosomes[index]) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __getitem__(self, index: int) -> Chromosome: <NEW_LINE> <INDENT> return self.chromosomes[index]
A List of `Multi-Chromosomes as a population represents different sizes.
62598fae091ae35668704c12
class DescribeServiceReleaseVersionResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Result = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Result") is not None: <NEW_LINE> <INDENT> self.Result = ServiceReleaseVersion() <NEW_LINE> self.Result._deserialize(params.get("Result")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId")
DescribeServiceReleaseVersion返回参数结构体
62598faef7d966606f747fd8
class F5(BBOBNfreeFunction): <NEW_LINE> <INDENT> funId = 5 <NEW_LINE> alpha = 100. <NEW_LINE> def initwithsize(self, curshape, dim): <NEW_LINE> <INDENT> if self.dim != dim: <NEW_LINE> <INDENT> if self.zerox: <NEW_LINE> <INDENT> self.xopt = zeros(dim) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.xopt = 5 * sign(compute_xopt(self.rseed, dim)) <NEW_LINE> <DEDENT> self.scales = -sign(self.xopt) * (self.alpha ** .5) ** linspace(0, 1, dim) <NEW_LINE> <DEDENT> if self.lastshape != curshape: <NEW_LINE> <INDENT> self.dim = dim <NEW_LINE> self.lastshape = curshape <NEW_LINE> self.arrxopt = resize(self.xopt, curshape) <NEW_LINE> <DEDENT> <DEDENT> def _evalfull(self, x): <NEW_LINE> <INDENT> fadd = self.fopt <NEW_LINE> curshape, dim = self.shape_(x) <NEW_LINE> if self.lastshape != curshape: <NEW_LINE> <INDENT> self.initwithsize(curshape, dim) <NEW_LINE> <DEDENT> fadd = fadd + 5 * np.sum(np.abs(self.scales)) <NEW_LINE> x = np.array(x) <NEW_LINE> idx_out_of_bounds = (x * self.arrxopt) > 25 <NEW_LINE> x[idx_out_of_bounds] = sign(x[idx_out_of_bounds]) * 5 <NEW_LINE> ftrue = dot(x, self.scales) <NEW_LINE> fval = self.noise(ftrue) <NEW_LINE> ftrue += fadd <NEW_LINE> fval += fadd <NEW_LINE> return fval, ftrue
Linear slope
62598fae460517430c432057
class Task(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.text = data['text'].encode("utf-8") <NEW_LINE> self.taskID = data['id'] <NEW_LINE> self.dateCreated = H.DateTime(str(data['createdAt'])) <NEW_LINE> self.priority = data['priority'] <NEW_LINE> self.value = data['value'] <NEW_LINE> self.isChallenge = data.has_key('challenge') and data['challenge'] != {} <NEW_LINE> self.color = ValueToColor(self.value) <NEW_LINE> self.difficulty = PriorityToDifficulty(self.priority) <NEW_LINE> self.x = 0 <NEW_LINE> self.y = 0 <NEW_LINE> <DEDENT> def SetXY(self, x=0, y=0): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def Display(self): <NEW_LINE> <INDENT> G.screen.ClearTextArea() <NEW_LINE> X, Y = self.x, self.y <NEW_LINE> task_title = self.text <NEW_LINE> if self.isChallenge: <NEW_LINE> <INDENT> task_title += " [Challenge]" <NEW_LINE> <DEDENT> title_wrap = textwrap.wrap(task_title, C.SCR_Y-20) <NEW_LINE> for i in title_wrap: <NEW_LINE> <INDENT> G.screen.Display(i+'\n', X, Y, color=self.color,bold=True) <NEW_LINE> X += 1 <NEW_LINE> <DEDENT> G.screen.Display("Difficulty: ", X, Y,bold=True) <NEW_LINE> G.screen.Display(self.difficulty, X, Y+12, color=C.SCR_COLOR_MAGENTA, bold=True) <NEW_LINE> X += 1 <NEW_LINE> G.screen.Display("Date Created: ", X, Y,bold=True) <NEW_LINE> G.screen.Display(self.dateCreated.DateCreatedFormat(),X, Y+14, color=C.SCR_COLOR_MAGENTA,bold=True) <NEW_LINE> X += 1 <NEW_LINE> return X <NEW_LINE> <DEDENT> def ChangePriority(self, key): <NEW_LINE> <INDENT> priorityDict = {"trivial": 0.1, "easy": 1, "medium": 1.5, "hard": 2} <NEW_LINE> self.priority = priorityDict[key] <NEW_LINE> self.data['priority'] = self.priority <NEW_LINE> self.difficulty = key
Basic template for a task. There will be separate derived classes for Habits, TODOs and Dailies. Basic display facilities are described in the display function of this class. Other details are displayed by the function in the derived classes
62598fae851cf427c66b82af
class PermissionOwnershipManager(models.Manager): <NEW_LINE> <INDENT> def get_ownership(self, permission, obj_or_class, owner): <NEW_LINE> <INDENT> from expedient.common.permissions.models import Permittee <NEW_LINE> from expedient.common.permissions.models import ObjectPermission <NEW_LINE> from expedient.common.permissions.models import PermissionOwnership <NEW_LINE> try: <NEW_LINE> <INDENT> obj_permission = ObjectPermission.objects.get_for_object_or_class( permission, obj_or_class) <NEW_LINE> <DEDENT> except ObjectPermission.DoesNotExist: <NEW_LINE> <INDENT> raise PermissionOwnership.DoesNotExist() <NEW_LINE> <DEDENT> permittee = Permittee.objects.get_as_permittee(owner) <NEW_LINE> return self.get( obj_permission=obj_permission, permittee=permittee, ) <NEW_LINE> <DEDENT> def delete_ownership(self, permission, obj_or_class, owner): <NEW_LINE> <INDENT> from expedient.common.permissions.models import PermissionOwnership <NEW_LINE> try: <NEW_LINE> <INDENT> po = self.get_ownership(permission, obj_or_class, owner) <NEW_LINE> <DEDENT> except PermissionOwnership.DoesNotExist: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> po.delete() <NEW_LINE> <DEDENT> <DEDENT> def delete_all_for_target(self, obj_or_class, owner): <NEW_LINE> <INDENT> from expedient.common.permissions.models import Permittee <NEW_LINE> permittee = Permittee.objects.get_as_permittee(owner) <NEW_LINE> if not isinstance(obj_or_class, models.Model): <NEW_LINE> <INDENT> obj_or_class = ContentType.objects.get_for_model() <NEW_LINE> <DEDENT> obj_type = ContentType.objects.get_for_model(obj_or_class) <NEW_LINE> self.filter( permittee=permittee, obj_permission__object_type=obj_type, obj_permission__object_id=obj_or_class.id, ).delete()
Manager for PermissionOwnership model. Adds the delete_ownership and get_ownership methods to the default manager.
62598fae67a9b606de545fc0
class FsmTsF(Fsm): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.cSound = kwargs.pop('cSound', None) <NEW_LINE> self.indxN = kwargs.pop('indxn', None) <NEW_LINE> self.tabN = kwargs.pop('ftable', None) <NEW_LINE> self.funct = kwargs.pop('funct', None) <NEW_LINE> super(FsmTsF, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def emitValue(self, evt): <NEW_LINE> <INDENT> self.cSound.TableSet(self.tabN, self.indxN, self.GetValue()) <NEW_LINE> self.funct()
transmit value to a csound table and perform a function
62598faea05bb46b3848a85f
class IRevSplitBlock(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(IRevSplitBlock, self).__init__() <NEW_LINE> <DEDENT> def forward(self, x, _): <NEW_LINE> <INDENT> x1, x2 = torch.chunk(x, chunks=2, dim=1) <NEW_LINE> return x1, x2 <NEW_LINE> <DEDENT> def inverse(self, x1, x2): <NEW_LINE> <INDENT> x = torch.cat((x1, x2), dim=1) <NEW_LINE> return x, None
iRevNet split block.
62598fae2c8b7c6e89bd37b9
class Meta: <NEW_LINE> <INDENT> model = ContactInformation <NEW_LINE> exclude = [ 'datetime_created', 'datetime_modified', 'entity_content_type', 'entity_object_id', ] <NEW_LINE> read_only_fields = [ 'email_address_verified', 'institute_webmail_address', ]
Meta class for ContactInformationSerializer
62598faeb7558d589546361e
class ExactMatchClassifier(IntentClassifier): <NEW_LINE> <INDENT> defaults = {"case_sensitive": True} <NEW_LINE> def __init__( self, component_config: Optional[Dict[Text, Any]] = None, intent_keyword_map: Optional[Dict] = None, ): <NEW_LINE> <INDENT> super(ExactMatchClassifier, self).__init__(component_config) <NEW_LINE> self.case_sensitive = self.component_config.get("case_sensitive") <NEW_LINE> self.intent_keyword_map = intent_keyword_map or {} <NEW_LINE> <DEDENT> def train( self, training_data: TrainingData, config: Optional[RasaNLUModelConfig] = None, **kwargs: Any, ) -> None: <NEW_LINE> <INDENT> for ex in training_data.training_examples: <NEW_LINE> <INDENT> self.intent_keyword_map[ex.text] = ex.get(INTENT) <NEW_LINE> <DEDENT> <DEDENT> def process(self, message: Message, **kwargs: Any) -> None: <NEW_LINE> <INDENT> intent_name = self._map_keyword_to_intent(message.text) <NEW_LINE> confidence = 0.0 if intent_name is None else 1.0 <NEW_LINE> intent = {"name": intent_name, "confidence": confidence} <NEW_LINE> if message.get(INTENT) is None or intent is not None: <NEW_LINE> <INDENT> message.set(INTENT, intent, add_to_output=True) <NEW_LINE> <DEDENT> <DEDENT> def _map_keyword_to_intent(self, text: Text) -> Optional[Text]: <NEW_LINE> <INDENT> for keyword, intent in self.intent_keyword_map.items(): <NEW_LINE> <INDENT> if keyword.strip() == text.strip(): <NEW_LINE> <INDENT> logger.debug( f"ExactMatchClassifier matched keyword '{keyword}' to" f" intent '{intent}'." ) <NEW_LINE> return intent <NEW_LINE> <DEDENT> <DEDENT> logger.debug("ExactMatchClassifier did not find any keywords in the message.") <NEW_LINE> return None <NEW_LINE> <DEDENT> def persist(self, file_name: Text, model_dir: Text) -> Dict[Text, Any]: <NEW_LINE> <INDENT> file_name = file_name + ".json" <NEW_LINE> keyword_file = os.path.join(model_dir, file_name) <NEW_LINE> utils.write_json_to_file(keyword_file, self.intent_keyword_map) <NEW_LINE> return {"file": file_name} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def load( cls, meta: Dict[Text, Any], model_dir: Optional[Text] = None, model_metadata: Metadata = None, cached_component: Optional["ExactMatchClassifier"] = None, **kwargs: Any, ) -> "ExactMatchClassifier": <NEW_LINE> <INDENT> if model_dir and meta.get("file"): <NEW_LINE> <INDENT> file_name = meta.get("file") <NEW_LINE> keyword_file = os.path.join(model_dir, file_name) <NEW_LINE> if os.path.exists(keyword_file): <NEW_LINE> <INDENT> intent_keyword_map = utils.read_json_file(keyword_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise_warning( f"Failed to load key word file for `IntentKeywordClassifier`, " f"maybe {keyword_file} does not exist?" ) <NEW_LINE> intent_keyword_map = None <NEW_LINE> <DEDENT> return cls(meta, intent_keyword_map) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( f"Failed to load keyword intent classifier model. " f"Path {os.path.abspath(meta.get('file'))} doesn't exist." )
Intent classifier using simple exact matching. The classifier takes a list of keywords and associated intents as an input. A input sentence is checked for the keywords and the intent is returned.
62598faebe383301e02537ed
class LSApprovedWorkers: <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.MAP, 'approved_workers', (TType.STRING,None,TType.I32,None), None, ), ) <NEW_LINE> def __init__(self, approved_workers=None,): <NEW_LINE> <INDENT> self.approved_workers = approved_workers <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.MAP: <NEW_LINE> <INDENT> self.approved_workers = {} <NEW_LINE> (_ktype591, _vtype592, _size590 ) = iprot.readMapBegin() <NEW_LINE> for _i594 in xrange(_size590): <NEW_LINE> <INDENT> _key595 = iprot.readString().decode('utf-8') <NEW_LINE> _val596 = iprot.readI32() <NEW_LINE> self.approved_workers[_key595] = _val596 <NEW_LINE> <DEDENT> iprot.readMapEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('LSApprovedWorkers') <NEW_LINE> if self.approved_workers is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('approved_workers', TType.MAP, 1) <NEW_LINE> oprot.writeMapBegin(TType.STRING, TType.I32, len(self.approved_workers)) <NEW_LINE> for kiter597,viter598 in self.approved_workers.items(): <NEW_LINE> <INDENT> oprot.writeString(kiter597.encode('utf-8')) <NEW_LINE> oprot.writeI32(viter598) <NEW_LINE> <DEDENT> oprot.writeMapEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if self.approved_workers is None: <NEW_LINE> <INDENT> raise TProtocol.TProtocolException(message='Required field approved_workers is unset!') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.approved_workers) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - approved_workers
62598faeac7a0e7691f724fd
class TestPrecisEngineTaskStatusResponse(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testPrecisEngineTaskStatusResponse(self): <NEW_LINE> <INDENT> pass
PrecisEngineTaskStatusResponse unit test stubs
62598faed58c6744b42dc2d1
class covarFunc (covariance): <NEW_LINE> <INDENT> def __init__(self,**kwargs): <NEW_LINE> <INDENT> self._dict= {} <NEW_LINE> if kwargs.has_key('logA'): <NEW_LINE> <INDENT> self.logA= kwargs['logA'] <NEW_LINE> <DEDENT> elif kwargs.has_key('A'): <NEW_LINE> <INDENT> self.logA= scipy.log(kwargs['A']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logA= 0. <NEW_LINE> <DEDENT> self._dict['logA']= self.logA <NEW_LINE> if kwargs.has_key('gamma'): <NEW_LINE> <INDENT> self.gamma= kwargs['gamma'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.gamma= 0. <NEW_LINE> <DEDENT> self._dict['gamma']= self.gamma <NEW_LINE> if kwargs.has_key('sr'): <NEW_LINE> <INDENT> self.sr= kwargs['sr'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sr= 0. <NEW_LINE> <DEDENT> self._dict['sr']= self.sr <NEW_LINE> if kwargs.has_key('si'): <NEW_LINE> <INDENT> self.si= kwargs['si'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.si= 0. <NEW_LINE> <DEDENT> self._dict['si']= self.si <NEW_LINE> if kwargs.has_key('sz'): <NEW_LINE> <INDENT> self.sz= kwargs['sz'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sz= 0. <NEW_LINE> <DEDENT> self._dict['sz']= self.sz <NEW_LINE> self.A= scipy.exp(self.logA) <NEW_LINE> self.ss= {'g':{'g':1.,'r':self.sr,'i':self.si,'z':self.sz}, 'r':{'g':self.sr,'r':self.sr**2.,'i':self.si*self.sr, 'z':self.sz*self.sr}, 'i':{'g':self.si,'r':self.si*self.sr,'i':self.si**2., 'z':self.sz*self.si}, 'z':{'g':self.sz,'r':self.sz*self.sr,'i':self.si*self.sz, 'z':self.sz**2.}} <NEW_LINE> <DEDENT> def evaluate(self,x,xp): <NEW_LINE> <INDENT> if self.gamma > 2. or self.gamma < 0.: return -9999.99 <NEW_LINE> prefactor= self.ss[x[1]][xp[1]] <NEW_LINE> return prefactor*0.5*(self._sf(_MAXH)-self._sf(numpy.fabs(x[0]-xp[0]))) <NEW_LINE> <DEDENT> def _sf(self,x): <NEW_LINE> <INDENT> return self.A*x**self.gamma <NEW_LINE> <DEDENT> def _list_params(self): <NEW_LINE> <INDENT> return self._dict.keys()
covarFunc KS11multi: covariance function with a power-law structure function for band g, and linear relation between g and r (eg)
62598faed486a94d0ba2bfc3
class UnderlinedStr(str): <NEW_LINE> <INDENT> def __init__(self, u_str): <NEW_LINE> <INDENT> str.__init__(u_str) <NEW_LINE> <DEDENT> def underline(self): <NEW_LINE> <INDENT> return str.__str__(self) + '\n' + format('', '-<' + str(len(self)))
Underlined string class definition
62598fae7047854f4633f3ce
class OrphanThread(AbstractThreadCheck): <NEW_LINE> <INDENT> def check(self): <NEW_LINE> <INDENT> module = tasks.find_module(self.mods, self.mod_addrs, self.thread.StartAddress) <NEW_LINE> return ('PS_CROSS_THREAD_FLAGS_SYSTEM' in self.flags and module == None)
Detect orphan threads
62598fae2c8b7c6e89bd37ba
class QLearningAgent(ReinforcementAgent): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> self.qvals = util.Counter() <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.qvals[(state, action)] <NEW_LINE> util.raiseNotDefined() <NEW_LINE> <DEDENT> def computeValueFromQValues(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> max_action = float("-inf") <NEW_LINE> if len(legalActions) == 0: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> for action in legalActions: <NEW_LINE> <INDENT> max_action = max(max_action, self.getQValue(state,action)) <NEW_LINE> <DEDENT> return max_action <NEW_LINE> util.raiseNotDefined() <NEW_LINE> <DEDENT> def computeActionFromQValues(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> best_action = self.computeValueFromQValues(state) <NEW_LINE> listOfActions = [] <NEW_LINE> i = 0 <NEW_LINE> lActions = True <NEW_LINE> if len(legalActions) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if lActions: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> for action in legalActions: <NEW_LINE> <INDENT> if best_action == self.getQValue(state, action): <NEW_LINE> <INDENT> listOfActions.append(action) <NEW_LINE> <DEDENT> <DEDENT> return random.choice(listOfActions) <NEW_LINE> <DEDENT> util.raiseNotDefined() <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> action = None <NEW_LINE> lActions = True <NEW_LINE> if lActions: <NEW_LINE> <INDENT> if len(legalActions) != 0: <NEW_LINE> <INDENT> if util.flipCoin(self.epsilon): <NEW_LINE> <INDENT> action = random.choice(legalActions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self.computeActionFromQValues(state) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> action = None <NEW_LINE> <DEDENT> <DEDENT> return action <NEW_LINE> util.raiseNotDefined() <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> lActions = True <NEW_LINE> i = 0 <NEW_LINE> if lActions: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> QVal = self.qvals[(state, action)] <NEW_LINE> newQVal = reward + (self.discount * self.computeValueFromQValues(nextState)) <NEW_LINE> self.qvals[(state, action)] = (((1 - self.alpha) * QVal) + (self.alpha * newQVal)) <NEW_LINE> <DEDENT> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromQValues(state) <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.computeValueFromQValues(state)
Q-Learning Agent Functions you should fill in: - computeValueFromQValues - computeActionFromQValues - getQValue - getAction - update Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.discount (discount rate) Functions you should use - self.getLegalActions(state) which returns legal actions for a state
62598faecb5e8a47e493c173
@pytest.mark.draft <NEW_LINE> @pytest.mark.components <NEW_LINE> @pytest.allure.story('Origins') <NEW_LINE> @pytest.allure.feature('POST') <NEW_LINE> class Test_PFE_Components(object): <NEW_LINE> <INDENT> @pytest.allure.link('https://jira.qumu.com/browse/TC-42557') <NEW_LINE> @pytest.mark.Origins <NEW_LINE> @pytest.mark.POST <NEW_LINE> def test_TC_42557_POST_Origins_Id(self, context): <NEW_LINE> <INDENT> with pytest.allure.step("""Verify that user with Manage Configuration permission is unable to edit/delete entities on "Authorization System" and "Origin" page if "Config admin can create" and "Configuration admin can edit" is set to true, after token expiry time. ."""): <NEW_LINE> <INDENT> originDetails = context.sc.OriginDetails( baseUris=[{ 'uri': 'ftp://172.30.2.149/FTP', 'roles': ['common.ftpfetch'] }], configAdminCanEdit=True, configurations=[{ 'id': 'automation' }], id='originDelete', name='Auto Delete Origin', tokenGenerator=None, visibleInAllConfigurations=False) <NEW_LINE> response = check( context.cl.Origins.createEntity( body=originDetails ) ) <NEW_LINE> <DEDENT> with pytest.allure.step("""Verify that user with Manage Configuration permission is unable to edit/delete entities on "Authorization System" and "Origin" page if "Config admin can create" and "Configuration admin can edit" is set to true, after token expiry time. ."""): <NEW_LINE> <INDENT> originDetails = context.sc.OriginDetails( baseUris=[{ 'uri': 'ftp://172.30.2.149/FTP', 'roles': ['common.ftpfetch'] }], configAdminCanEdit=True, configurations=[{ 'id': 'automation' }], id='originDelete', name='Auto Delete Origin', tokenGenerator=None, visibleInAllConfigurations=False) <NEW_LINE> request = context.cl.Origins.createEntity( body=originDetails ) <NEW_LINE> try: <NEW_LINE> <INDENT> client, response = check( request, quiet=True, returnResponse=True ) <NEW_LINE> <DEDENT> except (HTTPBadRequest, HTTPForbidden) as e: <NEW_LINE> <INDENT> get_error_message(e) | expect.any( should.start_with('may not be empty'), should.start_with('Invalid page parameter specified'), should.contain('Invalid Authorization Token') ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception( "Expected error message, got {} status code instead.".format( response.status_code))
PFE Origins test cases.
62598fae63b5f9789fe8515c
class EnvironmentHolder(Singleton): <NEW_LINE> <INDENT> projectDirectory: str <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.projectDirectory = self.__getProjectDirectory() <NEW_LINE> <DEDENT> def __getProjectDirectory(self) -> str: <NEW_LINE> <INDENT> if getattr(sys, 'frozen', False): <NEW_LINE> <INDENT> return os.path.dirname(sys.executable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return os.path.dirname(os.path.realpath(__file__)) + "\\..\\.."
docstring
62598fae4e4d56256637241b
class DebugMonitor(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.required = [ "debug_monitor"] <NEW_LINE> self.b_key = "debug-monitor" <NEW_LINE> self.a10_url="/axapi/v3/export-periodic/debug-monitor/{debug_monitor}" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.remote_file = "" <NEW_LINE> self.debug_monitor = "" <NEW_LINE> self.use_mgmt_port = "" <NEW_LINE> self.period = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value)
Class Description:: Debug Monitor Output. Class debug-monitor supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param remote_file: {"optional": true, "type": "string", "description": "profile name for remote url", "format": "url"} :param debug_monitor: {"description": "Debug Monitor Output", "format": "string", "minLength": 1, "optional": false, "maxLength": 63, "type": "string"} :param use_mgmt_port: {"default": 0, "optional": true, "type": "number", "description": "Use management port as source port", "format": "flag"} :param period: {"description": "Specify the period in second", "format": "number", "type": "number", "maximum": 31536000, "minimum": 60, "optional": true} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/export-periodic/debug-monitor/{debug_monitor}`.
62598fae8da39b475be031da
class PermissionsCreator(threading.Thread): <NEW_LINE> <INDENT> HOST = "localhost:9091" <NEW_LINE> GRPC_TIMEOUT = 10 <NEW_LINE> def __init__(self, work_q, response_q, id): <NEW_LINE> <INDENT> super(PermissionsCreator, self).__init__() <NEW_LINE> self.work_q = work_q <NEW_LINE> self.response_q = response_q <NEW_LINE> self.stop_condition = threading.Event() <NEW_LINE> self.log_pfx = id <NEW_LINE> self.channel = grpc.insecure_channel(PermissionsCreator.HOST) <NEW_LINE> self.stub = iam_grpc.IamServiceStub(self.channel) <NEW_LINE> <DEDENT> def create_permission(self, subject_aui, object_aui, role_aui, requesting_subject_aui, timeout=None): <NEW_LINE> <INDENT> response = self.stub.createPermission( iam_pb.CreatePermissionRequest( subject_aui=subject_aui, object_aui=object_aui, role_aui=role_aui, requesting_subject_aui=requesting_subject_aui), timeout=timeout) <NEW_LINE> return response <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while not self.stop_condition.is_set(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> permission = self.work_q.get(True, 0.05) <NEW_LINE> self.create_permission(permission.subject_aui, permission.object_aui, permission.role_aui, permission.requestor_aui, PermissionsCreator.GRPC_TIMEOUT) <NEW_LINE> self.response_q.put(True) <NEW_LINE> <DEDENT> except Queue.Empty: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def join(self, timeout=None): <NEW_LINE> <INDENT> self.stop_condition.set() <NEW_LINE> super(PermissionsCreator, self).join(timeout)
Permission creating thread. It will create a new IAM client connection and start consuming permissions information from the queue to form its create request. Each thread simulates a distinct application that might be invoking IAM RPC methods.
62598faeeab8aa0e5d30bd82
class SecurityPolicyType(Enum): <NEW_LINE> <INDENT> NoSecurity = 0 <NEW_LINE> Basic128Rsa15_Sign = 1 <NEW_LINE> Basic128Rsa15_SignAndEncrypt = 2 <NEW_LINE> Basic256_Sign = 3 <NEW_LINE> Basic256_SignAndEncrypt = 4
The supported types of SecurityPolicy. "None" "Basic128Rsa15_Sign" "Basic128Rsa15_SignAndEncrypt" "Basic256_Sign" "Basic256_SignAndEncrypt"
62598fae5fcc89381b266147
class Encoder(nn.Module): <NEW_LINE> <INDENT> def __init__(self,input_size,embedded_size,hidden_size,dropout_p=0.0): <NEW_LINE> <INDENT> super(Encoder,self).__init__() <NEW_LINE> self.input_size = input_size <NEW_LINE> self.hidden_size = hidden_size <NEW_LINE> self.embedded_size = embedded_size <NEW_LINE> self.dropout_p = dropout_p <NEW_LINE> self.embedding_layer = nn.Embedding(input_size,embedded_size) <NEW_LINE> self.dropout = nn.Dropout(p=dropout_p) <NEW_LINE> self.gru = nn.GRU(embedded_size,hidden_size // 2,num_layers = 1,bidirectional=True) <NEW_LINE> self.hidden_state = self.init_hidden() <NEW_LINE> <DEDENT> def forward(self,inputs): <NEW_LINE> <INDENT> embedded = self.embedding_layer(inputs) <NEW_LINE> embedded = self.dropout(embedded) <NEW_LINE> output,self.hidden_state = self.gru(embedded,self.hidden_state) <NEW_LINE> return output,self.hidden_state <NEW_LINE> <DEDENT> def init_hidden(self): <NEW_LINE> <INDENT> return (Variable(torch.randn(1,1,self.hidden_size // 2)),Variable(torch.randn(1,1,self.hidden_size // 2)))
input_size:输入大小,跟词典的len一样 embedded_size:embedd层的size hidden_size:Encoder层输出的隐藏状态size dropout_p:输入层的dropout的比率
62598fae67a9b606de545fc2
class GetSubDomain(View): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return HttpResponse(subdomain_from_request(request))
this view is just meant to test subdomain functionality
62598faef548e778e596b59a
class ModuleInfoArray(object): <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): <NEW_LINE> <INDENT> this = _x64dbgapi64.new_ModuleInfoArray(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _x64dbgapi64.delete_ModuleInfoArray <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def __getitem__(self, *args): <NEW_LINE> <INDENT> return _x64dbgapi64.ModuleInfoArray___getitem__(self, *args) <NEW_LINE> <DEDENT> def __setitem__(self, *args): <NEW_LINE> <INDENT> return _x64dbgapi64.ModuleInfoArray___setitem__(self, *args) <NEW_LINE> <DEDENT> def cast(self): <NEW_LINE> <INDENT> return _x64dbgapi64.ModuleInfoArray_cast(self) <NEW_LINE> <DEDENT> def frompointer(*args): <NEW_LINE> <INDENT> return _x64dbgapi64.ModuleInfoArray_frompointer(*args) <NEW_LINE> <DEDENT> frompointer = staticmethod(frompointer)
Proxy of C++ ModuleInfoArray class
62598fae7d847024c075c3b9
class Alias(BaseModel): <NEW_LINE> <INDENT> domain = models.ForeignKey( Domain, null=True, default=None, blank=True, on_delete=models.SET_NULL) <NEW_LINE> recipient = models.EmailField( _('Recipient Address'), max_length=100, unique=True, db_index=True) <NEW_LINE> forward = models.EmailField( _('Forward Address'), max_length=100) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('Alias') <NEW_LINE> verbose_name_plural = _('Alias') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"{0}>{1}".format(self.recipient, self.forward)
Alias - Used in :ref:`postfix.virtual_alias_maps`
62598faea8370b77170f03d2
class BrowsableAPIRendererWithoutForms(BrowsableAPIRenderer): <NEW_LINE> <INDENT> def get_rendered_html_form(self, data, view, method, request): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def get_raw_data_form(self, data, view, method, request): <NEW_LINE> <INDENT> serializer = getattr(data, 'serializer', None) <NEW_LINE> if serializer and not getattr(serializer, 'many', False): <NEW_LINE> <INDENT> instance = getattr(serializer, 'instance', None) <NEW_LINE> if isinstance(instance, Page): <NEW_LINE> <INDENT> instance = None <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> instance = None <NEW_LINE> <DEDENT> with override_method(view, request, method) as request: <NEW_LINE> <INDENT> if not self.show_form_for_method(view, method, request, instance): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> media_types = [parser.media_type for parser in view.parser_classes] <NEW_LINE> class GenericContentForm(forms.Form): <NEW_LINE> <INDENT> _content_type = forms.ChoiceField( label='Media type', choices=[(media_type, media_type) for media_type in media_types], initial=media_types[0], widget=forms.Select(attrs={'data-override': 'content-type'}) ) <NEW_LINE> _content = forms.CharField( label='Content', widget=forms.Textarea(attrs={'data-override': 'content'}), initial=None ) <NEW_LINE> <DEDENT> return GenericContentForm()
Renders the browsable api, but excludes the HTML form.
62598faed486a94d0ba2bfc4
class Action21(Action): <NEW_LINE> <INDENT> def execute(self, instance): <NEW_LINE> <INDENT> instance.objectPlayer.eventValue = self.evaluate_expression( self.get_parameter(0))
On interactive condition->Change channel name (for channel join request) Parameters: 0: New name (EXPSTRING, ExpressionParameter)
62598faee5267d203ee6b900
class Function(Definition): <NEW_LINE> <INDENT> def __init__(self, line, source): <NEW_LINE> <INDENT> Definition.__init__(self, line, '((?:virtual +|static +|)([^\(]+) +([^ \(]+\([^\)]*\)(?: +const|))(?: +override|))(.*)') <NEW_LINE> self.decl = self.matches.group(1) <NEW_LINE> self.type = self.matches.group(2) <NEW_LINE> self.signature = self.matches.group(3) <NEW_LINE> self.impl = self.matches.group(4).strip() <NEW_LINE> if re.match('^ *= *0 *;$', self.impl): <NEW_LINE> <INDENT> self.is_pure_virtual = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.is_pure_virtual = False <NEW_LINE> <DEDENT> if self.impl.endswith(';'): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> depth = self.impl.count('{') - self.impl.count('}') <NEW_LINE> if self.impl != '' and depth == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> line = source.readline() <NEW_LINE> if line == '': <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.impl += line <NEW_LINE> depth += line.count('{') <NEW_LINE> depth -= line.count('}') <NEW_LINE> if depth == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def write_decl(self, out, context): <NEW_LINE> <INDENT> if context == 'global': <NEW_LINE> <INDENT> out.writeline(self.decl + ';') <NEW_LINE> <DEDENT> elif context == 'class': <NEW_LINE> <INDENT> if self.impl != ';' and '\n' not in self.impl: <NEW_LINE> <INDENT> out.writeline('{decl} {impl}'.format(decl = self.decl, impl = self.impl)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out.writeline('{decl};'.format(decl = self.decl)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def write_def(self, out, cls = ''): <NEW_LINE> <INDENT> signature = re.sub(' *= *[^,)]+', lambda m: '/*' + m.group(0) + '*/', self.signature) <NEW_LINE> if cls: <NEW_LINE> <INDENT> if '\n' not in self.impl: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> out.writeline(self.type) <NEW_LINE> out.writeline('{cls}::{sign}'.format(cls = cls, sign = signature)) <NEW_LINE> for line in self.impl.split('\n'): <NEW_LINE> <INDENT> out.writeline(line) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> out.writeline(self.type) <NEW_LINE> out.writeline('{sign}'.format(sign = signature)) <NEW_LINE> for line in self.impl.split('\n'): <NEW_LINE> <INDENT> out.writeline(line)
Function branch definition. Write as a C++ function within the given scope.
62598fae4e4d56256637241c
class RAnytime(RPackage): <NEW_LINE> <INDENT> homepage = "http://dirk.eddelbuettel.com/code/anytime.html" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/anytime_0.3.9.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/anytime" <NEW_LINE> version('0.3.9', sha256='1096c15249ac70997a8a41c37eeb2a6d38530621abeae05d3dcd96a8acc7574a') <NEW_LINE> depends_on('r@3.2.0:', type=('build', 'run')) <NEW_LINE> depends_on('r-rcpp@0.12.9:', type=('build', 'run')) <NEW_LINE> depends_on('r-bh', type=('build', 'run'))
Anything to 'POSIXct' or 'Date' Converter Convert input in any one of character, integer, numeric, factor, or ordered type into 'POSIXct' (or 'Date') objects, using one of a number of predefined formats, and relying on Boost facilities for date and time parsing.
62598fae4f88993c371f0505
class DelimitedList(ma.fields.List): <NEW_LINE> <INDENT> delimiter: str = ',' <NEW_LINE> def __init__( self, cls_or_instance: typing.Union[ma.fields.Field, type], *, delimiter: typing.Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> self.delimiter = delimiter or __class__.delimiter <NEW_LINE> super().__init__(cls_or_instance, **kwargs) <NEW_LINE> <DEDENT> def _serialize(self, value, attr, obj, **kwargs): <NEW_LINE> <INDENT> return self.delimiter.join( format(each) for each in super()._serialize(value, attr, obj, **kwargs) ) <NEW_LINE> <DEDENT> def _deserialize(self, value, attr, data, **kwargs): <NEW_LINE> <INDENT> dsValue = value <NEW_LINE> if isinstance(dsValue, list): <NEW_LINE> <INDENT> dsValue = value[0] <NEW_LINE> <DEDENT> if not isinstance(dsValue, (str, bytes)): <NEW_LINE> <INDENT> raise ma.ValidationError('Invalid delimited list') <NEW_LINE> <DEDENT> return super()._deserialize(dsValue.split(self.delimiter), attr, data, **kwargs)
A field which is similar to a List, but takes its input as a delimited string (e.g. "foo,bar,baz"). Like List, it can be given a nested field type which it will use to de/serialize each element of the list. :param Field cls_or_instance: A field class or instance. :param str delimiter: Delimiter between values.
62598fae26068e7796d4c94b
class Tfidf: <NEW_LINE> <INDENT> def __init__(self,corpus): <NEW_LINE> <INDENT> self.tf = {} <NEW_LINE> self.idf={} <NEW_LINE> self.tfidfDict={} <NEW_LINE> self.corpus = corpus <NEW_LINE> <DEDENT> def _getTf(self,docModel,isTokenized=True,normalized=True): <NEW_LINE> <INDENT> if(isTokenized == True): <NEW_LINE> <INDENT> counting = Counter(docModel) <NEW_LINE> totalWords = len(docModel) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tokens = nltk.word_tokenize(docModel) <NEW_LINE> totalWords = len(tokens) <NEW_LINE> counting = Counter(tokens) <NEW_LINE> <DEDENT> if(normalized == True): <NEW_LINE> <INDENT> for word in set(counting): <NEW_LINE> <INDENT> counting[word] = counting[word]/totalWords <NEW_LINE> <DEDENT> <DEDENT> return counting <NEW_LINE> <DEDENT> def _getIdf(self): <NEW_LINE> <INDENT> idf = {} <NEW_LINE> numberOfDocuments = len(self.corpus.getCorpusFiles()) <NEW_LINE> for document in self.corpus.getCorpusFiles(): <NEW_LINE> <INDENT> for token in self.tf[document]: <NEW_LINE> <INDENT> if (token not in idf.keys()): <NEW_LINE> <INDENT> occurrences = 0 <NEW_LINE> for documentAux in self.corpus.getCorpusFiles(): <NEW_LINE> <INDENT> if (token in self.tf[documentAux]): <NEW_LINE> <INDENT> occurrences += 1 <NEW_LINE> <DEDENT> <DEDENT> idf[token] = math.log(float(numberOfDocuments / occurrences)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return idf <NEW_LINE> <DEDENT> def getTfidfAsDataframe(self): <NEW_LINE> <INDENT> return pd.DataFrame(self.tfidfDict) <NEW_LINE> <DEDENT> def getTfidf(self,dataFrame=True): <NEW_LINE> <INDENT> tfidf = {} <NEW_LINE> for document in self.corpus.getCorpusFiles(): <NEW_LINE> <INDENT> self.tf[document] = self._getTf(self.corpus.dictCorpus[document],isTokenized=False) <NEW_LINE> <DEDENT> self.idf = self._getIdf() <NEW_LINE> for document in self.corpus.getCorpusFiles(): <NEW_LINE> <INDENT> tfidf = {} <NEW_LINE> for token in self.tf[document]: <NEW_LINE> <INDENT> tfidf[token] = float(self.idf[token] * self.tf[document][token]) <NEW_LINE> <DEDENT> for token in self.idf: <NEW_LINE> <INDENT> if (token not in self.tf[document]): <NEW_LINE> <INDENT> tfidf[token] = 0 <NEW_LINE> <DEDENT> <DEDENT> self.tfidfDict[document] = tfidf <NEW_LINE> <DEDENT> <DEDENT> def sortDictByValue(self,dictonary): <NEW_LINE> <INDENT> return sorted(dictonary.items(), key=lambda x:x[1])
Classe que recebe o dicionário contendo os textos do Corpus e os modela como um Bag-of-Words Attributes: dictCorpus: Dicionário que modela o corpus.
62598fae7047854f4633f3d1
class GitVersionMixin(object): <NEW_LINE> <INDENT> def write_version_py(self, pyfile): <NEW_LINE> <INDENT> log.info("generating %s" % pyfile) <NEW_LINE> import vcs <NEW_LINE> gitstatus = vcs.GitStatus() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(pyfile, 'w') as fobj: <NEW_LINE> <INDENT> gitstatus.write(fobj, author=AUTHOR, email=AUTHOR_EMAIL) <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> if os.path.exists(pyfile): <NEW_LINE> <INDENT> os.unlink(pyfile) <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> return gitstatus <NEW_LINE> <DEDENT> def update_metadata(self): <NEW_LINE> <INDENT> import cisserver <NEW_LINE> self.distribution.metadata.version = cisserver.__version__ <NEW_LINE> desc, longdesc = cisserver.__doc__.split('\n', 1) <NEW_LINE> self.distribution.metadata.description = desc <NEW_LINE> self.distribution.metadata.long_description = longdesc.strip('\n')
Mixin class to add methods to generate version information from git.
62598fae5fc7496912d4827c
class Key(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass
Iterator object to iterate over keys.
62598fae3346ee7daa337643
class StorageManager(object): <NEW_LINE> <INDENT> def __init__(self, node): <NEW_LINE> <INDENT> self._node = node <NEW_LINE> self._interface_queue = {} <NEW_LINE> self.initStorageQueues() <NEW_LINE> self._MAX_BYTE = 0 <NEW_LINE> self._cur_byte = 0 <NEW_LINE> <DEDENT> def initStorageQueues(self): <NEW_LINE> <INDENT> for nbr in self._node.nbrs: <NEW_LINE> <INDENT> self._interface_queue[nbr] = collections.deque() <NEW_LINE> <DEDENT> <DEDENT> def __spaceAvailable(self, chunk): <NEW_LINE> <INDENT> return True if self._cur_byte + chunk.size() <= self._MAX_BYTE else False <NEW_LINE> <DEDENT> def putChunk(self, chunk): <NEW_LINE> <INDENT> if not self.__spaceAvailable(chunk): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> next_hop = self._node.getNextHop(chunk.dst()) <NEW_LINE> self._interface_queue[next_hop].append(chunk) <NEW_LINE> return True <NEW_LINE> <DEDENT> def getChunkByBufMan(self, buf_man_id): <NEW_LINE> <INDENT> queue = self._interface_queue[buf_man_id] <NEW_LINE> if not queue: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return queue.popleft()
How storage is used: 1. In BufMan.schedBuf(), * it first checks if there's chunks stored. If there is, retrieve it and return. * If there isn't, try to schedule from buffer. (with Per-If queuing) if a chunk is blocked, push it to storage. Repeat this until either a non-blocked chunk is found, or
62598faea8370b77170f03d3
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super(Alien, self).__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load('image/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) <NEW_LINE> <DEDENT> def check_edge(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) <NEW_LINE> self.rect.x = self.x
A class to represent a single alin in the fleet.
62598fae236d856c2adc9439
class MyMiddleware(MiddlewareMixin): <NEW_LINE> <INDENT> def process_request(self, request): <NEW_LINE> <INDENT> user = User.objects.get(id=1) <NEW_LINE> self.current_user = user
测试使用,免去登录
62598fae99cbb53fe6830ecf
class Mailed(object): <NEW_LINE> <INDENT> OFF = 0x00 <NEW_LINE> ON = 0x01 <NEW_LINE> def __init__(self, device): <NEW_LINE> <INDENT> self._device = device <NEW_LINE> config = device.get_active_configuration() <NEW_LINE> interface_number = config[(0, 0)].bInterfaceNumber <NEW_LINE> alternate_setting = usb.control.get_interface(device, interface_number) <NEW_LINE> intf = usb.util.find_descriptor(config, bInterfaceNumber=interface_number, bAlternateSetting=alternate_setting) <NEW_LINE> self._ep = usb.util.find_descriptor(intf, custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT) <NEW_LINE> assert self._ep, "Endpoint not found" <NEW_LINE> <DEDENT> def off(self): <NEW_LINE> <INDENT> self.set_color(Mailed.OFF) <NEW_LINE> <DEDENT> def on(self): <NEW_LINE> <INDENT> self.set_color(Mailed.ON) <NEW_LINE> <DEDENT> def blink(self, interval=0.5, times=10): <NEW_LINE> <INDENT> for i in range(times): <NEW_LINE> <INDENT> self.on() <NEW_LINE> time.sleep(interval) <NEW_LINE> self.off() <NEW_LINE> time.sleep(interval) <NEW_LINE> <DEDENT> <DEDENT> def blink_async(self, interval=0.5, times=10): <NEW_LINE> <INDENT> thread.start_new_thread(self.blink, (interval, times)) <NEW_LINE> <DEDENT> def set_color(self, color): <NEW_LINE> <INDENT> self._ep.write([color, 0x00, 0x00, 0x00, 0x00])
representation of mail led
62598faeeab8aa0e5d30bd84
class CouchDBEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, datetime.datetime): <NEW_LINE> <INDENT> return obj.isoformat()
Custom JSON encoder class for handling special data types
62598fae2ae34c7f260ab0d9
class JointTask(dTwistTask): <NEW_LINE> <INDENT> def __init__(self, joint, ctrl, *args, **kwargs): <NEW_LINE> <INDENT> dTwistTask.__init__(self, *args, **kwargs) <NEW_LINE> self._joint = joint <NEW_LINE> self._ctrl = ctrl <NEW_LINE> assert(isinstance(joint, Joint)) <NEW_LINE> assert(isinstance(ctrl, dTwistCtrl)) <NEW_LINE> if self._cdof == []: <NEW_LINE> <INDENT> self._cdof = arange(self._joint.ndof) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert(len(self._cdof) <= self._joint.ndof) <NEW_LINE> assert(all([cd < self._joint.ndof for cd in self._cdof])) <NEW_LINE> <DEDENT> self._cdof_in_joint = list(self._cdof) <NEW_LINE> <DEDENT> def init(self, world, LQP_ctrl): <NEW_LINE> <INDENT> dTwistTask.init(self, world, LQP_ctrl) <NEW_LINE> self._ctrl.init(world, LQP_ctrl) <NEW_LINE> joint_dofs_in_world = arange(self._ndof)[self._joint.dof] <NEW_LINE> self._cdof = joint_dofs_in_world[self._cdof_in_joint] <NEW_LINE> self._J[arange(len(self._cdof)), self._cdof] = 1 <NEW_LINE> <DEDENT> def _update_matrices(self, rstate, dt): <NEW_LINE> <INDENT> gpos = self._joint.gpos <NEW_LINE> gvel = self._joint.gvel <NEW_LINE> cmd = self._ctrl.update(gpos, gvel, rstate, dt) <NEW_LINE> self._dVdes[:] = cmd[self._cdof_in_joint]
TODO.
62598faedd821e528d6d8f2c