code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class DistinguishedFolderId(FolderId): <NEW_LINE> <INDENT> ELEMENT_NAME = "DistinguishedFolderId" <NEW_LINE> mailbox = MailboxField() <NEW_LINE> def clean(self, version=None): <NEW_LINE> <INDENT> from .folders import PublicFoldersRoot <NEW_LINE> super().clean(version=version) <NEW_LINE> if self.id == PublicFoldersRoot.DISTINGUISHED_FOLDER_ID: <NEW_LINE> <INDENT> self.mailbox = None | MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/distinguishedfolderid | 62598fa2dd821e528d6d8dac |
@six.add_metaclass(AsdfTypeMeta) <NEW_LINE> @six.add_metaclass(InheritDocstrings) <NEW_LINE> class AsdfType(object): <NEW_LINE> <INDENT> name = None <NEW_LINE> organization = 'stsci.edu' <NEW_LINE> standard = 'asdf' <NEW_LINE> version = (0, 1, 0) <NEW_LINE> types = [] <NEW_LINE> @classmethod <NEW_LINE> def make_yaml_tag(cls, name): <NEW_LINE> <INDENT> return format_tag( cls.organization, cls.standard, versioning.version_to_string(cls.version), name) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def validate(cls, tree, ctx): <NEW_LINE> <INDENT> from . import yamlutil <NEW_LINE> yamlutil.validate_for_tag(cls.yaml_tag, tree, ctx) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def to_tree(cls, node, ctx): <NEW_LINE> <INDENT> return node.__class__.__bases__[0](node) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def to_tree_tagged(cls, node, ctx): <NEW_LINE> <INDENT> obj = cls.to_tree(node, ctx) <NEW_LINE> return tagged.tag_object(cls.yaml_tag, obj) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_tree(cls, tree, ctx): <NEW_LINE> <INDENT> return cls(tree) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_tree_tagged(cls, tree, ctx): <NEW_LINE> <INDENT> return cls.from_tree(tree.data, ctx) | The base class of all custom types in the tree.
Besides the attributes defined below, most subclasses will also
override `to_tree` and `from_tree`.
To customize how the type's schema is located, override `get_schema_path`.
Attributes
----------
name : str
The name of the type.
organization : str
The organization responsible for the type.
standard : str
The standard the type is defined in. For built-in ASDF types,
this is ``"asdf"``.
version : 3-tuple of int
The version of the standard the type is defined in.
types : list of Python types
Custom Python types that, when found in the tree, will be
converted into basic types for YAML output. | 62598fa2435de62698e9bc6b |
class SmtpServerResponse(object): <NEW_LINE> <INDENT> swagger_types = { 'items': 'list[SmtpServer]' } <NEW_LINE> attribute_map = { 'items': 'items' } <NEW_LINE> required_args = { } <NEW_LINE> def __init__( self, items=None, ): <NEW_LINE> <INDENT> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> if key not in self.attribute_map: <NEW_LINE> <INDENT> raise KeyError("Invalid key `{}` for `SmtpServerResponse`".format(key)) <NEW_LINE> <DEDENT> self.__dict__[key] = value <NEW_LINE> <DEDENT> def __getattribute__(self, item): <NEW_LINE> <INDENT> value = object.__getattribute__(self, item) <NEW_LINE> if isinstance(value, Property): <NEW_LINE> <INDENT> raise AttributeError <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> if hasattr(self, attr): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if issubclass(SmtpServerResponse, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SmtpServerResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition. | 62598fa267a9b606de545e42 |
class FmtStr(object): <NEW_LINE> <INDENT> def __init__(self, execute_fmt, offset = None, padlen = 0, numbwritten = 0): <NEW_LINE> <INDENT> self.execute_fmt = execute_fmt <NEW_LINE> self.offset = offset <NEW_LINE> self.padlen = padlen <NEW_LINE> self.numbwritten = numbwritten <NEW_LINE> if self.offset == None: <NEW_LINE> <INDENT> self.offset, self.padlen = self.find_offset() <NEW_LINE> log.info("Found format string offset: %d", self.offset) <NEW_LINE> <DEDENT> self.writes = {} <NEW_LINE> self.leaker = MemLeak(self._leaker) <NEW_LINE> <DEDENT> def leak_stack(self, offset, prefix=""): <NEW_LINE> <INDENT> leak = self.execute_fmt(prefix+"START%{}$pEND".format(offset)) <NEW_LINE> try: <NEW_LINE> <INDENT> leak = re.findall(r"START(.*)END", leak, re.MULTILINE | re.DOTALL)[0] <NEW_LINE> leak = int(leak, 16) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> leak = 0 <NEW_LINE> <DEDENT> return leak <NEW_LINE> <DEDENT> def find_offset(self): <NEW_LINE> <INDENT> marker = cyclic(20) <NEW_LINE> for off in range(1,1000): <NEW_LINE> <INDENT> leak = self.leak_stack(off, marker) <NEW_LINE> leak = pack(leak) <NEW_LINE> pad = cyclic_find(leak) <NEW_LINE> if pad >= 0 and pad < 20: <NEW_LINE> <INDENT> return off, pad <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> log.error("Could not find offset to format string on stack") <NEW_LINE> return None, None <NEW_LINE> <DEDENT> <DEDENT> def _leaker(self, addr): <NEW_LINE> <INDENT> if addr & 0xfff == 0 and self.leaker._leak(addr+1, 3, False) == "ELF": <NEW_LINE> <INDENT> return "\x7f" <NEW_LINE> <DEDENT> fmtstr = randoms(self.padlen) + pack(addr) + "START%%%d$sEND" % self.offset <NEW_LINE> leak = self.execute_fmt(fmtstr) <NEW_LINE> leak = re.findall(r"START(.*)END", leak, re.MULTILINE | re.DOTALL)[0] <NEW_LINE> leak += "\x00" <NEW_LINE> return leak <NEW_LINE> <DEDENT> def execute_writes(self): <NEW_LINE> <INDENT> fmtstr = randoms(self.padlen) <NEW_LINE> fmtstr += fmtstr_payload(self.offset, self.writes, numbwritten=self.padlen, write_size='byte') <NEW_LINE> self.execute_fmt(fmtstr) <NEW_LINE> self.writes = {} <NEW_LINE> <DEDENT> def write(self, addr, data): <NEW_LINE> <INDENT> self.writes[addr] = data | Provides an automated format string exploitation.
It takes a function which is called every time the automated
process want to communicate with the vulnerable process. this
function takes a parameter with the payload that you have to
send to the vulnerable process and must return the process
returns.
If the `offset` parameter is not given, then try to find the right
offset by leaking stack data.
Arguments:
execute_fmt(function): function to call for communicate with the vulnerable process
offset(int): the first formatter's offset you control
padlen(int): size of the pad you want to add before the payload
numbwritten(int): number of already written bytes | 62598fa22ae34c7f260aaf58 |
class ClassBalancedSampler(Sampler): <NEW_LINE> <INDENT> def __init__(self, num_per_class, num_cl, num_inst, shuffle=True): <NEW_LINE> <INDENT> self.num_per_class = num_per_class <NEW_LINE> self.num_cl = num_cl <NEW_LINE> self.num_inst = num_inst <NEW_LINE> self.shuffle = shuffle <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> if self.shuffle: <NEW_LINE> <INDENT> batch = [[i + j * self.num_inst for i in torch.randperm(self.num_inst)[:self.num_per_class]] for j in range(self.num_cl)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> batch = [[i + j * self.num_inst for i in range(self.num_inst)[:self.num_per_class]] for j in range(self.num_cl)] <NEW_LINE> <DEDENT> batch = [item for sublist in batch for item in sublist] <NEW_LINE> if self.shuffle: <NEW_LINE> <INDENT> random.shuffle(batch) <NEW_LINE> <DEDENT> return iter(batch) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return 1 | Samples 'num_inst' examples each from 'num_cl' pools
of examples of size 'num_per_class' | 62598fa21f5feb6acb162a9a |
class Rb2PyError: <NEW_LINE> <INDENT> pass | Custom marker for thrown exceptions | 62598fa2d58c6744b42dc20f |
class Membership(ModelBase): <NEW_LINE> <INDENT> __tablename__ = "membership" <NEW_LINE> __table_args__ = (UniqueConstraint("user_id", "lexicon_id"),) <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> user_id = Column(Integer, ForeignKey("user.id"), nullable=False) <NEW_LINE> lexicon_id = Column(Integer, ForeignKey("lexicon.id"), nullable=False) <NEW_LINE> joined = Column(DateTime, nullable=False, server_default=func.now()) <NEW_LINE> last_post_seen = Column(DateTime, nullable=True) <NEW_LINE> is_editor = Column(Boolean, nullable=False, server_default=text("FALSE")) <NEW_LINE> notify_ready = Column(Boolean, nullable=False, default=True) <NEW_LINE> notify_reject = Column(Boolean, nullable=False, default=True) <NEW_LINE> notify_approve = Column(Boolean, nullable=False, default=True) <NEW_LINE> user = relationship("User", back_populates="memberships") <NEW_LINE> lexicon = relationship("Lexicon", back_populates="memberships") | Represents a user's participation in a Lexicon game. | 62598fa27d43ff248742733e |
class TableReference(proto.Message): <NEW_LINE> <INDENT> project_id = proto.Field( proto.STRING, number=1, ) <NEW_LINE> dataset_id = proto.Field( proto.STRING, number=2, ) <NEW_LINE> table_id = proto.Field( proto.STRING, number=3, ) <NEW_LINE> project_id_alternative = proto.RepeatedField( proto.STRING, number=4, ) <NEW_LINE> dataset_id_alternative = proto.RepeatedField( proto.STRING, number=5, ) <NEW_LINE> table_id_alternative = proto.RepeatedField( proto.STRING, number=6, ) | Attributes:
project_id (str):
Required. The ID of the project containing
this table.
dataset_id (str):
Required. The ID of the dataset containing
this table.
table_id (str):
Required. The ID of the table. The ID must contain only
letters (a-z, A-Z), numbers (0-9), or underscores (_). The
maximum length is 1,024 characters. Certain operations allow
suffixing of the table ID with a partition decorator, such
as ``sample_table$20190123``.
project_id_alternative (Sequence[str]):
The alternative field that will be used when ESF is not able
to translate the received data to the project_id field.
dataset_id_alternative (Sequence[str]):
The alternative field that will be used when ESF is not able
to translate the received data to the project_id field.
table_id_alternative (Sequence[str]):
The alternative field that will be used when ESF is not able
to translate the received data to the project_id field. | 62598fa28e7ae83300ee8f18 |
class Registration(Artifact): <NEW_LINE> <INDENT> __tablename__ = 'registration' <NEW_LINE> id = Column(Integer, ForeignKey('artifact.id'), primary_key=True) <NEW_LINE> __mapper_args__ = {"polymorphic_identity": "registration"} | Unused in our version of the system. | 62598fa26e29344779b004d4 |
class Home(RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> services = teams = [] <NEW_LINE> pending_count = 0 <NEW_LINE> if self.current_user: <NEW_LINE> <INDENT> services = [self.get_service(n) for n in self.current_user['services']] <NEW_LINE> teams = [self.get_team(n) for n in self.current_user['teams']] <NEW_LINE> if self.is_admin(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> view = self.db.view('user/count') <NEW_LINE> pending_count = view['pending'].rows[0].value <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.render('home.html', services=services, teams=teams, pending_count=pending_count, next=self.get_argument('next', '')) | Home page: Form to login or link to create new account. | 62598fa20a50d4780f705253 |
class IoK8sApiCoreV1DownwardAPIProjection(object): <NEW_LINE> <INDENT> swagger_types = { 'items': 'list[IoK8sApiCoreV1DownwardAPIVolumeFile]' } <NEW_LINE> attribute_map = { 'items': 'items' } <NEW_LINE> def __init__(self, items=None): <NEW_LINE> <INDENT> self._items = None <NEW_LINE> self.discriminator = None <NEW_LINE> if items is not None: <NEW_LINE> <INDENT> self.items = items <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> return self._items <NEW_LINE> <DEDENT> @items.setter <NEW_LINE> def items(self, items): <NEW_LINE> <INDENT> self._items = items <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(IoK8sApiCoreV1DownwardAPIProjection, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, IoK8sApiCoreV1DownwardAPIProjection): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa20a50d4780f705254 |
class DescribeDeviceClassRequest(AbstractModel): <NEW_LINE> <INDENT> pass | DescribeDeviceClass请求参数结构体
| 62598fa21f037a2d8b9e3f62 |
class CalculateNumberOfBands: <NEW_LINE> <INDENT> def __init__(self, filePath): <NEW_LINE> <INDENT> self.text = open(filePath, 'r').readlines() <NEW_LINE> self.parser = b_PyParse.MainSCFParser(self.text) <NEW_LINE> self.parser.parse() <NEW_LINE> <DEDENT> def getNumberOfBands(self, spCalc, soCalc, orbCalc, wCalc): <NEW_LINE> <INDENT> bandList = self.parser['Band List'] <NEW_LINE> theList = [ (i['band range'], i['occupancy']) for i in bandList if i['occupancy'] ] <NEW_LINE> iHOMO = theList[-1][0] <NEW_LINE> fHOMO = theList[-1][1] <NEW_LINE> if not wCalc: <NEW_LINE> <INDENT> if not spCalc and not soCalc and not orbCalc: <NEW_LINE> <INDENT> if fHOMO != 2.0: <NEW_LINE> <INDENT> print("HOMO band index =", iHOMO) <NEW_LINE> print("HOMO band occupancy =", fHOMO) <NEW_LINE> print("Possible reasons for the error are:") <NEW_LINE> print("* you have a metal (method does not work in this case)") <NEW_LINE> print("* you have an insulator with a small band gap and selected TEMP smearing in case.in2(c)") <NEW_LINE> print("In second case, switch to TETRA in case.in2(c) and re-run berrypi") <NEW_LINE> raise Exception("The HOMO band should have occupancy of 2") <NEW_LINE> <DEDENT> <DEDENT> elif spCalc or soCalc or orbCalc: <NEW_LINE> <INDENT> if fHOMO != 1.0: <NEW_LINE> <INDENT> print("HOMO band index =", iHOMO) <NEW_LINE> print("HOMO band occupancy =", fHOMO) <NEW_LINE> print("* you have a metal (method does not work in this case)") <NEW_LINE> print("* you have an insulator with a small band gap and selected TEMP smearing in case.in2(c)") <NEW_LINE> print("In second case, switch to TETRA in case.in2(c) and re-run berrypi") <NEW_LINE> raise Exception("The HOMO band should have occupancy of 1") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return iHOMO | Used to calculate the number of bands within the *.scf file to
determine the input for the write_w2win function.
You pass a file path to the *.scf in order to carry out this
calculation | 62598fa291af0d3eaad39c85 |
class BaseLoggingObj(object): <NEW_LINE> <INDENT> def __init__(self, config=Config): <NEW_LINE> <INDENT> logging.basicConfig(level=config.logging_level, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename=config.logging_file, filemode='a') <NEW_LINE> self.logging = logging | config的默认参数是com.Config 可通过构造修改 | 62598fa2d268445f26639abf |
class Integer(Number): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> self.value = value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self.value) <NEW_LINE> <DEDENT> def eval(self): <NEW_LINE> <INDENT> return self | An atom that holds an integer number.
| 62598fa2e5267d203ee6b786 |
class MakeBlastDb(object): <NEW_LINE> <INDENT> def __init__(self, fasta, out_name=None): <NEW_LINE> <INDENT> self.__fasta = fasta <NEW_LINE> self.__out_name = out_name <NEW_LINE> <DEDENT> def launch(self): <NEW_LINE> <INDENT> options = ['makeblastdb', '-in', self.__fasta, '-dbtype', 'nucl'] <NEW_LINE> if self.__out_name is not None: <NEW_LINE> <INDENT> options += ['-out', self.__out_name] <NEW_LINE> <DEDENT> subprocess.check_call(options) | The class implements a wrapper to launch makeblastdb from the
NCBI BLAST+ package. | 62598fa2462c4b4f79dbb885 |
class DeadConnection(Exception): <NEW_LINE> <INDENT> pass | Raised when the connection is lost. | 62598fa2be8e80087fbbeed9 |
class TestAccountDataApi(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.api = swagger_client.apis.account_data_api.AccountDataApi() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1exchangebanksummary(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1exchangeusercoinfee(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1exchangeuserfiatfee(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1netkisearch_netki_name(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1userexchangekycs(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1userexchangereferralcoinpaid(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1userexchangereferralcoinsuccessful(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1userexchangereferralfiatpaid(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1userexchangereferrals(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1userexchangetradesummary(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1userlogintoken_token(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1usersummary(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_v1userwalletsummary(self): <NEW_LINE> <INDENT> pass | AccountDataApi unit test stubs | 62598fa2bd1bec0571e15000 |
class Database(object): <NEW_LINE> <INDENT> pass | Real database access. | 62598fa26aa9bd52df0d4d43 |
class JogoMarcela: <NEW_LINE> <INDENT> def __init__(self, legendas=LEGENDAS, momentos=MOMENTOS): <NEW_LINE> <INDENT> self.quadros = momentos <NEW_LINE> telas = {nome: ACTIV.format(quadro, momento) for nome, (quadro, momento) in zip(legendas, momentos)} <NEW_LINE> print({te: ur[-18:] for te, ur in telas.items()}) <NEW_LINE> self._cria_cenas(telas) <NEW_LINE> self._inicia_jogo() <NEW_LINE> <DEDENT> def configura_momentos(self, cena): <NEW_LINE> <INDENT> origem_destino_titulo_texto, com_texto, hot = Config.CONFIGURA[cena] <NEW_LINE> origem, destino, titulo, texto = origem_destino_titulo_texto.split("#") <NEW_LINE> origem = getattr(JOGO.c, origem) <NEW_LINE> debug = False <NEW_LINE> @JOGO.n.texto(titulo, texto) <NEW_LINE> def configura_portal_com_texto(origem_, destino_, hot_spot=hot): <NEW_LINE> <INDENT> return origem_.portal(L=destino_, style=hot_spot, debug_=debug) <NEW_LINE> <DEDENT> def configura_portal_sem_texto(origem_, destino_, hot_spot=hot): <NEW_LINE> <INDENT> return origem_.portal(L=destino_, style=hot_spot) <NEW_LINE> <DEDENT> previo_destino = PreviaDoMomento(self, destino) <NEW_LINE> if com_texto: <NEW_LINE> <INDENT> portal_decorado = configura_portal_com_texto(origem, previo_destino) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> portal_decorado = configura_portal_sem_texto(origem, previo_destino) <NEW_LINE> <DEDENT> if debug: <NEW_LINE> <INDENT> self._decorador_do_vai_do_texto(portal_decorado) <NEW_LINE> <DEDENT> return previo_destino <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _decorador_do_vai_do_texto(port): <NEW_LINE> <INDENT> formato_do_texto_no_popup = "dict(left={left}, top={top}, width={width}, height={height})" <NEW_LINE> metodo_vai_original = port.texto.vai <NEW_LINE> def decorador_do_metodo_vai_do_texto(*a): <NEW_LINE> <INDENT> port.texto.txt = formato_do_texto_no_popup.format( **{k: v[:-2] for k, v in dict(left=port.elt.style.left, top=port.elt.style.top, width=port.elt.style.width, height=port.elt.style.minHeight).items()}) <NEW_LINE> metodo_vai_original(*a) <NEW_LINE> <DEDENT> port.texto.vai = lambda *a: decorador_do_metodo_vai_do_texto(*a) <NEW_LINE> <DEDENT> def _inicia_jogo(self): <NEW_LINE> <INDENT> self.configura_momentos("origem").vai() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _cria_cenas(cenas): <NEW_LINE> <INDENT> JOGO.c.c(**cenas) | Constroi o jogo completo da Marcela.
:param legendas: lista contendo nomes das cenas *[<nome da cena>, ...]*
:param momentos: lista de tuplas indicando o quadro e o momento *[(<q0>, <m0>), ... ]* | 62598fa201c39578d7f12bf8 |
class NodeStatus(Enum): <NEW_LINE> <INDENT> ACTIVE = 0 <NEW_LINE> LEAVING = 1 <NEW_LINE> FROZEN = 2 <NEW_LINE> IN_MAINTENANCE = 3 <NEW_LINE> LEFT = 4 <NEW_LINE> NOT_CREATED = 5 | This class contains possible node statuses | 62598fa2cb5e8a47e493c0b3 |
class GTFFeature(object): <NEW_LINE> <INDENT> def __init__(self, chrom=None, source=None, featuretype=None, start=None, end=None, score=None, strand=None, phase=None, attributes=None): <NEW_LINE> <INDENT> self._chrom = chrom <NEW_LINE> self._source = source <NEW_LINE> self._featuretype = featuretype <NEW_LINE> self._start = start <NEW_LINE> self._end = end <NEW_LINE> self._score = score <NEW_LINE> self._strand = strand <NEW_LINE> self._phase = phase <NEW_LINE> self._attributparse(attributes) <NEW_LINE> <DEDENT> def _attributparse(self, attributes): <NEW_LINE> <INDENT> self.attributes = AttrDict() <NEW_LINE> if attributes: <NEW_LINE> <INDENT> items = attributes.split(';') <NEW_LINE> for i in items: <NEW_LINE> <INDENT> if len(i) == 0: continue <NEW_LINE> try: <NEW_LINE> <INDENT> name, key = i.strip().split() <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> key = key.replace('"', '') <NEW_LINE> setattr(self.attributes, name, key) <NEW_LINE> <DEDENT> <DEDENT> return self.attributes <NEW_LINE> <DEDENT> @property <NEW_LINE> def chrom(self): <NEW_LINE> <INDENT> return self._chrom <NEW_LINE> <DEDENT> @property <NEW_LINE> def start(self): <NEW_LINE> <INDENT> return int(self._start) <NEW_LINE> <DEDENT> @property <NEW_LINE> def end(self): <NEW_LINE> <INDENT> return int(self._end) <NEW_LINE> <DEDENT> @property <NEW_LINE> def feature(self): <NEW_LINE> <INDENT> return self._featuretype <NEW_LINE> <DEDENT> @property <NEW_LINE> def strand(self): <NEW_LINE> <INDENT> return self._strand <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> length = int(self._end) - int(self._start) + 1 <NEW_LINE> if length < 1: <NEW_LINE> <INDENT> raise ValueError('Zero- or negative length feature') <NEW_LINE> <DEDENT> return length <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<GTF;gene {}>".format(self.attributes["gene_id"]) | Retrieve line from GFFfile class, and return information line by line. | 62598fa2a8ecb03325871088 |
class DetailProduct(DetailView): <NEW_LINE> <INDENT> context_object_name = "product" <NEW_LINE> model = Product <NEW_LINE> template_name = "products/detail_product.html" | This generic view renders detail_product template wich shows informations about a product | 62598fa2796e427e5384e60d |
class I0(UnaryScalarOp): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def st_impl(x): <NEW_LINE> <INDENT> return scipy.special.i0(x) <NEW_LINE> <DEDENT> def impl(self, x): <NEW_LINE> <INDENT> if imported_scipy_special: <NEW_LINE> <INDENT> return self.st_impl(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(I0, self).impl(x) <NEW_LINE> <DEDENT> <DEDENT> def grad(self, inp, grads): <NEW_LINE> <INDENT> x, = inp <NEW_LINE> gz, = grads <NEW_LINE> return [gz * i1(x)] | Modified Bessel function of order 0. | 62598fa230bbd722464698b4 |
class WrappedFile: <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.file = open(path, "r") <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self.file.__iter__() <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> return self.file.readline().lstrip() | File object that returns all lines striped on the left. | 62598fa23cc13d1c6d4655e6 |
class BreadthFirst: <NEW_LINE> <INDENT> k = 0 <NEW_LINE> @classmethod <NEW_LINE> def g(cls, parentnode: Node, action, childnode: Node): <NEW_LINE> <INDENT> return len(childnode.path()) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def h(cls, state): <NEW_LINE> <INDENT> return cls.k | BredthFirst - breadthfirst search | 62598fa2d7e4931a7ef3bf14 |
class CronosException(Exception): <NEW_LINE> <INDENT> pass | General parsing errors. | 62598fa2adb09d7d5dc0a404 |
class RegisteredServerArray(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[RegisteredServer]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(RegisteredServerArray, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None) | Array of RegisteredServer.
:param value: Collection of Registered Server.
:type value: list[~azure.mgmt.storagesync.models.RegisteredServer] | 62598fa2fbf16365ca793f35 |
class leoCompare (baseLeoCompare): <NEW_LINE> <INDENT> pass | A class containing Leo's compare code. | 62598fa2baa26c4b54d4f12a |
class Role(ChangeLoggedModel): <NEW_LINE> <INDENT> name = models.CharField( max_length=100, unique=True ) <NEW_LINE> slug = models.SlugField( max_length=100, unique=True ) <NEW_LINE> weight = models.PositiveSmallIntegerField( default=1000 ) <NEW_LINE> description = models.CharField( max_length=200, blank=True, ) <NEW_LINE> objects = RestrictedQuerySet.as_manager() <NEW_LINE> csv_headers = ['name', 'slug', 'weight', 'description'] <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['weight', 'name'] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def to_csv(self): <NEW_LINE> <INDENT> return ( self.name, self.slug, self.weight, self.description, ) | A Role represents the functional role of a Prefix or VLAN; for example, "Customer," "Infrastructure," or
"Management." | 62598fa238b623060ffa8f0e |
class ServiceError(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'possible_causes': {'key': 'possibleCauses', 'type': 'str'}, 'recommended_action': {'key': 'recommendedAction', 'type': 'str'}, 'activity_id': {'key': 'activityId', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ServiceError, self).__init__(**kwargs) <NEW_LINE> self.code = kwargs.get('code', None) <NEW_LINE> self.message = kwargs.get('message', None) <NEW_LINE> self.possible_causes = kwargs.get('possible_causes', None) <NEW_LINE> self.recommended_action = kwargs.get('recommended_action', None) <NEW_LINE> self.activity_id = kwargs.get('activity_id', None) | ASR error model.
:param code: Error code.
:type code: str
:param message: Error message.
:type message: str
:param possible_causes: Possible causes of error.
:type possible_causes: str
:param recommended_action: Recommended action to resolve error.
:type recommended_action: str
:param activity_id: Activity Id.
:type activity_id: str | 62598fa24f88993c371f0447 |
class RespPublicKeys: <NEW_LINE> <INDENT> def __init__(self, rsa_pub_key, paillier_pub_key): <NEW_LINE> <INDENT> self.rsa_pub_key = rsa_pub_key <NEW_LINE> self.paillier_pub_key = paillier_pub_key <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dictionary(cls, params): <NEW_LINE> <INDENT> rsa_pub_key = RSA.importKey(params['rsa_pub_key'].encode('ascii')) <NEW_LINE> paillier_pub_key = paillier.PublicKey.from_n(int(params['paillier_pub_key'], base=16)) <NEW_LINE> return cls(rsa_pub_key, paillier_pub_key) <NEW_LINE> <DEDENT> def to_dictionary(self): <NEW_LINE> <INDENT> rsa_pub_key_exported = self.rsa_pub_key.exportKey().decode('ascii') <NEW_LINE> paillier_pub_key_str = hex(self.paillier_pub_key.n) <NEW_LINE> return {'rsa_pub_key': rsa_pub_key_exported, 'paillier_pub_key': paillier_pub_key_str} | response contain public keys | 62598fa256b00c62f0fb272c |
class DBContext: <NEW_LINE> <INDENT> def __init__(self, sql_server): <NEW_LINE> <INDENT> self.sql_server = sql_server <NEW_LINE> self.db_engine = None <NEW_LINE> self.db_session = None <NEW_LINE> self.db_connection = None <NEW_LINE> self.db_error = None <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.db_error = None <NEW_LINE> try: <NEW_LINE> <INDENT> self.db_engine = self.sql_server.create_engine() <NEW_LINE> self.db_session = sessionmaker(bind=self.engine)() <NEW_LINE> self.db_connection = self.db_session.connection() <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> LOG.debug("Connection error") <NEW_LINE> LOG.debug(ex) <NEW_LINE> self.db_error = DBStatus.FAILED_TO_CONNECT <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> @property <NEW_LINE> def error(self): <NEW_LINE> <INDENT> return self.db_error <NEW_LINE> <DEDENT> @property <NEW_LINE> def engine(self): <NEW_LINE> <INDENT> return self.db_engine <NEW_LINE> <DEDENT> @property <NEW_LINE> def connection(self): <NEW_LINE> <INDENT> return self.db_connection <NEW_LINE> <DEDENT> @property <NEW_LINE> def session(self): <NEW_LINE> <INDENT> return self.db_session <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> if self.db_session: <NEW_LINE> <INDENT> self.db_session.close() <NEW_LINE> <DEDENT> if self.db_connection: <NEW_LINE> <INDENT> self.db_connection.close() <NEW_LINE> <DEDENT> if self.db_engine: <NEW_LINE> <INDENT> self.db_engine.dispose() | Simple helper class to setup and sql engine, a database session
and a connection.
NOTE: The error property should be always checked inside the
with statement to verify that the engine/connection/session
setup was successful. | 62598fa2090684286d593618 |
class TimerLog(list): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._entire_formatted_log = '' <NEW_LINE> super(TimerLog, self).__init__() <NEW_LINE> <DEDENT> def addTimer(self, loggedTimer=None, name='undefined', startedAt=None, endedAt=None): <NEW_LINE> <INDENT> loggedTimer = {'name': name} <NEW_LINE> super(TimerLog, self).append(loggedTimer) <NEW_LINE> <DEDENT> def save(self, file_path): <NEW_LINE> <INDENT> logfile = open(file_path, 'w') <NEW_LINE> pickled = jsonpickle.encode(self) <NEW_LINE> logfile.write(pickled) <NEW_LINE> logfile.close() <NEW_LINE> <DEDENT> def restore(self, file_path): <NEW_LINE> <INDENT> logfile = open(file_path, 'r') <NEW_LINE> self._entire_formatted_log = logfile.read() <NEW_LINE> unpickled = jsonpickle.decode(self._entire_formatted_log) <NEW_LINE> self.extend(unpickled) <NEW_LINE> logfile.close() | Persistent log of used Timers. | 62598fa263d6d428bbee262c |
class ModelException(Exception): <NEW_LINE> <INDENT> def __init__(self, msg, *args): <NEW_LINE> <INDENT> if args: <NEW_LINE> <INDENT> msg = msg % args <NEW_LINE> <DEDENT> self.msg = msg <NEW_LINE> Exception.__init__(self, msg) | Base Exception. | 62598fa299cbb53fe6830d4e |
class OrgTeacherView(View): <NEW_LINE> <INDENT> def get(self, request, org_id): <NEW_LINE> <INDENT> current_page = "teacher" <NEW_LINE> course_org = CourseOrg.objects.get(id=int(org_id)) <NEW_LINE> has_fav = False <NEW_LINE> if request.user.is_authenticated(): <NEW_LINE> <INDENT> if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2): <NEW_LINE> <INDENT> has_fav = True <NEW_LINE> <DEDENT> <DEDENT> all_teachers = course_org.teacher_set.all() <NEW_LINE> return render(request, 'org-detail-teachers.html', { 'course_org': course_org, 'current_page': current_page, 'all_teachers': all_teachers, 'has_fav': has_fav, }) | 机构教师 | 62598fa2d53ae8145f918307 |
class BanUserForm(forms.Form): <NEW_LINE> <INDENT> username = forms.TextField(lazy_gettext(u'Username'), required=True) <NEW_LINE> def validate_username(self, value): <NEW_LINE> <INDENT> user = User.query.filter_by(username=value).first() <NEW_LINE> if user is None: <NEW_LINE> <INDENT> raise forms.ValidationError(_(u'No such user.')) <NEW_LINE> <DEDENT> if self.request is not None and self.request.user == user: <NEW_LINE> <INDENT> raise forms.ValidationError(_(u'You cannot ban yourself.')) <NEW_LINE> <DEDENT> self.user = user | Used to ban new users. | 62598fa299fddb7c1ca62d25 |
class TtsApiForm(NanoTtsForm): <NEW_LINE> <INDENT> response_type = StringField( default='audio_content', widget=HiddenInput(), description="Defines if the API should return the audio file itself" + "or its address.") <NEW_LINE> def validate_response_type(form, field): <NEW_LINE> <INDENT> response_types = [x[0] for x in RESPONSE_TYPE_CHOICES] + ['', ''] <NEW_LINE> if field.data not in response_types: <NEW_LINE> <INDENT> raise validators.ValidationError( 'Invalid choice %s, must be one of %s' % (field.data, response_types)) | Gives access to NanoTtsForm fields plus more advanced API related fields. | 62598fa2d268445f26639ac0 |
class TestExceptionConsistency(unittest.TestCase): <NEW_LINE> <INDENT> def _getExceptionClasses(self): <NEW_LINE> <INDENT> classes = inspect.getmembers( exceptions, isClassAndBaseServerExceptionSubclass) <NEW_LINE> return [class_ for _, class_ in classes] <NEW_LINE> <DEDENT> def testCodeInvariants(self): <NEW_LINE> <INDENT> codes = set() <NEW_LINE> for class_ in self._getExceptionClasses(): <NEW_LINE> <INDENT> code = class_.getErrorCode() <NEW_LINE> self.assertNotIn(code, codes) <NEW_LINE> codes.add(code) <NEW_LINE> self.assertIsNotNone(code) <NEW_LINE> self.assertGreaterEqual(code, 0) <NEW_LINE> self.assertLessEqual(code, 2**31 - 1) <NEW_LINE> <DEDENT> <DEDENT> def testInstantiation(self): <NEW_LINE> <INDENT> for class_ in self._getExceptionClasses(): <NEW_LINE> <INDENT> if class_ == exceptions.RequestValidationFailureException: <NEW_LINE> <INDENT> wrongString = "thisIsWrong" <NEW_LINE> objClass = protocol.SearchReadsRequest <NEW_LINE> obj = objClass() <NEW_LINE> obj.start = wrongString <NEW_LINE> jsonDict = obj.toJsonDict() <NEW_LINE> args = (jsonDict, objClass) <NEW_LINE> <DEDENT> elif class_ == exceptions.ResponseValidationFailureException: <NEW_LINE> <INDENT> objClass = protocol.SearchReadsResponse <NEW_LINE> obj = objClass() <NEW_LINE> obj.alignments = [protocol.ReadAlignment()] <NEW_LINE> obj.alignments[0].alignment = protocol.LinearAlignment() <NEW_LINE> obj.alignments[0].alignment.mappingQuality = wrongString <NEW_LINE> jsonDict = obj.toJsonDict() <NEW_LINE> args = (jsonDict, objClass) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> numInitArgs = len(inspect.getargspec( class_.__init__).args) - 1 <NEW_LINE> args = ['arg' for _ in range(numInitArgs)] <NEW_LINE> <DEDENT> instance = class_(*args) <NEW_LINE> self.assertIsInstance(instance, exceptions.BaseServerException) <NEW_LINE> message = instance.getMessage() <NEW_LINE> self.assertIsInstance(message, basestring) <NEW_LINE> self.assertGreater(len(message), 0) <NEW_LINE> self.assertEqual(instance.getErrorCode(), class_.getErrorCode()) <NEW_LINE> <DEDENT> <DEDENT> def testValidationFailureExceptionMessages(self): <NEW_LINE> <INDENT> wrongString = "thisIsWrong" <NEW_LINE> objClass = protocol.SearchReadsRequest <NEW_LINE> obj = objClass() <NEW_LINE> obj.start = wrongString <NEW_LINE> jsonDict = obj.toJsonDict() <NEW_LINE> instance = exceptions.RequestValidationFailureException( jsonDict, objClass) <NEW_LINE> self.assertIn("invalid fields:", instance.message) <NEW_LINE> self.assertIn("u'start': u'thisIsWrong'", instance.message) <NEW_LINE> self.assertEqual(instance.message.count(wrongString), 2) <NEW_LINE> objClass = protocol.SearchReadsResponse <NEW_LINE> obj = objClass() <NEW_LINE> obj.alignments = [protocol.ReadAlignment()] <NEW_LINE> obj.alignments[0].alignment = protocol.LinearAlignment() <NEW_LINE> obj.alignments[0].alignment.mappingQuality = wrongString <NEW_LINE> jsonDict = obj.toJsonDict() <NEW_LINE> instance = exceptions.ResponseValidationFailureException( jsonDict, objClass) <NEW_LINE> self.assertIn("Invalid fields", instance.message) <NEW_LINE> self.assertEqual(instance.message.count(wrongString), 2) | Ensure invariants of exceptions:
- every exception has a non-None error code
- every exception has a unique error code
- every exception has an error code in the range [0, 2**31-1]
- every exception can be instantiated successfully | 62598fa255399d3f0562639d |
class CloudresourcemanagerFoldersTestIamPermissionsRequest(_messages.Message): <NEW_LINE> <INDENT> foldersId = _messages.StringField(1, required=True) <NEW_LINE> testIamPermissionsRequest = _messages.MessageField('TestIamPermissionsRequest', 2) | A CloudresourcemanagerFoldersTestIamPermissionsRequest object.
Fields:
foldersId: Part of `resource`. REQUIRED: The resource for which the policy
detail is being requested. `resource` is usually specified as a path.
For example, a Project resource is specified as `projects/{project}`.
testIamPermissionsRequest: A TestIamPermissionsRequest resource to be
passed as the request body. | 62598fa28a43f66fc4bf1ff7 |
class MdnManager(models.Manager): <NEW_LINE> <INDENT> def create_from_as2mdn(self, as2mdn, message, status, return_url=None): <NEW_LINE> <INDENT> signed = bool(as2mdn.digest_alg) <NEW_LINE> if as2mdn.message_id is None: <NEW_LINE> <INDENT> message_id = as2mdn.orig_message_id <NEW_LINE> logger.warning( f"Received MDN response without a message-id. Using original " f"message-id as ID instead: {message_id}" ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message_id = as2mdn.message_id <NEW_LINE> <DEDENT> mdn, _ = self.update_or_create( message=message, defaults=dict( mdn_id=message_id, status=status, signed=signed, return_url=return_url, ), ) <NEW_LINE> filename = f"{uuid4()}.mdn" <NEW_LINE> mdn.headers.save( name=f"{filename}.header", content=ContentFile(as2mdn.headers_str) ) <NEW_LINE> mdn.payload.save(filename, content=ContentFile(as2mdn.content)) <NEW_LINE> return mdn | Custom model manager for the AS2 MDN model. | 62598fa2e5267d203ee6b788 |
class TwoWayIterator: <NEW_LINE> <INDENT> def __init__(self, list_of_stuff): <NEW_LINE> <INDENT> self.items = list_of_stuff <NEW_LINE> self.index = 0 <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self.index == len(self.items) - 1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.index += 1 <NEW_LINE> return self.items[self.index] <NEW_LINE> <DEDENT> def previous(self): <NEW_LINE> <INDENT> if self.index == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.index -= 1 <NEW_LINE> return self.items[self.index] <NEW_LINE> <DEDENT> def current(self): <NEW_LINE> <INDENT> return self.items[self.index] | Two way iterator class that is used as the backend for paging | 62598fa2be8e80087fbbeedb |
class BronchialLobe(_CaseInsensitiveEnum): <NEW_LINE> <INDENT> upper_lobe = 'Upper lobe' <NEW_LINE> middle_lobe = 'Middle lobe' <NEW_LINE> lower_lobe = 'Lower lobe' <NEW_LINE> stump = 'Stump' <NEW_LINE> bronchus = 'Bronchus' <NEW_LINE> unknown = 'Unknown' <NEW_LINE> not_reported = 'Not reported' | The named location of a portion of a lung or bronchus. | 62598fa244b2445a339b68ab |
class IAvatar(icrux.IAvatar): <NEW_LINE> <INDENT> pass | Tub-specific avatar interface. | 62598fa201c39578d7f12bfa |
class ParseAcceptLanguageTests(unittest.TestCase): <NEW_LINE> <INDENT> def test_parses_well_formatted_strings(self): <NEW_LINE> <INDENT> well_formatted_strings_with_expectations = ( ('en-US', [('en_US', 1.0)]), ('en-US,el-GR,fr', [('en_US', 1.0), ('el_GR', 1.0), ('fr', 1.0)]), ('en-US,el;q=0.8', [('en_US', 1.0), ('el', 0.8)])) <NEW_LINE> for acc_lang, expectations in well_formatted_strings_with_expectations: <NEW_LINE> <INDENT> parsed = locales.parse_accept_language(acc_lang) <NEW_LINE> self.assertEquals(expectations, parsed) <NEW_LINE> <DEDENT> <DEDENT> def test_arranges_quality_scores_in_decreasing_order(self): <NEW_LINE> <INDENT> parsed = locales.parse_accept_language('en-US;q=0.8,el;q=1.0') <NEW_LINE> expected = [('el', 1.0), ('en_US', 0.8)] <NEW_LINE> self.assertEquals(expected, parsed) <NEW_LINE> <DEDENT> def test_appect_lang_header_length_capped_at_8k(self): <NEW_LINE> <INDENT> with self.assertRaises(AssertionError): <NEW_LINE> <INDENT> locales.parse_accept_language('x' * 8192) | Unit tests for parsing of Accept-Language HTTP header. | 62598fa2cb5e8a47e493c0b4 |
class RegisterView(MethodView): <NEW_LINE> <INDENT> decorators = [user_already_authenticated] <NEW_LINE> post_args = { 'email': fields.Email(required=True, validate=[unique_user_email]), 'password': fields.String( required=True, validate=[validate.Length(min=6, max=128)]) } <NEW_LINE> def login_user(self, user): <NEW_LINE> <INDENT> if not current_security.confirmable or current_security.login_without_confirmation: <NEW_LINE> <INDENT> after_this_request(_commit) <NEW_LINE> login_user(user) <NEW_LINE> <DEDENT> <DEDENT> def success_response(self, user): <NEW_LINE> <INDENT> return jsonify(default_user_payload(user)) <NEW_LINE> <DEDENT> @use_kwargs(post_args) <NEW_LINE> def post(self, **kwargs): <NEW_LINE> <INDENT> user = register_user(**kwargs) <NEW_LINE> self.login_user(user) <NEW_LINE> return self.success_response(user) | View to register a new user. | 62598fa2b7558d58954634a9 |
class Section(ndb.Model): <NEW_LINE> <INDENT> term = ndb.KeyProperty(kind=Term) <NEW_LINE> hour = ndb.StringProperty() <NEW_LINE> title = ndb.StringProperty() <NEW_LINE> instructor = ndb.KeyProperty(kind=Instructor, repeated=True) <NEW_LINE> location = ndb.StringProperty() <NEW_LINE> section = ndb.StringProperty() <NEW_LINE> full_title = ndb.ComputedProperty(lambda self: self.key.parent().string_id() + "-" + self.section) <NEW_LINE> search_course = ndb.ComputedProperty(lambda self: self.key.parent().string_id()) <NEW_LINE> search_dept = ndb.ComputedProperty(lambda self: filter(lambda letter:letter.isalpha(), self.key.parent().string_id())) <NEW_LINE> search_level = ndb.ComputedProperty(lambda self: self.key.parent().string_id()[:-2]) | A section of a class that is being offered during a term. | 62598fa27d847024c075c241 |
class LearningAgent(Agent): <NEW_LINE> <INDENT> def __init__(self, env, alphaBetaGamma=(0.8, 0.1, 0.005)): <NEW_LINE> <INDENT> super(LearningAgent, self).__init__(env) <NEW_LINE> self.color = 'red' <NEW_LINE> self.planner = RoutePlanner(self.env, self) <NEW_LINE> self.penalty = 0 <NEW_LINE> self.reward = 0 <NEW_LINE> self.alpha = alphaBetaGamma[0] <NEW_LINE> self.gamma = alphaBetaGamma[1] <NEW_LINE> self.epsilon = alphaBetaGamma[2] <NEW_LINE> self.Q = defaultdict(self.getDefaultQvalues) <NEW_LINE> self.totalPenaltiesSuccess = [] <NEW_LINE> self.totalRewardsSuccess = [] <NEW_LINE> self.totalStepsSuccess = [] <NEW_LINE> self.totalPenaltiesFailure = [] <NEW_LINE> self.totalRewardsFailure = [] <NEW_LINE> self.totalStepsFailure = [] <NEW_LINE> <DEDENT> def getDefaultQvalues(self): <NEW_LINE> <INDENT> Q = {} <NEW_LINE> for action in Environment.valid_actions: <NEW_LINE> <INDENT> Q[action] = 1 <NEW_LINE> <DEDENT> return Q <NEW_LINE> <DEDENT> def reset(self, destination=None): <NEW_LINE> <INDENT> self.planner.route_to(destination) <NEW_LINE> self.penalty = 0 <NEW_LINE> self.reward = 0 <NEW_LINE> <DEDENT> def update(self, t): <NEW_LINE> <INDENT> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> inputs = self.env.sense(self) <NEW_LINE> deadline = self.env.get_deadline(self) <NEW_LINE> self.state = (self.next_waypoint, inputs['light'], inputs['oncoming'], inputs['left']) <NEW_LINE> action = self.chooseAction() <NEW_LINE> reward = self.env.act(self, action) <NEW_LINE> if reward < 0: <NEW_LINE> <INDENT> self.penalty += 1 <NEW_LINE> <DEDENT> self.learn(t, action, reward) <NEW_LINE> self.reward += reward <NEW_LINE> if self.planner.next_waypoint() == None: <NEW_LINE> <INDENT> self.totalRewardsSuccess.append(self.reward) <NEW_LINE> self.totalPenaltiesSuccess.append(self.penalty) <NEW_LINE> self.totalStepsSuccess.append(t + 1) <NEW_LINE> <DEDENT> elif deadline == 0: <NEW_LINE> <INDENT> self.totalRewardsFailure.append(self.reward) <NEW_LINE> self.totalPenaltiesFailure.append(self.penalty) <NEW_LINE> self.totalStepsFailure.append(t + 1) <NEW_LINE> <DEDENT> <DEDENT> def learn(self, t, action, reward): <NEW_LINE> <INDENT> learningRate = 1.0 / (t + 1) ** self.alpha <NEW_LINE> newWaypoint = self.planner.next_waypoint() <NEW_LINE> newInputs = self.env.sense(self) <NEW_LINE> newState = (newWaypoint, newInputs['light'], newInputs['oncoming'], newInputs['left']) <NEW_LINE> newAction = self.chooseAction(newState) <NEW_LINE> newQ = reward + self.gamma * newAction[1] <NEW_LINE> currentQ = self.Q[self.state][action] <NEW_LINE> self.Q[self.state][action] = (1 - learningRate) * currentQ + learningRate * newQ <NEW_LINE> <DEDENT> def chooseAction(self, state=None): <NEW_LINE> <INDENT> if (state): <NEW_LINE> <INDENT> actions = self.Q[state] <NEW_LINE> return max(actions.iteritems(), key=operator.itemgetter(1)) <NEW_LINE> <DEDENT> bestAction = max(self.Q[self.state].iteritems(), key=operator.itemgetter(1))[0] <NEW_LINE> if random.random() < self.epsilon: <NEW_LINE> <INDENT> random_actions = [action for action in self.env.valid_actions if action != bestAction] <NEW_LINE> return random.choice(random_actions) <NEW_LINE> <DEDENT> return bestAction | An agent that learns to drive in the smartcab world. | 62598fa207f4c71912baf2be |
class ZhaoEtAl2006SSlabNSHMP2014(ZhaoEtAl2006SSlab): <NEW_LINE> <INDENT> def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): <NEW_LINE> <INDENT> C = self.COEFFS_ASC[imt] <NEW_LINE> C_SSLAB = self.COEFFS_SSLAB[imt] <NEW_LINE> d = dists.rrup <NEW_LINE> d[d == 0.0] = 0.1 <NEW_LINE> if rup.mag > 7.8: <NEW_LINE> <INDENT> rup_mag = 7.8 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rup_mag = rup.mag <NEW_LINE> <DEDENT> mean = self._compute_magnitude_term(C, rup_mag) + self._compute_distance_term(C, rup_mag, d) + self._compute_focal_depth_term(C, rup.hypo_depth) + self._compute_site_class_term(C, sites.vs30) + self._compute_magnitude_squared_term(P=C_SSLAB['PS'], M=6.5, Q=C_SSLAB['QS'], W=C_SSLAB['WS'], mag=rup_mag) + C_SSLAB['SS'] + self._compute_slab_correction_term(C_SSLAB, d) <NEW_LINE> mean = np.log(np.exp(mean) * 1e-2 / g) <NEW_LINE> stddevs = self._get_stddevs(C['sigma'], C_SSLAB['tauS'], stddev_types, num_sites=len(sites.vs30)) <NEW_LINE> return mean, stddevs | For the 2014 US National Seismic Hazard Maps the magnitude of Zhao et al.
(2006) for the subduction inslab events is capped at magnitude Mw 7.8 | 62598fa26aa9bd52df0d4d45 |
class ConfigFilterLinesEnvironmentMixin( ConfigEnvironmentMixin, FilterLinesEnvironmentMixin, ): <NEW_LINE> <INDENT> def __init__(self, config, **kw): <NEW_LINE> <INDENT> strict_utf8 = config.get_bool('emailstrictutf8', default=None) <NEW_LINE> if strict_utf8 is not None: <NEW_LINE> <INDENT> kw['strict_utf8'] = strict_utf8 <NEW_LINE> <DEDENT> email_max_line_length = config.get('emailmaxlinelength') <NEW_LINE> if email_max_line_length is not None: <NEW_LINE> <INDENT> kw['email_max_line_length'] = int(email_max_line_length) <NEW_LINE> <DEDENT> max_subject_length = config.get('subjectMaxLength', default=email_max_line_length) <NEW_LINE> if max_subject_length is not None: <NEW_LINE> <INDENT> kw['max_subject_length'] = int(max_subject_length) <NEW_LINE> <DEDENT> super(ConfigFilterLinesEnvironmentMixin, self).__init__( config=config, **kw ) | Handle encoding and maximum line length based on config. | 62598fa232920d7e50bc5ed1 |
class GateArg(IntEnum): <NEW_LINE> <INDENT> gtp1 = 1 <NEW_LINE> gtp2 = 2 <NEW_LINE> gtp3 = 3 | Possible gates for all ticked note commands.
Gate is an optional argument appended to the end of a ticked note command
which adds 1-3 ticks to the note's length, allowing for finer control. | 62598fa299cbb53fe6830d4f |
class NaiveBayesModelTreeClassifier(DecisionTreeClassifier): <NEW_LINE> <INDENT> def __init__(self, criterion="gini", splitter="best", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, class_weight=None, presort=False): <NEW_LINE> <INDENT> super().__init__( criterion=criterion, splitter=splitter, max_depth=max_depth, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, min_weight_fraction_leaf=min_weight_fraction_leaf, max_features=max_features, max_leaf_nodes=max_leaf_nodes, class_weight=class_weight, random_state=random_state, min_impurity_decrease=min_impurity_decrease, min_impurity_split=min_impurity_split, presort=presort) <NEW_LINE> self._leaves = {} <NEW_LINE> <DEDENT> def fit(self, X, y, sample_weight=None, check_input=True, X_idx_sorted=None): <NEW_LINE> <INDENT> super(DecisionTreeClassifier, self).fit( X, y, sample_weight=sample_weight, check_input=check_input, X_idx_sorted=X_idx_sorted) <NEW_LINE> leaves_indices = self.tree_.apply(X) <NEW_LINE> leaf_to_instances = defaultdict(list) <NEW_LINE> for instance_index, leaf_index in enumerate(leaves_indices): <NEW_LINE> <INDENT> leaf_to_instances[leaf_index].append(instance_index) <NEW_LINE> <DEDENT> for leaf_index, instances_indices in leaf_to_instances.items(): <NEW_LINE> <INDENT> self._leaves[leaf_index] = NaiveBayesLeaf(leaf_index) <NEW_LINE> self._leaves[leaf_index].fit(X[instances_indices,], y[instances_indices]) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def predict_proba(self, X, check_input=True): <NEW_LINE> <INDENT> X = self._validate_X_predict(X, check_input) <NEW_LINE> leaves_indices = self.apply(X) <NEW_LINE> n_samples = X.shape[0] <NEW_LINE> results = np.zeros(shape=(n_samples, self.n_classes_)) <NEW_LINE> for instance_index, leaf_index in enumerate(leaves_indices): <NEW_LINE> <INDENT> bayes_result = self._leaves[leaf_index].model.predict_proba([X[instance_index]]) <NEW_LINE> model_classes = list(self._leaves[leaf_index].model.classes_) <NEW_LINE> result_with_all_classes = np.zeros(shape=self.n_classes_) <NEW_LINE> for class_number in range(0, self.n_classes_): <NEW_LINE> <INDENT> if class_number in model_classes: <NEW_LINE> <INDENT> result_with_all_classes[class_number] = bayes_result[0, model_classes.index(class_number)] <NEW_LINE> <DEDENT> <DEDENT> results[instance_index] = result_with_all_classes <NEW_LINE> <DEDENT> return results | Decision tree that uses a Naive Bayes model in the leaves.
This tree will be used as a base_estimator for the Random Forest Classifier. | 62598fa2a8ecb0332587108a |
class Services: <NEW_LINE> <INDENT> loop = None <NEW_LINE> logger = None <NEW_LINE> daemon = None <NEW_LINE> aiodocker = None | These needs to be injected from the plugin init code | 62598fa2009cb60464d013a1 |
class PersonTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(PersonTests, self).setUp() <NEW_LINE> self.person = factories.PersonFactory() <NEW_LINE> <DEDENT> def test_full_name(self): <NEW_LINE> <INDENT> expected = self.person.given_name + ' ' + self.person.family_name <NEW_LINE> self.assertEqual(self.person.full_name, expected) <NEW_LINE> <DEDENT> def test_get_profile_image_url(self): <NEW_LINE> <INDENT> self.assertEqual(self.person.get_profile_image_url, self.person.profile_image_url) <NEW_LINE> person = factories.PersonFactory(profile_image_url=None) <NEW_LINE> self.assertEqual(person.get_profile_image_url, person.profile_image.url) <NEW_LINE> person = factories.PersonFactory(profile_image_url=None, profile_image=None) <NEW_LINE> self.assertFalse(person.get_profile_image_url) <NEW_LINE> <DEDENT> def test_str(self): <NEW_LINE> <INDENT> self.assertEqual(str(self.person), self.person.full_name) | Tests for the `Person` model. | 62598fa201c39578d7f12bfb |
class Encoder(Transcoder): <NEW_LINE> <INDENT> def __init__(self, filetype, command): <NEW_LINE> <INDENT> Transcoder.__init__(self) <NEW_LINE> self.filetype = filetype <NEW_LINE> self.mimetype = MIMETYPES[filetype] <NEW_LINE> self.command = command <NEW_LINE> <DEDENT> def encode(self, decoder_process, bitrate): <NEW_LINE> <INDENT> cmd = [find_executable(self.command[0])] + self.command[1:] <NEW_LINE> if 'BITRATE' in cmd: <NEW_LINE> <INDENT> cmd[cmd.index('BITRATE')] = str(bitrate) <NEW_LINE> <DEDENT> if 'KBITRATE' in cmd: <NEW_LINE> <INDENT> cmd[cmd.index('KBITRATE')] = str(bitrate) + 'k' <NEW_LINE> <DEDENT> return subprocess.Popen(cmd, stdin=decoder_process.stdout, stdout=subprocess.PIPE, stderr=Transcoder.devnull ) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<Encoder type='%s' cmd='%s'>" % (self.filetype, str(' '.join(self.command))) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__() | encoder | 62598fa22c8b7c6e89bd3642 |
class SetUUIDWithMkFs(SetUUID): <NEW_LINE> <INDENT> @skipIf(sys.version_info < (3, 4), "assertLogs is not supported") <NEW_LINE> def test_set_invalid_uuid(self): <NEW_LINE> <INDENT> an_fs = self._fs_class(device=self.loop_devices[0], uuid=self._invalid_uuid) <NEW_LINE> if self._fs_class._type == "swap": <NEW_LINE> <INDENT> with six.assertRaisesRegex(self, FSWriteUUIDError, "bad UUID format"): <NEW_LINE> <INDENT> an_fs.create() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> with self.assertLogs('blivet', 'WARNING') as logs: <NEW_LINE> <INDENT> an_fs.create() <NEW_LINE> <DEDENT> self.assertTrue(len(logs.output) >= 1) <NEW_LINE> self.assertRegex(logs.output[0], "UUID format.*unacceptable") <NEW_LINE> <DEDENT> <DEDENT> def test_set_uuid(self): <NEW_LINE> <INDENT> an_fs = self._fs_class(device=self.loop_devices[0], uuid=self._valid_uuid) <NEW_LINE> self.assertIsNone(an_fs.create()) <NEW_LINE> out = capture_output(["blkid", "-sUUID", "-ovalue", self.loop_devices[0]]) <NEW_LINE> self.assertEqual(out.strip(), self._valid_uuid) | Tests various aspects of setting an UUID for a filesystem where the
native mkfs tool can set the UUID. | 62598fa2e1aae11d1e7ce761 |
class HashiCorpVaultSecretProvider(SecretProviderBase): <NEW_LINE> <INDENT> name = 'SecretInVault' <NEW_LINE> def checkConfig(self, vaultServer=None, vaultToken=None, secretsmount=None): <NEW_LINE> <INDENT> if not isinstance(vaultServer, str): <NEW_LINE> <INDENT> config.error("vaultServer must be a string while it is %s" % (type(vaultServer,))) <NEW_LINE> <DEDENT> if not isinstance(vaultToken, str): <NEW_LINE> <INDENT> config.error("vaultToken must be a string while it is %s" % (type(vaultToken,))) <NEW_LINE> <DEDENT> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def reconfigService(self, vaultServer=None, vaultToken=None, secretsmount=None): <NEW_LINE> <INDENT> if secretsmount is None: <NEW_LINE> <INDENT> self.secretsmount = "secret" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.secretsmount = secretsmount <NEW_LINE> <DEDENT> self.vaultServer = vaultServer <NEW_LINE> self.vaultToken = vaultToken <NEW_LINE> if vaultServer.endswith('/'): <NEW_LINE> <INDENT> vaultServer = vaultServer[:-1] <NEW_LINE> <DEDENT> self._http = yield httpclientservice.HTTPClientService.getService( self.master, self.vaultServer, headers={'X-Vault-Token': self.vaultToken}) <NEW_LINE> <DEDENT> @defer.inlineCallbacks <NEW_LINE> def get(self, entry): <NEW_LINE> <INDENT> path = self.secretsmount + '/' + entry <NEW_LINE> proj = yield self._http.get('/v1/{0}'.format(path)) <NEW_LINE> code = yield proj.code <NEW_LINE> if code != 200: <NEW_LINE> <INDENT> raise KeyError("The key %s does not exist in Vault provider: request" " return code:%d." % (entry, code)) <NEW_LINE> <DEDENT> json = yield proj.json() <NEW_LINE> defer.returnValue(json.get(u'data', {}).get('value')) | basic provider where each secret is stored in Vault | 62598fa238b623060ffa8f10 |
class tetgen(PyMesh.tetgen): <NEW_LINE> <INDENT> @property <NEW_LINE> def mesh(self): <NEW_LINE> <INDENT> return form_mesh(self.vertices, self.faces, self.voxels); <NEW_LINE> <DEDENT> def __setattr__(self, key, value): <NEW_LINE> <INDENT> if not hasattr(self, key): <NEW_LINE> <INDENT> raise AttributeError( "Attribute '{}' does not exists!".format(key)); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> PyMesh.tetgen.__setattr__(self, key, value) | Wrapper around Si's `TetGen <http://wias-berlin.de/software/tetgen/>`_.
All attributes, except ``vertices``, ``faces``, ``voxels`` and ``mesh``,
are either input geometry or configuration parameters.
Attributes:
points (:class:`numpy.ndarray`): n by 3 list of points to be
tetrahedralized.
triangles (:class:`numpy.ndarray`): m by 3 matrix of indices into
points. Together, points and triangles defined PLC.
tetrhaedra (:class:`numpy.ndarray`): t by 4 matrix of indices into
points. Used for refinement.
point_markers (:class:`numpy.ndarray`): List of integer point markers of
size n. Point marker cannot be 0.
point_weights (:class:`numpy.ndarray`): List of point weights. Used for
weight Delaunay tetrahedralization.
triangle_marker (:class:`numpy.ndarray`): List of integer triangle
markers of size t.
split_boundary (``bool``): whether to split input boundary. Default is
true.
max_radius_edge_ratio (``float``): Default is 2.0.
min_dihedral_angle (``float``): Default is 0.0.
coarsening (``bool``): Coarsening the input tet mesh. Default is false.
max_tet_volume (``float``): Default is unbounded.
optimization_level (``int``): Ranges from 0 to 10. Default is 2.
max_num_steiner_points (``int``): Default is unbounded.
coplanar_tolerance (``float``): Used for determine when 4 points are
coplanar. Default is 1e-8.
exact_arithmetic (``bool``): Whether to use exact predicates. Default
is true.
merge_coplanar (``bool``): Whether to merge coplanar faces and nearby
vertices. Default is true.
weighted_delaunay (``bool``): Compute weighted Delaunay
tetrahedralization instead of conforming Delaunay. Default is
false. This option requires `point_weights`.
keep_convex_hull (``bool``): Keep all tets within the convex hull.
Default is false.
verbosity (``int``): Verbosity level. Ranges from 0 to 4:
0. no output
1. normal level of output
2. verbose output
3. more details
4. you must be debugging the tetgen code
vertices (:class:`numpy.ndarray`): Vertices of the output tet mesh.
faces (:class:`numpy.ndarray`): Faces of the output tet mesh.
voxels (:class:`numpy.ndarray`): Voxels of the output tet mesh.
mesh (:class:`Mesh`): Output tet mesh.
Example:
>>> input_mesh = pymesh.generate_icosphere(1.0, [0.0, 0.0, 0.0]);
>>> tetgen = pymesh.tetgen();
>>> tetgen.points = input_mesh.vertices; # Input points.
>>> tetgen.triangles = input_mesh.faces; # Input triangles
>>> tetgen.max_tet_volume = 0.01;
>>> tetgen.verbosity = 0;
>>> tetgen.run(); # Execute tetgen
>>> mesh = tetgen.mesh; # Extract output tetrahedral mesh. | 62598fa2eab8aa0e5d30bc04 |
class Preview( object ) : <NEW_LINE> <INDENT> pass | Preview class simulating a database model class, for translating wiki
text to html | 62598fa230dc7b766599f6ca |
class TextReplaceListRequest(object): <NEW_LINE> <INDENT> swagger_types = { 'text_replaces': 'list[TextReplace]', 'default_font': 'str', 'start_index': 'int', 'count_replace': 'int' } <NEW_LINE> attribute_map = { 'text_replaces': 'TextReplaces', 'default_font': 'DefaultFont', 'start_index': 'StartIndex', 'count_replace': 'CountReplace' } <NEW_LINE> def __init__(self, text_replaces=None, default_font=None, start_index=None, count_replace=None): <NEW_LINE> <INDENT> self._text_replaces = None <NEW_LINE> self._default_font = None <NEW_LINE> self._start_index = None <NEW_LINE> self._count_replace = None <NEW_LINE> self.text_replaces = text_replaces <NEW_LINE> if default_font is not None: <NEW_LINE> <INDENT> self.default_font = default_font <NEW_LINE> <DEDENT> if start_index is not None: <NEW_LINE> <INDENT> self.start_index = start_index <NEW_LINE> <DEDENT> if count_replace is not None: <NEW_LINE> <INDENT> self.count_replace = count_replace <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def text_replaces(self): <NEW_LINE> <INDENT> return self._text_replaces <NEW_LINE> <DEDENT> @text_replaces.setter <NEW_LINE> def text_replaces(self, text_replaces): <NEW_LINE> <INDENT> if text_replaces is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `text_replaces`, must not be `None`") <NEW_LINE> <DEDENT> self._text_replaces = text_replaces <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_font(self): <NEW_LINE> <INDENT> return self._default_font <NEW_LINE> <DEDENT> @default_font.setter <NEW_LINE> def default_font(self, default_font): <NEW_LINE> <INDENT> self._default_font = default_font <NEW_LINE> <DEDENT> @property <NEW_LINE> def start_index(self): <NEW_LINE> <INDENT> return self._start_index <NEW_LINE> <DEDENT> @start_index.setter <NEW_LINE> def start_index(self, start_index): <NEW_LINE> <INDENT> self._start_index = start_index <NEW_LINE> <DEDENT> @property <NEW_LINE> def count_replace(self): <NEW_LINE> <INDENT> return self._count_replace <NEW_LINE> <DEDENT> @count_replace.setter <NEW_LINE> def count_replace(self, count_replace): <NEW_LINE> <INDENT> self._count_replace = count_replace <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TextReplaceListRequest): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa28e7ae83300ee8f1d |
@pytest.mark.skipif( LooseVersion(pytest.config.getoption('--release')) < LooseVersion('14.0.0'), reason='This collection is fully implemented on 14.0.0 or greater.' ) <NEW_LINE> class TestLearningSuggestions(object): <NEW_LINE> <INDENT> def test_learning_suggestion(self, mgmt_root): <NEW_LINE> <INDENT> kind = 'tm:security:protocol-inspection:' 'learning-suggestions:learning-suggestionscollectionstats' <NEW_LINE> st = str(mgmt_root.tm.security.protocol_inspection. learning_suggestions.load().kind) <NEW_LINE> assert kind == st | TestLearningSuggestions functional tests | 62598fa2498bea3a75a5799f |
class TestHeketiVolume(BaseClass): <NEW_LINE> <INDENT> def _find_bricks(self, brick_paths, present): <NEW_LINE> <INDENT> oc_node = self.ocp_master_node[0] <NEW_LINE> cmd = ( 'bash -c "' 'if [ -d "%s" ]; then echo present; else echo absent; fi"') <NEW_LINE> g_hosts = list(g.config.get("gluster_servers", {}).keys()) <NEW_LINE> results = [] <NEW_LINE> assertion_method = self.assertIn if present else self.assertNotIn <NEW_LINE> for brick_path in brick_paths: <NEW_LINE> <INDENT> for g_host in g_hosts: <NEW_LINE> <INDENT> out = openshift_ops.cmd_run_on_gluster_pod_or_node( oc_node, cmd % brick_path, gluster_node=g_host) <NEW_LINE> results.append(out) <NEW_LINE> <DEDENT> assertion_method('present', results) <NEW_LINE> <DEDENT> <DEDENT> @pytest.mark.tier1 <NEW_LINE> def test_validate_brick_paths_on_gluster_pods_or_nodes(self): <NEW_LINE> <INDENT> vol = heketi_volume_create( self.heketi_client_node, self.heketi_server_url, size=1, json=True) <NEW_LINE> self.assertTrue(vol, "Failed to create 1Gb heketi volume") <NEW_LINE> vol_id = vol["bricks"][0]["volume"] <NEW_LINE> self.addCleanup( heketi_volume_delete, self.heketi_client_node, self.heketi_server_url, vol_id, raise_on_error=False) <NEW_LINE> brick_paths = [p['path'] for p in vol["bricks"]] <NEW_LINE> self._find_bricks(brick_paths, present=True) <NEW_LINE> out = heketi_volume_delete( self.heketi_client_node, self.heketi_server_url, vol_id) <NEW_LINE> self.assertTrue(out, "Failed to delete heketi volume %s" % vol_id) <NEW_LINE> self._find_bricks(brick_paths, present=False) | Check volume bricks presence in fstab files on Gluster PODs. | 62598fa23539df3088ecc131 |
@keys.assign(seq=seqs.GT, modes=_MODES_ACTION) <NEW_LINE> class ViActivateNextTab(ViOperatorDef): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> ViOperatorDef.__init__(self, *args, **kwargs) <NEW_LINE> self.scroll_into_view = True <NEW_LINE> <DEDENT> def translate(self, state): <NEW_LINE> <INDENT> cmd = {} <NEW_LINE> cmd['action'] = '_vi_gt' <NEW_LINE> cmd['action_args'] = {'mode': state.mode, 'count': state.count} <NEW_LINE> return cmd | Vim: `gt` | 62598fa210dbd63aa1c70a2c |
class test_regular_partition_uniform_distribution_rectangle_domain_int_01D(data_01D, regular_partition_uniform_distribution_rectangle_domain_int): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(test_regular_partition_uniform_distribution_rectangle_domain_int_01D, self).createData() <NEW_LINE> super( test_regular_partition_uniform_distribution_rectangle_domain_int_01D, self).setUp() | Tests :meth:`bet.calculateP.simpleFunP.regular_partition_uniform_distribution_rectangle_domain` on 01D data domain. | 62598fa216aa5153ce40037e |
class MyUserCreateSerializer(serializers.UserCreateSerializer): <NEW_LINE> <INDENT> class Meta(serializers.UserCreateSerializer.Meta): <NEW_LINE> <INDENT> fields = serializers.UserCreateSerializer.Meta.fields + ('first_name',) | Расширяет базовый сериализатор UserCreateSerializer | 62598fa27047854f4633f255 |
class UserProfileView(ExtendableModelMixin, generics.RetrieveUpdateAPIView): <NEW_LINE> <INDENT> def extend_response_data(self, data): <NEW_LINE> <INDENT> extend_users_response(data, self.request) <NEW_LINE> <DEDENT> queryset = User.objects.all() <NEW_LINE> permission_classes = (permissions.IsAuthenticated,) <NEW_LINE> serializer_class = ProfilePublicSerializer <NEW_LINE> def get_serializer_class(self): <NEW_LINE> <INDENT> if self.request.method in permissions.SAFE_METHODS: <NEW_LINE> <INDENT> return ProfilePublicSerializer <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ProfileUserSerializer <NEW_LINE> <DEDENT> <DEDENT> def get_object(self): <NEW_LINE> <INDENT> self.request.user.refresh_from_db() <NEW_LINE> return self.request.user | ---
PATCH:
parameters:
- name: website
description: user website
- name: gender
description: 0 - female, 1 - male.
- name: avatar
required: false
type: file
PUT:
parameters:
- name: website
description: user website
- name: gender
description: 0 - female, 1 - male. | 62598fa255399d3f0562639f |
class ScannerSetup(KSetting): <NEW_LINE> <INDENT> K_CODE = b'K504' <NEW_LINE> K_PATTERN = ( b'^<%s,([\d]{2,3})?,([0-2])?,([\d]{2,3})?,([\d]{2,3})?>$' % K_CODE) <NEW_LINE> def __init__( self, gain_level=350, agc_sampling_mode=AGCSamplingMode.Continuous, agc_min=70, agc_max=245): <NEW_LINE> <INDENT> self.gain_level = gain_level <NEW_LINE> self.agc_sampling_mode = agc_sampling_mode <NEW_LINE> self.agc_min = agc_min <NEW_LINE> self.agc_max = agc_max <NEW_LINE> <DEDENT> def is_valid(self): <NEW_LINE> <INDENT> return all([ isinstance(self.gain_level, int), self.scan_speed >= 40, self.scan_speed <= 255, isinstance(self.agc_sampling_mode, AGCSamplingMode), isinstance(self.agc_min, int), self.agc_min >= 40, self.agc_min <= 250, isinstance(self.agc_max, int), self.agc_max >= 60, self.agc_max <= 255, ]) <NEW_LINE> <DEDENT> def to_config_string(self): <NEW_LINE> <INDENT> return super().to_config_string([ self.gain_level, self.agc_sampling_mode.value, self.agc_min, self.agc_max, ]) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_config_string(cls, str_): <NEW_LINE> <INDENT> match = re.match(cls.K_PATTERN, str_) <NEW_LINE> try: <NEW_LINE> <INDENT> gain_level, agc_samling_mode, agc_min, agc_max = match.groups() <NEW_LINE> <DEDENT> except (ValueError, AttributeError): <NEW_LINE> <INDENT> raise InvalidConfigString( 'Cannot decode config string %s for K-code %s' % (str_, cls.K_CODE)) <NEW_LINE> <DEDENT> return cls( gain_level=int(gain_level), agc_sampling_mode=AGCSamplingMode(agc_samling_mode), agc_min=int(agc_min), agc_max=int(agc_max), ) | See page 4-17 of Microscan MS3 manual for reference
Note that the user manual groups the "Scan Speed" setting under the
"Scanner Setup" heading. This library treats it as separate setting because
it is stored with a distinct K-code `K500` while all other Scanner Setup
settings are stored with a K-code of `K504`. | 62598fa2462c4b4f79dbb889 |
class Centerline(MultiLineString): <NEW_LINE> <INDENT> def __init__(self, input_geom, interpolation_dist=5.1, **attributes): <NEW_LINE> <INDENT> if not isinstance(input_geom, Polygon): <NEW_LINE> <INDENT> raise ValueError( 'Input geometry must be of type shapely.geometry.Polygon!' ) <NEW_LINE> <DEDENT> self._input_geom = input_geom <NEW_LINE> self._interpolation_dist = abs(interpolation_dist) <NEW_LINE> self._minx = int(min(self._input_geom.envelope.exterior.xy[0])) <NEW_LINE> self._miny = int(min(self._input_geom.envelope.exterior.xy[1])) <NEW_LINE> for key in attributes: <NEW_LINE> <INDENT> setattr(self, key, attributes.get(key)) <NEW_LINE> <DEDENT> super(Centerline, self).__init__(lines=self._create_centerline()) <NEW_LINE> <DEDENT> def _create_centerline(self): <NEW_LINE> <INDENT> border = array(self.__densify_border()) <NEW_LINE> vor = Voronoi(border) <NEW_LINE> vertex = vor.vertices <NEW_LINE> lst_lines = [] <NEW_LINE> for j, ridge in enumerate(vor.ridge_vertices): <NEW_LINE> <INDENT> if -1 not in ridge: <NEW_LINE> <INDENT> line = LineString([ (vertex[ridge[0]][0] + self._minx, vertex[ridge[0]][1] + self._miny), (vertex[ridge[1]][0] + self._minx, vertex[ridge[1]][1] + self._miny)]) <NEW_LINE> if line.within(self._input_geom) and len(line.coords[0]) > 1: <NEW_LINE> <INDENT> lst_lines.append(line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return unary_union(lst_lines) <NEW_LINE> <DEDENT> def __densify_border(self): <NEW_LINE> <INDENT> if len(self._input_geom.interiors) == 0: <NEW_LINE> <INDENT> exterIN = LineString(self._input_geom.exterior) <NEW_LINE> points = self.__fixed_interpolation(exterIN) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exterIN = LineString(self._input_geom.exterior) <NEW_LINE> points = self.__fixed_interpolation(exterIN) <NEW_LINE> for j in range(len(self._input_geom.interiors)): <NEW_LINE> <INDENT> interIN = LineString(self._input_geom.interiors[j]) <NEW_LINE> points += self.__fixed_interpolation(interIN) <NEW_LINE> <DEDENT> <DEDENT> return points <NEW_LINE> <DEDENT> def __fixed_interpolation(self, line): <NEW_LINE> <INDENT> STARTPOINT = [line.xy[0][0] - self._minx, line.xy[1][0] - self._miny] <NEW_LINE> ENDPOINT = [line.xy[0][-1] - self._minx, line.xy[1][-1] - self._miny] <NEW_LINE> count = self._interpolation_dist <NEW_LINE> newline = [STARTPOINT] <NEW_LINE> while count < line.length: <NEW_LINE> <INDENT> point = line.interpolate(count) <NEW_LINE> newline.append([point.x - self._minx, point.y - self._miny]) <NEW_LINE> count += self._interpolation_dist <NEW_LINE> <DEDENT> newline.append(ENDPOINT) <NEW_LINE> return newline | The polygon's skeleton.
The polygon's attributes are copied and set as the centerline's
attributes. The rest of the attributes are inherited from the
MultiLineString class.
Attributes:
geoms (shapely.geometry.base.GeometrySequence): A sequence of
LineStrings
Extends:
shapely.geometry.MultiLineString | 62598fa26fb2d068a7693d73 |
class ChannelDispatchOperation(dbus.service.Object): <NEW_LINE> <INDENT> @dbus.service.method('org.freedesktop.Telepathy.ChannelDispatchOperation', in_signature='s', out_signature='') <NEW_LINE> def HandleWith(self, Handler): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @dbus.service.method('org.freedesktop.Telepathy.ChannelDispatchOperation', in_signature='', out_signature='') <NEW_LINE> def Claim(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @dbus.service.method('org.freedesktop.Telepathy.ChannelDispatchOperation', in_signature='sx', out_signature='') <NEW_LINE> def HandleWithTime(self, Handler, UserActionTime): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @dbus.service.signal('org.freedesktop.Telepathy.ChannelDispatchOperation', signature='oss') <NEW_LINE> def ChannelLost(self, Channel, Error, Message): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @dbus.service.signal('org.freedesktop.Telepathy.ChannelDispatchOperation', signature='') <NEW_LINE> def Finished(self): <NEW_LINE> <INDENT> pass | A channel dispatch operation is an object in the ChannelDispatcher
representing a batch of unrequested channels being announced to
client
Approver
processes.
These objects can result from new incoming channels or channels
which are automatically created for some reason, but cannot result
from outgoing requests for channels.
More specifically, whenever the
Connection.Interface.Requests.NewChannels
signal contains channels whose
Requested
property is false, or whenever the
Connection.NewChannel
signal contains a channel with suppress_handler false,
one or more ChannelDispatchOperation objects are created for those
channels.
(If some channels in a NewChannels signal are in different bundles,
this is an error. The channel dispatcher SHOULD recover by treating
the NewChannels signal as if it had been several NewChannels signals
each containing one channel.)
First, the channel dispatcher SHOULD construct a list of all the
Handlers
that could handle all the channels (based on their HandlerChannelFilter
property), ordered by
priority in some implementation-dependent way. If there are handlers
which could handle all the channels, one channel dispatch operation
SHOULD be created for all the channels. If there are not, one channel
dispatch operation SHOULD be created for each channel, each with
a list of channel handlers that could handle that channel.
If no handler at all can handle a channel, the channel dispatcher
SHOULD terminate that channel instead of creating a channel dispatcher
for it. It is RECOMMENDED that the channel dispatcher closes
the channels using Channel.Interface.Destroyable.Destroy
if supported, or Channel.Close
otherwise. As a special case, the channel dispatcher SHOULD NOT close
ContactList
channels, and if Close fails, the channel dispatcher SHOULD ignore
that channel.
ContactList channels are strange. We hope to replace them with
something better, such as an interface on the Connection, in a
future version of this specification.
When listing channel handlers, priority SHOULD be given to
channel handlers that are already handling channels from the same
bundle.
If a handler with BypassApproval
= True could handle all of the channels in the dispatch
operation, then the channel dispatcher SHOULD call HandleChannels
on that handler, and (assuming the call succeeds) emit
Finished and stop processing those
channels without involving any approvers.
Some channel types can be picked up "quietly" by an existing
channel handler. If a Text
channel is added to an existing bundle containing a StreamedMedia
channel, there shouldn't be
any approvers, flashing icons or notification bubbles, if the
the UI for the StreamedMedia channel can just add a text box
and display the message.
Otherwise, the channel dispatcher SHOULD send the channel dispatch
operation to all relevant approvers (in parallel) and wait for an
approver to claim the channels or request that they are handled.
See
AddDispatchOperation
for more details on this.
Finally, if the approver requested it, the channel dispatcher SHOULD
send the channels to a handler. | 62598fa263d6d428bbee262f |
class Tag(models.Model): <NEW_LINE> <INDENT> hash_id = models.CharField( db_index=True, max_length=32, blank=False, null=False, unique=True ) <NEW_LINE> added_by = models.ForeignKey(User, editable=False) <NEW_LINE> added_on = models.DateTimeField( db_index=True, auto_now_add=True, editable=False ) <NEW_LINE> objects = TagManager() <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return 'Tag ' + str(self.id) <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self = tag_presave(self) <NEW_LINE> super(Tag, self).save() <NEW_LINE> <DEDENT> def get_localization(self, lang): <NEW_LINE> <INDENT> return LocalizedTag.objects.get(tag=self, lang=lang) <NEW_LINE> <DEDENT> def get_all_localizations(self): <NEW_LINE> <INDENT> return LocalizedTag.objects.filter(tag=self) <NEW_LINE> <DEDENT> def merge(self, tag): <NEW_LINE> <INDENT> sentags = SentenceTag.objects.filter(tag=tag) <NEW_LINE> sentags.update(tag=self) <NEW_LINE> loctags = LocalizedTag.objects.filter(tag=tag) <NEW_LINE> loctags.update(tag=self) <NEW_LINE> tag.delete() <NEW_LINE> <DEDENT> def translate(self, text, lang): <NEW_LINE> <INDENT> LocalizedTag.objects.create(tag=self, text=text, lang=lang) <NEW_LINE> <DEDENT> @classproperty <NEW_LINE> @classmethod <NEW_LINE> def search(cls): <NEW_LINE> <INDENT> return SearchQuerySet().models(LocalizedTag) | This is probably a pretty desperate attempt at trying not to replicate
the sentences table and api. This table anchors all tags that are directly
related, allowing for localizations to be accessed from a common point.
This design allows for fast access and normalization but quickly
complicates things when users don't realize that a tag could've been
translated and not added. Merging the two nodes would require handling
a number of edge cases. All involving remapping the tag links from one
node to another and removing one of them. | 62598fa24428ac0f6e6583a8 |
class HcmdCoreError(Exception): <NEW_LINE> <INDENT> fmt = 'An unspecified error occurred' <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> msg = self.fmt.format(**kwargs) <NEW_LINE> Exception.__init__(self, msg) <NEW_LINE> self.kwargs = kwargs | The base exception class for obscmd exceptions.
:ivar msg: The descriptive message associated with the error. | 62598fa292d797404e388aa4 |
class RoomDetail(DetailView): <NEW_LINE> <INDENT> model = models.Room | 방 조회 정의 | 62598fa21f5feb6acb162aa0 |
class DiskEncryptionSettings(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'disk_encryption_key': {'key': 'diskEncryptionKey', 'type': 'KeyVaultSecretReference'}, 'key_encryption_key': {'key': 'keyEncryptionKey', 'type': 'KeyVaultKeyReference'}, 'enabled': {'key': 'enabled', 'type': 'bool'}, } <NEW_LINE> def __init__( self, *, disk_encryption_key: Optional["KeyVaultSecretReference"] = None, key_encryption_key: Optional["KeyVaultKeyReference"] = None, enabled: Optional[bool] = None, **kwargs ): <NEW_LINE> <INDENT> super(DiskEncryptionSettings, self).__init__(**kwargs) <NEW_LINE> self.disk_encryption_key = disk_encryption_key <NEW_LINE> self.key_encryption_key = key_encryption_key <NEW_LINE> self.enabled = enabled | Describes a Encryption Settings for a Disk.
:ivar disk_encryption_key: Specifies the location of the disk encryption key, which is a Key
Vault Secret.
:vartype disk_encryption_key: ~azure.mgmt.compute.v2018_06_01.models.KeyVaultSecretReference
:ivar key_encryption_key: Specifies the location of the key encryption key in Key Vault.
:vartype key_encryption_key: ~azure.mgmt.compute.v2018_06_01.models.KeyVaultKeyReference
:ivar enabled: Specifies whether disk encryption should be enabled on the virtual machine.
:vartype enabled: bool | 62598fa297e22403b383ad89 |
class BadDate(SimpleGenerator): <NEW_LINE> <INDENT> _strings = [ '1/1/1', '0/0/0', '0-0-0', '00-00-00', '-1/-1/-1', 'XX/XX/XX', '-1-1-1-1-1-1-1-1-1-1-1-', 'Jun 39th 1999', 'June -1th 1999', '2000', '1997', '0000', '0001', '9999', '0000-00', '0000-01', '0000-99', '0000-13', '0001-00', '0001-01', '0001-99', '0001-13', '9999-00', '9999-01', '9999-99', '9999-13', '0000-00-00', '0000-01-00', '0000-99-00', '0000-13-00', '0001-00-00', '0001-01-00', '0001-99-00', '0001-13-00', '9999-00-00', '9999-01-00', '9999-99-00', '9999-13-00', '0000-00-01', '0000-01-01', '0000-99-01', '0000-13-01', '0001-00-01', '0001-01-01', '0001-99-01', '0001-13-01', '9999-00-01', '9999-01-01', '9999-99-01', '9999-13-01', '0000-00-99', '0000-01-99', '0000-99-99', '0000-13-99', '0001-00-99', '0001-01-99', '0001-99-99', '0001-13-99', '9999-00-99', '9999-01-99', '9999-99-99', '9999-13-99', ] <NEW_LINE> def __init__(self, group=None): <NEW_LINE> <INDENT> SimpleGenerator.__init__(self, group) <NEW_LINE> self._generator = List(None, self._strings) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def unittest(): <NEW_LINE> <INDENT> g = BadDate(None) <NEW_LINE> if g.getValue() != '1/1/1': <NEW_LINE> <INDENT> raise Exception("BadDate unittest failed #1") <NEW_LINE> <DEDENT> g.next() <NEW_LINE> if g.getValue() != '0/0/0': <NEW_LINE> <INDENT> raise Exception("BadDate unittest failed #2") <NEW_LINE> <DEDENT> print("BadDate okay") | [BETA] Generates a lot of funky date's. This Generator is still missing
a lot of test cases.
- Invalid month, year, day
- Mixed up stuff
- Crazy odd date formats | 62598fa256ac1b37e6302069 |
class AllyBinarySensor(AllyDeviceEntity, BinarySensorEntity): <NEW_LINE> <INDENT> def __init__(self, ally, name, device_id, device_type): <NEW_LINE> <INDENT> self._ally = ally <NEW_LINE> self._device = ally.devices[device_id] <NEW_LINE> self._device_id = device_id <NEW_LINE> self._type = device_type <NEW_LINE> super().__init__(name, device_id, device_type) <NEW_LINE> _LOGGER.debug( "Device_id: %s --- Device: %s", self._device_id, self._device ) <NEW_LINE> self._type = device_type <NEW_LINE> self._unique_id = f"{device_type}_{device_id}_ally" <NEW_LINE> self._state = None <NEW_LINE> if self._type == "link": <NEW_LINE> <INDENT> self._state = self._device['online'] <NEW_LINE> <DEDENT> elif self._type == "open window": <NEW_LINE> <INDENT> self._state = bool(self._device['window_open']) <NEW_LINE> <DEDENT> elif self._type == "child lock": <NEW_LINE> <INDENT> self._state = bool(self._device['child_lock']) <NEW_LINE> <DEDENT> elif self._type == "connectivity": <NEW_LINE> <INDENT> self._state = bool(self._device['online']) <NEW_LINE> <DEDENT> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_ALLY_UPDATE_RECEIVED, self._async_update_callback, ) ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def unique_id(self): <NEW_LINE> <INDENT> return self._unique_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return f"{self._name} {self._type}" <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self): <NEW_LINE> <INDENT> if self._type == "link": <NEW_LINE> <INDENT> return DEVICE_CLASS_CONNECTIVITY <NEW_LINE> <DEDENT> elif self._type == "open window": <NEW_LINE> <INDENT> return DEVICE_CLASS_WINDOW <NEW_LINE> <DEDENT> elif self._type == "child_lock": <NEW_LINE> <INDENT> return DEVICE_CLASS_LOCK <NEW_LINE> <DEDENT> elif self._type == "connectivity": <NEW_LINE> <INDENT> return DEVICE_CLASS_CONNECTIVITY <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _async_update_callback(self): <NEW_LINE> <INDENT> self._async_update_data() <NEW_LINE> self.async_write_ha_state() <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _async_update_data(self): <NEW_LINE> <INDENT> _LOGGER.debug( "Loading new binary_sensor data for device %s", self._device_id ) <NEW_LINE> self._device = self._ally.devices[self._device_id] <NEW_LINE> if self._type == "link": <NEW_LINE> <INDENT> self._state = self._device['online'] <NEW_LINE> <DEDENT> elif self._type == "open window": <NEW_LINE> <INDENT> self._state = bool(self._device['window_open']) <NEW_LINE> <DEDENT> elif self._type == "child lock": <NEW_LINE> <INDENT> self._state = bool(self._device['child_lock']) <NEW_LINE> <DEDENT> elif self._type == "connectivity": <NEW_LINE> <INDENT> self._state = bool(self._device['online']) | Representation of an Ally binary_sensor. | 62598fa299cbb53fe6830d51 |
class Entry(Base): <NEW_LINE> <INDENT> __tablename__ = 'entries' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> title = Column(Unicode) <NEW_LINE> body = Column(Unicode) <NEW_LINE> creation_date = Column(DateTime) <NEW_LINE> def __init__(self, creation_date=None, *args, **kwargs): <NEW_LINE> <INDENT> super(Entry, self).__init__(*args, **kwargs) <NEW_LINE> if creation_date: <NEW_LINE> <INDENT> self.creation_date = tz('US/Pacific').localize(creation_date) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.creation_date = datetime.now(utc) <NEW_LINE> <DEDENT> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> if sys.version_info.major == 3: <NEW_LINE> <INDENT> local_creation_date = self.creation_date.astimezone(tz('US/Pacific')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> local_creation_date = self.creation_date <NEW_LINE> <DEDENT> return { 'id': self.id, 'title': self.title, 'body': self.body, 'creation_date': local_creation_date.strftime('%A, %B %d, %Y, %I:%M %p') } <NEW_LINE> <DEDENT> def to_html_dict(self): <NEW_LINE> <INDENT> attr = self.to_dict() <NEW_LINE> attr['body'] = markdown(attr['body']) <NEW_LINE> return attr | Create a table for journal entries. | 62598fa2851cf427c66b8146 |
class DenonCommand(object): <NEW_LINE> <INDENT> def __init__(self, host, port, timeout=1.0, max_bytes=1024): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.timeout = timeout <NEW_LINE> self.max_bytes = max_bytes <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> self.sock.connect((self.host, self.port)) <NEW_LINE> self.reciever = _Reciever(self.sock, self.timeout, self.max_bytes) <NEW_LINE> return self <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise DenonAvrConnectException('%s (%s:%s)' % (e[1], self.host, self.port)) <NEW_LINE> <DEDENT> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> self.sock.close() <NEW_LINE> if not isinstance(value, Exception): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> raise DenonAvrException(value) <NEW_LINE> <DEDENT> def send(self, content): <NEW_LINE> <INDENT> self.sock.send(content + '\r') <NEW_LINE> <DEDENT> def recieve(self): <NEW_LINE> <INDENT> return self.reciever.read() <NEW_LINE> <DEDENT> def recieve_string(self, *args, **kwargs): <NEW_LINE> <INDENT> r = self.recieve(*args, **kwargs) <NEW_LINE> return ''.join(r) | Run a single command.
Example:
with DenonCommand(<host>) as d:
d.send(<command>)
print(d.recieve()) | 62598fa2a8ecb0332587108c |
class BaseWorker(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.available_port = None <NEW_LINE> self.reconnecting = False <NEW_LINE> self.green_light = True <NEW_LINE> self.last_error = None <NEW_LINE> self.process = None <NEW_LINE> self.client = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def port(self): <NEW_LINE> <INDENT> raise RuntimeError('This method must be reimplemented') <NEW_LINE> <DEDENT> @property <NEW_LINE> def hostaddr(self): <NEW_LINE> <INDENT> return 'localhost' <NEW_LINE> <DEDENT> def start_json_server(self): <NEW_LINE> <INDENT> if self.server_is_active(): <NEW_LINE> <INDENT> if self.server_is_healthy(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.sanitize_server() <NEW_LINE> return <NEW_LINE> <DEDENT> logger.info('Starting anaconda JSON server...') <NEW_LINE> self.build_server() <NEW_LINE> <DEDENT> def server_is_active(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> s.settimeout(0.05) <NEW_LINE> s.connect((self.hostaddr, self.available_port)) <NEW_LINE> s.close() <NEW_LINE> <DEDENT> except socket.timeout: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> except socket.error as error: <NEW_LINE> <INDENT> if error.errno == errno.ECONNREFUSED: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error( 'Unexpected error in `server_is_active`: {}'.format(error) ) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def server_is_healthy(self): <NEW_LINE> <INDENT> if get_settings(active_view(), 'jsonserver_debug', False) is True: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if self.process.poll() is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> s.settimeout(0.5) <NEW_LINE> s.connect((self.hostname, self.available_port)) <NEW_LINE> s.sendall(bytes('{"method": "check"}', 'utf8')) <NEW_LINE> data = sublime.value_decode(s.recv(1024)) <NEW_LINE> s.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return data == b'Ok' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.error( 'Something is using the port {} in your system'.format( self.available_port ) ) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> @auto_project_switch <NEW_LINE> def _execute(self, callback, **data): <NEW_LINE> <INDENT> self.client.send_command(callback, **data) | Base class for different worker interfaces
| 62598fa2fbf16365ca793f39 |
class TriggerSpec(Model): <NEW_LINE> <INDENT> def __init__(self, name=None, description=None, state=None, superceded_by=None, parameters=None): <NEW_LINE> <INDENT> self.swagger_types = { 'name': str, 'description': str, 'state': str, 'superceded_by': str, 'parameters': List[TriggerParamSpec] } <NEW_LINE> self.attribute_map = { 'name': 'name', 'description': 'description', 'state': 'state', 'superceded_by': 'superceded_by', 'parameters': 'parameters' } <NEW_LINE> self._name = name <NEW_LINE> self._description = description <NEW_LINE> self._state = state <NEW_LINE> self._superceded_by = superceded_by <NEW_LINE> self._parameters = parameters <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt): <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def description(self): <NEW_LINE> <INDENT> return self._description <NEW_LINE> <DEDENT> @description.setter <NEW_LINE> def description(self, description): <NEW_LINE> <INDENT> self._description = description <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @state.setter <NEW_LINE> def state(self, state): <NEW_LINE> <INDENT> allowed_values = ["active", "deprecated", "eol"] <NEW_LINE> if state not in allowed_values: <NEW_LINE> <INDENT> raise ValueError( "Invalid value for `state` ({0}), must be one of {1}" .format(state, allowed_values) ) <NEW_LINE> <DEDENT> self._state = state <NEW_LINE> <DEDENT> @property <NEW_LINE> def superceded_by(self): <NEW_LINE> <INDENT> return self._superceded_by <NEW_LINE> <DEDENT> @superceded_by.setter <NEW_LINE> def superceded_by(self, superceded_by): <NEW_LINE> <INDENT> self._superceded_by = superceded_by <NEW_LINE> <DEDENT> @property <NEW_LINE> def parameters(self): <NEW_LINE> <INDENT> return self._parameters <NEW_LINE> <DEDENT> @parameters.setter <NEW_LINE> def parameters(self, parameters): <NEW_LINE> <INDENT> self._parameters = parameters | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 62598fa2baa26c4b54d4f12e |
class IPv6AccountIdentiferTestCase(test.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(IPv6AccountIdentiferTestCase, self).setUp() <NEW_LINE> self.flags(ipv6_backend='account_identifier') <NEW_LINE> ipv6.reset_backend() <NEW_LINE> <DEDENT> def test_to_global(self): <NEW_LINE> <INDENT> addr = ipv6.to_global('2001:db8::', '02:16:3e:33:44:55', 'test') <NEW_LINE> self.assertEquals(addr, '2001:db8::a94a:8fe5:ff33:4455') <NEW_LINE> <DEDENT> def test_to_mac(self): <NEW_LINE> <INDENT> mac = ipv6.to_mac('2001:db8::a94a:8fe5:ff33:4455') <NEW_LINE> self.assertEquals(mac, '02:16:3e:33:44:55') <NEW_LINE> <DEDENT> def test_to_global_with_bad_mac(self): <NEW_LINE> <INDENT> bad_mac = '02:16:3e:33:44:5X' <NEW_LINE> self.assertRaises(TypeError, ipv6.to_global, '2001:db8::', bad_mac, 'test') <NEW_LINE> <DEDENT> def test_to_global_with_bad_prefix(self): <NEW_LINE> <INDENT> bad_prefix = '78' <NEW_LINE> self.assertRaises(TypeError, ipv6.to_global, bad_prefix, '2001:db8::a94a:8fe5:ff33:4455', 'test') <NEW_LINE> <DEDENT> def test_to_global_with_bad_project(self): <NEW_LINE> <INDENT> bad_project = 'non-existent-project-name' <NEW_LINE> self.assertRaises(TypeError, ipv6.to_global, '2001:db8::', '2001:db8::a94a:8fe5:ff33:4455', bad_project) | Unit tests for IPv6 account_identifier backend operations. | 62598fa2a8370b77170f0259 |
class AuditLog(CritsDocument, CritsSchemaDocument, Document): <NEW_LINE> <INDENT> meta = { "allow_inheritance": False, "crits_type": "AuditLog", "collection": settings.COL_AUDIT_LOG, "latest_schema_version": 1, "schema_doc": { 'value': 'Value of the audit log entry', 'user': 'User the entry is about.', 'date': 'Date of the entry', 'type': 'Type of the audit entry', 'method': 'Method of the audit entry' } } <NEW_LINE> value = StringField() <NEW_LINE> user = StringField() <NEW_LINE> date = CritsDateTimeField(default=datetime.datetime.now) <NEW_LINE> target_type = StringField(db_field='type') <NEW_LINE> target_id = ObjectIdField() <NEW_LINE> method = StringField() | Audit Log Class | 62598fa2eab8aa0e5d30bc06 |
class PackageManager(Enum): <NEW_LINE> <INDENT> BREW = auto() <NEW_LINE> YUM = auto() <NEW_LINE> APT = auto() <NEW_LINE> @staticmethod <NEW_LINE> def from_label(label): <NEW_LINE> <INDENT> if label is None: <NEW_LINE> <INDENT> raise KeyError("Enum: No package manager was passed in") <NEW_LINE> <DEDENT> return PackageManager[label.upper()] | Represents a system package manager | 62598fa2d6c5a102081e1fc5 |
class SOAPException(Exception): <NEW_LINE> <INDENT> pass | SOAP exception | 62598fa276e4537e8c3ef42b |
class CodecError(TException): <NEW_LINE> <INDENT> thrift_spec = ( None, (1, TType.STRING, 'message', None, None, ), ) <NEW_LINE> def __init__(self, message=None,): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.message = iprot.readString(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('CodecError') <NEW_LINE> if self.message is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('message', TType.STRING, 1) <NEW_LINE> oprot.writeString(self.message) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- message | 62598fa25f7d997b871f931f |
class ContainedOnlyBy(Overlaps): <NEW_LINE> <INDENT> def matches(self, value): <NEW_LINE> <INDENT> raise NotImplementedError() | Check if an IP address is inside a network and no other network
is in between | 62598fa24f6381625f1993fc |
class SearchResponse(colander.MappingSchema): <NEW_LINE> <INDENT> success = colander.SchemaNode(colander.Boolean(), missing=colander.drop) <NEW_LINE> error = colander.SchemaNode(colander.Boolean(), missing=colander.drop) <NEW_LINE> results = MultiRants() | :class:`colander.MappingSchema` for SearchResponse objects. | 62598fa299cbb53fe6830d52 |
class VolumeDetails(Volume): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(VolumeDetails, self).__init__() <NEW_LINE> self.axrn = None <NEW_LINE> self.name = None <NEW_LINE> self.details = {} <NEW_LINE> fields = { "name": None, "axrn": None, "details": None } <NEW_LINE> self.set_fields(fields) | This class has additional details passed between argo
microservices that are not part of yaml specification | 62598fa230dc7b766599f6cc |
class ChannelEndState(object): <NEW_LINE> <INDENT> def __init__(self, participant_address, participant_balance, get_block_number): <NEW_LINE> <INDENT> if not isinstance(participant_balance, (int, long)): <NEW_LINE> <INDENT> raise ValueError('participant_balance must be an integer.') <NEW_LINE> <DEDENT> self.contract_balance = participant_balance <NEW_LINE> self.address = participant_address <NEW_LINE> self.transferred_amount = 0 <NEW_LINE> if isinstance(get_block_number, int): <NEW_LINE> <INDENT> self.nonce = 1 * (get_block_number * (2 ** 32)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nonce = 1 * (get_block_number() * (2 ** 32)) <NEW_LINE> <DEDENT> self.balance_proof = BalanceProof() <NEW_LINE> <DEDENT> def locked(self): <NEW_LINE> <INDENT> return self.balance_proof.locked() <NEW_LINE> <DEDENT> def update_contract_balance(self, contract_balance): <NEW_LINE> <INDENT> if contract_balance < self.contract_balance: <NEW_LINE> <INDENT> log.error('contract_balance cannot decrease') <NEW_LINE> raise ValueError('contract_balance cannot decrease') <NEW_LINE> <DEDENT> self.contract_balance = contract_balance <NEW_LINE> <DEDENT> def balance(self, other): <NEW_LINE> <INDENT> return self.contract_balance - self.transferred_amount + other.transferred_amount <NEW_LINE> <DEDENT> def distributable(self, other): <NEW_LINE> <INDENT> return self.balance(other) - other.locked() <NEW_LINE> <DEDENT> def compute_merkleroot_with(self, include): <NEW_LINE> <INDENT> merkletree = self.balance_proof.unclaimed_merkletree() <NEW_LINE> merkletree.append(sha3(include.as_bytes)) <NEW_LINE> return merkleroot(merkletree) <NEW_LINE> <DEDENT> def register_locked_transfer(self, locked_transfer): <NEW_LINE> <INDENT> self.balance_proof.register_locked_transfer(locked_transfer) <NEW_LINE> <DEDENT> def register_direct_transfer(self, direct_transfer): <NEW_LINE> <INDENT> self.balance_proof.register_direct_transfer(direct_transfer) <NEW_LINE> <DEDENT> def register_secret(self, secret): <NEW_LINE> <INDENT> self.balance_proof.register_secret(secret) <NEW_LINE> <DEDENT> def release_lock(self, partner, secret): <NEW_LINE> <INDENT> lock = self.balance_proof.release_lock_by_secret(secret) <NEW_LINE> amount = lock.amount <NEW_LINE> partner.transferred_amount += amount | Tracks the state of one of the participants in a channel. | 62598fa20a50d4780f705259 |
class ModifyDDoSLevelResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Id = None <NEW_LINE> self.DDoSLevel = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Id = params.get("Id") <NEW_LINE> self.DDoSLevel = params.get("DDoSLevel") <NEW_LINE> self.RequestId = params.get("RequestId") | ModifyDDoSLevel response structure.
| 62598fa28e7ae83300ee8f1f |
class tabs(WordprocessingMLElement): <NEW_LINE> <INDENT> pass | This element specifies a sequence of custom tab stops which shall be used for any tab characters in the current paragraph.
If this element is omitted on a given paragraph, its value is determined by the setting previously set at any level of
the style hierarchy (i.e. that previous setting remains unchanged). If this setting is never specified in the style
hierarchy, then no custom tab stops shall be used for this paragraph.
As well, this property is additive - tab stops at each level in the style hierarchy are added to each other to determine
the full set of tab stops for the paragraph. A hanging indent specified via the hanging attribute on the ind element
shall also always implicitly create a custom tab stop at its location.
Parent element: pPr
Child element: tab | 62598fa2dd821e528d6d8db3 |
class DummyStateStore(object): <NEW_LINE> <INDENT> def get_state(self): <NEW_LINE> <INDENT> return defer.succeed(None) <NEW_LINE> <DEDENT> def save_state(self, state): <NEW_LINE> <INDENT> return defer.succeed(None) | Fake state store that doesn't actually store the state. | 62598fa2498bea3a75a579a1 |
@attr.s(repr=False, cmp=False) <NEW_LINE> class BooleanElement(IntegerElement): <NEW_LINE> <INDENT> value = attr.ib(default=False, type=bool, converter=bool) <NEW_LINE> @classmethod <NEW_LINE> def read(cls, fp, **kwargs): <NEW_LINE> <INDENT> return cls(read_fmt('?3x', fp)[0]) <NEW_LINE> <DEDENT> def write(self, fp, **kwargs): <NEW_LINE> <INDENT> return write_fmt(fp, '?3x', self.value) | Single bool value element that has a `value` attribute.
Use with `@attr.s(repr=False)` decorator. | 62598fa2d268445f26639ac2 |
class Actor(Base): <NEW_LINE> <INDENT> __tablename__ = 'actor' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> name = Column(Text) <NEW_LINE> wiki_page = Column(Text, unique=True) <NEW_LINE> age = Column(Integer) <NEW_LINE> total_gross = Column(Float) <NEW_LINE> movies = relationship("Edge", back_populates="actor", cascade="all, delete-orphan") <NEW_LINE> def __init__(self, item=None): <NEW_LINE> <INDENT> super(Actor, self).__init__() <NEW_LINE> self.update(item) <NEW_LINE> <DEDENT> def update(self, item): <NEW_LINE> <INDENT> if not (isinstance(item, ActorItem) or isinstance(item, dict)): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.name = item.get("name", self.name) <NEW_LINE> self.age = item.get("age", self.age) <NEW_LINE> self.total_gross = item.get("total_gross", 0 if self.total_gross is None else self.total_gross) <NEW_LINE> self.wiki_page = get_wiki_page(item.get("wiki_page", self.wiki_page)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<{} "{}">'.format(self.__class__.__name__, self.name) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return { "id": self.id, "name": self.name, "wiki_page": self.wiki_page, "age": self.age, "total_gross": self.total_gross, "movies": [edge.movie.name for edge in self.movies if edge.movie.name is not None], } | The represent the actor nodes in the graph
(SQLAlchemy model: actor) | 62598fa22ae34c7f260aaf60 |
class ExceptionHandler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass | Used to handle the exceptions during the convertion progress | 62598fa2ac7a0e7691f7238a |
class CustomItemModel(BaseItemModel): <NEW_LINE> <INDENT> def __init__(self, columns, parent): <NEW_LINE> <INDENT> self._row_data = [] <NEW_LINE> self._sort_column1 = 0 <NEW_LINE> self._sort_column2 = 0 <NEW_LINE> self._sort_order = QtCore.Qt.AscendingOrder <NEW_LINE> super(CustomItemModel, self).__init__(columns, parent) <NEW_LINE> <DEDENT> def _set_row_data(self, row_data, removal_rows=None, addition_rows=None): <NEW_LINE> <INDENT> self._row_data = row_data <NEW_LINE> if addition_rows: <NEW_LINE> <INDENT> self.beginInsertRows(QtCore.QModelIndex(), addition_rows[0], addition_rows[1]) <NEW_LINE> self.endInsertRows() <NEW_LINE> <DEDENT> elif removal_rows: <NEW_LINE> <INDENT> self.beginRemoveRows(QtCore.QModelIndex(), removal_rows[0], removal_rows[1]) <NEW_LINE> self.endRemoveRows() <NEW_LINE> <DEDENT> <DEDENT> def _get_row_data(self): <NEW_LINE> <INDENT> return self._row_data <NEW_LINE> <DEDENT> def _index_cell_value(self, column, value): <NEW_LINE> <INDENT> for i, row in enumerate(self._row_data): <NEW_LINE> <INDENT> if row[column] == value: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> <DEDENT> return -1 <NEW_LINE> <DEDENT> def _lookup_cell_value(self, row, column): <NEW_LINE> <INDENT> return self._row_data[row][column] <NEW_LINE> <DEDENT> def _get_sort_column1(self): <NEW_LINE> <INDENT> return self._sort_column1 <NEW_LINE> <DEDENT> def _get_sort_column2(self): <NEW_LINE> <INDENT> return self._sort_column2 <NEW_LINE> <DEDENT> def rowCount(self, parent=None): <NEW_LINE> <INDENT> return len(self._row_data) <NEW_LINE> <DEDENT> def _sort_list(self, l: List) -> None: <NEW_LINE> <INDENT> ix1 = self._sort_column1 <NEW_LINE> ix2 = self._sort_column2 <NEW_LINE> if self._sort_order == QtCore.Qt.AscendingOrder: <NEW_LINE> <INDENT> l.sort(key=lambda v: (v[ix1], v[ix2])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> l.sort(key=lambda v: (v[ix1], v[ix2]), reverse=True) <NEW_LINE> <DEDENT> <DEDENT> def sort(self, column, sort_order): <NEW_LINE> <INDENT> if self._sort_column1 == column and self._sort_order == sort_order: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._sort_column1 = column <NEW_LINE> self._sort_order = sort_order <NEW_LINE> if len(self._row_data): <NEW_LINE> <INDENT> self.layoutAboutToBeChanged.emit() <NEW_LINE> self._sort_list(self._row_data) <NEW_LINE> self.layoutChanged.emit() | The main reason for this subclass is to give custom column alignment. | 62598fa2656771135c489503 |
@format_docstring(get_user_info_request, response_example=get_devices_response, post_request_example=post_devices_request, post_response_example=post_devices_response) <NEW_LINE> class DeviceList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated,IsOwnerOrSuperUser) <NEW_LINE> from .models import Device <NEW_LINE> queryset = Device.objects.all() <NEW_LINE> serializer_class = DeviceSerializer <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.is_valid(raise_exception=True) <NEW_LINE> serializer.save() <NEW_LINE> return serializer <NEW_LINE> <DEDENT> def is_valid_requestbody(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> self.queryset = self.queryset.filter(user=request.user) <NEW_LINE> return self.list(request, *args, **kwargs) <NEW_LINE> <DEDENT> def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if not self.is_valid_requestbody(): <NEW_LINE> <INDENT> return Response({'detail': "Unexpected arguments", 'args': ['deviceType']}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> data = request.data.copy() <NEW_LINE> data['user'] = request.user.id <NEW_LINE> serializer = self.serializer_class(data=data) <NEW_LINE> serializer = self.perform_create(serializer) <NEW_LINE> headers = self.get_success_headers(serializer.data) <NEW_LINE> return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers) | Device List
가능 메소드 : [ GET, Post ]
[ GET ]
Request: {}
Response: {response_example}
[ POST ]
Request: {post_request_example}
Response: {post_response_example} | 62598fa2b7558d58954634ad |
class ImageBuilder(AWSObject): <NEW_LINE> <INDENT> resource_type = "AWS::AppStream::ImageBuilder" <NEW_LINE> props: PropsDictType = { "AccessEndpoints": ([AccessEndpoint], False), "AppstreamAgentVersion": (str, False), "Description": (str, False), "DisplayName": (str, False), "DomainJoinInfo": (DomainJoinInfo, False), "EnableDefaultInternetAccess": (boolean, False), "IamRoleArn": (str, False), "ImageArn": (str, False), "ImageName": (str, False), "InstanceType": (str, True), "Name": (str, True), "Tags": (validate_tags_or_list, False), "VpcConfig": (VpcConfig, False), } | `ImageBuilder <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appstream-imagebuilder.html>`__ | 62598fa2627d3e7fe0e06d2b |
class AzureSQLConnectionStringCredentialPatch(DataSourceCredentialPatch): <NEW_LINE> <INDENT> _validation = { 'data_source_credential_type': {'required': True}, } <NEW_LINE> _attribute_map = { 'data_source_credential_type': {'key': 'dataSourceCredentialType', 'type': 'str'}, 'data_source_credential_name': {'key': 'dataSourceCredentialName', 'type': 'str'}, 'data_source_credential_description': {'key': 'dataSourceCredentialDescription', 'type': 'str'}, 'parameters': {'key': 'parameters', 'type': 'AzureSQLConnectionStringParamPatch'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AzureSQLConnectionStringCredentialPatch, self).__init__(**kwargs) <NEW_LINE> self.data_source_credential_type = 'AzureSQLConnectionString' <NEW_LINE> self.parameters = kwargs.get('parameters', None) | AzureSQLConnectionStringCredentialPatch.
All required parameters must be populated in order to send to Azure.
:param data_source_credential_type: Required. Type of data source credential.Constant filled by
server. Possible values include: "AzureSQLConnectionString", "DataLakeGen2SharedKey",
"ServicePrincipal", "ServicePrincipalInKV".
:type data_source_credential_type: str or
~azure.ai.metricsadvisor.models.DataSourceCredentialType
:param data_source_credential_name: Name of data source credential.
:type data_source_credential_name: str
:param data_source_credential_description: Description of data source credential.
:type data_source_credential_description: str
:param parameters:
:type parameters: ~azure.ai.metricsadvisor.models.AzureSQLConnectionStringParamPatch | 62598fa2442bda511e95c2da |
@dataclass <NEW_LINE> class RoomContextError(_ErrorWithRoomId): <NEW_LINE> <INDENT> pass | Response representing a unsuccessful room context request. | 62598fa2b7558d58954634ae |
class _ParseExampleDataset(dataset_ops.UnaryDataset): <NEW_LINE> <INDENT> def __init__(self, input_dataset, features, num_parallel_calls): <NEW_LINE> <INDENT> self._input_dataset = input_dataset <NEW_LINE> if not input_dataset._element_structure.is_compatible_with( structure.TensorStructure(dtypes.string, [None])): <NEW_LINE> <INDENT> raise TypeError("Input dataset should be a dataset of vectors of strings") <NEW_LINE> <DEDENT> self._num_parallel_calls = num_parallel_calls <NEW_LINE> self._features = parsing_ops._prepend_none_dimension(features) <NEW_LINE> (sparse_keys, sparse_types, dense_keys, dense_types, dense_defaults, dense_shapes) = parsing_ops._features_to_raw_params( self._features, [ parsing_ops.VarLenFeature, parsing_ops.SparseFeature, parsing_ops.FixedLenFeature, parsing_ops.FixedLenSequenceFeature ]) <NEW_LINE> (_, dense_defaults_vec, sparse_keys, sparse_types, dense_keys, dense_shapes, dense_shape_as_shape) = parsing_ops._process_raw_parameters( None, dense_defaults, sparse_keys, sparse_types, dense_keys, dense_types, dense_shapes) <NEW_LINE> self._sparse_keys = sparse_keys <NEW_LINE> self._sparse_types = sparse_types <NEW_LINE> self._dense_keys = dense_keys <NEW_LINE> self._dense_defaults = dense_defaults_vec <NEW_LINE> self._dense_shapes = dense_shapes <NEW_LINE> self._dense_types = dense_types <NEW_LINE> input_dataset_shape = dataset_ops.get_legacy_output_shapes( self._input_dataset) <NEW_LINE> dense_output_shapes = [input_dataset_shape.concatenate(shape) for shape in dense_shape_as_shape] <NEW_LINE> sparse_output_shapes = [input_dataset_shape.concatenate([None]) for _ in range(len(sparse_keys))] <NEW_LINE> output_shapes = dict( zip(self._dense_keys + self._sparse_keys, dense_output_shapes + sparse_output_shapes)) <NEW_LINE> output_types = dict( zip(self._dense_keys + self._sparse_keys, self._dense_types + self._sparse_types)) <NEW_LINE> output_classes = dict( zip(self._dense_keys + self._sparse_keys, [ops.Tensor for _ in range(len(self._dense_defaults))] + [sparse_tensor.SparseTensor for _ in range(len(self._sparse_keys)) ])) <NEW_LINE> self._structure = structure.convert_legacy_structure( output_types, output_shapes, output_classes) <NEW_LINE> variant_tensor = ( gen_experimental_dataset_ops.experimental_parse_example_dataset( self._input_dataset._variant_tensor, self._num_parallel_calls, self._dense_defaults, self._sparse_keys, self._dense_keys, self._sparse_types, self._dense_shapes, **dataset_ops.flat_structure(self))) <NEW_LINE> super(_ParseExampleDataset, self).__init__(input_dataset, variant_tensor) <NEW_LINE> <DEDENT> @property <NEW_LINE> def _element_structure(self): <NEW_LINE> <INDENT> return self._structure | A `Dataset` that parses `example` dataset into a `dict` dataset. | 62598fa207f4c71912baf2c3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.