code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class LeastSquaresOracle(BaseSmoothOracle): <NEW_LINE> <INDENT> def __init__(self, matvec_Ax, matvec_ATx, b): <NEW_LINE> <INDENT> self.matvec_Ax = matvec_Ax <NEW_LINE> self.matvec_ATx = matvec_ATx <NEW_LINE> self.b = b <NEW_LINE> <DEDENT> def func(self, x): <NEW_LINE> <INDENT> Ax_b = self.matvec_Ax(x) - self.b <NEW_LINE> return 0.5 * np.dot(Ax_b, Ax_b) <NEW_LINE> <DEDENT> def grad(self, x): <NEW_LINE> <INDENT> return self.matvec_ATx(self.matvec_Ax(x) - self.b)
Oracle for least-squares regression. f(x) = 0.5 ||Ax - b||_2^2
62598fb43d592f4c4edbaf75
class BinaryExpression(ColumnElement): <NEW_LINE> <INDENT> __visit_name__ = 'binary' <NEW_LINE> def __init__(self, left, right, operator, type_=None, negate=None, modifiers=None): <NEW_LINE> <INDENT> if isinstance(operator, str): <NEW_LINE> <INDENT> operator = operators.custom_op(operator) <NEW_LINE> <DEDENT> self._orig = (left, right) <NEW_LINE> self.left = _literal_as_text(left).self_group(against=operator) <NEW_LINE> self.right = _literal_as_text(right).self_group(against=operator) <NEW_LINE> self.operator = operator <NEW_LINE> self.type = sqltypes.to_instance(type_) <NEW_LINE> self.negate = negate <NEW_LINE> if modifiers is None: <NEW_LINE> <INDENT> self.modifiers = {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.modifiers = modifiers <NEW_LINE> <DEDENT> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> if self.operator in (operator.eq, operator.ne): <NEW_LINE> <INDENT> return self.operator(hash(self._orig[0]), hash(self._orig[1])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Boolean value of this clause is not defined") <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def is_comparison(self): <NEW_LINE> <INDENT> return operators.is_comparison(self.operator) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _from_objects(self): <NEW_LINE> <INDENT> return self.left._from_objects + self.right._from_objects <NEW_LINE> <DEDENT> def _copy_internals(self, clone=_clone, **kw): <NEW_LINE> <INDENT> self.left = clone(self.left, **kw) <NEW_LINE> self.right = clone(self.right, **kw) <NEW_LINE> <DEDENT> def get_children(self, **kwargs): <NEW_LINE> <INDENT> return self.left, self.right <NEW_LINE> <DEDENT> def compare(self, other, **kw): <NEW_LINE> <INDENT> return ( isinstance(other, BinaryExpression) and self.operator == other.operator and ( self.left.compare(other.left, **kw) and self.right.compare(other.right, **kw) or ( operators.is_commutative(self.operator) and self.left.compare(other.right, **kw) and self.right.compare(other.left, **kw) ) ) ) <NEW_LINE> <DEDENT> def self_group(self, against=None): <NEW_LINE> <INDENT> if operators.is_precedent(self.operator, against): <NEW_LINE> <INDENT> return Grouping(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> <DEDENT> def _negate(self): <NEW_LINE> <INDENT> if self.negate is not None: <NEW_LINE> <INDENT> return BinaryExpression( self.left, self.right, self.negate, negate=self.operator, type_=sqltypes.BOOLEANTYPE, modifiers=self.modifiers) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super(BinaryExpression, self)._negate()
Represent an expression that is ``LEFT <operator> RIGHT``. A :class:`.BinaryExpression` is generated automatically whenever two column expressions are used in a Python binary expresion:: >>> from sqlalchemy.sql import column >>> column('a') + column('b') <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0> >>> print(column('a') + column('b')) a + b
62598fb4851cf427c66b836a
class vn44_vn45(rose.upgrade.MacroUpgrade): <NEW_LINE> <INDENT> BEFORE_TAG = "vn4.4" <NEW_LINE> AFTER_TAG = "vn4.5" <NEW_LINE> def upgrade(self, config, meta_config=None): <NEW_LINE> <INDENT> return config, self.reports
Version bump macro
62598fb45fdd1c0f98e5e043
class StringWidget(Widget): <NEW_LINE> <INDENT> meta_type = "Naaya Schema String Widget" <NEW_LINE> meta_label = "Single line text" <NEW_LINE> meta_description = "Free text input box" <NEW_LINE> meta_sortorder = 150 <NEW_LINE> _properties = Widget._properties + ( { 'id': 'width', 'label': 'Display width', 'type': 'int', 'mode': 'w', }, { 'id': 'size_max', 'label': 'Maximum input width', 'type': 'int', 'mode': 'w', }, ) <NEW_LINE> _constructors = (addStringWidget,) <NEW_LINE> width = 50 <NEW_LINE> size_max = 0 <NEW_LINE> def _convert_to_form_string(self, value): <NEW_LINE> <INDENT> if isinstance(value, int): <NEW_LINE> <INDENT> value = str(value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> template = PageTemplateFile('../zpt/property_widget_string', globals())
String Widget
62598fb467a9b606de546084
class Action15(Action): <NEW_LINE> <INDENT> def execute(self, instance): <NEW_LINE> <INDENT> value = self.evaluate_index(0) <NEW_LINE> self.player.window.set_caption(value)
Set Title Parameters: 0: Set Title (EXPSTRING, ExpressionParameter)
62598fb44e4d5625663724dc
class AuthMiddleware(BaseMiddleware): <NEW_LINE> <INDENT> def before(self, environ: dict, start_response: Callable) -> WSGIRequest: <NEW_LINE> <INDENT> environ['session'] = None <NEW_LINE> environ['token'] = None <NEW_LINE> token = environ.get('HTTP_AUTHORIZATION') <NEW_LINE> if token is None: <NEW_LINE> <INDENT> logger.debug('No auth token') <NEW_LINE> return environ, start_response <NEW_LINE> <DEDENT> secret = environ.get('JWT_SECRET', os.environ.get('JWT_SECRET')) <NEW_LINE> if secret is None: <NEW_LINE> <INDENT> raise ConfigurationError('Missing decryption token') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> session: domain.Session = tokens.decode(token, secret) <NEW_LINE> environ['session'] = session <NEW_LINE> environ['token'] = token <NEW_LINE> <DEDENT> except InvalidToken as e: <NEW_LINE> <INDENT> logger.error(f'Auth token not valid: {token}') <NEW_LINE> exception = Unauthorized('Invalid auth token') <NEW_LINE> environ['session'] = exception <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error(f'Unhandled exception: {e}') <NEW_LINE> exception = InternalServerError(f'Unhandled: {e}') <NEW_LINE> environ['session'] = exception <NEW_LINE> <DEDENT> return environ, start_response
Middleware to handle auth information on requests. Before the request is handled by the application, the ``Authorization`` header is parsed for an encrypted JWT. If successfully decrypted, information about the user and their authorization scope is attached to the request. This can be accessed in the application via ``flask.request.environ['session']``. If Authorization header was not included, then that value will be ``None``. If the JWT could not be decrypted, the value will be an :class:`Unauthorized` exception instance. We cannot raise the exception here, because the middleware is executed outside of the Flask application. It's up to something running inside the application (e.g. :func:`arxiv.users.auth.decorators.scoped`) to raise the exception.
62598fb491f36d47f2230f03
class Standard(models.Model): <NEW_LINE> <INDENT> standard = models.CharField(max_length=200) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.standard
And again, to store the choices that will be listed for the user to choose between when selecting their approximate standard on each instrument they play.
62598fb421bff66bcd722d1d
class _ThreadThroughputInformation(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.total_bytes_transferred = 0 <NEW_LINE> self.total_elapsed_time = 0 <NEW_LINE> self.task_start_time = None <NEW_LINE> self.task_size = None <NEW_LINE> <DEDENT> def LogTaskStart(self, start_time, bytes_to_transfer): <NEW_LINE> <INDENT> self.task_start_time = start_time <NEW_LINE> self.task_size = bytes_to_transfer <NEW_LINE> <DEDENT> def LogTaskEnd(self, end_time): <NEW_LINE> <INDENT> self.total_elapsed_time += end_time - self.task_start_time <NEW_LINE> self.total_bytes_transferred += self.task_size <NEW_LINE> self.task_start_time = None <NEW_LINE> self.task_size = None <NEW_LINE> <DEDENT> def GetThroughput(self): <NEW_LINE> <INDENT> return CalculateThroughput(self.total_bytes_transferred, self.total_elapsed_time)
A class to keep track of throughput information for a single thread.
62598fb47047854f4633f490
class TutorForm(forms.ModelForm): <NEW_LINE> <INDENT> rate = forms.DecimalField(widget=forms.NumberInput(attrs={'placeholder': '24.00', })) <NEW_LINE> bio = forms.CharField(widget=forms.Textarea( attrs={'placeholder': 'This is your resume. Be very descriptive and describe yourself to prospective pupils.', 'class': 'md-textarea', 'maxlength': Tutor.BIO_MAX_LENGTH})) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Tutor <NEW_LINE> fields = ('rate', 'bio')
Main elements of the Tutor Form
62598fb4ff9c53063f51a703
class DatasetSchema(SchemaObject): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.schema = 'Dataset'
Schema Mixin for Dataset Usage: place after django model in class definition, schema will return the schema.org url for the object A body of structured information describing some topic(s) of interest.
62598fb4be383301e02538b1
class ARCommand: <NEW_LINE> <INDENT> def __init__(self, cmdName): <NEW_LINE> <INDENT> self.name = cmdName <NEW_LINE> self.comments = [] <NEW_LINE> self.args = [] <NEW_LINE> self.buf = ARCommandBuffer.ACK <NEW_LINE> self.timeout = ARCommandTimeoutPolicy.POP <NEW_LINE> self.listtype = ARCommandListType.NONE <NEW_LINE> <DEDENT> def setListType(self, ltype): <NEW_LINE> <INDENT> self.listtype = ltype <NEW_LINE> <DEDENT> def setBufferType(self, btype): <NEW_LINE> <INDENT> self.buf = btype <NEW_LINE> <DEDENT> def setTimeoutPolicy(self, pol): <NEW_LINE> <INDENT> self.timeout = pol <NEW_LINE> <DEDENT> def addCommentLine(self, newCommentLine): <NEW_LINE> <INDENT> self.comments.append(newCommentLine) <NEW_LINE> <DEDENT> def addArgument(self, newArgument): <NEW_LINE> <INDENT> self.args.append(newArgument) <NEW_LINE> <DEDENT> def check(self): <NEW_LINE> <INDENT> ret = '' <NEW_LINE> argret = '' <NEW_LINE> if len (self.comments) == 0: <NEW_LINE> <INDENT> ret = ret + '\n-- Command ' + self.name + ' don\'t have any comment !' <NEW_LINE> <DEDENT> for arg in self.args: <NEW_LINE> <INDENT> argret = argret + arg.check () <NEW_LINE> <DEDENT> if len (argret) != 0: <NEW_LINE> <INDENT> ret = ret + '\n-- Command ' + self.name + ' has errors in its arguments:' <NEW_LINE> <DEDENT> ret = ret + argret <NEW_LINE> return ret
Represent a command
62598fb47047854f4633f491
class RemoteFxTestCase(optional_feature._OptionalFeatureMixin, test_base.TestBase): <NEW_LINE> <INDENT> _MIN_HYPERV_VERSION = 6003 <NEW_LINE> _FEATURE_FLAVOR = {'extra_specs': {'os_resolution': '1920x1200', 'os_monitors': '1', 'os_vram': '1024'}} <NEW_LINE> @classmethod <NEW_LINE> def skip_checks(cls): <NEW_LINE> <INDENT> super(RemoteFxTestCase, cls).skip_checks() <NEW_LINE> if not CONF.hyperv.remotefx_enabled: <NEW_LINE> <INDENT> msg = ('The config option "hyperv.remotefx_enabled" is False. ' 'Skipping.') <NEW_LINE> raise cls.skipException(msg)
RemoteFX test suite. This test suit will spawn instances with RemoteFX enabled.
62598fb4379a373c97d990cb
class SystemHealthStory(page.Page): <NEW_LINE> <INDENT> __metaclass__ = _MetaSystemHealthStory <NEW_LINE> NAME = NotImplemented <NEW_LINE> URL = NotImplemented <NEW_LINE> ABSTRACT_STORY = True <NEW_LINE> SUPPORTED_PLATFORMS = platforms.ALL_PLATFORMS <NEW_LINE> def __init__(self, story_set, take_memory_measurement): <NEW_LINE> <INDENT> case, group, _ = self.NAME.split(':') <NEW_LINE> super(SystemHealthStory, self).__init__( shared_page_state_class=_SystemHealthSharedState, page_set=story_set, name=self.NAME, url=self.URL, credentials_path='../data/credentials.json', grouping_keys={'case': case, 'group': group}) <NEW_LINE> self._take_memory_measurement = take_memory_measurement <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def CanRun(cls, possible_browser): <NEW_LINE> <INDENT> if (decorators.ShouldSkip(cls, possible_browser)[0] or cls.ShouldDisable(possible_browser)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def ShouldDisable(cls, possible_browser): <NEW_LINE> <INDENT> del possible_browser <NEW_LINE> return False <NEW_LINE> <DEDENT> def _Measure(self, action_runner): <NEW_LINE> <INDENT> if self._take_memory_measurement: <NEW_LINE> <INDENT> action_runner.MeasureMemory(deterministic_mode=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action_runner.Wait(_WAIT_TIME_AFTER_LOAD) <NEW_LINE> <DEDENT> <DEDENT> def _Login(self, action_runner): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def _DidLoadDocument(self, action_runner): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def RunNavigateSteps(self, action_runner): <NEW_LINE> <INDENT> self._Login(action_runner) <NEW_LINE> super(SystemHealthStory, self).RunNavigateSteps(action_runner) <NEW_LINE> <DEDENT> def RunPageInteractions(self, action_runner): <NEW_LINE> <INDENT> action_runner.tab.WaitForDocumentReadyStateToBeComplete() <NEW_LINE> self._DidLoadDocument(action_runner) <NEW_LINE> self._Measure(action_runner)
Abstract base class for System Health user stories.
62598fb4f548e778e596b659
class TpsError(TpsException): <NEW_LINE> <INDENT> pass
error, continue remaining tests in test suite
62598fb492d797404e388bbe
class PanValidationSnippet(PanosSnippet): <NEW_LINE> <INDENT> required_metadata = {'name'} <NEW_LINE> optional_metadata = {'documentation_link': ''} <NEW_LINE> template_metadata = {'label', 'test', 'meta'} <NEW_LINE> conditional_template_metadata = {'test'} <NEW_LINE> def execute(self, context: dict) -> Tuple[str, str]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super().execute(context) <NEW_LINE> <DEDENT> except PanXapiError as px: <NEW_LINE> <INDENT> logger.error(f'Exception in {self.name}') <NEW_LINE> logger.error(px) <NEW_LINE> return str(px), 'failure' <NEW_LINE> <DEDENT> except PanoplyException as pe: <NEW_LINE> <INDENT> logger.error(f'Exception in {self.name}') <NEW_LINE> logger.error(pe) <NEW_LINE> return str(pe), 'failure' <NEW_LINE> <DEDENT> <DEDENT> def handle_output_type_validation(self, results: str) -> dict: <NEW_LINE> <INDENT> if not bool(results): <NEW_LINE> <INDENT> results = False <NEW_LINE> <DEDENT> output = dict() <NEW_LINE> output['results'] = results <NEW_LINE> output['label'] = self.metadata.get('label', '') <NEW_LINE> output['severity'] = self.metadata.get('severity', 'low') <NEW_LINE> output['meta'] = self.metadata.get('meta', {}) <NEW_LINE> output['documentation_link'] = self.metadata.get('documentation_link', '') <NEW_LINE> output['test'] = self.metadata.get('test', '') <NEW_LINE> if results: <NEW_LINE> <INDENT> output['output_message'] = self.render(self.metadata.get('pass_message', 'Snippet Validation Passed'), self.context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output['output_message'] = self.render(self.metadata.get('fail_message', 'Snippet Validation Failed'), self.context) <NEW_LINE> <DEDENT> o = dict() <NEW_LINE> o[self.name] = output <NEW_LINE> return o
Pan validation Snippet
62598fb43d592f4c4edbaf76
@attr.s <NEW_LINE> class MutationContext(object): <NEW_LINE> <INDENT> mutations = attr.ib(factory=dict, converter=mutations_list_to_dict) <NEW_LINE> message_path = attr.ib(factory=list) <NEW_LINE> protocol_session = attr.ib(type=ProtocolSession, default=None)
Context for current mutation(s). MutationContext objects are created by Session (the fuzz session manager) and passed to various Fuzzable functions as needed. For complex Fuzzable types that refer to other elements' rendered values, the implementation will typically pass the MutationContext along to child/referenced elements to ensure they are rendered properly. Note: Mutations are generated in the context of a Test Case, so a Mutation has a ProtocolSession, but a ProtocolSession does not necessarily have a MutationContext.
62598fb430dc7b766599f902
class TestCollector(base.AutomatedTest): <NEW_LINE> <INDENT> platforms = ["Windows"] <NEW_LINE> flow = "ArtifactCollectorFlow" <NEW_LINE> args = {"artifact_list": ["WindowsRunKeys"], "store_results_in_aff4": False} <NEW_LINE> def CheckFlow(self): <NEW_LINE> <INDENT> statentry_list = self.CheckCollectionNotEmptyWithRetry( self.session_id.Add(flow_runner.RESULTS_SUFFIX), self.token) <NEW_LINE> for statentry in statentry_list: <NEW_LINE> <INDENT> self.assertTrue(isinstance(statentry, rdf_client.StatEntry)) <NEW_LINE> self.assertTrue("Run" in statentry.pathspec.path)
Test ArtifactCollectorFlow.
62598fb4fff4ab517ebcd89b
class Template: <NEW_LINE> <INDENT> def __init__(self, template=None, description=None): <NEW_LINE> <INDENT> self.template = template <NEW_LINE> self.description = description <NEW_LINE> <DEDENT> def save(self, output_path): <NEW_LINE> <INDENT> with open(output_path, 'w') as f: <NEW_LINE> <INDENT> f.write(to_json(self.template)) <NEW_LINE> <DEDENT> if self.description: <NEW_LINE> <INDENT> with open(self.get_description_path(output_path), 'w') as f: <NEW_LINE> <INDENT> f.write(self.description) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_description_path(template_path): <NEW_LINE> <INDENT> return Path(template_path.parent / (str(template_path.stem) + ".txt")) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def load(cls, template_path): <NEW_LINE> <INDENT> description_path = cls.get_description_path(template_path) <NEW_LINE> if description_path.exists(): <NEW_LINE> <INDENT> with open(description_path, 'r') as f: <NEW_LINE> <INDENT> description = f.readlines() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> description = None <NEW_LINE> <DEDENT> with open(template_path, 'r') as f: <NEW_LINE> <INDENT> template = Dataset.from_json(json.load(f)) <NEW_LINE> <DEDENT> return cls(template=template, description=description) <NEW_LINE> <DEDENT> def get_description(self): <NEW_LINE> <INDENT> if self.description_path.exists(): <NEW_LINE> <INDENT> with open(self.description_path + ".json", 'r') as f: <NEW_LINE> <INDENT> return f.readlines() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def get_dicom_template(self): <NEW_LINE> <INDENT> with open(self.folder_path / self.file_name + ".json", 'r') as f: <NEW_LINE> <INDENT> return json.read(f)
A couple of files describing a dicom template. Makes is easy to save a human readable description together with the template
62598fb47d847024c075c473
class ImageType(object): <NEW_LINE> <INDENT> BASE = 'base' <NEW_LINE> IMPORT = 'import' <NEW_LINE> SNAPSHOT = 'snapshot'
@summary: Types denoting an Image's type
62598fb4be7bc26dc9251eb7
class StoreLoggerFilter(Filter): <NEW_LINE> <INDENT> def __init__(self, storage_url): <NEW_LINE> <INDENT> self.store = storage.create_store(storage_url, storage.REQUEST_LOG_STORE) <NEW_LINE> <DEDENT> def do_filter(self, query): <NEW_LINE> <INDENT> _LOG.debug("Logging query for %s", query) <NEW_LINE> record = { "query": str(query), "time": datetime.datetime.utcnow(), "device": query.device_addr } <NEW_LINE> store.create(record["time"], record)
A filter that will record all hostnames it receives into a store.
62598fb460cbc95b063643fb
class Solution: <NEW_LINE> <INDENT> def count(self,s): <NEW_LINE> <INDENT> t=''; count=0; curr='#' <NEW_LINE> for i in s: <NEW_LINE> <INDENT> if i!=curr: <NEW_LINE> <INDENT> if curr!='#': <NEW_LINE> <INDENT> t+=str(count)+curr <NEW_LINE> <DEDENT> curr=i <NEW_LINE> count=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count+=1 <NEW_LINE> <DEDENT> <DEDENT> t+=str(count)+curr <NEW_LINE> return t <NEW_LINE> <DEDENT> def countAndSay(self, n): <NEW_LINE> <INDENT> s='1' <NEW_LINE> for i in range(2,n+1): <NEW_LINE> <INDENT> s=self.count(s) <NEW_LINE> <DEDENT> return s
@param: n: the nth @return: the nth sequence
62598fb423849d37ff85116a
class ConfigFileParser(object): <NEW_LINE> <INDENT> def get_syntax_description(self): <NEW_LINE> <INDENT> raise NotImplementedError("get_syntax_description(..) not implemented") <NEW_LINE> <DEDENT> def parse(self, stream): <NEW_LINE> <INDENT> raise NotImplementedError("parse(..) not implemented") <NEW_LINE> <DEDENT> def serialize(self, items): <NEW_LINE> <INDENT> raise NotImplementedError("serialize(..) not implemented")
This abstract class can be extended to add support for new config file formats
62598fb4ec188e330fdf8945
@dataclass <NEW_LINE> class Assets(ComplexProperty): <NEW_LINE> <INDENT> alias: type = list <NEW_LINE> properties: dict = field( default_factory=lambda: { "id": { "property": StringProperty, "description": ("Id (Cod. ref.) do ativo (Somente leitura)."), "readOnly": True, }, "name": { "property": StringProperty, "description": ("Nome do ativo (Somente leitura)."), "readOnly": True, }, "label": { "property": StringProperty, "description": ("Etiqueta (única) do ativo (Somente leitura)."), "readOnly": True, }, "serialNumber": { "property": StringProperty, "description": ("Número de série do ativo (Somente leitura)."), "readOnly": True, }, "categoryFull": { "property": ArrayProperty, "description": ( "Lista com os nomes dos níveis da categoria selecionada no ativo " "(Somente leitura)." ), "readOnly": True, }, "categoryFirstLevel": { "property": StringProperty, "description": ( "Nome do primeiro nível da categoria selecionada no ativo (Somente leitura)." ), "readOnly": True, }, "categorySecondLevel": { "property": StringProperty, "description": ( "Nome do segundo nível da categoria selecionada no ativo (Somente leitura)." ), "readOnly": True, }, "categoryThirdLevel": { "property": StringProperty, "description": ( "Nome do terceiro nível da categoria selecionada no ativo (Somente leitura)." ), "readOnly": True, }, "isDeleted": { "property": BooleanProperty, "description": ( "Verdadeiro se o ativo foi deletado do ticket (Somente leitura)." ), "readOnly": True, }, } )
Tickets » Ativos Classe que representa o campo assets.
62598fb4a219f33f346c68bb
@attr.s <NEW_LINE> class DeviceValue(DeviceEvent): <NEW_LINE> <INDENT> attribute = attr.ib() <NEW_LINE> value = attr.ib()
The device poll has read a value.
62598fb430bbd722464699d4
class Face(FrozenClass): <NEW_LINE> <INDENT> def __init__(self, initial_indices=np.array([-1, -1, -1], dtype=int)): <NEW_LINE> <INDENT> self.vertex_indices = np.array(initial_indices, dtype=int) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.vertex_indices)
NOT TO CONFUSE WITH A REAL TRIANGLE (A FACE SAVES ONLY VERTEX INDICES, NO 3D INFORMATION)
62598fb45fcc89381b2661a7
class OpenCompressedTestCase(TestCase): <NEW_LINE> <INDENT> net = False <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> super(OpenCompressedTestCase, cls).setUpClass() <NEW_LINE> cls.base_file = os.path.join(_xml_data_dir, 'article-pyrus.xml') <NEW_LINE> with open(cls.base_file, 'rb') as f: <NEW_LINE> <INDENT> cls.original_content = f.read() <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _get_content(*args): <NEW_LINE> <INDENT> with tools.open_compressed(*args) as f: <NEW_LINE> <INDENT> return f.read() <NEW_LINE> <DEDENT> <DEDENT> def test_open_compressed_normal(self): <NEW_LINE> <INDENT> self.assertEqual(self._get_content(self.base_file), self.original_content) <NEW_LINE> <DEDENT> def test_open_compressed_bz2(self): <NEW_LINE> <INDENT> self.assertEqual(self._get_content(self.base_file + '.bz2'), self.original_content) <NEW_LINE> self.assertEqual(self._get_content(self.base_file + '.bz2', True), self.original_content) <NEW_LINE> <DEDENT> def test_open_compressed_gz(self): <NEW_LINE> <INDENT> self.assertEqual(self._get_content(self.base_file + '.gz'), self.original_content) <NEW_LINE> <DEDENT> def test_open_compressed_7z(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subprocess.Popen(['7za'], stdout=subprocess.PIPE).stdout.close() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> raise unittest.SkipTest('7za not installed') <NEW_LINE> <DEDENT> self.assertEqual(self._get_content(self.base_file + '.7z'), self.original_content) <NEW_LINE> self.assertRaises(OSError, self._get_content, self.base_file + '_invalid.7z', True)
Unit test class for tools. The tests for open_compressed requires that article-pyrus.xml* contain all the same content after extraction. The content itself is not important. The file article-pyrus.xml_invalid.7z is not a valid 7z file and open_compressed will fail extracting it using 7za.
62598fb4aad79263cf42e889
class BaseMiddleware(object): <NEW_LINE> <INDENT> def __init__(self, name, config, worker): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.config = config <NEW_LINE> self.worker = worker <NEW_LINE> <DEDENT> def setup_middleware(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def teardown_middleware(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def handle_consume_inbound(self, message, connector_name): <NEW_LINE> <INDENT> return self.handle_inbound(message, connector_name) <NEW_LINE> <DEDENT> def handle_publish_inbound(self, message, connector_name): <NEW_LINE> <INDENT> return self.handle_inbound(message, connector_name) <NEW_LINE> <DEDENT> def handle_inbound(self, message, connector_name): <NEW_LINE> <INDENT> return message <NEW_LINE> <DEDENT> def handle_consume_outbound(self, message, connector_name): <NEW_LINE> <INDENT> return self.handle_outbound(message, connector_name) <NEW_LINE> <DEDENT> def handle_publish_outbound(self, message, connector_name): <NEW_LINE> <INDENT> return self.handle_outbound(message, connector_name) <NEW_LINE> <DEDENT> def handle_outbound(self, message, connector_name): <NEW_LINE> <INDENT> return message <NEW_LINE> <DEDENT> def handle_consume_event(self, event, connector_name): <NEW_LINE> <INDENT> return self.handle_event(event, connector_name) <NEW_LINE> <DEDENT> def handle_publish_event(self, event, connector_name): <NEW_LINE> <INDENT> return self.handle_event(event, connector_name) <NEW_LINE> <DEDENT> def handle_event(self, event, connector_name): <NEW_LINE> <INDENT> return event <NEW_LINE> <DEDENT> def handle_consume_failure(self, failure, connector_name): <NEW_LINE> <INDENT> return self.handle_failure(failure, connector_name) <NEW_LINE> <DEDENT> def handle_publish_failure(self, failure, connector_name): <NEW_LINE> <INDENT> return self.handle_failure(failure, connector_name) <NEW_LINE> <DEDENT> def handle_failure(self, failure, connector_name): <NEW_LINE> <INDENT> return failure
Common middleware base class. This is a convenient definition of and set of common functionality for middleware classes. You need not subclass this and should not instantiate this directly. The :meth:`__init__` method should take exactly the following options so that your class can be instantiated from configuration in a standard way: :param string name: Name of the middleware. :param dict config: Dictionary of configuraiton items. :type worker: vumi.service.Worker :param worker: Reference to the transport or application being wrapped by this middleware. If you are subclassing this class, you should not override :meth:`__init__`. Custom setup should be done in :meth:`setup_middleware` instead.
62598fb43d592f4c4edbaf77
class EmailAddTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = User.objects.create_user('add', 'add@example.com', '1pass') <NEW_LINE> <DEDENT> def test_email_add(self): <NEW_LINE> <INDENT> retval = self.client.login(username='add', password='1pass') <NEW_LINE> self.assertTrue(retval) <NEW_LINE> args = {'email': 'add1@example.com'} <NEW_LINE> response = self.client.post(reverse('emailmgr_email_add'), args) <NEW_LINE> self.assertContains(response, "email address added", status_code=200) <NEW_LINE> e = EmailAddress.objects.get(email='add1@example.com') <NEW_LINE> self.assertTrue(e) <NEW_LINE> args = {'email': 'add1@example.com', 'follow': True} <NEW_LINE> response = self.client.post(reverse('emailmgr_email_add'), args) <NEW_LINE> self.assertContains(response, "This email address already in use.", status_code=200) <NEW_LINE> args = {'email': 'add2@example.com', 'follow': True} <NEW_LINE> response = self.client.post(reverse('emailmgr_email_add'), args) <NEW_LINE> self.assertNotContains(response, "This email address already in use.", status_code=200) <NEW_LINE> e = EmailAddress.objects.get(email='add2@example.com') <NEW_LINE> self.assertTrue(e) <NEW_LINE> self.assertFalse(e.is_primary) <NEW_LINE> self.assertTrue(e.identifier) <NEW_LINE> e = EmailAddress.objects.all() <NEW_LINE> self.assertTrue(len(e)==3) <NEW_LINE> user = User.objects.create_user('add3', 'add3@example.com', '1pass') <NEW_LINE> e = EmailAddress.objects.all() <NEW_LINE> self.assertTrue(len(e)==4) <NEW_LINE> e = EmailAddress.objects.get(email='add3@example.com') <NEW_LINE> self.assertTrue(e) <NEW_LINE> self.assertTrue(e.is_primary) <NEW_LINE> self.assertTrue(e.is_active) <NEW_LINE> self.assertTrue(e.identifier) <NEW_LINE> e1 = EmailAddress.objects.get(user=user) <NEW_LINE> self.assertTrue(e==e1)
Tests for Django emailmgr -- Add Email
62598fb432920d7e50bc610b
class HiddenLayer: <NEW_LINE> <INDENT> def __init__( self, inp, n_inp, n_out, activation_f=tensor.tanh, w_init_f="xavier_tanh", reg="l2", rand_state=42): <NEW_LINE> <INDENT> if isinstance(w_init_f, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> w_init_f = _W_INIT_METHODS[w_init_f] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError("'w_init_method' must be one in [%s]" % ", ".join(_W_INIT_METHODS.keys())) <NEW_LINE> <DEDENT> <DEDENT> self.input = inp <NEW_LINE> self.w = theano.shared( np.asarray( w_init_f(n_inp, n_out), dtype=self.input.dtype), name="w") <NEW_LINE> if isinstance(reg, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> reg = _REGULARIZATIONS[reg] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise ValueError("'reg' must be one in [%s]" % ", ".join(_REGULARIZATIONS.keys())) <NEW_LINE> <DEDENT> <DEDENT> self.reg = reg(self.w) <NEW_LINE> self.b = theano.shared( np.asarray( _get_rng(rand_state).uniform( low=-0.5, high=0.5, size=(n_out,)), dtype=self.input.dtype), name="b") <NEW_LINE> self.params = [self.w, self.b] <NEW_LINE> linear_output = tensor.dot(self.input, self.w) + self.b <NEW_LINE> self.output = activation_f(linear_output) <NEW_LINE> self.f = theano.function([self.input], self.output)
Hidden Layer for Multi Layer Perceptron.
62598fb463d6d428bbee2864
class KeyBase(object): <NEW_LINE> <INDENT> def __init__(self, options): <NEW_LINE> <INDENT> self.options = options <NEW_LINE> <DEDENT> def get_key(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def initialize(self, ve): <NEW_LINE> <INDENT> raise NotImplementedError
Base class for representing a specific distinguishible kind of a virtual environment.
62598fb47cff6e4e811b5ad6
class CLI: <NEW_LINE> <INDENT> def run(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="Simple one domain web crawler by Jonathan Harden") <NEW_LINE> parser.add_argument( "domain", help="Domain to crawl (will not leave the subdomain specified and will ignore any path part)", ) <NEW_LINE> parser.add_argument( "-v", "--verbose", action="store_true", help="Verbose, print INFO level logging", ) <NEW_LINE> args = parser.parse_args() <NEW_LINE> if args.verbose: <NEW_LINE> <INDENT> logging.basicConfig(level=logging.INFO) <NEW_LINE> <DEDENT> crawler = Crawler(args.domain) <NEW_LINE> crawler.crawl() <NEW_LINE> for page in crawler.site_map.all_pages(): <NEW_LINE> <INDENT> print("Page: {}".format(page.link)) <NEW_LINE> print(" Outbound Links:") <NEW_LINE> for out_link in set(page.out_links): <NEW_LINE> <INDENT> print(" {}".format(out_link)) <NEW_LINE> <DEDENT> print("\n\n")
Coordinating class to run the CLI
62598fb460cbc95b063643fc
class MockCreationError(ValueError): <NEW_LINE> <INDENT> pass
Exception raised when a mock value cannot be generated.
62598fb4091ae35668704cd6
class MultiBoxCoder(): <NEW_LINE> <INDENT> def __init__(self, grids, aspect_ratios, steps, sizes, variance=(0.1, 0.2)): <NEW_LINE> <INDENT> if not len(aspect_ratios) == len(grids): <NEW_LINE> <INDENT> raise ValueError('The length of aspect_ratios is wrong.') <NEW_LINE> <DEDENT> if not len(steps) == len(grids): <NEW_LINE> <INDENT> raise ValueError('The length of steps is wrong.') <NEW_LINE> <DEDENT> if not len(sizes) == len(grids) + 1: <NEW_LINE> <INDENT> raise ValueError('The length of sizes is wrong.') <NEW_LINE> <DEDENT> default_bbox = list() <NEW_LINE> for k, grid in enumerate(grids): <NEW_LINE> <INDENT> for v, u in itertools.product(range(grid), repeat=2): <NEW_LINE> <INDENT> cy = (v + 0.5) * steps[k] <NEW_LINE> cx = (u + 0.5) * steps[k] <NEW_LINE> s = sizes[k] <NEW_LINE> default_bbox.append((cy, cx, s, s)) <NEW_LINE> s = np.sqrt(sizes[k] * sizes[k + 1]) <NEW_LINE> default_bbox.append((cy, cx, s, s)) <NEW_LINE> <DEDENT> <DEDENT> self._default_bbox = np.stack(default_bbox) <NEW_LINE> self._variance = variance <NEW_LINE> <DEDENT> def decode(self, mb_loc, mb_conf, nms_thresh=0.45, score_thresh=0.6): <NEW_LINE> <INDENT> mb_bbox = self._default_bbox.copy() <NEW_LINE> mb_bbox[:, :2] += mb_loc[:, :2] * self._variance[0] * self._default_bbox[:, 2:] <NEW_LINE> mb_bbox[:, 2:] *= np.exp(mb_loc[:, 2:] * self._variance[1]) <NEW_LINE> mb_bbox[:, :2] -= mb_bbox[:, 2:] / 2 <NEW_LINE> mb_bbox[:, 2:] += mb_bbox[:, :2] <NEW_LINE> mb_score = np.exp(mb_conf) <NEW_LINE> mb_score /= mb_score.sum(axis=1, keepdims=True) <NEW_LINE> bbox = list() <NEW_LINE> label = list() <NEW_LINE> score = list() <NEW_LINE> for l in range(mb_conf.shape[1] - 1): <NEW_LINE> <INDENT> bbox_l = mb_bbox <NEW_LINE> score_l = mb_score[:, l + 1] <NEW_LINE> mask = score_l >= score_thresh <NEW_LINE> bbox_l = bbox_l[mask] <NEW_LINE> score_l = score_l[mask] <NEW_LINE> if nms_thresh is not None: <NEW_LINE> <INDENT> indices = non_maximum_suppression( bbox_l, nms_thresh, score_l) <NEW_LINE> bbox_l = bbox_l[indices] <NEW_LINE> score_l = score_l[indices] <NEW_LINE> <DEDENT> bbox.append(bbox_l) <NEW_LINE> label.append(np.array((l,) * len(bbox_l))) <NEW_LINE> score.append(score_l) <NEW_LINE> <DEDENT> bbox = np.vstack(bbox).astype(np.float32) <NEW_LINE> label = np.hstack(label).astype(np.int32) <NEW_LINE> score = np.hstack(score).astype(np.float32) <NEW_LINE> return bbox, label, score
partially taken from src/detector/model/multibox_decoder
62598fb438b623060ffa9154
class InvalidValueError(Exception): <NEW_LINE> <INDENT> pass
An invalid value for a given parameter was used
62598fb44f6381625f19951c
class BaseDirective(Directive): <NEW_LINE> <INDENT> has_content = True <NEW_LINE> final_argument_whitespace = True <NEW_LINE> def _make_header(self, name, title=False): <NEW_LINE> <INDENT> line = "\n" + "-" * len(name) + "\n" <NEW_LINE> if title: <NEW_LINE> <INDENT> return line + name + line <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return name + line <NEW_LINE> <DEDENT> <DEDENT> def _insert_rest(self, text): <NEW_LINE> <INDENT> self.state_machine.insert_input(statemachine.string2lines(text), "") <NEW_LINE> return [] <NEW_LINE> <DEDENT> def _create_mantid_algorithm(self, algorithm_name): <NEW_LINE> <INDENT> from mantid.api import AlgorithmManager <NEW_LINE> alg = AlgorithmManager.createUnmanaged(algorithm_name) <NEW_LINE> alg.initialize() <NEW_LINE> return alg
Contains shared functionality for Mantid custom directives.
62598fb467a9b606de546086
class DidaticosDetailForm(ModelForm): <NEW_LINE> <INDENT> _model_class = Didaticos <NEW_LINE> _include = [Didaticos.creation, Didaticos.Autor, Didaticos.preco, Didaticos.titulo, Didaticos.edicao, Didaticos.descricao, Didaticos.editora]
Form used to show entity details on app's admin page
62598fb4498bea3a75a57bd7
class LikeThisShizzleView(BrowserView): <NEW_LINE> <INDENT> def __call__(self, REQUEST, RESPONSE): <NEW_LINE> <INDENT> registry = getUtility(IRegistry) <NEW_LINE> anonuid = None <NEW_LINE> anonymous_voting = registry.get('cioppino.twothumbs.anonymousvoting', False) <NEW_LINE> portal_state = getMultiAdapter((self.context, self.request), name='plone_portal_state') <NEW_LINE> if portal_state.anonymous(): <NEW_LINE> <INDENT> if not anonymous_voting: <NEW_LINE> <INDENT> return RESPONSE.redirect('%s/login?came_from=%s' % (portal_state.portal_url(), REQUEST['HTTP_REFERER']) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> anonuid = self.request.cookies.get(COOKIENAME, None) <NEW_LINE> if anonuid is None: <NEW_LINE> <INDENT> anonuid = str(uuid4()) <NEW_LINE> RESPONSE.setCookie(COOKIENAME, anonuid) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> form = self.request.form <NEW_LINE> action = None <NEW_LINE> if form.get('form.lovinit', False): <NEW_LINE> <INDENT> action = rate.loveIt(self.context, userid=anonuid) <NEW_LINE> <DEDENT> elif form.get('form.hatedit', False): <NEW_LINE> <INDENT> action = rate.hateIt(self.context, userid=anonuid) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _(u"We don't like ambiguity around here. Check yo self " "before you wreck yo self.") <NEW_LINE> <DEDENT> if not form.get('ajax', False): <NEW_LINE> <INDENT> return RESPONSE.redirect(REQUEST['HTTP_REFERER']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tally = rate.getTally(self.context) <NEW_LINE> tally['action'] = action <NEW_LINE> translate = self._get_translator() <NEW_LINE> tally['msg'] = translate( self._getMessage(action), context=self.request ) <NEW_LINE> tally['close'] = translate( _(u"Close"), context=self.request ) <NEW_LINE> RESPONSE.setHeader('Content-Type', 'application/json; charset=utf-8') <NEW_LINE> response_json = json.dumps(tally) <NEW_LINE> RESPONSE.setHeader('content-length', len(response_json)) <NEW_LINE> return response_json <NEW_LINE> <DEDENT> <DEDENT> def _get_translator(self): <NEW_LINE> <INDENT> td = queryUtility(ITranslationDomain, name='cioppino.twothumbs') <NEW_LINE> if td: <NEW_LINE> <INDENT> return td.translate <NEW_LINE> <DEDENT> return nulltranslate <NEW_LINE> <DEDENT> def _getMessage(self, action): <NEW_LINE> <INDENT> if (action == 'like'): <NEW_LINE> <INDENT> return _(u"You liked this. Thanks for the feedback!") <NEW_LINE> <DEDENT> elif (action == 'dislike'): <NEW_LINE> <INDENT> return _(u"You dislike this. Thanks for the feedback!") <NEW_LINE> <DEDENT> elif (action == 'undo'): <NEW_LINE> <INDENT> return _(u"Your vote has been removed.")
Update the like/unlike status of a product via AJAX
62598fb4ff9c53063f51a705
class WeConnectApiTestBase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.client = self.app.test_client() <NEW_LINE> self.prefix = '/api/v2/' <NEW_LINE> self.users = { 'one': {"first_name": "jack", "last_name": "dan", "username": "jackdan", "password": "password"}, 'two': {"first_name": "jim", "last_name": "dan", "username": "jimdan", "password": "password"}, 'three': {"first_name": "eli", "last_name": "rwt", "username": "eli", "password": "password"}, 'four': {"first_name": "elijah", "last_name": "rwoth", "username": "elijahrwoth", "password": "password"}, 'bad': {"first_name": 'first_namefirst_namefirst_namefirst_namefirst_namefirst_namefirst_name', "last_name": '', "username": '', "password": ''} } <NEW_LINE> self.user_login = { 'one': {"username": "jackdan", "password": "password"}, 'two': {"username": "jimdan", "password": "password"}, 'three': {"username": "eli", "password": "password"}, 'four': {"username": "elijahrwoth", "password": "password"}, 'bad': {"username": '', "password": ''}, 'bad1': {"username": "eli", "password": "passrd"}, 'bad2': {"username": "elite", "password": "password"} } <NEW_LINE> self.businesses = { 'one': {"name": "Bondo", "description": "yummy", "category": "Eateries", "location": "Kabale", "photo": "photo"}, 'one_edit': {"name": "Bondo", "description": "yummy foods and deliveries", "category": "Eateries", "location": "Kabale", "photo": "photo"}, 'one_edit1': {"name": "Boondocks", "description": "yummy foods and deliveries", "category": "Eateries", "location": "Kabale", "photo": "photo"}, 'two': {"name": "", "description": "", "category": "", "location": "", "photo": ""}, 'three': {"name": "Boondocks", "description": "your favorite movies", "category": "Entertainment", "location": "Kamwenge", "photo": "photo"}, } <NEW_LINE> self.reviews = { 'one': {"name": "extra game", "description": "i was given meat yo"}, 'two': {"name": "", "description": ""} } <NEW_LINE> with self.app.app_context(): <NEW_LINE> <INDENT> db.session.close() <NEW_LINE> db.drop_all() <NEW_LINE> db.create_all() <NEW_LINE> <DEDENT> self.client.post(self.prefix + 'auth/register', content_type='application/json', data=json.dumps(self.users['one'])) <NEW_LINE> login = self.client.post(self.prefix + 'auth/login', content_type='application/json', data=json.dumps(self.user_login['one'])) <NEW_LINE> login_data = json.loads(login.data.decode()) <NEW_LINE> self.access_token = login_data["access_token"] <NEW_LINE> <DEDENT> def test_api_hello(self): <NEW_LINE> <INDENT> response = self.client.get(self.prefix) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> with self.app.app_context(): <NEW_LINE> <INDENT> db.session.close() <NEW_LINE> db.drop_all()
Test user api logic
62598fb43d592f4c4edbaf78
class EnvironmentWrapper(Environment): <NEW_LINE> <INDENT> def __init__(self, base_environment): <NEW_LINE> <INDENT> self._base = base_environment <NEW_LINE> self._orig_env = base_environment._orig_env <NEW_LINE> <DEDENT> @property <NEW_LINE> def dt(self): <NEW_LINE> <INDENT> return self._base.dt <NEW_LINE> <DEDENT> @property <NEW_LINE> def monitor(self): <NEW_LINE> <INDENT> return self._base.monitor <NEW_LINE> <DEDENT> @property <NEW_LINE> def dimensions(self): <NEW_LINE> <INDENT> return self._base.dimensions <NEW_LINE> <DEDENT> @property <NEW_LINE> def observation_info(self): <NEW_LINE> <INDENT> return self._base.observation_info <NEW_LINE> <DEDENT> @property <NEW_LINE> def action_info(self): <NEW_LINE> <INDENT> return self._base.action_info <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> return self._base.render() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> return self._base.reset() <NEW_LINE> <DEDENT> def step(self, a): <NEW_LINE> <INDENT> return self._base.step(a) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> return self._base.close() <NEW_LINE> <DEDENT> @property <NEW_LINE> def action_limits(self): <NEW_LINE> <INDENT> return [self._base.action_space.low, self._base.action_space.high] <NEW_LINE> <DEDENT> @property <NEW_LINE> def obs_limits(self): <NEW_LINE> <INDENT> return [self._base.observation_space.low, self._base.observation_space.high] <NEW_LINE> <DEDENT> @property <NEW_LINE> def env_state(self): <NEW_LINE> <INDENT> return self._base.env_state <NEW_LINE> <DEDENT> def set_state(self, qpos, qvalue): <NEW_LINE> <INDENT> return self._base.set_state(qpos, qvalue) <NEW_LINE> <DEDENT> def rng(self): <NEW_LINE> <INDENT> return self._base.rng() <NEW_LINE> <DEDENT> def set_rng(self, value): <NEW_LINE> <INDENT> self._base.set_rng(value) <NEW_LINE> return
A base class for environment wrappers which can alter the behavior of a given base environment. The base implementation maintains the behavior of the base environment.
62598fb45fdd1c0f98e5e046
class ModelGridRow(BaseNotifier): <NEW_LINE> <INDENT> def __init__(self, model): <NEW_LINE> <INDENT> super(ModelGridRow, self).__init__() <NEW_LINE> self.model = model <NEW_LINE> self.value = self.model.get_value() <NEW_LINE> self.short_value = self.value[0:100] <NEW_LINE> self.doc = '' <NEW_LINE> self._row_selected = False <NEW_LINE> self._doc_filled = False <NEW_LINE> self.is_visible = True <NEW_LINE> <DEDENT> def set_doc(self): <NEW_LINE> <INDENT> self.doc = self.model.get_doc() <NEW_LINE> self.NotifyPropertyChanged("doc")
base subview item for the datagrid holds the value and doc given by model and binds the model datas
62598fb457b8e32f52508178
class SRComp: <NEW_LINE> <INDENT> def __init__(self, root: Union[str, Path]) -> None: <NEW_LINE> <INDENT> self.root = Path(root) <NEW_LINE> self.state = check_output( ('git', 'rev-parse', 'HEAD'), universal_newlines=True, cwd=str(self.root), ).strip() <NEW_LINE> self.teams = teams.load_teams(self.root / 'teams.yaml') <NEW_LINE> self.arenas = arenas.load_arenas(self.root / 'arenas.yaml') <NEW_LINE> self.corners = arenas.load_corners(self.root / 'arenas.yaml') <NEW_LINE> self.num_teams_per_arena = len(self.corners) <NEW_LINE> scorer = load_scorer(self.root) <NEW_LINE> self.scores = scores.Scores( self.root, self.teams.keys(), scorer, self.num_teams_per_arena, ) <NEW_LINE> self.schedule = matches.MatchSchedule.create( self.root / 'schedule.yaml', self.root / 'league.yaml', self.scores, self.arenas, self.num_teams_per_arena, self.teams, ) <NEW_LINE> self.timezone = self.schedule.timezone <NEW_LINE> self.awards = compute_awards( self.scores, self.schedule.final_match, self.teams, self.root / 'awards.yaml', ) <NEW_LINE> self.venue = venue.Venue( self.teams.keys(), self.root / 'layout.yaml', self.root / 'shepherding.yaml', ) <NEW_LINE> self.venue.check_staging_times(self.schedule.staging_times)
A class containing all the various parts of a competition. :param Path root: The root path of the ``compstate`` repo.
62598fb4adb09d7d5dc0a644
class QueryWrapper(object): <NEW_LINE> <INDENT> def __init__(self, sql, params): <NEW_LINE> <INDENT> self.data = sql, list(params) <NEW_LINE> <DEDENT> def asSql(self, qn=None, connection=None): <NEW_LINE> <INDENT> return self.data
A type that indicates the contents are an SQL fragment and the associate parameters. Can be used to pass opaque data to a where-clause, for example.
62598fb48a43f66fc4bf2232
class AsyncUpcomingLaunch(UpcomingLaunch, BaseAsync): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> async def next(cls, network: Network, num: int): <NEW_LINE> <INDENT> return await cls.fetch(network)
A class representing an upcoming launch object.
62598fb4236d856c2adc949b
class SpotifyPlaylist(Resource): <NEW_LINE> <INDENT> __tablename__ = 'spotify_Playlists' <NEW_LINE> owner_uri = Column('owner_uri', String) <NEW_LINE> raw_uri = Column('raw_uri', String) <NEW_LINE> snapshot_id = Column('snapshot_id', String) <NEW_LINE> total_tracks = Column('total_tracks', Integer) <NEW_LINE> followers = Column('followers', Integer) <NEW_LINE> collaborative = Column('collaborative', Boolean) <NEW_LINE> description = Column('description', String) <NEW_LINE> public = Column('public', Boolean) <NEW_LINE> images = Column('images', String) <NEW_LINE> href = Column('href', String) <NEW_LINE> external_urls = Column('external_urls', String) <NEW_LINE> def __init__(self, jsondata): <NEW_LINE> <INDENT> d = jsondata <NEW_LINE> super().__init__( uri='spotify:playlist:{}'.format(d.get('id')), name=d.get('name'), id=d.get('id'), type=d.get('type'), provider='spotify', owner_uri=d.get('owner', {}).get('uri'), raw_uri=d.get('uri'), snapshot_id=d.get('snapshot_id'), total_tracks=d.get('tracks', {}).get('total'), public=d.get('public'), collaborative=d.get('collaborative'), images=json.dumps(d.get('images')), href=d.get('href'), external_urls=d.get('external_urls', {}).get('spotify'), followers=d.get('followers', {}).get('total'), description=d.get('description'), )
[ Playlist resources in Spotify ]
62598fb4ec188e330fdf8947
class UserGrantedAssetsApi(RootOrgViewMixin, ListAPIView): <NEW_LINE> <INDENT> permission_classes = (IsOrgAdminOrAppUser,) <NEW_LINE> serializer_class = AssetGrantedSerializer <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> user_id = self.kwargs.get('pk', '') <NEW_LINE> queryset = [] <NEW_LINE> if user_id: <NEW_LINE> <INDENT> user = get_object_or_404(User, id=user_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user = self.request.user <NEW_LINE> <DEDENT> util = AssetPermissionUtil(user) <NEW_LINE> for k, v in util.get_assets().items(): <NEW_LINE> <INDENT> system_users_granted = [s for s in v if s.protocol == k.protocol] <NEW_LINE> k.system_users_granted = system_users_granted <NEW_LINE> queryset.append(k) <NEW_LINE> <DEDENT> return queryset <NEW_LINE> <DEDENT> def get_permissions(self): <NEW_LINE> <INDENT> if self.kwargs.get('pk') is None: <NEW_LINE> <INDENT> self.permission_classes = (IsValidUser,) <NEW_LINE> <DEDENT> return super().get_permissions()
用户授权的所有资产
62598fb432920d7e50bc610c
class NUSimEnterprise(NUSimResource): <NEW_LINE> <INDENT> __vspk_class__ = vsdk.NUEnterprise <NEW_LINE> __unique_fields__ = ['externalID'] <NEW_LINE> __mandatory_fields__ = ['name'] <NEW_LINE> __default_fields__ = { 'VNFManagementEnabled': False, 'dictionaryVersion': 2, 'virtualFirewallRulesEnabled': False, 'flowCollectionEnabled': 'DISABLED', 'enableApplicationPerformanceManagement': False } <NEW_LINE> __get_parents__ = ['enterpriseprofile', 'me'] <NEW_LINE> __create_parents__ = ['me'] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(NUSimEnterprise, self).__init__()
Represents a Enterprise Notes: Definition of the enterprise object. This is the top level object that represents an enterprise.
62598fb4a219f33f346c68bd
class PosteriorMean(Mean): <NEW_LINE> <INDENT> def __init__(self, m_i, m_z, k_zi, z, K_z, y): <NEW_LINE> <INDENT> self.m_i = m_i <NEW_LINE> self.m_z = m_z <NEW_LINE> self.k_zi = k_zi <NEW_LINE> self.z = z <NEW_LINE> self.K_z = convert(K_z, AbstractMatrix) <NEW_LINE> self.y = B.uprank(y) <NEW_LINE> <DEDENT> @_dispatch <NEW_LINE> def __call__(self, x): <NEW_LINE> <INDENT> diff = B.subtract(self.y, self.m_z(self.z)) <NEW_LINE> return B.add(self.m_i(x), B.iqf(self.K_z, self.k_zi(self.z, x), diff))
Posterior mean. Args: m_i (:class:`.mean.Mean`): Mean of process corresponding to the input. m_z (:class:`.mean.Mean`): Mean of process corresponding to the data. k_zi (:class:`.kernel.Kernel`): Kernel between processes corresponding to the data and the input respectively. z (input): Locations of data. K_z (matrix): Kernel matrix of data. y (vector): Observations to condition on.
62598fb430bbd722464699d5
class FallaAutenticacion(Falla): <NEW_LINE> <INDENT> def __init__(self, resultado, prompt): <NEW_LINE> <INDENT> self.resultado = resultado <NEW_LINE> self.prompt = prompt <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> err = "La contraseña enviada para solicitar {!r} fue rechazada." <NEW_LINE> return err.format(self.prompt)
Una falla de autenticación, p. Ej. debido a contraseña ``sudo`` incorrecta. .. note:: Los objetos `.Resultado` adjuntos a estas excepciones generalmente carecen de información de código de salida, ya que el comando nunca se ejecutó por completo; en su lugar, se generó la excepción. .. versionadded:: 1.0
62598fb43539df3088ecc36b
class LuvColor(IlluminantMixin, ColorBase): <NEW_LINE> <INDENT> VALUES = ['luv_l', 'luv_u', 'luv_v'] <NEW_LINE> def __init__(self, luv_l, luv_u, luv_v, observer='2', illuminant='d50'): <NEW_LINE> <INDENT> super(LuvColor, self).__init__() <NEW_LINE> self.luv_l = float(luv_l) <NEW_LINE> self.luv_u = float(luv_u) <NEW_LINE> self.luv_v = float(luv_v) <NEW_LINE> self.set_observer(observer) <NEW_LINE> self.set_illuminant(illuminant)
Represents an Luv color.
62598fb4be8e80087fbbf11f
class TestingReport(View): <NEW_LINE> <INDENT> testing_report_views = { None: TestingReportByCaseRunTester, 'per_build_report': TestingReportByCaseRunTester, 'per_priority_report': TestingReportByCasePriority, 'runs_with_rates_per_plan_tag': TestingReportByPlanTags, 'per_plan_tag_report': TestingReportByPlanTagsDetail, 'runs_with_rates_per_plan_build': TestingReportByPlanBuild, 'per_plan_build_report': TestingReportByPlanBuildDetail, } <NEW_LINE> def _get_testing_report_view(self, report_type): <NEW_LINE> <INDENT> view_class = self.testing_report_views.get(report_type, None) <NEW_LINE> if view_class is None: <NEW_LINE> <INDENT> return self.testing_report_views[None].as_view() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return view_class.as_view() <NEW_LINE> <DEDENT> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> report_type = request.GET.get('report_type', None) <NEW_LINE> view = self._get_testing_report_view(report_type) <NEW_LINE> return view(request, *args, **kwargs)
Dispatch testing report according to report type
62598fb44a966d76dd5eef90
class MetaCycle(Cycle): <NEW_LINE> <INDENT> def __init__(self, *class_argument_pair: tuple): <NEW_LINE> <INDENT> super().__init__(class_argument_pair) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "Meta{}".format(super().__repr__()) <NEW_LINE> <DEDENT> def __next__(self) -> InfIt: <NEW_LINE> <INDENT> cls, arguments = super().__next__() <NEW_LINE> return cls(*arguments)
Infinite cycle that dynamically builds new InfIt objects when it get called.
62598fb4851cf427c66b836f
class TestCase(unittest.TestCase): <NEW_LINE> <INDENT> def _test_expected_links(self, graph, expected_links): <NEW_LINE> <INDENT> found = 0 <NEW_LINE> for link in graph['links']: <NEW_LINE> <INDENT> tuple_link = (link['source'], link['target']) <NEW_LINE> for expected_link in expected_links: <NEW_LINE> <INDENT> if set(tuple_link) == set(expected_link): <NEW_LINE> <INDENT> found += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.assertEqual(found, len(expected_links))
netdiff TestCase
62598fb401c39578d7f12e32
class SmartMeterTexasSensor(CoordinatorEntity, RestoreEntity, SensorEntity): <NEW_LINE> <INDENT> _attr_unit_of_measurement = ENERGY_KILO_WATT_HOUR <NEW_LINE> def __init__(self, meter: Meter, coordinator: DataUpdateCoordinator) -> None: <NEW_LINE> <INDENT> super().__init__(coordinator) <NEW_LINE> self.meter = meter <NEW_LINE> self._state = None <NEW_LINE> self._available = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return f"{ELECTRIC_METER} {self.meter.meter}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return f"{self.meter.esiid}_{self.meter.meter}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> return self._available <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self): <NEW_LINE> <INDENT> attributes = { METER_NUMBER: self.meter.meter, ESIID: self.meter.esiid, CONF_ADDRESS: self.meter.address, } <NEW_LINE> return attributes <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _state_update(self): <NEW_LINE> <INDENT> self._available = self.coordinator.last_update_success <NEW_LINE> if self._available: <NEW_LINE> <INDENT> self._state = self.meter.reading <NEW_LINE> <DEDENT> self.async_write_ha_state() <NEW_LINE> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> self.async_on_remove(self.coordinator.async_add_listener(self._state_update)) <NEW_LINE> if self.coordinator.last_update_success: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> last_state = await self.async_get_last_state() <NEW_LINE> if last_state: <NEW_LINE> <INDENT> self._state = last_state.state <NEW_LINE> self._available = True
Representation of an Smart Meter Texas sensor.
62598fb44c3428357761a373
class Interface(_Item): <NEW_LINE> <INDENT> def __init__(self, name=None): <NEW_LINE> <INDENT> super(Interface, self).__init__(name) <NEW_LINE> self.addresses = []
A network interface
62598fb45166f23b2e243494
class AdditiveGaussNoise(object): <NEW_LINE> <INDENT> def __init__(self, mean, std): <NEW_LINE> <INDENT> self.mean = mean <NEW_LINE> self.std = std <NEW_LINE> <DEDENT> def corrupt(self, data): <NEW_LINE> <INDENT> return data + self.mean + numx.random.standard_normal(data.shape) * self.std
An object that corrupts data by adding Gauss noise.
62598fb463d6d428bbee2866
class Think(System): <NEW_LINE> <INDENT> entity_filters = { 'constant': and_filter([ CharacterController, ConstantCharacterAI, ]), 'brownian_walker': and_filter([ CharacterController, BrownianWalkerAI, ]), } <NEW_LINE> def update(self, entities_by_filter): <NEW_LINE> <INDENT> for entity in entities_by_filter['constant']: <NEW_LINE> <INDENT> ai = entity[ConstantCharacterAI] <NEW_LINE> character = entity[CharacterController] <NEW_LINE> character.move = ai.move <NEW_LINE> character.heading = ai.heading <NEW_LINE> character.pitch = ai.pitch <NEW_LINE> character.sprints = ai.sprints <NEW_LINE> character.crouches = ai.crouches <NEW_LINE> character.jumps = ai.jumps <NEW_LINE> <DEDENT> for entity in entities_by_filter['brownian_walker']: <NEW_LINE> <INDENT> ai = entity[BrownianWalkerAI] <NEW_LINE> character = entity[CharacterController] <NEW_LINE> character.move = Vec3( ai.move.x * random.random(), ai.move.y * random.random(), ai.move.z * random.random(), ) <NEW_LINE> ai.heading += ai.heading_jitter * (random.random() - 0.5) * 2 <NEW_LINE> if ai.heading > 1: <NEW_LINE> <INDENT> ai.heading -= 2 <NEW_LINE> <DEDENT> elif ai.heading < -1: <NEW_LINE> <INDENT> ai.heading += 2 <NEW_LINE> <DEDENT> character.heading = ai.heading <NEW_LINE> character.pitch = 0 <NEW_LINE> character.sprints = 0 <NEW_LINE> character.crouches = 0 <NEW_LINE> character.jumps = 0
A System updating AI components.
62598fb467a9b606de546089
class Student: <NEW_LINE> <INDENT> def __init__(self, first_name, second_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.second_name = second_name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def to_json(self, attrs=None): <NEW_LINE> <INDENT> return self.__dict__
Student class
62598fb4498bea3a75a57bd9
class NetInfo(Monitor): <NEW_LINE> <INDENT> _module = "NET" <NEW_LINE> _purpose = "INFO" <NEW_LINE> _option = ";-l;-k" <NEW_LINE> def __init__(self, user=None): <NEW_LINE> <INDENT> Monitor.__init__(self, user) <NEW_LINE> self.__cmd = "ethtool" <NEW_LINE> <DEDENT> def _get(self, para): <NEW_LINE> <INDENT> opts = self._getopt() <NEW_LINE> outputs = "" <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output = subprocess.check_output("{cmd} {opt} {para}".format( cmd=self.__cmd, opt=next(opts), para=para).split()) <NEW_LINE> outputs += output.decode() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return outputs
To collect the nic config info
62598fb426068e7796d4ca10
class common_cleanup(aetest.CommonCleanup): <NEW_LINE> <INDENT> @aetest.subsection <NEW_LINE> def disconnect(self, steps, dist1): <NEW_LINE> <INDENT> with steps.start('Disconnecting from dist1'): <NEW_LINE> <INDENT> dist1.disconnect()
disconnect from ios routers
62598fb444b2445a339b69cf
class ApplicationGatewayProbe(SubResource): <NEW_LINE> <INDENT> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'protocol': {'key': 'properties.protocol', 'type': 'str'}, 'host': {'key': 'properties.host', 'type': 'str'}, 'path': {'key': 'properties.path', 'type': 'str'}, 'interval': {'key': 'properties.interval', 'type': 'int'}, 'timeout': {'key': 'properties.timeout', 'type': 'int'}, 'unhealthy_threshold': {'key': 'properties.unhealthyThreshold', 'type': 'int'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, etag: Optional[str] = None, protocol: Optional[Union[str, "ApplicationGatewayProtocol"]] = None, host: Optional[str] = None, path: Optional[str] = None, interval: Optional[int] = None, timeout: Optional[int] = None, unhealthy_threshold: Optional[int] = None, provisioning_state: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayProbe, self).__init__(id=id, **kwargs) <NEW_LINE> self.name = name <NEW_LINE> self.etag = etag <NEW_LINE> self.protocol = protocol <NEW_LINE> self.host = host <NEW_LINE> self.path = path <NEW_LINE> self.interval = interval <NEW_LINE> self.timeout = timeout <NEW_LINE> self.unhealthy_threshold = unhealthy_threshold <NEW_LINE> self.provisioning_state = provisioning_state
Probe of the application gateway. :param id: Resource ID. :type id: str :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str :param protocol: Protocol. Possible values are: 'Http' and 'Https'. Possible values include: "Http", "Https". :type protocol: str or ~azure.mgmt.network.v2016_09_01.models.ApplicationGatewayProtocol :param host: Host name to send the probe to. :type host: str :param path: Relative path of probe. Valid path starts from '/'. Probe is sent to :code:`<Protocol>`://:code:`<host>`::code:`<port>`:code:`<path>`. :type path: str :param interval: The probing interval in seconds. This is the time interval between two consecutive probes. Acceptable values are from 1 second to 86400 seconds. :type interval: int :param timeout: the probe timeout in seconds. Probe marked as failed if valid response is not received with this timeout period. Acceptable values are from 1 second to 86400 seconds. :type timeout: int :param unhealthy_threshold: The probe retry count. Backend server is marked down after consecutive probe failure count reaches UnhealthyThreshold. Acceptable values are from 1 second to 20. :type unhealthy_threshold: int :param provisioning_state: Provisioning state of the backend http settings resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str
62598fb4adb09d7d5dc0a646
class TestGatewayAppConfig(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.environ = dict(os.environ) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> os.environ = self.environ <NEW_LINE> <DEDENT> def test_config_env_vars(self): <NEW_LINE> <INDENT> os.environ['KG_PORT'] = '1234' <NEW_LINE> os.environ['KG_PORT_RETRIES'] = '4321' <NEW_LINE> os.environ['KG_IP'] = '1.1.1.1' <NEW_LINE> os.environ['KG_AUTH_TOKEN'] = 'fake-token' <NEW_LINE> os.environ['KG_ALLOW_CREDENTIALS'] = 'true' <NEW_LINE> os.environ['KG_ALLOW_HEADERS'] = 'Authorization' <NEW_LINE> os.environ['KG_ALLOW_METHODS'] = 'GET' <NEW_LINE> os.environ['KG_ALLOW_ORIGIN'] = '*' <NEW_LINE> os.environ['KG_EXPOSE_HEADERS'] = 'X-Fake-Header' <NEW_LINE> os.environ['KG_MAX_AGE'] = '5' <NEW_LINE> os.environ['KG_BASE_URL'] = '/fake/path' <NEW_LINE> os.environ['KG_MAX_KERNELS'] = '1' <NEW_LINE> os.environ['KG_SEED_URI'] = 'fake-notebook.ipynb' <NEW_LINE> os.environ['KG_PRESPAWN_COUNT'] = '1' <NEW_LINE> os.environ['KG_FORCE_KERNEL_NAME'] = 'fake_kernel_forced' <NEW_LINE> os.environ['KG_DEFAULT_KERNEL_NAME'] = 'fake_kernel' <NEW_LINE> app = KernelGatewayApp() <NEW_LINE> self.assertEqual(app.port, 1234) <NEW_LINE> self.assertEqual(app.port_retries, 4321) <NEW_LINE> self.assertEqual(app.ip, '1.1.1.1') <NEW_LINE> self.assertEqual(app.auth_token, 'fake-token') <NEW_LINE> self.assertEqual(app.allow_credentials, 'true') <NEW_LINE> self.assertEqual(app.allow_headers, 'Authorization') <NEW_LINE> self.assertEqual(app.allow_methods, 'GET') <NEW_LINE> self.assertEqual(app.allow_origin, '*') <NEW_LINE> self.assertEqual(app.expose_headers, 'X-Fake-Header') <NEW_LINE> self.assertEqual(app.max_age, '5') <NEW_LINE> self.assertEqual(app.base_url, '/fake/path') <NEW_LINE> self.assertEqual(app.max_kernels, 1) <NEW_LINE> self.assertEqual(app.seed_uri, 'fake-notebook.ipynb') <NEW_LINE> self.assertEqual(app.prespawn_count, 1) <NEW_LINE> self.assertEqual(app.default_kernel_name, 'fake_kernel') <NEW_LINE> self.assertEqual(app.force_kernel_name, 'fake_kernel_forced')
Tests configuration of the gateway app.
62598fb4009cb60464d015db
class SyncGit: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.repo = Repo(settings.GITHUB_PAGE_DIR) <NEW_LINE> <DEDENT> def sync(self, add_all=True, commit='add post', name='origin'): <NEW_LINE> <INDENT> if not settings.GITHUB_PAGE: <NEW_LINE> <INDENT> return False, 'Do not enable GITHUB_PAGE' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.add(add_all) <NEW_LINE> self.commit(commit) <NEW_LINE> self.push(name) <NEW_LINE> return True, 'Github page synced Successful' <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(str(e)) <NEW_LINE> return False, str(e) <NEW_LINE> <DEDENT> <DEDENT> def add(self, add_all=True): <NEW_LINE> <INDENT> self.repo.git.add(A=add_all) <NEW_LINE> <DEDENT> def commit(self, commit): <NEW_LINE> <INDENT> self.repo.index.commit(commit) <NEW_LINE> <DEDENT> def push(self, name='origin'): <NEW_LINE> <INDENT> self.repo.remote(name=name).push()
Git上传, 需要有对应setting里的项目目录, 且可以经过ssh上传github
62598fb4be7bc26dc9251eb9
@widgets.register <NEW_LINE> class ImageGL(bqplot.Mark): <NEW_LINE> <INDENT> _view_name = Unicode('ImageGLView').tag(sync=True) <NEW_LINE> _model_name = Unicode('ImageGLModel').tag(sync=True) <NEW_LINE> _view_module = Unicode('bqplot-image-gl').tag(sync=True) <NEW_LINE> _model_module = Unicode('bqplot-image-gl').tag(sync=True) <NEW_LINE> _view_module_version = Unicode('^' + __version__).tag(sync=True) <NEW_LINE> _model_module_version = Unicode('^' + __version__).tag(sync=True) <NEW_LINE> image = Array().tag(sync=True, scaled=True, rtype='Color', atype='bqplot.ColorAxis', **array_serialization) <NEW_LINE> interpolation = Unicode('nearest', allow_none=True).tag(sync=True) <NEW_LINE> opacity = Float(1.0).tag(sync=True) <NEW_LINE> x = Array(default_value=(0, 1)).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization) .valid(array_squeeze, shape(2)) <NEW_LINE> y = Array(default_value=(0, 1)).tag(sync=True, scaled=True, rtype='Number', atype='bqplot.Axis', **array_serialization) .valid(array_squeeze, shape(2)) <NEW_LINE> scales_metadata = Dict({ 'x': {'orientation': 'horizontal', 'dimension': 'x'}, 'y': {'orientation': 'vertical', 'dimension': 'y'}, 'image': {'dimension': 'color'}, }).tag(sync=True)
An example widget.
62598fb40fa83653e46f4f99
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> async def async_step_system(self, user_input=None): <NEW_LINE> <INDENT> await self.async_set_unique_id(DOMAIN) <NEW_LINE> self._abort_if_unique_id_configured() <NEW_LINE> return self.async_create_entry(title="Supervisor", data={})
Handle a config flow for Home Assistant Supervisor.
62598fb4cc40096d6161a236
class NaiveBayes(Classifier): <NEW_LINE> <INDENT> def __init__(self, getfeatures, filename=None): <NEW_LINE> <INDENT> return super(NaiveBayes, self).__init__(getfeatures, filename) <NEW_LINE> <DEDENT> def docprob(self, item, cat): <NEW_LINE> <INDENT> features = self.getfeatures(item) <NEW_LINE> p = 1 <NEW_LINE> for f in features: <NEW_LINE> <INDENT> p *= self.weightedprob(f, cat, self.fprob) <NEW_LINE> <DEDENT> return p <NEW_LINE> <DEDENT> def prob(self, item, cat): <NEW_LINE> <INDENT> catprob = self.catcount(cat) / self.totalcount() <NEW_LINE> docprob = self.docprob(item, cat) <NEW_LINE> return docprob * catprob
Subclass of Classifier for calculating the entire document probability.
62598fb4851cf427c66b8370
@unique <NEW_LINE> class Mp4VideoMetrics(Enum): <NEW_LINE> <INDENT> LAP_COUNTER = 'lap_counter' <NEW_LINE> COMPLETION_PERCENTAGE = 'completion_percentage' <NEW_LINE> RESET_COUNTER = 'reset_counter' <NEW_LINE> CRASH_COUNTER = 'crash_counter' <NEW_LINE> THROTTLE = 'throttle' <NEW_LINE> STEERING = 'steering' <NEW_LINE> BEST_LAP_TIME = 'best_lap_time' <NEW_LINE> TOTAL_EVALUATION_TIME = 'total_evaluation_time' <NEW_LINE> DONE = 'done' <NEW_LINE> @classmethod <NEW_LINE> def get_empty_dict(cls): <NEW_LINE> <INDENT> empty_dict = dict() <NEW_LINE> for enum_map in cls._value2member_map_.values(): <NEW_LINE> <INDENT> empty_dict[enum_map.value] = None <NEW_LINE> <DEDENT> return empty_dict
This enum is used for gathering the video metrics displayed on the mp4
62598fb4a79ad1619776a125
class CustomerFollowUp(models.Model): <NEW_LINE> <INDENT> customer = models.ForeignKey(to='Customer', verbose_name='客户名') <NEW_LINE> content = models.TextField(verbose_name='跟进内容') <NEW_LINE> consultant = models.ForeignKey(to='UserProfile', verbose_name='咨询顾问') <NEW_LINE> date = models.DateTimeField(auto_now_add=True, verbose_name='咨询日期') <NEW_LINE> intention_choices = ( (0, '两周内报名'), (1, '一个月内报名'), (2, '近期无报名计划'), (3, '无意向'), (4, '已报名'), (5, '已拉黑'), ) <NEW_LINE> intention = models.SmallIntegerField(choices=intention_choices, verbose_name='客户意向') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '{} : {}'.format(self.customer.qq, self.intention) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = '客户跟进表'
客户跟进表
62598fb4dc8b845886d53671
class Yokoshi(TimeStampedModel): <NEW_LINE> <INDENT> OMITAMA_LEVEL = Choices(('none', _('none_omitama_level')), ('basic', _('basic_omitama_level')), ('intermediate', _('intermediate_omitama_level')), ('advanced', _('advanced_omitama_level'))) <NEW_LINE> user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, db_index=True, verbose_name=_('Yokoshi|user')) <NEW_LINE> complete_name = models.CharField(max_length=500, db_index=True, verbose_name=_('Yokoshi|complete_name')) <NEW_LINE> last_name = models.CharField(null=True, max_length=200, db_index=True, verbose_name=_('Yokoshi|last_name')) <NEW_LINE> first_name = models.CharField(null=True, max_length=300, db_index=True, verbose_name=_('Yokoshi|first_name')) <NEW_LINE> phonetic_name = models.CharField(max_length=500, null=True, blank=True, db_index=True, editable=False, verbose_name=('Yokoshi|phonetic_name')) <NEW_LINE> email = models.EmailField(null=True, blank=True, verbose_name=_('Yokoshi|email')) <NEW_LINE> phone = models.CharField(max_length=40, null=True, blank=True, verbose_name=_('Yokoshi|phone')) <NEW_LINE> additional_information = models.TextField(max_length=30000, null=True, blank=True, verbose_name=_('Yokoshi|additional_information')) <NEW_LINE> birthday = models.DateField(null=True, blank=True, verbose_name=_('Yokoshi|birthday')) <NEW_LINE> is_inactive = models.BooleanField(default=False, verbose_name=_('Yokoshi|is_inactive')) <NEW_LINE> seminary_number = models.CharField(max_length=30, null=True, blank=True, verbose_name=_('Yokoshi|seminary_number')) <NEW_LINE> han = models.ForeignKey(Han, null=True, blank=True, db_index=True, verbose_name=_('Yokoshi|han')) <NEW_LINE> is_mtai = models.BooleanField(default=False, verbose_name=_('Yokoshi|is_mtai')) <NEW_LINE> is_ossuewanin = models.BooleanField(default=False, verbose_name=_('Yokoshi|is_ossuewanin')) <NEW_LINE> is_mikumite = models.BooleanField(default=False, verbose_name=_('Yokoshi|is_mikumite')) <NEW_LINE> omitama_level = models.CharField(choices=OMITAMA_LEVEL, default=OMITAMA_LEVEL.none, max_length=50) <NEW_LINE> indication = models.ForeignKey("Yokoshi", null=True, blank=True, db_index=True, verbose_name=_('Yokoshi|indication')) <NEW_LINE> last_registration_update = models.DateField(null=True, blank=True, verbose_name=_('Yokoshi|last_registration_update')) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('yokoshi') <NEW_LINE> verbose_name_plural = _('yokoshis') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'%s' % self.complete_name <NEW_LINE> <DEDENT> objects = models.Manager.from_queryset(YokoshiQuerySet)() <NEW_LINE> def save(self, force_insert=False, force_update=False, using=None): <NEW_LINE> <INDENT> if self.han is None: <NEW_LINE> <INDENT> self.han = Han.objects.get_or_create(name='Desconhecido')[0] <NEW_LINE> <DEDENT> super(Yokoshi, self).save(force_insert, force_update, using)
A yokoshi registry. Contains basic information for person identification, search, localization and contact. Can be linked with a django User too.
62598fb44a966d76dd5eef92
class dummy_context_mgr(): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> def __exit__(self, one, two, three): <NEW_LINE> <INDENT> return False
a fake context for plotting without style perhaps made obsolete by 'classic' style in new mpl
62598fb456ac1b37e63022a5
class TooManyConnectionsError(DatabaseError): <NEW_LINE> <INDENT> pass
Превышение ограничения количества соединений с MySQL
62598fb432920d7e50bc610e
class MCP3204(MCP32xx): <NEW_LINE> <INDENT> def __init__(self, channel=0, differential=False, **spi_args): <NEW_LINE> <INDENT> if not 0 <= channel < 4: <NEW_LINE> <INDENT> raise SPIBadChannel('channel must be between 0 and 3') <NEW_LINE> <DEDENT> super(MCP3204, self).__init__(channel, differential, **spi_args)
The `MCP3204`_ is a 12-bit analog to digital converter with 4 channels (0-3). .. _MCP3204: http://www.farnell.com/datasheets/808967.pdf
62598fb423849d37ff85116e
class UpdateEntityType(BaseScript): <NEW_LINE> <INDENT> def __init__(self, argv: Sequence[str], description: str): <NEW_LINE> <INDENT> super().__init__(argv, description) <NEW_LINE> self.parser.add_argument( "--name", required=True, type=str, help="The resource name of the entity type, for example 'entityTypes/ns.brand'", ) <NEW_LINE> self.parser.add_argument( "--display-name", required=False, type=str, help="The display name of the entity type", ) <NEW_LINE> self.parser.add_argument( "--description", required=False, type=str, help="One or more paragraphs of text description", ) <NEW_LINE> is_associative_group = self.parser.add_mutually_exclusive_group() <NEW_LINE> is_associative_group.add_argument( "--is-associative", default=None, required=False, action="store_true", help="Whether the entity type is associative", ) <NEW_LINE> is_associative_group.add_argument( "--no-is-associative", dest="is_associative", default=None, required=False, action="store_false", help="Whether the entity type is not associative", ) <NEW_LINE> <DEDENT> def run_script(self, client: ExabelClient, args: argparse.Namespace) -> None: <NEW_LINE> <INDENT> update_mask = [] <NEW_LINE> for field in ["display_name", "description", "is_associative"]: <NEW_LINE> <INDENT> if getattr(args, field) is not None: <NEW_LINE> <INDENT> update_mask.append(field) <NEW_LINE> <DEDENT> <DEDENT> entity_type = EntityType( name=args.name, display_name=args.display_name if args.display_name is not None else "", description=args.description if args.description is not None else "", is_associative=args.is_associative, ) <NEW_LINE> entity = client.entity_api.update_entity_type( entity_type=entity_type, update_mask=FieldMask(paths=update_mask) ) <NEW_LINE> print(entity)
Update an entity type.
62598fb4442bda511e95c513
class Kill(ChaosMonkeyBase): <NEW_LINE> <INDENT> jujud_cmd = 'kill-jujud' <NEW_LINE> mongod_cmd = 'kill-mongod' <NEW_LINE> restart_cmd = 'restart-unit' <NEW_LINE> group = 'kill' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(Kill, self).__init__() <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def factory(cls): <NEW_LINE> <INDENT> return cls() <NEW_LINE> <DEDENT> def get_pids(self, process): <NEW_LINE> <INDENT> pids = run_shell_command('pidof ' + process, quiet_mode=True) <NEW_LINE> if not pids: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return pids.strip().split(' ') <NEW_LINE> <DEDENT> def kill_jujud(self, quiet_mode=True): <NEW_LINE> <INDENT> pids = self.get_pids('jujud') <NEW_LINE> if not pids: <NEW_LINE> <INDENT> logging.error("Jujud process ID not found") <NEW_LINE> if not quiet_mode: <NEW_LINE> <INDENT> raise NotFound('Process id not found') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> run_shell_command('kill -s SIGKILL ' + pids[0]) <NEW_LINE> <DEDENT> def kill_mongodb(self, quiet_mode=True): <NEW_LINE> <INDENT> pids = self.get_pids('mongod') <NEW_LINE> if not pids: <NEW_LINE> <INDENT> logging.error("MongoDB process ID not found") <NEW_LINE> if not quiet_mode: <NEW_LINE> <INDENT> raise NotFound('Process id not found') <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> run_shell_command('kill -s SIGKILL ' + pids[0]) <NEW_LINE> <DEDENT> def restart_unit(self, quiet_mode=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> run_shell_command('shutdown -r now') <NEW_LINE> <DEDENT> except CalledProcessError: <NEW_LINE> <INDENT> logging.error("Error while executing command: shutdown -r now ") <NEW_LINE> if not quiet_mode: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get_chaos(self): <NEW_LINE> <INDENT> chaos = list() <NEW_LINE> chaos.append( Chaos( enable=self.kill_jujud, disable=None, group=self.group, command_str=self.jujud_cmd, description='Kill jujud process.')) <NEW_LINE> chaos.append( Chaos( enable=self.kill_mongodb, disable=None, group=self.group, command_str=self.mongod_cmd, description='Kill mongod process.')) <NEW_LINE> chaos.append( Chaos( enable=self.restart_unit, disable=None, group=self.group, command_str=self.restart_cmd, description='Restart the unit.')) <NEW_LINE> return chaos
Kill processes including shutting down a machine and restarting.
62598fb456ac1b37e63022a6
class EvaluationError(Exception): <NEW_LINE> <INDENT> pass
Exception raised when there's a problem evaluating the expression.
62598fb499cbb53fe6830f90
class PyPycrypto(PythonPackage): <NEW_LINE> <INDENT> homepage = "https://www.dlitz.net/software/pycrypto/" <NEW_LINE> url = "https://pypi.io/packages/source/p/pycrypto/pycrypto-2.6.1.tar.gz" <NEW_LINE> version('2.6.1', '55a61a054aa66812daf5161a0d5d7eda') <NEW_LINE> depends_on('gmp')
The Python Cryptography Toolkit
62598fb4498bea3a75a57bdc
class WinkDevice(Entity): <NEW_LINE> <INDENT> def __init__(self, wink, hass): <NEW_LINE> <INDENT> self.wink = wink <NEW_LINE> self._battery = self.wink.battery_level <NEW_LINE> hass.data[DOMAIN]['pubnub'].add_subscription( self.wink.pubnub_channel, self._pubnub_update) <NEW_LINE> hass.data[DOMAIN]['entities'].append(self) <NEW_LINE> <DEDENT> def _pubnub_update(self, message): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if message is None: <NEW_LINE> <INDENT> _LOGGER.error("Error on pubnub update for " + self.name + " pollin API for current state") <NEW_LINE> self.update_ha_state(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.wink.pubnub_update(message) <NEW_LINE> self.update_ha_state() <NEW_LINE> <DEDENT> <DEDENT> except (ValueError, KeyError, AttributeError): <NEW_LINE> <INDENT> _LOGGER.error("Error in pubnub JSON for " + self.name + " pollin API for current state") <NEW_LINE> self.update_ha_state(True) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return '{}.{}'.format(self.__class__, self.wink.device_id()) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.wink.name() <NEW_LINE> <DEDENT> @property <NEW_LINE> def available(self): <NEW_LINE> <INDENT> return self.wink.available <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.wink.update_state() <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return self.wink.pubnub_channel is None <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_state_attributes(self): <NEW_LINE> <INDENT> if self._battery: <NEW_LINE> <INDENT> return { ATTR_BATTERY_LEVEL: self._battery_level, } <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _battery_level(self): <NEW_LINE> <INDENT> if self.wink.battery_level is not None: <NEW_LINE> <INDENT> return self.wink.battery_level * 100
Representation a base Wink device.
62598fb467a9b606de54608a
class Rectangle: <NEW_LINE> <INDENT> def __init__(self, width=0, height=0): <NEW_LINE> <INDENT> if type(width) != int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if type(height) != int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if width < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> if height < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__width = width <NEW_LINE> self.__height = height <NEW_LINE> <DEDENT> @property <NEW_LINE> def width(self): <NEW_LINE> <INDENT> return self.__width <NEW_LINE> <DEDENT> @width.setter <NEW_LINE> def width(self, value): <NEW_LINE> <INDENT> if type(value) != int: <NEW_LINE> <INDENT> raise TypeError("width must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("width must be >= 0") <NEW_LINE> <DEDENT> self.__width = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def height(self): <NEW_LINE> <INDENT> return self.__height <NEW_LINE> <DEDENT> @height.setter <NEW_LINE> def height(self, value): <NEW_LINE> <INDENT> if type(value) != int: <NEW_LINE> <INDENT> raise TypeError("height must be an integer") <NEW_LINE> <DEDENT> if value < 0: <NEW_LINE> <INDENT> raise ValueError("height must be >= 0") <NEW_LINE> <DEDENT> self.__height = value <NEW_LINE> <DEDENT> def area(self): <NEW_LINE> <INDENT> return self.__width * self.__height <NEW_LINE> <DEDENT> def perimeter(self): <NEW_LINE> <INDENT> if self.__width == 0 or self.__height == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return 2 * (self.__width + self.__height) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> str_x = "" <NEW_LINE> if self.__width == 0 or self.__height == 0: <NEW_LINE> <INDENT> return str_x <NEW_LINE> <DEDENT> for x in range(self.__height): <NEW_LINE> <INDENT> str_x += "#" * self.__width <NEW_LINE> if x < self.__height - 1: <NEW_LINE> <INDENT> str_x += "\n" <NEW_LINE> <DEDENT> <DEDENT> return str_x <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Rectangle({}, {})".format(self.__width, self.__height)
Class Rectangle Creates a new Rectangle Attributes: __width: width size of the rectangle __height: height size of the rectangle
62598fb460cbc95b06364400
class Netscan(common.AbstractScanCommand): <NEW_LINE> <INDENT> scanners = [PoolScanUdpEndpoint, PoolScanTcpListener, PoolScanTcpEndpoint] <NEW_LINE> @staticmethod <NEW_LINE> def is_valid_profile(profile): <NEW_LINE> <INDENT> return (profile.metadata.get('os', 'unknown') == 'windows' and profile.metadata.get('major', 0) == 6) <NEW_LINE> <DEDENT> def calculate(self): <NEW_LINE> <INDENT> addr_space = utils.load_as(self._config) <NEW_LINE> if not self.is_valid_profile(addr_space.profile): <NEW_LINE> <INDENT> debug.error("This command does not support the selected profile.") <NEW_LINE> <DEDENT> for objct in self.scan_results(addr_space): <NEW_LINE> <INDENT> if isinstance(objct, _UDP_ENDPOINT): <NEW_LINE> <INDENT> for ver, laddr, _ in objct.dual_stack_sockets(): <NEW_LINE> <INDENT> yield objct, "UDP" + ver, laddr, objct.Port, "*", "*", "" <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(objct, _TCP_ENDPOINT): <NEW_LINE> <INDENT> if objct.AddressFamily == AF_INET: <NEW_LINE> <INDENT> proto = "TCPv4" <NEW_LINE> <DEDENT> elif objct.AddressFamily == AF_INET6: <NEW_LINE> <INDENT> proto = "TCPv6" <NEW_LINE> <DEDENT> yield objct, proto, objct.LocalAddress, objct.LocalPort, objct.RemoteAddress, objct.RemotePort, objct.State <NEW_LINE> <DEDENT> elif isinstance(objct, _TCP_LISTENER): <NEW_LINE> <INDENT> for ver, laddr, raddr in objct.dual_stack_sockets(): <NEW_LINE> <INDENT> yield objct, "TCP" + ver, laddr, objct.Port, raddr, 0, "LISTENING" <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def unified_output(self, data): <NEW_LINE> <INDENT> return TreeGrid([(self.offset_column(), Address), ("Proto", str), ("LocalAddr", str), ("LocalPort", str), ("ForeignAddr", str), ("ForeignPort", str), ("State", str), ("PID", int), ("Owner", str), ("Created", str)], self.generator(data)) <NEW_LINE> <DEDENT> def generator(self, data): <NEW_LINE> <INDENT> for net_object, proto, laddr, lport, raddr, rport, state in data: <NEW_LINE> <INDENT> lendpoint = "{0}:{1}".format(laddr, lport) <NEW_LINE> rendpoint = "{0}:{1}".format(raddr, rport) <NEW_LINE> yield (0, [Address(net_object.obj_offset), str(proto or '-'), str(laddr or '-'), str(lport or '-'), str(raddr or '-'), str(rport or '-'), str(state or '-'), int(net_object.Owner.UniqueProcessId), str(net_object.Owner.ImageFileName or '-'), str(net_object.CreateTime or '-')])
Scan a Vista (or later) image for connections and sockets
62598fb4f548e778e596b65f
class SentimentNet(Block): <NEW_LINE> <INDENT> def __init__(self, dropout, use_mean_pool=False, prefix=None, params=None): <NEW_LINE> <INDENT> super(SentimentNet, self).__init__(prefix=prefix, params=params) <NEW_LINE> self._use_mean_pool = use_mean_pool <NEW_LINE> with self.name_scope(): <NEW_LINE> <INDENT> self.embedding = None <NEW_LINE> self.encoder = None <NEW_LINE> self.agg_layer = AggregationLayer(use_mean_pool=use_mean_pool) <NEW_LINE> self.output = gluon.nn.HybridSequential() <NEW_LINE> with self.output.name_scope(): <NEW_LINE> <INDENT> self.output.add(gluon.nn.Dropout(dropout)) <NEW_LINE> self.output.add(gluon.nn.Dense(1, flatten=False)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def forward(self, data, valid_length): <NEW_LINE> <INDENT> encoded = self.encoder(self.embedding(data)) <NEW_LINE> agg_state = self.agg_layer(encoded, valid_length) <NEW_LINE> out = self.output(agg_state) <NEW_LINE> return out
Network for sentiment analysis.
62598fb4e1aae11d1e7ce882
class CertificateList(client_extension.List, CertificateExtension): <NEW_LINE> <INDENT> shell_command = 'a10-certificate-list' <NEW_LINE> list_columns = ['id', 'name', 'description']
List A10 SSL Certificates
62598fb430dc7b766599f908
class KNearestNeighbor(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def train(self, X, y): <NEW_LINE> <INDENT> self.X_train = X <NEW_LINE> self.y_train = y <NEW_LINE> <DEDENT> def predict(self, X, k=1, num_loops=0): <NEW_LINE> <INDENT> if num_loops == 0: <NEW_LINE> <INDENT> dists = self.compute_distances_no_loops(X) <NEW_LINE> <DEDENT> elif num_loops == 1: <NEW_LINE> <INDENT> dists = self.compute_distances_one_loop(X) <NEW_LINE> <DEDENT> elif num_loops == 2: <NEW_LINE> <INDENT> dists = self.compute_distances_two_loops(X) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Invalid value %d for num_loops' % num_loops) <NEW_LINE> <DEDENT> return self.predict_labels(dists, k=k) <NEW_LINE> <DEDENT> def compute_distances_two_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> for j in xrange(num_train): <NEW_LINE> <INDENT> pass <NEW_LINE> dists[i,j] = np.sqrt(np.sum(np.square(X[i,:]-self.X_train[j,:]))) <NEW_LINE> <DEDENT> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_one_loop(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> pass <NEW_LINE> dists[i] = np.sqrt(np.sum(np.square(self.X_train-X[i]),axis = 1)) <NEW_LINE> <DEDENT> return dists <NEW_LINE> <DEDENT> def compute_distances_no_loops(self, X): <NEW_LINE> <INDENT> num_test = X.shape[0] <NEW_LINE> num_train = self.X_train.shape[0] <NEW_LINE> dists = np.zeros((num_test, num_train)) <NEW_LINE> pass <NEW_LINE> dists = np.sqrt(-2*X.dot(self.X_train.T) + np.sum(np.square(self.X_train), axis = 1) + np.transpose([np.sum(np.square(X), axis = 1)])) <NEW_LINE> return dists <NEW_LINE> <DEDENT> def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in xrange(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> pass <NEW_LINE> closest_y = self.y_train[np.argsort(dists[i])[:k]] <NEW_LINE> pass <NEW_LINE> y_pred[i] = np.argmax(np.bincount(closest_y)) <NEW_LINE> <DEDENT> return y_pred
a kNN classifier with L2 distance
62598fb4167d2b6e312b702e
class CountSamples(NumpyBasedTraceStep): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def GetInterfaceRevision(): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def GetDescription(cls): <NEW_LINE> <INDENT> return 'Counts samples of the given signal and checks, whether the count lies between minSampleCount and maxSampleCount' <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def GetSignals(cls): <NEW_LINE> <INDENT> return [SignalDefinition('Signal', 'IN', optional=False, description='')] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def GetParameters(cls): <NEW_LINE> <INDENT> return [ParameterDefinition('minSampleCount', 'IN', description=''), ParameterDefinition('maxSampleCount', 'IN', description=''), ParameterDefinition('totalSampleCount', 'OUT', description='')] <NEW_LINE> <DEDENT> def Check(self, parameters): <NEW_LINE> <INDENT> if not (isinstance(parameters['minSampleCount'], (int, type(None))) and isinstance(parameters['maxSampleCount'], (int, type(None)))): <NEW_LINE> <INDENT> raise TypeError('Parameters minSampleCount and maxSampleCount must be an integer or None!') <NEW_LINE> <DEDENT> <DEDENT> def Process(self, parameters, report, timeAxis, ranges, signals): <NEW_LINE> <INDENT> minSampleCount = parameters['minSampleCount'] <NEW_LINE> maxSampleCount = parameters['maxSampleCount'] <NEW_LINE> checkSampleCount = not (minSampleCount is None and maxSampleCount is None) <NEW_LINE> if minSampleCount is None: <NEW_LINE> <INDENT> minSampleCount = float('-inf') <NEW_LINE> <DEDENT> if maxSampleCount is None: <NEW_LINE> <INDENT> maxSampleCount = float('inf') <NEW_LINE> <DEDENT> for triggerRange in ranges: <NEW_LINE> <INDENT> count = triggerRange.GetValues('Signal').shape[0] <NEW_LINE> if checkSampleCount: <NEW_LINE> <INDENT> if minSampleCount <= count <= maxSampleCount: <NEW_LINE> <INDENT> triggerRange.SetResultSuccess() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> triggerRange.SetResultFailed() <NEW_LINE> <DEDENT> <DEDENT> triggerRange.SetResultText('Sample count: %s' % count) <NEW_LINE> <DEDENT> parameters['totalSampleCount'] = int(signals['Signal'].GetValues().shape[0])
This is an implementation of NumpyBasedTraceStep. Use the interface as reference of available methods. Abstract methods have to be implemented. Other methods like GetDescription() are optionally overwritten. There are utility functions like CalculateRanges(), FitToAxis() that can be used in your code.
62598fb499fddb7c1ca62e48
class ConfidenceIntervalHalfVT(FloatValue): <NEW_LINE> <INDENT> role = ROLE.ERROR <NEW_LINE> vt_code = 'ci' <NEW_LINE> def __init__(self,v): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def se(self): <NEW_LINE> <INDENT> pass
An upper or lower half of a confidence interval
62598fb43539df3088ecc36e
class GeneralizedSigmoidScientific(equations_data.GeneralizedSigmoidData, EquationScientific): <NEW_LINE> <INDENT> pass
This class exists to add scientific methods to GeneralizedSigmoidData
62598fb43317a56b869be5aa
class Math: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def abs(x: Union[int, float]) -> Union[int, float]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def exp(x: Union[int, float]) -> Union[int, float]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def sign(x: Union[int, float]) -> int: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def random() -> float: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def floor(x: Union[int, float]) -> int: <NEW_LINE> <INDENT> pass
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
62598fb416aa5153ce4005bf
@total_ordering <NEW_LINE> class Point: <NEW_LINE> <INDENT> def __init__(self, x, y): <NEW_LINE> <INDENT> self.x = x <NEW_LINE> self.y = y <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return Point(self.x + other.x, self.y + other.y) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return Point(self.x - other.x, self.y - other.y) <NEW_LINE> <DEDENT> def __mul__(self, n): <NEW_LINE> <INDENT> return Point(self.x * n, self.y * n) <NEW_LINE> <DEDENT> def __div__(self, n): <NEW_LINE> <INDENT> return Point(self.x / n, self.y / n) <NEW_LINE> <DEDENT> def __neg__(self): <NEW_LINE> <INDENT> return Point(-self.x, -self.y) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.x == other.x and self.y == other.y <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self.length < other.length <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "({}, {})".format(self.x, self.y) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Point({}, {})".format(self.x, self.y) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(tuple((self.x, self.y))) <NEW_LINE> <DEDENT> def dist(self, other): <NEW_LINE> <INDENT> return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2) <NEW_LINE> <DEDENT> def dist_manhattan(self, other): <NEW_LINE> <INDENT> return abs(self.x - other.x) + abs(self.y - other.y) <NEW_LINE> <DEDENT> def angle(self, to=None): <NEW_LINE> <INDENT> if to is None: <NEW_LINE> <INDENT> return math.atan2(self.y, self.x) <NEW_LINE> <DEDENT> return math.atan2(self.y - to.y, self.x - to.x) <NEW_LINE> <DEDENT> @property <NEW_LINE> def manhattan(self): <NEW_LINE> <INDENT> return abs(self.x) + abs(self.y) <NEW_LINE> <DEDENT> @property <NEW_LINE> def length(self): <NEW_LINE> <INDENT> return math.sqrt(self.x ** 2 + self.y ** 2) <NEW_LINE> <DEDENT> def neighbours_4(self): <NEW_LINE> <INDENT> return [self + p for p in DIRS_4] <NEW_LINE> <DEDENT> def neighbours_8(self): <NEW_LINE> <INDENT> return [self + p for p in DIRS_8] <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return Point(x=self.x, y=self.y)
Simple 2-dimensional point.
62598fb47047854f4633f497
class Softmax: <NEW_LINE> <INDENT> def regularization_loss(self, W): <NEW_LINE> <INDENT> return np.sum(np.square(W)) <NEW_LINE> <DEDENT> def compute_loss(self, scores, correct_class, W=[]): <NEW_LINE> <INDENT> shifted_scores = scores - np.max(scores) <NEW_LINE> num = np.exp(shifted_scores[correct_class]) <NEW_LINE> den = np.sum(np.exp(shifted_scores)) <NEW_LINE> return -np.log(num / den) + self.regularization_loss(W) * self.r / 2 <NEW_LINE> <DEDENT> def compute_dscores(self, scores, correct_class): <NEW_LINE> <INDENT> shifted_scores = scores - np.max(scores) <NEW_LINE> exp_scores = np.exp(shifted_scores) <NEW_LINE> den = np.sum(exp_scores) <NEW_LINE> dscores = exp_scores / den <NEW_LINE> dscores[correct_class] -= 1 <NEW_LINE> return dscores <NEW_LINE> <DEDENT> def compute_gradient(self, X, y, W, b): <NEW_LINE> <INDENT> scores = W.dot(X) + b <NEW_LINE> shifted_scores = scores - np.max(scores) <NEW_LINE> exp_scores = np.exp(shifted_scores) <NEW_LINE> den = np.sum(exp_scores) <NEW_LINE> dscores = exp_scores / den <NEW_LINE> dscores[y] -= 1 <NEW_LINE> dW = dscores[:, np.newaxis].dot(X[np.newaxis, :]) <NEW_LINE> dW += W * self.r <NEW_LINE> db = dscores <NEW_LINE> return dW, db
Class computes softmax loss and gradient
62598fb4be8e80087fbbf123
class StorageValidationTasksTestCase(unittest.TestCase): <NEW_LINE> <INDENT> @patch('pyanaconda.modules.storage.partitioning.validate.storage_checker') <NEW_LINE> def test_validation(self, storage_checker): <NEW_LINE> <INDENT> storage = Mock() <NEW_LINE> report = StorageCheckerReport() <NEW_LINE> storage_checker.check.return_value = report <NEW_LINE> report = StorageValidateTask(storage).run() <NEW_LINE> assert report.is_valid() is True <NEW_LINE> assert report.error_messages == [] <NEW_LINE> assert report.warning_messages == [] <NEW_LINE> <DEDENT> @patch('pyanaconda.modules.storage.partitioning.validate.storage_checker') <NEW_LINE> def test_validation_failed(self, storage_checker): <NEW_LINE> <INDENT> storage = Mock() <NEW_LINE> report = StorageCheckerReport() <NEW_LINE> report.add_error("Fake error.") <NEW_LINE> report.add_warning("Fake warning.") <NEW_LINE> report.add_warning("Fake another warning.") <NEW_LINE> storage_checker.check.return_value = report <NEW_LINE> report = StorageValidateTask(storage).run() <NEW_LINE> assert report.is_valid() is False <NEW_LINE> assert report.error_messages == ["Fake error."] <NEW_LINE> assert report.warning_messages == ["Fake warning.", "Fake another warning."]
Test the storage validation tasks.
62598fb410dbd63aa1c70c72
class Terrain(object): <NEW_LINE> <INDENT> MAX_X = 128 <NEW_LINE> MAX_Y = 128 <NEW_LINE> MAX_Z = 128 <NEW_LINE> points = {} <NEW_LINE> noise = {} <NEW_LINE> def generateTerrain(self): <NEW_LINE> <INDENT> self.generateNoise() <NEW_LINE> <DEDENT> def generateNoise(self): <NEW_LINE> <INDENT> indX = 0 <NEW_LINE> while (indX < self.MAX_X): <NEW_LINE> <INDENT> indZ = 0 <NEW_LINE> while (indX < self.MAX_X): <NEW_LINE> <INDENT> self.noise[indX][indZ] = randint(0,self.MAX_Y-1) <NEW_LINE> indZ+=1 <NEW_LINE> <DEDENT> indX+=1 <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, params): <NEW_LINE> <INDENT> self.generateTerrain() <NEW_LINE> <DEDENT> def toString(self): <NEW_LINE> <INDENT> print ('Max X: ' + str(self.MAX_X)) <NEW_LINE> print ('Max Y: ' + str(self.MAX_Y)) <NEW_LINE> print ('Max Z: ' + str(self.MAX_Z))
The terrain object automatically generates terrain using fractals
62598fb401c39578d7f12e36
class DescribeInstanceVncUrlRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.InstanceId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.InstanceId = params.get("InstanceId")
DescribeInstanceVncUrl请求参数结构体
62598fb45fc7496912d482da
class Solution: <NEW_LINE> <INDENT> def maxCount(self, m, n, ops): <NEW_LINE> <INDENT> for op in ops: <NEW_LINE> <INDENT> m = min(m, op[0]) <NEW_LINE> n = min(n, op[1]) <NEW_LINE> <DEDENT> return m * n
@param m: an integer @param n: an integer @param ops: List[List[int]] @return: return an integer
62598fb4851cf427c66b8373
class HBaseRegionServerInfo(ComponentInfo): <NEW_LINE> <INDENT> implements(IHBaseRegionServerInfo) <NEW_LINE> adapts(HBaseRegionServer) <NEW_LINE> start_code = ProxyProperty('start_code') <NEW_LINE> is_alive = ProxyProperty('is_alive') <NEW_LINE> region_name = ProxyProperty('region_name') <NEW_LINE> handler_count = ProxyProperty('handler_count') <NEW_LINE> memstore_upper_limit = ProxyProperty('memstore_upper_limit') <NEW_LINE> memstore_lower_limit = ProxyProperty('memstore_lower_limit') <NEW_LINE> logflush_interval = ProxyProperty('logflush_interval') <NEW_LINE> @property <NEW_LINE> @info <NEW_LINE> def status(self): <NEW_LINE> <INDENT> return self.is_alive <NEW_LINE> <DEDENT> @property <NEW_LINE> @info <NEW_LINE> def region_ids(self): <NEW_LINE> <INDENT> return self._object.regions.objectIds()
API Info adapter factory for HBaseRegionServer
62598fb42ae34c7f260ab198
class Session(): <NEW_LINE> <INDENT> def __init__(self, addr, peer_addr, secret): <NEW_LINE> <INDENT> self.addr = addr <NEW_LINE> self.peer_addr = peer_addr <NEW_LINE> self.secret = secret <NEW_LINE> self._phash = None <NEW_LINE> self.valid = False <NEW_LINE> self.nonce = rand_str(40) <NEW_LINE> <DEDENT> def get_hash(self, peer_nonce): <NEW_LINE> <INDENT> if len(str(peer_nonce)) < NONCE_LEN: <NEW_LINE> <INDENT> raise AuthError('Nonce too short') <NEW_LINE> <DEDENT> passwd = '%s%s%s' % (self.secret, self.addr, peer_nonce) <NEW_LINE> self._phash = bcrypt_sha256.encrypt(passwd) <NEW_LINE> return self._phash <NEW_LINE> <DEDENT> def authenticate(self, _hash): <NEW_LINE> <INDENT> passwd = '%s%s%s' % (self.secret, self.peer_addr, self.nonce) <NEW_LINE> try: <NEW_LINE> <INDENT> self.valid = bcrypt_sha256.verify(passwd, _hash) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> log.error('Auth Error: from %s' % self.peer_addr) <NEW_LINE> self.valid = False <NEW_LINE> <DEDENT> return self.valid
Session for single client - recv nonce, send hash = get_hash(peer_nonce) - send nonce, recv hash = authenticate(_hash) - enc/dec secret + peer_addr + my_nonce
62598fb423849d37ff851170
class axisDesc : <NEW_LINE> <INDENT> def __init__(self, axis) : <NEW_LINE> <INDENT> self.axis = axis <NEW_LINE> self.value = None <NEW_LINE> <DEDENT> def __set__(self, instance, value) : <NEW_LINE> <INDENT> if value in self.axis.values : <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> elif isinstance(value, int) and value in self.axis.rev: <NEW_LINE> <INDENT> self.value = self.axis.rev[value] <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> message.error('axis %(name)s has no enumeration %(value)s', name=self.axis.name, value=value) <NEW_LINE> raise axisValueError <NEW_LINE> <DEDENT> <DEDENT> def __get__(self, instance, owner) : <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> def __int__(self) : <NEW_LINE> <INDENT> return self.axis.ord[self.value] <NEW_LINE> <DEDENT> def __iadd__(self, other) : <NEW_LINE> <INDENT> if isinstance(other, int) : <NEW_LINE> <INDENT> adj = other <NEW_LINE> <DEDENT> elif other in self.axis.values : <NEW_LINE> <INDENT> adj = self.axis.ord[other] <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> message.error('axis %(name)s has no enumeration %(value)s', name=self.axis.name, value=other) <NEW_LINE> raise axisValueError <NEW_LINE> <DEDENT> self.__set__(None, self.__int__ + adj)
Read/write model of axis for cursor
62598fb43d592f4c4edbaf7d
@dataclass_json(letter_case=LetterCase.CAMEL) <NEW_LINE> @dataclass <NEW_LINE> class ClusterSpec: <NEW_LINE> <INDENT> settings: Settings <NEW_LINE> topology: Topology = Topology() <NEW_LINE> distribution: Distribution = Distribution()
Represents the cluster spec. If dictionaries are passed as arguments, the constructor auto-converts them into the expected class instances.
62598fb463b5f9789fe85228
class IPv6Offset(types.TypeDecorator): <NEW_LINE> <INDENT> impl = types.Numeric(39, 0) <NEW_LINE> MIN_VALUE = 0 <NEW_LINE> MAX_VALUE = 340282366920938463463374607431768211456 <NEW_LINE> def load_dialect_impl(self, dialect): <NEW_LINE> <INDENT> if _is_mysql(dialect): <NEW_LINE> <INDENT> return mysql.DECIMAL(precision=39, scale=0, unsigned=True) <NEW_LINE> <DEDENT> return self.impl <NEW_LINE> <DEDENT> @property <NEW_LINE> def python_type(self): <NEW_LINE> <INDENT> return int
IPv6 address offset.
62598fb4a8370b77170f049a
class QDateTime(): <NEW_LINE> <INDENT> def addDays(self, p_int): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def addMonths(self, p_int): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def addMSecs(self, p_int): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def addSecs(self, p_int): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def addYears(self, p_int): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def currentDateTime(): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def currentDateTimeUtc(self): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def currentMSecsSinceEpoch(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def date(self): <NEW_LINE> <INDENT> return QDate <NEW_LINE> <DEDENT> def daysTo(self, QDateTime): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def fromMSecsSinceEpoch(self, p_int): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def fromString(self, QString, *__args): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def fromTime_t(self, p_int): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def isNull(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def isValid(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def msecsTo(self, QDateTime): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def secsTo(self, QDateTime): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def setDate(self, QDate): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setMSecsSinceEpoch(self, p_int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setTime(self, QTime): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setTimeSpec(self, Qt_TimeSpec): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setTime_t(self, p_int): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def time(self): <NEW_LINE> <INDENT> return QTime <NEW_LINE> <DEDENT> def timeSpec(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def toLocalTime(self): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def toMSecsSinceEpoch(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def toPyDateTime(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def toString(self, *__args): <NEW_LINE> <INDENT> return QString <NEW_LINE> <DEDENT> def toTimeSpec(self, Qt_TimeSpec): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def toTime_t(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def toUTC(self): <NEW_LINE> <INDENT> return QDateTime <NEW_LINE> <DEDENT> def __eq__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *__args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self, y): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce__(self, *args, **kwargs): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None)
QDateTime() QDateTime(QDateTime) QDateTime(QDate) QDateTime(QDate, QTime, Qt.TimeSpec timeSpec=Qt.LocalTime) QDateTime(int, int, int, int, int, int s=0, int msec=0, int timeSpec=0)
62598fb456ac1b37e63022a8
class ClientAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ("full_name", "is_vip", "sex", "birth_date") <NEW_LINE> list_filter = ("is_vip", "sex") <NEW_LINE> fieldsets = ( ("ФИО", { "fields": (("second_name", "first_name", "middle_name"),) }), ("Статус/Пол/ДР", { "fields": (("is_vip", "sex", "birth_date"),) }), ("Паспорт", { "fields": (("serial", "number", "date_issue"), ("police_department_id", "police_department"), ("birth_place", "registration"),) }), )
Клиенты
62598fb4f548e778e596b661
class ParamsError(BaseError): <NEW_LINE> <INDENT> def __init__(self, error_text): <NEW_LINE> <INDENT> super(ParamsError, self).__init__(error_text)
Parameters Error class
62598fb4d486a94d0ba2c08f
class ExceptionCategory(Category): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ExceptionCategory, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> def categorize(self, lineitem): <NEW_LINE> <INDENT> for desc in self.descriptions: <NEW_LINE> <INDENT> if desc in lineitem.description: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> lineitem.categorize(self)
ExceptionCategory will not apply fn to the lineitem if any of its descriptions match the lineitem description.
62598fb49c8ee823130401d1