code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Food(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen, food_str): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.food_str = food_str <NEW_LINE> self.text_color = (255, 30, 30) <NEW_LINE> self.font = pygame.font.SysFont(None, 35) <NEW_LINE> self.bg_color = (30, 255, 30) <NEW_LINE> self.image = self.font.render(self.food_str, True, self.text_color, self.bg_color) <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = random.randint(0,self.ai_settings.screen_width) <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.direction = 1 <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> self.direction = self.direction * -1 <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> self.direction = self.direction * -1 <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += self.ai_settings.food_speed_x * self.direction <NEW_LINE> self.y += self.ai_settings.food_speed_y <NEW_LINE> self.rect.x = self.x <NEW_LINE> self.rect.y = self.y
表示单个食物的类
62598fc9ad47b63b2c5a7bd0
class AdminAuthenticationForm(AuthenticationForm): <NEW_LINE> <INDENT> this_is_the_login_form = django.forms.BooleanField(widget=floppyforms.HiddenInput, initial=1, error_messages={'required': ugettext_lazy("Please log in again, because your session has expired.")}) <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> username = self.cleaned_data.get('username') <NEW_LINE> password = self.cleaned_data.get('password') <NEW_LINE> message = ERROR_MESSAGE <NEW_LINE> if username and password: <NEW_LINE> <INDENT> self.user_cache = authenticate(username=username, password=password) <NEW_LINE> if self.user_cache is None: <NEW_LINE> <INDENT> raise floppyforms.ValidationError(message % { 'username': self.username_field.verbose_name }) <NEW_LINE> <DEDENT> elif not self.user_cache.is_active or not self.user_cache.is_staff: <NEW_LINE> <INDENT> raise floppyforms.ValidationError(message % { 'username': self.username_field.verbose_name }) <NEW_LINE> <DEDENT> <DEDENT> return self.cleaned_data
A custom authentication form used in the admin app. Liberally copied from django.contrib.admin.forms.AdminAuthenticationForm
62598fc997e22403b383b27b
class StubServer(UserAccountMixin, asyncssh.SSHServer): <NEW_LINE> <INDENT> def connection_made(self, conn: asyncssh.SSHServerConnection) -> None: <NEW_LINE> <INDENT> print("SSH connection received from %s." % conn.get_extra_info("peername")[0]) <NEW_LINE> <DEDENT> def connection_lost(self, exc: typing.Union[None, Exception]) -> None: <NEW_LINE> <INDENT> if exc: <NEW_LINE> <INDENT> print("SSH connection error: " + str(exc), file=sys.stderr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("SSH connection closed.") <NEW_LINE> <DEDENT> <DEDENT> def begin_auth(self, username: str) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def password_auth_supported(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def validate_password(self, username: str, password: str) -> bool: <NEW_LINE> <INDENT> user = authenticate(**{self.username_field: username, "password": password}) <NEW_LINE> account = self.get_account(username) <NEW_LINE> if not (user and account): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
SFTP server interface based on asyncssh.SSHServer.
62598fc9ec188e330fdf8c0c
class install(distutils_install): <NEW_LINE> <INDENT> def run(self): <NEW_LINE> <INDENT> distutils_install.run(self) <NEW_LINE> print('') <NEW_LINE> print(bcolors.HEADER + 'License' + bcolors.ENDC) <NEW_LINE> print('') <NEW_LINE> print("Wirecloud is licensed under a AGPLv3+ license with a classpath-like exception \n" + "that allows widgets/operators and mashups to be licensed under any propietary or \n" + "open source license.") <NEW_LINE> print('') <NEW_LINE> license_file = os.path.join(self.install_purelib, 'wirecloud', 'LICENSE') <NEW_LINE> print('A copy of the license has been installed at: ' + bcolors.WARNING + license_file + bcolors.ENDC)
Customized setuptools install command - prints info about the license of Wirecloud after installing it.
62598fca167d2b6e312b72ee
class tr: <NEW_LINE> <INDENT> def __init__(self, transform): <NEW_LINE> <INDENT> self.tr = transform <NEW_LINE> <DEDENT> def __ror__(self, input): <NEW_LINE> <INDENT> return map(self.tr, input)
apply arbitrary transform to each sequence element
62598fcacc40096d6161a393
@dataclass(frozen=True) <NEW_LINE> class RangeLiteral: <NEW_LINE> <INDENT> start: Optional[int] = None <NEW_LINE> end: Optional[int] = None <NEW_LINE> def __str__(self) -> str: <NEW_LINE> <INDENT> if self.start is None: <NEW_LINE> <INDENT> return "*" <NEW_LINE> <DEDENT> elif self.end is None: <NEW_LINE> <INDENT> return f"*{self.start}" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f"*{self.start}..{self.end}"
RangeLiteral = '*', [SP], [IntegerLiteral, [SP]], ['..', [SP], [IntegerLiteral, [SP]]] ;
62598fca099cdd3c6367559d
class RelengPackageExtensionInterface(RelengExtensionInterface): <NEW_LINE> <INDENT> def build(self, name, opts): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def configure(self, name, opts): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def install(self, name, opts): <NEW_LINE> <INDENT> return False
interface to implement a custom fetch-type Extensions wishing to define a custom fetch type can implement this interface and register it (see ``add_fetch_type``) during the extension's setup stage. This will allow an project support custom VCS-types defined in package definitions (for example "<PKG>_VCS_TYPE='ext-myawesomefetchtype'").
62598fca283ffb24f3cf3bfc
class IncrementalCorrelationFilterThinWrapper(object): <NEW_LINE> <INDENT> def __init__(self, cf_callable=mccf, icf_callable=imccf): <NEW_LINE> <INDENT> self.cf_callable = cf_callable <NEW_LINE> self.icf_callable = icf_callable <NEW_LINE> <DEDENT> def increment(self, A, B, n_x, Z, t): <NEW_LINE> <INDENT> if isinstance(Z, list): <NEW_LINE> <INDENT> Z = np.asarray(Z) <NEW_LINE> <DEDENT> return self.icf_callable(A, B, n_x, Z, t) <NEW_LINE> <DEDENT> def train(self, X, t): <NEW_LINE> <INDENT> if isinstance(X, list): <NEW_LINE> <INDENT> X = np.asarray(X) <NEW_LINE> <DEDENT> return self.cf_callable(X, t)
Wrapper class for defining an Incremental Correlation Filter. Parameters ---------- cf_callable : `callable`, optional The correlation filter function. Possible options are: ============ =========================================== Class Method ============ =========================================== :map:`mccf` Multi-Channel Correlation Filter :map:`mosse` Minimum Output Sum of Squared Errors Filter ============ =========================================== icf_callable : `callable`, optional The incremental correlation filter function. Possible options are: ============= ======================================================= Class Method ============= ======================================================= :map:`imccf` Incremental Multi-Channel Correlation Filter :map:`imosse` Incremental Minimum Output Sum of Squared Errors Filter ============= =======================================================
62598fca26068e7796d4ccd3
class TndAsyncTestResource(TndBaseTestResource): <NEW_LINE> <INDENT> @gen.coroutine <NEW_LINE> def list(self): <NEW_LINE> <INDENT> raise gen.Return(self.fake_db) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def detail(self, pk): <NEW_LINE> <INDENT> for item in self.fake_db: <NEW_LINE> <INDENT> if item['id'] == int(pk): <NEW_LINE> <INDENT> raise gen.Return(item) <NEW_LINE> <DEDENT> <DEDENT> raise gen.Return(None) <NEW_LINE> <DEDENT> @gen.coroutine <NEW_LINE> def create(self): <NEW_LINE> <INDENT> self.fake_db.append(self.data)
asynchronous basic view_method
62598fca091ae35668704fa1
class DnsLogView(LogView): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> config = mmc.plugins.network.NetworkConfig("network") <NEW_LINE> self.logfile = config.dnsLogFile <NEW_LINE> self.maxElt= 200 <NEW_LINE> self.file = open(self.logfile, 'r') <NEW_LINE> if config.dnsType == "pdns": <NEW_LINE> <INDENT> self.pattern = { "named-syslog" : "^(?P<b>[A-z]{3}) *(?P<d>[0-9]+) (?P<H>[0-9]{2}):(?P<M>[0-9]{2}):(?P<S>[0-9]{2}) .* pdns\[[0-9]+\]: (?P<extra>.*)$", } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pattern = { "named-syslog" : "^(?P<b>[A-z]{3}) *(?P<d>[0-9]+) (?P<H>[0-9]{2}):(?P<M>[0-9]{2}):(?P<S>[0-9]{2}) .* named\[[0-9]+\]: (?P<extra>.*)$", "named-syslog1" : "^(?P<b>[A-z]{3}) *(?P<d>[0-9]+) (?P<H>[0-9]{2}):(?P<M>[0-9]{2}):(?P<S>[0-9]{2}) .* named-sdb\[[0-9]+\]: (?P<extra>.*)$", }
Get DNS service log content.
62598fca377c676e912f6f32
class ClientException(CallofDutyException): <NEW_LINE> <INDENT> pass
Exception which is thrown when an operation in the Client class fails.
62598fcad486a94d0ba2c34a
class BagStandardizer(BagPreprocesser): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(BagStandardizer, self).__init__(StandardScaler())
Standardizes each feature dimension to have zero mean and unit variance, regardless of the bag it falls into. This is just :class:`BagPreprocesser` with :class:`sklearn.preprocessing.StandardScaler`.
62598fca71ff763f4b5e7af9
class RouteRedirect(Route): <NEW_LINE> <INDENT> target = models.ForeignKey('routes.Route', related_name='+') <NEW_LINE> permanent = models.BooleanField(default=False) <NEW_LINE> view = views.RouteRedirectView.as_view() <NEW_LINE> def clean(self): <NEW_LINE> <INDENT> if self.target_id == self.route_ptr_id: <NEW_LINE> <INDENT> error = {'target': _('A RouteRedirect cannot redirect to itself.')} <NEW_LINE> raise ValidationError(error) <NEW_LINE> <DEDENT> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.clean() <NEW_LINE> return super().save(*args, **kwargs)
When `route` is browsed to, browser should be redirected to `target`. This model holds the data required to make that connection.
62598fca091ae35668704fa2
class Test_Console(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.mock_stdin = create_autospec(sys.stdin) <NEW_LINE> self.mock_stdout = create_autospec(sys.stdout) <NEW_LINE> <DEDENT> def create(self, server=None): <NEW_LINE> <INDENT> return HBNBCommand(stdin=self.mock_stdin, stdout=self.mock_stdout) <NEW_LINE> <DEDENT> def test_quit(self): <NEW_LINE> <INDENT> xit = self.create() <NEW_LINE> self.assertTrue(xit.onecmd("quit"))
Console Unittest
62598fcaad47b63b2c5a7bd4
class StructuredValue(Intangible): <NEW_LINE> <INDENT> pass
Structured values are strings - for example, addresses - that have certain constraints on their structure.
62598fca283ffb24f3cf3bff
class ConsecutiveHyperlinkedField(serializers.HyperlinkedIdentityField): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.lookup_fields = kwargs.pop('lookup_fields', None) <NEW_LINE> super(ConsecutiveHyperlinkedField, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getattr_consecutive(obj, dot_notated_string): <NEW_LINE> <INDENT> return reduce(getattr, dot_notated_string.split('.'), obj) <NEW_LINE> <DEDENT> def get_url(self, obj, view_name, request, url_format): <NEW_LINE> <INDENT> args = () <NEW_LINE> if self.lookup_fields: <NEW_LINE> <INDENT> args = (self.getattr_consecutive(obj, arg) for arg in self.lookup_fields) <NEW_LINE> <DEDENT> return reverse(view_name, args=args, request=request, format=url_format)
Inheritor of serializers.HyperlinkedIdentityField serializer that allows to define a tuple of lookup fields, where field can be dot-notated string.
62598fca0fa83653e46f5261
class Account(DefaultAccount): <NEW_LINE> <INDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> from django.core.urlresolvers import reverse <NEW_LINE> return reverse('character:sheet', kwargs={'object_id': self.id}) <NEW_LINE> <DEDENT> def last_puppet(self): <NEW_LINE> <INDENT> return self.db._last_puppet
This class describes the actual OOC account (i.e. the user connecting to the MUD). It does NOT have visual appearance in the game world (that is handled by the character which is connected to this). Comm channels are attended/joined using this object. It can be useful e.g. for storing configuration options for your game, but should generally not hold any character-related info (that's best handled on the character level). Can be set using BASE_ACCOUNT_TYPECLASS. * available properties key (string) - name of account name (string)- wrapper for user.username aliases (list of strings) - aliases to the object. Will be saved to database as AliasDB entries but returned as strings. dbref (int, read-only) - unique #id-number. Also "id" can be used. date_created (string) - time stamp of object creation permissions (list of strings) - list of permission strings user (User, read-only) - django User authorization object obj (Object) - game object controlled by account. 'character' can also be used. sessions (list of Sessions) - sessions connected to this account is_superuser (bool, read-only) - if the connected user is a superuser * Handlers locks - lock-handler: use locks.add() to add new lock strings db - attribute-handler: store/retrieve database attributes on this self.db.myattr=val, val=self.db.myattr ndb - non-persistent attribute handler: same as db but does not create a database entry when storing data scripts - script-handler. Add new scripts to object with scripts.add() cmdset - cmdset-handler. Use cmdset.add() to add new cmdsets to object nicks - nick-handler. New nicks with nicks.add(). * Helper methods msg(text=None, **kwargs) swap_character(new_character, delete_old_character=False) execute_cmd(raw_string, session=None) search(ostring, global_search=False, attribute_name=None, use_nicks=False, location=None, ignore_errors=False, account=False) is_typeclass(typeclass, exact=False) swap_typeclass(new_typeclass, clean_attributes=False, no_default=True) access(accessing_obj, access_type='read', default=False) check_permstring(permstring) * Hook methods (when re-implementation, remember methods need to have self as first arg) basetype_setup() at_account_creation() - note that the following hooks are also found on Objects and are usually handled on the character level: at_init() at_cmdset_get(**kwargs) at_first_login() at_post_login(session=None) at_disconnect() at_message_receive() at_message_send() at_server_reload() at_server_shutdown()
62598fcaa219f33f346c6b83
class PosetType(ABC): <NEW_LINE> <INDENT> def __init__(self, entity_universe_type='label'): <NEW_LINE> <INDENT> self.entity_universe_type = entity_universe_type <NEW_LINE> <DEDENT> def get_params(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_params(self): <NEW_LINE> <INDENT> pass
Abstract class for PosetType Used by models and data containers to query what kind of Poset is being fed in. Parameters: ------------ entity_universe_type: str "label": all potential entities in the universe are known "object": an entity is observed at most once "semi": "object" except entities can reoccur
62598fca3617ad0b5ee064c3
class NameValidator(BaseValidator): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(NameValidator, self).__init__() <NEW_LINE> <DEDENT> def check(self, parent): <NEW_LINE> <INDENT> control = self.GetWindow() <NEW_LINE> newName = control.GetValue() <NEW_LINE> msg, OK = '', True <NEW_LINE> if newName == '': <NEW_LINE> <INDENT> msg = _translate("Missing name") <NEW_LINE> OK = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> namespace = parent.frame.exp.namespace <NEW_LINE> used = namespace.exists(newName) <NEW_LINE> sameAsOldName = bool(newName == parent.params['name'].val) <NEW_LINE> if used and not sameAsOldName: <NEW_LINE> <INDENT> msg = _translate("That name is in use (by %s). Try another name.") % _translate(used) <NEW_LINE> msg = _translate("That name is in use (by {used}). Try another name." ).format(used = _translate(used)) <NEW_LINE> OK = False <NEW_LINE> <DEDENT> elif not namespace.isValid(newName): <NEW_LINE> <INDENT> msg = _translate("Name must be alpha-numeric or _, no spaces") <NEW_LINE> OK = False <NEW_LINE> <DEDENT> elif namespace.isPossiblyDerivable(newName): <NEW_LINE> <INDENT> msg = _translate(namespace.isPossiblyDerivable(newName)) <NEW_LINE> OK = True <NEW_LINE> <DEDENT> <DEDENT> parent.warningsDict['name'] = msg <NEW_LINE> return msg, OK
Validation checks if the value in Name field is a valid Python identifier and if it does not clash with existing names.
62598fcad8ef3951e32c8019
class NaturalLanguageProcessing(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.stop_words = set(stopwords.words('english')) <NEW_LINE> self.labeled_names = ([(name, 'male') for name in names.words('male.txt')] + [(name, 'female') for name in names.words('female.txt')]) <NEW_LINE> random.shuffle(self.labeled_names) <NEW_LINE> featuresets = [(self.gender_features(n), gender) for (n, gender) in self.labeled_names] <NEW_LINE> self.classifier = self.train_gender(featuresets[1000:]) <NEW_LINE> <DEDENT> def tokenize_text(self, text): <NEW_LINE> <INDENT> tokenizer = RegexpTokenizer(r'\w+') <NEW_LINE> return tokenizer.tokenize(text) <NEW_LINE> <DEDENT> def clear_empty_words(self, words): <NEW_LINE> <INDENT> filtered_sentence = [] <NEW_LINE> for word in words: <NEW_LINE> <INDENT> if word.lower() not in self.stop_words: <NEW_LINE> <INDENT> filtered_sentence.append(word) <NEW_LINE> <DEDENT> <DEDENT> return list(filtered_sentence) <NEW_LINE> <DEDENT> def find_human_names(self, words): <NEW_LINE> <INDENT> pos = pos_tag(words) <NEW_LINE> sentt = chunk.ne_chunk(pos, binary = False) <NEW_LINE> person_list = [] <NEW_LINE> person = [] <NEW_LINE> name = "" <NEW_LINE> for subtree in sentt.subtrees(filter=lambda t: t.label() == 'PERSON'): <NEW_LINE> <INDENT> for leaf in subtree.leaves(): <NEW_LINE> <INDENT> person.append(leaf[0]) <NEW_LINE> <DEDENT> if len(person) > 1: <NEW_LINE> <INDENT> for part in person: <NEW_LINE> <INDENT> name += part + ' ' <NEW_LINE> <DEDENT> if name[:-1] not in person_list: <NEW_LINE> <INDENT> person_list.append(name[:-1]) <NEW_LINE> <DEDENT> name = '' <NEW_LINE> <DEDENT> person = [] <NEW_LINE> <DEDENT> if (len(person_list) > 0): <NEW_LINE> <INDENT> person_list = self.tokenize_text(person_list[0]) <NEW_LINE> return person_list[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def find_digits(self, words): <NEW_LINE> <INDENT> aux = [] <NEW_LINE> for word in words: <NEW_LINE> <INDENT> if (word.isdigit()): <NEW_LINE> <INDENT> aux.append(word) <NEW_LINE> <DEDENT> <DEDENT> return aux <NEW_LINE> <DEDENT> def validate_age(self, age): <NEW_LINE> <INDENT> return True if age >= 10 and age <= 100 else False <NEW_LINE> <DEDENT> def gender_features(self, name): <NEW_LINE> <INDENT> features = {} <NEW_LINE> features["first_letter"] = name[0].lower() <NEW_LINE> features["last_letter"] = name[-1].lower() <NEW_LINE> for letter in 'abcdefghijklmnopqrstuvwxyz': <NEW_LINE> <INDENT> features["count({})".format(letter)] = name.lower().count(letter) <NEW_LINE> features["has({})".format(letter)] = (letter in name.lower()) <NEW_LINE> <DEDENT> return features <NEW_LINE> <DEDENT> def find_gender(self, name): <NEW_LINE> <INDENT> return self.classifier.classify(self.gender_features(name)) <NEW_LINE> <DEDENT> def train_gender(self, train_set): <NEW_LINE> <INDENT> return nbc.train(train_set) <NEW_LINE> <DEDENT> def get_stop_words(self): <NEW_LINE> <INDENT> return self.stop_words <NEW_LINE> <DEDENT> def find_mood(self, text): <NEW_LINE> <INDENT> params = {"text" : text} <NEW_LINE> response = requests.post("http://text-processing.com/api/sentiment/", params) <NEW_LINE> if (response.status_code == 200): <NEW_LINE> <INDENT> response = response.json() <NEW_LINE> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
docstring for Nlp.
62598fca656771135c4899ec
class AlfabetMusic(Resource): <NEW_LINE> <INDENT> def get(self, artista): <NEW_LINE> <INDENT> artista = remover_acentos_char_especiais(artista) <NEW_LINE> if not vagalume.request(artista, ''): <NEW_LINE> <INDENT> sys.exit(2) <NEW_LINE> <DEDENT> top_musicas, alfabet_musicas = vagalume.search(artista) <NEW_LINE> return {f'Todas as musicas de {artista}': alfabet_musicas}
Recurso para listar todas as musicas de um artista
62598fca3d592f4c4edbb22f
class Event(models.Model): <NEW_LINE> <INDENT> __package__ = 'UML.CommonBehavior' <NEW_LINE> packageable_element = models.OneToOneField('PackageableElement', on_delete=models.CASCADE, primary_key=True)
An Event is the specification of some occurrence that may potentially trigger effects by an object.
62598fca283ffb24f3cf3c02
class KeyImportParameters(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'key': {'required': True}, } <NEW_LINE> _attribute_map = { 'hsm': {'key': 'Hsm', 'type': 'bool'}, 'key': {'key': 'key', 'type': 'JsonWebKey'}, 'key_attributes': {'key': 'attributes', 'type': 'KeyAttributes'}, 'tags': {'key': 'tags', 'type': '{str}'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(KeyImportParameters, self).__init__(**kwargs) <NEW_LINE> self.hsm = kwargs.get('hsm', None) <NEW_LINE> self.key = kwargs['key'] <NEW_LINE> self.key_attributes = kwargs.get('key_attributes', None) <NEW_LINE> self.tags = kwargs.get('tags', None)
The key import parameters. All required parameters must be populated in order to send to Azure. :param hsm: Whether to import as a hardware key (HSM) or software key. :type hsm: bool :param key: Required. The Json web key. :type key: ~azure.keyvault.v7_1.models.JsonWebKey :param key_attributes: The key management attributes. :type key_attributes: ~azure.keyvault.v7_1.models.KeyAttributes :param tags: A set of tags. Application specific metadata in the form of key-value pairs. :type tags: dict[str, str]
62598fca23849d37ff85142f
class Tag(object): <NEW_LINE> <INDENT> def __init__(self, tree=MerkleTree(), chunksz=DEFAULT_CHUNK_SIZE, filesz=None): <NEW_LINE> <INDENT> self.tree = tree <NEW_LINE> self.chunksz = chunksz <NEW_LINE> self.filesz = filesz <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (isinstance(other, Tag) and self.tree == other.tree and self.chunksz == other.chunksz and self.filesz == other.filesz) <NEW_LINE> <DEDENT> def todict(self): <NEW_LINE> <INDENT> return {'tree': self.tree.todict(), 'chunksz': self.chunksz, 'filesz': self.filesz} <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def fromdict(dict): <NEW_LINE> <INDENT> tree = MerkleTree.fromdict(dict['tree']) <NEW_LINE> chunksz = dict['chunksz'] <NEW_LINE> filesz = dict['filesz'] <NEW_LINE> return Tag(tree, chunksz, filesz)
The Tag class represents the file tag that is a stripped merkle tree, that is a merkle tree without the leaves, which are the seeded hashes of each chunk. it also includes the chunk size used for breaking up the file
62598fcaa05bb46b3848abe9
class Worker(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, tasks, results): <NEW_LINE> <INDENT> super(Worker, self).__init__() <NEW_LINE> self.tasks = tasks <NEW_LINE> self.results = results <NEW_LINE> self.services = {} <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> result = [] <NEW_LINE> try: <NEW_LINE> <INDENT> task = self.tasks.get(block=True) <NEW_LINE> if isinstance(task, StopTask): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> result = consume_task(task, self.services) <NEW_LINE> self.results.put((task.video, result)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.error(u'Exception raised in worker %s' % self.name, exc_info=True) if sys.platform != 'win32' else logger.debug('Log line suppressed on windows') <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.tasks.task_done() <NEW_LINE> <DEDENT> <DEDENT> self.terminate() <NEW_LINE> logger.debug(u'Thread %s terminated' % self.name) if sys.platform != 'win32' else logger.debug('Log line suppressed on windows') <NEW_LINE> <DEDENT> def terminate(self): <NEW_LINE> <INDENT> for service_name, service in self.services.iteritems(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> service.terminate() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.error(u'Exception raised when terminating service %s' % service_name, exc_info=True) if sys.platform != 'win32' else logger.debug('Log line suppressed on windows')
Consume tasks and put the result in the queue
62598fca63b5f9789fe854f3
class IPaddress(models.Model): <NEW_LINE> <INDENT> ip_address = models.GenericIPAddressField(max_length=50, verbose_name='IP address', help_text=ugettext_lazy('IP address which is issued to a customer by a Remote Access Server.')) <NEW_LINE> ras = models.ForeignKey(RAS, verbose_name='Remote Access Server', help_text=ugettext_lazy('Remote Access Server which issue an IP address to a customer.')) <NEW_LINE> customer = models.ForeignKey(Customer,null=True,blank=True, verbose_name='Assigned Customer', help_text=ugettext_lazy('Customer to whom an IP address is issued by a Remote Access Server.')) <NEW_LINE> def ip_address_name(self): <NEW_LINE> <INDENT> return "%s : %s" % (self.ras.ras_name(), self.ip_address) <NEW_LINE> <DEDENT> ip_address_name.short_description = 'IP Address Name' <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.ip_address_name() <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = ugettext_lazy("IP Address") <NEW_LINE> verbose_name_plural = ugettext_lazy("IP Addresses")
IPaddress Class : IP addresses which Remote Access Servers can issue a IP address can be assigned to a customer
62598fca091ae35668704fa6
class CommandBase(Request): <NEW_LINE> <INDENT> is_command = True <NEW_LINE> _non_matched_attrs = Request._non_matched_attrs + ('command_name',) <NEW_LINE> @property <NEW_LINE> def command_name(self): <NEW_LINE> <INDENT> if self.docs and self.docs[0]: <NEW_LINE> <INDENT> return list(self.docs[0])[0] <NEW_LINE> <DEDENT> <DEDENT> def _matches_docs(self, docs, other_docs): <NEW_LINE> <INDENT> assert len(docs) == len(other_docs) == 1 <NEW_LINE> doc, = docs <NEW_LINE> other_doc, = other_docs <NEW_LINE> items = list(doc.items()) <NEW_LINE> other_items = list(other_doc.items()) <NEW_LINE> if items and other_items: <NEW_LINE> <INDENT> if items[0][0].lower() != other_items[0][0].lower(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if items[0][1] != other_items[0][1]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return super(CommandBase, self)._matches_docs( [OrderedDict(items[1:])], [OrderedDict(other_items[1:])])
A command the client executes on the server.
62598fcaff9c53063f51a9ca
class Student: <NEW_LINE> <INDENT> def __init__(self, first_name, last_name, age): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.age = age <NEW_LINE> <DEDENT> def to_json(self, attrs=None): <NEW_LINE> <INDENT> if attrs is None: <NEW_LINE> <INDENT> return self.__dict__ <NEW_LINE> <DEDENT> dict = {} <NEW_LINE> for i in attrs: <NEW_LINE> <INDENT> if i in self.__dict__: <NEW_LINE> <INDENT> dict[i] = self.__dict__[i] <NEW_LINE> <DEDENT> <DEDENT> return dict <NEW_LINE> <DEDENT> def reload_from_json(self, json): <NEW_LINE> <INDENT> if not json: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__dict__ = json
defines class Student
62598fcad8ef3951e32c801a
class HasCachedMethods(object): <NEW_LINE> <INDENT> def __init__(self, method_cache=None): <NEW_LINE> <INDENT> self._method_cache = method_cache or {} <NEW_LINE> <DEDENT> @property <NEW_LINE> def _method_cache_info(self): <NEW_LINE> <INDENT> cached_info = OrderedDict() <NEW_LINE> for k, v in self.__class__.__dict__.iteritems(): <NEW_LINE> <INDENT> if isinstance(v, property): <NEW_LINE> <INDENT> v = v.fget <NEW_LINE> <DEDENT> if hasattr(v, 'cache_info'): <NEW_LINE> <INDENT> cached_info[k] = v.cache_info() <NEW_LINE> <DEDENT> <DEDENT> return cached_info <NEW_LINE> <DEDENT> def _reset_method_cache(self): <NEW_LINE> <INDENT> if hasattr(self, '_method_cache'): <NEW_LINE> <INDENT> self._method_cache = {} <NEW_LINE> <DEDENT> for entry in self.__class__.__dict__.itervalues(): <NEW_LINE> <INDENT> if isinstance(entry, property): <NEW_LINE> <INDENT> entry = entry.fget <NEW_LINE> <DEDENT> if hasattr(entry, 'reset_cache_info'): <NEW_LINE> <INDENT> entry.reset_cache_info()
Provides convenience methods for working with :class:`cachedmethod`.
62598fcabf627c535bcb1828
class Measure(Thing): <NEW_LINE> <INDENT> def __init__(self, sensor_id, unit, medium=None, observation_type=None, description=None, id=None, material_properties=None, value_properties=None, on_index=False, outdoor=False, associated_locations=None, method=None, external_id=None, set_point=False, ambient=None): <NEW_LINE> <INDENT> super().__init__(id=id) <NEW_LINE> self.sensor_id = sensor_id <NEW_LINE> self.description = description <NEW_LINE> self.material_properties = material_properties <NEW_LINE> self.value_properties = value_properties <NEW_LINE> self.medium = medium <NEW_LINE> self.observation_type = observation_type <NEW_LINE> self.unit = unit <NEW_LINE> self.associated_locations = associated_locations or [] <NEW_LINE> self.on_index = on_index <NEW_LINE> self.outdoor = outdoor <NEW_LINE> self.external_id = external_id <NEW_LINE> self.method = method or 'Frequency' <NEW_LINE> self.set_point = set_point <NEW_LINE> self.ambient = ambient <NEW_LINE> <DEDENT> def add_external_id(self, ext_id): <NEW_LINE> <INDENT> self.external_id = ext_id
Measure description
62598fca4527f215b58ea24d
class NoteBooksTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_option_quotes(self): <NEW_LINE> <INDENT> option_data_frame = pandas.core.common.load( './quantlib/test/data/df_SPX_24jan2011.pkl' ) <NEW_LINE> df_final = Compute_IV( option_data_frame, tMin=0.5/12, nMin=6, QDMin=.2, QDMax=.8 ) <NEW_LINE> print('Number of rows: %d' % len(df_final.index)) <NEW_LINE> self.assertEqual(len(df_final.index), 553, 'Wrong number of rows')
Test some functions used in notebooks. Mostly useful to test stability of pandas API
62598fcadc8b845886d5393a
class Module_six_moves_urllib_robotparser(_LazyModule): <NEW_LINE> <INDENT> pass
Lazy loading of moved objects in scapy.modules.six.urllib_robotparser
62598fcaa219f33f346c6b87
class TableEntryWidget(urwid.AttrMap): <NEW_LINE> <INDENT> _text = None <NEW_LINE> signals = ["activate"] <NEW_LINE> def __init__(self, title): <NEW_LINE> <INDENT> self._text = SelectableText(title) <NEW_LINE> super(TableEntryWidget, self).__init__(self._text, 'table.entry', 'table.entry:focus') <NEW_LINE> <DEDENT> def keypress(self, size, key): <NEW_LINE> <INDENT> if urwid.Button._command_map[key] == 'activate': <NEW_LINE> <INDENT> self._emit('activate', None) <NEW_LINE> <DEDENT> return key <NEW_LINE> <DEDENT> def mouse_event(self, size, event, button, x, y, focus): <NEW_LINE> <INDENT> if button != 1 or not urwid.util.is_mouse_press(event): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self._emit('activate', self) <NEW_LINE> return True
An entry in a table
62598fca283ffb24f3cf3c04
class Piece: <NEW_LINE> <INDENT> def __init__(self, name, pos=0): <NEW_LINE> <INDENT> self.pos = pos <NEW_LINE> self.name = name <NEW_LINE> self.locations = [] <NEW_LINE> self.jail = False <NEW_LINE> self.jail_try = 0 <NEW_LINE> self.jail_free = False <NEW_LINE> <DEDENT> def move(self): <NEW_LINE> <INDENT> d1, d2 = self.roll() <NEW_LINE> if self.jail: <NEW_LINE> <INDENT> self.jail_turn(d1, d2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.pos += d1+d2 <NEW_LINE> <DEDENT> if self.pos > 39: <NEW_LINE> <INDENT> self.pos = self.pos - 40 <NEW_LINE> <DEDENT> if self.pos == 30: <NEW_LINE> <INDENT> self.pos = 10 <NEW_LINE> self.jail = True <NEW_LINE> <DEDENT> <DEDENT> def jail_turn(self, d1, d2): <NEW_LINE> <INDENT> if d1 == d2: <NEW_LINE> <INDENT> self.pos += d1+d2 <NEW_LINE> self.jail = False <NEW_LINE> self.jail_try = 0 <NEW_LINE> <DEDENT> elif self.jail_free: <NEW_LINE> <INDENT> self.pos += d1+d2 <NEW_LINE> self.jail = False <NEW_LINE> self.jail_try = 0 <NEW_LINE> self.jail_free = False <NEW_LINE> <DEDENT> elif self.jail_try == 2: <NEW_LINE> <INDENT> self.pos += d1+d2 <NEW_LINE> self.jail = False <NEW_LINE> self.jail_try = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.jail_try += 1 <NEW_LINE> <DEDENT> <DEDENT> def roll(self): <NEW_LINE> <INDENT> min = 1 <NEW_LINE> max = 6 <NEW_LINE> d1 = random.randint(min, max) <NEW_LINE> d2 = random.randint(min, max) <NEW_LINE> return d1, d2
Each instance of this class is a piece in the game. The class takes a name and an initial starting point as arguments.
62598fcacc40096d6161a397
class Config(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> _here = os.path.dirname(__file__) <NEW_LINE> sys.path.insert(0, os.path.abspath(os.path.join(_here, "..", ".."))) <NEW_LINE> sys.path.insert(0, os.path.abspath(os.path.join(_here))) <NEW_LINE> self.demo_root = os.path.abspath(os.path.join(_here, "..")) <NEW_LINE> self.root_url = "https://www.wikipedia.org" <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<Config: %s>" % str(self.__dict__)
Configuration variables for this test suite This creates a variable named CONFIG (${CONFIG} when included in a test as a variable file. Example: *** Settings *** | Variable | ../resources/config.py *** Test Cases *** | Example | | log | username: ${CONFIG}.username | | log | root url: ${CONFIG}.root_url
62598fca4428ac0f6e6588a6
class VtTradeData(VtBaseData): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(VtTradeData, self).__init__() <NEW_LINE> self.symbol = EMPTY_STRING <NEW_LINE> self.exchange = EMPTY_STRING <NEW_LINE> self.vtSymbol = EMPTY_STRING <NEW_LINE> self.tradeID = EMPTY_STRING <NEW_LINE> self.vtTradeID = EMPTY_STRING <NEW_LINE> self.orderID = EMPTY_STRING <NEW_LINE> self.vtOrderID = EMPTY_STRING <NEW_LINE> self.exchangeOrderID = EMPTY_STRING <NEW_LINE> self.direction = EMPTY_UNICODE <NEW_LINE> self.offset = EMPTY_UNICODE <NEW_LINE> self.price = EMPTY_FLOAT <NEW_LINE> self.volume = EMPTY_FLOAT <NEW_LINE> self.tradeTime = None <NEW_LINE> self.price_avg = EMPTY_FLOAT <NEW_LINE> self.fee = EMPTY_FLOAT <NEW_LINE> self.status = EMPTY_UNICODE <NEW_LINE> self.orderTime = EMPTY_STRING
成交数据类
62598fca851cf427c66b8633
class CompoundHeaderLine(HeaderLine): <NEW_LINE> <INDENT> def __init__(self, key, value, mapping): <NEW_LINE> <INDENT> super().__init__(key, value) <NEW_LINE> self.mapping = OrderedDict(mapping.items()) <NEW_LINE> if "Number" not in self.mapping: <NEW_LINE> <INDENT> warnings.warn( '[vcfpy] WARNING: missing number, using unbounded/"." instead', FieldMissingNumber ) <NEW_LINE> self.mapping["Number"] = "." <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.mapping["Number"] = self._parse_number(self.mapping["Number"]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> warnings.warn( ("[vcfpy] WARNING: invalid number {}, using " 'unbounded/"." instead').format( self.mapping["Number"] ), FieldInvalidNumber, ) <NEW_LINE> self.mapping["Number"] = "." <NEW_LINE> <DEDENT> <DEDENT> def copy(self): <NEW_LINE> <INDENT> mapping = OrderedDict(self.mapping.items()) <NEW_LINE> return self.__class__(self.key, self.value, mapping) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _parse_number(klass, number): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(number) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> if number in VALID_NUMBERS: <NEW_LINE> <INDENT> return number <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def value(self): <NEW_LINE> <INDENT> return mapping_to_str(self.mapping) <NEW_LINE> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> return "".join(map(str, ["##", self.key, "=", self.value])) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "CompoundHeaderLine({}, {}, {})".format( *map(repr, (self.key, self.value, self.mapping)) )
Base class for compound header lines, currently format and header lines Compound header lines describe fields that can have more than one entry. Don't use this class directly but rather the sub classes.
62598fca4c3428357761a63d
class UplinkStatusPropagationExtensionTestPlugin( db_base_plugin_v2.NeutronDbPluginV2, usp_db.UplinkStatusPropagationMixin): <NEW_LINE> <INDENT> supported_extension_aliases = [apidef.ALIAS] <NEW_LINE> @staticmethod <NEW_LINE> @resource_extend.extends([apidef.COLLECTION_NAME]) <NEW_LINE> def _extend_network_project_default(port_res, port_db): <NEW_LINE> <INDENT> return usp_db.UplinkStatusPropagationMixin._extend_port_dict( port_res, port_db) <NEW_LINE> <DEDENT> def create_port(self, context, port): <NEW_LINE> <INDENT> with context.session.begin(subtransactions=True): <NEW_LINE> <INDENT> new_port = super(UplinkStatusPropagationExtensionTestPlugin, self).create_port(context, port) <NEW_LINE> p = port['port'] <NEW_LINE> if 'propagate_uplink_status' not in p: <NEW_LINE> <INDENT> p['propagate_uplink_status'] = False <NEW_LINE> <DEDENT> self._process_create_port(context, p, new_port) <NEW_LINE> <DEDENT> return new_port
Test plugin to mixin the uplink status propagation extension.
62598fcaaad79263cf42eb4e
class VuetifyCompletions(sublime_plugin.EventListener): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.color_class_completions = [ ("%s \tColor class - Vuetify" % s, s) for s in color_classes] <NEW_LINE> <DEDENT> def on_query_completions(self, view, prefix, locations): <NEW_LINE> <INDENT> if view.match_selector(locations[0], "text.html string.quoted"): <NEW_LINE> <INDENT> LIMIT = 250 <NEW_LINE> cursor = locations[0] - len(prefix) - 1 <NEW_LINE> start = max(0, cursor - LIMIT - len(prefix)) <NEW_LINE> line = view.substr(sublime.Region(start, cursor)) <NEW_LINE> parts = line.split('=') <NEW_LINE> if len(parts) > 1 and parts[-2].strip().endswith("color"): <NEW_LINE> <INDENT> return self.color_class_completions <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> <DEDENT> elif view.match_selector(locations[0], "text.html - source"): <NEW_LINE> <INDENT> pt = locations[0] - len(prefix) - 1 <NEW_LINE> ch = view.substr(sublime.Region(pt, pt + 1)) <NEW_LINE> if ch != '<': <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (components, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return []
Provide tag completions for Vuetify elements and v-{component} attributes
62598fcad486a94d0ba2c352
class TextFile(Stream): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> self.name = name <NEW_LINE> file_handle = open(name, 'at') <NEW_LINE> Stream.__init__(self, file_handle) <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.stream.close() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._name == other.name and self.pattern == other.pattern
Destination to flush metrics to a file
62598fca0fa83653e46f5267
class DNTFile(object): <NEW_LINE> <INDENT> def __init__(self, filename): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.columns = [] <NEW_LINE> self.Row = None <NEW_LINE> self.rows = [] <NEW_LINE> <DEDENT> def read_all(self): <NEW_LINE> <INDENT> self.parse_header() <NEW_LINE> with open(self.filename, 'rb') as f: <NEW_LINE> <INDENT> f.seek(self.row_start, 0) <NEW_LINE> for i in range(self.num_rows): <NEW_LINE> <INDENT> self.read_row(f) <NEW_LINE> <DEDENT> assert f.read() == _TAIL, "Unexpected EOF" <NEW_LINE> <DEDENT> <DEDENT> def parse_header(self): <NEW_LINE> <INDENT> columns = [] <NEW_LINE> with open(self.filename, 'rb') as f: <NEW_LINE> <INDENT> header = f.read(4) <NEW_LINE> assert header == _HEADER, "Invalid header bytes: %s" % repr(header) <NEW_LINE> self.num_columns = struct.unpack('<H', f.read(2))[0] + 1 <NEW_LINE> self.num_rows = struct.unpack('<I', f.read(4))[0] <NEW_LINE> columns.append(column.Integer('id')) <NEW_LINE> while len(columns) < self.num_columns: <NEW_LINE> <INDENT> name_length = struct.unpack('<H', f.read(2))[0] <NEW_LINE> name = f.read(name_length).decode('euckr')[1:] <NEW_LINE> dtype = _TYPEMAP[struct.unpack('B', f.read(1))[0]] <NEW_LINE> columns.append(dtype(name)) <NEW_LINE> <DEDENT> self.row_start = f.tell() <NEW_LINE> <DEDENT> self.columns = columns <NEW_LINE> row_names = ['location_'] + [x.name for x in self.columns] <NEW_LINE> self.Row = namedtuple('Row', row_names) <NEW_LINE> <DEDENT> def read_row(self, f): <NEW_LINE> <INDENT> assert self.columns, "No columns defined." <NEW_LINE> data = {'location_': f.tell()} <NEW_LINE> for col in self.columns: <NEW_LINE> <INDENT> if col.datalen == column.VARIABLE_LEN: <NEW_LINE> <INDENT> datalen = col.decodelen(f.read(col.markerlen)) <NEW_LINE> data[col.name] = col.decode(f.read(datalen)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data[col.name] = col.decode(f.read(col.datalen)) <NEW_LINE> <DEDENT> <DEDENT> self.rows.append(self.Row(**data)) <NEW_LINE> <DEDENT> def write_row(self, f, row): <NEW_LINE> <INDENT> out = "" <NEW_LINE> for col, val in zip(self.columns, row[1:]): <NEW_LINE> <INDENT> out += col.encode(val) <NEW_LINE> <DEDENT> f.write(out)
Object for reading/writing DragonNest DNT files.
62598fcabf627c535bcb182a
class DrawerDriver(): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__(self, scale=1., options=None): <NEW_LINE> <INDENT> if options is None: <NEW_LINE> <INDENT> self._options = self.get_default_options(scale) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._options = options <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def get_default_options(scale=1.): <NEW_LINE> <INDENT> options = { 'display frame arrows': True, 'display links': True, 'display shapes': True, 'frame arrows length': 0.08 * scale, 'point radius': 0.008 * scale, 'plane half extents': (1. * scale, 1. * scale), 'force length': 0.1 * scale, 'force radius': 0.002 * scale} <NEW_LINE> return options <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def add_ground(self, up): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def init(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def finish(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def create_transform(self, pose, is_constant, name=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def create_frame_arrows(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def create_line(self, start, end, color, name=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def create_ellipsoid(self, radii, color, name=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create_sphere(self, radius, color, name=None): <NEW_LINE> <INDENT> return self.create_ellipsoid([radius] * 3, color) <NEW_LINE> <DEDENT> def create_point(self, color, name=None): <NEW_LINE> <INDENT> return self.create_sphere(self._options['point radius'], color) <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def create_box(self, half_extents, color, name=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def create_plane(self, coeffs, color, name=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def create_cylinder(self, length, radius, color, name=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def add_child(self, parent, child, category=None): <NEW_LINE> <INDENT> pass
ABC for drawer drivers. This class defines an interface for "drawer drivers" which take care of the low level details of drawing the world, on behalf of the :class:`arboris.visu.Drawer` class.
62598fcaab23a570cc2d4f2e
class DeploymentScriptsError(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorResponse'}, } <NEW_LINE> def __init__( self, *, error: Optional["ErrorResponse"] = None, **kwargs ): <NEW_LINE> <INDENT> super(DeploymentScriptsError, self).__init__(**kwargs) <NEW_LINE> self.error = error
Deployment scripts error response. :ivar error: Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). :vartype error: ~azure.mgmt.resource.deploymentscripts.v2020_10_01.models.ErrorResponse
62598fca4527f215b58ea24f
class Color(String): <NEW_LINE> <INDENT> pass
Color type user interface A subclass of `qargparse.String`, not production ready.
62598fcaaad79263cf42eb50
class Rescale(object): <NEW_LINE> <INDENT> def __init__(self,output_size): <NEW_LINE> <INDENT> assert isinstance(output_size, (int, tuple)) <NEW_LINE> self.output_size = output_size <NEW_LINE> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> image, landmarks = sample["image"], sample["landmarks"] <NEW_LINE> h, w = image.shape[:2] <NEW_LINE> if isinstance(self.output_size, int): <NEW_LINE> <INDENT> if h > w: <NEW_LINE> <INDENT> new_h, new_w = self.output_size* h / w , self.output_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_h, new_w = self.output_size, self.output_size* w / h <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> new_h, new_w = self.output_size <NEW_LINE> <DEDENT> new_h, new_w = int(new_h), int(new_w) <NEW_LINE> image = transform.resize(image, (new_h, new_w)) <NEW_LINE> landmarks = landmarks*[new_w / w, new_h / h] <NEW_LINE> return {"image":image, "landmarks":landmarks}
Rescale the image into a given size Args: output_size (tuple or int): Desired output size. If tuple, output is matched to output_size. If int, smaller of image edges is matched to output_size keeping aspect ratio the same.
62598fca656771135c4899f2
class Variable(object): <NEW_LINE> <INDENT> distributions = {'Normal': pyro.distributions.Normal, 'Binomial': pyro.distributions.Binomial, 'Exponential': pyro.distributions.Exponential, 'fixed': 0} <NEW_LINE> def __init__(self, internal, name, dist, param): <NEW_LINE> <INDENT> assert internal in [0,1], 'Internal must be a binary variable, i.e. can only take the values 0/1' <NEW_LINE> self.internal = internal <NEW_LINE> self.name = name <NEW_LINE> self.dist = dist <NEW_LINE> self.param = param <NEW_LINE> self.sample() <NEW_LINE> <DEDENT> def return_dist(self): <NEW_LINE> <INDENT> return Variable.distributions[self.dist](*self.param.values()) <NEW_LINE> <DEDENT> def sample(self): <NEW_LINE> <INDENT> if 'fixed' in self.dist: <NEW_LINE> <INDENT> self.current_value = self.param['fixed'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.current_value = Variable.distributions[self.dist](*self.param.values()).sample() <NEW_LINE> <DEDENT> <DEDENT> def get_current_value(self): <NEW_LINE> <INDENT> return self.current_value <NEW_LINE> <DEDENT> def __gt__(self, i): <NEW_LINE> <INDENT> c = self.get_current_value() <NEW_LINE> if c > i: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> def __eq__(self, i): <NEW_LINE> <INDENT> c = self.get_current_value() <NEW_LINE> if c == i: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> print(f'Distribution: {self.dist}') <NEW_LINE> print(f'Current Value: {self.current_value}') <NEW_LINE> return ''
Class to define a variable that is part of the psychological process. Wrapper around pyro.distribution object for easier interface.
62598fcad486a94d0ba2c354
class UTS: <NEW_LINE> <INDENT> BINARY_TYPE = ResourceType.UTS <NEW_LINE> def __init__( self ): <NEW_LINE> <INDENT> self.resref: ResRef = ResRef.from_blank() <NEW_LINE> self.tag: str = "" <NEW_LINE> self.comment: str = "" <NEW_LINE> self.active: bool = False <NEW_LINE> self.continuous: bool = False <NEW_LINE> self.looping: bool = False <NEW_LINE> self.positional: bool = False <NEW_LINE> self.random_pick: bool = False <NEW_LINE> self.random_position: bool = False <NEW_LINE> self.random_range_x: float = 0.0 <NEW_LINE> self.random_range_y: float = 0.0 <NEW_LINE> self.elevation: float = 0.0 <NEW_LINE> self.max_distance: float = 0.0 <NEW_LINE> self.min_distance: float = 0.0 <NEW_LINE> self.priority: int = 0 <NEW_LINE> self.interval: int = 0 <NEW_LINE> self.interval_variation: int = 0 <NEW_LINE> self.pitch_variation: float = 0.0 <NEW_LINE> self.volume: int = 0 <NEW_LINE> self.volume_variation: int = 0 <NEW_LINE> self.sounds: List[ResRef] = [] <NEW_LINE> self.name: LocalizedString = LocalizedString.from_invalid() <NEW_LINE> self.times: int = 0 <NEW_LINE> self.hours: int = 0 <NEW_LINE> self.palette_id: int = 0
Stores sound data. Attributes: tag: "Tag" field. resref: "TemplateResRef" field. active: "Active" field. continuous: "Continuous" field. looping: "Looping" field. positional: "Positional" field. random_position: "RandomPosition" field. random_pick: "Random" field. elevation: "Elevation" field. max_distance: "MaxDistance" field. min_distance: "MinDistance" field. random_range_x: "RandomRangeX" field. random_range_y: "RandomRangeY" field. interval: "Interval" field. interval_variation: "IntervalVrtn" field. pitch_variation: "PitchVariation" field. priority: "Priority" field. volume: "Volume" field. volume_variation: "VolumeVrtn" field. comment: "Comment" field. palette_id: "PaletteID" field. Used in toolset only. name: "LocName" field. Not used by the game engine. hours: "Hours" field. Not used by the game engine. times: "Times" field. Not used by the game engine.
62598fca956e5f7376df583f
class TableDescStats(BaseGenTableTest): <NEW_LINE> <INDENT> def runTest(self): <NEW_LINE> <INDENT> entries = self.do_table_desc_stats() <NEW_LINE> seen = set() <NEW_LINE> for entry in entries: <NEW_LINE> <INDENT> logging.debug(entry.show()) <NEW_LINE> self.assertNotIn(entry.table_id, seen) <NEW_LINE> self.assertNotIn(entry.name, seen) <NEW_LINE> seen.add(entry.table_id) <NEW_LINE> seen.add(entry.name) <NEW_LINE> if entry.table_id == TABLE_ID: <NEW_LINE> <INDENT> self.assertEqual(entry.name, "test") <NEW_LINE> self.assertEqual(entry.buckets_size, 64) <NEW_LINE> self.assertEqual(entry.max_entries, 1000) <NEW_LINE> <DEDENT> <DEDENT> self.assertIn(TABLE_ID, seen)
Test retrieving table desc stats
62598fca23849d37ff851435
class IC_7400(Base_14pin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pins = [ None, 0, 0, None, 0, 0, None, 0, None, 0, 0, None, 0, 0, 0] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> output = {} <NEW_LINE> output[3] = NAND(self.pins[1], self.pins[2]).output() <NEW_LINE> output[6] = NAND(self.pins[4], self.pins[5]).output() <NEW_LINE> output[8] = NAND(self.pins[9], self.pins[10]).output() <NEW_LINE> output[11] = NAND(self.pins[12], self.pins[13]).output() <NEW_LINE> if self.pins[7] == 0 and self.pins[14] == 1: <NEW_LINE> <INDENT> self.set_IC(output) <NEW_LINE> for i in self.output_connector: <NEW_LINE> <INDENT> self.output_connector[i].state = output[i] <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Ground and VCC pins have not been configured correctly.")
This is a QUAD 2 INPUT NAND gate IC Pin Configuration: Pin Number Description 1 A Input Gate 1 2 B Input Gate 1 3 Y Output Gate 1 4 A Input Gate 2 5 B Input Gate 2 6 Y Output Gate 2 7 Ground 8 Y Output Gate 3 9 B Input Gate 3 10 A Input Gate 3 11 Y Output Gate 4 12 B Input Gate 4 13 A Input Gate 4 14 Positive Supply This class needs 14 parameters. Each parameter being the pin value. The input has to be defined as a dictionary with pin number as the key and its value being either 1 or 0 To initialise the ic 7400: 1. set pin 7:0 2. set pin 14:1 How to use: >>> ic = IC_7400() >>> pin_config = {1: 1, 2: 0, 4: 0, 5: 0, 7: 0, 9: 1, 10: 1, 12: 0, 13: 0, 14: 1} >>> ic.set_IC(pin_cofig) >>> ic.drawIC() >>> ic.run() >>> ic.set_IC(ic.run()) >>> ic.drawIC() Methods: pins = [None,0,0,None,0,0,None,0,None,0,0,None,0,0,0]
62598fca5fdd1c0f98e5e30f
class ParseError(Exception): <NEW_LINE> <INDENT> pass
Exception raised when parsing fails
62598fca091ae35668704fad
class SLJ(Pair): <NEW_LINE> <INDENT> _cpp_class_name = 'PotentialPairSLJ' <NEW_LINE> def __init__(self, nlist, default_r_cut=None, default_r_on=0., mode='none'): <NEW_LINE> <INDENT> if mode == 'xplor': <NEW_LINE> <INDENT> raise ValueError("xplor is not a valid mode for SLJ potential") <NEW_LINE> <DEDENT> super().__init__(nlist, default_r_cut, default_r_on, mode) <NEW_LINE> params = TypeParameter( 'params', 'particle_types', TypeParameterDict(epsilon=float, sigma=float, len_keys=2)) <NEW_LINE> self._add_typeparam(params) <NEW_LINE> param_dict = ParameterDict(mode=OnlyFrom(['none', 'shift'])) <NEW_LINE> self._param_dict.update(param_dict) <NEW_LINE> self.mode = mode <NEW_LINE> self._nlist.diameter_shift = True
Shifted Lennard-Jones pair potential. Args: nlist (`hoomd.md.nlist.NList`): Neighbor list. default_r_cut (float): Default cutoff radius :math:`[\mathrm{length}]`. default_r_on (float): Default turn-on radius :math:`[\mathrm{length}]`. mode (str): Energy shifting mode. `SLJ` specifies that a shifted Lennard-Jones type pair potential should be applied between every non-excluded particle pair in the simulation. .. math:: :nowrap: \begin{eqnarray*} V_{\mathrm{SLJ}}(r) = & 4 \varepsilon \left[ \left( \frac{\sigma}{r - \Delta} \right)^{12} - \left( \frac{\sigma}{r - \Delta} \right)^{6} \right]; & r < (r_{\mathrm{cut}} + \Delta) \\ = & 0; & r \ge (r_{\mathrm{cut}} + \Delta) \\ \end{eqnarray*} where :math:`\Delta = (d_i + d_j)/2 - 1` and :math:`d_i` is the diameter of particle :math:`i`. See `Pair` for details on how forces are calculated and the available energy shifting and smoothing modes. Attention: Due to the way that `SLJ` modifies the cutoff criteria, a smoothing mode of *xplor* is not supported. Set the ``max_diameter`` property of the neighbor list object to the largest particle diameter in the system (where **diameter** is a per-particle property of the same name in `hoomd.State`). Warning: Failure to set ``max_diameter`` will result in missing pair interactions. .. py:attribute:: params The potential parameters. The dictionary has the following keys: * ``epsilon`` (`float`, **required**) - energy parameter :math:`\varepsilon` :math:`[\mathrm{energy}]` * ``sigma`` (`float`, **required**) - particle size :math:`\sigma` :math:`[\mathrm{length}]` Type: `TypeParameter` [`tuple` [``particle_type``, ``particle_type``], `dict`] Example:: nl = nlist.Cell() nl.max_diameter = 2.0 slj = pair.SLJ(default_r_cut=3.0, nlist=nl) slj.params[('A', 'B')] = dict(epsilon=2.0, r_cut=3.0) slj.r_cut[('B', 'B')] = 2**(1.0/6.0)
62598fcafbf16365ca79443d
class Mutation: <NEW_LINE> <INDENT> def __init__(self, childs, probability): <NEW_LINE> <INDENT> self.childs = childs <NEW_LINE> self.probability = probability <NEW_LINE> <DEDENT> def perform(self): <NEW_LINE> <INDENT> for i, ind in enumerate(self.childs): <NEW_LINE> <INDENT> self.__mutate(i, ind) <NEW_LINE> <DEDENT> <DEDENT> def __mutate(self, i, ind): <NEW_LINE> <INDENT> if not self.__will_mutate(): return <NEW_LINE> genes = list(ind.genes()) <NEW_LINE> mutation_gen = int(math.floor(random.random() * len(genes))) <NEW_LINE> genes[mutation_gen] = str(1 -int(genes[mutation_gen])) <NEW_LINE> ind = Individual() <NEW_LINE> ind.load_genes(''.join(genes)) <NEW_LINE> self.childs[i] = ind <NEW_LINE> <DEDENT> def __will_mutate(self): <NEW_LINE> <INDENT> return random.random() <= self.probability
Производит мутацию у потомков
62598fcaaad79263cf42eb52
class PageLinkComponent(core.LinkInline): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def defaultSettings(): <NEW_LINE> <INDENT> settings = core.LinkInline.defaultSettings() <NEW_LINE> settings['alternative'] = (None, "An alternative link to use when the file doesn't exist.") <NEW_LINE> settings['optional'] = (False, "Toggle the link as optional when the file doesn't exist.") <NEW_LINE> settings['exact'] = (False, "Enable/disable exact match for the markdown file.") <NEW_LINE> settings['language'] = (None, "The language used for source file syntax highlighting.") <NEW_LINE> return settings <NEW_LINE> <DEDENT> def createToken(self, parent, info, page, settings): <NEW_LINE> <INDENT> token = createTokenHelper('url', parent, info, page, settings) <NEW_LINE> return token or core.LinkInline.createToken(self, parent, info, page, settings)
Creates correct link when *.md files is provide, modal links when a source files is given, otherwise a core.Link token.
62598fca7c178a314d78d823
class JsonWidgetExportImportHandler(WidgetExportImportHandler): <NEW_LINE> <INDENT> def __init__(self, attributes): <NEW_LINE> <INDENT> self.attributes = attributes <NEW_LINE> <DEDENT> def read(self, widget_node, params): <NEW_LINE> <INDENT> child_nodes = dict( (noNS(c.tag), c.text.strip()) for c in widget_node.iterchildren() if noNS(c.tag) in self.attributes ) <NEW_LINE> for attr, value in child_nodes.items(): <NEW_LINE> <INDENT> params[attr] = self.attributes[attr](json.loads(value)) <NEW_LINE> <DEDENT> <DEDENT> def write(self, widget_node, params): <NEW_LINE> <INDENT> for attribute in self.attributes: <NEW_LINE> <INDENT> if params.get(attribute) is not None: <NEW_LINE> <INDENT> child = etree.Element(attribute) <NEW_LINE> child.text = json.dumps(params.get(attribute)) <NEW_LINE> widget_node.append(child)
plone.autoform widget attributes handler. May be given an arbitrary amount of attributes used on a widget, together with the expected type. The values are then parsed and stored as JSON. For example, the following xml... <field name="birthday" type="zope.schema.Date"> <form:widget type="plone.formwidget.datetime.z3cform.widget.DateWidget"> <years_range>[-100, 10]</years_range> </form:widget> </field> ...together with the following setup... Handler = JsonWidgetExportImportHandler({ 'years_range': tuple }) ...will ensure that the years_range in json is read from the xml and used as widget parameter in json.
62598fca283ffb24f3cf3c09
class TestDirectoryDomainListResults(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testDirectoryDomainListResults(self): <NEW_LINE> <INDENT> pass
DirectoryDomainListResults unit test stubs
62598fcaec188e330fdf8c1a
class RunningMax(Peak): <NEW_LINE> <INDENT> __documentation_section__ = 'Trigger Utility UGens' <NEW_LINE> __slots__ = () <NEW_LINE> _ordered_input_names = ( 'source', 'trigger', ) <NEW_LINE> _valid_calculation_rates = None <NEW_LINE> def __init__( self, calculation_rate=None, source=None, trigger=0, ): <NEW_LINE> <INDENT> Peak.__init__( self, calculation_rate=calculation_rate, source=source, trigger=trigger, ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def ar( cls, source=None, trigger=0, ): <NEW_LINE> <INDENT> from supriya.tools import synthdeftools <NEW_LINE> calculation_rate = synthdeftools.CalculationRate.AUDIO <NEW_LINE> ugen = cls._new_expanded( calculation_rate=calculation_rate, source=source, trigger=trigger, ) <NEW_LINE> return ugen <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def kr( cls, source=None, trigger=0, ): <NEW_LINE> <INDENT> from supriya.tools import synthdeftools <NEW_LINE> calculation_rate = synthdeftools.CalculationRate.CONTROL <NEW_LINE> ugen = cls._new_expanded( calculation_rate=calculation_rate, source=source, trigger=trigger, ) <NEW_LINE> return ugen <NEW_LINE> <DEDENT> @property <NEW_LINE> def source(self): <NEW_LINE> <INDENT> index = self._ordered_input_names.index('source') <NEW_LINE> return self._inputs[index] <NEW_LINE> <DEDENT> @property <NEW_LINE> def trigger(self): <NEW_LINE> <INDENT> index = self._ordered_input_names.index('trigger') <NEW_LINE> return self._inputs[index]
Tracks maximum signal amplitude. :: >>> source = ugentools.In.ar(0) >>> trigger = ugentools.Impulse.kr(1) >>> running_max = ugentools.RunningMax.ar( ... source=source, ... trigger=0, ... ) >>> running_max RunningMax.ar()
62598fca956e5f7376df5840
class DashIOAdvertisement(dbus.service.Object): <NEW_LINE> <INDENT> PATH_BASE = "/org/bluez/example/advertisement" <NEW_LINE> def __init__(self, index, service_uuid): <NEW_LINE> <INDENT> self.path = self.PATH_BASE + str(index) <NEW_LINE> self.bus = dbus.SystemBus() <NEW_LINE> self.service_uuids = [] <NEW_LINE> self.service_uuids.append(service_uuid) <NEW_LINE> self.properties = {} <NEW_LINE> self.properties["Type"] = "peripheral" <NEW_LINE> self.properties["LocalName"] = dbus.String("DashIO") <NEW_LINE> self.properties["ServiceUUIDs"] = dbus.Array(self.service_uuids, signature='s') <NEW_LINE> self.properties["IncludeTxPower"] = dbus.Boolean(True) <NEW_LINE> dbus.service.Object.__init__(self, self.bus, self.path) <NEW_LINE> self.register() <NEW_LINE> <DEDENT> def find_adapter(self, bus): <NEW_LINE> <INDENT> remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, "/"), DBUS_OM_IFACE) <NEW_LINE> objects = remote_om.GetManagedObjects() <NEW_LINE> for obj, props in objects.items(): <NEW_LINE> <INDENT> if LE_ADVERTISING_MANAGER_IFACE in props: <NEW_LINE> <INDENT> return obj <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def get_properties(self): <NEW_LINE> <INDENT> return {LE_ADVERTISEMENT_IFACE: self.properties} <NEW_LINE> <DEDENT> def get_path(self): <NEW_LINE> <INDENT> return dbus.ObjectPath(self.path) <NEW_LINE> <DEDENT> @dbus.service.method(DBUS_PROP_IFACE, in_signature="s", out_signature="a{sv}") <NEW_LINE> def GetAll(self, iface): <NEW_LINE> <INDENT> if iface != LE_ADVERTISEMENT_IFACE: <NEW_LINE> <INDENT> raise InvalidArgsException() <NEW_LINE> <DEDENT> return self.get_properties()[LE_ADVERTISEMENT_IFACE] <NEW_LINE> <DEDENT> @dbus.service.method(LE_ADVERTISEMENT_IFACE, in_signature='', out_signature='') <NEW_LINE> def Release(self): <NEW_LINE> <INDENT> logging.debug('%s: Released!', self.path) <NEW_LINE> <DEDENT> def register_ad_callback(self): <NEW_LINE> <INDENT> logging.debug("GATT advertisement registered") <NEW_LINE> <DEDENT> def register_ad_error_callback(self): <NEW_LINE> <INDENT> logging.debug("Failed to register GATT advertisement") <NEW_LINE> <DEDENT> def register(self): <NEW_LINE> <INDENT> bus = self.bus <NEW_LINE> adapter = self.find_adapter(bus) <NEW_LINE> ad_manager = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter), LE_ADVERTISING_MANAGER_IFACE) <NEW_LINE> ad_manager.RegisterAdvertisement(self.get_path(), {}, reply_handler=self.register_ad_callback, error_handler=self.register_ad_error_callback)
BLE Advertisement
62598fca60cbc95b063646c2
class HaVipDisassociateAddressIpRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.HaVipId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.HaVipId = params.get("HaVipId")
HaVipDisassociateAddressIp request structure.
62598fcacc40096d6161a39a
class SetGeometryType(Operator): <NEW_LINE> <INDENT> bl_idname = "phobos.define_geometry" <NEW_LINE> bl_label = "Define Geometry" <NEW_LINE> bl_options = {'UNDO'} <NEW_LINE> geomType : EnumProperty( items=defs.geometrytypes, name="Type", default="box", description="Phobos geometry type" ) <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> objs = context.selected_objects <NEW_LINE> for obj in objs: <NEW_LINE> <INDENT> if obj.phobostype == 'collision' or obj.phobostype == 'visual': <NEW_LINE> <INDENT> obj['geometry/type'] = self.geomType <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log("The object '" + obj.name + "' is no collision or visual.", 'WARNING') <NEW_LINE> <DEDENT> <DEDENT> log( "Changed geometry type for {} object{}".format(len(objs), 's' if len(objs) > 1 else '') + " to {}.".format(self.geomType), 'INFO', ) <NEW_LINE> log(" Objects: " + str([obj.name for obj in objs]), 'DEBUG') <NEW_LINE> return {'FINISHED'} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> ob = context.active_object <NEW_LINE> return ob is not None and ob.mode == 'OBJECT' and len(context.selected_objects) > 0 <NEW_LINE> <DEDENT> def draw(self, context): <NEW_LINE> <INDENT> layout = self.layout <NEW_LINE> layout.prop(self, 'geomType') <NEW_LINE> <DEDENT> def invoke(self, context, event): <NEW_LINE> <INDENT> return context.window_manager.invoke_props_dialog(self, width=200)
Edit geometry type of selected object(s)
62598fca71ff763f4b5e7b05
class AuthorizerFunc(Authorizer): <NEW_LINE> <INDENT> def __init__(self, f): <NEW_LINE> <INDENT> self._f = f <NEW_LINE> <DEDENT> def authorize(self, ctx, identity, ops): <NEW_LINE> <INDENT> allowed = [] <NEW_LINE> caveats = [] <NEW_LINE> for op in ops: <NEW_LINE> <INDENT> ok, fcaveats = self._f(ctx, identity, op) <NEW_LINE> allowed.append(ok) <NEW_LINE> if fcaveats is not None: <NEW_LINE> <INDENT> caveats.extend(fcaveats) <NEW_LINE> <DEDENT> <DEDENT> return allowed, caveats
Implements a simplified version of Authorizer that operates on a single operation at a time.
62598fca091ae35668704fae
class NbAbandon(Donnee): <NEW_LINE> <INDENT> cle = "nb_abandon" <NEW_LINE> expression = Donnee.compiler(r"^([0-9]+) matelots minimum$") <NEW_LINE> def __init__(self, nombre=1): <NEW_LINE> <INDENT> Donnee.__init__(self) <NEW_LINE> self.nombre = nombre <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Nombre de matelots minimum avant abandon : {}".format( self.nombre) <NEW_LINE> <DEDENT> def valeur(self): <NEW_LINE> <INDENT> return self.nombre <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def defaut(cls): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def convertir(cls, nombre): <NEW_LINE> <INDENT> return (int(nombre), )
Classe définissant la donnée de configuration 'nb_abandon'. Cette donnée de configuration permet de configurer le nombre minimum de matelots avant que l'équipage se rende. Si cette donnée est à 5 et qu'il ne reste plus que 5 matelots dans l'équipage, alors l'équipage se rend.
62598fca5fc7496912d4843c
class MachineSpecs(Base): <NEW_LINE> <INDENT> _def_cpu_cnt = {'workstation': 1, 'blade': 2, 'rackmount': 4} <NEW_LINE> _def_nic_cnt = {'workstation': 1, 'blade': 2, 'rackmount': 2} <NEW_LINE> _def_memory = {'workstation': 2048, 'blade': 8192, 'rackmount': 16384} <NEW_LINE> __tablename__ = 'machine_specs' <NEW_LINE> id = Column(Integer, Sequence('mach_specs_id_seq'), primary_key=True) <NEW_LINE> model_id = Column(Integer, ForeignKey('model.id', name='mach_spec_model_fk'), nullable=False) <NEW_LINE> cpu_id = Column(Integer, ForeignKey('cpu.id', name='mach_spec_cpu_fk'), nullable=False) <NEW_LINE> cpu_quantity = Column(Integer, nullable=False) <NEW_LINE> memory = Column(Integer, nullable=False, default=0) <NEW_LINE> disk_type = Column(Enum(64, disk_types), nullable=False) <NEW_LINE> disk_capacity = Column(Integer, nullable=False, default=36) <NEW_LINE> controller_type = Column(Enum(64, controller_types), nullable=False) <NEW_LINE> nic_count = Column(Integer, nullable=False, default=2) <NEW_LINE> nic_model_id = Column(Integer, ForeignKey('model.id', name='mach_spec_nic_model_fk'), nullable=False) <NEW_LINE> creation_date = deferred(Column(DateTime, default=datetime.now, nullable=False)) <NEW_LINE> comments = deferred(Column(String(255), nullable=True)) <NEW_LINE> model = relation(Model, innerjoin=True, foreign_keys=model_id, backref=backref('machine_specs', uselist=False)) <NEW_LINE> cpu = relation(Cpu, innerjoin=True) <NEW_LINE> nic_model = relation(Model, foreign_keys=nic_model_id) <NEW_LINE> __table_args__ = (UniqueConstraint(model_id, name='machine_specs_model_uk'),) <NEW_LINE> @property <NEW_LINE> def disk_name(self): <NEW_LINE> <INDENT> if self.controller_type == 'cciss': <NEW_LINE> <INDENT> return 'c0d0' <NEW_LINE> <DEDENT> return 'sda'
Captures the configuration hardware components for a given model
62598fcad8ef3951e32c801e
class Solution: <NEW_LINE> <INDENT> def sortedListToBST(self, head): <NEW_LINE> <INDENT> num = [] <NEW_LINE> while head: <NEW_LINE> <INDENT> num.append(head.val) <NEW_LINE> head = head.next <NEW_LINE> <DEDENT> return self.sortedArrayToBST(num) <NEW_LINE> <DEDENT> def sortedArrayToBST(self, num): <NEW_LINE> <INDENT> n = len(num) <NEW_LINE> if n == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i = n // 2 <NEW_LINE> node = TreeNode(num[i]) <NEW_LINE> node.left = self.sortedArrayToBST(num[0:i]) <NEW_LINE> node.right = self.sortedArrayToBST(num[i+1:]) <NEW_LINE> return node
@see https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
62598fcad486a94d0ba2c358
class AbstractSyncPlugin(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> NAME: typing.Optional[str] = None <NEW_LINE> @abc.abstractmethod <NEW_LINE> def configure(self, info: typing.Dict[str, typing.Any]) -> None: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def connect(self) -> None: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def disconnect(self) -> None: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def create_local_digest(self, path: pathlib.Path) -> str: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def create_remote_digest(self, path: pathlib.PurePath) -> str: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def list_path(self, path: pathlib.PurePath) -> typing.Iterable[pathlib.PurePath]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def retrieve_file(self, path: pathlib.PurePath, fileobj: typing.IO[bytes]) -> typing.Optional[int]: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def connection_schema(self) -> utils.JsonType: <NEW_LINE> <INDENT> raise NotImplementedError
The specification/"interface" a synchronization plugin implements. Every abstract method in this class is a plugin hook.
62598fca9f28863672818a3f
class NoBackupError(Error): <NEW_LINE> <INDENT> pass
Error for when you try to restore a backup but one does not exist.
62598fca283ffb24f3cf3c0b
class SlidersApp(HBox): <NEW_LINE> <INDENT> extra_generated_classes = [["SlidersApp", "SlidersApp", "HBox"]] <NEW_LINE> inputs = Instance(VBoxForm) <NEW_LINE> text = Instance(TextInput) <NEW_LINE> offset = Instance(Slider) <NEW_LINE> amplitude = Instance(Slider) <NEW_LINE> phase = Instance(Slider) <NEW_LINE> freq = Instance(Slider) <NEW_LINE> plot = Instance(Plot) <NEW_LINE> source = Instance(ColumnDataSource) <NEW_LINE> @classmethod <NEW_LINE> def create(cls): <NEW_LINE> <INDENT> obj = cls() <NEW_LINE> obj.source = ColumnDataSource(data=dict(x=[], y=[])) <NEW_LINE> obj.text = TextInput( title="title", name='title', value='my sine wave' ) <NEW_LINE> obj.offset = Slider( title="offset", name='offset', value=0.0, start=-5.0, end=5.0, step=0.1 ) <NEW_LINE> obj.amplitude = Slider( title="amplitude", name='amplitude', value=1.0, start=-5.0, end=5.0 ) <NEW_LINE> obj.phase = Slider( title="phase", name='phase', value=0.0, start=0.0, end=2*np.pi ) <NEW_LINE> obj.freq = Slider( title="frequency", name='frequency', value=1.0, start=0.1, end=5.1 ) <NEW_LINE> toolset = "crosshair,pan,reset,resize,save,wheel_zoom" <NEW_LINE> plot = figure(title_text_font_size="12pt", plot_height=400, plot_width=400, tools=toolset, title=obj.text.value, x_range=[0, 4*np.pi], y_range=[-2.5, 2.5] ) <NEW_LINE> plot.line('x', 'y', source=obj.source, line_width=3, line_alpha=0.6 ) <NEW_LINE> obj.plot = plot <NEW_LINE> obj.update_data() <NEW_LINE> obj.inputs = VBoxForm( children=[ obj.text, obj.offset, obj.amplitude, obj.phase, obj.freq ] ) <NEW_LINE> obj.children.append(obj.inputs) <NEW_LINE> obj.children.append(obj.plot) <NEW_LINE> return obj <NEW_LINE> <DEDENT> def setup_events(self): <NEW_LINE> <INDENT> super(SlidersApp, self).setup_events() <NEW_LINE> if not self.text: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.text.on_change('value', self, 'input_change') <NEW_LINE> for w in ["offset", "amplitude", "phase", "freq"]: <NEW_LINE> <INDENT> getattr(self, w).on_change('value', self, 'input_change') <NEW_LINE> <DEDENT> <DEDENT> def input_change(self, obj, attrname, old, new): <NEW_LINE> <INDENT> self.update_data() <NEW_LINE> self.plot.title = self.text.value <NEW_LINE> <DEDENT> def update_data(self): <NEW_LINE> <INDENT> N = 200 <NEW_LINE> a = self.amplitude.value <NEW_LINE> b = self.offset.value <NEW_LINE> w = self.phase.value <NEW_LINE> k = self.freq.value <NEW_LINE> x = np.linspace(0, 4*np.pi, N) <NEW_LINE> y = a*np.sin(k*x + w) + b <NEW_LINE> logging.debug( "PARAMS: offset: %s amplitude: %s", self.offset.value, self.amplitude.value ) <NEW_LINE> self.source.data = dict(x=x, y=y)
An example of a browser-based, interactive plot with slider controls.
62598fcaec188e330fdf8c1c
class Card(object): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return '<Card: {0}, estimation: {1}>'.format(self.name, self.task_estimate or 'None') <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def __init__(self, containing_list, card_dict, status): <NEW_LINE> <INDENT> self.status = status <NEW_LINE> self.list = containing_list <NEW_LINE> self.name = card_dict['name'] <NEW_LINE> try: <NEW_LINE> <INDENT> self.task_estimate = int(re.search(r'\((\d+)k\)', self.name).group(1)) <NEW_LINE> <DEDENT> except (IndexError, AttributeError): <NEW_LINE> <INDENT> self.task_estimate = 0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.case_number = int(re.search(r'^\[?(\d+)', self.name).group(1)) <NEW_LINE> <DEDENT> except (IndexError, AttributeError): <NEW_LINE> <INDENT> self.case_number = None <NEW_LINE> <DEDENT> if card_dict['idMembers'] != []: <NEW_LINE> <INDENT> self.assigned_to = User.query.filter(User.trello_user_id.in_(card_dict['idMembers'])).all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assigned_to = []
Represents a Trello card.
62598fcaa219f33f346c6b8f
class DynamicOperation(Operation): <NEW_LINE> <INDENT> def __call__(self, map_obj, **params): <NEW_LINE> <INDENT> self.p = param.ParamOverrides(self, params) <NEW_LINE> callback = self._dynamic_operation(map_obj) <NEW_LINE> if isinstance(map_obj, DynamicMap): <NEW_LINE> <INDENT> return map_obj.clone(callback=callback, shared_data=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._make_dynamic(map_obj, callback) <NEW_LINE> <DEDENT> <DEDENT> def _process(self, element): <NEW_LINE> <INDENT> return element <NEW_LINE> <DEDENT> def _dynamic_operation(self, map_obj): <NEW_LINE> <INDENT> if not isinstance(map_obj, DynamicMap): <NEW_LINE> <INDENT> def dynamic_operation(*key): <NEW_LINE> <INDENT> return self._process(map_obj[key]) <NEW_LINE> <DEDENT> return dynamic_operation <NEW_LINE> <DEDENT> def dynamic_operation(*key): <NEW_LINE> <INDENT> key = key[0] if map_obj.mode == 'open' else key <NEW_LINE> _, el = util.get_dynamic_item(map_obj, map_obj.kdims, key) <NEW_LINE> return self._process(el) <NEW_LINE> <DEDENT> return dynamic_operation <NEW_LINE> <DEDENT> def _make_dynamic(self, hmap, dynamic_fn): <NEW_LINE> <INDENT> dim_values = zip(*hmap.data.keys()) <NEW_LINE> params = util.get_param_values(hmap) <NEW_LINE> kdims = [d(values=list(values)) for d, values in zip(hmap.kdims, dim_values)] <NEW_LINE> return DynamicMap(dynamic_fn, **dict(params, kdims=kdims))
Dynamically applies an operation to the elements of a HoloMap or DynamicMap. Will return a DynamicMap wrapping the original map object, which will lazily evaluate when a key is requested. The _process method should be overridden in subclasses to apply a specific operation, DynamicOperation itself applies a no-op, making the DynamicOperation baseclass useful for converting existing HoloMaps to a DynamicMap.
62598fca5fcc89381b266310
class TodoForm(FlaskForm): <NEW_LINE> <INDENT> title = StringField(label=('Enter Task:'), validators=[DataRequired()]) <NEW_LINE> state = SelectField(u'Select State', choices=[( 'todo'), ('in-progress'), ('done')]) <NEW_LINE> submit = SubmitField('Add')
Todo form.
62598fca3d592f4c4edbb239
class DescribeEdgeSnNodesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.EdgeUnitId = None <NEW_LINE> self.NamePattern = None <NEW_LINE> self.SNPattern = None <NEW_LINE> self.RemarkPattern = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.EdgeUnitId = params.get("EdgeUnitId") <NEW_LINE> self.NamePattern = params.get("NamePattern") <NEW_LINE> self.SNPattern = params.get("SNPattern") <NEW_LINE> self.RemarkPattern = params.get("RemarkPattern") <NEW_LINE> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set))
DescribeEdgeSnNodes请求参数结构体
62598fcabe7bc26dc925201e
class VendingMachine(object): <NEW_LINE> <INDENT> def __init__(self, product, price): <NEW_LINE> <INDENT> self.product = product <NEW_LINE> self.price = price <NEW_LINE> self.balance = 0 <NEW_LINE> self.stock = 0 <NEW_LINE> <DEDENT> def restock(self, stock): <NEW_LINE> <INDENT> self.stock += stock <NEW_LINE> return (('Current {0} stock: {1}').format(self.product, self.stock)) <NEW_LINE> <DEDENT> def vend(self): <NEW_LINE> <INDENT> if self.stock < 1: <NEW_LINE> <INDENT> return ('Machine is out of stock.') <NEW_LINE> <DEDENT> elif self.balance < self.price: <NEW_LINE> <INDENT> return (('You must deposit ${0} more.').format(self.price-self.balance)) <NEW_LINE> <DEDENT> elif self.balance > self.price: <NEW_LINE> <INDENT> charge = self.balance - self.price <NEW_LINE> self.stock -= 1 <NEW_LINE> self.balance = 0 <NEW_LINE> return (('Here is your {0} and ${1} change.').format(self.product, charge)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stock -= 1 <NEW_LINE> self.balance = 0 <NEW_LINE> return (('Here is your {0}.').format(self.product)) <NEW_LINE> <DEDENT> <DEDENT> def deposit(self, amount): <NEW_LINE> <INDENT> if self.stock < 1: <NEW_LINE> <INDENT> return (('Machine is out of stock. Here is your ${0}.').format(amount)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.balance += amount <NEW_LINE> return (('Current balance: ${0}').format(self.balance))
A vending machine that vends some product for some price. >>> v = VendingMachine('crab', 10) >>> v.vend() 'Machine is out of stock.' >>> v.restock(2) 'Current crab stock: 2' >>> v.vend() 'You must deposit $10 more.' >>> v.deposit(7) 'Current balance: $7' >>> v.vend() 'You must deposit $3 more.' >>> v.deposit(5) 'Current balance: $12' >>> v.vend() 'Here is your crab and $2 change.' >>> v.deposit(10) 'Current balance: $10' >>> v.vend() 'Here is your crab.' >>> v.deposit(15) 'Machine is out of stock. Here is your $15.'
62598fca283ffb24f3cf3c0c
class TestSendSmtpEmailSender(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testSendSmtpEmailSender(self): <NEW_LINE> <INDENT> pass
SendSmtpEmailSender unit test stubs
62598fcaf9cc0f698b1c5496
class SubscriberList(ListCreateAPIView): <NEW_LINE> <INDENT> serializer_class = SubscriberSerializer <NEW_LINE> model = Subscriber <NEW_LINE> permission_classes = property(_permission_classes) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> return self.model.objects.filter(user=self.request.user) <NEW_LINE> <DEDENT> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user=self.request.user)
List and create new subscriptions for the currently logged in user.
62598fca26068e7796d4cce3
class GlobalConf(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.source_solver = SourceSolverConf() <NEW_LINE> self.script_solver = ScriptSolverConf() <NEW_LINE> self.model_solver = ModelSolverConf() <NEW_LINE> self.valid_solver = ValidConf()
The definition of global configuration
62598fca5fc7496912d4843d
class Normalize(object): <NEW_LINE> <INDENT> def __init__(self, mean, std): <NEW_LINE> <INDENT> self.mean = mean <NEW_LINE> self.std = std <NEW_LINE> <DEDENT> def __call__(self, tensor): <NEW_LINE> <INDENT> return F.normalize(tensor, self.mean, self.std)
用均值和标准偏差对张量图像进行归一化. 给定均值: ``(M1,...,Mn)`` 和标准差: ``(S1,..,Sn)`` 用于 ``n`` 个通道, 该变换将标准化输入 ``torch.*Tensor`` 的每一个通道. 例如: ``input[channel] = (input[channel] - mean[channel]) / std[channel]`` Args: mean (sequence): 每一个通道的均值序列. std (sequence): 每一个通道的标准差序列.
62598fca851cf427c66b863b
class InstanceView(object): <NEW_LINE> <INDENT> def __init__(self, instance, req=None): <NEW_LINE> <INDENT> self.instance = instance <NEW_LINE> self.req = req <NEW_LINE> <DEDENT> def data(self): <NEW_LINE> <INDENT> instance_dict = { "id": self.instance.id, "name": self.instance.name, "status": self.instance.status, "links": self._build_links(), "flavor": self._build_flavor_info(), "datastore": {"type": self.instance.datastore.name, "version": self.instance.datastore_version.name}, } <NEW_LINE> if CONF.trove_volume_support: <NEW_LINE> <INDENT> instance_dict['volume'] = {'size': self.instance.volume_size} <NEW_LINE> <DEDENT> LOG.debug(instance_dict) <NEW_LINE> return {"instance": instance_dict} <NEW_LINE> <DEDENT> def _build_links(self): <NEW_LINE> <INDENT> return create_links("instances", self.req, self.instance.id) <NEW_LINE> <DEDENT> def _build_flavor_info(self): <NEW_LINE> <INDENT> return { "id": self.instance.flavor_id, "links": self._build_flavor_links() } <NEW_LINE> <DEDENT> def _build_flavor_links(self): <NEW_LINE> <INDENT> return create_links("flavors", self.req, self.instance.flavor_id)
Uses a SimpleInstance.
62598fcaff9c53063f51a9d4
class Sin(Func): <NEW_LINE> <INDENT> function = 'SIN' <NEW_LINE> name = 'Sin'
SQL function for calculating the sine.
62598fca283ffb24f3cf3c0d
class PackageXmlAnalyzer(PackageAnalyzer): <NEW_LINE> <INDENT> def analyze_file(self, path: str, dependencies: dict) -> dict: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> file = open(path, "r") <NEW_LINE> tree = parse(file) <NEW_LINE> <DEDENT> except ParseError: <NEW_LINE> <INDENT> logging.warning("[PackageXmlAnalyzer]: Could not parse " + path + "; omitting file.") <NEW_LINE> return dependencies <NEW_LINE> <DEDENT> element = tree.getroot() <NEW_LINE> packagename = element.find('name').text <NEW_LINE> for tag in self._settings["package_xml_dependency_tags"]: <NEW_LINE> <INDENT> for element in element.findall(tag): <NEW_LINE> <INDENT> self.add_dependency(packagename, element.text, dependencies) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _analyze(self, path: str) -> dict: <NEW_LINE> <INDENT> packages = dict() <NEW_LINE> filellist = self.search_files(path, "package.xml") <NEW_LINE> for filename in filellist: <NEW_LINE> <INDENT> logging.info("[PackageXmlAnalyzer]: Analyzing " + filename) <NEW_LINE> self.analyze_file(filename, packages) <NEW_LINE> <DEDENT> return packages
Analyzer plug-in for ROS' package.xml files (catkin).
62598fcaab23a570cc2d4f32
class Paths(object): <NEW_LINE> <INDENT> def __init__(self, root_dir, project_dir, variant_dir): <NEW_LINE> <INDENT> self._root_dir = root_dir <NEW_LINE> self._project_dir = project_dir <NEW_LINE> self._variant_dir = variant_dir <NEW_LINE> self._sources_dir = root_dir.Dir('sources') <NEW_LINE> self._tools_dir = root_dir.Dir('tools') <NEW_LINE> <DEDENT> def module_build_file(self, module_name): <NEW_LINE> <INDENT> return self._sources_dir.Dir(module_name).File('sconscript') <NEW_LINE> <DEDENT> def variant_dir(self, module_name=None): <NEW_LINE> <INDENT> if module_name is None: <NEW_LINE> <INDENT> module_name = self.active_module_name() <NEW_LINE> <DEDENT> return self._variant_dir.Dir(module_name) <NEW_LINE> <DEDENT> def include_dir(self, module_name=None): <NEW_LINE> <INDENT> if module_name is None: <NEW_LINE> <INDENT> module_name = self.active_module_name() <NEW_LINE> <DEDENT> return self._sources_dir.Dir(module_name).Dir('src').Dir('include') <NEW_LINE> <DEDENT> def active_module_name(self): <NEW_LINE> <INDENT> module_path = scons.Dir('.').srcnode().path <NEW_LINE> return os.path.basename(os.path.normpath(module_path)) <NEW_LINE> <DEDENT> def unit_test_executable(self, module_name=None): <NEW_LINE> <INDENT> if module_name is None: <NEW_LINE> <INDENT> module_name = self.active_module_name() <NEW_LINE> <DEDENT> return self.variant_dir(module_name).File('test/' + module_name + '_test') <NEW_LINE> <DEDENT> def unit_test_library_build_file(self): <NEW_LINE> <INDENT> return self._tools_dir.Dir('gtest').File('sconscript') <NEW_LINE> <DEDENT> def glob(self, root_dir, pattern): <NEW_LINE> <INDENT> source_root = scons.Dir(root_dir).srcnode() <NEW_LINE> absolute_path = source_root.abspath[:-len(root_dir)] <NEW_LINE> absolute_index = len(absolute_path) <NEW_LINE> patterns = [] <NEW_LINE> for root, dirs, files in os.walk(source_root.abspath): <NEW_LINE> <INDENT> relative_path = root[absolute_index:] <NEW_LINE> glob_pattern = os.path.join(relative_path, pattern) <NEW_LINE> patterns.append(glob_pattern) <NEW_LINE> <DEDENT> files = [] <NEW_LINE> for p in patterns: <NEW_LINE> <INDENT> files.extend(scons.Glob(p)) <NEW_LINE> <DEDENT> return files
Defines common paths used for builds.
62598fca283ffb24f3cf3c0e
class PickleLoader(object): <NEW_LINE> <INDENT> def __init__(self, dir, letters=None): <NEW_LINE> <INDENT> if letters is not None: <NEW_LINE> <INDENT> letters = letters.upper() <NEW_LINE> <DEDENT> self.dir = dir <NEW_LINE> self.letters = letters <NEW_LINE> <DEDENT> def iterate(self): <NEW_LINE> <INDENT> for letter in string.ascii_uppercase: <NEW_LINE> <INDENT> if self.letters is None or letter in self.letters: <NEW_LINE> <INDENT> f = os.path.join(self.dir, letter) <NEW_LINE> if os.path.isfile(f): <NEW_LINE> <INDENT> with open(f, 'rb') as filehandle: <NEW_LINE> <INDENT> while 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sense = pickle.load(filehandle) <NEW_LINE> <DEDENT> except EOFError: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> yield sense
Iterator for loading and returning a series of SenseObjects from a sequence of pickled files
62598fca4428ac0f6e6588b0
class Orden(models.Model): <NEW_LINE> <INDENT> cliente = models.ForeignKey(Cliente, related_name='ordenes') <NEW_LINE> estado = models.ForeignKey(EstadoOrden, related_name='ordenes') <NEW_LINE> fechafin = models.DateField(null=True) <NEW_LINE> fechainicio = models.DateField(default=timezone.now) <NEW_LINE> observaciones = models.TextField(max_length=2048, null=True) <NEW_LINE> resolucion = models.TextField(max_length=2048, null=True) <NEW_LINE> responsable = models.ForeignKey(Operario, related_name='ordenes') <NEW_LINE> solicitud = models.TextField(max_length=2048) <NEW_LINE> @classmethod <NEW_LINE> def create(cls, cliente, estado, fechainicio, responsable, solicitud): <NEW_LINE> <INDENT> return Orden(cliente=cliente, estado=estado, fechainicio=fechainicio, responsable=responsable, solicitud=solicitud) <NEW_LINE> <DEDENT> def __str__(self,): <NEW_LINE> <INDENT> return "{} - {}: {}".format(self.pk, self.cliente, self.solicitud)
Esta clase incluye los datos de cabecera de una orden de trabajo
62598fca63b5f9789fe854ff
class ComposeTransform(Transform): <NEW_LINE> <INDENT> def __init__(self, parts): <NEW_LINE> <INDENT> super(ComposeTransform, self).__init__() <NEW_LINE> self.parts = parts <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ComposeTransform): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.parts == other.parts <NEW_LINE> <DEDENT> @constraints.dependent_property <NEW_LINE> def domain(self): <NEW_LINE> <INDENT> if not self.parts: <NEW_LINE> <INDENT> return constraints.real <NEW_LINE> <DEDENT> return self.parts[0].domain <NEW_LINE> <DEDENT> @constraints.dependent_property <NEW_LINE> def codomain(self): <NEW_LINE> <INDENT> if not self.parts: <NEW_LINE> <INDENT> return constraints.real <NEW_LINE> <DEDENT> return self.parts[-1].codomain <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def bijective(self): <NEW_LINE> <INDENT> return all(p.bijective for p in self.parts) <NEW_LINE> <DEDENT> @lazy_property <NEW_LINE> def event_dim(self): <NEW_LINE> <INDENT> return max(p.event_dim for p in self.parts) if self.parts else 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def inv(self): <NEW_LINE> <INDENT> inv = None <NEW_LINE> if self._inv is not None: <NEW_LINE> <INDENT> inv = self._inv() <NEW_LINE> <DEDENT> if inv is None: <NEW_LINE> <INDENT> inv = ComposeTransform([p.inv for p in reversed(self.parts)]) <NEW_LINE> self._inv = weakref.ref(inv) <NEW_LINE> inv._inv = weakref.ref(self) <NEW_LINE> <DEDENT> return inv <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> for part in self.parts: <NEW_LINE> <INDENT> x = part(x) <NEW_LINE> <DEDENT> return x <NEW_LINE> <DEDENT> def log_abs_det_jacobian(self, x, y): <NEW_LINE> <INDENT> if not self.parts: <NEW_LINE> <INDENT> return x.new([0]).expand_as(x) <NEW_LINE> <DEDENT> result = 0 <NEW_LINE> for part in self.parts: <NEW_LINE> <INDENT> y = part(x) <NEW_LINE> result += _sum_rightmost(part.log_abs_det_jacobian(x, y), self.event_dim - part.event_dim) <NEW_LINE> x = y <NEW_LINE> <DEDENT> return result
Composes multiple transforms in a chain. The transforms being composed are responsible for caching. Args: parts (list of :class:`Transform`): A list of transforms to compose.
62598fca099cdd3c636755a6
class Command(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'command' <NEW_LINE> __table_args__ = ( UniqueConstraint('jobstep_id', 'order', name='unq_command_order'), ) <NEW_LINE> id = Column(GUID, primary_key=True, default=uuid.uuid4) <NEW_LINE> jobstep_id = Column(GUID, ForeignKey('jobstep.id', ondelete="CASCADE"), nullable=False) <NEW_LINE> label = Column(String(128), nullable=False) <NEW_LINE> status = Column(EnumType(Status), nullable=False, default=Status.unknown) <NEW_LINE> return_code = Column(Integer, nullable=True) <NEW_LINE> script = Column(Text(), nullable=False) <NEW_LINE> env = Column(JSONEncodedDict, nullable=True) <NEW_LINE> cwd = Column(String(256), nullable=True) <NEW_LINE> artifacts = Column(ARRAY(String(256)), nullable=True) <NEW_LINE> date_started = Column(DateTime) <NEW_LINE> date_finished = Column(DateTime) <NEW_LINE> date_created = Column(DateTime, default=datetime.utcnow) <NEW_LINE> data = Column(JSONEncodedDict) <NEW_LINE> order = Column(Integer, default=0, server_default='0', nullable=False) <NEW_LINE> type = Column(EnumType(CommandType), nullable=False, default=CommandType.default, server_default='0') <NEW_LINE> jobstep = relationship('JobStep', backref=backref('commands', order_by='Command.order')) <NEW_LINE> __repr__ = model_repr('jobstep_id', 'script') <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Command, self).__init__(**kwargs) <NEW_LINE> if self.id is None: <NEW_LINE> <INDENT> self.id = uuid.uuid4() <NEW_LINE> <DEDENT> if self.status is None: <NEW_LINE> <INDENT> self.status = Status.unknown <NEW_LINE> <DEDENT> if self.date_created is None: <NEW_LINE> <INDENT> self.date_created = datetime.utcnow() <NEW_LINE> <DEDENT> if self.data is None: <NEW_LINE> <INDENT> self.data = {} <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def duration(self): <NEW_LINE> <INDENT> if self.date_started and self.date_finished: <NEW_LINE> <INDENT> duration = (self.date_finished - self.date_started).total_seconds() * 1000 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> duration = None <NEW_LINE> <DEDENT> return duration
The information of the script run on one node within a jobstep: the contents of the script are included, and later the command can be updated with status/return code. changes-client has no real magic beyond running commands, so the list of commands it ran basically tells you everything that happened. Looks like only mesos/lxc builds (DefaultBuildStep)
62598fca7cff6e4e811b5db1
class Comparator(Query): <NEW_LINE> <INDENT> def __init__(self, index, value): <NEW_LINE> <INDENT> self.index = index <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> def _get_value(self, names, value=_marker): <NEW_LINE> <INDENT> if value is _marker: <NEW_LINE> <INDENT> value = self._value <NEW_LINE> <DEDENT> if isinstance(value, list): <NEW_LINE> <INDENT> return [self._get_value(names, child) for child in value] <NEW_LINE> <DEDENT> elif isinstance(value, tuple): <NEW_LINE> <INDENT> return tuple(self._get_value(names, child) for child in value) <NEW_LINE> <DEDENT> elif isinstance(value, Name): <NEW_LINE> <INDENT> name = value.name <NEW_LINE> if name not in names: <NEW_LINE> <INDENT> raise NameError("No value passed in for name: %s" % name) <NEW_LINE> <DEDENT> return names[name] <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ' '.join((self.index.qname(), self.operator, repr(self._value))) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return (type(self) == type(other) and self.index == other.index and self._value == other._value) <NEW_LINE> <DEDENT> def flush(self, *arg, **kw): <NEW_LINE> <INDENT> self.index.flush(*arg, **kw) <NEW_LINE> <DEDENT> def execute(self, optimize=True, names=None, resolver=None): <NEW_LINE> <INDENT> if optimize: <NEW_LINE> <INDENT> query = self._optimize() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = self <NEW_LINE> <DEDENT> return self.index.resultset_from_query( query, names=names, resolver=resolver )
Base class for all comparators used in queries.
62598fca3346ee7daa33780c
class CheckersBase(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.reporter = ProblemReporter() <NEW_LINE> <DEDENT> def run(self, checker, path): <NEW_LINE> <INDENT> self.reporter.clear_problems() <NEW_LINE> controller._run_checker(checker, False, path) <NEW_LINE> <DEDENT> def get_reported_lines(self): <NEW_LINE> <INDENT> problems = self.reporter.get_problems() <NEW_LINE> lines = [] <NEW_LINE> for problem in problems.values()[0]: <NEW_LINE> <INDENT> lines.append(problem.line) <NEW_LINE> <DEDENT> return lines
Base class to use checkers test
62598fca7c178a314d78d829
class EDISegmentError(TransactionError): <NEW_LINE> <INDENT> pass
Class for EDISegment
62598fca3d592f4c4edbb23d
class _IndicatorColumn(_DenseColumn, _SequenceDenseColumn, collections.namedtuple('_IndicatorColumn', ['categorical_column'])): <NEW_LINE> <INDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return '{}_indicator'.format(self.categorical_column.name) <NEW_LINE> <DEDENT> def _transform_feature(self, inputs): <NEW_LINE> <INDENT> id_weight_pair = self.categorical_column._get_sparse_tensors(inputs) <NEW_LINE> id_tensor = id_weight_pair.id_tensor <NEW_LINE> weight_tensor = id_weight_pair.weight_tensor <NEW_LINE> if weight_tensor is not None: <NEW_LINE> <INDENT> weighted_column = sparse_ops.sparse_merge( sp_ids=id_tensor, sp_values=weight_tensor, vocab_size=int(self._variable_shape[-1])) <NEW_LINE> weighted_column = sparse_ops.sparse_slice(weighted_column, [0, 0], weighted_column.dense_shape) <NEW_LINE> return array_ops.scatter_nd(weighted_column.indices, weighted_column.values, weighted_column.dense_shape) <NEW_LINE> <DEDENT> dense_id_tensor = sparse_ops.sparse_tensor_to_dense( id_tensor, default_value=-1) <NEW_LINE> one_hot_id_tensor = array_ops.one_hot( dense_id_tensor, depth=self._variable_shape[-1], on_value=1.0, off_value=0.0) <NEW_LINE> return math_ops.reduce_sum(one_hot_id_tensor, axis=[-2]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _parse_example_spec(self): <NEW_LINE> <INDENT> return self.categorical_column._parse_example_spec <NEW_LINE> <DEDENT> @property <NEW_LINE> def _variable_shape(self): <NEW_LINE> <INDENT> return tensor_shape.TensorShape([1, self.categorical_column._num_buckets]) <NEW_LINE> <DEDENT> def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None): <NEW_LINE> <INDENT> del weight_collections <NEW_LINE> del trainable <NEW_LINE> if isinstance(self.categorical_column, _SequenceCategoricalColumn): <NEW_LINE> <INDENT> raise ValueError( 'In indicator_column: {}. ' 'categorical_column must not be of type _SequenceCategoricalColumn. ' 'Suggested fix A: If you wish to use input_layer, use a ' 'non-sequence categorical_column_with_*. ' 'Suggested fix B: If you wish to create sequence input, use ' 'sequence_input_layer instead of input_layer. ' 'Given (type {}): {}'.format( self.name, type(self.categorical_column), self.categorical_column)) <NEW_LINE> <DEDENT> return inputs.get(self) <NEW_LINE> <DEDENT> def _get_sequence_dense_tensor( self, inputs, weight_collections=None, trainable=None): <NEW_LINE> <INDENT> del weight_collections <NEW_LINE> del trainable <NEW_LINE> if not isinstance(self.categorical_column, _SequenceCategoricalColumn): <NEW_LINE> <INDENT> raise ValueError( 'In indicator_column: {}. ' 'categorical_column must be of type _SequenceCategoricalColumn ' 'to use sequence_input_layer. ' 'Suggested fix: Use one of sequence_categorical_column_with_*. ' 'Given (type {}): {}'.format( self.name, type(self.categorical_column), self.categorical_column)) <NEW_LINE> <DEDENT> dense_tensor = inputs.get(self) <NEW_LINE> sparse_tensors = self.categorical_column._get_sparse_tensors(inputs) <NEW_LINE> sequence_length = _sequence_length_from_sparse_tensor( sparse_tensors.id_tensor) <NEW_LINE> return _SequenceDenseColumn.TensorSequenceLengthPair( dense_tensor=dense_tensor, sequence_length=sequence_length)
Represents a one-hot column for use in deep networks. Args: categorical_column: A `_CategoricalColumn` which is created by `categorical_column_with_*` function.
62598fca5fcc89381b266312
class ModifyAnimatedGraphicsTemplateRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Definition = None <NEW_LINE> self.Name = None <NEW_LINE> self.Width = None <NEW_LINE> self.Height = None <NEW_LINE> self.ResolutionAdaptive = None <NEW_LINE> self.Format = None <NEW_LINE> self.Fps = None <NEW_LINE> self.Quality = None <NEW_LINE> self.Comment = None <NEW_LINE> self.SubAppId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Definition = params.get("Definition") <NEW_LINE> self.Name = params.get("Name") <NEW_LINE> self.Width = params.get("Width") <NEW_LINE> self.Height = params.get("Height") <NEW_LINE> self.ResolutionAdaptive = params.get("ResolutionAdaptive") <NEW_LINE> self.Format = params.get("Format") <NEW_LINE> self.Fps = params.get("Fps") <NEW_LINE> self.Quality = params.get("Quality") <NEW_LINE> self.Comment = params.get("Comment") <NEW_LINE> self.SubAppId = params.get("SubAppId")
ModifyAnimatedGraphicsTemplate request structure.
62598fcabe7bc26dc9252020
class Book(models.Model): <NEW_LINE> <INDENT> title = models.CharField(max_length=200) <NEW_LINE> author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) <NEW_LINE> summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book") <NEW_LINE> isbn = models.CharField( 'ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>' ) <NEW_LINE> genre = models.ManyToManyField(Genre, help_text="Select a genre for this book") <NEW_LINE> def display_genre(self): <NEW_LINE> <INDENT> return ', '.join([genre.name for genre in self.genre.all()[:3]]) <NEW_LINE> <DEDENT> display_genre.short_description = 'Genre' <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('book-detail', args=[str(self.id)])
Model representing a book (but not a specific copy of a book).
62598fcaadb09d7d5dc0a905
class SignatureEnvelopeSettingsInfo: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.swaggerTypes = { 'ownerShouldSign': 'bool', 'orderedSignature': 'bool', 'reminderTime': 'float', 'stepExpireTime': 'float', 'envelopeExpireTime': 'float', 'emailSubject': 'str', 'emailBody': 'str', 'isDemo': 'bool', 'waterMarkText': 'str', 'waterMarkImage': 'str', 'attachSignedDocument': 'bool', 'includeViewLink': 'bool', 'canBeCommented': 'bool', 'inPersonSign': 'bool' } <NEW_LINE> self.ownerShouldSign = None <NEW_LINE> self.orderedSignature = None <NEW_LINE> self.reminderTime = None <NEW_LINE> self.stepExpireTime = None <NEW_LINE> self.envelopeExpireTime = None <NEW_LINE> self.emailSubject = None <NEW_LINE> self.emailBody = None <NEW_LINE> self.isDemo = None <NEW_LINE> self.waterMarkText = None <NEW_LINE> self.waterMarkImage = None <NEW_LINE> self.attachSignedDocument = None <NEW_LINE> self.includeViewLink = None <NEW_LINE> self.canBeCommented = None <NEW_LINE> self.inPersonSign = None
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fca851cf427c66b863f
class DummyBaseEvent(object): <NEW_LINE> <INDENT> event_type = "boussole-dummy" <NEW_LINE> is_directory = False <NEW_LINE> def __init__(self, src, dst=None): <NEW_LINE> <INDENT> self.src_path = src <NEW_LINE> self.dest_path = dst or src
Dummy event base to pass to almost all handler event methods
62598fca50812a4eaa620daa
class DataCitePreconditionError(DataCiteRequestError): <NEW_LINE> <INDENT> pass
metadata must be uploaded first
62598fca283ffb24f3cf3c11
class Gifts(Setting): <NEW_LINE> <INDENT> def __init__(self, x, y, hw=25, hh=25, c=25): <NEW_LINE> <INDENT> super().__init__(x, y, hw, hh, c) <NEW_LINE> self.anchor = (0, 0) <NEW_LINE> self.get_sprite() <NEW_LINE> self.scale = 0.1 <NEW_LINE> <DEDENT> def get_sprite(self): <NEW_LINE> <INDENT> s = Sprite('pic/lipin.png') <NEW_LINE> self.add(s)
给玩家回血的物体
62598fcaec188e330fdf8c22
class Analyzer(): <NEW_LINE> <INDENT> def __init__(self, positives, negatives): <NEW_LINE> <INDENT> self.dic = {} <NEW_LINE> load_dictionary(self, positives, 1) <NEW_LINE> load_dictionary(self, negatives, -1) <NEW_LINE> <DEDENT> def analyze(self, tweet): <NEW_LINE> <INDENT> score = 0 <NEW_LINE> tokenizer = nltk.tokenize.TweetTokenizer(preserve_case = False) <NEW_LINE> tokens = tokenizer.tokenize(tweet) <NEW_LINE> for word in tokens: <NEW_LINE> <INDENT> if word in self.dic: <NEW_LINE> <INDENT> if self.dic[word] == 1: <NEW_LINE> <INDENT> score += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> score -= 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return score
Implements sentiment analysis.
62598fca55399d3f056268a6
class BasePlugin(QObject): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> super(BasePlugin, self).__init__() <NEW_LINE> <DEDENT> def activate(self): <NEW_LINE> <INDENT> pass
A base from which every plugin should inherit
62598fca4a966d76dd5ef264
class Selu: <NEW_LINE> <INDENT> def __call__(self, x): <NEW_LINE> <INDENT> return selu(x)
The scaled exponential linear unit [3]_ activation function is described by the following formula: :math:`a = 1.6732632423543772848170429916717` :math:`b = 1.0507009873554804934193349852946` :math:`f(x) = b*max(x, 0)+min(0, exp(x) - a)` Args: x (ndarray, Node): Input numpy array or Node instance. Example: >>> import renom as rm >>> import numpy as np >>> x = np.array([[1, -1]]) array([[ 1, -1]]) >>> rm.relu(x) selu([ 1.05070102, -1.11133075]) >>> # instantiation >>> activation = rm.Relu() >>> activation(x) selu([ 1.05070102, -1.11133075]) .. [3] Günter Klambauer, Thomas Unterthiner, Andreas Mayr, Sepp Hochreiter. Self-Normalizing Neural Networks. Learning (cs.LG); Machine Learning
62598fca5fc7496912d48440
class Confess(BaseMode): <NEW_LINE> <INDENT> STATE = ( ('待审核', '待审核'), ('通过', '通过'), ('未通过', '未通过') ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'confess' <NEW_LINE> <DEDENT> userID = models.IntegerField(default=1, verbose_name="用户id") <NEW_LINE> userName = models.CharField(max_length=30, default='表白墙', verbose_name="用户昵称") <NEW_LINE> context = models.TextField(default='', null=True, verbose_name="发表内容") <NEW_LINE> images = models.TextField(default='', verbose_name="发表配图") <NEW_LINE> state = models.CharField(max_length=50, choices=STATE, default='待审核', verbose_name="审核状态") <NEW_LINE> release_time = models.CharField(max_length=256, default=str(int(time())), verbose_name="发布时间") <NEW_LINE> is_delete = models.BooleanField(default=False, verbose_name="是否被删除") <NEW_LINE> contentType = models.IntegerField(default=1,verbose_name="内容类型(1:表白、2:失物招领、3:二手商品、4:其他)")
贴子表
62598fca851cf427c66b8641
class PhoneCallDiscardReasonDisconnect(TLObject): <NEW_LINE> <INDENT> __slots__: List[str] = [] <NEW_LINE> ID = 0xe095c1a0 <NEW_LINE> QUALNAME = "types.PhoneCallDiscardReasonDisconnect" <NEW_LINE> def __init__(self) -> None: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data: BytesIO, *args: Any) -> "PhoneCallDiscardReasonDisconnect": <NEW_LINE> <INDENT> return PhoneCallDiscardReasonDisconnect() <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> data = BytesIO() <NEW_LINE> data.write(Int(self.ID, False)) <NEW_LINE> return data.getvalue()
This object is a constructor of the base type :obj:`~pyrogram.raw.base.PhoneCallDiscardReason`. Details: - Layer: ``122`` - ID: ``0xe095c1a0`` **No parameters required.**
62598fcaaad79263cf42eb5c
class AnswerAPI(MethodView): <NEW_LINE> <INDENT> decorators = [token_required] <NEW_LINE> @staticmethod <NEW_LINE> def post(current_user, question_id): <NEW_LINE> <INDENT> database = Database(app.config['DATABASE_URL']) <NEW_LINE> answer_db = AnswerBbQueries() <NEW_LINE> data = request.get_json() <NEW_LINE> if validate_answer(data) == 'valid': <NEW_LINE> <INDENT> aauthor = current_user.username <NEW_LINE> query = database.fetch_by_param('questions', 'id', question_id) <NEW_LINE> if query is None: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> question = Question(query[0], query[1], query[2], query[3], query[4]) <NEW_LINE> if question.qauthor != aauthor: <NEW_LINE> <INDENT> answer_db.post_answer(question_id, data, aauthor) <NEW_LINE> return jsonify({'msg': 'You have offered an answer' + " Thank you."}), 201 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return jsonify( {'message': "You can't answer your own question"}), 403 <NEW_LINE> <DEDENT> <DEDENT> return jsonify({'message': validate_answer(data)}), 406 <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def put(current_user, question_id, answer_id): <NEW_LINE> <INDENT> database = Database(app.config['DATABASE_URL']) <NEW_LINE> answer_db = AnswerBbQueries() <NEW_LINE> qauthor = current_user.username <NEW_LINE> aauthor = current_user.username <NEW_LINE> query = database.fetch_by_param('questions', 'id', question_id) <NEW_LINE> query1 = database.fetch_by_param('answers', 'id', answer_id) <NEW_LINE> if query is None: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> question = Question(query[0], query[1], query[2], query[3], query[4]) <NEW_LINE> if question.qauthor == qauthor: <NEW_LINE> <INDENT> data = request.get_json() <NEW_LINE> print(data['status']) <NEW_LINE> if data['status'] == 'accepted' or data['status'] == 'not accepted': <NEW_LINE> <INDENT> answer_db.update_answer_status(answer_id, data) <NEW_LINE> response = { 'message': 'you have {} this answer' .format(data['status']) } <NEW_LINE> return make_response(jsonify(response)), 200 <NEW_LINE> <DEDENT> return jsonify({'message': 'The status can only be in 3 states,' + 'answered, accepted and not accepted'}),406 <NEW_LINE> <DEDENT> query1 = database.fetch_by_param('answers', 'id', answer_id) <NEW_LINE> if query1 is None: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> answer = Answer(query1[0], query1[1], query1[2], query1[3], query1[4]) <NEW_LINE> if answer.aauthor == aauthor: <NEW_LINE> <INDENT> data = request.get_json() <NEW_LINE> text1 = data['text1'] <NEW_LINE> answer_db.update_answer(answer_id, text1) <NEW_LINE> return jsonify({"message": "You have updated your answer"}), 201
This class-based view for answering a question.
62598fca656771135c4899fe
class GPSLoggerView(HomeAssistantView): <NEW_LINE> <INDENT> url = '/api/gpslogger' <NEW_LINE> name = 'api:gpslogger' <NEW_LINE> def __init__(self, async_see, config): <NEW_LINE> <INDENT> self.async_see = async_see <NEW_LINE> self._password = config.get(CONF_PASSWORD) <NEW_LINE> self.requires_auth = self._password is None <NEW_LINE> <DEDENT> async def get(self, request: Request): <NEW_LINE> <INDENT> hass = request.app['hass'] <NEW_LINE> data = request.query <NEW_LINE> if self._password is not None: <NEW_LINE> <INDENT> authenticated = CONF_API_PASSWORD in data and compare_digest( self._password, data[CONF_API_PASSWORD] ) <NEW_LINE> if not authenticated: <NEW_LINE> <INDENT> raise HTTPUnauthorized() <NEW_LINE> <DEDENT> <DEDENT> if 'latitude' not in data or 'longitude' not in data: <NEW_LINE> <INDENT> return ('Latitude and longitude not specified.', HTTP_UNPROCESSABLE_ENTITY) <NEW_LINE> <DEDENT> if 'device' not in data: <NEW_LINE> <INDENT> _LOGGER.error("Device id not specified") <NEW_LINE> return ('Device id not specified.', HTTP_UNPROCESSABLE_ENTITY) <NEW_LINE> <DEDENT> device = data['device'].replace('-', '') <NEW_LINE> gps_location = (data['latitude'], data['longitude']) <NEW_LINE> accuracy = 200 <NEW_LINE> battery = -1 <NEW_LINE> if 'accuracy' in data: <NEW_LINE> <INDENT> accuracy = int(float(data['accuracy'])) <NEW_LINE> <DEDENT> if 'battery' in data: <NEW_LINE> <INDENT> battery = float(data['battery']) <NEW_LINE> <DEDENT> attrs = {} <NEW_LINE> if 'speed' in data: <NEW_LINE> <INDENT> attrs['speed'] = float(data['speed']) <NEW_LINE> <DEDENT> if 'direction' in data: <NEW_LINE> <INDENT> attrs['direction'] = float(data['direction']) <NEW_LINE> <DEDENT> if 'altitude' in data: <NEW_LINE> <INDENT> attrs['altitude'] = float(data['altitude']) <NEW_LINE> <DEDENT> if 'provider' in data: <NEW_LINE> <INDENT> attrs['provider'] = data['provider'] <NEW_LINE> <DEDENT> if 'activity' in data: <NEW_LINE> <INDENT> attrs['activity'] = data['activity'] <NEW_LINE> <DEDENT> hass.async_add_job(self.async_see( dev_id=device, gps=gps_location, battery=battery, gps_accuracy=accuracy, attributes=attrs )) <NEW_LINE> return 'Setting location for {}'.format(device)
View to handle GPSLogger requests.
62598fca3d592f4c4edbb242