code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class DockerComposeInformation(DockerInformation): <NEW_LINE> <INDENT> SCHEMA: Dict[Tuple[str, ...], Tuple[str, ...]] = { ("compose", "project"): ("Config", "Labels", "com.docker.compose.project"), ("compose", "service"): ("Config", "Labels", "com.docker.compose.service"), ("compose", "container-number"): ("Config", "Labels", "com.docker.compose.container-number"), ("compose", "config_files"): ("Config", "Labels", "com.docker.compose.project.config_files"), }
Add information about the flask app and configuration
62598faa4f6381625f199481
class NodeFinder(object): <NEW_LINE> <INDENT> def __init__(self, matcher, limit=0): <NEW_LINE> <INDENT> self.matcher = matcher <NEW_LINE> self.limit = limit <NEW_LINE> <DEDENT> def find(self, node, list): <NEW_LINE> <INDENT> if self.matcher.match(node): <NEW_LINE> <INDENT> list.append(node) <NEW_LINE> self.limit -= 1 <NEW_LINE> if self.limit == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> for c in node.rawchildren: <NEW_LINE> <INDENT> self.find(c, list) <NEW_LINE> <DEDENT> return self
Find nodes based on flexable criteria. The I{matcher} is may be any object that implements a match(n) method. @ivar matcher: An object used as criteria for match. @type matcher: I{any}.match(n) @ivar limit: Limit the number of matches. 0=unlimited. @type limit: int
62598faaa219f33f346c679c
class ScratchWriteTests(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> ds = Dataset() <NEW_LINE> ds.PatientName = "Name^Patient" <NEW_LINE> subitem1 = Dataset() <NEW_LINE> subitem1.ContourNumber = 1 <NEW_LINE> subitem1.ContourData = ['2', '4', '8', '16'] <NEW_LINE> subitem2 = Dataset() <NEW_LINE> subitem2.ContourNumber = 2 <NEW_LINE> subitem2.ContourData = ['32', '64', '128', '196'] <NEW_LINE> sub_ds = Dataset() <NEW_LINE> sub_ds.ContourSequence = Sequence((subitem1, subitem2)) <NEW_LINE> ds.ROIContourSequence = Sequence((sub_ds,)) <NEW_LINE> self.ds = ds <NEW_LINE> <DEDENT> def compare_write(self, hex_std, file_ds): <NEW_LINE> <INDENT> out_filename = "scratch.dcm" <NEW_LINE> file_ds.save_as(out_filename) <NEW_LINE> std = hex2bytes(hex_std) <NEW_LINE> with open(out_filename, 'rb') as f: <NEW_LINE> <INDENT> bytes_written = f.read() <NEW_LINE> <DEDENT> same, pos = bytes_identical(std, bytes_written) <NEW_LINE> self.assertTrue(same, "Writing from scratch unexpected result - 1st diff at 0x%x" % pos) <NEW_LINE> if os.path.exists(out_filename): <NEW_LINE> <INDENT> os.remove(out_filename) <NEW_LINE> <DEDENT> <DEDENT> def testImpl_LE_deflen_write(self): <NEW_LINE> <INDENT> from _write_stds import impl_LE_deflen_std_hex as std <NEW_LINE> file_ds = FileDataset("test", self.ds) <NEW_LINE> self.compare_write(std, file_ds)
Simple dataset from scratch, written in all endian/VR combinations
62598faae5267d203ee6b890
class degrade_kanungo(PluginFunction): <NEW_LINE> <INDENT> self_type = ImageType([ONEBIT]) <NEW_LINE> args = Args([Float('eta', range=(0.0,1.0)), Float('a0', range=(0.0,1.0)), Float('a'), Float('b0', range=(0.0,1.0)), Float('b'), Int('k', default=2), Int('random_seed', default=0)]) <NEW_LINE> return_type = ImageType([ONEBIT]) <NEW_LINE> author = "Christoph Dalitz" <NEW_LINE> doc_examples = [(ONEBIT, 0.0, 0.5, 0.5, 0.5, 0.5, 2, 0)]
Degrades an image due to a scheme proposed by Kanungo et al. (see the reference below). This is supposed to emulate image defects introduced through printing and scanning. The degradation scheme depends on six parameters *(eta,a0,a,b0,b,k)* with the following meaning: - each foreground pixel (black) is flipped with probability `a0*exp(-a*d^2) + eta`, where d is the distance to the closest background pixel - each background pixel (white) is flipped with probability `b0*exp(-b*d^2) + eta`, where d is the distance to the closest foreground pixel - eventuall a morphological closing operation is performed with a disk of diameter *k*. If you want to skip this step set *k=0*; in that case you should do your own smoothing afterwards. The random generator is initialized with *random_seed* for allowing reproducible results. References: T. Kanungo, R.M. Haralick, H.S. Baird, et al.: *A statistical, nonparametric methodology for document degradation model validation.* IEEE Transactions on Pattern Analysis and Machine Intelligence 22, pp. 1209-1223 (2000)
62598faa99cbb53fe6830e5d
class IndLine(LinePlot): <NEW_LINE> <INDENT> def __init__(self, input_data, metabolite, display): <NEW_LINE> <INDENT> super().__init__(input_data, metabolite, display) <NEW_LINE> if "Replicates" not in self.data.index.names: <NEW_LINE> <INDENT> raise IndexError("Replicates column not found in index") <NEW_LINE> <DEDENT> self.conditions = self.data.index.get_level_values("Conditions").unique() <NEW_LINE> self.data = self.data.reorder_levels([0, 2, 1]) <NEW_LINE> self.dicts = {} <NEW_LINE> for condition in self.conditions: <NEW_LINE> <INDENT> df = self.data.loc[condition] <NEW_LINE> repdict = {} <NEW_LINE> for rep in df.index.get_level_values("Replicates"): <NEW_LINE> <INDENT> df2 = df.loc[rep, :] <NEW_LINE> repdict.update({rep: {"Times": list(df2.index.get_level_values("Time_Points")), "Values": list(df2.values)} }) <NEW_LINE> <DEDENT> self.dicts.update({condition: repdict}) <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return f"Plotting data: {self.dicts}" <NEW_LINE> <DEDENT> def build_plot(self): <NEW_LINE> <INDENT> figures = [] <NEW_LINE> max_number_reps = max([max(self.dicts[i].keys()) for i in self.dicts.keys()]) <NEW_LINE> color_lists = Colors.color_seq_gen(len(self.conditions), max_number_reps) <NEW_LINE> for condition, c_list in zip(self.conditions, color_lists): <NEW_LINE> <INDENT> fig, ax = plt.subplots() <NEW_LINE> for rep, color in zip(self.dicts[condition].keys(), c_list): <NEW_LINE> <INDENT> x = self.dicts[condition][rep]["Times"] <NEW_LINE> y = pd.Series(self.dicts[condition][rep]["Values"]) <NEW_LINE> self.maxes.append(np.nanmax(y)) <NEW_LINE> ax.plot(x, y, color=color, label=f"Replicate {rep}") <NEW_LINE> <DEDENT> y_lim = max(self.maxes) + (max(self.maxes) / 5) <NEW_LINE> self.maxes = [] <NEW_LINE> ax.set_ylim(bottom=self.y_min, top=y_lim) <NEW_LINE> ax.set_title(f"{self.metabolite}\n{condition}") <NEW_LINE> ax = LinePlot._place_legend(ax=ax) <NEW_LINE> ax.set_ylabel("Concentration in mM") <NEW_LINE> ax.set_xlabel("Time in hours") <NEW_LINE> fname = f"{self.metabolite}_{condition}" <NEW_LINE> if self.display: <NEW_LINE> <INDENT> fig.show() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> plt.close(fig) <NEW_LINE> <DEDENT> figures.append((fname, fig)) <NEW_LINE> <DEDENT> return figures
Class to generate lineplots from kinetic data. Each plot is specific to one condition and displays each replicate in a separate line.
62598faa63d6d428bbee2731
class Connect: <NEW_LINE> <INDENT> def __init__(self, host, user, password, db): <NEW_LINE> <INDENT> self.host = host <NEW_LINE> self.user = user <NEW_LINE> self.password = password <NEW_LINE> self.db = db <NEW_LINE> <DEDENT> def add_to_db(self, table_name, *args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection = pymysql.connect(host=self.host, user=self.user, password=self.password, db=self.db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) <NEW_LINE> with self.connection.cursor() as cursor: <NEW_LINE> <INDENT> sql = "SELECT id FROM {table_name};".format(table_name=table_name) <NEW_LINE> cursor.execute(sql) <NEW_LINE> new_row_pos = len([le for le in cursor]) + 1 <NEW_LINE> lt = list(args) <NEW_LINE> lt.insert(0, new_row_pos) <NEW_LINE> args = tuple(lt) <NEW_LINE> cursor.execute("INSERT INTO {table_name} ()" " VALUES {args};".format(table_name=table_name, args=args ) ) <NEW_LINE> self.connection.commit() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.connection.close() <NEW_LINE> <DEDENT> <DEDENT> def change_value(self, table_name, row_name='', value=0, number_of_rows=1, column_name='value'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection = pymysql.connect(host=self.host, user=self.user, password=self.password, db=self.db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) <NEW_LINE> row_to_change = 'counter_name' if table_name == 'player_counters' else 'currency' <NEW_LINE> with self.connection.cursor() as cursor: <NEW_LINE> <INDENT> cursor.execute("UPDATE {table_name}" " SET `{column_name}`={value}" " WHERE (`{row_to_change}`)='{row_name}'" " LIMIT {n};".format(table_name=table_name, column_name=column_name, value=value, row_to_change=row_to_change, row_name=row_name, n=number_of_rows ) ) <NEW_LINE> self.connection.commit() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.connection.close() <NEW_LINE> <DEDENT> <DEDENT> def show_db(self, table_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection = pymysql.connect(host=self.host, user=self.user, password=self.password, db=self.db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) <NEW_LINE> with self.connection.cursor() as cursor: <NEW_LINE> <INDENT> sql = "SELECT * FROM {table_name};".format(table_name=table_name) <NEW_LINE> cursor.execute(sql) <NEW_LINE> for row in [le.values() for le in cursor]: <NEW_LINE> <INDENT> print(row) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self.connection.close() <NEW_LINE> <DEDENT> <DEDENT> if __name__ == '__main__': <NEW_LINE> <INDENT> c = Connect('localhost', 'pad', 'padznich', 'pad_test') <NEW_LINE> c.change_value('player_counters', 'de', 1) <NEW_LINE> c.show_db('player_counters')
Making DataBase with MySQL.
62598faa60cbc95b063642d4
class IPv4Address(_BaseV4, _BaseAddress): <NEW_LINE> <INDENT> def __init__(self, address): <NEW_LINE> <INDENT> _BaseAddress.__init__(self, address) <NEW_LINE> _BaseV4.__init__(self, address) <NEW_LINE> if isinstance(address, int): <NEW_LINE> <INDENT> self._ip = address <NEW_LINE> if address < 0 or address > self._ALL_ONES: <NEW_LINE> <INDENT> raise AddressValueError(address) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> if (not isinstance(address, str) and isinstance(address, bytes) and len(address) == 4): <NEW_LINE> <INDENT> self._ip = struct.unpack('!I', address)[0] <NEW_LINE> return <NEW_LINE> <DEDENT> addr_str = str(address) <NEW_LINE> self._ip = self._ip_int_from_string(addr_str) <NEW_LINE> <DEDENT> @property <NEW_LINE> def packed(self): <NEW_LINE> <INDENT> return v4_int_to_packed(self._ip)
Represent and manipulate single IPv4 Addresses.
62598faab7558d58954635af
class TestFileFinderOSHomedir(TestFileFinderOSLinuxDarwin): <NEW_LINE> <INDENT> platforms = ["linux", "darwin", "windows"] <NEW_LINE> download = rdfvalue.FileFinderDownloadActionOptions() <NEW_LINE> action = rdfvalue.FileFinderAction( action_type=rdfvalue.FileFinderAction.Action.STAT) <NEW_LINE> output_path = "/analysis/test/homedirs" <NEW_LINE> args = {"paths": ["%%users.homedir%%/*"], "action": action, "runner_args": rdfvalue.FlowRunnerArgs(output=output_path)} <NEW_LINE> def CheckFlow(self): <NEW_LINE> <INDENT> results = aff4.FACTORY.Open(self.client_id.Add(self.output_path), token=self.token) <NEW_LINE> self.assertEqual(type(results), aff4.RDFValueCollection) <NEW_LINE> self.assertTrue(len(results) > 1)
List files in homedir with FileFinder. Exercise globbing and interpolation.
62598faa55399d3f056264aa
class Actor(nn.Module): <NEW_LINE> <INDENT> def __init__(self, state_size, action_size, seed, fc_units=256): <NEW_LINE> <INDENT> super(Actor, self).__init__() <NEW_LINE> self.seed = torch.manual_seed(seed) <NEW_LINE> self.fc1 = nn.Linear(state_size, fc_units) <NEW_LINE> self.fc2 = nn.Linear(fc_units, action_size) <NEW_LINE> self.reset_parameters() <NEW_LINE> <DEDENT> def reset_parameters(self): <NEW_LINE> <INDENT> self.fc1.weight.data.uniform_(*hidden_unit(self.fc1)) <NEW_LINE> self.fc2.weight.data.uniform_(-3e-3, 3e-3) <NEW_LINE> <DEDENT> def forward(self, state): <NEW_LINE> <INDENT> x = F.relu(self.fc1(state)) <NEW_LINE> return torch.tanh(self.fc2(x))
Actor (Policy) Model.
62598faaa8370b77170f0361
class Markov(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass
Implements Markov Filter (a Parametric Filter)
62598faa851cf427c66b8243
@gin.configurable <NEW_LINE> class PerStepSwitchPolicy(Policy): <NEW_LINE> <INDENT> def __init__(self, explore_policy_class, greedy_policy_class): <NEW_LINE> <INDENT> super(PerStepSwitchPolicy, self).__init__() <NEW_LINE> self._explore_policy = explore_policy_class() <NEW_LINE> self._greedy_policy = greedy_policy_class() <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self._explore_policy.reset() <NEW_LINE> self._greedy_policy.reset() <NEW_LINE> <DEDENT> def get_q_func(self, is_training=False, reuse=False, scope='q_func'): <NEW_LINE> <INDENT> return self._greedy_policy.get_q_func(is_training, reuse, scope=scope) <NEW_LINE> <DEDENT> def get_a_func(self, is_training=False, reuse=False): <NEW_LINE> <INDENT> return self._greedy_policy.get_a_func(is_training, reuse) <NEW_LINE> <DEDENT> def restore(self, checkpoint): <NEW_LINE> <INDENT> self._explore_policy.restore(checkpoint) <NEW_LINE> self._greedy_policy.restore(checkpoint) <NEW_LINE> <DEDENT> def sample_action(self, obs, explore_prob): <NEW_LINE> <INDENT> if np.random.random() < explore_prob: <NEW_LINE> <INDENT> return self._explore_policy.sample_action(obs, explore_prob) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self._greedy_policy.sample_action(obs, explore_prob)
Interpolates between an exploration policy and a greedy policy. A typical use case would be a scripted policy used to get some reasonable amount of random successes, and a greedy policy that is learned. Each of the exploration and greedy policies can still perform their own exploration actions after being selected by the PerStepSwitchPolicy.
62598faad58c6744b42dc299
class EventCaller: <NEW_LINE> <INDENT> def __init__(self, func, apply_func): <NEW_LINE> <INDENT> self.func = func <NEW_LINE> self.apply_func = apply_func <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.func(*args, **kwargs)
For now, this is just a wrapper to also store the apply_func. This should live somewhere else eventually.
62598faa76e4537e8c3ef533
class OrderView(APIView): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> ret = {'code': 1000, 'msg': None, 'data': None} <NEW_LINE> try: <NEW_LINE> <INDENT> ret['data'] = 'authenticate ok' <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return JsonResponse(ret)
订单相关业务
62598faaa8370b77170f0362
class AdminManager(Manager): <NEW_LINE> <INDENT> def __init__(self, interface='json', service=None): <NEW_LINE> <INDENT> super(AdminManager, self).__init__(CONF.identity.admin_username, CONF.identity.admin_password, CONF.identity.admin_tenant_name, interface=interface, service=service)
Manager object that uses the admin credentials for its managed client objects
62598faafff4ab517ebcd76b
class ELU(Module): <NEW_LINE> <INDENT> def __init__(self, alpha=1., inplace=False): <NEW_LINE> <INDENT> super(ELU, self).__init__() <NEW_LINE> self.alpha = alpha <NEW_LINE> self.inplace = inplace <NEW_LINE> <DEDENT> def forward(self, input): <NEW_LINE> <INDENT> return F.elu(input, self.alpha, self.inplace) <NEW_LINE> <DEDENT> def extra_repr(self): <NEW_LINE> <INDENT> inplace_str = ', inplace' if self.inplace else '' <NEW_LINE> return 'alpha={}{}'.format(self.alpha, inplace_str)
Applies element-wise, :math:`\text{ELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x) - 1))` Args: alpha: the :math:`\alpha` value for the ELU formulation. Default: 1.0 inplace: can optionally do the operation in-place. Default: ``False`` Shape: - Input: :math:`(N, *)` where `*` means, any number of additional dimensions - Output: :math:`(N, *)`, same shape as the input .. image:: scripts/activation_images/ELU.png Examples:: >>> m = nn.ELU() >>> input = torch.randn(2) >>> output = m(input)
62598faa236d856c2adc9400
class DecisionTreeModel(JavaModelWrapper): <NEW_LINE> <INDENT> def predict(self, x): <NEW_LINE> <INDENT> if isinstance(x, RDD): <NEW_LINE> <INDENT> return self.call("predict", x.map(_convert_to_vector)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.call("predict", _convert_to_vector(x)) <NEW_LINE> <DEDENT> <DEDENT> def numNodes(self): <NEW_LINE> <INDENT> return self._java_model.numNodes() <NEW_LINE> <DEDENT> def depth(self): <NEW_LINE> <INDENT> return self._java_model.depth() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self._java_model.toString() <NEW_LINE> <DEDENT> def toDebugString(self): <NEW_LINE> <INDENT> return self._java_model.toDebugString()
.. note:: Experimental A decision tree model for classification or regression.
62598faae76e3b2f99fd89bd
class add_callbacks: <NEW_LINE> <INDENT> def __init__(self, *callbacks): <NEW_LINE> <INDENT> self.callbacks = [normalize_callback(c) for c in callbacks] <NEW_LINE> Callback.active.update(self.callbacks) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __exit__(self, type, value, traceback): <NEW_LINE> <INDENT> for c in self.callbacks: <NEW_LINE> <INDENT> Callback.active.discard(c)
Context manager for callbacks. Takes several callbacks and applies them only in the enclosed context. Callbacks can either be represented as a ``Callback`` object, or as a tuple of length 4. Examples -------- >>> def pretask(key, dsk, state): ... print("Now running {0}").format(key) >>> callbacks = (None, pretask, None, None) >>> with add_callbacks(callbacks): # doctest: +SKIP ... res.compute()
62598faacc0a2c111447af97
class SudokuMatrixError (Exception): <NEW_LINE> <INDENT> pass
Sudoku matrix exception handler;
62598faacb5e8a47e493c13c
class ExchangeRatesProviderServicer(object): <NEW_LINE> <INDENT> def subscribe(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
The exchange rate service definition.
62598faaf9cc0f698b1c528c
class NetBoxConfluenceField(models.Model): <NEW_LINE> <INDENT> TYPE_CHOICES = ((name, the_class.verbose_name) for name, the_class in ABCLinkedFieldMeta.linked_field_classes.items()) <NEW_LINE> model_name = models.CharField(max_length=255, verbose_name='Model Name', help_text="Model Name") <NEW_LINE> field_type = models.CharField(max_length=255, verbose_name='Type', choices=TYPE_CHOICES, help_text="Field Type") <NEW_LINE> is_custom_field = models.BooleanField(verbose_name='Is Custom Field', help_text="Is the field `custom field`?", default=False) <NEW_LINE> field_name = models.CharField(max_length=255, verbose_name='Field') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ('model_name', 'field_name', 'is_custom_field') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{model} > {custom}{field} ({type})".format(model=self.model_name, custom=("custom_" if self.is_custom_field else ""), field=self.field_name, type=self.field_type) <NEW_LINE> <DEDENT> @property <NEW_LINE> def field_type_class(self): <NEW_LINE> <INDENT> return ABCLinkedFieldMeta.linked_field_classes[self.field_type]
Represents fields that should be synchronized/updated when they are edited on NetBox.
62598faa6aa9bd52df0d4e50
class CBWidth(SCPINode, SCPIQuery, SCPISet): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> _cmd = "CBWidth" <NEW_LINE> args = ["1"]
SOURce:RADio:ARB:NOISe:CBWidth Arguments: 1
62598faa4f6381625f199482
class UserProfileInfoForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta(): <NEW_LINE> <INDENT> model = UserProfileInfo <NEW_LINE> fields = ('portfolio_site', 'profile_pic')
docstring for UserProfileInfo.
62598faa2ae34c7f260ab069
class BRCPFField(CharField): <NEW_LINE> <INDENT> description = _("CPF Document") <NEW_LINE> default_error_messages = { 'invalid': _("Invalid CPF number."), 'max_digits': _("This field requires at most 11 digits or 14 characters."), } <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['max_length'] = 14 <NEW_LINE> super(BRCPFField, self).__init__(*args, **kwargs) <NEW_LINE> self.validators.append(BRCPFValidator())
A model field for the brazilian document named of CPF (Cadastro de Pessoa Física) .. versionadded:: 2.2
62598faa4527f215b58e9e69
class Spy(object): <NEW_LINE> <INDENT> def set_params(self, model, session): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.session = session <NEW_LINE> <DEDENT> def on_fit_begin(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_epoch_begin(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_train_on_batch_begin(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_train_on_batch_end(self, metric_lists): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_test_on_batch_begin(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_test_on_batch_end(self, metric_lists): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_epoch_end(self, epoch_results): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def on_fit_end(self): <NEW_LINE> <INDENT> pass
Monitors model training.
62598faaa79ad16197769fed
class vGeo(object): <NEW_LINE> <INDENT> def __init__(self, geo): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> latitude, longitude = (geo[0], geo[1]) <NEW_LINE> latitude = float(latitude) <NEW_LINE> longitude = float(longitude) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError('Input must be (float, float) for ' 'latitude and longitude') <NEW_LINE> <DEDENT> self.latitude = latitude <NEW_LINE> self.longitude = longitude <NEW_LINE> self.params = Parameters() <NEW_LINE> <DEDENT> def to_ical(self): <NEW_LINE> <INDENT> return '%s;%s' % (self.latitude, self.longitude) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_ical(ical): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> latitude, longitude = ical.split(';') <NEW_LINE> return (float(latitude), float(longitude)) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError("Expected 'float;float' , got: %s" % ical)
A special type that is only indirectly defined in the rfc.
62598fab435de62698e9bd7e
@six.python_2_unicode_compatible <NEW_LINE> class PerforceObject(object): <NEW_LINE> <INDENT> def __init__(self, connection=None): <NEW_LINE> <INDENT> self._connection = connection or Connection() <NEW_LINE> self._p4dict = {} <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__unicode__() <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u'<{}>'.format(self.__class__.__name__) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__unicode__()
Abstract class for dealing with the dictionaries coming back from p4 commands This is a simple descriptor for the incoming P4Dict
62598fab5fcc89381b266110
class ParametricSweepTaskFactory(TaskFactoryBase): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, 'parameter_sets': {'required': True, 'min_items': 1}, 'repeat_task': {'required': True} } <NEW_LINE> _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'parameter_sets': {'key': 'parameterSets', 'type': '[ParameterSet]'}, 'repeat_task': {'key': 'repeatTask', 'type': 'RepeatTask'}, 'merge_task': {'key': 'mergeTask', 'type': 'MergeTask'} } <NEW_LINE> def __init__(self, *, parameter_sets, repeat_task, merge_task=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(ParametricSweepTaskFactory, self).__init__(merge_task=merge_task, **kwargs) <NEW_LINE> if not parameter_sets: <NEW_LINE> <INDENT> raise ValueError("Parametric Sweep task factory requires at least one parameter set.") <NEW_LINE> <DEDENT> self.parameter_sets = parameter_sets <NEW_LINE> self.repeat_task = repeat_task <NEW_LINE> self.type = 'parametricSweep'
A Task Factory for generating a set of tasks based on one or more parameter sets to define a numeric input range. Each parameter set will have a start, end and step value. A task will be generated for each integer in this range. Multiple parameter sets can be combined for a multi-dimensional sweep. :param parameter_sets: A list if parameter sets from which tasks will be generated. :type parameter_sets: A list of :class:`ParameterSet<azext.batch.models.ParameterSet>` :param repeat_task: The task template the will be used to generate each task. :type repeat_task: :class:`RepeatTask <azext.batch.models.RepeatTask>` :param merge_task: An optional additional task to be run after all the other generated tasks have completed successfully. :type merge_task: :class:`MergeTask <azext.batch.models.MergeTask>`
62598fabbe8e80087fbbefeb
class Button: <NEW_LINE> <INDENT> def __init__(self, win, center, width, height, label): <NEW_LINE> <INDENT> w,h = width/2.0, height/2.0 <NEW_LINE> x,y = center.getX(), center.getY() <NEW_LINE> self.xmax, self.xmin = x+w, x-w <NEW_LINE> self.ymax, self.ymin = y+h, y-h <NEW_LINE> p1 = Point(self.xmin, self.ymin) <NEW_LINE> p2 = Point(self.xmax, self.ymax) <NEW_LINE> self.rect = Rectangle(p1,p2) <NEW_LINE> self.rect.setFill('lightgray') <NEW_LINE> self.rect.draw(win) <NEW_LINE> self.label = Text(center, label) <NEW_LINE> self.label.draw(win) <NEW_LINE> self.deactivate() <NEW_LINE> <DEDENT> def clicked(self, p): <NEW_LINE> <INDENT> return (self.active and self.xmin <= p.getX() <= self.xmax and self.ymin <= p.getY() <= self.ymax) <NEW_LINE> <DEDENT> def getLabel(self): <NEW_LINE> <INDENT> return self.label.getText() <NEW_LINE> <DEDENT> def activate(self): <NEW_LINE> <INDENT> self.label.setFill('black') <NEW_LINE> self.rect.setWidth(2) <NEW_LINE> self.active = True <NEW_LINE> <DEDENT> def deactivate(self): <NEW_LINE> <INDENT> self.label.setFill('darkgrey') <NEW_LINE> self.rect.setWidth(1) <NEW_LINE> self.active = False <NEW_LINE> <DEDENT> def update(self, win, label): <NEW_LINE> <INDENT> self.label.undraw() <NEW_LINE> center = self.center <NEW_LINE> self.label = Text(center, label) <NEW_LINE> self.active = False <NEW_LINE> self.label.draw(win) <NEW_LINE> <DEDENT> def undraw(self): <NEW_LINE> <INDENT> self.rect.undraw() <NEW_LINE> self.label.undraw()
A button is a labeled rectangle in a window. It is activated or deactivated with the activate() and deactivate() methods. The clicked(p) method returns true if the button is active and p is inside it.
62598fab45492302aabfc459
class MemberDetail(DetailView): <NEW_LINE> <INDENT> context_object_name = 'usr' <NEW_LINE> model = User <NEW_LINE> template_name = 'member/profile.html' <NEW_LINE> def get_object(self, queryset=None): <NEW_LINE> <INDENT> return get_object_or_404(User, username=urlunquote(self.kwargs['user_name'])) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super(MemberDetail, self).get_context_data(**kwargs) <NEW_LINE> usr = context['usr'] <NEW_LINE> profile = usr.profile <NEW_LINE> context['profile'] = profile <NEW_LINE> context['topics'] = list(Topic.objects.last_topics_of_a_member(usr, self.request.user)) <NEW_LINE> context['articles'] = PublishedContent.objects.last_articles_of_a_member_loaded(usr) <NEW_LINE> context['tutorials'] = PublishedContent.objects.last_tutorials_of_a_member_loaded(usr) <NEW_LINE> context['old_tutos'] = Profile.objects.all_old_tutos_from_site_du_zero(profile) <NEW_LINE> context['karmanotes'] = KarmaNote.objects.filter(user=usr).order_by('-create_at') <NEW_LINE> context['karmaform'] = KarmaForm(profile) <NEW_LINE> context['form'] = OldTutoForm(profile) <NEW_LINE> context['topic_read'] = TopicRead.objects.list_read_topic_pk(self.request.user, context['topics']) <NEW_LINE> return context
Displays details about a profile.
62598fab2c8b7c6e89bd374d
class Comment(models.Model): <NEW_LINE> <INDENT> article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name="article_comments") <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_comments") <NEW_LINE> comment = models.CharField(max_length=300) <NEW_LINE> time = models.DateTimeField(auto_now_add=True)
Creates Comments model
62598fab851cf427c66b8245
class Bootstrap4Tab(CMSPlugin): <NEW_LINE> <INDENT> template = models.CharField( verbose_name=_('Template'), choices=TAB_TEMPLATE_CHOICES, default=TAB_TEMPLATE_CHOICES[0][0], max_length=255, help_text=_('This is the template that will be used for the component.'), ) <NEW_LINE> tab_type = models.CharField( verbose_name=_('Type'), choices=TAB_TYPE_CHOICES, default=TAB_TYPE_CHOICES[0][0], max_length=255, ) <NEW_LINE> tab_alignment = models.CharField( verbose_name=_('Alignment'), choices=TAB_ALIGNMENT_CHOICES, blank=True, max_length=255, ) <NEW_LINE> tab_index = models.PositiveIntegerField( verbose_name=_('Index'), null=True, blank=True, help_text=_('Index of element to open on page load starting at 1.'), ) <NEW_LINE> tab_effect = models.CharField( verbose_name=_('Animation effect'), choices=TAB_EFFECT_CHOICES, blank=True, max_length=255, ) <NEW_LINE> tag_type = TagTypeField() <NEW_LINE> attributes = AttributesField() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return str(self.pk) <NEW_LINE> <DEDENT> def get_short_description(self): <NEW_LINE> <INDENT> text = '({})'.format(self.tab_type) <NEW_LINE> if self.tab_alignment: <NEW_LINE> <INDENT> text += ' .{}'.format(self.tab_alignment) <NEW_LINE> <DEDENT> return text
Components > "Navs - Tab" Plugin https://getbootstrap.com/docs/4.0/components/navs/
62598fab10dbd63aa1c70b3b
class ViewBuilder(common.ViewBuilder): <NEW_LINE> <INDENT> _collection_name = 'share_server_migration' <NEW_LINE> _detail_version_modifiers = [] <NEW_LINE> def get_progress(self, request, params): <NEW_LINE> <INDENT> result = { 'total_progress': params['total_progress'], 'task_state': params['task_state'], 'destination_share_server_id': params['destination_share_server_id'], } <NEW_LINE> self.update_versioned_resource_dict(request, result, params) <NEW_LINE> return result <NEW_LINE> <DEDENT> def build_check_migration(self, request, params, result): <NEW_LINE> <INDENT> requested_capabilities = { 'writable': params['writable'], 'nondisruptive': params['nondisruptive'], 'preserve_snapshots': params['preserve_snapshots'], 'share_network_id': params['new_share_network_id'], 'host': params['host'], } <NEW_LINE> supported_capabilities = { 'writable': result['writable'], 'nondisruptive': result['nondisruptive'], 'preserve_snapshots': result['preserve_snapshots'], 'share_network_id': result['share_network_id'], 'migration_cancel': result['migration_cancel'], 'migration_get_progress': result['migration_get_progress'] } <NEW_LINE> view = { 'compatible': result['compatible'], 'requested_capabilities': requested_capabilities, 'supported_capabilities': supported_capabilities, } <NEW_LINE> capabilities = { 'requested': copy.copy(params), 'supported': copy.copy(result) } <NEW_LINE> self.update_versioned_resource_dict(request, view, capabilities) <NEW_LINE> return view <NEW_LINE> <DEDENT> def migration_complete(self, request, params): <NEW_LINE> <INDENT> result = { 'destination_share_server_id': params['destination_share_server_id'], } <NEW_LINE> self.update_versioned_resource_dict(request, result, params) <NEW_LINE> return result
Model share server migration view data response as a python dictionary.
62598faba17c0f6771d5c1bd
class Parse(object): <NEW_LINE> <INDENT> def __init__(self, project): <NEW_LINE> <INDENT> self.project = project <NEW_LINE> <DEDENT> def __call__(self, config_files=None, dictionary=None): <NEW_LINE> <INDENT> config_files = self._config_files(config_files) <NEW_LINE> parser = configparser.ConfigParser() <NEW_LINE> self._load_config_files(parser, config_files) <NEW_LINE> if dictionary: <NEW_LINE> <INDENT> parser.read_dict(dictionary) <NEW_LINE> <DEDENT> return parser <NEW_LINE> <DEDENT> def _load_config_files(self, parser, config_files): <NEW_LINE> <INDENT> for file_ in config_files: <NEW_LINE> <INDENT> f = open(file_.name, 'r', encoding=file_.encoding) <NEW_LINE> parser.read_file(f, file_.name) <NEW_LINE> f.close() <NEW_LINE> <DEDENT> <DEDENT> def _config_files(self, config_files): <NEW_LINE> <INDENT> if config_files: <NEW_LINE> <INDENT> return find.config_files(self.project, config_files) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return find.config_files(self.project)
Object used to load and parse config files
62598fab66656f66f7d5a379
class Paginator(object): <NEW_LINE> <INDENT> def __init__(self, query, page=1, per_page=DEFAULT_PER_PAGE, total=None): <NEW_LINE> <INDENT> self.query = query <NEW_LINE> assert isinstance(per_page, int) and (per_page > 0), '`per_page` must be a positive integer' <NEW_LINE> self.per_page = per_page <NEW_LINE> if total is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> total = query.count() <NEW_LINE> <DEDENT> except (TypeError, AttributeError): <NEW_LINE> <INDENT> total = query.__len__() <NEW_LINE> <DEDENT> <DEDENT> self.total = total <NEW_LINE> page = sanitize_page_number(page) <NEW_LINE> if page == 'last': <NEW_LINE> <INDENT> page = self.num_pages <NEW_LINE> <DEDENT> self.page = page <NEW_LINE> if total > per_page * page: <NEW_LINE> <INDENT> showing = per_page <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> showing = total - per_page * (page - 1) <NEW_LINE> <DEDENT> self.showing = showing <NEW_LINE> <DEDENT> @property <NEW_LINE> def num_pages(self): <NEW_LINE> <INDENT> return int(ceil(self.total / float(self.per_page))) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_paginated(self): <NEW_LINE> <INDENT> return self.num_pages > 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_prev(self): <NEW_LINE> <INDENT> return self.page > 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_next(self): <NEW_LINE> <INDENT> return self.page < self.num_pages <NEW_LINE> <DEDENT> @property <NEW_LINE> def next_num(self): <NEW_LINE> <INDENT> return self.page + 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def prev_num(self): <NEW_LINE> <INDENT> return self.page - 1 <NEW_LINE> <DEDENT> @property <NEW_LINE> def prev(self): <NEW_LINE> <INDENT> if self.has_prev: <NEW_LINE> <INDENT> return Paginator(self.query, self.page - 1, per_page=self.per_page) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def next(self): <NEW_LINE> <INDENT> if self.has_next: <NEW_LINE> <INDENT> return Paginator(self.query, self.page + 1, per_page=self.per_page) <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def start_index(self): <NEW_LINE> <INDENT> return (self.page - 1) * self.per_page <NEW_LINE> <DEDENT> @property <NEW_LINE> def end_index(self): <NEW_LINE> <INDENT> end = self.start_index + self.per_page - 1 <NEW_LINE> return min(end, self.total - 1) <NEW_LINE> <DEDENT> @property <NEW_LINE> def items(self): <NEW_LINE> <INDENT> offset = (self.page - 1) * self.per_page <NEW_LINE> return self.query.limit(self.per_page).offset(offset) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for i in self.items: <NEW_LINE> <INDENT> yield i <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def pages(self, left_edge=2, left_current=2, right_current=5, right_edge=2): <NEW_LINE> <INDENT> last = 0 <NEW_LINE> for num in xrange(1, self.num_pages + 1): <NEW_LINE> <INDENT> if ((num <= left_edge) or ((num >= self.page - left_current) and (num < self.page + right_current)) or (num > self.num_pages - right_edge)): <NEW_LINE> <INDENT> if last + 1 != num: <NEW_LINE> <INDENT> yield None <NEW_LINE> <DEDENT> yield num <NEW_LINE> last = num
Helper class to paginate data. You can construct it from any SQLAlchemy query object or other iterable.
62598fabfff4ab517ebcd76d
class GoogleDirectionsFinder(DirectionsFinder, APIRequest): <NEW_LINE> <INDENT> def __init__(self, cfg): <NEW_LINE> <INDENT> DirectionsFinder.__init__(self) <NEW_LINE> APIRequest.__init__(self, cfg, 'google-directions', 'Google directions query') <NEW_LINE> self.directions_url = 'https://maps.googleapis.com/maps/api/directions/json' <NEW_LINE> if 'key' in cfg['DM']['directions'].keys(): <NEW_LINE> <INDENT> self.api_key = cfg['DM']['directions']['key'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.api_key = None <NEW_LINE> <DEDENT> <DEDENT> @lru_cache(maxsize=10) <NEW_LINE> def get_directions(self, waypoints, departure_time=None, arrival_time=None): <NEW_LINE> <INDENT> parameters = list() <NEW_LINE> if not waypoints.from_stop_geo: <NEW_LINE> <INDENT> from_waypoints =[expand_stop(waypoints.from_stop, False), expand_stop(waypoints.from_city, False)] <NEW_LINE> parameters.extend([wp for wp in from_waypoints if wp and wp != 'none']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parameters.append(waypoints.from_stop_geo['lat']) <NEW_LINE> parameters.append(waypoints.from_stop_geo['lon']) <NEW_LINE> <DEDENT> origin = ','.join(parameters).encode('utf-8') <NEW_LINE> parameters = list() <NEW_LINE> if not waypoints.to_stop_geo: <NEW_LINE> <INDENT> to_waypoints = [expand_stop(waypoints.to_stop, False), expand_stop(waypoints.to_city, False)] <NEW_LINE> parameters.extend([wp for wp in to_waypoints if wp and wp != 'none']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parameters.append(waypoints.to_stop_geo['lat']) <NEW_LINE> parameters.append(waypoints.to_stop_geo['lon']) <NEW_LINE> <DEDENT> destination = ','.join(parameters).encode('utf-8') <NEW_LINE> data = { 'origin': origin, 'destination': destination, 'region': 'us', 'alternatives': 'true', 'mode': 'transit', 'language': 'en', } <NEW_LINE> if departure_time: <NEW_LINE> <INDENT> data['departure_time'] = int(time.mktime(departure_time.timetuple())) <NEW_LINE> <DEDENT> elif arrival_time: <NEW_LINE> <INDENT> data['arrival_time'] = int(time.mktime(arrival_time.timetuple())) <NEW_LINE> <DEDENT> if self.api_key: <NEW_LINE> <INDENT> data['key'] = self.api_key <NEW_LINE> if waypoints.vehicle: <NEW_LINE> <INDENT> data['transit_mode'] = self.map_vehicle(waypoints.vehicle) <NEW_LINE> <DEDENT> data['transit_routing_preference'] = 'fewer_transfers' if waypoints.max_transfers else 'less_walking' <NEW_LINE> <DEDENT> self.system_logger.info("Google Directions request:\n" + str(data)) <NEW_LINE> page = urllib.urlopen(self.directions_url + '?' + urllib.urlencode(data)) <NEW_LINE> response = json.load(page) <NEW_LINE> self._log_response_json(response) <NEW_LINE> directions = GoogleDirections(input_json=response, travel=waypoints) <NEW_LINE> self.system_logger.info("Google Directions response:\n" + unicode(directions)) <NEW_LINE> return directions <NEW_LINE> <DEDENT> def map_vehicle(self, vehicle): <NEW_LINE> <INDENT> if vehicle in ['bus', 'subway', 'train', 'tram', 'rail']: <NEW_LINE> <INDENT> return vehicle <NEW_LINE> <DEDENT> if vehicle in ['monorail', 'night_tram', 'monorail']: <NEW_LINE> <INDENT> return 'rail' <NEW_LINE> <DEDENT> if vehicle in ['trolleybus', 'intercity_bus', 'night_bus']: <NEW_LINE> <INDENT> return 'bus' <NEW_LINE> <DEDENT> return 'bus|rail'
Transit direction finder using the Google Maps query engine.
62598fab92d797404e388b29
class TernausNetV2(nn.Module): <NEW_LINE> <INDENT> def __init__(self, num_classes=1, num_filters=32, is_deconv=False, num_input_channels=11, **kwargs): <NEW_LINE> <INDENT> super(TernausNetV2, self).__init__() <NEW_LINE> if 'norm_act' not in kwargs: <NEW_LINE> <INDENT> norm_act = ABN <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> norm_act = kwargs['norm_act'] <NEW_LINE> <DEDENT> self.pool = nn.MaxPool2d(2, 2) <NEW_LINE> encoder = WiderResNet(structure=[3, 3, 6, 3, 1, 1], classes=1000, norm_act=norm_act) <NEW_LINE> self.conv1 = Sequential( OrderedDict([('conv1', nn.Conv2d(num_input_channels, 64, 3, padding=1, bias=False))])) <NEW_LINE> self.conv2 = encoder.mod2 <NEW_LINE> self.conv3 = encoder.mod3 <NEW_LINE> self.conv4 = encoder.mod4 <NEW_LINE> self.conv5 = encoder.mod5 <NEW_LINE> self.center = DecoderBlock(1024, num_filters * 8, num_filters * 8, is_deconv=is_deconv) <NEW_LINE> self.dec5 = DecoderBlock(1024 + num_filters * 8, num_filters * 8, num_filters * 8, is_deconv=is_deconv) <NEW_LINE> self.dec4 = DecoderBlock(512 + num_filters * 8, num_filters * 8, num_filters * 8, is_deconv=is_deconv) <NEW_LINE> self.dec3 = DecoderBlock(256 + num_filters * 8, num_filters * 2, num_filters * 2, is_deconv=is_deconv) <NEW_LINE> self.dec2 = DecoderBlock(128 + num_filters * 2, num_filters * 2, num_filters, is_deconv=is_deconv) <NEW_LINE> self.dec1 = ConvRelu(64 + num_filters, num_filters) <NEW_LINE> self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> conv1 = self.conv1(x) <NEW_LINE> conv2 = self.conv2(self.pool(conv1)) <NEW_LINE> conv3 = self.conv3(self.pool(conv2)) <NEW_LINE> conv4 = self.conv4(self.pool(conv3)) <NEW_LINE> conv5 = self.conv5(self.pool(conv4)) <NEW_LINE> center = self.center(self.pool(conv5)) <NEW_LINE> dec5 = self.dec5(torch.cat([center, conv5], 1)) <NEW_LINE> dec4 = self.dec4(torch.cat([dec5, conv4], 1)) <NEW_LINE> dec3 = self.dec3(torch.cat([dec4, conv3], 1)) <NEW_LINE> dec2 = self.dec2(torch.cat([dec3, conv2], 1)) <NEW_LINE> dec1 = self.dec1(torch.cat([dec2, conv1], 1)) <NEW_LINE> return self.final(dec1)
Variation of the UNet architecture with InplaceABN encoder.
62598fab4e4d5625663723ae
class TripForm(FlaskForm): <NEW_LINE> <INDENT> departure = StringField( 'Departure', validators=[ DataRequired(), ] ) <NEW_LINE> departure_id = HiddenField( validators=[ DataRequired() ] ) <NEW_LINE> arrival = StringField( 'Arrival', validators=[ DataRequired(), ] ) <NEW_LINE> arrival_id = HiddenField( validators=[ DataRequired() ] ) <NEW_LINE> date = DateField( 'Trip date', format='%Y-%m-%d' ) <NEW_LINE> submit = SubmitField('Send trip request')
Trip form.
62598fabcc0a2c111447af99
class wrapumerate(object): <NEW_LINE> <INDENT> def __init__(self, stream): <NEW_LINE> <INDENT> self._exhausted = False <NEW_LINE> self._lineno = False <NEW_LINE> self._line = False <NEW_LINE> self._iter = enumerate(stream) <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self._exhausted: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._lineno, self._line = next(self._iter) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> self._exhausted = True <NEW_LINE> self._line = False <NEW_LINE> return False <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> __next__ = next <NEW_LINE> @property <NEW_LINE> def is_empty(self): <NEW_LINE> <INDENT> return self._exhausted <NEW_LINE> <DEDENT> @property <NEW_LINE> def line(self): <NEW_LINE> <INDENT> return self._line <NEW_LINE> <DEDENT> @property <NEW_LINE> def lineno(self): <NEW_LINE> <INDENT> return self._lineno
Enumerate wrapper that uses boolean end of stream status instead of StopIteration exception, and properties to access line information.
62598fab4428ac0f6e6584ad
class ConfigEntryNetatmoAuth(pyatmo.auth.NetatmOAuth2): <NEW_LINE> <INDENT> def __init__( self, hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry, implementation: config_entry_oauth2_flow.AbstractOAuth2Implementation, ): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.session = config_entry_oauth2_flow.OAuth2Session( hass, config_entry, implementation ) <NEW_LINE> super().__init__(token=self.session.token) <NEW_LINE> <DEDENT> def refresh_tokens(self,) -> dict: <NEW_LINE> <INDENT> run_coroutine_threadsafe( self.session.async_ensure_token_valid(), self.hass.loop ).result() <NEW_LINE> return self.session.token
Provide Netatmo authentication tied to an OAuth2 based config entry.
62598fabcb5e8a47e493c13d
class DepthCamera(AbstractDepthCamera): <NEW_LINE> <INDENT> _name = "Depth (XYZ) camera" <NEW_LINE> _short_desc = "A camera capturing 3D points cloud" <NEW_LINE> add_data('points', 'none', 'memoryview', "List of 3D points from the depth " "camera. memoryview of a set of float(x,y,z). The data is of size " "``(nb_points * 12)`` bytes (12=3*sizeof(float).") <NEW_LINE> add_data('nb_points', 0, 'int', "the number of points found in the " "points list. It must be inferior to cam_width * cam_height") <NEW_LINE> def initialize(self): <NEW_LINE> <INDENT> from morse.sensors.zbufferto3d import ZBufferTo3D <NEW_LINE> self.converter = ZBufferTo3D(self.local_data['intrinsic_matrix'][0][0], self.local_data['intrinsic_matrix'][1][1], self.near_clipping, self.far_clipping, self.image_width, self.image_height) <NEW_LINE> <DEDENT> def process_image(self, image): <NEW_LINE> <INDENT> pts = self.converter.recover(image) <NEW_LINE> self.local_data['points'] = pts <NEW_LINE> self.local_data['nb_points'] = int(len(pts) / 12)
This sensor generates a 3D point cloud from the camera perspective. See also :doc:`../sensors/camera` for generic informations about Morse cameras.
62598fab7047854f4633f363
class EventListener(object): <NEW_LINE> <INDENT> pass
Fake ``EventListener`` class. Currently no functionality implemented.
62598fab2ae34c7f260ab06b
class CoroBuilder(type): <NEW_LINE> <INDENT> def __new__(cls, clsname, bases, dct, **kwargs): <NEW_LINE> <INDENT> coro_list = dct.get('coroutines', []) <NEW_LINE> existing_coros = set() <NEW_LINE> def find_existing_coros(d): <NEW_LINE> <INDENT> for attr in d: <NEW_LINE> <INDENT> if attr.startswith("coro_") or attr.startswith("thread_"): <NEW_LINE> <INDENT> existing_coros.add(attr) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> find_existing_coros(dct) <NEW_LINE> for b in bases: <NEW_LINE> <INDENT> b_dct = b.__dict__ <NEW_LINE> coro_list.extend(b_dct.get('coroutines', [])) <NEW_LINE> find_existing_coros(b_dct) <NEW_LINE> <DEDENT> if _ExecutorMixin not in bases: <NEW_LINE> <INDENT> bases += (_ExecutorMixin,) <NEW_LINE> <DEDENT> for func in coro_list: <NEW_LINE> <INDENT> coro_name = 'coro_{}'.format(func) <NEW_LINE> if coro_name not in existing_coros: <NEW_LINE> <INDENT> dct[coro_name] = cls.coro_maker(func) <NEW_LINE> <DEDENT> <DEDENT> return super().__new__(cls, clsname, bases, dct) <NEW_LINE> <DEDENT> def __init__(cls, name, bases, dct): <NEW_LINE> <INDENT> super().__init__(name, bases, dct) <NEW_LINE> pool_workers = dct.get('pool_workers') <NEW_LINE> delegate = dct.get('delegate') <NEW_LINE> old_init = dct.get('__init__') <NEW_LINE> for b in bases: <NEW_LINE> <INDENT> b_dct = b.__dict__ <NEW_LINE> if not pool_workers: <NEW_LINE> <INDENT> pool_workers = b_dct.get('pool_workers') <NEW_LINE> <DEDENT> if not delegate: <NEW_LINE> <INDENT> delegate = b_dct.get('delegate') <NEW_LINE> <DEDENT> if not old_init: <NEW_LINE> <INDENT> old_init = b_dct.get('__init__') <NEW_LINE> <DEDENT> <DEDENT> cls.delegate = delegate <NEW_LINE> if pool_workers: <NEW_LINE> <INDENT> cls.pool_workers = pool_workers <NEW_LINE> <DEDENT> @wraps(old_init) <NEW_LINE> def init_func(self, *args, **kwargs): <NEW_LINE> <INDENT> if old_init: <NEW_LINE> <INDENT> old_init(self, *args, **kwargs) <NEW_LINE> <DEDENT> if cls.delegate: <NEW_LINE> <INDENT> ctx = kwargs.pop('ctx', None) <NEW_LINE> if ctx: <NEW_LINE> <INDENT> clz = getattr(ctx, cls.delegate.__name__) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> clz = cls.delegate <NEW_LINE> <DEDENT> self._obj = clz(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> cls.__init__ = init_func <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def coro_maker(func): <NEW_LINE> <INDENT> def coro_func(self, *args, loop=None, **kwargs): <NEW_LINE> <INDENT> return self.run_in_executor(getattr(self, func), *args, loop=loop, **kwargs) <NEW_LINE> <DEDENT> return coro_func
Metaclass for adding coroutines to a class. This metaclass has two main roles: 1) Make _ExecutorMixin a parent of the given class 2) For every function name listed in the class attribute "coroutines", add a new instance method to the class called "coro_<func_name>", which is an asyncio.coroutine that calls func_name in a ThreadPoolExecutor. Each wrapper class that uses this metaclass can define three class attributes that will influence the behavior of the metaclass: coroutines - A list of methods that should get coroutine versions in the wrapper. For example: coroutines = ['acquire', 'wait'] Will mean the class gets coro_acquire and coro_wait methods. delegate - The class object that is being wrapped. This object will be instantiated when the wrapper class is instantiated, and will be set to the `_obj` attribute of the instance. pool_workers - The number of workers in the ThreadPoolExecutor internally used by the wrapper class. This defaults to cpu_count(), but for classes that need to acquire locks, it should always be set to 1.
62598fab4f6381625f199483
class TagTestCase(TestCase): <NEW_LINE> <INDENT> def installTagLibrary(self, library): <NEW_LINE> <INDENT> template.libraries[library] = __import__(library) <NEW_LINE> <DEDENT> def renderTemplate(self, tstr, **context): <NEW_LINE> <INDENT> tmpl = template.Template(tstr) <NEW_LINE> cntxt = template.Context(context) <NEW_LINE> return tmpl.render(cntxt)
Helper class with some tag helper functions
62598fabadb09d7d5dc0a514
class ManageableResource(models.Model): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name + " (" + self.uuid + ")" <NEW_LINE> <DEDENT> def set_manager_group(self, group): <NEW_LINE> <INDENT> assign_perm("add_%s" % self._meta.verbose_name, group, self) <NEW_LINE> assign_perm("read_%s" % self._meta.verbose_name, group, self) <NEW_LINE> assign_perm("delete_%s" % self._meta.verbose_name, group, self) <NEW_LINE> assign_perm("change_%s" % self._meta.verbose_name, group, self) <NEW_LINE> <DEDENT> def get_manager_group(self): <NEW_LINE> <INDENT> group_permissions = get_groups_with_perms(self, attach_perms=True) <NEW_LINE> for group, permission in group_permissions.items(): <NEW_LINE> <INDENT> if "add_%s" % self._meta.verbose_name in permission: <NEW_LINE> <INDENT> return group.extendedgroup <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "manageableresource" <NEW_LINE> abstract = True
Abstract base class for manageable resources such as disk space and workflow engines
62598fabac7a0e7691f72494
class ReportField(StateField): <NEW_LINE> <INDENT> pass
An 8-bit report field.
62598fab8c0ade5d55dc3656
class StateController(Controller): <NEW_LINE> <INDENT> def is_open(self, address: Address) -> bool: <NEW_LINE> <INDENT> state_register = self.bus.read_byte_data(self.address, address.controller_register) <NEW_LINE> return state_register & address.register_bit_mask == 0
Controller which can read the state of the bays.
62598fab8e7ae83300ee902c
class Timer(object): <NEW_LINE> <INDENT> def __init__(self, collector, metric): <NEW_LINE> <INDENT> self.collector = collector <NEW_LINE> self.metric = metric <NEW_LINE> self.interval = None <NEW_LINE> self._sent = False <NEW_LINE> self._start_time = None <NEW_LINE> <DEDENT> def __call__(self, f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def wrapper(*args, **kw): <NEW_LINE> <INDENT> with self: <NEW_LINE> <INDENT> return f(*args, **kw) <NEW_LINE> <DEDENT> <DEDENT> return wrapper <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self.start() <NEW_LINE> <DEDENT> def __exit__(self, t, val, tb): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.interval = None <NEW_LINE> self._sent = False <NEW_LINE> self._start_time = time.time() <NEW_LINE> return self <NEW_LINE> <DEDENT> def stop(self, send=True): <NEW_LINE> <INDENT> if self._start_time is None: <NEW_LINE> <INDENT> raise MetricError("Can not stop - timer not started") <NEW_LINE> <DEDENT> delta = time.time() - self._start_time <NEW_LINE> self.interval = int(round(1000 * delta)) <NEW_LINE> if send: <NEW_LINE> <INDENT> self.send() <NEW_LINE> <DEDENT> return self.interval <NEW_LINE> <DEDENT> def send(self): <NEW_LINE> <INDENT> if self.interval is None: <NEW_LINE> <INDENT> raise MetricError('No time interval recorded') <NEW_LINE> <DEDENT> if self._sent: <NEW_LINE> <INDENT> raise MetricError('Already sent') <NEW_LINE> <DEDENT> self._sent = True <NEW_LINE> self.collector.timing(self.metric, self.interval)
Measure time interval between events
62598fab56ac1b37e6302175
class wo_declaration_main(models.TransientModel): <NEW_LINE> <INDENT> _inherit = 'wo.declaration.main' <NEW_LINE> @api.model <NEW_LINE> def default_get(self, fields_list): <NEW_LINE> <INDENT> res = super(wo_declaration_main, self).default_get(fields_list=fields_list) <NEW_LINE> wo = self.env['mrp.workorder'].browse(self._context.get('active_id')) <NEW_LINE> if wo.rm_draft_ids and not wo.reservation_ids: <NEW_LINE> <INDENT> raise except_orm(_('Error'), _('It is necessary to first make the output of the materials.')) <NEW_LINE> <DEDENT> return res
WorkOrder Declaration Main
62598faba8370b77170f0365
class User(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> username = models.CharField(_('username'), max_length=64, unique=True, help_text=_('5~30个字母,数字或@/./+/-/_字符。'), validators=[ validators.RegexValidator(r'^[\w.@+-]{5,30}$', _('输入有效的用户名。 ' '包含5~30个字母,数字或@/./+/-/_字符。'), 'invalid'), ], error_messages={ 'unique': _("A user with that username already exists."), }) <NEW_LINE> first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True) <NEW_LINE> last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True) <NEW_LINE> email = models.EmailField(_('email address'), blank=True, null=True) <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> mobile = models.CharField("手机号", help_text="手机号", max_length=15, blank=True, null=True) <NEW_LINE> nick_name = models.CharField("昵称", help_text="昵称", max_length=30, unique=True, blank=True, null=True) <NEW_LINE> remark = models.CharField("个性签名", help_text="个性签名", max_length=300, blank=True, null=True) <NEW_LINE> image = models.CharField("头像", help_text="头像图片URL路径", max_length=300, blank=True, null=True) <NEW_LINE> wechat = models.CharField("微信号", help_text="微信号", max_length=100, blank=True, null=True) <NEW_LINE> wechat_open_id = models.CharField("微信OpenId", help_text="微信OpenId", max_length=100, blank=True, null=True) <NEW_LINE> date_of_birth = models.DateField("生日", help_text="生日", blank=True, null=True) <NEW_LINE> objects = UserManager() <NEW_LINE> USERNAME_FIELD = 'username' <NEW_LINE> REQUIRED_FIELDS = [] <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('user') <NEW_LINE> verbose_name_plural = _('users') <NEW_LINE> db_table = "checknow_users" <NEW_LINE> <DEDENT> backend = "django.contrib.auth.backends.ModelBackend" <NEW_LINE> def _get_full_name(self): <NEW_LINE> <INDENT> if self.first_name and self.last_name: <NEW_LINE> <INDENT> return '%s%s' % (self.first_name, self.last_name) <NEW_LINE> <DEDENT> elif self.nick_name: <NEW_LINE> <INDENT> return self.nick_name <NEW_LINE> <DEDENT> elif self.username: <NEW_LINE> <INDENT> return self.username <NEW_LINE> <DEDENT> elif self.mobile: <NEW_LINE> <INDENT> return self.mobile <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "User%s" % self.id <NEW_LINE> <DEDENT> <DEDENT> full_name = property(_get_full_name) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self._get_full_name()
用户基本信息 http://python.usyiyi.cn/django/topics/auth/customizing.html#extending-user
62598fab26068e7796d4c8de
class ScheduleInstanceTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_schedule_instance(self): <NEW_LINE> <INDENT> schedule_instance_obj = ScheduleInstance() <NEW_LINE> self.assertNotEqual(schedule_instance_obj, None)
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598faba8ecb0332587119a
class Meta(object): <NEW_LINE> <INDENT> database = db.database <NEW_LINE> schema = db.schema
Define the common database configuration for the models All the configuration is loaded from db.connector, this is just a linking to have this in a dedicated file and share it to the models
62598fab2c8b7c6e89bd374f
class BotCorpusTrainer(Trainer): <NEW_LINE> <INDENT> def __init__(self, storage, **kwargs): <NEW_LINE> <INDENT> super(BotCorpusTrainer, self).__init__(storage, **kwargs) <NEW_LINE> from corpus import Corpus <NEW_LINE> self.corpus = Corpus() <NEW_LINE> <DEDENT> def train(self, *corpora): <NEW_LINE> <INDENT> trainer = ListTrainer(self.storage) <NEW_LINE> if len(corpora) == 1: <NEW_LINE> <INDENT> if isinstance(corpora[0], list): <NEW_LINE> <INDENT> corpora = corpora[0] <NEW_LINE> <DEDENT> <DEDENT> for corpus in corpora: <NEW_LINE> <INDENT> corpus_data = self.corpus.load_corpus(corpus) <NEW_LINE> for data in corpus_data: <NEW_LINE> <INDENT> for pair in data: <NEW_LINE> <INDENT> trainer.train(pair)
Allows the chat bot to be trained using data from the ChatterBot dialog corpus.
62598fab2c8b7c6e89bd3750
class OperationsScopedList(messages.Message): <NEW_LINE> <INDENT> class WarningValue(messages.Message): <NEW_LINE> <INDENT> class CodeValueValuesEnum(messages.Enum): <NEW_LINE> <INDENT> DEPRECATED_RESOURCE_USED = 0 <NEW_LINE> DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 1 <NEW_LINE> INJECTED_KERNELS_DEPRECATED = 2 <NEW_LINE> NEXT_HOP_ADDRESS_NOT_ASSIGNED = 3 <NEW_LINE> NEXT_HOP_CANNOT_IP_FORWARD = 4 <NEW_LINE> NEXT_HOP_INSTANCE_NOT_FOUND = 5 <NEW_LINE> NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 6 <NEW_LINE> NEXT_HOP_NOT_RUNNING = 7 <NEW_LINE> NO_RESULTS_ON_PAGE = 8 <NEW_LINE> REQUIRED_TOS_AGREEMENT = 9 <NEW_LINE> RESOURCE_NOT_DELETED = 10 <NEW_LINE> UNREACHABLE = 11 <NEW_LINE> <DEDENT> class DataValueListEntry(messages.Message): <NEW_LINE> <INDENT> key = messages.StringField(1) <NEW_LINE> value = messages.StringField(2) <NEW_LINE> <DEDENT> code = messages.EnumField('CodeValueValuesEnum', 1) <NEW_LINE> data = messages.MessageField('DataValueListEntry', 2, repeated=True) <NEW_LINE> message = messages.StringField(3) <NEW_LINE> <DEDENT> operations = messages.MessageField('Operation', 1, repeated=True) <NEW_LINE> warning = messages.MessageField('WarningValue', 2)
A OperationsScopedList object. Messages: WarningValue: [Output Only] Informational warning which replaces the list of operations when the list is empty. Fields: operations: [Output Only] List of operations contained in this scope. warning: [Output Only] Informational warning which replaces the list of operations when the list is empty.
62598fab236d856c2adc9402
class TempDirectory(object): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> self.name = tempfile.mkdtemp() <NEW_LINE> return self.name <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> shutil.rmtree(self.name, True)
A self cleaning temporary directory.
62598fab99fddb7c1ca62dae
class CommandAddRoutePacket(M2MPacket): <NEW_LINE> <INDENT> type = PacketType.command_add_route <NEW_LINE> attributes = [ ("command_id", int_types), ("node1", bytes), ("port1", int_types), ("node2", bytes), ("port2", int_types), ("requester", bytes), ("forwarded", int_types), ]
Command the server to generate a route from uuid1 to uuid2.
62598fab3539df3088ecc23e
class TestBarchart(unittest.TestCase): <NEW_LINE> <INDENT> layer = INTEGRATION_TESTING <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.portal = self.layer['portal'] <NEW_LINE> setRoles(self.portal, TEST_USER_ID, ['Manager']) <NEW_LINE> self.portal.invokeFactory('Survey', 's1') <NEW_LINE> self.s1 = getattr(self.portal, 's1') <NEW_LINE> self.s1.setAllowAnonymous(True) <NEW_LINE> self.s1.invokeFactory('Survey Select Question', 'ssq1') <NEW_LINE> self.s1.invokeFactory('Survey Text Question', 'stq1') <NEW_LINE> self.s1.invokeFactory('Survey Matrix', 'sm1') <NEW_LINE> self.s1.sm1.invokeFactory('Survey Matrix Question', 'smq1') <NEW_LINE> self.s1.invokeFactory('Sub Survey', 'sub1') <NEW_LINE> self.s1.sub1.invokeFactory('Survey Select Question', 'ssq2') <NEW_LINE> self.s1.sub1.invokeFactory('Survey Text Question', 'stq2') <NEW_LINE> self.s1.sub1.invokeFactory('Survey Matrix', 'sm2') <NEW_LINE> self.s1.sub1.sm2.invokeFactory('Survey Matrix Question', 'smq2') <NEW_LINE> <DEDENT> def testBarchartColours(self): <NEW_LINE> <INDENT> s1 = getattr(self, 's1') <NEW_LINE> colours = s1.getSurveyColors(0) <NEW_LINE> assert colours is not None
Ensure survey barchart works correctly
62598fab1f5feb6acb162bab
class InequalityModelDuplicatesTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.store = Store() <NEW_LINE> privApp = PrivateApplication(store=self.store) <NEW_LINE> installOn(privApp, self.store) <NEW_LINE> self.data = [] <NEW_LINE> for number in [1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 2, 1]: <NEW_LINE> <INDENT> self.data.append(DataThunk(store=self.store, a=number)) <NEW_LINE> <DEDENT> self.data.sort(key=lambda item: (item.a, item.storeID)) <NEW_LINE> self.model = TestableInequalityModel( self.store, DataThunk, None, [DataThunk.a, DataThunk.b, DataThunk.c], DataThunk.a, True) <NEW_LINE> <DEDENT> def test_rowsAfterValue(self): <NEW_LINE> <INDENT> self.assertEqual( self.model.rowsAfterValue(1, 3), self.data[4:4+3]) <NEW_LINE> <DEDENT> def test_rowsAfterItem(self): <NEW_LINE> <INDENT> self.assertEqual( self.model.rowsAfterItem(self.data[0], 3), self.data[1:4]) <NEW_LINE> self.assertEqual( self.model.rowsAfterItem(self.data[1], 3), self.data[2:5]) <NEW_LINE> self.assertEqual( self.model.rowsAfterItem(self.data[0], 1), [self.data[1]]) <NEW_LINE> <DEDENT> def test_rowsBeforeValue(self): <NEW_LINE> <INDENT> self.assertEqual( self.model.rowsBeforeValue(2, 3), self.data[5:8]) <NEW_LINE> <DEDENT> def test_rowsBeforeItem(self): <NEW_LINE> <INDENT> for x in range(len(self.data)): <NEW_LINE> <INDENT> self.assertEqual( self.model.rowsBeforeItem(self.data[x], 20), self.data[:x])
Similar to L{InequalityModelTestCase}, but test cases where there are multiple rows with the same value for the sort key.
62598fab67a9b606de545f57
class Chapter(ChapterData, FilterToggle): <NEW_LINE> <INDENT> _has_highlights_locator = ( By.CSS_SELECTOR, "input:not([disabled])") <NEW_LINE> @property <NEW_LINE> def has_highlights(self) -> bool: <NEW_LINE> <INDENT> return bool( self.find_elements(*self._has_highlights_locator))
A chapter filter option.
62598fab7047854f4633f365
class PasswordPolicy(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def all_tests(cls): <NEW_LINE> <INDENT> return dict(_tests.ATest.test_classes) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_names(cls, **tests): <NEW_LINE> <INDENT> _tests.ATest.test_classes['length'](8) <NEW_LINE> tests = [ _tests.ATest.test_classes[name]( *(args if isinstance(args, (list, tuple)) else [args]) ) for name, args in tests.items() ] <NEW_LINE> return cls(*tests) <NEW_LINE> <DEDENT> def __init__(self, *tests): <NEW_LINE> <INDENT> self._tests = tests <NEW_LINE> assert all([isinstance(c, _tests.ATest) for c in tests]), 'Tests should be instances of password_strength.tests.ATest' <NEW_LINE> <DEDENT> def password(self, password): <NEW_LINE> <INDENT> return BoundPasswordStats(password, self) <NEW_LINE> <DEDENT> def test(self, password): <NEW_LINE> <INDENT> return self.password(password).test()
Perform tests on a password.
62598faba219f33f346c67a2
@handler.subscribe(KubeDashboardEvent) <NEW_LINE> class KubeDashboard(Hunter): <NEW_LINE> <INDENT> def __init__(self, event): <NEW_LINE> <INDENT> self.event = event <NEW_LINE> <DEDENT> def get_nodes(self): <NEW_LINE> <INDENT> r = requests.get("http://{}:{}/api/v1/node".format(self.event.host, self.event.port)) <NEW_LINE> if r.status_code == 200 and "nodes" in r.text: <NEW_LINE> <INDENT> return list(map(lambda node: node["objectMeta"]["name"], json.loads(r.text)["nodes"])) <NEW_LINE> <DEDENT> <DEDENT> def execute(self): <NEW_LINE> <INDENT> self.publish_event(DashboardExposed(nodes=self.get_nodes()))
Dashboard Hunting Hunts open Dashboards, gets the type of nodes in the cluster
62598fabe5267d203ee6b896
class Scale(Layer): <NEW_LINE> <INDENT> def __init__(self, weights=None, axis=-1, momentum=0.9, beta_init='zero', gamma_init='one', **kwargs): <NEW_LINE> <INDENT> self.momentum = momentum <NEW_LINE> self.axis = axis <NEW_LINE> self.beta_init = initializers.get(beta_init) <NEW_LINE> self.gamma_init = initializers.get(gamma_init) <NEW_LINE> self.initial_weights = weights <NEW_LINE> super(Scale, self).__init__(**kwargs) <NEW_LINE> <DEDENT> def build(self, input_shape): <NEW_LINE> <INDENT> self.input_spec = [InputSpec(shape=input_shape)] <NEW_LINE> shape = (int(input_shape[self.axis]),) <NEW_LINE> self.gamma = K.variable( self.gamma_init(shape), name='{}_gamma'.format(self.name)) <NEW_LINE> self.beta = K.variable( self.beta_init(shape), name='{}_beta'.format(self.name)) <NEW_LINE> self.trainable_weights = [self.gamma, self.beta] <NEW_LINE> if self.initial_weights is not None: <NEW_LINE> <INDENT> self.set_weights(self.initial_weights) <NEW_LINE> del self.initial_weights <NEW_LINE> <DEDENT> <DEDENT> def call(self, x, mask=None): <NEW_LINE> <INDENT> input_shape = self.input_spec[0].shape <NEW_LINE> broadcast_shape = [1] * len(input_shape) <NEW_LINE> broadcast_shape[self.axis] = input_shape[self.axis] <NEW_LINE> out = K.reshape( self.gamma, broadcast_shape) * x + K.reshape(self.beta, broadcast_shape) <NEW_LINE> return out <NEW_LINE> <DEDENT> def get_config(self): <NEW_LINE> <INDENT> config = {"momentum": self.momentum, "axis": self.axis} <NEW_LINE> base_config = super(Scale, self).get_config() <NEW_LINE> return dict(list(base_config.items()) + list(config.items()))
Learns a set of weights and biases used for scaling the input data. the output consists simply in an element-wise multiplication of the input and a sum of a set of constants: out = in * gamma + beta, where 'gamma' and 'beta' are the weights and biases larned. # Arguments axis: integer, axis along which to normalize in mode 0. For instance, if your input tensor has shape (samples, channels, rows, cols), set axis to 1 to normalize per feature map (channels axis). momentum: momentum in the computation of the exponential average of the mean and standard deviation of the data, for feature-wise normalization. weights: Initialization weights. List of 2 Numpy arrays, with shapes: `[(input_shape,), (input_shape,)]` beta_init: name of initialization function for shift parameter (see [initializers](../initializers.md)), or alternatively, Theano/TensorFlow function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. gamma_init: name of initialization function for scale parameter (see [initializers](../initializers.md)), or alternatively, Theano/TensorFlow function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument. gamma_init: name of initialization function for scale parameter (see [initializers](../initializers.md)), or alternatively, Theano/TensorFlow function to use for weights initialization. This parameter is only relevant if you don't pass a `weights` argument.
62598fab4527f215b58e9e6d
class PredefinedTokensUnitTest(unittest.TestCase): <NEW_LINE> <INDENT> tests_subpath = os.path.join('Cdm', 'Projection', 'TestPredefinedTokens') <NEW_LINE> def test_get_predefined_tokens(self): <NEW_LINE> <INDENT> tokens = PredefinedTokens._get_predefined_tokens() <NEW_LINE> expected = 'always depth maxDepth noMaxDepth isArray cardinality.minimum cardinality.maximum referenceOnly normalized structured' <NEW_LINE> actual = ' '.join(tokens) <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_predefined_constants(self): <NEW_LINE> <INDENT> constants = PredefinedTokens._get_predefined_constants() <NEW_LINE> expected = 'true false' <NEW_LINE> actual = ' '.join(constants) <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_get_supported_operators(self): <NEW_LINE> <INDENT> ops = PredefinedTokens._get_supported_operators() <NEW_LINE> expected = '&& || > < == != >= <=' <NEW_LINE> actual = ' '.join(ops) <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_get_supported_parenthesis(self): <NEW_LINE> <INDENT> ops = PredefinedTokens._get_supported_parenthesis() <NEW_LINE> expected = '( )' <NEW_LINE> actual = ' '.join(ops) <NEW_LINE> self.assertEqual(expected, actual)
Unit test for PredefinedTokens functions
62598fab8e7ae83300ee902d
class IPExternalExample(doctest.Example): <NEW_LINE> <INDENT> def __init__(self, source, want, exc_msg=None, lineno=0, indent=0, options=None): <NEW_LINE> <INDENT> doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options) <NEW_LINE> self.source += '\n'
Doctest examples to be run in an external process.
62598fab8c0ade5d55dc3657
class DataTypeKey(BaseEnum): <NEW_LINE> <INDENT> DOSTA_ABCDJM_SIO_TELEMETERED = 'dosta_abcdjm_sio_telemetered' <NEW_LINE> DOSTA_ABCDJM_SIO_RECOVERED = 'dosta_abcdjm_sio_recovered'
These are the possible harvester/parser pairs for this driver
62598fab4e4d5625663723b1
class Cluster(TrackedResource): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, 'system_data': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'zones': {'key': 'zones', 'type': '[str]'}, 'properties': {'key': 'properties', 'type': 'ClusterGetProperties'}, 'identity': {'key': 'identity', 'type': 'ClusterIdentity'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, } <NEW_LINE> def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, etag: Optional[str] = None, zones: Optional[List[str]] = None, properties: Optional["ClusterGetProperties"] = None, identity: Optional["ClusterIdentity"] = None, **kwargs ): <NEW_LINE> <INDENT> super(Cluster, self).__init__(tags=tags, location=location, **kwargs) <NEW_LINE> self.etag = etag <NEW_LINE> self.zones = zones <NEW_LINE> self.properties = properties <NEW_LINE> self.identity = identity <NEW_LINE> self.system_data = None
The HDInsight cluster. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts". :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str :param etag: The ETag for the resource. :type etag: str :param zones: The availability zones. :type zones: list[str] :param properties: The properties of the cluster. :type properties: ~azure.mgmt.hdinsight.models.ClusterGetProperties :param identity: The identity of the cluster, if configured. :type identity: ~azure.mgmt.hdinsight.models.ClusterIdentity :ivar system_data: Metadata pertaining to creation and last modification of the resource. :vartype system_data: ~azure.mgmt.hdinsight.models.SystemData
62598fab167d2b6e312b6efd
class ChatRooms(Base): <NEW_LINE> <INDENT> __tablename__ = 'chat_rooms' <NEW_LINE> id = Column(Integer, primary_key=True, unique=True) <NEW_LINE> room_title = Column(String, unique=True) <NEW_LINE> room_members = relationship('Client', secondary=ChatLists) <NEW_LINE> def __init__(self, room_title): <NEW_LINE> <INDENT> self.room_title = room_title <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<ChatRoom ({}) >".format(self.room_title)
Таблица комнат для чата
62598fab4428ac0f6e6584b0
class Environment(TimeStampedBaseModel): <NEW_LINE> <INDENT> uuid = models.CharField( max_length=36, default=utils.generate_uuid, unique=True, blank=False, null=False, help_text="UUID of environment.") <NEW_LINE> name = models.CharField( max_length=255, unique=True, default=uuid.default, blank=True, null=True, help_text="Name of environment.") <NEW_LINE> data_archive_url = models.URLField( default='', blank=True, null=False, help_text="A base URL to the data archive used.") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return "{} ({})".format(self.name, self.uuid)
The environment (e.g. Prodstack, Staging).
62598fab55399d3f056264b0
class BatchPoolIdentity(Model): <NEW_LINE> <INDENT> _validation = { 'type': {'required': True}, } <NEW_LINE> _attribute_map = { 'type': {'key': 'type', 'type': 'PoolIdentityType'}, 'user_assigned_identities': {'key': 'userAssignedIdentities', 'type': '[UserAssignedIdentity]'}, } <NEW_LINE> def __init__(self, *, type, user_assigned_identities=None, **kwargs) -> None: <NEW_LINE> <INDENT> super(BatchPoolIdentity, self).__init__(**kwargs) <NEW_LINE> self.type = type <NEW_LINE> self.user_assigned_identities = user_assigned_identities
The identity of the Batch pool, if configured. The identity of the Batch pool, if configured. All required parameters must be populated in order to send to Azure. :param type: Required. The list of user identities associated with the Batch pool. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. Possible values include: 'UserAssigned', 'None' :type type: str or ~azure.batch.models.PoolIdentityType :param user_assigned_identities: The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. :type user_assigned_identities: list[~azure.batch.models.UserAssignedIdentity]
62598fab45492302aabfc45d
class EncoderConvolutions: <NEW_LINE> <INDENT> def __init__(self, is_training, hparams, activation=tf.nn.relu, scope=None): <NEW_LINE> <INDENT> super(EncoderConvolutions, self).__init__() <NEW_LINE> self.is_training = is_training <NEW_LINE> self.kernel_size = hparams.enc_conv_kernel_size <NEW_LINE> self.channels = hparams.enc_conv_channels <NEW_LINE> self.activation = activation <NEW_LINE> self.scope = "enc_conv_layers" if scope is None else scope <NEW_LINE> self.drop_rate = hparams.tacotron_dropout_rate <NEW_LINE> self.enc_conv_num_layers = hparams.enc_conv_num_layers <NEW_LINE> <DEDENT> def __call__(self, inputs): <NEW_LINE> <INDENT> with tf.compat.v1.variable_scope(self.scope): <NEW_LINE> <INDENT> x = inputs <NEW_LINE> for i in range(self.enc_conv_num_layers): <NEW_LINE> <INDENT> x = conv1d(x, self.kernel_size, self.channels, self.activation, self.is_training, self.drop_rate, "conv_layer_{}_".format(i + 1) + self.scope) <NEW_LINE> <DEDENT> <DEDENT> return x
Encoder convolutional layers used to find local dependencies in inputs characters.
62598fab85dfad0860cbfa3a
class FireAnt(Ant): <NEW_LINE> <INDENT> name = 'Fire' <NEW_LINE> damage = 3 <NEW_LINE> food_cost = 6 <NEW_LINE> armor = 1 <NEW_LINE> implemented = True <NEW_LINE> def reduce_armor(self, amount): <NEW_LINE> <INDENT> copy = self.place.bees[:] <NEW_LINE> self.armor -= amount <NEW_LINE> if self.armor <= 0: <NEW_LINE> <INDENT> for bee in copy: <NEW_LINE> <INDENT> bee.armor -= self.damage <NEW_LINE> if bee.armor <= 0: <NEW_LINE> <INDENT> self.place.remove_insect(bee) <NEW_LINE> <DEDENT> <DEDENT> self.place.remove_insect(self)
FireAnt cooks any Bee in its Place when it expires.
62598faba17c0f6771d5c1c1
class UpdateCallOrder(Price): <NEW_LINE> <INDENT> def __init__(self, call, **kwargs): <NEW_LINE> <INDENT> BlockchainInstance.__init__(self, **kwargs) <NEW_LINE> if isinstance(call, dict) and "call_price" in call: <NEW_LINE> <INDENT> super(UpdateCallOrder, self).__init__( call.get("call_price"), base=call["call_price"].get("base"), quote=call["call_price"].get("quote"), ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Couldn't parse 'Call'.") <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> t = "Margin Call: " <NEW_LINE> if "quote" in self and self["quote"]: <NEW_LINE> <INDENT> t += "%s " % str(self["quote"]) <NEW_LINE> <DEDENT> if "base" in self and self["base"]: <NEW_LINE> <INDENT> t += "%s " % str(self["base"]) <NEW_LINE> <DEDENT> return t + "@ " + Price.__repr__(self) <NEW_LINE> <DEDENT> __str__ = __repr__
This class inherits :class:`bitshares.price.Price` but has the ``base`` and ``quote`` Amounts not only be used to represent the **call price** (as a ratio of base and quote). :param bitshares.bitshares.BitShares blockchain_instance: BitShares instance
62598fab76e4537e8c3ef539
class haspattern(grepc): <NEW_LINE> <INDENT> exit_on_found = True
Tests if the input text matches the specified pattern This reads the input text line by line (or item by item for lists and generators), cast into a string before testing. like :class:`textops.grepc` it accepts testing on a specific column for a list of lists or testing on a specific key for list of dicts. It stops reading the input text as soon as the pattern is found : it is useful for big input text. Args: pattern (str): a regular expression string (case sensitive) key (int or str): test only one column or one key (optional) Returns: bool: True if the pattern is found. Examples: >>> input = 'error1\nerror2\nwarning1\ninfo1\nwarning2\ninfo2' >>> input | haspattern('error') True >>> input | haspattern('ERROR') False
62598fab44b2445a339b6936
class IShoppingList(Interface): <NEW_LINE> <INDENT> products = Attribute("products", "List of products.") <NEW_LINE> created = Attribute("created", "Creation date and time.")
Marker interface for Shopping list.
62598fab0a50d4780f70536a
class CategoryQuestion(models.Model): <NEW_LINE> <INDENT> category_question_id = models.AutoField(primary_key=True) <NEW_LINE> question = models.ForeignKey('questions.Question') <NEW_LINE> category = models.ForeignKey('categories.Category') <NEW_LINE> created_by = models.ForeignKey('auth.User', null=True, blank=True, on_delete=models.SET_NULL) <NEW_LINE> created_on = models.DateTimeField(auto_now_add=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.question.body <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> db_table = "category_question_id"
Category / Question Intermediate Class
62598fab0c0af96317c5630f
class UsageError(MandarinError): <NEW_LINE> <INDENT> description = 'Usage error'
Class representing error in command-line usage of `mandarin` tool
62598fab9c8ee82313040137
class TypeABCMeta(ABCMeta): <NEW_LINE> <INDENT> def __new__(mcls, name, bases, namespace, **kwargs): <NEW_LINE> <INDENT> cls = super(TypeABCMeta, mcls).__new__(mcls, name, bases, namespace, **kwargs) <NEW_LINE> abs_cls = mcls._find_ABC_from_bases(bases) <NEW_LINE> if abs_cls is not None: <NEW_LINE> <INDENT> mcls._verify_type_override(cls, abs_cls) <NEW_LINE> <DEDENT> return cls <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _find_ABC_from_bases(bases): <NEW_LINE> <INDENT> for base_cls in bases: <NEW_LINE> <INDENT> if isabstract(base_cls): <NEW_LINE> <INDENT> return base_cls <NEW_LINE> <DEDENT> <DEDENT> return <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _verify_type_override(mcls, cls, abs_cls): <NEW_LINE> <INDENT> for abs_method_name in abs_cls.__abstractmethods__: <NEW_LINE> <INDENT> method = cls.__dict__.get(abs_method_name) <NEW_LINE> abs_method = abs_cls.__dict__[abs_method_name] <NEW_LINE> if method is None: <NEW_LINE> <INDENT> mcls._raise_standard_abc_error(cls, abs_cls) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mcls._check_type_consistency(method, abs_method, abs_method_name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _raise_standard_abc_error(cls, abs_cls): <NEW_LINE> <INDENT> non_overridden_methods = [method for method in abs_cls.__abstractmethods__ if cls.__dict__.get(method) is None] <NEW_LINE> raise TypeError("Can't instantiate abstract class {} ".format({cls.__name__}) + "with abstract methods {}".format(', '.join(non_overridden_methods))) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _check_type_consistency(method, abs_method, abs_method_name): <NEW_LINE> <INDENT> method_type = type(method) <NEW_LINE> abs_method_type = type(abs_method) <NEW_LINE> if all(method_type is not cls for cls in abs_method_type.__mro__ if cls is not object): <NEW_LINE> <INDENT> possible_types = [cls.__name__ for cls in abs_method_type.__mro__ if cls is not object] <NEW_LINE> raise TypeError('The method "{}" must be '.format(abs_method_name) + 'one of the following types: {}.'.format(", ".join(possible_types)))
Metaclass that verifies if an ABC's descendant classes were overriden with the same types (in their methods and properties) as the original ABC. It does this when a new class is created, so it prevents the user from using the abstractmethod unless they have overridden the abstractmethod with the correct type.
62598fab2ae34c7f260ab06e
class CimcConnection(GenericSingleRpConnection): <NEW_LINE> <INDENT> os = 'cimc' <NEW_LINE> platform = None <NEW_LINE> chassis_type = 'single_rp' <NEW_LINE> state_machine_class = CimcStateMachine <NEW_LINE> connection_provider_class = CimcConnectionProvider <NEW_LINE> subcommand_list = CimcServiceList <NEW_LINE> settings = CimcSettings()
Connection class for cimc connections.
62598fabe76e3b2f99fd89c3
class Java: <NEW_LINE> <INDENT> def __init__(self, path): <NEW_LINE> <INDENT> self.path = path <NEW_LINE> <DEDENT> """Java.files() is a simple generator that returns all the files in given directory one at a time""" <NEW_LINE> def files(self): <NEW_LINE> <INDENT> for dir_path, dir_names, file_names in os.walk(self.path): <NEW_LINE> <INDENT> for filename in file_names: <NEW_LINE> <INDENT> yield os.path.join(dir_path, filename) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> """Java.get_file_content() returns the content of the selected file""" <NEW_LINE> @staticmethod <NEW_LINE> def get_file_content(filepath): <NEW_LINE> <INDENT> file = open(filepath) <NEW_LINE> return file.readlines()
Java class is created for convenient work with the program representation on hard disk (be it decompiled text or byte code). Now it supports only the text variant, but it`s in my plans to expand its features. This class` main task is to recursively scan the given folder for all code files and to return their contents one by one. This is done in two steps, explained beyond.
62598fab63b5f9789fe850f2
class Enemy(newSprite): <NEW_LINE> <INDENT> def __init__(self, filename, framesX=1, framesY=1): <NEW_LINE> <INDENT> newSprite.__init__(self, filename, framesX, framesY) <NEW_LINE> self.speed = 3 <NEW_LINE> self.rect.x = 400 <NEW_LINE> self.rect.y = 400 <NEW_LINE> self.health = 1 <NEW_LINE> <DEDENT> def move(self, frame): <NEW_LINE> <INDENT> if self.orientation == 0: <NEW_LINE> <INDENT> self.rect.y = self.rect.y + self.speed <NEW_LINE> self.changeImage(0 + frame *4) <NEW_LINE> <DEDENT> elif self.orientation ==1: <NEW_LINE> <INDENT> self.rect.y = self.rect.y - self.speed <NEW_LINE> self.changeImage(2 + frame*4) <NEW_LINE> <DEDENT> elif self.orientation ==2: <NEW_LINE> <INDENT> self.rect.x = self.rect.x + self.speed <NEW_LINE> self.changeImage(3 + frame*4) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rect.x = self.rect.x - self.speed <NEW_LINE> self.changeImage(1 + frame*4) <NEW_LINE> <DEDENT> <DEDENT> def turn(self): <NEW_LINE> <INDENT> self.orientation += 1 <NEW_LINE> self.orientation = self.orientation % 4 <NEW_LINE> <DEDENT> def hit(self): <NEW_LINE> <INDENT> self.health -=1 <NEW_LINE> playSound(enemy_hit) <NEW_LINE> if self.health == 0: <NEW_LINE> <INDENT> killSprite(self) <NEW_LINE> playSound(enemy_die)
Enemy is a generic base class used by more specific enemies
62598fab4428ac0f6e6584b1
class IWebActionMetadataSchema(Interface): <NEW_LINE> <INDENT> action_id = Int( title=u'Action ID', description=u'Automatically assigned unique ID for this action', required=True) <NEW_LINE> created = Datetime( title=u'Created', description=u'Time when this action was created.', required=True) <NEW_LINE> modified = Datetime( title=u'Modified', description=u'Time when this action was last modified.', required=True) <NEW_LINE> owner = TextLine( title=u'Owner', description=u'User that created the action.', required=True)
Metadata fields automatically added by the server.
62598fab3346ee7daa337610
class ICsTgateLayer(IDefaultBrowserLayer): <NEW_LINE> <INDENT> pass
Marker interface that defines a browser layer.
62598fabf548e778e596b531
class ButlerTaskRunner(TaskRunner): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def getTargetList(parsedCmd, **kwargs): <NEW_LINE> <INDENT> return TaskRunner.getTargetList(parsedCmd, butler=parsedCmd.butler, **kwargs)
Get a butler into the Task scripts
62598fab0c0af96317c56310
class Test_mc_set_params(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.mc_kwargs = {"diag_scale" : 1.0, "expand_power" : 2, "inflate_power" : 2, "max_iter" : 10, "threshold" : 0.00001, "tol" : 0.001} <NEW_LINE> self.clus = MCnumpy(**self.mc_kwargs) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> del self.clus <NEW_LINE> del self.mc_kwargs <NEW_LINE> <DEDENT> def test_invalid_keyword_assigment(self): <NEW_LINE> <INDENT> parameter_name = str(uuid1()) <NEW_LINE> parameter_val = str(uuid1()) <NEW_LINE> param_dict = {parameter_name : parameter_val} <NEW_LINE> with self.assertRaises(KeyError): <NEW_LINE> <INDENT> self.clus.set_params(param_dict) <NEW_LINE> <DEDENT> <DEDENT> def test_valid_keyword_assigment(self): <NEW_LINE> <INDENT> param_dict = self.mc_kwargs <NEW_LINE> param_dict["diag_scale"] = self.mc_kwargs["diag_scale"] + 1 <NEW_LINE> param_dict["expand_power"] = self.mc_kwargs["expand_power"] + 1 <NEW_LINE> param_dict["inflate_power"] = self.mc_kwargs["inflate_power"] + 1 <NEW_LINE> param_dict["max_iter"] = self.mc_kwargs["max_iter"] + 1 <NEW_LINE> param_dict["threshold"] = self.mc_kwargs["threshold"] + 1 <NEW_LINE> param_dict["tol"] = self.mc_kwargs["tol"] + 1 <NEW_LINE> self.clus.set_params(param_dict) <NEW_LINE> for _pname in param_dict.keys(): <NEW_LINE> <INDENT> self.assertAlmostEqual(self.clus.get_params()[_pname], param_dict[_pname])
Test setting parameters after initialisation.
62598fabe1aae11d1e7ce7ea
class ReceiptsClient: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._api_client = oauth2.OAuth2Client() <NEW_LINE> self._api_client_ready = False <NEW_LINE> self._account_id = None <NEW_LINE> self.transactions = [] <NEW_LINE> <DEDENT> def do_auth(self): <NEW_LINE> <INDENT> print("Starting OAuth2 flow...") <NEW_LINE> self._api_client.start_auth() <NEW_LINE> print("OAuth2 flow completed, testing API call...") <NEW_LINE> response = self._api_client.test_api_call() <NEW_LINE> if "authenticated" in response: <NEW_LINE> <INDENT> print("API call test successful!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error("OAuth2 flow seems to have failed.") <NEW_LINE> <DEDENT> self._api_client_ready = True <NEW_LINE> print("Retrieving account information...") <NEW_LINE> success, response = self._api_client.api_get("accounts", {}) <NEW_LINE> if not success or "accounts" not in response or len(response["accounts"]) < 1: <NEW_LINE> <INDENT> error("Could not retrieve accounts information") <NEW_LINE> <DEDENT> for account in response["accounts"]: <NEW_LINE> <INDENT> if "type" in account and account["type"] == "uk_retail": <NEW_LINE> <INDENT> self._account_id = account["id"] <NEW_LINE> print("Retrieved account information.") <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> if self._account_id is None: <NEW_LINE> <INDENT> error("Could not find a personal account") <NEW_LINE> <DEDENT> <DEDENT> def list_transactions(self): <NEW_LINE> <INDENT> if self._api_client is None or not self._api_client_ready: <NEW_LINE> <INDENT> error("API client not initialised.") <NEW_LINE> <DEDENT> success, response = self._api_client.api_get("transactions", { "account_id": self._account_id, }) <NEW_LINE> if not success or "transactions" not in response: <NEW_LINE> <INDENT> error("Could not list past transactions ({})".format(response)) <NEW_LINE> <DEDENT> self.transactions = response["transactions"] <NEW_LINE> print("All transactions loaded.") <NEW_LINE> <DEDENT> def read_receipt(self, receipt_id): <NEW_LINE> <INDENT> success, response = self._api_client.api_get("transaction-receipts", { "external_id": receipt_id, }) <NEW_LINE> if not success: <NEW_LINE> <INDENT> error("Failed to load receipt: {}".format(response)) <NEW_LINE> <DEDENT> print("Receipt read: {}".format(response)) <NEW_LINE> <DEDENT> def add_receipt_data(self, transaction, receipt): <NEW_LINE> <INDENT> receipt_marshaled = receipt.marshal() <NEW_LINE> receipt_id = monzotools.genReceiptID(transaction) <NEW_LINE> success, response = self._api_client.api_put("transaction-receipts/", receipt_marshaled) <NEW_LINE> if not success: <NEW_LINE> <INDENT> error("Failed to upload receipt: {}".format(response)) <NEW_LINE> <DEDENT> print("Successfully uploaded receipt {}: {}".format(receipt_id, response)) <NEW_LINE> <DEDENT> def add_junk_data_receipt(self, transaction): <NEW_LINE> <INDENT> receipt = monzotools.genReceipt(transaction, [], [("Junk Item", 99, 1)]) <NEW_LINE> self.add_receipt_data(transaction, receipt) <NEW_LINE> <DEDENT> def getTransactionMerchant(self, transaction): <NEW_LINE> <INDENT> transactionid = transaction["id"] <NEW_LINE> success, response = self._api_client.api_get(("transactions/" + transactionid), { "expand[]": "merchant", }) <NEW_LINE> if not success or "transaction" not in response: <NEW_LINE> <INDENT> error("Could not get past transaction ({})".format(response)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> name = response["transaction"]["merchant"]["name"] <NEW_LINE> return name <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return "NONE"
An example single-account client of the Monzo Transaction Receipts API. For the underlying OAuth2 implementation, see oauth2.OAuth2Client.
62598fab796e427e5384e721
class DataStruct(object): <NEW_LINE> <INDENT> def __init__(self, raw=None): <NEW_LINE> <INDENT> if raw is not None: <NEW_LINE> <INDENT> self.parse(Eater(raw, endianness="<")) <NEW_LINE> <DEDENT> <DEDENT> def parse(self, eater_obj): <NEW_LINE> <INDENT> raise NotImplementedError("This function must be implemented in subclasses")
Don't use this class unless you know what you are doing!
62598fab63d6d428bbee2739
class IMethodEventSource(object): <NEW_LINE> <INDENT> def addListener(self, eventType, obj, method): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def removeListener(self, eventType, obj, method): <NEW_LINE> <INDENT> raise NotImplementedError
Interface for classes supporting registration of methods as event receivers. For more information on the inheritable event mechanism see the L{muntjac.event package documentation<muntjac.event>}. @author: Vaadin Ltd. @author: Richard Lincoln @version: @VERSION@
62598fab71ff763f4b5e76fc
class UpdateMessagePollVote(TLObject): <NEW_LINE> <INDENT> __slots__ = ["poll_id", "user_id", "options"] <NEW_LINE> ID = 0x42f88f2c <NEW_LINE> QUALNAME = "types.UpdateMessagePollVote" <NEW_LINE> def __init__(self, *, poll_id: int, user_id: int, options: list): <NEW_LINE> <INDENT> self.poll_id = poll_id <NEW_LINE> self.user_id = user_id <NEW_LINE> self.options = options <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "UpdateMessagePollVote": <NEW_LINE> <INDENT> poll_id = Long.read(b) <NEW_LINE> user_id = Int.read(b) <NEW_LINE> options = TLObject.read(b, Bytes) <NEW_LINE> return UpdateMessagePollVote(poll_id=poll_id, user_id=user_id, options=options) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> b.write(Long(self.poll_id)) <NEW_LINE> b.write(Int(self.user_id)) <NEW_LINE> b.write(Vector(self.options, Bytes)) <NEW_LINE> return b.getvalue()
Attributes: LAYER: ``112`` Attributes: ID: ``0x42f88f2c`` Parameters: poll_id: ``int`` ``64-bit`` user_id: ``int`` ``32-bit`` options: List of ``bytes``
62598faba8ecb0332587119e
class TestModuleopen_passive_dns_database(unittest.TestCase): <NEW_LINE> <INDENT> default_options = { '_debug': False, '__logging': True, '__outputfilter': None, '_useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0', '_dnsserver': '', '_fetchtimeout': 5, '_internettlds': 'https://publicsuffix.org/list/effective_tld_names.dat', '_internettlds_cache': 72, '_genericusers': "abuse,admin,billing,compliance,devnull,dns,ftp,hostmaster,inoc,ispfeedback,ispsupport,list-request,list,maildaemon,marketing,noc,no-reply,noreply,null,peering,peering-notify,peering-request,phish,phishing,postmaster,privacy,registrar,registry,root,routing-registry,rr,sales,security,spam,support,sysadmin,tech,undisclosed-recipients,unsubscribe,usenet,uucp,webmaster,www", '__version__': '3.3', '__database': 'spiderfoot.test.db', '__modules__': None, '_socks1type': '', '_socks2addr': '', '_socks3port': '', '_socks4user': '', '_socks5pwd': '', '_torctlport': 9051, '__logstdout': False } <NEW_LINE> def test_opts(self): <NEW_LINE> <INDENT> module = sfp_open_passive_dns_database() <NEW_LINE> self.assertEqual(len(module.opts), len(module.optdescs)) <NEW_LINE> <DEDENT> def test_setup(self): <NEW_LINE> <INDENT> sf = SpiderFoot(self.default_options) <NEW_LINE> module = sfp_open_passive_dns_database() <NEW_LINE> module.setup(sf, dict()) <NEW_LINE> <DEDENT> def test_watchedEvents_should_return_list(self): <NEW_LINE> <INDENT> module = sfp_open_passive_dns_database() <NEW_LINE> self.assertIsInstance(module.watchedEvents(), list) <NEW_LINE> <DEDENT> def test_producedEvents_should_return_list(self): <NEW_LINE> <INDENT> module = sfp_open_passive_dns_database() <NEW_LINE> self.assertIsInstance(module.producedEvents(), list) <NEW_LINE> <DEDENT> @unittest.skip("todo") <NEW_LINE> def test_handleEvent(self): <NEW_LINE> <INDENT> sf = SpiderFoot(self.default_options) <NEW_LINE> module = sfp_open_passive_dns_database() <NEW_LINE> module.setup(sf, dict()) <NEW_LINE> target_value = 'example target value' <NEW_LINE> target_type = 'IP_ADDRESS' <NEW_LINE> target = SpiderFootTarget(target_value, target_type) <NEW_LINE> module.setTarget(target) <NEW_LINE> event_type = 'ROOT' <NEW_LINE> event_data = 'example data' <NEW_LINE> event_module = '' <NEW_LINE> source_event = '' <NEW_LINE> evt = SpiderFootEvent(event_type, event_data, event_module, source_event) <NEW_LINE> result = module.handleEvent(evt) <NEW_LINE> self.assertIsNone(result)
Test modules.sfp_open_passive_dns_database
62598fabbd1bec0571e1508a
class DBusManager(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._bus = dbus.SystemBus() <NEW_LINE> self._dbus_ifaces = {} <NEW_LINE> <DEDENT> def get_dbus_ifaces(self): <NEW_LINE> <INDENT> if not self._dbus_ifaces: connect_to_dbus() <NEW_LINE> return self._dbus_ifaces <NEW_LINE> <DEDENT> def get_interface(self, iface): <NEW_LINE> <INDENT> if not self._dbus_ifaces: connect_to_dbus() <NEW_LINE> return self._dbus_ifaces[iface] <NEW_LINE> <DEDENT> def get_bus(self): <NEW_LINE> <INDENT> return self._bus <NEW_LINE> <DEDENT> def set_mainloop(self, loop): <NEW_LINE> <INDENT> dbus.set_default_main_loop(loop) <NEW_LINE> <DEDENT> def connect_to_dbus(self): <NEW_LINE> <INDENT> proxy_obj = self._bus.get_object("org.wicd.daemon", '/org/wicd/daemon') <NEW_LINE> daemon = dbus.Interface(proxy_obj, 'org.wicd.daemon') <NEW_LINE> proxy_obj = self._bus.get_object("org.wicd.daemon", '/org/wicd/daemon/wireless') <NEW_LINE> wireless = dbus.Interface(proxy_obj, 'org.wicd.daemon.wireless') <NEW_LINE> proxy_obj = self._bus.get_object("org.wicd.daemon", '/org/wicd/daemon/wired') <NEW_LINE> wired = dbus.Interface(proxy_obj, 'org.wicd.daemon.wired') <NEW_LINE> self._dbus_ifaces = {"daemon" : daemon, "wireless" : wireless, "wired" : wired}
Manages the DBus objects used by wicd.
62598fab4f88993c371f04d1
class EpsilonGreedyMetaAgent(cls): <NEW_LINE> <INDENT> def __init__(self, exploration_rate, **kwargs): <NEW_LINE> <INDENT> self.exploration_rate = exploration_rate <NEW_LINE> super().__init__(**kwargs) <NEW_LINE> <DEDENT> def act(self, observation, actions): <NEW_LINE> <INDENT> if self.rng.random() < self.exploration_rate: <NEW_LINE> <INDENT> return super().force_act(observation, self.rng.choice(actions)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return super().best_act(observation, actions)
An Agent subclass that behaves epsilon greedily.
62598fab3539df3088ecc241
class StreamingResponse(Response): <NEW_LINE> <INDENT> def __init__( self, status: str, content: Generator[bytes, None, None], headers: Optional[Union[HeadersDict, Headers]] = None, encoding: str = "utf-8", ) -> None: <NEW_LINE> <INDENT> super().__init__( status=status, headers=headers, stream=cast(BinaryIO, GenStream(content)), encoding=encoding, ) <NEW_LINE> self.headers.add("transfer-encoding", "chunked") <NEW_LINE> <DEDENT> def get_content_length(self) -> Optional[int]: <NEW_LINE> <INDENT> return None
A chunked HTTP response, yielding content from a generator. Parameters: status: The status line of the response. content: A response content generator. headers: Optional response headers. encoding: An optional encoding for the response.
62598fab30dc7b766599f7db
class _GMixin: <NEW_LINE> <INDENT> @lazy_attribute <NEW_LINE> def _default_algorithm(self): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> @lazy_attribute <NEW_LINE> def _gcdata(self): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> def _get_algorithm(self, algorithm): <NEW_LINE> <INDENT> return self._default_algorithm if algorithm is None else algorithm <NEW_LINE> <DEDENT> @lazy_attribute <NEW_LINE> def _galois_closure(self): <NEW_LINE> <INDENT> return self._gcdata[0] <NEW_LINE> <DEDENT> def splitting_field(self): <NEW_LINE> <INDENT> return self._galois_closure <NEW_LINE> <DEDENT> @lazy_attribute <NEW_LINE> def _gc_map(self): <NEW_LINE> <INDENT> return self._gcdata[1]
This class provides some methods for Galois groups to be used for both permutation groups and abelian groups, subgroups and full Galois groups. It is just intended to provide common functionality between various different Galois group classes.
62598fab10dbd63aa1c70b41
@skipIf(not HAS_CERTS, 'Cannot find CA cert bundle') <NEW_LINE> @skipIf(NO_MOCK, NO_MOCK_REASON) <NEW_LINE> @patch('salt.cloud.clouds.dimensiondata.__virtual__', MagicMock(return_value='dimensiondata')) <NEW_LINE> class DimensionDataTestCase(ExtendedTestCase): <NEW_LINE> <INDENT> def test_avail_images_call(self): <NEW_LINE> <INDENT> self.assertRaises( SaltCloudSystemExit, dimensiondata.avail_images, call='action' ) <NEW_LINE> <DEDENT> def test_avail_locations_call(self): <NEW_LINE> <INDENT> self.assertRaises( SaltCloudSystemExit, dimensiondata.avail_locations, call='action' ) <NEW_LINE> <DEDENT> def test_avail_sizes_call(self): <NEW_LINE> <INDENT> self.assertRaises( SaltCloudSystemExit, dimensiondata.avail_sizes, call='action' ) <NEW_LINE> <DEDENT> def test_list_nodes_call(self): <NEW_LINE> <INDENT> self.assertRaises( SaltCloudSystemExit, dimensiondata.list_nodes, call='action' ) <NEW_LINE> <DEDENT> def test_destroy_call(self): <NEW_LINE> <INDENT> self.assertRaises( SaltCloudSystemExit, dimensiondata.destroy, name=VM_NAME, call='function' ) <NEW_LINE> <DEDENT> def test_avail_sizes(self): <NEW_LINE> <INDENT> sizes = dimensiondata.avail_sizes(call='foo') <NEW_LINE> self.assertEqual( len(sizes), 1 ) <NEW_LINE> self.assertEqual( sizes['default']['name'], 'default' ) <NEW_LINE> <DEDENT> @patch('libcloud.compute.drivers.dimensiondata.DimensionDataNodeDriver.list_nodes', MagicMock(return_value=[])) <NEW_LINE> def test_list_nodes(self): <NEW_LINE> <INDENT> nodes = dimensiondata.list_nodes() <NEW_LINE> self.assertEqual( nodes, {} ) <NEW_LINE> <DEDENT> @patch('libcloud.compute.drivers.dimensiondata.DimensionDataNodeDriver.list_locations', MagicMock(return_value=[])) <NEW_LINE> def test_list_locations(self): <NEW_LINE> <INDENT> locations = dimensiondata.avail_locations() <NEW_LINE> self.assertEqual( locations, {} )
Unit TestCase for salt.cloud.clouds.dimensiondata module.
62598fab851cf427c66b824b
class Graph(object): <NEW_LINE> <INDENT> params = ['title', 'category', 'args', 'vlabel', 'info'] <NEW_LINE> def __init__(self, name, title=None, category=None, args=None, vlabel=None, info=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.items = [] <NEW_LINE> if title is not None: <NEW_LINE> <INDENT> self.title = title <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.title = name <NEW_LINE> <DEDENT> self.category = category <NEW_LINE> self.args = args <NEW_LINE> self.vlabel = vlabel <NEW_LINE> self.info = info <NEW_LINE> <DEDENT> def append(self, item): <NEW_LINE> <INDENT> self.items.append(item) <NEW_LINE> <DEDENT> def set_value(self, item, value): <NEW_LINE> <INDENT> for i in self.items: <NEW_LINE> <INDENT> if i.name == item: <NEW_LINE> <INDENT> i.set_value(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def update_values(self): <NEW_LINE> <INDENT> for i in self.items: <NEW_LINE> <INDENT> i.update_value() <NEW_LINE> <DEDENT> <DEDENT> def str_value(self): <NEW_LINE> <INDENT> return '\n'.join([i.str_value() for i in self.items]) <NEW_LINE> <DEDENT> def str_config(self): <NEW_LINE> <INDENT> s = '\n'.join(["graph_%s %s" % (attr, getattr(self, attr)) for attr in self.params if getattr(self, attr, None) is not None]) <NEW_LINE> s += "\ngraph_order %s\n" % ' '.join([i.name for i in self.items]) <NEW_LINE> for i in self.items: <NEW_LINE> <INDENT> s += i.str_config() + '\n' <NEW_LINE> <DEDENT> return s <NEW_LINE> <DEDENT> def print_config(self): <NEW_LINE> <INDENT> print(self.str_config()) <NEW_LINE> <DEDENT> def print_value(self): <NEW_LINE> <INDENT> print(self.str_value())
Single graph, possibly with multiple items (data sources)
62598fab8a43f66fc4bf210a
class AvoidablePlace(pg.sprite.Sprite): <NEW_LINE> <INDENT> MARGINS = [40, 40, 10, 10] <NEW_LINE> def __init__(self, image): <NEW_LINE> <INDENT> pg.sprite.Sprite.__init__(self) <NEW_LINE> self.image = image <NEW_LINE> self.rect = image.get_rect() <NEW_LINE> <DEDENT> def set_random_position(self): <NEW_LINE> <INDENT> self.rect.center = get_random_position(self.MARGINS) <NEW_LINE> <DEDENT> def draw(self, surface): <NEW_LINE> <INDENT> surface.blit(self.image, self.rect)
Represents a home destination
62598fab498bea3a75a57aac
class InfList(list): <NEW_LINE> <INDENT> def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> self.default = kwds.pop('default', 0) <NEW_LINE> super(InfList, self).__init__(*args, **kwds) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(InfList, self).__getitem__(index) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> if self.default == None: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> return self.default <NEW_LINE> <DEDENT> <DEDENT> def __setitem__(self, index, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super(InfList, self).__setitem__(index, value) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> i = len(self) <NEW_LINE> if self.default == None: <NEW_LINE> <INDENT> self.append(value) <NEW_LINE> return <NEW_LINE> <DEDENT> while i < index: <NEW_LINE> <INDENT> self.append(self.default) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> self.append(value) <NEW_LINE> <DEDENT> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if super(InfList, self).__eq__(other): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lself, lother = len(self), len(other) <NEW_LINE> if lself < lother and self[:lother] == other: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __getslice__(self, i, j): <NEW_LINE> <INDENT> if self.default == None: <NEW_LINE> <INDENT> return super(InfList, self).__getslice__(i, j) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retval = InfList(default=self.default) <NEW_LINE> while i < j: <NEW_LINE> <INDENT> retval.append(self[i]) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> return retval
Represent an infinite list.
62598fab76e4537e8c3ef53b
class WallOrnamentDecoratorConfig(DecoratorConfig): <NEW_LINE> <INDENT> def __init__(self, level_types, wall_tile, ornamentation, rng, rate, top_only = True): <NEW_LINE> <INDENT> super().__init__(level_types) <NEW_LINE> self.wall_tile = wall_tile <NEW_LINE> self.ornamentation = ornamentation <NEW_LINE> self.top_only = top_only <NEW_LINE> self.rng = rng <NEW_LINE> self.rate = rate
Configuration for WallOrnamentDecorator .. versionadded:: 0.10
62598fab4e4d5625663723b4
class TestToaFlag(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> os.chdir(datadir) <NEW_LINE> cls.tim = "B1855+09_NANOGrav_dfg+12.tim" <NEW_LINE> cls.toas = toa.get_TOAs( cls.tim, ephem="DE405", planets=False, include_bipm=False ) <NEW_LINE> <DEDENT> def test_flag_value_float(self): <NEW_LINE> <INDENT> flag_value, valid = self.toas.get_flag_value("to") <NEW_LINE> assert len(flag_value) == self.toas.ntoas <NEW_LINE> for v in set(flag_value): <NEW_LINE> <INDENT> assert v in {-7.89e-07, -8.39e-07, None} <NEW_LINE> <DEDENT> count1 = {} <NEW_LINE> for flag_dict in self.toas.get_flags(): <NEW_LINE> <INDENT> fv1 = flag_dict.get("to") <NEW_LINE> if fv1 in list(count1.keys()): <NEW_LINE> <INDENT> count1[fv1] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count1[fv1] = 1 <NEW_LINE> <DEDENT> <DEDENT> count2 = {} <NEW_LINE> for fv2 in flag_value: <NEW_LINE> <INDENT> if fv2 in list(count2.keys()): <NEW_LINE> <INDENT> count2[fv2] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count2[fv2] = 1 <NEW_LINE> <DEDENT> <DEDENT> assert count1 == count2 <NEW_LINE> <DEDENT> def test_flag_value_fill(self): <NEW_LINE> <INDENT> flag_value, valid = self.toas.get_flag_value("to", fill_value=-9999) <NEW_LINE> for v in set(flag_value): <NEW_LINE> <INDENT> assert v in {-7.89e-07, -8.39e-07, -9999} <NEW_LINE> <DEDENT> <DEDENT> def test_flag_value_str(self): <NEW_LINE> <INDENT> flag_value, valid = self.toas.get_flag_value("be") <NEW_LINE> assert len(flag_value) == self.toas.ntoas <NEW_LINE> for v in set(flag_value): <NEW_LINE> <INDENT> assert v in {"ASP", "PUPPI"}
Compare delays from the dd model with tempo and PINT
62598fab3cc13d1c6d4656fb
class SympyDataTransformer(DataTransformer): <NEW_LINE> <INDENT> def __init__(self, functions: Mapping[str, Function]) -> None: <NEW_LINE> <INDENT> if any(map(lambda f: not isinstance(f, Function), functions.values())): <NEW_LINE> <INDENT> raise TypeError( "Not all values in the mapping are an instance of" f" {Function.__name__}" ) <NEW_LINE> <DEDENT> self.__functions = dict(functions) <NEW_LINE> <DEDENT> @property <NEW_LINE> def functions(self) -> Dict[str, Function]: <NEW_LINE> <INDENT> return dict(self.__functions) <NEW_LINE> <DEDENT> def __call__(self, data: DataSample) -> DataSample: <NEW_LINE> <INDENT> return { key: function(data) for key, function in self.__functions.items() } <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_sympy( cls, expressions: Dict["sp.Symbol", "sp.Expr"], backend: str, *, use_cse: bool = True, max_complexity: Optional[int] = None, ) -> "SympyDataTransformer": <NEW_LINE> <INDENT> expanded_expressions: Dict[str, "sp.Expr"] = { k.name: expr.doit() for k, expr in expressions.items() } <NEW_LINE> free_symbols: Set["sp.Symbol"] = set() <NEW_LINE> for expr in expanded_expressions.values(): <NEW_LINE> <INDENT> free_symbols |= expr.free_symbols <NEW_LINE> <DEDENT> ordered_symbols = tuple(sorted(free_symbols, key=lambda s: s.name)) <NEW_LINE> argument_order = tuple(map(str, ordered_symbols)) <NEW_LINE> functions = {} <NEW_LINE> for variable_name, expr in expanded_expressions.items(): <NEW_LINE> <INDENT> function = _lambdify_normal_or_fast( expr, ordered_symbols, backend, use_cse=use_cse, max_complexity=max_complexity, ) <NEW_LINE> functions[variable_name] = PositionalArgumentFunction( function, argument_order ) <NEW_LINE> <DEDENT> return cls(functions)
Implementation of a `.DataTransformer`.
62598faba8370b77170f036a
class Level: <NEW_LINE> <INDENT> def __init__(self, fichier): <NEW_LINE> <INDENT> self.fichier = fichier <NEW_LINE> self.structure = 0 <NEW_LINE> self.free = 0 <NEW_LINE> <DEDENT> def generer(self): <NEW_LINE> <INDENT> with open(self.fichier, "r") as fichier: <NEW_LINE> <INDENT> structure_niveau = [] <NEW_LINE> for ligne in fichier: <NEW_LINE> <INDENT> ligne_niveau = [] <NEW_LINE> for sprite in ligne: <NEW_LINE> <INDENT> if sprite != '\n': <NEW_LINE> <INDENT> ligne_niveau.append(sprite) <NEW_LINE> <DEDENT> <DEDENT> structure_niveau.append(ligne_niveau) <NEW_LINE> <DEDENT> self.structure = structure_niveau <NEW_LINE> <DEDENT> <DEDENT> def afficher(self, window): <NEW_LINE> <INDENT> wall = pygame.image.load(IMAGE_WALL).convert() <NEW_LINE> guardian = pygame.image.load(IMAGE_GUARDIAN).convert() <NEW_LINE> fond = pygame.image.load(IMAGE_FOND).convert() <NEW_LINE> num_ligne = 0 <NEW_LINE> for ligne in self.structure: <NEW_LINE> <INDENT> num_case = 0 <NEW_LINE> for sprite in ligne: <NEW_LINE> <INDENT> x = num_case * SPRITE_SIZE <NEW_LINE> y = num_ligne * SPRITE_SIZE <NEW_LINE> if sprite == 'm': <NEW_LINE> <INDENT> window.blit(wall, (x, y)) <NEW_LINE> <DEDENT> elif sprite == 'a': <NEW_LINE> <INDENT> window.blit(guardian, (x, y)) <NEW_LINE> <DEDENT> elif sprite == '0': <NEW_LINE> <INDENT> window.blit(fond, (x, y)) <NEW_LINE> self.free += 1 <NEW_LINE> <DEDENT> num_case += 1 <NEW_LINE> <DEDENT> num_ligne += 1 <NEW_LINE> <DEDENT> <DEDENT> def random_pos(self, n): <NEW_LINE> <INDENT> position = [i for i in range(1, self.free)] <NEW_LINE> choice = rd.sample(position, 3) <NEW_LINE> retour = [] <NEW_LINE> for j in range(n): <NEW_LINE> <INDENT> num_ligne = 0 <NEW_LINE> counter = 0 <NEW_LINE> for ligne in self.structure: <NEW_LINE> <INDENT> num_case = 0 <NEW_LINE> for sprite in ligne: <NEW_LINE> <INDENT> x = num_case * SPRITE_SIZE <NEW_LINE> y = num_ligne * SPRITE_SIZE <NEW_LINE> if sprite == '0': <NEW_LINE> <INDENT> counter += 1 <NEW_LINE> if counter == choice[j]: <NEW_LINE> <INDENT> retour.append((x, y)) <NEW_LINE> <DEDENT> <DEDENT> num_case += 1 <NEW_LINE> <DEDENT> num_ligne += 1 <NEW_LINE> <DEDENT> <DEDENT> return retour
class to Create the level
62598fabf7d966606f747f73