code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class token_case_in_range_bounded_by_tokens(rules.token_case): <NEW_LINE> <INDENT> def __init__(self, name, identifier, lTokens, oStart, oEnd): <NEW_LINE> <INDENT> rules.token_case.__init__(self, name=name, identifier=identifier, lTokens=lTokens) <NEW_LINE> self.oStart = oStart <NEW_LINE> self.oEnd = oEnd <NEW_LINE> <DEDENT> def _get_tokens_of_interest(self, oFile): <NEW_LINE> <INDENT> return oFile.get_tokens_matching_in_range_bounded_by_tokens(self.lTokens, self.oStart, self.oEnd) | Checks the case for words.
Parameters
----------
name : string
The group the rule belongs to.
identifier : string
unique identifier. Usually in the form of 00N.
lTokens : list of token types
oStart : token type
oEnd : token type | 62598fa0a79ad16197769e93 |
class Meta: <NEW_LINE> <INDENT> verbose_name_plural = _(messages.PLURAL_SCAN_TASKS_MSG) | Metadata for model. | 62598fa0a8370b77170f0213 |
class UnderscoreToPascalCaseTest(unittest2.TestCase): <NEW_LINE> <INDENT> def testEmpty(self): <NEW_LINE> <INDENT> self.assertEqual( util.underscore_to_pascalcase(None), None) <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase(''), '') <NEW_LINE> <DEDENT> def testUnderscores(self): <NEW_LINE> <INDENT> self.assertEqual( util.underscore_to_pascalcase('ab'), 'Ab') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('aB'), 'Ab') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('AB'), 'Ab') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('a_b'), 'AB') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('A_b'), 'AB') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('aa_bb'), 'AaBb') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('aa1_bb2'), 'Aa1Bb2') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('1aa_2bb'), '1aa2bb') <NEW_LINE> <DEDENT> def testWhitespace(self): <NEW_LINE> <INDENT> self.assertEqual( util.underscore_to_pascalcase(' '), ' ') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase(' a'), ' a') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('a '), 'A ') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase(' a '), ' a ') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('a b'), 'A b') <NEW_LINE> self.assertEqual( util.underscore_to_pascalcase('a b'), 'A b') | Behavioral tests of the underscore_to_pascalcase method. | 62598fa08e7ae83300ee8ecf |
class EntryDemo(Frame): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Frame.__init__(self) <NEW_LINE> self.pack(expand="yes", fill="both") <NEW_LINE> self.master.title("Testing entry component") <NEW_LINE> self.master.geometry("350x100") <NEW_LINE> self.frame1 = Frame(self) <NEW_LINE> self.frame1.pack(pady=5) <NEW_LINE> self.text1 = Entry(self.frame1, name="text1") <NEW_LINE> self.text1.bind("<Return>", self.showContents) <NEW_LINE> self.text1.pack(side="left", padx=5) <NEW_LINE> self.text2 = Entry(self.frame1, name="text2") <NEW_LINE> self.text2.insert(INSERT, "Enter text here") <NEW_LINE> self.text2.bind("<Return>", self.showContents) <NEW_LINE> self.text2.pack(side="left", padx=5) <NEW_LINE> self.frame2 = Frame(self) <NEW_LINE> self.frame2.pack(pady=5) <NEW_LINE> self.text3 = Entry(self.frame2, name="text3") <NEW_LINE> self.text3.insert(INSERT, "Uneditable text field") <NEW_LINE> self.text3.config(state=DISABLED) <NEW_LINE> self.text3.bind("<Return>", self.showContents) <NEW_LINE> self.text3.pack(side=LEFT, padx=5) <NEW_LINE> self.text4 = Entry(self.frame2, name="text4", show="*") <NEW_LINE> self.text4.insert(INSERT, "Hidden text") <NEW_LINE> self.text4.bind("<Return>", self.showContents) <NEW_LINE> self.text4.pack(side=LEFT, padx=5) <NEW_LINE> <DEDENT> def showContents(self, event): <NEW_LINE> <INDENT> theName = event.widget.winfo_name() <NEW_LINE> theContents = event.widget.get() <NEW_LINE> showinfo("Message", theName + ": " + theContents) | Demonstrate Entrys and Event binding | 62598fa0fbf16365ca793ee9 |
class SecondaryColorAttribute(AbstractAttribute): <NEW_LINE> <INDENT> plural = 'secondary_colors' <NEW_LINE> _fixed_count = 3 <NEW_LINE> def __init__(self, gl_type): <NEW_LINE> <INDENT> super().__init__(3, gl_type) <NEW_LINE> <DEDENT> def enable(self): <NEW_LINE> <INDENT> glEnableClientState(GL_SECONDARY_COLOR_ARRAY) <NEW_LINE> <DEDENT> def set_pointer(self, pointer): <NEW_LINE> <INDENT> glSecondaryColorPointer(3, self.gl_type, self.stride, self.offset + pointer) | Secondary color attribute. | 62598fa03eb6a72ae038a472 |
class RoleDefinerTests(IdentityRequest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.public_tenant = Tenant.objects.get(tenant_name="public") <NEW_LINE> <DEDENT> def test_role_create(self): <NEW_LINE> <INDENT> self.try_seed_roles() <NEW_LINE> roles = Role.objects.filter(platform_default=True) <NEW_LINE> self.assertTrue(len(roles)) <NEW_LINE> self.assertFalse(Role.objects.get(name="RBAC Administrator Local Test").platform_default) <NEW_LINE> <DEDENT> def test_role_update(self): <NEW_LINE> <INDENT> self.try_seed_roles() <NEW_LINE> Role.objects.all().delete() <NEW_LINE> roles = Role.objects.filter(platform_default=True) <NEW_LINE> self.assertFalse(len(roles)) <NEW_LINE> seed_roles(self.public_tenant) <NEW_LINE> roles = Role.objects.filter(platform_default=True) <NEW_LINE> self.assertTrue(len(roles)) <NEW_LINE> for access in Access.objects.all(): <NEW_LINE> <INDENT> self.assertEqual(access.tenant, self.public_tenant) <NEW_LINE> for rd in ResourceDefinition.objects.filter(access=access): <NEW_LINE> <INDENT> self.assertEqual(rd.tenant, self.public_tenant) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_role_update_version_diff(self): <NEW_LINE> <INDENT> self.try_seed_roles() <NEW_LINE> roles = Role.objects.filter(platform_default=True).update(version=0, platform_default=False) <NEW_LINE> self.assertFalse(len(Role.objects.filter(platform_default=True))) <NEW_LINE> seed_roles(self.public_tenant) <NEW_LINE> roles = Role.objects.filter(platform_default=True) <NEW_LINE> self.assertTrue(len(roles)) <NEW_LINE> <DEDENT> def try_seed_roles(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> seed_roles(self.public_tenant) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.fail(msg="seed_roles encountered an exception") <NEW_LINE> <DEDENT> <DEDENT> def test_try_seed_permissions(self): <NEW_LINE> <INDENT> self.assertFalse(len(Permission.objects.all())) <NEW_LINE> try: <NEW_LINE> <INDENT> seed_permissions(self.public_tenant) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.fail(msg="seed_permissions encountered an exception") <NEW_LINE> <DEDENT> self.assertTrue(len(Permission.objects.all())) <NEW_LINE> permission = Permission.objects.first() <NEW_LINE> self.assertTrue(permission.application) <NEW_LINE> self.assertTrue(permission.resource_type) <NEW_LINE> self.assertTrue(permission.verb) <NEW_LINE> self.assertTrue(permission.permission) <NEW_LINE> self.assertEqual(permission.tenant, self.public_tenant) <NEW_LINE> <DEDENT> def test_try_seed_permissions_update_description(self): <NEW_LINE> <INDENT> permission_string = "approval_local_test:templates:read" <NEW_LINE> self.assertFalse(len(Permission.objects.all())) <NEW_LINE> Permission.objects.create(permission=permission_string, tenant=self.public_tenant) <NEW_LINE> try: <NEW_LINE> <INDENT> seed_permissions(self.public_tenant) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.fail(msg="seed_permissions encountered an exception") <NEW_LINE> <DEDENT> self.assertEqual( Permission.objects.exclude(permission=permission_string).values_list("description").distinct().first(), ("",), ) <NEW_LINE> permission = Permission.objects.filter(permission=permission_string) <NEW_LINE> self.assertEqual(len(permission), 1) <NEW_LINE> self.assertEqual(permission.first().description, "Approval local test templates read.") <NEW_LINE> self.assertEqual(Permission.objects.filter(permission="catalog_local_test:approval_requests:read").count(), 1) | Test the role definer functions. | 62598fa0097d151d1a2c0e58 |
class HomeView(View): <NEW_LINE> <INDENT> def get(self, request): <NEW_LINE> <INDENT> photo_list = Photo.objects.filter(visibility=VISIBILITY_PUBLIC).order_by("-created_at")[:3] <NEW_LINE> context = { "photos": photo_list } <NEW_LINE> return render(request, "main.html", context) | Pagina de inicio | 62598fa0d7e4931a7ef3bec8 |
class RunProjectsLocationsDomainmappingsListRequest(_messages.Message): <NEW_LINE> <INDENT> continue_ = _messages.StringField(1) <NEW_LINE> fieldSelector = _messages.StringField(2) <NEW_LINE> includeUninitialized = _messages.BooleanField(3) <NEW_LINE> labelSelector = _messages.StringField(4) <NEW_LINE> limit = _messages.IntegerField(5, variant=_messages.Variant.INT32) <NEW_LINE> parent = _messages.StringField(6, required=True) <NEW_LINE> resourceVersion = _messages.StringField(7) <NEW_LINE> watch = _messages.BooleanField(8) | A RunProjectsLocationsDomainmappingsListRequest object.
Fields:
continue_: Optional encoded string to continue paging.
fieldSelector: Allows to filter resources based on a specific value for a
field name. Send this in a query string format. i.e.
'metadata.name%3Dlorem'. Not currently used by Cloud Run.
includeUninitialized: Not currently used by Cloud Run.
labelSelector: Allows to filter resources based on a label. Supported
operations are =, !=, exists, in, and notIn.
limit: The maximum number of records that should be returned.
parent: The project ID or project number from which the domain mappings
should be listed.
resourceVersion: The baseline resource version from which the list or
watch operation should start. Not currently used by Cloud Run.
watch: Flag that indicates that the client expects to watch this resource
as well. Not currently used by Cloud Run. | 62598fa0097d151d1a2c0e59 |
class HypervisorSshAttachAction(AttachAction): <NEW_LINE> <INDENT> baseclass() <NEW_LINE> @db.ro_transact <NEW_LINE> def _do_connection(self, size): <NEW_LINE> <INDENT> self.write("Attaching to %s. Use ^] to force exit.\n" % self.name) <NEW_LINE> phy = self.context.__parent__.__parent__.__parent__.__parent__ <NEW_LINE> ssh_connect_interactive_shell('root', phy.hostname, 22, self.transport, self._set_channel, size, self.command) | For consoles that are attached by running a command on the hypervisor host. | 62598fa091af0d3eaad39c3b |
class RangeSelectionsOverlay(RangeSelectionOverlay): <NEW_LINE> <INDENT> def _get_selection_screencoords(self): <NEW_LINE> <INDENT> ds = getattr(self.plot, self.axis) <NEW_LINE> selection = ds.metadata[self.metadata_name] <NEW_LINE> if selection is None or len(selection) == 1: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> elif len(selection)%2 != 0: <NEW_LINE> <INDENT> del selection[-1] <NEW_LINE> <DEDENT> if self.metadata_name == "selections": <NEW_LINE> <INDENT> coords = [] <NEW_LINE> for index in range(len(selection)/2): <NEW_LINE> <INDENT> interval = (selection[index*2],selection[index*2+1]) <NEW_LINE> coords.append(self.mapper.map_screen(array(interval))) <NEW_LINE> <DEDENT> return coords <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> selection_points = len(selection) <NEW_LINE> coords = [] <NEW_LINE> if len(ds._data) == selection_points: <NEW_LINE> <INDENT> selected = nonzero(selection)[0] <NEW_LINE> runs = arg_find_runs(selected) <NEW_LINE> for run in runs: <NEW_LINE> <INDENT> start = ds._data[selected[run[0]]] <NEW_LINE> end = ds._data[selected[run[1]-1]] <NEW_LINE> coords.append(self.mapper.map_screen(array((start, end)))) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> for index in range(len(selection)/2): <NEW_LINE> <INDENT> interval = (selection[index*2],selection[index*2+1]) <NEW_LINE> coords.append(self.mapper.map_screen(array(interval))) <NEW_LINE> <DEDENT> <DEDENT> return coords | Highlights the selected regions on a component.
Looks at a given metadata field of self.component for regions to draw as
selected. Re-implements the __get_selection_screencoords() method for a faster,
more efficient regions selection. | 62598fa04527f215b58e9d13 |
class PlottableData2D(Plottable): <NEW_LINE> <INDENT> def __init__(self, image=None, qx_data=None, qy_data=None, err_image=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None): <NEW_LINE> <INDENT> Plottable.__init__(self) <NEW_LINE> self.name = "Data2D" <NEW_LINE> self.label = None <NEW_LINE> self.data = image <NEW_LINE> self.qx_data = qx_data <NEW_LINE> self.qy_data = qx_data <NEW_LINE> self.err_data = err_image <NEW_LINE> self.source = None <NEW_LINE> self.detector = [] <NEW_LINE> self.xy_unit = 'A^{-1}' <NEW_LINE> self.z_unit = 'cm^{-1}' <NEW_LINE> self._zaxis = '' <NEW_LINE> self._xaxis = '\\rm{Q_{x}}' <NEW_LINE> self._xunit = 'A^{-1}' <NEW_LINE> self._yaxis = '\\rm{Q_{y}}' <NEW_LINE> self._yunit = 'A^{-1}' <NEW_LINE> self.x_bins = [] <NEW_LINE> self.y_bins = [] <NEW_LINE> self.xmin = xmin <NEW_LINE> self.xmax = xmax <NEW_LINE> self.ymin = ymin <NEW_LINE> self.ymax = ymax <NEW_LINE> self.zmin = zmin <NEW_LINE> self.zmax = zmax <NEW_LINE> self.id = None <NEW_LINE> <DEDENT> def xaxis(self, label, unit): <NEW_LINE> <INDENT> self._xaxis = label <NEW_LINE> self._xunit = unit <NEW_LINE> <DEDENT> def yaxis(self, label, unit): <NEW_LINE> <INDENT> self._yaxis = label <NEW_LINE> self._yunit = unit <NEW_LINE> <DEDENT> def zaxis(self, label, unit): <NEW_LINE> <INDENT> self._zaxis = label <NEW_LINE> self._zunit = unit <NEW_LINE> <DEDENT> def setValues(self, datainfo=None): <NEW_LINE> <INDENT> self.image = copy.deepcopy(datainfo.data) <NEW_LINE> self.qx_data = copy.deepcopy(datainfo.qx_data) <NEW_LINE> self.qy_data = copy.deepcopy(datainfo.qy_data) <NEW_LINE> self.err_image = copy.deepcopy(datainfo.err_data) <NEW_LINE> self.xy_unit = datainfo.Q_unit <NEW_LINE> self.z_unit = datainfo.I_unit <NEW_LINE> self._zaxis = datainfo._zaxis <NEW_LINE> self.xaxis(datainfo._xunit, datainfo._xaxis) <NEW_LINE> self.yaxis(datainfo._yunit, datainfo._yaxis) <NEW_LINE> self.xmin = datainfo.xmin <NEW_LINE> self.xmax = datainfo.xmax <NEW_LINE> self.ymin = datainfo.ymin <NEW_LINE> self.ymax = datainfo.ymax <NEW_LINE> self.x_bins = datainfo.x_bins <NEW_LINE> self.y_bins = datainfo.y_bins <NEW_LINE> <DEDENT> def set_zrange(self, zmin=None, zmax=None): <NEW_LINE> <INDENT> if zmin < zmax: <NEW_LINE> <INDENT> self.zmin = zmin <NEW_LINE> self.zmax = zmax <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise "zmin is greater or equal to zmax " <NEW_LINE> <DEDENT> <DEDENT> def render(self, plot, **kw): <NEW_LINE> <INDENT> plot.image(self.data, self.qx_data, self.qy_data, self.xmin, self.xmax, self.ymin, self.ymax, self.zmin, self.zmax, **kw) <NEW_LINE> <DEDENT> def changed(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def labels(cls, collection): <NEW_LINE> <INDENT> label_dict = {} <NEW_LINE> for item in collection: <NEW_LINE> <INDENT> if item.label == "Data2D": <NEW_LINE> <INDENT> item.label = item.name <NEW_LINE> <DEDENT> label_dict[item] = item.label <NEW_LINE> <DEDENT> return label_dict | 2D data class for image plotting | 62598fa05f7d997b871f92f7 |
class Input(_io): <NEW_LINE> <INDENT> dir='in' <NEW_LINE> def __init__(self, **cfg): <NEW_LINE> <INDENT> super().__init__(**cfg) <NEW_LINE> self.on_data_reply = cfg.get('on', self.on_data) <NEW_LINE> self.off_data_reply = cfg.get('off', self.off_data) <NEW_LINE> <DEDENT> async def run(self, amqp, chip, started: anyio.abc.Event = None): <NEW_LINE> <INDENT> async with amqp.new_channel() as chan: <NEW_LINE> <INDENT> await chan.exchange_declare(self.exch, self.exch_type) <NEW_LINE> if self.queue: <NEW_LINE> <INDENT> res = await chan.queue_declare(queue_name=self.queue, durable=True, exclusive=True, auto_delete=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = await chan.queue_declare(queue_name=self.queue, durable=False, exclusive=True, auto_delete=True) <NEW_LINE> self.queue = res.queue_name <NEW_LINE> <DEDENT> logger.debug("Bind %s %s %s", self.queue,self.exch,self.route) <NEW_LINE> await chan.queue_bind(self.queue, self.exch, routing_key=self.route) <NEW_LINE> pin = chip.line(self.pin) <NEW_LINE> async with chan.new_consumer(self.queue) as listener: <NEW_LINE> <INDENT> with pin.open(direction=gpio.DIRECTION_OUTPUT) as line: <NEW_LINE> <INDENT> if started is not None: <NEW_LINE> <INDENT> await started.set() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> async for body, envelope, properties in listener: <NEW_LINE> <INDENT> self.handle_msg(body, envelope, properties, line) <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> pin.value = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> async def handle_msg(self, body, envelope, properties, line): <NEW_LINE> <INDENT> data = data.decode("utf-8") <NEW_LINE> if self.json_path is not None: <NEW_LINE> <INDENT> data = json_decode(data) <NEW_LINE> for p in self.json_path: <NEW_LINE> <INDENT> data = data[p] <NEW_LINE> <DEDENT> <DEDENT> if data == self.on_data: <NEW_LINE> <INDENT> print("on") <NEW_LINE> <DEDENT> elif data == self.off_data: <NEW_LINE> <INDENT> print("off") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.warn("%s: unknown data %s", self.exch,line.value) | Represesent an Input pin: react whenever a specific AMQP message arrives. | 62598fa056ac1b37e630201a |
class PredictPurchaseInputSchema(Schema): <NEW_LINE> <INDENT> age = fields.Int(required = True) <NEW_LINE> salary = fields.Int(required = True) | Parameters:
- age (int)
- salary (int) | 62598fa0498bea3a75a57951 |
class WallAnt(Ant): <NEW_LINE> <INDENT> name = "Wall" <NEW_LINE> implemented = True <NEW_LINE> food_cost = 4 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> Ant.__init__(self, 4) | The WallAnt sits there and blocks things using its large armor value. | 62598fa056ac1b37e630201b |
class AzureResourceReference(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'source_arm_resource_id': {'required': True}, } <NEW_LINE> _attribute_map = { 'source_arm_resource_id': {'key': 'sourceArmResourceId', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(AzureResourceReference, self).__init__(**kwargs) <NEW_LINE> self.source_arm_resource_id = kwargs['source_arm_resource_id'] | Defines reference to an Azure resource.
All required parameters must be populated in order to send to Azure.
:param source_arm_resource_id: Required. Gets the ARM resource ID of the tracked resource being
referenced.
:type source_arm_resource_id: str | 62598fa0b7558d589546345d |
class Blog(BloggerEntry): <NEW_LINE> <INDENT> pass | Represents a blog which belongs to the user. | 62598fa0435de62698e9bc23 |
class TaskAddCollectionParameter(Model): <NEW_LINE> <INDENT> _validation = { 'value': {'required': True, 'max_items': 100}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[TaskAddParameter]'}, } <NEW_LINE> def __init__(self, value): <NEW_LINE> <INDENT> super(TaskAddCollectionParameter, self).__init__() <NEW_LINE> self.value = value | A collection of Azure Batch tasks to add.
:param value: The collection of tasks to add. The total serialized size of
this collection must be less than 4MB. If it is greater than 4MB (for
example if each task has 100's of resource files or environment
variables), the request will fail with code 'RequestBodyTooLarge' and
should be retried again with fewer tasks.
:type value: list[~azure.batch.models.TaskAddParameter] | 62598fa02ae34c7f260aaf10 |
class DEEP(Market): <NEW_LINE> <INDENT> @property <NEW_LINE> def url(self): <NEW_LINE> <INDENT> return "deep" <NEW_LINE> <DEDENT> def _convert_output(self, out): <NEW_LINE> <INDENT> return out <NEW_LINE> <DEDENT> @property <NEW_LINE> def symbol_required(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @property <NEW_LINE> def symbol_limit(self): <NEW_LINE> <INDENT> return 1 | Class to retrieve DEEP order book data
Real-time depth of book quotations direct from IEX. Returns aggregated
size of resting displayed orders at a price and side. Does not indicate
the size or number of individual orders at any price level. Non-displayed
orders and non-displayed portions of reserve orders are not counted.
Also provides last trade price and size information. Routed executions
are not reported.
Reference
---------
https://iextrading.com/developer/docs/#DEEP | 62598fa01b99ca400228f446 |
class MemoryStorage(object): <NEW_LINE> <INDENT> __slots__ = ('_memory', '_lock') <NEW_LINE> def __init__(self, *, m_process=False): <NEW_LINE> <INDENT> super(MemoryStorage, self).__init__() <NEW_LINE> self._memory = dict() <NEW_LINE> self._lock = threading.Lock() if not m_process else multiprocessing.Lock() <NEW_LINE> <DEDENT> def insert(self, key, value, override=False): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if key not in self._memory or override: <NEW_LINE> <INDENT> self._memory[key] = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('{key} has existed'.format(key=key)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def remove(self, key): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if key in self._memory: <NEW_LINE> <INDENT> self._memory.pop(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise KeyError('{key} not in {self}'.format(key=key, self=self.__class__.__name__)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def get(self, key, default=None): <NEW_LINE> <INDENT> return self._memory.get(key, default=default) <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self._memory.__getitem__(item) <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> return self._memory.__setitem__(key, value) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return len(self._memory) <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return self._memory.keys() <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return self._memory.values() <NEW_LINE> <DEDENT> def items(self): <NEW_LINE> <INDENT> return self._memory.items() <NEW_LINE> <DEDENT> def checkpoint(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def set_auto_commit(self, auto: bool): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self._memory.clear() | Store key-value pairs just in memory. | 62598fa08e71fb1e983bb8e7 |
class IGalleryRight(interface.Interface): <NEW_LINE> <INDENT> pass | Marker interface for the gallery right viewlet
| 62598fa07d43ff248742731a |
class DocumentIdentifierResolver(utopia.citation.Resolver): <NEW_LINE> <INDENT> def _unidentifiedDocumentRef(self, document): <NEW_LINE> <INDENT> evidence = [kend.model.Evidence(type='fingerprint', data=f, srctype='document') for f in document.fingerprints()] <NEW_LINE> return kend.model.DocumentReference(evidence=evidence) <NEW_LINE> <DEDENT> def _identifyDocumentRef(self, documentref): <NEW_LINE> <INDENT> id = getattr(documentref, 'id', None) <NEW_LINE> if id is None: <NEW_LINE> <INDENT> documentref = kend.client.Client().documents(documentref) <NEW_LINE> id = getattr(documentref, 'id', None) <NEW_LINE> <DEDENT> return id <NEW_LINE> <DEDENT> def _resolveDocumentId(self, document): <NEW_LINE> <INDENT> documentref = self._unidentifiedDocumentRef(document) <NEW_LINE> return self._identifyDocumentRef(documentref) <NEW_LINE> <DEDENT> def resolve(self, citations, document = None): <NEW_LINE> <INDENT> if document is not None: <NEW_LINE> <INDENT> utopia_id = utopia.citation.pick_from(citations, 'identifiers[utopia]', None) <NEW_LINE> if utopia_id is None: <NEW_LINE> <INDENT> utopia_id = utopia.tools.utils.metadata(document, 'identifiers[utopia]') <NEW_LINE> if utopia_id is None: <NEW_LINE> <INDENT> utopia_id = self._resolveDocumentId(document) <NEW_LINE> return {'identifiers': {'utopia': utopia_id}} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def provenance(self): <NEW_LINE> <INDENT> return {'whence': 'kend'} <NEW_LINE> <DEDENT> def purposes(self): <NEW_LINE> <INDENT> return 'identify' <NEW_LINE> <DEDENT> def weight(self): <NEW_LINE> <INDENT> return -10000 | Resolve a Utopia URI for this document. | 62598fa021a7993f00c65db4 |
class Donation(BaseModel): <NEW_LINE> <INDENT> gift_id = UUIDField(primary_key=True) <NEW_LINE> gift_num = SmallIntegerField() <NEW_LINE> value = FloatField() <NEW_LINE> donated_by = ForeignKeyField(Donor, null=False) | Schema definition | 62598fa0e5267d203ee6b73e |
class TestValidators(STCAdminTest): <NEW_LINE> <INDENT> def test_alphanumeric(self): <NEW_LINE> <INDENT> Validators.alphanumeric("a") <NEW_LINE> Validators.alphanumeric("1") <NEW_LINE> Validators.alphanumeric(" ") <NEW_LINE> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.alphanumeric("!") <NEW_LINE> <DEDENT> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.alphanumeric("~") <NEW_LINE> <DEDENT> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.alphanumeric("&") <NEW_LINE> <DEDENT> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.alphanumeric("0.5") <NEW_LINE> <DEDENT> <DEDENT> def test_numeric(self): <NEW_LINE> <INDENT> Validators.numeric("1") <NEW_LINE> Validators.numeric("25") <NEW_LINE> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.numeric("!") <NEW_LINE> <DEDENT> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.numeric("0.5") <NEW_LINE> <DEDENT> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.numeric(" ") <NEW_LINE> <DEDENT> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.numeric("a") <NEW_LINE> <DEDENT> <DEDENT> def test_allow_character(self): <NEW_LINE> <INDENT> Validators.allow_characters("HelloWorld", []) <NEW_LINE> Validators.allow_characters("Hello World", []) <NEW_LINE> Validators.allow_characters("Hello World 2", []) <NEW_LINE> Validators.allow_characters("Hello, World!", [",", "!"]) <NEW_LINE> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.allow_characters("Hello, World!", []) <NEW_LINE> <DEDENT> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.allow_characters("Hello World 2.5", []) <NEW_LINE> <DEDENT> <DEDENT> def test_disallow_characters(self): <NEW_LINE> <INDENT> Validators.disallow_characters("Helloworld", []) <NEW_LINE> Validators.disallow_characters("Hello world", []) <NEW_LINE> Validators.disallow_characters("Helloworld ~", []) <NEW_LINE> Validators.disallow_characters("Helloworld", ["~"]) <NEW_LINE> Validators.disallow_characters("2", ["~"]) <NEW_LINE> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> Validators.disallow_characters("Helloworld ~", ["~"]) <NEW_LINE> Validators.disallow_characters("2.5", ["."]) | Tests for Product Editor form validators. | 62598fa0ac7a0e7691f7233c |
class VaultRecord(models.Model): <NEW_LINE> <INDENT> vault = models.ForeignKey(Vault, related_name='records') <NEW_LINE> year = models.IntegerField(default=0) <NEW_LINE> month = models.IntegerField(default=0) <NEW_LINE> count = models.IntegerField(default=0) <NEW_LINE> @staticmethod <NEW_LINE> def update(vault, count): <NEW_LINE> <INDENT> dt = datetime.now() <NEW_LINE> affected = VaultRecord.objects.filter(vault=vault, year=dt.year, month=dt.month ).update(count=F('count') + 1) <NEW_LINE> if affected == 0: <NEW_LINE> <INDENT> VaultRecord(vault=vault, year=dt.year, month=dt.month, count=count).save() <NEW_LINE> <DEDENT> <DEDENT> class Meta: <NEW_LINE> <INDENT> app_label = 'codewiki' | Records a counter against a pages scraped. This could be extended to also log
API calls should that be necessary/ | 62598fa0d6c5a102081e1f77 |
class ComponentViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = models.Component.objects.all() <NEW_LINE> permission_classes = (permissions.IsAuthenticatedOrReadOnly,) <NEW_LINE> serializer_class = serializers.ComponentSerializer | API view for Component. | 62598fa03eb6a72ae038a474 |
class _Expr(object): <NEW_LINE> <INDENT> __metaclass__ = abc.ABCMeta <NEW_LINE> def __init__(self, backend): <NEW_LINE> <INDENT> self.backend = backend <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def Evaluate(self, obj): <NEW_LINE> <INDENT> pass | Expression base class. | 62598fa00a50d4780f70520b |
@registry.register_symbol_modality("ctc") <NEW_LINE> class CTCSymbolModality(SymbolModality): <NEW_LINE> <INDENT> def loss(self, logits, targets): <NEW_LINE> <INDENT> with tf.name_scope("ctc_loss", values=[logits, targets]): <NEW_LINE> <INDENT> targets_shape = targets.get_shape().as_list() <NEW_LINE> assert len(targets_shape) == 4 <NEW_LINE> assert targets_shape[2] == 1 <NEW_LINE> assert targets_shape[3] == 1 <NEW_LINE> targets = tf.squeeze(targets, axis=[2, 3]) <NEW_LINE> logits = tf.squeeze(logits, axis=[2, 3]) <NEW_LINE> targets_mask = 1 - tf.to_int32(tf.equal(targets, 0)) <NEW_LINE> targets_lengths = tf.reduce_sum(targets_mask, axis=1) <NEW_LINE> sparse_targets = tf.keras.backend.ctc_label_dense_to_sparse( targets, targets_lengths) <NEW_LINE> xent = tf.nn.ctc_loss( sparse_targets, logits, targets_lengths, time_major=False, preprocess_collapse_repeated=False, ctc_merge_repeated=False) <NEW_LINE> weights = self.targets_weights_fn(targets) <NEW_LINE> return tf.reduce_sum(xent), tf.reduce_sum(weights) | SymbolModality that uses CTC loss. | 62598fa067a9b606de545dfb |
class SensorParameter(Concept): <NEW_LINE> <INDENT> class Meta : <NEW_LINE> <INDENT> verbose_name="Sensed Parameter" <NEW_LINE> verbose_name_plural="Sensed Parameters" | A sensor parameter is measured by a sensor type.
This may be referenced by either an "observation procedure" or an "observed property". Parameters may be organised into generalisation hierarchies. Uses unadorned SKOS model, but may be extended later, for example to define UoM, precision etc. | 62598fa057b8e32f52508035 |
class FBCameraViewPlaneMode (object): <NEW_LINE> <INDENT> kFBViewPlaneDisabled=property(doc="Camera plane disabled. ") <NEW_LINE> kFBViewPlaneAlways=property(doc="Always draw camera plane. ") <NEW_LINE> kFBViewPlaneWhenMedia=property(doc="Camera plane when media. ") <NEW_LINE> pass | Camera plane viewing modes.
| 62598fa05f7d997b871f92f8 |
class ResolweAPI(slumber.API): <NEW_LINE> <INDENT> resource_class = ResolweResource | Use custom ResolweResource resource class in slumber's API. | 62598fa024f1403a926857cb |
class TestNewList(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_saving_a_POST_request(self): <NEW_LINE> <INDENT> lis = List.objects.create() <NEW_LINE> self.client.post('/lists/new',data={'item_text': 'A new list item'}) <NEW_LINE> self.assertEqual(Item.objects.count(),1) <NEW_LINE> new_item = Item.objects.first() <NEW_LINE> self.assertEqual(new_item.text,'A new list item') <NEW_LINE> <DEDENT> def test_redirect_after_post(self): <NEW_LINE> <INDENT> response = self.client.post('/lists/new',data={'item_text': 'A new list item'}) <NEW_LINE> new_list = List.objects.first() <NEW_LINE> self.assertRedirects(response,'/lists/%d/'%(new_list.id)) | Test case docstring. | 62598fa060cbc95b0636417f |
class EmailBackend(ModelBackend): <NEW_LINE> <INDENT> def authenticate(self, username=None, password=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user = User.objects.get(email=username) <NEW_LINE> <DEDENT> except User.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if user.check_password(password): <NEW_LINE> <INDENT> return user | Authentication backend that uses users' email as the main
id. | 62598fa0cb5e8a47e493c08e |
@dataclass <NEW_LINE> class BaseOrder: <NEW_LINE> <INDENT> def __post_init__(self): <NEW_LINE> <INDENT> self.validate() <NEW_LINE> <DEDENT> def json(self): <NEW_LINE> <INDENT> order_dict = self._filter() <NEW_LINE> return json.dumps(order_dict, cls=EnhancedJSONEncoder) <NEW_LINE> <DEDENT> def asdict(self): <NEW_LINE> <INDENT> clean_order_dict = json.loads(self.json()) <NEW_LINE> return clean_order_dict <NEW_LINE> <DEDENT> def _filter(self): <NEW_LINE> <INDENT> order_dict = asdict(self, dict_factory=self._filtered_dict_factory) <NEW_LINE> return order_dict <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _filtered_dict_factory(list_of_tuples): <NEW_LINE> <INDENT> filtered_dict = { key: value for key, value in list_of_tuples if value is not None } <NEW_LINE> return dict(filtered_dict) <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> error_list = self.check_for_errors() <NEW_LINE> if len(error_list) > 0: <NEW_LINE> <INDENT> raise OrderValidationError(error_list) <NEW_LINE> <DEDENT> <DEDENT> def check_for_errors(self): <NEW_LINE> <INDENT> validation_errors = [] <NEW_LINE> try: <NEW_LINE> <INDENT> annotations = self.__annotations__ <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return validation_errors <NEW_LINE> <DEDENT> if annotations: <NEW_LINE> <INDENT> for label, label_type in annotations.items(): <NEW_LINE> <INDENT> value = self.__dict__.get(label) <NEW_LINE> try: <NEW_LINE> <INDENT> if value is not None and not isinstance(value, label_type): <NEW_LINE> <INDENT> message = f"{value} is not valid value for {label}" <NEW_LINE> validation_errors.append(message) <NEW_LINE> <DEDENT> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> print(value, label_type) <NEW_LINE> raise err <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return validation_errors | Base Order dataclass
https://docs.python.org/3/library/dataclasses.html
https://stackoverflow.com/questions/12118695/efficient-way-to-remove-keys-with-empty-strings-from-a-dict | 62598fa06aa9bd52df0d4cfc |
class NgramDict(TextScore): <NEW_LINE> <INDENT> def __init__(self, ngramfile, sep=' '): <NEW_LINE> <INDENT> self.ngrams = {} <NEW_LINE> for line in file(ngramfile): <NEW_LINE> <INDENT> key,count = line.split(sep) <NEW_LINE> self.ngrams[key] = int(count) <NEW_LINE> <DEDENT> self.ngramLen = len(key) <NEW_LINE> self.all = sum(self.ngrams.itervalues()) <NEW_LINE> for key in self.ngrams.keys(): <NEW_LINE> <INDENT> self.ngrams[key] = log10(float(self.ngrams[key]) / self.all) <NEW_LINE> <DEDENT> self.floor = log10(0.01 / self.all) <NEW_LINE> <DEDENT> def score(self,text): <NEW_LINE> <INDENT> score = 0 <NEW_LINE> ngrams = self.ngrams.__getitem__ <NEW_LINE> text = text.replace(" ","") <NEW_LINE> for i in xrange(len(text) - self.ngramLen + 1): <NEW_LINE> <INDENT> chunk = text[i:i+self.ngramLen].upper() <NEW_LINE> if chunk in self.ngrams: <NEW_LINE> <INDENT> score += ngrams(chunk) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> score += self.floor <NEW_LINE> <DEDENT> <DEDENT> return score / (len(text) - self.ngramLen + 1) | use ngrams to score the text | 62598fa056ac1b37e630201c |
class TableCellStyle: <NEW_LINE> <INDENT> def __init__(self, obj=None): <NEW_LINE> <INDENT> if obj: <NEW_LINE> <INDENT> self.rborder = obj.rborder <NEW_LINE> self.lborder = obj.lborder <NEW_LINE> self.tborder = obj.tborder <NEW_LINE> self.bborder = obj.bborder <NEW_LINE> self.padding = obj.padding <NEW_LINE> self.longlist = obj.longlist <NEW_LINE> self.description = obj.description <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.rborder = 0 <NEW_LINE> self.lborder = 0 <NEW_LINE> self.tborder = 0 <NEW_LINE> self.bborder = 0 <NEW_LINE> self.padding = 0 <NEW_LINE> self.longlist = 0 <NEW_LINE> self.description = "" <NEW_LINE> <DEDENT> <DEDENT> def set_description(self, text): <NEW_LINE> <INDENT> self.description = text <NEW_LINE> <DEDENT> def get_description(self): <NEW_LINE> <INDENT> return self.description <NEW_LINE> <DEDENT> def set_padding(self, val): <NEW_LINE> <INDENT> self.padding = val <NEW_LINE> <DEDENT> def set_borders(self, val): <NEW_LINE> <INDENT> self.rborder = val <NEW_LINE> self.lborder = val <NEW_LINE> self.tborder = val <NEW_LINE> self.bborder = val <NEW_LINE> <DEDENT> def set_right_border(self, val): <NEW_LINE> <INDENT> self.rborder = val <NEW_LINE> <DEDENT> def set_left_border(self, val): <NEW_LINE> <INDENT> self.lborder = val <NEW_LINE> <DEDENT> def set_top_border(self, val): <NEW_LINE> <INDENT> self.tborder = val <NEW_LINE> <DEDENT> def set_bottom_border(self, val): <NEW_LINE> <INDENT> self.bborder = val <NEW_LINE> <DEDENT> def set_longlist(self, val): <NEW_LINE> <INDENT> self.longlist = val <NEW_LINE> <DEDENT> def get_padding(self): <NEW_LINE> <INDENT> return self.padding <NEW_LINE> <DEDENT> def get_right_border(self): <NEW_LINE> <INDENT> return self.rborder <NEW_LINE> <DEDENT> def get_left_border(self): <NEW_LINE> <INDENT> return self.lborder <NEW_LINE> <DEDENT> def get_top_border(self): <NEW_LINE> <INDENT> return self.tborder <NEW_LINE> <DEDENT> def get_bottom_border(self): <NEW_LINE> <INDENT> return self.bborder <NEW_LINE> <DEDENT> def get_longlist(self): <NEW_LINE> <INDENT> return self.longlist | Defines the style of a particular table cell. Characteristics are:
right border, left border, top border, bottom border, and padding. | 62598fa07d847024c075c1f8 |
class OpenSoundControlTest(ScriptedLoadableModuleTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> slicer.mrmlScene.Clear(0) <NEW_LINE> <DEDENT> def runTest(self): <NEW_LINE> <INDENT> self.setUp() <NEW_LINE> self.test_OpenSoundControl1() <NEW_LINE> <DEDENT> def test_OpenSoundControl1(self): <NEW_LINE> <INDENT> self.delayDisplay("Starting the test") <NEW_LINE> import urllib <NEW_LINE> downloads = ( ('http://slicer.kitware.com/midas3/download?items=5767', 'FA.nrrd', slicer.util.loadVolume), ) <NEW_LINE> for url,name,loader in downloads: <NEW_LINE> <INDENT> filePath = slicer.app.temporaryPath + '/' + name <NEW_LINE> if not os.path.exists(filePath) or os.stat(filePath).st_size == 0: <NEW_LINE> <INDENT> logging.info('Requesting download %s from %s...\n' % (name, url)) <NEW_LINE> urllib.urlretrieve(url, filePath) <NEW_LINE> <DEDENT> if loader: <NEW_LINE> <INDENT> logging.info('Loading %s...' % (name,)) <NEW_LINE> loader(filePath) <NEW_LINE> <DEDENT> <DEDENT> self.delayDisplay('Finished with download and loading') <NEW_LINE> volumeNode = slicer.util.getNode(pattern="FA") <NEW_LINE> logic = OpenSoundControlLogic() <NEW_LINE> self.assertIsNotNone( logic.hasImageData(volumeNode) ) <NEW_LINE> self.delayDisplay('Test passed!') | This is the test case for your scripted module.
Uses ScriptedLoadableModuleTest base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py | 62598fa045492302aabfc309 |
class Walls(object): <NEW_LINE> <INDENT> def __init__(self, length, breadth): <NEW_LINE> <INDENT> self.length = length <NEW_LINE> self.breadth = breadth <NEW_LINE> self.matrix = [] <NEW_LINE> for i in range(0, self.length): <NEW_LINE> <INDENT> self.matrix.append([]) <NEW_LINE> for j in range(0, self.breadth): <NEW_LINE> <INDENT> self.matrix[i].append('x') <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def makeBoundary(self, brdObject): <NEW_LINE> <INDENT> brd = brdObject.getMatrix() <NEW_LINE> for j in range(0, 4): <NEW_LINE> <INDENT> for i in range(0, brdObject.length): <NEW_LINE> <INDENT> brd[i][j] = 'x' <NEW_LINE> <DEDENT> <DEDENT> for i in range(0, 2): <NEW_LINE> <INDENT> for j in range(0, brdObject.breadth): <NEW_LINE> <INDENT> brd[i][j] = 'x' <NEW_LINE> <DEDENT> <DEDENT> for i in range(brdObject.length - 2, brdObject.length): <NEW_LINE> <INDENT> for j in range(0, brdObject.breadth): <NEW_LINE> <INDENT> brd[i][j] = 'x' <NEW_LINE> <DEDENT> <DEDENT> for j in range(brdObject.breadth - 4, brdObject.breadth): <NEW_LINE> <INDENT> for i in range(0, brdObject.length): <NEW_LINE> <INDENT> brd[i][j] = 'x' <NEW_LINE> <DEDENT> <DEDENT> x = 4 <NEW_LINE> y = 8 <NEW_LINE> while x < (brdObject.length - 4): <NEW_LINE> <INDENT> while y < (brdObject.breadth - 8): <NEW_LINE> <INDENT> editMatrix(brdObject, self, x, y) <NEW_LINE> y += 4 + self.breadth <NEW_LINE> <DEDENT> x += 2 + self.length <NEW_LINE> y = 8 <NEW_LINE> <DEDENT> <DEDENT> def getMatrix(self): <NEW_LINE> <INDENT> return self.matrix | Class walls. | 62598fa021bff66bcd722a96 |
class DefaultUserAgentTestCase(TestCase): <NEW_LINE> <INDENT> net = False <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> super(DefaultUserAgentTestCase, self).setUp() <NEW_LINE> self.orig_format = config.user_agent_format <NEW_LINE> config.user_agent_format = ('{script_product} ({script_comments}) {pwb} ' '({revision}) {http_backend} {python}') <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> super(DefaultUserAgentTestCase, self).tearDown() <NEW_LINE> config.user_agent_format = self.orig_format <NEW_LINE> <DEDENT> def test_default_user_agent(self): <NEW_LINE> <INDENT> self.assertTrue(http.user_agent().startswith( pywikibot.calledModuleName())) <NEW_LINE> self.assertIn('Pywikibot/' + pywikibot.__release__, http.user_agent()) <NEW_LINE> self.assertNotIn(' ', http.user_agent()) <NEW_LINE> self.assertNotIn('()', http.user_agent()) <NEW_LINE> self.assertNotIn('(;', http.user_agent()) <NEW_LINE> self.assertNotIn(';)', http.user_agent()) <NEW_LINE> self.assertIn('requests/', http.user_agent()) <NEW_LINE> self.assertIn('Python/' + str(PYTHON_VERSION[0]), http.user_agent()) | User agent formatting tests using the default config format string. | 62598fa0dd821e528d6d8d67 |
class Subject(object): <NEW_LINE> <INDENT> _sort_key = None <NEW_LINE> _order = 1 <NEW_LINE> def __init__(self, sid='', dset='', atrs=None): <NEW_LINE> <INDENT> self.sid = sid <NEW_LINE> self.dset = dset <NEW_LINE> self.atrs = None <NEW_LINE> self.ddir = '.' <NEW_LINE> self.dfile = '' <NEW_LINE> dir, file = os.path.split(dset) <NEW_LINE> if dir: self.ddir = dir <NEW_LINE> self.dfile = file <NEW_LINE> self.atrs = VO.VarsObject('subject %s' % sid) <NEW_LINE> if atrs != None: self.atrs.merge(atrs) <NEW_LINE> <DEDENT> def show(self): <NEW_LINE> <INDENT> natr = self.atrs.count()-1 <NEW_LINE> print("Subject %s, dset %s, natr = %d" % (self.sid, self.dset, natr)) <NEW_LINE> print(" ddir = %s\n dfile = %s\n" % (self.ddir, self.dfile)) <NEW_LINE> if natr > 0: <NEW_LINE> <INDENT> self.atrs.show(' attributes: ') | a simple subject object holding an ID, dataset name, and an
attribute dictionary | 62598fa0a219f33f346c664c |
class GetSavedGifs(Object): <NEW_LINE> <INDENT> ID = 0x83bf3d52 <NEW_LINE> def __init__(self, hash: int): <NEW_LINE> <INDENT> self.hash = hash <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(b: BytesIO, *args) -> "GetSavedGifs": <NEW_LINE> <INDENT> hash = Int.read(b) <NEW_LINE> return GetSavedGifs(hash) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> b = BytesIO() <NEW_LINE> b.write(Int(self.ID, False)) <NEW_LINE> b.write(Int(self.hash)) <NEW_LINE> return b.getvalue() | Attributes:
ID: ``0x83bf3d52``
Args:
hash: ``int`` ``32-bit``
Raises:
:obj:`Error <pyrogram.Error>`
Returns:
Either :obj:`messages.SavedGifsNotModified <pyrogram.api.types.messages.SavedGifsNotModified>` or :obj:`messages.SavedGifs <pyrogram.api.types.messages.SavedGifs>` | 62598fa032920d7e50bc5e88 |
class User(structs.RDFProtoStruct): <NEW_LINE> <INDENT> protobuf = knowledge_base_pb2.User <NEW_LINE> def __init__(self, initializer=None, age=None, **kwargs): <NEW_LINE> <INDENT> if isinstance(initializer, KnowledgeBaseUser): <NEW_LINE> <INDENT> super(User, self).__init__(initializer=None, age=age, **kwargs) <NEW_LINE> self.ParseFromString(initializer.SerializeToString()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(User, self).__init__(initializer=initializer, age=age, **kwargs) | Information about the users. | 62598fa08c0ade5d55dc35a8 |
class RetinanetClassLoss(object): <NEW_LINE> <INDENT> def __init__(self, params): <NEW_LINE> <INDENT> self._num_classes = params.num_classes <NEW_LINE> self._focal_loss_alpha = params.focal_loss_alpha <NEW_LINE> self._focal_loss_gamma = params.focal_loss_gamma <NEW_LINE> <DEDENT> def __call__(self, cls_outputs, labels, num_positives): <NEW_LINE> <INDENT> num_positives_sum = tf.reduce_sum(input_tensor=num_positives) + 1.0 <NEW_LINE> cls_losses = [] <NEW_LINE> for level in cls_outputs.keys(): <NEW_LINE> <INDENT> cls_losses.append(self.class_loss( cls_outputs[level], labels[level], num_positives_sum)) <NEW_LINE> <DEDENT> return tf.add_n(cls_losses) <NEW_LINE> <DEDENT> def class_loss(self, cls_outputs, cls_targets, num_positives, ignore_label=-2): <NEW_LINE> <INDENT> cls_targets_one_hot = tf.one_hot(cls_targets, self._num_classes) <NEW_LINE> bs, hw, _ = cls_outputs.get_shape().as_list() <NEW_LINE> cls_targets_one_hot = tf.reshape(cls_targets_one_hot, [bs, hw, -1]) <NEW_LINE> loss = focal_loss(cls_outputs, cls_targets_one_hot, self._focal_loss_alpha, self._focal_loss_gamma, num_positives) <NEW_LINE> ignore_loss = tf.where( tf.equal(cls_targets, ignore_label), tf.zeros_like(cls_targets, dtype=tf.float32), tf.ones_like(cls_targets, dtype=tf.float32), ) <NEW_LINE> ignore_loss = tf.expand_dims(ignore_loss, -1) <NEW_LINE> ignore_loss = tf.tile(ignore_loss, [1, 1, 1, self._num_classes]) <NEW_LINE> ignore_loss = tf.reshape(ignore_loss, tf.shape(input=loss)) <NEW_LINE> return tf.reduce_sum(input_tensor=ignore_loss * loss) | RetinaNet class loss. | 62598fa0a17c0f6771d5c06d |
class TextSearch(BaseExpression): <NEW_LINE> <INDENT> def __init__(self, pattern, use_re=False, case=False): <NEW_LINE> <INDENT> self._pattern = unicode(pattern) <NEW_LINE> self.negated = 0 <NEW_LINE> self._build_re(self._pattern, use_re=use_re, case=case) <NEW_LINE> self.titlesearch = TitleSearch(self._pattern, use_re=use_re, case=case) <NEW_LINE> <DEDENT> def costs(self): <NEW_LINE> <INDENT> return 10000 <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> if self.negated: neg = '-' <NEW_LINE> else: neg = '' <NEW_LINE> return u'%s"%s"' % (neg, unicode(self._pattern)) <NEW_LINE> <DEDENT> def highlight_re(self): <NEW_LINE> <INDENT> return u"(%s)" % self._pattern <NEW_LINE> <DEDENT> def search(self, page): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> results = self.titlesearch.search(page) <NEW_LINE> if results: <NEW_LINE> <INDENT> matches.extend(results) <NEW_LINE> <DEDENT> body = page.get_raw_body() <NEW_LINE> for match in self.search_re.finditer(body): <NEW_LINE> <INDENT> matches.append(TextMatch(match.start(),match.end())) <NEW_LINE> <DEDENT> if ((self.negated and matches) or (not self.negated and not matches)): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif matches: <NEW_LINE> <INDENT> return matches <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [Match()] <NEW_LINE> <DEDENT> <DEDENT> def indexed_query(self): <NEW_LINE> <INDENT> return xapian.Query(self._pattern) | A term that does a normal text search
Both page content and the page title are searched, using an
additional TitleSearch term. | 62598fa09c8ee82313040087 |
class KeyedEnumField(EnumField): <NEW_LINE> <INDENT> def get_prep_value(self, value): <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> return value.name <NEW_LINE> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> return getattr(self.enum, value) <NEW_LINE> <DEDENT> return super().to_python(value) <NEW_LINE> <DEDENT> def get_default(self): <NEW_LINE> <INDENT> if self.has_default(): <NEW_LINE> <INDENT> if self.default is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(self.default, str): <NEW_LINE> <INDENT> return self.default <NEW_LINE> <DEDENT> <DEDENT> return super().get_default() | An enum field that stores the names of the values as strings, rather than the values. | 62598fa0adb09d7d5dc0a3bc |
class DummyFSStorageBackend(BaseStorageBackend): <NEW_LINE> <INDENT> require_fs = True <NEW_LINE> def acquire(self, context): <NEW_LINE> <INDENT> fshelper = getMultiAdapter((self, context), IStorageBackendFSAdapter) <NEW_LINE> return DummyFSStorage(context, fshelper.acquire()) <NEW_LINE> <DEDENT> def install(self, context): <NEW_LINE> <INDENT> fshelper = getMultiAdapter((self, context), IStorageBackendFSAdapter) <NEW_LINE> fshelper.acquire() | Dummy backend that provides direct access to file system contents. | 62598fa007f4c71912baf27b |
class Semantics(Enum): <NEW_LINE> <INDENT> STRONG = 'strong' <NEW_LINE> EMPHASIS = 'em' <NEW_LINE> MARK = 'mark' <NEW_LINE> DELETED = 'del' <NEW_LINE> INSERTED = 'ins' <NEW_LINE> SUBSCRIPT = 'sub' <NEW_LINE> SUPERSCRIPT = 'sup' <NEW_LINE> CODE = 'code' <NEW_LINE> UNARTICULATED = 'u' <NEW_LINE> STRIKETHROUGH = 's' <NEW_LINE> VARIABLE = 'var' <NEW_LINE> H1 = 'h1' <NEW_LINE> H2 = 'h2' <NEW_LINE> H3 = 'h3' <NEW_LINE> H4 = 'h4' <NEW_LINE> H5 = 'h5' <NEW_LINE> H6 = 'h6' <NEW_LINE> PARAGRAPH = 'p' | Semantic tags. Values are html tags. | 62598fa08a43f66fc4bf1faf |
@auto_str <NEW_LINE> class MetricDescription(object): <NEW_LINE> <INDENT> def __init__(self, metric_id, display_name, description, group_id, aggregation=MetricAggregation.SUM, value_type=MetricValueType.NUMERIC, properties=(MetricProperties.SIZE_METRIC,)): <NEW_LINE> <INDENT> self.metricId = metric_id <NEW_LINE> self.analysisGroup = group_id <NEW_LINE> self.metricDefinition = { "name": display_name, "aggregation": aggregation, "description": description, "properties": properties, "valueType": value_type } | Description of a metric type to be addded at configuration time.
Args:
metric_id (str): The globally unique metric id.
display_name (str): The metric's name that is displayed in the UI.
description (str): A description explaining what this metric means.
group_id (str): the name of an analysis group under which the metric is placed (used to group the metrics in the
analysis profile).
aggregation (constants.MetricAggregation): How this metric is supposed to be aggregated up the directory
hierarchy. Defaults to ``SUM``.
value_type (constants.MetricValueType): Determines the metric's type. Defaults to ``NUMERIC``.
properties (set[constants.MetricProperties]): Determines the metric's properties. This has effects on how/if the
metric is displayed and assessed. Defaults to ``(SIZE_METRIC, )``.
| 62598fa016aa5153ce400332 |
class ImportOrderLinter(ImportOrderChecker): <NEW_LINE> <INDENT> def __init__(self, tree, filename, lines, order_style='cryptography'): <NEW_LINE> <INDENT> super(ImportOrderLinter, self).__init__(filename, tree) <NEW_LINE> self.lines = lines <NEW_LINE> self.options = { 'import_order_style': order_style, } <NEW_LINE> <DEDENT> def load_file(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def error(self, node, code, message): <NEW_LINE> <INDENT> lineno, col_offset = node.lineno, node.col_offset <NEW_LINE> return (lineno, col_offset, '{0} {1}'.format(code, message)) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> for error in self.check_order(): <NEW_LINE> <INDENT> yield error | Import order linter. | 62598fa04e4d562566372257 |
class ImageLoaderPIL(ImageLoaderBase): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def extensions(): <NEW_LINE> <INDENT> return ('bmp', 'bufr', 'cur', 'dcx', 'fits', 'fl', 'fpx', 'gbr', 'gd', 'gif', 'grib', 'hdf5', 'ico', 'im', 'imt', 'iptc', 'jpeg', 'jpg', 'mcidas', 'mic', 'mpeg', 'msp', 'pcd', 'pcx', 'pixar', 'png', 'ppm', 'psd', 'sgi', 'spider', 'tga', 'tiff', 'wal', 'wmf', 'xbm', 'xpm', 'xv') <NEW_LINE> <DEDENT> def _img_correct(self, _img_tmp): <NEW_LINE> <INDENT> if _img_tmp.mode.lower() not in ('rgb', 'rgba'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> imc = _img_tmp.convert('RGBA') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> Logger.warning( 'Image: Unable to convert image to rgba (was %s)' % (_img_tmp.mode.lower())) <NEW_LINE> raise <NEW_LINE> <DEDENT> _img_tmp = imc <NEW_LINE> <DEDENT> return _img_tmp <NEW_LINE> <DEDENT> def _img_read(self, im): <NEW_LINE> <INDENT> im.seek(0) <NEW_LINE> try: <NEW_LINE> <INDENT> img_ol = None <NEW_LINE> while True: <NEW_LINE> <INDENT> img_tmp = im <NEW_LINE> img_tmp = self._img_correct(img_tmp) <NEW_LINE> if img_ol: <NEW_LINE> <INDENT> img_ol.paste(img_tmp, (0, 0), img_tmp) <NEW_LINE> img_tmp = img_ol <NEW_LINE> <DEDENT> img_ol = img_tmp <NEW_LINE> yield ImageData(img_tmp.size[0], img_tmp.size[1], img_tmp.mode.lower(), img_tmp.tostring()) <NEW_LINE> im.seek(im.tell() + 1) <NEW_LINE> <DEDENT> <DEDENT> except EOFError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> def load(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> im = PILImage.open(filename) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> Logger.warning('Image: Unable to load image <%s>' % filename) <NEW_LINE> raise <NEW_LINE> <DEDENT> self.filename = filename <NEW_LINE> return list(self._img_read(im)) | Image loader based on PIL library.
.. versionadded::
In 1.0.8, GIF animation have been supported.
Gif animation has a lot of issues(transparency/color depths... etc).
In order to keep it simple; what is implimented here is what is
natively supported by pil.
As a general rule, try to use gifs that have no transparency.
Gif's with transparency will work but be ready for some
artifacts for now. | 62598fa03c8af77a43b67e59 |
class IllegalStateError(BaseException): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def navigate_without_paused(cls, direction): <NEW_LINE> <INDENT> if direction.startswith('f'): <NEW_LINE> <INDENT> direction = 'forward' <NEW_LINE> <DEDENT> elif direction.startswith('b'): <NEW_LINE> <INDENT> direction = 'backward' <NEW_LINE> <DEDENT> return cls('Cannot navigate {} unless paused'.format(direction)) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def navigate_beyond_played_frames(cls): <NEW_LINE> <INDENT> return cls('Cannot navigate forward to frames not played before') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def navigate_beyond_rewind_limit(cls): <NEW_LINE> <INDENT> return cls('Cannot navigate backward to frames beyond rewind limit') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def skip_at_nonlatest_frame(cls): <NEW_LINE> <INDENT> return cls('Cannot skip frames unless current frame is the latest ' 'frame already played') | Raised if an operation is applied to the video player at a wrong state.
Several factory methods are provided for different illegal player
operations. | 62598fa08da39b475be03013 |
class TangoTree(BinarySearchTree): <NEW_LINE> <INDENT> def __init__(d): <NEW_LINE> <INDENT> raise NotImplementedError() | The basic idea of a Tango Tree is to store "preferred child" paths,
where each node stores its most recently accessed child as the
preferred child. These paths can be stored as auxiliary BBSTs
sorted by the original keys. | 62598fa00a50d4780f70520d |
class AutoRestHeadExceptionTestService(object): <NEW_LINE> <INDENT> def __init__( self, credentials, base_url=None): <NEW_LINE> <INDENT> self.config = AutoRestHeadExceptionTestServiceConfiguration(credentials, base_url) <NEW_LINE> self._client = ServiceClient(self.config.credentials, self.config) <NEW_LINE> client_models = {} <NEW_LINE> self.api_version = '1.0.0' <NEW_LINE> self._serialize = Serializer(client_models) <NEW_LINE> self._deserialize = Deserializer(client_models) <NEW_LINE> self.head_exception = HeadExceptionOperations( self._client, self.config, self._serialize, self._deserialize) | Test Infrastructure for AutoRest
:ivar config: Configuration for client.
:vartype config: AutoRestHeadExceptionTestServiceConfiguration
:ivar head_exception: HeadException operations
:vartype head_exception: fixtures.acceptancetestsheadexceptions.operations.HeadExceptionOperations
:param credentials: Credentials needed for the client to connect to Azure.
:type credentials: :mod:`A msrestazure Credentials
object<msrestazure.azure_active_directory>`
:param str base_url: Service URL | 62598fa0379a373c97d98e49 |
class TraitConverter(Converter): <NEW_LINE> <INDENT> async def convert(self, ctx: Context, argument: str) -> bool: <NEW_LINE> <INDENT> bot: gb.GreedyGhost = ctx.bot <NEW_LINE> return bot.dbm.getTraitInfo(argument.lower()) | Validates a trait id NOTE: LANGUAGE NOT YET SUPPORTED | 62598fa0009cb60464d01358 |
class Restaurant: <NEW_LINE> <INDENT> def __init__(self, restaurant_name, cuisine_type): <NEW_LINE> <INDENT> self.restaurant_name = restaurant_name <NEW_LINE> self.cuisine_type = cuisine_type <NEW_LINE> <DEDENT> def describe_restaurant(self): <NEW_LINE> <INDENT> print("\nThe name of the restaurant is " + self.restaurant_name.title() + '.') <NEW_LINE> print("The cuisine of the restaurant is " + self.cuisine_type.title() + '.') <NEW_LINE> <DEDENT> def open_restaurant(self): <NEW_LINE> <INDENT> print("The restaurant is in business. ") | 模拟餐馆 | 62598fa0fff4ab517ebcd621 |
class Baseview(object): <NEW_LINE> <INDENT> def __init__(self, view): <NEW_LINE> <INDENT> self.connected = set() <NEW_LINE> self.builder = view.builder <NEW_LINE> <DEDENT> def test_and_set_connected(self, window_id): <NEW_LINE> <INDENT> if window_id in self.connected: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> self.connected.add(window_id) <NEW_LINE> return False <NEW_LINE> <DEDENT> def reconnect(self, widget, signal, callback, data=None): <NEW_LINE> <INDENT> if isinstance(widget, str): <NEW_LINE> <INDENT> widget = self.builder.get_object(widget) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> widget.disconnect_by_func(callback) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> widget.connect(signal, callback, data) <NEW_LINE> <DEDENT> def _create_treeview(self, object_id, columns): <NEW_LINE> <INDENT> treeview = self.builder.get_object(object_id) <NEW_LINE> if len(treeview.get_columns()) > 0: <NEW_LINE> <INDENT> return treeview <NEW_LINE> <DEDENT> treeview.set_vscroll_policy(Gtk.ScrollablePolicy.NATURAL) <NEW_LINE> types = [str for c in columns] <NEW_LINE> treeview.set_model(Gtk.ListStore(*types)) <NEW_LINE> renderers = {} <NEW_LINE> for i, colname in enumerate(columns): <NEW_LINE> <INDENT> renderers[colname] = Gtk.CellRendererText() <NEW_LINE> column = Gtk.TreeViewColumn(colname, renderers[colname], text=i) <NEW_LINE> column.clickable = True <NEW_LINE> treeview.append_column(column) <NEW_LINE> <DEDENT> return treeview <NEW_LINE> <DEDENT> def _message_dialog(self, header, kind, body, exit_): <NEW_LINE> <INDENT> d = Gtk.MessageDialog(self.builder.get_object('main_window'), 0, kind, Gtk.ButtonsType.OK, header) <NEW_LINE> if body: <NEW_LINE> <INDENT> d.format_secondary_markup(body) <NEW_LINE> <DEDENT> d.run() <NEW_LINE> d.destroy() <NEW_LINE> if exit_: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> <DEDENT> def show_warning(self, header, body=None, exit_=False): <NEW_LINE> <INDENT> self._message_dialog(header, Gtk.MessageType.WARNING, body, exit_) <NEW_LINE> <DEDENT> def show_error(self, header, body=None, exit_=False): <NEW_LINE> <INDENT> self._message_dialog(header, Gtk.MessageType.ERROR, body, exit_) <NEW_LINE> <DEDENT> def show_info(self, header, body=None, exit_=False): <NEW_LINE> <INDENT> self._message_dialog(header, Gtk.MessageType.INFO, body, exit_) | Common parts in MVC view components. | 62598fa0d486a94d0ba2be09 |
class SetupGui: <NEW_LINE> <INDENT> def __init__(self, master): <NEW_LINE> <INDENT> self.master = master <NEW_LINE> master.title("Etool setup") <NEW_LINE> self.label = Label(master, text="Etool setup") <NEW_LINE> self.label.pack() <NEW_LINE> self.install_button = Button(master, text="Start Setup", command=self.install) <NEW_LINE> self.install_button.pack() <NEW_LINE> self.close_button = Button(master, text="Close", command=master.quit) <NEW_LINE> self.close_button.pack() <NEW_LINE> <DEDENT> def install(self): <NEW_LINE> <INDENT> for package in ['boto3', 'requests', 'paramiko', 'sshtunnel', 'flask']: <NEW_LINE> <INDENT> print("Installing {}".format(package)) <NEW_LINE> pip.main(['install', package]) | DISABLED AT THE MOMENT | 62598fa010dbd63aa1c709e1 |
class BaseBackend(object): <NEW_LINE> <INDENT> def create_message(self, to: str, body: str): <NEW_LINE> <INDENT> raise NotImplemented( 'You should implement backend by yourself' ) | Base sms sender backend
Provide interface to be implemented for any sms backend | 62598fa045492302aabfc30a |
class SourceView(BaseVocabularyView): <NEW_LINE> <INDENT> def get_context(self): <NEW_LINE> <INDENT> if ISubForm.providedBy(self.context.form): <NEW_LINE> <INDENT> context = self.context.form.parentForm.context <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context = self.context.context <NEW_LINE> <DEDENT> return context <NEW_LINE> <DEDENT> @property <NEW_LINE> @memoize <NEW_LINE> def default_permission(self): <NEW_LINE> <INDENT> if IAddForm.providedBy(self.context.form): <NEW_LINE> <INDENT> return "cmf.AddPortalContent" <NEW_LINE> <DEDENT> return "cmf.ModifyPortalContent" <NEW_LINE> <DEDENT> def get_vocabulary(self): <NEW_LINE> <INDENT> widget = self.context <NEW_LINE> field = widget.field.bind(widget.context) <NEW_LINE> info = mergedTaggedValueDict(field.interface, WRITE_PERMISSIONS_KEY) <NEW_LINE> permission_name = info.get(field.__name__, self.default_permission) <NEW_LINE> permission = queryUtility(IPermission, name=permission_name) <NEW_LINE> if permission is None: <NEW_LINE> <INDENT> permission = getUtility(IPermission, name=self.default_permission) <NEW_LINE> <DEDENT> if not getSecurityManager().checkPermission( permission.title, self.get_context() ): <NEW_LINE> <INDENT> raise VocabLookupException("Vocabulary lookup not allowed.") <NEW_LINE> <DEDENT> if ICollection.providedBy(field): <NEW_LINE> <INDENT> return field.value_type.vocabulary <NEW_LINE> <DEDENT> return field.vocabulary | Queries a field's source and returns JSON-formatted results. | 62598fa0498bea3a75a57955 |
class MinimaxAgent(MultiAgentSearchAgent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> numberOfAgents = gameState.getNumAgents() <NEW_LINE> numberOfGhosts = numberOfAgents - 1 <NEW_LINE> v, action = self.minimax(self.depth, gameState, True, 0 ) <NEW_LINE> return action <NEW_LINE> <DEDENT> def minimax(self, depth, gameState, checkMaxPlayer, index): <NEW_LINE> <INDENT> action_final = Directions.STOP <NEW_LINE> if gameState.getLegalActions(0) == [] or depth == 0: <NEW_LINE> <INDENT> return self.evaluationFunction(gameState), Directions.STOP <NEW_LINE> <DEDENT> if checkMaxPlayer: <NEW_LINE> <INDENT> v = -999999999 <NEW_LINE> actions = gameState.getLegalActions(0) <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(0,action) <NEW_LINE> if not index == gameState.getNumAgents()-1: <NEW_LINE> <INDENT> val, action1 = self.minimax( depth, successor, False, index+1) <NEW_LINE> <DEDENT> if val > v : <NEW_LINE> <INDENT> action_final = action <NEW_LINE> v =val <NEW_LINE> <DEDENT> <DEDENT> return v, action_final <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> minEva = +999999999 <NEW_LINE> ghostActions = gameState.getLegalActions(index) <NEW_LINE> for action in ghostActions: <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(index, action) <NEW_LINE> if index == gameState.getNumAgents()-1: <NEW_LINE> <INDENT> val, action2 = self.minimax( depth - 1, successor, True, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val, action2 = self.minimax(depth, successor, False, index + 1) <NEW_LINE> <DEDENT> minEva = min(val, minEva) <NEW_LINE> <DEDENT> return minEva, action_final | Your minimax agent (question 2) | 62598fa0e64d504609df92d2 |
class OBJECT_OT_LimitDOFButton(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "mocap.limitdof" <NEW_LINE> bl_label = "Set DOF Constraints" <NEW_LINE> def execute(self, context): <NEW_LINE> <INDENT> performer_obj = [obj for obj in context.selected_objects if obj != context.active_object][0] <NEW_LINE> mocap_tools.limit_dof(context, performer_obj, context.active_object) <NEW_LINE> return {'FINISHED'} <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> if context.active_object: <NEW_LINE> <INDENT> activeIsArmature = isinstance(context.active_object.data, bpy.types.Armature) <NEW_LINE> <DEDENT> performer_obj = [obj for obj in context.selected_objects if obj != context.active_object] <NEW_LINE> if performer_obj: <NEW_LINE> <INDENT> return activeIsArmature and isinstance(performer_obj[0].data, bpy.types.Armature) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Create limit constraints on the active armature from the selected armature's animation's range of motion | 62598fa099cbb53fe6830d06 |
class get_high_scores_forms(messages.Message): <NEW_LINE> <INDENT> high_scores = messages.MessageField(get_high_scores_form, 1, repeated=True) | Used to return high score information | 62598fa0d268445f26639a9d |
class SimpleArraySurfacePointer(object, IDisposable): <NEW_LINE> <INDENT> def ConstPointer(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def Dispose(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def NonConstPointer(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def ToNonConstArray(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __enter__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __init__(self, *args): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __repr__(self, *args): <NEW_LINE> <INDENT> pass | Wrapper for a C++ ON_SimpleArray of ON_Surface* or const ON_Surface*. If
you are not writing C++ code then this class is not for you.
SimpleArraySurfacePointer() | 62598fa00a50d4780f70520e |
class SpcAlarm(alarm.AlarmControlPanel): <NEW_LINE> <INDENT> def __init__(self, area, api): <NEW_LINE> <INDENT> self._area = area <NEW_LINE> self._api = api <NEW_LINE> <DEDENT> async def async_added_to_hass(self): <NEW_LINE> <INDENT> self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_UPDATE_ALARM.format(self._area.id), self._update_callback, ) ) <NEW_LINE> <DEDENT> @callback <NEW_LINE> def _update_callback(self): <NEW_LINE> <INDENT> self.async_schedule_update_ha_state(True) <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._area.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def changed_by(self): <NEW_LINE> <INDENT> return self._area.last_changed_by <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return _get_alarm_state(self._area) <NEW_LINE> <DEDENT> @property <NEW_LINE> def supported_features(self) -> int: <NEW_LINE> <INDENT> return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY | SUPPORT_ALARM_ARM_NIGHT <NEW_LINE> <DEDENT> async def async_alarm_disarm(self, code=None): <NEW_LINE> <INDENT> await self._api.change_mode(area=self._area, new_mode=AreaMode.UNSET) <NEW_LINE> <DEDENT> async def async_alarm_arm_home(self, code=None): <NEW_LINE> <INDENT> await self._api.change_mode(area=self._area, new_mode=AreaMode.PART_SET_A) <NEW_LINE> <DEDENT> async def async_alarm_arm_night(self, code=None): <NEW_LINE> <INDENT> await self._api.change_mode(area=self._area, new_mode=AreaMode.PART_SET_B) <NEW_LINE> <DEDENT> async def async_alarm_arm_away(self, code=None): <NEW_LINE> <INDENT> await self._api.change_mode(area=self._area, new_mode=AreaMode.FULL_SET) | Representation of the SPC alarm panel. | 62598fa04e4d562566372258 |
class Curve(object): <NEW_LINE> <INDENT> def __init__(self, name, raw): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.raw = raw <NEW_LINE> if raw.get("value") is None: <NEW_LINE> <INDENT> self.raw["value"] = [] <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> return self.raw[key] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.raw[key] = value | A single curve within a CurveSet. | 62598fa0442bda511e95c28e |
class PpapProcessor(DataProcessor): <NEW_LINE> <INDENT> def get_train_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples(self.load_data(os.path.join(data_dir, "train.pkl")), "train") <NEW_LINE> <DEDENT> def get_dev_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples(self.load_data(os.path.join(data_dir, "dev.pkl")), "dev") <NEW_LINE> <DEDENT> def get_test_examples(self, data_dir): <NEW_LINE> <INDENT> return self._create_examples(self.load_data(os.path.join(data_dir, "test.pkl")), "test") <NEW_LINE> <DEDENT> def get_labels(self): <NEW_LINE> <INDENT> return ["0", "1"] <NEW_LINE> <DEDENT> def load_data(self, input_file): <NEW_LINE> <INDENT> max_bytes = 2**31 - 1 <NEW_LINE> bytes_in = bytearray(0) <NEW_LINE> input_size = os.path.getsize(input_file) <NEW_LINE> with open(input_file, 'rb') as f_in: <NEW_LINE> <INDENT> for _ in range(0, input_size, max_bytes): <NEW_LINE> <INDENT> bytes_in += f_in.read(max_bytes) <NEW_LINE> <DEDENT> <DEDENT> return pickle.loads(bytes_in)[1] <NEW_LINE> <DEDENT> def _create_examples(self, lines, set_type): <NEW_LINE> <INDENT> examples = [] <NEW_LINE> for (i, line) in enumerate(lines): <NEW_LINE> <INDENT> line = line.replace("\n", "") <NEW_LINE> parts = line.strip().split('#') <NEW_LINE> context = '' <NEW_LINE> for (i, index) in enumerate(parts[1:-1]): <NEW_LINE> <INDENT> if i: <NEW_LINE> <INDENT> context += ' ' <NEW_LINE> <DEDENT> context += index <NEW_LINE> <DEDENT> guid = "%s-%s" % (set_type, tokenization.convert_to_unicode(str(i))) <NEW_LINE> text_a = tokenization.convert_to_unicode(context) <NEW_LINE> text_b = tokenization.convert_to_unicode(parts[-1]) <NEW_LINE> if set_type == "test": <NEW_LINE> <INDENT> label = "0" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> label = tokenization.convert_to_unicode(parts[0]) <NEW_LINE> <DEDENT> examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) <NEW_LINE> <DEDENT> return examples | Processor for the MultiNLI data set (GLUE version). | 62598fa0b7558d5895463462 |
class Size(Vector): <NEW_LINE> <INDENT> def __init__(self, value, units, win=None): <NEW_LINE> <INDENT> Vector.__init__(self, value, units, win) | Class representing a size.
Parameters
----------
value : ArrayLike
Array of values representing size axis-aligned bounding box within a
coordinate system. Sizes are specified in a similar manner to
`~psychopy.layout.Vector` as either 1xN for single vectors, and Nx2 or
Nx3 for multiple positions.
units : str or None
Units which `value` has been specified in. Applicable values are
`'pix'`, `'deg'`, `'degFlat'`, `'degFlatPos'`, `'cm'`, `'pt'`, `'norm'`,
`'height'`, or `None`.
win : `~psychopy.visual.Window` or None
Window associated with this size object. This value must be specified if
you wish to map sizes to coordinate systems that require additional
information about the monitor the window is being displayed on. | 62598fa08c0ade5d55dc35a9 |
class BrowserImportsItem(BrowserItem): <NEW_LINE> <INDENT> def __init__(self, parent, text): <NEW_LINE> <INDENT> BrowserItem.__init__(self, parent, text) <NEW_LINE> self.type_ = BrowserItemImports <NEW_LINE> self.icon = UI.PixmapCache.getIcon("imports.png") <NEW_LINE> <DEDENT> def lessThan(self, other, column, order): <NEW_LINE> <INDENT> if issubclass(other.__class__, BrowserClassItem) or issubclass(other.__class__, BrowserClassAttributesItem): <NEW_LINE> <INDENT> return order == Qt.AscendingOrder <NEW_LINE> <DEDENT> return BrowserItem.lessThan(self, other, column, order) | Class implementing the data structure for browser import items. | 62598fa0be383301e025362b |
class LoadAllModulesTest(SimpleTestCase): <NEW_LINE> <INDENT> @patch('os.walk') <NEW_LINE> @patch('importlib.import_module') <NEW_LINE> def test_should_import_all_modules(self, import_module, walk): <NEW_LINE> <INDENT> walk.return_value = [ ('module', [], ['file1.py', 'file2.py']), ('module/submodule', [], ['file3.py', 'file4.py']), ] <NEW_LINE> load_all_modules(sentinel.directory) <NEW_LINE> import_module.assert_has_calls([ call('module.file1'), call('module.file2'), call('module.submodule.file3'), call('module.submodule.file4'), ]) <NEW_LINE> <DEDENT> @patch('os.walk') <NEW_LINE> @patch('importlib.import_module') <NEW_LINE> def test_should_not_import_modules_from_ignored_dirs(self, import_module, walk): <NEW_LINE> <INDENT> ignore_dirs = ['migrations'] <NEW_LINE> walk.return_value = [ ('module', [], ['file1.py', 'file2.py']), ('module/migrations', [], ['file3.py', 'file4.py']), ] <NEW_LINE> load_all_modules(sentinel.directory, ignore_dirs=ignore_dirs) <NEW_LINE> import_module.assert_has_calls([ call('module.file1'), call('module.file2'), ]) <NEW_LINE> <DEDENT> @patch('os.walk') <NEW_LINE> @patch('importlib.import_module') <NEW_LINE> def test_should_not_import_not_py_files(self, import_module, walk): <NEW_LINE> <INDENT> walk.return_value = [ ('module', [], ['file1.py', 'file2.py']), ('module/submodule', [], ['file3.py', 'file4.txt']), ] <NEW_LINE> load_all_modules(sentinel.directory) <NEW_LINE> import_module.assert_has_calls([ call('module.file1'), call('module.file2'), call('module.submodule.file3'), ]) <NEW_LINE> <DEDENT> @patch('os.walk') <NEW_LINE> @patch('importlib.import_module') <NEW_LINE> @patch('smarttest.utils.log') <NEW_LINE> def test_should_ignore_not_importing_modules(self, log, import_module, walk): <NEW_LINE> <INDENT> import_module.side_effect = ImportError <NEW_LINE> walk.return_value = [ ('module', [], ['file1.py', 'file2.py']), ('module/submodule', [], ['file3.py', 'file4.txt']), ] <NEW_LINE> load_all_modules(sentinel.directory) <NEW_LINE> self.assertTrue(log.warning.called) | :py:meth:`smarttest.utils.load_all_modules` | 62598fa030bbd72246469891 |
class GitHubException(ProviderException): <NEW_LINE> <INDENT> pass | GitHub returned an error from an API call. | 62598fa0925a0f43d25e7e72 |
class CSDM_Leaf_Dynamics(SimulationObject): <NEW_LINE> <INDENT> class Parameters(ParamTemplate): <NEW_LINE> <INDENT> CSDM_MAX = Float() <NEW_LINE> CSDM_MIN = Float() <NEW_LINE> CSDM_A = Float() <NEW_LINE> CSDM_B = Float() <NEW_LINE> CSDM_T1 = Float() <NEW_LINE> CSDM_T2 = Float() <NEW_LINE> <DEDENT> class StateVariable(StatesTemplate): <NEW_LINE> <INDENT> LAI = Float() <NEW_LINE> DAYNR = Int() <NEW_LINE> LAIMAX = Float() <NEW_LINE> <DEDENT> def _CSDM(self, daynr): <NEW_LINE> <INDENT> p = self.params <NEW_LINE> LAI_growth = 1./(1. + exp(-p.CSDM_B*(daynr - p.CSDM_T1)))**2 <NEW_LINE> LAI_senescence = -exp(p.CSDM_A*(daynr - p.CSDM_T2)) <NEW_LINE> LAI = p.CSDM_MIN + p.CSDM_MAX*(LAI_growth + LAI_senescence) <NEW_LINE> if LAI < p.CSDM_MIN: <NEW_LINE> <INDENT> msg = ("LAI of CSDM model smaller then lower LAI limit "+ "(CSDM_MIN)! Adjusting LAI to CSDM_MIN.") <NEW_LINE> self.logger.warn(msg) <NEW_LINE> LAI = max(p.CSDM_MIN, LAI) <NEW_LINE> <DEDENT> return LAI <NEW_LINE> <DEDENT> def initialize(self, day, kiosk, cropdata): <NEW_LINE> <INDENT> self.params = self.Parameters(cropdata) <NEW_LINE> LAI = self._CSDM(1) <NEW_LINE> self.states = self.StateVariable(kiosk, LAI=LAI, DAYNR=1, LAIMAX=self.params.CSDM_MIN, publish="LAI") <NEW_LINE> <DEDENT> @prepare_rates <NEW_LINE> def calc_rates(self, day, drv): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @prepare_states <NEW_LINE> def integrate(self, day): <NEW_LINE> <INDENT> self.states.DAYNR += 1 <NEW_LINE> self.states.LAI = self._CSDM(self.states.DAYNR) <NEW_LINE> if self.states.LAI > self.states.LAIMAX: <NEW_LINE> <INDENT> self.states.LAIMAX = self.states.LAI <NEW_LINE> <DEDENT> if self.states.DAYNR > self.params.CSDM_T2: <NEW_LINE> <INDENT> self._send_signal(signal=signals.crop_finish, day=day, finish_type="Canopy died according to CSDM leaf model.", crop_delete=True) | Leaf dynamics according to the Canopy Structure Dynamic Model.
The only difference is that in the real CSDM the temperature sum is the
driving variable, while in this case it is simply the day number since the start of the model.
Reference:
Koetz et al. 2005. Use of coupled canopy structure dynamic and radiative
transfer models to estimate biophysical canopy characteristics.
Remote Sensing of Environment. Volume 95, Issue 1, 15 March 2005,
Pages 115-124. http://dx.doi.org/10.1016/j.rse.2004.11.017 | 62598fa03539df3088ecc0e9 |
class ProbabilisticMixIn: <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> if "prob" in kwargs: <NEW_LINE> <INDENT> if "logprob" in kwargs: <NEW_LINE> <INDENT> raise TypeError("Must specify either prob or logprob " "(not both)") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ProbabilisticMixIn.set_prob(self, kwargs["prob"]) <NEW_LINE> <DEDENT> <DEDENT> elif "logprob" in kwargs: <NEW_LINE> <INDENT> ProbabilisticMixIn.set_logprob(self, kwargs["logprob"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__prob = self.__logprob = None <NEW_LINE> <DEDENT> <DEDENT> def set_prob(self, prob): <NEW_LINE> <INDENT> self.__prob = prob <NEW_LINE> self.__logprob = None <NEW_LINE> <DEDENT> def set_logprob(self, logprob): <NEW_LINE> <INDENT> self.__logprob = logprob <NEW_LINE> self.__prob = None <NEW_LINE> <DEDENT> def prob(self): <NEW_LINE> <INDENT> if self.__prob is None: <NEW_LINE> <INDENT> if self.__logprob is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.__prob = 2 ** (self.__logprob) <NEW_LINE> <DEDENT> return self.__prob <NEW_LINE> <DEDENT> def logprob(self): <NEW_LINE> <INDENT> if self.__logprob is None: <NEW_LINE> <INDENT> if self.__prob is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.__logprob = math.log(self.__prob, 2) <NEW_LINE> <DEDENT> return self.__logprob | A mix-in class to associate probabilities with other classes
(trees, rules, etc.). To use the ``ProbabilisticMixIn`` class,
define a new class that derives from an existing class and from
ProbabilisticMixIn. You will need to define a new constructor for
the new class, which explicitly calls the constructors of both its
parent classes. For example:
>>> from nltk.probability import ProbabilisticMixIn
>>> class A:
... def __init__(self, x, y): self.data = (x,y)
...
>>> class ProbabilisticA(A, ProbabilisticMixIn):
... def __init__(self, x, y, **prob_kwarg):
... A.__init__(self, x, y)
... ProbabilisticMixIn.__init__(self, **prob_kwarg)
See the documentation for the ProbabilisticMixIn
``constructor<__init__>`` for information about the arguments it
expects.
You should generally also redefine the string representation
methods, the comparison methods, and the hashing method. | 62598fa085dfad0860cbf98f |
class TestLbHttpResponseHeaderDeleteAction(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testLbHttpResponseHeaderDeleteAction(self): <NEW_LINE> <INDENT> pass | LbHttpResponseHeaderDeleteAction unit test stubs | 62598fa03d592f4c4edbad03 |
class cc_dim_uc(cc_dim): <NEW_LINE> <INDENT> def __init__(self, X, cc_datatype_class, index, Z=None, n_grid=30, distargs=None): <NEW_LINE> <INDENT> super(cc_dim_uc, self).__init__(X, cc_datatype_class, index, Z=None, n_grid=30, distargs=None) <NEW_LINE> self.mode = 'uncollapsed' <NEW_LINE> self.params = dict() <NEW_LINE> <DEDENT> def singleton_predictive_logp(self,n): <NEW_LINE> <INDENT> x = self.X[n] <NEW_LINE> lp, params = self.model.singleton_logp(x, self.hypers) <NEW_LINE> self.params = params <NEW_LINE> return lp <NEW_LINE> <DEDENT> def create_singleton_cluster(self, n, current): <NEW_LINE> <INDENT> x = self.X[n] <NEW_LINE> self.clusters[current].remove_element(x) <NEW_LINE> self.clusters.append(self.model(distargs=self.distargs)) <NEW_LINE> self.clusters[-1].set_hypers(self.hypers) <NEW_LINE> self.clusters[-1].set_params(self.params) <NEW_LINE> self.clusters[-1].insert_element(x) <NEW_LINE> <DEDENT> def update_hypers(self): <NEW_LINE> <INDENT> for cluster in self.clusters: <NEW_LINE> <INDENT> cluster.set_hypers(self.hypers) <NEW_LINE> cluster.update_component_parameters() <NEW_LINE> <DEDENT> self.hypers = self.clusters[0].update_hypers(self.clusters, self.hypers_grids) <NEW_LINE> <DEDENT> def reassign(self, Z): <NEW_LINE> <INDENT> self.clusters = [] <NEW_LINE> K = max(Z)+1 <NEW_LINE> for k in range(K): <NEW_LINE> <INDENT> cluster = self.model(distargs=self.distargs) <NEW_LINE> cluster.set_hypers(self.hypers) <NEW_LINE> self.clusters.append(cluster) <NEW_LINE> <DEDENT> for i in range(self.N): <NEW_LINE> <INDENT> k = Z[i] <NEW_LINE> self.clusters[k].insert_element(self.X[i]) <NEW_LINE> <DEDENT> for cluster in self.clusters: <NEW_LINE> <INDENT> cluster.update_component_parameters() <NEW_LINE> <DEDENT> assert len(self.clusters) == max(Z)+1 <NEW_LINE> N = 0 <NEW_LINE> for k in range(K): <NEW_LINE> <INDENT> assert self.clusters[k].N > 0 <NEW_LINE> N += self.clusters[k].N <NEW_LINE> <DEDENT> assert N == len(Z) | cc_dim. Column. Holds data, model type, and hyperparameters. | 62598fa091f36d47f2230dbb |
class link(object): <NEW_LINE> <INDENT> updating = False <NEW_LINE> def __init__(self, source, target, transform=None): <NEW_LINE> <INDENT> _validate_link(source, target) <NEW_LINE> self.source, self.target = source, target <NEW_LINE> self._transform, self._transform_inv = ( transform if transform else (lambda x: x,) * 2) <NEW_LINE> self.link() <NEW_LINE> <DEDENT> def link(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(self.target[0], self.target[1], self._transform(getattr(self.source[0], self.source[1]))) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.source[0].observe(self._update_target, names=self.source[1]) <NEW_LINE> self.target[0].observe(self._update_source, names=self.target[1]) <NEW_LINE> <DEDENT> <DEDENT> @contextlib.contextmanager <NEW_LINE> def _busy_updating(self): <NEW_LINE> <INDENT> self.updating = True <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.updating = False <NEW_LINE> <DEDENT> <DEDENT> def _update_target(self, change): <NEW_LINE> <INDENT> if self.updating: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with self._busy_updating(): <NEW_LINE> <INDENT> setattr(self.target[0], self.target[1], self._transform(change.new)) <NEW_LINE> if getattr(self.source[0], self.source[1]) != change.new: <NEW_LINE> <INDENT> raise TraitError( "Broken link {}: the source value changed while updating " "the target.".format(self)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _update_source(self, change): <NEW_LINE> <INDENT> if self.updating: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with self._busy_updating(): <NEW_LINE> <INDENT> setattr(self.source[0], self.source[1], self._transform_inv(change.new)) <NEW_LINE> if getattr(self.target[0], self.target[1]) != change.new: <NEW_LINE> <INDENT> raise TraitError( "Broken link {}: the target value changed while updating " "the source.".format(self)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def unlink(self): <NEW_LINE> <INDENT> self.source[0].unobserve(self._update_target, names=self.source[1]) <NEW_LINE> self.target[0].unobserve(self._update_source, names=self.target[1]) | Link traits from different objects together so they remain in sync.
Parameters
----------
source : (object / attribute name) pair
target : (object / attribute name) pair
transform: iterable with two callables (optional)
Data transformation between source and target and target and source.
Examples
--------
>>> c = link((src, 'value'), (tgt, 'value'))
>>> src.value = 5 # updates other objects as well | 62598fa0f7d966606f747e17 |
class Icmpv6(A10BaseClass): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.ERROR_MSG = "" <NEW_LINE> self.required=[] <NEW_LINE> self.b_key = "icmpv6" <NEW_LINE> self.a10_url="/axapi/v3/cgnv6/nat/icmpv6" <NEW_LINE> self.DeviceProxy = "" <NEW_LINE> self.respond_to_ping = "" <NEW_LINE> self.uuid = "" <NEW_LINE> for keys, value in kwargs.items(): <NEW_LINE> <INDENT> setattr(self,keys, value) | Class Description::
ICMPv6 configuration for IPv6 NAT.
Class icmpv6 supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param respond_to_ping: {"default": 0, "optional": true, "type": "number", "description": "Respond to ICMPv6 echo requests to NAT pool IPs (default: disabled)", "format": "flag"}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/cgnv6/nat/icmpv6`. | 62598fa0a79ad16197769e9a |
class SubsampleTransform(Transform): <NEW_LINE> <INDENT> def __init__(self, width=5, **kwargs): <NEW_LINE> <INDENT> super(SubsampleTransform, self).__init__(**kwargs) <NEW_LINE> self.width = width <NEW_LINE> <DEDENT> def transform(self, samples): <NEW_LINE> <INDENT> super(SubsampleTransform, self).transform(samples) <NEW_LINE> if self.width == 1: <NEW_LINE> <INDENT> print("subsampling width is 1, skipping") <NEW_LINE> return samples <NEW_LINE> <DEDENT> timelen = len(select.getsamplingnames(samples)) <NEW_LINE> sublen = np.ceil(timelen/self.width).astype('int') <NEW_LINE> if timelen % self.width != 0: <NEW_LINE> <INDENT> self.padlen = self.width - (timelen % self.width) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.padlen = 0 <NEW_LINE> <DEDENT> zpadlen = int(np.log10(sublen)) + 1 <NEW_LINE> timenames = ['t_'+str.zfill(x, zpadlen) for x in np.arange(0, sublen).astype('str')] <NEW_LINE> subcolix = pd.MultiIndex.from_product([self.channels, timenames], names=['channel','sample']) <NEW_LINE> sub_samples = pd.DataFrame(index=samples.index, columns=subcolix, dtype=samples.values.dtype) <NEW_LINE> for ix, sample in samples.iterrows(): <NEW_LINE> <INDENT> self.update_status(len(samples)) <NEW_LINE> for chix, channel in enumerate(self.channels): <NEW_LINE> <INDENT> data = sample[channel].values <NEW_LINE> data = np.pad(data, (0, self.padlen), mode='edge') <NEW_LINE> data = decimate(data, self.width, zero_phase=True) <NEW_LINE> sub_samples.loc[ix].loc[channel].values[:] = data <NEW_LINE> <DEDENT> <DEDENT> return sub_samples | Subsample time series by some width.
Pads sample if sample size is not a multiple of width.
Parameters
----------
width: integer (default 5)
Number of consecutive time points to average.
Returns
----
Re-indexed Dataframe with subsampled data for each sample. | 62598fa063d6d428bbee25e6 |
class KubernetesConfigSource(ConfigSource): <NEW_LINE> <INDENT> def __init__(self, label, client, name, **kwargs): <NEW_LINE> <INDENT> self.type = "kubernetes" <NEW_LINE> self.client = client <NEW_LINE> self.name = name <NEW_LINE> self.namespace = kwargs.get("namespace") or "default" <NEW_LINE> self.key = kwargs.get("key") <NEW_LINE> self.config_type = kwargs.get("config_type") or "json" <NEW_LINE> super(KubernetesConfigSource, self).__init__(label) <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> if yapconf.kubernetes_client and not isinstance( self.client, yapconf.kubernetes_client.CoreV1Api ): <NEW_LINE> <INDENT> raise YapconfSourceError( "Invalid source (%s). Client must be supplied and must be of " "type %s. Got type: %s" % ( self.label, type(yapconf.kubernetes_client.CoreV1Api), type(self.client), ) ) <NEW_LINE> <DEDENT> if self.config_type == "yaml" and not yapconf.yaml_support: <NEW_LINE> <INDENT> raise YapconfSourceError( "Kubernetes config source specified that the configmap " "contained a yaml config. In order to support yaml loading, " "you will need to `pip install yapconf[yaml]`." ) <NEW_LINE> <DEDENT> if self.config_type not in yapconf.FILE_TYPES: <NEW_LINE> <INDENT> raise YapconfSourceError( "Invalid config type specified for a kubernetes config. %s is " "not supported. Supported types are %s" % (self.name, yapconf.FILE_TYPES) ) <NEW_LINE> <DEDENT> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> result = self.client.read_namespaced_config_map(self.name, self.namespace) <NEW_LINE> if self.key is None: <NEW_LINE> <INDENT> return result.data <NEW_LINE> <DEDENT> if self.key not in result.data: <NEW_LINE> <INDENT> raise YapconfLoadError( "Loaded configmap %s, but could not find key %s in the data " "portion of the configmap." % self.key ) <NEW_LINE> <DEDENT> nested_config = result.data[self.key] <NEW_LINE> if self.config_type == "json": <NEW_LINE> <INDENT> return json.loads(nested_config,) <NEW_LINE> <DEDENT> elif self.config_type == "yaml": <NEW_LINE> <INDENT> return yapconf.yaml.load(nested_config) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise NotImplementedError( "Cannot load config with type %s" % self.config_type ) <NEW_LINE> <DEDENT> <DEDENT> def _watch(self, handler, data): <NEW_LINE> <INDENT> w = watch.Watch() <NEW_LINE> for event in w.stream( self.client.list_namespaced_config_map, namespace=self.namespace ): <NEW_LINE> <INDENT> config_map = event["object"] <NEW_LINE> if config_map.metadata.name != self.name: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if event["type"] == "DELETED": <NEW_LINE> <INDENT> raise YapconfSourceError( "Kubernetes config watcher died. The configmap %s was " "deleted." % self.name ) <NEW_LINE> <DEDENT> if event["type"] == "MODIFIED": <NEW_LINE> <INDENT> handler.handle_config_change(self.get_data()) | A kubernetes config data source.
This is meant to load things directly from the kubernetes API.
Specifically, it can load things from config maps.
Keyword Args:
client: A kubernetes client from the kubernetes package.
name (str): The name of the ConfigMap to load.
namespace (str): The namespace for the ConfigMap
key (str): A key for the given ConfigMap data object.
config_type (str): Used in conjunction with 'key', if 'key' points to
a data blob, this will specify whether to use json or yaml to load
the file. | 62598fa04e4d562566372259 |
class StopAction(PlumberyAction): <NEW_LINE> <INDENT> def process(self, blueprint): <NEW_LINE> <INDENT> plogging.info("- process blueprint") | Stops nodes
:param settings: specific settings for this action
:type param: ``dict`` | 62598fa00c0af96317c561b6 |
class GroupDeviceItem(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.DeviceId = None <NEW_LINE> self.NickName = None <NEW_LINE> self.Status = None <NEW_LINE> self.ExtraInformation = None <NEW_LINE> self.DeviceType = None <NEW_LINE> self.RTSPUrl = None <NEW_LINE> self.DeviceCode = None <NEW_LINE> self.IsRecord = None <NEW_LINE> self.Recordable = None <NEW_LINE> self.Protocol = None <NEW_LINE> self.CreateTime = None <NEW_LINE> self.ChannelNum = None <NEW_LINE> self.VideoChannelNum = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.DeviceId = params.get("DeviceId") <NEW_LINE> self.NickName = params.get("NickName") <NEW_LINE> self.Status = params.get("Status") <NEW_LINE> self.ExtraInformation = params.get("ExtraInformation") <NEW_LINE> self.DeviceType = params.get("DeviceType") <NEW_LINE> self.RTSPUrl = params.get("RTSPUrl") <NEW_LINE> self.DeviceCode = params.get("DeviceCode") <NEW_LINE> self.IsRecord = params.get("IsRecord") <NEW_LINE> self.Recordable = params.get("Recordable") <NEW_LINE> self.Protocol = params.get("Protocol") <NEW_LINE> self.CreateTime = params.get("CreateTime") <NEW_LINE> self.ChannelNum = params.get("ChannelNum") <NEW_LINE> self.VideoChannelNum = params.get("VideoChannelNum") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | 分组下设备信息
| 62598fa0d7e4931a7ef3bece |
class ResNet34(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ResNet34, self).__init__() <NEW_LINE> self.model_name = 'resnet34' <NEW_LINE> self.pre = nn.Sequential( nn.Conv2d(3, 64, 7, 2, 3, bias=False), nn.BatchNorm(64), nn.ReLU(inplace=True), nn.MaxPool2d(3, 2, 1) ) <NEW_LINE> self.layer1 = self._make_layer(64, 128, 3, stride=1) <NEW_LINE> self.layer2 = self._make_layer(128, 256, 4, stride=2) <NEW_LINE> self.layer3 = self._make_layer(256, 512, 6, stride=1, dilation=2) <NEW_LINE> self.layer4 = self._make_layer(512, 512, 3, stride=1, dilation=4) <NEW_LINE> <DEDENT> def _make_layer(inchannel, outchannel, block_num, stride=1, dilation=1): <NEW_LINE> <INDENT> shortcut = nn.Sequential( nn.Conv2d(inchannel, outchannel, 1, stride, bias=False), nn.BatchNorm2d(outchannel) ) <NEW_LINE> layers = [] <NEW_LINE> layers.append(ResidualBlock(in_channel, out_channel, stride, shortcut, dilation)) <NEW_LINE> for i in range(1, block_num): <NEW_LINE> <INDENT> layers.append(ResidualBlock(outchannel, outchannel, dilation=dilation)) <NEW_LINE> <DEDENT> return nn.Sequential(*layers) <NEW_LINE> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> x = self.pre(x) <NEW_LINE> x = self.layer1(x) <NEW_LINE> x = self.layer2(x) <NEW_LINE> x_3 = self.layer3(x) <NEW_LINE> x = self.layer4(x_3) <NEW_LINE> return x | ResNet34 used for feature extractors.
output is x, x_3.the size of them are (batch_size, 512, h/4, w/4) | 62598fa0009cb60464d0135a |
class GRRMemoryDriver(GRRSignedBlob): <NEW_LINE> <INDENT> class SchemaCls(GRRSignedBlob.SchemaCls): <NEW_LINE> <INDENT> INSTALLATION = aff4.Attribute( "aff4:driver/installation", rdf_client.DriverInstallTemplate, "The driver installation control protobuf.", "installation", default=rdf_client.DriverInstallTemplate( driver_name="pmem", device_path=r"\\.\pmem")) | A driver for acquiring memory. | 62598fa07047854f4633f20f |
class Ally(Character): <NEW_LINE> <INDENT> def __init__(self, name: str, hp: int, max_hp: int, attack: int, speed: int): <NEW_LINE> <INDENT> super().__init__(name, hp, max_hp, attack, speed, team=1, level=1, exp=0, target_exp=200) <NEW_LINE> <DEDENT> def act(self, players): <NEW_LINE> <INDENT> all_enemy_locations = self.get_all_enemies(players) <NEW_LINE> enemies = {character.name: character for character in players if character.team != 1} <NEW_LINE> if all_enemy_locations: <NEW_LINE> <INDENT> if self.is_alive: <NEW_LINE> <INDENT> if all_enemy_locations.count(1): <NEW_LINE> <INDENT> targeted_index = all_enemy_locations[0] <NEW_LINE> targeted_player = players[targeted_index] <NEW_LINE> damaged_player = self.deal_damage(targeted_player) <NEW_LINE> players[targeted_index] = damaged_player <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> targeted_enemy = None <NEW_LINE> while targeted_enemy is None: <NEW_LINE> <INDENT> user_input = input('>') <NEW_LINE> targeted_enemy = enemies.get(user_input) <NEW_LINE> <DEDENT> damaged_player = self.deal_damage(targeted_enemy) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return players <NEW_LINE> <DEDENT> def move_input(self): <NEW_LINE> <INDENT> move = None <NEW_LINE> while move is None: <NEW_LINE> <INDENT> m_input = input('>') <NEW_LINE> move = m_input <NEW_LINE> if move == 'f': <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif move == 'i': <NEW_LINE> <INDENT> self.use_item() <NEW_LINE> <DEDENT> elif move == 's': <NEW_LINE> <INDENT> self.get_stats() <NEW_LINE> self.move_input() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.move_input() <NEW_LINE> <DEDENT> return move <NEW_LINE> <DEDENT> <DEDENT> def use_item(self): <NEW_LINE> <INDENT> if potion.name in inventory: <NEW_LINE> <INDENT> print(f'would you like to use {potion.name}?') <NEW_LINE> print('[y]es or [n] no') <NEW_LINE> item_input = input('>') <NEW_LINE> if item_input == 'y': <NEW_LINE> <INDENT> if self.hp < self.max_hp: <NEW_LINE> <INDENT> self.hp += potion.hp_restore <NEW_LINE> inventory.remove(potion.name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('It won\'t help') <NEW_LINE> self.move_input() <NEW_LINE> <DEDENT> <DEDENT> if item_input == 'n': <NEW_LINE> <INDENT> self.move_input() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print('Your inventory is empty') <NEW_LINE> self.move_input() <NEW_LINE> <DEDENT> <DEDENT> def get_stats(self): <NEW_LINE> <INDENT> if self.is_alive(): <NEW_LINE> <INDENT> stats = { 'name': self.name, 'hp/max hp': f'{self.hp}/{self.max_hp}', 'attack': self.attack, 'speed': self.speed } <NEW_LINE> print(stats) | This is a subclass of characters specific to team 1 | 62598fa0bd1bec0571e14fde |
class UserHistorySerializer(serializers.Serializer): <NEW_LINE> <INDENT> sku_id = serializers.IntegerField(label='商品编号',min_value=1,required=True) <NEW_LINE> def validate_sku_id(self,value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> SKU.objects.get(pk=value) <NEW_LINE> <DEDENT> except SKU.DoesNotExist: <NEW_LINE> <INDENT> raise serializers.ValidationError('商品不存在') <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def create(self, validated_data): <NEW_LINE> <INDENT> user_id = self.context['request'].user.id <NEW_LINE> sku_id = validated_data['sku_id'] <NEW_LINE> redis_conn = get_redis_connection('history') <NEW_LINE> redis_conn.lrem('history_%s'%user_id,0,sku_id) <NEW_LINE> redis_conn.lpush('history_%s'%user_id,sku_id) <NEW_LINE> redis_conn.ltrim('history_%s'%user_id,0,4) <NEW_LINE> return validated_data | 添加用户浏览记录序列化器 | 62598fa00a50d4780f705210 |
class Tag(Base): <NEW_LINE> <INDENT> __tablename__ = 'tags' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> label = Column(String(63)) <NEW_LINE> description = Column(String(255), default='') <NEW_LINE> protected = Column(Boolean, default=False) <NEW_LINE> pinned = Column(Boolean, default=False) <NEW_LINE> def __init__(self, label=None): <NEW_LINE> <INDENT> if label: self.label = label <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get(id=None, label=None): <NEW_LINE> <INDENT> session = ProjectConfig.instance().Session() <NEW_LINE> query = session.query(Tag) <NEW_LINE> if id is not None: query = query.filter(Tag.id == id) <NEW_LINE> if label is not None: query = query.filter(Tag.label == label) <NEW_LINE> tag = query.first() <NEW_LINE> session.close() <NEW_LINE> return tag <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def put(tag): <NEW_LINE> <INDENT> session = ProjectConfig.instance().Session() <NEW_LINE> session.add(tag) <NEW_LINE> session.commit() <NEW_LINE> d = tag.json() <NEW_LINE> session.close() <NEW_LINE> return d <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def all_pinned(): <NEW_LINE> <INDENT> session = ProjectConfig.instance().Session() <NEW_LINE> query = session.query(Tag).filter(Tag.pinned == True) <NEW_LINE> results = query.all() <NEW_LINE> session.close() <NEW_LINE> return results <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def all_protected(): <NEW_LINE> <INDENT> session = ProjectConfig.instance().Session() <NEW_LINE> query = session.query(Tag).filter(Tag.protected == True) <NEW_LINE> results = query.all() <NEW_LINE> session.close() <NEW_LINE> return results <NEW_LINE> <DEDENT> def json(self): <NEW_LINE> <INDENT> data = { c.name: getattr(self, c.name) for c in self.__table__.columns } <NEW_LINE> return data <NEW_LINE> <DEDENT> def min_metadata(self): <NEW_LINE> <INDENT> return True if self.label else False <NEW_LINE> <DEDENT> def save(self): <NEW_LINE> <INDENT> if not self.min_metadata(): raise SpecError('Missing required attributes') <NEW_LINE> Tag.put(self) <NEW_LINE> return self | ORM model representing a project tag | 62598fa001c39578d7f12bb5 |
class PooledConnection(ConnectionWrapper): <NEW_LINE> <INDENT> def __init__(self, pool, cnx, key, tid): <NEW_LINE> <INDENT> ConnectionWrapper.__init__(self, cnx) <NEW_LINE> self._pool = pool <NEW_LINE> self._key = key <NEW_LINE> self._tid = tid <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> if self.cnx: <NEW_LINE> <INDENT> self._pool._return_cnx(self.cnx, self._key, self._tid) <NEW_LINE> self.cnx = None <NEW_LINE> <DEDENT> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.close() | A database connection that can be pooled. When closed, it gets returned
to the pool. | 62598fa08e7ae83300ee8ed6 |
class WatcherEventHandler: <NEW_LINE> <INDENT> def __init__(self, callback, patterns, timeout=3): <NEW_LINE> <INDENT> self.logger = logging.getLogger(__name__) <NEW_LINE> self.callback = callback <NEW_LINE> self.timeout = timeout <NEW_LINE> self.files = {} <NEW_LINE> self.patterns = patterns <NEW_LINE> self.handlers = { 'gc': self._gc_handler, 'created': self._create_handler, 'modified': self._update_handler, } <NEW_LINE> <DEDENT> def dispatch(self, event): <NEW_LINE> <INDENT> self.handlers.get(event.event_type, lambda event: None)(event) <NEW_LINE> <DEDENT> def _gc_handler(self, event): <NEW_LINE> <INDENT> for file in list(self.files.keys()): <NEW_LINE> <INDENT> delta = event.datetime - self.files[file] <NEW_LINE> if delta.total_seconds() > self.timeout: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.callback(file) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> self.logger.error("Error %s", ex) <NEW_LINE> <DEDENT> self.logger.info('GC: %s', self.files[file]) <NEW_LINE> del self.files[file] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def _create_handler(self, event): <NEW_LINE> <INDENT> if match_any_paths([event.src_path], included_patterns=self.patterns): <NEW_LINE> <INDENT> self.files[event.src_path] = datetime.now() <NEW_LINE> self.logger.info('File created: %s', event) <NEW_LINE> <DEDENT> <DEDENT> def _update_handler(self, event): <NEW_LINE> <INDENT> if event.src_path in self.files and match_any_paths([event.src_path], included_patterns=self.patterns): <NEW_LINE> <INDENT> self.files[event.src_path] = datetime.now() <NEW_LINE> self.logger.info('File modified: %s', event) | Watcher Event Handler Class | 62598fa08e71fb1e983bb8ed |
class ForcingTerm(object): <NEW_LINE> <INDENT> def __init__(self, weights, basis_functions): <NEW_LINE> <INDENT> self.w = weights <NEW_LINE> self.psi = basis_functions <NEW_LINE> <DEDENT> @property <NEW_LINE> def weights(self): <NEW_LINE> <INDENT> return self.w <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_linear(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_parametric(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_recurrent(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def compute(self, s): <NEW_LINE> <INDENT> psi_track = self.psi(s) <NEW_LINE> if len(psi_track.shape) == 1: <NEW_LINE> <INDENT> return np.dot(psi_track, self.w) / np.sum(psi_track) <NEW_LINE> <DEDENT> return np.dot(psi_track, self.w) / np.sum(psi_track, axis=1) <NEW_LINE> <DEDENT> def weighted_basis(self, s): <NEW_LINE> <INDENT> return self.psi(s) * self.w <NEW_LINE> <DEDENT> def normalized_weighted_basis(self, s): <NEW_LINE> <INDENT> psi_track = self.psi(s) <NEW_LINE> return ((psi_track * self.w).T / np.sum(psi_track, axis=1)).T <NEW_LINE> <DEDENT> def __call__(self, s): <NEW_LINE> <INDENT> return self.compute(s) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.__class__.__name__ <NEW_LINE> <DEDENT> def train(self, f_target): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> generate_weights = train | Forcing term used in DMPs
This basically computes the unscaled forcing term, i.e. a weighted sum of basis functions, which is given by:
.. math:: f(s) = \frac{ sum_{i} \psi_i(s) w_i }{ \sum_i \psi_i(s) }
where :math:`w` are the learnable weight parameters, and :math:`\psi` are the basis functions evaluated at the
given input phase variable :math:`s`. | 62598fa092d797404e388a81 |
class ModelFileCached(BaseModelFile): <NEW_LINE> <INDENT> def __init__(self, cache_id): <NEW_LINE> <INDENT> self._cache_id = cache_id <NEW_LINE> <DEDENT> @cached_property <NEW_LINE> def filename(self): <NEW_LINE> <INDENT> return cache_path(CACHED_PRODUCT_FILE[self._cache_id]) | Model file with cache filename. | 62598fa032920d7e50bc5e8d |
class CallSubprocess(Action): <NEW_LINE> <INDENT> def __init__(self, command, kwargs={}, label=DEFAULT, *args, **kwds): <NEW_LINE> <INDENT> Action.__init__(self, " ".join(command) if label is DEFAULT else label, *args, **kwds) <NEW_LINE> self.__command = command <NEW_LINE> self.__kwargs = kwargs <NEW_LINE> <DEDENT> def do_execute(self, dependency_statuses): <NEW_LINE> <INDENT> subprocess.check_call(self.__command, **self.__kwargs) | A stock action that calls a subprocess. | 62598fa08e7ae83300ee8ed7 |
class SimulationYAMLReader: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.yaml = None <NEW_LINE> <DEDENT> def read_yaml_from_file(self, yaml_file) -> SimulationRepr: <NEW_LINE> <INDENT> with open(yaml_file, "r") as yf: <NEW_LINE> <INDENT> self.yaml = yaml.full_load(yf) <NEW_LINE> <DEDENT> return self._parse_yaml() <NEW_LINE> <DEDENT> def read_yaml_from_str(self, yaml_str) -> SimulationRepr: <NEW_LINE> <INDENT> self.yaml = yaml.full_load(yaml_str) <NEW_LINE> return self._parse_yaml() <NEW_LINE> <DEDENT> def _parse_yaml(self) -> SimulationRepr: <NEW_LINE> <INDENT> if not self.yaml: <NEW_LINE> <INDENT> raise ValueError(f"Invalid state for YAML reader. No YAML to parse.") <NEW_LINE> <DEDENT> sr = SimulationRepr(name=self.yaml["simulation"]) <NEW_LINE> if "events" in self.yaml.keys(): <NEW_LINE> <INDENT> events = self.yaml["events"] <NEW_LINE> for event_class in events: <NEW_LINE> <INDENT> event = events[event_class] <NEW_LINE> event_name = event.get("name", None) <NEW_LINE> event_attributes = event.get("attributes", []) <NEW_LINE> sr.add_event(EventRepr(class_name=event_class, event_name=event_name, attributes=event_attributes)) <NEW_LINE> <DEDENT> <DEDENT> if "entities" in self.yaml.keys(): <NEW_LINE> <INDENT> entities = self.yaml["entities"] <NEW_LINE> for entity_class in entities: <NEW_LINE> <INDENT> entity = entities[entity_class] <NEW_LINE> entity_name = entity.get("name", None) <NEW_LINE> entity_attributes = entity.get("attributes", []) <NEW_LINE> entity_repr = EntityRepr(class_name=entity_class, entity_name=entity_name, attributes=entity_attributes) <NEW_LINE> handlers = entity.get("handlers", None) <NEW_LINE> if handlers: <NEW_LINE> <INDENT> if "entities" in handlers.keys(): <NEW_LINE> <INDENT> entity_handlers = handlers["entities"] <NEW_LINE> for entity_to_handle in entity_handlers.keys(): <NEW_LINE> <INDENT> entity_repr.entity_handlers[entity_to_handle] = entity_handlers[entity_to_handle] <NEW_LINE> <DEDENT> <DEDENT> if "events" in handlers.keys(): <NEW_LINE> <INDENT> for event_name in handlers["events"]: <NEW_LINE> <INDENT> if event_name == "time_update": <NEW_LINE> <INDENT> entity_repr.time_update_handler = True <NEW_LINE> <DEDENT> elif event_name == "simulation_shutdown": <NEW_LINE> <INDENT> entity_repr.simulation_shutdown_handler = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entity_repr.event_handlers.append(event_name) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> sr.add_entity(entity=entity_repr) <NEW_LINE> <DEDENT> <DEDENT> return sr | Reads a simulation description from YAML, then validate, and then parse. | 62598fa0d7e4931a7ef3bed0 |
class APIError(Exception): <NEW_LINE> <INDENT> def __init__(self, response): <NEW_LINE> <INDENT> self.response = response <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return (( 'Mailgun API {method} at {url} failed ' 'with status code {status_code}:\n{text}').format( method=self.response.request.method, url=self.response.request.url, status_code=self.response.status_code, text=self.response.text)) | Error response from the Mailgun server. | 62598fa07d847024c075c1fd |
class _Save_StatCosave(AppendableLink, OneItemLink): <NEW_LINE> <INDENT> def _enable(self): <NEW_LINE> <INDENT> if not super(_Save_StatCosave, self)._enable(): return False <NEW_LINE> self._cosave = self._get_cosave() <NEW_LINE> return bool(self._cosave) <NEW_LINE> <DEDENT> def _get_cosave(self): <NEW_LINE> <INDENT> raise AbstractError(u'_get_cosave not implemented') <NEW_LINE> <DEDENT> def Execute(self): <NEW_LINE> <INDENT> with BusyCursor(): <NEW_LINE> <INDENT> log = bolt.LogFile(io.StringIO()) <NEW_LINE> self._cosave.dump_to_log(log, self._selected_info.header.masters) <NEW_LINE> logtxt = log.out.getvalue() <NEW_LINE> <DEDENT> self._showLog(logtxt, title=self._cosave.abs_path.tail, fixedFont=False) | Base for xSE and pluggy cosaves stats menus | 62598fa0462c4b4f79dbb843 |
class Pattern: <NEW_LINE> <INDENT> def search(self, document): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> return OrPattern(self, other) <NEW_LINE> <DEDENT> def __mul__(self, other): <NEW_LINE> <INDENT> return AndPattern(self, other) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return SubPattern(self, other) | Check if the document have a specific pattern | 62598fa067a9b606de545e01 |
class Address(Base): <NEW_LINE> <INDENT> __tablename__ = 'address' <NEW_LINE> id = Column(Integer, primary_key=True, autoincrement=True) <NEW_LINE> user_id = Column(Integer, ForeignKey('user.id'), nullable=False, comment='外键: 下单的用户id') <NEW_LINE> name = Column(String(30), nullable=False, comment='收货人姓名') <NEW_LINE> mobile = Column(String(20), nullable=False, comment='手机') <NEW_LINE> province = Column(String(20), comment='省份') <NEW_LINE> city = Column(String(20), comment='城市') <NEW_LINE> country = Column(String(20), comment='县区') <NEW_LINE> detail = Column(String(100), comment='详细地址') <NEW_LINE> def keys(self): <NEW_LINE> <INDENT> self.hide('id', 'user_id') <NEW_LINE> return self.fields | 配送信息 | 62598fa0d486a94d0ba2be0d |
class BagFactory(): <NEW_LINE> <INDENT> def __init__(self, color='turquoise', material='leather', length=1, width=1, height=1): <NEW_LINE> <INDENT> self.color = color <NEW_LINE> self.material = material <NEW_LINE> self.length = int(length) <NEW_LINE> self.width = int(width) <NEW_LINE> self.height = int(height) <NEW_LINE> <DEDENT> def dumbVolume(self): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> inc = 0.5 <NEW_LINE> for i in range(self.length): <NEW_LINE> <INDENT> for j in range(self.width): <NEW_LINE> <INDENT> for k in range(self.height): <NEW_LINE> <INDENT> count += inc <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return 2 * count <NEW_LINE> <DEDENT> def volume(self): <NEW_LINE> <INDENT> return self.length * self.width * self.height <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.length <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'I am a %s bag of length %d' % (self.color, self.length) <NEW_LINE> <DEDENT> def __gt__(self, otherBag): <NEW_LINE> <INDENT> return self.volume() > otherBag.volume() | This is a factory that produces bags, preferably turquoise.
Founded in Australia, with subsidiary operations in the UK.
@param color: A C{str} giving the color.
@raises ValueError: if C{height} is not an integer. | 62598fa038b623060ffa8eca |
class AuditObjectReference(_messages.Message): <NEW_LINE> <INDENT> apiVersion = _messages.StringField(1) <NEW_LINE> name = _messages.StringField(2) <NEW_LINE> resource = _messages.StringField(3) <NEW_LINE> subresource = _messages.StringField(4) | AuditObjectReference contains enough information to let you inspect or
modify the referred object. Should match ObjectReference in https://github.
com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apiserver/pkg/apis/
audit/v1alpha1/generated.proto.
Fields:
apiVersion: +optional In alpha, this field follows Kubernetes
conventions, except there is a leading slash for the core group. I.e.
the core group is represented as "/v1"; other group versions are
represented as "fully.qualified.group.name/v1".
name: +optional
resource: +optional
subresource: +optional | 62598fa030dc7b766599f685 |
class Solution: <NEW_LINE> <INDENT> def numRollsToTarget(self, d: int, f: int, target: int) -> int: <NEW_LINE> <INDENT> if target > d*f or target < d: return 0 <NEW_LINE> mod = 1000000007 <NEW_LINE> dp = [0]*(target+1) <NEW_LINE> dp[0] = 1 <NEW_LINE> i = 1 <NEW_LINE> while i <= d: <NEW_LINE> <INDENT> tmp = [0]*(target+1) <NEW_LINE> for j in range(1, f+1): <NEW_LINE> <INDENT> for k in range(j, target+1): <NEW_LINE> <INDENT> tmp[k] = (tmp[k] + dp[k - j]) % mod <NEW_LINE> <DEDENT> <DEDENT> dp[:] = tmp[:] <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> return dp[target] | https://www.cnblogs.com/Dylan-Java-NYC/p/12196018.html
e.g. 3 f=6 dices, target = 7
d ar 0 1 2 3 4 5 6 7
1 dp = [0, 1, 1, 1, 1, 1, 1, 0]
2 dp = [0, 0, 1, 2, 3, 4, 5, 6]
3 dp = [0, 0, 0, 1, 3, 6, 10, 15] | 62598fa0b7558d5895463465 |
class Profile(models.Model): <NEW_LINE> <INDENT> STUDENT = 'student' <NEW_LINE> TEACHER = 'teacher' <NEW_LINE> PARENT = 'parent' <NEW_LINE> PRINCIPAL = 'principal' <NEW_LINE> ADMIN = 'admin' <NEW_LINE> TYPES = ( (STUDENT, _('Student')), (TEACHER, _('Teacher')), (PARENT, _('Parent')), (PRINCIPAL, _('Principal')), (ADMIN, _('Admin')), ) <NEW_LINE> user = models.ForeignKey(User, blank=True, null=True, help_text=_("The (optional) user account associated with this profile.")) <NEW_LINE> name = models.CharField(max_length=255, help_text=_("The person's first name")) <NEW_LINE> surname = models.CharField(max_length=255, help_text=_("The person's last name")) <NEW_LINE> mobile = models.CharField(max_length=100, null=True, blank=True, help_text=_("The person's mobile phone number.")) <NEW_LINE> profile_type = models.CharField(max_length=30, choices=TYPES, default=STUDENT) <NEW_LINE> school = models.ForeignKey('School', null=True, blank=True, help_text=_("The school for this user, if any")) <NEW_LINE> grade = models.IntegerField(null=True, blank=True, help_text=_("The grade associated with this profile, if any")) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return "%s %s" % (self.name, self.surname) | Every user in the system has a profile, but not every profile has a user
associated with it. | 62598fa0f548e778e596b3e5 |
class HStoreField(forms.CharField): <NEW_LINE> <INDENT> widget = forms.Textarea <NEW_LINE> default_error_messages = { 'invalid_json': _('Could not load JSON data.'), 'invalid_format': _('Input must be a JSON dictionary.'), } <NEW_LINE> def prepare_value(self, value): <NEW_LINE> <INDENT> if isinstance(value, dict): <NEW_LINE> <INDENT> return json.dumps(value) <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def to_python(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> if not isinstance(value, dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = json.loads(value) <NEW_LINE> <DEDENT> except json.JSONDecodeError: <NEW_LINE> <INDENT> raise ValidationError( self.error_messages['invalid_json'], code='invalid_json', ) <NEW_LINE> <DEDENT> <DEDENT> if not isinstance(value, dict): <NEW_LINE> <INDENT> raise ValidationError( self.error_messages['invalid_format'], code='invalid_format', ) <NEW_LINE> <DEDENT> for key, val in value.items(): <NEW_LINE> <INDENT> if val is not None: <NEW_LINE> <INDENT> val = str(val) <NEW_LINE> <DEDENT> value[key] = val <NEW_LINE> <DEDENT> return value <NEW_LINE> <DEDENT> def has_changed(self, initial, data): <NEW_LINE> <INDENT> initial_value = self.to_python(initial) <NEW_LINE> return super().has_changed(initial_value, data) | A field for HStore data which accepts dictionary JSON input. | 62598fa0a8ecb03325871045 |
class GenderAgeTrafficDetail(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Gender = None <NEW_LINE> self.AgeGap = None <NEW_LINE> self.TrafficCount = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Gender = params.get("Gender") <NEW_LINE> self.AgeGap = params.get("AgeGap") <NEW_LINE> self.TrafficCount = params.get("TrafficCount") | 性别年龄分组下的客流信息
| 62598fa0796e427e5384e5cb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.