code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class SchoolAdmin(utils.ModelAdmin): <NEW_LINE> <INDENT> list_display = ( 'id', 'title', 'school_type', 'email', ) <NEW_LINE> list_filter = ( 'school_type', ) <NEW_LINE> search_fields = ( 'id', 'title', 'email', ) <NEW_LINE> sheet_mapping = ( (_(u'ID'), ('id',)), (_(u'Title'), ('title',)), (_(u'Type'), ('get_school_type_display',)), (_(u'Email'), ('email',)), (_(u'Municipality'), ('municipality', 'title',)), (_(u'Municipality code'), ('municipality', 'code',)), )
Administration for school.
6259906c63b5f9789fe86983
class GetState(Object): <NEW_LINE> <INDENT> ID = 0xedd4882a <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "GetState": <NEW_LINE> <INDENT> return GetState() <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> return b.getvalue()
Attributes: ID: ``0xedd4882a`` No parameters required. Raises: :obj:`Error <pyrogram.Error>` Returns: :obj:`updates.State <pyrogram.api.types.updates.State>`
6259906c627d3e7fe0e086a9
class SitemapCsvColumnEnum(object): <NEW_LINE> <INDENT> INDEX = SITEMAP_PROP_NT(0, 'index') <NEW_LINE> """ The name of the Adobe Illustrator file represented by the siteMap. """ <NEW_LINE> FILENAME = SITEMAP_PROP_NT(1, 'filename') <NEW_LINE> FEDERAL_EAST = SITEMAP_PROP_NT(2, 'federal_east') <NEW_LINE> FEDERAL_NORTH = SITEMAP_PROP_NT(3, 'federal_north') <NEW_LINE> LEFT = SITEMAP_PROP_NT(4, 'left') <NEW_LINE> TOP = SITEMAP_PROP_NT(5, 'top') <NEW_LINE> WIDTH = SITEMAP_PROP_NT(6, 'width') <NEW_LINE> HEIGHT = SITEMAP_PROP_NT(7, 'height') <NEW_LINE> FEDERAL_X = SITEMAP_PROP_NT(8, 'federal_x') <NEW_LINE> FEDERAL_Y = SITEMAP_PROP_NT(9, 'federal_y') <NEW_LINE> TRANSLATE_X = SITEMAP_PROP_NT(10, 'translate_x') <NEW_LINE> TRANSLATE_Z = SITEMAP_PROP_NT(11, 'translate_z') <NEW_LINE> ROTATE_X = SITEMAP_PROP_NT(12, 'rotate_x') <NEW_LINE> ROTATE_Y = SITEMAP_PROP_NT(13, 'rotate_y') <NEW_LINE> ROTATE_Z = SITEMAP_PROP_NT(14, 'rotate_z') <NEW_LINE> SCALE = SITEMAP_PROP_NT(15, 'scale')
A class for...
6259906c8a43f66fc4bf39b4
class TreeEmbedding_HTU_plain_leaf(TreeEmbedding_HTU): <NEW_LINE> <INDENT> def __init__(self, name, **kwargs): <NEW_LINE> <INDENT> super(TreeEmbedding_HTU_plain_leaf, self).__init__(name='HTU_' + name, **kwargs) <NEW_LINE> with tf.variable_scope(self.name) as scope: <NEW_LINE> <INDENT> self._plain_leaf_fc = fc_scoped(num_units=self.state_size, activation_fn=tf.nn.tanh, scope=scope, keep_prob=self.keep_prob, name=VAR_PREFIX_FC_PLAIN_LEAF + '_%d' % self.state_size) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> embed_tree = td.ForwardDeclaration(input_type=td.PyObjectType(), output_type=self.map.output_type) <NEW_LINE> state = td.OneOf(key_fn=self.has_children(), case_blocks={ True: self.new_state(head=self.head_w_direction, children=self.children() >> td.Map(embed_tree())), False: self.head_w_direction() >> td.GetItem(0) >> self._plain_leaf_fc }) <NEW_LINE> embed_tree.resolve_to(state) <NEW_LINE> return state
Calculates an embedding over a (recursive) SequenceNode.
6259906c63d6d428bbee3e9a
class Trackable(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.slots = {} <NEW_LINE> <DEDENT> def signal_connect(self, name, func, *args): <NEW_LINE> <INDENT> if not self.slots.has_key(name): <NEW_LINE> <INDENT> self.slots[name] = Slot() <NEW_LINE> <DEDENT> self.slots[name].subscribe(func, *args) <NEW_LINE> <DEDENT> def signal_is_connected(self, name, func): <NEW_LINE> <INDENT> if not self.slots.has_key(name): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.slots[name].is_subscribed(func) <NEW_LINE> <DEDENT> def signal_disconnect(self, name, func = None): <NEW_LINE> <INDENT> if not self.slots.has_key(name): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if func: <NEW_LINE> <INDENT> self.slots[name].unsubscribe(func) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.slots[name].unsubscribe_all() <NEW_LINE> <DEDENT> <DEDENT> def signal_disconnect_all(self): <NEW_LINE> <INDENT> for slot in self.slots.itervalues(): <NEW_LINE> <INDENT> slot.unsubscribe_all() <NEW_LINE> <DEDENT> self.slots = {} <NEW_LINE> <DEDENT> def signal_subscribers(self, name): <NEW_LINE> <INDENT> if not self.slots.has_key(name): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return self.slots[name].n_subscribers() <NEW_LINE> <DEDENT> def signal_emit(self, name, *args, **kwargs): <NEW_LINE> <INDENT> if not self.slots.has_key(name): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.slots[name].signal_emit(*args, **kwargs)
Inherit from this class to add signal/event capability to a Python object.
6259906c4f88993c371f1130
class TSNEPlotter: <NEW_LINE> <INDENT> def __init__(self, X, y): <NEW_LINE> <INDENT> self.X = X <NEW_LINE> self.y = np.asarray(y) <NEW_LINE> <DEDENT> def plot(self, n=2, outliers=True, sparsity=0, **kwargs): <NEW_LINE> <INDENT> assert n == 2 or n == 3, 'n MUST be 2 or 3' <NEW_LINE> assert sparsity >= 0, 'sparsity MUST be non-negative' <NEW_LINE> X = self.X[::(1 + sparsity)] <NEW_LINE> y = self.y[::(1 + sparsity)] <NEW_LINE> tsne = TSNE(n_components=n, **kwargs).fit_transform(X, y) <NEW_LINE> if n == 2: <NEW_LINE> <INDENT> ax = plt.figure().add_subplot() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ax = plt.figure().add_subplot(111, projection='3d') <NEW_LINE> ax.set_zlabel('t-SNE component #3') <NEW_LINE> <DEDENT> if not outliers: <NEW_LINE> <INDENT> outliers = EllipticEnvelope().fit_predict(tsne, None) <NEW_LINE> tsne = tsne[outliers > 0] <NEW_LINE> y = y[outliers > 0] <NEW_LINE> <DEDENT> scatter = ax.scatter(*tsne.T.tolist(), c=y) <NEW_LINE> ax.legend(*scatter.legend_elements(), title="Classes") <NEW_LINE> ax.set_xlabel('t-SNE component #1') <NEW_LINE> ax.set_ylabel('t-SNE component #2') <NEW_LINE> if n == 3: <NEW_LINE> <INDENT> ax.set_zlabel('t-SNE component #3') <NEW_LINE> <DEDENT> plt.show()
Plot t-SNE components
6259906c3539df3088ecdac0
class __descript(object): <NEW_LINE> <INDENT> def __init__(self, f, checker): <NEW_LINE> <INDENT> self.f = f <NEW_LINE> self.__name__ = self.f.__name__ <NEW_LINE> self.__doc__ = self.f.__doc__ <NEW_LINE> self.__dict__.update(self.f.__dict__) <NEW_LINE> self.__checker = checker <NEW_LINE> <DEDENT> def __get__(self, instance, klass): <NEW_LINE> <INDENT> if instance is None: <NEW_LINE> <INDENT> return self.__method_unbound(klass) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__method_bound(instance, klass) <NEW_LINE> <DEDENT> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> self.__checker.validate_params(self.f, False, *args, **kwargs) <NEW_LINE> result = self.f(*args, **kwargs) <NEW_LINE> self.__checker.validate_result(result) <NEW_LINE> return result <NEW_LINE> <DEDENT> return wrapper(*args, **kwargs) <NEW_LINE> <DEDENT> def __method_unbound(self, klass): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> raise TypeError('unbound method {}() must be called with {} instance '.format( self.f.__name__, klass.__name__)) <NEW_LINE> <DEDENT> return wrapper <NEW_LINE> <DEDENT> def __method_bound(self, instance, klass): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> self.__checker.check_type('self', instance, klass) <NEW_LINE> self.__checker.validate_params(self.f, True, *args, **kwargs) <NEW_LINE> result = self.f(instance, *args, **kwargs) <NEW_LINE> self.__checker.validate_result(result) <NEW_LINE> return result <NEW_LINE> <DEDENT> setattr(instance, self.f.__name__, wrapper) <NEW_LINE> return wrapper
This class is intended to delay the definition of the method wrapper which surrounds the user's function or user's class method. This is necessary for two reasons: 1. the Python runtime may pass lately the user's function or class method to be decorated. It happens when the decorator itself accepts arguments. In this case, the decorator must wait until its __get__ or its __call__ methods are called and, since that happens, then instantiate ``this`` class since that the user's function or users's class method will be known at that point. 2. the Python runtime executes decorated functions in different ways, depending whether they are actually functions or actually class methods. a. In the case of functions, the Python runtime calls the ``__call__`` method directly. In this case, a wrapper is built and called immediately, returning its results to the Python runtime. b. In the case of class methods, the Python runtime calls ``__get__`` and passes an instance object, in order to obtain a bounded callable to that instance. Then, the Python runtime calls the ``__call__`` method in order to execute the class method. Notice that, in the extreme case of a decorator with arguments, applied to a class method, the Python runtime will (1) first call ``__get__`` in order to obtain an unbounded reference to the users' class method at decoration time (compilation time), then (2) call ``__get__`` at runtime when the ``instance`` object is passed and a bounded reference to the user's class method and then (3) finally, method ``__call__`` is called, in order to execute the bounded class method.
6259906c44b2445a339b7570
class GoExon(object): <NEW_LINE> <INDENT> self.id = 0 <NEW_LINE> self.genome_locus = None <NEW_LINE> self.gene_association = None <NEW_LINE> def __init__(self, initialData={}): <NEW_LINE> <INDENT> for k,v in initData.iteritems(): <NEW_LINE> <INDENT> setattr(self, k, v)
aibs.model.goexon (autogen)
6259906cd6c5a102081e394c
class HomogeneousTransform3D(DifferentiableMap): <NEW_LINE> <INDENT> def __init__(self, p0=np.zeros(3)): <NEW_LINE> <INDENT> assert p0.size == 3 <NEW_LINE> self._n = p0.size + 1 <NEW_LINE> self._T = np.eye(self.input_dimension()) <NEW_LINE> self._p = np.ones(self.input_dimension()) <NEW_LINE> self._p[:self.output_dimension()] = p0 <NEW_LINE> <DEDENT> def output_dimension(self): <NEW_LINE> <INDENT> return self._n - 1 <NEW_LINE> <DEDENT> def input_dimension(self): <NEW_LINE> <INDENT> return self._n <NEW_LINE> <DEDENT> def point(self): <NEW_LINE> <INDENT> return self._p[:self.output_dimension()] <NEW_LINE> <DEDENT> def forward(self, q): <NEW_LINE> <INDENT> assert q.size == self.input_dimension() <NEW_LINE> dim = self.output_dimension() <NEW_LINE> self._T[:dim, :dim] = rotation_matrix_2d_radian(q[dim]) <NEW_LINE> self._T[:dim, dim] = q[:dim] <NEW_LINE> return np.dot(self._T, self._p)[:dim]
Homeogeneous transformation as DifferentiableMap details: Takes an angle and rotates the point p0 by this angle f(q) = T(q) * p_0 where T defines a rotation and translation (6DoFs) q_{0,1} => translation q_{2} => rotation T = [ R(q) p(q) ] [ 0 0 1 ] We use the Euler angel convention 3-2-1, which is found TODO it would be nice to match the ROS convention we simply use this one because it was available as derivation in termes for sin and cos. It seems that ROS dos Static-Z-Y-X so it should be the same. Still needs to test.
6259906c2ae34c7f260ac90a
class MCVirtLockException(MCVirtException): <NEW_LINE> <INDENT> pass
A lock has already been found.
6259906c5166f23b2e244bf5
class Results(object): <NEW_LINE> <INDENT> name = None <NEW_LINE> outputs = None <NEW_LINE> def __init__(self, name): <NEW_LINE> <INDENT> self.outputs = [] <NEW_LINE> self.name = name <NEW_LINE> <DEDENT> def addOutput(self, name): <NEW_LINE> <INDENT> for o in self.outputs: <NEW_LINE> <INDENT> if o.name == name: <NEW_LINE> <INDENT> return o <NEW_LINE> <DEDENT> <DEDENT> o = Output(name) <NEW_LINE> self.outputs.append(o) <NEW_LINE> return o <NEW_LINE> <DEDENT> def write(self, file = sys.stdout): <NEW_LINE> <INDENT> for output in self.outputs: <NEW_LINE> <INDENT> file.write("pin(" + output.name + "):\n") <NEW_LINE> for input in output.inputs: <NEW_LINE> <INDENT> file.write(" related_pin(" + input.name + "):\n") <NEW_LINE> file.write(" cap: %.2f fF\n" % input.inputCapa) <NEW_LINE> for arc in input.arcs: <NEW_LINE> <INDENT> file.write(" arc(" + arc.name + "):\n") <NEW_LINE> slewLine = ", ".join([ "%-8.2f" % s.value for s in arc.capas[0].slews ]) <NEW_LINE> for prop in [ "delay", "transition", "power" ]: <NEW_LINE> <INDENT> file.write(" " + prop + ":\n") <NEW_LINE> file.write(" # " + slewLine + " # input slew (ps)\n") <NEW_LINE> for capa in arc.capas: <NEW_LINE> <INDENT> line = ", ".join([ "%-8.2f" % s.__dict__[prop] for s in capa.slews ]) <NEW_LINE> file.write(" [ " + line + " ] # C=" + ("%.2f" % capa.value) + "fF\n")
Represents the results for one cell
6259906cfff4ab517ebcf03d
class VentasForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Ventas <NEW_LINE> fields = ('producto', 'unidades_ventidas', 'fecha_venta')
Autor: Johan Vasquez Fecha: 29/04/2018 Descripción: Formulario para gestionar los sensores registrados en el sistema
6259906c4a966d76dd5f070c
class SkuDescription(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'resource_type': {'readonly': True}, 'name': {'readonly': True}, 'size': {'readonly': True}, 'locations': {'readonly': True}, 'location_info': {'readonly': True}, 'restrictions': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'resource_type': {'key': 'resourceType', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'size': {'key': 'size', 'type': 'str'}, 'locations': {'key': 'locations', 'type': '[str]'}, 'location_info': {'key': 'locationInfo', 'type': '[SkuLocationInfoItem]'}, 'restrictions': {'key': 'restrictions', 'type': '[object]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(SkuDescription, self).__init__(**kwargs) <NEW_LINE> self.resource_type = None <NEW_LINE> self.name = None <NEW_LINE> self.size = None <NEW_LINE> self.locations = None <NEW_LINE> self.location_info = None <NEW_LINE> self.restrictions = None
The Kusto SKU description of given resource type. Variables are only populated by the server, and will be ignored when sending a request. :ivar resource_type: The resource type. :vartype resource_type: str :ivar name: The name of the SKU. :vartype name: str :ivar size: The size of the SKU. :vartype size: str :ivar locations: The set of locations that the SKU is available. :vartype locations: list[str] :ivar location_info: Locations and zones. :vartype location_info: list[~azure.mgmt.synapse.models.SkuLocationInfoItem] :ivar restrictions: The restrictions because of which SKU cannot be used. :vartype restrictions: list[any]
6259906c66673b3332c31c20
class EntryState(object): <NEW_LINE> <INDENT> def __init__(self, dn, cursor): <NEW_LINE> <INDENT> self.dn = dn <NEW_LINE> self._initial_status = None <NEW_LINE> self._to = None <NEW_LINE> self.status = STATUS_INIT <NEW_LINE> self.attributes = CaseInsensitiveWithAliasDict() <NEW_LINE> self.raw_attributes = CaseInsensitiveWithAliasDict() <NEW_LINE> self.response = None <NEW_LINE> self.cursor = cursor <NEW_LINE> self.origin = None <NEW_LINE> self.read_time = None <NEW_LINE> self.changes = OrderedDict() <NEW_LINE> if cursor.definition: <NEW_LINE> <INDENT> self.definition = cursor.definition <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.definition = None <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> if self.__dict__ and self.dn is not None: <NEW_LINE> <INDENT> r = 'DN: ' + to_stdout_encoding(self.dn) + ' - STATUS: ' + ((self._initial_status + ', ') if self._initial_status != self.status else '') + self.status + ' - READ TIME: ' + (self.read_time.isoformat() if self.read_time else '<never>') + linesep <NEW_LINE> r += 'attributes: ' + ', '.join(sorted(self.attributes.keys())) + linesep <NEW_LINE> r += 'object def: ' + (', '.join(sorted(self.definition._object_class)) if self.definition._object_class else '<None>') + linesep <NEW_LINE> r += 'attr defs: ' + ', '.join(sorted(self.definition._attributes.keys())) + linesep <NEW_LINE> r += 'response: ' + ('present' if self.response else '<None>') + linesep <NEW_LINE> r += 'cursor: ' + (self.cursor.__class__.__name__ if self.cursor else '<None>') + linesep <NEW_LINE> return r <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return object.__repr__(self) <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__repr__() <NEW_LINE> <DEDENT> def __getstate__(self): <NEW_LINE> <INDENT> cpy = dict(self.__dict__) <NEW_LINE> cpy['cursor'] = None <NEW_LINE> return cpy <NEW_LINE> <DEDENT> def set_status(self, status): <NEW_LINE> <INDENT> conf_ignored_mandatory_attributes_in_object_def = [v.lower() for v in get_config_parameter('IGNORED_MANDATORY_ATTRIBUTES_IN_OBJECT_DEF')] <NEW_LINE> if status not in STATUSES: <NEW_LINE> <INDENT> error_message = 'invalid entry status ' + str(status) <NEW_LINE> if log_enabled(ERROR): <NEW_LINE> <INDENT> log(ERROR, '%s for <%s>', error_message, self) <NEW_LINE> <DEDENT> raise LDAPCursorError(error_message) <NEW_LINE> <DEDENT> if status in INITIAL_STATUSES: <NEW_LINE> <INDENT> self._initial_status = status <NEW_LINE> <DEDENT> self.status = status <NEW_LINE> if status == STATUS_DELETED: <NEW_LINE> <INDENT> self._initial_status = STATUS_VIRTUAL <NEW_LINE> <DEDENT> if status == STATUS_COMMITTED: <NEW_LINE> <INDENT> self._initial_status = STATUS_WRITABLE <NEW_LINE> <DEDENT> if self.status == STATUS_VIRTUAL or (self.status == STATUS_PENDING_CHANGES and self._initial_status == STATUS_VIRTUAL): <NEW_LINE> <INDENT> for attr in self.definition._attributes: <NEW_LINE> <INDENT> if self.definition._attributes[attr].mandatory and attr.lower() not in conf_ignored_mandatory_attributes_in_object_def: <NEW_LINE> <INDENT> if (attr not in self.attributes or self.attributes[attr].virtual) and attr not in self.changes: <NEW_LINE> <INDENT> self.status = STATUS_MANDATORY_MISSING <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def entry_raw_attributes(self): <NEW_LINE> <INDENT> return self.raw_attributes
Contains data on the status of the entry. Does not pollute the Entry __dict__.
6259906c2c8b7c6e89bd5008
class PayeeSchema(Schema): <NEW_LINE> <INDENT> id = fields.Int() <NEW_LINE> name = fields.Str(required=True) <NEW_LINE> role = EnumField(PayeeRole, by_value=True) <NEW_LINE> system = fields.Bool() <NEW_LINE> hidden = fields.Bool() <NEW_LINE> category_id = fields.Int() <NEW_LINE> account_id = fields.Int() <NEW_LINE> amount = fields.Decimal(places=4, as_string=True) <NEW_LINE> memo = fields.Str()
Schema for a `Payee` object
6259906cd268445f2663a76e
class ToTensor(object): <NEW_LINE> <INDENT> def __init__(self, channels, device): <NEW_LINE> <INDENT> self.channels = channels <NEW_LINE> self.device = device <NEW_LINE> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> image_real1, image_real2, image_fake = sample['image_real1'], sample['image_real2'], sample['image_fake'] <NEW_LINE> label_real1, label_real2, label_fake = sample['label_real1'], sample['label_real2'], sample['label_fake'] <NEW_LINE> mask_real1, mask_real2, mask_fake = sample['mask_real1'], sample['mask_real2'], sample['mask_fake'] <NEW_LINE> if self.channels == 1: <NEW_LINE> <INDENT> image_real1, image_real2, image_fake = image_real1[:,:,None], image_real2[:,:,None], image_fake[:,:,None] <NEW_LINE> <DEDENT> mask_real1, mask_real2, mask_fake = mask_real1[:,:,None], mask_real2[:,:,None], mask_fake[:,:,None] <NEW_LINE> image_real1 = np.ascontiguousarray(image_real1.transpose(2, 0, 1).astype(np.float32)) <NEW_LINE> image_real2 = np.ascontiguousarray(image_real2.transpose(2, 0, 1).astype(np.float32)) <NEW_LINE> image_fake = np.ascontiguousarray(image_fake.transpose(2, 0, 1).astype(np.float32)) <NEW_LINE> mask_real1 = np.ascontiguousarray(mask_real1.transpose(2, 0, 1).astype(np.float32)) <NEW_LINE> mask_real2 = np.ascontiguousarray(mask_real2.transpose(2, 0, 1).astype(np.float32)) <NEW_LINE> mask_fake = np.ascontiguousarray(mask_fake.transpose(2, 0, 1).astype(np.float32)) <NEW_LINE> label_real1 = np.ascontiguousarray(label_real1).astype(np.float32) <NEW_LINE> label_real2 = np.ascontiguousarray(label_real2).astype(np.float32) <NEW_LINE> label_fake = np.ascontiguousarray(label_fake).astype(np.float32) <NEW_LINE> image_real1 = torch.from_numpy(image_real1 * (1.0 / 255.0)).to(self.device) <NEW_LINE> image_real2 = torch.from_numpy(image_real2 * (1.0 / 255.0)).to(self.device) <NEW_LINE> image_fake = torch.from_numpy(image_fake * (1.0 / 255.0)).to(self.device) <NEW_LINE> mask_real1 = torch.from_numpy(mask_real1 * (1.0 / 255.0)).to(self.device) <NEW_LINE> mask_real2 = torch.from_numpy(mask_real2 * (1.0 / 255.0)).to(self.device) <NEW_LINE> mask_fake = torch.from_numpy(mask_fake * (1.0 / 255.0)).to(self.device) <NEW_LINE> label_real1 = torch.from_numpy(label_real1).to(self.device) <NEW_LINE> label_real2 = torch.from_numpy(label_real2).to(self.device) <NEW_LINE> label_fake = torch.from_numpy(label_fake).to(self.device) <NEW_LINE> return { 'image_real1': image_real1, 'image_real2': image_real2, 'image_fake': image_fake, 'mask_real1': mask_real1, 'mask_real2': mask_real2, 'mask_fake': mask_fake, 'label_real1': label_real1, 'label_real2': label_real2, 'label_fake': label_fake }
Convert ndarrays in sample to Tensors.
6259906c4c3428357761bad6
class Movie(object) : <NEW_LINE> <INDENT> def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube) : <NEW_LINE> <INDENT> self.title = movie_title <NEW_LINE> self.storyline = movie_storyline <NEW_LINE> self.poster_image_url = poster_image <NEW_LINE> self.trailer_youtube_url = trailer_youtube <NEW_LINE> <DEDENT> def show_trailer(self) : <NEW_LINE> <INDENT> webbrowser.open(self.youtube_trailer) <NEW_LINE> return
Class to store movie related information
6259906c45492302aabfdcfb
class TensorConfig: <NEW_LINE> <INDENT> def __init__(self, shape: [List[int]], dtype: [str]="float32", data: Optional[np.array]=None): <NEW_LINE> <INDENT> self.shape = shape <NEW_LINE> self.dtype = dtype <NEW_LINE> self.data = data
A config builder for a input or a weight. InputVar's shape can be [-1, xxx], batch_size
6259906c1b99ca4002290147
class ProfileFeedItem(models.Model): <NEW_LINE> <INDENT> user_profile = models.ForeignKey('UserProfile', on_delete = models.CASCADE) <NEW_LINE> status_text = models.CharField(max_length = 255) <NEW_LINE> created_on = models.DateTimeField(auto_now_add = True) <NEW_LINE> def ___str___(self): <NEW_LINE> <INDENT> return self.status_text
Profile status updates
6259906c8a43f66fc4bf39b6
class ApplicationGatewayBackendHealth(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'backend_address_pools': {'key': 'backendAddressPools', 'type': '[ApplicationGatewayBackendHealthPool]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ApplicationGatewayBackendHealth, self).__init__(**kwargs) <NEW_LINE> self.backend_address_pools = kwargs.get('backend_address_pools', None)
Response for ApplicationGatewayBackendHealth API service call. :param backend_address_pools: A list of ApplicationGatewayBackendHealthPool resources. :type backend_address_pools: list[~azure.mgmt.network.v2019_07_01.models.ApplicationGatewayBackendHealthPool]
6259906cf7d966606f7494cd
class W2Tree(FuncTree) : <NEW_LINE> <INDENT> def __init__ ( self , weight , tree = None ) : <NEW_LINE> <INDENT> assert isinstance ( weight , Weight ) , 'Wrong type of weight!' <NEW_LINE> assert tree is None or isinstance ( tree , ROOT.TTree ) , 'Wrong type of tree!' <NEW_LINE> FuncTree.__init__ ( self , tree ) <NEW_LINE> self.__weight = weight <NEW_LINE> <DEDENT> def evaluate ( self ) : <NEW_LINE> <INDENT> t = self.tree () <NEW_LINE> w = self.__weight ( t ) <NEW_LINE> return w <NEW_LINE> <DEDENT> @property <NEW_LINE> def weight ( self ) : <NEW_LINE> <INDENT> return self.__weight
Helper class to add the weight into ROOT.TTree >>> w = Weight ( ... ) ## the weighting object >>> tree = ... ## The tree >>> wf = W2Tree ( w , tree ) ## create the weighting function >>> tree.add_new_branch ( 'weight' , wf )
6259906c4f6381625f19a0b9
class Item(metaclass=ABCMeta): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def update(self): <NEW_LINE> <INDENT> pass
Clase abstracta que describe el contrato y comportamiento base de un Item.
6259906c76e4537e8c3f0da7
class LoginView(View): <NEW_LINE> <INDENT> template_name = 'gift/login.html' <NEW_LINE> port = 995 <NEW_LINE> next = '' <NEW_LINE> def get(self, request): <NEW_LINE> <INDENT> self.next = request.GET.get('next', '') <NEW_LINE> if request.user.is_authenticated() and not request.user.is_superuser: <NEW_LINE> <INDENT> return redirect('gift:option') <NEW_LINE> <DEDENT> args = dict(form=LoginForm(None), next=self.next) <NEW_LINE> return render(request, self.template_name, args) <NEW_LINE> <DEDENT> def post(self, request): <NEW_LINE> <INDENT> redirect_to = request.POST.get('next', self.next) <NEW_LINE> form = LoginForm(request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> username = form.cleaned_data.get('username') <NEW_LINE> password = form.cleaned_data.get('password') <NEW_LINE> server = form.cleaned_data.get('login_server') <NEW_LINE> print("calling authenticate function in django") <NEW_LINE> user = auth.authenticate(username=username, password=password, server=server, port=self.port) <NEW_LINE> print(user) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> if not is_safe_url(url=redirect_to, host=request.get_host()): <NEW_LINE> <INDENT> auth.login(request=request, user=user) <NEW_LINE> return redirect('gift:option') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return redirect(redirect_to) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> form.add_error(None, 'No user exists for given credentials.') <NEW_LINE> return render(request, self.template_name, dict(form=form)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return render(request, self.template_name, dict(form=form))
7 View class for handling login functionality.
6259906c3346ee7daa338270
class ModifyLoadBalancerAttributesRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.LoadBalancerId = None <NEW_LINE> self.LoadBalancerName = None <NEW_LINE> self.InternetChargeInfo = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.LoadBalancerId = params.get("LoadBalancerId") <NEW_LINE> self.LoadBalancerName = params.get("LoadBalancerName") <NEW_LINE> if params.get("InternetChargeInfo") is not None: <NEW_LINE> <INDENT> self.InternetChargeInfo = LoadBalancerInternetAccessible() <NEW_LINE> self.InternetChargeInfo._deserialize(params.get("InternetChargeInfo"))
ModifyLoadBalancerAttributes请求参数结构体
6259906ce1aae11d1e7cf41f
@registry.register_problem <NEW_LINE> class StanfordNLIWikiLMSharedVocab(StanfordNLI): <NEW_LINE> <INDENT> @property <NEW_LINE> def vocab_filename(self): <NEW_LINE> <INDENT> return wiki_lm.LanguagemodelEnWiki32k().vocab_filename
StanfordNLI classification problems with the Wiki vocabulary
6259906c1f5feb6acb164413
class XMLParser(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._tree = None <NEW_LINE> self._data: str = "" <NEW_LINE> <DEDENT> def _parse(self, data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> def get_first_link(self, path='data/select.xml') -> str: <NEW_LINE> <INDENT> root = ET.parse(path) <NEW_LINE> result = root.findall('*')[1] <NEW_LINE> for i in result.findall(".//doc"): <NEW_LINE> <INDENT> if i.findtext('str[@name="file_type"]').upper() == "DLTINS": <NEW_LINE> <INDENT> value = i.findtext('str[@name="download_link"]') <NEW_LINE> if not value: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return ""
Parser for XML file
6259906c99cbb53fe683270b
class Exportchownmode(basestring): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_api_name(): <NEW_LINE> <INDENT> return "exportchownmode"
restricted|unrestricted Possible values: <ul> <li> "restricted" , <li> "unrestricted" </ul>
6259906c5fc7496912d48e7a
class KOICatalog(ExoplanetArchiveCatalog): <NEW_LINE> <INDENT> name = "q1_q17_dr24_koi" <NEW_LINE> def join_stars(self, df=None): <NEW_LINE> <INDENT> if df is None: <NEW_LINE> <INDENT> df = self.df <NEW_LINE> <DEDENT> kic = KICatalog(data_root=self.data_root) <NEW_LINE> return pd.merge(df, kic.df, on="kepid")
Kepler Kepler Objects of Interest (Q1 through Q17)
6259906c92d797404e38976d
class _ConnectionCtx(object): <NEW_LINE> <INDENT> def __enter__(self): <NEW_LINE> <INDENT> global _db_ctx <NEW_LINE> self.should_cleanup = False <NEW_LINE> if not _db_ctx.is_init(): <NEW_LINE> <INDENT> _db_ctx.init() <NEW_LINE> self.should_cleanup = True <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exctype, excvalue, traceback): <NEW_LINE> <INDENT> global _db_ctx <NEW_LINE> if self.should_cleanup: <NEW_LINE> <INDENT> _db_ctx.cleanup()
开启和关闭 connection,并且可以嵌套使用,只作用于当前的connection with connection(): pass with connection(): pass 定义了__enter__()和__exit__()的对象可以用于with语句,确保任何情况下__exit__()方法可以被调用。
6259906c442bda511e95d96a
@Predictor.register("textual-entailment") <NEW_LINE> class DecomposableAttentionPredictor(Predictor): <NEW_LINE> <INDENT> def predict(self, premise: str, hypothesis: str) -> JsonDict: <NEW_LINE> <INDENT> return self.predict_json({"premise": premise, "hypothesis": hypothesis}) <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def _json_to_instance(self, json_dict: JsonDict) -> Instance: <NEW_LINE> <INDENT> premise_text = json_dict["premise"] <NEW_LINE> hypothesis_text = json_dict["hypothesis"] <NEW_LINE> return self._dataset_reader.text_to_instance(premise_text, hypothesis_text) <NEW_LINE> <DEDENT> @overrides <NEW_LINE> def predictions_to_labeled_instances( self, instance: Instance, outputs: Dict[str, numpy.ndarray] ) -> List[Instance]: <NEW_LINE> <INDENT> new_instance = deepcopy(instance) <NEW_LINE> label = numpy.argmax(outputs["label_logits"]) <NEW_LINE> new_instance.add_field("label", LabelField(int(label), skip_indexing=True)) <NEW_LINE> return [new_instance]
Predictor for the [`DecomposableAttention`](../models/decomposable_attention.md) model.
6259906cfff4ab517ebcf03f
class BibliographyTransform(docutils.transforms.Transform): <NEW_LINE> <INDENT> default_priority = 10 <NEW_LINE> def apply(self): <NEW_LINE> <INDENT> env = self.document.settings.env <NEW_LINE> for bibnode in self.document.traverse(bibliography): <NEW_LINE> <INDENT> id_ = bibnode['ids'][0] <NEW_LINE> entries = [get_bibliography_entry(env.bibtex_bibfiles, key) for key in env.footbib_cache.cited[env.docname][id_]] <NEW_LINE> entries2 = [entry for entry in entries if entry is not None] <NEW_LINE> style = find_plugin( 'pybtex.style.formatting', env.app.config.bibtex_style)() <NEW_LINE> backend = find_plugin('pybtex.backends', 'docutils')() <NEW_LINE> footnotes = docutils.nodes.paragraph() <NEW_LINE> for entry in style.format_entries(entries2): <NEW_LINE> <INDENT> footnote = backend.footnote(entry, self.document) <NEW_LINE> node_text_transform(footnote, transform_url_command) <NEW_LINE> footnotes += footnote <NEW_LINE> <DEDENT> if env.bibtex_footbibliography_header is not None: <NEW_LINE> <INDENT> nodes = [env.bibtex_footbibliography_header.deepcopy(), footnotes] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nodes = footnotes <NEW_LINE> <DEDENT> bibnode.replace_self(nodes)
A docutils transform to generate footnotes for bibliography nodes.
6259906c460517430c432c68
class Issue(models.Model): <NEW_LINE> <INDENT> subject = models.CharField( ugettext_lazy('Betreff'), max_length=255, help_text=ugettext_lazy( "Beispiel: 'Newsletter der ESG Leipzig – Wintersemester " "2015/2016 – Ausgabe 12'.")) <NEW_LINE> text = models.TextField( ugettext_lazy('Text'), help_text=ugettext_lazy( 'Der Newsletter wird als plain text versendet, das heißt, ' 'HTML-Tags können nicht verwendet werden.')) <NEW_LINE> mailed_on = models.DateTimeField( ugettext_lazy('Versendet am'), auto_now_add=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('mailed_on',) <NEW_LINE> verbose_name = ugettext_lazy('Ausgabe') <NEW_LINE> verbose_name_plural = ugettext_lazy('Ausgaben') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ' – '.join((localize(self.mailed_on), self.subject))
Model for newsletter issues.
6259906c4527f215b58eb5b2
class InferenceModule: <NEW_LINE> <INDENT> def __init__(self, ghostAgent): <NEW_LINE> <INDENT> self.ghostAgent = ghostAgent <NEW_LINE> self.index = ghostAgent.index <NEW_LINE> <DEDENT> def getPositionDistribution(self, gameState): <NEW_LINE> <INDENT> ghostPosition = gameState.getGhostPosition(self.index) <NEW_LINE> actionDist = self.ghostAgent.getDistribution(gameState) <NEW_LINE> dist = util.Counter() <NEW_LINE> for action, prob in actionDist.items(): <NEW_LINE> <INDENT> successorPosition = game.Actions.getSuccessor(ghostPosition, action) <NEW_LINE> dist[successorPosition] = prob <NEW_LINE> <DEDENT> return dist <NEW_LINE> <DEDENT> def setGhostPosition(self, gameState, ghostPosition): <NEW_LINE> <INDENT> conf = game.Configuration(ghostPosition, game.Directions.STOP) <NEW_LINE> gameState.data.agentStates[self.index] = game.AgentState(conf, False) <NEW_LINE> return gameState <NEW_LINE> <DEDENT> def observeState(self, gameState): <NEW_LINE> <INDENT> distances = gameState.getNoisyGhostDistances() <NEW_LINE> if len(distances) >= self.index: <NEW_LINE> <INDENT> obs = distances[self.index - 1] <NEW_LINE> self.observe(obs, gameState) <NEW_LINE> <DEDENT> <DEDENT> def initialize(self, gameState): <NEW_LINE> <INDENT> self.legalPositions = [p for p in gameState.getWalls().asList(False) if p[1] > 1] <NEW_LINE> self.initializeUniformly(gameState) <NEW_LINE> <DEDENT> def initializeUniformly(self, gameState): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def observe(self, observation, gameState): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def elapseTime(self, gameState): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getBeliefDistribution(self): <NEW_LINE> <INDENT> pass
An inference module tracks a belief distribution over a ghost's location. This is an abstract class, which you should not modify.
6259906cd486a94d0ba2d7e4
class PersonalDetails(TelegramObject): <NEW_LINE> <INDENT> def __init__( self, first_name: str, last_name: str, birth_date: str, gender: str, country_code: str, residence_country_code: str, first_name_native: str = None, last_name_native: str = None, middle_name: str = None, middle_name_native: str = None, bot: 'Bot' = None, **_kwargs: Any, ): <NEW_LINE> <INDENT> self.first_name = first_name <NEW_LINE> self.last_name = last_name <NEW_LINE> self.middle_name = middle_name <NEW_LINE> self.birth_date = birth_date <NEW_LINE> self.gender = gender <NEW_LINE> self.country_code = country_code <NEW_LINE> self.residence_country_code = residence_country_code <NEW_LINE> self.first_name_native = first_name_native <NEW_LINE> self.last_name_native = last_name_native <NEW_LINE> self.middle_name_native = middle_name_native <NEW_LINE> self.bot = bot
This object represents personal details. Attributes: first_name (:obj:`str`): First Name. middle_name (:obj:`str`): Optional. First Name. last_name (:obj:`str`): Last Name. birth_date (:obj:`str`): Date of birth in DD.MM.YYYY format. gender (:obj:`str`): Gender, male or female. country_code (:obj:`str`): Citizenship (ISO 3166-1 alpha-2 country code). residence_country_code (:obj:`str`): Country of residence (ISO 3166-1 alpha-2 country code). first_name_native (:obj:`str`): First Name in the language of the user's country of residence. middle_name_native (:obj:`str`): Optional. Middle Name in the language of the user's country of residence. last_name_native (:obj:`str`): Last Name in the language of the user's country of residence.
6259906cd268445f2663a76f
class ScheduleUpdateParameters(msrest.serialization.Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'description': {'key': 'properties.description', 'type': 'str'}, 'is_enabled': {'key': 'properties.isEnabled', 'type': 'bool'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(ScheduleUpdateParameters, self).__init__(**kwargs) <NEW_LINE> self.name = kwargs.get('name', None) <NEW_LINE> self.description = kwargs.get('description', None) <NEW_LINE> self.is_enabled = kwargs.get('is_enabled', None)
The parameters supplied to the update schedule operation. :param name: Gets or sets the name of the Schedule. :type name: str :param description: Gets or sets the description of the schedule. :type description: str :param is_enabled: Gets or sets a value indicating whether this schedule is enabled. :type is_enabled: bool
6259906cac7a0e7691f73d0c
class CredentialsFormatError(Exception): <NEW_LINE> <INDENT> def __init__(self, custom_message=None): <NEW_LINE> <INDENT> self.msg = 'Ill-formatted credentials' <NEW_LINE> self.custom_message = custom_message <NEW_LINE> if self.custom_message is not None: <NEW_LINE> <INDENT> self.msg += ': '+self.custom_message <NEW_LINE> <DEDENT> self.msg += '.' <NEW_LINE> super(self.__class__, self).__init__(self.msg)
To be raised if credentials are ill-formatted or miss essential items.
6259906c0c0af96317c57971
class CurrencyRate(db.Model): <NEW_LINE> <INDENT> __tablename__ = 'currency_rate' <NEW_LINE> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> currency = db.Column(db.String(3)) <NEW_LINE> rate = db.Column(db.Numeric) <NEW_LINE> base_currency_id = db.Column(db.Integer, db.ForeignKey('base_currency.id'), nullable=False) <NEW_LINE> __table_args__ = ( db.UniqueConstraint('currency', 'base_currency_id'), ) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return f'CurrencyRate base_id: {self.base_currency_id} ' f'currency: {self.currency}, rate: {self.rate}'
Currency Rate model
6259906c63b5f9789fe86987
class MedicineFormMedicines(models.Model): <NEW_LINE> <INDENT> countryform = models.ForeignKey(CountryForm) <NEW_LINE> medicine = models.ManyToManyField(Medicine) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name_plural = "Medicine Form Medicines" <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return u"%s" % (self.countryform)
Class used to allocate specific medicines to specific forms. This is useful in the case where one country has multiple medicines forms. When creating the medicines form those medicines listed in this table will be allocated to that specific form. In the implementation, if a form is not listed here, then all the medicines listed in that country will be used instead. I'm not really happy with this class because without the comment, it is not clear what it does but I'm not sure how to implement it in any other way. It also introduces redundancy in the country field with the medicines table.
6259906c45492302aabfdcfd
class SwiftAPI(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> session = _get_swift_session() <NEW_LINE> params = { 'retries': CONF.swift.swift_max_retries, 'preauthurl': keystone.get_service_url( session, service_type='object-store'), 'preauthtoken': keystone.get_admin_auth_token(session) } <NEW_LINE> verify = session.verify <NEW_LINE> params['insecure'] = not verify <NEW_LINE> if verify and isinstance(verify, six.string_types): <NEW_LINE> <INDENT> params['cacert'] = verify <NEW_LINE> <DEDENT> self.connection = swift_client.Connection(**params) <NEW_LINE> <DEDENT> def create_object(self, container, object, filename, object_headers=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection.put_container(container) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("put container") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> with open(filename, "r") as fileobj: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj_uuid = self.connection.put_object(container, object, fileobj, headers=object_headers) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("put object") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> <DEDENT> return obj_uuid <NEW_LINE> <DEDENT> def get_temp_url(self, container, object, timeout): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> account_info = self.connection.head_account() <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("head account") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> parse_result = parse.urlparse(self.connection.url) <NEW_LINE> swift_object_path = '/'.join((parse_result.path, container, object)) <NEW_LINE> temp_url_key = account_info['x-account-meta-temp-url-key'] <NEW_LINE> url_path = swift_utils.generate_temp_url(swift_object_path, timeout, temp_url_key, 'GET') <NEW_LINE> return parse.urlunparse((parse_result.scheme, parse_result.netloc, url_path, None, None, None)) <NEW_LINE> <DEDENT> def delete_object(self, container, object): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection.delete_object(container, object) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("delete object") <NEW_LINE> if e.http_status == http_client.NOT_FOUND: <NEW_LINE> <INDENT> raise exception.SwiftObjectNotFoundError(object=object, container=container, operation=operation) <NEW_LINE> <DEDENT> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> <DEDENT> def head_object(self, container, object): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.connection.head_object(container, object) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("head object") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e) <NEW_LINE> <DEDENT> <DEDENT> def update_object_meta(self, container, object, object_headers): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection.post_object(container, object, object_headers) <NEW_LINE> <DEDENT> except swift_exceptions.ClientException as e: <NEW_LINE> <INDENT> operation = _("post object") <NEW_LINE> raise exception.SwiftOperationError(operation=operation, error=e)
API for communicating with Swift.
6259906c38b623060ffaa465
class ModifiedMixin: <NEW_LINE> <INDENT> def _init(self): <NEW_LINE> <INDENT> self.clearModifiedFlag() <NEW_LINE> self.bind('<<Modified>>', self._beenModified) <NEW_LINE> <DEDENT> def _beenModified(self, event=None): <NEW_LINE> <INDENT> if self._resetting_modified_flag: return <NEW_LINE> self.clearModifiedFlag() <NEW_LINE> self.beenModified(event) <NEW_LINE> <DEDENT> def beenModified(self, event=None): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def clearModifiedFlag(self): <NEW_LINE> <INDENT> self._resetting_modified_flag = True <NEW_LINE> try: <NEW_LINE> <INDENT> self.tk.call(self._w, 'edit', 'modified', 0) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self._resetting_modified_flag = False
Class to allow a Tkinter Text widget to notice when it's modified. To use this mixin, subclass from Tkinter.Text and the mixin, then write an __init__() method for the new class that calls _init(). Then override the beenModified() method to implement the behavior that you want to happen when the Text is modified.
6259906ca219f33f346c802d
class Window(object): <NEW_LINE> <INDENT> _JAVA_MIN_LONG = -(1 << 63) <NEW_LINE> _JAVA_MAX_LONG = (1 << 63) - 1 <NEW_LINE> _PRECEDING_THRESHOLD = max(-sys.maxsize, _JAVA_MIN_LONG) <NEW_LINE> _FOLLOWING_THRESHOLD = min(sys.maxsize, _JAVA_MAX_LONG) <NEW_LINE> unboundedPreceding = _JAVA_MIN_LONG <NEW_LINE> unboundedFollowing = _JAVA_MAX_LONG <NEW_LINE> currentRow = 0 <NEW_LINE> @staticmethod <NEW_LINE> @since(1.4) <NEW_LINE> def partitionBy(*cols): <NEW_LINE> <INDENT> sc = SparkContext._active_spark_context <NEW_LINE> jspec = sc._jvm.org.apache.spark.sql.expressions.Window.partitionBy(_to_java_cols(cols)) <NEW_LINE> return WindowSpec(jspec) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @since(1.4) <NEW_LINE> def orderBy(*cols): <NEW_LINE> <INDENT> sc = SparkContext._active_spark_context <NEW_LINE> jspec = sc._jvm.org.apache.spark.sql.expressions.Window.orderBy(_to_java_cols(cols)) <NEW_LINE> return WindowSpec(jspec) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @since(2.1) <NEW_LINE> def rowsBetween(start, end): <NEW_LINE> <INDENT> if start <= Window._PRECEDING_THRESHOLD: <NEW_LINE> <INDENT> start = Window.unboundedPreceding <NEW_LINE> <DEDENT> if end >= Window._FOLLOWING_THRESHOLD: <NEW_LINE> <INDENT> end = Window.unboundedFollowing <NEW_LINE> <DEDENT> sc = SparkContext._active_spark_context <NEW_LINE> jspec = sc._jvm.org.apache.spark.sql.expressions.Window.rowsBetween(start, end) <NEW_LINE> return WindowSpec(jspec) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> @since(2.1) <NEW_LINE> def rangeBetween(start, end): <NEW_LINE> <INDENT> if isinstance(start, (int, long)) and isinstance(end, (int, long)): <NEW_LINE> <INDENT> if start <= Window._PRECEDING_THRESHOLD: <NEW_LINE> <INDENT> start = Window.unboundedPreceding <NEW_LINE> <DEDENT> if end >= Window._FOLLOWING_THRESHOLD: <NEW_LINE> <INDENT> end = Window.unboundedFollowing <NEW_LINE> <DEDENT> <DEDENT> elif isinstance(start, Column) and isinstance(end, Column): <NEW_LINE> <INDENT> start = start._jc <NEW_LINE> end = end._jc <NEW_LINE> <DEDENT> sc = SparkContext._active_spark_context <NEW_LINE> jspec = sc._jvm.org.apache.spark.sql.expressions.Window.rangeBetween(start, end) <NEW_LINE> return WindowSpec(jspec)
Utility functions for defining window in DataFrames. For example: >>> # ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW >>> window = Window.orderBy("date").rowsBetween(Window.unboundedPreceding, Window.currentRow) >>> # PARTITION BY country ORDER BY date RANGE BETWEEN 3 PRECEDING AND 3 FOLLOWING >>> window = Window.orderBy("date").partitionBy("country").rangeBetween(-3, 3) .. note:: Experimental .. versionadded:: 1.4
6259906c76e4537e8c3f0da8
class VisualisationData(BaseData): <NEW_LINE> <INDENT> name_attributes = [ "xl_x_value", "xl_y_value", "xl_z_value", "gyro_x_value", "gyro_y_value", "gyro_z_value", "altitude_value", "time_stamp", ] <NEW_LINE> math_mutation = [ MutationScaleData, MutationAxeGenerateData ]
Набор данных для визуализации
6259906c097d151d1a2c2895
class _RC(configparser.SafeConfigParser): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> configparser.SafeConfigParser.__init__(self) <NEW_LINE> self.reload_rc() <NEW_LINE> <DEDENT> def _clear(self): <NEW_LINE> <INDENT> self.remove_section(configparser.DEFAULTSECT) <NEW_LINE> for s in self.sections(): <NEW_LINE> <INDENT> self.remove_section(s) <NEW_LINE> <DEDENT> <DEDENT> def _init_defaults(self): <NEW_LINE> <INDENT> for section, settings in RC_DEFAULTS.items(): <NEW_LINE> <INDENT> self.add_section(section) <NEW_LINE> for k, v in settings.items(): <NEW_LINE> <INDENT> self.set(section, k, str(v)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def read_file(self, fp, filename=None): <NEW_LINE> <INDENT> if filename is None: <NEW_LINE> <INDENT> if hasattr(fp, 'name'): <NEW_LINE> <INDENT> filename = fp.name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filename = '<???>' <NEW_LINE> <DEDENT> <DEDENT> logger.info('Reading configuration from {}'.format(filename)) <NEW_LINE> try: <NEW_LINE> <INDENT> return configparser.SafeConfigParser.read_file(self, fp, filename) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return configparser.SafeConfigParser.readfp(self, fp, filename) <NEW_LINE> <DEDENT> <DEDENT> def read(self, filenames): <NEW_LINE> <INDENT> logger.info('Reading configuration files {}'.format(filenames)) <NEW_LINE> return configparser.SafeConfigParser.read(self, filenames) <NEW_LINE> <DEDENT> def reload_rc(self, filenames=None): <NEW_LINE> <INDENT> if filenames is None: <NEW_LINE> <INDENT> filenames = RC_FILES <NEW_LINE> <DEDENT> self._clear() <NEW_LINE> self._init_defaults() <NEW_LINE> self.read(filenames)
Allows reading from and writing to Sirsim RC settings. This object is a :class:`configparser.ConfigParser`, which means that values can be accessed and manipulated with ``get`` and ``set``:: oldsize = sirsim.rc.get("decoder_cache", "size") sirsim.rc.set("decoder_cache", "size", "2 GB") ``get`` and ``set`` return and expect strings. There are also special getter methods for booleans, ints, and floats:: simple = sirsim.rc.getboolean("exceptions", "simplified") In addition to the normal :class:`configparser.ConfigParser` methods, this object also has a ``reload_rc`` method to reset ``sirsim.rc`` to default settings:: sirsim.rc.reload_rc() # Reads defaults from configuration files sirsim.rc.reload_rc(filenames=[]) # Ignores configuration files
6259906c0a50d4780f7069d3
class ApplicationTypeInfo(Model): <NEW_LINE> <INDENT> _attribute_map = { 'name': {'key': 'Name', 'type': 'str'}, 'version': {'key': 'Version', 'type': 'str'}, 'status': {'key': 'Status', 'type': 'str'}, 'default_parameter_list': {'key': 'DefaultParameterList', 'type': '[ApplicationParameter]'}, } <NEW_LINE> def __init__(self, name=None, version=None, status=None, default_parameter_list=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.version = version <NEW_LINE> self.status = status <NEW_LINE> self.default_parameter_list = default_parameter_list
Information about an application type. :param name: The name of the application type. :type name: str :param version: The version of the application type. :type version: str :param status: Possible values include: 'Invalid', 'Provisioning', 'Available', 'Unprovisioning', 'Failed' :type status: str :param default_parameter_list: :type default_parameter_list: list of :class:`ApplicationParameter <azure.servicefabric.models.ApplicationParameter>`
6259906c16aa5153ce401cff
class Person: <NEW_LINE> <INDENT> def __init__(self, name, eyecolor, age): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.eyecolor = eyecolor <NEW_LINE> self.age = age
This describes about the Person
6259906c3317a56b869bf156
class Model_336(SerialDevice): <NEW_LINE> <INDENT> def __init__(self, settings): <NEW_LINE> <INDENT> settings = {**DEFAULTS, **settings} <NEW_LINE> self.units = settings.get("units", "K") <NEW_LINE> super().__init__(settings) <NEW_LINE> <DEDENT> units = property(operator.attrgetter('_units')) <NEW_LINE> @units.setter <NEW_LINE> def units(self, value): <NEW_LINE> <INDENT> assert value in ["C", "K"], "valid units : 'C', 'K'" <NEW_LINE> self.cmd = codecs.decode(value + "RDG?{sensor}\r\n", "unicode-escape") <NEW_LINE> self._units = value <NEW_LINE> <DEDENT> def read_sensor(self, sensor): <NEW_LINE> <INDENT> serial_cmd = self.cmd.format(sensor=sensor) <NEW_LINE> logger.debug(f"read_data() sensor={sensor} query: {serial_cmd}") <NEW_LINE> self.write(bytes(serial_cmd, "utf8")) <NEW_LINE> response = self.readline() <NEW_LINE> logger.debug(f"read_data() sensor={sensor} response: {response}") <NEW_LINE> response = response.strip().decode("utf-8") <NEW_LINE> return response
read Lakeshore Model 336 temperature sensors
6259906caad79263cf42ffdb
class DeployHooks(SignalHandler): <NEW_LINE> <INDENT> name = 'deploy_hooks' <NEW_LINE> def run_hooks(self, event): <NEW_LINE> <INDENT> if event['clean'] and self.site.config.get('NO_HOOKS_ON_CLEAN', True): <NEW_LINE> <INDENT> self.logger.notice("No hooks run, since site was cleaned.") <NEW_LINE> return <NEW_LINE> <DEDENT> for entry_type in ('deployed', 'undeployed'): <NEW_LINE> <INDENT> for entry in event[entry_type]: <NEW_LINE> <INDENT> hook_key_name = '%s_HOOKS' % entry_type.upper() <NEW_LINE> for command in self.site.config.get(hook_key_name, []): <NEW_LINE> <INDENT> if callable(command): <NEW_LINE> <INDENT> command(entry) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._run_command(self._format_command(command, entry)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def set_site(self, site): <NEW_LINE> <INDENT> self.site = site <NEW_LINE> self.logger = get_logger(self.name, self.site.loghandlers) <NEW_LINE> ready = signal('deployed') <NEW_LINE> ready.connect(self.run_hooks) <NEW_LINE> <DEDENT> def _format_command(self, template, entry): <NEW_LINE> <INDENT> context = dict(entry=entry) <NEW_LINE> command = self.site.template_system.render_template_to_string( template, context ) <NEW_LINE> return command <NEW_LINE> <DEDENT> def _run_command(self, command): <NEW_LINE> <INDENT> self.logger.notice("==> {0}".format(command)) <NEW_LINE> try: <NEW_LINE> <INDENT> subprocess.check_call(command, shell=True) <NEW_LINE> <DEDENT> except subprocess.CalledProcessError as e: <NEW_LINE> <INDENT> self.logger.error('Failed post deploy hook — command {0} ' 'returned {1}'.format(e.cmd, e.returncode)) <NEW_LINE> sys.exit(e.returncode)
Add custom actions to be performed when new posts are deployed.
6259906c44b2445a339b7572
@ui.register_ui( button_delete=ui.Button(By.CSS_SELECTOR, 'button.btn-danger'), dropdown_menu=DropdownMenu(), link_folder=ui.Link(By.XPATH, './td//a')) <NEW_LINE> class RowObject(_ui.Row): <NEW_LINE> <INDENT> pass
Row with object.
6259906c4e4d562566373c2c
class SurfaceBaseSeries(BaseSeries): <NEW_LINE> <INDENT> is_3Dsurface = True <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(SurfaceBaseSeries, self).__init__() <NEW_LINE> self.surface_color = None <NEW_LINE> <DEDENT> def get_color_array(self): <NEW_LINE> <INDENT> c = self.surface_color <NEW_LINE> if callable(c): <NEW_LINE> <INDENT> f = np.vectorize(c) <NEW_LINE> arity = len(getargspec(c)[0]) <NEW_LINE> if self.is_parametric: <NEW_LINE> <INDENT> variables = map(centers_of_faces,self.get_parameter_meshes()) <NEW_LINE> if arity == 1: <NEW_LINE> <INDENT> return f(variables[0]) <NEW_LINE> <DEDENT> elif arity == 2: <NEW_LINE> <INDENT> return f(*variables) <NEW_LINE> <DEDENT> <DEDENT> variables = map(centers_of_faces, self.get_meshes()) <NEW_LINE> if arity == 1: <NEW_LINE> <INDENT> return f(variables[0]) <NEW_LINE> <DEDENT> elif arity == 2: <NEW_LINE> <INDENT> return f(*variables[:2]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return f(*variables) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return c*np.ones(self.nb_of_points)
A base class for 3D surfaces.
6259906c99cbb53fe683270d
class AuthorizationToken: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.response = self.generate(**kwargs) <NEW_LINE> <DEDENT> def generate(self, **kwargs): <NEW_LINE> <INDENT> return dict(code='', state='', status_code=302)
[RFC6749 - Section:] 4.1.2. Authorization Response If the resource owner grants the access request, the authorization server issues an authorization code and delivers it to the client
6259906c3539df3088ecdac5
class HTTPPreconditionFailed(HTTPError): <NEW_LINE> <INDENT> def __init__(self, title, description, **kwargs): <NEW_LINE> <INDENT> HTTPError.__init__(self, status.HTTP_412, title, description, **kwargs)
412 Precondition Failed. The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. This response code allows the client to place preconditions on the current resource metainformation (header field data) and thus prevent the requested method from being applied to a resource other than the one intended. (RFC 2616) Args: title (str): Error title (e.g., 'Image Not Modified'). description (str): Human-friendly description of the error, along with a helpful suggestion or two. kwargs (optional): Same as for ``HTTPError``.
6259906cdd821e528d6da594
class ReferralRequest(domainresource.DomainResource): <NEW_LINE> <INDENT> resource_name = "ReferralRequest" <NEW_LINE> def __init__(self, jsondict=None): <NEW_LINE> <INDENT> self.date = None <NEW_LINE> self.dateSent = None <NEW_LINE> self.description = None <NEW_LINE> self.encounter = None <NEW_LINE> self.fulfillmentTime = None <NEW_LINE> self.identifier = None <NEW_LINE> self.patient = None <NEW_LINE> self.priority = None <NEW_LINE> self.reason = None <NEW_LINE> self.recipient = None <NEW_LINE> self.requester = None <NEW_LINE> self.serviceRequested = None <NEW_LINE> self.specialty = None <NEW_LINE> self.status = None <NEW_LINE> self.supportingInformation = None <NEW_LINE> self.type = None <NEW_LINE> super(ReferralRequest, self).__init__(jsondict) <NEW_LINE> <DEDENT> def elementProperties(self): <NEW_LINE> <INDENT> js = super(ReferralRequest, self).elementProperties() <NEW_LINE> js.extend([ ("date", "date", fhirdate.FHIRDate, False, None, False), ("dateSent", "dateSent", fhirdate.FHIRDate, False, None, False), ("description", "description", str, False, None, False), ("encounter", "encounter", fhirreference.FHIRReference, False, None, False), ("fulfillmentTime", "fulfillmentTime", period.Period, False, None, False), ("identifier", "identifier", identifier.Identifier, True, None, False), ("patient", "patient", fhirreference.FHIRReference, False, None, False), ("priority", "priority", codeableconcept.CodeableConcept, False, None, False), ("reason", "reason", codeableconcept.CodeableConcept, False, None, False), ("recipient", "recipient", fhirreference.FHIRReference, True, None, False), ("requester", "requester", fhirreference.FHIRReference, False, None, False), ("serviceRequested", "serviceRequested", codeableconcept.CodeableConcept, True, None, False), ("specialty", "specialty", codeableconcept.CodeableConcept, False, None, False), ("status", "status", str, False, None, True), ("supportingInformation", "supportingInformation", fhirreference.FHIRReference, True, None, False), ("type", "type", codeableconcept.CodeableConcept, False, None, False), ]) <NEW_LINE> return js
A request for referral or transfer of care. Used to record and send details about a request for referral service or transfer of a patient to the care of another provider or provider organization.
6259906c91f36d47f2231aa2
class PatternTokenizer(Tokenizer): <NEW_LINE> <INDENT> solr_class = 'solr.PatternTokenizerFactory' <NEW_LINE> options = ['pattern', 'group']
To be subclassed further as needed, for instance: class GroupingPatternTokenizer(PatternTokenizer): pattern= "'([^']+)'" group = 1
6259906c4c3428357761bada
class CourseDetailStudentsView(CourseDetailStudentViewMixin, FormView): <NEW_LINE> <INDENT> form_class = AddStudentOnCourseForm <NEW_LINE> template_name = "learning/course/details/students.html" <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context.update( PaginatorFactory.get_paginator_as_context( self.object.registrations.order_by("student__last_login").all(), self.request.GET, nb_per_page=10) ) <NEW_LINE> context["number_student"] = self.object.registrations.count() <NEW_LINE> return context
View students registered on a course in a HTML page.
6259906cf548e778e596cdb4
class Start: <NEW_LINE> <INDENT> def GET(self): <NEW_LINE> <INDENT> return render.start()
This class shows the homepage (refers to 'start.html').
6259906c21bff66bcd72448e
class ExpressRouteServiceProvider(Resource): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'peering_locations': {'key': 'properties.peeringLocations', 'type': '[str]'}, 'bandwidths_offered': {'key': 'properties.bandwidthsOffered', 'type': '[ExpressRouteServiceProviderBandwidthsOffered]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__(self, id=None, location=None, tags=None, peering_locations=None, bandwidths_offered=None, provisioning_state=None): <NEW_LINE> <INDENT> super(ExpressRouteServiceProvider, self).__init__(id=id, location=location, tags=tags) <NEW_LINE> self.peering_locations = peering_locations <NEW_LINE> self.bandwidths_offered = bandwidths_offered <NEW_LINE> self.provisioning_state = provisioning_state
A ExpressRouteResourceProvider object. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource location. :type location: str :param tags: Resource tags. :type tags: dict[str, str] :param peering_locations: Get a list of peering locations. :type peering_locations: list[str] :param bandwidths_offered: Gets bandwidths offered. :type bandwidths_offered: list[~azure.mgmt.network.v2016_12_01.models.ExpressRouteServiceProviderBandwidthsOffered] :param provisioning_state: Gets the provisioning state of the resource. :type provisioning_state: str
6259906ca17c0f6771d5d7bc
class _Fax(object): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> self._client = client <NEW_LINE> <DEDENT> def send(self, to, files=None, content_urls=None, header_text=None, batch_delay=None, batch_collision_avoidance=None, callback_url=None, cancel_timeout=None, tags_dict=None, caller_id=None, test_fail=None): <NEW_LINE> <INDENT> if isinstance(files, string_types): <NEW_LINE> <INDENT> files = [files] <NEW_LINE> <DEDENT> if isinstance(content_urls, string_types): <NEW_LINE> <INDENT> content_urls = [content_urls] <NEW_LINE> <DEDENT> if isinstance(to, string_types): <NEW_LINE> <INDENT> to = [to] <NEW_LINE> <DEDENT> opt_args = _opt_args_to_dict(file=files, content_url=content_urls, header_text=header_text, batch_delay=batch_delay, batch_collision_avoidance=batch_collision_avoidance, callback_url=callback_url, cancel_timeout=cancel_timeout, caller_id=caller_id, test_fail=test_fail) <NEW_LINE> _add_tags_dict(tags_dict, opt_args) <NEW_LINE> return self._client.send_fax(to=to, **opt_args) <NEW_LINE> <DEDENT> def status(self, fax_id): <NEW_LINE> <INDENT> return self._client.get_fax(fax_id) <NEW_LINE> <DEDENT> def cancel(self, fax_id): <NEW_LINE> <INDENT> return self._client.cancel_fax(fax_id) <NEW_LINE> <DEDENT> def get_file(self, fax_id, thumbnail=None): <NEW_LINE> <INDENT> opt_args = _opt_args_to_dict(thumbnail=thumbnail) <NEW_LINE> return self._client.get_fax_file(fax_id, **opt_args) <NEW_LINE> <DEDENT> def delete(self, fax_id): <NEW_LINE> <INDENT> return self._client.delete_fax(fax_id) <NEW_LINE> <DEDENT> def delete_file(self, fax_id): <NEW_LINE> <INDENT> return self._client.delete_fax_file(fax_id) <NEW_LINE> <DEDENT> def resend(self, fax_id): <NEW_LINE> <INDENT> return self._client.resend_fax(fax_id) <NEW_LINE> <DEDENT> def query_faxes(self, created_before=None, created_after=None, direction=None, status=None, phone_number=None, tags_dict=None, per_page=None, page=None): <NEW_LINE> <INDENT> opt_args = _opt_args_to_dict(created_before=created_before, created_after=created_after, direction=direction, status=status, phone_number=phone_number, per_page=per_page, page=page) <NEW_LINE> _add_tags_dict(tags_dict, opt_args) <NEW_LINE> return self._client.query_faxes(**opt_args)
class for all APIs related to faxes. Don't instantiate directly - use the Fax instance in the PhaxioApi object.
6259906ccc0a2c111447c6e4
class RequestVerifier(object): <NEW_LINE> <INDENT> def __init__(self, accept_remote, accept_ips, docker_logging): <NEW_LINE> <INDENT> self.__accept_remote = accept_remote <NEW_LINE> self.__accept_ips = accept_ips <NEW_LINE> self.__docker_logging = docker_logging <NEW_LINE> <DEDENT> def verify_request(self, client_address): <NEW_LINE> <INDENT> result = True <NEW_LINE> address, port = client_address <NEW_LINE> if self.__docker_logging: <NEW_LINE> <INDENT> result = self.__accept_remote or address in self.__accept_ips <NEW_LINE> <DEDENT> if not result: <NEW_LINE> <INDENT> global_log.log( scalyr_logging.DEBUG_LEVEL_4, "Rejecting request from %s" % six.text_type(client_address), ) <NEW_LINE> <DEDENT> return result
Determines whether or not a request should be processed based on the state of various config options
6259906c4a966d76dd5f0711
class Mutator(MutatorDescribe): <NEW_LINE> <INDENT> pass
Relaxes around a residue on init and mutates. * ``.target`` mutation see Target namedtuple (resi, chain) * ``.neighbours`` list of neighbours * ``.pdbblock`` str pdb block * ``.pose`` pyrosetta.Pose * ``._pdb2pose`` points to ``self.pose.pdb_info().pdb2pose``, while target_pdb2pose accepts Target and gives back int
6259906c097d151d1a2c2897
class QuestionQuote(Quote): <NEW_LINE> <INDENT> def says(self): <NEW_LINE> <INDENT> return self.words + '?'
docstring for QuestionQuote
6259906c3346ee7daa338272
class BuildErrorException(Exception): <NEW_LINE> <INDENT> def __init__(self, message='Build Error'): <NEW_LINE> <INDENT> self.message = message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return repr(self.message)
Exception on server build
6259906c3317a56b869bf157
class Primitive_verify_sig (Primitive): <NEW_LINE> <INDENT> def __init__ (self, G, name, attributes): <NEW_LINE> <INDENT> interfaces = { 'inputs': ['msg', 'auth', 'pubkey'], 'outputs': ['result'] } <NEW_LINE> super ().setup (name, G, attributes, interfaces) <NEW_LINE> self.append_rule (Intg(self.input.pubkey)) <NEW_LINE> self.append_rule (Implies (Conf(self.input.msg), Conf(self.output.result)))
The signature verification primitive Checks whether an auth value represents a valid message signature by a given public key.
6259906c67a9b606de5476b6
class TFIDF(NgramExtractor): <NEW_LINE> <INDENT> def __init__(self, n) -> None: <NEW_LINE> <INDENT> super().__init__(n)
Extracts TF-IDF
6259906ce76e3b2f99fda229
class SpectralClustering: <NEW_LINE> <INDENT> def __init__(self, n_clusters, norm_method='row', is_exact=True): <NEW_LINE> <INDENT> self.nc = n_clusters <NEW_LINE> self.is_exact = is_exact <NEW_LINE> if norm_method == None: <NEW_LINE> <INDENT> self.norm = 0 <NEW_LINE> <DEDENT> elif norm_method == 'row': <NEW_LINE> <INDENT> self.norm = 1 <NEW_LINE> <DEDENT> elif norm_method == 'deg': <NEW_LINE> <INDENT> self.norm = 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("norm_method can only be one of {None, 'row', 'deg'}.") <NEW_LINE> <DEDENT> print('> Initialization parameters: n_cluster={}'.format(self.nc)) <NEW_LINE> if self.norm == 0: <NEW_LINE> <INDENT> print('> Unnormalized spectral embedding.') <NEW_LINE> <DEDENT> elif self.norm == 1: <NEW_LINE> <INDENT> print('> Row normalized spectral embedding.') <NEW_LINE> <DEDENT> elif self.norm == 2: <NEW_LINE> <INDENT> print('> Degree normalized spectral embedding.') <NEW_LINE> <DEDENT> <DEDENT> def compute_eigs(self): <NEW_LINE> <INDENT> if self.is_exact: <NEW_LINE> <INDENT> self.Heigval, self.Heigvec = np.linalg.eigh(self.H_) <NEW_LINE> print('> Exact eigs done') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Heigval, self.Heigvec = sp.sparse.linalg.eigsh(self.H_, k=self.nc, which='SM') <NEW_LINE> print('> Approximate eigs done') <NEW_LINE> <DEDENT> <DEDENT> def fit(self, Lap_): <NEW_LINE> <INDENT> self.H_ = Lap_ <NEW_LINE> self.compute_eigs() <NEW_LINE> if self.norm == 0: <NEW_LINE> <INDENT> spec_embed = self.Heigvec[:,:self.nc] <NEW_LINE> <DEDENT> elif self.norm == 1: <NEW_LINE> <INDENT> spec_embed = (self.Heigvec[:,:self.nc].T/np.sqrt(np.sum(self.Heigvec[:,:self.nc]**2, axis=1))).T <NEW_LINE> <DEDENT> elif self.norm == 2: <NEW_LINE> <INDENT> spec_embed = (self.Heigvec[:,:self.nc].T / np.abs(self.Heigvec[:,0])).T <NEW_LINE> <DEDENT> km_ = KMeans(n_clusters = self.nc, n_init=100).fit(spec_embed) <NEW_LINE> self.labels_ = km_.labels_
The class SpectralClustering is initialized by specifying the number of clusters: n_cluster Other optional parameters: - norm_method: None, "row" or "deg". Default is "row." If None, spectral embedding is not normalized; If "row," spectral embedding is normalized each row (each row represent a node); If "deg," spectral embedding is normalized by degree vector. - is_exact: bool. Default is True. If True, exact eigenvectors and eigenvalues will be computed. If False, first n_cluster low energy eigenvectors and eigenvalues (small eigenvalues) will be computed Method: fit (Laplacian_matrix) compute eigenvalue and eigenvectors of Laplacian_matrix and perform spectral embedding. >> clf = SpectralClustering(n_cluster=5) >> clf.fit(Laplacian) Attribute: labels_, a numpy array containing the class labels, e.g. >> clf.labels_ Reference A Tutorial on Spectral Clustering, 2007 Ulrike von Luxburg http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323
6259906c92d797404e38976f
class Author(models.Model): <NEW_LINE> <INDENT> first_name = models.CharField(max_length=100) <NEW_LINE> last_name = models.CharField(max_length=100) <NEW_LINE> date_of_birth = models.DateField(null=True, blank=True) <NEW_LINE> date_of_death = models.DateField('Died', null=True, blank=True) <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('author-detail-view', args=[str(self.id)]) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s, %s' % (self.last_name, self.first_name) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> ordering = ['last_name']
Model representing an author.
6259906c7b25080760ed88f6
class ExportarDatosView(View): <NEW_LINE> <INDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> from django.core.management import call_command <NEW_LINE> call_command('dumpdata', 'auth.group', output="datos_iniciales/roles.json") <NEW_LINE> messages.success(request, "Se ha exportado la información de los roles en el archivo 'datos_iniciales/roles.json'") <NEW_LINE> return redirect('gestion_usuarios:listar_roles')
Autor: RADY CONSULTORES Fecha: 2 Septiembre 2016 Vista para exportar datos sobre los roles para poder reutilizarla en las diferentes instancias del proyecto en esta se utiliza el comando dumpdata para exportar el archivo roles.json
6259906c32920d7e50bc786f
class DataFrameParallelProcessor: <NEW_LINE> <INDENT> def __init__(self, processors, n_jobs=1): <NEW_LINE> <INDENT> self.processors = processors <NEW_LINE> self.n_jobs = n_jobs <NEW_LINE> <DEDENT> def process(self, dfAll, columns): <NEW_LINE> <INDENT> df_processor = DataFrameProcessor(self.processors) <NEW_LINE> p = multiprocessing.Pool(self.n_jobs) <NEW_LINE> dfs = p.imap(df_processor.process, [dfAll[col] for col in columns]) <NEW_LINE> for col,df in zip(columns, dfs): <NEW_LINE> <INDENT> dfAll[col] = df <NEW_LINE> <DEDENT> return dfAll
WARNING: This class will operate on the original input dataframe itself https://stackoverflow.com/questions/26520781/multiprocessing-pool-whats-the-difference-between-map-async-and-imap
6259906cd486a94d0ba2d7e8
class ErrorRaiser: <NEW_LINE> <INDENT> def __init__(self, level = 0): <NEW_LINE> <INDENT> self._level = level <NEW_LINE> <DEDENT> def error(self, exception): <NEW_LINE> <INDENT> if self._level <= 1: <NEW_LINE> <INDENT> raise exception <NEW_LINE> <DEDENT> <DEDENT> def fatalError(self, exception): <NEW_LINE> <INDENT> if self._level <= 2: <NEW_LINE> <INDENT> raise exception <NEW_LINE> <DEDENT> <DEDENT> def warning(self, exception): <NEW_LINE> <INDENT> if self._level <= 0: <NEW_LINE> <INDENT> raise exception
A simple class that just raises the exceptions it is passed.
6259906c91f36d47f2231aa3
class SimpleDDGenerator(DDGenerator, NamedObject): <NEW_LINE> <INDENT> def __init__(self, parent, idem1, idem2, name): <NEW_LINE> <INDENT> DDGenerator.__init__(self, parent, idem1, idem2) <NEW_LINE> NamedObject.__init__(self, name) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "%s:%s,%s" % (self.name, str(self.idem1), str(self.idem2)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash((self.parent, self.idem1, self.idem2, self.name)) <NEW_LINE> <DEDENT> def toDGenerator(self, new_parent): <NEW_LINE> <INDENT> new_idem = TensorIdempotent((self.idem1, self.idem2)) <NEW_LINE> new_gen = SimpleDGenerator(new_parent, new_idem, self.name) <NEW_LINE> new_gen.__dict__.update(self.__dict__) <NEW_LINE> new_gen.parent, new_gen.idem, new_gen.name = new_parent, new_idem, self.name <NEW_LINE> return new_gen
Represents a generator of type DD structure, distinguished by name.
6259906c63b5f9789fe8698b
class PkgFileMissingPkgEntry(LinterCheckBase): <NEW_LINE> <INDENT> name = 'pkgfile_missing_pkgentry' <NEW_LINE> check_type = LinterCheckType.PKGFILE <NEW_LINE> header = 'built packages without a referring repo.db entry' <NEW_LINE> def check(self, pkgfile): <NEW_LINE> <INDENT> if not pkgfile.pkgentries: <NEW_LINE> <INDENT> builddate = pkgfile.builddate.strftime("%Y-%m-%d %H:%M:%S") <NEW_LINE> raise LinterIssue('%s (built %s)', pkgfile, builddate)
for the list of built packages, check wether a repo.db entry exists that refers to the package. The check reports an issue for each built package that is not referred to by a repo.db entry.
6259906c63d6d428bbee3e9e
class Ship: <NEW_LINE> <INDENT> def __init__(self,ai_game): <NEW_LINE> <INDENT> self.screen=ai_game.screen <NEW_LINE> self.settings = ai_game.settings <NEW_LINE> self.screen_rect=ai_game.screen.get_rect() <NEW_LINE> self.image=pygame.image.load('images/ship.bmp') <NEW_LINE> self.rect=self.image.get_rect() <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> self.rect.midbottom=self.screen_rect.midbottom <NEW_LINE> self.y = float(self.rect.y) <NEW_LINE> self.x = self.screen_rect.right/2 <NEW_LINE> self.moving_right = False <NEW_LINE> self.moving_left = False <NEW_LINE> self.moving_up = False <NEW_LINE> self.moving_down = False <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image,self.rect) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.moving_right and self.rect.right < self.screen_rect.right: <NEW_LINE> <INDENT> self.x += self.settings.ship_speed <NEW_LINE> <DEDENT> if self.moving_left and self.rect.left > 0: <NEW_LINE> <INDENT> self.x -= self.settings.ship_speed <NEW_LINE> <DEDENT> if self.moving_up and self.rect.top >0: <NEW_LINE> <INDENT> self.y -= self.settings.ship_speed <NEW_LINE> <DEDENT> if self.moving_down and self.rect.bottom <self.screen_rect.bottom: <NEW_LINE> <INDENT> self.y += self.settings.ship_speed <NEW_LINE> <DEDENT> self.rect.x = self.x <NEW_LINE> self.rect.y = self.y
Aclasstomanagetheship.
6259906ca219f33f346c8031
class TechnicalSpecificationForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = TechnicalSpecification <NEW_LINE> fields = ['name', 'value'] <NEW_LINE> widgets = {'name': forms.TextInput(attrs={"placeholder": "specification", "size": "10"}), 'value': forms.TextInput(attrs={"placeholder": "value", "size": "10"})} <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(TechnicalSpecificationForm, self).__init__(*args, **kwargs) <NEW_LINE> for fk in self.fields: <NEW_LINE> <INDENT> self.fields[fk].required = False
Form used for adding or editing technical specification It is a model form, which contains fields name and value. After initialization it sets both fields required attribute to false, since form can also be blank. This is verified in the view, used for editing or adding a device.
6259906c99fddb7c1ca639e5
class Online_SaleOrder(models.Model): <NEW_LINE> <INDENT> choices = ( (False, '保存'), (True, '删除'), ) <NEW_LINE> channel = models.CharField(max_length=30, null=False, verbose_name='销售渠道') <NEW_LINE> orderdate = models.DateField(verbose_name='订单日期', null=False) <NEW_LINE> ordertime = models.TimeField(verbose_name='下单时间', null=False) <NEW_LINE> orderNo = models.CharField(max_length=20, null=False, verbose_name='订单编号') <NEW_LINE> customer = models.CharField(max_length=20, null=False, verbose_name='客户姓名') <NEW_LINE> cuscellphone = models.DecimalField(max_digits=11, decimal_places=0, null=False, verbose_name='联系电话') <NEW_LINE> province = models.CharField(max_length=30, null=False, verbose_name='省') <NEW_LINE> city = models.CharField(max_length=30, null=False, verbose_name='市') <NEW_LINE> skuNo = models.DecimalField(max_digits=10, decimal_places=0, null=False, verbose_name='sku编码') <NEW_LINE> amount = models.DecimalField(max_digits=8, decimal_places=2, null=False, verbose_name='数量') <NEW_LINE> price = models.DecimalField(max_digits=8, decimal_places=2, null=False, verbose_name='商品单价') <NEW_LINE> Sumprice = models.DecimalField(max_digits=8, decimal_places=2, null=False, verbose_name='商品总金额') <NEW_LINE> discountprice = models.DecimalField(max_digits=8, decimal_places=2, null=False, verbose_name='折扣金额') <NEW_LINE> orderPay= models.DecimalField(max_digits=8, decimal_places=2, null=False, verbose_name='订单实付金额') <NEW_LINE> promotion= models.CharField(max_length=50, null=False, verbose_name='优惠活动') <NEW_LINE> edited_by = models.ForeignKey('auth.User', verbose_name='编辑人', null=False, on_delete=models.CASCADE) <NEW_LINE> created_time = models.DateTimeField(auto_now_add=True, editable=False, verbose_name='创建时间', null=False) <NEW_LINE> modified_time = models.DateTimeField(auto_now=True, editable=False, verbose_name='编辑时间', null=False) <NEW_LINE> is_delete = models.BooleanField(choices=choices, default=False, null=False, verbose_name='逻辑删除') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = '销售订单' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.orderNo
销售订单
6259906c091ae3566870645d
class GradientTape(object): <NEW_LINE> <INDENT> def __init__(self, persistent=False): <NEW_LINE> <INDENT> self._tape = None <NEW_LINE> self._persistent = persistent <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self._tape = tape.push_new_tape(persistent=self._persistent) <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, typ, value, traceback): <NEW_LINE> <INDENT> tape.pop_tape(self._tape) <NEW_LINE> <DEDENT> def watch(self, tensor): <NEW_LINE> <INDENT> for t in nest.flatten(tensor): <NEW_LINE> <INDENT> if isinstance(t, resource_variable_ops.ResourceVariable): <NEW_LINE> <INDENT> t = t.handle <NEW_LINE> <DEDENT> tape.watch(t) <NEW_LINE> <DEDENT> <DEDENT> def gradient(self, target, sources): <NEW_LINE> <INDENT> if self._tape is None: <NEW_LINE> <INDENT> raise RuntimeError("GradientTape.gradient can only be called once " "on non-persistent tapes, and " "only when the context manager has exited.") <NEW_LINE> <DEDENT> sources = [x.handle if isinstance(x, resource_variable_ops.ResourceVariable) else x for x in sources] <NEW_LINE> grad = imperative_grad.imperative_grad( _default_vspace, self._tape, [target], sources) <NEW_LINE> if not self._persistent: <NEW_LINE> <INDENT> self._tape = None <NEW_LINE> <DEDENT> return grad
Records operations to use to compute gradients. Operations are recorded if: - they happen in code marked by this context manager - at least one of their inputs is being watched Outputs of recorded operations are watched. Variables are automatically watched and tensors can be manually watched by calling the watch method on the context manager. Example usage: ```python with tfe.GradientTape() as g: x = tf.constant(3.0) g.watch(x) y = x * x grad = g.gradient(y, [x])[0] assert grad.numpy() == 6.0 ``` It is possible to use GradientTapes to compute higher-order derivatives as follows: ```python with tfe.GradientTape() as g: x = tf.constant(3.0) g.watch(x) y = x * x with tfe.GradientTape() as gg: gg.watch(y) z = 2 * y inner_grad = gg.gradient(z, [y])[0] assert inner_grad.numpy() == 2 y = y + inner_grad grad = g.gradient(y, [x])[0] assert grad.numpy() == 6.0 ``` By default, the resources held by a GradientTape are released as soon as GradientTape.gradient() method is called. However, if one need to compute multiple gradients over the same computation, she can create a persistent GradientTape. Persistent tapes allow multiple calls to the gradient() method and release resources when the tape object is destructed. Example usage: ```python with tfe.GradientTape(persistent=True) as g: x = tf.constant(3.0) g.watch(x) y = x * x z = y * y dz_dx = g.gradient(z, [x])[0] assert dz_dx.numpy() == 108.0 # 4*x^3 at x = 3 dy_dx = g.gradient(y, [x])[0] assert dy_dx.numpy() == 6.0 del g # Drop the reference to the tape
6259906c7047854f46340be0
class clear_log(ProtectedPage): <NEW_LINE> <INDENT> def GET(self): <NEW_LINE> <INDENT> qdict = web.input() <NEW_LINE> with open('./data/log.json', 'w') as f: <NEW_LINE> <INDENT> f.write('') <NEW_LINE> <DEDENT> raise web.seeother('/vl')
Delete all log records
6259906c3539df3088ecdac8
class MetaHandler(type): <NEW_LINE> <INDENT> def __init__(cls, name, bases, _dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cls._msg_handlers[cls.__msgtype__] = cls <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> cls._msg_handlers = {}
Metaclass for MessageHandler
6259906c3346ee7daa338273
class WalletExists(Exception): <NEW_LINE> <INDENT> pass
A wallet has already been created and requires a password to be unlocked by means of :func:`morphenepython.wallet.Wallet.unlock`.
6259906caad79263cf42ffdf
class InventoryViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = InventoryItem.objects.all() <NEW_LINE> serializer_class = InventoryItemSerializer <NEW_LINE> filter_fields = ( 'application__name', 'application__bundleid', 'application__bundlename', 'machine__hostname', 'machine__serial', 'machine__id', 'version', 'path', 'application__caption', 'application__description', 'application__hotfixid', 'application__installdate', 'application__installdate2', 'application__version') <NEW_LINE> search_fields = ( 'application__name', 'application__bundleid', 'application__bundlename', 'application__caption', 'application__description', 'application__hotfixid', 'application__installdate', 'application__installdate2', 'application__version')
list: You may also use the `search` querystring to perform text searches across the `application__name`, `application__bundleid`, `application__bundlename` fields. Example `/api/inventory/?search=Adobe` or `/api/inventory/?search=KB5000802`
6259906c4428ac0f6e659d5c
class BlogDetailView(DetailView): <NEW_LINE> <INDENT> model = Blog <NEW_LINE> template_name = "blog_detail.html" <NEW_LINE> context_object_name = "blog" <NEW_LINE> pk_url_kwarg = 'blog_id'
博客详情
6259906c99cbb53fe6832711
class Chain( object ): <NEW_LINE> <INDENT> def __init__(self, input_filenames, tree_name=None): <NEW_LINE> <INDENT> self.files = input_filenames <NEW_LINE> if isinstance(input_filenames, basestring): <NEW_LINE> <INDENT> self.files = glob.glob(input_filenames) <NEW_LINE> if len(self.files)==0: <NEW_LINE> <INDENT> raise ValueError('no matching file name: '+input_filenames) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if False in [ ((is_pfn(fnam) and os.path.isfile(fnam)) or is_lfn(fnam)) or is_rootfn(fnam) for fnam in self.files]: <NEW_LINE> <INDENT> err = 'at least one input file does not exist\n' <NEW_LINE> err += pprint.pformat(self.files) <NEW_LINE> raise ValueError(err) <NEW_LINE> <DEDENT> <DEDENT> if tree_name is None: <NEW_LINE> <INDENT> tree_name = self._guessTreeName(input_filenames) <NEW_LINE> <DEDENT> self.chain = TChain(tree_name) <NEW_LINE> for file in self.files: <NEW_LINE> <INDENT> self.chain.Add(file) <NEW_LINE> <DEDENT> <DEDENT> def _guessTreeName(self, pattern): <NEW_LINE> <INDENT> names = [] <NEW_LINE> for fnam in self.files: <NEW_LINE> <INDENT> rfile = TFile(fnam) <NEW_LINE> for key in rfile.GetListOfKeys(): <NEW_LINE> <INDENT> obj = rfile.Get(key.GetName()) <NEW_LINE> if type(obj) is TTree: <NEW_LINE> <INDENT> names.append( key.GetName() ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> thename = set(names) <NEW_LINE> if len(thename)==1: <NEW_LINE> <INDENT> return list(thename)[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> err = [ 'several TTree keys in {pattern}:'.format( pattern=pattern ), ','.join(thename) ] <NEW_LINE> raise ValueError('\n'.join(err)) <NEW_LINE> <DEDENT> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return getattr(self.chain, attr) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return iter(self.chain) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return int(self.chain.GetEntries()) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> self.chain.GetEntry(index) <NEW_LINE> return self.chain
Wrapper to TChain, with a python iterable interface. from chain import Chain the_chain = Chain('../test/test_*.root', 'test_tree') event3 = the_chain[2] print event3.var1 for event in the_chain: print event.var1
6259906c67a9b606de5476b7
class Resource(object): <NEW_LINE> <INDENT> _type_ = "rdfs:Resource" <NEW_LINE> __module__ = "tralchemy.rdfs" <NEW_LINE> def __init__(self, uri): <NEW_LINE> <INDENT> self.uri = get_classname(uri) <NEW_LINE> self.triples = {} <NEW_LINE> self.cache = {} <NEW_LINE> <DEDENT> def properties(self): <NEW_LINE> <INDENT> uri = self.uri <NEW_LINE> if uri.startswith("http://"): <NEW_LINE> <INDENT> uri = "<%s>" % uri <NEW_LINE> <DEDENT> results = tracker_query("SELECT ?key, ?value WHERE { %s ?key ?value }" % uri) <NEW_LINE> for key, value in results: <NEW_LINE> <INDENT> yield get_classname(str(key)), str(value) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def get(cls, **kwargs): <NEW_LINE> <INDENT> fragment = "" <NEW_LINE> for key, value in kwargs.iteritems(): <NEW_LINE> <INDENT> key = getattr(cls, key).uri <NEW_LINE> fragment += " . ?o %s %s" % (key, value) <NEW_LINE> <DEDENT> results = tracker_query("SELECT ?o WHERE { ?o rdf:type %s %s}" % (cls._type_, fragment)) <NEW_LINE> for result in results: <NEW_LINE> <INDENT> classname = get_classname(result[0]) <NEW_LINE> yield cls(classname) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def create(cls, **kwargs): <NEW_LINE> <INDENT> o = cls(kwargs.get('uid', 'http://localhost/resource/%s' % str(uuid.uuid4()))) <NEW_LINE> for k, v in kwargs.iteritems(): <NEW_LINE> <INDENT> if k == "uid" or k =="commit": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> setattr(o, k, v) <NEW_LINE> <DEDENT> if not 'commit' in kwargs or kwargs['commit']: <NEW_LINE> <INDENT> o.commit() <NEW_LINE> <DEDENT> return o <NEW_LINE> <DEDENT> def delete(self): <NEW_LINE> <INDENT> tracker_update("DELETE { <%s> a %s. }" % (self.uri, self._type_)) <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> query = "INSERT { <%s> a %s" % (self.uri, self._type_) <NEW_LINE> for k, v in self.triples.iteritems(): <NEW_LINE> <INDENT> if isinstance(v, list): <NEW_LINE> <INDENT> for i in v: <NEW_LINE> <INDENT> query += " ; %s %s" % (k, i) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> query += " ; %s %s" % (k, v) <NEW_LINE> <DEDENT> <DEDENT> query += " . }" <NEW_LINE> tracker_update(query) <NEW_LINE> self.triples = {}
Everything is a resource
6259906c5fc7496912d48e7d
class UserViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> queryset = User.objects.all() <NEW_LINE> serializer_class = UserSerializer
This viewset automatically provide 'list' and 'detail' actions.
6259906ce5267d203ee6cfd3
class AbstractImageMobject(Mobject): <NEW_LINE> <INDENT> CONFIG = { "height": 2.0, "pixel_array_dtype": "uint8", } <NEW_LINE> def get_pixel_array(self): <NEW_LINE> <INDENT> raise Exception("Not implemented") <NEW_LINE> <DEDENT> def set_color(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def init_points(self): <NEW_LINE> <INDENT> self.points = np.array([ UP + LEFT, UP + RIGHT, DOWN + LEFT, ]) <NEW_LINE> self.center() <NEW_LINE> h, w = self.get_pixel_array().shape[:2] <NEW_LINE> self.stretch_to_fit_height(self.height) <NEW_LINE> self.stretch_to_fit_width(self.height * w / h) <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return self.deepcopy()
Automatically filters out black pixels
6259906c23849d37ff8528e0
class FlntuXMmpCdsParserDataParticle(MmpCdsParserDataParticle): <NEW_LINE> <INDENT> _data_particle_type = DataParticleType.INSTRUMENT <NEW_LINE> def _get_mmp_cds_subclass_particle_params(self, dict_data): <NEW_LINE> <INDENT> chlorophyll = self._encode_value(FlntuXMmpCdsParserDataParticleKey.CHLAFLO, dict_data[FlntuXMmpCdsParserDataParticleKey.CHLAFLO], int) <NEW_LINE> ntuflo = self._encode_value(FlntuXMmpCdsParserDataParticleKey.NTUFLO, dict_data[FlntuXMmpCdsParserDataParticleKey.NTUFLO], int) <NEW_LINE> return [chlorophyll, ntuflo]
Class for parsing data from the FlntuXMmpCds data set
6259906c45492302aabfdd03
class DerOctetString(DerObject): <NEW_LINE> <INDENT> def __init__(self, value=b'', implicit=None): <NEW_LINE> <INDENT> DerObject.__init__(self, 0x04, value, implicit, False)
Class to model a DER OCTET STRING. An example of encoding is: >>> from Crypto.Util.asn1 import DerOctetString >>> from binascii import hexlify, unhexlify >>> os_der = DerOctetString(b'\xaa') >>> os_der.payload += b'\xbb' >>> print hexlify(os_der.encode()) which will show ``0402aabb``, the DER encoding for the byte string ``b'\xAA\xBB'``. For decoding: >>> s = unhexlify(b'0402aabb') >>> try: >>> os_der = DerOctetString() >>> os_der.decode(s) >>> print hexlify(os_der.payload) >>> except ValueError: >>> print "Not a valid DER OCTET STRING" the output will be ``aabb``. :ivar payload: The content of the string :vartype payload: byte string
6259906cac7a0e7691f73d12
class Assign(Updateable, Pretty, Navigatable): <NEW_LINE> <INDENT> def __init__(self, assign_to=None, tag_category=None, docker_labels=None, selections=None, appliance=None): <NEW_LINE> <INDENT> Navigatable.__init__(self, appliance=appliance) <NEW_LINE> self.assign_to = assign_to <NEW_LINE> self.tag_category = tag_category <NEW_LINE> self.docker_labels = docker_labels <NEW_LINE> self.selections = selections <NEW_LINE> <DEDENT> def storageassign(self): <NEW_LINE> <INDENT> view = navigate_to(self, 'Storage') <NEW_LINE> was_change = self._fill(view) <NEW_LINE> if was_change: <NEW_LINE> <INDENT> view.save_button.click() <NEW_LINE> view.flash.assert_no_error() <NEW_LINE> view.flash.assert_message('Rate Assignments saved') <NEW_LINE> <DEDENT> <DEDENT> def computeassign(self): <NEW_LINE> <INDENT> view = navigate_to(self, 'Compute') <NEW_LINE> was_change = self._fill(view) <NEW_LINE> if was_change: <NEW_LINE> <INDENT> view.save_button.click() <NEW_LINE> view.flash.assert_no_error() <NEW_LINE> view.flash.assert_message('Rate Assignments saved') <NEW_LINE> <DEDENT> <DEDENT> def _fill(self, view): <NEW_LINE> <INDENT> fill_details = dict( assign_to=self.assign_to, tag_category=self.tag_category, docker_labels=self.docker_labels, selections=self.selections, ) <NEW_LINE> return view.fill(fill_details)
Model of Chargeback Assignment page in cfme. Args: assign_to: Assign the chargeback rate to entities such as VM,Provider,datastore or the Enterprise itself. tag_category: Tag category of the entity selections: Selection of a particular entity to which the rate is to be assigned. Eg:If the chargeback rate is to be assigned to providers,select which of the managed providers the rate is to be assigned. Usage: enterprise = Assign( assign_to="The Enterprise", selections={ 'Enterprise': {'Rate': 'Default'} }) enterprise.computeassign()
6259906c5fcc89381b266d6c
class Solution: <NEW_LINE> <INDENT> def searchMatrix(self, matrix, target): <NEW_LINE> <INDENT> if matrix == [] or matrix[0] == []: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> row, column = len(matrix), len(matrix[0]) <NEW_LINE> i, j = row - 1, 0 <NEW_LINE> count = 0 <NEW_LINE> while i >= 0 and j < column: <NEW_LINE> <INDENT> if matrix[i][j] == target: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> i -= 1 <NEW_LINE> j += 1 <NEW_LINE> <DEDENT> elif matrix[i][j] < target: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> <DEDENT> elif matrix[i][j] > target: <NEW_LINE> <INDENT> i -= 1 <NEW_LINE> <DEDENT> <DEDENT> return count
@param matrix: An list of lists of integers @param target: An integer you want to search in matrix @return: An integer indicates the total occurrence of target in the given matrix
6259906c99fddb7c1ca639e6
class Interface(object): <NEW_LINE> <INDENT> input_spec = None <NEW_LINE> output_spec = None <NEW_LINE> _can_resume = False <NEW_LINE> _always_run = False <NEW_LINE> @property <NEW_LINE> def can_resume(self): <NEW_LINE> <INDENT> return self._can_resume <NEW_LINE> <DEDENT> @property <NEW_LINE> def always_run(self): <NEW_LINE> <INDENT> return self._always_run <NEW_LINE> <DEDENT> @property <NEW_LINE> def version(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _outputs(cls): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def help(cls, returnhelp=False): <NEW_LINE> <INDENT> allhelp = format_help(cls) <NEW_LINE> if returnhelp: <NEW_LINE> <INDENT> return allhelp <NEW_LINE> <DEDENT> print(allhelp) <NEW_LINE> return None <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def aggregate_outputs(self, runtime=None, needed_outputs=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _list_outputs(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def _get_filecopy_info(cls): <NEW_LINE> <INDENT> iflogger.warning( "_get_filecopy_info member of Interface was deprecated " "in nipype-1.1.6 and will be removed in 1.2.0" ) <NEW_LINE> return get_filecopy_info(cls)
This is an abstract definition for Interface objects. It provides no functionality. It defines the necessary attributes and methods all Interface objects should have.
6259906ca219f33f346c8033
class Ufl(PythonPackage): <NEW_LINE> <INDENT> homepage = "https://bitbucket.org/fenics-project/ufl" <NEW_LINE> url = "https://bitbucket.org/fenics-project/ufl/downloads/ufl-2017.2.0.tar.gz" <NEW_LINE> git='https://bitbucket.org/fenics-project/ufl' <NEW_LINE> version('2019.1.0', tag='2019.1.0') <NEW_LINE> version('2018.1.0', tag='2018.1.0') <NEW_LINE> version('2017.2.0', tag='2017.2.0.post0') <NEW_LINE> version('2017.1.0', tag='2017.1.0.post1') <NEW_LINE> depends_on('py-setuptools', type="build") <NEW_LINE> depends_on('py-numpy', type=("build","run")) <NEW_LINE> depends_on('py-six', type=("build","run"))
UFL - Unified Form Language The Unified Form Language (UFL) is a domain specific language for declaration of finite element discretizations of variational forms. More precisely, it defines a flexible interface for choosing finite element spaces and defining expressions for weak forms in a notation close to mathematical notation. UFL is part of the FEniCS Project. For more information, visit http://www.fenicsproject.org
6259906c76e4537e8c3f0dae
class FakeAssetpack(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.pack_id = 'test_assetpack_name'
The fakest assetpack around
6259906cfff4ab517ebcf046
class ApplicationHelper(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def init(cls): <NEW_LINE> <INDENT> ApplicationRegistry.game = "MTG" <NEW_LINE> sys.path.append(os.path.abspath("plugins/" + ApplicationRegistry.game)) <NEW_LINE> image_helper = __import__("ImageHelper") <NEW_LINE> ApplicationRegistry.image_helper = image_helper <NEW_LINE> sys.path.append(os.path.abspath("plugins/" + ApplicationRegistry.game)) <NEW_LINE> import settings <NEW_LINE> ApplicationRegistry.settings = settings.settings <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_setting(cls, key): <NEW_LINE> <INDENT> return ApplicationRegisty.key <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_gui_lib(cls): <NEW_LINE> <INDENT> return "autopy" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_vision_lib(cls): <NEW_LINE> <INDENT> return "opencv" <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_inventory_adapter(cls): <NEW_LINE> <INDENT> return "txt"
Does initial setup for application wide variables.
6259906c8e7ae83300eea8bb
class ForceUTF8Response(object): <NEW_LINE> <INDENT> encoding = 'utf-8' <NEW_LINE> def process_response(self, request, response, spider): <NEW_LINE> <INDENT> new_body = response.body_as_unicode().encode(self.encoding) <NEW_LINE> return response.replace(body=new_body, encoding=self.encoding)
A downloader middleware to force UTF-8 encoding for all responses.
6259906c3539df3088ecdaca
class AnalysisProp(base.PublicBase): <NEW_LINE> <INDENT> analysisprop_id = sqlalchemy.Column(sqlalchemy.BIGINT, nullable=False, primary_key=True, autoincrement=True) <NEW_LINE> analysis_id = sqlalchemy.Column(sqlalchemy.BIGINT, sqlalchemy.ForeignKey( Analysis.analysis_id, onupdate="CASCADE", ondelete="CASCADE"), nullable=False) <NEW_LINE> type_id = sqlalchemy.Column(sqlalchemy.BIGINT, sqlalchemy.ForeignKey( cv.CvTerm.cvterm_id, onupdate="CASCADE", ondelete="CASCADE"), nullable=False) <NEW_LINE> value = sqlalchemy.Column(sqlalchemy.TEXT, nullable=True) <NEW_LINE> __tablename__ = "analysisprop" <NEW_LINE> __table_args__ = (sqlalchemy.UniqueConstraint(analysis_id, type_id, value, name="analysisprop_c1"), sqlalchemy.Index("analysisprop_idx1", analysis_id), sqlalchemy.Index("analysisprop_idx2", type_id)) <NEW_LINE> analysis = sqlalchemy.orm.relationship(Analysis, foreign_keys=analysis_id, backref="analysisprop_analysis") <NEW_LINE> type = sqlalchemy.orm.relationship(cv.CvTerm, foreign_keys=type_id, backref="analysisprop_type") <NEW_LINE> def __init__(self, analysis_id, type_id, value=None, analysisprop_id=None): <NEW_LINE> <INDENT> for key, val in locals().items(): <NEW_LINE> <INDENT> if key != self: <NEW_LINE> <INDENT> setattr(self, key, val) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<companalysis.AnalysisProp(analysisprop_id={0}, analysis_id={1}, type_id={2}, value='{3}')>". format(self.analysisprop_id, self.analysis_id, self.type_id, self.value)
Class for the CHADO 'analysisprop' table
6259906c3346ee7daa338274
class PlayerCreator(flow.SWFlow): <NEW_LINE> <INDENT> def __init__(self, state, spawner, name, species, background): <NEW_LINE> <INDENT> super().__init__(state, spawner, None) <NEW_LINE> self.register_entry_point(FINAL_ENTRY_POINT, self.create_player) <NEW_LINE> self.name = name <NEW_LINE> self.species = species <NEW_LINE> self.background = background <NEW_LINE> <DEDENT> def create_player(self): <NEW_LINE> <INDENT> import sw.stage.world_generation as worldgen <NEW_LINE> player = player_from_scratch(self.name, self.species, self.background) <NEW_LINE> self.state.player = player <NEW_LINE> new_flow = worldgen.WorldGeneration(self.state, self.ui_spawner) <NEW_LINE> raise flow.ChangeFlow(new_flow, worldgen.ENTRY_POINT)
The final flow that will create the player character.
6259906c7d43ff2487428027
class ContextEncoder(NumberEncoder): <NEW_LINE> <INDENT> def __init__(self, pronouncer = Pronouncer(), phoneme_to_digit_dict = None, max_word_length = None, context_length = 2, min_sentence_length = 5): <NEW_LINE> <INDENT> super(ContextEncoder, self).__init__(pronouncer = pronouncer, phoneme_to_digit_dict = phoneme_to_digit_dict) <NEW_LINE> max_digits_per_word = 19 <NEW_LINE> if max_word_length == None or max_word_length < 1 or max_word_length > max_digits_per_word: <NEW_LINE> <INDENT> max_word_length = max_digits_per_word <NEW_LINE> <DEDENT> self.max_word_length = max_word_length <NEW_LINE> max_reasonable_context = 5 <NEW_LINE> if context_length == None or context_length < 0 or context_length > max_reasonable_context: <NEW_LINE> <INDENT> context_length = max_reasonable_context <NEW_LINE> <DEDENT> self.context_length = context_length <NEW_LINE> self.phonemes_to_words_dict = self._get_phonemes_to_words_dict() <NEW_LINE> self.min_sentence_length = min_sentence_length <NEW_LINE> <DEDENT> def _select_encoding(self, previous_words, encodings): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def encode_number(self, number, max_word_length = None, context_length = None): <NEW_LINE> <INDENT> if max_word_length == None: <NEW_LINE> <INDENT> max_word_length = self.max_word_length <NEW_LINE> <DEDENT> if context_length == None: <NEW_LINE> <INDENT> context_length = self.context_length <NEW_LINE> <DEDENT> encoded_index = 0 <NEW_LINE> encodings = [] <NEW_LINE> while encoded_index < len(number): <NEW_LINE> <INDENT> chunk_encodings = set() <NEW_LINE> for chunk_length in range(1, max_word_length + 1): <NEW_LINE> <INDENT> number_chunk = number[encoded_index : encoded_index + chunk_length] <NEW_LINE> chunk_encodings |= set(self._encode_number_chunk(number_chunk)) <NEW_LINE> <DEDENT> if len(chunk_encodings) == 0: <NEW_LINE> <INDENT> number_chunk = number[encoded_index : encoded_index + max_word_length] <NEW_LINE> print('Cannot find encoding for number chunk \'{0}\''.format(number_chunk)) <NEW_LINE> return None <NEW_LINE> <DEDENT> if len(encodings) >= self.min_sentence_length and '.' not in encodings[-self.min_sentence_length:]: <NEW_LINE> <INDENT> chunk_encodings |= set('.') <NEW_LINE> <DEDENT> context = tuple(encodings[len(encodings) - context_length : len(encodings)]) <NEW_LINE> chunk_encoding = self._select_encoding(context, list(chunk_encodings)) <NEW_LINE> encodings += [chunk_encoding] <NEW_LINE> encoded_index += len(self.decode_word(chunk_encoding)) <NEW_LINE> <DEDENT> return encodings
ContextEncoder is the base class for any encoder that uses the previously chosen words as context and somehow picks from the set of all possible words (possibly of limited word length).
6259906c4428ac0f6e659d5e
class Font(_graphics.Font): <NEW_LINE> <INDENT> def render_text(self, text): <NEW_LINE> <INDENT> image_attributes = super().render_text(text) <NEW_LINE> return Image(*image_attributes)
The Font class specifies a font used for drawing text.
6259906cbaa26c4b54d50ad4
class KDETerminal(LinuxTerminal): <NEW_LINE> <INDENT> name = "KDE" <NEW_LINE> @staticmethod <NEW_LINE> def detect(): <NEW_LINE> <INDENT> return os.environ.get('KDE_FULL_SESSION', '') == 'true' <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_command_line(): <NEW_LINE> <INDENT> s = subprocess.check_output( ['kreadconfig', '--file', 'kdeglobals', '--group', 'General', '--key', 'TerminalApplication', '--default', 'konsole']).replace( '\n', '') <NEW_LINE> return ['nohup', s, '-e']
Handles terminals on KDE (e.g. Konsole).
6259906c44b2445a339b7575
class RestorePointListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'value': {'readonly': True}, 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[RestorePoint]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(RestorePointListResult, self).__init__(**kwargs) <NEW_LINE> self.value = None <NEW_LINE> self.next_link = None
A list of long term retention backups. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: Array of results. :vartype value: list[~azure.mgmt.sql.models.RestorePoint] :ivar next_link: Link to retrieve next page of results. :vartype next_link: str
6259906c9c8ee82313040d9e
class locked_cached_property(werkzeug.utils.cached_property): <NEW_LINE> <INDENT> def __init__(self, fget, name=None, doc=None): <NEW_LINE> <INDENT> super().__init__(fget, name=name, doc=doc) <NEW_LINE> self.lock = RLock() <NEW_LINE> <DEDENT> def __get__(self, obj, type=None): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> with self.lock: <NEW_LINE> <INDENT> return super().__get__(obj, type=type) <NEW_LINE> <DEDENT> <DEDENT> def __set__(self, obj, value): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> super().__set__(obj, value) <NEW_LINE> <DEDENT> <DEDENT> def __delete__(self, obj): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> super().__delete__(obj)
A :func:`property` that is only evaluated once. Like :class:`werkzeug.utils.cached_property` except access uses a lock for thread safety. .. versionchanged:: 2.0 Inherits from Werkzeug's ``cached_property`` (and ``property``).
6259906cd486a94d0ba2d7eb
class YamllintTest(SanitySingleVersion): <NEW_LINE> <INDENT> @property <NEW_LINE> def error_code(self): <NEW_LINE> <INDENT> return 'ansible-test' <NEW_LINE> <DEDENT> def filter_targets(self, targets): <NEW_LINE> <INDENT> yaml_targets = [target for target in targets if os.path.splitext(target.path)[1] in ('.yml', '.yaml')] <NEW_LINE> for plugin_type, plugin_path in sorted(data_context().content.plugin_paths.items()): <NEW_LINE> <INDENT> if plugin_type == 'module_utils': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> yaml_targets.extend([target for target in targets if os.path.splitext(target.path)[1] == '.py' and os.path.basename(target.path) != '__init__.py' and is_subdir(target.path, plugin_path)]) <NEW_LINE> <DEDENT> return yaml_targets <NEW_LINE> <DEDENT> def test(self, args, targets, python_version): <NEW_LINE> <INDENT> pyyaml_presence = check_pyyaml(args, python_version, quiet=True) <NEW_LINE> if not pyyaml_presence['cloader']: <NEW_LINE> <INDENT> display.warning("Skipping sanity test '%s' due to missing libyaml support in PyYAML." % self.name) <NEW_LINE> return SanitySkipped(self.name) <NEW_LINE> <DEDENT> settings = self.load_processor(args) <NEW_LINE> paths = [target.path for target in targets.include] <NEW_LINE> python = find_python(python_version) <NEW_LINE> results = self.test_paths(args, paths, python) <NEW_LINE> results = settings.process_errors(results, paths) <NEW_LINE> if results: <NEW_LINE> <INDENT> return SanityFailure(self.name, messages=results) <NEW_LINE> <DEDENT> return SanitySuccess(self.name) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def test_paths(args, paths, python): <NEW_LINE> <INDENT> cmd = [ python, os.path.join(SANITY_ROOT, 'yamllint', 'yamllinter.py'), ] <NEW_LINE> data = '\n'.join(paths) <NEW_LINE> display.info(data, verbosity=4) <NEW_LINE> try: <NEW_LINE> <INDENT> stdout, stderr = run_command(args, cmd, data=data, capture=True) <NEW_LINE> status = 0 <NEW_LINE> <DEDENT> except SubprocessError as ex: <NEW_LINE> <INDENT> stdout = ex.stdout <NEW_LINE> stderr = ex.stderr <NEW_LINE> status = ex.status <NEW_LINE> <DEDENT> if stderr: <NEW_LINE> <INDENT> raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout) <NEW_LINE> <DEDENT> if args.explain: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> results = json.loads(stdout)['messages'] <NEW_LINE> results = [SanityMessage( code=r['code'], message=r['message'], path=r['path'], line=int(r['line']), column=int(r['column']), level=r['level'], ) for r in results] <NEW_LINE> return results
Sanity test using yamllint.
6259906c7d847024c075dc08