code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class FundamentalSettingToggleMixin(ClassprefsTooltipMixin): <NEW_LINE> <INDENT> local_setting = None <NEW_LINE> def isChecked(self): <NEW_LINE> <INDENT> return getattr(self.mode.locals, self.local_setting) <NEW_LINE> <DEDENT> def action(self, index=-1, multiplier=1): <NEW_LINE> <INDENT> value = self.isChecked() <NEW_LINE> setattr(self.mode.locals, self.local_setting, not value) <NEW_LINE> self.mode.applyDefaultSettings()
Abstract class used to implement a toggle button for a setting of FundamentalMode.
62598f9f8da39b475be02ffd
class PersonAdmin(TranslatableAdmin): <NEW_LINE> <INDENT> inlines = [LinkInline, ] <NEW_LINE> list_display = [ 'roman_first_name', 'roman_last_name', 'non_roman_first_name_link', 'non_roman_last_name', 'chosen_name', 'gender', 'title', 'role', 'phone', 'email', 'ordering', 'all_translations', ] <NEW_LINE> list_select_related = [] <NEW_LINE> def non_roman_first_name_link(self, obj): <NEW_LINE> <INDENT> return u'<a href="{0}/">{1}</a>'.format( obj.pk, obj.non_roman_first_name) <NEW_LINE> <DEDENT> non_roman_first_name_link.allow_tags = True <NEW_LINE> non_roman_first_name_link.short_description = "Non roman first name"
Admin for the ``Person`` model.
62598f9f3eb6a72ae038a45f
class ExtraFunction(Function): <NEW_LINE> <INDENT> def __init__(self, cname, prototype, pathfordoc): <NEW_LINE> <INDENT> self.name = cname <NEW_LINE> self.pyname = cname.split('era')[-1].lower() <NEW_LINE> self.filepath, self.filename = os.path.split(pathfordoc) <NEW_LINE> self.prototype = prototype.strip() <NEW_LINE> if prototype.endswith('{') or prototype.endswith(';'): <NEW_LINE> <INDENT> self.prototype = prototype[:-1].strip() <NEW_LINE> <DEDENT> incomment = False <NEW_LINE> lastcomment = None <NEW_LINE> with open(pathfordoc, 'r') as f: <NEW_LINE> <INDENT> for l in f: <NEW_LINE> <INDENT> if incomment: <NEW_LINE> <INDENT> if l.lstrip().startswith('*/'): <NEW_LINE> <INDENT> incomment = False <NEW_LINE> lastcomment = ''.join(lastcomment) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if l.startswith('**'): <NEW_LINE> <INDENT> l = l[2:] <NEW_LINE> <DEDENT> lastcomment.append(l) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if l.lstrip().startswith('/*'): <NEW_LINE> <INDENT> incomment = True <NEW_LINE> lastcomment = [] <NEW_LINE> <DEDENT> if l.startswith(self.prototype): <NEW_LINE> <INDENT> self.doc = lastcomment <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Did not find prototype {} in file ' '{}'.format(self.prototype, pathfordoc)) <NEW_LINE> <DEDENT> <DEDENT> self.args = [] <NEW_LINE> argset = re.search(fr"{self.name}\(([^)]+)?\)", self.prototype).group(1) <NEW_LINE> if argset is not None: <NEW_LINE> <INDENT> for arg in argset.split(', '): <NEW_LINE> <INDENT> self.args.append(Argument(arg, self.doc)) <NEW_LINE> <DEDENT> <DEDENT> self.ret = re.match(f"^(.*){self.name}", self.prototype).group(1).strip() <NEW_LINE> if self.ret != 'void': <NEW_LINE> <INDENT> self.args.append(Return(self.ret, self.doc)) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> r = super().__repr__() <NEW_LINE> if r.startswith('Function'): <NEW_LINE> <INDENT> r = 'Extra' + r <NEW_LINE> <DEDENT> return r
An "extra" function - e.g. one not following the SOFA/ERFA standard format. Parameters ---------- cname : str The name of the function in C prototype : str The prototype for the function (usually derived from the header) pathfordoc : str The path to a file that contains the prototype, with the documentation as a multiline string *before* it.
62598f9f4f6381625f1993cb
class BudgetFactory(factory.django.DjangoModelFactory): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Budget <NEW_LINE> <DEDENT> user = factory.SubFactory(UserFactory) <NEW_LINE> name = factory.Faker('word') <NEW_LINE> total_budget = 1000.0
Create budget instance for test purposes
62598f9f45492302aabfc2f4
class TestAbout(object): <NEW_LINE> <INDENT> def test_about_view(self): <NEW_LINE> <INDENT> request = DummyRequest(route='/about') <NEW_LINE> response = about_view(request) <NEW_LINE> assert response <NEW_LINE> assert response["page"] == "aboutpage" <NEW_LINE> assert response["title"] == "About"
This class tests the functionality of the About view.
62598f9f3617ad0b5ee05f6f
class PairedDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, initial_dataset, number_of_pairs, seed=0): <NEW_LINE> <INDENT> self.initial_dataset = initial_dataset <NEW_LINE> pairs_list = self.initial_dataset.pairs_list <NEW_LINE> np.random.seed(seed) <NEW_LINE> if pairs_list is None: <NEW_LINE> <INDENT> max_idx = min(number_of_pairs, len(initial_dataset)) <NEW_LINE> nx, ny = max_idx, max_idx <NEW_LINE> xy = np.mgrid[:nx, :ny].reshape(2, -1).T <NEW_LINE> number_of_pairs = min(xy.shape[0], number_of_pairs) <NEW_LINE> self.pairs = xy.take(np.random.choice(xy.shape[0], number_of_pairs, replace=False), axis=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> images = self.initial_dataset.images <NEW_LINE> name_to_index = {name: index for index, name in enumerate(images)} <NEW_LINE> pairs = pd.read_csv(pairs_list) <NEW_LINE> pairs = pairs[np.logical_and(pairs['source'].isin(images), pairs['driving'].isin(images))] <NEW_LINE> number_of_pairs = min(pairs.shape[0], number_of_pairs) <NEW_LINE> self.pairs = [] <NEW_LINE> self.start_frames = [] <NEW_LINE> for ind in range(number_of_pairs): <NEW_LINE> <INDENT> self.pairs.append( (name_to_index[pairs['driving'].iloc[ind]], name_to_index[pairs['source'].iloc[ind]])) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self.pairs) <NEW_LINE> <DEDENT> def __getitem__(self, idx): <NEW_LINE> <INDENT> pair = self.pairs[idx] <NEW_LINE> first = self.initial_dataset[pair[0]] <NEW_LINE> second = self.initial_dataset[pair[1]] <NEW_LINE> first = {'driving_' + key: value for key, value in first.items()} <NEW_LINE> second = {'source_' + key: value for key, value in second.items()} <NEW_LINE> return {**first, **second}
Dataset of pairs for transfer.
62598f9f435de62698e9bc12
class Index(FablePage): <NEW_LINE> <INDENT> def __init__(self, request, response): <NEW_LINE> <INDENT> FablePage.__init__(self, request, response, "index.html")
/index page
62598f9f236d856c2adc9349
class Person(Atom): <NEW_LINE> <INDENT> name = Str() <NEW_LINE> age = Range(low=0) <NEW_LINE> dog = Typed(Dog, ()) <NEW_LINE> def _observe_age(self, change: ChangeDict) -> None: <NEW_LINE> <INDENT> print("Age changed: {0}".format(change["value"])) <NEW_LINE> <DEDENT> @observe("name") <NEW_LINE> def any_name_i_want(self, change: ChangeDict) -> None: <NEW_LINE> <INDENT> print("Name changed: {0}".format(change["value"])) <NEW_LINE> <DEDENT> @observe("dog.name") <NEW_LINE> def another_random_name(self, change: ChangeDict) -> None: <NEW_LINE> <INDENT> print("Dog name changed: {0}".format(change["value"]))
A simple class representing a person object.
62598f9f8a43f66fc4bf1f9a
class PacketCaptureListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'value': {'key': 'value', 'type': '[PacketCaptureResult]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(PacketCaptureListResult, self).__init__(**kwargs) <NEW_LINE> self.value = kwargs.get('value', None)
List of packet capture sessions. :param value: Information about packet capture sessions. :type value: list[~azure.mgmt.network.v2018_12_01.models.PacketCaptureResult]
62598f9fb7558d589546344c
class Code(BaseCode): <NEW_LINE> <INDENT> _type = object.Type(u"Code") <NEW_LINE> __immutable_fields__ = ["_consts[*]", "_bytecode", "_stack_size", "_meta"] <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return Code._type <NEW_LINE> <DEDENT> def __init__(self, name, bytecode, consts, stack_size, debug_points, meta=nil): <NEW_LINE> <INDENT> BaseCode.__init__(self) <NEW_LINE> self._bytecode = bytecode <NEW_LINE> self._consts = consts <NEW_LINE> self._name = name <NEW_LINE> self._stack_size = stack_size <NEW_LINE> self._debug_points = debug_points <NEW_LINE> self._meta = meta <NEW_LINE> <DEDENT> def with_meta(self, meta): <NEW_LINE> <INDENT> return Code(self._name, self._bytecode, self._consts, self._stack_size, self._debug_points, meta) <NEW_LINE> <DEDENT> def get_debug_points(self): <NEW_LINE> <INDENT> return self._debug_points <NEW_LINE> <DEDENT> def _invoke(self, args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return interpret(self, args) <NEW_LINE> <DEDENT> except object.WrappedException as ex: <NEW_LINE> <INDENT> ex._ex._trace.append(object.PixieCodeInfo(self._name)) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> @elidable_promote() <NEW_LINE> def get_consts(self): <NEW_LINE> <INDENT> return self._consts <NEW_LINE> <DEDENT> @elidable_promote() <NEW_LINE> def get_bytecode(self): <NEW_LINE> <INDENT> return self._bytecode <NEW_LINE> <DEDENT> @elidable_promote() <NEW_LINE> def stack_size(self): <NEW_LINE> <INDENT> return self._stack_size <NEW_LINE> <DEDENT> @elidable_promote() <NEW_LINE> def get_base_code(self): <NEW_LINE> <INDENT> return self
Interpreted code block. Contains consts and
62598f9f4e4d562566372242
class Bars(object): <NEW_LINE> <INDENT> def __init__(self, latest_bars, single_bar=False): <NEW_LINE> <INDENT> self.length = len(latest_bars) <NEW_LINE> if single_bar: <NEW_LINE> <INDENT> self.datetime = latest_bars[-1][0] <NEW_LINE> self.open = latest_bars[-1][1] <NEW_LINE> self.high = latest_bars[-1][2] <NEW_LINE> self.low = latest_bars[-1][3] <NEW_LINE> self.close = latest_bars[-1][4] <NEW_LINE> self.volume = latest_bars[-1][5] <NEW_LINE> self.is_positive = True if self.close > self.open else False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.datetime = [i[0] for i in latest_bars] <NEW_LINE> self.open = [i[1] for i in latest_bars] <NEW_LINE> self.high = [i[2] for i in latest_bars] <NEW_LINE> self.low = [i[3] for i in latest_bars] <NEW_LINE> self.close = [i[4] for i in latest_bars] <NEW_LINE> self.volume = [i[5] for i in latest_bars] <NEW_LINE> <DEDENT> <DEDENT> def mavg(self, price_type='close'): <NEW_LINE> <INDENT> return np.mean(getattr(self, price_type)) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.length <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.datetime)+' open:'+str(self.open) + ' high:'+str(self.high)+' low:'+str(self.low)+' close:'+str(self.close)+' volume:'+str(self.volume)
Object exposed to users to reflect prices on a single or on multiple days.
62598f9f6e29344779b0047a
class FirewallAction: <NEW_LINE> <INDENT> def __init__(self, do_command, undo_command): <NEW_LINE> <INDENT> self.do_command = do_command <NEW_LINE> self.undo_command = undo_command <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{}({!r}, {!r})".format( self.__class__.__name__, self.do_command, self.undo_command) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def enable(cls): <NEW_LINE> <INDENT> return cls("ufw --force enable", "ufw disable") <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def rule(cls, rule): <NEW_LINE> <INDENT> if rule.startswith('netem'): <NEW_LINE> <INDENT> return cls('tc qdisc add dev eth0 root {}'.format(rule), 'tc qdisc del dev eth0 root') <NEW_LINE> <DEDENT> return cls("ufw {}".format(rule), "ufw delete {}".format(rule)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def deny_port_rule(cls, port): <NEW_LINE> <INDENT> return cls.rule("deny {:d}".format(port)) <NEW_LINE> <DEDENT> def do(self): <NEW_LINE> <INDENT> run_shell_command(self.do_command) <NEW_LINE> <DEDENT> def undo(self): <NEW_LINE> <INDENT> run_shell_command(self.undo_command)
FirewallAction encapsulates a ufw command and a means of undoing it.
62598f9f30bbd72246469886
class LSTM(link.Chain): <NEW_LINE> <INDENT> def __init__(self, in_size, out_size): <NEW_LINE> <INDENT> super(LSTM, self).__init__( upward=linear.Linear(in_size, 4 * out_size), lateral=linear.Linear(out_size, 4 * out_size, nobias=True), ) <NEW_LINE> self.state_size = out_size <NEW_LINE> self.reset_state() <NEW_LINE> <DEDENT> def reset_state(self): <NEW_LINE> <INDENT> self.c = self.h = None <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> lstm_in = self.upward(x) <NEW_LINE> if self.h is not None: <NEW_LINE> <INDENT> lstm_in += self.lateral(self.h) <NEW_LINE> <DEDENT> if self.c is None: <NEW_LINE> <INDENT> xp = self.xp <NEW_LINE> self.c = variable.Variable( xp.zeros((len(x.data), self.state_size), dtype=x.data.dtype), volatile='auto') <NEW_LINE> <DEDENT> self.c, self.h = lstm.lstm(self.c, lstm_in) <NEW_LINE> return self.h
Fully-connected LSTM layer. This is a fully-connected LSTM layer as a chain. Unlike the :func:`~chainer.functions.lstm` function, which is defined as a stateless activation function, this chain holds upward and lateral connections as child links. It also maintains *states*, including the cell state and the output at the previous time step. Therefore, it can be used as a *stateful LSTM*. Args: in_size (int): Dimensionality of input vectors. out_size (int): Dimensionality of output vectors. Attributes: upward (chainer.links.Linear): Linear layer of upward connections. lateral (chainer.links.Linear): Linear layer of lateral connections. c (chainer.Variable): Cell states of LSTM units. h (chainer.Variable): Output at the previous timestep.
62598f9f925a0f43d25e7e5b
class atualizaFestaForm(ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = festa <NEW_LINE> fields = list(set(festa_fields) - set(not_editable_fields))
Formulario para atualizacao de novo evento do tipo festa.
62598f9f85dfad0860cbf984
class Miner(): <NEW_LINE> <INDENT> def __init__(self, parent, uncles, coinbase): <NEW_LINE> <INDENT> self.nonce = 0 <NEW_LINE> ts = max(int(time.time()), parent.timestamp+1) <NEW_LINE> self.block = blocks.Block.init_from_parent(parent, coinbase, timestamp=ts, uncles=[u.list_header() for u in uncles]) <NEW_LINE> self.pre_finalize_state_root = self.block.state_root <NEW_LINE> self.block.finalize() <NEW_LINE> logger.debug('Mining #%d %s', self.block.number, self.block.hex_hash()) <NEW_LINE> logger.debug('Difficulty %s', self.block.difficulty) <NEW_LINE> <DEDENT> def add_transaction(self, transaction): <NEW_LINE> <INDENT> old_state_root = self.block.state_root <NEW_LINE> self.block.state_root = self.pre_finalize_state_root <NEW_LINE> try: <NEW_LINE> <INDENT> success, output = processblock.apply_transaction(self.block, transaction) <NEW_LINE> <DEDENT> except processblock.InvalidTransaction as e: <NEW_LINE> <INDENT> logger.debug('Invalid Transaction %r: %r', transaction, e) <NEW_LINE> success = False <NEW_LINE> <DEDENT> self.pre_finalize_state_root = self.block.state_root <NEW_LINE> self.block.finalize() <NEW_LINE> if not success: <NEW_LINE> <INDENT> logger.debug('transaction %r not applied', transaction) <NEW_LINE> assert old_state_root == self.block.state_root <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert transaction in self.block.get_transactions() <NEW_LINE> logger.debug( 'transaction %r applied to %r res: %r', transaction, self.block, output) <NEW_LINE> assert old_state_root != self.block.state_root <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> def get_transactions(self): <NEW_LINE> <INDENT> return self.block.get_transactions() <NEW_LINE> <DEDENT> def mine(self, steps=1000): <NEW_LINE> <INDENT> nonce_bin_prefix = '\x00' * (32 - len(struct.pack('>q', 0))) <NEW_LINE> target = 2 ** 256 / self.block.difficulty <NEW_LINE> rlp_Hn = self.block.serialize_header_without_nonce() <NEW_LINE> for nonce in range(self.nonce, self.nonce + steps): <NEW_LINE> <INDENT> nonce_bin = nonce_bin_prefix + struct.pack('>q', nonce) <NEW_LINE> h = utils.sha3(utils.sha3(rlp_Hn) + nonce_bin) <NEW_LINE> l256 = utils.big_endian_to_int(h) <NEW_LINE> if l256 < target: <NEW_LINE> <INDENT> self.block.nonce = nonce_bin <NEW_LINE> assert self.block.check_proof_of_work(self.block.nonce) is True <NEW_LINE> assert self.block.get_parent() <NEW_LINE> logger.debug( 'Nonce found %d %r', nonce, self.block) <NEW_LINE> return self.block <NEW_LINE> <DEDENT> <DEDENT> self.nonce = nonce <NEW_LINE> return False
Mines on the current head Stores received transactions The process of finalising a block involves four stages: 1) Validate (or, if mining, determine) uncles; 2) validate (or, if mining, determine) transactions; 3) apply rewards; 4) verify (or, if mining, compute a valid) state and nonce.
62598f9f76e4537e8c3ef3d6
class EngineError(LoggableError): <NEW_LINE> <INDENT> pass
Connection or other backend error.
62598f9f3d592f4c4edbaced
class XMLServer(SimpleXMLRPCServer): <NEW_LINE> <INDENT> def __init__(self, *args): <NEW_LINE> <INDENT> SimpleXMLRPCServer.__init__(self, (args[0], args[1])) <NEW_LINE> <DEDENT> def server_bind(self): <NEW_LINE> <INDENT> self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> SimpleXMLRPCServer.server_bind(self) <NEW_LINE> <DEDENT> def verify_request(self, request, client_address): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if client_address[0] in accessList: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> return 1
Augmented XML-RPC server class
62598f9fa79ad16197769e84
class ElectraPreTrainedModel(BertPreTrainedModel): <NEW_LINE> <INDENT> config_class = ElectraConfig <NEW_LINE> pretrained_model_archive_map = ELECTRA_PRETRAINED_MODEL_ARCHIVE_MAP <NEW_LINE> load_tf_weights = load_tf_weights_in_electra <NEW_LINE> base_model_prefix = "electra"
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
62598f9f596a897236127a9b
class ColumnFlagsFlag(Flags): <NEW_LINE> <INDENT> pass
Column flags representation class of groonga
62598f9f7cff6e4e811b5843
class MXNetBackend(Backend): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def perform_import_export(graph_proto, input_shape): <NEW_LINE> <INDENT> graph = GraphProto() <NEW_LINE> sym, arg_params, aux_params = graph.from_onnx(graph_proto) <NEW_LINE> params = {} <NEW_LINE> params.update(arg_params) <NEW_LINE> params.update(aux_params) <NEW_LINE> converter = MXNetGraph() <NEW_LINE> graph_proto = converter.create_onnx_graph_proto(sym, params, in_shape=input_shape, in_type=mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype('float32')]) <NEW_LINE> sym, arg_params, aux_params = graph.from_onnx(graph_proto) <NEW_LINE> return sym, arg_params, aux_params <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def prepare(cls, model, device='CPU', **kwargs): <NEW_LINE> <INDENT> graph = GraphProto() <NEW_LINE> metadata = graph.get_graph_metadata(model.graph) <NEW_LINE> input_data = metadata['input_tensor_data'] <NEW_LINE> input_shape = [data[1] for data in input_data] <NEW_LINE> sym, arg_params, aux_params = MXNetBackend.perform_import_export(model.graph, input_shape) <NEW_LINE> return MXNetBackendRep(sym, arg_params, aux_params, device) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def supports_device(cls, device): <NEW_LINE> <INDENT> return device == 'CPU'
MXNet backend for ONNX
62598f9f462c4b4f79dbb82b
class AppServiceCertificatePatchResource(ProxyOnlyResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'key_vault_id': {'key': 'properties.keyVaultId', 'type': 'str'}, 'key_vault_secret_name': {'key': 'properties.keyVaultSecretName', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, kind: Optional[str] = None, key_vault_id: Optional[str] = None, key_vault_secret_name: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(AppServiceCertificatePatchResource, self).__init__(kind=kind, **kwargs) <NEW_LINE> self.key_vault_id = key_vault_id <NEW_LINE> self.key_vault_secret_name = key_vault_secret_name <NEW_LINE> self.provisioning_state = None
Key Vault container ARM resource for a certificate that is purchased through Azure. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id. :vartype id: str :ivar name: Resource Name. :vartype name: str :ivar kind: Kind of resource. :vartype kind: str :ivar type: Resource type. :vartype type: str :ivar key_vault_id: Key Vault resource Id. :vartype key_vault_id: str :ivar key_vault_secret_name: Key Vault secret name. :vartype key_vault_secret_name: str :ivar provisioning_state: Status of the Key Vault secret. Possible values include: "Initialized", "WaitingOnCertificateOrder", "Succeeded", "CertificateOrderFailed", "OperationNotPermittedOnKeyVault", "AzureServiceUnauthorizedToAccessKeyVault", "KeyVaultDoesNotExist", "KeyVaultSecretDoesNotExist", "UnknownError", "ExternalPrivateKey", "Unknown". :vartype provisioning_state: str or ~azure.mgmt.web.v2015_08_01.models.KeyVaultSecretStatus
62598f9f009cb60464d01344
class AutoBatchingMixin(object): <NEW_LINE> <INDENT> MIN_IDEAL_BATCH_DURATION = .2 <NEW_LINE> MAX_IDEAL_BATCH_DURATION = 2 <NEW_LINE> _effective_batch_size = 1 <NEW_LINE> _smoothed_batch_duration = 0.0 <NEW_LINE> def compute_batch_size(self): <NEW_LINE> <INDENT> old_batch_size = self._effective_batch_size <NEW_LINE> batch_duration = self._smoothed_batch_duration <NEW_LINE> if (batch_duration > 0 and batch_duration < self.MIN_IDEAL_BATCH_DURATION): <NEW_LINE> <INDENT> ideal_batch_size = int(old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration) <NEW_LINE> batch_size = max(2 * ideal_batch_size, 1) <NEW_LINE> self._effective_batch_size = batch_size <NEW_LINE> if self.parallel.verbose >= 10: <NEW_LINE> <INDENT> self.parallel._print( "Batch computation too fast (%.4fs.) " "Setting batch_size=%d.", (batch_duration, batch_size)) <NEW_LINE> <DEDENT> <DEDENT> elif (batch_duration > self.MAX_IDEAL_BATCH_DURATION and old_batch_size >= 2): <NEW_LINE> <INDENT> batch_size = old_batch_size // 2 <NEW_LINE> self._effective_batch_size = batch_size <NEW_LINE> if self.parallel.verbose >= 10: <NEW_LINE> <INDENT> self.parallel._print( "Batch computation too slow (%.4fs.) " "Setting batch_size=%d.", (batch_duration, batch_size)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> batch_size = old_batch_size <NEW_LINE> <DEDENT> if batch_size != old_batch_size: <NEW_LINE> <INDENT> self._smoothed_batch_duration = 0 <NEW_LINE> <DEDENT> return batch_size <NEW_LINE> <DEDENT> def batch_completed(self, batch_size, duration): <NEW_LINE> <INDENT> if batch_size == self._effective_batch_size: <NEW_LINE> <INDENT> old_duration = self._smoothed_batch_duration <NEW_LINE> if old_duration == 0: <NEW_LINE> <INDENT> new_duration = duration <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_duration = 0.8 * old_duration + 0.2 * duration <NEW_LINE> <DEDENT> self._smoothed_batch_duration = new_duration
A helper class for automagically batching jobs.
62598f9fd7e4931a7ef3beb8
class MainWidget(UiComponent): <NEW_LINE> <INDENT> component_type = "main_widget" <NEW_LINE> instantiate = UiComponent.IMMEDIATELY <NEW_LINE> def information_box(self, message): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def question_box(self, question, option0, option1, option2): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def error_box(self, message): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def enable_edit_current_card(self, enabled): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def enable_delete_current_card(self, enabled): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def enable_browse_cards(self, enable): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def save_file_dialog(self, path, filter, caption=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def open_file_dialog(self, path, filter, caption=""): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_window_title(self, title): <NEW_LINE> <INDENT> pass
Describes the interface that the main widget needs to implement in order to be used by the main controller.
62598f9f24f1403a926857c2
class Image(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.display = None <NEW_LINE> <DEDENT> def show_image(self, image, width, height): <NEW_LINE> <INDENT> size = (width, height) <NEW_LINE> self.display = pygame.display.set_mode(size, 0) <NEW_LINE> self.snapshot = pygame.surface.Surface(size, 0, self.display) <NEW_LINE> img = pygame.image.load(StringIO(image)) <NEW_LINE> self.display.blit(img, (0, 0)) <NEW_LINE> pygame.display.flip() <NEW_LINE> <DEDENT> def sizefactor(self, count): <NEW_LINE> <INDENT> i = 1 <NEW_LINE> while(count > i**2): <NEW_LINE> <INDENT> i+=1 <NEW_LINE> <DEDENT> return i <NEW_LINE> <DEDENT> def show_images(self, images, width, height): <NEW_LINE> <INDENT> surface_size = (width, height) <NEW_LINE> image_count_side = self.sizefactor(len(images)) <NEW_LINE> image_width = width / image_count_side <NEW_LINE> image_height = height / image_count_side <NEW_LINE> self.display = pygame.display.set_mode(surface_size, 0) <NEW_LINE> self.snapshot = pygame.surface.Surface(surface_size, 0, self.display) <NEW_LINE> for idy in range(image_count_side): <NEW_LINE> <INDENT> for idx in range(image_count_side): <NEW_LINE> <INDENT> image_index = idy*image_count_side + idx <NEW_LINE> if image_index >= len(images): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> image = images[image_index] <NEW_LINE> img = pygame.image.load(StringIO(image)) <NEW_LINE> img = pygame.transform.scale(img, (image_width, image_height)) <NEW_LINE> self.display.blit(img, (idx*image_width, idy*image_height)) <NEW_LINE> <DEDENT> <DEDENT> pygame.display.flip() <NEW_LINE> <DEDENT> def detect_face(self, image): <NEW_LINE> <INDENT> linux_prefix = "/usr/share/opencv" <NEW_LINE> mac_prefix = "/usr/local/share/OpenCV" <NEW_LINE> suffix = "/haarcascades/haarcascade_frontalface_default.xml" <NEW_LINE> linux_path = linux_prefix + suffix <NEW_LINE> mac_path = mac_prefix + suffix <NEW_LINE> if os.path.exists(linux_path) : <NEW_LINE> <INDENT> cpath = linux_path <NEW_LINE> <DEDENT> elif os.path.exists(mac_path) : <NEW_LINE> <INDENT> cpath = mac_path <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> raise Exception("No Haarcascade found") <NEW_LINE> <DEDENT> classifier = cv2.CascadeClassifier(cpath) <NEW_LINE> jpg = numpy.fromstring(image, numpy.int8) <NEW_LINE> image = cv2.imdecode(jpg, 1) <NEW_LINE> faces = classifier.detectMultiScale(image) <NEW_LINE> if len(faces) > 0 : <NEW_LINE> <INDENT> for (x,y,w,h) in faces : <NEW_LINE> <INDENT> if w < 120 : <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def to_string(self, image, format): <NEW_LINE> <INDENT> buffer = StringIO() <NEW_LINE> image.save(buffer, format=format) <NEW_LINE> return buffer.getvalue() <NEW_LINE> <DEDENT> def from_string(self, img_str): <NEW_LINE> <INDENT> buffer = StringIO(img_str) <NEW_LINE> image = self.open(buffer) <NEW_LINE> return image <NEW_LINE> <DEDENT> def new(self, mode, size): <NEW_LINE> <INDENT> return PIL_Image.new(mode, size) <NEW_LINE> <DEDENT> def open(self, fp): <NEW_LINE> <INDENT> return PIL_Image.open(fp) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if not self.display is None: <NEW_LINE> <INDENT> pygame.display.quit()
Image object
62598f9f07f4c71912baf26b
class EventViewSet(ListModelMixin, CreateModelMixin, GenericViewSet): <NEW_LINE> <INDENT> permission_classes = (IsAuthenticated, IsEventOwnerOrReadOnly) <NEW_LINE> serializer_class = EventSerializer <NEW_LINE> filter_fields = ('module', 'module_name', 'start_date', 'end_date') <NEW_LINE> search_fields = ('name', 'description') <NEW_LINE> ordering = ('-modified',) <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> queryset = Event.objects.filter(uni=self.request.user.uni)
Authenticated users can see any event, owners can modify their own event.
62598f9f1f5feb6acb162a42
class SocketError(Error): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> super().__init__(message, 200)
To be raised when the request was sucessful, but the server was unable to notify one or more of the clients in real time because of some kind of problem concerning messaging via Web Sockets. THE RESPONSE STATUS IS STILL 200
62598f9f7047854f4633f203
@implements_iterator <NEW_LINE> class TemplateStream(object): <NEW_LINE> <INDENT> def __init__(self, gen): <NEW_LINE> <INDENT> self._gen = gen <NEW_LINE> self.disable_buffering() <NEW_LINE> <DEDENT> def dump(self, fp, encoding=None, errors='strict'): <NEW_LINE> <INDENT> close = False <NEW_LINE> if isinstance(fp, string_types): <NEW_LINE> <INDENT> fp = open(fp, encoding is None and 'w' or 'wb') <NEW_LINE> close = True <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if encoding is not None: <NEW_LINE> <INDENT> iterable = (x.encode(encoding, errors) for x in self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iterable = self <NEW_LINE> <DEDENT> if hasattr(fp, 'writelines'): <NEW_LINE> <INDENT> fp.writelines(iterable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for item in iterable: <NEW_LINE> <INDENT> fp.write(item) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> if close: <NEW_LINE> <INDENT> fp.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def disable_buffering(self): <NEW_LINE> <INDENT> self._next = get_next(self._gen) <NEW_LINE> self.buffered = False <NEW_LINE> <DEDENT> def enable_buffering(self, size=5): <NEW_LINE> <INDENT> if size <= 1: <NEW_LINE> <INDENT> raise ValueError('buffer size too small') <NEW_LINE> <DEDENT> def generator(next): <NEW_LINE> <INDENT> buf = [] <NEW_LINE> c_size = 0 <NEW_LINE> push = buf.append <NEW_LINE> while 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while c_size < size: <NEW_LINE> <INDENT> c = next() <NEW_LINE> push(c) <NEW_LINE> if c: <NEW_LINE> <INDENT> c_size += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> if not c_size: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> yield concat(buf) <NEW_LINE> del buf[:] <NEW_LINE> c_size = 0 <NEW_LINE> <DEDENT> <DEDENT> self.buffered = True <NEW_LINE> self._next = get_next(generator(get_next(self._gen))) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> return self._next()
A template stream works pretty much like an ordinary python generator but it can buffer multiple items to reduce the number of total iterations. Per default the output is unbuffered which means that for every unbuffered instruction in the template one unicode string is yielded. If buffering is enabled with a buffer size of 5, five items are combined into a new unicode string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration.
62598f9f236d856c2adc934a
class QLearningAgent(ReinforcementAgent): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> self.qvalue = [] <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> if self.qvalue: <NEW_LINE> <INDENT> for qval in self.qvalue: <NEW_LINE> <INDENT> if qval[0] == state and qval[1] == action: <NEW_LINE> <INDENT> return(qval[2]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return(0.0) <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> action_list = self.getLegalActions(state) <NEW_LINE> if action_list: <NEW_LINE> <INDENT> actions = [] <NEW_LINE> for action in action_list: <NEW_LINE> <INDENT> actions.append(self.getQValue(state, action)) <NEW_LINE> <DEDENT> return(max(actions)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return(0.0) <NEW_LINE> <DEDENT> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> action_list = self.getLegalActions(state) <NEW_LINE> if action_list: <NEW_LINE> <INDENT> actions = [] <NEW_LINE> for action in action_list: <NEW_LINE> <INDENT> actions.append(self.getQValue(state, action)) <NEW_LINE> <DEDENT> return(action_list[actions.index(max(actions))]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> action_list = self.getLegalActions(state) <NEW_LINE> action = None <NEW_LINE> if util.flipCoin(self.epsilon) and action_list: <NEW_LINE> <INDENT> action = random.choice(action_list) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self.getPolicy(state) <NEW_LINE> <DEDENT> return(action) <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> update_flag = 0 <NEW_LINE> q_value = (1-self.alpha) * self.getValue(state) + self.alpha * reward + self.alpha * self.gamma * self.getValue(nextState) <NEW_LINE> if self.qvalue: <NEW_LINE> <INDENT> for qval in self.qvalue: <NEW_LINE> <INDENT> if qval[0] == state and qval[1] == action: <NEW_LINE> <INDENT> qval[2] = q_value <NEW_LINE> update_flag = 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.qvalue.append([state,action,q_value]) <NEW_LINE> update_flag = 1 <NEW_LINE> <DEDENT> if update_flag == 0: <NEW_LINE> <INDENT> self.qvalue.append([state,action,q_value]) <NEW_LINE> <DEDENT> return None
Q-Learning Agent Functions you should fill in: - getQValue - getAction - getValue - getPolicy - update Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.gamma (discount rate) Functions you should use - self.getLegalActions(state) which returns legal actions for a state
62598f9feab8aa0e5d30bba7
class LVMReader(): <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.filename = path.split("/")[-1][:-4] + ".dat" <NEW_LINE> self._raw = list() <NEW_LINE> self.__data = list() <NEW_LINE> with open(path) as lvm: <NEW_LINE> <INDENT> self._raw = lvm.readlines() <NEW_LINE> <DEDENT> self.__clean() <NEW_LINE> <DEDENT> def __clean(self): <NEW_LINE> <INDENT> for i in range(len(self._raw)): <NEW_LINE> <INDENT> self._raw[i] = self._raw[i].replace(",", ".") <NEW_LINE> self.__data.append( self._raw[i].strip().split("\t") ) <NEW_LINE> <DEDENT> if ["***End_of_Header***"] in self.__data: <NEW_LINE> <INDENT> i = len(self.__data) - 1 - self.__data[::-1].index( ["***End_of_Header***"] ) + 2 <NEW_LINE> <DEDENT> else: i = 0 <NEW_LINE> self.__data = self.__data[i:] <NEW_LINE> self.__data = [ [ float(x) for x in row ] for row in self.__data ] <NEW_LINE> self.__data = LVMReader.transpose(self.__data) <NEW_LINE> <DEDENT> def transpose(array): <NEW_LINE> <INDENT> return list(map(list, zip(*array)))[:] <NEW_LINE> <DEDENT> def export(array, path="", space="\t", end="", header="", transposed=False): <NEW_LINE> <INDENT> if not transposed: array = LVMReader.transpose(array) <NEW_LINE> if header != "": header += "\n" <NEW_LINE> with open(path, "w") as out: <NEW_LINE> <INDENT> out.write(header) <NEW_LINE> for i in array: <NEW_LINE> <INDENT> out.write(space.join("{:E}".format(x) for x in i) + end) <NEW_LINE> out.write("\n") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def columns(self): <NEW_LINE> <INDENT> return self.__data[:] <NEW_LINE> <DEDENT> @property <NEW_LINE> def rows(self): <NEW_LINE> <INDENT> return LVMReader.transpose(self.__data)
Load *.lvm files exported by LabView Parameters ---------- path: string Location of the file Attributes ---------- filename: string Filename to export to. data: 2D-array The converted and cleaned up data. Every column is a list inside of the data list. transposed: 2D-array The data attribute transposed. Every row is a list inside of the data list. Methods ------- transpose(list) Transposes a 2D-array list (e.g. matrix, table, ...) export(path="", space=" ", end="", transposed=False) Exports the data as a text table to the given path with the given file name.
62598f9f3539df3088ecc0d5
class CollectGoogleSections(CollectSectionsBase): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(CollectGoogleSections, self).__init__(*args, **kwargs) <NEW_LINE> self._to_remove = None <NEW_LINE> <DEDENT> def get_handler_name(self, node): <NEW_LINE> <INDENT> if isinstance(node, nodes.admonition): <NEW_LINE> <INDENT> if len(node) and isinstance(node[0], nodes.title): <NEW_LINE> <INDENT> return node[0].astext() <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(node, nodes.note): <NEW_LINE> <INDENT> return 'note' <NEW_LINE> <DEDENT> elif isinstance(node, seealso): <NEW_LINE> <INDENT> return 'seealso' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return node.tagname <NEW_LINE> <DEDENT> <DEDENT> def add_to_section(self, section_name, node, remove_title=True, unwrap=True): <NEW_LINE> <INDENT> node['real_parent'] = node.parent <NEW_LINE> self.add_to_remove(node) <NEW_LINE> section = self.get_docstring_section(section_name, node) <NEW_LINE> if remove_title and isinstance(node[0], nodes.title): <NEW_LINE> <INDENT> node.remove(node[0]) <NEW_LINE> <DEDENT> if unwrap: <NEW_LINE> <INDENT> section.extend(node.children) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> section += node <NEW_LINE> <DEDENT> return section <NEW_LINE> <DEDENT> def process_notes(self, node): <NEW_LINE> <INDENT> self.add_to_section('notes', node) <NEW_LINE> <DEDENT> def process_note(self, node): <NEW_LINE> <INDENT> self.add_to_section('note', node, unwrap=False) <NEW_LINE> <DEDENT> def process_examples(self, node): <NEW_LINE> <INDENT> self.add_to_section('examples', node) <NEW_LINE> <DEDENT> def process_example(self, node): <NEW_LINE> <INDENT> self.add_to_section('example', node) <NEW_LINE> <DEDENT> def process_references(self, node): <NEW_LINE> <INDENT> self.add_to_section('references', node) <NEW_LINE> <DEDENT> def process_seealso(self, node): <NEW_LINE> <INDENT> self.add_to_section('seealso', node, unwrap=False) <NEW_LINE> <DEDENT> def process_todo(self, node): <NEW_LINE> <INDENT> section = self.add_to_section('todo', node, unwrap=False) <NEW_LINE> section['skip_section_processing'] = True <NEW_LINE> <DEDENT> def process_warning(self, node): <NEW_LINE> <INDENT> self.add_to_section('warning', node, unwrap=False) <NEW_LINE> <DEDENT> def process_field_list(self, node): <NEW_LINE> <INDENT> for el in node.children[:]: <NEW_LINE> <INDENT> if not isinstance(el, nodes.field): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> field_signature = el.children[0].children[0] <NEW_LINE> if field_signature != 'Warns': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.add_to_section('warns', el, unwrap=False)
Transform to collect google-style sections.
62598f9fa17c0f6771d5c05b
class BaseConfigTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> from Products.FileSystemStorage.configuration import schema <NEW_LINE> self.schema = schema.fssSchema <NEW_LINE> return
Common resources for testing FSS configuration
62598f9f4a966d76dd5eed02
class Umesimd(CMakePackage): <NEW_LINE> <INDENT> homepage = "https://github.com/edanor/umesimd" <NEW_LINE> url = "https://github.com/edanor/umesimd/archive/v0.8.1.tar.gz" <NEW_LINE> version('0.8.1', sha256='78f457634ee593495083cf8eb6ec1cf7f274db5ff7210c37b3a954f1a712d357') <NEW_LINE> version('0.7.1', sha256='c5377f8223fbf93ad79412e4b40fd14e88a86e08aa573f49df38a159d451023d') <NEW_LINE> version('0.6.1', sha256='15d9fde1a5c89f3c77c42550c2b55d25a581971002157a338e01104079cdf843') <NEW_LINE> version('0.5.2', sha256='8a02c0322b38f1e1757675bb781e190b2458fb8bc508a6bd03356da248362daf') <NEW_LINE> version('0.5.1', sha256='6b7bc62548170e15e98d9e4c57c2980d2cd46593167d6d4b83765aa57175e5ad') <NEW_LINE> version('0.4.2', sha256='a5dd2ec7ecf781af01f7e3336975870f34bfc8c79ef4bba90ec90e43b5f5969f') <NEW_LINE> version('0.4.1', sha256='e05b9f886164826005c8db5d2240f22cb88593c05b4fe45c81aba4d1d57a9bfa') <NEW_LINE> version('0.3.2', sha256='90399fa64489ca4d492a57a49582f5b827d4710a691f533822fd61edc346e8f6') <NEW_LINE> version('0.3.1', sha256='9bab8b4c70e11dbdd864a09053225c74cfabb801739e09a314ddeb1d84a43f0a')
UME::SIMD is an explicit vectorization library. The library defines homogeneous interface for accessing functionality of SIMD registers of AVX, AVX2, AVX512 and IMCI (KNCNI, k1om) instruction set.
62598f9f1b99ca400228f43e
class Solution: <NEW_LINE> <INDENT> def climbStairs(self, n): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> dp = [1 for i in range(n + 1)] <NEW_LINE> for i in range(2, n + 1): <NEW_LINE> <INDENT> dp[i] = dp[i - 1] + dp[i - 2] <NEW_LINE> <DEDENT> return dp[-1]
@param n: An integer @return: An integer
62598f9f01c39578d7f12b9f
class MDTabsLabel(ToggleButtonBehavior, Label): <NEW_LINE> <INDENT> text_color_normal = ListProperty((1, 1, 1, 1)) <NEW_LINE> text_color_active = ListProperty((1, 1, 1, 1)) <NEW_LINE> tab = ObjectProperty() <NEW_LINE> tab_bar = ObjectProperty() <NEW_LINE> callback = ObjectProperty() <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.min_space = 0 <NEW_LINE> <DEDENT> def on_release(self): <NEW_LINE> <INDENT> self.tab_bar.parent.dispatch("on_tab_switch", self.tab, self, self.text) <NEW_LINE> if self.state == "down": <NEW_LINE> <INDENT> self.tab_bar.parent.carousel.load_slide(self.tab) <NEW_LINE> <DEDENT> <DEDENT> def on_texture(self, widget, texture): <NEW_LINE> <INDENT> if texture: <NEW_LINE> <INDENT> self.width = texture.width <NEW_LINE> self.min_space = self.width <NEW_LINE> <DEDENT> <DEDENT> def _trigger_update_tab_indicator(self): <NEW_LINE> <INDENT> if self.state == "down": <NEW_LINE> <INDENT> self.tab_bar.update_indicator(self.x, self.width)
This class it represent the label of each tab.
62598f9f21bff66bcd722a84
class my_DQPSK_Demod(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> raise AttributeError("No constructor defined") <NEW_LINE> <DEDENT> __repr__ = _swig_repr <NEW_LINE> def make(): <NEW_LINE> <INDENT> return _guyu_swig.my_DQPSK_Demod_make() <NEW_LINE> <DEDENT> make = staticmethod(make) <NEW_LINE> __swig_destroy__ = _guyu_swig.delete_my_DQPSK_Demod <NEW_LINE> __del__ = lambda self: None
Proxy of C++ gr::guyu::my_DQPSK_Demod class.
62598f9f3539df3088ecc0d6
class StockBasic(BaseModel): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> db_table = 'stock_basic' <NEW_LINE> <DEDENT> code = CharField() <NEW_LINE> name = CharField() <NEW_LINE> industry = CharField() <NEW_LINE> area = CharField() <NEW_LINE> pe = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> outstanding = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> totals = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> totalAssets = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> liquidAssets = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> fixedAssets = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> reserved = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> reservedPerShare = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> eps = DecimalField(max_digits=12, decimal_places=3) <NEW_LINE> bvps = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> pb = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> timeToMarket = IntegerField() <NEW_LINE> undp = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> perundp = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> rev = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> profit = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> gpr = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> npr = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> holders = DecimalField(max_digits=12, decimal_places=2) <NEW_LINE> insert_date = DateField('%Y%m%d')
股票列表
62598f9f5f7d997b871f92f0
class InputRecord(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.primer_info = [] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> output = "" <NEW_LINE> for name, primer1, primer2 in self.primer_info: <NEW_LINE> <INDENT> output += "%s %s %s\n" % (name, primer1, primer2) <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def add_primer_set(self, primer_name, first_primer_seq, second_primer_seq): <NEW_LINE> <INDENT> self.primer_info.append((primer_name, first_primer_seq, second_primer_seq))
Represent the input file into the primersearch program. This makes it easy to add primer information and write it out to the simple primer file format.
62598f9f4527f215b58e9d05
class Block(models.Model): <NEW_LINE> <INDENT> name = models.CharField("板块标题", max_length=100) <NEW_LINE> desc = models.CharField("板块描述", max_length=100) <NEW_LINE> manager_name = models.CharField("管理员名字", max_length=100) <NEW_LINE> status = models.IntegerField("状态", choices =((0, "正常"), (-1, "删除"))) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "首页" <NEW_LINE> verbose_name_plural = "首页板块"
定义表结构,就是对类进行定义属性
62598f9f0a50d4780f7051fb
class new_LakeShore(Device): <NEW_LINE> <INDENT> input_A = Cpt(EpicsSignal, '{Env:01-Chan:A}T-I') <NEW_LINE> input_A_celsius = Cpt(EpicsSignal, '{Env:01-Chan:A}T:C-I') <NEW_LINE> input_B = Cpt(EpicsSignal, '{Env:01-Chan:B}T-I') <NEW_LINE> input_C = Cpt(EpicsSignal, '{Env:01-Chan:C}T-I') <NEW_LINE> input_D = Cpt(EpicsSignal, '{Env:01-Chan:D}T-I') <NEW_LINE> output1 = output_lakeshore('XF:12ID-ES{Env:01-Out:1}', name='ls_outpu1') <NEW_LINE> output2 = output_lakeshore('XF:12ID-ES{Env:01-Out:2}', name='ls_outpu2') <NEW_LINE> output3 = output_lakeshore('XF:12ID-ES{Env:01-Out:3}', name='ls_outpu3') <NEW_LINE> output4 = output_lakeshore('XF:12ID-ES{Env:01-Out:4}', name='ls_outpu4')
Lakeshore is the device reading the temperature from the heating stage for SAXS and GISAXS. This class define the PVs to read and write to control lakeshore :param Device: ophyd device
62598f9f30dc7b766599f66f
class Payment(models.Model): <NEW_LINE> <INDENT> customer = models.ForeignKey("Customer", db_constraint=False) <NEW_LINE> course = models.ForeignKey("Course", verbose_name="所报课程", db_constraint=False) <NEW_LINE> amount = models.PositiveIntegerField(verbose_name="数额", default=500) <NEW_LINE> consultant = models.ForeignKey("UserProfile", db_constraint=False) <NEW_LINE> date = models.DateTimeField(auto_now_add=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "%s %s" % (self.customer, self.amount) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "交费记录表" <NEW_LINE> verbose_name_plural = "交费记录表"
交费记录表
62598f9f56ac1b37e630200c
class UPSMultiExporter(UPSExporter): <NEW_LINE> <INDENT> def __init__( self, config, insecure=False, threading=False, verbose=False, login_timeout=3 ): <NEW_LINE> <INDENT> self.logger = create_logger( f"{__name__}.{self.__class__.__name__}", not verbose ) <NEW_LINE> self.insecure = insecure <NEW_LINE> self.threading = threading <NEW_LINE> self.verbose = verbose <NEW_LINE> self.login_timeout = login_timeout <NEW_LINE> self.ups_devices = self.get_ups_devices(config) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_devices(config): <NEW_LINE> <INDENT> if isinstance(config, str): <NEW_LINE> <INDENT> with open(config) as json_file: <NEW_LINE> <INDENT> devices = json.load(json_file) <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(config, dict): <NEW_LINE> <INDENT> devices = config <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise AttributeError("Only config path (str) or dict accepted") <NEW_LINE> <DEDENT> return devices <NEW_LINE> <DEDENT> def get_ups_devices(self, config) -> list: <NEW_LINE> <INDENT> devices = self.get_devices(config) <NEW_LINE> return [ UPSScraper( value['address'], (value['user'], value['password']), key, insecure=self.insecure, verbose=self.verbose, login_timeout=self.login_timeout ) for key, value in devices.items() ] <NEW_LINE> <DEDENT> def scrape_data(self): <NEW_LINE> <INDENT> if self.threading: <NEW_LINE> <INDENT> with ThreadPoolExecutor() as executor: <NEW_LINE> <INDENT> futures = [ executor.submit(ups.get_measures) for ups in self.ups_devices ] <NEW_LINE> try: <NEW_LINE> <INDENT> for future in as_completed(futures, self.login_timeout+1): <NEW_LINE> <INDENT> yield future.result() <NEW_LINE> <DEDENT> <DEDENT> except TimeoutError as err: <NEW_LINE> <INDENT> self.logger.exception(err) <NEW_LINE> yield None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for ups in self.ups_devices: <NEW_LINE> <INDENT> yield ups.get_measures()
Prometheus exporter for multiple UPSs. Collects metrics from multiple UPSs at the same time. If threading is enabled, multiple threads will be used to collect sensor readings which is considerably faster. :param config: str Path to the configuration file, containing UPS ip/hostname, username, and password combinations for all UPSs to be monitored :param insecure: bool Whether to connect to UPSs with self-signed SSL certificates :param threading: bool Whether to use multiple threads to scrape the data 'parallel'. This is surely the best way to increase the speed :param verbose: bool Allow logging output for development :param login_timeout: float Login timeout for authentication
62598f9f07f4c71912baf26d
class Movie(Video): <NEW_LINE> <INDENT> def __init__(self, object_dict, connector): <NEW_LINE> <INDENT> super().__init__(object_dict, connector) <NEW_LINE> <DEDENT> @property <NEW_LINE> def premiere_date(self): <NEW_LINE> <INDENT> return self.object_dict.get('PremiereDate')
Class representing movie objects Parameters ---------- object_dict : dict same as for `EmbyObject` connector : embypy.utils.connector.Connector same as for `EmbyObject`
62598f9ff548e778e596b3cf
class SFparkAvailabilityRecord(Base): <NEW_LINE> <INDENT> __tablename__ = 'sfpark_avl' <NEW_LINE> id = Column(BigInteger, primary_key=True, autoincrement=True) <NEW_LINE> loc_id = Column(BigInteger, ForeignKey('sfpark_loc.id')) <NEW_LINE> date_id = Column(Integer) <NEW_LINE> availability_updated_timestamp = Column(DateTime) <NEW_LINE> occ = Column(Integer) <NEW_LINE> oper = Column(Integer) <NEW_LINE> def __init__(self, loc_id, date_id, updated_time, json): <NEW_LINE> <INDENT> self.loc_id = loc_id <NEW_LINE> self.date_id = date_id <NEW_LINE> self.availability_updated_timestamp = updated_time <NEW_LINE> if "OCC" in json: self.occ = int(json["OCC"]) <NEW_LINE> if "OPER" in json: self.oper = int(json["OPER"])
Maps the object representation of a single availability (main) record of SFPark data to its representation in a relational database. These will be udpated every minute. A corresponding database, named sfdata, should be available, and contain a table with the following definition: CREATE TABLE sfpark_avl ( id BIGSERIAL NOT NULL PRIMARY KEY, # Unique ID and primary index loc_id INT NOT NULL, # ID to link back to location table date_id INT NOT NULL, # date ID in form YYYYMMDD availability_updated_timestamp TIMESTAMP, # Returns the Timestamp of when the availability data response was updated for the request occ INTEGER, # Number of spaces currently occupied oper INTEGER # Number of spaces currently operational for this location );
62598f9f498bea3a75a57943
class ProfileTestCase(test.TestCase): <NEW_LINE> <INDENT> def _pre_setup(self): <NEW_LINE> <INDENT> self._original_installed_apps = list(settings.INSTALLED_APPS) <NEW_LINE> settings.INSTALLED_APPS += ('userena.tests.profiles',) <NEW_LINE> loading.cache.loaded = False <NEW_LINE> call_command('syncdb', interactive=False, verbosity=0) <NEW_LINE> super(ProfileTestCase, self)._pre_setup() <NEW_LINE> <DEDENT> def _post_teardown(self): <NEW_LINE> <INDENT> super(ProfileTestCase, self)._post_teardown() <NEW_LINE> settings.INSTALLED_APPS = self._original_installed_apps <NEW_LINE> loading.cache.loaded = False
A custom TestCase that loads the profile application for testing purposes
62598f9f7047854f4633f204
class DPTFrequency(DPT4ByteFloat): <NEW_LINE> <INDENT> dpt_main_number = 14 <NEW_LINE> dpt_sub_number = 33 <NEW_LINE> value_type = "frequency" <NEW_LINE> unit = "Hz"
DPT 14.033 DPT_Value_Frequency.
62598f9f090684286d5935eb
class Radius(ContinuousRange): <NEW_LINE> <INDENT> def __init__(self, centre, radius): <NEW_LINE> <INDENT> self._centre = centre <NEW_LINE> self._radius = radius <NEW_LINE> self._start = self._centre - self._radius <NEW_LINE> self._end = self._centre + self._radius
Used to tell proxy methods that a range of values defined by a centre and a radius should be queried for - special case of filter clauses.
62598f9f236d856c2adc934b
class IRCMessage: <NEW_LINE> <INDENT> def __init__(self, command, *args, prefix=None): <NEW_LINE> <INDENT> if command.isdigit(): <NEW_LINE> <INDENT> self.command = NUMERICS.get(command, command) <NEW_LINE> self.numeric = command <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.command = command <NEW_LINE> self.numeric = None <NEW_LINE> <DEDENT> self.args = args <NEW_LINE> self.prefix = prefix <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> parts = [self.command] + list(self.args) <NEW_LINE> if self.args and ' ' in parts[-1]: <NEW_LINE> <INDENT> parts[-1] = ':' + parts[-1] <NEW_LINE> <DEDENT> return ' '.join(parts) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse(cls, line): <NEW_LINE> <INDENT> m = PATTERN.match(line) <NEW_LINE> if not m: <NEW_LINE> <INDENT> raise ValueError(repr(line)) <NEW_LINE> <DEDENT> arg_str = m.group('args').lstrip(' ') <NEW_LINE> if arg_str: <NEW_LINE> <INDENT> args = re.split(' +', arg_str) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args = [] <NEW_LINE> <DEDENT> if m.group('trailing'): <NEW_LINE> <INDENT> args.append(m.group('trailing')) <NEW_LINE> <DEDENT> return cls(m.group('command'), *args, prefix=m.group('prefix'))
IRCMessage A class that abstracts parsing and rendering of IRC messages.
62598f9f63b5f9789fe84f97
class RayleighConfigBaseClass(object): <NEW_LINE> <INDENT> def __init__(self, aerosol_type, atm_type='us-standard'): <NEW_LINE> <INDENT> options = get_config() <NEW_LINE> self.do_download = 'download_from_internet' in options and options['download_from_internet'] <NEW_LINE> self._lutfiles_version_uptodate = False <NEW_LINE> if atm_type not in ATMOSPHERES: <NEW_LINE> <INDENT> raise AttributeError('Atmosphere type not supported! ' + 'Need to be one of {}'.format(str(ATMOSPHERES))) <NEW_LINE> <DEDENT> self._aerosol_type = aerosol_type <NEW_LINE> if aerosol_type not in AEROSOL_TYPES: <NEW_LINE> <INDENT> raise AttributeError('Aerosol type not supported! ' + 'Need to be one of {0}'.format(str(AEROSOL_TYPES))) <NEW_LINE> <DEDENT> if atm_type not in ATMOSPHERES.keys(): <NEW_LINE> <INDENT> LOG.error("Atmosphere type %s not supported", atm_type) <NEW_LINE> <DEDENT> LOG.info("Atmosphere chosen: %s", atm_type) <NEW_LINE> if (self._aerosol_type in ATM_CORRECTION_LUT_VERSION and self._get_lutfiles_version() == ATM_CORRECTION_LUT_VERSION[self._aerosol_type]['version']): <NEW_LINE> <INDENT> self.lutfiles_version_uptodate = True <NEW_LINE> <DEDENT> <DEDENT> def _get_lutfiles_version(self): <NEW_LINE> <INDENT> basedir = get_rayleigh_lut_dir(self._aerosol_type) <NEW_LINE> lutfiles_version_path = os.path.join(basedir, ATM_CORRECTION_LUT_VERSION[self._aerosol_type]['filename']) <NEW_LINE> if not os.path.exists(lutfiles_version_path): <NEW_LINE> <INDENT> return "v0.0.0" <NEW_LINE> <DEDENT> with open(lutfiles_version_path, 'r') as fpt: <NEW_LINE> <INDENT> return fpt.readline().strip() <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def lutfiles_version_uptodate(self): <NEW_LINE> <INDENT> return self._lutfiles_version_uptodate <NEW_LINE> <DEDENT> @lutfiles_version_uptodate.setter <NEW_LINE> def lutfiles_version_uptodate(self, value): <NEW_LINE> <INDENT> self._lutfiles_version_uptodate = value
A base class for the Atmospheric correction, handling the configuration and LUT download.
62598f9f92d797404e388a77
class MergePR(ClusterMethod): <NEW_LINE> <INDENT> def __init__(self, map): <NEW_LINE> <INDENT> in1 = map["$p"] <NEW_LINE> in2 = map["$r"] <NEW_LINE> outvars = set(in1.vars).union(in2.vars) <NEW_LINE> out = Rigid(outvars) <NEW_LINE> self._inputs = [in1, in2] <NEW_LINE> self._outputs = [out] <NEW_LINE> ClusterMethod.__init__(self) <NEW_LINE> <DEDENT> def _pattern(): <NEW_LINE> <INDENT> pattern = [["point","$p",["$a"]], ["rigid", "$r", ["$a"]]] <NEW_LINE> return pattern2graph(pattern) <NEW_LINE> <DEDENT> pattern = staticmethod(_pattern) <NEW_LINE> patterngraph = _pattern() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> s = "MergePR("+str(self._inputs[0])+"+"+str(self._inputs[1])+"->"+str(self._outputs[0])+")" <NEW_LINE> s += "[" + self.status_str()+"]" <NEW_LINE> return s <NEW_LINE> <DEDENT> def multi_execute(self, inmap): <NEW_LINE> <INDENT> diag_print("MergePR.multi_execute called","clmethods") <NEW_LINE> c1 = self._inputs[0] <NEW_LINE> c2 = self._inputs[1] <NEW_LINE> conf1 = inmap[c1] <NEW_LINE> conf2 = inmap[c2] <NEW_LINE> if len(c1.vars) == 1: <NEW_LINE> <INDENT> return [conf2.copy()] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [conf1.copy()]
Represents a merging of a one-point cluster with any other rigid The first cluster determines the orientation of the resulting cluster
62598f9f2ae34c7f260aaf02
class ContentLoss(nn.Module): <NEW_LINE> <INDENT> def __init__(self, target, weight): <NEW_LINE> <INDENT> super(ContentLoss, self).__init__() <NEW_LINE> self.target = target.detach() * weight <NEW_LINE> self.weight = weight <NEW_LINE> self.criterion = nn.MSELoss() <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> self.loss = self.criterion.forward(input*self.weight, self.target) <NEW_LINE> self.output = input <NEW_LINE> return self.output <NEW_LINE> <DEDENT> def backward(self, retain_variables=True): <NEW_LINE> <INDENT> self.loss.backward(retain_variables=retain_variables) <NEW_LINE> return self.loss.data[0]
Calculate the loss of the content layers
62598f9f7d847024c075c1e8
class RotationTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): <NEW_LINE> <INDENT> def __init__( self, server_address, RequestHandlerClass, broadcaster, bind_and_activate=True, ): <NEW_LINE> <INDENT> self.broadcaster = broadcaster <NEW_LINE> socketserver.TCPServer.__init__( self, server_address, RequestHandlerClass, bind_and_activate=bind_and_activate )
TCP server will be in its own thread, and handle TCP connection requests.
62598f9f9c8ee8231304007f
class CustomUser(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> uuid = models.CharField(unique=True,auto_created=True,default=uuid.uuid4,editable=False,max_length=50,primary_key=True) <NEW_LINE> email = models.EmailField(_(u'邮箱'), max_length=254, unique=True) <NEW_LINE> username = models.CharField(_(u'用户名'), max_length=30, unique=True) <NEW_LINE> first_name = models.CharField(_('first name'), max_length=30, blank=True) <NEW_LINE> last_name = models.CharField(_('last name'), max_length=30, blank=True) <NEW_LINE> department = models.ForeignKey(Department, blank=True, null=True,related_name='users', verbose_name="部门",on_delete=models.SET_NULL) <NEW_LINE> mobile = models.CharField(_(u'手机'), max_length=30, blank=False, validators=[validators.RegexValidator(r'^[0-9+()-]+$', _('Enter a valid mobile number.'), 'invalid')]) <NEW_LINE> session_key = models.CharField(max_length=60, blank=True, null=True, verbose_name=u"session_key") <NEW_LINE> user_key = models.TextField(blank=True, null=True, verbose_name=u"用户登录key") <NEW_LINE> menu_status = models.BooleanField(default=False, verbose_name=u'用户菜单状态') <NEW_LINE> user_active = models.BooleanField(verbose_name=u'设置密码状态', default=0) <NEW_LINE> is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) <NEW_LINE> is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) <NEW_LINE> date_joined = models.DateTimeField(_('date joined'), default=timezone.now) <NEW_LINE> objects = CustomUserManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = [] <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.first_name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _('user') <NEW_LINE> verbose_name_plural = _('users') <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> full_name = '%s %s' % (self.first_name, self.last_name) <NEW_LINE> return full_name.strip() <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.first_name <NEW_LINE> <DEDENT> def email_user(self, subject, message, from_email=None): <NEW_LINE> <INDENT> send_mail(subject, message, from_email, [self.email])
A fully featured User model with admin-compliant permissions that uses a full-length email field as the username. Email and password are required. Other fields are optional.
62598f9f45492302aabfc2f9
class AxisGenerator(object): <NEW_LINE> <INDENT> LOGGER = logging.getLogger(__name__) <NEW_LINE> @staticmethod <NEW_LINE> def _subdivide_circle(centre, n_lines, random_radius=False): <NEW_LINE> <INDENT> segment_list = [] <NEW_LINE> for i in xrange(0, n_lines): <NEW_LINE> <INDENT> angle = radians(i * (360/n_lines)) <NEW_LINE> x0, y0 = centre <NEW_LINE> cos_ = cos(angle) <NEW_LINE> sin_ = sin(angle) <NEW_LINE> if abs(cos_) < 0.000000001: <NEW_LINE> <INDENT> cos_ = 0 <NEW_LINE> <DEDENT> if abs(sin_) < 0.000000001: <NEW_LINE> <INDENT> sin_ = 0 <NEW_LINE> <DEDENT> r = 1 if not random_radius else random.uniform(1, 3) <NEW_LINE> x1 = x0 + r * cos_ <NEW_LINE> y1 = y0 + r * sin_ <NEW_LINE> segment = [x0, x1, y0, y1] <NEW_LINE> segment_list.append(segment) <NEW_LINE> <DEDENT> return segment_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _generate_weights(no_weights, random_weights=False): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def generate_star_axis(axis_labels, weight_list=None, random_weights=True): <NEW_LINE> <INDENT> no_axis = len(axis_labels) <NEW_LINE> segment_list = AxisGenerator._subdivide_circle((0, 0), no_axis) <NEW_LINE> df = pd.DataFrame(segment_list, axis_labels, columns=["x0", "x1", "y0", "y1"]) <NEW_LINE> return df
Static class with methods to generate DataFrames representing axis
62598f9f97e22403b383ad2e
class TranslationNotFound(BaseError): <NEW_LINE> <INDENT> def __init__(self, val, message='No translation was found using the current translator. Try another translator?'): <NEW_LINE> <INDENT> super(TranslationNotFound, self).__init__(val, message)
exception thrown if no translation was found for the text provided by the user
62598f9f44b2445a339b687e
class Config: <NEW_LINE> <INDENT> pass
The config class
62598f9f3539df3088ecc0d7
class GreaterThanZeroInt( GreaterThanZero ): <NEW_LINE> <INDENT> def __set__( self, inst, value ): <NEW_LINE> <INDENT> super( GreaterThanZeroInt, self ).__set__( inst, int( value ) )
Force value to be a Int
62598f9f32920d7e50bc5e79
class Genetic_Algorithm(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def select_parents(self, population, num_parents): <NEW_LINE> <INDENT> parents_by_fitness = population[0:int(num_parents * cv.PARENTS_BY_FITNESS_PERCENT)] <NEW_LINE> proper_parents = [x for x in population if x.strength_raito >cv.SAFETY_FACTOR][ 0:int(num_parents * cv.PROPER_PARENTS_PERCENT)] <NEW_LINE> population_copy = copy.deepcopy(population) <NEW_LINE> population_copy.sort(key = lambda c: np.abs(c.strength_raito - cv.SAFETY_FACTOR)) <NEW_LINE> remain_number = num_parents - len(parents_by_fitness) - len(proper_parents) <NEW_LINE> parents_by_constraint = population_copy[0:remain_number] <NEW_LINE> return parents_by_fitness + proper_parents + parents_by_constraint <NEW_LINE> <DEDENT> def crossover(self, parents, offspring_number): <NEW_LINE> <INDENT> offspring = [] <NEW_LINE> while(len(offspring) < offspring_number): <NEW_LINE> <INDENT> p1_pos = int(np.random.randint(0, len(parents), 1)) <NEW_LINE> p2_pos = int(np.random.randint(0, len(parents), 1)) <NEW_LINE> p1_angle_list = parents[p1_pos].angle_list <NEW_LINE> p2_angle_list = parents[p2_pos].angle_list <NEW_LINE> p1_height_list = parents[p1_pos].height_list <NEW_LINE> p2_height_list = parents[p2_pos].height_list <NEW_LINE> p1_material_list = parents[p1_pos].material_list <NEW_LINE> p2_material_list = parents[p2_pos].material_list <NEW_LINE> child = copy.deepcopy(parents[0]) <NEW_LINE> random_number = int(np.random.randint(0,4,1)) <NEW_LINE> child.angle_list = get_combine_offspring_list(p1_angle_list, p2_angle_list,random_number) <NEW_LINE> child.height_list = get_combine_offspring_list(p1_height_list,p2_height_list,random_number) <NEW_LINE> child.material_list = get_combine_offspring_list(p1_material_list, p2_material_list,random_number) <NEW_LINE> child.fitness = -1 <NEW_LINE> offspring.append(child) <NEW_LINE> <DEDENT> return offspring <NEW_LINE> <DEDENT> def mutation(self, offspring, mutation_percent=0.5): <NEW_LINE> <INDENT> for i in range(len(offspring)): <NEW_LINE> <INDENT> if(np.random.rand() > 1 - mutation_percent): <NEW_LINE> <INDENT> get_chromosome_mutation(offspring[i].angle_list,cv.ANGLE) <NEW_LINE> get_chromosome_mutation(offspring[i].material_list,cv.MATERIAL) <NEW_LINE> <DEDENT> <DEDENT> return
Docstring for Genetic_Algorithm.
62598f9f85dfad0860cbf986
class FUNCKIND(Enum,IComparable,IFormattable,IConvertible): <NEW_LINE> <INDENT> def __eq__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __format__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ge__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __gt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __le__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __lt__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __ne__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __reduce_ex__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self,*args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> FUNC_DISPATCH=None <NEW_LINE> FUNC_NONVIRTUAL=None <NEW_LINE> FUNC_PUREVIRTUAL=None <NEW_LINE> FUNC_STATIC=None <NEW_LINE> FUNC_VIRTUAL=None <NEW_LINE> value__=None
Use System.Runtime.InteropServices.ComTypes.FUNCKIND instead. enum FUNCKIND,values: FUNC_DISPATCH (4),FUNC_NONVIRTUAL (2),FUNC_PUREVIRTUAL (1),FUNC_STATIC (3),FUNC_VIRTUAL (0)
62598f9f76e4537e8c3ef3da
class MypyFileItem(MypyItem): <NEW_LINE> <INDENT> def runtest(self): <NEW_LINE> <INDENT> results = MypyResults.from_session(self.session) <NEW_LINE> abspath = os.path.abspath(str(self.fspath)) <NEW_LINE> errors = results.abspath_errors.get(abspath) <NEW_LINE> if errors: <NEW_LINE> <INDENT> raise MypyError(file_error_formatter(self, results, errors)) <NEW_LINE> <DEDENT> <DEDENT> def reportinfo(self): <NEW_LINE> <INDENT> return ( self.fspath, None, self.config.invocation_dir.bestrelpath(self.fspath), )
A check for Mypy errors in a File.
62598f9f3539df3088ecc0d8
class GrpcRequestLogger(grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor): <NEW_LINE> <INDENT> def __init__(self, log_file): <NEW_LINE> <INDENT> self.log_file = log_file <NEW_LINE> with open(self.log_file, 'w') as f: <NEW_LINE> <INDENT> f.write("") <NEW_LINE> <DEDENT> <DEDENT> def log_message(self, method_name, body): <NEW_LINE> <INDENT> with open(self.log_file, 'a') as f: <NEW_LINE> <INDENT> ts = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] <NEW_LINE> msg = str(body) <NEW_LINE> f.write("\n[%s] %s\n---\n" % (ts, method_name)) <NEW_LINE> if len(msg) < MSG_LOG_MAX_LEN: <NEW_LINE> <INDENT> f.write(str(body)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> f.write("Message too long (%d bytes)! Skipping log...\n" % len(msg)) <NEW_LINE> <DEDENT> f.write('---\n') <NEW_LINE> <DEDENT> <DEDENT> def intercept_unary_unary(self, continuation, client_call_details, request): <NEW_LINE> <INDENT> self.log_message(client_call_details.method, request) <NEW_LINE> return continuation(client_call_details, request) <NEW_LINE> <DEDENT> def intercept_unary_stream(self, continuation, client_call_details, request): <NEW_LINE> <INDENT> self.log_message(client_call_details.method, request) <NEW_LINE> return continuation(client_call_details, request)
Implementation of a gRPC interceptor that logs request to a file
62598fa00c0af96317c561a4
@register_heartbeat_backend <NEW_LINE> @zope.interface.implementer(IHeartbeatBackend) <NEW_LINE> @zope.component.adapter(IClient) <NEW_LINE> class NoOpHeartbeatBackendForClient(_BaseHeartbeatBackend): <NEW_LINE> <INDENT> name = 'noop_heartbeat_backend' <NEW_LINE> async def handle_heartbeat(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def handle_timeout(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def configure(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> async def stop(self): <NEW_LINE> <INDENT> pass
No op Heartbeat
62598fa05fdd1c0f98e5ddbc
class Waiter(BaseHandler): <NEW_LINE> <INDENT> def __init__(self, name, matcher, stream=None): <NEW_LINE> <INDENT> BaseHandler.__init__(self, name, matcher, stream=stream) <NEW_LINE> self._payload = queue.Queue() <NEW_LINE> <DEDENT> def prerun(self, payload): <NEW_LINE> <INDENT> self._payload.put(payload) <NEW_LINE> <DEDENT> def run(self, payload): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def wait(self, timeout=None): <NEW_LINE> <INDENT> if timeout is None: <NEW_LINE> <INDENT> timeout = self.stream.response_timeout <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> stanza = self._payload.get(True, timeout) <NEW_LINE> <DEDENT> except queue.Empty: <NEW_LINE> <INDENT> stanza = False <NEW_LINE> log.warning("Timed out waiting for %s" % self.name) <NEW_LINE> <DEDENT> self.stream.removeHandler(self.name) <NEW_LINE> return stanza <NEW_LINE> <DEDENT> def check_delete(self): <NEW_LINE> <INDENT> return True
The Waiter handler allows an event handler to block until a particular stanza has been received. The handler will either be given the matched stanza, or False if the waiter has timed out. Methods: check_delete -- Overrides BaseHandler.check_delete prerun -- Overrides BaseHandler.prerun run -- Overrides BaseHandler.run wait -- Wait for a stanza to arrive and return it to an event handler.
62598fa091f36d47f2230db2
class ScreenStitchSession(models.Model): <NEW_LINE> <INDENT> key_name = models.CharField(max_length=32) <NEW_LINE> timestamp = models.DateTimeField(auto_now_add=True) <NEW_LINE> connected = models.BooleanField(default=False)
Bare bones model for a session between a client and a host. This is currently setup to only have one connection, since the connected field is Boolean, its either connected or not. The timestamp can be used to delete old sessions if they don't get deleted when the host disconnects.
62598fa0f7d966606f747e05
class CIMStorageVolume(LogicalDisk, CIMComponent): <NEW_LINE> <INDENT> def getRRDTemplates(self): <NEW_LINE> <INDENT> templates = [] <NEW_LINE> for tname in [self.__class__.__name__]: <NEW_LINE> <INDENT> templ = self.getRRDTemplateByName(tname) <NEW_LINE> if templ: templates.append(templ) <NEW_LINE> <DEDENT> return templates
StorageVolume object
62598fa04e4d562566372247
class DiskCache(QNetworkDiskCache): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super().__init__(parent) <NEW_LINE> cache_dir = standarddir.get(QStandardPaths.CacheLocation) <NEW_LINE> self.setCacheDirectory(os.path.join(cache_dir, 'http')) <NEW_LINE> self.setMaximumCacheSize(config.get('storage', 'cache-size')) <NEW_LINE> objreg.get('config').changed.connect(self.cache_size_changed) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return utils.get_repr(self, size=self.cacheSize(), maxsize=self.maximumCacheSize(), path=self.cacheDirectory()) <NEW_LINE> <DEDENT> @config.change_filter('storage', 'cache-size') <NEW_LINE> def cache_size_changed(self): <NEW_LINE> <INDENT> self.setMaximumCacheSize(config.get('storage', 'cache-size'))
Disk cache which sets correct cache dir and size.
62598fa06fb2d068a7693d46
class Analysis: <NEW_LINE> <INDENT> def __init__(self, minimizer, main_config, mc_config=None): <NEW_LINE> <INDENT> self.config = main_config <NEW_LINE> self.minimizer = minimizer <NEW_LINE> self.mc_config = mc_config <NEW_LINE> pass <NEW_LINE> <DEDENT> def chi2_scan(self): <NEW_LINE> <INDENT> if 'chi2 scan' not in self.config: <NEW_LINE> <INDENT> raise ValueError('Called chi2_scan, but no config specified in' ' main.ini. Add a "[chi2 scan]" section to main.') <NEW_LINE> <DEDENT> self.grids = {} <NEW_LINE> for param, value in self.config.items('chi2 scan'): <NEW_LINE> <INDENT> par_config = value.split() <NEW_LINE> start = float(par_config[0]) <NEW_LINE> end = float(par_config[1]) <NEW_LINE> num_points = int(par_config[2]) <NEW_LINE> self.grids[param] = np.linspace(start, end, num_points) <NEW_LINE> <DEDENT> dim = len(self.grids.keys()) <NEW_LINE> if dim > 2: <NEW_LINE> <INDENT> raise ValueError('chi2_scan only supports one/two parameter scans') <NEW_LINE> <DEDENT> sample_params = {} <NEW_LINE> sample_params['fix'] = {} <NEW_LINE> sample_params['values'] = {} <NEW_LINE> sample_params['errors'] = {} <NEW_LINE> for param in self.grids.keys(): <NEW_LINE> <INDENT> sample_params['fix'][param] = True <NEW_LINE> sample_params['errors'][param] = 0. <NEW_LINE> <DEDENT> self.scan_results = [] <NEW_LINE> par1 = list(self.grids.keys())[0] <NEW_LINE> if dim == 1: <NEW_LINE> <INDENT> for i, value in enumerate(self.grids[par1]): <NEW_LINE> <INDENT> sample_params['values'][par1] = value <NEW_LINE> self.minimizer.minimize(sample_params) <NEW_LINE> result = self.minimizer.values <NEW_LINE> result['fval'] = self.minimizer.fmin.fval <NEW_LINE> self.scan_results.append(result) <NEW_LINE> print('INFO: finished chi2scan iteration {} of {}'.format( i + 1, len(self.grids[par1]))) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> par2 = list(self.grids.keys())[1] <NEW_LINE> for i, value_1 in enumerate(self.grids[par1]): <NEW_LINE> <INDENT> for j, value_2 in enumerate(self.grids[par2]): <NEW_LINE> <INDENT> sample_params['values'][par1] = value_1 <NEW_LINE> sample_params['values'][par2] = value_2 <NEW_LINE> self.minimizer.minimize(sample_params) <NEW_LINE> result = self.minimizer.values <NEW_LINE> result['fval'] = self.minimizer.fmin.fval <NEW_LINE> self.scan_results.append(result) <NEW_LINE> print('INFO: finished chi2scan iteration {} of {}'.format( i * len(self.grids[par2]) + j + 1, len(self.grids[par1]) * len(self.grids[par2]))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return self.scan_results
Vega analysis class. - Compute parameter scan - Create Monte Carlo realizations of the data - Run FastMC analysis
62598fa0e1aae11d1e7ce736
class CornersProblem(search.SearchProblem): <NEW_LINE> <INDENT> def __init__(self, startingGameState): <NEW_LINE> <INDENT> self.walls = startingGameState.getWalls() <NEW_LINE> self.startingPosition = startingGameState.getPacmanPosition() <NEW_LINE> top, right = self.walls.height-2, self.walls.width-2 <NEW_LINE> self.corners = ((1,1), (1,top), (right, 1), (right, top)) <NEW_LINE> for corner in self.corners: <NEW_LINE> <INDENT> if not startingGameState.hasFood(*corner): <NEW_LINE> <INDENT> print('Warning: no food in corner ' + str(corner)) <NEW_LINE> <DEDENT> <DEDENT> self._expanded = 0 <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> self.visualize = True <NEW_LINE> self._visited, self._visitedlist = {}, [] <NEW_LINE> <DEDENT> def getStartState(self): <NEW_LINE> <INDENT> return (self.startingPosition, self.corners) <NEW_LINE> <DEDENT> def isGoalState(self, state): <NEW_LINE> <INDENT> isGoal = state[1] <NEW_LINE> if isGoal and self.visualize: <NEW_LINE> <INDENT> self._visitedlist.append(state[0]) <NEW_LINE> import __main__ <NEW_LINE> if '_display' in dir(__main__): <NEW_LINE> <INDENT> if 'drawExpandedCells' in dir(__main__._display): <NEW_LINE> <INDENT> __main__._display.drawExpandedCells(self._visitedlist) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return isGoal <NEW_LINE> <DEDENT> def getSuccessors(self, state): <NEW_LINE> <INDENT> successors = [] <NEW_LINE> for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]: <NEW_LINE> <INDENT> x, y = state[0] <NEW_LINE> dx, dy = Actions.directionToVector(action) <NEW_LINE> nextx, nexty = int(x + dx), int(y + dy) <NEW_LINE> if not self.walls[nextx][nexty]: <NEW_LINE> <INDENT> next_pos = (nextx, nexty) <NEW_LINE> cost = 1 <NEW_LINE> if next_pos in state[1]: <NEW_LINE> <INDENT> next_corners = state[1][:] <NEW_LINE> next_corners.remove(next_pos) <NEW_LINE> successors.append(((next_pos, next_corners), action, cost)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> successors.append(((next_pos, state[1]), action, cost)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self._expanded += 1 <NEW_LINE> if state[0] not in self._visited: <NEW_LINE> <INDENT> self._visited[state[0]] = True <NEW_LINE> self._visitedlist.append(state[0]) <NEW_LINE> <DEDENT> return successors <NEW_LINE> <DEDENT> def getCostOfActions(self, actions): <NEW_LINE> <INDENT> if actions == None: return 999999 <NEW_LINE> x,y= self.startingPosition <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> dx, dy = Actions.directionToVector(action) <NEW_LINE> x, y = int(x + dx), int(y + dy) <NEW_LINE> if self.walls[x][y]: return 999999 <NEW_LINE> <DEDENT> return len(actions)
This search problem finds paths through all four corners of a layout. You must select a suitable state space and successor function
62598fa0e76e3b2f99fd885b
class Message: <NEW_LINE> <INDENT> magic: int <NEW_LINE> message_type: MessageType <NEW_LINE> src_id: int <NEW_LINE> local_time: int <NEW_LINE> payload_len: int <NEW_LINE> payload: bytes <NEW_LINE> def __init__(self, msg_type: MessageType, src_id: int, local_time=0, payload=b''): <NEW_LINE> <INDENT> self.magic = MESSAGE_MAGIC <NEW_LINE> self.message_type = msg_type <NEW_LINE> self.src_id = src_id <NEW_LINE> self.local_time = local_time <NEW_LINE> self.payload = payload <NEW_LINE> self.payload_len = len(self.payload) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_bytes(msg: bytes) -> 'Message': <NEW_LINE> <INDENT> header = msg[:12] <NEW_LINE> payload = msg[12:] <NEW_LINE> magic, type, src, local_time, payload_len = struct.unpack('>HHHIH', header) <NEW_LINE> assert magic == MESSAGE_MAGIC <NEW_LINE> return Message(type, src, local_time, payload) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_socket(handle: socket) -> 'Message': <NEW_LINE> <INDENT> header = handle.recv(12) <NEW_LINE> if len(header) == 0: <NEW_LINE> <INDENT> return Message(None, -1) <NEW_LINE> <DEDENT> payload = b'' <NEW_LINE> magic, type, src_id, local_time, payload_len = struct.unpack('>HHHIH', header) <NEW_LINE> assert magic == MESSAGE_MAGIC <NEW_LINE> if payload_len != 0: <NEW_LINE> <INDENT> payload = handle.recv(payload_len) <NEW_LINE> <DEDENT> return Message(type, src_id, local_time, payload) <NEW_LINE> <DEDENT> def to_bytes(self) -> bytes: <NEW_LINE> <INDENT> fmt = f'>HHHIH{self.payload_len}s' <NEW_LINE> return struct.pack(fmt, self.magic, self.message_type, self.src_id, self.local_time, self.payload_len, self.payload)
Класс, представляющий сообщение, которыми обмениваются процессы распределённой системы.
62598fa0462c4b4f79dbb82f
class UserCredentials(object): <NEW_LINE> <INDENT> def __init__(self, app_info, user_id, credentials): <NEW_LINE> <INDENT> self.app_info = app_info <NEW_LINE> self.user_id = user_id <NEW_LINE> self._credentials = credentials <NEW_LINE> <DEDENT> def credentials(self): <NEW_LINE> <INDENT> return self._credentials <NEW_LINE> <DEDENT> def set_new_credentials(self, new_credentials): <NEW_LINE> <INDENT> self._credentials = new_credentials <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "UserCredentials(user=%r) for app %r.%r" % (self.user_id, self.app_info.provider_name, self.app_info.app_name)
This class holds user_id and credentials (password or OAuth2 tokens). Credentials is a dictionary here.
62598fa0097d151d1a2c0e4c
class ReceiveSMSHandler(BaseHandler): <NEW_LINE> <INDENT> allowed_methods = ('GET',) <NEW_LINE> exclude = ('user',) <NEW_LINE> @throttle(60, 60) <NEW_LINE> def read(self, request): <NEW_LINE> <INDENT> form = forms.ReceivedSMSForm({ 'user': request.user.pk, 'to_msisdn': request.GET.get('r'), 'from_msisdn': request.GET.get('s'), 'message': request.GET.get('text'), 'transport_name': 'E-scape', 'transport_msg_id': request.GET.get('smsc'), 'received_at': datetime.utcnow() }) <NEW_LINE> if not form.is_valid(): <NEW_LINE> <INDENT> raise FormValidationError(form) <NEW_LINE> <DEDENT> receive_sms = form.save() <NEW_LINE> logging.debug('Receiving an SMS from: %s' % receive_sms.from_msisdn) <NEW_LINE> signals.sms_received.send(sender=ReceivedSMS, instance=receive_sms, pk=receive_sms.pk) <NEW_LINE> response = rc.ALL_OK <NEW_LINE> response.content = '' <NEW_LINE> return response
NOTE: This gateway sends the variables to us via GET instead of POST.
62598fa04428ac0f6e65834f
class funcional_analyzer(object): <NEW_LINE> <INDENT> pass
This class is in charge of parsing given functions and parameters of environment and providing class <environment_properties> with needed input data TODO
62598fa0e64d504609df92ca
class Bcf( Binary): <NEW_LINE> <INDENT> edam_format = "format_3020" <NEW_LINE> edam_data = "data_3498" <NEW_LINE> file_ext = "bcf" <NEW_LINE> MetadataElement( name="bcf_index", desc="BCF Index File", param=metadata.FileParameter, file_ext="csi", readonly=True, no_value=None, visible=False, optional=True ) <NEW_LINE> def sniff( self, filename ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> header = gzip.open( filename ).read(3) <NEW_LINE> if binascii.b2a_hex( header ) == binascii.hexlify( 'BCF' ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def set_meta( self, dataset, overwrite=True, **kwd ): <NEW_LINE> <INDENT> index_file = dataset.metadata.bcf_index <NEW_LINE> if not index_file: <NEW_LINE> <INDENT> index_file = dataset.metadata.spec['bcf_index'].param.new_file( dataset=dataset ) <NEW_LINE> <DEDENT> dataset_symlink = os.path.join( os.path.dirname( index_file.file_name ), '__dataset_%d_%s' % ( dataset.id, os.path.basename( index_file.file_name ) ) ) <NEW_LINE> os.symlink( dataset.file_name, dataset_symlink ) <NEW_LINE> stderr_name = tempfile.NamedTemporaryFile( prefix="bcf_index_stderr" ).name <NEW_LINE> command = [ 'bcftools', 'index', dataset_symlink ] <NEW_LINE> try: <NEW_LINE> <INDENT> subprocess.check_call( args=command, stderr=open( stderr_name, 'wb' ) ) <NEW_LINE> shutil.move( dataset_symlink + '.csi', index_file.file_name ) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> stderr = open( stderr_name ).read().strip() <NEW_LINE> raise Exception('Error setting BCF metadata: %s' % (stderr or str(e))) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.remove( stderr_name ) <NEW_LINE> os.remove( dataset_symlink ) <NEW_LINE> <DEDENT> dataset.metadata.bcf_index = index_file
Class describing a BCF file
62598fa030dc7b766599f671
class DestinyEntitiesItemsDestinyItemSocketsComponent(object): <NEW_LINE> <INDENT> swagger_types = { 'sockets': 'list[DestinyEntitiesItemsDestinyItemSocketState]' } <NEW_LINE> attribute_map = { 'sockets': 'sockets' } <NEW_LINE> def __init__(self, sockets=None): <NEW_LINE> <INDENT> self._sockets = None <NEW_LINE> self.discriminator = None <NEW_LINE> if sockets is not None: <NEW_LINE> <INDENT> self.sockets = sockets <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def sockets(self): <NEW_LINE> <INDENT> return self._sockets <NEW_LINE> <DEDENT> @sockets.setter <NEW_LINE> def sockets(self, sockets): <NEW_LINE> <INDENT> self._sockets = sockets <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> 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, DestinyEntitiesItemsDestinyItemSocketsComponent): <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.
62598fa0d486a94d0ba2bdf9
class dataset: <NEW_LINE> <INDENT> def __init__(self, alias, fullpath, isData, unitsPerJob=1, totalUnits=1, splitting='FileBased', priority=1, inputDBS='global', label='', doHLT=1, doJetFilter=0): <NEW_LINE> <INDENT> self.alias = alias <NEW_LINE> self.fullpath = fullpath <NEW_LINE> self.isData = isData <NEW_LINE> self.unitsPerJob = unitsPerJob <NEW_LINE> self.totalUnits = totalUnits <NEW_LINE> self.splitting = splitting <NEW_LINE> self.priority = priority <NEW_LINE> self.inputDBS = inputDBS <NEW_LINE> self.label = label <NEW_LINE> self.doHLT = doHLT <NEW_LINE> self.doJetFilter = doJetFilter
Simple class to hold information relevant to a given dataset for CRAB jobs. label is unused member that can be used to hold extra information specific to each MultiCRAB config. E.g. dataset("WJetsToLNuInclusive", "/WJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v1/AODSIM", MC, 1000, 1000000, 10, 'EventBased', 'WJet')
62598fa024f1403a926857c4
class TestSiteObjectDeprecatedFunctions(DefaultSiteTestCase, DeprecationTestCase): <NEW_LINE> <INDENT> cached = True <NEW_LINE> user = True <NEW_LINE> def test_live_version(self): <NEW_LINE> <INDENT> mysite = self.get_site() <NEW_LINE> ver = mysite.live_version() <NEW_LINE> self.assertIsInstance(ver, tuple) <NEW_LINE> self.assertTrue(all(isinstance(ver[i], int) for i in (0, 1))) <NEW_LINE> self.assertIsInstance(ver[2], basestring) <NEW_LINE> <DEDENT> def test_token(self): <NEW_LINE> <INDENT> mysite = self.get_site() <NEW_LINE> mainpage = self.get_mainpage() <NEW_LINE> ttype = "edit" <NEW_LINE> try: <NEW_LINE> <INDENT> token = mysite.tokens[ttype] <NEW_LINE> <DEDENT> except pywikibot.Error as error_msg: <NEW_LINE> <INDENT> self.assertRegex( unicode(error_msg), "Action '[a-z]+' is not allowed for user .* on .* wiki.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.assertEqual(token, mysite.token(mainpage, ttype)) <NEW_LINE> self.assertDeprecation("pywikibot.site.APISite.token is deprecated" ", use the 'tokens' property instead.")
Test cases for Site deprecated methods.
62598fa0d268445f26639a95
class Account: <NEW_LINE> <INDENT> def __init__(self, account, password, proxy=None): <NEW_LINE> <INDENT> self.account = account <NEW_LINE> self.password = password <NEW_LINE> self._proxy = proxy <NEW_LINE> self._token = None <NEW_LINE> <DEDENT> def _parse_token(self, response=None): <NEW_LINE> <INDENT> token_url = 'https://tinychat.com/start?#signin' <NEW_LINE> if response is None: <NEW_LINE> <INDENT> response = web.get( url=token_url, referer=token_url, proxy=self._proxy) <NEW_LINE> <DEDENT> if len(response.errors) > 0: <NEW_LINE> <INDENT> log.error(response.errors) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> soup = BeautifulSoup(response.content, 'html.parser') <NEW_LINE> token = soup.find(attrs={'name': 'csrf-token'}) <NEW_LINE> self._token = token['content'] <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def logout(): <NEW_LINE> <INDENT> cookies = ['user', 'pass', 'hash'] <NEW_LINE> for cookie in cookies: <NEW_LINE> <INDENT> web.WebSession.delete_cookie(cookie) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def is_logged_in(): <NEW_LINE> <INDENT> has_cookie = web.WebSession.has_cookie('pass') <NEW_LINE> if has_cookie: <NEW_LINE> <INDENT> is_expired = web.WebSession.is_cookie_expired('pass') <NEW_LINE> if is_expired: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> if self._token is None: <NEW_LINE> <INDENT> self._parse_token() <NEW_LINE> <DEDENT> url = 'https://tinychat.com/login' <NEW_LINE> form_data = { 'login_username': self.account, 'login_password': self.password, 'remember': '1', 'next': 'https://tinychat.com/', '_token': self._token } <NEW_LINE> login_response = web.post(url=url, data=form_data, proxy=self._proxy) <NEW_LINE> self._parse_token(response=login_response) <NEW_LINE> return self.is_logged_in()
This class contains methods to do login/logout and check if logged in or not.
62598fa0009cb60464d01349
class FloatField(Field): <NEW_LINE> <INDENT> def __init__(self, name=None, primary_key=False, default=None, ddl='FLOAT'): <NEW_LINE> <INDENT> super().__init__(name, ddl, primary_key, default)
浮点类型
62598fa04e4d562566372248
class Miscellanea(ListTableBase): <NEW_LINE> <INDENT> Columns = [ Column('name', align=QtCore.Qt.AlignLeft, editable=True), Column('mtype', 'Type', align=QtCore.Qt.AlignCenter, editable=True), Column('useFor', editable=True), Column('amount', editable=True), Column('timing.use', editable=True), Column('timing.duration', editable=True), ] <NEW_LINE> @property <NEW_LINE> def salts(self): <NEW_LINE> <INDENT> return [item for item in self.items if item.mtype.lower() == 'water agent' and 'acid' not in item.name.lower()] <NEW_LINE> <DEDENT> @property <NEW_LINE> def mashSalts(self): <NEW_LINE> <INDENT> return [salt for salt in self.salts if salt.timing.use.lower() == 'mash'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def kettleSalts(self): <NEW_LINE> <INDENT> return [salt for salt in self.salts if salt.timing.use.lower() == 'boil'] <NEW_LINE> <DEDENT> @property <NEW_LINE> def acids(self): <NEW_LINE> <INDENT> return [item for item in self.items if item.mtype.lower() == 'water agent' and 'acid' in item.name.lower()] <NEW_LINE> <DEDENT> def from_excel(self, worksheet): <NEW_LINE> <INDENT> raise NotImplementedError('Miscellaneous items are not defined in Excel libraries.') <NEW_LINE> <DEDENT> def sort(self): <NEW_LINE> <INDENT> self.items.sort(key=lambda misc: (-misc.amount.root, misc.name)) <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> return [item.to_dict() for item in self] <NEW_LINE> <DEDENT> def from_dict(self, recipe, data): <NEW_LINE> <INDENT> for item in data: <NEW_LINE> <INDENT> misc = Miscellaneous(recipe) <NEW_LINE> misc.from_dict(item) <NEW_LINE> self.append(misc) <NEW_LINE> <DEDENT> self.resize()
Provides for a list of misc objects, specifically created to aid in parsing Excel database files and display within a QtTableView.
62598fa02c8b7c6e89bd35eb
class StreamUpdate: <NEW_LINE> <INDENT> update_id: UUID <NEW_LINE> update_moment: datetime <NEW_LINE> update_type: StreamUpdateType <NEW_LINE> raw_data: Dict[str, any] <NEW_LINE> def __init__(self, update_moment: datetime, update_type: StreamUpdateType, acct_info: dict = None, symbol: str = None, candle: dict = None, order: dict = None): <NEW_LINE> <INDENT> self.update_id = uuid.uuid4() <NEW_LINE> self.update_moment = update_moment <NEW_LINE> self.update_type = update_type <NEW_LINE> self.raw_data = { 'acct_info': acct_info, 'symbol' : symbol, 'candle' : candle, 'order' : order} <NEW_LINE> <DEDENT> def get_symbol(self) -> str: <NEW_LINE> <INDENT> return self.raw_data['symbol'] <NEW_LINE> <DEDENT> def get_candle(self) -> Candle: <NEW_LINE> <INDENT> return None if self.raw_data['candle'] is None else Candle.from_json(self.raw_data['candle']) <NEW_LINE> <DEDENT> def get_order(self) -> Optional[Order]: <NEW_LINE> <INDENT> return None if self.raw_data['order'] is None else Order.from_json(self.raw_data['order']) <NEW_LINE> <DEDENT> def get_acct_info(self) -> AccountInfo: <NEW_LINE> <INDENT> return AccountInfo.from_json(self.raw_data['acct_info']) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, json_data: Dict[str, any]) -> 'StreamUpdate': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> update = StreamUpdate(update_moment=datetime.strptime(json_data['update_moment'], DATE_TIME_FORMAT), update_type=StreamUpdateType[json_data['update_type']], **json_data['raw_data']) <NEW_LINE> update.update_id = UUID(json_data['update_id']) <NEW_LINE> return update <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> traceback.print_exc() <NEW_LINE> <DEDENT> <DEDENT> def to_json(self) -> Dict[str, any]: <NEW_LINE> <INDENT> return { 'update_id' : str(self.update_id), 'update_moment': self.update_moment.strftime(DATE_TIME_FORMAT), 'update_type' : self.update_type.name, 'raw_data' : self.raw_data } <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.update_id == other.update_id
An update from the broker or live data stream, meant to trigger strategy logic.
62598fa03cc13d1c6d465590
class GxWorkspaceFolder(CoClass): <NEW_LINE> <INDENT> _reg_clsid_ = GUID('{A58934AD-0EC4-4B18-9AE3-DE3A7221302B}') <NEW_LINE> _idlflags_ = [] <NEW_LINE> _typelib_path_ = typelib_path <NEW_LINE> _reg_typelib_ = ('{ADC7DE29-DC0B-448E-BBF6-27E4E34CF2EC}', 10, 2)
GxObject that represents a workspace folder.
62598fa0e5267d203ee6b732
class TestStandardCLI(unittest.TestCase): <NEW_LINE> <INDENT> def test_can_call_standard_help(self): <NEW_LINE> <INDENT> command = ['ogo', 'calib', 'standard', '--help'] <NEW_LINE> self.assertTrue(subprocess.check_output(command)) <NEW_LINE> <DEDENT> def test_blank_standard_call_fails(self): <NEW_LINE> <INDENT> command = ['ogo', 'calib', 'standard'] <NEW_LINE> with self.assertRaises(subprocess.CalledProcessError): <NEW_LINE> <INDENT> subprocess.check_output(command, stderr=subprocess.STDOUT)
Test the ogo command line interface for calib standard
62598fa0a79ad16197769e89
class DeleteItem(EWSAccountService, EWSPooledMixIn): <NEW_LINE> <INDENT> SERVICE_NAME = 'DeleteItem' <NEW_LINE> element_container_name = None <NEW_LINE> def call(self, items, delete_type, send_meeting_cancellations, affected_task_occurrences, suppress_read_receipts): <NEW_LINE> <INDENT> return self._pool_requests(payload_func=self.get_payload, **dict( items=items, delete_type=delete_type, send_meeting_cancellations=send_meeting_cancellations, affected_task_occurrences=affected_task_occurrences, suppress_read_receipts=suppress_read_receipts, )) <NEW_LINE> <DEDENT> def get_payload(self, items, delete_type, send_meeting_cancellations, affected_task_occurrences, suppress_read_receipts): <NEW_LINE> <INDENT> from .properties import ItemId, OccurrenceItemId <NEW_LINE> if self.account.version.build >= EXCHANGE_2013_SP1: <NEW_LINE> <INDENT> deleteitem = create_element( 'm:%s' % self.SERVICE_NAME, DeleteType=delete_type, SendMeetingCancellations=send_meeting_cancellations, AffectedTaskOccurrences=affected_task_occurrences, SuppressReadReceipts='true' if suppress_read_receipts else 'false', ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> deleteitem = create_element( 'm:%s' % self.SERVICE_NAME, DeleteType=delete_type, SendMeetingCancellations=send_meeting_cancellations, AffectedTaskOccurrences=affected_task_occurrences, ) <NEW_LINE> <DEDENT> item_ids = create_element('m:ItemIds') <NEW_LINE> for item in items: <NEW_LINE> <INDENT> log.debug('Deleting item %s', item) <NEW_LINE> if getattr(item, 'occurrence_item_id', None): <NEW_LINE> <INDENT> set_xml_value(item_ids, item.occurrence_item_id, version=self.account.version) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> set_xml_value(item_ids, to_item_id(item, ItemId), version=self.account.version) <NEW_LINE> <DEDENT> <DEDENT> if not len(item_ids): <NEW_LINE> <INDENT> raise ValueError('"items" must not be empty') <NEW_LINE> <DEDENT> deleteitem.append(item_ids) <NEW_LINE> return deleteitem
Takes a folder and a list of (id, changekey) tuples. Returns result of deletion as a list of tuples (success[True|False], errormessage), in the same order as the input list. MSDN: https://msdn.microsoft.com/en-us/library/office/aa562961(v=exchg.150).aspx
62598fa021a7993f00c65da8
class BonusFire(Bonus): <NEW_LINE> <INDENT> def __init__(self,cube): <NEW_LINE> <INDENT> Bonus.__init__(self,cube) <NEW_LINE> self.color=(1., 0., 0., .7) <NEW_LINE> <DEDENT> def collect(self,player): <NEW_LINE> <INDENT> Bonus.collect(self,player) <NEW_LINE> player.flameStrength+=1
gives the player extra fire strength
62598fa0baa26c4b54d4f0d4
class LaunchdJob(object): <NEW_LINE> <INDENT> def __init__(self, label, pid=-1, laststatus=""): <NEW_LINE> <INDENT> self._label = label <NEW_LINE> if pid != -1: <NEW_LINE> <INDENT> self._pid = pid <NEW_LINE> <DEDENT> if laststatus != "": <NEW_LINE> <INDENT> self._laststatus = laststatus <NEW_LINE> <DEDENT> self._properties = None <NEW_LINE> self._plist_fname = None <NEW_LINE> <DEDENT> @property <NEW_LINE> def label(self): <NEW_LINE> <INDENT> return self._label <NEW_LINE> <DEDENT> @property <NEW_LINE> def pid(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._pid <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.refresh() <NEW_LINE> return self._pid <NEW_LINE> <DEDENT> @property <NEW_LINE> def laststatus(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._laststatus <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.refresh() <NEW_LINE> return self._laststatus <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def properties(self): <NEW_LINE> <INDENT> if hasattr(self, "_nsproperties"): <NEW_LINE> <INDENT> self._properties = convert_NSDictionary_to_dict(self._nsproperties) <NEW_LINE> del self._nsproperties <NEW_LINE> <DEDENT> if self._properties is None: <NEW_LINE> <INDENT> self.refresh() <NEW_LINE> <DEDENT> return self._properties <NEW_LINE> <DEDENT> def exists(self): <NEW_LINE> <INDENT> return ServiceManagement.SMJobCopyDictionary(None, self.label) is not None <NEW_LINE> <DEDENT> def refresh(self): <NEW_LINE> <INDENT> val = ServiceManagement.SMJobCopyDictionary(None, self.label) <NEW_LINE> if val is None: <NEW_LINE> <INDENT> raise ValueError("job '%s' does not exist" % self.label) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._properties = convert_NSDictionary_to_dict(val) <NEW_LINE> try: <NEW_LINE> <INDENT> self._pid = self._properties["PID"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self._pid = None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._laststatus = self._properties["LastExitStatus"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self._laststatus = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def plistfilename(self): <NEW_LINE> <INDENT> if self._plist_fname is None: <NEW_LINE> <INDENT> self._plist_fname = discover_filename(self.label) <NEW_LINE> <DEDENT> return self._plist_fname
Class to lazily query the properties of the LaunchdJob when accessed.
62598fa00c0af96317c561a7
class Scte20PlusEmbeddedDestinationSettings(AWSProperty): <NEW_LINE> <INDENT> props: PropsDictType = {}
`Scte20PlusEmbeddedDestinationSettings <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-scte20plusembeddeddestinationsettings.html>`__
62598fa0d58c6744b42dc1e5
class ExceptionHandler(AbstractExceptionHandler): <NEW_LINE> <INDENT> def can_handle(self, handler_input, exception): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def handle(self, handler_input, exception): <NEW_LINE> <INDENT> logger.error(exception, exc_info=True) <NEW_LINE> return ( handler_input.response_builder .speak("Es ist ein Fehler aufgetreten. Bitte versuche es erneut.") .ask("Bitte versuche es erneut.") .response )
Generic error handling to capture any syntax or routing errors. If you receive an error stating the request handler chain is not found, you have not implemented a handler for the intent being invoked or included it in the skill builder below.
62598fa0fbf16365ca793edf
class PasteBlock(Action): <NEW_LINE> <INDENT> def execute(self, instance): <NEW_LINE> <INDENT> pass
Editing->Block->Paste
62598fa07cff6e4e811b5849
class DefaultNodeAssignmentBackend(object): <NEW_LINE> <INDENT> implements(INodeAssignment) <NEW_LINE> def __init__(self, service_entry=None, **kw): <NEW_LINE> <INDENT> self._service_entry = service_entry <NEW_LINE> self._metadata = defaultdict(dict) <NEW_LINE> self._flag = defaultdict(bool) <NEW_LINE> <DEDENT> @property <NEW_LINE> def service_entry(self): <NEW_LINE> <INDENT> if self._service_entry is None: <NEW_LINE> <INDENT> settings = get_current_registry().settings <NEW_LINE> self._service_entry = settings.get('tokenserver.service_entry') <NEW_LINE> <DEDENT> return self._service_entry <NEW_LINE> <DEDENT> def get_node(self, email, service): <NEW_LINE> <INDENT> uid = _USERS_UIDS.get(service, {}).get(email, None) <NEW_LINE> if not self._flag[service]: <NEW_LINE> <INDENT> urls = self.get_metadata(service, needs_acceptance=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> urls = None <NEW_LINE> <DEDENT> return uid, self.service_entry, urls <NEW_LINE> <DEDENT> def allocate_node(self, email, service): <NEW_LINE> <INDENT> status = self.get_node(email, service) <NEW_LINE> if status[0] is not None: <NEW_LINE> <INDENT> raise BackendError("Node already assigned") <NEW_LINE> <DEDENT> global _UID <NEW_LINE> uid = _UID <NEW_LINE> _UID += 1 <NEW_LINE> _USERS_UIDS[service][email] = uid <NEW_LINE> return uid, self.service_entry <NEW_LINE> <DEDENT> def set_metadata(self, service, name, value, needs_acceptance=False): <NEW_LINE> <INDENT> self._metadata[service][name] = value, needs_acceptance <NEW_LINE> <DEDENT> def get_metadata(self, service, name=None, needs_acceptance=None): <NEW_LINE> <INDENT> metadata = [] <NEW_LINE> if name is None: <NEW_LINE> <INDENT> items = self._metadata[service].items() <NEW_LINE> for name, (value, _needs_acceptance) in items: <NEW_LINE> <INDENT> if needs_acceptance is not None: <NEW_LINE> <INDENT> if needs_acceptance == _needs_acceptance: <NEW_LINE> <INDENT> metadata.append((name, value, _needs_acceptance)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> metadata.append((name, value, _needs_acceptance)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> value, _needs_acceptance = self._metadata[service][name] <NEW_LINE> if needs_acceptance is not None: <NEW_LINE> <INDENT> if needs_acceptance == _needs_acceptance: <NEW_LINE> <INDENT> metadata.append((name, value, _needs_acceptance)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> metadata.append((name, value, _needs_acceptance)) <NEW_LINE> <DEDENT> <DEDENT> return metadata <NEW_LINE> <DEDENT> def set_accepted_conditions_flag(self, service, value, email=None): <NEW_LINE> <INDENT> self._flag[service] = value
Dead simple NodeAssignment backend always returning the same service entry. This is useful in the case we don't need to deal with multiple services (e.g if someone wants to setup his own tokenserver always using the same node)
62598fa04428ac0f6e658350
class Term(PseudoConst): <NEW_LINE> <INDENT> def __init__(self, a): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.a = a <NEW_LINE> <DEDENT> def return_value(self): <NEW_LINE> <INDENT> if _default_graph.n - self.a >= 0: <NEW_LINE> <INDENT> return(_default_graph.y_true[_default_graph.n - self.a]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('increase the starting number, can not compute U_n-',self.a,' because first value is for n = ',_default_graph.n) <NEW_LINE> return(0)
the output value will be u_n-a a is a positive integer
62598fa01f037a2d8b9e3f0d
class PcapReader(): <NEW_LINE> <INDENT> def __init__(self, filename, link_type=dpkt.pcap.DLT_EN10MB): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.pcap_reader = None <NEW_LINE> try: <NEW_LINE> <INDENT> f = open(self.filename, "r") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logger.error("Could not open %s"%filename) <NEW_LINE> return <NEW_LINE> <DEDENT> self.pcap_reader = dpkt.pcap.Reader(f) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> if self.pcap_reader is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.pcap_reader.__iter__() <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.pcap_reader.close()
Very simple class to create a pcap file from a network stream
62598fa0f548e778e596b3d3
class RedisClient(): <NEW_LINE> <INDENT> def __init__(self,type,host=REDIS_HOST,port=REDIS_PORT,password=REDIS_PASSWORD): <NEW_LINE> <INDENT> self.db = redis.StrictRedis(host=host,port=port,password=password) <NEW_LINE> pass <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> pass
为连接数据库提供封装的方法 
62598fa0656771135c4894a9
class IRequire(Interface): <NEW_LINE> <INDENT> permission = Permission( title=u"Permission ID", description=u"The id of the permission to require.")
Require a permission to access selected module attributes The given permission is required to access any names provided directly in the attributes attribute or any names defined by interfaces listed in the interface attribute.
62598fa0b7558d5895463454
class BuildDefinitionStep(Model): <NEW_LINE> <INDENT> _attribute_map = { 'always_run': {'key': 'alwaysRun', 'type': 'bool'}, 'condition': {'key': 'condition', 'type': 'str'}, 'continue_on_error': {'key': 'continueOnError', 'type': 'bool'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'enabled': {'key': 'enabled', 'type': 'bool'}, 'environment': {'key': 'environment', 'type': '{str}'}, 'inputs': {'key': 'inputs', 'type': '{str}'}, 'ref_name': {'key': 'refName', 'type': 'str'}, 'task': {'key': 'task', 'type': 'TaskDefinitionReference'}, 'timeout_in_minutes': {'key': 'timeoutInMinutes', 'type': 'int'} } <NEW_LINE> def __init__(self, always_run=None, condition=None, continue_on_error=None, display_name=None, enabled=None, environment=None, inputs=None, ref_name=None, task=None, timeout_in_minutes=None): <NEW_LINE> <INDENT> super(BuildDefinitionStep, self).__init__() <NEW_LINE> self.always_run = always_run <NEW_LINE> self.condition = condition <NEW_LINE> self.continue_on_error = continue_on_error <NEW_LINE> self.display_name = display_name <NEW_LINE> self.enabled = enabled <NEW_LINE> self.environment = environment <NEW_LINE> self.inputs = inputs <NEW_LINE> self.ref_name = ref_name <NEW_LINE> self.task = task <NEW_LINE> self.timeout_in_minutes = timeout_in_minutes
BuildDefinitionStep. :param always_run: Indicates whether this step should run even if a previous step fails. :type always_run: bool :param condition: A condition that determines whether this step should run. :type condition: str :param continue_on_error: Indicates whether the phase should continue even if this step fails. :type continue_on_error: bool :param display_name: The display name for this step. :type display_name: str :param enabled: Indicates whether the step is enabled. :type enabled: bool :param environment: :type environment: dict :param inputs: :type inputs: dict :param ref_name: The reference name for this step. :type ref_name: str :param task: The task associated with this step. :type task: :class:`TaskDefinitionReference <build.v4_1.models.TaskDefinitionReference>` :param timeout_in_minutes: The time, in minutes, that this step is allowed to run. :type timeout_in_minutes: int
62598fa0925a0f43d25e7e63
class CoreV2ServicesModelEdgeRouterHosts(object): <NEW_LINE> <INDENT> openapi_types = { 'edge_router_id': 'str', 'server_egress': 'CoreV2ServicesModelServerEgress' } <NEW_LINE> attribute_map = { 'edge_router_id': 'edgeRouterId', 'server_egress': 'serverEgress' } <NEW_LINE> def __init__(self, edge_router_id=None, server_egress=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._edge_router_id = None <NEW_LINE> self._server_egress = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.edge_router_id = edge_router_id <NEW_LINE> self.server_egress = server_egress <NEW_LINE> <DEDENT> @property <NEW_LINE> def edge_router_id(self): <NEW_LINE> <INDENT> return self._edge_router_id <NEW_LINE> <DEDENT> @edge_router_id.setter <NEW_LINE> def edge_router_id(self, edge_router_id): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and edge_router_id is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `edge_router_id`, must not be `None`") <NEW_LINE> <DEDENT> self._edge_router_id = edge_router_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def server_egress(self): <NEW_LINE> <INDENT> return self._server_egress <NEW_LINE> <DEDENT> @server_egress.setter <NEW_LINE> def server_egress(self, server_egress): <NEW_LINE> <INDENT> if self.local_vars_configuration.client_side_validation and server_egress is None: <NEW_LINE> <INDENT> raise ValueError("Invalid value for `server_egress`, must not be `None`") <NEW_LINE> <DEDENT> self._server_egress = server_egress <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_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 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, CoreV2ServicesModelEdgeRouterHosts): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, CoreV2ServicesModelEdgeRouterHosts): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62598fa0a17c0f6771d5c060
class IssueTracker(object): <NEW_LINE> <INDENT> pass
Parent of all IssueTracker objects.
62598fa0a219f33f346c6640
class Collection(SwordHttpHandler): <NEW_LINE> <INDENT> def GET(self, collection): <NEW_LINE> <INDENT> ssslog.debug("GET on Collection (list collection contents); Incoming HTTP headers: " + str(web.ctx.environ)) <NEW_LINE> try: <NEW_LINE> <INDENT> auth = self.http_basic_authenticate(web) <NEW_LINE> <DEDENT> except SwordError as e: <NEW_LINE> <INDENT> return self.manage_error(e) <NEW_LINE> <DEDENT> ss = SwordServer(config, auth) <NEW_LINE> cl = ss.list_collection(collection) <NEW_LINE> web.header("Content-Type", "text/xml") <NEW_LINE> return cl <NEW_LINE> <DEDENT> def POST(self, collection): <NEW_LINE> <INDENT> ssslog.debug("POST to Collection (create new item); Incoming HTTP headers: " + str(web.ctx.environ)) <NEW_LINE> try: <NEW_LINE> <INDENT> auth = self.http_basic_authenticate(web) <NEW_LINE> self.validate_deposit_request(web, "6.3.3", "6.3.1", "6.3.2") <NEW_LINE> deposit = self.get_deposit(web, auth) <NEW_LINE> ss = SwordServer(config, auth) <NEW_LINE> result = ss.deposit_new(collection, deposit) <NEW_LINE> ssslog.info("Item created") <NEW_LINE> web.header("Content-Type", "application/atom+xml;type=entry") <NEW_LINE> web.header("Location", result.location) <NEW_LINE> web.ctx.status = "201 Created" <NEW_LINE> if config.return_deposit_receipt: <NEW_LINE> <INDENT> ssslog.info("Returning deposit receipt") <NEW_LINE> return result.receipt <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ssslog.info("Omitting deposit receipt") <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> except SwordError as e: <NEW_LINE> <INDENT> return self.manage_error(e)
Handle all requests to SWORD/ATOM Collections (these are the collections listed in the Service Document) - Col-URI
62598fa0442bda511e95c280
class NetChop(object): <NEW_LINE> <INDENT> def predict(self, sequences): <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile(suffix=".fsa", mode="w") as input_fd: <NEW_LINE> <INDENT> for (i, sequence) in enumerate(sequences): <NEW_LINE> <INDENT> input_fd.write("> %d\n" % i) <NEW_LINE> input_fd.write(sequence) <NEW_LINE> input_fd.write("\n") <NEW_LINE> <DEDENT> input_fd.flush() <NEW_LINE> try: <NEW_LINE> <INDENT> output = subprocess.check_output(["netChop", input_fd.name]) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as e: <NEW_LINE> <INDENT> logging.error("Error calling netChop: %s:\n%s" % (e, e.output)) <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> parsed = self.parse_netchop(output) <NEW_LINE> assert len(parsed) == len(sequences), "Expected %d results but got %d" % ( len(sequences), len(parsed)) <NEW_LINE> assert [len(x) for x in parsed] == [len(x) for x in sequences] <NEW_LINE> return parsed <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse_netchop(netchop_output): <NEW_LINE> <INDENT> line_iterator = iter(netchop_output.decode().split("\n")) <NEW_LINE> scores = [] <NEW_LINE> for line in line_iterator: <NEW_LINE> <INDENT> if "pos" in line and 'AA' in line and 'score' in line: <NEW_LINE> <INDENT> scores.append([]) <NEW_LINE> if "----" not in next(line_iterator): <NEW_LINE> <INDENT> raise ValueError("Dashes expected") <NEW_LINE> <DEDENT> line = next(line_iterator) <NEW_LINE> while '-------' not in line: <NEW_LINE> <INDENT> score = float(line.split()[3]) <NEW_LINE> scores[-1].append(score) <NEW_LINE> line = next(line_iterator) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return scores
Wrapper around netChop tool. Assumes netChop is in your PATH.
62598fa0a17c0f6771d5c061
class MaxPool2d(_Pooling2d): <NEW_LINE> <INDENT> def __init__(self, kernel_size, stride, padding=0, dilation=1): <NEW_LINE> <INDENT> super().__init__("Max", kernel_size, stride, padding, dilation) <NEW_LINE> self.args = [kernel_size, stride, padding, dilation] <NEW_LINE> <DEDENT> def set_input(self, input_shape): <NEW_LINE> <INDENT> super().set_input(input_shape) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> return super().forward(x)
2-D max pooling layer. Arguments: kernel_size (int): size of kernel to be used for pooling operation stride (int): stride for the kernel in pooling operations padding (int, optional): padding for the image to handle edges while pooling (default: 0) dilation (int, optional): dilation for the pooling operation (default: 1)
62598fa032920d7e50bc5e7d
class SH1106_SPI(_SH1106): <NEW_LINE> <INDENT> def __init__(self, width, height, spi, dc, reset, cs, *, external_vcc=False, baudrate=8000000, polarity=0, phase=0): <NEW_LINE> <INDENT> self.rate = 10 * 1024 * 1024 <NEW_LINE> dc.switch_to_output(value=0) <NEW_LINE> cs.switch_to_output(value=1) <NEW_LINE> self.spi_bus = spi <NEW_LINE> self.spi_bus.try_lock() <NEW_LINE> self.spi_bus.configure(baudrate=baudrate, polarity=polarity, phase=phase) <NEW_LINE> self.spi_bus.unlock() <NEW_LINE> self.dc_pin = dc <NEW_LINE> self.buffer = bytearray((height // 8) * width) <NEW_LINE> framebuffer = framebuf.FrameBuffer1(self.buffer, width, height) <NEW_LINE> super().__init__(framebuffer, width, height, external_vcc, reset) <NEW_LINE> <DEDENT> def write_cmd(self, cmd): <NEW_LINE> <INDENT> self.dc_pin.value = 0 <NEW_LINE> self.spi_bus.try_lock() <NEW_LINE> self.spi_bus.write(bytearray([cmd])) <NEW_LINE> <DEDENT> def write_framebuf(self): <NEW_LINE> <INDENT> self.spi_bus.try_lock() <NEW_LINE> spi_write = self.spi_bus.write <NEW_LINE> write = self.write_cmd <NEW_LINE> for page in range(0, 8): <NEW_LINE> <INDENT> page_mult = (page << 7) <NEW_LINE> write(0xB0 + page) <NEW_LINE> write(0x02) <NEW_LINE> write(0x10) <NEW_LINE> self.dc_pin.value = 1 <NEW_LINE> spi_write(self.buffer, start=page_mult, end=page_mult + self.width) <NEW_LINE> <DEDENT> self.spi_bus.unlock()
SPI class for SH1106 :param width: the width of the physical screen in pixels, :param height: the height of the physical screen in pixels, :param spi: the SPI peripheral to use, :param dc: the data/command pin to use (often labeled "D/C"), :param reset: the reset pin to use, :param cs: the chip-select pin to use (sometimes labeled "SS").
62598fa021bff66bcd722a8a
class install_scripts(_install): <NEW_LINE> <INDENT> description = "Install the Shell Profile (Linux/Unix)" <NEW_LINE> user_options = _install.user_options + [ ('root=', None, "install everything relative to this alternate root directory"), ] <NEW_LINE> boolean_options = _install.boolean_options + ['skip-profile'] <NEW_LINE> profile_filename = 'mysql-utilities.sh' <NEW_LINE> profile_d_dir = '/etc/profile.d/' <NEW_LINE> def initialize_options(self): <NEW_LINE> <INDENT> _install.initialize_options(self) <NEW_LINE> self.skip_profile = False <NEW_LINE> self.root = None <NEW_LINE> self.install_dir = None <NEW_LINE> <DEDENT> def finalize_options(self): <NEW_LINE> <INDENT> _install.finalize_options(self) <NEW_LINE> self.set_undefined_options('install', ('install_dir', 'install_dir'), ('root', 'root')) <NEW_LINE> <DEDENT> def _create_shell_profile(self): <NEW_LINE> <INDENT> if self.skip_profile: <NEW_LINE> <INDENT> log.info("Not adding shell profile %s (skipped)" % ( os.path.join(self.profile_d_dir, self.profile_filename))) <NEW_LINE> return <NEW_LINE> <DEDENT> if self.root: <NEW_LINE> <INDENT> profile_dir = change_root(self.root, self.profile_d_dir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> profile_dir = self.profile_d_dir <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> dir_util.mkpath(profile_dir) <NEW_LINE> <DEDENT> except DistutilsFileError as err: <NEW_LINE> <INDENT> log.info("Not installing mysql-utilities.sh: {0}".format(err)) <NEW_LINE> self.skip_profile = True <NEW_LINE> return <NEW_LINE> <DEDENT> destfile = os.path.join(profile_dir, self.profile_filename) <NEW_LINE> if not os.access(os.path.dirname(destfile), os.X_OK | os.W_OK): <NEW_LINE> <INDENT> log.info("Not installing mysql-utilities.sh in " "{folder} (no permission)".format(folder=destfile)) <NEW_LINE> self.skip_profile = True <NEW_LINE> return <NEW_LINE> <DEDENT> if os.path.exists(os.path.dirname(destfile)): <NEW_LINE> <INDENT> if os.path.isdir(destfile) and not os.path.islink(destfile): <NEW_LINE> <INDENT> dir_util.remove_tree(destfile) <NEW_LINE> <DEDENT> elif os.path.exists(destfile): <NEW_LINE> <INDENT> log.info("Removing {filename}".format(filename=destfile)) <NEW_LINE> os.unlink(destfile) <NEW_LINE> <DEDENT> <DEDENT> script = PROFILE_SCRIPT % (self.install_dir,) <NEW_LINE> log.info("Writing {filename}".format(filename=destfile)) <NEW_LINE> open(destfile, "w+").write(script) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self._create_shell_profile() <NEW_LINE> <DEDENT> def get_outputs(self): <NEW_LINE> <INDENT> outputs = _install.get_outputs(self) <NEW_LINE> return outputs
Install MySQL Utilities scripts
62598fa056b00c62f0fb26d7