code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
|---|---|---|
class _PropertyInstance(dict): <NEW_LINE> <INDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> return self.__getitem__(attr)
|
Stores properties as a dictionary and
allows access to them via attributes
|
62599019507cdc57c63a5b44
|
class Surface: <NEW_LINE> <INDENT> def __init__(self, *nodes, degree: int = 2): <NEW_LINE> <INDENT> self._nodes = np.asfortranarray(list(nodes)) <NEW_LINE> self.degree = degree <NEW_LINE> <DEDENT> @property <NEW_LINE> def nodes(self): <NEW_LINE> <INDENT> return self._nodes.tolist() <NEW_LINE> <DEDENT> def get_xy_coords(self, num_points = 100): <NEW_LINE> <INDENT> s_vals = np.linspace(0, 1, num_points) <NEW_LINE> points = self.bezier.evaluate_multi(s_vals) <NEW_LINE> x, y = zip(*points) <NEW_LINE> return list(x), list(y) <NEW_LINE> <DEDENT> def get_y(self, x: float, **kwargs): <NEW_LINE> <INDENT> def newton_rap(function, target, **kwargs): <NEW_LINE> <INDENT> def get_zero_function(function, target): <NEW_LINE> <INDENT> def the_function(x): <NEW_LINE> <INDENT> coords = function(x) <NEW_LINE> return coords[0][0] - target <NEW_LINE> <DEDENT> return the_function <NEW_LINE> <DEDENT> return opt.newton(get_zero_function(function, target), **kwargs) <NEW_LINE> <DEDENT> s = newton_rap(self.bezier.evaluate, x, **kwargs) <NEW_LINE> return self.bezier.evaluate(s)[0][1], s <NEW_LINE> <DEDENT> @property <NEW_LINE> def bezier(self): <NEW_LINE> <INDENT> return bezier.Curve(self._nodes, degree = self.degree) <NEW_LINE> <DEDENT> def __mul__(self, value: float): <NEW_LINE> <INDENT> new_nodes = self._nodes * value <NEW_LINE> return Surface(*new_nodes, self.degree) <NEW_LINE> <DEDENT> def __eq__(self, surface: 'Surface'): <NEW_LINE> <INDENT> return self._nodes.all() == surface._nodes.all() <NEW_LINE> <DEDENT> def plot(num_points, **kwargs): <NEW_LINE> <INDENT> return self.bezier.plot(num_points, **kwargs)
|
Class that represents a Surface from a number of nodes and degree
|
6259901991af0d3eaad3abc5
|
class ShowVariablesBoot(ShowVariablesBootSchema): <NEW_LINE> <INDENT> cli_command = 'show variables boot' <NEW_LINE> def cli(self, output=None): <NEW_LINE> <INDENT> if output is None: <NEW_LINE> <INDENT> out = self.device.execute(self.cli_command) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = output <NEW_LINE> <DEDENT> parsed_dict = {} <NEW_LINE> p = re.compile(r'^root=(?P<root>[\w\/]+) +' r'platform=(?P<platform>[\w]+) +' r'boardtype=(?P<boardtype>[\w]+) +' r'cardtype=(?P<cardtype>[\w]+) +' r'iputype=(?P<iputype>[\w]+) +' r'vmtype=(?P<vmtype>[\w -]+) +' r'bigphysarea="?(?P<bigphysarea>[\w]+)"? +' r'chassis_type=(?P<chassis_type>[\w]+) +' r'intel_idle\.max_cstate=(?P<intel_idle_max_cstate>[\d]+) +' r'processor\.max_cstate=(?P<processor_max_cstate>[\d]+) +' r'chassis_serial=(?P<chassis_serial>[\w]+) +' r'chassis_pid=(?P<chassis_pid>[\w-]+) +' r'console=(?P<primary_console>[\w]+) +' r'(console=(?P<secondary_console>[\w]+) +)?' r'prod=(?P<prod>[\d]+) +' r'pci=(?P<pci>hpmemsize=(?P<hpmemsize>[\w]+)\,\s*hpiosize=(?P<hpiosize>[\w]+))$') <NEW_LINE> for line in out.splitlines(): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> m = p.match(line) <NEW_LINE> if m: <NEW_LINE> <INDENT> group = m.groupdict() <NEW_LINE> boot_variables_dict = parsed_dict.setdefault('boot_variables', {}) <NEW_LINE> boot_variables_dict['root'] = group['root'] <NEW_LINE> boot_variables_dict['platform'] = group['platform'] <NEW_LINE> boot_variables_dict['boardtype'] = group['boardtype'] <NEW_LINE> boot_variables_dict['cardtype'] = group['cardtype'] <NEW_LINE> boot_variables_dict['iputype'] = group['iputype'] <NEW_LINE> boot_variables_dict['vmtype'] = group['vmtype'] <NEW_LINE> boot_variables_dict['bigphysarea'] = group['bigphysarea'] <NEW_LINE> boot_variables_dict['chassis_type'] = group['chassis_type'] <NEW_LINE> boot_variables_dict['intel_idle_max_cstate'] = int(group['intel_idle_max_cstate']) <NEW_LINE> boot_variables_dict['processor_max_cstate'] = int(group['processor_max_cstate']) <NEW_LINE> boot_variables_dict['chassis_serial'] = group['chassis_serial'] <NEW_LINE> boot_variables_dict['chassis_pid'] = group['chassis_pid'] <NEW_LINE> boot_variables_dict['primary_console'] = group['primary_console'] <NEW_LINE> boot_variables_dict['secondary_console'] = group['secondary_console'] <NEW_LINE> boot_variables_dict['prod'] = int(group['prod']) <NEW_LINE> pci_dict = boot_variables_dict.setdefault('pci', {}) <NEW_LINE> pci_dict['hpmemsize'] = group['hpmemsize'] <NEW_LINE> pci_dict['hpiosize'] = group['hpiosize'] <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> return parsed_dict
|
Parser for show variables boot
|
625990195166f23b2e244175
|
class LogViewSet(viewsets.ReadOnlyModelViewSet): <NEW_LINE> <INDENT> filter_backends = [filters.OrderingFilter, filters.SearchFilter] <NEW_LINE> ordering = ["-date_created"] <NEW_LINE> ordering_fields = "__all__" <NEW_LINE> pagination_class = pagination.CustomPageNumberPagination <NEW_LINE> permission_classes = ( permissions.IsAuthenticated, permissions.DjangoModelPermissions, ) <NEW_LINE> queryset = models.Log.objects.all() <NEW_LINE> search_fields = ["logger", "level", "message"] <NEW_LINE> serializer_class = serializers.LogSerializer
|
Log viewset.
|
62599019bf627c535bcb2254
|
class TestCheck(Check): <NEW_LINE> <INDENT> __test__ = True <NEW_LINE> @property <NEW_LINE> def this_check(self): <NEW_LINE> <INDENT> return chk <NEW_LINE> <DEDENT> def test_smoke(self): <NEW_LINE> <INDENT> assert self.passes("""Smoke phrase with nothing flagged.""") <NEW_LINE> assert not self.passes("""It goes back to the stone age.""") <NEW_LINE> <DEDENT> def test_smoke_check_months(self): <NEW_LINE> <INDENT> assert chk.check_months("""Smoke phrase with nothing flagged""") == [] <NEW_LINE> assert chk.check_months("""A nice day in june.""") != [] <NEW_LINE> <DEDENT> def test_smoke_check_days(self): <NEW_LINE> <INDENT> assert chk.check_days("""Smoke phrase with nothing flagged""") == [] <NEW_LINE> assert chk.check_days("""It happened on friday.""") != []
|
The test class for misc.capitalization.
|
62599019925a0f43d25e8de7
|
class UCProgramVariableCollection (object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.log = logging.getLogger(__name__) <NEW_LINE> self.by_index = [] <NEW_LINE> self.by_name = {} <NEW_LINE> <DEDENT> def getVariable(self, name): <NEW_LINE> <INDENT> if(name in self.by_name): <NEW_LINE> <INDENT> return self.by_name[name] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def getPortNames(self): <NEW_LINE> <INDENT> return [v.name for v in self.by_index if v.isPort()] <NEW_LINE> <DEDENT> def getPorts(self): <NEW_LINE> <INDENT> return [v for v in self.by_index if v.isPort()] <NEW_LINE> <DEDENT> def addProgramVariable(self, variable): <NEW_LINE> <INDENT> assert type(variable) is UCProgramVariable, "variable should be of type UCProgramVariable" <NEW_LINE> if not variable.name in self.by_name: <NEW_LINE> <INDENT> self.by_name[variable.name] = variable <NEW_LINE> self.by_index.append(variable) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log.error("The variable with name '%s' has already been declared" % port.name)
|
Represents a collection of program variables
|
625990190a366e3fb87dd79b
|
class TemplateMatch(Feature): <NEW_LINE> <INDENT> template_image = None <NEW_LINE> quality = 0 <NEW_LINE> w = 0 <NEW_LINE> h = 0 <NEW_LINE> def __init__(self, image, template, location, quality): <NEW_LINE> <INDENT> self.template_image = template <NEW_LINE> self.image = image <NEW_LINE> self.quality = quality <NEW_LINE> w = template.width <NEW_LINE> h = template.height <NEW_LINE> at_x = location[0] <NEW_LINE> at_y = location[1] <NEW_LINE> points = [(at_x,at_y),(at_x+w,at_y),(at_x+w,at_y+h),(at_x,at_y+h)] <NEW_LINE> super(TemplateMatch, self).__init__(image, at_x, at_y, points) <NEW_LINE> <DEDENT> def _templateOverlaps(self,other): <NEW_LINE> <INDENT> (maxx,minx,maxy,miny) = self.extents() <NEW_LINE> overlap = False <NEW_LINE> for p in other.points: <NEW_LINE> <INDENT> if( p[0] <= maxx and p[0] >= minx and p[1] <= maxy and p[1] >= miny ): <NEW_LINE> <INDENT> overlap = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return overlap <NEW_LINE> <DEDENT> def consume(self, other): <NEW_LINE> <INDENT> (maxx,minx,maxy,miny) = self.extents() <NEW_LINE> (maxx0,minx0,maxy0,miny0) = other.extents() <NEW_LINE> maxx = max(maxx,maxx0) <NEW_LINE> minx = min(minx,minx0) <NEW_LINE> maxy = max(maxy,maxy0) <NEW_LINE> miny = min(miny,miny0) <NEW_LINE> self.x = minx <NEW_LINE> self.y = miny <NEW_LINE> self.points = [(minx,miny),(minx,maxy),(maxx,maxy),(maxx,miny)] <NEW_LINE> self._updateExtents() <NEW_LINE> <DEDENT> def rescale(self,w,h): <NEW_LINE> <INDENT> (maxx,minx,maxy,miny) = self.extents() <NEW_LINE> xc = minx+((maxx-minx)/2) <NEW_LINE> yc = miny+((maxy-miny)/2) <NEW_LINE> x = xc-(w/2) <NEW_LINE> y = yc-(h/2) <NEW_LINE> self.x = x <NEW_LINE> self.y = y <NEW_LINE> self.points = [(x,y), (x+w,y), (x+w,y+h), (x,y+h)] <NEW_LINE> self._updateExtents() <NEW_LINE> <DEDENT> def draw(self, color = Color.GREEN, width = 1): <NEW_LINE> <INDENT> self.image.dl().rectangle((self.x,self.y), (self.width(), self.height()), color = color, width=width)
|
**SUMMARY**
This class is used for template (pattern) matching in images.
The template matching cannot handle scale or rotation.
|
625990195e10d32532ce3fda
|
class Testcase_320_180_MultipartTableFeaturesOmittingMatch(base_tests.SimpleDataPlane): <NEW_LINE> <INDENT> @wireshark_capture <NEW_LINE> def runTest(self): <NEW_LINE> <INDENT> logging.info("Running 320.180 - Table features omitting match test") <NEW_LINE> logging.info("Delete all flows on DUT") <NEW_LINE> rv = delete_all_flows(self.controller) <NEW_LINE> self.assertEqual(rv, 0, "Failed to delete all flows") <NEW_LINE> ModifyTableFeatures = test_param_get("modify", 2) <NEW_LINE> request = ofp.message.table_features_stats_request() <NEW_LINE> stats = get_stats(self, request) <NEW_LINE> self.assertIsNotNone(stats, "Did not receive table features stats reply.") <NEW_LINE> for item in stats: <NEW_LINE> <INDENT> list_prop = [] <NEW_LINE> for prop in item.properties: <NEW_LINE> <INDENT> if type(prop) != ofp.common.table_feature_prop_match: <NEW_LINE> <INDENT> list_prop.append(prop) <NEW_LINE> <DEDENT> <DEDENT> item.properties = list_prop <NEW_LINE> <DEDENT> req = ofp.message.table_features_stats_request(entries=stats) <NEW_LINE> if ModifyTableFeatures==2: <NEW_LINE> <INDENT> self.controller.message_send(req) <NEW_LINE> reply, _ = self.controller.poll(exp_msg=ofp.const.OFPT_ERROR) <NEW_LINE> self.assertIsNotNone(reply, "Didn't receive expected error message.") <NEW_LINE> self.assertEqual(reply.err_type, ofp.const.OFPET_BAD_REQUEST, "Error type was not OFPET_BAD_REQUEST.") <NEW_LINE> self.assertEqual(reply.code, ofp.const.OFPTFFC_BAD_LEN, "Error type was not OFPTFFC_BAD_LEN.") <NEW_LINE> logging.info("Received correct error message.") <NEW_LINE> <DEDENT> elif ModifyTableFeatures==0: <NEW_LINE> <INDENT> self.controller.message_send(req) <NEW_LINE> reply, _ = self.controller.poll(exp_msg=ofp.const.OFPT_ERROR) <NEW_LINE> self.assertIsNotNone(reply, "Didn't receive expected error message.") <NEW_LINE> self.assertEqual(reply.err_type, ofp.const.OFPET_TABLE_FEATURES_FAILED, "Error type was not OFPET_TABLE_FEATURES_FAILED.") <NEW_LINE> self.assertEqual(reply.code, ofp.const.OFPBRC_BAD_LEN, "Error type was not OFPBRC_BAD_LEN.") <NEW_LINE> logging.info("Received correct error message.") <NEW_LINE> <DEDENT> elif ModifyTableFeatures==1: <NEW_LINE> <INDENT> self.controller.message_send(req) <NEW_LINE> reply, _ = self.controller.poll(exp_msg=ofp.const.OFPT_ERROR) <NEW_LINE> self.assertIsNotNone(reply, "Didn't receive expected error message.") <NEW_LINE> self.assertEqual(reply.err_type, ofp.const.OFPET_TABLE_FEATURES_FAILED, "Error type was not OFPET_TABLE_FEATURES_FAILED.") <NEW_LINE> self.assertEqual(reply.code, ofp.const.OFPTFFC_EPERM, "Error type was not OFPTFFC_EPERM.") <NEW_LINE> logging.info("Received correct error message.")
|
320.180 - Table features omitting match
Verify an attempt to set table feature properties without including the match property triggers an error message.
|
625990198c3a8732951f7309
|
class UnionWithData(ctypes.Union): <NEW_LINE> <INDENT> _pack_ = 1 <NEW_LINE> _fields_ = [("input_buffer", ctypes.c_byte * ctypes.sizeof(dynamic_struct)), ("struct_data", dynamic_struct)]
|
This union binds the buffer with the struct or union by holding them as two fields (that's how unions work
in C). Only the struct field should be returned, however, so the user won't be able to access (or know
about) the buffer array field.
|
625990195e10d32532ce3fdb
|
class BahdanauAttention(nn.Module): <NEW_LINE> <INDENT> def __init__(self, hidden_dim=128, query_dim=128, memory_dim=128): <NEW_LINE> <INDENT> super(BahdanauAttention, self).__init__() <NEW_LINE> self.hidden_dim = hidden_dim <NEW_LINE> self.query_dim = query_dim <NEW_LINE> self.memory_dim = memory_dim <NEW_LINE> self.sofmax = nn.Softmax() <NEW_LINE> self.query_layer = nn.Linear(query_dim, hidden_dim, bias=False) <NEW_LINE> self.memory_layer = nn.Linear(memory_dim, hidden_dim, bias=False) <NEW_LINE> self.alignment_layer = nn.Linear(hidden_dim, 1, bias=False) <NEW_LINE> <DEDENT> def alignment_score(self, query, keys): <NEW_LINE> <INDENT> query = self.query_layer(query) <NEW_LINE> keys = self.memory_layer(keys) <NEW_LINE> extendded_query = query.unsqueeze(1) <NEW_LINE> alignment = self.alignment_layer(functional.tanh(extendded_query + keys)) <NEW_LINE> return alignment.squeeze(2) <NEW_LINE> <DEDENT> def forward(self, query, keys): <NEW_LINE> <INDENT> alignment_score = self.alignment_score(query, keys) <NEW_LINE> weight = functional.softmax(alignment_score) <NEW_LINE> context = weight.unsqueeze(2) * keys <NEW_LINE> total_context = context.sum(1) <NEW_LINE> return total_context, alignment_score
|
Reused from https://github.com/chrisbangun/pytorch-seq2seq_with_attention/
|
62599019925a0f43d25e8deb
|
@format_doc(geodetic_base_doc) <NEW_LINE> class BaseGeodeticRepresentation(BaseRepresentation): <NEW_LINE> <INDENT> attr_classes = {'lon': Longitude, 'lat': Latitude, 'height': u.Quantity} <NEW_LINE> def __init_subclass__(cls, **kwargs): <NEW_LINE> <INDENT> super().__init_subclass__(**kwargs) <NEW_LINE> if '_ellipsoid' in cls.__dict__: <NEW_LINE> <INDENT> ELLIPSOIDS[cls._ellipsoid] = cls <NEW_LINE> <DEDENT> <DEDENT> def __init__(self, lon, lat=None, height=None, copy=True): <NEW_LINE> <INDENT> if height is None and not isinstance(lon, self.__class__): <NEW_LINE> <INDENT> height = 0 << u.m <NEW_LINE> <DEDENT> super().__init__(lon, lat, height, copy=copy) <NEW_LINE> if not self.height.unit.is_equivalent(u.m): <NEW_LINE> <INDENT> raise u.UnitTypeError(f"{self.__class__.__name__} requires " f"height with units of length.") <NEW_LINE> <DEDENT> <DEDENT> def to_cartesian(self): <NEW_LINE> <INDENT> xyz = erfa.gd2gc(getattr(erfa, self._ellipsoid), self.lon, self.lat, self.height) <NEW_LINE> return CartesianRepresentation(xyz, xyz_axis=-1, copy=False) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_cartesian(cls, cart): <NEW_LINE> <INDENT> lon, lat, height = erfa.gc2gd(getattr(erfa, cls._ellipsoid), cart.get_xyz(xyz_axis=-1)) <NEW_LINE> return cls(lon, lat, height, copy=False)
|
Base geodetic representation.
|
62599019507cdc57c63a5b4b
|
class BlogDetailView(generic.DetailView): <NEW_LINE> <INDENT> model = Blog
|
Generic class-based detail view for a blog.
|
6259901956b00c62f0fb3668
|
class Response( models.Model ): <NEW_LINE> <INDENT> instance = models.ForeignKey( Instance , blank=False , null=False , editable = False , unique = True ) <NEW_LINE> response = models.TextField( editable = False ) <NEW_LINE> mimeType = models.TextField( editable = True ) <NEW_LINE> def __unicode__( self ) : return unicode( self.instance ) <NEW_LINE> def __str__( self ) : return unicode(self).encode("utf8") <NEW_LINE> class Admin : pass
|
Task Response storage.
DB fields:
instance - process instance;
response - process XML response (if not in plain text GZIP+BASE64 is applied).
|
625990190a366e3fb87dd7a1
|
class SequencingMachine(UuidStampedMixin, TimeStampedModel): <NEW_LINE> <INDENT> vendor_id = models.CharField( unique=True, db_index=True, max_length=100, help_text='Vendor ID of the machine') <NEW_LINE> label = models.CharField( max_length=100, help_text='Short name of the machine') <NEW_LINE> description = models.TextField( blank=True, null=True, help_text=( 'Short description of the machine. ' + markdown_allowed())) <NEW_LINE> machine_model = models.CharField( choices=MACHINE_MODELS, max_length=100, help_text='The model of the machine') <NEW_LINE> slot_count = models.IntegerField(default=1) <NEW_LINE> dual_index_workflow = models.CharField( max_length=10, choices=INDEX_WORKFLOWS, default=INDEX_WORKFLOW_A, help_text='Workflow to use for dual indexing') <NEW_LINE> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('instrument_view', kwargs={'uuid': self.uuid}) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def has_None_permission(request): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def has_read_permission(request): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def has_write_permission(request): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def has_list_permission(request): <NEW_LINE> <INDENT> return request.user.has_perm('flowcells.SequencingMachine:list') <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def has_create_permission(request): <NEW_LINE> <INDENT> return request.user.has_perm('flowcells.SequencingMachine:create') <NEW_LINE> <DEDENT> def has_object_retrieve_permission(self, request): <NEW_LINE> <INDENT> return request.user.has_perm('flowcells.SequencingMachine:retrieve', self) <NEW_LINE> <DEDENT> def has_object_by_vendor_id_permission(self, request): <NEW_LINE> <INDENT> return request.user.has_perm('flowcells.SequencingMachine:by_vendor_id', self) <NEW_LINE> <DEDENT> def has_object_update_permission(self, request): <NEW_LINE> <INDENT> return request.user.has_perm('flowcells.SequencingMachine:update', self) <NEW_LINE> <DEDENT> def has_object_destroy_permission(self, request): <NEW_LINE> <INDENT> return request.user.has_perm('flowcells.SequencingMachine:create', self) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> tpl = 'SequencingMachine({})' <NEW_LINE> vals = (self.uuid, self.vendor_id, self.label, self.description, self.machine_model, self.slot_count, self.dual_index_workflow) <NEW_LINE> return tpl.format(', '.join(repr(v) for v in vals)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self)
|
Represent a sequencing machine instance
|
6259901956b00c62f0fb366a
|
class Thread(models.Model): <NEW_LINE> <INDENT> created = models.DateTimeField(blank=True, null=True, auto_now_add=True) <NEW_LINE> user = models.ForeignKey(hmod.SiteUser) <NEW_LINE> topic = models.ForeignKey(Topic) <NEW_LINE> title = models.TextField(blank=True, null=True) <NEW_LINE> options = JSONField(blank=True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '%s: %s' % (self.id, self.title) <NEW_LINE> <DEDENT> def get_option(self, name, default=None): <NEW_LINE> <INDENT> if isinstance(self.options, dict): <NEW_LINE> <INDENT> return self.options.get(name, default) <NEW_LINE> <DEDENT> return default <NEW_LINE> <DEDENT> def set_option(self, name, value): <NEW_LINE> <INDENT> if not isinstance(self.options, dict): <NEW_LINE> <INDENT> self.options = {} <NEW_LINE> <DEDENT> self.options[name] = value <NEW_LINE> <DEDENT> def get_hash(self): <NEW_LINE> <INDENT> m = hashlib.md5() <NEW_LINE> m.update(self.created.isoformat().encode('utf8')) <NEW_LINE> m.update(self.get_option('salt', 'somedefault').encode('utf8')) <NEW_LINE> return m
|
A discussion thread within a topic
|
62599019d164cc6175821d2b
|
class Checkbox(_CheckableInput): <NEW_LINE> <INDENT> def __init__(self, name="", value=""): <NEW_LINE> <INDENT> super().__init__("checkbox", name, value)
|
An HTML checkbox (<input type="checkbox">) element.
>>> cb = Checkbox("my-name", "my-value")
>>> cb.checked = True
|
62599019d18da76e235b7824
|
class Notation(XMLSchemaComponent): <NEW_LINE> <INDENT> required = ['name', 'public'] <NEW_LINE> attributes = {'id': None, 'name': None, 'public': None, 'system': None} <NEW_LINE> contents = {'xsd': ('annotation')} <NEW_LINE> tag = 'notation' <NEW_LINE> def __init__(self, parent): <NEW_LINE> <INDENT> XMLSchemaComponent.__init__(self, parent) <NEW_LINE> self.annotation = None <NEW_LINE> <DEDENT> def fromDom(self, node): <NEW_LINE> <INDENT> self.setAttributes(node) <NEW_LINE> contents = self.getContents(node) <NEW_LINE> for i in contents: <NEW_LINE> <INDENT> component = SplitQName(i.getTagName())[1] <NEW_LINE> if component == 'annotation' and not self.annotation: <NEW_LINE> <INDENT> self.annotation = Annotation(self) <NEW_LINE> self.annotation.fromDom(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise SchemaError('Unknown component (%s)' % (i.getTagName()))
|
<notation>
parent:
schema
attributes:
id -- ID
name -- NCName, Required
public -- token, Required
system -- anyURI
contents:
annotation?
|
625990199b70327d1c57fb2e
|
class EmotionRecogniser(object): <NEW_LINE> <INDENT> def __init__(self, dev_data, dev_targets, eval_data, eval_targets, features_min_max): <NEW_LINE> <INDENT> logging.info("Initialising emotion recognising") <NEW_LINE> self._error = -1 <NEW_LINE> self._dev_data = dev_data <NEW_LINE> self._dev_targets = dev_targets <NEW_LINE> self._eval_data = eval_data <NEW_LINE> self._eval_targets = eval_targets <NEW_LINE> self._error_list = list() <NEW_LINE> self._net = nl.net.newff( [[-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0], [-2.0, 2.0] ], [Conf.HIDDEN_NEURONS, Conf.OUTPUTS] ) <NEW_LINE> logging.info("Neural network created") <NEW_LINE> <DEDENT> def get_eval_targets(self): <NEW_LINE> <INDENT> return self._eval_targets <NEW_LINE> <DEDENT> def set_net(self, net): <NEW_LINE> <INDENT> self._net = net <NEW_LINE> <DEDENT> def train(self): <NEW_LINE> <INDENT> err = self._net.train(self._dev_data, self._dev_targets) <NEW_LINE> self._error_list = err <NEW_LINE> self._error = err.pop() <NEW_LINE> logging.info("Neural network trained") <NEW_LINE> return err <NEW_LINE> <DEDENT> def evaluate(self): <NEW_LINE> <INDENT> ev = self._net.sim(self._eval_data) <NEW_LINE> logging.info("Neural network evaluated") <NEW_LINE> return ev <NEW_LINE> <DEDENT> def evaluate_data(self, data): <NEW_LINE> <INDENT> ev = self._net.sim(data) <NEW_LINE> logging.info("Neural network evaluated") <NEW_LINE> return ev <NEW_LINE> <DEDENT> def save_net(self, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._net.save(path+str(self._error)) <NEW_LINE> logging.info("Neural succesfully network saved at:{0}".format(Conf.NET_FILE)) <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> logging.error(e)
|
Class containing neural network object, used to train and evaluate
|
62599019d164cc6175821d2d
|
class Event(object): <NEW_LINE> <INDENT> def __init__(self, json_obj): <NEW_LINE> <INDENT> self.id = json_obj['id'] <NEW_LINE> self.raw_json = json_obj <NEW_LINE> self._attributes = json_obj['attributes'] <NEW_LINE> <DEDENT> def __getattr__(self, attr): <NEW_LINE> <INDENT> if attr not in self._attributes: <NEW_LINE> <INDENT> raise AttributeError("Event object has no attribute " + attr) <NEW_LINE> <DEDENT> return self._attributes[attr] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.title.encode('utf-8')
|
Class to represent a Tech @ NYU Event
|
62599019462c4b4f79dbc7b9
|
class CredentialProblemReportRequestSchema(Schema): <NEW_LINE> <INDENT> explain_ltxt = fields.Str(required=True)
|
Request schema for sending a problem report.
|
625990190a366e3fb87dd7a5
|
class Writer(object): <NEW_LINE> <INDENT> def __init__(self, doc_type=None): <NEW_LINE> <INDENT> super(Writer, self).__init__() <NEW_LINE> self.db_name = config.db_name <NEW_LINE> self.doc_type = doc_type <NEW_LINE> self.conn = MongoClient(config.mongodb_uri) <NEW_LINE> self.db = self.conn[self.db_name] <NEW_LINE> self.coll = self.db[self.doc_type] <NEW_LINE> <DEDENT> def insert_many(self, docs): <NEW_LINE> <INDENT> self.coll.insert_many(docs) <NEW_LINE> success = True <NEW_LINE> return success <NEW_LINE> <DEDENT> def insert_one(self, doc): <NEW_LINE> <INDENT> self.coll.insert_one(doc) <NEW_LINE> success = True <NEW_LINE> return success <NEW_LINE> <DEDENT> def create_update_index(self): <NEW_LINE> <INDENT> machines_index = [('ssh_key_name', 'text'), ('type', 'text'), ('public_dns', 'text'), ('private_dns', 'text'), ('tags', 'text'), ('security_group', 'text')] <NEW_LINE> try: <NEW_LINE> <INDENT> res = self.coll.create_index(machines_index, name='machines_index', background=True) <NEW_LINE> <DEDENT> except pymongo.errors.OperationFailure as error: <NEW_LINE> <INDENT> if error.code == 85: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
|
Storage Reader Object
|
625990196fece00bbaccc766
|
@override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE) <NEW_LINE> class TestWikiAccessForStudent(TestWikiAccessBase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(TestWikiAccessForStudent, self).setUp() <NEW_LINE> self.student = UserFactory.create() <NEW_LINE> <DEDENT> def test_student_is_not_root_wiki_staff(self): <NEW_LINE> <INDENT> self.assertFalse(user_is_article_course_staff(self.student, self.wiki.article)) <NEW_LINE> <DEDENT> def test_student_is_not_course_wiki_staff(self): <NEW_LINE> <INDENT> for page in self.wiki_math101_pages: <NEW_LINE> <INDENT> self.assertFalse(user_is_article_course_staff(self.student, page.article))
|
Test access for students.
|
62599019be8e80087fbbfe24
|
class GaussLogisticActiveLearnerMO(GaussLogisticProblem, mps.MyopicOracleExperimentDesigner): <NEW_LINE> <INDENT> pass
|
Active Learning on the Bayesian Logistic Model with the Oracle policy.
|
6259901921a7993f00c66d2d
|
class User(UserMixin): <NEW_LINE> <INDENT> pass
|
User representation
|
625990190a366e3fb87dd7a7
|
class point3d(object): <NEW_LINE> <INDENT> def __init__(self, x = np.float32(0.0), y = np.float32(0.0), z = np.float32(0.0)): <NEW_LINE> <INDENT> self._x = np.float32( x ) <NEW_LINE> self._y = np.float32( y ) <NEW_LINE> self._z = np.float32( z ) <NEW_LINE> <DEDENT> @property <NEW_LINE> def x(self): <NEW_LINE> <INDENT> return self._x <NEW_LINE> <DEDENT> @property <NEW_LINE> def y(self): <NEW_LINE> <INDENT> return self._y <NEW_LINE> <DEDENT> @property <NEW_LINE> def z(self): <NEW_LINE> <INDENT> return self._z <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "({0}, {1}, {2})".format(self._x, self._y, self._z) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "{0} {1} {2}".format(self._x, self._y, self._z) <NEW_LINE> <DEDENT> def __getitem__(self, i): <NEW_LINE> <INDENT> if i < X: <NEW_LINE> <INDENT> raise IndexError("point3d::__getitem__: negative index {0}".format(i)) <NEW_LINE> <DEDENT> if i == X: <NEW_LINE> <INDENT> return self._x <NEW_LINE> <DEDENT> if i == Y: <NEW_LINE> <INDENT> return self._y <NEW_LINE> <DEDENT> if i == Z: <NEW_LINE> <INDENT> return self._z <NEW_LINE> <DEDENT> raise IndexError("point3d::__getitem__: index too large {0}".format(i)) <NEW_LINE> <DEDENT> def __setitem__(self, i, value): <NEW_LINE> <INDENT> if i < X: <NEW_LINE> <INDENT> raise IndexError("point3d::__setitem__: negative index {0}".format(i)) <NEW_LINE> <DEDENT> if i == X: <NEW_LINE> <INDENT> self._x = value <NEW_LINE> return <NEW_LINE> <DEDENT> if i == Y: <NEW_LINE> <INDENT> self._y = value <NEW_LINE> return <NEW_LINE> <DEDENT> if i == Z: <NEW_LINE> <INDENT> self._z = value <NEW_LINE> return <NEW_LINE> <DEDENT> raise IndexError("point3d::__setitem__: index too large {0}".format(i)) <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return point3d(self._x + other._x, self._y + other._y, self._z + other._z) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return point3d(self._x - other._x, self._y - other._y, self._z - other._z) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def distance(pa, pb): <NEW_LINE> <INDENT> return hypot(pa._x - pb._x, pa._y - pb._y, pa._z - pb._z) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def distance2(pa, pb): <NEW_LINE> <INDENT> return squared(pa._x - pb._x) + squared(pa._y - pb._y) + squared(pa._z - pb._z) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def cvt2array(tuples): <NEW_LINE> <INDENT> rc = [] <NEW_LINE> for t in tuples: <NEW_LINE> <INDENT> rc.append(point3d(np.float32(t[X]), np.float32(t[Y]), np.float32(t[Z]))) <NEW_LINE> <DEDENT> return rc
|
3D point made from three floats
|
62599019a8ecb03325871fd0
|
class RepeatingTimer: <NEW_LINE> <INDENT> def __init__(self, interval): <NEW_LINE> <INDENT> self.interval = interval <NEW_LINE> self.callbacks = [] <NEW_LINE> <DEDENT> def register(self, f, *args, **kwargs): <NEW_LINE> <INDENT> self.callbacks.append(Callback(f, args, kwargs)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.running = True <NEW_LINE> while self.running: <NEW_LINE> <INDENT> start_iter = time.time() <NEW_LINE> for callback in self.callbacks: <NEW_LINE> <INDENT> callback.function(*callback.args, **callback.kwargs) <NEW_LINE> <DEDENT> sleep_time = self.interval - (time.time() - start_iter) <NEW_LINE> if(sleep_time > 0): <NEW_LINE> <INDENT> time.sleep(sleep_time) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warning('Iteration took too long')
|
Calls a set of functions in regular intervals
|
6259901991af0d3eaad3abd5
|
class KeyMatcher(object): <NEW_LINE> <INDENT> def __init__(self, keys_to_track): <NEW_LINE> <INDENT> self.keys_to_track = keys_to_track <NEW_LINE> self.tracker = {} <NEW_LINE> for key_to_track in self.keys_to_track: <NEW_LINE> <INDENT> self.tracker[key_to_track] = {} <NEW_LINE> <DEDENT> <DEDENT> def add(self, obj, match_dict): <NEW_LINE> <INDENT> for match_key in match_dict.keys(): <NEW_LINE> <INDENT> assert match_key in self.keys_to_track <NEW_LINE> <DEDENT> for key_to_track in self.keys_to_track: <NEW_LINE> <INDENT> if match_dict.has_key(key_to_track): <NEW_LINE> <INDENT> match_val = match_dict[key_to_track] <NEW_LINE> if match_val is None or match_val == '': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tracker[key_to_track][match_val] = obj <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def match(self, match_dict): <NEW_LINE> <INDENT> for match_key in match_dict.keys(): <NEW_LINE> <INDENT> assert match_key in self.keys_to_track <NEW_LINE> <DEDENT> for key_to_track in self.keys_to_track: <NEW_LINE> <INDENT> if match_dict.has_key(key_to_track): <NEW_LINE> <INDENT> match_val = match_dict[key_to_track] <NEW_LINE> if self.tracker[key_to_track].has_key(match_val): <NEW_LINE> <INDENT> return self.tracker[key_to_track][match_val] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self.keys_to_track
|
Lets you define keys that should be tracked. You then add()
matches. You can then match() against the keys you defined.
The reason this exists is to support a "hierarchy" of matches. For
example, you may want to match on key A--and if there's a match,
you're done. Then if there's no match on key A, try key B. &c.
|
6259901a0a366e3fb87dd7a9
|
class _IMetricProxy: <NEW_LINE> <INDENT> __jsii_type__: typing.ClassVar[str] = "@aws-cdk/aws-cloudwatch.IMetric" <NEW_LINE> @jsii.member(jsii_name="toAlarmConfig") <NEW_LINE> def to_alarm_config(self) -> "MetricAlarmConfig": <NEW_LINE> <INDENT> return jsii.invoke(self, "toAlarmConfig", []) <NEW_LINE> <DEDENT> @jsii.member(jsii_name="toGraphConfig") <NEW_LINE> def to_graph_config(self) -> "MetricGraphConfig": <NEW_LINE> <INDENT> return jsii.invoke(self, "toGraphConfig", []) <NEW_LINE> <DEDENT> @jsii.member(jsii_name="toMetricConfig") <NEW_LINE> def to_metric_config(self) -> "MetricConfig": <NEW_LINE> <INDENT> return jsii.invoke(self, "toMetricConfig", [])
|
Interface for metrics.
|
6259901a56b00c62f0fb3672
|
class OBFS(Binary): <NEW_LINE> <INDENT> file_ext = 'obfs' <NEW_LINE> composite_type = 'basic' <NEW_LINE> allow_datatype_change = False <NEW_LINE> MetadataElement(name="base_name", default='OpenBabel Fastsearch Index', readonly=True, visible=True, optional=True,) <NEW_LINE> def __init__(self, **kwd): <NEW_LINE> <INDENT> Binary.__init__(self, **kwd) <NEW_LINE> self.add_composite_file('molecule.fs', is_binary=True, description='OpenBabel Fastsearch Index') <NEW_LINE> self.add_composite_file('molecule.sdf', optional=True, is_binary=False, description='Molecule File') <NEW_LINE> self.add_composite_file('molecule.smi', optional=True, is_binary=False, description='Molecule File') <NEW_LINE> self.add_composite_file('molecule.inchi', optional=True, is_binary=False, description='Molecule File') <NEW_LINE> self.add_composite_file('molecule.mol2', optional=True, is_binary=False, description='Molecule File') <NEW_LINE> self.add_composite_file('molecule.cml', optional=True, is_binary=False, description='Molecule File') <NEW_LINE> <DEDENT> def set_peek(self, dataset, is_multi_byte=False): <NEW_LINE> <INDENT> if not dataset.dataset.purged: <NEW_LINE> <INDENT> dataset.peek = "OpenBabel Fastsearch Index" <NEW_LINE> dataset.blurb = "OpenBabel Fastsearch Index" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dataset.peek = "file does not exist" <NEW_LINE> dataset.blurb = "file purged from disk" <NEW_LINE> <DEDENT> <DEDENT> def display_peek(self, dataset): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return dataset.peek <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return "OpenBabel Fastsearch Index" <NEW_LINE> <DEDENT> <DEDENT> def display_data(self, trans, data, preview=False, filename=None, to_ext=None, **kwd): <NEW_LINE> <INDENT> return "This is a OpenBabel Fastsearch format. You can speed up your similarity and substructure search with it." <NEW_LINE> <DEDENT> def get_mime(self): <NEW_LINE> <INDENT> return 'text/plain' <NEW_LINE> <DEDENT> def merge(split_files, output_file, extra_merge_args): <NEW_LINE> <INDENT> raise NotImplementedError("Merging Fastsearch indices is not supported.") <NEW_LINE> <DEDENT> def split(cls, input_datasets, subdir_generator_function, split_params): <NEW_LINE> <INDENT> if split_params is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> raise NotImplementedError("Splitting Fastsearch indices is not possible.")
|
OpenBabel Fastsearch format (fs).
|
6259901a5e10d32532ce3fe1
|
class Concord232Alarm(alarm.AlarmControlPanel): <NEW_LINE> <INDENT> def __init__(self, hass, url, name): <NEW_LINE> <INDENT> from concord232 import client as concord232_client <NEW_LINE> self._state = STATE_UNKNOWN <NEW_LINE> self._hass = hass <NEW_LINE> self._name = name <NEW_LINE> self._url = url <NEW_LINE> try: <NEW_LINE> <INDENT> client = concord232_client.Client(self._url) <NEW_LINE> <DEDENT> except requests.exceptions.ConnectionError as ex: <NEW_LINE> <INDENT> _LOGGER.error("Unable to connect to Concord232: %s", str(ex)) <NEW_LINE> <DEDENT> self._alarm = client <NEW_LINE> self._alarm.partitions = self._alarm.list_partitions() <NEW_LINE> self._alarm.last_partition_update = datetime.datetime.now() <NEW_LINE> self.update() <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def code_format(self): <NEW_LINE> <INDENT> return '[0-9]{4}([0-9]{2})?' <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> part = self._alarm.list_partitions()[0] <NEW_LINE> <DEDENT> except requests.exceptions.ConnectionError as ex: <NEW_LINE> <INDENT> _LOGGER.error("Unable to connect to %(host)s: %(reason)s", dict(host=self._url, reason=ex)) <NEW_LINE> newstate = STATE_UNKNOWN <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> _LOGGER.error("Concord232 reports no partitions") <NEW_LINE> newstate = STATE_UNKNOWN <NEW_LINE> <DEDENT> if part['arming_level'] == 'Off': <NEW_LINE> <INDENT> newstate = STATE_ALARM_DISARMED <NEW_LINE> <DEDENT> elif 'Home' in part['arming_level']: <NEW_LINE> <INDENT> newstate = STATE_ALARM_ARMED_HOME <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newstate = STATE_ALARM_ARMED_AWAY <NEW_LINE> <DEDENT> if not newstate == self._state: <NEW_LINE> <INDENT> _LOGGER.info("State Chnage from %s to %s", self._state, newstate) <NEW_LINE> self._state = newstate <NEW_LINE> <DEDENT> return self._state <NEW_LINE> <DEDENT> def alarm_disarm(self, code=None): <NEW_LINE> <INDENT> self._alarm.disarm(code) <NEW_LINE> <DEDENT> def alarm_arm_home(self, code=None): <NEW_LINE> <INDENT> self._alarm.arm('home') <NEW_LINE> <DEDENT> def alarm_arm_away(self, code=None): <NEW_LINE> <INDENT> self._alarm.arm('auto')
|
Represents the Concord232-based alarm panel.
|
6259901a91af0d3eaad3abd7
|
class Send(VbaLibraryFunc): <NEW_LINE> <INDENT> def eval(self, context, params=None): <NEW_LINE> <INDENT> return 200
|
Faked emulation of HTTP send(). Always returns 200.
|
6259901abe8e80087fbbfe28
|
class Log: <NEW_LINE> <INDENT> def __init__(self, filename="") -> None: <NEW_LINE> <INDENT> self._logger = logging.getLogger(filename) <NEW_LINE> self._log_level = logging.DEBUG <NEW_LINE> self._log_dir = None <NEW_LINE> self.log_format = LOG_FORMAT <NEW_LINE> self.rp_logger = None <NEW_LINE> <DEDENT> def set_rp_logger(self, logger): <NEW_LINE> <INDENT> self.rp_logger = logger <NEW_LINE> <DEDENT> @property <NEW_LINE> def log_dir(self) -> str: <NEW_LINE> <INDENT> return self._log_dir <NEW_LINE> <DEDENT> @property <NEW_LINE> def log_level(self) -> int: <NEW_LINE> <INDENT> return self._log_level <NEW_LINE> <DEDENT> @property <NEW_LINE> def config(self) -> Dict: <NEW_LINE> <INDENT> return TestMetaData() <NEW_LINE> <DEDENT> @property <NEW_LINE> def run_id(self) -> str: <NEW_LINE> <INDENT> return self.config.get("run_id") <NEW_LINE> <DEDENT> @property <NEW_LINE> def metadata(self) -> Dict: <NEW_LINE> <INDENT> return dict( { "test_run_id": self.run_id, "testing_tool": "cephci", "rhcs": self.config.get("rhcs"), "test_build": self.config.get("rhbuild", "released"), } ) <NEW_LINE> <DEDENT> def _log(self, level: str, message: Any, *args, **kwargs) -> None: <NEW_LINE> <INDENT> log = { "info": self._logger.info, "debug": self._logger.debug, "warning": self._logger.warning, "error": self._logger.error, "exception": self._logger.exception, } <NEW_LINE> extra = deepcopy(self.metadata) <NEW_LINE> extra.update(kwargs.get("metadata", {})) <NEW_LINE> log[level](message, *args, extra=extra, **kwargs) <NEW_LINE> <DEDENT> def info(self, message: Any, *args, **kwargs) -> None: <NEW_LINE> <INDENT> self._log( "info", message, *args, **kwargs, ) <NEW_LINE> <DEDENT> def debug(self, message: Any, *args, **kwargs) -> None: <NEW_LINE> <INDENT> self._log( "debug", message, *args, **kwargs, ) <NEW_LINE> <DEDENT> def warning(self, message: Any, *args, **kwargs) -> None: <NEW_LINE> <INDENT> self._log("warning", message, *args, **kwargs) <NEW_LINE> <DEDENT> def error( self, message: Any, *args, **kwargs, ) -> None: <NEW_LINE> <INDENT> kwargs["exc_info"] = kwargs.get("exc_info", True) <NEW_LINE> if self.rp_logger: <NEW_LINE> <INDENT> self.rp_logger.log(message=message, level="ERROR") <NEW_LINE> <DEDENT> self._log("error", message, *args, **kwargs) <NEW_LINE> <DEDENT> def exception( self, message: Any, *args, **kwargs, ) -> None: <NEW_LINE> <INDENT> kwargs["exc_info"] = kwargs.get("exc_info", True) <NEW_LINE> self._log("exception", message, *args, **kwargs)
|
CephCI Logger object to help streamline logging.
|
6259901a9b70327d1c57fb36
|
class ProjectTestCase(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> project1 = Project.objects.create(title="Test Project 1", creator="user_test1", tagline="Test Tagline 1", content="Test Content 1", avail_mem=True, sponsor=False, slug="test1-slug",resource="Test Resource 1") <NEW_LINE> project2 = Project.objects.create() <NEW_LINE> self.user1 = User.objects.create_user('user_test1', 'test1@test.com', 'groupthink') <NEW_LINE> Membership.objects.create(user=self.user1, project=project1, invite_reason='') <NEW_LINE> <DEDENT> def test_get_my_projects(self): <NEW_LINE> <INDENT> my_projects = Project.get_my_projects(self.user1) <NEW_LINE> for proj in my_projects: <NEW_LINE> <INDENT> self.assertEqual(proj.slug, 'test1-slug') <NEW_LINE> <DEDENT> <DEDENT> def test_get_all_projects(self): <NEW_LINE> <INDENT> all_projects = Project.get_all_projects() <NEW_LINE> self.assertEqual(len(all_projects), 2) <NEW_LINE> <DEDENT> def test_get_created_projects(self): <NEW_LINE> <INDENT> created_projects = Project.get_created_projects(self.user1) <NEW_LINE> for proj in created_projects: <NEW_LINE> <INDENT> self.assertEqual(proj.creator, 'user_test1')
|
Tests various methods included in projects/models.py
Adapted from: https://docs.djangoproject.com/en/1.11/topics/testing/overview/
|
6259901a0a366e3fb87dd7ab
|
class stock_move(osv.osv): <NEW_LINE> <INDENT> _inherit = 'stock.move' <NEW_LINE> def default_get(self, cr, uid, fields, context=None): <NEW_LINE> <INDENT> if not context: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> res = super(stock_move, self).default_get(cr, uid, fields, context=context) <NEW_LINE> res['date'] = res['date_expected'] = context.get('date_expected', time.strftime('%Y-%m-%d %H:%M:%S')) <NEW_LINE> return res <NEW_LINE> <DEDENT> def do_partial(self, cr, uid, ids, partial_datas, context=None): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> date_tools = self.pool.get('date.tools') <NEW_LINE> res = super(stock_move, self).do_partial(cr, uid, ids, partial_datas, context=context) <NEW_LINE> so_obj = self.pool.get('sale.order') <NEW_LINE> for obj in self.browse(cr, uid, ids, context=context): <NEW_LINE> <INDENT> if obj.picking_id and obj.picking_id.sale_id and not obj.picking_id.sale_id.shipment_date: <NEW_LINE> <INDENT> sale_id = obj.picking_id.sale_id.id <NEW_LINE> date_format = date_tools.get_date_format(cr, uid, context=context) <NEW_LINE> db_date_format = date_tools.get_db_date_format(cr, uid, context=context) <NEW_LINE> today = time.strftime(date_format) <NEW_LINE> today_db = time.strftime(db_date_format) <NEW_LINE> so_obj.write(cr, uid, [sale_id], {'shipment_date': today_db}) <NEW_LINE> so_obj.log(cr, uid, sale_id, _("Shipment Date of the Field Order '%s' has been updated to %s.") % (obj.picking_id.sale_id.name, today)) <NEW_LINE> <DEDENT> <DEDENT> return res
|
shipment date of sale order is updated
|
6259901a56b00c62f0fb3674
|
class AssessmentDto(BaseDto): <NEW_LINE> <INDENT> allottedMinutes = ndb.IntegerProperty(indexed=False) <NEW_LINE> owner = ndb.KeyProperty(UserDto) <NEW_LINE> closeTime = ndb.StringProperty() <NEW_LINE> description = ndb.StringProperty(indexed=False) <NEW_LINE> openTime = ndb.StringProperty() <NEW_LINE> pointsForCorrectAns = ndb.IntegerProperty(indexed=False) <NEW_LINE> pointsForWrongAns = ndb.IntegerProperty(indexed=False) <NEW_LINE> published = ndb.BooleanProperty() <NEW_LINE> randomizeAnswers = ndb.BooleanProperty(indexed=False) <NEW_LINE> randomizeQuestions = ndb.BooleanProperty(indexed=False) <NEW_LINE> showScore = ndb.BooleanProperty(indexed=False) <NEW_LINE> startTime = ndb.StringProperty() <NEW_LINE> title = ndb.StringProperty(indexed=False)
|
Represents an assessment.
|
6259901a796e427e5384f536
|
class RedditerCreationForm(UserCreationForm): <NEW_LINE> <INDENT> def __init__(self, *args, **kargs): <NEW_LINE> <INDENT> super(RedditerCreationForm, self).__init__(*args, **kargs)
|
A form that creates a user, with no privileges, from the given email and
password.
|
6259901ad164cc6175821d35
|
class AttrVI_ATTR_TERMCHAR(RangeAttribute): <NEW_LINE> <INDENT> resources = [(constants.InterfaceType.gpib, 'INSTR'), (constants.InterfaceType.gpib, 'INTFC'), (constants.InterfaceType.asrl, 'INSTR'), (constants.InterfaceType.tcpip, 'INSTR'), (constants.InterfaceType.tcpip, 'SOCKET'), (constants.InterfaceType.usb, 'INSTR'), (constants.InterfaceType.usb, 'RAW'), (constants.InterfaceType.vxi, 'INSTR'), (constants.InterfaceType.vxi, 'SERVANT')] <NEW_LINE> py_name = '' <NEW_LINE> visa_name = 'VI_ATTR_TERMCHAR' <NEW_LINE> visa_type = 'ViUInt8' <NEW_LINE> default = 0x0A <NEW_LINE> read, write, local = True, True, True <NEW_LINE> min_value, max_value, values = 0, 0xFF, []
|
VI_ATTR_TERMCHAR is the termination character. When the termination
character is read and VI_ATTR_TERMCHAR_EN is enabled during a read
operation, the read operation terminates.
|
6259901a925a0f43d25e8df9
|
class _ActuatorEncoder(json.JSONEncoder): <NEW_LINE> <INDENT> def default(self, o): <NEW_LINE> <INDENT> if isinstance(o, Actuator): <NEW_LINE> <INDENT> dct = {} <NEW_LINE> dct["status"] = o.actuatorState.value <NEW_LINE> dct["value"] = o.value <NEW_LINE> return dct <NEW_LINE> <DEDENT> return json.JSONEncoder.default(self, o)
|
Actuator JSON encoder that returns
dictionary with status and value
|
6259901aa8ecb03325871fd6
|
class _dataclasses: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def patch(cls): <NEW_LINE> <INDENT> def raise_if_frozen(self, fun, name, *args, **kwargs): <NEW_LINE> <INDENT> _raise_if(f"cannot assign to/delete field {name!r}", getattr(self, '__frozen__', False)) <NEW_LINE> getattr(object, fun)(self, name, *args, **kwargs) <NEW_LINE> <DEDENT> def init(self, *args, **kwargs): <NEW_LINE> <INDENT> if args and hasattr(self, '__frozen__'): <NEW_LINE> <INDENT> logger.debug(f"Assuming {self} is from the patched __new__ with __from_argv__, already initialized, skipping init.") <NEW_LINE> return <NEW_LINE> <DEDENT> self.__original_init__(*args, **kwargs) <NEW_LINE> object.__setattr__(self, '__frozen__', True) <NEW_LINE> self.__class__.__arg_suite__.post_validation(self) <NEW_LINE> <DEDENT> cls.__init__, cls.__original_init__ = init, cls.__init__ <NEW_LINE> cls.__setattr__ = lambda self, name, value: raise_if_frozen(self, '__setattr__', name, value) <NEW_LINE> cls.__delattr__ = lambda self, name, : raise_if_frozen(self, '__delattr__', name) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def field_default(arg_class, raw_arg_name): <NEW_LINE> <INDENT> f = arg_class.__dataclass_fields__[raw_arg_name] <NEW_LINE> return f.default_factory() if f.default_factory is not MISSING else f.default <NEW_LINE> <DEDENT> proxy = lambda t: _dataclasses if is_dataclass(t) else None <NEW_LINE> asdict = lambda args: asdict(args) <NEW_LINE> new_instance = lambda arg_class, _: arg_class.__original_new__(arg_class)
|
dataclass proxy
|
6259901a6fece00bbaccc76f
|
class Alianza(Candidatura): <NEW_LINE> <INDENT> plural_name = NOMBRE_JSON_ALIANZAS <NEW_LINE> def full_dict(self, img_func, listas=True): <NEW_LINE> <INDENT> alianza = self.to_dict() <NEW_LINE> alianza['imagen'] = img_func(alianza['codigo']) <NEW_LINE> alianza['listas'] = [] <NEW_LINE> if listas: <NEW_LINE> <INDENT> for lista in self.listas: <NEW_LINE> <INDENT> lista_dict = lista.to_dict() <NEW_LINE> lista_dict['candidatos'] = [cand.full_dict(img_func) for cand in lista.candidatos] <NEW_LINE> alianza['listas'].append(lista_dict) <NEW_LINE> <DEDENT> <DEDENT> return alianza <NEW_LINE> <DEDENT> def candidatos_principales(self, cod_categoria): <NEW_LINE> <INDENT> ids_listas = [lista.codigo for lista in self.listas] <NEW_LINE> candidatos = Candidato.many(titular=True, numero_de_orden=1, cod_lista__in=ids_listas, cod_categoria=cod_categoria) <NEW_LINE> return candidatos <NEW_LINE> <DEDENT> @property <NEW_LINE> def listas(self): <NEW_LINE> <INDENT> listas = [] <NEW_LINE> for partido in self.partidos: <NEW_LINE> <INDENT> listas.extend(partido.listas) <NEW_LINE> <DEDENT> return listas <NEW_LINE> <DEDENT> def es_blanco(self): <NEW_LINE> <INDENT> return self.codigo.endswith(COD_LISTA_BLANCO)
|
Alianza que participa de la eleccion.
|
6259901a0a366e3fb87dd7af
|
class LayerObjective(Objective): <NEW_LINE> <INDENT> def __init__(self, model, layer, channel=None, neuron=None, shortcut=False, batchwise=False): <NEW_LINE> <INDENT> self.model = model <NEW_LINE> self.layer = layer <NEW_LINE> self.channel = channel <NEW_LINE> self.neuron = neuron <NEW_LINE> self.shortcut = shortcut <NEW_LINE> self.batchwise = batchwise <NEW_LINE> if self.shortcut: <NEW_LINE> <INDENT> self.active = False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.model[layer] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise ValueError(f"Can't find layer {layer}. Use 'get_layer_names' to print all layer names.") <NEW_LINE> <DEDENT> <DEDENT> def objective_function(self, x): <NEW_LINE> <INDENT> def layer_hook(hook, module, input, output): <NEW_LINE> <INDENT> rank = len(output.shape) <NEW_LINE> c = self.channel or slice(None) <NEW_LINE> n = self.neuron or slice(None) <NEW_LINE> offset = ((0 if self.channel is None else 1) + (0 if self.neuron is None else 2)) <NEW_LINE> dims = list(range(1,rank - offset)) if self.batchwise else [] <NEW_LINE> if rank == 4: <NEW_LINE> <INDENT> self.loss = -torch.mean(output[:, c, n, n], dim=dims) <NEW_LINE> <DEDENT> elif rank == 2: <NEW_LINE> <INDENT> self.loss = -torch.mean(output[:, n], dim=dims) <NEW_LINE> assert self.channel is None, f"Channel is unused for layer {self.layer}" <NEW_LINE> <DEDENT> self.active = True <NEW_LINE> <DEDENT> with Hook(self.model[self.layer], layer_hook, detach=False, clone=True): <NEW_LINE> <INDENT> if self.shortcut: <NEW_LINE> <INDENT> for i, m in enumerate(self.model.children()): <NEW_LINE> <INDENT> x = m(x) <NEW_LINE> if self.active: <NEW_LINE> <INDENT> self.active = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> x = self.model(x) <NEW_LINE> <DEDENT> <DEDENT> return self.loss <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> msg = f"{self.cls_name}: {self.layer}" <NEW_LINE> if self.channel is not None: <NEW_LINE> <INDENT> msg += f":{self.channel}" <NEW_LINE> <DEDENT> if self.neuron is not None: <NEW_LINE> <INDENT> msg += f":{self.neuron}" <NEW_LINE> <DEDENT> if self.channel is None and self.neuron is not None and self.model[self.layer].weight.size(0)==1000: <NEW_LINE> <INDENT> msg += f" {imagenet_labels[self.neuron]}" <NEW_LINE> <DEDENT> return msg
|
Generate an Objective from a particular layer of a network.
Supports the layer indexing that interpret provides as well as
options for selecting the channel or neuron of the layer.
Parameters:
model (nn.Module): PyTorch model.
layer (str or int): the layer to optimise.
channel (int): the channel to optimise. (optional)
neuron (int): the neuron to optimise. (optional)
shortcut (bool): Whether to attempt to shortcut the network's
computation. Only works for Sequential type models.
batchwise (bool): Calculate the loss for each element in the batch.
|
6259901a56b00c62f0fb3678
|
class ToggleDrive(yeti.Module): <NEW_LINE> <INDENT> USE_CAN = False <NEW_LINE> def module_init(self): <NEW_LINE> <INDENT> self.referee = Referee(self) <NEW_LINE> self.joystick = wpilib.Joystick(0) <NEW_LINE> self.referee.watch(self.joystick) <NEW_LINE> if self.USE_CAN: <NEW_LINE> <INDENT> motor_controller_class = wpilib.CANJaguar <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> motor_controller_class = wpilib.Jaguar <NEW_LINE> <DEDENT> self.right_front_cim = motor_controller_class(0) <NEW_LINE> self.referee.watch(self.right_front_cim) <NEW_LINE> self.left_front_cim = motor_controller_class(1) <NEW_LINE> self.referee.watch(self.left_front_cim) <NEW_LINE> self.right_rear_cim = motor_controller_class(2) <NEW_LINE> self.referee.watch(self.right_rear_cim) <NEW_LINE> self.left_rear_cim = motor_controller_class(3) <NEW_LINE> self.referee.watch(self.left_rear_cim) <NEW_LINE> self.robotdrive = wpilib.RobotDrive(self.left_front_cim, self.left_rear_cim, self.right_front_cim, self.right_rear_cim) <NEW_LINE> self.referee.watch(self.robotdrive) <NEW_LINE> <DEDENT> @gamemode.teleop_task <NEW_LINE> @asyncio.coroutine <NEW_LINE> def teleop_loop(self): <NEW_LINE> <INDENT> while gamemode.is_teleop(): <NEW_LINE> <INDENT> strafemode = self.joystick.getRawButton(9) <NEW_LINE> if strafemode: <NEW_LINE> <INDENT> self.robotdrive.mecanumDrive_Cartesian(-self.joystick.getX(), -self.joystick.getY(), 0, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.robotdrive.mecanumDrive_Cartesian(0, -self.joystick.getY(), -self.joystick.getX(), 0) <NEW_LINE> <DEDENT> yield from asyncio.sleep(.05)
|
A 1-Joystick Mecanum drivetrain module, holding button 10 to switch between spin and strafe.
|
6259901ad18da76e235b782b
|
class ActionCounterWithWindow(TransformerMixin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.column_names = ['action_counter'] <NEW_LINE> <DEDENT> def fit(self, X): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, X): <NEW_LINE> <INDENT> return X[self.column_names] <NEW_LINE> <DEDENT> def get_feature_names(self): <NEW_LINE> <INDENT> return self.column_names <NEW_LINE> <DEDENT> def append_features(self, X): <NEW_LINE> <INDENT> configuration_data = json.loads(open("configuration.json", "r").read()) <NEW_LINE> window_size = configuration_data['time_window_sizes']['action_features'] <NEW_LINE> actions_in_the_window_counters = [] <NEW_LINE> for index, row in X.iterrows(): <NEW_LINE> <INDENT> X_temp = deepcopy(X) <NEW_LINE> time_from_start = row['time_from_start_sec'] <NEW_LINE> include_in_the_window = [] <NEW_LINE> for index2, row2 in X.iterrows(): <NEW_LINE> <INDENT> time_to_check = row2['time_from_start_sec'] <NEW_LINE> if check_if_time_in_window_size(time_from_start, time_to_check, window_size): <NEW_LINE> <INDENT> include_in_the_window.append(1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> include_in_the_window.append(0) <NEW_LINE> <DEDENT> <DEDENT> X_temp['in_window'] = include_in_the_window <NEW_LINE> X_temp = X_temp[X_temp['in_window'] == 1] <NEW_LINE> actions_in_the_window_counters.append(len(X_temp)) <NEW_LINE> <DEDENT> X['action_counter'] = actions_in_the_window_counters <NEW_LINE> return X
|
All actions are counted (also actions that were not modified between train-eval loops)
|
6259901a796e427e5384f53c
|
class Deuterium(IsotopeMixin, Hidrogen): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(1)
|
Deuterium element
|
6259901a21a7993f00c66d39
|
class getPersonByName_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None, dataException=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.dataException = dataException <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.success = Person() <NEW_LINE> self.success.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.dataException = DataException() <NEW_LINE> self.dataException.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getPersonByName_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRUCT, 0) <NEW_LINE> self.success.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.dataException is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('dataException', TType.STRUCT, 1) <NEW_LINE> self.dataException.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
|
Attributes:
- success
- dataException
|
6259901a91af0d3eaad3abe0
|
class UnsubscribeForm(AlertPreferenceForm): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(UnsubscribeForm, self).__init__(*args, **kwargs) <NEW_LINE> for backend in self.backends: <NEW_LINE> <INDENT> for alert in self.alerts: <NEW_LINE> <INDENT> field_id = self._field_id(alert.id, backend.id) <NEW_LINE> self.fields[field_id].widget = forms.HiddenInput() <NEW_LINE> self.fields[field_id].initial = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> alert_prefs = super(UnsubscribeForm, self).save(*args, **kwargs) <NEW_LINE> affected_alerts = Alert.objects.filter( is_sent=False, user=self.user, backend__in=[backend.id for backend in self.backends], alert_type__in=[alert.id for alert in self.alerts] ) <NEW_LINE> affected_alerts.delete() <NEW_LINE> return alert_prefs
|
This form does not show any check boxes, it expects to be placed into
the page with only a submit button and some text explaining that by
clicking the submit button the user will unsubscribe form the Alert
notifications. (the alert that is passed in)
|
6259901a0a366e3fb87dd7b3
|
class ContractList(generics.ListCreateAPIView): <NEW_LINE> <INDENT> queryset = Contract.objects.all() <NEW_LINE> serializer_class = ContractSerializer <NEW_LINE> filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter] <NEW_LINE> filterset_fields = ['user__username', 'structure__name', 'type_contract', 'renewable', 'state'] <NEW_LINE> search_fields = ['user__username', 'structure__name', 'employee__name', 'partner__name', 'type_contract'] <NEW_LINE> ordering_fields = ['created_at', 'signing_date'] <NEW_LINE> permission_classes = [permissions.IsAuthenticatedOrReadOnly] <NEW_LINE> def perform_create(self, serializer): <NEW_LINE> <INDENT> serializer.save(user=self.request.user)
|
Ce generics fournit les actions `list`, `create` pour les contrats
|
6259901a9b70327d1c57fb3f
|
class BearerTokenError(Exception): <NEW_LINE> <INDENT> _errors = { 'invalid_request': ( 'The request is otherwise malformed', 400 ), 'invalid_token': ( 'The access token provided is expired, revoked, malformed, ' 'or invalid for other reasons', 401 ), 'insufficient_scope': ( 'The request requires higher privileges than provided by ' 'the access token', 403 ), } <NEW_LINE> def __init__(self, code): <NEW_LINE> <INDENT> self.code = code <NEW_LINE> error_tuple = self._errors.get(code, ('', '')) <NEW_LINE> self.description = error_tuple[0] <NEW_LINE> self.status = error_tuple[1]
|
OAuth2 errors.
https://tools.ietf.org/html/rfc6750#section-3.1
|
6259901a8c3a8732951f7320
|
class TimeoutError(CommunicationError): <NEW_LINE> <INDENT> pass
|
Raised when an NFC Forum Digital Specification timeout error
occured.
|
6259901a5166f23b2e244191
|
class NodeDispatcher(object): <NEW_LINE> <INDENT> def __init__(self, registry, node, user, permissions): <NEW_LINE> <INDENT> self.registry = registry <NEW_LINE> self.node = node <NEW_LINE> self.user = user <NEW_LINE> self.permissions = permissions <NEW_LINE> <DEDENT> def __call__(self, endpoint, args): <NEW_LINE> <INDENT> if '/' not in endpoint: <NEW_LINE> <INDENT> raise ViewNotFound(endpoint) <NEW_LINE> <DEDENT> viewname, endpointname = endpoint.split('/', 1) <NEW_LINE> view = self.registry.viewlist[viewname](self.node, self.user, self.permissions) <NEW_LINE> g.view = view <NEW_LINE> return view.view_functions[endpointname](view, **args)
|
Dispatch a view. Internal class used by :meth:`NodePublisher.publish`.
:param registry: Registry to look up views in.
:param node: Node for which we are dispatching views.
:param user: User for which we are rendering the view.
:param permissions: Externally-granted permissions for this user.
The view instance is made available as ``flask.g.view``.
|
6259901ad18da76e235b782d
|
class User(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(_('email address'), max_length=254, unique=True) <NEW_LINE> first_name = models.CharField(_('first name'), max_length=30, blank=True) <NEW_LINE> last_name = models.CharField(_('last name'), max_length=30, blank=True) <NEW_LINE> is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) <NEW_LINE> is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) <NEW_LINE> date_joined = models.DateTimeField(_('date joined'), default=timezone.now) <NEW_LINE> objects = UserManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = [] <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('user') <NEW_LINE> verbose_name_plural = _('users') <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return "/users/%s/" % urlquote(self.email) <NEW_LINE> <DEDENT> def get_full_name(self): <NEW_LINE> <INDENT> full_name = '%s %s' % (self.first_name, self.last_name) <NEW_LINE> return full_name.strip() <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.first_name <NEW_LINE> <DEDENT> def email_user(self, subject, message, from_email=None): <NEW_LINE> <INDENT> send_mail(subject, message, from_email, [self.email])
|
A fully featured User model with admin-compliant permissions that uses
a full-length email field as the username.
Email and password are required. Other fields are optional.
|
6259901a91af0d3eaad3abe2
|
class _AccessGroups(lhn.AccordionGroup): <NEW_LINE> <INDENT> _locator_button_create_new = locator.LhnMenu.BUTTON_CREATE_NEW_ACCESS_GROUPS <NEW_LINE> _locator_spinny = locator.LhnMenu.SPINNY_ACCESS_GROUPS
|
Access groups dropdown in LHN.
|
6259901a925a0f43d25e8e03
|
class TestDetectListType: <NEW_LINE> <INDENT> test_data = [ FixtureTestData(int, None), FixtureTestData(str, None), FixtureTestData(typing.List[int], int), FixtureTestData(typing.List[str], str), FixtureTestData(typing.List[BogusClass], BogusClass), FixtureTestData(BogusClass, None) ] <NEW_LINE> test_ids = [ "{input} => {output}".format( input=test_datum.input, output=test_datum.output, ) for test_datum in test_data ] <NEW_LINE> @pytest.mark.parametrize("test_data", test_data, ids=test_ids) <NEW_LINE> def test_correctness(self, test_data): <NEW_LINE> <INDENT> assert _arm.detect_list_type(test_data.input) == test_data.output <NEW_LINE> <DEDENT> def test_py37_above(self, mocker): <NEW_LINE> <INDENT> target_typ = int <NEW_LINE> mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(3, 7)) <NEW_LINE> built_typ = mocker.patch( "{}._typing._GenericAlias".format(TARGET_MODULE), create=True, _name="List", __args__=[target_typ]) <NEW_LINE> if sys.version_info >= (3, 0): <NEW_LINE> <INDENT> mocker.patch("builtins.type", create=True, return_value=built_typ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mocker.patch("__builtin__.type", create=True, return_value=built_typ) <NEW_LINE> <DEDENT> assert _arm.detect_list_type(built_typ) == target_typ <NEW_LINE> <DEDENT> def test_py30_to_36(self, mocker): <NEW_LINE> <INDENT> target_typ = int <NEW_LINE> mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(3, 0)) <NEW_LINE> built_typ = mocker.patch( "{}._typing.GenericMeta".format(TARGET_MODULE), create=True, __extra__=list, __args__=[target_typ]) <NEW_LINE> mocker.patch("{}.type".format(TARGET_MODULE), return_value=built_typ) <NEW_LINE> assert _arm.detect_list_type(built_typ) == target_typ <NEW_LINE> <DEDENT> def test_py30_to_36_with_type_exception(self, mocker): <NEW_LINE> <INDENT> target_typ = int <NEW_LINE> mocker.patch("{}._sys".format(TARGET_MODULE), version_info=(3, 0)) <NEW_LINE> built_typ = mocker.patch( "{}._typing.GenericMeta".format(TARGET_MODULE), create=True, __origin__=typing.List, __args__=[target_typ]) <NEW_LINE> mocker.patch("{}.type".format(TARGET_MODULE), side_effect=AttributeError()) <NEW_LINE> assert _arm.detect_list_type(built_typ) == target_typ
|
Testing class for `codepost.models.abstract.api_resource_metaclass`
method `detect_list_type`.
|
6259901ad164cc6175821d41
|
class PostExecutionHook(BaseToolDeclaration): <NEW_LINE> <INDENT> pass
|
A declarative class for contributing a measurement post-execution.
PostExecutionHook object can be contributed as extensions child to the
'post-execution' extension point of the 'exopy.measurement' plugin.
|
6259901ad18da76e235b782f
|
class LogoutView(RedirectView): <NEW_LINE> <INDENT> def get_redirect_url(self, *args, **kwargs): <NEW_LINE> <INDENT> url = self.request.META.get('HTTP_REFERER', '/') <NEW_LINE> return url <NEW_LINE> <DEDENT> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> if self.request.user.is_authenticated(): <NEW_LINE> <INDENT> logout(request) <NEW_LINE> <DEDENT> return super(LogoutView, self).get(request, *args, **kwargs)
|
Обработчик кнопки 'ВЫЙТИ'
|
6259901a462c4b4f79dbc7cd
|
class JSONConverter(BaseConverter): <NEW_LINE> <INDENT> def __init__(self, *args, json_spaces=4, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self.config['outfile_type'] = '.json' <NEW_LINE> self.config['allow_comments'] = False <NEW_LINE> self.config['json_space'] = ' '*json_spaces <NEW_LINE> self.last_indent = None <NEW_LINE> self.last_line = '' <NEW_LINE> <DEDENT> def get_outfile(self,outfile): <NEW_LINE> <INDENT> outfile = super().get_outfile(outfile) <NEW_LINE> if not outfile.tell(): <NEW_LINE> <INDENT> outfile.write('{\n') <NEW_LINE> outfile.write('{}"version": {},\n'.format(self.config['json_space'], json.dumps(self.config['version']))) <NEW_LINE> self.last_indent = self.config['json_space'] <NEW_LINE> <DEDENT> return outfile <NEW_LINE> <DEDENT> def comma_check(self, outfile): <NEW_LINE> <INDENT> prev_line = self.last_line.rstrip() <NEW_LINE> if prev_line.endswith(','): <NEW_LINE> <INDENT> seek_dist = len(self.last_indent) - 1 <NEW_LINE> outfile.seek(outfile.tell()-seek_dist) <NEW_LINE> outfile.write('\n') <NEW_LINE> <DEDENT> <DEDENT> def output_token(self, token, outfile): <NEW_LINE> <INDENT> if token['type'] is TokenType.SQL: <NEW_LINE> <INDENT> if not token['contents'].lower().startswith('prepare'): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> key,query = PREPARE_REGEX.match(token['contents']).groups() <NEW_LINE> query = query.replace('\n', ' ') <NEW_LINE> line = '{}"{}": {},\n'.format(self.last_indent, key, json.dumps(query)) <NEW_LINE> outfile.write(line) <NEW_LINE> self.last_line = line <NEW_LINE> <DEDENT> <DEDENT> elif token['type'] is TokenType.GROUP_TAG: <NEW_LINE> <INDENT> if token['contents']['tag'].lower() == STARTGROUP_TAG: <NEW_LINE> <INDENT> line = '{0}"{1}": {{\n'.format(self.last_indent, token['contents']['name']) <NEW_LINE> outfile.write(line) <NEW_LINE> self.last_line = line <NEW_LINE> self.last_indent += self.config['json_space'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.last_indent = self.last_indent[:len(self.config['json_space'])] <NEW_LINE> self.comma_check(outfile) <NEW_LINE> line = '{}}},\n'.format(self.last_indent) <NEW_LINE> outfile.write(line) <NEW_LINE> self.last_line = line <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def output_tokens(self): <NEW_LINE> <INDENT> super().output_tokens() <NEW_LINE> for outfile in self.outfiles.values(): <NEW_LINE> <INDENT> self.comma_check(outfile) <NEW_LINE> outfile.write('}')
|
tosses all comments
uses groups to make nested dicts
only converts PREPARE sql statements:
use name inside the PREPARE portion as key name
the parametrized query ready for the pg api
|
6259901a91af0d3eaad3abe6
|
class LightweightChart(FigureCanvas): <NEW_LINE> <INDENT> fig = None <NEW_LINE> plot = None <NEW_LINE> num_ticks = 4 <NEW_LINE> margin, maxSize = 0.0, 1.0 <NEW_LINE> def __init__(self, parent, dates=None, values=None, name=None, width=3.2, height=2.4, dpi=100): <NEW_LINE> <INDENT> self.fig = Figure(figsize=(width, height), dpi=dpi) <NEW_LINE> FigureCanvas.__init__(self, self.fig) <NEW_LINE> self.setParent(parent) <NEW_LINE> FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) <NEW_LINE> FigureCanvas.updateGeometry(self) <NEW_LINE> bounds=[self.margin, self.margin, self.maxSize, self.maxSize] <NEW_LINE> self.plot=self.fig.add_axes(bounds) <NEW_LINE> self.setData(dates,values,name) <NEW_LINE> <DEDENT> def setData(self, dates, values,name=None): <NEW_LINE> <INDENT> if(dates==None or values==None or len(dates)!=len(values)): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.dates=dates <NEW_LINE> self.values=values <NEW_LINE> if(name!=None): <NEW_LINE> <INDENT> self.name=name <NEW_LINE> <DEDENT> if(self.plot!=None): <NEW_LINE> <INDENT> self.updatePlot() <NEW_LINE> <DEDENT> <DEDENT> def updatePlot(self): <NEW_LINE> <INDENT> if(self.plot==None or self.dates==None or self.values==None): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> ax=self.plot <NEW_LINE> ax.clear() <NEW_LINE> x=range(len(self.dates)) <NEW_LINE> ax.plot(x,self.values,'b-',label=self.name) <NEW_LINE> ax.set_xlim(x[0],x[-1]) <NEW_LINE> minVal=min(self.values) <NEW_LINE> maxVal=max(self.values) <NEW_LINE> ax.set_ylim(minVal-0.01*abs(minVal),maxVal+0.01*abs(maxVal)) <NEW_LINE> self.formatDateAxis(ax) <NEW_LINE> self.draw() <NEW_LINE> <DEDENT> def formatDateAxis(self,ax): <NEW_LINE> <INDENT> length=len(self.dates) <NEW_LINE> if(length>self.num_ticks): <NEW_LINE> <INDENT> step=length/self.num_ticks <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> step=1 <NEW_LINE> <DEDENT> x=range(0,length,step) <NEW_LINE> ax.xaxis.set_major_locator(FixedLocator(x)) <NEW_LINE> ticks=ax.get_xticks() <NEW_LINE> labels=[] <NEW_LINE> for i, label in enumerate(ax.get_xticklabels()): <NEW_LINE> <INDENT> label.set_size(5) <NEW_LINE> index=int(ticks[i]) <NEW_LINE> if(index>=len(self.dates)): <NEW_LINE> <INDENT> labels.append('') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> labels.append(self.dates[index]) <NEW_LINE> <DEDENT> label.set_horizontalalignment('center') <NEW_LINE> <DEDENT> ax.xaxis.set_major_formatter(FixedFormatter(labels)) <NEW_LINE> for label in ax.get_yticklabels(): <NEW_LINE> <INDENT> label.set_size(5)
|
Jest to klasa do wyświetlania "lekkich" wykresów, tzn. takich które będą na
głównej stronie i odnoszą się do rynku jako całości (indeksy, A/D line itd.)
Nie można po nich rysować, wyświetlać wolumenu, zmieniać skali etc. Ponadto
klasa ta nie korzysta z ChartData tylko rysuje na pałę zwykłą tablicę.
|
6259901ad18da76e235b7830
|
class Manuscript(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=20,verbose_name='稿件名') <NEW_LINE> createTime = models.DateField(verbose_name='发布日期') <NEW_LINE> issuer = models.CharField(max_length=10,verbose_name='发布人') <NEW_LINE> content = models.CharField(max_length=500,verbose_name='稿件文字内容') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'tb_manuscript' <NEW_LINE> verbose_name = '历史稿件' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name
|
历史稿件
|
6259901a9b70327d1c57fb47
|
class ValueTypeInt(ValueType): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def get_code(): <NEW_LINE> <INDENT> return VALUE_TYPE_CODE.INT <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def check_consistency(value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(value) <NEW_LINE> return True <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def recovery_process(value): <NEW_LINE> <INDENT> if ValueTypeInt.check_consistency(value): <NEW_LINE> <INDENT> return str(int(value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def create_edit_widget(value, style=None): <NEW_LINE> <INDENT> widget = LineEdit() <NEW_LINE> widget.setValidator(QRegExpValidator(QRegExp(r'[+\-\d][\d]+'))) <NEW_LINE> value = ValueTypeInt.recovery_process(value) <NEW_LINE> if value: <NEW_LINE> <INDENT> widget.setText(value) <NEW_LINE> <DEDENT> if style is not None: <NEW_LINE> <INDENT> font = QFont('Arial', VW_FONT_SIZE) <NEW_LINE> font.setBold(True) <NEW_LINE> widget.setFont(font) <NEW_LINE> <DEDENT> return widget <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_filled(widget): <NEW_LINE> <INDENT> return re.search(r'^[+\-\d]*[\d]+$', widget.text()) is not None <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_edit_widget_data(widget): <NEW_LINE> <INDENT> return ValueTypeInt.recovery_process(widget.text()) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def sort_subquery(query, subquery, direction): <NEW_LINE> <INDENT> if direction == 'ASC': <NEW_LINE> <INDENT> return sort_value_type_int_asc(query, subquery) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return sort_value_type_int_desc(query, subquery) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def is_recovery_accepted(code): <NEW_LINE> <INDENT> if code in [VALUE_TYPE_CODE.IMAGE]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
|
an int
|
6259901a925a0f43d25e8e09
|
class Evieext(AutotoolsPackage): <NEW_LINE> <INDENT> homepage = "http://cgit.freedesktop.org/xorg/proto/evieproto" <NEW_LINE> url = "https://www.x.org/archive/individual/proto/evieext-1.1.1.tar.gz" <NEW_LINE> version('1.1.1', '018a7d24d0c7926d594246320bcb6a86') <NEW_LINE> depends_on('pkg-config@0.9.0:', type='build') <NEW_LINE> depends_on('util-macros', type='build')
|
Extended Visual Information Extension (XEVIE).
This extension defines a protocol for a client to determine information
about core X visuals beyond what the core protocol provides.
|
6259901a507cdc57c63a5b69
|
class ParseError(BonesError): <NEW_LINE> <INDENT> def __init__(self, innerException, arg): <NEW_LINE> <INDENT> self.innerException = innerException <NEW_LINE> self.argument = arg
|
Error for when an automatic parse of an option fails.
|
6259901ad18da76e235b7831
|
class FontBrowseButton(wx.Panel): <NEW_LINE> <INDENT> def __init__(self, parent, font=None): <NEW_LINE> <INDENT> wx.Panel.__init__(self, parent, -1) <NEW_LINE> btn = wx.Button(self, -1, "Select Font") <NEW_LINE> self.Bind(wx.EVT_BUTTON, self.OnSelectFont, btn) <NEW_LINE> self.sampleText = wx.TextCtrl(self, -1, size=(150, -1), style=wx.TE_CENTRE) <NEW_LINE> self.sampleText.SetEditable(False) <NEW_LINE> self.sampleText.SetBackgroundColour(wx.WHITE) <NEW_LINE> if font is None: <NEW_LINE> <INDENT> self.curFont = self.sampleText.GetFont() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.curFont = font <NEW_LINE> <DEDENT> self.curClr = wx.BLACK <NEW_LINE> sizer = wx.BoxSizer(wx.HORIZONTAL) <NEW_LINE> sizer.Add(self.sampleText, 1, wx.EXPAND) <NEW_LINE> sizer.Add(btn, 0, wx.EXPAND) <NEW_LINE> self.SetSizer(sizer) <NEW_LINE> self.UpdateUI() <NEW_LINE> <DEDENT> def UpdateUI(self): <NEW_LINE> <INDENT> self.sampleText.SetFont(self.curFont) <NEW_LINE> self.sampleText.SetForegroundColour(self.curClr) <NEW_LINE> self.sampleText.SetValue("%s %s" % (self.curFont.GetFaceName(), self.curFont.GetPointSize())) <NEW_LINE> self.Layout() <NEW_LINE> <DEDENT> def OnSelectFont(self, evt): <NEW_LINE> <INDENT> data = wx.FontData() <NEW_LINE> data.EnableEffects(True) <NEW_LINE> data.SetColour(self.curClr) <NEW_LINE> data.SetInitialFont(self.curFont) <NEW_LINE> dlg = wx.FontDialog(self, data) <NEW_LINE> if dlg.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> data = dlg.GetFontData() <NEW_LINE> font = data.GetChosenFont() <NEW_LINE> colour = data.GetColour() <NEW_LINE> self.curFont = font <NEW_LINE> self.curClr = colour <NEW_LINE> self.UpdateUI() <NEW_LINE> <DEDENT> dlg.Destroy() <NEW_LINE> <DEDENT> def getFont(self): <NEW_LINE> <INDENT> return self.curFont <NEW_LINE> <DEDENT> def setFont(self, font): <NEW_LINE> <INDENT> if font is not None: <NEW_LINE> <INDENT> self.curFont = font <NEW_LINE> <DEDENT> self.UpdateUI()
|
Simple panel and button to choose and display a new font.
Borrowed from the wxPython demo.
|
6259901a796e427e5384f547
|
class TestLongerString(unittest.TestCase): <NEW_LINE> <INDENT> def test_string_1_is_string(self): <NEW_LINE> <INDENT> str1 = 2 <NEW_LINE> str2 = "Mammoth" <NEW_LINE> self.assertEqual(longer_word(str1, str2), "All inputs must be string") <NEW_LINE> <DEDENT> def test_string_2_is_string(self): <NEW_LINE> <INDENT> str1 = "Mammoth" <NEW_LINE> str2 = 456.36 <NEW_LINE> self.assertEqual(longer_word(str1, str2), "All inputs must be string") <NEW_LINE> <DEDENT> def test_for_equal_length_strings(self): <NEW_LINE> <INDENT> str1 = "Andela" <NEW_LINE> str2 = "Andela" <NEW_LINE> result = str1 + "\n" + str2 <NEW_LINE> self.assertEqual(longer_word(str1, str2), result) <NEW_LINE> <DEDENT> def test_for_longer_string_1(self): <NEW_LINE> <INDENT> str1 = "Thor" <NEW_LINE> str2 = "Iron Man" <NEW_LINE> self.assertEqual(longer_word(str1, str2), str2) <NEW_LINE> <DEDENT> def test_for_longer_string_2(self): <NEW_LINE> <INDENT> str1 = "My Feelings" <NEW_LINE> str2 = "Kiki Challenge" <NEW_LINE> self.assertEqual(longer_word(str1, str2), str2)
|
Class to test longer string function
|
6259901a0a366e3fb87dd7bd
|
class Tee: <NEW_LINE> <INDENT> def __init__(self, name, mode): <NEW_LINE> <INDENT> self.file_name = name <NEW_LINE> self.mode = mode <NEW_LINE> self.file = None <NEW_LINE> self.stdout = sys.stdout <NEW_LINE> self.stderr = sys.stderr <NEW_LINE> sys.stdout = self <NEW_LINE> sys.stderr = self <NEW_LINE> <DEDENT> def write(self, data): <NEW_LINE> <INDENT> self.file.write(data) <NEW_LINE> self.stdout.write(data) <NEW_LINE> <DEDENT> def flush(self): <NEW_LINE> <INDENT> self.file.flush() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.file = open(self.file_name, self.mode) <NEW_LINE> <DEDENT> def __exit__(self, _type, _value, _traceback): <NEW_LINE> <INDENT> sys.stdout = self.stdout <NEW_LINE> sys.stderr = self.stderr <NEW_LINE> self.file.close()
|
Class duplicating stdout and stderr to a specified log file and
|
6259901a287bf620b62729b1
|
class Dog(AnimalActions): <NEW_LINE> <INDENT> strings = dict( quack="The dog cannot quack.", feathers="The dog has no feathers.", bark="Arf!", fur="The dog has white fur with black spots." )
|
Class Dog to define properties of Dog
|
6259901ad18da76e235b7832
|
class DefinitionList: <NEW_LINE> <INDENT> __maxDefinitionPrefixLength = 24 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.__items = [] <NEW_LINE> <DEDENT> def add(self, name, definition): <NEW_LINE> <INDENT> if isinstance(definition, basestring): <NEW_LINE> <INDENT> definition = Paragraph(definition) <NEW_LINE> <DEDENT> if definition is None: <NEW_LINE> <INDENT> definition = EMPTY <NEW_LINE> <DEDENT> self.__items.append((name, definition)) <NEW_LINE> return self <NEW_LINE> <DEDENT> def _format(self, prefixLength): <NEW_LINE> <INDENT> definitionPrefixLength = 2 + max( itertools.chain( [prefixLength], ( len(prefixedName) for prefixedName, definition, shortEnough in self.__prefixedItems(prefixLength) if shortEnough ) ) ) <NEW_LINE> return itertools.chain.from_iterable( self.__formatItem(item, definitionPrefixLength) for item in self.__prefixedItems(prefixLength) ) <NEW_LINE> <DEDENT> def __prefixedItems(self, prefixLength): <NEW_LINE> <INDENT> for name, definition in self.__items: <NEW_LINE> <INDENT> prefixedName = prefixLength * " " + name <NEW_LINE> shortEnough = len(prefixedName) <= self.__maxDefinitionPrefixLength <NEW_LINE> yield prefixedName, definition, shortEnough <NEW_LINE> <DEDENT> <DEDENT> def __formatItem(self, item, definitionPrefixLength): <NEW_LINE> <INDENT> prefixedName, definition, shortEnough = item <NEW_LINE> subsequentIndent = definitionPrefixLength * " " <NEW_LINE> nameMustBeOnItsOwnLine = not shortEnough <NEW_LINE> if nameMustBeOnItsOwnLine: <NEW_LINE> <INDENT> yield prefixedName <NEW_LINE> initialIndent = subsequentIndent <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> initialIndent = prefixedName + (definitionPrefixLength - len(prefixedName)) * " " <NEW_LINE> <DEDENT> foo = True <NEW_LINE> for line in definition._format(definitionPrefixLength): <NEW_LINE> <INDENT> if foo: <NEW_LINE> <INDENT> foo = False <NEW_LINE> if not nameMustBeOnItsOwnLine: <NEW_LINE> <INDENT> line = prefixedName + line[len(prefixedName):] <NEW_LINE> <DEDENT> <DEDENT> yield line <NEW_LINE> <DEDENT> if foo: <NEW_LINE> <INDENT> yield prefixedName
|
A list of terms with their definitions.
>>> print Document().add(Section("Section title")
... .add(DefinitionList()
... .add("Item", Paragraph("Definition 1"))
... .add("Other item", Paragraph("Definition 2"))
... )
... ).format()
Section title
Item Definition 1
Other item Definition 2
|
6259901a0a366e3fb87dd7bf
|
class SocketListener(object): <NEW_LINE> <INDENT> def __init__(self, address, family, backlog=1): <NEW_LINE> <INDENT> self._socket = socket.socket(getattr(socket, family)) <NEW_LINE> try: <NEW_LINE> <INDENT> if os.name == 'posix': <NEW_LINE> <INDENT> self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> <DEDENT> self._socket.setblocking(True) <NEW_LINE> self._socket.bind(address) <NEW_LINE> self._socket.listen(backlog) <NEW_LINE> self._address = self._socket.getsockname() <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> self._socket.close() <NEW_LINE> raise <NEW_LINE> <DEDENT> self._family = family <NEW_LINE> self._last_accepted = None <NEW_LINE> if family == 'AF_UNIX': <NEW_LINE> <INDENT> self._unlink = Finalize( self, os.unlink, args=(address,), exitpriority=0 ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._unlink = None <NEW_LINE> <DEDENT> <DEDENT> def accept(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s, self._last_accepted = self._socket.accept() <NEW_LINE> <DEDENT> except InterruptedError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> s.setblocking(True) <NEW_LINE> return Connection(s.detach()) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._socket.close() <NEW_LINE> if self._unlink is not None: <NEW_LINE> <INDENT> self._unlink()
|
Representation of a socket which is bound to an address and listening
|
6259901a8c3a8732951f732c
|
class BaseModel(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> unique_together = ("slug", "version") <NEW_LINE> default_permissions = () <NEW_LINE> get_latest_by = "version" <NEW_LINE> <DEDENT> slug = ResolweSlugField(populate_from="name", unique_with="version", max_length=100) <NEW_LINE> version = VersionField(number_bits=VERSION_NUMBER_BITS, default="0.0.0") <NEW_LINE> name = models.CharField(max_length=100) <NEW_LINE> created = models.DateTimeField(auto_now_add=True, db_index=True) <NEW_LINE> modified = models.DateTimeField(auto_now=True, db_index=True) <NEW_LINE> contributor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> name_max_len = self._meta.get_field("name").max_length <NEW_LINE> if len(self.name) > name_max_len: <NEW_LINE> <INDENT> self.name = self.name[: (name_max_len - 3)] + "..." <NEW_LINE> <DEDENT> for _ in range(MAX_SLUG_RETRIES): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> super().save(*args, **kwargs) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> except IntegrityError as error: <NEW_LINE> <INDENT> if "{}_slug".format(self._meta.db_table) in error.args[0]: <NEW_LINE> <INDENT> self.slug = None <NEW_LINE> continue <NEW_LINE> <DEDENT> raise <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise IntegrityError( "Maximum number of retries exceeded during slug generation" )
|
Abstract model that includes common fields for other models.
|
6259901aa8ecb03325871fe8
|
class SummarizationPipeline: <NEW_LINE> <INDENT> def __init__(self, log_level: int = LOG_LEVEL): <NEW_LINE> <INDENT> logging.basicConfig( format='%(asctime)s %(name)s %(levelname)-8s %(message)s', level=log_level, datefmt='%d/%m/%Y %I:%M:%S %p' ) <NEW_LINE> self.logger = logging.getLogger("SummaryDAOPostgresql") <NEW_LINE> self.db = SummaryDAOSingleton() <NEW_LINE> self.text_preprocessor = TextPreprocessor() <NEW_LINE> self.encoder = SplitterEncoder() <NEW_LINE> self.summarizer = Summarizer() <NEW_LINE> self.text_postprocessor = TextPostprocessor() <NEW_LINE> <DEDENT> def run(self, request_id: str, summary: Summary): <NEW_LINE> <INDENT> preprocessed_text = self.text_preprocessor.preprocess(summary.source) <NEW_LINE> new_summary_id = generate_summary_id(preprocessed_text, summary.model, summary.params) <NEW_LINE> self.db.update_source(summary.source, preprocessed_text, summary.id_, new_summary_id) <NEW_LINE> self.db.update_summary(request_id, status=SummaryStatus.ENCODING.value) <NEW_LINE> encoded_text = self.encoder.encode(preprocessed_text) <NEW_LINE> self.db.update_summary(request_id, status=SummaryStatus.SUMMARIZING.value) <NEW_LINE> raw_summary = self.summarizer.summarize( encoded_text, **summary.params ) <NEW_LINE> self.db.update_summary(request_id, status=SummaryStatus.POSTPROCESSING.value) <NEW_LINE> summary = self.text_postprocessor.postprocess(raw_summary) <NEW_LINE> self.db.update_summary( request_id, status=SummaryStatus.COMPLETED.value, output=summary, output_length=len(summary), ended_at=datetime.now() )
|
Summarization pipeline.
This class takes care of the different summarization steps. It also updates
the summaries stored in the database.
Args:
#TODO
|
6259901a5e10d32532ce3fec
|
class CityDetailView(DetailView): <NEW_LINE> <INDENT> model = City <NEW_LINE> slug_field = "name" <NEW_LINE> slug_url_kwarg = "city"
|
Definitely read up on DetailView here:
http://ccbv.co.uk/projects/Django/1.5/django.views.generic.detail/DetailView/
This is similar to ListView (context_object_name and all that), but
here you also need a field to identify the object.
|
6259901a5166f23b2e24419d
|
class NewspaperEcransBrowser(BaseBrowser): <NEW_LINE> <INDENT> PAGES = { "http://www.ecrans.fr/.*": ArticlePage, } <NEW_LINE> def is_logged(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def login(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fillobj(self, obj, fields): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def get_content(self, _id): <NEW_LINE> <INDENT> self.location(_id) <NEW_LINE> return self.page.get_article(_id)
|
NewspaperEcransBrowser class
|
6259901ad164cc6175821d49
|
class NwsLocalServerException(Exception): <NEW_LINE> <INDENT> pass
|
Exception thrown if an error occurs while starting the local server.
|
6259901a462c4b4f79dbc7d5
|
class RoundRobinPartition(Partition): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__partitions = [-1] <NEW_LINE> self.seq = 0 <NEW_LINE> <DEDENT> def partition(self, key_record, num_partition: int): <NEW_LINE> <INDENT> self.seq = (self.seq + 1) % num_partition <NEW_LINE> self.__partitions[0] = self.seq <NEW_LINE> return self.__partitions
|
Partition record to downstream tasks in a round-robin matter.
|
6259901aa8ecb03325871fec
|
class LN_LSTMCell(tf.contrib.rnn.RNNCell): <NEW_LINE> <INDENT> def __init__(self, num_units, f_bias=1.0, use_zoneout=False, zoneout_keep_h = 0.9, zoneout_keep_c = 0.5, is_training = False): <NEW_LINE> <INDENT> super(LN_LSTMCell, self).__init__() <NEW_LINE> self.num_units = num_units <NEW_LINE> self.f_bias = f_bias <NEW_LINE> self.use_zoneout = use_zoneout <NEW_LINE> self.zoneout_keep_h = zoneout_keep_h <NEW_LINE> self.zoneout_keep_c = zoneout_keep_c <NEW_LINE> self.is_training = is_training <NEW_LINE> <DEDENT> def call(self, x, state): <NEW_LINE> <INDENT> with tf.variable_scope(type(self).__name__): <NEW_LINE> <INDENT> h, c = state <NEW_LINE> h_size = self.num_units <NEW_LINE> x_size = x.get_shape().as_list()[1] <NEW_LINE> w_init = aux.orthogonal_initializer(1.0) <NEW_LINE> h_init = aux.orthogonal_initializer(1.0) <NEW_LINE> b_init = tf.constant_initializer(0.0) <NEW_LINE> W_xh = tf.get_variable('W_xh', [x_size, 4 * h_size], initializer=w_init, dtype=tf.float32) <NEW_LINE> W_hh = tf.get_variable('W_hh', [h_size, 4 * h_size], initializer=h_init, dtype=tf.float32) <NEW_LINE> bias = tf.get_variable('bias', [4 * h_size], initializer=b_init, dtype=tf.float32) <NEW_LINE> concat = tf.concat(axis=1, values=[x, h]) <NEW_LINE> W_full = tf.concat(axis=0, values=[W_xh, W_hh]) <NEW_LINE> concat = tf.matmul(concat, W_full) + bias <NEW_LINE> concat = aux.layer_norm_all(concat, 4, h_size, 'ln') <NEW_LINE> i, j, f, o = tf.split(axis=1, num_or_size_splits=4, value=concat) <NEW_LINE> new_c = c * tf.sigmoid(f + self.f_bias) + tf.sigmoid(i) * tf.tanh(j) <NEW_LINE> new_h = tf.tanh(aux.layer_norm(new_c, 'ln_c')) * tf.sigmoid(o) <NEW_LINE> if self.use_zoneout: <NEW_LINE> <INDENT> new_h, new_c = aux.zoneout(new_h, new_c, h, c, self.zoneout_keep_h, self.zoneout_keep_c, self.is_training) <NEW_LINE> <DEDENT> <DEDENT> return new_h, (new_h, new_c) <NEW_LINE> <DEDENT> @property <NEW_LINE> def state_size(self): <NEW_LINE> <INDENT> return (self.num_units, self.num_units) <NEW_LINE> <DEDENT> @property <NEW_LINE> def output_size(self): <NEW_LINE> <INDENT> return (self.num_units, self.num_units) <NEW_LINE> <DEDENT> def zero_state(self, batch_size, dtype): <NEW_LINE> <INDENT> h = tf.zeros([batch_size, self.num_units], dtype=dtype) <NEW_LINE> c = tf.zeros([batch_size, self.num_units], dtype=dtype) <NEW_LINE> return (h, c)
|
Layer-Norm, with Ortho Initialization and Zoneout.
https://arxiv.org/abs/1607.06450 - Layer Norm
https://arxiv.org/abs/1606.01305 - Zoneout
derived from
https://github.com/OlavHN/bnlstm
https://github.com/LeavesBreathe/tensorflow_with_latest_papers
https://github.com/hardmaru/supercell
|
6259901a6fece00bbaccc785
|
class Flatten(ZooKerasLayer): <NEW_LINE> <INDENT> def __init__(self, input_shape=None, **kwargs): <NEW_LINE> <INDENT> super(Flatten, self).__init__(None, list(input_shape) if input_shape else None, **kwargs)
|
Flattens the input without affecting the batch size.
When you use this layer as the first layer of a model, you need to provide the argument
input_shape (a shape tuple, does not include the batch dimension).
# Arguments
input_shape: A shape tuple, not including batch.
name: String to set the name of the layer.
If not specified, its name will by default to be a generated string.
>>> flatten = Flatten(input_shape=(3, 10, 2))
creating: createZooKerasFlatten
|
6259901a9b70327d1c57fb51
|
class Architecture(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def _spawn(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def train(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def test(self): <NEW_LINE> <INDENT> pass
|
Abstract class for distributed architectures
|
6259901ad164cc6175821d4f
|
class Wrapper(object): <NEW_LINE> <INDENT> BASE_ATTRS = ('id', 'name') <NEW_LINE> __metaclass__ = abc.ABCMeta <NEW_LINE> @abc.abstractmethod <NEW_LINE> def __init__(self, wrapped, parent=None, gi=None): <NEW_LINE> <INDENT> if not isinstance(wrapped, collections.Mapping): <NEW_LINE> <INDENT> raise TypeError('wrapped object must be a mapping type') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> dumped = json.dumps(wrapped) <NEW_LINE> <DEDENT> except (TypeError, ValueError): <NEW_LINE> <INDENT> raise ValueError('wrapped object must be JSON-serializable') <NEW_LINE> <DEDENT> object.__setattr__(self, 'wrapped', json.loads(dumped)) <NEW_LINE> for k in self.BASE_ATTRS: <NEW_LINE> <INDENT> object.__setattr__(self, k, self.wrapped.get(k)) <NEW_LINE> <DEDENT> object.__setattr__(self, '_cached_parent', parent) <NEW_LINE> object.__setattr__(self, 'is_modified', False) <NEW_LINE> object.__setattr__(self, 'gi', gi) <NEW_LINE> <DEDENT> @abc.abstractproperty <NEW_LINE> def gi_module(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def parent(self): <NEW_LINE> <INDENT> return self._cached_parent <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_mapped(self): <NEW_LINE> <INDENT> return self.id is not None <NEW_LINE> <DEDENT> def unmap(self): <NEW_LINE> <INDENT> object.__setattr__(self, 'id', None) <NEW_LINE> <DEDENT> def clone(self): <NEW_LINE> <INDENT> return self.__class__(self.wrapped) <NEW_LINE> <DEDENT> def touch(self): <NEW_LINE> <INDENT> object.__setattr__(self, 'is_modified', True) <NEW_LINE> if self.parent: <NEW_LINE> <INDENT> self.parent.touch() <NEW_LINE> <DEDENT> <DEDENT> def to_json(self): <NEW_LINE> <INDENT> return json.dumps(self.wrapped) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_json(cls, jdef): <NEW_LINE> <INDENT> return cls(json.loads(jdef)) <NEW_LINE> <DEDENT> def __setattr__(self, name, value): <NEW_LINE> <INDENT> if name not in self.wrapped: <NEW_LINE> <INDENT> raise AttributeError("can't set attribute") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.wrapped[name] = value <NEW_LINE> object.__setattr__(self, name, value) <NEW_LINE> self.touch() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "%s(%r)" % (self.__class__.__name__, self.wrapped)
|
Abstract base class for Galaxy entity wrappers.
Wrapper instances wrap deserialized JSON dictionaries such as the
ones obtained by the Galaxy web API, converting key-based access to
attribute-based access (e.g., ``library['name'] -> library.name``).
Dict keys that are converted to attributes are listed in the
``BASE_ATTRS`` class variable: this is the 'stable' interface.
Note that the wrapped dictionary is accessible via the ``wrapped``
attribute.
|
6259901a462c4b4f79dbc7db
|
class GlobalConfiguration(object): <NEW_LINE> <INDENT> def __init__(self, process, pidfile="", globalTimeout=300, loglevel=10): <NEW_LINE> <INDENT> self.globalTimeout = globalTimeout <NEW_LINE> logging.basicConfig(level=loglevel) <NEW_LINE> self.globalLoglevel = loglevel <NEW_LINE> self.processes = process['username'] <NEW_LINE> <DEDENT> def getProcesses(self): <NEW_LINE> <INDENT> return self.processes <NEW_LINE> <DEDENT> def getGlobalTimeout(self): <NEW_LINE> <INDENT> return self.globalTimeout
|
classdocs
|
6259901a0a366e3fb87dd7c7
|
class uart(object): <NEW_LINE> <INDENT> SOT = '{' <NEW_LINE> EOT = '}' <NEW_LINE> CR = '\r' <NEW_LINE> LF = '\n' <NEW_LINE> CRLF = CR+LF <NEW_LINE> def __init__(self, port, baudrate): <NEW_LINE> <INDENT> self.interface = serial.Serial(baudrate=baudrate) <NEW_LINE> self.interface.port = port <NEW_LINE> self.isOpen = False <NEW_LINE> self.logger = logger.logger("uart") <NEW_LINE> <DEDENT> def open(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.interface.open() <NEW_LINE> <DEDENT> except serial.SerialException as e: <NEW_LINE> <INDENT> if str(e) != "Port is already open.": <NEW_LINE> <INDENT> self.logger.log.error("error in uart.open: {}".format(e)) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> self.logger.log.debug("Successfully opened serial interface port: {}". format(self.interface.port)) <NEW_LINE> self.isOpen = True <NEW_LINE> return True <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.interface.close() <NEW_LINE> self.isOpen = False <NEW_LINE> self.logger.log.debug("Successfully closed serial port: {}". format(self.interface.port)) <NEW_LINE> <DEDENT> def readUntil(self, seq): <NEW_LINE> <INDENT> run = True <NEW_LINE> data = "" <NEW_LINE> if type(seq) is list: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif type(seq) is str: <NEW_LINE> <INDENT> seq = [seq] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.log.error("seq parameter is of an invalid type: {}". format(type(seq))) <NEW_LINE> <DEDENT> while run: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data += self.interface.read() <NEW_LINE> for item in seq: <NEW_LINE> <INDENT> if data.endswith(item): <NEW_LINE> <INDENT> run = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> run = False <NEW_LINE> self.logger.log.error(e) <NEW_LINE> return "" <NEW_LINE> <DEDENT> <DEDENT> self.logger.log.debug("Successfully read serial data: {}". format(data)) <NEW_LINE> return data <NEW_LINE> <DEDENT> def sendRaw(self, *data): <NEW_LINE> <INDENT> byteString = "".join(common.flatten(data)) <NEW_LINE> try: <NEW_LINE> <INDENT> bytesWritten = self.interface.write(byteString) <NEW_LINE> self.interface.flush() <NEW_LINE> if byteString and bytesWritten: <NEW_LINE> <INDENT> self.logger.log.debug("Successfully wrote serial data: {}". format(byteString)) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.log.error("Did not write serial data: {}". format(byteString)) <NEW_LINE> return False <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.logger.log.error("Got exception: {}". format(e)) <NEW_LINE> self.logger.log.error("Did not write serial data: {}". format(byteString)) <NEW_LINE> return False
|
Abstracts some basic uart functionality from the pyserial module
|
6259901a5166f23b2e2441a5
|
class JSON(Parser): <NEW_LINE> <INDENT> _alias_ = 'json' <NEW_LINE> _version_ = '1.0' <NEW_LINE> def parse(self): <NEW_LINE> <INDENT> return 'json'
|
Dummy JSON parser
|
6259901ad18da76e235b7837
|
class Button(base.Peripherial): <NEW_LINE> <INDENT> def update_state(self): <NEW_LINE> <INDENT> pass
|
We're not supporting external button on linux.
Feel free to implement Your peripherials here.
|
6259901a462c4b4f79dbc7dd
|
class FakeSecurityGroup(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def create_one_security_group(attrs={}, methods={}): <NEW_LINE> <INDENT> security_group_attrs = { 'id': 'security-group-id-' + uuid.uuid4().hex, 'name': 'security-group-name-' + uuid.uuid4().hex, 'description': 'security-group-description-' + uuid.uuid4().hex, 'tenant_id': 'project-id-' + uuid.uuid4().hex, 'security_group_rules': [], } <NEW_LINE> security_group_attrs.update(attrs) <NEW_LINE> security_group_methods = {} <NEW_LINE> security_group_methods.update(methods) <NEW_LINE> security_group = fakes.FakeResource( info=copy.deepcopy(security_group_attrs), methods=copy.deepcopy(security_group_methods), loaded=True) <NEW_LINE> return security_group <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_security_groups(attrs={}, methods={}, count=2): <NEW_LINE> <INDENT> security_groups = [] <NEW_LINE> for i in range(0, count): <NEW_LINE> <INDENT> security_groups.append( FakeSecurityGroup.create_one_security_group(attrs, methods)) <NEW_LINE> <DEDENT> return security_groups
|
Fake one or more security groups.
|
6259901a6fece00bbaccc789
|
class ReportTests(TestCase): <NEW_LINE> <INDENT> fixtures = ['admin_user.json', 'forum_example.json'] <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> self.client = logIn() <NEW_LINE> <DEDENT> def test_report_thread(self): <NEW_LINE> <INDENT> response = self.client.post( reverse( 'forum.views.report', kwargs={'object_id': test_thread_id, 'object_type': 'thread'}), {'title': test_text, 'content': test_text, 'submit': 'submit'}, follow=True) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def test_report_post(self): <NEW_LINE> <INDENT> response = self.client.post( reverse( 'forum.views.report', kwargs={'object_id': test_post_id, 'object_type': 'post'}), {'title': test_text, 'content': test_text, 'submit': 'submit'}, follow=True) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> <DEDENT> def test_get(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('forum.views.reports')) <NEW_LINE> self.assertEqual(response.status_code, 200)
|
Tests operations related to reports.
|
6259901a796e427e5384f553
|
@export <NEW_LINE> class RandomZoom(RandomTransform): <NEW_LINE> <INDENT> def __init__( self, pad: bool = True, min_factor: float = 0.25, max_factor: float = 1.25 ) -> None: <NEW_LINE> <INDENT> super().__init__( transform=Zoom(pad=pad), min_factor=min_factor, max_factor=max_factor )
|
Callable class for randomly zooming, in and out, images and bounding boxes.
Parameters
----------
pad
min_factor
max_factor
|
6259901a56b00c62f0fb3692
|
class TeamModelAdminTest(case.DBTestCase): <NEW_LINE> <INDENT> @property <NEW_LINE> def admin(self): <NEW_LINE> <INDENT> from moztrap.model.mtadmin import TeamModelAdmin <NEW_LINE> return TeamModelAdmin <NEW_LINE> <DEDENT> def test_fieldsets(self): <NEW_LINE> <INDENT> ma = self.admin(self.model.ProductVersion, AdminSite()) <NEW_LINE> fs = ma.get_fieldsets(None, None) <NEW_LINE> self.assertEqual(len(fs), 4) <NEW_LINE> default, team, deletion, meta = fs <NEW_LINE> self.assertNotIn("has_team", default[1]["fields"]) <NEW_LINE> self.assertNotIn("own_team", default[1]["fields"]) <NEW_LINE> self.assertEqual(team[0], "Team") <NEW_LINE> self.assertEqual(team[1]["fields"], [("has_team", "own_team")])
|
Tests of TeamModelAdmin.
|
6259901b5166f23b2e2441a7
|
class ManualInGame(): <NEW_LINE> <INDENT> def __init__( self, surfaceDest, rectManual, tutorialScheduler, fontManual=fontConsole ): <NEW_LINE> <INDENT> self.surfaceDest = surfaceDest <NEW_LINE> self.rectManual = rectManual <NEW_LINE> self.tutorialScheduler = tutorialScheduler <NEW_LINE> self.fontManual = fontManual <NEW_LINE> self.imgManual = pygame.Surface(self.rectManual.size).convert() <NEW_LINE> <DEDENT> def refresh(self): <NEW_LINE> <INDENT> manualTexts = list(language.MANUAL_TEXTS[language.languageCurrent]) <NEW_LINE> self.imgManual.fill((0, 0, 0)) <NEW_LINE> pygame.draw.rect(self.imgManual, COLOR_DEFAULT, pyRect(0, 0, 340, 127), 2) <NEW_LINE> colorToWrite = COLOR_DEFAULT <NEW_LINE> textToWrite = manualTexts.pop(0) <NEW_LINE> imgText = self.fontManual.render(textToWrite, 0, colorToWrite) <NEW_LINE> self.imgManual.blit(imgText, pyRect(10, 5)) <NEW_LINE> textToWrite = manualTexts.pop(0) <NEW_LINE> imgText = self.fontManual.render(textToWrite, 0, colorToWrite) <NEW_LINE> self.imgManual.blit(imgText, pyRect(10, 25)) <NEW_LINE> textToWrite = manualTexts.pop(0) <NEW_LINE> imgText = self.fontManual.render(textToWrite, 0, colorToWrite) <NEW_LINE> self.imgManual.blit(imgText, pyRect(10, 45)) <NEW_LINE> if self.tutorialScheduler is not None: <NEW_LINE> <INDENT> textToWrite = manualTexts.pop(0) <NEW_LINE> imgText = self.fontManual.render(textToWrite, 0, colorToWrite) <NEW_LINE> self.imgManual.blit(imgText, pyRect(10, 85)) <NEW_LINE> textToWrite = manualTexts.pop(0) <NEW_LINE> imgText = self.fontManual.render(textToWrite, 0, colorToWrite) <NEW_LINE> self.imgManual.blit(imgText, pyRect(10, 100)) <NEW_LINE> <DEDENT> <DEDENT> def display(self): <NEW_LINE> <INDENT> self.surfaceDest.blit(self.imgManual, self.rectManual)
|
classe qui affiche le manuel du jeu pendant le jeu.
(Ça affiche la liste des touche)
type MVC : osef.
|
6259901b507cdc57c63a5b77
|
class SyncStepDetailInfo(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.StepNo = None <NEW_LINE> self.StepName = None <NEW_LINE> self.CanStop = None <NEW_LINE> self.StepId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.StepNo = params.get("StepNo") <NEW_LINE> self.StepName = params.get("StepName") <NEW_LINE> self.CanStop = params.get("CanStop") <NEW_LINE> self.StepId = params.get("StepId")
|
Sync task progress
|
6259901b91af0d3eaad3abfa
|
class UnknownColumnException(Exception): <NEW_LINE> <INDENT> def __init__(self, message: str, errors: dict, cls: Base, column: str, *args): <NEW_LINE> <INDENT> super().__init__(message, *args) <NEW_LINE> self.__errors = errors <NEW_LINE> self.__cls = cls <NEW_LINE> self.__column = column <NEW_LINE> <DEDENT> @property <NEW_LINE> def errors(self) -> dict: <NEW_LINE> <INDENT> return self.__errors <NEW_LINE> <DEDENT> @property <NEW_LINE> def cls(self) -> Base: <NEW_LINE> <INDENT> return self.__cls <NEW_LINE> <DEDENT> @property <NEW_LINE> def column(self) -> str: <NEW_LINE> <INDENT> return self.__column
|
Exception for Repo Objects: Unknown Column
|
6259901b63f4b57ef008645d
|
@ddt <NEW_LINE> class TestMainPageBuyerBanners(HelpNavigateCheckMethods, HelpNavigateData, HelpAuthCheckMethods): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUp(cls): <NEW_LINE> <INDENT> default_user_id = AccountingMethods.get_default_user_id(role='buyer') <NEW_LINE> cls.user = databases.db1.accounting.get_user_by_account_id(default_user_id)[0] <NEW_LINE> AccountingMethods.save_user_password(user_id=cls.user["id"], hash_passwd=cls.user["code_value"]) <NEW_LINE> cls.driver = HelpLifeCycleMethods.get_driver() <NEW_LINE> service_log.preparing_env(cls) <NEW_LINE> default_new_passwd = AccountingMethods.get_default_password() <NEW_LINE> hash_res_new = generate_sha256(default_new_passwd, cls.user["salt"]) <NEW_LINE> databases.db1.accounting.update_user_password(cls.user["id"], hash_res_new) <NEW_LINE> cls.go_main(cls.driver, phone=cls.user["phone"], passwd=default_new_passwd, flag_auth=True) <NEW_LINE> <DEDENT> @skip('deprecated') <NEW_LINE> @priority('low') <NEW_LINE> @data(*HelpNavigateData.SUITE_MAIN_BANNER_V) <NEW_LINE> def test_check_banner_main(self, test_data): <NEW_LINE> <INDENT> service_log.run(self) <NEW_LINE> test_data["second_click"] = HelpNavigateData.click_main.MAIN_BANNER <NEW_LINE> self.check_navigate_two_click(self.driver, test_data) <NEW_LINE> <DEDENT> @skip('deprecated') <NEW_LINE> @priority('low') <NEW_LINE> @data(*HelpNavigateData.SUITE_MAIN_BANNER_RIGHT_B) <NEW_LINE> def test_check_banner_right(self, test_data): <NEW_LINE> <INDENT> service_log.run(self) <NEW_LINE> self.check_navigate(self.driver, test_data) <NEW_LINE> <DEDENT> @skip('deprecated') <NEW_LINE> @priority('low') <NEW_LINE> @data(*HelpNavigateData.SUITE_MAIN_BANNER_WIDTH) <NEW_LINE> def test_check_banner_width(self, test_data): <NEW_LINE> <INDENT> service_log.run(self) <NEW_LINE> self.check_navigate(self.driver, test_data) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDown(cls): <NEW_LINE> <INDENT> AccountingMethods.recover_user_password(databases.db1) <NEW_LINE> cls.driver.quit() <NEW_LINE> service_log.end()
|
Story: Баннер на главной странице для покупателя
|
6259901b462c4b4f79dbc7e1
|
class Station(Producer): <NEW_LINE> <INDENT> key_schema = avro.load(f"{Path(__file__).parents[0]}/schemas/arrival_key.json") <NEW_LINE> value_schema = avro.load(f"{Path(__file__).parents[0]}/schemas/arrival_value.json") <NEW_LINE> def __init__(self, station_id, name, color, direction_a=None, direction_b=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> topic_name = f"com.udacity.cta.station.arrivals" <NEW_LINE> super().__init__( topic_name, key_schema=Station.key_schema, value_schema=Station.value_schema, num_partitions=1, num_replicas=1, ) <NEW_LINE> self.station_id = int(station_id) <NEW_LINE> self.color = color <NEW_LINE> self.dir_a = direction_a <NEW_LINE> self.dir_b = direction_b <NEW_LINE> self.a_train = None <NEW_LINE> self.b_train = None <NEW_LINE> self.turnstile = Turnstile(self) <NEW_LINE> <DEDENT> def run(self, train, direction, prev_station_id, prev_direction): <NEW_LINE> <INDENT> self.producer.produce( topic=self.topic_name, key={ "timestamp": self.time_millis() }, value={ "station_id": self.station_id, "train_id": train.train_id, "direction": direction, "line": self.color.name, "train_status": train.status.name, "prev_station_id": prev_station_id, "prev_direction": prev_direction } ) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Station | {:^5} | {:<30} | Direction A: | {:^5} | departing" " to {:<30} | Direction B: | {:^5} | departing to {:<30} | " .format( self.station_id, self.name, self.a_train.train_id if self.a_train is not None else "---", self.dir_a.name if self.dir_a is not None else "---", self.b_train.train_id if self.b_train is not None else "---", self.dir_b.name if self.dir_b is not None else "---", ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str(self) <NEW_LINE> <DEDENT> def arrive_a(self, train, prev_station_id, prev_direction): <NEW_LINE> <INDENT> self.a_train = train <NEW_LINE> self.run(train, "a", prev_station_id, prev_direction) <NEW_LINE> <DEDENT> def arrive_b(self, train, prev_station_id, prev_direction): <NEW_LINE> <INDENT> self.b_train = train <NEW_LINE> self.run(train, "b", prev_station_id, prev_direction) <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.turnstile.close() <NEW_LINE> super(Station, self).close()
|
Defines a single station
|
6259901b0a366e3fb87dd7cd
|
class Side(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.units = [] <NEW_LINE> self.other = None <NEW_LINE> self.name = name <NEW_LINE> self.has_king = False <NEW_LINE> self.rallied = 0 <NEW_LINE> self.influenced = False <NEW_LINE> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self.__init__(self.name) <NEW_LINE> <DEDENT> def get_units(self): <NEW_LINE> <INDENT> return self.units[:] <NEW_LINE> <DEDENT> def rally(self): <NEW_LINE> <INDENT> self.rallied = 5 <NEW_LINE> <DEDENT> def get_rallied(self): <NEW_LINE> <INDENT> return self.rallied > 0 <NEW_LINE> <DEDENT> def influence(self): <NEW_LINE> <INDENT> self.influenced = True <NEW_LINE> <DEDENT> def get_influenced(self): <NEW_LINE> <INDENT> return self.influenced <NEW_LINE> <DEDENT> def king_alive(self): <NEW_LINE> <INDENT> return self.has_king <NEW_LINE> <DEDENT> def get_num_units(self): <NEW_LINE> <INDENT> return len(self.units) <NEW_LINE> <DEDENT> def add_opponent(self, other): <NEW_LINE> <INDENT> self.other = other <NEW_LINE> <DEDENT> def get_opponent(self): <NEW_LINE> <INDENT> return self.other <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def add_unit(self, unit): <NEW_LINE> <INDENT> self.units.append(unit) <NEW_LINE> if type(unit) == King: <NEW_LINE> <INDENT> self.has_king = True <NEW_LINE> <DEDENT> <DEDENT> def remove_unit(self, unit): <NEW_LINE> <INDENT> self.units.remove(unit) <NEW_LINE> if type(unit) == King: <NEW_LINE> <INDENT> self.has_king = False <NEW_LINE> <DEDENT> <DEDENT> def tick(self): <NEW_LINE> <INDENT> if self.rallied > 0: <NEW_LINE> <INDENT> self.rallied -= 1 <NEW_LINE> <DEDENT> self.influenced = False <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name.lower()
|
Represents an individual side/army (typically white and black).
|
6259901b6fece00bbaccc78d
|
class RegisterForm(ExtendedForm): <NEW_LINE> <INDENT> login = TextField(_('Username'), [validators.Required(), validators.Length(min=4, max=25)]) <NEW_LINE> password = PasswordField(_('Password'), [validators.Required(), validators.EqualTo('password2', message=_('Passwords must match'))]) <NEW_LINE> password2 = PasswordField(_('Repeat Password'), [validators.Required()]) <NEW_LINE> email = TextField(_('Email Address'), [validators.Required(), validators.Email()]) <NEW_LINE> def validate_login(form, field): <NEW_LINE> <INDENT> if AuthUser.get_by_login(field.data) is not None: <NEW_LINE> <INDENT> raise validators.ValidationError( _('Sorry that username already exists.')) <NEW_LINE> <DEDENT> <DEDENT> def create_user(self, login): <NEW_LINE> <INDENT> group = self.request.registry.settings.get('apex.default_user_group', None) <NEW_LINE> user = apex.lib.libapex.create_user(username=login, password=self.data['password'], email=self.data['email'], group=group) <NEW_LINE> return user <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> new_user = self.create_user(self.data['login']) <NEW_LINE> self.after_signup(user=new_user) <NEW_LINE> return new_user <NEW_LINE> <DEDENT> def after_signup(self, **kwargs): <NEW_LINE> <INDENT> pass
|
Registration Form
|
6259901b9b70327d1c57fb58
|
class GameStats(): <NEW_LINE> <INDENT> def __init__(self, ai_settings): <NEW_LINE> <INDENT> self.ai_settings = ai_settings <NEW_LINE> self.reset_stats() <NEW_LINE> self.game_active = False <NEW_LINE> self.high_score = 0 <NEW_LINE> <DEDENT> def reset_stats(self): <NEW_LINE> <INDENT> self.ship_left = self.ai_settings.ship_limit <NEW_LINE> self.score = 0 <NEW_LINE> self.level = 1
|
Track game info
|
6259901b796e427e5384f557
|
class NamedChainReadWriter(ReadWriter): <NEW_LINE> <INDENT> __slots__ = ('_pairs',) <NEW_LINE> def __init__(self, pairs): <NEW_LINE> <INDENT> assert pairs is not None <NEW_LINE> self._pairs = pairs <NEW_LINE> <DEDENT> def read(self, stream): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for name, rw in self._pairs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = rw.read(stream) <NEW_LINE> if name != skip: <NEW_LINE> <INDENT> result[name] = value <NEW_LINE> <DEDENT> <DEDENT> except ReadException as e: <NEW_LINE> <INDENT> raise ReadException( "Failed to read %s: %s" % (name, e.message) ) <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def write(self, obj, stream): <NEW_LINE> <INDENT> for name, rw in self._pairs: <NEW_LINE> <INDENT> if name != skip: <NEW_LINE> <INDENT> rw.write(obj[name], stream) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rw.write(None, stream) <NEW_LINE> <DEDENT> <DEDENT> return stream <NEW_LINE> <DEDENT> def width(self): <NEW_LINE> <INDENT> return sum(rw.width() for _, rw in self._pairs)
|
See :py:func:`dictionary` for documentation.
|
6259901b6fece00bbaccc78f
|
class FileTestRunner(object): <NEW_LINE> <INDENT> default_command = ['python'] <NEW_LINE> def __init__(self, file_filter, test_mapper, command=None): <NEW_LINE> <INDENT> self.file_filter = file_filter <NEW_LINE> self.test_mapper = test_mapper <NEW_LINE> self.command = command or self.default_command <NEW_LINE> <DEDENT> def run(self, filename): <NEW_LINE> <INDENT> if not self.file_filter.should_test(filename): <NEW_LINE> <INDENT> log.info("Ignoring not testable file: %s", filename) <NEW_LINE> return <NEW_LINE> <DEDENT> log.info("Running test for source file: %s", filename) <NEW_LINE> test_filename = self.test_mapper.get_test_filename(filename) <NEW_LINE> if not os.path.isfile(test_filename): <NEW_LINE> <INDENT> log.warn("Missing test for %s. Expected at %s", filename, test_filename) <NEW_LINE> return <NEW_LINE> <DEDENT> test_name = self.get_test_name(test_filename) <NEW_LINE> self.run_test(test_name) <NEW_LINE> <DEDENT> def run_test(self, test_name): <NEW_LINE> <INDENT> log.info("Running test: %s", self.command + [test_name]) <NEW_LINE> subprocess.call(self.command + [test_name]) <NEW_LINE> <DEDENT> def get_test_name(self, filename): <NEW_LINE> <INDENT> return filename
|
A test runner which runs a test file using `command`.
|
6259901b287bf620b62729c2
|
class RegistryRealbasic(unittest.TestCase): <NEW_LINE> <INDENT> def test_registry_has_zero_len_after_reset(self,): <NEW_LINE> <INDENT> registry.reset() <NEW_LINE> self.assertEqual(registry.size(),0) <NEW_LINE> <DEDENT> def test_registry_hasnt_get_an_added_job_after_reset(self,): <NEW_LINE> <INDENT> registry.add_target("name",None) <NEW_LINE> registry.reset() <NEW_LINE> self.assertFalse(registry.has_target("name"))
|
Test the basic reset and len functions
this testcase test the functions used to
ensure the main tests are truley independent.
If these fail the RegistryTests TestCase is unreliable
|
6259901b507cdc57c63a5b7d
|
class Status(RequestHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> n_orders = list(self.db.view("order", "status", reduce=True))[0].value <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> n_orders = 0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> n_forms = list(self.db.view("form", "all", reduce=True))[0].value <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> n_forms = 0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> n_accounts = list(self.db.view("account", "all", reduce=True))[0].value <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> n_accounts = 0 <NEW_LINE> <DEDENT> self.write(dict(status="OK", n_orders=n_orders, n_forms=n_forms, n_accounts=n_accounts))
|
Return JSON for the current status and some counts for the database.
|
6259901bd164cc6175821d59
|
class Provider: <NEW_LINE> <INDENT> def __init__(self, provider_id, cloud_prop): <NEW_LINE> <INDENT> self.provider_id = provider_id <NEW_LINE> self._provider_key = self.get_provider_key(cloud_prop) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not other or not isinstance(other, Provider): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self._provider_key == other._provider_key <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> if not other or not isinstance(other, Provider): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self._provider_key != other._provider_key <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(("cloudbase.Provider", self._provider_key)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_provider_key(cls, cloud_prop): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def init_instance(self, cloud_prop): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def assign_ip(self, props): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def get_instance_status(self, prop): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def terminate_instances(self, props): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def wait_instances(self, props, wait_state="running"): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def create_snapshot(self, props, name=None, description=None, memory=False): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def revert_to_snapshot(self, props, name=None): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def remove_snapshot(self, props, name): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def power_off_instances(self, props): <NEW_LINE> <INDENT> assert 0, "implement in sub-class" <NEW_LINE> <DEDENT> def power_on_instances(self, props): <NEW_LINE> <INDENT> assert 0, "implement in sub-class"
|
Abstract base-class for cloud-specific cloud provider logic
|
6259901b91af0d3eaad3abfe
|
class ReservedWordError(SexpError): <NEW_LINE> <INDENT> pass
|
Identifier is a reserved word.
ReservedWordError('None', sexp, idx)
|
6259901bd18da76e235b783b
|
class UserErrorHandler: <NEW_LINE> <INDENT> type = 'error' <NEW_LINE> def __init__(self, name, error): <NEW_LINE> <INDENT> self.name = self.longname = name <NEW_LINE> self.doc = self.shortdoc = '' <NEW_LINE> self._error = error <NEW_LINE> self.timeout = '' <NEW_LINE> <DEDENT> def init_keyword(self, varz): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def run(self, *args): <NEW_LINE> <INDENT> raise DataError(self._error)
|
Created if creating handlers fail -- running raises DataError.
The idea is not to raise DataError at processing time and prevent all
tests in affected test case file from executing. Instead UserErrorHandler
is created and if it is ever run DataError is raised then.
|
6259901b56b00c62f0fb369a
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.